]>
Commit | Line | Data |
---|---|---|
1 | (function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.bitcoinjs = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){ | |
2 | (function (global){ | |
3 | 'use strict'; | |
4 | ||
5 | // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js | |
6 | // original notice: | |
7 | ||
8 | /*! | |
9 | * The buffer module from node.js, for the browser. | |
10 | * | |
11 | * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> | |
12 | * @license MIT | |
13 | */ | |
14 | function compare(a, b) { | |
15 | if (a === b) { | |
16 | return 0; | |
17 | } | |
18 | ||
19 | var x = a.length; | |
20 | var y = b.length; | |
21 | ||
22 | for (var i = 0, len = Math.min(x, y); i < len; ++i) { | |
23 | if (a[i] !== b[i]) { | |
24 | x = a[i]; | |
25 | y = b[i]; | |
26 | break; | |
27 | } | |
28 | } | |
29 | ||
30 | if (x < y) { | |
31 | return -1; | |
32 | } | |
33 | if (y < x) { | |
34 | return 1; | |
35 | } | |
36 | return 0; | |
37 | } | |
38 | function isBuffer(b) { | |
39 | if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { | |
40 | return global.Buffer.isBuffer(b); | |
41 | } | |
42 | return !!(b != null && b._isBuffer); | |
43 | } | |
44 | ||
45 | // based on node assert, original notice: | |
46 | ||
47 | // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 | |
48 | // | |
49 | // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! | |
50 | // | |
51 | // Originally from narwhal.js (http://narwhaljs.org) | |
52 | // Copyright (c) 2009 Thomas Robinson <280north.com> | |
53 | // | |
54 | // Permission is hereby granted, free of charge, to any person obtaining a copy | |
55 | // of this software and associated documentation files (the 'Software'), to | |
56 | // deal in the Software without restriction, including without limitation the | |
57 | // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or | |
58 | // sell copies of the Software, and to permit persons to whom the Software is | |
59 | // furnished to do so, subject to the following conditions: | |
60 | // | |
61 | // The above copyright notice and this permission notice shall be included in | |
62 | // all copies or substantial portions of the Software. | |
63 | // | |
64 | // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR | |
65 | // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, | |
66 | // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE | |
67 | // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN | |
68 | // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION | |
69 | // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. | |
70 | ||
71 | var util = require('util/'); | |
72 | var hasOwn = Object.prototype.hasOwnProperty; | |
73 | var pSlice = Array.prototype.slice; | |
74 | var functionsHaveNames = (function () { | |
75 | return function foo() {}.name === 'foo'; | |
76 | }()); | |
77 | function pToString (obj) { | |
78 | return Object.prototype.toString.call(obj); | |
79 | } | |
80 | function isView(arrbuf) { | |
81 | if (isBuffer(arrbuf)) { | |
82 | return false; | |
83 | } | |
84 | if (typeof global.ArrayBuffer !== 'function') { | |
85 | return false; | |
86 | } | |
87 | if (typeof ArrayBuffer.isView === 'function') { | |
88 | return ArrayBuffer.isView(arrbuf); | |
89 | } | |
90 | if (!arrbuf) { | |
91 | return false; | |
92 | } | |
93 | if (arrbuf instanceof DataView) { | |
94 | return true; | |
95 | } | |
96 | if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { | |
97 | return true; | |
98 | } | |
99 | return false; | |
100 | } | |
101 | // 1. The assert module provides functions that throw | |
102 | // AssertionError's when particular conditions are not met. The | |
103 | // assert module must conform to the following interface. | |
104 | ||
105 | var assert = module.exports = ok; | |
106 | ||
107 | // 2. The AssertionError is defined in assert. | |
108 | // new assert.AssertionError({ message: message, | |
109 | // actual: actual, | |
110 | // expected: expected }) | |
111 | ||
112 | var regex = /\s*function\s+([^\(\s]*)\s*/; | |
113 | // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js | |
114 | function getName(func) { | |
115 | if (!util.isFunction(func)) { | |
116 | return; | |
117 | } | |
118 | if (functionsHaveNames) { | |
119 | return func.name; | |
120 | } | |
121 | var str = func.toString(); | |
122 | var match = str.match(regex); | |
123 | return match && match[1]; | |
124 | } | |
125 | assert.AssertionError = function AssertionError(options) { | |
126 | this.name = 'AssertionError'; | |
127 | this.actual = options.actual; | |
128 | this.expected = options.expected; | |
129 | this.operator = options.operator; | |
130 | if (options.message) { | |
131 | this.message = options.message; | |
132 | this.generatedMessage = false; | |
133 | } else { | |
134 | this.message = getMessage(this); | |
135 | this.generatedMessage = true; | |
136 | } | |
137 | var stackStartFunction = options.stackStartFunction || fail; | |
138 | if (Error.captureStackTrace) { | |
139 | Error.captureStackTrace(this, stackStartFunction); | |
140 | } else { | |
141 | // non v8 browsers so we can have a stacktrace | |
142 | var err = new Error(); | |
143 | if (err.stack) { | |
144 | var out = err.stack; | |
145 | ||
146 | // try to strip useless frames | |
147 | var fn_name = getName(stackStartFunction); | |
148 | var idx = out.indexOf('\n' + fn_name); | |
149 | if (idx >= 0) { | |
150 | // once we have located the function frame | |
151 | // we need to strip out everything before it (and its line) | |
152 | var next_line = out.indexOf('\n', idx + 1); | |
153 | out = out.substring(next_line + 1); | |
154 | } | |
155 | ||
156 | this.stack = out; | |
157 | } | |
158 | } | |
159 | }; | |
160 | ||
161 | // assert.AssertionError instanceof Error | |
162 | util.inherits(assert.AssertionError, Error); | |
163 | ||
164 | function truncate(s, n) { | |
165 | if (typeof s === 'string') { | |
166 | return s.length < n ? s : s.slice(0, n); | |
167 | } else { | |
168 | return s; | |
169 | } | |
170 | } | |
171 | function inspect(something) { | |
172 | if (functionsHaveNames || !util.isFunction(something)) { | |
173 | return util.inspect(something); | |
174 | } | |
175 | var rawname = getName(something); | |
176 | var name = rawname ? ': ' + rawname : ''; | |
177 | return '[Function' + name + ']'; | |
178 | } | |
179 | function getMessage(self) { | |
180 | return truncate(inspect(self.actual), 128) + ' ' + | |
181 | self.operator + ' ' + | |
182 | truncate(inspect(self.expected), 128); | |
183 | } | |
184 | ||
185 | // At present only the three keys mentioned above are used and | |
186 | // understood by the spec. Implementations or sub modules can pass | |
187 | // other keys to the AssertionError's constructor - they will be | |
188 | // ignored. | |
189 | ||
190 | // 3. All of the following functions must throw an AssertionError | |
191 | // when a corresponding condition is not met, with a message that | |
192 | // may be undefined if not provided. All assertion methods provide | |
193 | // both the actual and expected values to the assertion error for | |
194 | // display purposes. | |
195 | ||
196 | function fail(actual, expected, message, operator, stackStartFunction) { | |
197 | throw new assert.AssertionError({ | |
198 | message: message, | |
199 | actual: actual, | |
200 | expected: expected, | |
201 | operator: operator, | |
202 | stackStartFunction: stackStartFunction | |
203 | }); | |
204 | } | |
205 | ||
206 | // EXTENSION! allows for well behaved errors defined elsewhere. | |
207 | assert.fail = fail; | |
208 | ||
209 | // 4. Pure assertion tests whether a value is truthy, as determined | |
210 | // by !!guard. | |
211 | // assert.ok(guard, message_opt); | |
212 | // This statement is equivalent to assert.equal(true, !!guard, | |
213 | // message_opt);. To test strictly for the value true, use | |
214 | // assert.strictEqual(true, guard, message_opt);. | |
215 | ||
216 | function ok(value, message) { | |
217 | if (!value) fail(value, true, message, '==', assert.ok); | |
218 | } | |
219 | assert.ok = ok; | |
220 | ||
221 | // 5. The equality assertion tests shallow, coercive equality with | |
222 | // ==. | |
223 | // assert.equal(actual, expected, message_opt); | |
224 | ||
225 | assert.equal = function equal(actual, expected, message) { | |
226 | if (actual != expected) fail(actual, expected, message, '==', assert.equal); | |
227 | }; | |
228 | ||
229 | // 6. The non-equality assertion tests for whether two objects are not equal | |
230 | // with != assert.notEqual(actual, expected, message_opt); | |
231 | ||
232 | assert.notEqual = function notEqual(actual, expected, message) { | |
233 | if (actual == expected) { | |
234 | fail(actual, expected, message, '!=', assert.notEqual); | |
235 | } | |
236 | }; | |
237 | ||
238 | // 7. The equivalence assertion tests a deep equality relation. | |
239 | // assert.deepEqual(actual, expected, message_opt); | |
240 | ||
241 | assert.deepEqual = function deepEqual(actual, expected, message) { | |
242 | if (!_deepEqual(actual, expected, false)) { | |
243 | fail(actual, expected, message, 'deepEqual', assert.deepEqual); | |
244 | } | |
245 | }; | |
246 | ||
247 | assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { | |
248 | if (!_deepEqual(actual, expected, true)) { | |
249 | fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); | |
250 | } | |
251 | }; | |
252 | ||
253 | function _deepEqual(actual, expected, strict, memos) { | |
254 | // 7.1. All identical values are equivalent, as determined by ===. | |
255 | if (actual === expected) { | |
256 | return true; | |
257 | } else if (isBuffer(actual) && isBuffer(expected)) { | |
258 | return compare(actual, expected) === 0; | |
259 | ||
260 | // 7.2. If the expected value is a Date object, the actual value is | |
261 | // equivalent if it is also a Date object that refers to the same time. | |
262 | } else if (util.isDate(actual) && util.isDate(expected)) { | |
263 | return actual.getTime() === expected.getTime(); | |
264 | ||
265 | // 7.3 If the expected value is a RegExp object, the actual value is | |
266 | // equivalent if it is also a RegExp object with the same source and | |
267 | // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). | |
268 | } else if (util.isRegExp(actual) && util.isRegExp(expected)) { | |
269 | return actual.source === expected.source && | |
270 | actual.global === expected.global && | |
271 | actual.multiline === expected.multiline && | |
272 | actual.lastIndex === expected.lastIndex && | |
273 | actual.ignoreCase === expected.ignoreCase; | |
274 | ||
275 | // 7.4. Other pairs that do not both pass typeof value == 'object', | |
276 | // equivalence is determined by ==. | |
277 | } else if ((actual === null || typeof actual !== 'object') && | |
278 | (expected === null || typeof expected !== 'object')) { | |
279 | return strict ? actual === expected : actual == expected; | |
280 | ||
281 | // If both values are instances of typed arrays, wrap their underlying | |
282 | // ArrayBuffers in a Buffer each to increase performance | |
283 | // This optimization requires the arrays to have the same type as checked by | |
284 | // Object.prototype.toString (aka pToString). Never perform binary | |
285 | // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their | |
286 | // bit patterns are not identical. | |
287 | } else if (isView(actual) && isView(expected) && | |
288 | pToString(actual) === pToString(expected) && | |
289 | !(actual instanceof Float32Array || | |
290 | actual instanceof Float64Array)) { | |
291 | return compare(new Uint8Array(actual.buffer), | |
292 | new Uint8Array(expected.buffer)) === 0; | |
293 | ||
294 | // 7.5 For all other Object pairs, including Array objects, equivalence is | |
295 | // determined by having the same number of owned properties (as verified | |
296 | // with Object.prototype.hasOwnProperty.call), the same set of keys | |
297 | // (although not necessarily the same order), equivalent values for every | |
298 | // corresponding key, and an identical 'prototype' property. Note: this | |
299 | // accounts for both named and indexed properties on Arrays. | |
300 | } else if (isBuffer(actual) !== isBuffer(expected)) { | |
301 | return false; | |
302 | } else { | |
303 | memos = memos || {actual: [], expected: []}; | |
304 | ||
305 | var actualIndex = memos.actual.indexOf(actual); | |
306 | if (actualIndex !== -1) { | |
307 | if (actualIndex === memos.expected.indexOf(expected)) { | |
308 | return true; | |
309 | } | |
310 | } | |
311 | ||
312 | memos.actual.push(actual); | |
313 | memos.expected.push(expected); | |
314 | ||
315 | return objEquiv(actual, expected, strict, memos); | |
316 | } | |
317 | } | |
318 | ||
319 | function isArguments(object) { | |
320 | return Object.prototype.toString.call(object) == '[object Arguments]'; | |
321 | } | |
322 | ||
323 | function objEquiv(a, b, strict, actualVisitedObjects) { | |
324 | if (a === null || a === undefined || b === null || b === undefined) | |
325 | return false; | |
326 | // if one is a primitive, the other must be same | |
327 | if (util.isPrimitive(a) || util.isPrimitive(b)) | |
328 | return a === b; | |
329 | if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) | |
330 | return false; | |
331 | var aIsArgs = isArguments(a); | |
332 | var bIsArgs = isArguments(b); | |
333 | if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) | |
334 | return false; | |
335 | if (aIsArgs) { | |
336 | a = pSlice.call(a); | |
337 | b = pSlice.call(b); | |
338 | return _deepEqual(a, b, strict); | |
339 | } | |
340 | var ka = objectKeys(a); | |
341 | var kb = objectKeys(b); | |
342 | var key, i; | |
343 | // having the same number of owned properties (keys incorporates | |
344 | // hasOwnProperty) | |
345 | if (ka.length !== kb.length) | |
346 | return false; | |
347 | //the same set of keys (although not necessarily the same order), | |
348 | ka.sort(); | |
349 | kb.sort(); | |
350 | //~~~cheap key test | |
351 | for (i = ka.length - 1; i >= 0; i--) { | |
352 | if (ka[i] !== kb[i]) | |
353 | return false; | |
354 | } | |
355 | //equivalent values for every corresponding key, and | |
356 | //~~~possibly expensive deep test | |
357 | for (i = ka.length - 1; i >= 0; i--) { | |
358 | key = ka[i]; | |
359 | if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) | |
360 | return false; | |
361 | } | |
362 | return true; | |
363 | } | |
364 | ||
365 | // 8. The non-equivalence assertion tests for any deep inequality. | |
366 | // assert.notDeepEqual(actual, expected, message_opt); | |
367 | ||
368 | assert.notDeepEqual = function notDeepEqual(actual, expected, message) { | |
369 | if (_deepEqual(actual, expected, false)) { | |
370 | fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); | |
371 | } | |
372 | }; | |
373 | ||
374 | assert.notDeepStrictEqual = notDeepStrictEqual; | |
375 | function notDeepStrictEqual(actual, expected, message) { | |
376 | if (_deepEqual(actual, expected, true)) { | |
377 | fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); | |
378 | } | |
379 | } | |
380 | ||
381 | ||
382 | // 9. The strict equality assertion tests strict equality, as determined by ===. | |
383 | // assert.strictEqual(actual, expected, message_opt); | |
384 | ||
385 | assert.strictEqual = function strictEqual(actual, expected, message) { | |
386 | if (actual !== expected) { | |
387 | fail(actual, expected, message, '===', assert.strictEqual); | |
388 | } | |
389 | }; | |
390 | ||
391 | // 10. The strict non-equality assertion tests for strict inequality, as | |
392 | // determined by !==. assert.notStrictEqual(actual, expected, message_opt); | |
393 | ||
394 | assert.notStrictEqual = function notStrictEqual(actual, expected, message) { | |
395 | if (actual === expected) { | |
396 | fail(actual, expected, message, '!==', assert.notStrictEqual); | |
397 | } | |
398 | }; | |
399 | ||
400 | function expectedException(actual, expected) { | |
401 | if (!actual || !expected) { | |
402 | return false; | |
403 | } | |
404 | ||
405 | if (Object.prototype.toString.call(expected) == '[object RegExp]') { | |
406 | return expected.test(actual); | |
407 | } | |
408 | ||
409 | try { | |
410 | if (actual instanceof expected) { | |
411 | return true; | |
412 | } | |
413 | } catch (e) { | |
414 | // Ignore. The instanceof check doesn't work for arrow functions. | |
415 | } | |
416 | ||
417 | if (Error.isPrototypeOf(expected)) { | |
418 | return false; | |
419 | } | |
420 | ||
421 | return expected.call({}, actual) === true; | |
422 | } | |
423 | ||
424 | function _tryBlock(block) { | |
425 | var error; | |
426 | try { | |
427 | block(); | |
428 | } catch (e) { | |
429 | error = e; | |
430 | } | |
431 | return error; | |
432 | } | |
433 | ||
434 | function _throws(shouldThrow, block, expected, message) { | |
435 | var actual; | |
436 | ||
437 | if (typeof block !== 'function') { | |
438 | throw new TypeError('"block" argument must be a function'); | |
439 | } | |
440 | ||
441 | if (typeof expected === 'string') { | |
442 | message = expected; | |
443 | expected = null; | |
444 | } | |
445 | ||
446 | actual = _tryBlock(block); | |
447 | ||
448 | message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + | |
449 | (message ? ' ' + message : '.'); | |
450 | ||
451 | if (shouldThrow && !actual) { | |
452 | fail(actual, expected, 'Missing expected exception' + message); | |
453 | } | |
454 | ||
455 | var userProvidedMessage = typeof message === 'string'; | |
456 | var isUnwantedException = !shouldThrow && util.isError(actual); | |
457 | var isUnexpectedException = !shouldThrow && actual && !expected; | |
458 | ||
459 | if ((isUnwantedException && | |
460 | userProvidedMessage && | |
461 | expectedException(actual, expected)) || | |
462 | isUnexpectedException) { | |
463 | fail(actual, expected, 'Got unwanted exception' + message); | |
464 | } | |
465 | ||
466 | if ((shouldThrow && actual && expected && | |
467 | !expectedException(actual, expected)) || (!shouldThrow && actual)) { | |
468 | throw actual; | |
469 | } | |
470 | } | |
471 | ||
472 | // 11. Expected to throw an error: | |
473 | // assert.throws(block, Error_opt, message_opt); | |
474 | ||
475 | assert.throws = function(block, /*optional*/error, /*optional*/message) { | |
476 | _throws(true, block, error, message); | |
477 | }; | |
478 | ||
479 | // EXTENSION! This is annoying to write outside this module. | |
480 | assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { | |
481 | _throws(false, block, error, message); | |
482 | }; | |
483 | ||
484 | assert.ifError = function(err) { if (err) throw err; }; | |
485 | ||
486 | var objectKeys = Object.keys || function (obj) { | |
487 | var keys = []; | |
488 | for (var key in obj) { | |
489 | if (hasOwn.call(obj, key)) keys.push(key); | |
490 | } | |
491 | return keys; | |
492 | }; | |
493 | ||
494 | }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | |
495 | },{"util/":32}],2:[function(require,module,exports){ | |
496 | 'use strict' | |
497 | ||
498 | exports.byteLength = byteLength | |
499 | exports.toByteArray = toByteArray | |
500 | exports.fromByteArray = fromByteArray | |
501 | ||
502 | var lookup = [] | |
503 | var revLookup = [] | |
504 | var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array | |
505 | ||
506 | var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' | |
507 | for (var i = 0, len = code.length; i < len; ++i) { | |
508 | lookup[i] = code[i] | |
509 | revLookup[code.charCodeAt(i)] = i | |
510 | } | |
511 | ||
512 | revLookup['-'.charCodeAt(0)] = 62 | |
513 | revLookup['_'.charCodeAt(0)] = 63 | |
514 | ||
515 | function placeHoldersCount (b64) { | |
516 | var len = b64.length | |
517 | if (len % 4 > 0) { | |
518 | throw new Error('Invalid string. Length must be a multiple of 4') | |
519 | } | |
520 | ||
521 | // the number of equal signs (place holders) | |
522 | // if there are two placeholders, than the two characters before it | |
523 | // represent one byte | |
524 | // if there is only one, then the three characters before it represent 2 bytes | |
525 | // this is just a cheap hack to not do indexOf twice | |
526 | return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 | |
527 | } | |
528 | ||
529 | function byteLength (b64) { | |
530 | // base64 is 4/3 + up to two characters of the original data | |
531 | return (b64.length * 3 / 4) - placeHoldersCount(b64) | |
532 | } | |
533 | ||
534 | function toByteArray (b64) { | |
535 | var i, l, tmp, placeHolders, arr | |
536 | var len = b64.length | |
537 | placeHolders = placeHoldersCount(b64) | |
538 | ||
539 | arr = new Arr((len * 3 / 4) - placeHolders) | |
540 | ||
541 | // if there are placeholders, only get up to the last complete 4 chars | |
542 | l = placeHolders > 0 ? len - 4 : len | |
543 | ||
544 | var L = 0 | |
545 | ||
546 | for (i = 0; i < l; i += 4) { | |
547 | tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] | |
548 | arr[L++] = (tmp >> 16) & 0xFF | |
549 | arr[L++] = (tmp >> 8) & 0xFF | |
550 | arr[L++] = tmp & 0xFF | |
551 | } | |
552 | ||
553 | if (placeHolders === 2) { | |
554 | tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) | |
555 | arr[L++] = tmp & 0xFF | |
556 | } else if (placeHolders === 1) { | |
557 | tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) | |
558 | arr[L++] = (tmp >> 8) & 0xFF | |
559 | arr[L++] = tmp & 0xFF | |
560 | } | |
561 | ||
562 | return arr | |
563 | } | |
564 | ||
565 | function tripletToBase64 (num) { | |
566 | return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] | |
567 | } | |
568 | ||
569 | function encodeChunk (uint8, start, end) { | |
570 | var tmp | |
571 | var output = [] | |
572 | for (var i = start; i < end; i += 3) { | |
573 | tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) | |
574 | output.push(tripletToBase64(tmp)) | |
575 | } | |
576 | return output.join('') | |
577 | } | |
578 | ||
579 | function fromByteArray (uint8) { | |
580 | var tmp | |
581 | var len = uint8.length | |
582 | var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes | |
583 | var output = '' | |
584 | var parts = [] | |
585 | var maxChunkLength = 16383 // must be multiple of 3 | |
586 | ||
587 | // go through the array every three bytes, we'll deal with trailing stuff later | |
588 | for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { | |
589 | parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) | |
590 | } | |
591 | ||
592 | // pad the end with zeros, but make sure to not forget the extra bytes | |
593 | if (extraBytes === 1) { | |
594 | tmp = uint8[len - 1] | |
595 | output += lookup[tmp >> 2] | |
596 | output += lookup[(tmp << 4) & 0x3F] | |
597 | output += '==' | |
598 | } else if (extraBytes === 2) { | |
599 | tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) | |
600 | output += lookup[tmp >> 10] | |
601 | output += lookup[(tmp >> 4) & 0x3F] | |
602 | output += lookup[(tmp << 2) & 0x3F] | |
603 | output += '=' | |
604 | } | |
605 | ||
606 | parts.push(output) | |
607 | ||
608 | return parts.join('') | |
609 | } | |
610 | ||
611 | },{}],3:[function(require,module,exports){ | |
612 | ||
613 | },{}],4:[function(require,module,exports){ | |
614 | /*! | |
615 | * The buffer module from node.js, for the browser. | |
616 | * | |
617 | * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> | |
618 | * @license MIT | |
619 | */ | |
620 | /* eslint-disable no-proto */ | |
621 | ||
622 | 'use strict' | |
623 | ||
624 | var base64 = require('base64-js') | |
625 | var ieee754 = require('ieee754') | |
626 | ||
627 | exports.Buffer = Buffer | |
628 | exports.SlowBuffer = SlowBuffer | |
629 | exports.INSPECT_MAX_BYTES = 50 | |
630 | ||
631 | var K_MAX_LENGTH = 0x7fffffff | |
632 | exports.kMaxLength = K_MAX_LENGTH | |
633 | ||
634 | /** | |
635 | * If `Buffer.TYPED_ARRAY_SUPPORT`: | |
636 | * === true Use Uint8Array implementation (fastest) | |
637 | * === false Print warning and recommend using `buffer` v4.x which has an Object | |
638 | * implementation (most compatible, even IE6) | |
639 | * | |
640 | * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, | |
641 | * Opera 11.6+, iOS 4.2+. | |
642 | * | |
643 | * We report that the browser does not support typed arrays if the are not subclassable | |
644 | * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` | |
645 | * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support | |
646 | * for __proto__ and has a buggy typed array implementation. | |
647 | */ | |
648 | Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() | |
649 | ||
650 | if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && | |
651 | typeof console.error === 'function') { | |
652 | console.error( | |
653 | 'This browser lacks typed array (Uint8Array) support which is required by ' + | |
654 | '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' | |
655 | ) | |
656 | } | |
657 | ||
658 | function typedArraySupport () { | |
659 | // Can typed array instances can be augmented? | |
660 | try { | |
661 | var arr = new Uint8Array(1) | |
662 | arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} | |
663 | return arr.foo() === 42 | |
664 | } catch (e) { | |
665 | return false | |
666 | } | |
667 | } | |
668 | ||
669 | function createBuffer (length) { | |
670 | if (length > K_MAX_LENGTH) { | |
671 | throw new RangeError('Invalid typed array length') | |
672 | } | |
673 | // Return an augmented `Uint8Array` instance | |
674 | var buf = new Uint8Array(length) | |
675 | buf.__proto__ = Buffer.prototype | |
676 | return buf | |
677 | } | |
678 | ||
679 | /** | |
680 | * The Buffer constructor returns instances of `Uint8Array` that have their | |
681 | * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of | |
682 | * `Uint8Array`, so the returned instances will have all the node `Buffer` methods | |
683 | * and the `Uint8Array` methods. Square bracket notation works as expected -- it | |
684 | * returns a single octet. | |
685 | * | |
686 | * The `Uint8Array` prototype remains unmodified. | |
687 | */ | |
688 | ||
689 | function Buffer (arg, encodingOrOffset, length) { | |
690 | // Common case. | |
691 | if (typeof arg === 'number') { | |
692 | if (typeof encodingOrOffset === 'string') { | |
693 | throw new Error( | |
694 | 'If encoding is specified then the first argument must be a string' | |
695 | ) | |
696 | } | |
697 | return allocUnsafe(arg) | |
698 | } | |
699 | return from(arg, encodingOrOffset, length) | |
700 | } | |
701 | ||
702 | // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 | |
703 | if (typeof Symbol !== 'undefined' && Symbol.species && | |
704 | Buffer[Symbol.species] === Buffer) { | |
705 | Object.defineProperty(Buffer, Symbol.species, { | |
706 | value: null, | |
707 | configurable: true, | |
708 | enumerable: false, | |
709 | writable: false | |
710 | }) | |
711 | } | |
712 | ||
713 | Buffer.poolSize = 8192 // not used by this implementation | |
714 | ||
715 | function from (value, encodingOrOffset, length) { | |
716 | if (typeof value === 'number') { | |
717 | throw new TypeError('"value" argument must not be a number') | |
718 | } | |
719 | ||
720 | if (value instanceof ArrayBuffer) { | |
721 | return fromArrayBuffer(value, encodingOrOffset, length) | |
722 | } | |
723 | ||
724 | if (typeof value === 'string') { | |
725 | return fromString(value, encodingOrOffset) | |
726 | } | |
727 | ||
728 | return fromObject(value) | |
729 | } | |
730 | ||
731 | /** | |
732 | * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError | |
733 | * if value is a number. | |
734 | * Buffer.from(str[, encoding]) | |
735 | * Buffer.from(array) | |
736 | * Buffer.from(buffer) | |
737 | * Buffer.from(arrayBuffer[, byteOffset[, length]]) | |
738 | **/ | |
739 | Buffer.from = function (value, encodingOrOffset, length) { | |
740 | return from(value, encodingOrOffset, length) | |
741 | } | |
742 | ||
743 | // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: | |
744 | // https://github.com/feross/buffer/pull/148 | |
745 | Buffer.prototype.__proto__ = Uint8Array.prototype | |
746 | Buffer.__proto__ = Uint8Array | |
747 | ||
748 | function assertSize (size) { | |
749 | if (typeof size !== 'number') { | |
750 | throw new TypeError('"size" argument must be a number') | |
751 | } else if (size < 0) { | |
752 | throw new RangeError('"size" argument must not be negative') | |
753 | } | |
754 | } | |
755 | ||
756 | function alloc (size, fill, encoding) { | |
757 | assertSize(size) | |
758 | if (size <= 0) { | |
759 | return createBuffer(size) | |
760 | } | |
761 | if (fill !== undefined) { | |
762 | // Only pay attention to encoding if it's a string. This | |
763 | // prevents accidentally sending in a number that would | |
764 | // be interpretted as a start offset. | |
765 | return typeof encoding === 'string' | |
766 | ? createBuffer(size).fill(fill, encoding) | |
767 | : createBuffer(size).fill(fill) | |
768 | } | |
769 | return createBuffer(size) | |
770 | } | |
771 | ||
772 | /** | |
773 | * Creates a new filled Buffer instance. | |
774 | * alloc(size[, fill[, encoding]]) | |
775 | **/ | |
776 | Buffer.alloc = function (size, fill, encoding) { | |
777 | return alloc(size, fill, encoding) | |
778 | } | |
779 | ||
780 | function allocUnsafe (size) { | |
781 | assertSize(size) | |
782 | return createBuffer(size < 0 ? 0 : checked(size) | 0) | |
783 | } | |
784 | ||
785 | /** | |
786 | * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. | |
787 | * */ | |
788 | Buffer.allocUnsafe = function (size) { | |
789 | return allocUnsafe(size) | |
790 | } | |
791 | /** | |
792 | * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. | |
793 | */ | |
794 | Buffer.allocUnsafeSlow = function (size) { | |
795 | return allocUnsafe(size) | |
796 | } | |
797 | ||
798 | function fromString (string, encoding) { | |
799 | if (typeof encoding !== 'string' || encoding === '') { | |
800 | encoding = 'utf8' | |
801 | } | |
802 | ||
803 | if (!Buffer.isEncoding(encoding)) { | |
804 | throw new TypeError('"encoding" must be a valid string encoding') | |
805 | } | |
806 | ||
807 | var length = byteLength(string, encoding) | 0 | |
808 | var buf = createBuffer(length) | |
809 | ||
810 | var actual = buf.write(string, encoding) | |
811 | ||
812 | if (actual !== length) { | |
813 | // Writing a hex string, for example, that contains invalid characters will | |
814 | // cause everything after the first invalid character to be ignored. (e.g. | |
815 | // 'abxxcd' will be treated as 'ab') | |
816 | buf = buf.slice(0, actual) | |
817 | } | |
818 | ||
819 | return buf | |
820 | } | |
821 | ||
822 | function fromArrayLike (array) { | |
823 | var length = array.length < 0 ? 0 : checked(array.length) | 0 | |
824 | var buf = createBuffer(length) | |
825 | for (var i = 0; i < length; i += 1) { | |
826 | buf[i] = array[i] & 255 | |
827 | } | |
828 | return buf | |
829 | } | |
830 | ||
831 | function fromArrayBuffer (array, byteOffset, length) { | |
832 | if (byteOffset < 0 || array.byteLength < byteOffset) { | |
833 | throw new RangeError('\'offset\' is out of bounds') | |
834 | } | |
835 | ||
836 | if (array.byteLength < byteOffset + (length || 0)) { | |
837 | throw new RangeError('\'length\' is out of bounds') | |
838 | } | |
839 | ||
840 | var buf | |
841 | if (byteOffset === undefined && length === undefined) { | |
842 | buf = new Uint8Array(array) | |
843 | } else if (length === undefined) { | |
844 | buf = new Uint8Array(array, byteOffset) | |
845 | } else { | |
846 | buf = new Uint8Array(array, byteOffset, length) | |
847 | } | |
848 | ||
849 | // Return an augmented `Uint8Array` instance | |
850 | buf.__proto__ = Buffer.prototype | |
851 | return buf | |
852 | } | |
853 | ||
854 | function fromObject (obj) { | |
855 | if (Buffer.isBuffer(obj)) { | |
856 | var len = checked(obj.length) | 0 | |
857 | var buf = createBuffer(len) | |
858 | ||
859 | if (buf.length === 0) { | |
860 | return buf | |
861 | } | |
862 | ||
863 | obj.copy(buf, 0, 0, len) | |
864 | return buf | |
865 | } | |
866 | ||
867 | if (obj) { | |
868 | if (isArrayBufferView(obj) || 'length' in obj) { | |
869 | if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { | |
870 | return createBuffer(0) | |
871 | } | |
872 | return fromArrayLike(obj) | |
873 | } | |
874 | ||
875 | if (obj.type === 'Buffer' && Array.isArray(obj.data)) { | |
876 | return fromArrayLike(obj.data) | |
877 | } | |
878 | } | |
879 | ||
880 | throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') | |
881 | } | |
882 | ||
883 | function checked (length) { | |
884 | // Note: cannot use `length < K_MAX_LENGTH` here because that fails when | |
885 | // length is NaN (which is otherwise coerced to zero.) | |
886 | if (length >= K_MAX_LENGTH) { | |
887 | throw new RangeError('Attempt to allocate Buffer larger than maximum ' + | |
888 | 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') | |
889 | } | |
890 | return length | 0 | |
891 | } | |
892 | ||
893 | function SlowBuffer (length) { | |
894 | if (+length != length) { // eslint-disable-line eqeqeq | |
895 | length = 0 | |
896 | } | |
897 | return Buffer.alloc(+length) | |
898 | } | |
899 | ||
900 | Buffer.isBuffer = function isBuffer (b) { | |
901 | return b != null && b._isBuffer === true | |
902 | } | |
903 | ||
904 | Buffer.compare = function compare (a, b) { | |
905 | if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { | |
906 | throw new TypeError('Arguments must be Buffers') | |
907 | } | |
908 | ||
909 | if (a === b) return 0 | |
910 | ||
911 | var x = a.length | |
912 | var y = b.length | |
913 | ||
914 | for (var i = 0, len = Math.min(x, y); i < len; ++i) { | |
915 | if (a[i] !== b[i]) { | |
916 | x = a[i] | |
917 | y = b[i] | |
918 | break | |
919 | } | |
920 | } | |
921 | ||
922 | if (x < y) return -1 | |
923 | if (y < x) return 1 | |
924 | return 0 | |
925 | } | |
926 | ||
927 | Buffer.isEncoding = function isEncoding (encoding) { | |
928 | switch (String(encoding).toLowerCase()) { | |
929 | case 'hex': | |
930 | case 'utf8': | |
931 | case 'utf-8': | |
932 | case 'ascii': | |
933 | case 'latin1': | |
934 | case 'binary': | |
935 | case 'base64': | |
936 | case 'ucs2': | |
937 | case 'ucs-2': | |
938 | case 'utf16le': | |
939 | case 'utf-16le': | |
940 | return true | |
941 | default: | |
942 | return false | |
943 | } | |
944 | } | |
945 | ||
946 | Buffer.concat = function concat (list, length) { | |
947 | if (!Array.isArray(list)) { | |
948 | throw new TypeError('"list" argument must be an Array of Buffers') | |
949 | } | |
950 | ||
951 | if (list.length === 0) { | |
952 | return Buffer.alloc(0) | |
953 | } | |
954 | ||
955 | var i | |
956 | if (length === undefined) { | |
957 | length = 0 | |
958 | for (i = 0; i < list.length; ++i) { | |
959 | length += list[i].length | |
960 | } | |
961 | } | |
962 | ||
963 | var buffer = Buffer.allocUnsafe(length) | |
964 | var pos = 0 | |
965 | for (i = 0; i < list.length; ++i) { | |
966 | var buf = list[i] | |
967 | if (!Buffer.isBuffer(buf)) { | |
968 | throw new TypeError('"list" argument must be an Array of Buffers') | |
969 | } | |
970 | buf.copy(buffer, pos) | |
971 | pos += buf.length | |
972 | } | |
973 | return buffer | |
974 | } | |
975 | ||
976 | function byteLength (string, encoding) { | |
977 | if (Buffer.isBuffer(string)) { | |
978 | return string.length | |
979 | } | |
980 | if (isArrayBufferView(string) || string instanceof ArrayBuffer) { | |
981 | return string.byteLength | |
982 | } | |
983 | if (typeof string !== 'string') { | |
984 | string = '' + string | |
985 | } | |
986 | ||
987 | var len = string.length | |
988 | if (len === 0) return 0 | |
989 | ||
990 | // Use a for loop to avoid recursion | |
991 | var loweredCase = false | |
992 | for (;;) { | |
993 | switch (encoding) { | |
994 | case 'ascii': | |
995 | case 'latin1': | |
996 | case 'binary': | |
997 | return len | |
998 | case 'utf8': | |
999 | case 'utf-8': | |
1000 | case undefined: | |
1001 | return utf8ToBytes(string).length | |
1002 | case 'ucs2': | |
1003 | case 'ucs-2': | |
1004 | case 'utf16le': | |
1005 | case 'utf-16le': | |
1006 | return len * 2 | |
1007 | case 'hex': | |
1008 | return len >>> 1 | |
1009 | case 'base64': | |
1010 | return base64ToBytes(string).length | |
1011 | default: | |
1012 | if (loweredCase) return utf8ToBytes(string).length // assume utf8 | |
1013 | encoding = ('' + encoding).toLowerCase() | |
1014 | loweredCase = true | |
1015 | } | |
1016 | } | |
1017 | } | |
1018 | Buffer.byteLength = byteLength | |
1019 | ||
1020 | function slowToString (encoding, start, end) { | |
1021 | var loweredCase = false | |
1022 | ||
1023 | // No need to verify that "this.length <= MAX_UINT32" since it's a read-only | |
1024 | // property of a typed array. | |
1025 | ||
1026 | // This behaves neither like String nor Uint8Array in that we set start/end | |
1027 | // to their upper/lower bounds if the value passed is out of range. | |
1028 | // undefined is handled specially as per ECMA-262 6th Edition, | |
1029 | // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. | |
1030 | if (start === undefined || start < 0) { | |
1031 | start = 0 | |
1032 | } | |
1033 | // Return early if start > this.length. Done here to prevent potential uint32 | |
1034 | // coercion fail below. | |
1035 | if (start > this.length) { | |
1036 | return '' | |
1037 | } | |
1038 | ||
1039 | if (end === undefined || end > this.length) { | |
1040 | end = this.length | |
1041 | } | |
1042 | ||
1043 | if (end <= 0) { | |
1044 | return '' | |
1045 | } | |
1046 | ||
1047 | // Force coersion to uint32. This will also coerce falsey/NaN values to 0. | |
1048 | end >>>= 0 | |
1049 | start >>>= 0 | |
1050 | ||
1051 | if (end <= start) { | |
1052 | return '' | |
1053 | } | |
1054 | ||
1055 | if (!encoding) encoding = 'utf8' | |
1056 | ||
1057 | while (true) { | |
1058 | switch (encoding) { | |
1059 | case 'hex': | |
1060 | return hexSlice(this, start, end) | |
1061 | ||
1062 | case 'utf8': | |
1063 | case 'utf-8': | |
1064 | return utf8Slice(this, start, end) | |
1065 | ||
1066 | case 'ascii': | |
1067 | return asciiSlice(this, start, end) | |
1068 | ||
1069 | case 'latin1': | |
1070 | case 'binary': | |
1071 | return latin1Slice(this, start, end) | |
1072 | ||
1073 | case 'base64': | |
1074 | return base64Slice(this, start, end) | |
1075 | ||
1076 | case 'ucs2': | |
1077 | case 'ucs-2': | |
1078 | case 'utf16le': | |
1079 | case 'utf-16le': | |
1080 | return utf16leSlice(this, start, end) | |
1081 | ||
1082 | default: | |
1083 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) | |
1084 | encoding = (encoding + '').toLowerCase() | |
1085 | loweredCase = true | |
1086 | } | |
1087 | } | |
1088 | } | |
1089 | ||
1090 | // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) | |
1091 | // to detect a Buffer instance. It's not possible to use `instanceof Buffer` | |
1092 | // reliably in a browserify context because there could be multiple different | |
1093 | // copies of the 'buffer' package in use. This method works even for Buffer | |
1094 | // instances that were created from another copy of the `buffer` package. | |
1095 | // See: https://github.com/feross/buffer/issues/154 | |
1096 | Buffer.prototype._isBuffer = true | |
1097 | ||
1098 | function swap (b, n, m) { | |
1099 | var i = b[n] | |
1100 | b[n] = b[m] | |
1101 | b[m] = i | |
1102 | } | |
1103 | ||
1104 | Buffer.prototype.swap16 = function swap16 () { | |
1105 | var len = this.length | |
1106 | if (len % 2 !== 0) { | |
1107 | throw new RangeError('Buffer size must be a multiple of 16-bits') | |
1108 | } | |
1109 | for (var i = 0; i < len; i += 2) { | |
1110 | swap(this, i, i + 1) | |
1111 | } | |
1112 | return this | |
1113 | } | |
1114 | ||
1115 | Buffer.prototype.swap32 = function swap32 () { | |
1116 | var len = this.length | |
1117 | if (len % 4 !== 0) { | |
1118 | throw new RangeError('Buffer size must be a multiple of 32-bits') | |
1119 | } | |
1120 | for (var i = 0; i < len; i += 4) { | |
1121 | swap(this, i, i + 3) | |
1122 | swap(this, i + 1, i + 2) | |
1123 | } | |
1124 | return this | |
1125 | } | |
1126 | ||
1127 | Buffer.prototype.swap64 = function swap64 () { | |
1128 | var len = this.length | |
1129 | if (len % 8 !== 0) { | |
1130 | throw new RangeError('Buffer size must be a multiple of 64-bits') | |
1131 | } | |
1132 | for (var i = 0; i < len; i += 8) { | |
1133 | swap(this, i, i + 7) | |
1134 | swap(this, i + 1, i + 6) | |
1135 | swap(this, i + 2, i + 5) | |
1136 | swap(this, i + 3, i + 4) | |
1137 | } | |
1138 | return this | |
1139 | } | |
1140 | ||
1141 | Buffer.prototype.toString = function toString () { | |
1142 | var length = this.length | |
1143 | if (length === 0) return '' | |
1144 | if (arguments.length === 0) return utf8Slice(this, 0, length) | |
1145 | return slowToString.apply(this, arguments) | |
1146 | } | |
1147 | ||
1148 | Buffer.prototype.equals = function equals (b) { | |
1149 | if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') | |
1150 | if (this === b) return true | |
1151 | return Buffer.compare(this, b) === 0 | |
1152 | } | |
1153 | ||
1154 | Buffer.prototype.inspect = function inspect () { | |
1155 | var str = '' | |
1156 | var max = exports.INSPECT_MAX_BYTES | |
1157 | if (this.length > 0) { | |
1158 | str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') | |
1159 | if (this.length > max) str += ' ... ' | |
1160 | } | |
1161 | return '<Buffer ' + str + '>' | |
1162 | } | |
1163 | ||
1164 | Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { | |
1165 | if (!Buffer.isBuffer(target)) { | |
1166 | throw new TypeError('Argument must be a Buffer') | |
1167 | } | |
1168 | ||
1169 | if (start === undefined) { | |
1170 | start = 0 | |
1171 | } | |
1172 | if (end === undefined) { | |
1173 | end = target ? target.length : 0 | |
1174 | } | |
1175 | if (thisStart === undefined) { | |
1176 | thisStart = 0 | |
1177 | } | |
1178 | if (thisEnd === undefined) { | |
1179 | thisEnd = this.length | |
1180 | } | |
1181 | ||
1182 | if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { | |
1183 | throw new RangeError('out of range index') | |
1184 | } | |
1185 | ||
1186 | if (thisStart >= thisEnd && start >= end) { | |
1187 | return 0 | |
1188 | } | |
1189 | if (thisStart >= thisEnd) { | |
1190 | return -1 | |
1191 | } | |
1192 | if (start >= end) { | |
1193 | return 1 | |
1194 | } | |
1195 | ||
1196 | start >>>= 0 | |
1197 | end >>>= 0 | |
1198 | thisStart >>>= 0 | |
1199 | thisEnd >>>= 0 | |
1200 | ||
1201 | if (this === target) return 0 | |
1202 | ||
1203 | var x = thisEnd - thisStart | |
1204 | var y = end - start | |
1205 | var len = Math.min(x, y) | |
1206 | ||
1207 | var thisCopy = this.slice(thisStart, thisEnd) | |
1208 | var targetCopy = target.slice(start, end) | |
1209 | ||
1210 | for (var i = 0; i < len; ++i) { | |
1211 | if (thisCopy[i] !== targetCopy[i]) { | |
1212 | x = thisCopy[i] | |
1213 | y = targetCopy[i] | |
1214 | break | |
1215 | } | |
1216 | } | |
1217 | ||
1218 | if (x < y) return -1 | |
1219 | if (y < x) return 1 | |
1220 | return 0 | |
1221 | } | |
1222 | ||
1223 | // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, | |
1224 | // OR the last index of `val` in `buffer` at offset <= `byteOffset`. | |
1225 | // | |
1226 | // Arguments: | |
1227 | // - buffer - a Buffer to search | |
1228 | // - val - a string, Buffer, or number | |
1229 | // - byteOffset - an index into `buffer`; will be clamped to an int32 | |
1230 | // - encoding - an optional encoding, relevant is val is a string | |
1231 | // - dir - true for indexOf, false for lastIndexOf | |
1232 | function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { | |
1233 | // Empty buffer means no match | |
1234 | if (buffer.length === 0) return -1 | |
1235 | ||
1236 | // Normalize byteOffset | |
1237 | if (typeof byteOffset === 'string') { | |
1238 | encoding = byteOffset | |
1239 | byteOffset = 0 | |
1240 | } else if (byteOffset > 0x7fffffff) { | |
1241 | byteOffset = 0x7fffffff | |
1242 | } else if (byteOffset < -0x80000000) { | |
1243 | byteOffset = -0x80000000 | |
1244 | } | |
1245 | byteOffset = +byteOffset // Coerce to Number. | |
1246 | if (numberIsNaN(byteOffset)) { | |
1247 | // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer | |
1248 | byteOffset = dir ? 0 : (buffer.length - 1) | |
1249 | } | |
1250 | ||
1251 | // Normalize byteOffset: negative offsets start from the end of the buffer | |
1252 | if (byteOffset < 0) byteOffset = buffer.length + byteOffset | |
1253 | if (byteOffset >= buffer.length) { | |
1254 | if (dir) return -1 | |
1255 | else byteOffset = buffer.length - 1 | |
1256 | } else if (byteOffset < 0) { | |
1257 | if (dir) byteOffset = 0 | |
1258 | else return -1 | |
1259 | } | |
1260 | ||
1261 | // Normalize val | |
1262 | if (typeof val === 'string') { | |
1263 | val = Buffer.from(val, encoding) | |
1264 | } | |
1265 | ||
1266 | // Finally, search either indexOf (if dir is true) or lastIndexOf | |
1267 | if (Buffer.isBuffer(val)) { | |
1268 | // Special case: looking for empty string/buffer always fails | |
1269 | if (val.length === 0) { | |
1270 | return -1 | |
1271 | } | |
1272 | return arrayIndexOf(buffer, val, byteOffset, encoding, dir) | |
1273 | } else if (typeof val === 'number') { | |
1274 | val = val & 0xFF // Search for a byte value [0-255] | |
1275 | if (typeof Uint8Array.prototype.indexOf === 'function') { | |
1276 | if (dir) { | |
1277 | return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) | |
1278 | } else { | |
1279 | return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) | |
1280 | } | |
1281 | } | |
1282 | return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) | |
1283 | } | |
1284 | ||
1285 | throw new TypeError('val must be string, number or Buffer') | |
1286 | } | |
1287 | ||
1288 | function arrayIndexOf (arr, val, byteOffset, encoding, dir) { | |
1289 | var indexSize = 1 | |
1290 | var arrLength = arr.length | |
1291 | var valLength = val.length | |
1292 | ||
1293 | if (encoding !== undefined) { | |
1294 | encoding = String(encoding).toLowerCase() | |
1295 | if (encoding === 'ucs2' || encoding === 'ucs-2' || | |
1296 | encoding === 'utf16le' || encoding === 'utf-16le') { | |
1297 | if (arr.length < 2 || val.length < 2) { | |
1298 | return -1 | |
1299 | } | |
1300 | indexSize = 2 | |
1301 | arrLength /= 2 | |
1302 | valLength /= 2 | |
1303 | byteOffset /= 2 | |
1304 | } | |
1305 | } | |
1306 | ||
1307 | function read (buf, i) { | |
1308 | if (indexSize === 1) { | |
1309 | return buf[i] | |
1310 | } else { | |
1311 | return buf.readUInt16BE(i * indexSize) | |
1312 | } | |
1313 | } | |
1314 | ||
1315 | var i | |
1316 | if (dir) { | |
1317 | var foundIndex = -1 | |
1318 | for (i = byteOffset; i < arrLength; i++) { | |
1319 | if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { | |
1320 | if (foundIndex === -1) foundIndex = i | |
1321 | if (i - foundIndex + 1 === valLength) return foundIndex * indexSize | |
1322 | } else { | |
1323 | if (foundIndex !== -1) i -= i - foundIndex | |
1324 | foundIndex = -1 | |
1325 | } | |
1326 | } | |
1327 | } else { | |
1328 | if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength | |
1329 | for (i = byteOffset; i >= 0; i--) { | |
1330 | var found = true | |
1331 | for (var j = 0; j < valLength; j++) { | |
1332 | if (read(arr, i + j) !== read(val, j)) { | |
1333 | found = false | |
1334 | break | |
1335 | } | |
1336 | } | |
1337 | if (found) return i | |
1338 | } | |
1339 | } | |
1340 | ||
1341 | return -1 | |
1342 | } | |
1343 | ||
1344 | Buffer.prototype.includes = function includes (val, byteOffset, encoding) { | |
1345 | return this.indexOf(val, byteOffset, encoding) !== -1 | |
1346 | } | |
1347 | ||
1348 | Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { | |
1349 | return bidirectionalIndexOf(this, val, byteOffset, encoding, true) | |
1350 | } | |
1351 | ||
1352 | Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { | |
1353 | return bidirectionalIndexOf(this, val, byteOffset, encoding, false) | |
1354 | } | |
1355 | ||
1356 | function hexWrite (buf, string, offset, length) { | |
1357 | offset = Number(offset) || 0 | |
1358 | var remaining = buf.length - offset | |
1359 | if (!length) { | |
1360 | length = remaining | |
1361 | } else { | |
1362 | length = Number(length) | |
1363 | if (length > remaining) { | |
1364 | length = remaining | |
1365 | } | |
1366 | } | |
1367 | ||
1368 | // must be an even number of digits | |
1369 | var strLen = string.length | |
1370 | if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') | |
1371 | ||
1372 | if (length > strLen / 2) { | |
1373 | length = strLen / 2 | |
1374 | } | |
1375 | for (var i = 0; i < length; ++i) { | |
1376 | var parsed = parseInt(string.substr(i * 2, 2), 16) | |
1377 | if (numberIsNaN(parsed)) return i | |
1378 | buf[offset + i] = parsed | |
1379 | } | |
1380 | return i | |
1381 | } | |
1382 | ||
1383 | function utf8Write (buf, string, offset, length) { | |
1384 | return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) | |
1385 | } | |
1386 | ||
1387 | function asciiWrite (buf, string, offset, length) { | |
1388 | return blitBuffer(asciiToBytes(string), buf, offset, length) | |
1389 | } | |
1390 | ||
1391 | function latin1Write (buf, string, offset, length) { | |
1392 | return asciiWrite(buf, string, offset, length) | |
1393 | } | |
1394 | ||
1395 | function base64Write (buf, string, offset, length) { | |
1396 | return blitBuffer(base64ToBytes(string), buf, offset, length) | |
1397 | } | |
1398 | ||
1399 | function ucs2Write (buf, string, offset, length) { | |
1400 | return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) | |
1401 | } | |
1402 | ||
1403 | Buffer.prototype.write = function write (string, offset, length, encoding) { | |
1404 | // Buffer#write(string) | |
1405 | if (offset === undefined) { | |
1406 | encoding = 'utf8' | |
1407 | length = this.length | |
1408 | offset = 0 | |
1409 | // Buffer#write(string, encoding) | |
1410 | } else if (length === undefined && typeof offset === 'string') { | |
1411 | encoding = offset | |
1412 | length = this.length | |
1413 | offset = 0 | |
1414 | // Buffer#write(string, offset[, length][, encoding]) | |
1415 | } else if (isFinite(offset)) { | |
1416 | offset = offset >>> 0 | |
1417 | if (isFinite(length)) { | |
1418 | length = length >>> 0 | |
1419 | if (encoding === undefined) encoding = 'utf8' | |
1420 | } else { | |
1421 | encoding = length | |
1422 | length = undefined | |
1423 | } | |
1424 | } else { | |
1425 | throw new Error( | |
1426 | 'Buffer.write(string, encoding, offset[, length]) is no longer supported' | |
1427 | ) | |
1428 | } | |
1429 | ||
1430 | var remaining = this.length - offset | |
1431 | if (length === undefined || length > remaining) length = remaining | |
1432 | ||
1433 | if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { | |
1434 | throw new RangeError('Attempt to write outside buffer bounds') | |
1435 | } | |
1436 | ||
1437 | if (!encoding) encoding = 'utf8' | |
1438 | ||
1439 | var loweredCase = false | |
1440 | for (;;) { | |
1441 | switch (encoding) { | |
1442 | case 'hex': | |
1443 | return hexWrite(this, string, offset, length) | |
1444 | ||
1445 | case 'utf8': | |
1446 | case 'utf-8': | |
1447 | return utf8Write(this, string, offset, length) | |
1448 | ||
1449 | case 'ascii': | |
1450 | return asciiWrite(this, string, offset, length) | |
1451 | ||
1452 | case 'latin1': | |
1453 | case 'binary': | |
1454 | return latin1Write(this, string, offset, length) | |
1455 | ||
1456 | case 'base64': | |
1457 | // Warning: maxLength not taken into account in base64Write | |
1458 | return base64Write(this, string, offset, length) | |
1459 | ||
1460 | case 'ucs2': | |
1461 | case 'ucs-2': | |
1462 | case 'utf16le': | |
1463 | case 'utf-16le': | |
1464 | return ucs2Write(this, string, offset, length) | |
1465 | ||
1466 | default: | |
1467 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) | |
1468 | encoding = ('' + encoding).toLowerCase() | |
1469 | loweredCase = true | |
1470 | } | |
1471 | } | |
1472 | } | |
1473 | ||
1474 | Buffer.prototype.toJSON = function toJSON () { | |
1475 | return { | |
1476 | type: 'Buffer', | |
1477 | data: Array.prototype.slice.call(this._arr || this, 0) | |
1478 | } | |
1479 | } | |
1480 | ||
1481 | function base64Slice (buf, start, end) { | |
1482 | if (start === 0 && end === buf.length) { | |
1483 | return base64.fromByteArray(buf) | |
1484 | } else { | |
1485 | return base64.fromByteArray(buf.slice(start, end)) | |
1486 | } | |
1487 | } | |
1488 | ||
1489 | function utf8Slice (buf, start, end) { | |
1490 | end = Math.min(buf.length, end) | |
1491 | var res = [] | |
1492 | ||
1493 | var i = start | |
1494 | while (i < end) { | |
1495 | var firstByte = buf[i] | |
1496 | var codePoint = null | |
1497 | var bytesPerSequence = (firstByte > 0xEF) ? 4 | |
1498 | : (firstByte > 0xDF) ? 3 | |
1499 | : (firstByte > 0xBF) ? 2 | |
1500 | : 1 | |
1501 | ||
1502 | if (i + bytesPerSequence <= end) { | |
1503 | var secondByte, thirdByte, fourthByte, tempCodePoint | |
1504 | ||
1505 | switch (bytesPerSequence) { | |
1506 | case 1: | |
1507 | if (firstByte < 0x80) { | |
1508 | codePoint = firstByte | |
1509 | } | |
1510 | break | |
1511 | case 2: | |
1512 | secondByte = buf[i + 1] | |
1513 | if ((secondByte & 0xC0) === 0x80) { | |
1514 | tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) | |
1515 | if (tempCodePoint > 0x7F) { | |
1516 | codePoint = tempCodePoint | |
1517 | } | |
1518 | } | |
1519 | break | |
1520 | case 3: | |
1521 | secondByte = buf[i + 1] | |
1522 | thirdByte = buf[i + 2] | |
1523 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { | |
1524 | tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) | |
1525 | if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { | |
1526 | codePoint = tempCodePoint | |
1527 | } | |
1528 | } | |
1529 | break | |
1530 | case 4: | |
1531 | secondByte = buf[i + 1] | |
1532 | thirdByte = buf[i + 2] | |
1533 | fourthByte = buf[i + 3] | |
1534 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { | |
1535 | tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) | |
1536 | if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { | |
1537 | codePoint = tempCodePoint | |
1538 | } | |
1539 | } | |
1540 | } | |
1541 | } | |
1542 | ||
1543 | if (codePoint === null) { | |
1544 | // we did not generate a valid codePoint so insert a | |
1545 | // replacement char (U+FFFD) and advance only 1 byte | |
1546 | codePoint = 0xFFFD | |
1547 | bytesPerSequence = 1 | |
1548 | } else if (codePoint > 0xFFFF) { | |
1549 | // encode to utf16 (surrogate pair dance) | |
1550 | codePoint -= 0x10000 | |
1551 | res.push(codePoint >>> 10 & 0x3FF | 0xD800) | |
1552 | codePoint = 0xDC00 | codePoint & 0x3FF | |
1553 | } | |
1554 | ||
1555 | res.push(codePoint) | |
1556 | i += bytesPerSequence | |
1557 | } | |
1558 | ||
1559 | return decodeCodePointsArray(res) | |
1560 | } | |
1561 | ||
1562 | // Based on http://stackoverflow.com/a/22747272/680742, the browser with | |
1563 | // the lowest limit is Chrome, with 0x10000 args. | |
1564 | // We go 1 magnitude less, for safety | |
1565 | var MAX_ARGUMENTS_LENGTH = 0x1000 | |
1566 | ||
1567 | function decodeCodePointsArray (codePoints) { | |
1568 | var len = codePoints.length | |
1569 | if (len <= MAX_ARGUMENTS_LENGTH) { | |
1570 | return String.fromCharCode.apply(String, codePoints) // avoid extra slice() | |
1571 | } | |
1572 | ||
1573 | // Decode in chunks to avoid "call stack size exceeded". | |
1574 | var res = '' | |
1575 | var i = 0 | |
1576 | while (i < len) { | |
1577 | res += String.fromCharCode.apply( | |
1578 | String, | |
1579 | codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) | |
1580 | ) | |
1581 | } | |
1582 | return res | |
1583 | } | |
1584 | ||
1585 | function asciiSlice (buf, start, end) { | |
1586 | var ret = '' | |
1587 | end = Math.min(buf.length, end) | |
1588 | ||
1589 | for (var i = start; i < end; ++i) { | |
1590 | ret += String.fromCharCode(buf[i] & 0x7F) | |
1591 | } | |
1592 | return ret | |
1593 | } | |
1594 | ||
1595 | function latin1Slice (buf, start, end) { | |
1596 | var ret = '' | |
1597 | end = Math.min(buf.length, end) | |
1598 | ||
1599 | for (var i = start; i < end; ++i) { | |
1600 | ret += String.fromCharCode(buf[i]) | |
1601 | } | |
1602 | return ret | |
1603 | } | |
1604 | ||
1605 | function hexSlice (buf, start, end) { | |
1606 | var len = buf.length | |
1607 | ||
1608 | if (!start || start < 0) start = 0 | |
1609 | if (!end || end < 0 || end > len) end = len | |
1610 | ||
1611 | var out = '' | |
1612 | for (var i = start; i < end; ++i) { | |
1613 | out += toHex(buf[i]) | |
1614 | } | |
1615 | return out | |
1616 | } | |
1617 | ||
1618 | function utf16leSlice (buf, start, end) { | |
1619 | var bytes = buf.slice(start, end) | |
1620 | var res = '' | |
1621 | for (var i = 0; i < bytes.length; i += 2) { | |
1622 | res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) | |
1623 | } | |
1624 | return res | |
1625 | } | |
1626 | ||
1627 | Buffer.prototype.slice = function slice (start, end) { | |
1628 | var len = this.length | |
1629 | start = ~~start | |
1630 | end = end === undefined ? len : ~~end | |
1631 | ||
1632 | if (start < 0) { | |
1633 | start += len | |
1634 | if (start < 0) start = 0 | |
1635 | } else if (start > len) { | |
1636 | start = len | |
1637 | } | |
1638 | ||
1639 | if (end < 0) { | |
1640 | end += len | |
1641 | if (end < 0) end = 0 | |
1642 | } else if (end > len) { | |
1643 | end = len | |
1644 | } | |
1645 | ||
1646 | if (end < start) end = start | |
1647 | ||
1648 | var newBuf = this.subarray(start, end) | |
1649 | // Return an augmented `Uint8Array` instance | |
1650 | newBuf.__proto__ = Buffer.prototype | |
1651 | return newBuf | |
1652 | } | |
1653 | ||
1654 | /* | |
1655 | * Need to make sure that buffer isn't trying to write out of bounds. | |
1656 | */ | |
1657 | function checkOffset (offset, ext, length) { | |
1658 | if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') | |
1659 | if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') | |
1660 | } | |
1661 | ||
1662 | Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { | |
1663 | offset = offset >>> 0 | |
1664 | byteLength = byteLength >>> 0 | |
1665 | if (!noAssert) checkOffset(offset, byteLength, this.length) | |
1666 | ||
1667 | var val = this[offset] | |
1668 | var mul = 1 | |
1669 | var i = 0 | |
1670 | while (++i < byteLength && (mul *= 0x100)) { | |
1671 | val += this[offset + i] * mul | |
1672 | } | |
1673 | ||
1674 | return val | |
1675 | } | |
1676 | ||
1677 | Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { | |
1678 | offset = offset >>> 0 | |
1679 | byteLength = byteLength >>> 0 | |
1680 | if (!noAssert) { | |
1681 | checkOffset(offset, byteLength, this.length) | |
1682 | } | |
1683 | ||
1684 | var val = this[offset + --byteLength] | |
1685 | var mul = 1 | |
1686 | while (byteLength > 0 && (mul *= 0x100)) { | |
1687 | val += this[offset + --byteLength] * mul | |
1688 | } | |
1689 | ||
1690 | return val | |
1691 | } | |
1692 | ||
1693 | Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { | |
1694 | offset = offset >>> 0 | |
1695 | if (!noAssert) checkOffset(offset, 1, this.length) | |
1696 | return this[offset] | |
1697 | } | |
1698 | ||
1699 | Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { | |
1700 | offset = offset >>> 0 | |
1701 | if (!noAssert) checkOffset(offset, 2, this.length) | |
1702 | return this[offset] | (this[offset + 1] << 8) | |
1703 | } | |
1704 | ||
1705 | Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { | |
1706 | offset = offset >>> 0 | |
1707 | if (!noAssert) checkOffset(offset, 2, this.length) | |
1708 | return (this[offset] << 8) | this[offset + 1] | |
1709 | } | |
1710 | ||
1711 | Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { | |
1712 | offset = offset >>> 0 | |
1713 | if (!noAssert) checkOffset(offset, 4, this.length) | |
1714 | ||
1715 | return ((this[offset]) | | |
1716 | (this[offset + 1] << 8) | | |
1717 | (this[offset + 2] << 16)) + | |
1718 | (this[offset + 3] * 0x1000000) | |
1719 | } | |
1720 | ||
1721 | Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { | |
1722 | offset = offset >>> 0 | |
1723 | if (!noAssert) checkOffset(offset, 4, this.length) | |
1724 | ||
1725 | return (this[offset] * 0x1000000) + | |
1726 | ((this[offset + 1] << 16) | | |
1727 | (this[offset + 2] << 8) | | |
1728 | this[offset + 3]) | |
1729 | } | |
1730 | ||
1731 | Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { | |
1732 | offset = offset >>> 0 | |
1733 | byteLength = byteLength >>> 0 | |
1734 | if (!noAssert) checkOffset(offset, byteLength, this.length) | |
1735 | ||
1736 | var val = this[offset] | |
1737 | var mul = 1 | |
1738 | var i = 0 | |
1739 | while (++i < byteLength && (mul *= 0x100)) { | |
1740 | val += this[offset + i] * mul | |
1741 | } | |
1742 | mul *= 0x80 | |
1743 | ||
1744 | if (val >= mul) val -= Math.pow(2, 8 * byteLength) | |
1745 | ||
1746 | return val | |
1747 | } | |
1748 | ||
1749 | Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { | |
1750 | offset = offset >>> 0 | |
1751 | byteLength = byteLength >>> 0 | |
1752 | if (!noAssert) checkOffset(offset, byteLength, this.length) | |
1753 | ||
1754 | var i = byteLength | |
1755 | var mul = 1 | |
1756 | var val = this[offset + --i] | |
1757 | while (i > 0 && (mul *= 0x100)) { | |
1758 | val += this[offset + --i] * mul | |
1759 | } | |
1760 | mul *= 0x80 | |
1761 | ||
1762 | if (val >= mul) val -= Math.pow(2, 8 * byteLength) | |
1763 | ||
1764 | return val | |
1765 | } | |
1766 | ||
1767 | Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { | |
1768 | offset = offset >>> 0 | |
1769 | if (!noAssert) checkOffset(offset, 1, this.length) | |
1770 | if (!(this[offset] & 0x80)) return (this[offset]) | |
1771 | return ((0xff - this[offset] + 1) * -1) | |
1772 | } | |
1773 | ||
1774 | Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { | |
1775 | offset = offset >>> 0 | |
1776 | if (!noAssert) checkOffset(offset, 2, this.length) | |
1777 | var val = this[offset] | (this[offset + 1] << 8) | |
1778 | return (val & 0x8000) ? val | 0xFFFF0000 : val | |
1779 | } | |
1780 | ||
1781 | Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { | |
1782 | offset = offset >>> 0 | |
1783 | if (!noAssert) checkOffset(offset, 2, this.length) | |
1784 | var val = this[offset + 1] | (this[offset] << 8) | |
1785 | return (val & 0x8000) ? val | 0xFFFF0000 : val | |
1786 | } | |
1787 | ||
1788 | Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { | |
1789 | offset = offset >>> 0 | |
1790 | if (!noAssert) checkOffset(offset, 4, this.length) | |
1791 | ||
1792 | return (this[offset]) | | |
1793 | (this[offset + 1] << 8) | | |
1794 | (this[offset + 2] << 16) | | |
1795 | (this[offset + 3] << 24) | |
1796 | } | |
1797 | ||
1798 | Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { | |
1799 | offset = offset >>> 0 | |
1800 | if (!noAssert) checkOffset(offset, 4, this.length) | |
1801 | ||
1802 | return (this[offset] << 24) | | |
1803 | (this[offset + 1] << 16) | | |
1804 | (this[offset + 2] << 8) | | |
1805 | (this[offset + 3]) | |
1806 | } | |
1807 | ||
1808 | Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { | |
1809 | offset = offset >>> 0 | |
1810 | if (!noAssert) checkOffset(offset, 4, this.length) | |
1811 | return ieee754.read(this, offset, true, 23, 4) | |
1812 | } | |
1813 | ||
1814 | Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { | |
1815 | offset = offset >>> 0 | |
1816 | if (!noAssert) checkOffset(offset, 4, this.length) | |
1817 | return ieee754.read(this, offset, false, 23, 4) | |
1818 | } | |
1819 | ||
1820 | Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { | |
1821 | offset = offset >>> 0 | |
1822 | if (!noAssert) checkOffset(offset, 8, this.length) | |
1823 | return ieee754.read(this, offset, true, 52, 8) | |
1824 | } | |
1825 | ||
1826 | Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { | |
1827 | offset = offset >>> 0 | |
1828 | if (!noAssert) checkOffset(offset, 8, this.length) | |
1829 | return ieee754.read(this, offset, false, 52, 8) | |
1830 | } | |
1831 | ||
1832 | function checkInt (buf, value, offset, ext, max, min) { | |
1833 | if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') | |
1834 | if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') | |
1835 | if (offset + ext > buf.length) throw new RangeError('Index out of range') | |
1836 | } | |
1837 | ||
1838 | Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { | |
1839 | value = +value | |
1840 | offset = offset >>> 0 | |
1841 | byteLength = byteLength >>> 0 | |
1842 | if (!noAssert) { | |
1843 | var maxBytes = Math.pow(2, 8 * byteLength) - 1 | |
1844 | checkInt(this, value, offset, byteLength, maxBytes, 0) | |
1845 | } | |
1846 | ||
1847 | var mul = 1 | |
1848 | var i = 0 | |
1849 | this[offset] = value & 0xFF | |
1850 | while (++i < byteLength && (mul *= 0x100)) { | |
1851 | this[offset + i] = (value / mul) & 0xFF | |
1852 | } | |
1853 | ||
1854 | return offset + byteLength | |
1855 | } | |
1856 | ||
1857 | Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { | |
1858 | value = +value | |
1859 | offset = offset >>> 0 | |
1860 | byteLength = byteLength >>> 0 | |
1861 | if (!noAssert) { | |
1862 | var maxBytes = Math.pow(2, 8 * byteLength) - 1 | |
1863 | checkInt(this, value, offset, byteLength, maxBytes, 0) | |
1864 | } | |
1865 | ||
1866 | var i = byteLength - 1 | |
1867 | var mul = 1 | |
1868 | this[offset + i] = value & 0xFF | |
1869 | while (--i >= 0 && (mul *= 0x100)) { | |
1870 | this[offset + i] = (value / mul) & 0xFF | |
1871 | } | |
1872 | ||
1873 | return offset + byteLength | |
1874 | } | |
1875 | ||
1876 | Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { | |
1877 | value = +value | |
1878 | offset = offset >>> 0 | |
1879 | if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) | |
1880 | this[offset] = (value & 0xff) | |
1881 | return offset + 1 | |
1882 | } | |
1883 | ||
1884 | Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { | |
1885 | value = +value | |
1886 | offset = offset >>> 0 | |
1887 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) | |
1888 | this[offset] = (value & 0xff) | |
1889 | this[offset + 1] = (value >>> 8) | |
1890 | return offset + 2 | |
1891 | } | |
1892 | ||
1893 | Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { | |
1894 | value = +value | |
1895 | offset = offset >>> 0 | |
1896 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) | |
1897 | this[offset] = (value >>> 8) | |
1898 | this[offset + 1] = (value & 0xff) | |
1899 | return offset + 2 | |
1900 | } | |
1901 | ||
1902 | Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { | |
1903 | value = +value | |
1904 | offset = offset >>> 0 | |
1905 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) | |
1906 | this[offset + 3] = (value >>> 24) | |
1907 | this[offset + 2] = (value >>> 16) | |
1908 | this[offset + 1] = (value >>> 8) | |
1909 | this[offset] = (value & 0xff) | |
1910 | return offset + 4 | |
1911 | } | |
1912 | ||
1913 | Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { | |
1914 | value = +value | |
1915 | offset = offset >>> 0 | |
1916 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) | |
1917 | this[offset] = (value >>> 24) | |
1918 | this[offset + 1] = (value >>> 16) | |
1919 | this[offset + 2] = (value >>> 8) | |
1920 | this[offset + 3] = (value & 0xff) | |
1921 | return offset + 4 | |
1922 | } | |
1923 | ||
1924 | Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { | |
1925 | value = +value | |
1926 | offset = offset >>> 0 | |
1927 | if (!noAssert) { | |
1928 | var limit = Math.pow(2, (8 * byteLength) - 1) | |
1929 | ||
1930 | checkInt(this, value, offset, byteLength, limit - 1, -limit) | |
1931 | } | |
1932 | ||
1933 | var i = 0 | |
1934 | var mul = 1 | |
1935 | var sub = 0 | |
1936 | this[offset] = value & 0xFF | |
1937 | while (++i < byteLength && (mul *= 0x100)) { | |
1938 | if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { | |
1939 | sub = 1 | |
1940 | } | |
1941 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF | |
1942 | } | |
1943 | ||
1944 | return offset + byteLength | |
1945 | } | |
1946 | ||
1947 | Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { | |
1948 | value = +value | |
1949 | offset = offset >>> 0 | |
1950 | if (!noAssert) { | |
1951 | var limit = Math.pow(2, (8 * byteLength) - 1) | |
1952 | ||
1953 | checkInt(this, value, offset, byteLength, limit - 1, -limit) | |
1954 | } | |
1955 | ||
1956 | var i = byteLength - 1 | |
1957 | var mul = 1 | |
1958 | var sub = 0 | |
1959 | this[offset + i] = value & 0xFF | |
1960 | while (--i >= 0 && (mul *= 0x100)) { | |
1961 | if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { | |
1962 | sub = 1 | |
1963 | } | |
1964 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF | |
1965 | } | |
1966 | ||
1967 | return offset + byteLength | |
1968 | } | |
1969 | ||
1970 | Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { | |
1971 | value = +value | |
1972 | offset = offset >>> 0 | |
1973 | if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) | |
1974 | if (value < 0) value = 0xff + value + 1 | |
1975 | this[offset] = (value & 0xff) | |
1976 | return offset + 1 | |
1977 | } | |
1978 | ||
1979 | Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { | |
1980 | value = +value | |
1981 | offset = offset >>> 0 | |
1982 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) | |
1983 | this[offset] = (value & 0xff) | |
1984 | this[offset + 1] = (value >>> 8) | |
1985 | return offset + 2 | |
1986 | } | |
1987 | ||
1988 | Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { | |
1989 | value = +value | |
1990 | offset = offset >>> 0 | |
1991 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) | |
1992 | this[offset] = (value >>> 8) | |
1993 | this[offset + 1] = (value & 0xff) | |
1994 | return offset + 2 | |
1995 | } | |
1996 | ||
1997 | Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { | |
1998 | value = +value | |
1999 | offset = offset >>> 0 | |
2000 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) | |
2001 | this[offset] = (value & 0xff) | |
2002 | this[offset + 1] = (value >>> 8) | |
2003 | this[offset + 2] = (value >>> 16) | |
2004 | this[offset + 3] = (value >>> 24) | |
2005 | return offset + 4 | |
2006 | } | |
2007 | ||
2008 | Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { | |
2009 | value = +value | |
2010 | offset = offset >>> 0 | |
2011 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) | |
2012 | if (value < 0) value = 0xffffffff + value + 1 | |
2013 | this[offset] = (value >>> 24) | |
2014 | this[offset + 1] = (value >>> 16) | |
2015 | this[offset + 2] = (value >>> 8) | |
2016 | this[offset + 3] = (value & 0xff) | |
2017 | return offset + 4 | |
2018 | } | |
2019 | ||
2020 | function checkIEEE754 (buf, value, offset, ext, max, min) { | |
2021 | if (offset + ext > buf.length) throw new RangeError('Index out of range') | |
2022 | if (offset < 0) throw new RangeError('Index out of range') | |
2023 | } | |
2024 | ||
2025 | function writeFloat (buf, value, offset, littleEndian, noAssert) { | |
2026 | value = +value | |
2027 | offset = offset >>> 0 | |
2028 | if (!noAssert) { | |
2029 | checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) | |
2030 | } | |
2031 | ieee754.write(buf, value, offset, littleEndian, 23, 4) | |
2032 | return offset + 4 | |
2033 | } | |
2034 | ||
2035 | Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { | |
2036 | return writeFloat(this, value, offset, true, noAssert) | |
2037 | } | |
2038 | ||
2039 | Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { | |
2040 | return writeFloat(this, value, offset, false, noAssert) | |
2041 | } | |
2042 | ||
2043 | function writeDouble (buf, value, offset, littleEndian, noAssert) { | |
2044 | value = +value | |
2045 | offset = offset >>> 0 | |
2046 | if (!noAssert) { | |
2047 | checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) | |
2048 | } | |
2049 | ieee754.write(buf, value, offset, littleEndian, 52, 8) | |
2050 | return offset + 8 | |
2051 | } | |
2052 | ||
2053 | Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { | |
2054 | return writeDouble(this, value, offset, true, noAssert) | |
2055 | } | |
2056 | ||
2057 | Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { | |
2058 | return writeDouble(this, value, offset, false, noAssert) | |
2059 | } | |
2060 | ||
2061 | // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) | |
2062 | Buffer.prototype.copy = function copy (target, targetStart, start, end) { | |
2063 | if (!start) start = 0 | |
2064 | if (!end && end !== 0) end = this.length | |
2065 | if (targetStart >= target.length) targetStart = target.length | |
2066 | if (!targetStart) targetStart = 0 | |
2067 | if (end > 0 && end < start) end = start | |
2068 | ||
2069 | // Copy 0 bytes; we're done | |
2070 | if (end === start) return 0 | |
2071 | if (target.length === 0 || this.length === 0) return 0 | |
2072 | ||
2073 | // Fatal error conditions | |
2074 | if (targetStart < 0) { | |
2075 | throw new RangeError('targetStart out of bounds') | |
2076 | } | |
2077 | if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') | |
2078 | if (end < 0) throw new RangeError('sourceEnd out of bounds') | |
2079 | ||
2080 | // Are we oob? | |
2081 | if (end > this.length) end = this.length | |
2082 | if (target.length - targetStart < end - start) { | |
2083 | end = target.length - targetStart + start | |
2084 | } | |
2085 | ||
2086 | var len = end - start | |
2087 | var i | |
2088 | ||
2089 | if (this === target && start < targetStart && targetStart < end) { | |
2090 | // descending copy from end | |
2091 | for (i = len - 1; i >= 0; --i) { | |
2092 | target[i + targetStart] = this[i + start] | |
2093 | } | |
2094 | } else if (len < 1000) { | |
2095 | // ascending copy from start | |
2096 | for (i = 0; i < len; ++i) { | |
2097 | target[i + targetStart] = this[i + start] | |
2098 | } | |
2099 | } else { | |
2100 | Uint8Array.prototype.set.call( | |
2101 | target, | |
2102 | this.subarray(start, start + len), | |
2103 | targetStart | |
2104 | ) | |
2105 | } | |
2106 | ||
2107 | return len | |
2108 | } | |
2109 | ||
2110 | // Usage: | |
2111 | // buffer.fill(number[, offset[, end]]) | |
2112 | // buffer.fill(buffer[, offset[, end]]) | |
2113 | // buffer.fill(string[, offset[, end]][, encoding]) | |
2114 | Buffer.prototype.fill = function fill (val, start, end, encoding) { | |
2115 | // Handle string cases: | |
2116 | if (typeof val === 'string') { | |
2117 | if (typeof start === 'string') { | |
2118 | encoding = start | |
2119 | start = 0 | |
2120 | end = this.length | |
2121 | } else if (typeof end === 'string') { | |
2122 | encoding = end | |
2123 | end = this.length | |
2124 | } | |
2125 | if (val.length === 1) { | |
2126 | var code = val.charCodeAt(0) | |
2127 | if (code < 256) { | |
2128 | val = code | |
2129 | } | |
2130 | } | |
2131 | if (encoding !== undefined && typeof encoding !== 'string') { | |
2132 | throw new TypeError('encoding must be a string') | |
2133 | } | |
2134 | if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { | |
2135 | throw new TypeError('Unknown encoding: ' + encoding) | |
2136 | } | |
2137 | } else if (typeof val === 'number') { | |
2138 | val = val & 255 | |
2139 | } | |
2140 | ||
2141 | // Invalid ranges are not set to a default, so can range check early. | |
2142 | if (start < 0 || this.length < start || this.length < end) { | |
2143 | throw new RangeError('Out of range index') | |
2144 | } | |
2145 | ||
2146 | if (end <= start) { | |
2147 | return this | |
2148 | } | |
2149 | ||
2150 | start = start >>> 0 | |
2151 | end = end === undefined ? this.length : end >>> 0 | |
2152 | ||
2153 | if (!val) val = 0 | |
2154 | ||
2155 | var i | |
2156 | if (typeof val === 'number') { | |
2157 | for (i = start; i < end; ++i) { | |
2158 | this[i] = val | |
2159 | } | |
2160 | } else { | |
2161 | var bytes = Buffer.isBuffer(val) | |
2162 | ? val | |
2163 | : new Buffer(val, encoding) | |
2164 | var len = bytes.length | |
2165 | for (i = 0; i < end - start; ++i) { | |
2166 | this[i + start] = bytes[i % len] | |
2167 | } | |
2168 | } | |
2169 | ||
2170 | return this | |
2171 | } | |
2172 | ||
2173 | // HELPER FUNCTIONS | |
2174 | // ================ | |
2175 | ||
2176 | var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g | |
2177 | ||
2178 | function base64clean (str) { | |
2179 | // Node strips out invalid characters like \n and \t from the string, base64-js does not | |
2180 | str = str.trim().replace(INVALID_BASE64_RE, '') | |
2181 | // Node converts strings with length < 2 to '' | |
2182 | if (str.length < 2) return '' | |
2183 | // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not | |
2184 | while (str.length % 4 !== 0) { | |
2185 | str = str + '=' | |
2186 | } | |
2187 | return str | |
2188 | } | |
2189 | ||
2190 | function toHex (n) { | |
2191 | if (n < 16) return '0' + n.toString(16) | |
2192 | return n.toString(16) | |
2193 | } | |
2194 | ||
2195 | function utf8ToBytes (string, units) { | |
2196 | units = units || Infinity | |
2197 | var codePoint | |
2198 | var length = string.length | |
2199 | var leadSurrogate = null | |
2200 | var bytes = [] | |
2201 | ||
2202 | for (var i = 0; i < length; ++i) { | |
2203 | codePoint = string.charCodeAt(i) | |
2204 | ||
2205 | // is surrogate component | |
2206 | if (codePoint > 0xD7FF && codePoint < 0xE000) { | |
2207 | // last char was a lead | |
2208 | if (!leadSurrogate) { | |
2209 | // no lead yet | |
2210 | if (codePoint > 0xDBFF) { | |
2211 | // unexpected trail | |
2212 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) | |
2213 | continue | |
2214 | } else if (i + 1 === length) { | |
2215 | // unpaired lead | |
2216 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) | |
2217 | continue | |
2218 | } | |
2219 | ||
2220 | // valid lead | |
2221 | leadSurrogate = codePoint | |
2222 | ||
2223 | continue | |
2224 | } | |
2225 | ||
2226 | // 2 leads in a row | |
2227 | if (codePoint < 0xDC00) { | |
2228 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) | |
2229 | leadSurrogate = codePoint | |
2230 | continue | |
2231 | } | |
2232 | ||
2233 | // valid surrogate pair | |
2234 | codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 | |
2235 | } else if (leadSurrogate) { | |
2236 | // valid bmp char, but last char was a lead | |
2237 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) | |
2238 | } | |
2239 | ||
2240 | leadSurrogate = null | |
2241 | ||
2242 | // encode utf8 | |
2243 | if (codePoint < 0x80) { | |
2244 | if ((units -= 1) < 0) break | |
2245 | bytes.push(codePoint) | |
2246 | } else if (codePoint < 0x800) { | |
2247 | if ((units -= 2) < 0) break | |
2248 | bytes.push( | |
2249 | codePoint >> 0x6 | 0xC0, | |
2250 | codePoint & 0x3F | 0x80 | |
2251 | ) | |
2252 | } else if (codePoint < 0x10000) { | |
2253 | if ((units -= 3) < 0) break | |
2254 | bytes.push( | |
2255 | codePoint >> 0xC | 0xE0, | |
2256 | codePoint >> 0x6 & 0x3F | 0x80, | |
2257 | codePoint & 0x3F | 0x80 | |
2258 | ) | |
2259 | } else if (codePoint < 0x110000) { | |
2260 | if ((units -= 4) < 0) break | |
2261 | bytes.push( | |
2262 | codePoint >> 0x12 | 0xF0, | |
2263 | codePoint >> 0xC & 0x3F | 0x80, | |
2264 | codePoint >> 0x6 & 0x3F | 0x80, | |
2265 | codePoint & 0x3F | 0x80 | |
2266 | ) | |
2267 | } else { | |
2268 | throw new Error('Invalid code point') | |
2269 | } | |
2270 | } | |
2271 | ||
2272 | return bytes | |
2273 | } | |
2274 | ||
2275 | function asciiToBytes (str) { | |
2276 | var byteArray = [] | |
2277 | for (var i = 0; i < str.length; ++i) { | |
2278 | // Node's code seems to be doing this and not & 0x7F.. | |
2279 | byteArray.push(str.charCodeAt(i) & 0xFF) | |
2280 | } | |
2281 | return byteArray | |
2282 | } | |
2283 | ||
2284 | function utf16leToBytes (str, units) { | |
2285 | var c, hi, lo | |
2286 | var byteArray = [] | |
2287 | for (var i = 0; i < str.length; ++i) { | |
2288 | if ((units -= 2) < 0) break | |
2289 | ||
2290 | c = str.charCodeAt(i) | |
2291 | hi = c >> 8 | |
2292 | lo = c % 256 | |
2293 | byteArray.push(lo) | |
2294 | byteArray.push(hi) | |
2295 | } | |
2296 | ||
2297 | return byteArray | |
2298 | } | |
2299 | ||
2300 | function base64ToBytes (str) { | |
2301 | return base64.toByteArray(base64clean(str)) | |
2302 | } | |
2303 | ||
2304 | function blitBuffer (src, dst, offset, length) { | |
2305 | for (var i = 0; i < length; ++i) { | |
2306 | if ((i + offset >= dst.length) || (i >= src.length)) break | |
2307 | dst[i + offset] = src[i] | |
2308 | } | |
2309 | return i | |
2310 | } | |
2311 | ||
2312 | // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` | |
2313 | function isArrayBufferView (obj) { | |
2314 | return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) | |
2315 | } | |
2316 | ||
2317 | function numberIsNaN (obj) { | |
2318 | return obj !== obj // eslint-disable-line no-self-compare | |
2319 | } | |
2320 | ||
2321 | },{"base64-js":2,"ieee754":7}],5:[function(require,module,exports){ | |
2322 | (function (Buffer){ | |
2323 | // Copyright Joyent, Inc. and other Node contributors. | |
2324 | // | |
2325 | // Permission is hereby granted, free of charge, to any person obtaining a | |
2326 | // copy of this software and associated documentation files (the | |
2327 | // "Software"), to deal in the Software without restriction, including | |
2328 | // without limitation the rights to use, copy, modify, merge, publish, | |
2329 | // distribute, sublicense, and/or sell copies of the Software, and to permit | |
2330 | // persons to whom the Software is furnished to do so, subject to the | |
2331 | // following conditions: | |
2332 | // | |
2333 | // The above copyright notice and this permission notice shall be included | |
2334 | // in all copies or substantial portions of the Software. | |
2335 | // | |
2336 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
2337 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
2338 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | |
2339 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | |
2340 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | |
2341 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
2342 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | |
2343 | ||
2344 | // NOTE: These type checking functions intentionally don't use `instanceof` | |
2345 | // because it is fragile and can be easily faked with `Object.create()`. | |
2346 | ||
2347 | function isArray(arg) { | |
2348 | if (Array.isArray) { | |
2349 | return Array.isArray(arg); | |
2350 | } | |
2351 | return objectToString(arg) === '[object Array]'; | |
2352 | } | |
2353 | exports.isArray = isArray; | |
2354 | ||
2355 | function isBoolean(arg) { | |
2356 | return typeof arg === 'boolean'; | |
2357 | } | |
2358 | exports.isBoolean = isBoolean; | |
2359 | ||
2360 | function isNull(arg) { | |
2361 | return arg === null; | |
2362 | } | |
2363 | exports.isNull = isNull; | |
2364 | ||
2365 | function isNullOrUndefined(arg) { | |
2366 | return arg == null; | |
2367 | } | |
2368 | exports.isNullOrUndefined = isNullOrUndefined; | |
2369 | ||
2370 | function isNumber(arg) { | |
2371 | return typeof arg === 'number'; | |
2372 | } | |
2373 | exports.isNumber = isNumber; | |
2374 | ||
2375 | function isString(arg) { | |
2376 | return typeof arg === 'string'; | |
2377 | } | |
2378 | exports.isString = isString; | |
2379 | ||
2380 | function isSymbol(arg) { | |
2381 | return typeof arg === 'symbol'; | |
2382 | } | |
2383 | exports.isSymbol = isSymbol; | |
2384 | ||
2385 | function isUndefined(arg) { | |
2386 | return arg === void 0; | |
2387 | } | |
2388 | exports.isUndefined = isUndefined; | |
2389 | ||
2390 | function isRegExp(re) { | |
2391 | return objectToString(re) === '[object RegExp]'; | |
2392 | } | |
2393 | exports.isRegExp = isRegExp; | |
2394 | ||
2395 | function isObject(arg) { | |
2396 | return typeof arg === 'object' && arg !== null; | |
2397 | } | |
2398 | exports.isObject = isObject; | |
2399 | ||
2400 | function isDate(d) { | |
2401 | return objectToString(d) === '[object Date]'; | |
2402 | } | |
2403 | exports.isDate = isDate; | |
2404 | ||
2405 | function isError(e) { | |
2406 | return (objectToString(e) === '[object Error]' || e instanceof Error); | |
2407 | } | |
2408 | exports.isError = isError; | |
2409 | ||
2410 | function isFunction(arg) { | |
2411 | return typeof arg === 'function'; | |
2412 | } | |
2413 | exports.isFunction = isFunction; | |
2414 | ||
2415 | function isPrimitive(arg) { | |
2416 | return arg === null || | |
2417 | typeof arg === 'boolean' || | |
2418 | typeof arg === 'number' || | |
2419 | typeof arg === 'string' || | |
2420 | typeof arg === 'symbol' || // ES6 symbol | |
2421 | typeof arg === 'undefined'; | |
2422 | } | |
2423 | exports.isPrimitive = isPrimitive; | |
2424 | ||
2425 | exports.isBuffer = Buffer.isBuffer; | |
2426 | ||
2427 | function objectToString(o) { | |
2428 | return Object.prototype.toString.call(o); | |
2429 | } | |
2430 | ||
2431 | }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) | |
2432 | },{"../../is-buffer/index.js":9}],6:[function(require,module,exports){ | |
2433 | // Copyright Joyent, Inc. and other Node contributors. | |
2434 | // | |
2435 | // Permission is hereby granted, free of charge, to any person obtaining a | |
2436 | // copy of this software and associated documentation files (the | |
2437 | // "Software"), to deal in the Software without restriction, including | |
2438 | // without limitation the rights to use, copy, modify, merge, publish, | |
2439 | // distribute, sublicense, and/or sell copies of the Software, and to permit | |
2440 | // persons to whom the Software is furnished to do so, subject to the | |
2441 | // following conditions: | |
2442 | // | |
2443 | // The above copyright notice and this permission notice shall be included | |
2444 | // in all copies or substantial portions of the Software. | |
2445 | // | |
2446 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
2447 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
2448 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | |
2449 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | |
2450 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | |
2451 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
2452 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | |
2453 | ||
2454 | function EventEmitter() { | |
2455 | this._events = this._events || {}; | |
2456 | this._maxListeners = this._maxListeners || undefined; | |
2457 | } | |
2458 | module.exports = EventEmitter; | |
2459 | ||
2460 | // Backwards-compat with node 0.10.x | |
2461 | EventEmitter.EventEmitter = EventEmitter; | |
2462 | ||
2463 | EventEmitter.prototype._events = undefined; | |
2464 | EventEmitter.prototype._maxListeners = undefined; | |
2465 | ||
2466 | // By default EventEmitters will print a warning if more than 10 listeners are | |
2467 | // added to it. This is a useful default which helps finding memory leaks. | |
2468 | EventEmitter.defaultMaxListeners = 10; | |
2469 | ||
2470 | // Obviously not all Emitters should be limited to 10. This function allows | |
2471 | // that to be increased. Set to zero for unlimited. | |
2472 | EventEmitter.prototype.setMaxListeners = function(n) { | |
2473 | if (!isNumber(n) || n < 0 || isNaN(n)) | |
2474 | throw TypeError('n must be a positive number'); | |
2475 | this._maxListeners = n; | |
2476 | return this; | |
2477 | }; | |
2478 | ||
2479 | EventEmitter.prototype.emit = function(type) { | |
2480 | var er, handler, len, args, i, listeners; | |
2481 | ||
2482 | if (!this._events) | |
2483 | this._events = {}; | |
2484 | ||
2485 | // If there is no 'error' event listener then throw. | |
2486 | if (type === 'error') { | |
2487 | if (!this._events.error || | |
2488 | (isObject(this._events.error) && !this._events.error.length)) { | |
2489 | er = arguments[1]; | |
2490 | if (er instanceof Error) { | |
2491 | throw er; // Unhandled 'error' event | |
2492 | } else { | |
2493 | // At least give some kind of context to the user | |
2494 | var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); | |
2495 | err.context = er; | |
2496 | throw err; | |
2497 | } | |
2498 | } | |
2499 | } | |
2500 | ||
2501 | handler = this._events[type]; | |
2502 | ||
2503 | if (isUndefined(handler)) | |
2504 | return false; | |
2505 | ||
2506 | if (isFunction(handler)) { | |
2507 | switch (arguments.length) { | |
2508 | // fast cases | |
2509 | case 1: | |
2510 | handler.call(this); | |
2511 | break; | |
2512 | case 2: | |
2513 | handler.call(this, arguments[1]); | |
2514 | break; | |
2515 | case 3: | |
2516 | handler.call(this, arguments[1], arguments[2]); | |
2517 | break; | |
2518 | // slower | |
2519 | default: | |
2520 | args = Array.prototype.slice.call(arguments, 1); | |
2521 | handler.apply(this, args); | |
2522 | } | |
2523 | } else if (isObject(handler)) { | |
2524 | args = Array.prototype.slice.call(arguments, 1); | |
2525 | listeners = handler.slice(); | |
2526 | len = listeners.length; | |
2527 | for (i = 0; i < len; i++) | |
2528 | listeners[i].apply(this, args); | |
2529 | } | |
2530 | ||
2531 | return true; | |
2532 | }; | |
2533 | ||
2534 | EventEmitter.prototype.addListener = function(type, listener) { | |
2535 | var m; | |
2536 | ||
2537 | if (!isFunction(listener)) | |
2538 | throw TypeError('listener must be a function'); | |
2539 | ||
2540 | if (!this._events) | |
2541 | this._events = {}; | |
2542 | ||
2543 | // To avoid recursion in the case that type === "newListener"! Before | |
2544 | // adding it to the listeners, first emit "newListener". | |
2545 | if (this._events.newListener) | |
2546 | this.emit('newListener', type, | |
2547 | isFunction(listener.listener) ? | |
2548 | listener.listener : listener); | |
2549 | ||
2550 | if (!this._events[type]) | |
2551 | // Optimize the case of one listener. Don't need the extra array object. | |
2552 | this._events[type] = listener; | |
2553 | else if (isObject(this._events[type])) | |
2554 | // If we've already got an array, just append. | |
2555 | this._events[type].push(listener); | |
2556 | else | |
2557 | // Adding the second element, need to change to array. | |
2558 | this._events[type] = [this._events[type], listener]; | |
2559 | ||
2560 | // Check for listener leak | |
2561 | if (isObject(this._events[type]) && !this._events[type].warned) { | |
2562 | if (!isUndefined(this._maxListeners)) { | |
2563 | m = this._maxListeners; | |
2564 | } else { | |
2565 | m = EventEmitter.defaultMaxListeners; | |
2566 | } | |
2567 | ||
2568 | if (m && m > 0 && this._events[type].length > m) { | |
2569 | this._events[type].warned = true; | |
2570 | console.error('(node) warning: possible EventEmitter memory ' + | |
2571 | 'leak detected. %d listeners added. ' + | |
2572 | 'Use emitter.setMaxListeners() to increase limit.', | |
2573 | this._events[type].length); | |
2574 | if (typeof console.trace === 'function') { | |
2575 | // not supported in IE 10 | |
2576 | console.trace(); | |
2577 | } | |
2578 | } | |
2579 | } | |
2580 | ||
2581 | return this; | |
2582 | }; | |
2583 | ||
2584 | EventEmitter.prototype.on = EventEmitter.prototype.addListener; | |
2585 | ||
2586 | EventEmitter.prototype.once = function(type, listener) { | |
2587 | if (!isFunction(listener)) | |
2588 | throw TypeError('listener must be a function'); | |
2589 | ||
2590 | var fired = false; | |
2591 | ||
2592 | function g() { | |
2593 | this.removeListener(type, g); | |
2594 | ||
2595 | if (!fired) { | |
2596 | fired = true; | |
2597 | listener.apply(this, arguments); | |
2598 | } | |
2599 | } | |
2600 | ||
2601 | g.listener = listener; | |
2602 | this.on(type, g); | |
2603 | ||
2604 | return this; | |
2605 | }; | |
2606 | ||
2607 | // emits a 'removeListener' event iff the listener was removed | |
2608 | EventEmitter.prototype.removeListener = function(type, listener) { | |
2609 | var list, position, length, i; | |
2610 | ||
2611 | if (!isFunction(listener)) | |
2612 | throw TypeError('listener must be a function'); | |
2613 | ||
2614 | if (!this._events || !this._events[type]) | |
2615 | return this; | |
2616 | ||
2617 | list = this._events[type]; | |
2618 | length = list.length; | |
2619 | position = -1; | |
2620 | ||
2621 | if (list === listener || | |
2622 | (isFunction(list.listener) && list.listener === listener)) { | |
2623 | delete this._events[type]; | |
2624 | if (this._events.removeListener) | |
2625 | this.emit('removeListener', type, listener); | |
2626 | ||
2627 | } else if (isObject(list)) { | |
2628 | for (i = length; i-- > 0;) { | |
2629 | if (list[i] === listener || | |
2630 | (list[i].listener && list[i].listener === listener)) { | |
2631 | position = i; | |
2632 | break; | |
2633 | } | |
2634 | } | |
2635 | ||
2636 | if (position < 0) | |
2637 | return this; | |
2638 | ||
2639 | if (list.length === 1) { | |
2640 | list.length = 0; | |
2641 | delete this._events[type]; | |
2642 | } else { | |
2643 | list.splice(position, 1); | |
2644 | } | |
2645 | ||
2646 | if (this._events.removeListener) | |
2647 | this.emit('removeListener', type, listener); | |
2648 | } | |
2649 | ||
2650 | return this; | |
2651 | }; | |
2652 | ||
2653 | EventEmitter.prototype.removeAllListeners = function(type) { | |
2654 | var key, listeners; | |
2655 | ||
2656 | if (!this._events) | |
2657 | return this; | |
2658 | ||
2659 | // not listening for removeListener, no need to emit | |
2660 | if (!this._events.removeListener) { | |
2661 | if (arguments.length === 0) | |
2662 | this._events = {}; | |
2663 | else if (this._events[type]) | |
2664 | delete this._events[type]; | |
2665 | return this; | |
2666 | } | |
2667 | ||
2668 | // emit removeListener for all listeners on all events | |
2669 | if (arguments.length === 0) { | |
2670 | for (key in this._events) { | |
2671 | if (key === 'removeListener') continue; | |
2672 | this.removeAllListeners(key); | |
2673 | } | |
2674 | this.removeAllListeners('removeListener'); | |
2675 | this._events = {}; | |
2676 | return this; | |
2677 | } | |
2678 | ||
2679 | listeners = this._events[type]; | |
2680 | ||
2681 | if (isFunction(listeners)) { | |
2682 | this.removeListener(type, listeners); | |
2683 | } else if (listeners) { | |
2684 | // LIFO order | |
2685 | while (listeners.length) | |
2686 | this.removeListener(type, listeners[listeners.length - 1]); | |
2687 | } | |
2688 | delete this._events[type]; | |
2689 | ||
2690 | return this; | |
2691 | }; | |
2692 | ||
2693 | EventEmitter.prototype.listeners = function(type) { | |
2694 | var ret; | |
2695 | if (!this._events || !this._events[type]) | |
2696 | ret = []; | |
2697 | else if (isFunction(this._events[type])) | |
2698 | ret = [this._events[type]]; | |
2699 | else | |
2700 | ret = this._events[type].slice(); | |
2701 | return ret; | |
2702 | }; | |
2703 | ||
2704 | EventEmitter.prototype.listenerCount = function(type) { | |
2705 | if (this._events) { | |
2706 | var evlistener = this._events[type]; | |
2707 | ||
2708 | if (isFunction(evlistener)) | |
2709 | return 1; | |
2710 | else if (evlistener) | |
2711 | return evlistener.length; | |
2712 | } | |
2713 | return 0; | |
2714 | }; | |
2715 | ||
2716 | EventEmitter.listenerCount = function(emitter, type) { | |
2717 | return emitter.listenerCount(type); | |
2718 | }; | |
2719 | ||
2720 | function isFunction(arg) { | |
2721 | return typeof arg === 'function'; | |
2722 | } | |
2723 | ||
2724 | function isNumber(arg) { | |
2725 | return typeof arg === 'number'; | |
2726 | } | |
2727 | ||
2728 | function isObject(arg) { | |
2729 | return typeof arg === 'object' && arg !== null; | |
2730 | } | |
2731 | ||
2732 | function isUndefined(arg) { | |
2733 | return arg === void 0; | |
2734 | } | |
2735 | ||
2736 | },{}],7:[function(require,module,exports){ | |
2737 | exports.read = function (buffer, offset, isLE, mLen, nBytes) { | |
2738 | var e, m | |
2739 | var eLen = nBytes * 8 - mLen - 1 | |
2740 | var eMax = (1 << eLen) - 1 | |
2741 | var eBias = eMax >> 1 | |
2742 | var nBits = -7 | |
2743 | var i = isLE ? (nBytes - 1) : 0 | |
2744 | var d = isLE ? -1 : 1 | |
2745 | var s = buffer[offset + i] | |
2746 | ||
2747 | i += d | |
2748 | ||
2749 | e = s & ((1 << (-nBits)) - 1) | |
2750 | s >>= (-nBits) | |
2751 | nBits += eLen | |
2752 | for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} | |
2753 | ||
2754 | m = e & ((1 << (-nBits)) - 1) | |
2755 | e >>= (-nBits) | |
2756 | nBits += mLen | |
2757 | for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} | |
2758 | ||
2759 | if (e === 0) { | |
2760 | e = 1 - eBias | |
2761 | } else if (e === eMax) { | |
2762 | return m ? NaN : ((s ? -1 : 1) * Infinity) | |
2763 | } else { | |
2764 | m = m + Math.pow(2, mLen) | |
2765 | e = e - eBias | |
2766 | } | |
2767 | return (s ? -1 : 1) * m * Math.pow(2, e - mLen) | |
2768 | } | |
2769 | ||
2770 | exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { | |
2771 | var e, m, c | |
2772 | var eLen = nBytes * 8 - mLen - 1 | |
2773 | var eMax = (1 << eLen) - 1 | |
2774 | var eBias = eMax >> 1 | |
2775 | var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) | |
2776 | var i = isLE ? 0 : (nBytes - 1) | |
2777 | var d = isLE ? 1 : -1 | |
2778 | var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 | |
2779 | ||
2780 | value = Math.abs(value) | |
2781 | ||
2782 | if (isNaN(value) || value === Infinity) { | |
2783 | m = isNaN(value) ? 1 : 0 | |
2784 | e = eMax | |
2785 | } else { | |
2786 | e = Math.floor(Math.log(value) / Math.LN2) | |
2787 | if (value * (c = Math.pow(2, -e)) < 1) { | |
2788 | e-- | |
2789 | c *= 2 | |
2790 | } | |
2791 | if (e + eBias >= 1) { | |
2792 | value += rt / c | |
2793 | } else { | |
2794 | value += rt * Math.pow(2, 1 - eBias) | |
2795 | } | |
2796 | if (value * c >= 2) { | |
2797 | e++ | |
2798 | c /= 2 | |
2799 | } | |
2800 | ||
2801 | if (e + eBias >= eMax) { | |
2802 | m = 0 | |
2803 | e = eMax | |
2804 | } else if (e + eBias >= 1) { | |
2805 | m = (value * c - 1) * Math.pow(2, mLen) | |
2806 | e = e + eBias | |
2807 | } else { | |
2808 | m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) | |
2809 | e = 0 | |
2810 | } | |
2811 | } | |
2812 | ||
2813 | for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} | |
2814 | ||
2815 | e = (e << mLen) | m | |
2816 | eLen += mLen | |
2817 | for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} | |
2818 | ||
2819 | buffer[offset + i - d] |= s * 128 | |
2820 | } | |
2821 | ||
2822 | },{}],8:[function(require,module,exports){ | |
2823 | if (typeof Object.create === 'function') { | |
2824 | // implementation from standard node.js 'util' module | |
2825 | module.exports = function inherits(ctor, superCtor) { | |
2826 | ctor.super_ = superCtor | |
2827 | ctor.prototype = Object.create(superCtor.prototype, { | |
2828 | constructor: { | |
2829 | value: ctor, | |
2830 | enumerable: false, | |
2831 | writable: true, | |
2832 | configurable: true | |
2833 | } | |
2834 | }); | |
2835 | }; | |
2836 | } else { | |
2837 | // old school shim for old browsers | |
2838 | module.exports = function inherits(ctor, superCtor) { | |
2839 | ctor.super_ = superCtor | |
2840 | var TempCtor = function () {} | |
2841 | TempCtor.prototype = superCtor.prototype | |
2842 | ctor.prototype = new TempCtor() | |
2843 | ctor.prototype.constructor = ctor | |
2844 | } | |
2845 | } | |
2846 | ||
2847 | },{}],9:[function(require,module,exports){ | |
2848 | /*! | |
2849 | * Determine if an object is a Buffer | |
2850 | * | |
2851 | * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org> | |
2852 | * @license MIT | |
2853 | */ | |
2854 | ||
2855 | // The _isBuffer check is for Safari 5-7 support, because it's missing | |
2856 | // Object.prototype.constructor. Remove this eventually | |
2857 | module.exports = function (obj) { | |
2858 | return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) | |
2859 | } | |
2860 | ||
2861 | function isBuffer (obj) { | |
2862 | return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) | |
2863 | } | |
2864 | ||
2865 | // For Node v0.10 support. Remove this eventually. | |
2866 | function isSlowBuffer (obj) { | |
2867 | return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) | |
2868 | } | |
2869 | ||
2870 | },{}],10:[function(require,module,exports){ | |
2871 | var toString = {}.toString; | |
2872 | ||
2873 | module.exports = Array.isArray || function (arr) { | |
2874 | return toString.call(arr) == '[object Array]'; | |
2875 | }; | |
2876 | ||
2877 | },{}],11:[function(require,module,exports){ | |
2878 | (function (process){ | |
2879 | 'use strict'; | |
2880 | ||
2881 | if (!process.version || | |
2882 | process.version.indexOf('v0.') === 0 || | |
2883 | process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { | |
2884 | module.exports = nextTick; | |
2885 | } else { | |
2886 | module.exports = process.nextTick; | |
2887 | } | |
2888 | ||
2889 | function nextTick(fn, arg1, arg2, arg3) { | |
2890 | if (typeof fn !== 'function') { | |
2891 | throw new TypeError('"callback" argument must be a function'); | |
2892 | } | |
2893 | var len = arguments.length; | |
2894 | var args, i; | |
2895 | switch (len) { | |
2896 | case 0: | |
2897 | case 1: | |
2898 | return process.nextTick(fn); | |
2899 | case 2: | |
2900 | return process.nextTick(function afterTickOne() { | |
2901 | fn.call(null, arg1); | |
2902 | }); | |
2903 | case 3: | |
2904 | return process.nextTick(function afterTickTwo() { | |
2905 | fn.call(null, arg1, arg2); | |
2906 | }); | |
2907 | case 4: | |
2908 | return process.nextTick(function afterTickThree() { | |
2909 | fn.call(null, arg1, arg2, arg3); | |
2910 | }); | |
2911 | default: | |
2912 | args = new Array(len - 1); | |
2913 | i = 0; | |
2914 | while (i < args.length) { | |
2915 | args[i++] = arguments[i]; | |
2916 | } | |
2917 | return process.nextTick(function afterTick() { | |
2918 | fn.apply(null, args); | |
2919 | }); | |
2920 | } | |
2921 | } | |
2922 | ||
2923 | }).call(this,require('_process')) | |
2924 | },{"_process":12}],12:[function(require,module,exports){ | |
2925 | // shim for using process in browser | |
2926 | var process = module.exports = {}; | |
2927 | ||
2928 | // cached from whatever global is present so that test runners that stub it | |
2929 | // don't break things. But we need to wrap it in a try catch in case it is | |
2930 | // wrapped in strict mode code which doesn't define any globals. It's inside a | |
2931 | // function because try/catches deoptimize in certain engines. | |
2932 | ||
2933 | var cachedSetTimeout; | |
2934 | var cachedClearTimeout; | |
2935 | ||
2936 | function defaultSetTimout() { | |
2937 | throw new Error('setTimeout has not been defined'); | |
2938 | } | |
2939 | function defaultClearTimeout () { | |
2940 | throw new Error('clearTimeout has not been defined'); | |
2941 | } | |
2942 | (function () { | |
2943 | try { | |
2944 | if (typeof setTimeout === 'function') { | |
2945 | cachedSetTimeout = setTimeout; | |
2946 | } else { | |
2947 | cachedSetTimeout = defaultSetTimout; | |
2948 | } | |
2949 | } catch (e) { | |
2950 | cachedSetTimeout = defaultSetTimout; | |
2951 | } | |
2952 | try { | |
2953 | if (typeof clearTimeout === 'function') { | |
2954 | cachedClearTimeout = clearTimeout; | |
2955 | } else { | |
2956 | cachedClearTimeout = defaultClearTimeout; | |
2957 | } | |
2958 | } catch (e) { | |
2959 | cachedClearTimeout = defaultClearTimeout; | |
2960 | } | |
2961 | } ()) | |
2962 | function runTimeout(fun) { | |
2963 | if (cachedSetTimeout === setTimeout) { | |
2964 | //normal enviroments in sane situations | |
2965 | return setTimeout(fun, 0); | |
2966 | } | |
2967 | // if setTimeout wasn't available but was latter defined | |
2968 | if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { | |
2969 | cachedSetTimeout = setTimeout; | |
2970 | return setTimeout(fun, 0); | |
2971 | } | |
2972 | try { | |
2973 | // when when somebody has screwed with setTimeout but no I.E. maddness | |
2974 | return cachedSetTimeout(fun, 0); | |
2975 | } catch(e){ | |
2976 | try { | |
2977 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally | |
2978 | return cachedSetTimeout.call(null, fun, 0); | |
2979 | } catch(e){ | |
2980 | // 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 | |
2981 | return cachedSetTimeout.call(this, fun, 0); | |
2982 | } | |
2983 | } | |
2984 | ||
2985 | ||
2986 | } | |
2987 | function runClearTimeout(marker) { | |
2988 | if (cachedClearTimeout === clearTimeout) { | |
2989 | //normal enviroments in sane situations | |
2990 | return clearTimeout(marker); | |
2991 | } | |
2992 | // if clearTimeout wasn't available but was latter defined | |
2993 | if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { | |
2994 | cachedClearTimeout = clearTimeout; | |
2995 | return clearTimeout(marker); | |
2996 | } | |
2997 | try { | |
2998 | // when when somebody has screwed with setTimeout but no I.E. maddness | |
2999 | return cachedClearTimeout(marker); | |
3000 | } catch (e){ | |
3001 | try { | |
3002 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally | |
3003 | return cachedClearTimeout.call(null, marker); | |
3004 | } catch (e){ | |
3005 | // 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. | |
3006 | // Some versions of I.E. have different rules for clearTimeout vs setTimeout | |
3007 | return cachedClearTimeout.call(this, marker); | |
3008 | } | |
3009 | } | |
3010 | ||
3011 | ||
3012 | ||
3013 | } | |
3014 | var queue = []; | |
3015 | var draining = false; | |
3016 | var currentQueue; | |
3017 | var queueIndex = -1; | |
3018 | ||
3019 | function cleanUpNextTick() { | |
3020 | if (!draining || !currentQueue) { | |
3021 | return; | |
3022 | } | |
3023 | draining = false; | |
3024 | if (currentQueue.length) { | |
3025 | queue = currentQueue.concat(queue); | |
3026 | } else { | |
3027 | queueIndex = -1; | |
3028 | } | |
3029 | if (queue.length) { | |
3030 | drainQueue(); | |
3031 | } | |
3032 | } | |
3033 | ||
3034 | function drainQueue() { | |
3035 | if (draining) { | |
3036 | return; | |
3037 | } | |
3038 | var timeout = runTimeout(cleanUpNextTick); | |
3039 | draining = true; | |
3040 | ||
3041 | var len = queue.length; | |
3042 | while(len) { | |
3043 | currentQueue = queue; | |
3044 | queue = []; | |
3045 | while (++queueIndex < len) { | |
3046 | if (currentQueue) { | |
3047 | currentQueue[queueIndex].run(); | |
3048 | } | |
3049 | } | |
3050 | queueIndex = -1; | |
3051 | len = queue.length; | |
3052 | } | |
3053 | currentQueue = null; | |
3054 | draining = false; | |
3055 | runClearTimeout(timeout); | |
3056 | } | |
3057 | ||
3058 | process.nextTick = function (fun) { | |
3059 | var args = new Array(arguments.length - 1); | |
3060 | if (arguments.length > 1) { | |
3061 | for (var i = 1; i < arguments.length; i++) { | |
3062 | args[i - 1] = arguments[i]; | |
3063 | } | |
3064 | } | |
3065 | queue.push(new Item(fun, args)); | |
3066 | if (queue.length === 1 && !draining) { | |
3067 | runTimeout(drainQueue); | |
3068 | } | |
3069 | }; | |
3070 | ||
3071 | // v8 likes predictible objects | |
3072 | function Item(fun, array) { | |
3073 | this.fun = fun; | |
3074 | this.array = array; | |
3075 | } | |
3076 | Item.prototype.run = function () { | |
3077 | this.fun.apply(null, this.array); | |
3078 | }; | |
3079 | process.title = 'browser'; | |
3080 | process.browser = true; | |
3081 | process.env = {}; | |
3082 | process.argv = []; | |
3083 | process.version = ''; // empty string to avoid regexp issues | |
3084 | process.versions = {}; | |
3085 | ||
3086 | function noop() {} | |
3087 | ||
3088 | process.on = noop; | |
3089 | process.addListener = noop; | |
3090 | process.once = noop; | |
3091 | process.off = noop; | |
3092 | process.removeListener = noop; | |
3093 | process.removeAllListeners = noop; | |
3094 | process.emit = noop; | |
3095 | process.prependListener = noop; | |
3096 | process.prependOnceListener = noop; | |
3097 | ||
3098 | process.listeners = function (name) { return [] } | |
3099 | ||
3100 | process.binding = function (name) { | |
3101 | throw new Error('process.binding is not supported'); | |
3102 | }; | |
3103 | ||
3104 | process.cwd = function () { return '/' }; | |
3105 | process.chdir = function (dir) { | |
3106 | throw new Error('process.chdir is not supported'); | |
3107 | }; | |
3108 | process.umask = function() { return 0; }; | |
3109 | ||
3110 | },{}],13:[function(require,module,exports){ | |
3111 | module.exports = require('./lib/_stream_duplex.js'); | |
3112 | ||
3113 | },{"./lib/_stream_duplex.js":14}],14:[function(require,module,exports){ | |
3114 | // Copyright Joyent, Inc. and other Node contributors. | |
3115 | // | |
3116 | // Permission is hereby granted, free of charge, to any person obtaining a | |
3117 | // copy of this software and associated documentation files (the | |
3118 | // "Software"), to deal in the Software without restriction, including | |
3119 | // without limitation the rights to use, copy, modify, merge, publish, | |
3120 | // distribute, sublicense, and/or sell copies of the Software, and to permit | |
3121 | // persons to whom the Software is furnished to do so, subject to the | |
3122 | // following conditions: | |
3123 | // | |
3124 | // The above copyright notice and this permission notice shall be included | |
3125 | // in all copies or substantial portions of the Software. | |
3126 | // | |
3127 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
3128 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
3129 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | |
3130 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | |
3131 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | |
3132 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
3133 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | |
3134 | ||
3135 | // a duplex stream is just a stream that is both readable and writable. | |
3136 | // Since JS doesn't have multiple prototypal inheritance, this class | |
3137 | // prototypally inherits from Readable, and then parasitically from | |
3138 | // Writable. | |
3139 | ||
3140 | 'use strict'; | |
3141 | ||
3142 | /*<replacement>*/ | |
3143 | ||
3144 | var processNextTick = require('process-nextick-args'); | |
3145 | /*</replacement>*/ | |
3146 | ||
3147 | /*<replacement>*/ | |
3148 | var objectKeys = Object.keys || function (obj) { | |
3149 | var keys = []; | |
3150 | for (var key in obj) { | |
3151 | keys.push(key); | |
3152 | }return keys; | |
3153 | }; | |
3154 | /*</replacement>*/ | |
3155 | ||
3156 | module.exports = Duplex; | |
3157 | ||
3158 | /*<replacement>*/ | |
3159 | var util = require('core-util-is'); | |
3160 | util.inherits = require('inherits'); | |
3161 | /*</replacement>*/ | |
3162 | ||
3163 | var Readable = require('./_stream_readable'); | |
3164 | var Writable = require('./_stream_writable'); | |
3165 | ||
3166 | util.inherits(Duplex, Readable); | |
3167 | ||
3168 | var keys = objectKeys(Writable.prototype); | |
3169 | for (var v = 0; v < keys.length; v++) { | |
3170 | var method = keys[v]; | |
3171 | if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; | |
3172 | } | |
3173 | ||
3174 | function Duplex(options) { | |
3175 | if (!(this instanceof Duplex)) return new Duplex(options); | |
3176 | ||
3177 | Readable.call(this, options); | |
3178 | Writable.call(this, options); | |
3179 | ||
3180 | if (options && options.readable === false) this.readable = false; | |
3181 | ||
3182 | if (options && options.writable === false) this.writable = false; | |
3183 | ||
3184 | this.allowHalfOpen = true; | |
3185 | if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; | |
3186 | ||
3187 | this.once('end', onend); | |
3188 | } | |
3189 | ||
3190 | // the no-half-open enforcer | |
3191 | function onend() { | |
3192 | // if we allow half-open state, or if the writable side ended, | |
3193 | // then we're ok. | |
3194 | if (this.allowHalfOpen || this._writableState.ended) return; | |
3195 | ||
3196 | // no more data can be written. | |
3197 | // But allow more writes to happen in this tick. | |
3198 | processNextTick(onEndNT, this); | |
3199 | } | |
3200 | ||
3201 | function onEndNT(self) { | |
3202 | self.end(); | |
3203 | } | |
3204 | ||
3205 | Object.defineProperty(Duplex.prototype, 'destroyed', { | |
3206 | get: function () { | |
3207 | if (this._readableState === undefined || this._writableState === undefined) { | |
3208 | return false; | |
3209 | } | |
3210 | return this._readableState.destroyed && this._writableState.destroyed; | |
3211 | }, | |
3212 | set: function (value) { | |
3213 | // we ignore the value if the stream | |
3214 | // has not been initialized yet | |
3215 | if (this._readableState === undefined || this._writableState === undefined) { | |
3216 | return; | |
3217 | } | |
3218 | ||
3219 | // backward compatibility, the user is explicitly | |
3220 | // managing destroyed | |
3221 | this._readableState.destroyed = value; | |
3222 | this._writableState.destroyed = value; | |
3223 | } | |
3224 | }); | |
3225 | ||
3226 | Duplex.prototype._destroy = function (err, cb) { | |
3227 | this.push(null); | |
3228 | this.end(); | |
3229 | ||
3230 | processNextTick(cb, err); | |
3231 | }; | |
3232 | ||
3233 | function forEach(xs, f) { | |
3234 | for (var i = 0, l = xs.length; i < l; i++) { | |
3235 | f(xs[i], i); | |
3236 | } | |
3237 | } | |
3238 | },{"./_stream_readable":16,"./_stream_writable":18,"core-util-is":5,"inherits":8,"process-nextick-args":11}],15:[function(require,module,exports){ | |
3239 | // Copyright Joyent, Inc. and other Node contributors. | |
3240 | // | |
3241 | // Permission is hereby granted, free of charge, to any person obtaining a | |
3242 | // copy of this software and associated documentation files (the | |
3243 | // "Software"), to deal in the Software without restriction, including | |
3244 | // without limitation the rights to use, copy, modify, merge, publish, | |
3245 | // distribute, sublicense, and/or sell copies of the Software, and to permit | |
3246 | // persons to whom the Software is furnished to do so, subject to the | |
3247 | // following conditions: | |
3248 | // | |
3249 | // The above copyright notice and this permission notice shall be included | |
3250 | // in all copies or substantial portions of the Software. | |
3251 | // | |
3252 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
3253 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
3254 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | |
3255 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | |
3256 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | |
3257 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
3258 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | |
3259 | ||
3260 | // a passthrough stream. | |
3261 | // basically just the most minimal sort of Transform stream. | |
3262 | // Every written chunk gets output as-is. | |
3263 | ||
3264 | 'use strict'; | |
3265 | ||
3266 | module.exports = PassThrough; | |
3267 | ||
3268 | var Transform = require('./_stream_transform'); | |
3269 | ||
3270 | /*<replacement>*/ | |
3271 | var util = require('core-util-is'); | |
3272 | util.inherits = require('inherits'); | |
3273 | /*</replacement>*/ | |
3274 | ||
3275 | util.inherits(PassThrough, Transform); | |
3276 | ||
3277 | function PassThrough(options) { | |
3278 | if (!(this instanceof PassThrough)) return new PassThrough(options); | |
3279 | ||
3280 | Transform.call(this, options); | |
3281 | } | |
3282 | ||
3283 | PassThrough.prototype._transform = function (chunk, encoding, cb) { | |
3284 | cb(null, chunk); | |
3285 | }; | |
3286 | },{"./_stream_transform":17,"core-util-is":5,"inherits":8}],16:[function(require,module,exports){ | |
3287 | (function (process,global){ | |
3288 | // Copyright Joyent, Inc. and other Node contributors. | |
3289 | // | |
3290 | // Permission is hereby granted, free of charge, to any person obtaining a | |
3291 | // copy of this software and associated documentation files (the | |
3292 | // "Software"), to deal in the Software without restriction, including | |
3293 | // without limitation the rights to use, copy, modify, merge, publish, | |
3294 | // distribute, sublicense, and/or sell copies of the Software, and to permit | |
3295 | // persons to whom the Software is furnished to do so, subject to the | |
3296 | // following conditions: | |
3297 | // | |
3298 | // The above copyright notice and this permission notice shall be included | |
3299 | // in all copies or substantial portions of the Software. | |
3300 | // | |
3301 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
3302 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
3303 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | |
3304 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | |
3305 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | |
3306 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
3307 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | |
3308 | ||
3309 | 'use strict'; | |
3310 | ||
3311 | /*<replacement>*/ | |
3312 | ||
3313 | var processNextTick = require('process-nextick-args'); | |
3314 | /*</replacement>*/ | |
3315 | ||
3316 | module.exports = Readable; | |
3317 | ||
3318 | /*<replacement>*/ | |
3319 | var isArray = require('isarray'); | |
3320 | /*</replacement>*/ | |
3321 | ||
3322 | /*<replacement>*/ | |
3323 | var Duplex; | |
3324 | /*</replacement>*/ | |
3325 | ||
3326 | Readable.ReadableState = ReadableState; | |
3327 | ||
3328 | /*<replacement>*/ | |
3329 | var EE = require('events').EventEmitter; | |
3330 | ||
3331 | var EElistenerCount = function (emitter, type) { | |
3332 | return emitter.listeners(type).length; | |
3333 | }; | |
3334 | /*</replacement>*/ | |
3335 | ||
3336 | /*<replacement>*/ | |
3337 | var Stream = require('./internal/streams/stream'); | |
3338 | /*</replacement>*/ | |
3339 | ||
3340 | // TODO(bmeurer): Change this back to const once hole checks are | |
3341 | // properly optimized away early in Ignition+TurboFan. | |
3342 | /*<replacement>*/ | |
3343 | var Buffer = require('safe-buffer').Buffer; | |
3344 | var OurUint8Array = global.Uint8Array || function () {}; | |
3345 | function _uint8ArrayToBuffer(chunk) { | |
3346 | return Buffer.from(chunk); | |
3347 | } | |
3348 | function _isUint8Array(obj) { | |
3349 | return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; | |
3350 | } | |
3351 | /*</replacement>*/ | |
3352 | ||
3353 | /*<replacement>*/ | |
3354 | var util = require('core-util-is'); | |
3355 | util.inherits = require('inherits'); | |
3356 | /*</replacement>*/ | |
3357 | ||
3358 | /*<replacement>*/ | |
3359 | var debugUtil = require('util'); | |
3360 | var debug = void 0; | |
3361 | if (debugUtil && debugUtil.debuglog) { | |
3362 | debug = debugUtil.debuglog('stream'); | |
3363 | } else { | |
3364 | debug = function () {}; | |
3365 | } | |
3366 | /*</replacement>*/ | |
3367 | ||
3368 | var BufferList = require('./internal/streams/BufferList'); | |
3369 | var destroyImpl = require('./internal/streams/destroy'); | |
3370 | var StringDecoder; | |
3371 | ||
3372 | util.inherits(Readable, Stream); | |
3373 | ||
3374 | var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; | |
3375 | ||
3376 | function prependListener(emitter, event, fn) { | |
3377 | // Sadly this is not cacheable as some libraries bundle their own | |
3378 | // event emitter implementation with them. | |
3379 | if (typeof emitter.prependListener === 'function') { | |
3380 | return emitter.prependListener(event, fn); | |
3381 | } else { | |
3382 | // This is a hack to make sure that our error handler is attached before any | |
3383 | // userland ones. NEVER DO THIS. This is here only because this code needs | |
3384 | // to continue to work with older versions of Node.js that do not include | |
3385 | // the prependListener() method. The goal is to eventually remove this hack. | |
3386 | 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]]; | |
3387 | } | |
3388 | } | |
3389 | ||
3390 | function ReadableState(options, stream) { | |
3391 | Duplex = Duplex || require('./_stream_duplex'); | |
3392 | ||
3393 | options = options || {}; | |
3394 | ||
3395 | // object stream flag. Used to make read(n) ignore n and to | |
3396 | // make all the buffer merging and length checks go away | |
3397 | this.objectMode = !!options.objectMode; | |
3398 | ||
3399 | if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; | |
3400 | ||
3401 | // the point at which it stops calling _read() to fill the buffer | |
3402 | // Note: 0 is a valid value, means "don't call _read preemptively ever" | |
3403 | var hwm = options.highWaterMark; | |
3404 | var defaultHwm = this.objectMode ? 16 : 16 * 1024; | |
3405 | this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; | |
3406 | ||
3407 | // cast to ints. | |
3408 | this.highWaterMark = Math.floor(this.highWaterMark); | |
3409 | ||
3410 | // A linked list is used to store data chunks instead of an array because the | |
3411 | // linked list can remove elements from the beginning faster than | |
3412 | // array.shift() | |
3413 | this.buffer = new BufferList(); | |
3414 | this.length = 0; | |
3415 | this.pipes = null; | |
3416 | this.pipesCount = 0; | |
3417 | this.flowing = null; | |
3418 | this.ended = false; | |
3419 | this.endEmitted = false; | |
3420 | this.reading = false; | |
3421 | ||
3422 | // a flag to be able to tell if the event 'readable'/'data' is emitted | |
3423 | // immediately, or on a later tick. We set this to true at first, because | |
3424 | // any actions that shouldn't happen until "later" should generally also | |
3425 | // not happen before the first read call. | |
3426 | this.sync = true; | |
3427 | ||
3428 | // whenever we return null, then we set a flag to say | |
3429 | // that we're awaiting a 'readable' event emission. | |
3430 | this.needReadable = false; | |
3431 | this.emittedReadable = false; | |
3432 | this.readableListening = false; | |
3433 | this.resumeScheduled = false; | |
3434 | ||
3435 | // has it been destroyed | |
3436 | this.destroyed = false; | |
3437 | ||
3438 | // Crypto is kind of old and crusty. Historically, its default string | |
3439 | // encoding is 'binary' so we have to make this configurable. | |
3440 | // Everything else in the universe uses 'utf8', though. | |
3441 | this.defaultEncoding = options.defaultEncoding || 'utf8'; | |
3442 | ||
3443 | // the number of writers that are awaiting a drain event in .pipe()s | |
3444 | this.awaitDrain = 0; | |
3445 | ||
3446 | // if true, a maybeReadMore has been scheduled | |
3447 | this.readingMore = false; | |
3448 | ||
3449 | this.decoder = null; | |
3450 | this.encoding = null; | |
3451 | if (options.encoding) { | |
3452 | if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; | |
3453 | this.decoder = new StringDecoder(options.encoding); | |
3454 | this.encoding = options.encoding; | |
3455 | } | |
3456 | } | |
3457 | ||
3458 | function Readable(options) { | |
3459 | Duplex = Duplex || require('./_stream_duplex'); | |
3460 | ||
3461 | if (!(this instanceof Readable)) return new Readable(options); | |
3462 | ||
3463 | this._readableState = new ReadableState(options, this); | |
3464 | ||
3465 | // legacy | |
3466 | this.readable = true; | |
3467 | ||
3468 | if (options) { | |
3469 | if (typeof options.read === 'function') this._read = options.read; | |
3470 | ||
3471 | if (typeof options.destroy === 'function') this._destroy = options.destroy; | |
3472 | } | |
3473 | ||
3474 | Stream.call(this); | |
3475 | } | |
3476 | ||
3477 | Object.defineProperty(Readable.prototype, 'destroyed', { | |
3478 | get: function () { | |
3479 | if (this._readableState === undefined) { | |
3480 | return false; | |
3481 | } | |
3482 | return this._readableState.destroyed; | |
3483 | }, | |
3484 | set: function (value) { | |
3485 | // we ignore the value if the stream | |
3486 | // has not been initialized yet | |
3487 | if (!this._readableState) { | |
3488 | return; | |
3489 | } | |
3490 | ||
3491 | // backward compatibility, the user is explicitly | |
3492 | // managing destroyed | |
3493 | this._readableState.destroyed = value; | |
3494 | } | |
3495 | }); | |
3496 | ||
3497 | Readable.prototype.destroy = destroyImpl.destroy; | |
3498 | Readable.prototype._undestroy = destroyImpl.undestroy; | |
3499 | Readable.prototype._destroy = function (err, cb) { | |
3500 | this.push(null); | |
3501 | cb(err); | |
3502 | }; | |
3503 | ||
3504 | // Manually shove something into the read() buffer. | |
3505 | // This returns true if the highWaterMark has not been hit yet, | |
3506 | // similar to how Writable.write() returns true if you should | |
3507 | // write() some more. | |
3508 | Readable.prototype.push = function (chunk, encoding) { | |
3509 | var state = this._readableState; | |
3510 | var skipChunkCheck; | |
3511 | ||
3512 | if (!state.objectMode) { | |
3513 | if (typeof chunk === 'string') { | |
3514 | encoding = encoding || state.defaultEncoding; | |
3515 | if (encoding !== state.encoding) { | |
3516 | chunk = Buffer.from(chunk, encoding); | |
3517 | encoding = ''; | |
3518 | } | |
3519 | skipChunkCheck = true; | |
3520 | } | |
3521 | } else { | |
3522 | skipChunkCheck = true; | |
3523 | } | |
3524 | ||
3525 | return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); | |
3526 | }; | |
3527 | ||
3528 | // Unshift should *always* be something directly out of read() | |
3529 | Readable.prototype.unshift = function (chunk) { | |
3530 | return readableAddChunk(this, chunk, null, true, false); | |
3531 | }; | |
3532 | ||
3533 | function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { | |
3534 | var state = stream._readableState; | |
3535 | if (chunk === null) { | |
3536 | state.reading = false; | |
3537 | onEofChunk(stream, state); | |
3538 | } else { | |
3539 | var er; | |
3540 | if (!skipChunkCheck) er = chunkInvalid(state, chunk); | |
3541 | if (er) { | |
3542 | stream.emit('error', er); | |
3543 | } else if (state.objectMode || chunk && chunk.length > 0) { | |
3544 | if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { | |
3545 | chunk = _uint8ArrayToBuffer(chunk); | |
3546 | } | |
3547 | ||
3548 | if (addToFront) { | |
3549 | if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); | |
3550 | } else if (state.ended) { | |
3551 | stream.emit('error', new Error('stream.push() after EOF')); | |
3552 | } else { | |
3553 | state.reading = false; | |
3554 | if (state.decoder && !encoding) { | |
3555 | chunk = state.decoder.write(chunk); | |
3556 | if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); | |
3557 | } else { | |
3558 | addChunk(stream, state, chunk, false); | |
3559 | } | |
3560 | } | |
3561 | } else if (!addToFront) { | |
3562 | state.reading = false; | |
3563 | } | |
3564 | } | |
3565 | ||
3566 | return needMoreData(state); | |
3567 | } | |
3568 | ||
3569 | function addChunk(stream, state, chunk, addToFront) { | |
3570 | if (state.flowing && state.length === 0 && !state.sync) { | |
3571 | stream.emit('data', chunk); | |
3572 | stream.read(0); | |
3573 | } else { | |
3574 | // update the buffer info. | |
3575 | state.length += state.objectMode ? 1 : chunk.length; | |
3576 | if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); | |
3577 | ||
3578 | if (state.needReadable) emitReadable(stream); | |
3579 | } | |
3580 | maybeReadMore(stream, state); | |
3581 | } | |
3582 | ||
3583 | function chunkInvalid(state, chunk) { | |
3584 | var er; | |
3585 | if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { | |
3586 | er = new TypeError('Invalid non-string/buffer chunk'); | |
3587 | } | |
3588 | return er; | |
3589 | } | |
3590 | ||
3591 | // if it's past the high water mark, we can push in some more. | |
3592 | // Also, if we have no data yet, we can stand some | |
3593 | // more bytes. This is to work around cases where hwm=0, | |
3594 | // such as the repl. Also, if the push() triggered a | |
3595 | // readable event, and the user called read(largeNumber) such that | |
3596 | // needReadable was set, then we ought to push more, so that another | |
3597 | // 'readable' event will be triggered. | |
3598 | function needMoreData(state) { | |
3599 | return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); | |
3600 | } | |
3601 | ||
3602 | Readable.prototype.isPaused = function () { | |
3603 | return this._readableState.flowing === false; | |
3604 | }; | |
3605 | ||
3606 | // backwards compatibility. | |
3607 | Readable.prototype.setEncoding = function (enc) { | |
3608 | if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; | |
3609 | this._readableState.decoder = new StringDecoder(enc); | |
3610 | this._readableState.encoding = enc; | |
3611 | return this; | |
3612 | }; | |
3613 | ||
3614 | // Don't raise the hwm > 8MB | |
3615 | var MAX_HWM = 0x800000; | |
3616 | function computeNewHighWaterMark(n) { | |
3617 | if (n >= MAX_HWM) { | |
3618 | n = MAX_HWM; | |
3619 | } else { | |
3620 | // Get the next highest power of 2 to prevent increasing hwm excessively in | |
3621 | // tiny amounts | |
3622 | n--; | |
3623 | n |= n >>> 1; | |
3624 | n |= n >>> 2; | |
3625 | n |= n >>> 4; | |
3626 | n |= n >>> 8; | |
3627 | n |= n >>> 16; | |
3628 | n++; | |
3629 | } | |
3630 | return n; | |
3631 | } | |
3632 | ||
3633 | // This function is designed to be inlinable, so please take care when making | |
3634 | // changes to the function body. | |
3635 | function howMuchToRead(n, state) { | |
3636 | if (n <= 0 || state.length === 0 && state.ended) return 0; | |
3637 | if (state.objectMode) return 1; | |
3638 | if (n !== n) { | |
3639 | // Only flow one buffer at a time | |
3640 | if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; | |
3641 | } | |
3642 | // If we're asking for more than the current hwm, then raise the hwm. | |
3643 | if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); | |
3644 | if (n <= state.length) return n; | |
3645 | // Don't have enough | |
3646 | if (!state.ended) { | |
3647 | state.needReadable = true; | |
3648 | return 0; | |
3649 | } | |
3650 | return state.length; | |
3651 | } | |
3652 | ||
3653 | // you can override either this method, or the async _read(n) below. | |
3654 | Readable.prototype.read = function (n) { | |
3655 | debug('read', n); | |
3656 | n = parseInt(n, 10); | |
3657 | var state = this._readableState; | |
3658 | var nOrig = n; | |
3659 | ||
3660 | if (n !== 0) state.emittedReadable = false; | |
3661 | ||
3662 | // if we're doing read(0) to trigger a readable event, but we | |
3663 | // already have a bunch of data in the buffer, then just trigger | |
3664 | // the 'readable' event and move on. | |
3665 | if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { | |
3666 | debug('read: emitReadable', state.length, state.ended); | |
3667 | if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); | |
3668 | return null; | |
3669 | } | |
3670 | ||
3671 | n = howMuchToRead(n, state); | |
3672 | ||
3673 | // if we've ended, and we're now clear, then finish it up. | |
3674 | if (n === 0 && state.ended) { | |
3675 | if (state.length === 0) endReadable(this); | |
3676 | return null; | |
3677 | } | |
3678 | ||
3679 | // All the actual chunk generation logic needs to be | |
3680 | // *below* the call to _read. The reason is that in certain | |
3681 | // synthetic stream cases, such as passthrough streams, _read | |
3682 | // may be a completely synchronous operation which may change | |
3683 | // the state of the read buffer, providing enough data when | |
3684 | // before there was *not* enough. | |
3685 | // | |
3686 | // So, the steps are: | |
3687 | // 1. Figure out what the state of things will be after we do | |
3688 | // a read from the buffer. | |
3689 | // | |
3690 | // 2. If that resulting state will trigger a _read, then call _read. | |
3691 | // Note that this may be asynchronous, or synchronous. Yes, it is | |
3692 | // deeply ugly to write APIs this way, but that still doesn't mean | |
3693 | // that the Readable class should behave improperly, as streams are | |
3694 | // designed to be sync/async agnostic. | |
3695 | // Take note if the _read call is sync or async (ie, if the read call | |
3696 | // has returned yet), so that we know whether or not it's safe to emit | |
3697 | // 'readable' etc. | |
3698 | // | |
3699 | // 3. Actually pull the requested chunks out of the buffer and return. | |
3700 | ||
3701 | // if we need a readable event, then we need to do some reading. | |
3702 | var doRead = state.needReadable; | |
3703 | debug('need readable', doRead); | |
3704 | ||
3705 | // if we currently have less than the highWaterMark, then also read some | |
3706 | if (state.length === 0 || state.length - n < state.highWaterMark) { | |
3707 | doRead = true; | |
3708 | debug('length less than watermark', doRead); | |
3709 | } | |
3710 | ||
3711 | // however, if we've ended, then there's no point, and if we're already | |
3712 | // reading, then it's unnecessary. | |
3713 | if (state.ended || state.reading) { | |
3714 | doRead = false; | |
3715 | debug('reading or ended', doRead); | |
3716 | } else if (doRead) { | |
3717 | debug('do read'); | |
3718 | state.reading = true; | |
3719 | state.sync = true; | |
3720 | // if the length is currently zero, then we *need* a readable event. | |
3721 | if (state.length === 0) state.needReadable = true; | |
3722 | // call internal read method | |
3723 | this._read(state.highWaterMark); | |
3724 | state.sync = false; | |
3725 | // If _read pushed data synchronously, then `reading` will be false, | |
3726 | // and we need to re-evaluate how much data we can return to the user. | |
3727 | if (!state.reading) n = howMuchToRead(nOrig, state); | |
3728 | } | |
3729 | ||
3730 | var ret; | |
3731 | if (n > 0) ret = fromList(n, state);else ret = null; | |
3732 | ||
3733 | if (ret === null) { | |
3734 | state.needReadable = true; | |
3735 | n = 0; | |
3736 | } else { | |
3737 | state.length -= n; | |
3738 | } | |
3739 | ||
3740 | if (state.length === 0) { | |
3741 | // If we have nothing in the buffer, then we want to know | |
3742 | // as soon as we *do* get something into the buffer. | |
3743 | if (!state.ended) state.needReadable = true; | |
3744 | ||
3745 | // If we tried to read() past the EOF, then emit end on the next tick. | |
3746 | if (nOrig !== n && state.ended) endReadable(this); | |
3747 | } | |
3748 | ||
3749 | if (ret !== null) this.emit('data', ret); | |
3750 | ||
3751 | return ret; | |
3752 | }; | |
3753 | ||
3754 | function onEofChunk(stream, state) { | |
3755 | if (state.ended) return; | |
3756 | if (state.decoder) { | |
3757 | var chunk = state.decoder.end(); | |
3758 | if (chunk && chunk.length) { | |
3759 | state.buffer.push(chunk); | |
3760 | state.length += state.objectMode ? 1 : chunk.length; | |
3761 | } | |
3762 | } | |
3763 | state.ended = true; | |
3764 | ||
3765 | // emit 'readable' now to make sure it gets picked up. | |
3766 | emitReadable(stream); | |
3767 | } | |
3768 | ||
3769 | // Don't emit readable right away in sync mode, because this can trigger | |
3770 | // another read() call => stack overflow. This way, it might trigger | |
3771 | // a nextTick recursion warning, but that's not so bad. | |
3772 | function emitReadable(stream) { | |
3773 | var state = stream._readableState; | |
3774 | state.needReadable = false; | |
3775 | if (!state.emittedReadable) { | |
3776 | debug('emitReadable', state.flowing); | |
3777 | state.emittedReadable = true; | |
3778 | if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); | |
3779 | } | |
3780 | } | |
3781 | ||
3782 | function emitReadable_(stream) { | |
3783 | debug('emit readable'); | |
3784 | stream.emit('readable'); | |
3785 | flow(stream); | |
3786 | } | |
3787 | ||
3788 | // at this point, the user has presumably seen the 'readable' event, | |
3789 | // and called read() to consume some data. that may have triggered | |
3790 | // in turn another _read(n) call, in which case reading = true if | |
3791 | // it's in progress. | |
3792 | // However, if we're not ended, or reading, and the length < hwm, | |
3793 | // then go ahead and try to read some more preemptively. | |
3794 | function maybeReadMore(stream, state) { | |
3795 | if (!state.readingMore) { | |
3796 | state.readingMore = true; | |
3797 | processNextTick(maybeReadMore_, stream, state); | |
3798 | } | |
3799 | } | |
3800 | ||
3801 | function maybeReadMore_(stream, state) { | |
3802 | var len = state.length; | |
3803 | while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { | |
3804 | debug('maybeReadMore read 0'); | |
3805 | stream.read(0); | |
3806 | if (len === state.length) | |
3807 | // didn't get any data, stop spinning. | |
3808 | break;else len = state.length; | |
3809 | } | |
3810 | state.readingMore = false; | |
3811 | } | |
3812 | ||
3813 | // abstract method. to be overridden in specific implementation classes. | |
3814 | // call cb(er, data) where data is <= n in length. | |
3815 | // for virtual (non-string, non-buffer) streams, "length" is somewhat | |
3816 | // arbitrary, and perhaps not very meaningful. | |
3817 | Readable.prototype._read = function (n) { | |
3818 | this.emit('error', new Error('_read() is not implemented')); | |
3819 | }; | |
3820 | ||
3821 | Readable.prototype.pipe = function (dest, pipeOpts) { | |
3822 | var src = this; | |
3823 | var state = this._readableState; | |
3824 | ||
3825 | switch (state.pipesCount) { | |
3826 | case 0: | |
3827 | state.pipes = dest; | |
3828 | break; | |
3829 | case 1: | |
3830 | state.pipes = [state.pipes, dest]; | |
3831 | break; | |
3832 | default: | |
3833 | state.pipes.push(dest); | |
3834 | break; | |
3835 | } | |
3836 | state.pipesCount += 1; | |
3837 | debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); | |
3838 | ||
3839 | var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; | |
3840 | ||
3841 | var endFn = doEnd ? onend : unpipe; | |
3842 | if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); | |
3843 | ||
3844 | dest.on('unpipe', onunpipe); | |
3845 | function onunpipe(readable, unpipeInfo) { | |
3846 | debug('onunpipe'); | |
3847 | if (readable === src) { | |
3848 | if (unpipeInfo && unpipeInfo.hasUnpiped === false) { | |
3849 | unpipeInfo.hasUnpiped = true; | |
3850 | cleanup(); | |
3851 | } | |
3852 | } | |
3853 | } | |
3854 | ||
3855 | function onend() { | |
3856 | debug('onend'); | |
3857 | dest.end(); | |
3858 | } | |
3859 | ||
3860 | // when the dest drains, it reduces the awaitDrain counter | |
3861 | // on the source. This would be more elegant with a .once() | |
3862 | // handler in flow(), but adding and removing repeatedly is | |
3863 | // too slow. | |
3864 | var ondrain = pipeOnDrain(src); | |
3865 | dest.on('drain', ondrain); | |
3866 | ||
3867 | var cleanedUp = false; | |
3868 | function cleanup() { | |
3869 | debug('cleanup'); | |
3870 | // cleanup event handlers once the pipe is broken | |
3871 | dest.removeListener('close', onclose); | |
3872 | dest.removeListener('finish', onfinish); | |
3873 | dest.removeListener('drain', ondrain); | |
3874 | dest.removeListener('error', onerror); | |
3875 | dest.removeListener('unpipe', onunpipe); | |
3876 | src.removeListener('end', onend); | |
3877 | src.removeListener('end', unpipe); | |
3878 | src.removeListener('data', ondata); | |
3879 | ||
3880 | cleanedUp = true; | |
3881 | ||
3882 | // if the reader is waiting for a drain event from this | |
3883 | // specific writer, then it would cause it to never start | |
3884 | // flowing again. | |
3885 | // So, if this is awaiting a drain, then we just call it now. | |
3886 | // If we don't know, then assume that we are waiting for one. | |
3887 | if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); | |
3888 | } | |
3889 | ||
3890 | // If the user pushes more data while we're writing to dest then we'll end up | |
3891 | // in ondata again. However, we only want to increase awaitDrain once because | |
3892 | // dest will only emit one 'drain' event for the multiple writes. | |
3893 | // => Introduce a guard on increasing awaitDrain. | |
3894 | var increasedAwaitDrain = false; | |
3895 | src.on('data', ondata); | |
3896 | function ondata(chunk) { | |
3897 | debug('ondata'); | |
3898 | increasedAwaitDrain = false; | |
3899 | var ret = dest.write(chunk); | |
3900 | if (false === ret && !increasedAwaitDrain) { | |
3901 | // If the user unpiped during `dest.write()`, it is possible | |
3902 | // to get stuck in a permanently paused state if that write | |
3903 | // also returned false. | |
3904 | // => Check whether `dest` is still a piping destination. | |
3905 | if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { | |
3906 | debug('false write response, pause', src._readableState.awaitDrain); | |
3907 | src._readableState.awaitDrain++; | |
3908 | increasedAwaitDrain = true; | |
3909 | } | |
3910 | src.pause(); | |
3911 | } | |
3912 | } | |
3913 | ||
3914 | // if the dest has an error, then stop piping into it. | |
3915 | // however, don't suppress the throwing behavior for this. | |
3916 | function onerror(er) { | |
3917 | debug('onerror', er); | |
3918 | unpipe(); | |
3919 | dest.removeListener('error', onerror); | |
3920 | if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); | |
3921 | } | |
3922 | ||
3923 | // Make sure our error handler is attached before userland ones. | |
3924 | prependListener(dest, 'error', onerror); | |
3925 | ||
3926 | // Both close and finish should trigger unpipe, but only once. | |
3927 | function onclose() { | |
3928 | dest.removeListener('finish', onfinish); | |
3929 | unpipe(); | |
3930 | } | |
3931 | dest.once('close', onclose); | |
3932 | function onfinish() { | |
3933 | debug('onfinish'); | |
3934 | dest.removeListener('close', onclose); | |
3935 | unpipe(); | |
3936 | } | |
3937 | dest.once('finish', onfinish); | |
3938 | ||
3939 | function unpipe() { | |
3940 | debug('unpipe'); | |
3941 | src.unpipe(dest); | |
3942 | } | |
3943 | ||
3944 | // tell the dest that it's being piped to | |
3945 | dest.emit('pipe', src); | |
3946 | ||
3947 | // start the flow if it hasn't been started already. | |
3948 | if (!state.flowing) { | |
3949 | debug('pipe resume'); | |
3950 | src.resume(); | |
3951 | } | |
3952 | ||
3953 | return dest; | |
3954 | }; | |
3955 | ||
3956 | function pipeOnDrain(src) { | |
3957 | return function () { | |
3958 | var state = src._readableState; | |
3959 | debug('pipeOnDrain', state.awaitDrain); | |
3960 | if (state.awaitDrain) state.awaitDrain--; | |
3961 | if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { | |
3962 | state.flowing = true; | |
3963 | flow(src); | |
3964 | } | |
3965 | }; | |
3966 | } | |
3967 | ||
3968 | Readable.prototype.unpipe = function (dest) { | |
3969 | var state = this._readableState; | |
3970 | var unpipeInfo = { hasUnpiped: false }; | |
3971 | ||
3972 | // if we're not piping anywhere, then do nothing. | |
3973 | if (state.pipesCount === 0) return this; | |
3974 | ||
3975 | // just one destination. most common case. | |
3976 | if (state.pipesCount === 1) { | |
3977 | // passed in one, but it's not the right one. | |
3978 | if (dest && dest !== state.pipes) return this; | |
3979 | ||
3980 | if (!dest) dest = state.pipes; | |
3981 | ||
3982 | // got a match. | |
3983 | state.pipes = null; | |
3984 | state.pipesCount = 0; | |
3985 | state.flowing = false; | |
3986 | if (dest) dest.emit('unpipe', this, unpipeInfo); | |
3987 | return this; | |
3988 | } | |
3989 | ||
3990 | // slow case. multiple pipe destinations. | |
3991 | ||
3992 | if (!dest) { | |
3993 | // remove all. | |
3994 | var dests = state.pipes; | |
3995 | var len = state.pipesCount; | |
3996 | state.pipes = null; | |
3997 | state.pipesCount = 0; | |
3998 | state.flowing = false; | |
3999 | ||
4000 | for (var i = 0; i < len; i++) { | |
4001 | dests[i].emit('unpipe', this, unpipeInfo); | |
4002 | }return this; | |
4003 | } | |
4004 | ||
4005 | // try to find the right one. | |
4006 | var index = indexOf(state.pipes, dest); | |
4007 | if (index === -1) return this; | |
4008 | ||
4009 | state.pipes.splice(index, 1); | |
4010 | state.pipesCount -= 1; | |
4011 | if (state.pipesCount === 1) state.pipes = state.pipes[0]; | |
4012 | ||
4013 | dest.emit('unpipe', this, unpipeInfo); | |
4014 | ||
4015 | return this; | |
4016 | }; | |
4017 | ||
4018 | // set up data events if they are asked for | |
4019 | // Ensure readable listeners eventually get something | |
4020 | Readable.prototype.on = function (ev, fn) { | |
4021 | var res = Stream.prototype.on.call(this, ev, fn); | |
4022 | ||
4023 | if (ev === 'data') { | |
4024 | // Start flowing on next tick if stream isn't explicitly paused | |
4025 | if (this._readableState.flowing !== false) this.resume(); | |
4026 | } else if (ev === 'readable') { | |
4027 | var state = this._readableState; | |
4028 | if (!state.endEmitted && !state.readableListening) { | |
4029 | state.readableListening = state.needReadable = true; | |
4030 | state.emittedReadable = false; | |
4031 | if (!state.reading) { | |
4032 | processNextTick(nReadingNextTick, this); | |
4033 | } else if (state.length) { | |
4034 | emitReadable(this); | |
4035 | } | |
4036 | } | |
4037 | } | |
4038 | ||
4039 | return res; | |
4040 | }; | |
4041 | Readable.prototype.addListener = Readable.prototype.on; | |
4042 | ||
4043 | function nReadingNextTick(self) { | |
4044 | debug('readable nexttick read 0'); | |
4045 | self.read(0); | |
4046 | } | |
4047 | ||
4048 | // pause() and resume() are remnants of the legacy readable stream API | |
4049 | // If the user uses them, then switch into old mode. | |
4050 | Readable.prototype.resume = function () { | |
4051 | var state = this._readableState; | |
4052 | if (!state.flowing) { | |
4053 | debug('resume'); | |
4054 | state.flowing = true; | |
4055 | resume(this, state); | |
4056 | } | |
4057 | return this; | |
4058 | }; | |
4059 | ||
4060 | function resume(stream, state) { | |
4061 | if (!state.resumeScheduled) { | |
4062 | state.resumeScheduled = true; | |
4063 | processNextTick(resume_, stream, state); | |
4064 | } | |
4065 | } | |
4066 | ||
4067 | function resume_(stream, state) { | |
4068 | if (!state.reading) { | |
4069 | debug('resume read 0'); | |
4070 | stream.read(0); | |
4071 | } | |
4072 | ||
4073 | state.resumeScheduled = false; | |
4074 | state.awaitDrain = 0; | |
4075 | stream.emit('resume'); | |
4076 | flow(stream); | |
4077 | if (state.flowing && !state.reading) stream.read(0); | |
4078 | } | |
4079 | ||
4080 | Readable.prototype.pause = function () { | |
4081 | debug('call pause flowing=%j', this._readableState.flowing); | |
4082 | if (false !== this._readableState.flowing) { | |
4083 | debug('pause'); | |
4084 | this._readableState.flowing = false; | |
4085 | this.emit('pause'); | |
4086 | } | |
4087 | return this; | |
4088 | }; | |
4089 | ||
4090 | function flow(stream) { | |
4091 | var state = stream._readableState; | |
4092 | debug('flow', state.flowing); | |
4093 | while (state.flowing && stream.read() !== null) {} | |
4094 | } | |
4095 | ||
4096 | // wrap an old-style stream as the async data source. | |
4097 | // This is *not* part of the readable stream interface. | |
4098 | // It is an ugly unfortunate mess of history. | |
4099 | Readable.prototype.wrap = function (stream) { | |
4100 | var state = this._readableState; | |
4101 | var paused = false; | |
4102 | ||
4103 | var self = this; | |
4104 | stream.on('end', function () { | |
4105 | debug('wrapped end'); | |
4106 | if (state.decoder && !state.ended) { | |
4107 | var chunk = state.decoder.end(); | |
4108 | if (chunk && chunk.length) self.push(chunk); | |
4109 | } | |
4110 | ||
4111 | self.push(null); | |
4112 | }); | |
4113 | ||
4114 | stream.on('data', function (chunk) { | |
4115 | debug('wrapped data'); | |
4116 | if (state.decoder) chunk = state.decoder.write(chunk); | |
4117 | ||
4118 | // don't skip over falsy values in objectMode | |
4119 | if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; | |
4120 | ||
4121 | var ret = self.push(chunk); | |
4122 | if (!ret) { | |
4123 | paused = true; | |
4124 | stream.pause(); | |
4125 | } | |
4126 | }); | |
4127 | ||
4128 | // proxy all the other methods. | |
4129 | // important when wrapping filters and duplexes. | |
4130 | for (var i in stream) { | |
4131 | if (this[i] === undefined && typeof stream[i] === 'function') { | |
4132 | this[i] = function (method) { | |
4133 | return function () { | |
4134 | return stream[method].apply(stream, arguments); | |
4135 | }; | |
4136 | }(i); | |
4137 | } | |
4138 | } | |
4139 | ||
4140 | // proxy certain important events. | |
4141 | for (var n = 0; n < kProxyEvents.length; n++) { | |
4142 | stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); | |
4143 | } | |
4144 | ||
4145 | // when we try to consume some more bytes, simply unpause the | |
4146 | // underlying stream. | |
4147 | self._read = function (n) { | |
4148 | debug('wrapped _read', n); | |
4149 | if (paused) { | |
4150 | paused = false; | |
4151 | stream.resume(); | |
4152 | } | |
4153 | }; | |
4154 | ||
4155 | return self; | |
4156 | }; | |
4157 | ||
4158 | // exposed for testing purposes only. | |
4159 | Readable._fromList = fromList; | |
4160 | ||
4161 | // Pluck off n bytes from an array of buffers. | |
4162 | // Length is the combined lengths of all the buffers in the list. | |
4163 | // This function is designed to be inlinable, so please take care when making | |
4164 | // changes to the function body. | |
4165 | function fromList(n, state) { | |
4166 | // nothing buffered | |
4167 | if (state.length === 0) return null; | |
4168 | ||
4169 | var ret; | |
4170 | if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { | |
4171 | // read it all, truncate the list | |
4172 | 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); | |
4173 | state.buffer.clear(); | |
4174 | } else { | |
4175 | // read part of list | |
4176 | ret = fromListPartial(n, state.buffer, state.decoder); | |
4177 | } | |
4178 | ||
4179 | return ret; | |
4180 | } | |
4181 | ||
4182 | // Extracts only enough buffered data to satisfy the amount requested. | |
4183 | // This function is designed to be inlinable, so please take care when making | |
4184 | // changes to the function body. | |
4185 | function fromListPartial(n, list, hasStrings) { | |
4186 | var ret; | |
4187 | if (n < list.head.data.length) { | |
4188 | // slice is the same for buffers and strings | |
4189 | ret = list.head.data.slice(0, n); | |
4190 | list.head.data = list.head.data.slice(n); | |
4191 | } else if (n === list.head.data.length) { | |
4192 | // first chunk is a perfect match | |
4193 | ret = list.shift(); | |
4194 | } else { | |
4195 | // result spans more than one buffer | |
4196 | ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); | |
4197 | } | |
4198 | return ret; | |
4199 | } | |
4200 | ||
4201 | // Copies a specified amount of characters from the list of buffered data | |
4202 | // chunks. | |
4203 | // This function is designed to be inlinable, so please take care when making | |
4204 | // changes to the function body. | |
4205 | function copyFromBufferString(n, list) { | |
4206 | var p = list.head; | |
4207 | var c = 1; | |
4208 | var ret = p.data; | |
4209 | n -= ret.length; | |
4210 | while (p = p.next) { | |
4211 | var str = p.data; | |
4212 | var nb = n > str.length ? str.length : n; | |
4213 | if (nb === str.length) ret += str;else ret += str.slice(0, n); | |
4214 | n -= nb; | |
4215 | if (n === 0) { | |
4216 | if (nb === str.length) { | |
4217 | ++c; | |
4218 | if (p.next) list.head = p.next;else list.head = list.tail = null; | |
4219 | } else { | |
4220 | list.head = p; | |
4221 | p.data = str.slice(nb); | |
4222 | } | |
4223 | break; | |
4224 | } | |
4225 | ++c; | |
4226 | } | |
4227 | list.length -= c; | |
4228 | return ret; | |
4229 | } | |
4230 | ||
4231 | // Copies a specified amount of bytes from the list of buffered data chunks. | |
4232 | // This function is designed to be inlinable, so please take care when making | |
4233 | // changes to the function body. | |
4234 | function copyFromBuffer(n, list) { | |
4235 | var ret = Buffer.allocUnsafe(n); | |
4236 | var p = list.head; | |
4237 | var c = 1; | |
4238 | p.data.copy(ret); | |
4239 | n -= p.data.length; | |
4240 | while (p = p.next) { | |
4241 | var buf = p.data; | |
4242 | var nb = n > buf.length ? buf.length : n; | |
4243 | buf.copy(ret, ret.length - n, 0, nb); | |
4244 | n -= nb; | |
4245 | if (n === 0) { | |
4246 | if (nb === buf.length) { | |
4247 | ++c; | |
4248 | if (p.next) list.head = p.next;else list.head = list.tail = null; | |
4249 | } else { | |
4250 | list.head = p; | |
4251 | p.data = buf.slice(nb); | |
4252 | } | |
4253 | break; | |
4254 | } | |
4255 | ++c; | |
4256 | } | |
4257 | list.length -= c; | |
4258 | return ret; | |
4259 | } | |
4260 | ||
4261 | function endReadable(stream) { | |
4262 | var state = stream._readableState; | |
4263 | ||
4264 | // If we get here before consuming all the bytes, then that is a | |
4265 | // bug in node. Should never happen. | |
4266 | if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); | |
4267 | ||
4268 | if (!state.endEmitted) { | |
4269 | state.ended = true; | |
4270 | processNextTick(endReadableNT, state, stream); | |
4271 | } | |
4272 | } | |
4273 | ||
4274 | function endReadableNT(state, stream) { | |
4275 | // Check that we didn't get one last unshift. | |
4276 | if (!state.endEmitted && state.length === 0) { | |
4277 | state.endEmitted = true; | |
4278 | stream.readable = false; | |
4279 | stream.emit('end'); | |
4280 | } | |
4281 | } | |
4282 | ||
4283 | function forEach(xs, f) { | |
4284 | for (var i = 0, l = xs.length; i < l; i++) { | |
4285 | f(xs[i], i); | |
4286 | } | |
4287 | } | |
4288 | ||
4289 | function indexOf(xs, x) { | |
4290 | for (var i = 0, l = xs.length; i < l; i++) { | |
4291 | if (xs[i] === x) return i; | |
4292 | } | |
4293 | return -1; | |
4294 | } | |
4295 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | |
4296 | },{"./_stream_duplex":14,"./internal/streams/BufferList":19,"./internal/streams/destroy":20,"./internal/streams/stream":21,"_process":12,"core-util-is":5,"events":6,"inherits":8,"isarray":10,"process-nextick-args":11,"safe-buffer":26,"string_decoder/":28,"util":3}],17:[function(require,module,exports){ | |
4297 | // Copyright Joyent, Inc. and other Node contributors. | |
4298 | // | |
4299 | // Permission is hereby granted, free of charge, to any person obtaining a | |
4300 | // copy of this software and associated documentation files (the | |
4301 | // "Software"), to deal in the Software without restriction, including | |
4302 | // without limitation the rights to use, copy, modify, merge, publish, | |
4303 | // distribute, sublicense, and/or sell copies of the Software, and to permit | |
4304 | // persons to whom the Software is furnished to do so, subject to the | |
4305 | // following conditions: | |
4306 | // | |
4307 | // The above copyright notice and this permission notice shall be included | |
4308 | // in all copies or substantial portions of the Software. | |
4309 | // | |
4310 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
4311 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
4312 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | |
4313 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | |
4314 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | |
4315 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
4316 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | |
4317 | ||
4318 | // a transform stream is a readable/writable stream where you do | |
4319 | // something with the data. Sometimes it's called a "filter", | |
4320 | // but that's not a great name for it, since that implies a thing where | |
4321 | // some bits pass through, and others are simply ignored. (That would | |
4322 | // be a valid example of a transform, of course.) | |
4323 | // | |
4324 | // While the output is causally related to the input, it's not a | |
4325 | // necessarily symmetric or synchronous transformation. For example, | |
4326 | // a zlib stream might take multiple plain-text writes(), and then | |
4327 | // emit a single compressed chunk some time in the future. | |
4328 | // | |
4329 | // Here's how this works: | |
4330 | // | |
4331 | // The Transform stream has all the aspects of the readable and writable | |
4332 | // stream classes. When you write(chunk), that calls _write(chunk,cb) | |
4333 | // internally, and returns false if there's a lot of pending writes | |
4334 | // buffered up. When you call read(), that calls _read(n) until | |
4335 | // there's enough pending readable data buffered up. | |
4336 | // | |
4337 | // In a transform stream, the written data is placed in a buffer. When | |
4338 | // _read(n) is called, it transforms the queued up data, calling the | |
4339 | // buffered _write cb's as it consumes chunks. If consuming a single | |
4340 | // written chunk would result in multiple output chunks, then the first | |
4341 | // outputted bit calls the readcb, and subsequent chunks just go into | |
4342 | // the read buffer, and will cause it to emit 'readable' if necessary. | |
4343 | // | |
4344 | // This way, back-pressure is actually determined by the reading side, | |
4345 | // since _read has to be called to start processing a new chunk. However, | |
4346 | // a pathological inflate type of transform can cause excessive buffering | |
4347 | // here. For example, imagine a stream where every byte of input is | |
4348 | // interpreted as an integer from 0-255, and then results in that many | |
4349 | // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in | |
4350 | // 1kb of data being output. In this case, you could write a very small | |
4351 | // amount of input, and end up with a very large amount of output. In | |
4352 | // such a pathological inflating mechanism, there'd be no way to tell | |
4353 | // the system to stop doing the transform. A single 4MB write could | |
4354 | // cause the system to run out of memory. | |
4355 | // | |
4356 | // However, even in such a pathological case, only a single written chunk | |
4357 | // would be consumed, and then the rest would wait (un-transformed) until | |
4358 | // the results of the previous transformed chunk were consumed. | |
4359 | ||
4360 | 'use strict'; | |
4361 | ||
4362 | module.exports = Transform; | |
4363 | ||
4364 | var Duplex = require('./_stream_duplex'); | |
4365 | ||
4366 | /*<replacement>*/ | |
4367 | var util = require('core-util-is'); | |
4368 | util.inherits = require('inherits'); | |
4369 | /*</replacement>*/ | |
4370 | ||
4371 | util.inherits(Transform, Duplex); | |
4372 | ||
4373 | function TransformState(stream) { | |
4374 | this.afterTransform = function (er, data) { | |
4375 | return afterTransform(stream, er, data); | |
4376 | }; | |
4377 | ||
4378 | this.needTransform = false; | |
4379 | this.transforming = false; | |
4380 | this.writecb = null; | |
4381 | this.writechunk = null; | |
4382 | this.writeencoding = null; | |
4383 | } | |
4384 | ||
4385 | function afterTransform(stream, er, data) { | |
4386 | var ts = stream._transformState; | |
4387 | ts.transforming = false; | |
4388 | ||
4389 | var cb = ts.writecb; | |
4390 | ||
4391 | if (!cb) { | |
4392 | return stream.emit('error', new Error('write callback called multiple times')); | |
4393 | } | |
4394 | ||
4395 | ts.writechunk = null; | |
4396 | ts.writecb = null; | |
4397 | ||
4398 | if (data !== null && data !== undefined) stream.push(data); | |
4399 | ||
4400 | cb(er); | |
4401 | ||
4402 | var rs = stream._readableState; | |
4403 | rs.reading = false; | |
4404 | if (rs.needReadable || rs.length < rs.highWaterMark) { | |
4405 | stream._read(rs.highWaterMark); | |
4406 | } | |
4407 | } | |
4408 | ||
4409 | function Transform(options) { | |
4410 | if (!(this instanceof Transform)) return new Transform(options); | |
4411 | ||
4412 | Duplex.call(this, options); | |
4413 | ||
4414 | this._transformState = new TransformState(this); | |
4415 | ||
4416 | var stream = this; | |
4417 | ||
4418 | // start out asking for a readable event once data is transformed. | |
4419 | this._readableState.needReadable = true; | |
4420 | ||
4421 | // we have implemented the _read method, and done the other things | |
4422 | // that Readable wants before the first _read call, so unset the | |
4423 | // sync guard flag. | |
4424 | this._readableState.sync = false; | |
4425 | ||
4426 | if (options) { | |
4427 | if (typeof options.transform === 'function') this._transform = options.transform; | |
4428 | ||
4429 | if (typeof options.flush === 'function') this._flush = options.flush; | |
4430 | } | |
4431 | ||
4432 | // When the writable side finishes, then flush out anything remaining. | |
4433 | this.once('prefinish', function () { | |
4434 | if (typeof this._flush === 'function') this._flush(function (er, data) { | |
4435 | done(stream, er, data); | |
4436 | });else done(stream); | |
4437 | }); | |
4438 | } | |
4439 | ||
4440 | Transform.prototype.push = function (chunk, encoding) { | |
4441 | this._transformState.needTransform = false; | |
4442 | return Duplex.prototype.push.call(this, chunk, encoding); | |
4443 | }; | |
4444 | ||
4445 | // This is the part where you do stuff! | |
4446 | // override this function in implementation classes. | |
4447 | // 'chunk' is an input chunk. | |
4448 | // | |
4449 | // Call `push(newChunk)` to pass along transformed output | |
4450 | // to the readable side. You may call 'push' zero or more times. | |
4451 | // | |
4452 | // Call `cb(err)` when you are done with this chunk. If you pass | |
4453 | // an error, then that'll put the hurt on the whole operation. If you | |
4454 | // never call cb(), then you'll never get another chunk. | |
4455 | Transform.prototype._transform = function (chunk, encoding, cb) { | |
4456 | throw new Error('_transform() is not implemented'); | |
4457 | }; | |
4458 | ||
4459 | Transform.prototype._write = function (chunk, encoding, cb) { | |
4460 | var ts = this._transformState; | |
4461 | ts.writecb = cb; | |
4462 | ts.writechunk = chunk; | |
4463 | ts.writeencoding = encoding; | |
4464 | if (!ts.transforming) { | |
4465 | var rs = this._readableState; | |
4466 | if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); | |
4467 | } | |
4468 | }; | |
4469 | ||
4470 | // Doesn't matter what the args are here. | |
4471 | // _transform does all the work. | |
4472 | // That we got here means that the readable side wants more data. | |
4473 | Transform.prototype._read = function (n) { | |
4474 | var ts = this._transformState; | |
4475 | ||
4476 | if (ts.writechunk !== null && ts.writecb && !ts.transforming) { | |
4477 | ts.transforming = true; | |
4478 | this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); | |
4479 | } else { | |
4480 | // mark that we need a transform, so that any data that comes in | |
4481 | // will get processed, now that we've asked for it. | |
4482 | ts.needTransform = true; | |
4483 | } | |
4484 | }; | |
4485 | ||
4486 | Transform.prototype._destroy = function (err, cb) { | |
4487 | var _this = this; | |
4488 | ||
4489 | Duplex.prototype._destroy.call(this, err, function (err2) { | |
4490 | cb(err2); | |
4491 | _this.emit('close'); | |
4492 | }); | |
4493 | }; | |
4494 | ||
4495 | function done(stream, er, data) { | |
4496 | if (er) return stream.emit('error', er); | |
4497 | ||
4498 | if (data !== null && data !== undefined) stream.push(data); | |
4499 | ||
4500 | // if there's nothing in the write buffer, then that means | |
4501 | // that nothing more will ever be provided | |
4502 | var ws = stream._writableState; | |
4503 | var ts = stream._transformState; | |
4504 | ||
4505 | if (ws.length) throw new Error('Calling transform done when ws.length != 0'); | |
4506 | ||
4507 | if (ts.transforming) throw new Error('Calling transform done when still transforming'); | |
4508 | ||
4509 | return stream.push(null); | |
4510 | } | |
4511 | },{"./_stream_duplex":14,"core-util-is":5,"inherits":8}],18:[function(require,module,exports){ | |
4512 | (function (process,global){ | |
4513 | // Copyright Joyent, Inc. and other Node contributors. | |
4514 | // | |
4515 | // Permission is hereby granted, free of charge, to any person obtaining a | |
4516 | // copy of this software and associated documentation files (the | |
4517 | // "Software"), to deal in the Software without restriction, including | |
4518 | // without limitation the rights to use, copy, modify, merge, publish, | |
4519 | // distribute, sublicense, and/or sell copies of the Software, and to permit | |
4520 | // persons to whom the Software is furnished to do so, subject to the | |
4521 | // following conditions: | |
4522 | // | |
4523 | // The above copyright notice and this permission notice shall be included | |
4524 | // in all copies or substantial portions of the Software. | |
4525 | // | |
4526 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
4527 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
4528 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | |
4529 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | |
4530 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | |
4531 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
4532 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | |
4533 | ||
4534 | // A bit simpler than readable streams. | |
4535 | // Implement an async ._write(chunk, encoding, cb), and it'll handle all | |
4536 | // the drain event emission and buffering. | |
4537 | ||
4538 | 'use strict'; | |
4539 | ||
4540 | /*<replacement>*/ | |
4541 | ||
4542 | var processNextTick = require('process-nextick-args'); | |
4543 | /*</replacement>*/ | |
4544 | ||
4545 | module.exports = Writable; | |
4546 | ||
4547 | /* <replacement> */ | |
4548 | function WriteReq(chunk, encoding, cb) { | |
4549 | this.chunk = chunk; | |
4550 | this.encoding = encoding; | |
4551 | this.callback = cb; | |
4552 | this.next = null; | |
4553 | } | |
4554 | ||
4555 | // It seems a linked list but it is not | |
4556 | // there will be only 2 of these for each stream | |
4557 | function CorkedRequest(state) { | |
4558 | var _this = this; | |
4559 | ||
4560 | this.next = null; | |
4561 | this.entry = null; | |
4562 | this.finish = function () { | |
4563 | onCorkedFinish(_this, state); | |
4564 | }; | |
4565 | } | |
4566 | /* </replacement> */ | |
4567 | ||
4568 | /*<replacement>*/ | |
4569 | var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; | |
4570 | /*</replacement>*/ | |
4571 | ||
4572 | /*<replacement>*/ | |
4573 | var Duplex; | |
4574 | /*</replacement>*/ | |
4575 | ||
4576 | Writable.WritableState = WritableState; | |
4577 | ||
4578 | /*<replacement>*/ | |
4579 | var util = require('core-util-is'); | |
4580 | util.inherits = require('inherits'); | |
4581 | /*</replacement>*/ | |
4582 | ||
4583 | /*<replacement>*/ | |
4584 | var internalUtil = { | |
4585 | deprecate: require('util-deprecate') | |
4586 | }; | |
4587 | /*</replacement>*/ | |
4588 | ||
4589 | /*<replacement>*/ | |
4590 | var Stream = require('./internal/streams/stream'); | |
4591 | /*</replacement>*/ | |
4592 | ||
4593 | /*<replacement>*/ | |
4594 | var Buffer = require('safe-buffer').Buffer; | |
4595 | var OurUint8Array = global.Uint8Array || function () {}; | |
4596 | function _uint8ArrayToBuffer(chunk) { | |
4597 | return Buffer.from(chunk); | |
4598 | } | |
4599 | function _isUint8Array(obj) { | |
4600 | return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; | |
4601 | } | |
4602 | /*</replacement>*/ | |
4603 | ||
4604 | var destroyImpl = require('./internal/streams/destroy'); | |
4605 | ||
4606 | util.inherits(Writable, Stream); | |
4607 | ||
4608 | function nop() {} | |
4609 | ||
4610 | function WritableState(options, stream) { | |
4611 | Duplex = Duplex || require('./_stream_duplex'); | |
4612 | ||
4613 | options = options || {}; | |
4614 | ||
4615 | // object stream flag to indicate whether or not this stream | |
4616 | // contains buffers or objects. | |
4617 | this.objectMode = !!options.objectMode; | |
4618 | ||
4619 | if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; | |
4620 | ||
4621 | // the point at which write() starts returning false | |
4622 | // Note: 0 is a valid value, means that we always return false if | |
4623 | // the entire buffer is not flushed immediately on write() | |
4624 | var hwm = options.highWaterMark; | |
4625 | var defaultHwm = this.objectMode ? 16 : 16 * 1024; | |
4626 | this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; | |
4627 | ||
4628 | // cast to ints. | |
4629 | this.highWaterMark = Math.floor(this.highWaterMark); | |
4630 | ||
4631 | // if _final has been called | |
4632 | this.finalCalled = false; | |
4633 | ||
4634 | // drain event flag. | |
4635 | this.needDrain = false; | |
4636 | // at the start of calling end() | |
4637 | this.ending = false; | |
4638 | // when end() has been called, and returned | |
4639 | this.ended = false; | |
4640 | // when 'finish' is emitted | |
4641 | this.finished = false; | |
4642 | ||
4643 | // has it been destroyed | |
4644 | this.destroyed = false; | |
4645 | ||
4646 | // should we decode strings into buffers before passing to _write? | |
4647 | // this is here so that some node-core streams can optimize string | |
4648 | // handling at a lower level. | |
4649 | var noDecode = options.decodeStrings === false; | |
4650 | this.decodeStrings = !noDecode; | |
4651 | ||
4652 | // Crypto is kind of old and crusty. Historically, its default string | |
4653 | // encoding is 'binary' so we have to make this configurable. | |
4654 | // Everything else in the universe uses 'utf8', though. | |
4655 | this.defaultEncoding = options.defaultEncoding || 'utf8'; | |
4656 | ||
4657 | // not an actual buffer we keep track of, but a measurement | |
4658 | // of how much we're waiting to get pushed to some underlying | |
4659 | // socket or file. | |
4660 | this.length = 0; | |
4661 | ||
4662 | // a flag to see when we're in the middle of a write. | |
4663 | this.writing = false; | |
4664 | ||
4665 | // when true all writes will be buffered until .uncork() call | |
4666 | this.corked = 0; | |
4667 | ||
4668 | // a flag to be able to tell if the onwrite cb is called immediately, | |
4669 | // or on a later tick. We set this to true at first, because any | |
4670 | // actions that shouldn't happen until "later" should generally also | |
4671 | // not happen before the first write call. | |
4672 | this.sync = true; | |
4673 | ||
4674 | // a flag to know if we're processing previously buffered items, which | |
4675 | // may call the _write() callback in the same tick, so that we don't | |
4676 | // end up in an overlapped onwrite situation. | |
4677 | this.bufferProcessing = false; | |
4678 | ||
4679 | // the callback that's passed to _write(chunk,cb) | |
4680 | this.onwrite = function (er) { | |
4681 | onwrite(stream, er); | |
4682 | }; | |
4683 | ||
4684 | // the callback that the user supplies to write(chunk,encoding,cb) | |
4685 | this.writecb = null; | |
4686 | ||
4687 | // the amount that is being written when _write is called. | |
4688 | this.writelen = 0; | |
4689 | ||
4690 | this.bufferedRequest = null; | |
4691 | this.lastBufferedRequest = null; | |
4692 | ||
4693 | // number of pending user-supplied write callbacks | |
4694 | // this must be 0 before 'finish' can be emitted | |
4695 | this.pendingcb = 0; | |
4696 | ||
4697 | // emit prefinish if the only thing we're waiting for is _write cbs | |
4698 | // This is relevant for synchronous Transform streams | |
4699 | this.prefinished = false; | |
4700 | ||
4701 | // True if the error was already emitted and should not be thrown again | |
4702 | this.errorEmitted = false; | |
4703 | ||
4704 | // count buffered requests | |
4705 | this.bufferedRequestCount = 0; | |
4706 | ||
4707 | // allocate the first CorkedRequest, there is always | |
4708 | // one allocated and free to use, and we maintain at most two | |
4709 | this.corkedRequestsFree = new CorkedRequest(this); | |
4710 | } | |
4711 | ||
4712 | WritableState.prototype.getBuffer = function getBuffer() { | |
4713 | var current = this.bufferedRequest; | |
4714 | var out = []; | |
4715 | while (current) { | |
4716 | out.push(current); | |
4717 | current = current.next; | |
4718 | } | |
4719 | return out; | |
4720 | }; | |
4721 | ||
4722 | (function () { | |
4723 | try { | |
4724 | Object.defineProperty(WritableState.prototype, 'buffer', { | |
4725 | get: internalUtil.deprecate(function () { | |
4726 | return this.getBuffer(); | |
4727 | }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') | |
4728 | }); | |
4729 | } catch (_) {} | |
4730 | })(); | |
4731 | ||
4732 | // Test _writableState for inheritance to account for Duplex streams, | |
4733 | // whose prototype chain only points to Readable. | |
4734 | var realHasInstance; | |
4735 | if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { | |
4736 | realHasInstance = Function.prototype[Symbol.hasInstance]; | |
4737 | Object.defineProperty(Writable, Symbol.hasInstance, { | |
4738 | value: function (object) { | |
4739 | if (realHasInstance.call(this, object)) return true; | |
4740 | ||
4741 | return object && object._writableState instanceof WritableState; | |
4742 | } | |
4743 | }); | |
4744 | } else { | |
4745 | realHasInstance = function (object) { | |
4746 | return object instanceof this; | |
4747 | }; | |
4748 | } | |
4749 | ||
4750 | function Writable(options) { | |
4751 | Duplex = Duplex || require('./_stream_duplex'); | |
4752 | ||
4753 | // Writable ctor is applied to Duplexes, too. | |
4754 | // `realHasInstance` is necessary because using plain `instanceof` | |
4755 | // would return false, as no `_writableState` property is attached. | |
4756 | ||
4757 | // Trying to use the custom `instanceof` for Writable here will also break the | |
4758 | // Node.js LazyTransform implementation, which has a non-trivial getter for | |
4759 | // `_writableState` that would lead to infinite recursion. | |
4760 | if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { | |
4761 | return new Writable(options); | |
4762 | } | |
4763 | ||
4764 | this._writableState = new WritableState(options, this); | |
4765 | ||
4766 | // legacy. | |
4767 | this.writable = true; | |
4768 | ||
4769 | if (options) { | |
4770 | if (typeof options.write === 'function') this._write = options.write; | |
4771 | ||
4772 | if (typeof options.writev === 'function') this._writev = options.writev; | |
4773 | ||
4774 | if (typeof options.destroy === 'function') this._destroy = options.destroy; | |
4775 | ||
4776 | if (typeof options.final === 'function') this._final = options.final; | |
4777 | } | |
4778 | ||
4779 | Stream.call(this); | |
4780 | } | |
4781 | ||
4782 | // Otherwise people can pipe Writable streams, which is just wrong. | |
4783 | Writable.prototype.pipe = function () { | |
4784 | this.emit('error', new Error('Cannot pipe, not readable')); | |
4785 | }; | |
4786 | ||
4787 | function writeAfterEnd(stream, cb) { | |
4788 | var er = new Error('write after end'); | |
4789 | // TODO: defer error events consistently everywhere, not just the cb | |
4790 | stream.emit('error', er); | |
4791 | processNextTick(cb, er); | |
4792 | } | |
4793 | ||
4794 | // Checks that a user-supplied chunk is valid, especially for the particular | |
4795 | // mode the stream is in. Currently this means that `null` is never accepted | |
4796 | // and undefined/non-string values are only allowed in object mode. | |
4797 | function validChunk(stream, state, chunk, cb) { | |
4798 | var valid = true; | |
4799 | var er = false; | |
4800 | ||
4801 | if (chunk === null) { | |
4802 | er = new TypeError('May not write null values to stream'); | |
4803 | } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { | |
4804 | er = new TypeError('Invalid non-string/buffer chunk'); | |
4805 | } | |
4806 | if (er) { | |
4807 | stream.emit('error', er); | |
4808 | processNextTick(cb, er); | |
4809 | valid = false; | |
4810 | } | |
4811 | return valid; | |
4812 | } | |
4813 | ||
4814 | Writable.prototype.write = function (chunk, encoding, cb) { | |
4815 | var state = this._writableState; | |
4816 | var ret = false; | |
4817 | var isBuf = _isUint8Array(chunk) && !state.objectMode; | |
4818 | ||
4819 | if (isBuf && !Buffer.isBuffer(chunk)) { | |
4820 | chunk = _uint8ArrayToBuffer(chunk); | |
4821 | } | |
4822 | ||
4823 | if (typeof encoding === 'function') { | |
4824 | cb = encoding; | |
4825 | encoding = null; | |
4826 | } | |
4827 | ||
4828 | if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; | |
4829 | ||
4830 | if (typeof cb !== 'function') cb = nop; | |
4831 | ||
4832 | if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { | |
4833 | state.pendingcb++; | |
4834 | ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); | |
4835 | } | |
4836 | ||
4837 | return ret; | |
4838 | }; | |
4839 | ||
4840 | Writable.prototype.cork = function () { | |
4841 | var state = this._writableState; | |
4842 | ||
4843 | state.corked++; | |
4844 | }; | |
4845 | ||
4846 | Writable.prototype.uncork = function () { | |
4847 | var state = this._writableState; | |
4848 | ||
4849 | if (state.corked) { | |
4850 | state.corked--; | |
4851 | ||
4852 | if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); | |
4853 | } | |
4854 | }; | |
4855 | ||
4856 | Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { | |
4857 | // node::ParseEncoding() requires lower case. | |
4858 | if (typeof encoding === 'string') encoding = encoding.toLowerCase(); | |
4859 | 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); | |
4860 | this._writableState.defaultEncoding = encoding; | |
4861 | return this; | |
4862 | }; | |
4863 | ||
4864 | function decodeChunk(state, chunk, encoding) { | |
4865 | if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { | |
4866 | chunk = Buffer.from(chunk, encoding); | |
4867 | } | |
4868 | return chunk; | |
4869 | } | |
4870 | ||
4871 | // if we're already writing something, then just put this | |
4872 | // in the queue, and wait our turn. Otherwise, call _write | |
4873 | // If we return false, then we need a drain event, so set that flag. | |
4874 | function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { | |
4875 | if (!isBuf) { | |
4876 | var newChunk = decodeChunk(state, chunk, encoding); | |
4877 | if (chunk !== newChunk) { | |
4878 | isBuf = true; | |
4879 | encoding = 'buffer'; | |
4880 | chunk = newChunk; | |
4881 | } | |
4882 | } | |
4883 | var len = state.objectMode ? 1 : chunk.length; | |
4884 | ||
4885 | state.length += len; | |
4886 | ||
4887 | var ret = state.length < state.highWaterMark; | |
4888 | // we must ensure that previous needDrain will not be reset to false. | |
4889 | if (!ret) state.needDrain = true; | |
4890 | ||
4891 | if (state.writing || state.corked) { | |
4892 | var last = state.lastBufferedRequest; | |
4893 | state.lastBufferedRequest = { | |
4894 | chunk: chunk, | |
4895 | encoding: encoding, | |
4896 | isBuf: isBuf, | |
4897 | callback: cb, | |
4898 | next: null | |
4899 | }; | |
4900 | if (last) { | |
4901 | last.next = state.lastBufferedRequest; | |
4902 | } else { | |
4903 | state.bufferedRequest = state.lastBufferedRequest; | |
4904 | } | |
4905 | state.bufferedRequestCount += 1; | |
4906 | } else { | |
4907 | doWrite(stream, state, false, len, chunk, encoding, cb); | |
4908 | } | |
4909 | ||
4910 | return ret; | |
4911 | } | |
4912 | ||
4913 | function doWrite(stream, state, writev, len, chunk, encoding, cb) { | |
4914 | state.writelen = len; | |
4915 | state.writecb = cb; | |
4916 | state.writing = true; | |
4917 | state.sync = true; | |
4918 | if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); | |
4919 | state.sync = false; | |
4920 | } | |
4921 | ||
4922 | function onwriteError(stream, state, sync, er, cb) { | |
4923 | --state.pendingcb; | |
4924 | ||
4925 | if (sync) { | |
4926 | // defer the callback if we are being called synchronously | |
4927 | // to avoid piling up things on the stack | |
4928 | processNextTick(cb, er); | |
4929 | // this can emit finish, and it will always happen | |
4930 | // after error | |
4931 | processNextTick(finishMaybe, stream, state); | |
4932 | stream._writableState.errorEmitted = true; | |
4933 | stream.emit('error', er); | |
4934 | } else { | |
4935 | // the caller expect this to happen before if | |
4936 | // it is async | |
4937 | cb(er); | |
4938 | stream._writableState.errorEmitted = true; | |
4939 | stream.emit('error', er); | |
4940 | // this can emit finish, but finish must | |
4941 | // always follow error | |
4942 | finishMaybe(stream, state); | |
4943 | } | |
4944 | } | |
4945 | ||
4946 | function onwriteStateUpdate(state) { | |
4947 | state.writing = false; | |
4948 | state.writecb = null; | |
4949 | state.length -= state.writelen; | |
4950 | state.writelen = 0; | |
4951 | } | |
4952 | ||
4953 | function onwrite(stream, er) { | |
4954 | var state = stream._writableState; | |
4955 | var sync = state.sync; | |
4956 | var cb = state.writecb; | |
4957 | ||
4958 | onwriteStateUpdate(state); | |
4959 | ||
4960 | if (er) onwriteError(stream, state, sync, er, cb);else { | |
4961 | // Check if we're actually ready to finish, but don't emit yet | |
4962 | var finished = needFinish(state); | |
4963 | ||
4964 | if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { | |
4965 | clearBuffer(stream, state); | |
4966 | } | |
4967 | ||
4968 | if (sync) { | |
4969 | /*<replacement>*/ | |
4970 | asyncWrite(afterWrite, stream, state, finished, cb); | |
4971 | /*</replacement>*/ | |
4972 | } else { | |
4973 | afterWrite(stream, state, finished, cb); | |
4974 | } | |
4975 | } | |
4976 | } | |
4977 | ||
4978 | function afterWrite(stream, state, finished, cb) { | |
4979 | if (!finished) onwriteDrain(stream, state); | |
4980 | state.pendingcb--; | |
4981 | cb(); | |
4982 | finishMaybe(stream, state); | |
4983 | } | |
4984 | ||
4985 | // Must force callback to be called on nextTick, so that we don't | |
4986 | // emit 'drain' before the write() consumer gets the 'false' return | |
4987 | // value, and has a chance to attach a 'drain' listener. | |
4988 | function onwriteDrain(stream, state) { | |
4989 | if (state.length === 0 && state.needDrain) { | |
4990 | state.needDrain = false; | |
4991 | stream.emit('drain'); | |
4992 | } | |
4993 | } | |
4994 | ||
4995 | // if there's something in the buffer waiting, then process it | |
4996 | function clearBuffer(stream, state) { | |
4997 | state.bufferProcessing = true; | |
4998 | var entry = state.bufferedRequest; | |
4999 | ||
5000 | if (stream._writev && entry && entry.next) { | |
5001 | // Fast case, write everything using _writev() | |
5002 | var l = state.bufferedRequestCount; | |
5003 | var buffer = new Array(l); | |
5004 | var holder = state.corkedRequestsFree; | |
5005 | holder.entry = entry; | |
5006 | ||
5007 | var count = 0; | |
5008 | var allBuffers = true; | |
5009 | while (entry) { | |
5010 | buffer[count] = entry; | |
5011 | if (!entry.isBuf) allBuffers = false; | |
5012 | entry = entry.next; | |
5013 | count += 1; | |
5014 | } | |
5015 | buffer.allBuffers = allBuffers; | |
5016 | ||
5017 | doWrite(stream, state, true, state.length, buffer, '', holder.finish); | |
5018 | ||
5019 | // doWrite is almost always async, defer these to save a bit of time | |
5020 | // as the hot path ends with doWrite | |
5021 | state.pendingcb++; | |
5022 | state.lastBufferedRequest = null; | |
5023 | if (holder.next) { | |
5024 | state.corkedRequestsFree = holder.next; | |
5025 | holder.next = null; | |
5026 | } else { | |
5027 | state.corkedRequestsFree = new CorkedRequest(state); | |
5028 | } | |
5029 | } else { | |
5030 | // Slow case, write chunks one-by-one | |
5031 | while (entry) { | |
5032 | var chunk = entry.chunk; | |
5033 | var encoding = entry.encoding; | |
5034 | var cb = entry.callback; | |
5035 | var len = state.objectMode ? 1 : chunk.length; | |
5036 | ||
5037 | doWrite(stream, state, false, len, chunk, encoding, cb); | |
5038 | entry = entry.next; | |
5039 | // if we didn't call the onwrite immediately, then | |
5040 | // it means that we need to wait until it does. | |
5041 | // also, that means that the chunk and cb are currently | |
5042 | // being processed, so move the buffer counter past them. | |
5043 | if (state.writing) { | |
5044 | break; | |
5045 | } | |
5046 | } | |
5047 | ||
5048 | if (entry === null) state.lastBufferedRequest = null; | |
5049 | } | |
5050 | ||
5051 | state.bufferedRequestCount = 0; | |
5052 | state.bufferedRequest = entry; | |
5053 | state.bufferProcessing = false; | |
5054 | } | |
5055 | ||
5056 | Writable.prototype._write = function (chunk, encoding, cb) { | |
5057 | cb(new Error('_write() is not implemented')); | |
5058 | }; | |
5059 | ||
5060 | Writable.prototype._writev = null; | |
5061 | ||
5062 | Writable.prototype.end = function (chunk, encoding, cb) { | |
5063 | var state = this._writableState; | |
5064 | ||
5065 | if (typeof chunk === 'function') { | |
5066 | cb = chunk; | |
5067 | chunk = null; | |
5068 | encoding = null; | |
5069 | } else if (typeof encoding === 'function') { | |
5070 | cb = encoding; | |
5071 | encoding = null; | |
5072 | } | |
5073 | ||
5074 | if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); | |
5075 | ||
5076 | // .end() fully uncorks | |
5077 | if (state.corked) { | |
5078 | state.corked = 1; | |
5079 | this.uncork(); | |
5080 | } | |
5081 | ||
5082 | // ignore unnecessary end() calls. | |
5083 | if (!state.ending && !state.finished) endWritable(this, state, cb); | |
5084 | }; | |
5085 | ||
5086 | function needFinish(state) { | |
5087 | return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; | |
5088 | } | |
5089 | function callFinal(stream, state) { | |
5090 | stream._final(function (err) { | |
5091 | state.pendingcb--; | |
5092 | if (err) { | |
5093 | stream.emit('error', err); | |
5094 | } | |
5095 | state.prefinished = true; | |
5096 | stream.emit('prefinish'); | |
5097 | finishMaybe(stream, state); | |
5098 | }); | |
5099 | } | |
5100 | function prefinish(stream, state) { | |
5101 | if (!state.prefinished && !state.finalCalled) { | |
5102 | if (typeof stream._final === 'function') { | |
5103 | state.pendingcb++; | |
5104 | state.finalCalled = true; | |
5105 | processNextTick(callFinal, stream, state); | |
5106 | } else { | |
5107 | state.prefinished = true; | |
5108 | stream.emit('prefinish'); | |
5109 | } | |
5110 | } | |
5111 | } | |
5112 | ||
5113 | function finishMaybe(stream, state) { | |
5114 | var need = needFinish(state); | |
5115 | if (need) { | |
5116 | prefinish(stream, state); | |
5117 | if (state.pendingcb === 0) { | |
5118 | state.finished = true; | |
5119 | stream.emit('finish'); | |
5120 | } | |
5121 | } | |
5122 | return need; | |
5123 | } | |
5124 | ||
5125 | function endWritable(stream, state, cb) { | |
5126 | state.ending = true; | |
5127 | finishMaybe(stream, state); | |
5128 | if (cb) { | |
5129 | if (state.finished) processNextTick(cb);else stream.once('finish', cb); | |
5130 | } | |
5131 | state.ended = true; | |
5132 | stream.writable = false; | |
5133 | } | |
5134 | ||
5135 | function onCorkedFinish(corkReq, state, err) { | |
5136 | var entry = corkReq.entry; | |
5137 | corkReq.entry = null; | |
5138 | while (entry) { | |
5139 | var cb = entry.callback; | |
5140 | state.pendingcb--; | |
5141 | cb(err); | |
5142 | entry = entry.next; | |
5143 | } | |
5144 | if (state.corkedRequestsFree) { | |
5145 | state.corkedRequestsFree.next = corkReq; | |
5146 | } else { | |
5147 | state.corkedRequestsFree = corkReq; | |
5148 | } | |
5149 | } | |
5150 | ||
5151 | Object.defineProperty(Writable.prototype, 'destroyed', { | |
5152 | get: function () { | |
5153 | if (this._writableState === undefined) { | |
5154 | return false; | |
5155 | } | |
5156 | return this._writableState.destroyed; | |
5157 | }, | |
5158 | set: function (value) { | |
5159 | // we ignore the value if the stream | |
5160 | // has not been initialized yet | |
5161 | if (!this._writableState) { | |
5162 | return; | |
5163 | } | |
5164 | ||
5165 | // backward compatibility, the user is explicitly | |
5166 | // managing destroyed | |
5167 | this._writableState.destroyed = value; | |
5168 | } | |
5169 | }); | |
5170 | ||
5171 | Writable.prototype.destroy = destroyImpl.destroy; | |
5172 | Writable.prototype._undestroy = destroyImpl.undestroy; | |
5173 | Writable.prototype._destroy = function (err, cb) { | |
5174 | this.end(); | |
5175 | cb(err); | |
5176 | }; | |
5177 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | |
5178 | },{"./_stream_duplex":14,"./internal/streams/destroy":20,"./internal/streams/stream":21,"_process":12,"core-util-is":5,"inherits":8,"process-nextick-args":11,"safe-buffer":26,"util-deprecate":29}],19:[function(require,module,exports){ | |
5179 | 'use strict'; | |
5180 | ||
5181 | /*<replacement>*/ | |
5182 | ||
5183 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | |
5184 | ||
5185 | var Buffer = require('safe-buffer').Buffer; | |
5186 | /*</replacement>*/ | |
5187 | ||
5188 | function copyBuffer(src, target, offset) { | |
5189 | src.copy(target, offset); | |
5190 | } | |
5191 | ||
5192 | module.exports = function () { | |
5193 | function BufferList() { | |
5194 | _classCallCheck(this, BufferList); | |
5195 | ||
5196 | this.head = null; | |
5197 | this.tail = null; | |
5198 | this.length = 0; | |
5199 | } | |
5200 | ||
5201 | BufferList.prototype.push = function push(v) { | |
5202 | var entry = { data: v, next: null }; | |
5203 | if (this.length > 0) this.tail.next = entry;else this.head = entry; | |
5204 | this.tail = entry; | |
5205 | ++this.length; | |
5206 | }; | |
5207 | ||
5208 | BufferList.prototype.unshift = function unshift(v) { | |
5209 | var entry = { data: v, next: this.head }; | |
5210 | if (this.length === 0) this.tail = entry; | |
5211 | this.head = entry; | |
5212 | ++this.length; | |
5213 | }; | |
5214 | ||
5215 | BufferList.prototype.shift = function shift() { | |
5216 | if (this.length === 0) return; | |
5217 | var ret = this.head.data; | |
5218 | if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; | |
5219 | --this.length; | |
5220 | return ret; | |
5221 | }; | |
5222 | ||
5223 | BufferList.prototype.clear = function clear() { | |
5224 | this.head = this.tail = null; | |
5225 | this.length = 0; | |
5226 | }; | |
5227 | ||
5228 | BufferList.prototype.join = function join(s) { | |
5229 | if (this.length === 0) return ''; | |
5230 | var p = this.head; | |
5231 | var ret = '' + p.data; | |
5232 | while (p = p.next) { | |
5233 | ret += s + p.data; | |
5234 | }return ret; | |
5235 | }; | |
5236 | ||
5237 | BufferList.prototype.concat = function concat(n) { | |
5238 | if (this.length === 0) return Buffer.alloc(0); | |
5239 | if (this.length === 1) return this.head.data; | |
5240 | var ret = Buffer.allocUnsafe(n >>> 0); | |
5241 | var p = this.head; | |
5242 | var i = 0; | |
5243 | while (p) { | |
5244 | copyBuffer(p.data, ret, i); | |
5245 | i += p.data.length; | |
5246 | p = p.next; | |
5247 | } | |
5248 | return ret; | |
5249 | }; | |
5250 | ||
5251 | return BufferList; | |
5252 | }(); | |
5253 | },{"safe-buffer":26}],20:[function(require,module,exports){ | |
5254 | 'use strict'; | |
5255 | ||
5256 | /*<replacement>*/ | |
5257 | ||
5258 | var processNextTick = require('process-nextick-args'); | |
5259 | /*</replacement>*/ | |
5260 | ||
5261 | // undocumented cb() API, needed for core, not for public API | |
5262 | function destroy(err, cb) { | |
5263 | var _this = this; | |
5264 | ||
5265 | var readableDestroyed = this._readableState && this._readableState.destroyed; | |
5266 | var writableDestroyed = this._writableState && this._writableState.destroyed; | |
5267 | ||
5268 | if (readableDestroyed || writableDestroyed) { | |
5269 | if (cb) { | |
5270 | cb(err); | |
5271 | } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { | |
5272 | processNextTick(emitErrorNT, this, err); | |
5273 | } | |
5274 | return; | |
5275 | } | |
5276 | ||
5277 | // we set destroyed to true before firing error callbacks in order | |
5278 | // to make it re-entrance safe in case destroy() is called within callbacks | |
5279 | ||
5280 | if (this._readableState) { | |
5281 | this._readableState.destroyed = true; | |
5282 | } | |
5283 | ||
5284 | // if this is a duplex stream mark the writable part as destroyed as well | |
5285 | if (this._writableState) { | |
5286 | this._writableState.destroyed = true; | |
5287 | } | |
5288 | ||
5289 | this._destroy(err || null, function (err) { | |
5290 | if (!cb && err) { | |
5291 | processNextTick(emitErrorNT, _this, err); | |
5292 | if (_this._writableState) { | |
5293 | _this._writableState.errorEmitted = true; | |
5294 | } | |
5295 | } else if (cb) { | |
5296 | cb(err); | |
5297 | } | |
5298 | }); | |
5299 | } | |
5300 | ||
5301 | function undestroy() { | |
5302 | if (this._readableState) { | |
5303 | this._readableState.destroyed = false; | |
5304 | this._readableState.reading = false; | |
5305 | this._readableState.ended = false; | |
5306 | this._readableState.endEmitted = false; | |
5307 | } | |
5308 | ||
5309 | if (this._writableState) { | |
5310 | this._writableState.destroyed = false; | |
5311 | this._writableState.ended = false; | |
5312 | this._writableState.ending = false; | |
5313 | this._writableState.finished = false; | |
5314 | this._writableState.errorEmitted = false; | |
5315 | } | |
5316 | } | |
5317 | ||
5318 | function emitErrorNT(self, err) { | |
5319 | self.emit('error', err); | |
5320 | } | |
5321 | ||
5322 | module.exports = { | |
5323 | destroy: destroy, | |
5324 | undestroy: undestroy | |
5325 | }; | |
5326 | },{"process-nextick-args":11}],21:[function(require,module,exports){ | |
5327 | module.exports = require('events').EventEmitter; | |
5328 | ||
5329 | },{"events":6}],22:[function(require,module,exports){ | |
5330 | module.exports = require('./readable').PassThrough | |
5331 | ||
5332 | },{"./readable":23}],23:[function(require,module,exports){ | |
5333 | exports = module.exports = require('./lib/_stream_readable.js'); | |
5334 | exports.Stream = exports; | |
5335 | exports.Readable = exports; | |
5336 | exports.Writable = require('./lib/_stream_writable.js'); | |
5337 | exports.Duplex = require('./lib/_stream_duplex.js'); | |
5338 | exports.Transform = require('./lib/_stream_transform.js'); | |
5339 | exports.PassThrough = require('./lib/_stream_passthrough.js'); | |
5340 | ||
5341 | },{"./lib/_stream_duplex.js":14,"./lib/_stream_passthrough.js":15,"./lib/_stream_readable.js":16,"./lib/_stream_transform.js":17,"./lib/_stream_writable.js":18}],24:[function(require,module,exports){ | |
5342 | module.exports = require('./readable').Transform | |
5343 | ||
5344 | },{"./readable":23}],25:[function(require,module,exports){ | |
5345 | module.exports = require('./lib/_stream_writable.js'); | |
5346 | ||
5347 | },{"./lib/_stream_writable.js":18}],26:[function(require,module,exports){ | |
5348 | /* eslint-disable node/no-deprecated-api */ | |
5349 | var buffer = require('buffer') | |
5350 | var Buffer = buffer.Buffer | |
5351 | ||
5352 | // alternative to using Object.keys for old browsers | |
5353 | function copyProps (src, dst) { | |
5354 | for (var key in src) { | |
5355 | dst[key] = src[key] | |
5356 | } | |
5357 | } | |
5358 | if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { | |
5359 | module.exports = buffer | |
5360 | } else { | |
5361 | // Copy properties from require('buffer') | |
5362 | copyProps(buffer, exports) | |
5363 | exports.Buffer = SafeBuffer | |
5364 | } | |
5365 | ||
5366 | function SafeBuffer (arg, encodingOrOffset, length) { | |
5367 | return Buffer(arg, encodingOrOffset, length) | |
5368 | } | |
5369 | ||
5370 | // Copy static methods from Buffer | |
5371 | copyProps(Buffer, SafeBuffer) | |
5372 | ||
5373 | SafeBuffer.from = function (arg, encodingOrOffset, length) { | |
5374 | if (typeof arg === 'number') { | |
5375 | throw new TypeError('Argument must not be a number') | |
5376 | } | |
5377 | return Buffer(arg, encodingOrOffset, length) | |
5378 | } | |
5379 | ||
5380 | SafeBuffer.alloc = function (size, fill, encoding) { | |
5381 | if (typeof size !== 'number') { | |
5382 | throw new TypeError('Argument must be a number') | |
5383 | } | |
5384 | var buf = Buffer(size) | |
5385 | if (fill !== undefined) { | |
5386 | if (typeof encoding === 'string') { | |
5387 | buf.fill(fill, encoding) | |
5388 | } else { | |
5389 | buf.fill(fill) | |
5390 | } | |
5391 | } else { | |
5392 | buf.fill(0) | |
5393 | } | |
5394 | return buf | |
5395 | } | |
5396 | ||
5397 | SafeBuffer.allocUnsafe = function (size) { | |
5398 | if (typeof size !== 'number') { | |
5399 | throw new TypeError('Argument must be a number') | |
5400 | } | |
5401 | return Buffer(size) | |
5402 | } | |
5403 | ||
5404 | SafeBuffer.allocUnsafeSlow = function (size) { | |
5405 | if (typeof size !== 'number') { | |
5406 | throw new TypeError('Argument must be a number') | |
5407 | } | |
5408 | return buffer.SlowBuffer(size) | |
5409 | } | |
5410 | ||
5411 | },{"buffer":4}],27:[function(require,module,exports){ | |
5412 | // Copyright Joyent, Inc. and other Node contributors. | |
5413 | // | |
5414 | // Permission is hereby granted, free of charge, to any person obtaining a | |
5415 | // copy of this software and associated documentation files (the | |
5416 | // "Software"), to deal in the Software without restriction, including | |
5417 | // without limitation the rights to use, copy, modify, merge, publish, | |
5418 | // distribute, sublicense, and/or sell copies of the Software, and to permit | |
5419 | // persons to whom the Software is furnished to do so, subject to the | |
5420 | // following conditions: | |
5421 | // | |
5422 | // The above copyright notice and this permission notice shall be included | |
5423 | // in all copies or substantial portions of the Software. | |
5424 | // | |
5425 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
5426 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
5427 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | |
5428 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | |
5429 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | |
5430 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
5431 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | |
5432 | ||
5433 | module.exports = Stream; | |
5434 | ||
5435 | var EE = require('events').EventEmitter; | |
5436 | var inherits = require('inherits'); | |
5437 | ||
5438 | inherits(Stream, EE); | |
5439 | Stream.Readable = require('readable-stream/readable.js'); | |
5440 | Stream.Writable = require('readable-stream/writable.js'); | |
5441 | Stream.Duplex = require('readable-stream/duplex.js'); | |
5442 | Stream.Transform = require('readable-stream/transform.js'); | |
5443 | Stream.PassThrough = require('readable-stream/passthrough.js'); | |
5444 | ||
5445 | // Backwards-compat with node 0.4.x | |
5446 | Stream.Stream = Stream; | |
5447 | ||
5448 | ||
5449 | ||
5450 | // old-style streams. Note that the pipe method (the only relevant | |
5451 | // part of this class) is overridden in the Readable class. | |
5452 | ||
5453 | function Stream() { | |
5454 | EE.call(this); | |
5455 | } | |
5456 | ||
5457 | Stream.prototype.pipe = function(dest, options) { | |
5458 | var source = this; | |
5459 | ||
5460 | function ondata(chunk) { | |
5461 | if (dest.writable) { | |
5462 | if (false === dest.write(chunk) && source.pause) { | |
5463 | source.pause(); | |
5464 | } | |
5465 | } | |
5466 | } | |
5467 | ||
5468 | source.on('data', ondata); | |
5469 | ||
5470 | function ondrain() { | |
5471 | if (source.readable && source.resume) { | |
5472 | source.resume(); | |
5473 | } | |
5474 | } | |
5475 | ||
5476 | dest.on('drain', ondrain); | |
5477 | ||
5478 | // If the 'end' option is not supplied, dest.end() will be called when | |
5479 | // source gets the 'end' or 'close' events. Only dest.end() once. | |
5480 | if (!dest._isStdio && (!options || options.end !== false)) { | |
5481 | source.on('end', onend); | |
5482 | source.on('close', onclose); | |
5483 | } | |
5484 | ||
5485 | var didOnEnd = false; | |
5486 | function onend() { | |
5487 | if (didOnEnd) return; | |
5488 | didOnEnd = true; | |
5489 | ||
5490 | dest.end(); | |
5491 | } | |
5492 | ||
5493 | ||
5494 | function onclose() { | |
5495 | if (didOnEnd) return; | |
5496 | didOnEnd = true; | |
5497 | ||
5498 | if (typeof dest.destroy === 'function') dest.destroy(); | |
5499 | } | |
5500 | ||
5501 | // don't leave dangling pipes when there are errors. | |
5502 | function onerror(er) { | |
5503 | cleanup(); | |
5504 | if (EE.listenerCount(this, 'error') === 0) { | |
5505 | throw er; // Unhandled stream error in pipe. | |
5506 | } | |
5507 | } | |
5508 | ||
5509 | source.on('error', onerror); | |
5510 | dest.on('error', onerror); | |
5511 | ||
5512 | // remove all the event listeners that were added. | |
5513 | function cleanup() { | |
5514 | source.removeListener('data', ondata); | |
5515 | dest.removeListener('drain', ondrain); | |
5516 | ||
5517 | source.removeListener('end', onend); | |
5518 | source.removeListener('close', onclose); | |
5519 | ||
5520 | source.removeListener('error', onerror); | |
5521 | dest.removeListener('error', onerror); | |
5522 | ||
5523 | source.removeListener('end', cleanup); | |
5524 | source.removeListener('close', cleanup); | |
5525 | ||
5526 | dest.removeListener('close', cleanup); | |
5527 | } | |
5528 | ||
5529 | source.on('end', cleanup); | |
5530 | source.on('close', cleanup); | |
5531 | ||
5532 | dest.on('close', cleanup); | |
5533 | ||
5534 | dest.emit('pipe', source); | |
5535 | ||
5536 | // Allow for unix-like usage: A.pipe(B).pipe(C) | |
5537 | return dest; | |
5538 | }; | |
5539 | ||
5540 | },{"events":6,"inherits":8,"readable-stream/duplex.js":13,"readable-stream/passthrough.js":22,"readable-stream/readable.js":23,"readable-stream/transform.js":24,"readable-stream/writable.js":25}],28:[function(require,module,exports){ | |
5541 | 'use strict'; | |
5542 | ||
5543 | var Buffer = require('safe-buffer').Buffer; | |
5544 | ||
5545 | var isEncoding = Buffer.isEncoding || function (encoding) { | |
5546 | encoding = '' + encoding; | |
5547 | switch (encoding && encoding.toLowerCase()) { | |
5548 | 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': | |
5549 | return true; | |
5550 | default: | |
5551 | return false; | |
5552 | } | |
5553 | }; | |
5554 | ||
5555 | function _normalizeEncoding(enc) { | |
5556 | if (!enc) return 'utf8'; | |
5557 | var retried; | |
5558 | while (true) { | |
5559 | switch (enc) { | |
5560 | case 'utf8': | |
5561 | case 'utf-8': | |
5562 | return 'utf8'; | |
5563 | case 'ucs2': | |
5564 | case 'ucs-2': | |
5565 | case 'utf16le': | |
5566 | case 'utf-16le': | |
5567 | return 'utf16le'; | |
5568 | case 'latin1': | |
5569 | case 'binary': | |
5570 | return 'latin1'; | |
5571 | case 'base64': | |
5572 | case 'ascii': | |
5573 | case 'hex': | |
5574 | return enc; | |
5575 | default: | |
5576 | if (retried) return; // undefined | |
5577 | enc = ('' + enc).toLowerCase(); | |
5578 | retried = true; | |
5579 | } | |
5580 | } | |
5581 | }; | |
5582 | ||
5583 | // Do not cache `Buffer.isEncoding` when checking encoding names as some | |
5584 | // modules monkey-patch it to support additional encodings | |
5585 | function normalizeEncoding(enc) { | |
5586 | var nenc = _normalizeEncoding(enc); | |
5587 | if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); | |
5588 | return nenc || enc; | |
5589 | } | |
5590 | ||
5591 | // StringDecoder provides an interface for efficiently splitting a series of | |
5592 | // buffers into a series of JS strings without breaking apart multi-byte | |
5593 | // characters. | |
5594 | exports.StringDecoder = StringDecoder; | |
5595 | function StringDecoder(encoding) { | |
5596 | this.encoding = normalizeEncoding(encoding); | |
5597 | var nb; | |
5598 | switch (this.encoding) { | |
5599 | case 'utf16le': | |
5600 | this.text = utf16Text; | |
5601 | this.end = utf16End; | |
5602 | nb = 4; | |
5603 | break; | |
5604 | case 'utf8': | |
5605 | this.fillLast = utf8FillLast; | |
5606 | nb = 4; | |
5607 | break; | |
5608 | case 'base64': | |
5609 | this.text = base64Text; | |
5610 | this.end = base64End; | |
5611 | nb = 3; | |
5612 | break; | |
5613 | default: | |
5614 | this.write = simpleWrite; | |
5615 | this.end = simpleEnd; | |
5616 | return; | |
5617 | } | |
5618 | this.lastNeed = 0; | |
5619 | this.lastTotal = 0; | |
5620 | this.lastChar = Buffer.allocUnsafe(nb); | |
5621 | } | |
5622 | ||
5623 | StringDecoder.prototype.write = function (buf) { | |
5624 | if (buf.length === 0) return ''; | |
5625 | var r; | |
5626 | var i; | |
5627 | if (this.lastNeed) { | |
5628 | r = this.fillLast(buf); | |
5629 | if (r === undefined) return ''; | |
5630 | i = this.lastNeed; | |
5631 | this.lastNeed = 0; | |
5632 | } else { | |
5633 | i = 0; | |
5634 | } | |
5635 | if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); | |
5636 | return r || ''; | |
5637 | }; | |
5638 | ||
5639 | StringDecoder.prototype.end = utf8End; | |
5640 | ||
5641 | // Returns only complete characters in a Buffer | |
5642 | StringDecoder.prototype.text = utf8Text; | |
5643 | ||
5644 | // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer | |
5645 | StringDecoder.prototype.fillLast = function (buf) { | |
5646 | if (this.lastNeed <= buf.length) { | |
5647 | buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); | |
5648 | return this.lastChar.toString(this.encoding, 0, this.lastTotal); | |
5649 | } | |
5650 | buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); | |
5651 | this.lastNeed -= buf.length; | |
5652 | }; | |
5653 | ||
5654 | // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a | |
5655 | // continuation byte. | |
5656 | function utf8CheckByte(byte) { | |
5657 | 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; | |
5658 | return -1; | |
5659 | } | |
5660 | ||
5661 | // Checks at most 3 bytes at the end of a Buffer in order to detect an | |
5662 | // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) | |
5663 | // needed to complete the UTF-8 character (if applicable) are returned. | |
5664 | function utf8CheckIncomplete(self, buf, i) { | |
5665 | var j = buf.length - 1; | |
5666 | if (j < i) return 0; | |
5667 | var nb = utf8CheckByte(buf[j]); | |
5668 | if (nb >= 0) { | |
5669 | if (nb > 0) self.lastNeed = nb - 1; | |
5670 | return nb; | |
5671 | } | |
5672 | if (--j < i) return 0; | |
5673 | nb = utf8CheckByte(buf[j]); | |
5674 | if (nb >= 0) { | |
5675 | if (nb > 0) self.lastNeed = nb - 2; | |
5676 | return nb; | |
5677 | } | |
5678 | if (--j < i) return 0; | |
5679 | nb = utf8CheckByte(buf[j]); | |
5680 | if (nb >= 0) { | |
5681 | if (nb > 0) { | |
5682 | if (nb === 2) nb = 0;else self.lastNeed = nb - 3; | |
5683 | } | |
5684 | return nb; | |
5685 | } | |
5686 | return 0; | |
5687 | } | |
5688 | ||
5689 | // Validates as many continuation bytes for a multi-byte UTF-8 character as | |
5690 | // needed or are available. If we see a non-continuation byte where we expect | |
5691 | // one, we "replace" the validated continuation bytes we've seen so far with | |
5692 | // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding | |
5693 | // behavior. The continuation byte check is included three times in the case | |
5694 | // where all of the continuation bytes for a character exist in the same buffer. | |
5695 | // It is also done this way as a slight performance increase instead of using a | |
5696 | // loop. | |
5697 | function utf8CheckExtraBytes(self, buf, p) { | |
5698 | if ((buf[0] & 0xC0) !== 0x80) { | |
5699 | self.lastNeed = 0; | |
5700 | return '\ufffd'.repeat(p); | |
5701 | } | |
5702 | if (self.lastNeed > 1 && buf.length > 1) { | |
5703 | if ((buf[1] & 0xC0) !== 0x80) { | |
5704 | self.lastNeed = 1; | |
5705 | return '\ufffd'.repeat(p + 1); | |
5706 | } | |
5707 | if (self.lastNeed > 2 && buf.length > 2) { | |
5708 | if ((buf[2] & 0xC0) !== 0x80) { | |
5709 | self.lastNeed = 2; | |
5710 | return '\ufffd'.repeat(p + 2); | |
5711 | } | |
5712 | } | |
5713 | } | |
5714 | } | |
5715 | ||
5716 | // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. | |
5717 | function utf8FillLast(buf) { | |
5718 | var p = this.lastTotal - this.lastNeed; | |
5719 | var r = utf8CheckExtraBytes(this, buf, p); | |
5720 | if (r !== undefined) return r; | |
5721 | if (this.lastNeed <= buf.length) { | |
5722 | buf.copy(this.lastChar, p, 0, this.lastNeed); | |
5723 | return this.lastChar.toString(this.encoding, 0, this.lastTotal); | |
5724 | } | |
5725 | buf.copy(this.lastChar, p, 0, buf.length); | |
5726 | this.lastNeed -= buf.length; | |
5727 | } | |
5728 | ||
5729 | // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a | |
5730 | // partial character, the character's bytes are buffered until the required | |
5731 | // number of bytes are available. | |
5732 | function utf8Text(buf, i) { | |
5733 | var total = utf8CheckIncomplete(this, buf, i); | |
5734 | if (!this.lastNeed) return buf.toString('utf8', i); | |
5735 | this.lastTotal = total; | |
5736 | var end = buf.length - (total - this.lastNeed); | |
5737 | buf.copy(this.lastChar, 0, end); | |
5738 | return buf.toString('utf8', i, end); | |
5739 | } | |
5740 | ||
5741 | // For UTF-8, a replacement character for each buffered byte of a (partial) | |
5742 | // character needs to be added to the output. | |
5743 | function utf8End(buf) { | |
5744 | var r = buf && buf.length ? this.write(buf) : ''; | |
5745 | if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); | |
5746 | return r; | |
5747 | } | |
5748 | ||
5749 | // UTF-16LE typically needs two bytes per character, but even if we have an even | |
5750 | // number of bytes available, we need to check if we end on a leading/high | |
5751 | // surrogate. In that case, we need to wait for the next two bytes in order to | |
5752 | // decode the last character properly. | |
5753 | function utf16Text(buf, i) { | |
5754 | if ((buf.length - i) % 2 === 0) { | |
5755 | var r = buf.toString('utf16le', i); | |
5756 | if (r) { | |
5757 | var c = r.charCodeAt(r.length - 1); | |
5758 | if (c >= 0xD800 && c <= 0xDBFF) { | |
5759 | this.lastNeed = 2; | |
5760 | this.lastTotal = 4; | |
5761 | this.lastChar[0] = buf[buf.length - 2]; | |
5762 | this.lastChar[1] = buf[buf.length - 1]; | |
5763 | return r.slice(0, -1); | |
5764 | } | |
5765 | } | |
5766 | return r; | |
5767 | } | |
5768 | this.lastNeed = 1; | |
5769 | this.lastTotal = 2; | |
5770 | this.lastChar[0] = buf[buf.length - 1]; | |
5771 | return buf.toString('utf16le', i, buf.length - 1); | |
5772 | } | |
5773 | ||
5774 | // For UTF-16LE we do not explicitly append special replacement characters if we | |
5775 | // end on a partial character, we simply let v8 handle that. | |
5776 | function utf16End(buf) { | |
5777 | var r = buf && buf.length ? this.write(buf) : ''; | |
5778 | if (this.lastNeed) { | |
5779 | var end = this.lastTotal - this.lastNeed; | |
5780 | return r + this.lastChar.toString('utf16le', 0, end); | |
5781 | } | |
5782 | return r; | |
5783 | } | |
5784 | ||
5785 | function base64Text(buf, i) { | |
5786 | var n = (buf.length - i) % 3; | |
5787 | if (n === 0) return buf.toString('base64', i); | |
5788 | this.lastNeed = 3 - n; | |
5789 | this.lastTotal = 3; | |
5790 | if (n === 1) { | |
5791 | this.lastChar[0] = buf[buf.length - 1]; | |
5792 | } else { | |
5793 | this.lastChar[0] = buf[buf.length - 2]; | |
5794 | this.lastChar[1] = buf[buf.length - 1]; | |
5795 | } | |
5796 | return buf.toString('base64', i, buf.length - n); | |
5797 | } | |
5798 | ||
5799 | function base64End(buf) { | |
5800 | var r = buf && buf.length ? this.write(buf) : ''; | |
5801 | if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); | |
5802 | return r; | |
5803 | } | |
5804 | ||
5805 | // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) | |
5806 | function simpleWrite(buf) { | |
5807 | return buf.toString(this.encoding); | |
5808 | } | |
5809 | ||
5810 | function simpleEnd(buf) { | |
5811 | return buf && buf.length ? this.write(buf) : ''; | |
5812 | } | |
5813 | },{"safe-buffer":26}],29:[function(require,module,exports){ | |
5814 | (function (global){ | |
5815 | ||
5816 | /** | |
5817 | * Module exports. | |
5818 | */ | |
5819 | ||
5820 | module.exports = deprecate; | |
5821 | ||
5822 | /** | |
5823 | * Mark that a method should not be used. | |
5824 | * Returns a modified function which warns once by default. | |
5825 | * | |
5826 | * If `localStorage.noDeprecation = true` is set, then it is a no-op. | |
5827 | * | |
5828 | * If `localStorage.throwDeprecation = true` is set, then deprecated functions | |
5829 | * will throw an Error when invoked. | |
5830 | * | |
5831 | * If `localStorage.traceDeprecation = true` is set, then deprecated functions | |
5832 | * will invoke `console.trace()` instead of `console.error()`. | |
5833 | * | |
5834 | * @param {Function} fn - the function to deprecate | |
5835 | * @param {String} msg - the string to print to the console when `fn` is invoked | |
5836 | * @returns {Function} a new "deprecated" version of `fn` | |
5837 | * @api public | |
5838 | */ | |
5839 | ||
5840 | function deprecate (fn, msg) { | |
5841 | if (config('noDeprecation')) { | |
5842 | return fn; | |
5843 | } | |
5844 | ||
5845 | var warned = false; | |
5846 | function deprecated() { | |
5847 | if (!warned) { | |
5848 | if (config('throwDeprecation')) { | |
5849 | throw new Error(msg); | |
5850 | } else if (config('traceDeprecation')) { | |
5851 | console.trace(msg); | |
5852 | } else { | |
5853 | console.warn(msg); | |
5854 | } | |
5855 | warned = true; | |
5856 | } | |
5857 | return fn.apply(this, arguments); | |
5858 | } | |
5859 | ||
5860 | return deprecated; | |
5861 | } | |
5862 | ||
5863 | /** | |
5864 | * Checks `localStorage` for boolean values for the given `name`. | |
5865 | * | |
5866 | * @param {String} name | |
5867 | * @returns {Boolean} | |
5868 | * @api private | |
5869 | */ | |
5870 | ||
5871 | function config (name) { | |
5872 | // accessing global.localStorage can trigger a DOMException in sandboxed iframes | |
5873 | try { | |
5874 | if (!global.localStorage) return false; | |
5875 | } catch (_) { | |
5876 | return false; | |
5877 | } | |
5878 | var val = global.localStorage[name]; | |
5879 | if (null == val) return false; | |
5880 | return String(val).toLowerCase() === 'true'; | |
5881 | } | |
5882 | ||
5883 | }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | |
5884 | },{}],30:[function(require,module,exports){ | |
5885 | arguments[4][8][0].apply(exports,arguments) | |
5886 | },{"dup":8}],31:[function(require,module,exports){ | |
5887 | module.exports = function isBuffer(arg) { | |
5888 | return arg && typeof arg === 'object' | |
5889 | && typeof arg.copy === 'function' | |
5890 | && typeof arg.fill === 'function' | |
5891 | && typeof arg.readUInt8 === 'function'; | |
5892 | } | |
5893 | },{}],32:[function(require,module,exports){ | |
5894 | (function (process,global){ | |
5895 | // Copyright Joyent, Inc. and other Node contributors. | |
5896 | // | |
5897 | // Permission is hereby granted, free of charge, to any person obtaining a | |
5898 | // copy of this software and associated documentation files (the | |
5899 | // "Software"), to deal in the Software without restriction, including | |
5900 | // without limitation the rights to use, copy, modify, merge, publish, | |
5901 | // distribute, sublicense, and/or sell copies of the Software, and to permit | |
5902 | // persons to whom the Software is furnished to do so, subject to the | |
5903 | // following conditions: | |
5904 | // | |
5905 | // The above copyright notice and this permission notice shall be included | |
5906 | // in all copies or substantial portions of the Software. | |
5907 | // | |
5908 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | |
5909 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | |
5910 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | |
5911 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | |
5912 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | |
5913 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | |
5914 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | |
5915 | ||
5916 | var formatRegExp = /%[sdj%]/g; | |
5917 | exports.format = function(f) { | |
5918 | if (!isString(f)) { | |
5919 | var objects = []; | |
5920 | for (var i = 0; i < arguments.length; i++) { | |
5921 | objects.push(inspect(arguments[i])); | |
5922 | } | |
5923 | return objects.join(' '); | |
5924 | } | |
5925 | ||
5926 | var i = 1; | |
5927 | var args = arguments; | |
5928 | var len = args.length; | |
5929 | var str = String(f).replace(formatRegExp, function(x) { | |
5930 | if (x === '%%') return '%'; | |
5931 | if (i >= len) return x; | |
5932 | switch (x) { | |
5933 | case '%s': return String(args[i++]); | |
5934 | case '%d': return Number(args[i++]); | |
5935 | case '%j': | |
5936 | try { | |
5937 | return JSON.stringify(args[i++]); | |
5938 | } catch (_) { | |
5939 | return '[Circular]'; | |
5940 | } | |
5941 | default: | |
5942 | return x; | |
5943 | } | |
5944 | }); | |
5945 | for (var x = args[i]; i < len; x = args[++i]) { | |
5946 | if (isNull(x) || !isObject(x)) { | |
5947 | str += ' ' + x; | |
5948 | } else { | |
5949 | str += ' ' + inspect(x); | |
5950 | } | |
5951 | } | |
5952 | return str; | |
5953 | }; | |
5954 | ||
5955 | ||
5956 | // Mark that a method should not be used. | |
5957 | // Returns a modified function which warns once by default. | |
5958 | // If --no-deprecation is set, then it is a no-op. | |
5959 | exports.deprecate = function(fn, msg) { | |
5960 | // Allow for deprecating things in the process of starting up. | |
5961 | if (isUndefined(global.process)) { | |
5962 | return function() { | |
5963 | return exports.deprecate(fn, msg).apply(this, arguments); | |
5964 | }; | |
5965 | } | |
5966 | ||
5967 | if (process.noDeprecation === true) { | |
5968 | return fn; | |
5969 | } | |
5970 | ||
5971 | var warned = false; | |
5972 | function deprecated() { | |
5973 | if (!warned) { | |
5974 | if (process.throwDeprecation) { | |
5975 | throw new Error(msg); | |
5976 | } else if (process.traceDeprecation) { | |
5977 | console.trace(msg); | |
5978 | } else { | |
5979 | console.error(msg); | |
5980 | } | |
5981 | warned = true; | |
5982 | } | |
5983 | return fn.apply(this, arguments); | |
5984 | } | |
5985 | ||
5986 | return deprecated; | |
5987 | }; | |
5988 | ||
5989 | ||
5990 | var debugs = {}; | |
5991 | var debugEnviron; | |
5992 | exports.debuglog = function(set) { | |
5993 | if (isUndefined(debugEnviron)) | |
5994 | debugEnviron = process.env.NODE_DEBUG || ''; | |
5995 | set = set.toUpperCase(); | |
5996 | if (!debugs[set]) { | |
5997 | if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { | |
5998 | var pid = process.pid; | |
5999 | debugs[set] = function() { | |
6000 | var msg = exports.format.apply(exports, arguments); | |
6001 | console.error('%s %d: %s', set, pid, msg); | |
6002 | }; | |
6003 | } else { | |
6004 | debugs[set] = function() {}; | |
6005 | } | |
6006 | } | |
6007 | return debugs[set]; | |
6008 | }; | |
6009 | ||
6010 | ||
6011 | /** | |
6012 | * Echos the value of a value. Trys to print the value out | |
6013 | * in the best way possible given the different types. | |
6014 | * | |
6015 | * @param {Object} obj The object to print out. | |
6016 | * @param {Object} opts Optional options object that alters the output. | |
6017 | */ | |
6018 | /* legacy: obj, showHidden, depth, colors*/ | |
6019 | function inspect(obj, opts) { | |
6020 | // default options | |
6021 | var ctx = { | |
6022 | seen: [], | |
6023 | stylize: stylizeNoColor | |
6024 | }; | |
6025 | // legacy... | |
6026 | if (arguments.length >= 3) ctx.depth = arguments[2]; | |
6027 | if (arguments.length >= 4) ctx.colors = arguments[3]; | |
6028 | if (isBoolean(opts)) { | |
6029 | // legacy... | |
6030 | ctx.showHidden = opts; | |
6031 | } else if (opts) { | |
6032 | // got an "options" object | |
6033 | exports._extend(ctx, opts); | |
6034 | } | |
6035 | // set default options | |
6036 | if (isUndefined(ctx.showHidden)) ctx.showHidden = false; | |
6037 | if (isUndefined(ctx.depth)) ctx.depth = 2; | |
6038 | if (isUndefined(ctx.colors)) ctx.colors = false; | |
6039 | if (isUndefined(ctx.customInspect)) ctx.customInspect = true; | |
6040 | if (ctx.colors) ctx.stylize = stylizeWithColor; | |
6041 | return formatValue(ctx, obj, ctx.depth); | |
6042 | } | |
6043 | exports.inspect = inspect; | |
6044 | ||
6045 | ||
6046 | // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics | |
6047 | inspect.colors = { | |
6048 | 'bold' : [1, 22], | |
6049 | 'italic' : [3, 23], | |
6050 | 'underline' : [4, 24], | |
6051 | 'inverse' : [7, 27], | |
6052 | 'white' : [37, 39], | |
6053 | 'grey' : [90, 39], | |
6054 | 'black' : [30, 39], | |
6055 | 'blue' : [34, 39], | |
6056 | 'cyan' : [36, 39], | |
6057 | 'green' : [32, 39], | |
6058 | 'magenta' : [35, 39], | |
6059 | 'red' : [31, 39], | |
6060 | 'yellow' : [33, 39] | |
6061 | }; | |
6062 | ||
6063 | // Don't use 'blue' not visible on cmd.exe | |
6064 | inspect.styles = { | |
6065 | 'special': 'cyan', | |
6066 | 'number': 'yellow', | |
6067 | 'boolean': 'yellow', | |
6068 | 'undefined': 'grey', | |
6069 | 'null': 'bold', | |
6070 | 'string': 'green', | |
6071 | 'date': 'magenta', | |
6072 | // "name": intentionally not styling | |
6073 | 'regexp': 'red' | |
6074 | }; | |
6075 | ||
6076 | ||
6077 | function stylizeWithColor(str, styleType) { | |
6078 | var style = inspect.styles[styleType]; | |
6079 | ||
6080 | if (style) { | |
6081 | return '\u001b[' + inspect.colors[style][0] + 'm' + str + | |
6082 | '\u001b[' + inspect.colors[style][1] + 'm'; | |
6083 | } else { | |
6084 | return str; | |
6085 | } | |
6086 | } | |
6087 | ||
6088 | ||
6089 | function stylizeNoColor(str, styleType) { | |
6090 | return str; | |
6091 | } | |
6092 | ||
6093 | ||
6094 | function arrayToHash(array) { | |
6095 | var hash = {}; | |
6096 | ||
6097 | array.forEach(function(val, idx) { | |
6098 | hash[val] = true; | |
6099 | }); | |
6100 | ||
6101 | return hash; | |
6102 | } | |
6103 | ||
6104 | ||
6105 | function formatValue(ctx, value, recurseTimes) { | |
6106 | // Provide a hook for user-specified inspect functions. | |
6107 | // Check that value is an object with an inspect function on it | |
6108 | if (ctx.customInspect && | |
6109 | value && | |
6110 | isFunction(value.inspect) && | |
6111 | // Filter out the util module, it's inspect function is special | |
6112 | value.inspect !== exports.inspect && | |
6113 | // Also filter out any prototype objects using the circular check. | |
6114 | !(value.constructor && value.constructor.prototype === value)) { | |
6115 | var ret = value.inspect(recurseTimes, ctx); | |
6116 | if (!isString(ret)) { | |
6117 | ret = formatValue(ctx, ret, recurseTimes); | |
6118 | } | |
6119 | return ret; | |
6120 | } | |
6121 | ||
6122 | // Primitive types cannot have properties | |
6123 | var primitive = formatPrimitive(ctx, value); | |
6124 | if (primitive) { | |
6125 | return primitive; | |
6126 | } | |
6127 | ||
6128 | // Look up the keys of the object. | |
6129 | var keys = Object.keys(value); | |
6130 | var visibleKeys = arrayToHash(keys); | |
6131 | ||
6132 | if (ctx.showHidden) { | |
6133 | keys = Object.getOwnPropertyNames(value); | |
6134 | } | |
6135 | ||
6136 | // IE doesn't make error fields non-enumerable | |
6137 | // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx | |
6138 | if (isError(value) | |
6139 | && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { | |
6140 | return formatError(value); | |
6141 | } | |
6142 | ||
6143 | // Some type of object without properties can be shortcutted. | |
6144 | if (keys.length === 0) { | |
6145 | if (isFunction(value)) { | |
6146 | var name = value.name ? ': ' + value.name : ''; | |
6147 | return ctx.stylize('[Function' + name + ']', 'special'); | |
6148 | } | |
6149 | if (isRegExp(value)) { | |
6150 | return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); | |
6151 | } | |
6152 | if (isDate(value)) { | |
6153 | return ctx.stylize(Date.prototype.toString.call(value), 'date'); | |
6154 | } | |
6155 | if (isError(value)) { | |
6156 | return formatError(value); | |
6157 | } | |
6158 | } | |
6159 | ||
6160 | var base = '', array = false, braces = ['{', '}']; | |
6161 | ||
6162 | // Make Array say that they are Array | |
6163 | if (isArray(value)) { | |
6164 | array = true; | |
6165 | braces = ['[', ']']; | |
6166 | } | |
6167 | ||
6168 | // Make functions say that they are functions | |
6169 | if (isFunction(value)) { | |
6170 | var n = value.name ? ': ' + value.name : ''; | |
6171 | base = ' [Function' + n + ']'; | |
6172 | } | |
6173 | ||
6174 | // Make RegExps say that they are RegExps | |
6175 | if (isRegExp(value)) { | |
6176 | base = ' ' + RegExp.prototype.toString.call(value); | |
6177 | } | |
6178 | ||
6179 | // Make dates with properties first say the date | |
6180 | if (isDate(value)) { | |
6181 | base = ' ' + Date.prototype.toUTCString.call(value); | |
6182 | } | |
6183 | ||
6184 | // Make error with message first say the error | |
6185 | if (isError(value)) { | |
6186 | base = ' ' + formatError(value); | |
6187 | } | |
6188 | ||
6189 | if (keys.length === 0 && (!array || value.length == 0)) { | |
6190 | return braces[0] + base + braces[1]; | |
6191 | } | |
6192 | ||
6193 | if (recurseTimes < 0) { | |
6194 | if (isRegExp(value)) { | |
6195 | return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); | |
6196 | } else { | |
6197 | return ctx.stylize('[Object]', 'special'); | |
6198 | } | |
6199 | } | |
6200 | ||
6201 | ctx.seen.push(value); | |
6202 | ||
6203 | var output; | |
6204 | if (array) { | |
6205 | output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); | |
6206 | } else { | |
6207 | output = keys.map(function(key) { | |
6208 | return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); | |
6209 | }); | |
6210 | } | |
6211 | ||
6212 | ctx.seen.pop(); | |
6213 | ||
6214 | return reduceToSingleString(output, base, braces); | |
6215 | } | |
6216 | ||
6217 | ||
6218 | function formatPrimitive(ctx, value) { | |
6219 | if (isUndefined(value)) | |
6220 | return ctx.stylize('undefined', 'undefined'); | |
6221 | if (isString(value)) { | |
6222 | var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') | |
6223 | .replace(/'/g, "\\'") | |
6224 | .replace(/\\"/g, '"') + '\''; | |
6225 | return ctx.stylize(simple, 'string'); | |
6226 | } | |
6227 | if (isNumber(value)) | |
6228 | return ctx.stylize('' + value, 'number'); | |
6229 | if (isBoolean(value)) | |
6230 | return ctx.stylize('' + value, 'boolean'); | |
6231 | // For some reason typeof null is "object", so special case here. | |
6232 | if (isNull(value)) | |
6233 | return ctx.stylize('null', 'null'); | |
6234 | } | |
6235 | ||
6236 | ||
6237 | function formatError(value) { | |
6238 | return '[' + Error.prototype.toString.call(value) + ']'; | |
6239 | } | |
6240 | ||
6241 | ||
6242 | function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { | |
6243 | var output = []; | |
6244 | for (var i = 0, l = value.length; i < l; ++i) { | |
6245 | if (hasOwnProperty(value, String(i))) { | |
6246 | output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, | |
6247 | String(i), true)); | |
6248 | } else { | |
6249 | output.push(''); | |
6250 | } | |
6251 | } | |
6252 | keys.forEach(function(key) { | |
6253 | if (!key.match(/^\d+$/)) { | |
6254 | output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, | |
6255 | key, true)); | |
6256 | } | |
6257 | }); | |
6258 | return output; | |
6259 | } | |
6260 | ||
6261 | ||
6262 | function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { | |
6263 | var name, str, desc; | |
6264 | desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; | |
6265 | if (desc.get) { | |
6266 | if (desc.set) { | |
6267 | str = ctx.stylize('[Getter/Setter]', 'special'); | |
6268 | } else { | |
6269 | str = ctx.stylize('[Getter]', 'special'); | |
6270 | } | |
6271 | } else { | |
6272 | if (desc.set) { | |
6273 | str = ctx.stylize('[Setter]', 'special'); | |
6274 | } | |
6275 | } | |
6276 | if (!hasOwnProperty(visibleKeys, key)) { | |
6277 | name = '[' + key + ']'; | |
6278 | } | |
6279 | if (!str) { | |
6280 | if (ctx.seen.indexOf(desc.value) < 0) { | |
6281 | if (isNull(recurseTimes)) { | |
6282 | str = formatValue(ctx, desc.value, null); | |
6283 | } else { | |
6284 | str = formatValue(ctx, desc.value, recurseTimes - 1); | |
6285 | } | |
6286 | if (str.indexOf('\n') > -1) { | |
6287 | if (array) { | |
6288 | str = str.split('\n').map(function(line) { | |
6289 | return ' ' + line; | |
6290 | }).join('\n').substr(2); | |
6291 | } else { | |
6292 | str = '\n' + str.split('\n').map(function(line) { | |
6293 | return ' ' + line; | |
6294 | }).join('\n'); | |
6295 | } | |
6296 | } | |
6297 | } else { | |
6298 | str = ctx.stylize('[Circular]', 'special'); | |
6299 | } | |
6300 | } | |
6301 | if (isUndefined(name)) { | |
6302 | if (array && key.match(/^\d+$/)) { | |
6303 | return str; | |
6304 | } | |
6305 | name = JSON.stringify('' + key); | |
6306 | if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { | |
6307 | name = name.substr(1, name.length - 2); | |
6308 | name = ctx.stylize(name, 'name'); | |
6309 | } else { | |
6310 | name = name.replace(/'/g, "\\'") | |
6311 | .replace(/\\"/g, '"') | |
6312 | .replace(/(^"|"$)/g, "'"); | |
6313 | name = ctx.stylize(name, 'string'); | |
6314 | } | |
6315 | } | |
6316 | ||
6317 | return name + ': ' + str; | |
6318 | } | |
6319 | ||
6320 | ||
6321 | function reduceToSingleString(output, base, braces) { | |
6322 | var numLinesEst = 0; | |
6323 | var length = output.reduce(function(prev, cur) { | |
6324 | numLinesEst++; | |
6325 | if (cur.indexOf('\n') >= 0) numLinesEst++; | |
6326 | return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; | |
6327 | }, 0); | |
6328 | ||
6329 | if (length > 60) { | |
6330 | return braces[0] + | |
6331 | (base === '' ? '' : base + '\n ') + | |
6332 | ' ' + | |
6333 | output.join(',\n ') + | |
6334 | ' ' + | |
6335 | braces[1]; | |
6336 | } | |
6337 | ||
6338 | return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; | |
6339 | } | |
6340 | ||
6341 | ||
6342 | // NOTE: These type checking functions intentionally don't use `instanceof` | |
6343 | // because it is fragile and can be easily faked with `Object.create()`. | |
6344 | function isArray(ar) { | |
6345 | return Array.isArray(ar); | |
6346 | } | |
6347 | exports.isArray = isArray; | |
6348 | ||
6349 | function isBoolean(arg) { | |
6350 | return typeof arg === 'boolean'; | |
6351 | } | |
6352 | exports.isBoolean = isBoolean; | |
6353 | ||
6354 | function isNull(arg) { | |
6355 | return arg === null; | |
6356 | } | |
6357 | exports.isNull = isNull; | |
6358 | ||
6359 | function isNullOrUndefined(arg) { | |
6360 | return arg == null; | |
6361 | } | |
6362 | exports.isNullOrUndefined = isNullOrUndefined; | |
6363 | ||
6364 | function isNumber(arg) { | |
6365 | return typeof arg === 'number'; | |
6366 | } | |
6367 | exports.isNumber = isNumber; | |
6368 | ||
6369 | function isString(arg) { | |
6370 | return typeof arg === 'string'; | |
6371 | } | |
6372 | exports.isString = isString; | |
6373 | ||
6374 | function isSymbol(arg) { | |
6375 | return typeof arg === 'symbol'; | |
6376 | } | |
6377 | exports.isSymbol = isSymbol; | |
6378 | ||
6379 | function isUndefined(arg) { | |
6380 | return arg === void 0; | |
6381 | } | |
6382 | exports.isUndefined = isUndefined; | |
6383 | ||
6384 | function isRegExp(re) { | |
6385 | return isObject(re) && objectToString(re) === '[object RegExp]'; | |
6386 | } | |
6387 | exports.isRegExp = isRegExp; | |
6388 | ||
6389 | function isObject(arg) { | |
6390 | return typeof arg === 'object' && arg !== null; | |
6391 | } | |
6392 | exports.isObject = isObject; | |
6393 | ||
6394 | function isDate(d) { | |
6395 | return isObject(d) && objectToString(d) === '[object Date]'; | |
6396 | } | |
6397 | exports.isDate = isDate; | |
6398 | ||
6399 | function isError(e) { | |
6400 | return isObject(e) && | |
6401 | (objectToString(e) === '[object Error]' || e instanceof Error); | |
6402 | } | |
6403 | exports.isError = isError; | |
6404 | ||
6405 | function isFunction(arg) { | |
6406 | return typeof arg === 'function'; | |
6407 | } | |
6408 | exports.isFunction = isFunction; | |
6409 | ||
6410 | function isPrimitive(arg) { | |
6411 | return arg === null || | |
6412 | typeof arg === 'boolean' || | |
6413 | typeof arg === 'number' || | |
6414 | typeof arg === 'string' || | |
6415 | typeof arg === 'symbol' || // ES6 symbol | |
6416 | typeof arg === 'undefined'; | |
6417 | } | |
6418 | exports.isPrimitive = isPrimitive; | |
6419 | ||
6420 | exports.isBuffer = require('./support/isBuffer'); | |
6421 | ||
6422 | function objectToString(o) { | |
6423 | return Object.prototype.toString.call(o); | |
6424 | } | |
6425 | ||
6426 | ||
6427 | function pad(n) { | |
6428 | return n < 10 ? '0' + n.toString(10) : n.toString(10); | |
6429 | } | |
6430 | ||
6431 | ||
6432 | var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', | |
6433 | 'Oct', 'Nov', 'Dec']; | |
6434 | ||
6435 | // 26 Feb 16:19:34 | |
6436 | function timestamp() { | |
6437 | var d = new Date(); | |
6438 | var time = [pad(d.getHours()), | |
6439 | pad(d.getMinutes()), | |
6440 | pad(d.getSeconds())].join(':'); | |
6441 | return [d.getDate(), months[d.getMonth()], time].join(' '); | |
6442 | } | |
6443 | ||
6444 | ||
6445 | // log is just a thin wrapper to console.log that prepends a timestamp | |
6446 | exports.log = function() { | |
6447 | console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); | |
6448 | }; | |
6449 | ||
6450 | ||
6451 | /** | |
6452 | * Inherit the prototype methods from one constructor into another. | |
6453 | * | |
6454 | * The Function.prototype.inherits from lang.js rewritten as a standalone | |
6455 | * function (not on Function.prototype). NOTE: If this file is to be loaded | |
6456 | * during bootstrapping this function needs to be rewritten using some native | |
6457 | * functions as prototype setup using normal JavaScript does not work as | |
6458 | * expected during bootstrapping (see mirror.js in r114903). | |
6459 | * | |
6460 | * @param {function} ctor Constructor function which needs to inherit the | |
6461 | * prototype. | |
6462 | * @param {function} superCtor Constructor function to inherit prototype from. | |
6463 | */ | |
6464 | exports.inherits = require('inherits'); | |
6465 | ||
6466 | exports._extend = function(origin, add) { | |
6467 | // Don't do anything if add isn't an object | |
6468 | if (!add || !isObject(add)) return origin; | |
6469 | ||
6470 | var keys = Object.keys(add); | |
6471 | var i = keys.length; | |
6472 | while (i--) { | |
6473 | origin[keys[i]] = add[keys[i]]; | |
6474 | } | |
6475 | return origin; | |
6476 | }; | |
6477 | ||
6478 | function hasOwnProperty(obj, prop) { | |
6479 | return Object.prototype.hasOwnProperty.call(obj, prop); | |
6480 | } | |
6481 | ||
6482 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | |
6483 | },{"./support/isBuffer":31,"_process":12,"inherits":30}],33:[function(require,module,exports){ | |
6484 | module.exports = { | |
6485 | base58: require('bs58'), | |
6486 | bitcoin: require('bitcoinjs-lib'), | |
6487 | ecurve: require('ecurve'), | |
6488 | BigInteger: require('bigi') | |
6489 | } | |
6490 | ||
6491 | },{"bigi":37,"bitcoinjs-lib":50,"bs58":79,"ecurve":89}],34:[function(require,module,exports){ | |
6492 | // base-x encoding | |
6493 | // Forked from https://github.com/cryptocoinjs/bs58 | |
6494 | // Originally written by Mike Hearn for BitcoinJ | |
6495 | // Copyright (c) 2011 Google Inc | |
6496 | // Ported to JavaScript by Stefan Thomas | |
6497 | // Merged Buffer refactorings from base58-native by Stephen Pair | |
6498 | // Copyright (c) 2013 BitPay Inc | |
6499 | ||
6500 | var Buffer = require('safe-buffer').Buffer | |
6501 | ||
6502 | module.exports = function base (ALPHABET) { | |
6503 | var ALPHABET_MAP = {} | |
6504 | var BASE = ALPHABET.length | |
6505 | var LEADER = ALPHABET.charAt(0) | |
6506 | ||
6507 | // pre-compute lookup table | |
6508 | for (var z = 0; z < ALPHABET.length; z++) { | |
6509 | var x = ALPHABET.charAt(z) | |
6510 | ||
6511 | if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') | |
6512 | ALPHABET_MAP[x] = z | |
6513 | } | |
6514 | ||
6515 | function encode (source) { | |
6516 | if (source.length === 0) return '' | |
6517 | ||
6518 | var digits = [0] | |
6519 | for (var i = 0; i < source.length; ++i) { | |
6520 | for (var j = 0, carry = source[i]; j < digits.length; ++j) { | |
6521 | carry += digits[j] << 8 | |
6522 | digits[j] = carry % BASE | |
6523 | carry = (carry / BASE) | 0 | |
6524 | } | |
6525 | ||
6526 | while (carry > 0) { | |
6527 | digits.push(carry % BASE) | |
6528 | carry = (carry / BASE) | 0 | |
6529 | } | |
6530 | } | |
6531 | ||
6532 | var string = '' | |
6533 | ||
6534 | // deal with leading zeros | |
6535 | for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += ALPHABET[0] | |
6536 | // convert digits to a string | |
6537 | for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]] | |
6538 | ||
6539 | return string | |
6540 | } | |
6541 | ||
6542 | function decodeUnsafe (string) { | |
6543 | if (string.length === 0) return Buffer.allocUnsafe(0) | |
6544 | ||
6545 | var bytes = [0] | |
6546 | for (var i = 0; i < string.length; i++) { | |
6547 | var value = ALPHABET_MAP[string[i]] | |
6548 | if (value === undefined) return | |
6549 | ||
6550 | for (var j = 0, carry = value; j < bytes.length; ++j) { | |
6551 | carry += bytes[j] * BASE | |
6552 | bytes[j] = carry & 0xff | |
6553 | carry >>= 8 | |
6554 | } | |
6555 | ||
6556 | while (carry > 0) { | |
6557 | bytes.push(carry & 0xff) | |
6558 | carry >>= 8 | |
6559 | } | |
6560 | } | |
6561 | ||
6562 | // deal with leading zeros | |
6563 | for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) { | |
6564 | bytes.push(0) | |
6565 | } | |
6566 | ||
6567 | return Buffer.from(bytes.reverse()) | |
6568 | } | |
6569 | ||
6570 | function decode (string) { | |
6571 | var buffer = decodeUnsafe(string) | |
6572 | if (buffer) return buffer | |
6573 | ||
6574 | throw new Error('Non-base' + BASE + ' character') | |
6575 | } | |
6576 | ||
6577 | return { | |
6578 | encode: encode, | |
6579 | decodeUnsafe: decodeUnsafe, | |
6580 | decode: decode | |
6581 | } | |
6582 | } | |
6583 | ||
6584 | },{"safe-buffer":98}],35:[function(require,module,exports){ | |
6585 | // (public) Constructor | |
6586 | function BigInteger(a, b, c) { | |
6587 | if (!(this instanceof BigInteger)) | |
6588 | return new BigInteger(a, b, c) | |
6589 | ||
6590 | if (a != null) { | |
6591 | if ("number" == typeof a) this.fromNumber(a, b, c) | |
6592 | else if (b == null && "string" != typeof a) this.fromString(a, 256) | |
6593 | else this.fromString(a, b) | |
6594 | } | |
6595 | } | |
6596 | ||
6597 | var proto = BigInteger.prototype | |
6598 | ||
6599 | // duck-typed isBigInteger | |
6600 | proto.__bigi = require('../package.json').version | |
6601 | BigInteger.isBigInteger = function (obj, check_ver) { | |
6602 | return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi) | |
6603 | } | |
6604 | ||
6605 | // Bits per digit | |
6606 | var dbits | |
6607 | ||
6608 | // am: Compute w_j += (x*this_i), propagate carries, | |
6609 | // c is initial carry, returns final carry. | |
6610 | // c < 3*dvalue, x < 2*dvalue, this_i < dvalue | |
6611 | // We need to select the fastest one that works in this environment. | |
6612 | ||
6613 | // am1: use a single mult and divide to get the high bits, | |
6614 | // max digit bits should be 26 because | |
6615 | // max internal value = 2*dvalue^2-2*dvalue (< 2^53) | |
6616 | function am1(i, x, w, j, c, n) { | |
6617 | while (--n >= 0) { | |
6618 | var v = x * this[i++] + w[j] + c | |
6619 | c = Math.floor(v / 0x4000000) | |
6620 | w[j++] = v & 0x3ffffff | |
6621 | } | |
6622 | return c | |
6623 | } | |
6624 | // am2 avoids a big mult-and-extract completely. | |
6625 | // Max digit bits should be <= 30 because we do bitwise ops | |
6626 | // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) | |
6627 | function am2(i, x, w, j, c, n) { | |
6628 | var xl = x & 0x7fff, | |
6629 | xh = x >> 15 | |
6630 | while (--n >= 0) { | |
6631 | var l = this[i] & 0x7fff | |
6632 | var h = this[i++] >> 15 | |
6633 | var m = xh * l + h * xl | |
6634 | l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff) | |
6635 | c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30) | |
6636 | w[j++] = l & 0x3fffffff | |
6637 | } | |
6638 | return c | |
6639 | } | |
6640 | // Alternately, set max digit bits to 28 since some | |
6641 | // browsers slow down when dealing with 32-bit numbers. | |
6642 | function am3(i, x, w, j, c, n) { | |
6643 | var xl = x & 0x3fff, | |
6644 | xh = x >> 14 | |
6645 | while (--n >= 0) { | |
6646 | var l = this[i] & 0x3fff | |
6647 | var h = this[i++] >> 14 | |
6648 | var m = xh * l + h * xl | |
6649 | l = xl * l + ((m & 0x3fff) << 14) + w[j] + c | |
6650 | c = (l >> 28) + (m >> 14) + xh * h | |
6651 | w[j++] = l & 0xfffffff | |
6652 | } | |
6653 | return c | |
6654 | } | |
6655 | ||
6656 | // wtf? | |
6657 | BigInteger.prototype.am = am1 | |
6658 | dbits = 26 | |
6659 | ||
6660 | BigInteger.prototype.DB = dbits | |
6661 | BigInteger.prototype.DM = ((1 << dbits) - 1) | |
6662 | var DV = BigInteger.prototype.DV = (1 << dbits) | |
6663 | ||
6664 | var BI_FP = 52 | |
6665 | BigInteger.prototype.FV = Math.pow(2, BI_FP) | |
6666 | BigInteger.prototype.F1 = BI_FP - dbits | |
6667 | BigInteger.prototype.F2 = 2 * dbits - BI_FP | |
6668 | ||
6669 | // Digit conversions | |
6670 | var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz" | |
6671 | var BI_RC = new Array() | |
6672 | var rr, vv | |
6673 | rr = "0".charCodeAt(0) | |
6674 | for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv | |
6675 | rr = "a".charCodeAt(0) | |
6676 | for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv | |
6677 | rr = "A".charCodeAt(0) | |
6678 | for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv | |
6679 | ||
6680 | function int2char(n) { | |
6681 | return BI_RM.charAt(n) | |
6682 | } | |
6683 | ||
6684 | function intAt(s, i) { | |
6685 | var c = BI_RC[s.charCodeAt(i)] | |
6686 | return (c == null) ? -1 : c | |
6687 | } | |
6688 | ||
6689 | // (protected) copy this to r | |
6690 | function bnpCopyTo(r) { | |
6691 | for (var i = this.t - 1; i >= 0; --i) r[i] = this[i] | |
6692 | r.t = this.t | |
6693 | r.s = this.s | |
6694 | } | |
6695 | ||
6696 | // (protected) set from integer value x, -DV <= x < DV | |
6697 | function bnpFromInt(x) { | |
6698 | this.t = 1 | |
6699 | this.s = (x < 0) ? -1 : 0 | |
6700 | if (x > 0) this[0] = x | |
6701 | else if (x < -1) this[0] = x + DV | |
6702 | else this.t = 0 | |
6703 | } | |
6704 | ||
6705 | // return bigint initialized to value | |
6706 | function nbv(i) { | |
6707 | var r = new BigInteger() | |
6708 | r.fromInt(i) | |
6709 | return r | |
6710 | } | |
6711 | ||
6712 | // (protected) set from string and radix | |
6713 | function bnpFromString(s, b) { | |
6714 | var self = this | |
6715 | ||
6716 | var k | |
6717 | if (b == 16) k = 4 | |
6718 | else if (b == 8) k = 3 | |
6719 | else if (b == 256) k = 8; // byte array | |
6720 | else if (b == 2) k = 1 | |
6721 | else if (b == 32) k = 5 | |
6722 | else if (b == 4) k = 2 | |
6723 | else { | |
6724 | self.fromRadix(s, b) | |
6725 | return | |
6726 | } | |
6727 | self.t = 0 | |
6728 | self.s = 0 | |
6729 | var i = s.length, | |
6730 | mi = false, | |
6731 | sh = 0 | |
6732 | while (--i >= 0) { | |
6733 | var x = (k == 8) ? s[i] & 0xff : intAt(s, i) | |
6734 | if (x < 0) { | |
6735 | if (s.charAt(i) == "-") mi = true | |
6736 | continue | |
6737 | } | |
6738 | mi = false | |
6739 | if (sh == 0) | |
6740 | self[self.t++] = x | |
6741 | else if (sh + k > self.DB) { | |
6742 | self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh | |
6743 | self[self.t++] = (x >> (self.DB - sh)) | |
6744 | } else | |
6745 | self[self.t - 1] |= x << sh | |
6746 | sh += k | |
6747 | if (sh >= self.DB) sh -= self.DB | |
6748 | } | |
6749 | if (k == 8 && (s[0] & 0x80) != 0) { | |
6750 | self.s = -1 | |
6751 | if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh | |
6752 | } | |
6753 | self.clamp() | |
6754 | if (mi) BigInteger.ZERO.subTo(self, self) | |
6755 | } | |
6756 | ||
6757 | // (protected) clamp off excess high words | |
6758 | function bnpClamp() { | |
6759 | var c = this.s & this.DM | |
6760 | while (this.t > 0 && this[this.t - 1] == c)--this.t | |
6761 | } | |
6762 | ||
6763 | // (public) return string representation in given radix | |
6764 | function bnToString(b) { | |
6765 | var self = this | |
6766 | if (self.s < 0) return "-" + self.negate() | |
6767 | .toString(b) | |
6768 | var k | |
6769 | if (b == 16) k = 4 | |
6770 | else if (b == 8) k = 3 | |
6771 | else if (b == 2) k = 1 | |
6772 | else if (b == 32) k = 5 | |
6773 | else if (b == 4) k = 2 | |
6774 | else return self.toRadix(b) | |
6775 | var km = (1 << k) - 1, | |
6776 | d, m = false, | |
6777 | r = "", | |
6778 | i = self.t | |
6779 | var p = self.DB - (i * self.DB) % k | |
6780 | if (i-- > 0) { | |
6781 | if (p < self.DB && (d = self[i] >> p) > 0) { | |
6782 | m = true | |
6783 | r = int2char(d) | |
6784 | } | |
6785 | while (i >= 0) { | |
6786 | if (p < k) { | |
6787 | d = (self[i] & ((1 << p) - 1)) << (k - p) | |
6788 | d |= self[--i] >> (p += self.DB - k) | |
6789 | } else { | |
6790 | d = (self[i] >> (p -= k)) & km | |
6791 | if (p <= 0) { | |
6792 | p += self.DB | |
6793 | --i | |
6794 | } | |
6795 | } | |
6796 | if (d > 0) m = true | |
6797 | if (m) r += int2char(d) | |
6798 | } | |
6799 | } | |
6800 | return m ? r : "0" | |
6801 | } | |
6802 | ||
6803 | // (public) -this | |
6804 | function bnNegate() { | |
6805 | var r = new BigInteger() | |
6806 | BigInteger.ZERO.subTo(this, r) | |
6807 | return r | |
6808 | } | |
6809 | ||
6810 | // (public) |this| | |
6811 | function bnAbs() { | |
6812 | return (this.s < 0) ? this.negate() : this | |
6813 | } | |
6814 | ||
6815 | // (public) return + if this > a, - if this < a, 0 if equal | |
6816 | function bnCompareTo(a) { | |
6817 | var r = this.s - a.s | |
6818 | if (r != 0) return r | |
6819 | var i = this.t | |
6820 | r = i - a.t | |
6821 | if (r != 0) return (this.s < 0) ? -r : r | |
6822 | while (--i >= 0) | |
6823 | if ((r = this[i] - a[i]) != 0) return r | |
6824 | return 0 | |
6825 | } | |
6826 | ||
6827 | // returns bit length of the integer x | |
6828 | function nbits(x) { | |
6829 | var r = 1, | |
6830 | t | |
6831 | if ((t = x >>> 16) != 0) { | |
6832 | x = t | |
6833 | r += 16 | |
6834 | } | |
6835 | if ((t = x >> 8) != 0) { | |
6836 | x = t | |
6837 | r += 8 | |
6838 | } | |
6839 | if ((t = x >> 4) != 0) { | |
6840 | x = t | |
6841 | r += 4 | |
6842 | } | |
6843 | if ((t = x >> 2) != 0) { | |
6844 | x = t | |
6845 | r += 2 | |
6846 | } | |
6847 | if ((t = x >> 1) != 0) { | |
6848 | x = t | |
6849 | r += 1 | |
6850 | } | |
6851 | return r | |
6852 | } | |
6853 | ||
6854 | // (public) return the number of bits in "this" | |
6855 | function bnBitLength() { | |
6856 | if (this.t <= 0) return 0 | |
6857 | return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) | |
6858 | } | |
6859 | ||
6860 | // (public) return the number of bytes in "this" | |
6861 | function bnByteLength() { | |
6862 | return this.bitLength() >> 3 | |
6863 | } | |
6864 | ||
6865 | // (protected) r = this << n*DB | |
6866 | function bnpDLShiftTo(n, r) { | |
6867 | var i | |
6868 | for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i] | |
6869 | for (i = n - 1; i >= 0; --i) r[i] = 0 | |
6870 | r.t = this.t + n | |
6871 | r.s = this.s | |
6872 | } | |
6873 | ||
6874 | // (protected) r = this >> n*DB | |
6875 | function bnpDRShiftTo(n, r) { | |
6876 | for (var i = n; i < this.t; ++i) r[i - n] = this[i] | |
6877 | r.t = Math.max(this.t - n, 0) | |
6878 | r.s = this.s | |
6879 | } | |
6880 | ||
6881 | // (protected) r = this << n | |
6882 | function bnpLShiftTo(n, r) { | |
6883 | var self = this | |
6884 | var bs = n % self.DB | |
6885 | var cbs = self.DB - bs | |
6886 | var bm = (1 << cbs) - 1 | |
6887 | var ds = Math.floor(n / self.DB), | |
6888 | c = (self.s << bs) & self.DM, | |
6889 | i | |
6890 | for (i = self.t - 1; i >= 0; --i) { | |
6891 | r[i + ds + 1] = (self[i] >> cbs) | c | |
6892 | c = (self[i] & bm) << bs | |
6893 | } | |
6894 | for (i = ds - 1; i >= 0; --i) r[i] = 0 | |
6895 | r[ds] = c | |
6896 | r.t = self.t + ds + 1 | |
6897 | r.s = self.s | |
6898 | r.clamp() | |
6899 | } | |
6900 | ||
6901 | // (protected) r = this >> n | |
6902 | function bnpRShiftTo(n, r) { | |
6903 | var self = this | |
6904 | r.s = self.s | |
6905 | var ds = Math.floor(n / self.DB) | |
6906 | if (ds >= self.t) { | |
6907 | r.t = 0 | |
6908 | return | |
6909 | } | |
6910 | var bs = n % self.DB | |
6911 | var cbs = self.DB - bs | |
6912 | var bm = (1 << bs) - 1 | |
6913 | r[0] = self[ds] >> bs | |
6914 | for (var i = ds + 1; i < self.t; ++i) { | |
6915 | r[i - ds - 1] |= (self[i] & bm) << cbs | |
6916 | r[i - ds] = self[i] >> bs | |
6917 | } | |
6918 | if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs | |
6919 | r.t = self.t - ds | |
6920 | r.clamp() | |
6921 | } | |
6922 | ||
6923 | // (protected) r = this - a | |
6924 | function bnpSubTo(a, r) { | |
6925 | var self = this | |
6926 | var i = 0, | |
6927 | c = 0, | |
6928 | m = Math.min(a.t, self.t) | |
6929 | while (i < m) { | |
6930 | c += self[i] - a[i] | |
6931 | r[i++] = c & self.DM | |
6932 | c >>= self.DB | |
6933 | } | |
6934 | if (a.t < self.t) { | |
6935 | c -= a.s | |
6936 | while (i < self.t) { | |
6937 | c += self[i] | |
6938 | r[i++] = c & self.DM | |
6939 | c >>= self.DB | |
6940 | } | |
6941 | c += self.s | |
6942 | } else { | |
6943 | c += self.s | |
6944 | while (i < a.t) { | |
6945 | c -= a[i] | |
6946 | r[i++] = c & self.DM | |
6947 | c >>= self.DB | |
6948 | } | |
6949 | c -= a.s | |
6950 | } | |
6951 | r.s = (c < 0) ? -1 : 0 | |
6952 | if (c < -1) r[i++] = self.DV + c | |
6953 | else if (c > 0) r[i++] = c | |
6954 | r.t = i | |
6955 | r.clamp() | |
6956 | } | |
6957 | ||
6958 | // (protected) r = this * a, r != this,a (HAC 14.12) | |
6959 | // "this" should be the larger one if appropriate. | |
6960 | function bnpMultiplyTo(a, r) { | |
6961 | var x = this.abs(), | |
6962 | y = a.abs() | |
6963 | var i = x.t | |
6964 | r.t = i + y.t | |
6965 | while (--i >= 0) r[i] = 0 | |
6966 | for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t) | |
6967 | r.s = 0 | |
6968 | r.clamp() | |
6969 | if (this.s != a.s) BigInteger.ZERO.subTo(r, r) | |
6970 | } | |
6971 | ||
6972 | // (protected) r = this^2, r != this (HAC 14.16) | |
6973 | function bnpSquareTo(r) { | |
6974 | var x = this.abs() | |
6975 | var i = r.t = 2 * x.t | |
6976 | while (--i >= 0) r[i] = 0 | |
6977 | for (i = 0; i < x.t - 1; ++i) { | |
6978 | var c = x.am(i, x[i], r, 2 * i, 0, 1) | |
6979 | if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { | |
6980 | r[i + x.t] -= x.DV | |
6981 | r[i + x.t + 1] = 1 | |
6982 | } | |
6983 | } | |
6984 | if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1) | |
6985 | r.s = 0 | |
6986 | r.clamp() | |
6987 | } | |
6988 | ||
6989 | // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) | |
6990 | // r != q, this != m. q or r may be null. | |
6991 | function bnpDivRemTo(m, q, r) { | |
6992 | var self = this | |
6993 | var pm = m.abs() | |
6994 | if (pm.t <= 0) return | |
6995 | var pt = self.abs() | |
6996 | if (pt.t < pm.t) { | |
6997 | if (q != null) q.fromInt(0) | |
6998 | if (r != null) self.copyTo(r) | |
6999 | return | |
7000 | } | |
7001 | if (r == null) r = new BigInteger() | |
7002 | var y = new BigInteger(), | |
7003 | ts = self.s, | |
7004 | ms = m.s | |
7005 | var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus | |
7006 | if (nsh > 0) { | |
7007 | pm.lShiftTo(nsh, y) | |
7008 | pt.lShiftTo(nsh, r) | |
7009 | } else { | |
7010 | pm.copyTo(y) | |
7011 | pt.copyTo(r) | |
7012 | } | |
7013 | var ys = y.t | |
7014 | var y0 = y[ys - 1] | |
7015 | if (y0 == 0) return | |
7016 | var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0) | |
7017 | var d1 = self.FV / yt, | |
7018 | d2 = (1 << self.F1) / yt, | |
7019 | e = 1 << self.F2 | |
7020 | var i = r.t, | |
7021 | j = i - ys, | |
7022 | t = (q == null) ? new BigInteger() : q | |
7023 | y.dlShiftTo(j, t) | |
7024 | if (r.compareTo(t) >= 0) { | |
7025 | r[r.t++] = 1 | |
7026 | r.subTo(t, r) | |
7027 | } | |
7028 | BigInteger.ONE.dlShiftTo(ys, t) | |
7029 | t.subTo(y, y); // "negative" y so we can replace sub with am later | |
7030 | while (y.t < ys) y[y.t++] = 0 | |
7031 | while (--j >= 0) { | |
7032 | // Estimate quotient digit | |
7033 | var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2) | |
7034 | if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out | |
7035 | y.dlShiftTo(j, t) | |
7036 | r.subTo(t, r) | |
7037 | while (r[i] < --qd) r.subTo(t, r) | |
7038 | } | |
7039 | } | |
7040 | if (q != null) { | |
7041 | r.drShiftTo(ys, q) | |
7042 | if (ts != ms) BigInteger.ZERO.subTo(q, q) | |
7043 | } | |
7044 | r.t = ys | |
7045 | r.clamp() | |
7046 | if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder | |
7047 | if (ts < 0) BigInteger.ZERO.subTo(r, r) | |
7048 | } | |
7049 | ||
7050 | // (public) this mod a | |
7051 | function bnMod(a) { | |
7052 | var r = new BigInteger() | |
7053 | this.abs() | |
7054 | .divRemTo(a, null, r) | |
7055 | if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r) | |
7056 | return r | |
7057 | } | |
7058 | ||
7059 | // Modular reduction using "classic" algorithm | |
7060 | function Classic(m) { | |
7061 | this.m = m | |
7062 | } | |
7063 | ||
7064 | function cConvert(x) { | |
7065 | if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m) | |
7066 | else return x | |
7067 | } | |
7068 | ||
7069 | function cRevert(x) { | |
7070 | return x | |
7071 | } | |
7072 | ||
7073 | function cReduce(x) { | |
7074 | x.divRemTo(this.m, null, x) | |
7075 | } | |
7076 | ||
7077 | function cMulTo(x, y, r) { | |
7078 | x.multiplyTo(y, r) | |
7079 | this.reduce(r) | |
7080 | } | |
7081 | ||
7082 | function cSqrTo(x, r) { | |
7083 | x.squareTo(r) | |
7084 | this.reduce(r) | |
7085 | } | |
7086 | ||
7087 | Classic.prototype.convert = cConvert | |
7088 | Classic.prototype.revert = cRevert | |
7089 | Classic.prototype.reduce = cReduce | |
7090 | Classic.prototype.mulTo = cMulTo | |
7091 | Classic.prototype.sqrTo = cSqrTo | |
7092 | ||
7093 | // (protected) return "-1/this % 2^DB"; useful for Mont. reduction | |
7094 | // justification: | |
7095 | // xy == 1 (mod m) | |
7096 | // xy = 1+km | |
7097 | // xy(2-xy) = (1+km)(1-km) | |
7098 | // x[y(2-xy)] = 1-k^2m^2 | |
7099 | // x[y(2-xy)] == 1 (mod m^2) | |
7100 | // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 | |
7101 | // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. | |
7102 | // JS multiply "overflows" differently from C/C++, so care is needed here. | |
7103 | function bnpInvDigit() { | |
7104 | if (this.t < 1) return 0 | |
7105 | var x = this[0] | |
7106 | if ((x & 1) == 0) return 0 | |
7107 | var y = x & 3; // y == 1/x mod 2^2 | |
7108 | y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 | |
7109 | y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 | |
7110 | y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 | |
7111 | // last step - calculate inverse mod DV directly | |
7112 | // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints | |
7113 | y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits | |
7114 | // we really want the negative inverse, and -DV < y < DV | |
7115 | return (y > 0) ? this.DV - y : -y | |
7116 | } | |
7117 | ||
7118 | // Montgomery reduction | |
7119 | function Montgomery(m) { | |
7120 | this.m = m | |
7121 | this.mp = m.invDigit() | |
7122 | this.mpl = this.mp & 0x7fff | |
7123 | this.mph = this.mp >> 15 | |
7124 | this.um = (1 << (m.DB - 15)) - 1 | |
7125 | this.mt2 = 2 * m.t | |
7126 | } | |
7127 | ||
7128 | // xR mod m | |
7129 | function montConvert(x) { | |
7130 | var r = new BigInteger() | |
7131 | x.abs() | |
7132 | .dlShiftTo(this.m.t, r) | |
7133 | r.divRemTo(this.m, null, r) | |
7134 | if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r) | |
7135 | return r | |
7136 | } | |
7137 | ||
7138 | // x/R mod m | |
7139 | function montRevert(x) { | |
7140 | var r = new BigInteger() | |
7141 | x.copyTo(r) | |
7142 | this.reduce(r) | |
7143 | return r | |
7144 | } | |
7145 | ||
7146 | // x = x/R mod m (HAC 14.32) | |
7147 | function montReduce(x) { | |
7148 | while (x.t <= this.mt2) // pad x so am has enough room later | |
7149 | x[x.t++] = 0 | |
7150 | for (var i = 0; i < this.m.t; ++i) { | |
7151 | // faster way of calculating u0 = x[i]*mp mod DV | |
7152 | var j = x[i] & 0x7fff | |
7153 | var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM | |
7154 | // use am to combine the multiply-shift-add into one call | |
7155 | j = i + this.m.t | |
7156 | x[j] += this.m.am(0, u0, x, i, 0, this.m.t) | |
7157 | // propagate carry | |
7158 | while (x[j] >= x.DV) { | |
7159 | x[j] -= x.DV | |
7160 | x[++j]++ | |
7161 | } | |
7162 | } | |
7163 | x.clamp() | |
7164 | x.drShiftTo(this.m.t, x) | |
7165 | if (x.compareTo(this.m) >= 0) x.subTo(this.m, x) | |
7166 | } | |
7167 | ||
7168 | // r = "x^2/R mod m"; x != r | |
7169 | function montSqrTo(x, r) { | |
7170 | x.squareTo(r) | |
7171 | this.reduce(r) | |
7172 | } | |
7173 | ||
7174 | // r = "xy/R mod m"; x,y != r | |
7175 | function montMulTo(x, y, r) { | |
7176 | x.multiplyTo(y, r) | |
7177 | this.reduce(r) | |
7178 | } | |
7179 | ||
7180 | Montgomery.prototype.convert = montConvert | |
7181 | Montgomery.prototype.revert = montRevert | |
7182 | Montgomery.prototype.reduce = montReduce | |
7183 | Montgomery.prototype.mulTo = montMulTo | |
7184 | Montgomery.prototype.sqrTo = montSqrTo | |
7185 | ||
7186 | // (protected) true iff this is even | |
7187 | function bnpIsEven() { | |
7188 | return ((this.t > 0) ? (this[0] & 1) : this.s) == 0 | |
7189 | } | |
7190 | ||
7191 | // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) | |
7192 | function bnpExp(e, z) { | |
7193 | if (e > 0xffffffff || e < 1) return BigInteger.ONE | |
7194 | var r = new BigInteger(), | |
7195 | r2 = new BigInteger(), | |
7196 | g = z.convert(this), | |
7197 | i = nbits(e) - 1 | |
7198 | g.copyTo(r) | |
7199 | while (--i >= 0) { | |
7200 | z.sqrTo(r, r2) | |
7201 | if ((e & (1 << i)) > 0) z.mulTo(r2, g, r) | |
7202 | else { | |
7203 | var t = r | |
7204 | r = r2 | |
7205 | r2 = t | |
7206 | } | |
7207 | } | |
7208 | return z.revert(r) | |
7209 | } | |
7210 | ||
7211 | // (public) this^e % m, 0 <= e < 2^32 | |
7212 | function bnModPowInt(e, m) { | |
7213 | var z | |
7214 | if (e < 256 || m.isEven()) z = new Classic(m) | |
7215 | else z = new Montgomery(m) | |
7216 | return this.exp(e, z) | |
7217 | } | |
7218 | ||
7219 | // protected | |
7220 | proto.copyTo = bnpCopyTo | |
7221 | proto.fromInt = bnpFromInt | |
7222 | proto.fromString = bnpFromString | |
7223 | proto.clamp = bnpClamp | |
7224 | proto.dlShiftTo = bnpDLShiftTo | |
7225 | proto.drShiftTo = bnpDRShiftTo | |
7226 | proto.lShiftTo = bnpLShiftTo | |
7227 | proto.rShiftTo = bnpRShiftTo | |
7228 | proto.subTo = bnpSubTo | |
7229 | proto.multiplyTo = bnpMultiplyTo | |
7230 | proto.squareTo = bnpSquareTo | |
7231 | proto.divRemTo = bnpDivRemTo | |
7232 | proto.invDigit = bnpInvDigit | |
7233 | proto.isEven = bnpIsEven | |
7234 | proto.exp = bnpExp | |
7235 | ||
7236 | // public | |
7237 | proto.toString = bnToString | |
7238 | proto.negate = bnNegate | |
7239 | proto.abs = bnAbs | |
7240 | proto.compareTo = bnCompareTo | |
7241 | proto.bitLength = bnBitLength | |
7242 | proto.byteLength = bnByteLength | |
7243 | proto.mod = bnMod | |
7244 | proto.modPowInt = bnModPowInt | |
7245 | ||
7246 | // (public) | |
7247 | function bnClone() { | |
7248 | var r = new BigInteger() | |
7249 | this.copyTo(r) | |
7250 | return r | |
7251 | } | |
7252 | ||
7253 | // (public) return value as integer | |
7254 | function bnIntValue() { | |
7255 | if (this.s < 0) { | |
7256 | if (this.t == 1) return this[0] - this.DV | |
7257 | else if (this.t == 0) return -1 | |
7258 | } else if (this.t == 1) return this[0] | |
7259 | else if (this.t == 0) return 0 | |
7260 | // assumes 16 < DB < 32 | |
7261 | return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0] | |
7262 | } | |
7263 | ||
7264 | // (public) return value as byte | |
7265 | function bnByteValue() { | |
7266 | return (this.t == 0) ? this.s : (this[0] << 24) >> 24 | |
7267 | } | |
7268 | ||
7269 | // (public) return value as short (assumes DB>=16) | |
7270 | function bnShortValue() { | |
7271 | return (this.t == 0) ? this.s : (this[0] << 16) >> 16 | |
7272 | } | |
7273 | ||
7274 | // (protected) return x s.t. r^x < DV | |
7275 | function bnpChunkSize(r) { | |
7276 | return Math.floor(Math.LN2 * this.DB / Math.log(r)) | |
7277 | } | |
7278 | ||
7279 | // (public) 0 if this == 0, 1 if this > 0 | |
7280 | function bnSigNum() { | |
7281 | if (this.s < 0) return -1 | |
7282 | else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0 | |
7283 | else return 1 | |
7284 | } | |
7285 | ||
7286 | // (protected) convert to radix string | |
7287 | function bnpToRadix(b) { | |
7288 | if (b == null) b = 10 | |
7289 | if (this.signum() == 0 || b < 2 || b > 36) return "0" | |
7290 | var cs = this.chunkSize(b) | |
7291 | var a = Math.pow(b, cs) | |
7292 | var d = nbv(a), | |
7293 | y = new BigInteger(), | |
7294 | z = new BigInteger(), | |
7295 | r = "" | |
7296 | this.divRemTo(d, y, z) | |
7297 | while (y.signum() > 0) { | |
7298 | r = (a + z.intValue()) | |
7299 | .toString(b) | |
7300 | .substr(1) + r | |
7301 | y.divRemTo(d, y, z) | |
7302 | } | |
7303 | return z.intValue() | |
7304 | .toString(b) + r | |
7305 | } | |
7306 | ||
7307 | // (protected) convert from radix string | |
7308 | function bnpFromRadix(s, b) { | |
7309 | var self = this | |
7310 | self.fromInt(0) | |
7311 | if (b == null) b = 10 | |
7312 | var cs = self.chunkSize(b) | |
7313 | var d = Math.pow(b, cs), | |
7314 | mi = false, | |
7315 | j = 0, | |
7316 | w = 0 | |
7317 | for (var i = 0; i < s.length; ++i) { | |
7318 | var x = intAt(s, i) | |
7319 | if (x < 0) { | |
7320 | if (s.charAt(i) == "-" && self.signum() == 0) mi = true | |
7321 | continue | |
7322 | } | |
7323 | w = b * w + x | |
7324 | if (++j >= cs) { | |
7325 | self.dMultiply(d) | |
7326 | self.dAddOffset(w, 0) | |
7327 | j = 0 | |
7328 | w = 0 | |
7329 | } | |
7330 | } | |
7331 | if (j > 0) { | |
7332 | self.dMultiply(Math.pow(b, j)) | |
7333 | self.dAddOffset(w, 0) | |
7334 | } | |
7335 | if (mi) BigInteger.ZERO.subTo(self, self) | |
7336 | } | |
7337 | ||
7338 | // (protected) alternate constructor | |
7339 | function bnpFromNumber(a, b, c) { | |
7340 | var self = this | |
7341 | if ("number" == typeof b) { | |
7342 | // new BigInteger(int,int,RNG) | |
7343 | if (a < 2) self.fromInt(1) | |
7344 | else { | |
7345 | self.fromNumber(a, c) | |
7346 | if (!self.testBit(a - 1)) // force MSB set | |
7347 | self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self) | |
7348 | if (self.isEven()) self.dAddOffset(1, 0); // force odd | |
7349 | while (!self.isProbablePrime(b)) { | |
7350 | self.dAddOffset(2, 0) | |
7351 | if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self) | |
7352 | } | |
7353 | } | |
7354 | } else { | |
7355 | // new BigInteger(int,RNG) | |
7356 | var x = new Array(), | |
7357 | t = a & 7 | |
7358 | x.length = (a >> 3) + 1 | |
7359 | b.nextBytes(x) | |
7360 | if (t > 0) x[0] &= ((1 << t) - 1) | |
7361 | else x[0] = 0 | |
7362 | self.fromString(x, 256) | |
7363 | } | |
7364 | } | |
7365 | ||
7366 | // (public) convert to bigendian byte array | |
7367 | function bnToByteArray() { | |
7368 | var self = this | |
7369 | var i = self.t, | |
7370 | r = new Array() | |
7371 | r[0] = self.s | |
7372 | var p = self.DB - (i * self.DB) % 8, | |
7373 | d, k = 0 | |
7374 | if (i-- > 0) { | |
7375 | if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p) | |
7376 | r[k++] = d | (self.s << (self.DB - p)) | |
7377 | while (i >= 0) { | |
7378 | if (p < 8) { | |
7379 | d = (self[i] & ((1 << p) - 1)) << (8 - p) | |
7380 | d |= self[--i] >> (p += self.DB - 8) | |
7381 | } else { | |
7382 | d = (self[i] >> (p -= 8)) & 0xff | |
7383 | if (p <= 0) { | |
7384 | p += self.DB | |
7385 | --i | |
7386 | } | |
7387 | } | |
7388 | if ((d & 0x80) != 0) d |= -256 | |
7389 | if (k === 0 && (self.s & 0x80) != (d & 0x80))++k | |
7390 | if (k > 0 || d != self.s) r[k++] = d | |
7391 | } | |
7392 | } | |
7393 | return r | |
7394 | } | |
7395 | ||
7396 | function bnEquals(a) { | |
7397 | return (this.compareTo(a) == 0) | |
7398 | } | |
7399 | ||
7400 | function bnMin(a) { | |
7401 | return (this.compareTo(a) < 0) ? this : a | |
7402 | } | |
7403 | ||
7404 | function bnMax(a) { | |
7405 | return (this.compareTo(a) > 0) ? this : a | |
7406 | } | |
7407 | ||
7408 | // (protected) r = this op a (bitwise) | |
7409 | function bnpBitwiseTo(a, op, r) { | |
7410 | var self = this | |
7411 | var i, f, m = Math.min(a.t, self.t) | |
7412 | for (i = 0; i < m; ++i) r[i] = op(self[i], a[i]) | |
7413 | if (a.t < self.t) { | |
7414 | f = a.s & self.DM | |
7415 | for (i = m; i < self.t; ++i) r[i] = op(self[i], f) | |
7416 | r.t = self.t | |
7417 | } else { | |
7418 | f = self.s & self.DM | |
7419 | for (i = m; i < a.t; ++i) r[i] = op(f, a[i]) | |
7420 | r.t = a.t | |
7421 | } | |
7422 | r.s = op(self.s, a.s) | |
7423 | r.clamp() | |
7424 | } | |
7425 | ||
7426 | // (public) this & a | |
7427 | function op_and(x, y) { | |
7428 | return x & y | |
7429 | } | |
7430 | ||
7431 | function bnAnd(a) { | |
7432 | var r = new BigInteger() | |
7433 | this.bitwiseTo(a, op_and, r) | |
7434 | return r | |
7435 | } | |
7436 | ||
7437 | // (public) this | a | |
7438 | function op_or(x, y) { | |
7439 | return x | y | |
7440 | } | |
7441 | ||
7442 | function bnOr(a) { | |
7443 | var r = new BigInteger() | |
7444 | this.bitwiseTo(a, op_or, r) | |
7445 | return r | |
7446 | } | |
7447 | ||
7448 | // (public) this ^ a | |
7449 | function op_xor(x, y) { | |
7450 | return x ^ y | |
7451 | } | |
7452 | ||
7453 | function bnXor(a) { | |
7454 | var r = new BigInteger() | |
7455 | this.bitwiseTo(a, op_xor, r) | |
7456 | return r | |
7457 | } | |
7458 | ||
7459 | // (public) this & ~a | |
7460 | function op_andnot(x, y) { | |
7461 | return x & ~y | |
7462 | } | |
7463 | ||
7464 | function bnAndNot(a) { | |
7465 | var r = new BigInteger() | |
7466 | this.bitwiseTo(a, op_andnot, r) | |
7467 | return r | |
7468 | } | |
7469 | ||
7470 | // (public) ~this | |
7471 | function bnNot() { | |
7472 | var r = new BigInteger() | |
7473 | for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i] | |
7474 | r.t = this.t | |
7475 | r.s = ~this.s | |
7476 | return r | |
7477 | } | |
7478 | ||
7479 | // (public) this << n | |
7480 | function bnShiftLeft(n) { | |
7481 | var r = new BigInteger() | |
7482 | if (n < 0) this.rShiftTo(-n, r) | |
7483 | else this.lShiftTo(n, r) | |
7484 | return r | |
7485 | } | |
7486 | ||
7487 | // (public) this >> n | |
7488 | function bnShiftRight(n) { | |
7489 | var r = new BigInteger() | |
7490 | if (n < 0) this.lShiftTo(-n, r) | |
7491 | else this.rShiftTo(n, r) | |
7492 | return r | |
7493 | } | |
7494 | ||
7495 | // return index of lowest 1-bit in x, x < 2^31 | |
7496 | function lbit(x) { | |
7497 | if (x == 0) return -1 | |
7498 | var r = 0 | |
7499 | if ((x & 0xffff) == 0) { | |
7500 | x >>= 16 | |
7501 | r += 16 | |
7502 | } | |
7503 | if ((x & 0xff) == 0) { | |
7504 | x >>= 8 | |
7505 | r += 8 | |
7506 | } | |
7507 | if ((x & 0xf) == 0) { | |
7508 | x >>= 4 | |
7509 | r += 4 | |
7510 | } | |
7511 | if ((x & 3) == 0) { | |
7512 | x >>= 2 | |
7513 | r += 2 | |
7514 | } | |
7515 | if ((x & 1) == 0)++r | |
7516 | return r | |
7517 | } | |
7518 | ||
7519 | // (public) returns index of lowest 1-bit (or -1 if none) | |
7520 | function bnGetLowestSetBit() { | |
7521 | for (var i = 0; i < this.t; ++i) | |
7522 | if (this[i] != 0) return i * this.DB + lbit(this[i]) | |
7523 | if (this.s < 0) return this.t * this.DB | |
7524 | return -1 | |
7525 | } | |
7526 | ||
7527 | // return number of 1 bits in x | |
7528 | function cbit(x) { | |
7529 | var r = 0 | |
7530 | while (x != 0) { | |
7531 | x &= x - 1 | |
7532 | ++r | |
7533 | } | |
7534 | return r | |
7535 | } | |
7536 | ||
7537 | // (public) return number of set bits | |
7538 | function bnBitCount() { | |
7539 | var r = 0, | |
7540 | x = this.s & this.DM | |
7541 | for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x) | |
7542 | return r | |
7543 | } | |
7544 | ||
7545 | // (public) true iff nth bit is set | |
7546 | function bnTestBit(n) { | |
7547 | var j = Math.floor(n / this.DB) | |
7548 | if (j >= this.t) return (this.s != 0) | |
7549 | return ((this[j] & (1 << (n % this.DB))) != 0) | |
7550 | } | |
7551 | ||
7552 | // (protected) this op (1<<n) | |
7553 | function bnpChangeBit(n, op) { | |
7554 | var r = BigInteger.ONE.shiftLeft(n) | |
7555 | this.bitwiseTo(r, op, r) | |
7556 | return r | |
7557 | } | |
7558 | ||
7559 | // (public) this | (1<<n) | |
7560 | function bnSetBit(n) { | |
7561 | return this.changeBit(n, op_or) | |
7562 | } | |
7563 | ||
7564 | // (public) this & ~(1<<n) | |
7565 | function bnClearBit(n) { | |
7566 | return this.changeBit(n, op_andnot) | |
7567 | } | |
7568 | ||
7569 | // (public) this ^ (1<<n) | |
7570 | function bnFlipBit(n) { | |
7571 | return this.changeBit(n, op_xor) | |
7572 | } | |
7573 | ||
7574 | // (protected) r = this + a | |
7575 | function bnpAddTo(a, r) { | |
7576 | var self = this | |
7577 | ||
7578 | var i = 0, | |
7579 | c = 0, | |
7580 | m = Math.min(a.t, self.t) | |
7581 | while (i < m) { | |
7582 | c += self[i] + a[i] | |
7583 | r[i++] = c & self.DM | |
7584 | c >>= self.DB | |
7585 | } | |
7586 | if (a.t < self.t) { | |
7587 | c += a.s | |
7588 | while (i < self.t) { | |
7589 | c += self[i] | |
7590 | r[i++] = c & self.DM | |
7591 | c >>= self.DB | |
7592 | } | |
7593 | c += self.s | |
7594 | } else { | |
7595 | c += self.s | |
7596 | while (i < a.t) { | |
7597 | c += a[i] | |
7598 | r[i++] = c & self.DM | |
7599 | c >>= self.DB | |
7600 | } | |
7601 | c += a.s | |
7602 | } | |
7603 | r.s = (c < 0) ? -1 : 0 | |
7604 | if (c > 0) r[i++] = c | |
7605 | else if (c < -1) r[i++] = self.DV + c | |
7606 | r.t = i | |
7607 | r.clamp() | |
7608 | } | |
7609 | ||
7610 | // (public) this + a | |
7611 | function bnAdd(a) { | |
7612 | var r = new BigInteger() | |
7613 | this.addTo(a, r) | |
7614 | return r | |
7615 | } | |
7616 | ||
7617 | // (public) this - a | |
7618 | function bnSubtract(a) { | |
7619 | var r = new BigInteger() | |
7620 | this.subTo(a, r) | |
7621 | return r | |
7622 | } | |
7623 | ||
7624 | // (public) this * a | |
7625 | function bnMultiply(a) { | |
7626 | var r = new BigInteger() | |
7627 | this.multiplyTo(a, r) | |
7628 | return r | |
7629 | } | |
7630 | ||
7631 | // (public) this^2 | |
7632 | function bnSquare() { | |
7633 | var r = new BigInteger() | |
7634 | this.squareTo(r) | |
7635 | return r | |
7636 | } | |
7637 | ||
7638 | // (public) this / a | |
7639 | function bnDivide(a) { | |
7640 | var r = new BigInteger() | |
7641 | this.divRemTo(a, r, null) | |
7642 | return r | |
7643 | } | |
7644 | ||
7645 | // (public) this % a | |
7646 | function bnRemainder(a) { | |
7647 | var r = new BigInteger() | |
7648 | this.divRemTo(a, null, r) | |
7649 | return r | |
7650 | } | |
7651 | ||
7652 | // (public) [this/a,this%a] | |
7653 | function bnDivideAndRemainder(a) { | |
7654 | var q = new BigInteger(), | |
7655 | r = new BigInteger() | |
7656 | this.divRemTo(a, q, r) | |
7657 | return new Array(q, r) | |
7658 | } | |
7659 | ||
7660 | // (protected) this *= n, this >= 0, 1 < n < DV | |
7661 | function bnpDMultiply(n) { | |
7662 | this[this.t] = this.am(0, n - 1, this, 0, 0, this.t) | |
7663 | ++this.t | |
7664 | this.clamp() | |
7665 | } | |
7666 | ||
7667 | // (protected) this += n << w words, this >= 0 | |
7668 | function bnpDAddOffset(n, w) { | |
7669 | if (n == 0) return | |
7670 | while (this.t <= w) this[this.t++] = 0 | |
7671 | this[w] += n | |
7672 | while (this[w] >= this.DV) { | |
7673 | this[w] -= this.DV | |
7674 | if (++w >= this.t) this[this.t++] = 0 | |
7675 | ++this[w] | |
7676 | } | |
7677 | } | |
7678 | ||
7679 | // A "null" reducer | |
7680 | function NullExp() {} | |
7681 | ||
7682 | function nNop(x) { | |
7683 | return x | |
7684 | } | |
7685 | ||
7686 | function nMulTo(x, y, r) { | |
7687 | x.multiplyTo(y, r) | |
7688 | } | |
7689 | ||
7690 | function nSqrTo(x, r) { | |
7691 | x.squareTo(r) | |
7692 | } | |
7693 | ||
7694 | NullExp.prototype.convert = nNop | |
7695 | NullExp.prototype.revert = nNop | |
7696 | NullExp.prototype.mulTo = nMulTo | |
7697 | NullExp.prototype.sqrTo = nSqrTo | |
7698 | ||
7699 | // (public) this^e | |
7700 | function bnPow(e) { | |
7701 | return this.exp(e, new NullExp()) | |
7702 | } | |
7703 | ||
7704 | // (protected) r = lower n words of "this * a", a.t <= n | |
7705 | // "this" should be the larger one if appropriate. | |
7706 | function bnpMultiplyLowerTo(a, n, r) { | |
7707 | var i = Math.min(this.t + a.t, n) | |
7708 | r.s = 0; // assumes a,this >= 0 | |
7709 | r.t = i | |
7710 | while (i > 0) r[--i] = 0 | |
7711 | var j | |
7712 | for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t) | |
7713 | for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i) | |
7714 | r.clamp() | |
7715 | } | |
7716 | ||
7717 | // (protected) r = "this * a" without lower n words, n > 0 | |
7718 | // "this" should be the larger one if appropriate. | |
7719 | function bnpMultiplyUpperTo(a, n, r) { | |
7720 | --n | |
7721 | var i = r.t = this.t + a.t - n | |
7722 | r.s = 0; // assumes a,this >= 0 | |
7723 | while (--i >= 0) r[i] = 0 | |
7724 | for (i = Math.max(n - this.t, 0); i < a.t; ++i) | |
7725 | r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n) | |
7726 | r.clamp() | |
7727 | r.drShiftTo(1, r) | |
7728 | } | |
7729 | ||
7730 | // Barrett modular reduction | |
7731 | function Barrett(m) { | |
7732 | // setup Barrett | |
7733 | this.r2 = new BigInteger() | |
7734 | this.q3 = new BigInteger() | |
7735 | BigInteger.ONE.dlShiftTo(2 * m.t, this.r2) | |
7736 | this.mu = this.r2.divide(m) | |
7737 | this.m = m | |
7738 | } | |
7739 | ||
7740 | function barrettConvert(x) { | |
7741 | if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m) | |
7742 | else if (x.compareTo(this.m) < 0) return x | |
7743 | else { | |
7744 | var r = new BigInteger() | |
7745 | x.copyTo(r) | |
7746 | this.reduce(r) | |
7747 | return r | |
7748 | } | |
7749 | } | |
7750 | ||
7751 | function barrettRevert(x) { | |
7752 | return x | |
7753 | } | |
7754 | ||
7755 | // x = x mod m (HAC 14.42) | |
7756 | function barrettReduce(x) { | |
7757 | var self = this | |
7758 | x.drShiftTo(self.m.t - 1, self.r2) | |
7759 | if (x.t > self.m.t + 1) { | |
7760 | x.t = self.m.t + 1 | |
7761 | x.clamp() | |
7762 | } | |
7763 | self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3) | |
7764 | self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2) | |
7765 | while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1) | |
7766 | x.subTo(self.r2, x) | |
7767 | while (x.compareTo(self.m) >= 0) x.subTo(self.m, x) | |
7768 | } | |
7769 | ||
7770 | // r = x^2 mod m; x != r | |
7771 | function barrettSqrTo(x, r) { | |
7772 | x.squareTo(r) | |
7773 | this.reduce(r) | |
7774 | } | |
7775 | ||
7776 | // r = x*y mod m; x,y != r | |
7777 | function barrettMulTo(x, y, r) { | |
7778 | x.multiplyTo(y, r) | |
7779 | this.reduce(r) | |
7780 | } | |
7781 | ||
7782 | Barrett.prototype.convert = barrettConvert | |
7783 | Barrett.prototype.revert = barrettRevert | |
7784 | Barrett.prototype.reduce = barrettReduce | |
7785 | Barrett.prototype.mulTo = barrettMulTo | |
7786 | Barrett.prototype.sqrTo = barrettSqrTo | |
7787 | ||
7788 | // (public) this^e % m (HAC 14.85) | |
7789 | function bnModPow(e, m) { | |
7790 | var i = e.bitLength(), | |
7791 | k, r = nbv(1), | |
7792 | z | |
7793 | if (i <= 0) return r | |
7794 | else if (i < 18) k = 1 | |
7795 | else if (i < 48) k = 3 | |
7796 | else if (i < 144) k = 4 | |
7797 | else if (i < 768) k = 5 | |
7798 | else k = 6 | |
7799 | if (i < 8) | |
7800 | z = new Classic(m) | |
7801 | else if (m.isEven()) | |
7802 | z = new Barrett(m) | |
7803 | else | |
7804 | z = new Montgomery(m) | |
7805 | ||
7806 | // precomputation | |
7807 | var g = new Array(), | |
7808 | n = 3, | |
7809 | k1 = k - 1, | |
7810 | km = (1 << k) - 1 | |
7811 | g[1] = z.convert(this) | |
7812 | if (k > 1) { | |
7813 | var g2 = new BigInteger() | |
7814 | z.sqrTo(g[1], g2) | |
7815 | while (n <= km) { | |
7816 | g[n] = new BigInteger() | |
7817 | z.mulTo(g2, g[n - 2], g[n]) | |
7818 | n += 2 | |
7819 | } | |
7820 | } | |
7821 | ||
7822 | var j = e.t - 1, | |
7823 | w, is1 = true, | |
7824 | r2 = new BigInteger(), | |
7825 | t | |
7826 | i = nbits(e[j]) - 1 | |
7827 | while (j >= 0) { | |
7828 | if (i >= k1) w = (e[j] >> (i - k1)) & km | |
7829 | else { | |
7830 | w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i) | |
7831 | if (j > 0) w |= e[j - 1] >> (this.DB + i - k1) | |
7832 | } | |
7833 | ||
7834 | n = k | |
7835 | while ((w & 1) == 0) { | |
7836 | w >>= 1 | |
7837 | --n | |
7838 | } | |
7839 | if ((i -= n) < 0) { | |
7840 | i += this.DB | |
7841 | --j | |
7842 | } | |
7843 | if (is1) { // ret == 1, don't bother squaring or multiplying it | |
7844 | g[w].copyTo(r) | |
7845 | is1 = false | |
7846 | } else { | |
7847 | while (n > 1) { | |
7848 | z.sqrTo(r, r2) | |
7849 | z.sqrTo(r2, r) | |
7850 | n -= 2 | |
7851 | } | |
7852 | if (n > 0) z.sqrTo(r, r2) | |
7853 | else { | |
7854 | t = r | |
7855 | r = r2 | |
7856 | r2 = t | |
7857 | } | |
7858 | z.mulTo(r2, g[w], r) | |
7859 | } | |
7860 | ||
7861 | while (j >= 0 && (e[j] & (1 << i)) == 0) { | |
7862 | z.sqrTo(r, r2) | |
7863 | t = r | |
7864 | r = r2 | |
7865 | r2 = t | |
7866 | if (--i < 0) { | |
7867 | i = this.DB - 1 | |
7868 | --j | |
7869 | } | |
7870 | } | |
7871 | } | |
7872 | return z.revert(r) | |
7873 | } | |
7874 | ||
7875 | // (public) gcd(this,a) (HAC 14.54) | |
7876 | function bnGCD(a) { | |
7877 | var x = (this.s < 0) ? this.negate() : this.clone() | |
7878 | var y = (a.s < 0) ? a.negate() : a.clone() | |
7879 | if (x.compareTo(y) < 0) { | |
7880 | var t = x | |
7881 | x = y | |
7882 | y = t | |
7883 | } | |
7884 | var i = x.getLowestSetBit(), | |
7885 | g = y.getLowestSetBit() | |
7886 | if (g < 0) return x | |
7887 | if (i < g) g = i | |
7888 | if (g > 0) { | |
7889 | x.rShiftTo(g, x) | |
7890 | y.rShiftTo(g, y) | |
7891 | } | |
7892 | while (x.signum() > 0) { | |
7893 | if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x) | |
7894 | if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y) | |
7895 | if (x.compareTo(y) >= 0) { | |
7896 | x.subTo(y, x) | |
7897 | x.rShiftTo(1, x) | |
7898 | } else { | |
7899 | y.subTo(x, y) | |
7900 | y.rShiftTo(1, y) | |
7901 | } | |
7902 | } | |
7903 | if (g > 0) y.lShiftTo(g, y) | |
7904 | return y | |
7905 | } | |
7906 | ||
7907 | // (protected) this % n, n < 2^26 | |
7908 | function bnpModInt(n) { | |
7909 | if (n <= 0) return 0 | |
7910 | var d = this.DV % n, | |
7911 | r = (this.s < 0) ? n - 1 : 0 | |
7912 | if (this.t > 0) | |
7913 | if (d == 0) r = this[0] % n | |
7914 | else | |
7915 | for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n | |
7916 | return r | |
7917 | } | |
7918 | ||
7919 | // (public) 1/this % m (HAC 14.61) | |
7920 | function bnModInverse(m) { | |
7921 | var ac = m.isEven() | |
7922 | if (this.signum() === 0) throw new Error('division by zero') | |
7923 | if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO | |
7924 | var u = m.clone(), | |
7925 | v = this.clone() | |
7926 | var a = nbv(1), | |
7927 | b = nbv(0), | |
7928 | c = nbv(0), | |
7929 | d = nbv(1) | |
7930 | while (u.signum() != 0) { | |
7931 | while (u.isEven()) { | |
7932 | u.rShiftTo(1, u) | |
7933 | if (ac) { | |
7934 | if (!a.isEven() || !b.isEven()) { | |
7935 | a.addTo(this, a) | |
7936 | b.subTo(m, b) | |
7937 | } | |
7938 | a.rShiftTo(1, a) | |
7939 | } else if (!b.isEven()) b.subTo(m, b) | |
7940 | b.rShiftTo(1, b) | |
7941 | } | |
7942 | while (v.isEven()) { | |
7943 | v.rShiftTo(1, v) | |
7944 | if (ac) { | |
7945 | if (!c.isEven() || !d.isEven()) { | |
7946 | c.addTo(this, c) | |
7947 | d.subTo(m, d) | |
7948 | } | |
7949 | c.rShiftTo(1, c) | |
7950 | } else if (!d.isEven()) d.subTo(m, d) | |
7951 | d.rShiftTo(1, d) | |
7952 | } | |
7953 | if (u.compareTo(v) >= 0) { | |
7954 | u.subTo(v, u) | |
7955 | if (ac) a.subTo(c, a) | |
7956 | b.subTo(d, b) | |
7957 | } else { | |
7958 | v.subTo(u, v) | |
7959 | if (ac) c.subTo(a, c) | |
7960 | d.subTo(b, d) | |
7961 | } | |
7962 | } | |
7963 | if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO | |
7964 | while (d.compareTo(m) >= 0) d.subTo(m, d) | |
7965 | while (d.signum() < 0) d.addTo(m, d) | |
7966 | return d | |
7967 | } | |
7968 | ||
7969 | var lowprimes = [ | |
7970 | 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71, | |
7971 | 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151, | |
7972 | 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233, | |
7973 | 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317, | |
7974 | 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419, | |
7975 | 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503, | |
7976 | 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607, | |
7977 | 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701, | |
7978 | 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811, | |
7979 | 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911, | |
7980 | 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997 | |
7981 | ] | |
7982 | ||
7983 | var lplim = (1 << 26) / lowprimes[lowprimes.length - 1] | |
7984 | ||
7985 | // (public) test primality with certainty >= 1-.5^t | |
7986 | function bnIsProbablePrime(t) { | |
7987 | var i, x = this.abs() | |
7988 | if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { | |
7989 | for (i = 0; i < lowprimes.length; ++i) | |
7990 | if (x[0] == lowprimes[i]) return true | |
7991 | return false | |
7992 | } | |
7993 | if (x.isEven()) return false | |
7994 | i = 1 | |
7995 | while (i < lowprimes.length) { | |
7996 | var m = lowprimes[i], | |
7997 | j = i + 1 | |
7998 | while (j < lowprimes.length && m < lplim) m *= lowprimes[j++] | |
7999 | m = x.modInt(m) | |
8000 | while (i < j) if (m % lowprimes[i++] == 0) return false | |
8001 | } | |
8002 | return x.millerRabin(t) | |
8003 | } | |
8004 | ||
8005 | // (protected) true if probably prime (HAC 4.24, Miller-Rabin) | |
8006 | function bnpMillerRabin(t) { | |
8007 | var n1 = this.subtract(BigInteger.ONE) | |
8008 | var k = n1.getLowestSetBit() | |
8009 | if (k <= 0) return false | |
8010 | var r = n1.shiftRight(k) | |
8011 | t = (t + 1) >> 1 | |
8012 | if (t > lowprimes.length) t = lowprimes.length | |
8013 | var a = new BigInteger(null) | |
8014 | var j, bases = [] | |
8015 | for (var i = 0; i < t; ++i) { | |
8016 | for (;;) { | |
8017 | j = lowprimes[Math.floor(Math.random() * lowprimes.length)] | |
8018 | if (bases.indexOf(j) == -1) break | |
8019 | } | |
8020 | bases.push(j) | |
8021 | a.fromInt(j) | |
8022 | var y = a.modPow(r, this) | |
8023 | if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { | |
8024 | var j = 1 | |
8025 | while (j++ < k && y.compareTo(n1) != 0) { | |
8026 | y = y.modPowInt(2, this) | |
8027 | if (y.compareTo(BigInteger.ONE) == 0) return false | |
8028 | } | |
8029 | if (y.compareTo(n1) != 0) return false | |
8030 | } | |
8031 | } | |
8032 | return true | |
8033 | } | |
8034 | ||
8035 | // protected | |
8036 | proto.chunkSize = bnpChunkSize | |
8037 | proto.toRadix = bnpToRadix | |
8038 | proto.fromRadix = bnpFromRadix | |
8039 | proto.fromNumber = bnpFromNumber | |
8040 | proto.bitwiseTo = bnpBitwiseTo | |
8041 | proto.changeBit = bnpChangeBit | |
8042 | proto.addTo = bnpAddTo | |
8043 | proto.dMultiply = bnpDMultiply | |
8044 | proto.dAddOffset = bnpDAddOffset | |
8045 | proto.multiplyLowerTo = bnpMultiplyLowerTo | |
8046 | proto.multiplyUpperTo = bnpMultiplyUpperTo | |
8047 | proto.modInt = bnpModInt | |
8048 | proto.millerRabin = bnpMillerRabin | |
8049 | ||
8050 | // public | |
8051 | proto.clone = bnClone | |
8052 | proto.intValue = bnIntValue | |
8053 | proto.byteValue = bnByteValue | |
8054 | proto.shortValue = bnShortValue | |
8055 | proto.signum = bnSigNum | |
8056 | proto.toByteArray = bnToByteArray | |
8057 | proto.equals = bnEquals | |
8058 | proto.min = bnMin | |
8059 | proto.max = bnMax | |
8060 | proto.and = bnAnd | |
8061 | proto.or = bnOr | |
8062 | proto.xor = bnXor | |
8063 | proto.andNot = bnAndNot | |
8064 | proto.not = bnNot | |
8065 | proto.shiftLeft = bnShiftLeft | |
8066 | proto.shiftRight = bnShiftRight | |
8067 | proto.getLowestSetBit = bnGetLowestSetBit | |
8068 | proto.bitCount = bnBitCount | |
8069 | proto.testBit = bnTestBit | |
8070 | proto.setBit = bnSetBit | |
8071 | proto.clearBit = bnClearBit | |
8072 | proto.flipBit = bnFlipBit | |
8073 | proto.add = bnAdd | |
8074 | proto.subtract = bnSubtract | |
8075 | proto.multiply = bnMultiply | |
8076 | proto.divide = bnDivide | |
8077 | proto.remainder = bnRemainder | |
8078 | proto.divideAndRemainder = bnDivideAndRemainder | |
8079 | proto.modPow = bnModPow | |
8080 | proto.modInverse = bnModInverse | |
8081 | proto.pow = bnPow | |
8082 | proto.gcd = bnGCD | |
8083 | proto.isProbablePrime = bnIsProbablePrime | |
8084 | ||
8085 | // JSBN-specific extension | |
8086 | proto.square = bnSquare | |
8087 | ||
8088 | // constants | |
8089 | BigInteger.ZERO = nbv(0) | |
8090 | BigInteger.ONE = nbv(1) | |
8091 | BigInteger.valueOf = nbv | |
8092 | ||
8093 | module.exports = BigInteger | |
8094 | ||
8095 | },{"../package.json":38}],36:[function(require,module,exports){ | |
8096 | (function (Buffer){ | |
8097 | // FIXME: Kind of a weird way to throw exceptions, consider removing | |
8098 | var assert = require('assert') | |
8099 | var BigInteger = require('./bigi') | |
8100 | ||
8101 | /** | |
8102 | * Turns a byte array into a big integer. | |
8103 | * | |
8104 | * This function will interpret a byte array as a big integer in big | |
8105 | * endian notation. | |
8106 | */ | |
8107 | BigInteger.fromByteArrayUnsigned = function(byteArray) { | |
8108 | // BigInteger expects a DER integer conformant byte array | |
8109 | if (byteArray[0] & 0x80) { | |
8110 | return new BigInteger([0].concat(byteArray)) | |
8111 | } | |
8112 | ||
8113 | return new BigInteger(byteArray) | |
8114 | } | |
8115 | ||
8116 | /** | |
8117 | * Returns a byte array representation of the big integer. | |
8118 | * | |
8119 | * This returns the absolute of the contained value in big endian | |
8120 | * form. A value of zero results in an empty array. | |
8121 | */ | |
8122 | BigInteger.prototype.toByteArrayUnsigned = function() { | |
8123 | var byteArray = this.toByteArray() | |
8124 | return byteArray[0] === 0 ? byteArray.slice(1) : byteArray | |
8125 | } | |
8126 | ||
8127 | BigInteger.fromDERInteger = function(byteArray) { | |
8128 | return new BigInteger(byteArray) | |
8129 | } | |
8130 | ||
8131 | /* | |
8132 | * Converts BigInteger to a DER integer representation. | |
8133 | * | |
8134 | * The format for this value uses the most significant bit as a sign | |
8135 | * bit. If the most significant bit is already set and the integer is | |
8136 | * positive, a 0x00 is prepended. | |
8137 | * | |
8138 | * Examples: | |
8139 | * | |
8140 | * 0 => 0x00 | |
8141 | * 1 => 0x01 | |
8142 | * -1 => 0xff | |
8143 | * 127 => 0x7f | |
8144 | * -127 => 0x81 | |
8145 | * 128 => 0x0080 | |
8146 | * -128 => 0x80 | |
8147 | * 255 => 0x00ff | |
8148 | * -255 => 0xff01 | |
8149 | * 16300 => 0x3fac | |
8150 | * -16300 => 0xc054 | |
8151 | * 62300 => 0x00f35c | |
8152 | * -62300 => 0xff0ca4 | |
8153 | */ | |
8154 | BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray | |
8155 | ||
8156 | BigInteger.fromBuffer = function(buffer) { | |
8157 | // BigInteger expects a DER integer conformant byte array | |
8158 | if (buffer[0] & 0x80) { | |
8159 | var byteArray = Array.prototype.slice.call(buffer) | |
8160 | ||
8161 | return new BigInteger([0].concat(byteArray)) | |
8162 | } | |
8163 | ||
8164 | return new BigInteger(buffer) | |
8165 | } | |
8166 | ||
8167 | BigInteger.fromHex = function(hex) { | |
8168 | if (hex === '') return BigInteger.ZERO | |
8169 | ||
8170 | assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string') | |
8171 | assert.equal(hex.length % 2, 0, 'Incomplete hex') | |
8172 | return new BigInteger(hex, 16) | |
8173 | } | |
8174 | ||
8175 | BigInteger.prototype.toBuffer = function(size) { | |
8176 | var byteArray = this.toByteArrayUnsigned() | |
8177 | var zeros = [] | |
8178 | ||
8179 | var padding = size - byteArray.length | |
8180 | while (zeros.length < padding) zeros.push(0) | |
8181 | ||
8182 | return new Buffer(zeros.concat(byteArray)) | |
8183 | } | |
8184 | ||
8185 | BigInteger.prototype.toHex = function(size) { | |
8186 | return this.toBuffer(size).toString('hex') | |
8187 | } | |
8188 | ||
8189 | }).call(this,require("buffer").Buffer) | |
8190 | },{"./bigi":35,"assert":1,"buffer":4}],37:[function(require,module,exports){ | |
8191 | var BigInteger = require('./bigi') | |
8192 | ||
8193 | //addons | |
8194 | require('./convert') | |
8195 | ||
8196 | module.exports = BigInteger | |
8197 | },{"./bigi":35,"./convert":36}],38:[function(require,module,exports){ | |
8198 | module.exports={ | |
8199 | "_args": [ | |
8200 | [ | |
8201 | "bigi", | |
8202 | "/home/ian/git/bitcoin/bitcoinjs-lib-browser" | |
8203 | ] | |
8204 | ], | |
8205 | "_from": "bigi@latest", | |
8206 | "_id": "bigi@1.4.2", | |
8207 | "_inCache": true, | |
8208 | "_installable": true, | |
8209 | "_location": "/bigi", | |
8210 | "_nodeVersion": "6.1.0", | |
8211 | "_npmOperationalInternal": { | |
8212 | "host": "packages-12-west.internal.npmjs.com", | |
8213 | "tmp": "tmp/bigi-1.4.2.tgz_1469584192413_0.6801238611806184" | |
8214 | }, | |
8215 | "_npmUser": { | |
8216 | "email": "jprichardson@gmail.com", | |
8217 | "name": "jprichardson" | |
8218 | }, | |
8219 | "_npmVersion": "3.8.6", | |
8220 | "_phantomChildren": {}, | |
8221 | "_requested": { | |
8222 | "name": "bigi", | |
8223 | "raw": "bigi", | |
8224 | "rawSpec": "", | |
8225 | "scope": null, | |
8226 | "spec": "latest", | |
8227 | "type": "tag" | |
8228 | }, | |
8229 | "_requiredBy": [ | |
8230 | "#USER", | |
8231 | "/bitcoinjs-lib", | |
8232 | "/ecurve" | |
8233 | ], | |
8234 | "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz", | |
8235 | "_shasum": "9c665a95f88b8b08fc05cfd731f561859d725825", | |
8236 | "_shrinkwrap": null, | |
8237 | "_spec": "bigi", | |
8238 | "_where": "/home/ian/git/bitcoin/bitcoinjs-lib-browser", | |
8239 | "bugs": { | |
8240 | "url": "https://github.com/cryptocoinjs/bigi/issues" | |
8241 | }, | |
8242 | "dependencies": {}, | |
8243 | "description": "Big integers.", | |
8244 | "devDependencies": { | |
8245 | "coveralls": "^2.11.2", | |
8246 | "istanbul": "^0.3.5", | |
8247 | "jshint": "^2.5.1", | |
8248 | "mocha": "^2.1.0", | |
8249 | "mochify": "^2.1.0" | |
8250 | }, | |
8251 | "directories": {}, | |
8252 | "dist": { | |
8253 | "shasum": "9c665a95f88b8b08fc05cfd731f561859d725825", | |
8254 | "tarball": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz" | |
8255 | }, | |
8256 | "gitHead": "c25308081c896ff84702303722bf5ecd8b3f78e3", | |
8257 | "homepage": "https://github.com/cryptocoinjs/bigi#readme", | |
8258 | "keywords": [ | |
8259 | "cryptography", | |
8260 | "math", | |
8261 | "bitcoin", | |
8262 | "arbitrary", | |
8263 | "precision", | |
8264 | "arithmetic", | |
8265 | "big", | |
8266 | "integer", | |
8267 | "int", | |
8268 | "number", | |
8269 | "biginteger", | |
8270 | "bigint", | |
8271 | "bignumber", | |
8272 | "decimal", | |
8273 | "float" | |
8274 | ], | |
8275 | "main": "./lib/index.js", | |
8276 | "maintainers": [ | |
8277 | { | |
8278 | "email": "boydb@midnightdesign.ws", | |
8279 | "name": "midnightlightning" | |
8280 | }, | |
8281 | { | |
8282 | "email": "sidazhang89@gmail.com", | |
8283 | "name": "sidazhang" | |
8284 | }, | |
8285 | { | |
8286 | "email": "npm@shesek.info", | |
8287 | "name": "nadav" | |
8288 | }, | |
8289 | { | |
8290 | "email": "jprichardson@gmail.com", | |
8291 | "name": "jprichardson" | |
8292 | } | |
8293 | ], | |
8294 | "name": "bigi", | |
8295 | "optionalDependencies": {}, | |
8296 | "readme": "ERROR: No README data found!", | |
8297 | "repository": { | |
8298 | "type": "git", | |
8299 | "url": "git+https://github.com/cryptocoinjs/bigi.git" | |
8300 | }, | |
8301 | "scripts": { | |
8302 | "browser-test": "mochify --wd -R spec", | |
8303 | "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js", | |
8304 | "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info", | |
8305 | "jshint": "jshint --config jshint.json lib/*.js ; true", | |
8306 | "test": "_mocha -- test/*.js", | |
8307 | "unit": "mocha" | |
8308 | }, | |
8309 | "testling": { | |
8310 | "browsers": [ | |
8311 | "ie/9..latest", | |
8312 | "firefox/latest", | |
8313 | "chrome/latest", | |
8314 | "safari/6.0..latest", | |
8315 | "iphone/6.0..latest", | |
8316 | "android-browser/4.2..latest" | |
8317 | ], | |
8318 | "files": "test/*.js", | |
8319 | "harness": "mocha" | |
8320 | }, | |
8321 | "version": "1.4.2" | |
8322 | } | |
8323 | ||
8324 | },{}],39:[function(require,module,exports){ | |
8325 | // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki | |
8326 | // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] | |
8327 | // NOTE: SIGHASH byte ignored AND restricted, truncate before use | |
8328 | ||
8329 | var Buffer = require('safe-buffer').Buffer | |
8330 | ||
8331 | function check (buffer) { | |
8332 | if (buffer.length < 8) return false | |
8333 | if (buffer.length > 72) return false | |
8334 | if (buffer[0] !== 0x30) return false | |
8335 | if (buffer[1] !== buffer.length - 2) return false | |
8336 | if (buffer[2] !== 0x02) return false | |
8337 | ||
8338 | var lenR = buffer[3] | |
8339 | if (lenR === 0) return false | |
8340 | if (5 + lenR >= buffer.length) return false | |
8341 | if (buffer[4 + lenR] !== 0x02) return false | |
8342 | ||
8343 | var lenS = buffer[5 + lenR] | |
8344 | if (lenS === 0) return false | |
8345 | if ((6 + lenR + lenS) !== buffer.length) return false | |
8346 | ||
8347 | if (buffer[4] & 0x80) return false | |
8348 | if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false | |
8349 | ||
8350 | if (buffer[lenR + 6] & 0x80) return false | |
8351 | if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false | |
8352 | return true | |
8353 | } | |
8354 | ||
8355 | function decode (buffer) { | |
8356 | if (buffer.length < 8) throw new Error('DER sequence length is too short') | |
8357 | if (buffer.length > 72) throw new Error('DER sequence length is too long') | |
8358 | if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') | |
8359 | if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') | |
8360 | if (buffer[2] !== 0x02) throw new Error('Expected DER integer') | |
8361 | ||
8362 | var lenR = buffer[3] | |
8363 | if (lenR === 0) throw new Error('R length is zero') | |
8364 | if (5 + lenR >= buffer.length) throw new Error('R length is too long') | |
8365 | if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') | |
8366 | ||
8367 | var lenS = buffer[5 + lenR] | |
8368 | if (lenS === 0) throw new Error('S length is zero') | |
8369 | if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') | |
8370 | ||
8371 | if (buffer[4] & 0x80) throw new Error('R value is negative') | |
8372 | if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') | |
8373 | ||
8374 | if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') | |
8375 | if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') | |
8376 | ||
8377 | // non-BIP66 - extract R, S values | |
8378 | return { | |
8379 | r: buffer.slice(4, 4 + lenR), | |
8380 | s: buffer.slice(6 + lenR) | |
8381 | } | |
8382 | } | |
8383 | ||
8384 | /* | |
8385 | * Expects r and s to be positive DER integers. | |
8386 | * | |
8387 | * The DER format uses the most significant bit as a sign bit (& 0x80). | |
8388 | * If the significant bit is set AND the integer is positive, a 0x00 is prepended. | |
8389 | * | |
8390 | * Examples: | |
8391 | * | |
8392 | * 0 => 0x00 | |
8393 | * 1 => 0x01 | |
8394 | * -1 => 0xff | |
8395 | * 127 => 0x7f | |
8396 | * -127 => 0x81 | |
8397 | * 128 => 0x0080 | |
8398 | * -128 => 0x80 | |
8399 | * 255 => 0x00ff | |
8400 | * -255 => 0xff01 | |
8401 | * 16300 => 0x3fac | |
8402 | * -16300 => 0xc054 | |
8403 | * 62300 => 0x00f35c | |
8404 | * -62300 => 0xff0ca4 | |
8405 | */ | |
8406 | function encode (r, s) { | |
8407 | var lenR = r.length | |
8408 | var lenS = s.length | |
8409 | if (lenR === 0) throw new Error('R length is zero') | |
8410 | if (lenS === 0) throw new Error('S length is zero') | |
8411 | if (lenR > 33) throw new Error('R length is too long') | |
8412 | if (lenS > 33) throw new Error('S length is too long') | |
8413 | if (r[0] & 0x80) throw new Error('R value is negative') | |
8414 | if (s[0] & 0x80) throw new Error('S value is negative') | |
8415 | if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') | |
8416 | if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') | |
8417 | ||
8418 | var signature = Buffer.allocUnsafe(6 + lenR + lenS) | |
8419 | ||
8420 | // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] | |
8421 | signature[0] = 0x30 | |
8422 | signature[1] = signature.length - 2 | |
8423 | signature[2] = 0x02 | |
8424 | signature[3] = r.length | |
8425 | r.copy(signature, 4) | |
8426 | signature[4 + lenR] = 0x02 | |
8427 | signature[5 + lenR] = s.length | |
8428 | s.copy(signature, 6 + lenR) | |
8429 | ||
8430 | return signature | |
8431 | } | |
8432 | ||
8433 | module.exports = { | |
8434 | check: check, | |
8435 | decode: decode, | |
8436 | encode: encode | |
8437 | } | |
8438 | ||
8439 | },{"safe-buffer":98}],40:[function(require,module,exports){ | |
8440 | module.exports={ | |
8441 | "OP_FALSE": 0, | |
8442 | "OP_0": 0, | |
8443 | "OP_PUSHDATA1": 76, | |
8444 | "OP_PUSHDATA2": 77, | |
8445 | "OP_PUSHDATA4": 78, | |
8446 | "OP_1NEGATE": 79, | |
8447 | "OP_RESERVED": 80, | |
8448 | "OP_1": 81, | |
8449 | "OP_TRUE": 81, | |
8450 | "OP_2": 82, | |
8451 | "OP_3": 83, | |
8452 | "OP_4": 84, | |
8453 | "OP_5": 85, | |
8454 | "OP_6": 86, | |
8455 | "OP_7": 87, | |
8456 | "OP_8": 88, | |
8457 | "OP_9": 89, | |
8458 | "OP_10": 90, | |
8459 | "OP_11": 91, | |
8460 | "OP_12": 92, | |
8461 | "OP_13": 93, | |
8462 | "OP_14": 94, | |
8463 | "OP_15": 95, | |
8464 | "OP_16": 96, | |
8465 | ||
8466 | "OP_NOP": 97, | |
8467 | "OP_VER": 98, | |
8468 | "OP_IF": 99, | |
8469 | "OP_NOTIF": 100, | |
8470 | "OP_VERIF": 101, | |
8471 | "OP_VERNOTIF": 102, | |
8472 | "OP_ELSE": 103, | |
8473 | "OP_ENDIF": 104, | |
8474 | "OP_VERIFY": 105, | |
8475 | "OP_RETURN": 106, | |
8476 | ||
8477 | "OP_TOALTSTACK": 107, | |
8478 | "OP_FROMALTSTACK": 108, | |
8479 | "OP_2DROP": 109, | |
8480 | "OP_2DUP": 110, | |
8481 | "OP_3DUP": 111, | |
8482 | "OP_2OVER": 112, | |
8483 | "OP_2ROT": 113, | |
8484 | "OP_2SWAP": 114, | |
8485 | "OP_IFDUP": 115, | |
8486 | "OP_DEPTH": 116, | |
8487 | "OP_DROP": 117, | |
8488 | "OP_DUP": 118, | |
8489 | "OP_NIP": 119, | |
8490 | "OP_OVER": 120, | |
8491 | "OP_PICK": 121, | |
8492 | "OP_ROLL": 122, | |
8493 | "OP_ROT": 123, | |
8494 | "OP_SWAP": 124, | |
8495 | "OP_TUCK": 125, | |
8496 | ||
8497 | "OP_CAT": 126, | |
8498 | "OP_SUBSTR": 127, | |
8499 | "OP_LEFT": 128, | |
8500 | "OP_RIGHT": 129, | |
8501 | "OP_SIZE": 130, | |
8502 | ||
8503 | "OP_INVERT": 131, | |
8504 | "OP_AND": 132, | |
8505 | "OP_OR": 133, | |
8506 | "OP_XOR": 134, | |
8507 | "OP_EQUAL": 135, | |
8508 | "OP_EQUALVERIFY": 136, | |
8509 | "OP_RESERVED1": 137, | |
8510 | "OP_RESERVED2": 138, | |
8511 | ||
8512 | "OP_1ADD": 139, | |
8513 | "OP_1SUB": 140, | |
8514 | "OP_2MUL": 141, | |
8515 | "OP_2DIV": 142, | |
8516 | "OP_NEGATE": 143, | |
8517 | "OP_ABS": 144, | |
8518 | "OP_NOT": 145, | |
8519 | "OP_0NOTEQUAL": 146, | |
8520 | "OP_ADD": 147, | |
8521 | "OP_SUB": 148, | |
8522 | "OP_MUL": 149, | |
8523 | "OP_DIV": 150, | |
8524 | "OP_MOD": 151, | |
8525 | "OP_LSHIFT": 152, | |
8526 | "OP_RSHIFT": 153, | |
8527 | ||
8528 | "OP_BOOLAND": 154, | |
8529 | "OP_BOOLOR": 155, | |
8530 | "OP_NUMEQUAL": 156, | |
8531 | "OP_NUMEQUALVERIFY": 157, | |
8532 | "OP_NUMNOTEQUAL": 158, | |
8533 | "OP_LESSTHAN": 159, | |
8534 | "OP_GREATERTHAN": 160, | |
8535 | "OP_LESSTHANOREQUAL": 161, | |
8536 | "OP_GREATERTHANOREQUAL": 162, | |
8537 | "OP_MIN": 163, | |
8538 | "OP_MAX": 164, | |
8539 | ||
8540 | "OP_WITHIN": 165, | |
8541 | ||
8542 | "OP_RIPEMD160": 166, | |
8543 | "OP_SHA1": 167, | |
8544 | "OP_SHA256": 168, | |
8545 | "OP_HASH160": 169, | |
8546 | "OP_HASH256": 170, | |
8547 | "OP_CODESEPARATOR": 171, | |
8548 | "OP_CHECKSIG": 172, | |
8549 | "OP_CHECKSIGVERIFY": 173, | |
8550 | "OP_CHECKMULTISIG": 174, | |
8551 | "OP_CHECKMULTISIGVERIFY": 175, | |
8552 | ||
8553 | "OP_NOP1": 176, | |
8554 | "OP_NOP2": 177, | |
8555 | "OP_CHECKLOCKTIMEVERIFY": 177, | |
8556 | ||
8557 | "OP_NOP3": 178, | |
8558 | "OP_NOP4": 179, | |
8559 | "OP_NOP5": 180, | |
8560 | "OP_NOP6": 181, | |
8561 | "OP_NOP7": 182, | |
8562 | "OP_NOP8": 183, | |
8563 | "OP_NOP9": 184, | |
8564 | "OP_NOP10": 185, | |
8565 | ||
8566 | "OP_PUBKEYHASH": 253, | |
8567 | "OP_PUBKEY": 254, | |
8568 | "OP_INVALIDOPCODE": 255 | |
8569 | } | |
8570 | ||
8571 | },{}],41:[function(require,module,exports){ | |
8572 | var OPS = require('./index.json') | |
8573 | ||
8574 | var map = {} | |
8575 | for (var op in OPS) { | |
8576 | var code = OPS[op] | |
8577 | map[code] = op | |
8578 | } | |
8579 | ||
8580 | module.exports = map | |
8581 | ||
8582 | },{"./index.json":40}],42:[function(require,module,exports){ | |
8583 | var Buffer = require('safe-buffer').Buffer | |
8584 | var bs58check = require('bs58check') | |
8585 | var bscript = require('./script') | |
8586 | var networks = require('./networks') | |
8587 | var typeforce = require('typeforce') | |
8588 | var types = require('./types') | |
8589 | ||
8590 | function fromBase58Check (address) { | |
8591 | var payload = bs58check.decode(address) | |
8592 | if (payload.length < 21) throw new TypeError(address + ' is too short') | |
8593 | if (payload.length > 21) throw new TypeError(address + ' is too long') | |
8594 | ||
8595 | var version = payload.readUInt8(0) | |
8596 | var hash = payload.slice(1) | |
8597 | ||
8598 | return { hash: hash, version: version } | |
8599 | } | |
8600 | ||
8601 | function toBase58Check (hash, version) { | |
8602 | typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments) | |
8603 | ||
8604 | var payload = Buffer.allocUnsafe(21) | |
8605 | payload.writeUInt8(version, 0) | |
8606 | hash.copy(payload, 1) | |
8607 | ||
8608 | return bs58check.encode(payload) | |
8609 | } | |
8610 | ||
8611 | function fromOutputScript (outputScript, network) { | |
8612 | network = network || networks.bitcoin | |
8613 | ||
8614 | if (bscript.pubKeyHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(3, 23), network.pubKeyHash) | |
8615 | if (bscript.scriptHash.output.check(outputScript)) return toBase58Check(bscript.compile(outputScript).slice(2, 22), network.scriptHash) | |
8616 | ||
8617 | throw new Error(bscript.toASM(outputScript) + ' has no matching Address') | |
8618 | } | |
8619 | ||
8620 | function toOutputScript (address, network) { | |
8621 | network = network || networks.bitcoin | |
8622 | ||
8623 | var decode = fromBase58Check(address) | |
8624 | if (decode.version === network.pubKeyHash) return bscript.pubKeyHash.output.encode(decode.hash) | |
8625 | if (decode.version === network.scriptHash) return bscript.scriptHash.output.encode(decode.hash) | |
8626 | ||
8627 | throw new Error(address + ' has no matching Script') | |
8628 | } | |
8629 | ||
8630 | module.exports = { | |
8631 | fromBase58Check: fromBase58Check, | |
8632 | fromOutputScript: fromOutputScript, | |
8633 | toBase58Check: toBase58Check, | |
8634 | toOutputScript: toOutputScript | |
8635 | } | |
8636 | ||
8637 | },{"./networks":51,"./script":52,"./types":78,"bs58check":80,"safe-buffer":98,"typeforce":109}],43:[function(require,module,exports){ | |
8638 | var Buffer = require('safe-buffer').Buffer | |
8639 | var bcrypto = require('./crypto') | |
8640 | var fastMerkleRoot = require('merkle-lib/fastRoot') | |
8641 | var typeforce = require('typeforce') | |
8642 | var types = require('./types') | |
8643 | var varuint = require('varuint-bitcoin') | |
8644 | ||
8645 | var Transaction = require('./transaction') | |
8646 | ||
8647 | function Block () { | |
8648 | this.version = 1 | |
8649 | this.prevHash = null | |
8650 | this.merkleRoot = null | |
8651 | this.timestamp = 0 | |
8652 | this.bits = 0 | |
8653 | this.nonce = 0 | |
8654 | } | |
8655 | ||
8656 | Block.fromBuffer = function (buffer) { | |
8657 | if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)') | |
8658 | ||
8659 | var offset = 0 | |
8660 | function readSlice (n) { | |
8661 | offset += n | |
8662 | return buffer.slice(offset - n, offset) | |
8663 | } | |
8664 | ||
8665 | function readUInt32 () { | |
8666 | var i = buffer.readUInt32LE(offset) | |
8667 | offset += 4 | |
8668 | return i | |
8669 | } | |
8670 | ||
8671 | function readInt32 () { | |
8672 | var i = buffer.readInt32LE(offset) | |
8673 | offset += 4 | |
8674 | return i | |
8675 | } | |
8676 | ||
8677 | var block = new Block() | |
8678 | block.version = readInt32() | |
8679 | block.prevHash = readSlice(32) | |
8680 | block.merkleRoot = readSlice(32) | |
8681 | block.timestamp = readUInt32() | |
8682 | block.bits = readUInt32() | |
8683 | block.nonce = readUInt32() | |
8684 | ||
8685 | if (buffer.length === 80) return block | |
8686 | ||
8687 | function readVarInt () { | |
8688 | var vi = varuint.decode(buffer, offset) | |
8689 | offset += varuint.decode.bytes | |
8690 | return vi | |
8691 | } | |
8692 | ||
8693 | function readTransaction () { | |
8694 | var tx = Transaction.fromBuffer(buffer.slice(offset), true) | |
8695 | offset += tx.byteLength() | |
8696 | return tx | |
8697 | } | |
8698 | ||
8699 | var nTransactions = readVarInt() | |
8700 | block.transactions = [] | |
8701 | ||
8702 | for (var i = 0; i < nTransactions; ++i) { | |
8703 | var tx = readTransaction() | |
8704 | block.transactions.push(tx) | |
8705 | } | |
8706 | ||
8707 | return block | |
8708 | } | |
8709 | ||
8710 | Block.prototype.byteLength = function (headersOnly) { | |
8711 | if (headersOnly || !this.transactions) return 80 | |
8712 | ||
8713 | return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) { | |
8714 | return a + x.byteLength() | |
8715 | }, 0) | |
8716 | } | |
8717 | ||
8718 | Block.fromHex = function (hex) { | |
8719 | return Block.fromBuffer(Buffer.from(hex, 'hex')) | |
8720 | } | |
8721 | ||
8722 | Block.prototype.getHash = function () { | |
8723 | return bcrypto.hash256(this.toBuffer(true)) | |
8724 | } | |
8725 | ||
8726 | Block.prototype.getId = function () { | |
8727 | return this.getHash().reverse().toString('hex') | |
8728 | } | |
8729 | ||
8730 | Block.prototype.getUTCDate = function () { | |
8731 | var date = new Date(0) // epoch | |
8732 | date.setUTCSeconds(this.timestamp) | |
8733 | ||
8734 | return date | |
8735 | } | |
8736 | ||
8737 | // TODO: buffer, offset compatibility | |
8738 | Block.prototype.toBuffer = function (headersOnly) { | |
8739 | var buffer = Buffer.allocUnsafe(this.byteLength(headersOnly)) | |
8740 | ||
8741 | var offset = 0 | |
8742 | function writeSlice (slice) { | |
8743 | slice.copy(buffer, offset) | |
8744 | offset += slice.length | |
8745 | } | |
8746 | ||
8747 | function writeInt32 (i) { | |
8748 | buffer.writeInt32LE(i, offset) | |
8749 | offset += 4 | |
8750 | } | |
8751 | function writeUInt32 (i) { | |
8752 | buffer.writeUInt32LE(i, offset) | |
8753 | offset += 4 | |
8754 | } | |
8755 | ||
8756 | writeInt32(this.version) | |
8757 | writeSlice(this.prevHash) | |
8758 | writeSlice(this.merkleRoot) | |
8759 | writeUInt32(this.timestamp) | |
8760 | writeUInt32(this.bits) | |
8761 | writeUInt32(this.nonce) | |
8762 | ||
8763 | if (headersOnly || !this.transactions) return buffer | |
8764 | ||
8765 | varuint.encode(this.transactions.length, buffer, offset) | |
8766 | offset += varuint.encode.bytes | |
8767 | ||
8768 | this.transactions.forEach(function (tx) { | |
8769 | var txSize = tx.byteLength() // TODO: extract from toBuffer? | |
8770 | tx.toBuffer(buffer, offset) | |
8771 | offset += txSize | |
8772 | }) | |
8773 | ||
8774 | return buffer | |
8775 | } | |
8776 | ||
8777 | Block.prototype.toHex = function (headersOnly) { | |
8778 | return this.toBuffer(headersOnly).toString('hex') | |
8779 | } | |
8780 | ||
8781 | Block.calculateTarget = function (bits) { | |
8782 | var exponent = ((bits & 0xff000000) >> 24) - 3 | |
8783 | var mantissa = bits & 0x007fffff | |
8784 | var target = Buffer.alloc(32, 0) | |
8785 | target.writeUInt32BE(mantissa, 28 - exponent) | |
8786 | return target | |
8787 | } | |
8788 | ||
8789 | Block.calculateMerkleRoot = function (transactions) { | |
8790 | typeforce([{ getHash: types.Function }], transactions) | |
8791 | if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions') | |
8792 | ||
8793 | var hashes = transactions.map(function (transaction) { | |
8794 | return transaction.getHash() | |
8795 | }) | |
8796 | ||
8797 | return fastMerkleRoot(hashes, bcrypto.hash256) | |
8798 | } | |
8799 | ||
8800 | Block.prototype.checkMerkleRoot = function () { | |
8801 | if (!this.transactions) return false | |
8802 | ||
8803 | var actualMerkleRoot = Block.calculateMerkleRoot(this.transactions) | |
8804 | return this.merkleRoot.compare(actualMerkleRoot) === 0 | |
8805 | } | |
8806 | ||
8807 | Block.prototype.checkProofOfWork = function () { | |
8808 | var hash = this.getHash().reverse() | |
8809 | var target = Block.calculateTarget(this.bits) | |
8810 | ||
8811 | return hash.compare(target) <= 0 | |
8812 | } | |
8813 | ||
8814 | module.exports = Block | |
8815 | ||
8816 | },{"./crypto":45,"./transaction":76,"./types":78,"merkle-lib/fastRoot":94,"safe-buffer":98,"typeforce":109,"varuint-bitcoin":111}],44:[function(require,module,exports){ | |
8817 | var pushdata = require('pushdata-bitcoin') | |
8818 | var varuint = require('varuint-bitcoin') | |
8819 | ||
8820 | // https://github.com/feross/buffer/blob/master/index.js#L1127 | |
8821 | function verifuint (value, max) { | |
8822 | if (typeof value !== 'number') throw new Error('cannot write a non-number as a number') | |
8823 | if (value < 0) throw new Error('specified a negative value for writing an unsigned value') | |
8824 | if (value > max) throw new Error('RangeError: value out of range') | |
8825 | if (Math.floor(value) !== value) throw new Error('value has a fractional component') | |
8826 | } | |
8827 | ||
8828 | function readUInt64LE (buffer, offset) { | |
8829 | var a = buffer.readUInt32LE(offset) | |
8830 | var b = buffer.readUInt32LE(offset + 4) | |
8831 | b *= 0x100000000 | |
8832 | ||
8833 | verifuint(b + a, 0x001fffffffffffff) | |
8834 | ||
8835 | return b + a | |
8836 | } | |
8837 | ||
8838 | function writeUInt64LE (buffer, value, offset) { | |
8839 | verifuint(value, 0x001fffffffffffff) | |
8840 | ||
8841 | buffer.writeInt32LE(value & -1, offset) | |
8842 | buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4) | |
8843 | return offset + 8 | |
8844 | } | |
8845 | ||
8846 | // TODO: remove in 4.0.0? | |
8847 | function readVarInt (buffer, offset) { | |
8848 | var result = varuint.decode(buffer, offset) | |
8849 | ||
8850 | return { | |
8851 | number: result, | |
8852 | size: varuint.decode.bytes | |
8853 | } | |
8854 | } | |
8855 | ||
8856 | // TODO: remove in 4.0.0? | |
8857 | function writeVarInt (buffer, number, offset) { | |
8858 | varuint.encode(number, buffer, offset) | |
8859 | return varuint.encode.bytes | |
8860 | } | |
8861 | ||
8862 | module.exports = { | |
8863 | pushDataSize: pushdata.encodingLength, | |
8864 | readPushDataInt: pushdata.decode, | |
8865 | readUInt64LE: readUInt64LE, | |
8866 | readVarInt: readVarInt, | |
8867 | varIntBuffer: varuint.encode, | |
8868 | varIntSize: varuint.encodingLength, | |
8869 | writePushDataInt: pushdata.encode, | |
8870 | writeUInt64LE: writeUInt64LE, | |
8871 | writeVarInt: writeVarInt | |
8872 | } | |
8873 | ||
8874 | },{"pushdata-bitcoin":95,"varuint-bitcoin":111}],45:[function(require,module,exports){ | |
8875 | var createHash = require('create-hash') | |
8876 | ||
8877 | function ripemd160 (buffer) { | |
8878 | return createHash('rmd160').update(buffer).digest() | |
8879 | } | |
8880 | ||
8881 | function sha1 (buffer) { | |
8882 | return createHash('sha1').update(buffer).digest() | |
8883 | } | |
8884 | ||
8885 | function sha256 (buffer) { | |
8886 | return createHash('sha256').update(buffer).digest() | |
8887 | } | |
8888 | ||
8889 | function hash160 (buffer) { | |
8890 | return ripemd160(sha256(buffer)) | |
8891 | } | |
8892 | ||
8893 | function hash256 (buffer) { | |
8894 | return sha256(sha256(buffer)) | |
8895 | } | |
8896 | ||
8897 | module.exports = { | |
8898 | hash160: hash160, | |
8899 | hash256: hash256, | |
8900 | ripemd160: ripemd160, | |
8901 | sha1: sha1, | |
8902 | sha256: sha256 | |
8903 | } | |
8904 | ||
8905 | },{"create-hash":82}],46:[function(require,module,exports){ | |
8906 | var Buffer = require('safe-buffer').Buffer | |
8907 | var createHmac = require('create-hmac') | |
8908 | var typeforce = require('typeforce') | |
8909 | var types = require('./types') | |
8910 | ||
8911 | var BigInteger = require('bigi') | |
8912 | var ECSignature = require('./ecsignature') | |
8913 | ||
8914 | var ZERO = Buffer.alloc(1, 0) | |
8915 | var ONE = Buffer.alloc(1, 1) | |
8916 | ||
8917 | var ecurve = require('ecurve') | |
8918 | var secp256k1 = ecurve.getCurveByName('secp256k1') | |
8919 | ||
8920 | // https://tools.ietf.org/html/rfc6979#section-3.2 | |
8921 | function deterministicGenerateK (hash, x, checkSig) { | |
8922 | typeforce(types.tuple( | |
8923 | types.Hash256bit, | |
8924 | types.Buffer256bit, | |
8925 | types.Function | |
8926 | ), arguments) | |
8927 | ||
8928 | // Step A, ignored as hash already provided | |
8929 | // Step B | |
8930 | // Step C | |
8931 | var k = Buffer.alloc(32, 0) | |
8932 | var v = Buffer.alloc(32, 1) | |
8933 | ||
8934 | // Step D | |
8935 | k = createHmac('sha256', k) | |
8936 | .update(v) | |
8937 | .update(ZERO) | |
8938 | .update(x) | |
8939 | .update(hash) | |
8940 | .digest() | |
8941 | ||
8942 | // Step E | |
8943 | v = createHmac('sha256', k).update(v).digest() | |
8944 | ||
8945 | // Step F | |
8946 | k = createHmac('sha256', k) | |
8947 | .update(v) | |
8948 | .update(ONE) | |
8949 | .update(x) | |
8950 | .update(hash) | |
8951 | .digest() | |
8952 | ||
8953 | // Step G | |
8954 | v = createHmac('sha256', k).update(v).digest() | |
8955 | ||
8956 | // Step H1/H2a, ignored as tlen === qlen (256 bit) | |
8957 | // Step H2b | |
8958 | v = createHmac('sha256', k).update(v).digest() | |
8959 | ||
8960 | var T = BigInteger.fromBuffer(v) | |
8961 | ||
8962 | // Step H3, repeat until T is within the interval [1, n - 1] and is suitable for ECDSA | |
8963 | while (T.signum() <= 0 || T.compareTo(secp256k1.n) >= 0 || !checkSig(T)) { | |
8964 | k = createHmac('sha256', k) | |
8965 | .update(v) | |
8966 | .update(ZERO) | |
8967 | .digest() | |
8968 | ||
8969 | v = createHmac('sha256', k).update(v).digest() | |
8970 | ||
8971 | // Step H1/H2a, again, ignored as tlen === qlen (256 bit) | |
8972 | // Step H2b again | |
8973 | v = createHmac('sha256', k).update(v).digest() | |
8974 | T = BigInteger.fromBuffer(v) | |
8975 | } | |
8976 | ||
8977 | return T | |
8978 | } | |
8979 | ||
8980 | var N_OVER_TWO = secp256k1.n.shiftRight(1) | |
8981 | ||
8982 | function sign (hash, d) { | |
8983 | typeforce(types.tuple(types.Hash256bit, types.BigInt), arguments) | |
8984 | ||
8985 | var x = d.toBuffer(32) | |
8986 | var e = BigInteger.fromBuffer(hash) | |
8987 | var n = secp256k1.n | |
8988 | var G = secp256k1.G | |
8989 | ||
8990 | var r, s | |
8991 | deterministicGenerateK(hash, x, function (k) { | |
8992 | var Q = G.multiply(k) | |
8993 | ||
8994 | if (secp256k1.isInfinity(Q)) return false | |
8995 | ||
8996 | r = Q.affineX.mod(n) | |
8997 | if (r.signum() === 0) return false | |
8998 | ||
8999 | s = k.modInverse(n).multiply(e.add(d.multiply(r))).mod(n) | |
9000 | if (s.signum() === 0) return false | |
9001 | ||
9002 | return true | |
9003 | }) | |
9004 | ||
9005 | // enforce low S values, see bip62: 'low s values in signatures' | |
9006 | if (s.compareTo(N_OVER_TWO) > 0) { | |
9007 | s = n.subtract(s) | |
9008 | } | |
9009 | ||
9010 | return new ECSignature(r, s) | |
9011 | } | |
9012 | ||
9013 | function verify (hash, signature, Q) { | |
9014 | typeforce(types.tuple( | |
9015 | types.Hash256bit, | |
9016 | types.ECSignature, | |
9017 | types.ECPoint | |
9018 | ), arguments) | |
9019 | ||
9020 | var n = secp256k1.n | |
9021 | var G = secp256k1.G | |
9022 | ||
9023 | var r = signature.r | |
9024 | var s = signature.s | |
9025 | ||
9026 | // 1.4.1 Enforce r and s are both integers in the interval [1, n − 1] | |
9027 | if (r.signum() <= 0 || r.compareTo(n) >= 0) return false | |
9028 | if (s.signum() <= 0 || s.compareTo(n) >= 0) return false | |
9029 | ||
9030 | // 1.4.2 H = Hash(M), already done by the user | |
9031 | // 1.4.3 e = H | |
9032 | var e = BigInteger.fromBuffer(hash) | |
9033 | ||
9034 | // Compute s^-1 | |
9035 | var sInv = s.modInverse(n) | |
9036 | ||
9037 | // 1.4.4 Compute u1 = es^−1 mod n | |
9038 | // u2 = rs^−1 mod n | |
9039 | var u1 = e.multiply(sInv).mod(n) | |
9040 | var u2 = r.multiply(sInv).mod(n) | |
9041 | ||
9042 | // 1.4.5 Compute R = (xR, yR) | |
9043 | // R = u1G + u2Q | |
9044 | var R = G.multiplyTwo(u1, Q, u2) | |
9045 | ||
9046 | // 1.4.5 (cont.) Enforce R is not at infinity | |
9047 | if (secp256k1.isInfinity(R)) return false | |
9048 | ||
9049 | // 1.4.6 Convert the field element R.x to an integer | |
9050 | var xR = R.affineX | |
9051 | ||
9052 | // 1.4.7 Set v = xR mod n | |
9053 | var v = xR.mod(n) | |
9054 | ||
9055 | // 1.4.8 If v = r, output "valid", and if v != r, output "invalid" | |
9056 | return v.equals(r) | |
9057 | } | |
9058 | ||
9059 | module.exports = { | |
9060 | deterministicGenerateK: deterministicGenerateK, | |
9061 | sign: sign, | |
9062 | verify: verify, | |
9063 | ||
9064 | // TODO: remove | |
9065 | __curve: secp256k1 | |
9066 | } | |
9067 | ||
9068 | },{"./ecsignature":48,"./types":78,"bigi":37,"create-hmac":85,"ecurve":89,"safe-buffer":98,"typeforce":109}],47:[function(require,module,exports){ | |
9069 | var baddress = require('./address') | |
9070 | var bcrypto = require('./crypto') | |
9071 | var ecdsa = require('./ecdsa') | |
9072 | var randomBytes = require('randombytes') | |
9073 | var typeforce = require('typeforce') | |
9074 | var types = require('./types') | |
9075 | var wif = require('wif') | |
9076 | ||
9077 | var NETWORKS = require('./networks') | |
9078 | var BigInteger = require('bigi') | |
9079 | ||
9080 | var ecurve = require('ecurve') | |
9081 | var secp256k1 = ecdsa.__curve | |
9082 | ||
9083 | function ECPair (d, Q, options) { | |
9084 | if (options) { | |
9085 | typeforce({ | |
9086 | compressed: types.maybe(types.Boolean), | |
9087 | network: types.maybe(types.Network) | |
9088 | }, options) | |
9089 | } | |
9090 | ||
9091 | options = options || {} | |
9092 | ||
9093 | if (d) { | |
9094 | if (d.signum() <= 0) throw new Error('Private key must be greater than 0') | |
9095 | if (d.compareTo(secp256k1.n) >= 0) throw new Error('Private key must be less than the curve order') | |
9096 | if (Q) throw new TypeError('Unexpected publicKey parameter') | |
9097 | ||
9098 | this.d = d | |
9099 | } else { | |
9100 | typeforce(types.ECPoint, Q) | |
9101 | ||
9102 | this.__Q = Q | |
9103 | } | |
9104 | ||
9105 | this.compressed = options.compressed === undefined ? true : options.compressed | |
9106 | this.network = options.network || NETWORKS.bitcoin | |
9107 | } | |
9108 | ||
9109 | Object.defineProperty(ECPair.prototype, 'Q', { | |
9110 | get: function () { | |
9111 | if (!this.__Q && this.d) { | |
9112 | this.__Q = secp256k1.G.multiply(this.d) | |
9113 | } | |
9114 | ||
9115 | return this.__Q | |
9116 | } | |
9117 | }) | |
9118 | ||
9119 | ECPair.fromPublicKeyBuffer = function (buffer, network) { | |
9120 | var Q = ecurve.Point.decodeFrom(secp256k1, buffer) | |
9121 | ||
9122 | return new ECPair(null, Q, { | |
9123 | compressed: Q.compressed, | |
9124 | network: network | |
9125 | }) | |
9126 | } | |
9127 | ||
9128 | ECPair.fromWIF = function (string, network) { | |
9129 | var decoded = wif.decode(string) | |
9130 | var version = decoded.version | |
9131 | ||
9132 | // list of networks? | |
9133 | if (types.Array(network)) { | |
9134 | network = network.filter(function (x) { | |
9135 | return version === x.wif | |
9136 | }).pop() | |
9137 | ||
9138 | if (!network) throw new Error('Unknown network version') | |
9139 | ||
9140 | // otherwise, assume a network object (or default to bitcoin) | |
9141 | } else { | |
9142 | network = network || NETWORKS.bitcoin | |
9143 | ||
9144 | if (version !== network.wif) throw new Error('Invalid network version') | |
9145 | } | |
9146 | ||
9147 | var d = BigInteger.fromBuffer(decoded.privateKey) | |
9148 | ||
9149 | return new ECPair(d, null, { | |
9150 | compressed: decoded.compressed, | |
9151 | network: network | |
9152 | }) | |
9153 | } | |
9154 | ||
9155 | ECPair.makeRandom = function (options) { | |
9156 | options = options || {} | |
9157 | ||
9158 | var rng = options.rng || randomBytes | |
9159 | ||
9160 | var d | |
9161 | do { | |
9162 | var buffer = rng(32) | |
9163 | typeforce(types.Buffer256bit, buffer) | |
9164 | ||
9165 | d = BigInteger.fromBuffer(buffer) | |
9166 | } while (d.signum() <= 0 || d.compareTo(secp256k1.n) >= 0) | |
9167 | ||
9168 | return new ECPair(d, null, options) | |
9169 | } | |
9170 | ||
9171 | ECPair.prototype.getAddress = function () { | |
9172 | return baddress.toBase58Check(bcrypto.hash160(this.getPublicKeyBuffer()), this.getNetwork().pubKeyHash) | |
9173 | } | |
9174 | ||
9175 | ECPair.prototype.getNetwork = function () { | |
9176 | return this.network | |
9177 | } | |
9178 | ||
9179 | ECPair.prototype.getPublicKeyBuffer = function () { | |
9180 | return this.Q.getEncoded(this.compressed) | |
9181 | } | |
9182 | ||
9183 | ECPair.prototype.sign = function (hash) { | |
9184 | if (!this.d) throw new Error('Missing private key') | |
9185 | ||
9186 | return ecdsa.sign(hash, this.d) | |
9187 | } | |
9188 | ||
9189 | ECPair.prototype.toWIF = function () { | |
9190 | if (!this.d) throw new Error('Missing private key') | |
9191 | ||
9192 | return wif.encode(this.network.wif, this.d.toBuffer(32), this.compressed) | |
9193 | } | |
9194 | ||
9195 | ECPair.prototype.verify = function (hash, signature) { | |
9196 | return ecdsa.verify(hash, signature, this.Q) | |
9197 | } | |
9198 | ||
9199 | module.exports = ECPair | |
9200 | ||
9201 | },{"./address":42,"./crypto":45,"./ecdsa":46,"./networks":51,"./types":78,"bigi":37,"ecurve":89,"randombytes":96,"typeforce":109,"wif":112}],48:[function(require,module,exports){ | |
9202 | (function (Buffer){ | |
9203 | var bip66 = require('bip66') | |
9204 | var typeforce = require('typeforce') | |
9205 | var types = require('./types') | |
9206 | ||
9207 | var BigInteger = require('bigi') | |
9208 | ||
9209 | function ECSignature (r, s) { | |
9210 | typeforce(types.tuple(types.BigInt, types.BigInt), arguments) | |
9211 | ||
9212 | this.r = r | |
9213 | this.s = s | |
9214 | } | |
9215 | ||
9216 | ECSignature.parseCompact = function (buffer) { | |
9217 | if (buffer.length !== 65) throw new Error('Invalid signature length') | |
9218 | ||
9219 | var flagByte = buffer.readUInt8(0) - 27 | |
9220 | if (flagByte !== (flagByte & 7)) throw new Error('Invalid signature parameter') | |
9221 | ||
9222 | var compressed = !!(flagByte & 4) | |
9223 | var recoveryParam = flagByte & 3 | |
9224 | ||
9225 | var r = BigInteger.fromBuffer(buffer.slice(1, 33)) | |
9226 | var s = BigInteger.fromBuffer(buffer.slice(33)) | |
9227 | ||
9228 | return { | |
9229 | compressed: compressed, | |
9230 | i: recoveryParam, | |
9231 | signature: new ECSignature(r, s) | |
9232 | } | |
9233 | } | |
9234 | ||
9235 | ECSignature.fromDER = function (buffer) { | |
9236 | var decode = bip66.decode(buffer) | |
9237 | var r = BigInteger.fromDERInteger(decode.r) | |
9238 | var s = BigInteger.fromDERInteger(decode.s) | |
9239 | ||
9240 | return new ECSignature(r, s) | |
9241 | } | |
9242 | ||
9243 | // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) | |
9244 | ECSignature.parseScriptSignature = function (buffer) { | |
9245 | var hashType = buffer.readUInt8(buffer.length - 1) | |
9246 | var hashTypeMod = hashType & ~0x80 | |
9247 | ||
9248 | if (hashTypeMod <= 0x00 || hashTypeMod >= 0x04) throw new Error('Invalid hashType ' + hashType) | |
9249 | ||
9250 | return { | |
9251 | signature: ECSignature.fromDER(buffer.slice(0, -1)), | |
9252 | hashType: hashType | |
9253 | } | |
9254 | } | |
9255 | ||
9256 | ECSignature.prototype.toCompact = function (i, compressed) { | |
9257 | if (compressed) { | |
9258 | i += 4 | |
9259 | } | |
9260 | ||
9261 | i += 27 | |
9262 | ||
9263 | var buffer = Buffer.alloc(65) | |
9264 | buffer.writeUInt8(i, 0) | |
9265 | this.r.toBuffer(32).copy(buffer, 1) | |
9266 | this.s.toBuffer(32).copy(buffer, 33) | |
9267 | ||
9268 | return buffer | |
9269 | } | |
9270 | ||
9271 | ECSignature.prototype.toDER = function () { | |
9272 | var r = Buffer.from(this.r.toDERInteger()) | |
9273 | var s = Buffer.from(this.s.toDERInteger()) | |
9274 | ||
9275 | return bip66.encode(r, s) | |
9276 | } | |
9277 | ||
9278 | ECSignature.prototype.toScriptSignature = function (hashType) { | |
9279 | var hashTypeMod = hashType & ~0x80 | |
9280 | if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType) | |
9281 | ||
9282 | var hashTypeBuffer = Buffer.alloc(1) | |
9283 | hashTypeBuffer.writeUInt8(hashType, 0) | |
9284 | ||
9285 | return Buffer.concat([this.toDER(), hashTypeBuffer]) | |
9286 | } | |
9287 | ||
9288 | module.exports = ECSignature | |
9289 | ||
9290 | }).call(this,require("buffer").Buffer) | |
9291 | },{"./types":78,"bigi":37,"bip66":39,"buffer":4,"typeforce":109}],49:[function(require,module,exports){ | |
9292 | var Buffer = require('safe-buffer').Buffer | |
9293 | var base58check = require('bs58check') | |
9294 | var bcrypto = require('./crypto') | |
9295 | var createHmac = require('create-hmac') | |
9296 | var typeforce = require('typeforce') | |
9297 | var types = require('./types') | |
9298 | var NETWORKS = require('./networks') | |
9299 | ||
9300 | var BigInteger = require('bigi') | |
9301 | var ECPair = require('./ecpair') | |
9302 | ||
9303 | var ecurve = require('ecurve') | |
9304 | var curve = ecurve.getCurveByName('secp256k1') | |
9305 | ||
9306 | function HDNode (keyPair, chainCode) { | |
9307 | typeforce(types.tuple('ECPair', types.Buffer256bit), arguments) | |
9308 | ||
9309 | if (!keyPair.compressed) throw new TypeError('BIP32 only allows compressed keyPairs') | |
9310 | ||
9311 | this.keyPair = keyPair | |
9312 | this.chainCode = chainCode | |
9313 | this.depth = 0 | |
9314 | this.index = 0 | |
9315 | this.parentFingerprint = 0x00000000 | |
9316 | } | |
9317 | ||
9318 | HDNode.HIGHEST_BIT = 0x80000000 | |
9319 | HDNode.LENGTH = 78 | |
9320 | HDNode.MASTER_SECRET = Buffer.from('Bitcoin seed', 'utf8') | |
9321 | ||
9322 | HDNode.fromSeedBuffer = function (seed, network) { | |
9323 | typeforce(types.tuple(types.Buffer, types.maybe(types.Network)), arguments) | |
9324 | ||
9325 | if (seed.length < 16) throw new TypeError('Seed should be at least 128 bits') | |
9326 | if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits') | |
9327 | ||
9328 | var I = createHmac('sha512', HDNode.MASTER_SECRET).update(seed).digest() | |
9329 | var IL = I.slice(0, 32) | |
9330 | var IR = I.slice(32) | |
9331 | ||
9332 | // In case IL is 0 or >= n, the master key is invalid | |
9333 | // This is handled by the ECPair constructor | |
9334 | var pIL = BigInteger.fromBuffer(IL) | |
9335 | var keyPair = new ECPair(pIL, null, { | |
9336 | network: network | |
9337 | }) | |
9338 | ||
9339 | return new HDNode(keyPair, IR) | |
9340 | } | |
9341 | ||
9342 | HDNode.fromSeedHex = function (hex, network) { | |
9343 | return HDNode.fromSeedBuffer(Buffer.from(hex, 'hex'), network) | |
9344 | } | |
9345 | ||
9346 | HDNode.fromBase58 = function (string, networks) { | |
9347 | var buffer = base58check.decode(string) | |
9348 | if (buffer.length !== 78) throw new Error('Invalid buffer length') | |
9349 | ||
9350 | // 4 bytes: version bytes | |
9351 | var version = buffer.readUInt32BE(0) | |
9352 | var network | |
9353 | ||
9354 | // list of networks? | |
9355 | if (Array.isArray(networks)) { | |
9356 | network = networks.filter(function (x) { | |
9357 | return version === x.bip32.private || | |
9358 | version === x.bip32.public | |
9359 | }).pop() | |
9360 | ||
9361 | if (!network) throw new Error('Unknown network version') | |
9362 | ||
9363 | // otherwise, assume a network object (or default to bitcoin) | |
9364 | } else { | |
9365 | network = networks || NETWORKS.bitcoin | |
9366 | } | |
9367 | ||
9368 | if (version !== network.bip32.private && | |
9369 | version !== network.bip32.public) throw new Error('Invalid network version') | |
9370 | ||
9371 | // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... | |
9372 | var depth = buffer[4] | |
9373 | ||
9374 | // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) | |
9375 | var parentFingerprint = buffer.readUInt32BE(5) | |
9376 | if (depth === 0) { | |
9377 | if (parentFingerprint !== 0x00000000) throw new Error('Invalid parent fingerprint') | |
9378 | } | |
9379 | ||
9380 | // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. | |
9381 | // This is encoded in MSB order. (0x00000000 if master key) | |
9382 | var index = buffer.readUInt32BE(9) | |
9383 | if (depth === 0 && index !== 0) throw new Error('Invalid index') | |
9384 | ||
9385 | // 32 bytes: the chain code | |
9386 | var chainCode = buffer.slice(13, 45) | |
9387 | var keyPair | |
9388 | ||
9389 | // 33 bytes: private key data (0x00 + k) | |
9390 | if (version === network.bip32.private) { | |
9391 | if (buffer.readUInt8(45) !== 0x00) throw new Error('Invalid private key') | |
9392 | ||
9393 | var d = BigInteger.fromBuffer(buffer.slice(46, 78)) | |
9394 | keyPair = new ECPair(d, null, { network: network }) | |
9395 | ||
9396 | // 33 bytes: public key data (0x02 + X or 0x03 + X) | |
9397 | } else { | |
9398 | var Q = ecurve.Point.decodeFrom(curve, buffer.slice(45, 78)) | |
9399 | // Q.compressed is assumed, if somehow this assumption is broken, `new HDNode` will throw | |
9400 | ||
9401 | // Verify that the X coordinate in the public point corresponds to a point on the curve. | |
9402 | // If not, the extended public key is invalid. | |
9403 | curve.validate(Q) | |
9404 | ||
9405 | keyPair = new ECPair(null, Q, { network: network }) | |
9406 | } | |
9407 | ||
9408 | var hd = new HDNode(keyPair, chainCode) | |
9409 | hd.depth = depth | |
9410 | hd.index = index | |
9411 | hd.parentFingerprint = parentFingerprint | |
9412 | ||
9413 | return hd | |
9414 | } | |
9415 | ||
9416 | HDNode.prototype.getAddress = function () { | |
9417 | return this.keyPair.getAddress() | |
9418 | } | |
9419 | ||
9420 | HDNode.prototype.getIdentifier = function () { | |
9421 | return bcrypto.hash160(this.keyPair.getPublicKeyBuffer()) | |
9422 | } | |
9423 | ||
9424 | HDNode.prototype.getFingerprint = function () { | |
9425 | return this.getIdentifier().slice(0, 4) | |
9426 | } | |
9427 | ||
9428 | HDNode.prototype.getNetwork = function () { | |
9429 | return this.keyPair.getNetwork() | |
9430 | } | |
9431 | ||
9432 | HDNode.prototype.getPublicKeyBuffer = function () { | |
9433 | return this.keyPair.getPublicKeyBuffer() | |
9434 | } | |
9435 | ||
9436 | HDNode.prototype.neutered = function () { | |
9437 | var neuteredKeyPair = new ECPair(null, this.keyPair.Q, { | |
9438 | network: this.keyPair.network | |
9439 | }) | |
9440 | ||
9441 | var neutered = new HDNode(neuteredKeyPair, this.chainCode) | |
9442 | neutered.depth = this.depth | |
9443 | neutered.index = this.index | |
9444 | neutered.parentFingerprint = this.parentFingerprint | |
9445 | ||
9446 | return neutered | |
9447 | } | |
9448 | ||
9449 | HDNode.prototype.sign = function (hash) { | |
9450 | return this.keyPair.sign(hash) | |
9451 | } | |
9452 | ||
9453 | HDNode.prototype.verify = function (hash, signature) { | |
9454 | return this.keyPair.verify(hash, signature) | |
9455 | } | |
9456 | ||
9457 | HDNode.prototype.toBase58 = function (__isPrivate) { | |
9458 | if (__isPrivate !== undefined) throw new TypeError('Unsupported argument in 2.0.0') | |
9459 | ||
9460 | // Version | |
9461 | var network = this.keyPair.network | |
9462 | var version = (!this.isNeutered()) ? network.bip32.private : network.bip32.public | |
9463 | var buffer = Buffer.allocUnsafe(78) | |
9464 | ||
9465 | // 4 bytes: version bytes | |
9466 | buffer.writeUInt32BE(version, 0) | |
9467 | ||
9468 | // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... | |
9469 | buffer.writeUInt8(this.depth, 4) | |
9470 | ||
9471 | // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) | |
9472 | buffer.writeUInt32BE(this.parentFingerprint, 5) | |
9473 | ||
9474 | // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. | |
9475 | // This is encoded in big endian. (0x00000000 if master key) | |
9476 | buffer.writeUInt32BE(this.index, 9) | |
9477 | ||
9478 | // 32 bytes: the chain code | |
9479 | this.chainCode.copy(buffer, 13) | |
9480 | ||
9481 | // 33 bytes: the public key or private key data | |
9482 | if (!this.isNeutered()) { | |
9483 | // 0x00 + k for private keys | |
9484 | buffer.writeUInt8(0, 45) | |
9485 | this.keyPair.d.toBuffer(32).copy(buffer, 46) | |
9486 | ||
9487 | // 33 bytes: the public key | |
9488 | } else { | |
9489 | // X9.62 encoding for public keys | |
9490 | this.keyPair.getPublicKeyBuffer().copy(buffer, 45) | |
9491 | } | |
9492 | ||
9493 | return base58check.encode(buffer) | |
9494 | } | |
9495 | ||
9496 | // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions | |
9497 | HDNode.prototype.derive = function (index) { | |
9498 | typeforce(types.UInt32, index) | |
9499 | ||
9500 | var isHardened = index >= HDNode.HIGHEST_BIT | |
9501 | var data = Buffer.allocUnsafe(37) | |
9502 | ||
9503 | // Hardened child | |
9504 | if (isHardened) { | |
9505 | if (this.isNeutered()) throw new TypeError('Could not derive hardened child key') | |
9506 | ||
9507 | // data = 0x00 || ser256(kpar) || ser32(index) | |
9508 | data[0] = 0x00 | |
9509 | this.keyPair.d.toBuffer(32).copy(data, 1) | |
9510 | data.writeUInt32BE(index, 33) | |
9511 | ||
9512 | // Normal child | |
9513 | } else { | |
9514 | // data = serP(point(kpar)) || ser32(index) | |
9515 | // = serP(Kpar) || ser32(index) | |
9516 | this.keyPair.getPublicKeyBuffer().copy(data, 0) | |
9517 | data.writeUInt32BE(index, 33) | |
9518 | } | |
9519 | ||
9520 | var I = createHmac('sha512', this.chainCode).update(data).digest() | |
9521 | var IL = I.slice(0, 32) | |
9522 | var IR = I.slice(32) | |
9523 | ||
9524 | var pIL = BigInteger.fromBuffer(IL) | |
9525 | ||
9526 | // In case parse256(IL) >= n, proceed with the next value for i | |
9527 | if (pIL.compareTo(curve.n) >= 0) { | |
9528 | return this.derive(index + 1) | |
9529 | } | |
9530 | ||
9531 | // Private parent key -> private child key | |
9532 | var derivedKeyPair | |
9533 | if (!this.isNeutered()) { | |
9534 | // ki = parse256(IL) + kpar (mod n) | |
9535 | var ki = pIL.add(this.keyPair.d).mod(curve.n) | |
9536 | ||
9537 | // In case ki == 0, proceed with the next value for i | |
9538 | if (ki.signum() === 0) { | |
9539 | return this.derive(index + 1) | |
9540 | } | |
9541 | ||
9542 | derivedKeyPair = new ECPair(ki, null, { | |
9543 | network: this.keyPair.network | |
9544 | }) | |
9545 | ||
9546 | // Public parent key -> public child key | |
9547 | } else { | |
9548 | // Ki = point(parse256(IL)) + Kpar | |
9549 | // = G*IL + Kpar | |
9550 | var Ki = curve.G.multiply(pIL).add(this.keyPair.Q) | |
9551 | ||
9552 | // In case Ki is the point at infinity, proceed with the next value for i | |
9553 | if (curve.isInfinity(Ki)) { | |
9554 | return this.derive(index + 1) | |
9555 | } | |
9556 | ||
9557 | derivedKeyPair = new ECPair(null, Ki, { | |
9558 | network: this.keyPair.network | |
9559 | }) | |
9560 | } | |
9561 | ||
9562 | var hd = new HDNode(derivedKeyPair, IR) | |
9563 | hd.depth = this.depth + 1 | |
9564 | hd.index = index | |
9565 | hd.parentFingerprint = this.getFingerprint().readUInt32BE(0) | |
9566 | ||
9567 | return hd | |
9568 | } | |
9569 | ||
9570 | HDNode.prototype.deriveHardened = function (index) { | |
9571 | typeforce(types.UInt31, index) | |
9572 | ||
9573 | // Only derives hardened private keys by default | |
9574 | return this.derive(index + HDNode.HIGHEST_BIT) | |
9575 | } | |
9576 | ||
9577 | // Private === not neutered | |
9578 | // Public === neutered | |
9579 | HDNode.prototype.isNeutered = function () { | |
9580 | return !(this.keyPair.d) | |
9581 | } | |
9582 | ||
9583 | HDNode.prototype.derivePath = function (path) { | |
9584 | typeforce(types.BIP32Path, path) | |
9585 | ||
9586 | var splitPath = path.split('/') | |
9587 | if (splitPath[0] === 'm') { | |
9588 | if (this.parentFingerprint) { | |
9589 | throw new Error('Not a master node') | |
9590 | } | |
9591 | ||
9592 | splitPath = splitPath.slice(1) | |
9593 | } | |
9594 | ||
9595 | return splitPath.reduce(function (prevHd, indexStr) { | |
9596 | var index | |
9597 | if (indexStr.slice(-1) === "'") { | |
9598 | index = parseInt(indexStr.slice(0, -1), 10) | |
9599 | return prevHd.deriveHardened(index) | |
9600 | } else { | |
9601 | index = parseInt(indexStr, 10) | |
9602 | return prevHd.derive(index) | |
9603 | } | |
9604 | }, this) | |
9605 | } | |
9606 | ||
9607 | module.exports = HDNode | |
9608 | ||
9609 | },{"./crypto":45,"./ecpair":47,"./networks":51,"./types":78,"bigi":37,"bs58check":80,"create-hmac":85,"ecurve":89,"safe-buffer":98,"typeforce":109}],50:[function(require,module,exports){ | |
9610 | module.exports = { | |
9611 | Block: require('./block'), | |
9612 | ECPair: require('./ecpair'), | |
9613 | ECSignature: require('./ecsignature'), | |
9614 | HDNode: require('./hdnode'), | |
9615 | Transaction: require('./transaction'), | |
9616 | TransactionBuilder: require('./transaction_builder'), | |
9617 | ||
9618 | address: require('./address'), | |
9619 | bufferutils: require('./bufferutils'), // TODO: remove in 4.0.0 | |
9620 | crypto: require('./crypto'), | |
9621 | networks: require('./networks'), | |
9622 | opcodes: require('bitcoin-ops'), | |
9623 | script: require('./script') | |
9624 | } | |
9625 | ||
9626 | },{"./address":42,"./block":43,"./bufferutils":44,"./crypto":45,"./ecpair":47,"./ecsignature":48,"./hdnode":49,"./networks":51,"./script":52,"./transaction":76,"./transaction_builder":77,"bitcoin-ops":40}],51:[function(require,module,exports){ | |
9627 | // https://en.bitcoin.it/wiki/List_of_address_prefixes | |
9628 | // Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 | |
9629 | ||
9630 | module.exports = { | |
9631 | bitcoin: { | |
9632 | messagePrefix: '\x18Bitcoin Signed Message:\n', | |
9633 | bip32: { | |
9634 | public: 0x0488b21e, | |
9635 | private: 0x0488ade4 | |
9636 | }, | |
9637 | pubKeyHash: 0x00, | |
9638 | scriptHash: 0x05, | |
9639 | wif: 0x80 | |
9640 | }, | |
9641 | testnet: { | |
9642 | messagePrefix: '\x18Bitcoin Signed Message:\n', | |
9643 | bip32: { | |
9644 | public: 0x043587cf, | |
9645 | private: 0x04358394 | |
9646 | }, | |
9647 | pubKeyHash: 0x6f, | |
9648 | scriptHash: 0xc4, | |
9649 | wif: 0xef | |
9650 | }, | |
9651 | litecoin: { | |
9652 | messagePrefix: '\x19Litecoin Signed Message:\n', | |
9653 | bip32: { | |
9654 | public: 0x0488b21e, | |
9655 | private: 0x0488ade4, | |
9656 | }, | |
9657 | pubKeyHash: 0x30, | |
9658 | scriptHash: 0x32, | |
9659 | wif: 0xb0 | |
9660 | }, | |
9661 | litecoinLtub: { | |
9662 | messagePrefix: '\x19Litecoin Signed Message:\n', | |
9663 | bip32: { | |
9664 | public: 0x019da462, | |
9665 | private: 0x019d9cfe | |
9666 | }, | |
9667 | pubKeyHash: 0x30, | |
9668 | scriptHash: 0x32, | |
9669 | wif: 0xb0 | |
9670 | } | |
9671 | } | |
9672 | ||
9673 | },{}],52:[function(require,module,exports){ | |
9674 | var Buffer = require('safe-buffer').Buffer | |
9675 | var bip66 = require('bip66') | |
9676 | var pushdata = require('pushdata-bitcoin') | |
9677 | var typeforce = require('typeforce') | |
9678 | var types = require('./types') | |
9679 | var scriptNumber = require('./script_number') | |
9680 | ||
9681 | var OPS = require('bitcoin-ops') | |
9682 | var REVERSE_OPS = require('bitcoin-ops/map') | |
9683 | var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1 | |
9684 | ||
9685 | function isOPInt (value) { | |
9686 | return types.Number(value) && | |
9687 | ((value === OPS.OP_0) || | |
9688 | (value >= OPS.OP_1 && value <= OPS.OP_16) || | |
9689 | (value === OPS.OP_1NEGATE)) | |
9690 | } | |
9691 | ||
9692 | function isPushOnlyChunk (value) { | |
9693 | return types.Buffer(value) || isOPInt(value) | |
9694 | } | |
9695 | ||
9696 | function isPushOnly (value) { | |
9697 | return types.Array(value) && value.every(isPushOnlyChunk) | |
9698 | } | |
9699 | ||
9700 | function compile (chunks) { | |
9701 | // TODO: remove me | |
9702 | if (Buffer.isBuffer(chunks)) return chunks | |
9703 | ||
9704 | typeforce(types.Array, chunks) | |
9705 | ||
9706 | var bufferSize = chunks.reduce(function (accum, chunk) { | |
9707 | // data chunk | |
9708 | if (Buffer.isBuffer(chunk)) { | |
9709 | // adhere to BIP62.3, minimal push policy | |
9710 | if (chunk.length === 1 && (chunk[0] === 0x81 || (chunk[0] >= 1 && chunk[0] <= 16))) { | |
9711 | return accum + 1 | |
9712 | } | |
9713 | ||
9714 | return accum + pushdata.encodingLength(chunk.length) + chunk.length | |
9715 | } | |
9716 | ||
9717 | // opcode | |
9718 | return accum + 1 | |
9719 | }, 0.0) | |
9720 | ||
9721 | var buffer = Buffer.allocUnsafe(bufferSize) | |
9722 | var offset = 0 | |
9723 | ||
9724 | chunks.forEach(function (chunk) { | |
9725 | // data chunk | |
9726 | if (Buffer.isBuffer(chunk)) { | |
9727 | // adhere to BIP62.3, minimal push policy | |
9728 | if (chunk.length === 1 && chunk[0] >= 1 && chunk[0] <= 16) { | |
9729 | var opcode = OP_INT_BASE + chunk[0] | |
9730 | buffer.writeUInt8(opcode, offset) | |
9731 | offset += 1 | |
9732 | return | |
9733 | } | |
9734 | ||
9735 | if (chunk.length === 1 && chunk[0] === 0x81) { | |
9736 | buffer.writeUInt8(OPS.OP_1NEGATE, offset) | |
9737 | offset += 1 | |
9738 | return | |
9739 | } | |
9740 | ||
9741 | offset += pushdata.encode(buffer, chunk.length, offset) | |
9742 | ||
9743 | chunk.copy(buffer, offset) | |
9744 | offset += chunk.length | |
9745 | ||
9746 | // opcode | |
9747 | } else { | |
9748 | buffer.writeUInt8(chunk, offset) | |
9749 | offset += 1 | |
9750 | } | |
9751 | }) | |
9752 | ||
9753 | if (offset !== buffer.length) throw new Error('Could not decode chunks') | |
9754 | return buffer | |
9755 | } | |
9756 | ||
9757 | function decompile (buffer) { | |
9758 | // TODO: remove me | |
9759 | if (types.Array(buffer)) return buffer | |
9760 | ||
9761 | typeforce(types.Buffer, buffer) | |
9762 | ||
9763 | var chunks = [] | |
9764 | var i = 0 | |
9765 | ||
9766 | while (i < buffer.length) { | |
9767 | var opcode = buffer[i] | |
9768 | ||
9769 | // data chunk | |
9770 | if ((opcode > OPS.OP_0) && (opcode <= OPS.OP_PUSHDATA4)) { | |
9771 | var d = pushdata.decode(buffer, i) | |
9772 | ||
9773 | // did reading a pushDataInt fail? empty script | |
9774 | if (d === null) return [] | |
9775 | i += d.size | |
9776 | ||
9777 | // attempt to read too much data? empty script | |
9778 | if (i + d.number > buffer.length) return [] | |
9779 | ||
9780 | var data = buffer.slice(i, i + d.number) | |
9781 | i += d.number | |
9782 | ||
9783 | chunks.push(data) | |
9784 | ||
9785 | // opcode | |
9786 | } else { | |
9787 | chunks.push(opcode) | |
9788 | ||
9789 | i += 1 | |
9790 | } | |
9791 | } | |
9792 | ||
9793 | return chunks | |
9794 | } | |
9795 | ||
9796 | function toASM (chunks) { | |
9797 | if (Buffer.isBuffer(chunks)) { | |
9798 | chunks = decompile(chunks) | |
9799 | } | |
9800 | ||
9801 | return chunks.map(function (chunk) { | |
9802 | // data? | |
9803 | if (Buffer.isBuffer(chunk)) return chunk.toString('hex') | |
9804 | ||
9805 | // opcode! | |
9806 | return REVERSE_OPS[chunk] | |
9807 | }).join(' ') | |
9808 | } | |
9809 | ||
9810 | function fromASM (asm) { | |
9811 | typeforce(types.String, asm) | |
9812 | ||
9813 | return compile(asm.split(' ').map(function (chunkStr) { | |
9814 | // opcode? | |
9815 | if (OPS[chunkStr] !== undefined) return OPS[chunkStr] | |
9816 | typeforce(types.Hex, chunkStr) | |
9817 | ||
9818 | // data! | |
9819 | return Buffer.from(chunkStr, 'hex') | |
9820 | })) | |
9821 | } | |
9822 | ||
9823 | function toStack (chunks) { | |
9824 | chunks = decompile(chunks) | |
9825 | typeforce(isPushOnly, chunks) | |
9826 | ||
9827 | return chunks.map(function (op) { | |
9828 | if (Buffer.isBuffer(op)) return op | |
9829 | if (op === OPS.OP_0) return Buffer.allocUnsafe(0) | |
9830 | ||
9831 | return scriptNumber.encode(op - OP_INT_BASE) | |
9832 | }) | |
9833 | } | |
9834 | ||
9835 | function isCanonicalPubKey (buffer) { | |
9836 | if (!Buffer.isBuffer(buffer)) return false | |
9837 | if (buffer.length < 33) return false | |
9838 | ||
9839 | switch (buffer[0]) { | |
9840 | case 0x02: | |
9841 | case 0x03: | |
9842 | return buffer.length === 33 | |
9843 | case 0x04: | |
9844 | return buffer.length === 65 | |
9845 | } | |
9846 | ||
9847 | return false | |
9848 | } | |
9849 | ||
9850 | function isDefinedHashType (hashType) { | |
9851 | var hashTypeMod = hashType & ~0x80 | |
9852 | ||
9853 | // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE | |
9854 | return hashTypeMod > 0x00 && hashTypeMod < 0x04 | |
9855 | } | |
9856 | ||
9857 | function isCanonicalSignature (buffer) { | |
9858 | if (!Buffer.isBuffer(buffer)) return false | |
9859 | if (!isDefinedHashType(buffer[buffer.length - 1])) return false | |
9860 | ||
9861 | return bip66.check(buffer.slice(0, -1)) | |
9862 | } | |
9863 | ||
9864 | module.exports = { | |
9865 | compile: compile, | |
9866 | decompile: decompile, | |
9867 | fromASM: fromASM, | |
9868 | toASM: toASM, | |
9869 | toStack: toStack, | |
9870 | ||
9871 | number: require('./script_number'), | |
9872 | ||
9873 | isCanonicalPubKey: isCanonicalPubKey, | |
9874 | isCanonicalSignature: isCanonicalSignature, | |
9875 | isPushOnly: isPushOnly, | |
9876 | isDefinedHashType: isDefinedHashType | |
9877 | } | |
9878 | ||
9879 | var templates = require('./templates') | |
9880 | for (var key in templates) { | |
9881 | module.exports[key] = templates[key] | |
9882 | } | |
9883 | ||
9884 | },{"./script_number":53,"./templates":54,"./types":78,"bip66":39,"bitcoin-ops":40,"bitcoin-ops/map":41,"pushdata-bitcoin":95,"safe-buffer":98,"typeforce":109}],53:[function(require,module,exports){ | |
9885 | var Buffer = require('safe-buffer').Buffer | |
9886 | ||
9887 | function decode (buffer, maxLength, minimal) { | |
9888 | maxLength = maxLength || 4 | |
9889 | minimal = minimal === undefined ? true : minimal | |
9890 | ||
9891 | var length = buffer.length | |
9892 | if (length === 0) return 0 | |
9893 | if (length > maxLength) throw new TypeError('Script number overflow') | |
9894 | if (minimal) { | |
9895 | if ((buffer[length - 1] & 0x7f) === 0) { | |
9896 | if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number') | |
9897 | } | |
9898 | } | |
9899 | ||
9900 | // 40-bit | |
9901 | if (length === 5) { | |
9902 | var a = buffer.readUInt32LE(0) | |
9903 | var b = buffer.readUInt8(4) | |
9904 | ||
9905 | if (b & 0x80) return -(((b & ~0x80) * 0x100000000) + a) | |
9906 | return (b * 0x100000000) + a | |
9907 | } | |
9908 | ||
9909 | var result = 0 | |
9910 | ||
9911 | // 32-bit / 24-bit / 16-bit / 8-bit | |
9912 | for (var i = 0; i < length; ++i) { | |
9913 | result |= buffer[i] << (8 * i) | |
9914 | } | |
9915 | ||
9916 | if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << (8 * (length - 1)))) | |
9917 | return result | |
9918 | } | |
9919 | ||
9920 | function scriptNumSize (i) { | |
9921 | return i > 0x7fffffff ? 5 | |
9922 | : i > 0x7fffff ? 4 | |
9923 | : i > 0x7fff ? 3 | |
9924 | : i > 0x7f ? 2 | |
9925 | : i > 0x00 ? 1 | |
9926 | : 0 | |
9927 | } | |
9928 | ||
9929 | function encode (number) { | |
9930 | var value = Math.abs(number) | |
9931 | var size = scriptNumSize(value) | |
9932 | var buffer = Buffer.allocUnsafe(size) | |
9933 | var negative = number < 0 | |
9934 | ||
9935 | for (var i = 0; i < size; ++i) { | |
9936 | buffer.writeUInt8(value & 0xff, i) | |
9937 | value >>= 8 | |
9938 | } | |
9939 | ||
9940 | if (buffer[size - 1] & 0x80) { | |
9941 | buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1) | |
9942 | } else if (negative) { | |
9943 | buffer[size - 1] |= 0x80 | |
9944 | } | |
9945 | ||
9946 | return buffer | |
9947 | } | |
9948 | ||
9949 | module.exports = { | |
9950 | decode: decode, | |
9951 | encode: encode | |
9952 | } | |
9953 | ||
9954 | },{"safe-buffer":98}],54:[function(require,module,exports){ | |
9955 | var decompile = require('../script').decompile | |
9956 | var multisig = require('./multisig') | |
9957 | var nullData = require('./nulldata') | |
9958 | var pubKey = require('./pubkey') | |
9959 | var pubKeyHash = require('./pubkeyhash') | |
9960 | var scriptHash = require('./scripthash') | |
9961 | var witnessPubKeyHash = require('./witnesspubkeyhash') | |
9962 | var witnessScriptHash = require('./witnessscripthash') | |
9963 | var witnessCommitment = require('./witnesscommitment') | |
9964 | ||
9965 | var types = { | |
9966 | MULTISIG: 'multisig', | |
9967 | NONSTANDARD: 'nonstandard', | |
9968 | NULLDATA: 'nulldata', | |
9969 | P2PK: 'pubkey', | |
9970 | P2PKH: 'pubkeyhash', | |
9971 | P2SH: 'scripthash', | |
9972 | P2WPKH: 'witnesspubkeyhash', | |
9973 | P2WSH: 'witnessscripthash', | |
9974 | WITNESS_COMMITMENT: 'witnesscommitment' | |
9975 | } | |
9976 | ||
9977 | function classifyOutput (script) { | |
9978 | if (witnessPubKeyHash.output.check(script)) return types.P2WPKH | |
9979 | if (witnessScriptHash.output.check(script)) return types.P2WSH | |
9980 | if (pubKeyHash.output.check(script)) return types.P2PKH | |
9981 | if (scriptHash.output.check(script)) return types.P2SH | |
9982 | ||
9983 | // XXX: optimization, below functions .decompile before use | |
9984 | var chunks = decompile(script) | |
9985 | if (multisig.output.check(chunks)) return types.MULTISIG | |
9986 | if (pubKey.output.check(chunks)) return types.P2PK | |
9987 | if (witnessCommitment.output.check(chunks)) return types.WITNESS_COMMITMENT | |
9988 | if (nullData.output.check(chunks)) return types.NULLDATA | |
9989 | ||
9990 | return types.NONSTANDARD | |
9991 | } | |
9992 | ||
9993 | function classifyInput (script, allowIncomplete) { | |
9994 | // XXX: optimization, below functions .decompile before use | |
9995 | var chunks = decompile(script) | |
9996 | ||
9997 | if (pubKeyHash.input.check(chunks)) return types.P2PKH | |
9998 | if (scriptHash.input.check(chunks, allowIncomplete)) return types.P2SH | |
9999 | if (multisig.input.check(chunks, allowIncomplete)) return types.MULTISIG | |
10000 | if (pubKey.input.check(chunks)) return types.P2PK | |
10001 | ||
10002 | return types.NONSTANDARD | |
10003 | } | |
10004 | ||
10005 | function classifyWitness (script, allowIncomplete) { | |
10006 | // XXX: optimization, below functions .decompile before use | |
10007 | var chunks = decompile(script) | |
10008 | ||
10009 | if (witnessPubKeyHash.input.check(chunks)) return types.P2WPKH | |
10010 | if (witnessScriptHash.input.check(chunks, allowIncomplete)) return types.P2WSH | |
10011 | ||
10012 | return types.NONSTANDARD | |
10013 | } | |
10014 | ||
10015 | module.exports = { | |
10016 | classifyInput: classifyInput, | |
10017 | classifyOutput: classifyOutput, | |
10018 | classifyWitness: classifyWitness, | |
10019 | multisig: multisig, | |
10020 | nullData: nullData, | |
10021 | pubKey: pubKey, | |
10022 | pubKeyHash: pubKeyHash, | |
10023 | scriptHash: scriptHash, | |
10024 | witnessPubKeyHash: witnessPubKeyHash, | |
10025 | witnessScriptHash: witnessScriptHash, | |
10026 | witnessCommitment: witnessCommitment, | |
10027 | types: types | |
10028 | } | |
10029 | ||
10030 | },{"../script":52,"./multisig":55,"./nulldata":58,"./pubkey":59,"./pubkeyhash":62,"./scripthash":65,"./witnesscommitment":68,"./witnesspubkeyhash":70,"./witnessscripthash":73}],55:[function(require,module,exports){ | |
10031 | module.exports = { | |
10032 | input: require('./input'), | |
10033 | output: require('./output') | |
10034 | } | |
10035 | ||
10036 | },{"./input":56,"./output":57}],56:[function(require,module,exports){ | |
10037 | // OP_0 [signatures ...] | |
10038 | ||
10039 | var Buffer = require('safe-buffer').Buffer | |
10040 | var bscript = require('../../script') | |
10041 | var typeforce = require('typeforce') | |
10042 | var OPS = require('bitcoin-ops') | |
10043 | ||
10044 | function partialSignature (value) { | |
10045 | return value === OPS.OP_0 || bscript.isCanonicalSignature(value) | |
10046 | } | |
10047 | ||
10048 | function check (script, allowIncomplete) { | |
10049 | var chunks = bscript.decompile(script) | |
10050 | if (chunks.length < 2) return false | |
10051 | if (chunks[0] !== OPS.OP_0) return false | |
10052 | ||
10053 | if (allowIncomplete) { | |
10054 | return chunks.slice(1).every(partialSignature) | |
10055 | } | |
10056 | ||
10057 | return chunks.slice(1).every(bscript.isCanonicalSignature) | |
10058 | } | |
10059 | check.toJSON = function () { return 'multisig input' } | |
10060 | ||
10061 | var EMPTY_BUFFER = Buffer.allocUnsafe(0) | |
10062 | ||
10063 | function encodeStack (signatures, scriptPubKey) { | |
10064 | typeforce([partialSignature], signatures) | |
10065 | ||
10066 | if (scriptPubKey) { | |
10067 | var scriptData = bscript.multisig.output.decode(scriptPubKey) | |
10068 | ||
10069 | if (signatures.length < scriptData.m) { | |
10070 | throw new TypeError('Not enough signatures provided') | |
10071 | } | |
10072 | ||
10073 | if (signatures.length > scriptData.pubKeys.length) { | |
10074 | throw new TypeError('Too many signatures provided') | |
10075 | } | |
10076 | } | |
10077 | ||
10078 | return [].concat(EMPTY_BUFFER, signatures) | |
10079 | } | |
10080 | ||
10081 | function encode (signatures, scriptPubKey) { | |
10082 | return bscript.compile(encodeStack(signatures, scriptPubKey)) | |
10083 | } | |
10084 | ||
10085 | function decodeStack (stack, allowIncomplete) { | |
10086 | typeforce(check, stack, allowIncomplete) | |
10087 | return stack.slice(1) | |
10088 | } | |
10089 | ||
10090 | function decode (buffer, allowIncomplete) { | |
10091 | var stack = bscript.decompile(buffer) | |
10092 | return decodeStack(stack, allowIncomplete) | |
10093 | } | |
10094 | ||
10095 | module.exports = { | |
10096 | check: check, | |
10097 | decode: decode, | |
10098 | decodeStack: decodeStack, | |
10099 | encode: encode, | |
10100 | encodeStack: encodeStack | |
10101 | } | |
10102 | ||
10103 | },{"../../script":52,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109}],57:[function(require,module,exports){ | |
10104 | // m [pubKeys ...] n OP_CHECKMULTISIG | |
10105 | ||
10106 | var bscript = require('../../script') | |
10107 | var types = require('../../types') | |
10108 | var typeforce = require('typeforce') | |
10109 | var OPS = require('bitcoin-ops') | |
10110 | var OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1 | |
10111 | ||
10112 | function check (script, allowIncomplete) { | |
10113 | var chunks = bscript.decompile(script) | |
10114 | ||
10115 | if (chunks.length < 4) return false | |
10116 | if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) return false | |
10117 | if (!types.Number(chunks[0])) return false | |
10118 | if (!types.Number(chunks[chunks.length - 2])) return false | |
10119 | var m = chunks[0] - OP_INT_BASE | |
10120 | var n = chunks[chunks.length - 2] - OP_INT_BASE | |
10121 | ||
10122 | if (m <= 0) return false | |
10123 | if (n > 16) return false | |
10124 | if (m > n) return false | |
10125 | if (n !== chunks.length - 3) return false | |
10126 | if (allowIncomplete) return true | |
10127 | ||
10128 | var keys = chunks.slice(1, -2) | |
10129 | return keys.every(bscript.isCanonicalPubKey) | |
10130 | } | |
10131 | check.toJSON = function () { return 'multi-sig output' } | |
10132 | ||
10133 | function encode (m, pubKeys) { | |
10134 | typeforce({ | |
10135 | m: types.Number, | |
10136 | pubKeys: [bscript.isCanonicalPubKey] | |
10137 | }, { | |
10138 | m: m, | |
10139 | pubKeys: pubKeys | |
10140 | }) | |
10141 | ||
10142 | var n = pubKeys.length | |
10143 | if (n < m) throw new TypeError('Not enough pubKeys provided') | |
10144 | ||
10145 | return bscript.compile([].concat( | |
10146 | OP_INT_BASE + m, | |
10147 | pubKeys, | |
10148 | OP_INT_BASE + n, | |
10149 | OPS.OP_CHECKMULTISIG | |
10150 | )) | |
10151 | } | |
10152 | ||
10153 | function decode (buffer, allowIncomplete) { | |
10154 | var chunks = bscript.decompile(buffer) | |
10155 | typeforce(check, chunks, allowIncomplete) | |
10156 | ||
10157 | return { | |
10158 | m: chunks[0] - OP_INT_BASE, | |
10159 | pubKeys: chunks.slice(1, -2) | |
10160 | } | |
10161 | } | |
10162 | ||
10163 | module.exports = { | |
10164 | check: check, | |
10165 | decode: decode, | |
10166 | encode: encode | |
10167 | } | |
10168 | ||
10169 | },{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],58:[function(require,module,exports){ | |
10170 | // OP_RETURN {data} | |
10171 | ||
10172 | var bscript = require('../script') | |
10173 | var types = require('../types') | |
10174 | var typeforce = require('typeforce') | |
10175 | var OPS = require('bitcoin-ops') | |
10176 | ||
10177 | function check (script) { | |
10178 | var buffer = bscript.compile(script) | |
10179 | ||
10180 | return buffer.length > 1 && | |
10181 | buffer[0] === OPS.OP_RETURN | |
10182 | } | |
10183 | check.toJSON = function () { return 'null data output' } | |
10184 | ||
10185 | function encode (data) { | |
10186 | typeforce(types.Buffer, data) | |
10187 | ||
10188 | return bscript.compile([OPS.OP_RETURN, data]) | |
10189 | } | |
10190 | ||
10191 | function decode (buffer) { | |
10192 | typeforce(check, buffer) | |
10193 | ||
10194 | return buffer.slice(2) | |
10195 | } | |
10196 | ||
10197 | module.exports = { | |
10198 | output: { | |
10199 | check: check, | |
10200 | decode: decode, | |
10201 | encode: encode | |
10202 | } | |
10203 | } | |
10204 | ||
10205 | },{"../script":52,"../types":78,"bitcoin-ops":40,"typeforce":109}],59:[function(require,module,exports){ | |
10206 | arguments[4][55][0].apply(exports,arguments) | |
10207 | },{"./input":60,"./output":61,"dup":55}],60:[function(require,module,exports){ | |
10208 | // {signature} | |
10209 | ||
10210 | var bscript = require('../../script') | |
10211 | var types = require('../../types') | |
10212 | var typeforce = require('typeforce') | |
10213 | ||
10214 | function check (script) { | |
10215 | var chunks = bscript.decompile(script) | |
10216 | ||
10217 | return chunks.length === 1 && | |
10218 | bscript.isCanonicalSignature(chunks[0]) | |
10219 | } | |
10220 | check.toJSON = function () { return 'pubKey input' } | |
10221 | ||
10222 | function encodeStack (signature) { | |
10223 | typeforce(types.Buffer, signature) | |
10224 | return [signature] | |
10225 | } | |
10226 | ||
10227 | function encode (signature) { | |
10228 | return bscript.compile(encodeStack(signature)) | |
10229 | } | |
10230 | ||
10231 | function decodeStack (stack) { | |
10232 | typeforce(check, stack) | |
10233 | return stack[0] | |
10234 | } | |
10235 | ||
10236 | function decode (buffer) { | |
10237 | var stack = bscript.decompile(buffer) | |
10238 | return decodeStack(stack) | |
10239 | } | |
10240 | ||
10241 | module.exports = { | |
10242 | check: check, | |
10243 | decode: decode, | |
10244 | decodeStack: decodeStack, | |
10245 | encode: encode, | |
10246 | encodeStack: encodeStack | |
10247 | } | |
10248 | ||
10249 | },{"../../script":52,"../../types":78,"typeforce":109}],61:[function(require,module,exports){ | |
10250 | // {pubKey} OP_CHECKSIG | |
10251 | ||
10252 | var bscript = require('../../script') | |
10253 | var typeforce = require('typeforce') | |
10254 | var OPS = require('bitcoin-ops') | |
10255 | ||
10256 | function check (script) { | |
10257 | var chunks = bscript.decompile(script) | |
10258 | ||
10259 | return chunks.length === 2 && | |
10260 | bscript.isCanonicalPubKey(chunks[0]) && | |
10261 | chunks[1] === OPS.OP_CHECKSIG | |
10262 | } | |
10263 | check.toJSON = function () { return 'pubKey output' } | |
10264 | ||
10265 | function encode (pubKey) { | |
10266 | typeforce(bscript.isCanonicalPubKey, pubKey) | |
10267 | ||
10268 | return bscript.compile([pubKey, OPS.OP_CHECKSIG]) | |
10269 | } | |
10270 | ||
10271 | function decode (buffer) { | |
10272 | var chunks = bscript.decompile(buffer) | |
10273 | typeforce(check, chunks) | |
10274 | ||
10275 | return chunks[0] | |
10276 | } | |
10277 | ||
10278 | module.exports = { | |
10279 | check: check, | |
10280 | decode: decode, | |
10281 | encode: encode | |
10282 | } | |
10283 | ||
10284 | },{"../../script":52,"bitcoin-ops":40,"typeforce":109}],62:[function(require,module,exports){ | |
10285 | arguments[4][55][0].apply(exports,arguments) | |
10286 | },{"./input":63,"./output":64,"dup":55}],63:[function(require,module,exports){ | |
10287 | // {signature} {pubKey} | |
10288 | ||
10289 | var bscript = require('../../script') | |
10290 | var types = require('../../types') | |
10291 | var typeforce = require('typeforce') | |
10292 | ||
10293 | function check (script) { | |
10294 | var chunks = bscript.decompile(script) | |
10295 | ||
10296 | return chunks.length === 2 && | |
10297 | bscript.isCanonicalSignature(chunks[0]) && | |
10298 | bscript.isCanonicalPubKey(chunks[1]) | |
10299 | } | |
10300 | check.toJSON = function () { return 'pubKeyHash input' } | |
10301 | ||
10302 | function encodeStack (signature, pubKey) { | |
10303 | typeforce({ | |
10304 | signature: types.Buffer, pubKey: types.Buffer | |
10305 | }, { | |
10306 | signature: signature, pubKey: pubKey | |
10307 | }) | |
10308 | ||
10309 | return [signature, pubKey] | |
10310 | } | |
10311 | ||
10312 | function encode (signature, pubKey) { | |
10313 | return bscript.compile(encodeStack(signature, pubKey)) | |
10314 | } | |
10315 | ||
10316 | function decodeStack (stack) { | |
10317 | typeforce(check, stack) | |
10318 | ||
10319 | return { | |
10320 | signature: stack[0], | |
10321 | pubKey: stack[1] | |
10322 | } | |
10323 | } | |
10324 | ||
10325 | function decode (buffer) { | |
10326 | var stack = bscript.decompile(buffer) | |
10327 | return decodeStack(stack) | |
10328 | } | |
10329 | ||
10330 | module.exports = { | |
10331 | check: check, | |
10332 | decode: decode, | |
10333 | decodeStack: decodeStack, | |
10334 | encode: encode, | |
10335 | encodeStack: encodeStack | |
10336 | } | |
10337 | ||
10338 | },{"../../script":52,"../../types":78,"typeforce":109}],64:[function(require,module,exports){ | |
10339 | // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG | |
10340 | ||
10341 | var bscript = require('../../script') | |
10342 | var types = require('../../types') | |
10343 | var typeforce = require('typeforce') | |
10344 | var OPS = require('bitcoin-ops') | |
10345 | ||
10346 | function check (script) { | |
10347 | var buffer = bscript.compile(script) | |
10348 | ||
10349 | return buffer.length === 25 && | |
10350 | buffer[0] === OPS.OP_DUP && | |
10351 | buffer[1] === OPS.OP_HASH160 && | |
10352 | buffer[2] === 0x14 && | |
10353 | buffer[23] === OPS.OP_EQUALVERIFY && | |
10354 | buffer[24] === OPS.OP_CHECKSIG | |
10355 | } | |
10356 | check.toJSON = function () { return 'pubKeyHash output' } | |
10357 | ||
10358 | function encode (pubKeyHash) { | |
10359 | typeforce(types.Hash160bit, pubKeyHash) | |
10360 | ||
10361 | return bscript.compile([ | |
10362 | OPS.OP_DUP, | |
10363 | OPS.OP_HASH160, | |
10364 | pubKeyHash, | |
10365 | OPS.OP_EQUALVERIFY, | |
10366 | OPS.OP_CHECKSIG | |
10367 | ]) | |
10368 | } | |
10369 | ||
10370 | function decode (buffer) { | |
10371 | typeforce(check, buffer) | |
10372 | ||
10373 | return buffer.slice(3, 23) | |
10374 | } | |
10375 | ||
10376 | module.exports = { | |
10377 | check: check, | |
10378 | decode: decode, | |
10379 | encode: encode | |
10380 | } | |
10381 | ||
10382 | },{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],65:[function(require,module,exports){ | |
10383 | arguments[4][55][0].apply(exports,arguments) | |
10384 | },{"./input":66,"./output":67,"dup":55}],66:[function(require,module,exports){ | |
10385 | // <scriptSig> {serialized scriptPubKey script} | |
10386 | ||
10387 | var Buffer = require('safe-buffer').Buffer | |
10388 | var bscript = require('../../script') | |
10389 | var typeforce = require('typeforce') | |
10390 | ||
10391 | function check (script, allowIncomplete) { | |
10392 | var chunks = bscript.decompile(script) | |
10393 | if (chunks.length < 1) return false | |
10394 | ||
10395 | var lastChunk = chunks[chunks.length - 1] | |
10396 | if (!Buffer.isBuffer(lastChunk)) return false | |
10397 | ||
10398 | var scriptSigChunks = bscript.decompile(bscript.compile(chunks.slice(0, -1))) | |
10399 | var redeemScriptChunks = bscript.decompile(lastChunk) | |
10400 | ||
10401 | // is redeemScript a valid script? | |
10402 | if (redeemScriptChunks.length === 0) return false | |
10403 | ||
10404 | // is redeemScriptSig push only? | |
10405 | if (!bscript.isPushOnly(scriptSigChunks)) return false | |
10406 | ||
10407 | var inputType = bscript.classifyInput(scriptSigChunks, allowIncomplete) | |
10408 | var outputType = bscript.classifyOutput(redeemScriptChunks) | |
10409 | if (chunks.length === 1) { | |
10410 | return outputType === bscript.types.P2WSH || outputType === bscript.types.P2WPKH | |
10411 | } | |
10412 | return inputType === outputType | |
10413 | } | |
10414 | check.toJSON = function () { return 'scriptHash input' } | |
10415 | ||
10416 | function encodeStack (redeemScriptStack, redeemScript) { | |
10417 | var serializedScriptPubKey = bscript.compile(redeemScript) | |
10418 | ||
10419 | return [].concat(redeemScriptStack, serializedScriptPubKey) | |
10420 | } | |
10421 | ||
10422 | function encode (redeemScriptSig, redeemScript) { | |
10423 | var redeemScriptStack = bscript.decompile(redeemScriptSig) | |
10424 | ||
10425 | return bscript.compile(encodeStack(redeemScriptStack, redeemScript)) | |
10426 | } | |
10427 | ||
10428 | function decodeStack (stack) { | |
10429 | typeforce(check, stack) | |
10430 | ||
10431 | return { | |
10432 | redeemScriptStack: stack.slice(0, -1), | |
10433 | redeemScript: stack[stack.length - 1] | |
10434 | } | |
10435 | } | |
10436 | ||
10437 | function decode (buffer) { | |
10438 | var stack = bscript.decompile(buffer) | |
10439 | var result = decodeStack(stack) | |
10440 | result.redeemScriptSig = bscript.compile(result.redeemScriptStack) | |
10441 | delete result.redeemScriptStack | |
10442 | return result | |
10443 | } | |
10444 | ||
10445 | module.exports = { | |
10446 | check: check, | |
10447 | decode: decode, | |
10448 | decodeStack: decodeStack, | |
10449 | encode: encode, | |
10450 | encodeStack: encodeStack | |
10451 | } | |
10452 | ||
10453 | },{"../../script":52,"safe-buffer":98,"typeforce":109}],67:[function(require,module,exports){ | |
10454 | // OP_HASH160 {scriptHash} OP_EQUAL | |
10455 | ||
10456 | var bscript = require('../../script') | |
10457 | var types = require('../../types') | |
10458 | var typeforce = require('typeforce') | |
10459 | var OPS = require('bitcoin-ops') | |
10460 | ||
10461 | function check (script) { | |
10462 | var buffer = bscript.compile(script) | |
10463 | ||
10464 | return buffer.length === 23 && | |
10465 | buffer[0] === OPS.OP_HASH160 && | |
10466 | buffer[1] === 0x14 && | |
10467 | buffer[22] === OPS.OP_EQUAL | |
10468 | } | |
10469 | check.toJSON = function () { return 'scriptHash output' } | |
10470 | ||
10471 | function encode (scriptHash) { | |
10472 | typeforce(types.Hash160bit, scriptHash) | |
10473 | ||
10474 | return bscript.compile([OPS.OP_HASH160, scriptHash, OPS.OP_EQUAL]) | |
10475 | } | |
10476 | ||
10477 | function decode (buffer) { | |
10478 | typeforce(check, buffer) | |
10479 | ||
10480 | return buffer.slice(2, 22) | |
10481 | } | |
10482 | ||
10483 | module.exports = { | |
10484 | check: check, | |
10485 | decode: decode, | |
10486 | encode: encode | |
10487 | } | |
10488 | ||
10489 | },{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],68:[function(require,module,exports){ | |
10490 | module.exports = { | |
10491 | output: require('./output') | |
10492 | } | |
10493 | ||
10494 | },{"./output":69}],69:[function(require,module,exports){ | |
10495 | // OP_RETURN {aa21a9ed} {commitment} | |
10496 | ||
10497 | var Buffer = require('safe-buffer').Buffer | |
10498 | var bscript = require('../../script') | |
10499 | var types = require('../../types') | |
10500 | var typeforce = require('typeforce') | |
10501 | var OPS = require('bitcoin-ops') | |
10502 | ||
10503 | var HEADER = Buffer.from('aa21a9ed', 'hex') | |
10504 | ||
10505 | function check (script) { | |
10506 | var buffer = bscript.compile(script) | |
10507 | ||
10508 | return buffer.length > 37 && | |
10509 | buffer[0] === OPS.OP_RETURN && | |
10510 | buffer[1] === 0x24 && | |
10511 | buffer.slice(2, 6).equals(HEADER) | |
10512 | } | |
10513 | ||
10514 | check.toJSON = function () { return 'Witness commitment output' } | |
10515 | ||
10516 | function encode (commitment) { | |
10517 | typeforce(types.Hash256bit, commitment) | |
10518 | ||
10519 | var buffer = Buffer.allocUnsafe(36) | |
10520 | HEADER.copy(buffer, 0) | |
10521 | commitment.copy(buffer, 4) | |
10522 | ||
10523 | return bscript.compile([OPS.OP_RETURN, buffer]) | |
10524 | } | |
10525 | ||
10526 | function decode (buffer) { | |
10527 | typeforce(check, buffer) | |
10528 | ||
10529 | return bscript.decompile(buffer)[1].slice(4, 36) | |
10530 | } | |
10531 | ||
10532 | module.exports = { | |
10533 | check: check, | |
10534 | decode: decode, | |
10535 | encode: encode | |
10536 | } | |
10537 | ||
10538 | },{"../../script":52,"../../types":78,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109}],70:[function(require,module,exports){ | |
10539 | arguments[4][55][0].apply(exports,arguments) | |
10540 | },{"./input":71,"./output":72,"dup":55}],71:[function(require,module,exports){ | |
10541 | // {signature} {pubKey} | |
10542 | ||
10543 | var pkh = require('../pubkeyhash/input') | |
10544 | ||
10545 | module.exports = { | |
10546 | check: pkh.check, | |
10547 | decodeStack: pkh.decodeStack, | |
10548 | encodeStack: pkh.encodeStack | |
10549 | } | |
10550 | ||
10551 | },{"../pubkeyhash/input":63}],72:[function(require,module,exports){ | |
10552 | // OP_0 {pubKeyHash} | |
10553 | ||
10554 | var bscript = require('../../script') | |
10555 | var types = require('../../types') | |
10556 | var typeforce = require('typeforce') | |
10557 | var OPS = require('bitcoin-ops') | |
10558 | ||
10559 | function check (script) { | |
10560 | var buffer = bscript.compile(script) | |
10561 | ||
10562 | return buffer.length === 22 && | |
10563 | buffer[0] === OPS.OP_0 && | |
10564 | buffer[1] === 0x14 | |
10565 | } | |
10566 | check.toJSON = function () { return 'Witness pubKeyHash output' } | |
10567 | ||
10568 | function encode (pubKeyHash) { | |
10569 | typeforce(types.Hash160bit, pubKeyHash) | |
10570 | ||
10571 | return bscript.compile([OPS.OP_0, pubKeyHash]) | |
10572 | } | |
10573 | ||
10574 | function decode (buffer) { | |
10575 | typeforce(check, buffer) | |
10576 | ||
10577 | return buffer.slice(2) | |
10578 | } | |
10579 | ||
10580 | module.exports = { | |
10581 | check: check, | |
10582 | decode: decode, | |
10583 | encode: encode | |
10584 | } | |
10585 | ||
10586 | },{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],73:[function(require,module,exports){ | |
10587 | arguments[4][55][0].apply(exports,arguments) | |
10588 | },{"./input":74,"./output":75,"dup":55}],74:[function(require,module,exports){ | |
10589 | // {signature} {pubKey} | |
10590 | ||
10591 | var p2sh = require('../scripthash/input') | |
10592 | ||
10593 | module.exports = { | |
10594 | check: p2sh.check, | |
10595 | decodeStack: p2sh.decodeStack, | |
10596 | encodeStack: p2sh.encodeStack | |
10597 | } | |
10598 | ||
10599 | },{"../scripthash/input":66}],75:[function(require,module,exports){ | |
10600 | // OP_0 {scriptHash} | |
10601 | ||
10602 | var bscript = require('../../script') | |
10603 | var types = require('../../types') | |
10604 | var typeforce = require('typeforce') | |
10605 | var OPS = require('bitcoin-ops') | |
10606 | ||
10607 | function check (script) { | |
10608 | var buffer = bscript.compile(script) | |
10609 | ||
10610 | return buffer.length === 34 && | |
10611 | buffer[0] === OPS.OP_0 && | |
10612 | buffer[1] === 0x20 | |
10613 | } | |
10614 | check.toJSON = function () { return 'Witness scriptHash output' } | |
10615 | ||
10616 | function encode (scriptHash) { | |
10617 | typeforce(types.Hash256bit, scriptHash) | |
10618 | ||
10619 | return bscript.compile([OPS.OP_0, scriptHash]) | |
10620 | } | |
10621 | ||
10622 | function decode (buffer) { | |
10623 | typeforce(check, buffer) | |
10624 | ||
10625 | return buffer.slice(2) | |
10626 | } | |
10627 | ||
10628 | module.exports = { | |
10629 | check: check, | |
10630 | decode: decode, | |
10631 | encode: encode | |
10632 | } | |
10633 | ||
10634 | },{"../../script":52,"../../types":78,"bitcoin-ops":40,"typeforce":109}],76:[function(require,module,exports){ | |
10635 | var Buffer = require('safe-buffer').Buffer | |
10636 | var bcrypto = require('./crypto') | |
10637 | var bscript = require('./script') | |
10638 | var bufferutils = require('./bufferutils') | |
10639 | var opcodes = require('bitcoin-ops') | |
10640 | var typeforce = require('typeforce') | |
10641 | var types = require('./types') | |
10642 | var varuint = require('varuint-bitcoin') | |
10643 | ||
10644 | function varSliceSize (someScript) { | |
10645 | var length = someScript.length | |
10646 | ||
10647 | return varuint.encodingLength(length) + length | |
10648 | } | |
10649 | ||
10650 | function vectorSize (someVector) { | |
10651 | var length = someVector.length | |
10652 | ||
10653 | return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) { | |
10654 | return sum + varSliceSize(witness) | |
10655 | }, 0) | |
10656 | } | |
10657 | ||
10658 | function Transaction () { | |
10659 | this.version = 1 | |
10660 | this.locktime = 0 | |
10661 | this.ins = [] | |
10662 | this.outs = [] | |
10663 | } | |
10664 | ||
10665 | Transaction.DEFAULT_SEQUENCE = 0xffffffff | |
10666 | Transaction.SIGHASH_ALL = 0x01 | |
10667 | Transaction.SIGHASH_NONE = 0x02 | |
10668 | Transaction.SIGHASH_SINGLE = 0x03 | |
10669 | Transaction.SIGHASH_ANYONECANPAY = 0x80 | |
10670 | Transaction.ADVANCED_TRANSACTION_MARKER = 0x00 | |
10671 | Transaction.ADVANCED_TRANSACTION_FLAG = 0x01 | |
10672 | ||
10673 | var EMPTY_SCRIPT = Buffer.allocUnsafe(0) | |
10674 | var EMPTY_WITNESS = [] | |
10675 | var ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex') | |
10676 | var ONE = Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex') | |
10677 | var VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex') | |
10678 | var BLANK_OUTPUT = { | |
10679 | script: EMPTY_SCRIPT, | |
10680 | valueBuffer: VALUE_UINT64_MAX | |
10681 | } | |
10682 | ||
10683 | Transaction.fromBuffer = function (buffer, __noStrict) { | |
10684 | var offset = 0 | |
10685 | function readSlice (n) { | |
10686 | offset += n | |
10687 | return buffer.slice(offset - n, offset) | |
10688 | } | |
10689 | ||
10690 | function readUInt32 () { | |
10691 | var i = buffer.readUInt32LE(offset) | |
10692 | offset += 4 | |
10693 | return i | |
10694 | } | |
10695 | ||
10696 | function readInt32 () { | |
10697 | var i = buffer.readInt32LE(offset) | |
10698 | offset += 4 | |
10699 | return i | |
10700 | } | |
10701 | ||
10702 | function readUInt64 () { | |
10703 | var i = bufferutils.readUInt64LE(buffer, offset) | |
10704 | offset += 8 | |
10705 | return i | |
10706 | } | |
10707 | ||
10708 | function readVarInt () { | |
10709 | var vi = varuint.decode(buffer, offset) | |
10710 | offset += varuint.decode.bytes | |
10711 | return vi | |
10712 | } | |
10713 | ||
10714 | function readVarSlice () { | |
10715 | return readSlice(readVarInt()) | |
10716 | } | |
10717 | ||
10718 | function readVector () { | |
10719 | var count = readVarInt() | |
10720 | var vector = [] | |
10721 | for (var i = 0; i < count; i++) vector.push(readVarSlice()) | |
10722 | return vector | |
10723 | } | |
10724 | ||
10725 | var tx = new Transaction() | |
10726 | tx.version = readInt32() | |
10727 | ||
10728 | var marker = buffer.readUInt8(offset) | |
10729 | var flag = buffer.readUInt8(offset + 1) | |
10730 | ||
10731 | var hasWitnesses = false | |
10732 | if (marker === Transaction.ADVANCED_TRANSACTION_MARKER && | |
10733 | flag === Transaction.ADVANCED_TRANSACTION_FLAG) { | |
10734 | offset += 2 | |
10735 | hasWitnesses = true | |
10736 | } | |
10737 | ||
10738 | var vinLen = readVarInt() | |
10739 | for (var i = 0; i < vinLen; ++i) { | |
10740 | tx.ins.push({ | |
10741 | hash: readSlice(32), | |
10742 | index: readUInt32(), | |
10743 | script: readVarSlice(), | |
10744 | sequence: readUInt32(), | |
10745 | witness: EMPTY_WITNESS | |
10746 | }) | |
10747 | } | |
10748 | ||
10749 | var voutLen = readVarInt() | |
10750 | for (i = 0; i < voutLen; ++i) { | |
10751 | tx.outs.push({ | |
10752 | value: readUInt64(), | |
10753 | script: readVarSlice() | |
10754 | }) | |
10755 | } | |
10756 | ||
10757 | if (hasWitnesses) { | |
10758 | for (i = 0; i < vinLen; ++i) { | |
10759 | tx.ins[i].witness = readVector() | |
10760 | } | |
10761 | ||
10762 | // was this pointless? | |
10763 | if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data') | |
10764 | } | |
10765 | ||
10766 | tx.locktime = readUInt32() | |
10767 | ||
10768 | if (__noStrict) return tx | |
10769 | if (offset !== buffer.length) throw new Error('Transaction has unexpected data') | |
10770 | ||
10771 | return tx | |
10772 | } | |
10773 | ||
10774 | Transaction.fromHex = function (hex) { | |
10775 | return Transaction.fromBuffer(Buffer.from(hex, 'hex')) | |
10776 | } | |
10777 | ||
10778 | Transaction.isCoinbaseHash = function (buffer) { | |
10779 | typeforce(types.Hash256bit, buffer) | |
10780 | for (var i = 0; i < 32; ++i) { | |
10781 | if (buffer[i] !== 0) return false | |
10782 | } | |
10783 | return true | |
10784 | } | |
10785 | ||
10786 | Transaction.prototype.isCoinbase = function () { | |
10787 | return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) | |
10788 | } | |
10789 | ||
10790 | Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) { | |
10791 | typeforce(types.tuple( | |
10792 | types.Hash256bit, | |
10793 | types.UInt32, | |
10794 | types.maybe(types.UInt32), | |
10795 | types.maybe(types.Buffer) | |
10796 | ), arguments) | |
10797 | ||
10798 | if (types.Null(sequence)) { | |
10799 | sequence = Transaction.DEFAULT_SEQUENCE | |
10800 | } | |
10801 | ||
10802 | // Add the input and return the input's index | |
10803 | return (this.ins.push({ | |
10804 | hash: hash, | |
10805 | index: index, | |
10806 | script: scriptSig || EMPTY_SCRIPT, | |
10807 | sequence: sequence, | |
10808 | witness: EMPTY_WITNESS | |
10809 | }) - 1) | |
10810 | } | |
10811 | ||
10812 | Transaction.prototype.addOutput = function (scriptPubKey, value) { | |
10813 | typeforce(types.tuple(types.Buffer, types.Satoshi), arguments) | |
10814 | ||
10815 | // Add the output and return the output's index | |
10816 | return (this.outs.push({ | |
10817 | script: scriptPubKey, | |
10818 | value: value | |
10819 | }) - 1) | |
10820 | } | |
10821 | ||
10822 | Transaction.prototype.hasWitnesses = function () { | |
10823 | return this.ins.some(function (x) { | |
10824 | return x.witness.length !== 0 | |
10825 | }) | |
10826 | } | |
10827 | ||
10828 | Transaction.prototype.weight = function () { | |
10829 | var base = this.__byteLength(false) | |
10830 | var total = this.__byteLength(true) | |
10831 | return base * 3 + total | |
10832 | } | |
10833 | ||
10834 | Transaction.prototype.virtualSize = function () { | |
10835 | return Math.ceil(this.weight() / 4) | |
10836 | } | |
10837 | ||
10838 | Transaction.prototype.byteLength = function () { | |
10839 | return this.__byteLength(true) | |
10840 | } | |
10841 | ||
10842 | Transaction.prototype.__byteLength = function (__allowWitness) { | |
10843 | var hasWitnesses = __allowWitness && this.hasWitnesses() | |
10844 | ||
10845 | return ( | |
10846 | (hasWitnesses ? 10 : 8) + | |
10847 | varuint.encodingLength(this.ins.length) + | |
10848 | varuint.encodingLength(this.outs.length) + | |
10849 | this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) + | |
10850 | this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) + | |
10851 | (hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0) | |
10852 | ) | |
10853 | } | |
10854 | ||
10855 | Transaction.prototype.clone = function () { | |
10856 | var newTx = new Transaction() | |
10857 | newTx.version = this.version | |
10858 | newTx.locktime = this.locktime | |
10859 | ||
10860 | newTx.ins = this.ins.map(function (txIn) { | |
10861 | return { | |
10862 | hash: txIn.hash, | |
10863 | index: txIn.index, | |
10864 | script: txIn.script, | |
10865 | sequence: txIn.sequence, | |
10866 | witness: txIn.witness | |
10867 | } | |
10868 | }) | |
10869 | ||
10870 | newTx.outs = this.outs.map(function (txOut) { | |
10871 | return { | |
10872 | script: txOut.script, | |
10873 | value: txOut.value | |
10874 | } | |
10875 | }) | |
10876 | ||
10877 | return newTx | |
10878 | } | |
10879 | ||
10880 | /** | |
10881 | * Hash transaction for signing a specific input. | |
10882 | * | |
10883 | * Bitcoin uses a different hash for each signed transaction input. | |
10884 | * This method copies the transaction, makes the necessary changes based on the | |
10885 | * hashType, and then hashes the result. | |
10886 | * This hash can then be used to sign the provided transaction input. | |
10887 | */ | |
10888 | Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) { | |
10889 | typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments) | |
10890 | ||
10891 | // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 | |
10892 | if (inIndex >= this.ins.length) return ONE | |
10893 | ||
10894 | // ignore OP_CODESEPARATOR | |
10895 | var ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) { | |
10896 | return x !== opcodes.OP_CODESEPARATOR | |
10897 | })) | |
10898 | ||
10899 | var txTmp = this.clone() | |
10900 | ||
10901 | // SIGHASH_NONE: ignore all outputs? (wildcard payee) | |
10902 | if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { | |
10903 | txTmp.outs = [] | |
10904 | ||
10905 | // ignore sequence numbers (except at inIndex) | |
10906 | txTmp.ins.forEach(function (input, i) { | |
10907 | if (i === inIndex) return | |
10908 | ||
10909 | input.sequence = 0 | |
10910 | }) | |
10911 | ||
10912 | // SIGHASH_SINGLE: ignore all outputs, except at the same index? | |
10913 | } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { | |
10914 | // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 | |
10915 | if (inIndex >= this.outs.length) return ONE | |
10916 | ||
10917 | // truncate outputs after | |
10918 | txTmp.outs.length = inIndex + 1 | |
10919 | ||
10920 | // "blank" outputs before | |
10921 | for (var i = 0; i < inIndex; i++) { | |
10922 | txTmp.outs[i] = BLANK_OUTPUT | |
10923 | } | |
10924 | ||
10925 | // ignore sequence numbers (except at inIndex) | |
10926 | txTmp.ins.forEach(function (input, y) { | |
10927 | if (y === inIndex) return | |
10928 | ||
10929 | input.sequence = 0 | |
10930 | }) | |
10931 | } | |
10932 | ||
10933 | // SIGHASH_ANYONECANPAY: ignore inputs entirely? | |
10934 | if (hashType & Transaction.SIGHASH_ANYONECANPAY) { | |
10935 | txTmp.ins = [txTmp.ins[inIndex]] | |
10936 | txTmp.ins[0].script = ourScript | |
10937 | ||
10938 | // SIGHASH_ALL: only ignore input scripts | |
10939 | } else { | |
10940 | // "blank" others input scripts | |
10941 | txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT }) | |
10942 | txTmp.ins[inIndex].script = ourScript | |
10943 | } | |
10944 | ||
10945 | // serialize and hash | |
10946 | var buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4) | |
10947 | buffer.writeInt32LE(hashType, buffer.length - 4) | |
10948 | txTmp.__toBuffer(buffer, 0, false) | |
10949 | ||
10950 | return bcrypto.hash256(buffer) | |
10951 | } | |
10952 | ||
10953 | Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) { | |
10954 | typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments) | |
10955 | ||
10956 | var tbuffer, toffset | |
10957 | function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) } | |
10958 | function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) } | |
10959 | function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) } | |
10960 | function writeVarInt (i) { | |
10961 | varuint.encode(i, tbuffer, toffset) | |
10962 | toffset += varuint.encode.bytes | |
10963 | } | |
10964 | function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) } | |
10965 | ||
10966 | var hashOutputs = ZERO | |
10967 | var hashPrevouts = ZERO | |
10968 | var hashSequence = ZERO | |
10969 | ||
10970 | if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { | |
10971 | tbuffer = Buffer.allocUnsafe(36 * this.ins.length) | |
10972 | toffset = 0 | |
10973 | ||
10974 | this.ins.forEach(function (txIn) { | |
10975 | writeSlice(txIn.hash) | |
10976 | writeUInt32(txIn.index) | |
10977 | }) | |
10978 | ||
10979 | hashPrevouts = bcrypto.hash256(tbuffer) | |
10980 | } | |
10981 | ||
10982 | if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) && | |
10983 | (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && | |
10984 | (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { | |
10985 | tbuffer = Buffer.allocUnsafe(4 * this.ins.length) | |
10986 | toffset = 0 | |
10987 | ||
10988 | this.ins.forEach(function (txIn) { | |
10989 | writeUInt32(txIn.sequence) | |
10990 | }) | |
10991 | ||
10992 | hashSequence = bcrypto.hash256(tbuffer) | |
10993 | } | |
10994 | ||
10995 | if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && | |
10996 | (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { | |
10997 | var txOutsSize = this.outs.reduce(function (sum, output) { | |
10998 | return sum + 8 + varSliceSize(output.script) | |
10999 | }, 0) | |
11000 | ||
11001 | tbuffer = Buffer.allocUnsafe(txOutsSize) | |
11002 | toffset = 0 | |
11003 | ||
11004 | this.outs.forEach(function (out) { | |
11005 | writeUInt64(out.value) | |
11006 | writeVarSlice(out.script) | |
11007 | }) | |
11008 | ||
11009 | hashOutputs = bcrypto.hash256(tbuffer) | |
11010 | } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) { | |
11011 | var output = this.outs[inIndex] | |
11012 | ||
11013 | tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script)) | |
11014 | toffset = 0 | |
11015 | writeUInt64(output.value) | |
11016 | writeVarSlice(output.script) | |
11017 | ||
11018 | hashOutputs = bcrypto.hash256(tbuffer) | |
11019 | } | |
11020 | ||
11021 | tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript)) | |
11022 | toffset = 0 | |
11023 | ||
11024 | var input = this.ins[inIndex] | |
11025 | writeUInt32(this.version) | |
11026 | writeSlice(hashPrevouts) | |
11027 | writeSlice(hashSequence) | |
11028 | writeSlice(input.hash) | |
11029 | writeUInt32(input.index) | |
11030 | writeVarSlice(prevOutScript) | |
11031 | writeUInt64(value) | |
11032 | writeUInt32(input.sequence) | |
11033 | writeSlice(hashOutputs) | |
11034 | writeUInt32(this.locktime) | |
11035 | writeUInt32(hashType) | |
11036 | return bcrypto.hash256(tbuffer) | |
11037 | } | |
11038 | ||
11039 | Transaction.prototype.getHash = function () { | |
11040 | return bcrypto.hash256(this.__toBuffer(undefined, undefined, false)) | |
11041 | } | |
11042 | ||
11043 | Transaction.prototype.getId = function () { | |
11044 | // transaction hash's are displayed in reverse order | |
11045 | return this.getHash().reverse().toString('hex') | |
11046 | } | |
11047 | ||
11048 | Transaction.prototype.toBuffer = function (buffer, initialOffset) { | |
11049 | return this.__toBuffer(buffer, initialOffset, true) | |
11050 | } | |
11051 | ||
11052 | Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) { | |
11053 | if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness)) | |
11054 | ||
11055 | var offset = initialOffset || 0 | |
11056 | function writeSlice (slice) { offset += slice.copy(buffer, offset) } | |
11057 | function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) } | |
11058 | function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) } | |
11059 | function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) } | |
11060 | function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) } | |
11061 | function writeVarInt (i) { | |
11062 | varuint.encode(i, buffer, offset) | |
11063 | offset += varuint.encode.bytes | |
11064 | } | |
11065 | function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) } | |
11066 | function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) } | |
11067 | ||
11068 | writeInt32(this.version) | |
11069 | ||
11070 | var hasWitnesses = __allowWitness && this.hasWitnesses() | |
11071 | ||
11072 | if (hasWitnesses) { | |
11073 | writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER) | |
11074 | writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG) | |
11075 | } | |
11076 | ||
11077 | writeVarInt(this.ins.length) | |
11078 | ||
11079 | this.ins.forEach(function (txIn) { | |
11080 | writeSlice(txIn.hash) | |
11081 | writeUInt32(txIn.index) | |
11082 | writeVarSlice(txIn.script) | |
11083 | writeUInt32(txIn.sequence) | |
11084 | }) | |
11085 | ||
11086 | writeVarInt(this.outs.length) | |
11087 | this.outs.forEach(function (txOut) { | |
11088 | if (!txOut.valueBuffer) { | |
11089 | writeUInt64(txOut.value) | |
11090 | } else { | |
11091 | writeSlice(txOut.valueBuffer) | |
11092 | } | |
11093 | ||
11094 | writeVarSlice(txOut.script) | |
11095 | }) | |
11096 | ||
11097 | if (hasWitnesses) { | |
11098 | this.ins.forEach(function (input) { | |
11099 | writeVector(input.witness) | |
11100 | }) | |
11101 | } | |
11102 | ||
11103 | writeUInt32(this.locktime) | |
11104 | ||
11105 | // avoid slicing unless necessary | |
11106 | if (initialOffset !== undefined) return buffer.slice(initialOffset, offset) | |
11107 | return buffer | |
11108 | } | |
11109 | ||
11110 | Transaction.prototype.toHex = function () { | |
11111 | return this.toBuffer().toString('hex') | |
11112 | } | |
11113 | ||
11114 | Transaction.prototype.setInputScript = function (index, scriptSig) { | |
11115 | typeforce(types.tuple(types.Number, types.Buffer), arguments) | |
11116 | ||
11117 | this.ins[index].script = scriptSig | |
11118 | } | |
11119 | ||
11120 | Transaction.prototype.setWitness = function (index, witness) { | |
11121 | typeforce(types.tuple(types.Number, [types.Buffer]), arguments) | |
11122 | ||
11123 | this.ins[index].witness = witness | |
11124 | } | |
11125 | ||
11126 | module.exports = Transaction | |
11127 | ||
11128 | },{"./bufferutils":44,"./crypto":45,"./script":52,"./types":78,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109,"varuint-bitcoin":111}],77:[function(require,module,exports){ | |
11129 | var Buffer = require('safe-buffer').Buffer | |
11130 | var baddress = require('./address') | |
11131 | var bcrypto = require('./crypto') | |
11132 | var bscript = require('./script') | |
11133 | var networks = require('./networks') | |
11134 | var ops = require('bitcoin-ops') | |
11135 | var typeforce = require('typeforce') | |
11136 | var types = require('./types') | |
11137 | var scriptTypes = bscript.types | |
11138 | var SIGNABLE = [bscript.types.P2PKH, bscript.types.P2PK, bscript.types.MULTISIG] | |
11139 | var P2SH = SIGNABLE.concat([bscript.types.P2WPKH, bscript.types.P2WSH]) | |
11140 | ||
11141 | var ECPair = require('./ecpair') | |
11142 | var ECSignature = require('./ecsignature') | |
11143 | var Transaction = require('./transaction') | |
11144 | ||
11145 | function extractChunks (type, chunks, script) { | |
11146 | var pubKeys = [] | |
11147 | var signatures = [] | |
11148 | switch (type) { | |
11149 | case scriptTypes.P2PKH: | |
11150 | // if (redeemScript) throw new Error('Nonstandard... P2SH(P2PKH)') | |
11151 | pubKeys = chunks.slice(1) | |
11152 | signatures = chunks.slice(0, 1) | |
11153 | break | |
11154 | ||
11155 | case scriptTypes.P2PK: | |
11156 | pubKeys[0] = script ? bscript.pubKey.output.decode(script) : undefined | |
11157 | signatures = chunks.slice(0, 1) | |
11158 | break | |
11159 | ||
11160 | case scriptTypes.MULTISIG: | |
11161 | if (script) { | |
11162 | var multisig = bscript.multisig.output.decode(script) | |
11163 | pubKeys = multisig.pubKeys | |
11164 | } | |
11165 | ||
11166 | signatures = chunks.slice(1).map(function (chunk) { | |
11167 | return chunk.length === 0 ? undefined : chunk | |
11168 | }) | |
11169 | break | |
11170 | } | |
11171 | ||
11172 | return { | |
11173 | pubKeys: pubKeys, | |
11174 | signatures: signatures | |
11175 | } | |
11176 | } | |
11177 | function expandInput (scriptSig, witnessStack) { | |
11178 | if (scriptSig.length === 0 && witnessStack.length === 0) return {} | |
11179 | ||
11180 | var prevOutScript | |
11181 | var prevOutType | |
11182 | var scriptType | |
11183 | var script | |
11184 | var redeemScript | |
11185 | var witnessScript | |
11186 | var witnessScriptType | |
11187 | var redeemScriptType | |
11188 | var witness = false | |
11189 | var p2wsh = false | |
11190 | var p2sh = false | |
11191 | var witnessProgram | |
11192 | var chunks | |
11193 | ||
11194 | var scriptSigChunks = bscript.decompile(scriptSig) | |
11195 | var sigType = bscript.classifyInput(scriptSigChunks, true) | |
11196 | if (sigType === scriptTypes.P2SH) { | |
11197 | p2sh = true | |
11198 | redeemScript = scriptSigChunks[scriptSigChunks.length - 1] | |
11199 | redeemScriptType = bscript.classifyOutput(redeemScript) | |
11200 | prevOutScript = bscript.scriptHash.output.encode(bcrypto.hash160(redeemScript)) | |
11201 | prevOutType = scriptTypes.P2SH | |
11202 | script = redeemScript | |
11203 | } | |
11204 | ||
11205 | var classifyWitness = bscript.classifyWitness(witnessStack) | |
11206 | if (classifyWitness === scriptTypes.P2WSH) { | |
11207 | witnessScript = witnessStack[witnessStack.length - 1] | |
11208 | witnessScriptType = bscript.classifyOutput(witnessScript) | |
11209 | p2wsh = true | |
11210 | if (scriptSig.length === 0) { | |
11211 | prevOutScript = bscript.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript)) | |
11212 | prevOutType = scriptTypes.P2WSH | |
11213 | if (typeof redeemScript !== 'undefined') { | |
11214 | throw new Error('Redeem script given when unnecessary') | |
11215 | } | |
11216 | // bare witness | |
11217 | } else { | |
11218 | if (!redeemScript) { | |
11219 | throw new Error('No redeemScript provided for P2WSH, but scriptSig non-empty') | |
11220 | } | |
11221 | witnessProgram = bscript.witnessScriptHash.output.encode(bcrypto.sha256(witnessScript)) | |
11222 | if (!redeemScript.equals(witnessProgram)) { | |
11223 | throw new Error('Redeem script didn\'t match witnessScript') | |
11224 | } | |
11225 | } | |
11226 | ||
11227 | if (SIGNABLE.indexOf(bscript.classifyOutput(witnessScript)) === -1) { | |
11228 | throw new Error('unsupported witness script') | |
11229 | } | |
11230 | script = witnessScript | |
11231 | scriptType = witnessScriptType | |
11232 | chunks = witnessStack.slice(0, -1) | |
11233 | } else if (classifyWitness === scriptTypes.P2WPKH) { | |
11234 | var key = witnessStack[witnessStack.length - 1] | |
11235 | var keyHash = bcrypto.hash160(key) | |
11236 | if (scriptSig.length === 0) { | |
11237 | prevOutScript = bscript.witnessPubKeyHash.output.encode(keyHash) | |
11238 | prevOutType = scriptTypes.P2WPKH | |
11239 | if (typeof redeemScript !== 'undefined') { | |
11240 | throw new Error('Redeem script given when unnecessary') | |
11241 | } | |
11242 | } else { | |
11243 | if (!redeemScript) { | |
11244 | throw new Error('No redeemScript provided for P2WPKH, but scriptSig wasn\'t empty') | |
11245 | } | |
11246 | witnessProgram = bscript.witnessPubKeyHash.output.encode(keyHash) | |
11247 | if (!redeemScript.equals(witnessProgram)) { | |
11248 | throw new Error('Redeem script did not have the right witness program') | |
11249 | } | |
11250 | } | |
11251 | ||
11252 | scriptType = scriptTypes.P2PKH | |
11253 | chunks = witnessStack | |
11254 | } else if (redeemScript) { | |
11255 | if (P2SH.indexOf(redeemScriptType) === -1) { | |
11256 | throw new Error('Bad redeemscript!') | |
11257 | } | |
11258 | ||
11259 | script = redeemScript | |
11260 | scriptType = redeemScriptType | |
11261 | chunks = scriptSigChunks.slice(0, -1) | |
11262 | } else { | |
11263 | prevOutType = scriptType = bscript.classifyInput(scriptSig) | |
11264 | chunks = scriptSigChunks | |
11265 | } | |
11266 | ||
11267 | var expanded = extractChunks(scriptType, chunks, script) | |
11268 | ||
11269 | var result = { | |
11270 | pubKeys: expanded.pubKeys, | |
11271 | signatures: expanded.signatures, | |
11272 | prevOutScript: prevOutScript, | |
11273 | prevOutType: prevOutType, | |
11274 | signType: scriptType, | |
11275 | signScript: script, | |
11276 | witness: Boolean(witness) | |
11277 | } | |
11278 | ||
11279 | if (p2sh) { | |
11280 | result.redeemScript = redeemScript | |
11281 | result.redeemScriptType = redeemScriptType | |
11282 | } | |
11283 | ||
11284 | if (p2wsh) { | |
11285 | result.witnessScript = witnessScript | |
11286 | result.witnessScriptType = witnessScriptType | |
11287 | } | |
11288 | ||
11289 | return result | |
11290 | } | |
11291 | ||
11292 | // could be done in expandInput, but requires the original Transaction for hashForSignature | |
11293 | function fixMultisigOrder (input, transaction, vin) { | |
11294 | if (input.redeemScriptType !== scriptTypes.MULTISIG || !input.redeemScript) return | |
11295 | if (input.pubKeys.length === input.signatures.length) return | |
11296 | ||
11297 | var unmatched = input.signatures.concat() | |
11298 | ||
11299 | input.signatures = input.pubKeys.map(function (pubKey) { | |
11300 | var keyPair = ECPair.fromPublicKeyBuffer(pubKey) | |
11301 | var match | |
11302 | ||
11303 | // check for a signature | |
11304 | unmatched.some(function (signature, i) { | |
11305 | // skip if undefined || OP_0 | |
11306 | if (!signature) return false | |
11307 | ||
11308 | // TODO: avoid O(n) hashForSignature | |
11309 | var parsed = ECSignature.parseScriptSignature(signature) | |
11310 | var hash = transaction.hashForSignature(vin, input.redeemScript, parsed.hashType) | |
11311 | ||
11312 | // skip if signature does not match pubKey | |
11313 | if (!keyPair.verify(hash, parsed.signature)) return false | |
11314 | ||
11315 | // remove matched signature from unmatched | |
11316 | unmatched[i] = undefined | |
11317 | match = signature | |
11318 | ||
11319 | return true | |
11320 | }) | |
11321 | ||
11322 | return match | |
11323 | }) | |
11324 | } | |
11325 | ||
11326 | function expandOutput (script, scriptType, ourPubKey) { | |
11327 | typeforce(types.Buffer, script) | |
11328 | ||
11329 | var scriptChunks = bscript.decompile(script) | |
11330 | if (!scriptType) { | |
11331 | scriptType = bscript.classifyOutput(script) | |
11332 | } | |
11333 | ||
11334 | var pubKeys = [] | |
11335 | ||
11336 | switch (scriptType) { | |
11337 | // does our hash160(pubKey) match the output scripts? | |
11338 | case scriptTypes.P2PKH: | |
11339 | if (!ourPubKey) break | |
11340 | ||
11341 | var pkh1 = scriptChunks[2] | |
11342 | var pkh2 = bcrypto.hash160(ourPubKey) | |
11343 | if (pkh1.equals(pkh2)) pubKeys = [ourPubKey] | |
11344 | break | |
11345 | ||
11346 | // does our hash160(pubKey) match the output scripts? | |
11347 | case scriptTypes.P2WPKH: | |
11348 | if (!ourPubKey) break | |
11349 | ||
11350 | var wpkh1 = scriptChunks[1] | |
11351 | var wpkh2 = bcrypto.hash160(ourPubKey) | |
11352 | if (wpkh1.equals(wpkh2)) pubKeys = [ourPubKey] | |
11353 | break | |
11354 | ||
11355 | case scriptTypes.P2PK: | |
11356 | pubKeys = scriptChunks.slice(0, 1) | |
11357 | break | |
11358 | ||
11359 | case scriptTypes.MULTISIG: | |
11360 | pubKeys = scriptChunks.slice(1, -2) | |
11361 | break | |
11362 | ||
11363 | default: return { scriptType: scriptType } | |
11364 | } | |
11365 | ||
11366 | return { | |
11367 | pubKeys: pubKeys, | |
11368 | scriptType: scriptType, | |
11369 | signatures: pubKeys.map(function () { return undefined }) | |
11370 | } | |
11371 | } | |
11372 | ||
11373 | function checkP2shInput (input, redeemScriptHash) { | |
11374 | if (input.prevOutType) { | |
11375 | if (input.prevOutType !== scriptTypes.P2SH) throw new Error('PrevOutScript must be P2SH') | |
11376 | ||
11377 | var prevOutScriptScriptHash = bscript.decompile(input.prevOutScript)[1] | |
11378 | if (!prevOutScriptScriptHash.equals(redeemScriptHash)) throw new Error('Inconsistent hash160(RedeemScript)') | |
11379 | } | |
11380 | } | |
11381 | ||
11382 | function checkP2WSHInput (input, witnessScriptHash) { | |
11383 | if (input.prevOutType) { | |
11384 | if (input.prevOutType !== scriptTypes.P2WSH) throw new Error('PrevOutScript must be P2WSH') | |
11385 | ||
11386 | var scriptHash = bscript.decompile(input.prevOutScript)[1] | |
11387 | if (!scriptHash.equals(witnessScriptHash)) throw new Error('Inconsistent sha25(WitnessScript)') | |
11388 | } | |
11389 | } | |
11390 | ||
11391 | function prepareInput (input, kpPubKey, redeemScript, witnessValue, witnessScript) { | |
11392 | var expanded | |
11393 | var prevOutType | |
11394 | var prevOutScript | |
11395 | ||
11396 | var p2sh = false | |
11397 | var p2shType | |
11398 | var redeemScriptHash | |
11399 | ||
11400 | var witness = false | |
11401 | var p2wsh = false | |
11402 | var witnessType | |
11403 | var witnessScriptHash | |
11404 | ||
11405 | var signType | |
11406 | var signScript | |
11407 | ||
11408 | if (redeemScript && witnessScript) { | |
11409 | redeemScriptHash = bcrypto.hash160(redeemScript) | |
11410 | witnessScriptHash = bcrypto.sha256(witnessScript) | |
11411 | checkP2shInput(input, redeemScriptHash) | |
11412 | ||
11413 | if (!redeemScript.equals(bscript.witnessScriptHash.output.encode(witnessScriptHash))) throw new Error('Witness script inconsistent with redeem script') | |
11414 | ||
11415 | expanded = expandOutput(witnessScript, undefined, kpPubKey) | |
11416 | if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"') | |
11417 | prevOutType = bscript.types.P2SH | |
11418 | prevOutScript = bscript.scriptHash.output.encode(redeemScriptHash) | |
11419 | p2sh = witness = p2wsh = true | |
11420 | p2shType = bscript.types.P2WSH | |
11421 | signType = witnessType = expanded.scriptType | |
11422 | signScript = witnessScript | |
11423 | } else if (redeemScript) { | |
11424 | redeemScriptHash = bcrypto.hash160(redeemScript) | |
11425 | checkP2shInput(input, redeemScriptHash) | |
11426 | ||
11427 | expanded = expandOutput(redeemScript, undefined, kpPubKey) | |
11428 | if (!expanded.pubKeys) throw new Error('RedeemScript not supported "' + bscript.toASM(redeemScript) + '"') | |
11429 | ||
11430 | prevOutType = bscript.types.P2SH | |
11431 | prevOutScript = bscript.scriptHash.output.encode(redeemScriptHash) | |
11432 | p2sh = true | |
11433 | signType = p2shType = expanded.scriptType | |
11434 | signScript = redeemScript | |
11435 | witness = signType === bscript.types.P2WPKH | |
11436 | } else if (witnessScript) { | |
11437 | witnessScriptHash = bcrypto.sha256(witnessScript) | |
11438 | checkP2WSHInput(input, witnessScriptHash) | |
11439 | ||
11440 | expanded = expandOutput(witnessScript, undefined, kpPubKey) | |
11441 | if (!expanded.pubKeys) throw new Error('WitnessScript not supported "' + bscript.toASM(redeemScript) + '"') | |
11442 | ||
11443 | prevOutType = bscript.types.P2WSH | |
11444 | prevOutScript = bscript.witnessScriptHash.output.encode(witnessScriptHash) | |
11445 | witness = p2wsh = true | |
11446 | signType = witnessType = expanded.scriptType | |
11447 | signScript = witnessScript | |
11448 | } else if (input.prevOutType) { | |
11449 | // embedded scripts are not possible without a redeemScript | |
11450 | if (input.prevOutType === scriptTypes.P2SH || | |
11451 | input.prevOutType === scriptTypes.P2WSH) { | |
11452 | throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript') | |
11453 | } | |
11454 | ||
11455 | prevOutType = input.prevOutType | |
11456 | prevOutScript = input.prevOutScript | |
11457 | expanded = expandOutput(input.prevOutScript, input.prevOutType, kpPubKey) | |
11458 | if (!expanded.pubKeys) return | |
11459 | ||
11460 | witness = (input.prevOutType === scriptTypes.P2WPKH) | |
11461 | signType = prevOutType | |
11462 | signScript = prevOutScript | |
11463 | } else { | |
11464 | prevOutScript = bscript.pubKeyHash.output.encode(bcrypto.hash160(kpPubKey)) | |
11465 | expanded = expandOutput(prevOutScript, scriptTypes.P2PKH, kpPubKey) | |
11466 | prevOutType = scriptTypes.P2PKH | |
11467 | witness = false | |
11468 | signType = prevOutType | |
11469 | signScript = prevOutScript | |
11470 | } | |
11471 | ||
11472 | if (witness && !types.Satoshi(witnessValue)) { | |
11473 | throw new Error('Input was witness but not given witness value') | |
11474 | } | |
11475 | ||
11476 | if (signType === scriptTypes.P2WPKH) { | |
11477 | signScript = bscript.pubKeyHash.output.encode(bscript.witnessPubKeyHash.output.decode(signScript)) | |
11478 | } | |
11479 | ||
11480 | if (p2sh) { | |
11481 | input.redeemScript = redeemScript | |
11482 | input.redeemScriptType = p2shType | |
11483 | } | |
11484 | ||
11485 | if (p2wsh) { | |
11486 | input.witnessScript = witnessScript | |
11487 | input.witnessScriptType = witnessType | |
11488 | } | |
11489 | ||
11490 | input.pubKeys = expanded.pubKeys | |
11491 | input.signatures = expanded.signatures | |
11492 | input.signScript = signScript | |
11493 | input.signType = signType | |
11494 | input.prevOutScript = prevOutScript | |
11495 | input.prevOutType = prevOutType | |
11496 | input.witness = witness | |
11497 | } | |
11498 | ||
11499 | function buildStack (type, signatures, pubKeys, allowIncomplete) { | |
11500 | if (type === scriptTypes.P2PKH) { | |
11501 | if (signatures.length === 1 && Buffer.isBuffer(signatures[0]) && pubKeys.length === 1) return bscript.pubKeyHash.input.encodeStack(signatures[0], pubKeys[0]) | |
11502 | } else if (type === scriptTypes.P2PK) { | |
11503 | if (signatures.length === 1 && Buffer.isBuffer(signatures[0])) return bscript.pubKey.input.encodeStack(signatures[0]) | |
11504 | } else if (type === scriptTypes.MULTISIG) { | |
11505 | if (signatures.length > 0) { | |
11506 | signatures = signatures.map(function (signature) { | |
11507 | return signature || ops.OP_0 | |
11508 | }) | |
11509 | if (!allowIncomplete) { | |
11510 | // remove blank signatures | |
11511 | signatures = signatures.filter(function (x) { return x !== ops.OP_0 }) | |
11512 | } | |
11513 | ||
11514 | return bscript.multisig.input.encodeStack(signatures /* see if it's necessary first */) | |
11515 | } | |
11516 | } else { | |
11517 | throw new Error('Not yet supported') | |
11518 | } | |
11519 | ||
11520 | if (!allowIncomplete) throw new Error('Not enough signatures provided') | |
11521 | ||
11522 | return [] | |
11523 | } | |
11524 | ||
11525 | function buildInput (input, allowIncomplete) { | |
11526 | var scriptType = input.prevOutType | |
11527 | var sig = [] | |
11528 | var witness = [] | |
11529 | if (SIGNABLE.indexOf(scriptType) !== -1) { | |
11530 | sig = buildStack(scriptType, input.signatures, input.pubKeys, allowIncomplete) | |
11531 | } | |
11532 | ||
11533 | var p2sh = false | |
11534 | if (scriptType === bscript.types.P2SH) { | |
11535 | // We can remove this error later when we have a guarantee prepareInput | |
11536 | // rejects unsignable scripts - it MUST be signable at this point. | |
11537 | if (P2SH.indexOf(input.redeemScriptType) === -1) { | |
11538 | throw new Error('Impossible to sign this type') | |
11539 | } | |
11540 | p2sh = true | |
11541 | if (SIGNABLE.indexOf(input.redeemScriptType) !== -1) { | |
11542 | sig = buildStack(input.redeemScriptType, input.signatures, input.pubKeys, allowIncomplete) | |
11543 | } | |
11544 | // If it wasn't SIGNABLE, it's witness, defer to that | |
11545 | scriptType = input.redeemScriptType | |
11546 | } | |
11547 | ||
11548 | if (scriptType === bscript.types.P2WPKH) { | |
11549 | // P2WPKH is a special case of P2PKH | |
11550 | witness = buildStack(bscript.types.P2PKH, input.signatures, input.pubKeys, allowIncomplete) | |
11551 | } else if (scriptType === bscript.types.P2WSH) { | |
11552 | // We can remove this check later | |
11553 | if (SIGNABLE.indexOf(input.witnessScriptType) !== -1) { | |
11554 | witness = buildStack(input.witnessScriptType, input.signatures, input.pubKeys, allowIncomplete) | |
11555 | witness.push(input.witnessScript) | |
11556 | } else { | |
11557 | // We can remove this error later when we have a guarantee prepareInput | |
11558 | // rejects unsignble scripts - it MUST be signable at this point. | |
11559 | throw new Error() | |
11560 | } | |
11561 | ||
11562 | scriptType = input.witnessScriptType | |
11563 | } | |
11564 | ||
11565 | // append redeemScript if necessary | |
11566 | if (p2sh) { | |
11567 | sig.push(input.redeemScript) | |
11568 | } | |
11569 | ||
11570 | return { | |
11571 | type: scriptType, | |
11572 | script: bscript.compile(sig), | |
11573 | witness: witness | |
11574 | } | |
11575 | } | |
11576 | ||
11577 | function TransactionBuilder (network, maximumFeeRate) { | |
11578 | this.prevTxMap = {} | |
11579 | this.network = network || networks.bitcoin | |
11580 | ||
11581 | // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth) | |
11582 | this.maximumFeeRate = maximumFeeRate || 1000 | |
11583 | ||
11584 | this.inputs = [] | |
11585 | this.tx = new Transaction() | |
11586 | } | |
11587 | ||
11588 | TransactionBuilder.prototype.setLockTime = function (locktime) { | |
11589 | typeforce(types.UInt32, locktime) | |
11590 | ||
11591 | // if any signatures exist, throw | |
11592 | if (this.inputs.some(function (input) { | |
11593 | if (!input.signatures) return false | |
11594 | ||
11595 | return input.signatures.some(function (s) { return s }) | |
11596 | })) { | |
11597 | throw new Error('No, this would invalidate signatures') | |
11598 | } | |
11599 | ||
11600 | this.tx.locktime = locktime | |
11601 | } | |
11602 | ||
11603 | TransactionBuilder.prototype.setVersion = function (version) { | |
11604 | typeforce(types.UInt32, version) | |
11605 | ||
11606 | // XXX: this might eventually become more complex depending on what the versions represent | |
11607 | this.tx.version = version | |
11608 | } | |
11609 | ||
11610 | TransactionBuilder.fromTransaction = function (transaction, network) { | |
11611 | var txb = new TransactionBuilder(network) | |
11612 | ||
11613 | // Copy transaction fields | |
11614 | txb.setVersion(transaction.version) | |
11615 | txb.setLockTime(transaction.locktime) | |
11616 | ||
11617 | // Copy outputs (done first to avoid signature invalidation) | |
11618 | transaction.outs.forEach(function (txOut) { | |
11619 | txb.addOutput(txOut.script, txOut.value) | |
11620 | }) | |
11621 | ||
11622 | // Copy inputs | |
11623 | transaction.ins.forEach(function (txIn) { | |
11624 | txb.__addInputUnsafe(txIn.hash, txIn.index, { | |
11625 | sequence: txIn.sequence, | |
11626 | script: txIn.script, | |
11627 | witness: txIn.witness | |
11628 | }) | |
11629 | }) | |
11630 | ||
11631 | // fix some things not possible through the public API | |
11632 | txb.inputs.forEach(function (input, i) { | |
11633 | fixMultisigOrder(input, transaction, i) | |
11634 | }) | |
11635 | ||
11636 | return txb | |
11637 | } | |
11638 | ||
11639 | TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) { | |
11640 | if (!this.__canModifyInputs()) { | |
11641 | throw new Error('No, this would invalidate signatures') | |
11642 | } | |
11643 | ||
11644 | var value | |
11645 | ||
11646 | // is it a hex string? | |
11647 | if (typeof txHash === 'string') { | |
11648 | // transaction hashs's are displayed in reverse order, un-reverse it | |
11649 | txHash = Buffer.from(txHash, 'hex').reverse() | |
11650 | ||
11651 | // is it a Transaction object? | |
11652 | } else if (txHash instanceof Transaction) { | |
11653 | var txOut = txHash.outs[vout] | |
11654 | prevOutScript = txOut.script | |
11655 | value = txOut.value | |
11656 | ||
11657 | txHash = txHash.getHash() | |
11658 | } | |
11659 | ||
11660 | return this.__addInputUnsafe(txHash, vout, { | |
11661 | sequence: sequence, | |
11662 | prevOutScript: prevOutScript, | |
11663 | value: value | |
11664 | }) | |
11665 | } | |
11666 | ||
11667 | TransactionBuilder.prototype.__addInputUnsafe = function (txHash, vout, options) { | |
11668 | if (Transaction.isCoinbaseHash(txHash)) { | |
11669 | throw new Error('coinbase inputs not supported') | |
11670 | } | |
11671 | ||
11672 | var prevTxOut = txHash.toString('hex') + ':' + vout | |
11673 | if (this.prevTxMap[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut) | |
11674 | ||
11675 | var input = {} | |
11676 | ||
11677 | // derive what we can from the scriptSig | |
11678 | if (options.script !== undefined) { | |
11679 | input = expandInput(options.script, options.witness || []) | |
11680 | } | |
11681 | ||
11682 | // if an input value was given, retain it | |
11683 | if (options.value !== undefined) { | |
11684 | input.value = options.value | |
11685 | } | |
11686 | ||
11687 | // derive what we can from the previous transactions output script | |
11688 | if (!input.prevOutScript && options.prevOutScript) { | |
11689 | var prevOutType | |
11690 | ||
11691 | if (!input.pubKeys && !input.signatures) { | |
11692 | var expanded = expandOutput(options.prevOutScript) | |
11693 | ||
11694 | if (expanded.pubKeys) { | |
11695 | input.pubKeys = expanded.pubKeys | |
11696 | input.signatures = expanded.signatures | |
11697 | } | |
11698 | ||
11699 | prevOutType = expanded.scriptType | |
11700 | } | |
11701 | ||
11702 | input.prevOutScript = options.prevOutScript | |
11703 | input.prevOutType = prevOutType || bscript.classifyOutput(options.prevOutScript) | |
11704 | } | |
11705 | ||
11706 | var vin = this.tx.addInput(txHash, vout, options.sequence, options.scriptSig) | |
11707 | this.inputs[vin] = input | |
11708 | this.prevTxMap[prevTxOut] = vin | |
11709 | ||
11710 | return vin | |
11711 | } | |
11712 | ||
11713 | TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) { | |
11714 | if (!this.__canModifyOutputs()) { | |
11715 | throw new Error('No, this would invalidate signatures') | |
11716 | } | |
11717 | ||
11718 | // Attempt to get a script if it's a base58 address string | |
11719 | if (typeof scriptPubKey === 'string') { | |
11720 | scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network) | |
11721 | } | |
11722 | ||
11723 | return this.tx.addOutput(scriptPubKey, value) | |
11724 | } | |
11725 | ||
11726 | TransactionBuilder.prototype.build = function () { | |
11727 | return this.__build(false) | |
11728 | } | |
11729 | TransactionBuilder.prototype.buildIncomplete = function () { | |
11730 | return this.__build(true) | |
11731 | } | |
11732 | ||
11733 | TransactionBuilder.prototype.__build = function (allowIncomplete) { | |
11734 | if (!allowIncomplete) { | |
11735 | if (!this.tx.ins.length) throw new Error('Transaction has no inputs') | |
11736 | if (!this.tx.outs.length) throw new Error('Transaction has no outputs') | |
11737 | } | |
11738 | ||
11739 | var tx = this.tx.clone() | |
11740 | // Create script signatures from inputs | |
11741 | this.inputs.forEach(function (input, i) { | |
11742 | var scriptType = input.witnessScriptType || input.redeemScriptType || input.prevOutType | |
11743 | if (!scriptType && !allowIncomplete) throw new Error('Transaction is not complete') | |
11744 | var result = buildInput(input, allowIncomplete) | |
11745 | ||
11746 | // skip if no result | |
11747 | if (!allowIncomplete) { | |
11748 | if (SIGNABLE.indexOf(result.type) === -1 && result.type !== bscript.types.P2WPKH) { | |
11749 | throw new Error(result.type + ' not supported') | |
11750 | } | |
11751 | } | |
11752 | ||
11753 | tx.setInputScript(i, result.script) | |
11754 | tx.setWitness(i, result.witness) | |
11755 | }) | |
11756 | ||
11757 | if (!allowIncomplete) { | |
11758 | // do not rely on this, its merely a last resort | |
11759 | if (this.__overMaximumFees(tx.byteLength())) { | |
11760 | throw new Error('Transaction has absurd fees') | |
11761 | } | |
11762 | } | |
11763 | ||
11764 | return tx | |
11765 | } | |
11766 | ||
11767 | function canSign (input) { | |
11768 | return input.prevOutScript !== undefined && | |
11769 | input.signScript !== undefined && | |
11770 | input.pubKeys !== undefined && | |
11771 | input.signatures !== undefined && | |
11772 | input.signatures.length === input.pubKeys.length && | |
11773 | input.pubKeys.length > 0 && | |
11774 | input.witness !== undefined | |
11775 | } | |
11776 | ||
11777 | TransactionBuilder.prototype.sign = function (vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) { | |
11778 | if (keyPair.network !== this.network) throw new Error('Inconsistent network') | |
11779 | if (!this.inputs[vin]) throw new Error('No input at index: ' + vin) | |
11780 | hashType = hashType || Transaction.SIGHASH_ALL | |
11781 | ||
11782 | var input = this.inputs[vin] | |
11783 | ||
11784 | // if redeemScript was previously provided, enforce consistency | |
11785 | if (input.redeemScript !== undefined && | |
11786 | redeemScript && | |
11787 | !input.redeemScript.equals(redeemScript)) { | |
11788 | throw new Error('Inconsistent redeemScript') | |
11789 | } | |
11790 | ||
11791 | var kpPubKey = keyPair.getPublicKeyBuffer() | |
11792 | if (!canSign(input)) { | |
11793 | prepareInput(input, kpPubKey, redeemScript, witnessValue, witnessScript) | |
11794 | if (!canSign(input)) throw Error(input.prevOutType + ' not supported') | |
11795 | } | |
11796 | ||
11797 | // ready to sign | |
11798 | var signatureHash | |
11799 | if (input.witness) { | |
11800 | signatureHash = this.tx.hashForWitnessV0(vin, input.signScript, witnessValue, hashType) | |
11801 | } else { | |
11802 | signatureHash = this.tx.hashForSignature(vin, input.signScript, hashType) | |
11803 | } | |
11804 | // enforce in order signing of public keys | |
11805 | var signed = input.pubKeys.some(function (pubKey, i) { | |
11806 | if (!kpPubKey.equals(pubKey)) return false | |
11807 | if (input.signatures[i]) throw new Error('Signature already exists') | |
11808 | ||
11809 | input.signatures[i] = keyPair.sign(signatureHash).toScriptSignature(hashType) | |
11810 | return true | |
11811 | }) | |
11812 | ||
11813 | if (!signed) throw new Error('Key pair cannot sign for this input') | |
11814 | } | |
11815 | ||
11816 | function signatureHashType (buffer) { | |
11817 | return buffer.readUInt8(buffer.length - 1) | |
11818 | } | |
11819 | ||
11820 | TransactionBuilder.prototype.__canModifyInputs = function () { | |
11821 | return this.inputs.every(function (input) { | |
11822 | // any signatures? | |
11823 | if (input.signatures === undefined) return true | |
11824 | ||
11825 | return input.signatures.every(function (signature) { | |
11826 | if (!signature) return true | |
11827 | var hashType = signatureHashType(signature) | |
11828 | ||
11829 | // if SIGHASH_ANYONECANPAY is set, signatures would not | |
11830 | // be invalidated by more inputs | |
11831 | return hashType & Transaction.SIGHASH_ANYONECANPAY | |
11832 | }) | |
11833 | }) | |
11834 | } | |
11835 | ||
11836 | TransactionBuilder.prototype.__canModifyOutputs = function () { | |
11837 | var nInputs = this.tx.ins.length | |
11838 | var nOutputs = this.tx.outs.length | |
11839 | ||
11840 | return this.inputs.every(function (input) { | |
11841 | if (input.signatures === undefined) return true | |
11842 | ||
11843 | return input.signatures.every(function (signature) { | |
11844 | if (!signature) return true | |
11845 | var hashType = signatureHashType(signature) | |
11846 | ||
11847 | var hashTypeMod = hashType & 0x1f | |
11848 | if (hashTypeMod === Transaction.SIGHASH_NONE) return true | |
11849 | if (hashTypeMod === Transaction.SIGHASH_SINGLE) { | |
11850 | // if SIGHASH_SINGLE is set, and nInputs > nOutputs | |
11851 | // some signatures would be invalidated by the addition | |
11852 | // of more outputs | |
11853 | return nInputs <= nOutputs | |
11854 | } | |
11855 | }) | |
11856 | }) | |
11857 | } | |
11858 | ||
11859 | TransactionBuilder.prototype.__overMaximumFees = function (bytes) { | |
11860 | // not all inputs will have .value defined | |
11861 | var incoming = this.inputs.reduce(function (a, x) { return a + (x.value >>> 0) }, 0) | |
11862 | ||
11863 | // but all outputs do, and if we have any input value | |
11864 | // we can immediately determine if the outputs are too small | |
11865 | var outgoing = this.tx.outs.reduce(function (a, x) { return a + x.value }, 0) | |
11866 | var fee = incoming - outgoing | |
11867 | var feeRate = fee / bytes | |
11868 | ||
11869 | return feeRate > this.maximumFeeRate | |
11870 | } | |
11871 | ||
11872 | module.exports = TransactionBuilder | |
11873 | ||
11874 | },{"./address":42,"./crypto":45,"./ecpair":47,"./ecsignature":48,"./networks":51,"./script":52,"./transaction":76,"./types":78,"bitcoin-ops":40,"safe-buffer":98,"typeforce":109}],78:[function(require,module,exports){ | |
11875 | var typeforce = require('typeforce') | |
11876 | ||
11877 | var UINT31_MAX = Math.pow(2, 31) - 1 | |
11878 | function UInt31 (value) { | |
11879 | return typeforce.UInt32(value) && value <= UINT31_MAX | |
11880 | } | |
11881 | ||
11882 | function BIP32Path (value) { | |
11883 | return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) | |
11884 | } | |
11885 | BIP32Path.toJSON = function () { return 'BIP32 derivation path' } | |
11886 | ||
11887 | var SATOSHI_MAX = 21 * 1e14 | |
11888 | function Satoshi (value) { | |
11889 | return typeforce.UInt53(value) && value <= SATOSHI_MAX | |
11890 | } | |
11891 | ||
11892 | // external dependent types | |
11893 | var BigInt = typeforce.quacksLike('BigInteger') | |
11894 | var ECPoint = typeforce.quacksLike('Point') | |
11895 | ||
11896 | // exposed, external API | |
11897 | var ECSignature = typeforce.compile({ r: BigInt, s: BigInt }) | |
11898 | var Network = typeforce.compile({ | |
11899 | messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String), | |
11900 | bip32: { | |
11901 | public: typeforce.UInt32, | |
11902 | private: typeforce.UInt32 | |
11903 | }, | |
11904 | pubKeyHash: typeforce.UInt8, | |
11905 | scriptHash: typeforce.UInt8, | |
11906 | wif: typeforce.UInt8 | |
11907 | }) | |
11908 | ||
11909 | // extend typeforce types with ours | |
11910 | var types = { | |
11911 | BigInt: BigInt, | |
11912 | BIP32Path: BIP32Path, | |
11913 | Buffer256bit: typeforce.BufferN(32), | |
11914 | ECPoint: ECPoint, | |
11915 | ECSignature: ECSignature, | |
11916 | Hash160bit: typeforce.BufferN(20), | |
11917 | Hash256bit: typeforce.BufferN(32), | |
11918 | Network: Network, | |
11919 | Satoshi: Satoshi, | |
11920 | UInt31: UInt31 | |
11921 | } | |
11922 | ||
11923 | for (var typeName in typeforce) { | |
11924 | types[typeName] = typeforce[typeName] | |
11925 | } | |
11926 | ||
11927 | module.exports = types | |
11928 | ||
11929 | },{"typeforce":109}],79:[function(require,module,exports){ | |
11930 | var basex = require('base-x') | |
11931 | var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' | |
11932 | ||
11933 | module.exports = basex(ALPHABET) | |
11934 | ||
11935 | },{"base-x":34}],80:[function(require,module,exports){ | |
11936 | (function (Buffer){ | |
11937 | 'use strict' | |
11938 | ||
11939 | var base58 = require('bs58') | |
11940 | var createHash = require('create-hash') | |
11941 | ||
11942 | // SHA256(SHA256(buffer)) | |
11943 | function sha256x2 (buffer) { | |
11944 | var tmp = createHash('sha256').update(buffer).digest() | |
11945 | return createHash('sha256').update(tmp).digest() | |
11946 | } | |
11947 | ||
11948 | // Encode a buffer as a base58-check encoded string | |
11949 | function encode (payload) { | |
11950 | var checksum = sha256x2(payload) | |
11951 | ||
11952 | return base58.encode(Buffer.concat([ | |
11953 | payload, | |
11954 | checksum | |
11955 | ], payload.length + 4)) | |
11956 | } | |
11957 | ||
11958 | function decodeRaw (buffer) { | |
11959 | var payload = buffer.slice(0, -4) | |
11960 | var checksum = buffer.slice(-4) | |
11961 | var newChecksum = sha256x2(payload) | |
11962 | ||
11963 | if (checksum[0] ^ newChecksum[0] | | |
11964 | checksum[1] ^ newChecksum[1] | | |
11965 | checksum[2] ^ newChecksum[2] | | |
11966 | checksum[3] ^ newChecksum[3]) return | |
11967 | ||
11968 | return payload | |
11969 | } | |
11970 | ||
11971 | // Decode a base58-check encoded string to a buffer, no result if checksum is wrong | |
11972 | function decodeUnsafe (string) { | |
11973 | var buffer = base58.decodeUnsafe(string) | |
11974 | if (!buffer) return | |
11975 | ||
11976 | return decodeRaw(buffer) | |
11977 | } | |
11978 | ||
11979 | function decode (string) { | |
11980 | var buffer = base58.decode(string) | |
11981 | var payload = decodeRaw(buffer) | |
11982 | if (!payload) throw new Error('Invalid checksum') | |
11983 | return payload | |
11984 | } | |
11985 | ||
11986 | module.exports = { | |
11987 | encode: encode, | |
11988 | decode: decode, | |
11989 | decodeUnsafe: decodeUnsafe | |
11990 | } | |
11991 | ||
11992 | }).call(this,require("buffer").Buffer) | |
11993 | },{"bs58":79,"buffer":4,"create-hash":82}],81:[function(require,module,exports){ | |
11994 | var Buffer = require('safe-buffer').Buffer | |
11995 | var Transform = require('stream').Transform | |
11996 | var StringDecoder = require('string_decoder').StringDecoder | |
11997 | var inherits = require('inherits') | |
11998 | ||
11999 | function CipherBase (hashMode) { | |
12000 | Transform.call(this) | |
12001 | this.hashMode = typeof hashMode === 'string' | |
12002 | if (this.hashMode) { | |
12003 | this[hashMode] = this._finalOrDigest | |
12004 | } else { | |
12005 | this.final = this._finalOrDigest | |
12006 | } | |
12007 | if (this._final) { | |
12008 | this.__final = this._final | |
12009 | this._final = null | |
12010 | } | |
12011 | this._decoder = null | |
12012 | this._encoding = null | |
12013 | } | |
12014 | inherits(CipherBase, Transform) | |
12015 | ||
12016 | CipherBase.prototype.update = function (data, inputEnc, outputEnc) { | |
12017 | if (typeof data === 'string') { | |
12018 | data = Buffer.from(data, inputEnc) | |
12019 | } | |
12020 | ||
12021 | var outData = this._update(data) | |
12022 | if (this.hashMode) return this | |
12023 | ||
12024 | if (outputEnc) { | |
12025 | outData = this._toString(outData, outputEnc) | |
12026 | } | |
12027 | ||
12028 | return outData | |
12029 | } | |
12030 | ||
12031 | CipherBase.prototype.setAutoPadding = function () {} | |
12032 | CipherBase.prototype.getAuthTag = function () { | |
12033 | throw new Error('trying to get auth tag in unsupported state') | |
12034 | } | |
12035 | ||
12036 | CipherBase.prototype.setAuthTag = function () { | |
12037 | throw new Error('trying to set auth tag in unsupported state') | |
12038 | } | |
12039 | ||
12040 | CipherBase.prototype.setAAD = function () { | |
12041 | throw new Error('trying to set aad in unsupported state') | |
12042 | } | |
12043 | ||
12044 | CipherBase.prototype._transform = function (data, _, next) { | |
12045 | var err | |
12046 | try { | |
12047 | if (this.hashMode) { | |
12048 | this._update(data) | |
12049 | } else { | |
12050 | this.push(this._update(data)) | |
12051 | } | |
12052 | } catch (e) { | |
12053 | err = e | |
12054 | } finally { | |
12055 | next(err) | |
12056 | } | |
12057 | } | |
12058 | CipherBase.prototype._flush = function (done) { | |
12059 | var err | |
12060 | try { | |
12061 | this.push(this.__final()) | |
12062 | } catch (e) { | |
12063 | err = e | |
12064 | } | |
12065 | ||
12066 | done(err) | |
12067 | } | |
12068 | CipherBase.prototype._finalOrDigest = function (outputEnc) { | |
12069 | var outData = this.__final() || Buffer.alloc(0) | |
12070 | if (outputEnc) { | |
12071 | outData = this._toString(outData, outputEnc, true) | |
12072 | } | |
12073 | return outData | |
12074 | } | |
12075 | ||
12076 | CipherBase.prototype._toString = function (value, enc, fin) { | |
12077 | if (!this._decoder) { | |
12078 | this._decoder = new StringDecoder(enc) | |
12079 | this._encoding = enc | |
12080 | } | |
12081 | ||
12082 | if (this._encoding !== enc) throw new Error('can\'t switch encodings') | |
12083 | ||
12084 | var out = this._decoder.write(value) | |
12085 | if (fin) { | |
12086 | out += this._decoder.end() | |
12087 | } | |
12088 | ||
12089 | return out | |
12090 | } | |
12091 | ||
12092 | module.exports = CipherBase | |
12093 | ||
12094 | },{"inherits":93,"safe-buffer":98,"stream":27,"string_decoder":28}],82:[function(require,module,exports){ | |
12095 | (function (Buffer){ | |
12096 | 'use strict' | |
12097 | var inherits = require('inherits') | |
12098 | var md5 = require('./md5') | |
12099 | var RIPEMD160 = require('ripemd160') | |
12100 | var sha = require('sha.js') | |
12101 | ||
12102 | var Base = require('cipher-base') | |
12103 | ||
12104 | function HashNoConstructor (hash) { | |
12105 | Base.call(this, 'digest') | |
12106 | ||
12107 | this._hash = hash | |
12108 | this.buffers = [] | |
12109 | } | |
12110 | ||
12111 | inherits(HashNoConstructor, Base) | |
12112 | ||
12113 | HashNoConstructor.prototype._update = function (data) { | |
12114 | this.buffers.push(data) | |
12115 | } | |
12116 | ||
12117 | HashNoConstructor.prototype._final = function () { | |
12118 | var buf = Buffer.concat(this.buffers) | |
12119 | var r = this._hash(buf) | |
12120 | this.buffers = null | |
12121 | ||
12122 | return r | |
12123 | } | |
12124 | ||
12125 | function Hash (hash) { | |
12126 | Base.call(this, 'digest') | |
12127 | ||
12128 | this._hash = hash | |
12129 | } | |
12130 | ||
12131 | inherits(Hash, Base) | |
12132 | ||
12133 | Hash.prototype._update = function (data) { | |
12134 | this._hash.update(data) | |
12135 | } | |
12136 | ||
12137 | Hash.prototype._final = function () { | |
12138 | return this._hash.digest() | |
12139 | } | |
12140 | ||
12141 | module.exports = function createHash (alg) { | |
12142 | alg = alg.toLowerCase() | |
12143 | if (alg === 'md5') return new HashNoConstructor(md5) | |
12144 | if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160()) | |
12145 | ||
12146 | return new Hash(sha(alg)) | |
12147 | } | |
12148 | ||
12149 | }).call(this,require("buffer").Buffer) | |
12150 | },{"./md5":84,"buffer":4,"cipher-base":81,"inherits":93,"ripemd160":97,"sha.js":100}],83:[function(require,module,exports){ | |
12151 | (function (Buffer){ | |
12152 | 'use strict' | |
12153 | var intSize = 4 | |
12154 | var zeroBuffer = new Buffer(intSize) | |
12155 | zeroBuffer.fill(0) | |
12156 | ||
12157 | var charSize = 8 | |
12158 | var hashSize = 16 | |
12159 | ||
12160 | function toArray (buf) { | |
12161 | if ((buf.length % intSize) !== 0) { | |
12162 | var len = buf.length + (intSize - (buf.length % intSize)) | |
12163 | buf = Buffer.concat([buf, zeroBuffer], len) | |
12164 | } | |
12165 | ||
12166 | var arr = new Array(buf.length >>> 2) | |
12167 | for (var i = 0, j = 0; i < buf.length; i += intSize, j++) { | |
12168 | arr[j] = buf.readInt32LE(i) | |
12169 | } | |
12170 | ||
12171 | return arr | |
12172 | } | |
12173 | ||
12174 | module.exports = function hash (buf, fn) { | |
12175 | var arr = fn(toArray(buf), buf.length * charSize) | |
12176 | buf = new Buffer(hashSize) | |
12177 | for (var i = 0; i < arr.length; i++) { | |
12178 | buf.writeInt32LE(arr[i], i << 2, true) | |
12179 | } | |
12180 | return buf | |
12181 | } | |
12182 | ||
12183 | }).call(this,require("buffer").Buffer) | |
12184 | },{"buffer":4}],84:[function(require,module,exports){ | |
12185 | 'use strict' | |
12186 | /* | |
12187 | * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message | |
12188 | * Digest Algorithm, as defined in RFC 1321. | |
12189 | * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. | |
12190 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet | |
12191 | * Distributed under the BSD License | |
12192 | * See http://pajhome.org.uk/crypt/md5 for more info. | |
12193 | */ | |
12194 | ||
12195 | var makeHash = require('./make-hash') | |
12196 | ||
12197 | /* | |
12198 | * Calculate the MD5 of an array of little-endian words, and a bit length | |
12199 | */ | |
12200 | function core_md5 (x, len) { | |
12201 | /* append padding */ | |
12202 | x[len >> 5] |= 0x80 << ((len) % 32) | |
12203 | x[(((len + 64) >>> 9) << 4) + 14] = len | |
12204 | ||
12205 | var a = 1732584193 | |
12206 | var b = -271733879 | |
12207 | var c = -1732584194 | |
12208 | var d = 271733878 | |
12209 | ||
12210 | for (var i = 0; i < x.length; i += 16) { | |
12211 | var olda = a | |
12212 | var oldb = b | |
12213 | var oldc = c | |
12214 | var oldd = d | |
12215 | ||
12216 | a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936) | |
12217 | d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586) | |
12218 | c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819) | |
12219 | b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330) | |
12220 | a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897) | |
12221 | d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426) | |
12222 | c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341) | |
12223 | b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983) | |
12224 | a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416) | |
12225 | d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417) | |
12226 | c = md5_ff(c, d, a, b, x[i + 10], 17, -42063) | |
12227 | b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162) | |
12228 | a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682) | |
12229 | d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101) | |
12230 | c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290) | |
12231 | b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329) | |
12232 | ||
12233 | a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510) | |
12234 | d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632) | |
12235 | c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713) | |
12236 | b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302) | |
12237 | a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691) | |
12238 | d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083) | |
12239 | c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335) | |
12240 | b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848) | |
12241 | a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438) | |
12242 | d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690) | |
12243 | c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961) | |
12244 | b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501) | |
12245 | a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467) | |
12246 | d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784) | |
12247 | c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473) | |
12248 | b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734) | |
12249 | ||
12250 | a = md5_hh(a, b, c, d, x[i + 5], 4, -378558) | |
12251 | d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463) | |
12252 | c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562) | |
12253 | b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556) | |
12254 | a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060) | |
12255 | d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353) | |
12256 | c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632) | |
12257 | b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640) | |
12258 | a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174) | |
12259 | d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222) | |
12260 | c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979) | |
12261 | b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189) | |
12262 | a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487) | |
12263 | d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835) | |
12264 | c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520) | |
12265 | b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651) | |
12266 | ||
12267 | a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844) | |
12268 | d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415) | |
12269 | c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905) | |
12270 | b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055) | |
12271 | a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571) | |
12272 | d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606) | |
12273 | c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523) | |
12274 | b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799) | |
12275 | a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359) | |
12276 | d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744) | |
12277 | c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380) | |
12278 | b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649) | |
12279 | a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070) | |
12280 | d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379) | |
12281 | c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259) | |
12282 | b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551) | |
12283 | ||
12284 | a = safe_add(a, olda) | |
12285 | b = safe_add(b, oldb) | |
12286 | c = safe_add(c, oldc) | |
12287 | d = safe_add(d, oldd) | |
12288 | } | |
12289 | ||
12290 | return [a, b, c, d] | |
12291 | } | |
12292 | ||
12293 | /* | |
12294 | * These functions implement the four basic operations the algorithm uses. | |
12295 | */ | |
12296 | function md5_cmn (q, a, b, x, s, t) { | |
12297 | return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b) | |
12298 | } | |
12299 | ||
12300 | function md5_ff (a, b, c, d, x, s, t) { | |
12301 | return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t) | |
12302 | } | |
12303 | ||
12304 | function md5_gg (a, b, c, d, x, s, t) { | |
12305 | return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t) | |
12306 | } | |
12307 | ||
12308 | function md5_hh (a, b, c, d, x, s, t) { | |
12309 | return md5_cmn(b ^ c ^ d, a, b, x, s, t) | |
12310 | } | |
12311 | ||
12312 | function md5_ii (a, b, c, d, x, s, t) { | |
12313 | return md5_cmn(c ^ (b | (~d)), a, b, x, s, t) | |
12314 | } | |
12315 | ||
12316 | /* | |
12317 | * Add integers, wrapping at 2^32. This uses 16-bit operations internally | |
12318 | * to work around bugs in some JS interpreters. | |
12319 | */ | |
12320 | function safe_add (x, y) { | |
12321 | var lsw = (x & 0xFFFF) + (y & 0xFFFF) | |
12322 | var msw = (x >> 16) + (y >> 16) + (lsw >> 16) | |
12323 | return (msw << 16) | (lsw & 0xFFFF) | |
12324 | } | |
12325 | ||
12326 | /* | |
12327 | * Bitwise rotate a 32-bit number to the left. | |
12328 | */ | |
12329 | function bit_rol (num, cnt) { | |
12330 | return (num << cnt) | (num >>> (32 - cnt)) | |
12331 | } | |
12332 | ||
12333 | module.exports = function md5 (buf) { | |
12334 | return makeHash(buf, core_md5) | |
12335 | } | |
12336 | ||
12337 | },{"./make-hash":83}],85:[function(require,module,exports){ | |
12338 | 'use strict' | |
12339 | var inherits = require('inherits') | |
12340 | var Legacy = require('./legacy') | |
12341 | var Base = require('cipher-base') | |
12342 | var Buffer = require('safe-buffer').Buffer | |
12343 | var md5 = require('create-hash/md5') | |
12344 | var RIPEMD160 = require('ripemd160') | |
12345 | ||
12346 | var sha = require('sha.js') | |
12347 | ||
12348 | var ZEROS = Buffer.alloc(128) | |
12349 | ||
12350 | function Hmac (alg, key) { | |
12351 | Base.call(this, 'digest') | |
12352 | if (typeof key === 'string') { | |
12353 | key = Buffer.from(key) | |
12354 | } | |
12355 | ||
12356 | var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 | |
12357 | ||
12358 | this._alg = alg | |
12359 | this._key = key | |
12360 | if (key.length > blocksize) { | |
12361 | var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) | |
12362 | key = hash.update(key).digest() | |
12363 | } else if (key.length < blocksize) { | |
12364 | key = Buffer.concat([key, ZEROS], blocksize) | |
12365 | } | |
12366 | ||
12367 | var ipad = this._ipad = Buffer.allocUnsafe(blocksize) | |
12368 | var opad = this._opad = Buffer.allocUnsafe(blocksize) | |
12369 | ||
12370 | for (var i = 0; i < blocksize; i++) { | |
12371 | ipad[i] = key[i] ^ 0x36 | |
12372 | opad[i] = key[i] ^ 0x5C | |
12373 | } | |
12374 | this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) | |
12375 | this._hash.update(ipad) | |
12376 | } | |
12377 | ||
12378 | inherits(Hmac, Base) | |
12379 | ||
12380 | Hmac.prototype._update = function (data) { | |
12381 | this._hash.update(data) | |
12382 | } | |
12383 | ||
12384 | Hmac.prototype._final = function () { | |
12385 | var h = this._hash.digest() | |
12386 | var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) | |
12387 | return hash.update(this._opad).update(h).digest() | |
12388 | } | |
12389 | ||
12390 | module.exports = function createHmac (alg, key) { | |
12391 | alg = alg.toLowerCase() | |
12392 | if (alg === 'rmd160' || alg === 'ripemd160') { | |
12393 | return new Hmac('rmd160', key) | |
12394 | } | |
12395 | if (alg === 'md5') { | |
12396 | return new Legacy(md5, key) | |
12397 | } | |
12398 | return new Hmac(alg, key) | |
12399 | } | |
12400 | ||
12401 | },{"./legacy":86,"cipher-base":81,"create-hash/md5":84,"inherits":93,"ripemd160":97,"safe-buffer":98,"sha.js":100}],86:[function(require,module,exports){ | |
12402 | 'use strict' | |
12403 | var inherits = require('inherits') | |
12404 | var Buffer = require('safe-buffer').Buffer | |
12405 | ||
12406 | var Base = require('cipher-base') | |
12407 | ||
12408 | var ZEROS = Buffer.alloc(128) | |
12409 | var blocksize = 64 | |
12410 | ||
12411 | function Hmac (alg, key) { | |
12412 | Base.call(this, 'digest') | |
12413 | if (typeof key === 'string') { | |
12414 | key = Buffer.from(key) | |
12415 | } | |
12416 | ||
12417 | this._alg = alg | |
12418 | this._key = key | |
12419 | ||
12420 | if (key.length > blocksize) { | |
12421 | key = alg(key) | |
12422 | } else if (key.length < blocksize) { | |
12423 | key = Buffer.concat([key, ZEROS], blocksize) | |
12424 | } | |
12425 | ||
12426 | var ipad = this._ipad = Buffer.allocUnsafe(blocksize) | |
12427 | var opad = this._opad = Buffer.allocUnsafe(blocksize) | |
12428 | ||
12429 | for (var i = 0; i < blocksize; i++) { | |
12430 | ipad[i] = key[i] ^ 0x36 | |
12431 | opad[i] = key[i] ^ 0x5C | |
12432 | } | |
12433 | ||
12434 | this._hash = [ipad] | |
12435 | } | |
12436 | ||
12437 | inherits(Hmac, Base) | |
12438 | ||
12439 | Hmac.prototype._update = function (data) { | |
12440 | this._hash.push(data) | |
12441 | } | |
12442 | ||
12443 | Hmac.prototype._final = function () { | |
12444 | var h = this._alg(Buffer.concat(this._hash)) | |
12445 | return this._alg(Buffer.concat([this._opad, h])) | |
12446 | } | |
12447 | module.exports = Hmac | |
12448 | ||
12449 | },{"cipher-base":81,"inherits":93,"safe-buffer":98}],87:[function(require,module,exports){ | |
12450 | var assert = require('assert') | |
12451 | var BigInteger = require('bigi') | |
12452 | ||
12453 | var Point = require('./point') | |
12454 | ||
12455 | function Curve (p, a, b, Gx, Gy, n, h) { | |
12456 | this.p = p | |
12457 | this.a = a | |
12458 | this.b = b | |
12459 | this.G = Point.fromAffine(this, Gx, Gy) | |
12460 | this.n = n | |
12461 | this.h = h | |
12462 | ||
12463 | this.infinity = new Point(this, null, null, BigInteger.ZERO) | |
12464 | ||
12465 | // result caching | |
12466 | this.pOverFour = p.add(BigInteger.ONE).shiftRight(2) | |
12467 | ||
12468 | // determine size of p in bytes | |
12469 | this.pLength = Math.floor((this.p.bitLength() + 7) / 8) | |
12470 | } | |
12471 | ||
12472 | Curve.prototype.pointFromX = function (isOdd, x) { | |
12473 | var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p) | |
12474 | var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves | |
12475 | ||
12476 | var y = beta | |
12477 | if (beta.isEven() ^ !isOdd) { | |
12478 | y = this.p.subtract(y) // -y % p | |
12479 | } | |
12480 | ||
12481 | return Point.fromAffine(this, x, y) | |
12482 | } | |
12483 | ||
12484 | Curve.prototype.isInfinity = function (Q) { | |
12485 | if (Q === this.infinity) return true | |
12486 | ||
12487 | return Q.z.signum() === 0 && Q.y.signum() !== 0 | |
12488 | } | |
12489 | ||
12490 | Curve.prototype.isOnCurve = function (Q) { | |
12491 | if (this.isInfinity(Q)) return true | |
12492 | ||
12493 | var x = Q.affineX | |
12494 | var y = Q.affineY | |
12495 | var a = this.a | |
12496 | var b = this.b | |
12497 | var p = this.p | |
12498 | ||
12499 | // Check that xQ and yQ are integers in the interval [0, p - 1] | |
12500 | if (x.signum() < 0 || x.compareTo(p) >= 0) return false | |
12501 | if (y.signum() < 0 || y.compareTo(p) >= 0) return false | |
12502 | ||
12503 | // and check that y^2 = x^3 + ax + b (mod p) | |
12504 | var lhs = y.square().mod(p) | |
12505 | var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p) | |
12506 | return lhs.equals(rhs) | |
12507 | } | |
12508 | ||
12509 | /** | |
12510 | * Validate an elliptic curve point. | |
12511 | * | |
12512 | * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive | |
12513 | */ | |
12514 | Curve.prototype.validate = function (Q) { | |
12515 | // Check Q != O | |
12516 | assert(!this.isInfinity(Q), 'Point is at infinity') | |
12517 | assert(this.isOnCurve(Q), 'Point is not on the curve') | |
12518 | ||
12519 | // Check nQ = O (where Q is a scalar multiple of G) | |
12520 | var nQ = Q.multiply(this.n) | |
12521 | assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G') | |
12522 | ||
12523 | return true | |
12524 | } | |
12525 | ||
12526 | module.exports = Curve | |
12527 | ||
12528 | },{"./point":91,"assert":1,"bigi":37}],88:[function(require,module,exports){ | |
12529 | module.exports={ | |
12530 | "secp128r1": { | |
12531 | "p": "fffffffdffffffffffffffffffffffff", | |
12532 | "a": "fffffffdfffffffffffffffffffffffc", | |
12533 | "b": "e87579c11079f43dd824993c2cee5ed3", | |
12534 | "n": "fffffffe0000000075a30d1b9038a115", | |
12535 | "h": "01", | |
12536 | "Gx": "161ff7528b899b2d0c28607ca52c5b86", | |
12537 | "Gy": "cf5ac8395bafeb13c02da292dded7a83" | |
12538 | }, | |
12539 | "secp160k1": { | |
12540 | "p": "fffffffffffffffffffffffffffffffeffffac73", | |
12541 | "a": "00", | |
12542 | "b": "07", | |
12543 | "n": "0100000000000000000001b8fa16dfab9aca16b6b3", | |
12544 | "h": "01", | |
12545 | "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb", | |
12546 | "Gy": "938cf935318fdced6bc28286531733c3f03c4fee" | |
12547 | }, | |
12548 | "secp160r1": { | |
12549 | "p": "ffffffffffffffffffffffffffffffff7fffffff", | |
12550 | "a": "ffffffffffffffffffffffffffffffff7ffffffc", | |
12551 | "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45", | |
12552 | "n": "0100000000000000000001f4c8f927aed3ca752257", | |
12553 | "h": "01", | |
12554 | "Gx": "4a96b5688ef573284664698968c38bb913cbfc82", | |
12555 | "Gy": "23a628553168947d59dcc912042351377ac5fb32" | |
12556 | }, | |
12557 | "secp192k1": { | |
12558 | "p": "fffffffffffffffffffffffffffffffffffffffeffffee37", | |
12559 | "a": "00", | |
12560 | "b": "03", | |
12561 | "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d", | |
12562 | "h": "01", | |
12563 | "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d", | |
12564 | "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d" | |
12565 | }, | |
12566 | "secp192r1": { | |
12567 | "p": "fffffffffffffffffffffffffffffffeffffffffffffffff", | |
12568 | "a": "fffffffffffffffffffffffffffffffefffffffffffffffc", | |
12569 | "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1", | |
12570 | "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831", | |
12571 | "h": "01", | |
12572 | "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012", | |
12573 | "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811" | |
12574 | }, | |
12575 | "secp256k1": { | |
12576 | "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f", | |
12577 | "a": "00", | |
12578 | "b": "07", | |
12579 | "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141", | |
12580 | "h": "01", | |
12581 | "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798", | |
12582 | "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8" | |
12583 | }, | |
12584 | "secp256r1": { | |
12585 | "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff", | |
12586 | "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc", | |
12587 | "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b", | |
12588 | "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551", | |
12589 | "h": "01", | |
12590 | "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296", | |
12591 | "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5" | |
12592 | } | |
12593 | } | |
12594 | ||
12595 | },{}],89:[function(require,module,exports){ | |
12596 | var Point = require('./point') | |
12597 | var Curve = require('./curve') | |
12598 | ||
12599 | var getCurveByName = require('./names') | |
12600 | ||
12601 | module.exports = { | |
12602 | Curve: Curve, | |
12603 | Point: Point, | |
12604 | getCurveByName: getCurveByName | |
12605 | } | |
12606 | ||
12607 | },{"./curve":87,"./names":90,"./point":91}],90:[function(require,module,exports){ | |
12608 | var BigInteger = require('bigi') | |
12609 | ||
12610 | var curves = require('./curves.json') | |
12611 | var Curve = require('./curve') | |
12612 | ||
12613 | function getCurveByName (name) { | |
12614 | var curve = curves[name] | |
12615 | if (!curve) return null | |
12616 | ||
12617 | var p = new BigInteger(curve.p, 16) | |
12618 | var a = new BigInteger(curve.a, 16) | |
12619 | var b = new BigInteger(curve.b, 16) | |
12620 | var n = new BigInteger(curve.n, 16) | |
12621 | var h = new BigInteger(curve.h, 16) | |
12622 | var Gx = new BigInteger(curve.Gx, 16) | |
12623 | var Gy = new BigInteger(curve.Gy, 16) | |
12624 | ||
12625 | return new Curve(p, a, b, Gx, Gy, n, h) | |
12626 | } | |
12627 | ||
12628 | module.exports = getCurveByName | |
12629 | ||
12630 | },{"./curve":87,"./curves.json":88,"bigi":37}],91:[function(require,module,exports){ | |
12631 | (function (Buffer){ | |
12632 | var assert = require('assert') | |
12633 | var BigInteger = require('bigi') | |
12634 | ||
12635 | var THREE = BigInteger.valueOf(3) | |
12636 | ||
12637 | function Point (curve, x, y, z) { | |
12638 | assert.notStrictEqual(z, undefined, 'Missing Z coordinate') | |
12639 | ||
12640 | this.curve = curve | |
12641 | this.x = x | |
12642 | this.y = y | |
12643 | this.z = z | |
12644 | this._zInv = null | |
12645 | ||
12646 | this.compressed = true | |
12647 | } | |
12648 | ||
12649 | Object.defineProperty(Point.prototype, 'zInv', { | |
12650 | get: function () { | |
12651 | if (this._zInv === null) { | |
12652 | this._zInv = this.z.modInverse(this.curve.p) | |
12653 | } | |
12654 | ||
12655 | return this._zInv | |
12656 | } | |
12657 | }) | |
12658 | ||
12659 | Object.defineProperty(Point.prototype, 'affineX', { | |
12660 | get: function () { | |
12661 | return this.x.multiply(this.zInv).mod(this.curve.p) | |
12662 | } | |
12663 | }) | |
12664 | ||
12665 | Object.defineProperty(Point.prototype, 'affineY', { | |
12666 | get: function () { | |
12667 | return this.y.multiply(this.zInv).mod(this.curve.p) | |
12668 | } | |
12669 | }) | |
12670 | ||
12671 | Point.fromAffine = function (curve, x, y) { | |
12672 | return new Point(curve, x, y, BigInteger.ONE) | |
12673 | } | |
12674 | ||
12675 | Point.prototype.equals = function (other) { | |
12676 | if (other === this) return true | |
12677 | if (this.curve.isInfinity(this)) return this.curve.isInfinity(other) | |
12678 | if (this.curve.isInfinity(other)) return this.curve.isInfinity(this) | |
12679 | ||
12680 | // u = Y2 * Z1 - Y1 * Z2 | |
12681 | var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p) | |
12682 | ||
12683 | if (u.signum() !== 0) return false | |
12684 | ||
12685 | // v = X2 * Z1 - X1 * Z2 | |
12686 | var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p) | |
12687 | ||
12688 | return v.signum() === 0 | |
12689 | } | |
12690 | ||
12691 | Point.prototype.negate = function () { | |
12692 | var y = this.curve.p.subtract(this.y) | |
12693 | ||
12694 | return new Point(this.curve, this.x, y, this.z) | |
12695 | } | |
12696 | ||
12697 | Point.prototype.add = function (b) { | |
12698 | if (this.curve.isInfinity(this)) return b | |
12699 | if (this.curve.isInfinity(b)) return this | |
12700 | ||
12701 | var x1 = this.x | |
12702 | var y1 = this.y | |
12703 | var x2 = b.x | |
12704 | var y2 = b.y | |
12705 | ||
12706 | // u = Y2 * Z1 - Y1 * Z2 | |
12707 | var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p) | |
12708 | // v = X2 * Z1 - X1 * Z2 | |
12709 | var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p) | |
12710 | ||
12711 | if (v.signum() === 0) { | |
12712 | if (u.signum() === 0) { | |
12713 | return this.twice() // this == b, so double | |
12714 | } | |
12715 | ||
12716 | return this.curve.infinity // this = -b, so infinity | |
12717 | } | |
12718 | ||
12719 | var v2 = v.square() | |
12720 | var v3 = v2.multiply(v) | |
12721 | var x1v2 = x1.multiply(v2) | |
12722 | var zu2 = u.square().multiply(this.z) | |
12723 | ||
12724 | // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3) | |
12725 | var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p) | |
12726 | // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3 | |
12727 | 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) | |
12728 | // z3 = v^3 * z1 * z2 | |
12729 | var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p) | |
12730 | ||
12731 | return new Point(this.curve, x3, y3, z3) | |
12732 | } | |
12733 | ||
12734 | Point.prototype.twice = function () { | |
12735 | if (this.curve.isInfinity(this)) return this | |
12736 | if (this.y.signum() === 0) return this.curve.infinity | |
12737 | ||
12738 | var x1 = this.x | |
12739 | var y1 = this.y | |
12740 | ||
12741 | var y1z1 = y1.multiply(this.z).mod(this.curve.p) | |
12742 | var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p) | |
12743 | var a = this.curve.a | |
12744 | ||
12745 | // w = 3 * x1^2 + a * z1^2 | |
12746 | var w = x1.square().multiply(THREE) | |
12747 | ||
12748 | if (a.signum() !== 0) { | |
12749 | w = w.add(this.z.square().multiply(a)) | |
12750 | } | |
12751 | ||
12752 | w = w.mod(this.curve.p) | |
12753 | // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1) | |
12754 | var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p) | |
12755 | // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3 | |
12756 | var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p) | |
12757 | // z3 = 8 * (y1 * z1)^3 | |
12758 | var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p) | |
12759 | ||
12760 | return new Point(this.curve, x3, y3, z3) | |
12761 | } | |
12762 | ||
12763 | // Simple NAF (Non-Adjacent Form) multiplication algorithm | |
12764 | // TODO: modularize the multiplication algorithm | |
12765 | Point.prototype.multiply = function (k) { | |
12766 | if (this.curve.isInfinity(this)) return this | |
12767 | if (k.signum() === 0) return this.curve.infinity | |
12768 | ||
12769 | var e = k | |
12770 | var h = e.multiply(THREE) | |
12771 | ||
12772 | var neg = this.negate() | |
12773 | var R = this | |
12774 | ||
12775 | for (var i = h.bitLength() - 2; i > 0; --i) { | |
12776 | var hBit = h.testBit(i) | |
12777 | var eBit = e.testBit(i) | |
12778 | ||
12779 | R = R.twice() | |
12780 | ||
12781 | if (hBit !== eBit) { | |
12782 | R = R.add(hBit ? this : neg) | |
12783 | } | |
12784 | } | |
12785 | ||
12786 | return R | |
12787 | } | |
12788 | ||
12789 | // Compute this*j + x*k (simultaneous multiplication) | |
12790 | Point.prototype.multiplyTwo = function (j, x, k) { | |
12791 | var i = Math.max(j.bitLength(), k.bitLength()) - 1 | |
12792 | var R = this.curve.infinity | |
12793 | var both = this.add(x) | |
12794 | ||
12795 | while (i >= 0) { | |
12796 | var jBit = j.testBit(i) | |
12797 | var kBit = k.testBit(i) | |
12798 | ||
12799 | R = R.twice() | |
12800 | ||
12801 | if (jBit) { | |
12802 | if (kBit) { | |
12803 | R = R.add(both) | |
12804 | } else { | |
12805 | R = R.add(this) | |
12806 | } | |
12807 | } else if (kBit) { | |
12808 | R = R.add(x) | |
12809 | } | |
12810 | --i | |
12811 | } | |
12812 | ||
12813 | return R | |
12814 | } | |
12815 | ||
12816 | Point.prototype.getEncoded = function (compressed) { | |
12817 | if (compressed == null) compressed = this.compressed | |
12818 | if (this.curve.isInfinity(this)) return new Buffer('00', 'hex') // Infinity point encoded is simply '00' | |
12819 | ||
12820 | var x = this.affineX | |
12821 | var y = this.affineY | |
12822 | var byteLength = this.curve.pLength | |
12823 | var buffer | |
12824 | ||
12825 | // 0x02/0x03 | X | |
12826 | if (compressed) { | |
12827 | buffer = new Buffer(1 + byteLength) | |
12828 | buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0) | |
12829 | ||
12830 | // 0x04 | X | Y | |
12831 | } else { | |
12832 | buffer = new Buffer(1 + byteLength + byteLength) | |
12833 | buffer.writeUInt8(0x04, 0) | |
12834 | ||
12835 | y.toBuffer(byteLength).copy(buffer, 1 + byteLength) | |
12836 | } | |
12837 | ||
12838 | x.toBuffer(byteLength).copy(buffer, 1) | |
12839 | ||
12840 | return buffer | |
12841 | } | |
12842 | ||
12843 | Point.decodeFrom = function (curve, buffer) { | |
12844 | var type = buffer.readUInt8(0) | |
12845 | var compressed = (type !== 4) | |
12846 | ||
12847 | var byteLength = Math.floor((curve.p.bitLength() + 7) / 8) | |
12848 | var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength)) | |
12849 | ||
12850 | var Q | |
12851 | if (compressed) { | |
12852 | assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length') | |
12853 | assert(type === 0x02 || type === 0x03, 'Invalid sequence tag') | |
12854 | ||
12855 | var isOdd = (type === 0x03) | |
12856 | Q = curve.pointFromX(isOdd, x) | |
12857 | } else { | |
12858 | assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length') | |
12859 | ||
12860 | var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength)) | |
12861 | Q = Point.fromAffine(curve, x, y) | |
12862 | } | |
12863 | ||
12864 | Q.compressed = compressed | |
12865 | return Q | |
12866 | } | |
12867 | ||
12868 | Point.prototype.toString = function () { | |
12869 | if (this.curve.isInfinity(this)) return '(INFINITY)' | |
12870 | ||
12871 | return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')' | |
12872 | } | |
12873 | ||
12874 | module.exports = Point | |
12875 | ||
12876 | }).call(this,require("buffer").Buffer) | |
12877 | },{"assert":1,"bigi":37,"buffer":4}],92:[function(require,module,exports){ | |
12878 | (function (Buffer){ | |
12879 | 'use strict' | |
12880 | var Transform = require('stream').Transform | |
12881 | var inherits = require('inherits') | |
12882 | ||
12883 | function HashBase (blockSize) { | |
12884 | Transform.call(this) | |
12885 | ||
12886 | this._block = new Buffer(blockSize) | |
12887 | this._blockSize = blockSize | |
12888 | this._blockOffset = 0 | |
12889 | this._length = [0, 0, 0, 0] | |
12890 | ||
12891 | this._finalized = false | |
12892 | } | |
12893 | ||
12894 | inherits(HashBase, Transform) | |
12895 | ||
12896 | HashBase.prototype._transform = function (chunk, encoding, callback) { | |
12897 | var error = null | |
12898 | try { | |
12899 | if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding) | |
12900 | this.update(chunk) | |
12901 | } catch (err) { | |
12902 | error = err | |
12903 | } | |
12904 | ||
12905 | callback(error) | |
12906 | } | |
12907 | ||
12908 | HashBase.prototype._flush = function (callback) { | |
12909 | var error = null | |
12910 | try { | |
12911 | this.push(this._digest()) | |
12912 | } catch (err) { | |
12913 | error = err | |
12914 | } | |
12915 | ||
12916 | callback(error) | |
12917 | } | |
12918 | ||
12919 | HashBase.prototype.update = function (data, encoding) { | |
12920 | if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') | |
12921 | if (this._finalized) throw new Error('Digest already called') | |
12922 | if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary') | |
12923 | ||
12924 | // consume data | |
12925 | var block = this._block | |
12926 | var offset = 0 | |
12927 | while (this._blockOffset + data.length - offset >= this._blockSize) { | |
12928 | for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] | |
12929 | this._update() | |
12930 | this._blockOffset = 0 | |
12931 | } | |
12932 | while (offset < data.length) block[this._blockOffset++] = data[offset++] | |
12933 | ||
12934 | // update length | |
12935 | for (var j = 0, carry = data.length * 8; carry > 0; ++j) { | |
12936 | this._length[j] += carry | |
12937 | carry = (this._length[j] / 0x0100000000) | 0 | |
12938 | if (carry > 0) this._length[j] -= 0x0100000000 * carry | |
12939 | } | |
12940 | ||
12941 | return this | |
12942 | } | |
12943 | ||
12944 | HashBase.prototype._update = function (data) { | |
12945 | throw new Error('_update is not implemented') | |
12946 | } | |
12947 | ||
12948 | HashBase.prototype.digest = function (encoding) { | |
12949 | if (this._finalized) throw new Error('Digest already called') | |
12950 | this._finalized = true | |
12951 | ||
12952 | var digest = this._digest() | |
12953 | if (encoding !== undefined) digest = digest.toString(encoding) | |
12954 | return digest | |
12955 | } | |
12956 | ||
12957 | HashBase.prototype._digest = function () { | |
12958 | throw new Error('_digest is not implemented') | |
12959 | } | |
12960 | ||
12961 | module.exports = HashBase | |
12962 | ||
12963 | }).call(this,require("buffer").Buffer) | |
12964 | },{"buffer":4,"inherits":93,"stream":27}],93:[function(require,module,exports){ | |
12965 | arguments[4][8][0].apply(exports,arguments) | |
12966 | },{"dup":8}],94:[function(require,module,exports){ | |
12967 | (function (Buffer){ | |
12968 | // constant-space merkle root calculation algorithm | |
12969 | module.exports = function fastRoot (values, digestFn) { | |
12970 | if (!Array.isArray(values)) throw TypeError('Expected values Array') | |
12971 | if (typeof digestFn !== 'function') throw TypeError('Expected digest Function') | |
12972 | ||
12973 | var length = values.length | |
12974 | var results = values.concat() | |
12975 | ||
12976 | while (length > 1) { | |
12977 | var j = 0 | |
12978 | ||
12979 | for (var i = 0; i < length; i += 2, ++j) { | |
12980 | var left = results[i] | |
12981 | var right = i + 1 === length ? left : results[i + 1] | |
12982 | var data = Buffer.concat([left, right]) | |
12983 | ||
12984 | results[j] = digestFn(data) | |
12985 | } | |
12986 | ||
12987 | length = j | |
12988 | } | |
12989 | ||
12990 | return results[0] | |
12991 | } | |
12992 | ||
12993 | }).call(this,require("buffer").Buffer) | |
12994 | },{"buffer":4}],95:[function(require,module,exports){ | |
12995 | var OPS = require('bitcoin-ops') | |
12996 | ||
12997 | function encodingLength (i) { | |
12998 | return i < OPS.OP_PUSHDATA1 ? 1 | |
12999 | : i <= 0xff ? 2 | |
13000 | : i <= 0xffff ? 3 | |
13001 | : 5 | |
13002 | } | |
13003 | ||
13004 | function encode (buffer, number, offset) { | |
13005 | var size = encodingLength(number) | |
13006 | ||
13007 | // ~6 bit | |
13008 | if (size === 1) { | |
13009 | buffer.writeUInt8(number, offset) | |
13010 | ||
13011 | // 8 bit | |
13012 | } else if (size === 2) { | |
13013 | buffer.writeUInt8(OPS.OP_PUSHDATA1, offset) | |
13014 | buffer.writeUInt8(number, offset + 1) | |
13015 | ||
13016 | // 16 bit | |
13017 | } else if (size === 3) { | |
13018 | buffer.writeUInt8(OPS.OP_PUSHDATA2, offset) | |
13019 | buffer.writeUInt16LE(number, offset + 1) | |
13020 | ||
13021 | // 32 bit | |
13022 | } else { | |
13023 | buffer.writeUInt8(OPS.OP_PUSHDATA4, offset) | |
13024 | buffer.writeUInt32LE(number, offset + 1) | |
13025 | } | |
13026 | ||
13027 | return size | |
13028 | } | |
13029 | ||
13030 | function decode (buffer, offset) { | |
13031 | var opcode = buffer.readUInt8(offset) | |
13032 | var number, size | |
13033 | ||
13034 | // ~6 bit | |
13035 | if (opcode < OPS.OP_PUSHDATA1) { | |
13036 | number = opcode | |
13037 | size = 1 | |
13038 | ||
13039 | // 8 bit | |
13040 | } else if (opcode === OPS.OP_PUSHDATA1) { | |
13041 | if (offset + 2 > buffer.length) return null | |
13042 | number = buffer.readUInt8(offset + 1) | |
13043 | size = 2 | |
13044 | ||
13045 | // 16 bit | |
13046 | } else if (opcode === OPS.OP_PUSHDATA2) { | |
13047 | if (offset + 3 > buffer.length) return null | |
13048 | number = buffer.readUInt16LE(offset + 1) | |
13049 | size = 3 | |
13050 | ||
13051 | // 32 bit | |
13052 | } else { | |
13053 | if (offset + 5 > buffer.length) return null | |
13054 | if (opcode !== OPS.OP_PUSHDATA4) throw new Error('Unexpected opcode') | |
13055 | ||
13056 | number = buffer.readUInt32LE(offset + 1) | |
13057 | size = 5 | |
13058 | } | |
13059 | ||
13060 | return { | |
13061 | opcode: opcode, | |
13062 | number: number, | |
13063 | size: size | |
13064 | } | |
13065 | } | |
13066 | ||
13067 | module.exports = { | |
13068 | encodingLength: encodingLength, | |
13069 | encode: encode, | |
13070 | decode: decode | |
13071 | } | |
13072 | ||
13073 | },{"bitcoin-ops":40}],96:[function(require,module,exports){ | |
13074 | (function (process,global){ | |
13075 | 'use strict' | |
13076 | ||
13077 | function oldBrowser () { | |
13078 | throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') | |
13079 | } | |
13080 | ||
13081 | var Buffer = require('safe-buffer').Buffer | |
13082 | var crypto = global.crypto || global.msCrypto | |
13083 | ||
13084 | if (crypto && crypto.getRandomValues) { | |
13085 | module.exports = randomBytes | |
13086 | } else { | |
13087 | module.exports = oldBrowser | |
13088 | } | |
13089 | ||
13090 | function randomBytes (size, cb) { | |
13091 | // phantomjs needs to throw | |
13092 | if (size > 65536) throw new Error('requested too many random bytes') | |
13093 | // in case browserify isn't using the Uint8Array version | |
13094 | var rawBytes = new global.Uint8Array(size) | |
13095 | ||
13096 | // This will not work in older browsers. | |
13097 | // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues | |
13098 | if (size > 0) { // getRandomValues fails on IE if size == 0 | |
13099 | crypto.getRandomValues(rawBytes) | |
13100 | } | |
13101 | ||
13102 | // XXX: phantomjs doesn't like a buffer being passed here | |
13103 | var bytes = Buffer.from(rawBytes.buffer) | |
13104 | ||
13105 | if (typeof cb === 'function') { | |
13106 | return process.nextTick(function () { | |
13107 | cb(null, bytes) | |
13108 | }) | |
13109 | } | |
13110 | ||
13111 | return bytes | |
13112 | } | |
13113 | ||
13114 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | |
13115 | },{"_process":12,"safe-buffer":98}],97:[function(require,module,exports){ | |
13116 | (function (Buffer){ | |
13117 | 'use strict' | |
13118 | var inherits = require('inherits') | |
13119 | var HashBase = require('hash-base') | |
13120 | ||
13121 | function RIPEMD160 () { | |
13122 | HashBase.call(this, 64) | |
13123 | ||
13124 | // state | |
13125 | this._a = 0x67452301 | |
13126 | this._b = 0xefcdab89 | |
13127 | this._c = 0x98badcfe | |
13128 | this._d = 0x10325476 | |
13129 | this._e = 0xc3d2e1f0 | |
13130 | } | |
13131 | ||
13132 | inherits(RIPEMD160, HashBase) | |
13133 | ||
13134 | RIPEMD160.prototype._update = function () { | |
13135 | var m = new Array(16) | |
13136 | for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4) | |
13137 | ||
13138 | var al = this._a | |
13139 | var bl = this._b | |
13140 | var cl = this._c | |
13141 | var dl = this._d | |
13142 | var el = this._e | |
13143 | ||
13144 | // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 | |
13145 | // K = 0x00000000 | |
13146 | // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8 | |
13147 | al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10) | |
13148 | el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10) | |
13149 | dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10) | |
13150 | cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10) | |
13151 | bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10) | |
13152 | al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10) | |
13153 | el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10) | |
13154 | dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10) | |
13155 | cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10) | |
13156 | bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10) | |
13157 | al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10) | |
13158 | el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10) | |
13159 | dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10) | |
13160 | cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10) | |
13161 | bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10) | |
13162 | al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10) | |
13163 | ||
13164 | // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8 | |
13165 | // K = 0x5a827999 | |
13166 | // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12 | |
13167 | el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10) | |
13168 | dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10) | |
13169 | cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10) | |
13170 | bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10) | |
13171 | al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10) | |
13172 | el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10) | |
13173 | dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10) | |
13174 | cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10) | |
13175 | bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10) | |
13176 | al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10) | |
13177 | el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10) | |
13178 | dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10) | |
13179 | cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10) | |
13180 | bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10) | |
13181 | al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10) | |
13182 | el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10) | |
13183 | ||
13184 | // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12 | |
13185 | // K = 0x6ed9eba1 | |
13186 | // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5 | |
13187 | dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10) | |
13188 | cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10) | |
13189 | bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10) | |
13190 | al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10) | |
13191 | el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10) | |
13192 | dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10) | |
13193 | cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10) | |
13194 | bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10) | |
13195 | al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10) | |
13196 | el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10) | |
13197 | dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10) | |
13198 | cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10) | |
13199 | bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10) | |
13200 | al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10) | |
13201 | el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10) | |
13202 | dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10) | |
13203 | ||
13204 | // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2 | |
13205 | // K = 0x8f1bbcdc | |
13206 | // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12 | |
13207 | cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10) | |
13208 | bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10) | |
13209 | al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10) | |
13210 | el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10) | |
13211 | dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10) | |
13212 | cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10) | |
13213 | bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10) | |
13214 | al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10) | |
13215 | el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10) | |
13216 | dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10) | |
13217 | cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10) | |
13218 | bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10) | |
13219 | al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10) | |
13220 | el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10) | |
13221 | dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10) | |
13222 | cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10) | |
13223 | ||
13224 | // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 | |
13225 | // K = 0xa953fd4e | |
13226 | // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 | |
13227 | bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10) | |
13228 | al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10) | |
13229 | el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10) | |
13230 | dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10) | |
13231 | cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10) | |
13232 | bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10) | |
13233 | al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10) | |
13234 | el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10) | |
13235 | dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10) | |
13236 | cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10) | |
13237 | bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10) | |
13238 | al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10) | |
13239 | el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10) | |
13240 | dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10) | |
13241 | cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10) | |
13242 | bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10) | |
13243 | ||
13244 | var ar = this._a | |
13245 | var br = this._b | |
13246 | var cr = this._c | |
13247 | var dr = this._d | |
13248 | var er = this._e | |
13249 | ||
13250 | // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12 | |
13251 | // K' = 0x50a28be6 | |
13252 | // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6 | |
13253 | ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10) | |
13254 | er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10) | |
13255 | dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10) | |
13256 | cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10) | |
13257 | br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10) | |
13258 | ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10) | |
13259 | er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10) | |
13260 | dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10) | |
13261 | cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10) | |
13262 | br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10) | |
13263 | ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10) | |
13264 | er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10) | |
13265 | dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10) | |
13266 | cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10) | |
13267 | br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10) | |
13268 | ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10) | |
13269 | ||
13270 | // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2 | |
13271 | // K' = 0x5c4dd124 | |
13272 | // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11 | |
13273 | er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10) | |
13274 | dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10) | |
13275 | cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10) | |
13276 | br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10) | |
13277 | ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10) | |
13278 | er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10) | |
13279 | dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10) | |
13280 | cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10) | |
13281 | br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10) | |
13282 | ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10) | |
13283 | er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10) | |
13284 | dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10) | |
13285 | cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10) | |
13286 | br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10) | |
13287 | ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10) | |
13288 | er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10) | |
13289 | ||
13290 | // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13 | |
13291 | // K' = 0x6d703ef3 | |
13292 | // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5 | |
13293 | dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10) | |
13294 | cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10) | |
13295 | br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10) | |
13296 | ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10) | |
13297 | er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10) | |
13298 | dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10) | |
13299 | cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10) | |
13300 | br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10) | |
13301 | ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10) | |
13302 | er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10) | |
13303 | dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10) | |
13304 | cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10) | |
13305 | br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10) | |
13306 | ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10) | |
13307 | er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10) | |
13308 | dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10) | |
13309 | ||
13310 | // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14 | |
13311 | // K' = 0x7a6d76e9 | |
13312 | // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8 | |
13313 | cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10) | |
13314 | br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10) | |
13315 | ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10) | |
13316 | er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10) | |
13317 | dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10) | |
13318 | cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10) | |
13319 | br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10) | |
13320 | ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10) | |
13321 | er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10) | |
13322 | dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10) | |
13323 | cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10) | |
13324 | br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10) | |
13325 | ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10) | |
13326 | er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10) | |
13327 | dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10) | |
13328 | cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10) | |
13329 | ||
13330 | // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 | |
13331 | // K' = 0x00000000 | |
13332 | // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 | |
13333 | br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10) | |
13334 | ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10) | |
13335 | er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10) | |
13336 | dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10) | |
13337 | cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10) | |
13338 | br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10) | |
13339 | ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10) | |
13340 | er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10) | |
13341 | dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10) | |
13342 | cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10) | |
13343 | br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10) | |
13344 | ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10) | |
13345 | er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10) | |
13346 | dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10) | |
13347 | cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10) | |
13348 | br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10) | |
13349 | ||
13350 | // change state | |
13351 | var t = (this._b + cl + dr) | 0 | |
13352 | this._b = (this._c + dl + er) | 0 | |
13353 | this._c = (this._d + el + ar) | 0 | |
13354 | this._d = (this._e + al + br) | 0 | |
13355 | this._e = (this._a + bl + cr) | 0 | |
13356 | this._a = t | |
13357 | } | |
13358 | ||
13359 | RIPEMD160.prototype._digest = function () { | |
13360 | // create padding and handle blocks | |
13361 | this._block[this._blockOffset++] = 0x80 | |
13362 | if (this._blockOffset > 56) { | |
13363 | this._block.fill(0, this._blockOffset, 64) | |
13364 | this._update() | |
13365 | this._blockOffset = 0 | |
13366 | } | |
13367 | ||
13368 | this._block.fill(0, this._blockOffset, 56) | |
13369 | this._block.writeUInt32LE(this._length[0], 56) | |
13370 | this._block.writeUInt32LE(this._length[1], 60) | |
13371 | this._update() | |
13372 | ||
13373 | // produce result | |
13374 | var buffer = new Buffer(20) | |
13375 | buffer.writeInt32LE(this._a, 0) | |
13376 | buffer.writeInt32LE(this._b, 4) | |
13377 | buffer.writeInt32LE(this._c, 8) | |
13378 | buffer.writeInt32LE(this._d, 12) | |
13379 | buffer.writeInt32LE(this._e, 16) | |
13380 | return buffer | |
13381 | } | |
13382 | ||
13383 | function rotl (x, n) { | |
13384 | return (x << n) | (x >>> (32 - n)) | |
13385 | } | |
13386 | ||
13387 | function fn1 (a, b, c, d, e, m, k, s) { | |
13388 | return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 | |
13389 | } | |
13390 | ||
13391 | function fn2 (a, b, c, d, e, m, k, s) { | |
13392 | return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 | |
13393 | } | |
13394 | ||
13395 | function fn3 (a, b, c, d, e, m, k, s) { | |
13396 | return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 | |
13397 | } | |
13398 | ||
13399 | function fn4 (a, b, c, d, e, m, k, s) { | |
13400 | return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 | |
13401 | } | |
13402 | ||
13403 | function fn5 (a, b, c, d, e, m, k, s) { | |
13404 | return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 | |
13405 | } | |
13406 | ||
13407 | module.exports = RIPEMD160 | |
13408 | ||
13409 | }).call(this,require("buffer").Buffer) | |
13410 | },{"buffer":4,"hash-base":92,"inherits":93}],98:[function(require,module,exports){ | |
13411 | arguments[4][26][0].apply(exports,arguments) | |
13412 | },{"buffer":4,"dup":26}],99:[function(require,module,exports){ | |
13413 | (function (Buffer){ | |
13414 | // prototype class for hash functions | |
13415 | function Hash (blockSize, finalSize) { | |
13416 | this._block = new Buffer(blockSize) | |
13417 | this._finalSize = finalSize | |
13418 | this._blockSize = blockSize | |
13419 | this._len = 0 | |
13420 | this._s = 0 | |
13421 | } | |
13422 | ||
13423 | Hash.prototype.update = function (data, enc) { | |
13424 | if (typeof data === 'string') { | |
13425 | enc = enc || 'utf8' | |
13426 | data = new Buffer(data, enc) | |
13427 | } | |
13428 | ||
13429 | var l = this._len += data.length | |
13430 | var s = this._s || 0 | |
13431 | var f = 0 | |
13432 | var buffer = this._block | |
13433 | ||
13434 | while (s < l) { | |
13435 | var t = Math.min(data.length, f + this._blockSize - (s % this._blockSize)) | |
13436 | var ch = (t - f) | |
13437 | ||
13438 | for (var i = 0; i < ch; i++) { | |
13439 | buffer[(s % this._blockSize) + i] = data[i + f] | |
13440 | } | |
13441 | ||
13442 | s += ch | |
13443 | f += ch | |
13444 | ||
13445 | if ((s % this._blockSize) === 0) { | |
13446 | this._update(buffer) | |
13447 | } | |
13448 | } | |
13449 | this._s = s | |
13450 | ||
13451 | return this | |
13452 | } | |
13453 | ||
13454 | Hash.prototype.digest = function (enc) { | |
13455 | // Suppose the length of the message M, in bits, is l | |
13456 | var l = this._len * 8 | |
13457 | ||
13458 | // Append the bit 1 to the end of the message | |
13459 | this._block[this._len % this._blockSize] = 0x80 | |
13460 | ||
13461 | // and then k zero bits, where k is the smallest non-negative solution to the equation (l + 1 + k) === finalSize mod blockSize | |
13462 | this._block.fill(0, this._len % this._blockSize + 1) | |
13463 | ||
13464 | if (l % (this._blockSize * 8) >= this._finalSize * 8) { | |
13465 | this._update(this._block) | |
13466 | this._block.fill(0) | |
13467 | } | |
13468 | ||
13469 | // to this append the block which is equal to the number l written in binary | |
13470 | // TODO: handle case where l is > Math.pow(2, 29) | |
13471 | this._block.writeInt32BE(l, this._blockSize - 4) | |
13472 | ||
13473 | var hash = this._update(this._block) || this._hash() | |
13474 | ||
13475 | return enc ? hash.toString(enc) : hash | |
13476 | } | |
13477 | ||
13478 | Hash.prototype._update = function () { | |
13479 | throw new Error('_update must be implemented by subclass') | |
13480 | } | |
13481 | ||
13482 | module.exports = Hash | |
13483 | ||
13484 | }).call(this,require("buffer").Buffer) | |
13485 | },{"buffer":4}],100:[function(require,module,exports){ | |
13486 | var exports = module.exports = function SHA (algorithm) { | |
13487 | algorithm = algorithm.toLowerCase() | |
13488 | ||
13489 | var Algorithm = exports[algorithm] | |
13490 | if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') | |
13491 | ||
13492 | return new Algorithm() | |
13493 | } | |
13494 | ||
13495 | exports.sha = require('./sha') | |
13496 | exports.sha1 = require('./sha1') | |
13497 | exports.sha224 = require('./sha224') | |
13498 | exports.sha256 = require('./sha256') | |
13499 | exports.sha384 = require('./sha384') | |
13500 | exports.sha512 = require('./sha512') | |
13501 | ||
13502 | },{"./sha":101,"./sha1":102,"./sha224":103,"./sha256":104,"./sha384":105,"./sha512":106}],101:[function(require,module,exports){ | |
13503 | (function (Buffer){ | |
13504 | /* | |
13505 | * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined | |
13506 | * in FIPS PUB 180-1 | |
13507 | * This source code is derived from sha1.js of the same repository. | |
13508 | * The difference between SHA-0 and SHA-1 is just a bitwise rotate left | |
13509 | * operation was added. | |
13510 | */ | |
13511 | ||
13512 | var inherits = require('inherits') | |
13513 | var Hash = require('./hash') | |
13514 | ||
13515 | var K = [ | |
13516 | 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 | |
13517 | ] | |
13518 | ||
13519 | var W = new Array(80) | |
13520 | ||
13521 | function Sha () { | |
13522 | this.init() | |
13523 | this._w = W | |
13524 | ||
13525 | Hash.call(this, 64, 56) | |
13526 | } | |
13527 | ||
13528 | inherits(Sha, Hash) | |
13529 | ||
13530 | Sha.prototype.init = function () { | |
13531 | this._a = 0x67452301 | |
13532 | this._b = 0xefcdab89 | |
13533 | this._c = 0x98badcfe | |
13534 | this._d = 0x10325476 | |
13535 | this._e = 0xc3d2e1f0 | |
13536 | ||
13537 | return this | |
13538 | } | |
13539 | ||
13540 | function rotl5 (num) { | |
13541 | return (num << 5) | (num >>> 27) | |
13542 | } | |
13543 | ||
13544 | function rotl30 (num) { | |
13545 | return (num << 30) | (num >>> 2) | |
13546 | } | |
13547 | ||
13548 | function ft (s, b, c, d) { | |
13549 | if (s === 0) return (b & c) | ((~b) & d) | |
13550 | if (s === 2) return (b & c) | (b & d) | (c & d) | |
13551 | return b ^ c ^ d | |
13552 | } | |
13553 | ||
13554 | Sha.prototype._update = function (M) { | |
13555 | var W = this._w | |
13556 | ||
13557 | var a = this._a | 0 | |
13558 | var b = this._b | 0 | |
13559 | var c = this._c | 0 | |
13560 | var d = this._d | 0 | |
13561 | var e = this._e | 0 | |
13562 | ||
13563 | for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) | |
13564 | for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] | |
13565 | ||
13566 | for (var j = 0; j < 80; ++j) { | |
13567 | var s = ~~(j / 20) | |
13568 | var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 | |
13569 | ||
13570 | e = d | |
13571 | d = c | |
13572 | c = rotl30(b) | |
13573 | b = a | |
13574 | a = t | |
13575 | } | |
13576 | ||
13577 | this._a = (a + this._a) | 0 | |
13578 | this._b = (b + this._b) | 0 | |
13579 | this._c = (c + this._c) | 0 | |
13580 | this._d = (d + this._d) | 0 | |
13581 | this._e = (e + this._e) | 0 | |
13582 | } | |
13583 | ||
13584 | Sha.prototype._hash = function () { | |
13585 | var H = new Buffer(20) | |
13586 | ||
13587 | H.writeInt32BE(this._a | 0, 0) | |
13588 | H.writeInt32BE(this._b | 0, 4) | |
13589 | H.writeInt32BE(this._c | 0, 8) | |
13590 | H.writeInt32BE(this._d | 0, 12) | |
13591 | H.writeInt32BE(this._e | 0, 16) | |
13592 | ||
13593 | return H | |
13594 | } | |
13595 | ||
13596 | module.exports = Sha | |
13597 | ||
13598 | }).call(this,require("buffer").Buffer) | |
13599 | },{"./hash":99,"buffer":4,"inherits":93}],102:[function(require,module,exports){ | |
13600 | (function (Buffer){ | |
13601 | /* | |
13602 | * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined | |
13603 | * in FIPS PUB 180-1 | |
13604 | * Version 2.1a Copyright Paul Johnston 2000 - 2002. | |
13605 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet | |
13606 | * Distributed under the BSD License | |
13607 | * See http://pajhome.org.uk/crypt/md5 for details. | |
13608 | */ | |
13609 | ||
13610 | var inherits = require('inherits') | |
13611 | var Hash = require('./hash') | |
13612 | ||
13613 | var K = [ | |
13614 | 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 | |
13615 | ] | |
13616 | ||
13617 | var W = new Array(80) | |
13618 | ||
13619 | function Sha1 () { | |
13620 | this.init() | |
13621 | this._w = W | |
13622 | ||
13623 | Hash.call(this, 64, 56) | |
13624 | } | |
13625 | ||
13626 | inherits(Sha1, Hash) | |
13627 | ||
13628 | Sha1.prototype.init = function () { | |
13629 | this._a = 0x67452301 | |
13630 | this._b = 0xefcdab89 | |
13631 | this._c = 0x98badcfe | |
13632 | this._d = 0x10325476 | |
13633 | this._e = 0xc3d2e1f0 | |
13634 | ||
13635 | return this | |
13636 | } | |
13637 | ||
13638 | function rotl1 (num) { | |
13639 | return (num << 1) | (num >>> 31) | |
13640 | } | |
13641 | ||
13642 | function rotl5 (num) { | |
13643 | return (num << 5) | (num >>> 27) | |
13644 | } | |
13645 | ||
13646 | function rotl30 (num) { | |
13647 | return (num << 30) | (num >>> 2) | |
13648 | } | |
13649 | ||
13650 | function ft (s, b, c, d) { | |
13651 | if (s === 0) return (b & c) | ((~b) & d) | |
13652 | if (s === 2) return (b & c) | (b & d) | (c & d) | |
13653 | return b ^ c ^ d | |
13654 | } | |
13655 | ||
13656 | Sha1.prototype._update = function (M) { | |
13657 | var W = this._w | |
13658 | ||
13659 | var a = this._a | 0 | |
13660 | var b = this._b | 0 | |
13661 | var c = this._c | 0 | |
13662 | var d = this._d | 0 | |
13663 | var e = this._e | 0 | |
13664 | ||
13665 | for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) | |
13666 | for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) | |
13667 | ||
13668 | for (var j = 0; j < 80; ++j) { | |
13669 | var s = ~~(j / 20) | |
13670 | var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 | |
13671 | ||
13672 | e = d | |
13673 | d = c | |
13674 | c = rotl30(b) | |
13675 | b = a | |
13676 | a = t | |
13677 | } | |
13678 | ||
13679 | this._a = (a + this._a) | 0 | |
13680 | this._b = (b + this._b) | 0 | |
13681 | this._c = (c + this._c) | 0 | |
13682 | this._d = (d + this._d) | 0 | |
13683 | this._e = (e + this._e) | 0 | |
13684 | } | |
13685 | ||
13686 | Sha1.prototype._hash = function () { | |
13687 | var H = new Buffer(20) | |
13688 | ||
13689 | H.writeInt32BE(this._a | 0, 0) | |
13690 | H.writeInt32BE(this._b | 0, 4) | |
13691 | H.writeInt32BE(this._c | 0, 8) | |
13692 | H.writeInt32BE(this._d | 0, 12) | |
13693 | H.writeInt32BE(this._e | 0, 16) | |
13694 | ||
13695 | return H | |
13696 | } | |
13697 | ||
13698 | module.exports = Sha1 | |
13699 | ||
13700 | }).call(this,require("buffer").Buffer) | |
13701 | },{"./hash":99,"buffer":4,"inherits":93}],103:[function(require,module,exports){ | |
13702 | (function (Buffer){ | |
13703 | /** | |
13704 | * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined | |
13705 | * in FIPS 180-2 | |
13706 | * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. | |
13707 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet | |
13708 | * | |
13709 | */ | |
13710 | ||
13711 | var inherits = require('inherits') | |
13712 | var Sha256 = require('./sha256') | |
13713 | var Hash = require('./hash') | |
13714 | ||
13715 | var W = new Array(64) | |
13716 | ||
13717 | function Sha224 () { | |
13718 | this.init() | |
13719 | ||
13720 | this._w = W // new Array(64) | |
13721 | ||
13722 | Hash.call(this, 64, 56) | |
13723 | } | |
13724 | ||
13725 | inherits(Sha224, Sha256) | |
13726 | ||
13727 | Sha224.prototype.init = function () { | |
13728 | this._a = 0xc1059ed8 | |
13729 | this._b = 0x367cd507 | |
13730 | this._c = 0x3070dd17 | |
13731 | this._d = 0xf70e5939 | |
13732 | this._e = 0xffc00b31 | |
13733 | this._f = 0x68581511 | |
13734 | this._g = 0x64f98fa7 | |
13735 | this._h = 0xbefa4fa4 | |
13736 | ||
13737 | return this | |
13738 | } | |
13739 | ||
13740 | Sha224.prototype._hash = function () { | |
13741 | var H = new Buffer(28) | |
13742 | ||
13743 | H.writeInt32BE(this._a, 0) | |
13744 | H.writeInt32BE(this._b, 4) | |
13745 | H.writeInt32BE(this._c, 8) | |
13746 | H.writeInt32BE(this._d, 12) | |
13747 | H.writeInt32BE(this._e, 16) | |
13748 | H.writeInt32BE(this._f, 20) | |
13749 | H.writeInt32BE(this._g, 24) | |
13750 | ||
13751 | return H | |
13752 | } | |
13753 | ||
13754 | module.exports = Sha224 | |
13755 | ||
13756 | }).call(this,require("buffer").Buffer) | |
13757 | },{"./hash":99,"./sha256":104,"buffer":4,"inherits":93}],104:[function(require,module,exports){ | |
13758 | (function (Buffer){ | |
13759 | /** | |
13760 | * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined | |
13761 | * in FIPS 180-2 | |
13762 | * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. | |
13763 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet | |
13764 | * | |
13765 | */ | |
13766 | ||
13767 | var inherits = require('inherits') | |
13768 | var Hash = require('./hash') | |
13769 | ||
13770 | var K = [ | |
13771 | 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, | |
13772 | 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, | |
13773 | 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, | |
13774 | 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, | |
13775 | 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, | |
13776 | 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, | |
13777 | 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, | |
13778 | 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, | |
13779 | 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, | |
13780 | 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, | |
13781 | 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, | |
13782 | 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, | |
13783 | 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, | |
13784 | 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, | |
13785 | 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, | |
13786 | 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 | |
13787 | ] | |
13788 | ||
13789 | var W = new Array(64) | |
13790 | ||
13791 | function Sha256 () { | |
13792 | this.init() | |
13793 | ||
13794 | this._w = W // new Array(64) | |
13795 | ||
13796 | Hash.call(this, 64, 56) | |
13797 | } | |
13798 | ||
13799 | inherits(Sha256, Hash) | |
13800 | ||
13801 | Sha256.prototype.init = function () { | |
13802 | this._a = 0x6a09e667 | |
13803 | this._b = 0xbb67ae85 | |
13804 | this._c = 0x3c6ef372 | |
13805 | this._d = 0xa54ff53a | |
13806 | this._e = 0x510e527f | |
13807 | this._f = 0x9b05688c | |
13808 | this._g = 0x1f83d9ab | |
13809 | this._h = 0x5be0cd19 | |
13810 | ||
13811 | return this | |
13812 | } | |
13813 | ||
13814 | function ch (x, y, z) { | |
13815 | return z ^ (x & (y ^ z)) | |
13816 | } | |
13817 | ||
13818 | function maj (x, y, z) { | |
13819 | return (x & y) | (z & (x | y)) | |
13820 | } | |
13821 | ||
13822 | function sigma0 (x) { | |
13823 | return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) | |
13824 | } | |
13825 | ||
13826 | function sigma1 (x) { | |
13827 | return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) | |
13828 | } | |
13829 | ||
13830 | function gamma0 (x) { | |
13831 | return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) | |
13832 | } | |
13833 | ||
13834 | function gamma1 (x) { | |
13835 | return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) | |
13836 | } | |
13837 | ||
13838 | Sha256.prototype._update = function (M) { | |
13839 | var W = this._w | |
13840 | ||
13841 | var a = this._a | 0 | |
13842 | var b = this._b | 0 | |
13843 | var c = this._c | 0 | |
13844 | var d = this._d | 0 | |
13845 | var e = this._e | 0 | |
13846 | var f = this._f | 0 | |
13847 | var g = this._g | 0 | |
13848 | var h = this._h | 0 | |
13849 | ||
13850 | for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) | |
13851 | for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 | |
13852 | ||
13853 | for (var j = 0; j < 64; ++j) { | |
13854 | var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 | |
13855 | var T2 = (sigma0(a) + maj(a, b, c)) | 0 | |
13856 | ||
13857 | h = g | |
13858 | g = f | |
13859 | f = e | |
13860 | e = (d + T1) | 0 | |
13861 | d = c | |
13862 | c = b | |
13863 | b = a | |
13864 | a = (T1 + T2) | 0 | |
13865 | } | |
13866 | ||
13867 | this._a = (a + this._a) | 0 | |
13868 | this._b = (b + this._b) | 0 | |
13869 | this._c = (c + this._c) | 0 | |
13870 | this._d = (d + this._d) | 0 | |
13871 | this._e = (e + this._e) | 0 | |
13872 | this._f = (f + this._f) | 0 | |
13873 | this._g = (g + this._g) | 0 | |
13874 | this._h = (h + this._h) | 0 | |
13875 | } | |
13876 | ||
13877 | Sha256.prototype._hash = function () { | |
13878 | var H = new Buffer(32) | |
13879 | ||
13880 | H.writeInt32BE(this._a, 0) | |
13881 | H.writeInt32BE(this._b, 4) | |
13882 | H.writeInt32BE(this._c, 8) | |
13883 | H.writeInt32BE(this._d, 12) | |
13884 | H.writeInt32BE(this._e, 16) | |
13885 | H.writeInt32BE(this._f, 20) | |
13886 | H.writeInt32BE(this._g, 24) | |
13887 | H.writeInt32BE(this._h, 28) | |
13888 | ||
13889 | return H | |
13890 | } | |
13891 | ||
13892 | module.exports = Sha256 | |
13893 | ||
13894 | }).call(this,require("buffer").Buffer) | |
13895 | },{"./hash":99,"buffer":4,"inherits":93}],105:[function(require,module,exports){ | |
13896 | (function (Buffer){ | |
13897 | var inherits = require('inherits') | |
13898 | var SHA512 = require('./sha512') | |
13899 | var Hash = require('./hash') | |
13900 | ||
13901 | var W = new Array(160) | |
13902 | ||
13903 | function Sha384 () { | |
13904 | this.init() | |
13905 | this._w = W | |
13906 | ||
13907 | Hash.call(this, 128, 112) | |
13908 | } | |
13909 | ||
13910 | inherits(Sha384, SHA512) | |
13911 | ||
13912 | Sha384.prototype.init = function () { | |
13913 | this._ah = 0xcbbb9d5d | |
13914 | this._bh = 0x629a292a | |
13915 | this._ch = 0x9159015a | |
13916 | this._dh = 0x152fecd8 | |
13917 | this._eh = 0x67332667 | |
13918 | this._fh = 0x8eb44a87 | |
13919 | this._gh = 0xdb0c2e0d | |
13920 | this._hh = 0x47b5481d | |
13921 | ||
13922 | this._al = 0xc1059ed8 | |
13923 | this._bl = 0x367cd507 | |
13924 | this._cl = 0x3070dd17 | |
13925 | this._dl = 0xf70e5939 | |
13926 | this._el = 0xffc00b31 | |
13927 | this._fl = 0x68581511 | |
13928 | this._gl = 0x64f98fa7 | |
13929 | this._hl = 0xbefa4fa4 | |
13930 | ||
13931 | return this | |
13932 | } | |
13933 | ||
13934 | Sha384.prototype._hash = function () { | |
13935 | var H = new Buffer(48) | |
13936 | ||
13937 | function writeInt64BE (h, l, offset) { | |
13938 | H.writeInt32BE(h, offset) | |
13939 | H.writeInt32BE(l, offset + 4) | |
13940 | } | |
13941 | ||
13942 | writeInt64BE(this._ah, this._al, 0) | |
13943 | writeInt64BE(this._bh, this._bl, 8) | |
13944 | writeInt64BE(this._ch, this._cl, 16) | |
13945 | writeInt64BE(this._dh, this._dl, 24) | |
13946 | writeInt64BE(this._eh, this._el, 32) | |
13947 | writeInt64BE(this._fh, this._fl, 40) | |
13948 | ||
13949 | return H | |
13950 | } | |
13951 | ||
13952 | module.exports = Sha384 | |
13953 | ||
13954 | }).call(this,require("buffer").Buffer) | |
13955 | },{"./hash":99,"./sha512":106,"buffer":4,"inherits":93}],106:[function(require,module,exports){ | |
13956 | (function (Buffer){ | |
13957 | var inherits = require('inherits') | |
13958 | var Hash = require('./hash') | |
13959 | ||
13960 | var K = [ | |
13961 | 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, | |
13962 | 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, | |
13963 | 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, | |
13964 | 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, | |
13965 | 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, | |
13966 | 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, | |
13967 | 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, | |
13968 | 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, | |
13969 | 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, | |
13970 | 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, | |
13971 | 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, | |
13972 | 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, | |
13973 | 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, | |
13974 | 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, | |
13975 | 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, | |
13976 | 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, | |
13977 | 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, | |
13978 | 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, | |
13979 | 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, | |
13980 | 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, | |
13981 | 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, | |
13982 | 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, | |
13983 | 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, | |
13984 | 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, | |
13985 | 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, | |
13986 | 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, | |
13987 | 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, | |
13988 | 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, | |
13989 | 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, | |
13990 | 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, | |
13991 | 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, | |
13992 | 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, | |
13993 | 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, | |
13994 | 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, | |
13995 | 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, | |
13996 | 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, | |
13997 | 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, | |
13998 | 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, | |
13999 | 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, | |
14000 | 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 | |
14001 | ] | |
14002 | ||
14003 | var W = new Array(160) | |
14004 | ||
14005 | function Sha512 () { | |
14006 | this.init() | |
14007 | this._w = W | |
14008 | ||
14009 | Hash.call(this, 128, 112) | |
14010 | } | |
14011 | ||
14012 | inherits(Sha512, Hash) | |
14013 | ||
14014 | Sha512.prototype.init = function () { | |
14015 | this._ah = 0x6a09e667 | |
14016 | this._bh = 0xbb67ae85 | |
14017 | this._ch = 0x3c6ef372 | |
14018 | this._dh = 0xa54ff53a | |
14019 | this._eh = 0x510e527f | |
14020 | this._fh = 0x9b05688c | |
14021 | this._gh = 0x1f83d9ab | |
14022 | this._hh = 0x5be0cd19 | |
14023 | ||
14024 | this._al = 0xf3bcc908 | |
14025 | this._bl = 0x84caa73b | |
14026 | this._cl = 0xfe94f82b | |
14027 | this._dl = 0x5f1d36f1 | |
14028 | this._el = 0xade682d1 | |
14029 | this._fl = 0x2b3e6c1f | |
14030 | this._gl = 0xfb41bd6b | |
14031 | this._hl = 0x137e2179 | |
14032 | ||
14033 | return this | |
14034 | } | |
14035 | ||
14036 | function Ch (x, y, z) { | |
14037 | return z ^ (x & (y ^ z)) | |
14038 | } | |
14039 | ||
14040 | function maj (x, y, z) { | |
14041 | return (x & y) | (z & (x | y)) | |
14042 | } | |
14043 | ||
14044 | function sigma0 (x, xl) { | |
14045 | return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) | |
14046 | } | |
14047 | ||
14048 | function sigma1 (x, xl) { | |
14049 | return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) | |
14050 | } | |
14051 | ||
14052 | function Gamma0 (x, xl) { | |
14053 | return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) | |
14054 | } | |
14055 | ||
14056 | function Gamma0l (x, xl) { | |
14057 | return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) | |
14058 | } | |
14059 | ||
14060 | function Gamma1 (x, xl) { | |
14061 | return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) | |
14062 | } | |
14063 | ||
14064 | function Gamma1l (x, xl) { | |
14065 | return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) | |
14066 | } | |
14067 | ||
14068 | function getCarry (a, b) { | |
14069 | return (a >>> 0) < (b >>> 0) ? 1 : 0 | |
14070 | } | |
14071 | ||
14072 | Sha512.prototype._update = function (M) { | |
14073 | var W = this._w | |
14074 | ||
14075 | var ah = this._ah | 0 | |
14076 | var bh = this._bh | 0 | |
14077 | var ch = this._ch | 0 | |
14078 | var dh = this._dh | 0 | |
14079 | var eh = this._eh | 0 | |
14080 | var fh = this._fh | 0 | |
14081 | var gh = this._gh | 0 | |
14082 | var hh = this._hh | 0 | |
14083 | ||
14084 | var al = this._al | 0 | |
14085 | var bl = this._bl | 0 | |
14086 | var cl = this._cl | 0 | |
14087 | var dl = this._dl | 0 | |
14088 | var el = this._el | 0 | |
14089 | var fl = this._fl | 0 | |
14090 | var gl = this._gl | 0 | |
14091 | var hl = this._hl | 0 | |
14092 | ||
14093 | for (var i = 0; i < 32; i += 2) { | |
14094 | W[i] = M.readInt32BE(i * 4) | |
14095 | W[i + 1] = M.readInt32BE(i * 4 + 4) | |
14096 | } | |
14097 | for (; i < 160; i += 2) { | |
14098 | var xh = W[i - 15 * 2] | |
14099 | var xl = W[i - 15 * 2 + 1] | |
14100 | var gamma0 = Gamma0(xh, xl) | |
14101 | var gamma0l = Gamma0l(xl, xh) | |
14102 | ||
14103 | xh = W[i - 2 * 2] | |
14104 | xl = W[i - 2 * 2 + 1] | |
14105 | var gamma1 = Gamma1(xh, xl) | |
14106 | var gamma1l = Gamma1l(xl, xh) | |
14107 | ||
14108 | // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] | |
14109 | var Wi7h = W[i - 7 * 2] | |
14110 | var Wi7l = W[i - 7 * 2 + 1] | |
14111 | ||
14112 | var Wi16h = W[i - 16 * 2] | |
14113 | var Wi16l = W[i - 16 * 2 + 1] | |
14114 | ||
14115 | var Wil = (gamma0l + Wi7l) | 0 | |
14116 | var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 | |
14117 | Wil = (Wil + gamma1l) | 0 | |
14118 | Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 | |
14119 | Wil = (Wil + Wi16l) | 0 | |
14120 | Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 | |
14121 | ||
14122 | W[i] = Wih | |
14123 | W[i + 1] = Wil | |
14124 | } | |
14125 | ||
14126 | for (var j = 0; j < 160; j += 2) { | |
14127 | Wih = W[j] | |
14128 | Wil = W[j + 1] | |
14129 | ||
14130 | var majh = maj(ah, bh, ch) | |
14131 | var majl = maj(al, bl, cl) | |
14132 | ||
14133 | var sigma0h = sigma0(ah, al) | |
14134 | var sigma0l = sigma0(al, ah) | |
14135 | var sigma1h = sigma1(eh, el) | |
14136 | var sigma1l = sigma1(el, eh) | |
14137 | ||
14138 | // t1 = h + sigma1 + ch + K[j] + W[j] | |
14139 | var Kih = K[j] | |
14140 | var Kil = K[j + 1] | |
14141 | ||
14142 | var chh = Ch(eh, fh, gh) | |
14143 | var chl = Ch(el, fl, gl) | |
14144 | ||
14145 | var t1l = (hl + sigma1l) | 0 | |
14146 | var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 | |
14147 | t1l = (t1l + chl) | 0 | |
14148 | t1h = (t1h + chh + getCarry(t1l, chl)) | 0 | |
14149 | t1l = (t1l + Kil) | 0 | |
14150 | t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 | |
14151 | t1l = (t1l + Wil) | 0 | |
14152 | t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 | |
14153 | ||
14154 | // t2 = sigma0 + maj | |
14155 | var t2l = (sigma0l + majl) | 0 | |
14156 | var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 | |
14157 | ||
14158 | hh = gh | |
14159 | hl = gl | |
14160 | gh = fh | |
14161 | gl = fl | |
14162 | fh = eh | |
14163 | fl = el | |
14164 | el = (dl + t1l) | 0 | |
14165 | eh = (dh + t1h + getCarry(el, dl)) | 0 | |
14166 | dh = ch | |
14167 | dl = cl | |
14168 | ch = bh | |
14169 | cl = bl | |
14170 | bh = ah | |
14171 | bl = al | |
14172 | al = (t1l + t2l) | 0 | |
14173 | ah = (t1h + t2h + getCarry(al, t1l)) | 0 | |
14174 | } | |
14175 | ||
14176 | this._al = (this._al + al) | 0 | |
14177 | this._bl = (this._bl + bl) | 0 | |
14178 | this._cl = (this._cl + cl) | 0 | |
14179 | this._dl = (this._dl + dl) | 0 | |
14180 | this._el = (this._el + el) | 0 | |
14181 | this._fl = (this._fl + fl) | 0 | |
14182 | this._gl = (this._gl + gl) | 0 | |
14183 | this._hl = (this._hl + hl) | 0 | |
14184 | ||
14185 | this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 | |
14186 | this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 | |
14187 | this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 | |
14188 | this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 | |
14189 | this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 | |
14190 | this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 | |
14191 | this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 | |
14192 | this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 | |
14193 | } | |
14194 | ||
14195 | Sha512.prototype._hash = function () { | |
14196 | var H = new Buffer(64) | |
14197 | ||
14198 | function writeInt64BE (h, l, offset) { | |
14199 | H.writeInt32BE(h, offset) | |
14200 | H.writeInt32BE(l, offset + 4) | |
14201 | } | |
14202 | ||
14203 | writeInt64BE(this._ah, this._al, 0) | |
14204 | writeInt64BE(this._bh, this._bl, 8) | |
14205 | writeInt64BE(this._ch, this._cl, 16) | |
14206 | writeInt64BE(this._dh, this._dl, 24) | |
14207 | writeInt64BE(this._eh, this._el, 32) | |
14208 | writeInt64BE(this._fh, this._fl, 40) | |
14209 | writeInt64BE(this._gh, this._gl, 48) | |
14210 | writeInt64BE(this._hh, this._hl, 56) | |
14211 | ||
14212 | return H | |
14213 | } | |
14214 | ||
14215 | module.exports = Sha512 | |
14216 | ||
14217 | }).call(this,require("buffer").Buffer) | |
14218 | },{"./hash":99,"buffer":4,"inherits":93}],107:[function(require,module,exports){ | |
14219 | var inherits = require('inherits') | |
14220 | var native = require('./native') | |
14221 | ||
14222 | function TfTypeError (type, value, valueTypeName) { | |
14223 | this.__error = Error.call(this) | |
14224 | this.__type = type | |
14225 | this.__value = value | |
14226 | this.__valueTypeName = valueTypeName | |
14227 | ||
14228 | var message | |
14229 | Object.defineProperty(this, 'message', { | |
14230 | enumerable: true, | |
14231 | get: function () { | |
14232 | if (message) return message | |
14233 | ||
14234 | valueTypeName = valueTypeName || getValueTypeName(value) | |
14235 | message = tfErrorString(type, value, valueTypeName) | |
14236 | ||
14237 | return message | |
14238 | } | |
14239 | }) | |
14240 | } | |
14241 | ||
14242 | function TfPropertyTypeError (type, property, label, value, error, valueTypeName) { | |
14243 | this.__error = error || Error.call(this) | |
14244 | this.__label = label | |
14245 | this.__property = property | |
14246 | this.__type = type | |
14247 | this.__value = value | |
14248 | this.__valueTypeName = valueTypeName | |
14249 | ||
14250 | var message | |
14251 | Object.defineProperty(this, 'message', { | |
14252 | enumerable: true, | |
14253 | get: function () { | |
14254 | if (message) return message | |
14255 | if (type) { | |
14256 | valueTypeName = valueTypeName || getValueTypeName(value) | |
14257 | message = tfPropertyErrorString(type, label, property, value, valueTypeName) | |
14258 | } else { | |
14259 | message = 'Unexpected property "' + property + '"' | |
14260 | } | |
14261 | ||
14262 | return message | |
14263 | } | |
14264 | }) | |
14265 | } | |
14266 | ||
14267 | // inherit from Error, assign stack | |
14268 | [TfTypeError, TfPropertyTypeError].forEach(function (tfErrorType) { | |
14269 | inherits(tfErrorType, Error) | |
14270 | Object.defineProperty(tfErrorType, 'stack', { | |
14271 | get: function () { return this.__error.stack } | |
14272 | }) | |
14273 | }) | |
14274 | ||
14275 | function tfCustomError (expected, actual) { | |
14276 | return new TfTypeError(expected, {}, actual) | |
14277 | } | |
14278 | ||
14279 | function tfSubError (e, property, label) { | |
14280 | // sub child? | |
14281 | if (e instanceof TfPropertyTypeError) { | |
14282 | property = property + '.' + e.__property | |
14283 | label = e.__label | |
14284 | ||
14285 | return new TfPropertyTypeError( | |
14286 | e.__type, property, label, e.__value, e.__error, e.__valueTypeName | |
14287 | ) | |
14288 | } | |
14289 | ||
14290 | // child? | |
14291 | if (e instanceof TfTypeError) { | |
14292 | return new TfPropertyTypeError( | |
14293 | e.__type, property, label, e.__value, e.__error, e.__valueTypeName | |
14294 | ) | |
14295 | } | |
14296 | ||
14297 | return e | |
14298 | } | |
14299 | ||
14300 | function getTypeName (fn) { | |
14301 | return fn.name || fn.toString().match(/function (.*?)\s*\(/)[1] | |
14302 | } | |
14303 | ||
14304 | function getValueTypeName (value) { | |
14305 | return native.Nil(value) ? '' : getTypeName(value.constructor) | |
14306 | } | |
14307 | ||
14308 | function getValue (value) { | |
14309 | if (native.Function(value)) return '' | |
14310 | if (native.String(value)) return JSON.stringify(value) | |
14311 | if (value && native.Object(value)) return '' | |
14312 | return value | |
14313 | } | |
14314 | ||
14315 | function tfJSON (type) { | |
14316 | if (native.Function(type)) return type.toJSON ? type.toJSON() : getTypeName(type) | |
14317 | if (native.Array(type)) return 'Array' | |
14318 | if (type && native.Object(type)) return 'Object' | |
14319 | ||
14320 | return type !== undefined ? type : '' | |
14321 | } | |
14322 | ||
14323 | function tfErrorString (type, value, valueTypeName) { | |
14324 | var valueJson = getValue(value) | |
14325 | ||
14326 | return 'Expected ' + tfJSON(type) + ', got' + | |
14327 | (valueTypeName !== '' ? ' ' + valueTypeName : '') + | |
14328 | (valueJson !== '' ? ' ' + valueJson : '') | |
14329 | } | |
14330 | ||
14331 | function tfPropertyErrorString (type, label, name, value, valueTypeName) { | |
14332 | var description = '" of type ' | |
14333 | if (label === 'key') description = '" with key type ' | |
14334 | ||
14335 | return tfErrorString('property "' + tfJSON(name) + description + tfJSON(type), value, valueTypeName) | |
14336 | } | |
14337 | ||
14338 | module.exports = { | |
14339 | TfTypeError: TfTypeError, | |
14340 | TfPropertyTypeError: TfPropertyTypeError, | |
14341 | tfCustomError: tfCustomError, | |
14342 | tfSubError: tfSubError, | |
14343 | tfJSON: tfJSON, | |
14344 | getValueTypeName: getValueTypeName | |
14345 | } | |
14346 | ||
14347 | },{"./native":110,"inherits":93}],108:[function(require,module,exports){ | |
14348 | (function (Buffer){ | |
14349 | var NATIVE = require('./native') | |
14350 | var ERRORS = require('./errors') | |
14351 | ||
14352 | function _Buffer (value) { | |
14353 | return Buffer.isBuffer(value) | |
14354 | } | |
14355 | ||
14356 | function Hex (value) { | |
14357 | return typeof value === 'string' && /^([0-9a-f]{2})+$/i.test(value) | |
14358 | } | |
14359 | ||
14360 | function _LengthN (type, length) { | |
14361 | var name = type.toJSON() | |
14362 | ||
14363 | function Length (value) { | |
14364 | if (!type(value)) return false | |
14365 | if (value.length === length) return true | |
14366 | ||
14367 | throw ERRORS.tfCustomError(name + '(Length: ' + length + ')', name + '(Length: ' + value.length + ')') | |
14368 | } | |
14369 | Length.toJSON = function () { return name } | |
14370 | ||
14371 | return Length | |
14372 | } | |
14373 | ||
14374 | var _ArrayN = _LengthN.bind(null, NATIVE.Array) | |
14375 | var _BufferN = _LengthN.bind(null, _Buffer) | |
14376 | var _HexN = _LengthN.bind(null, Hex) | |
14377 | ||
14378 | var UINT53_MAX = Math.pow(2, 53) - 1 | |
14379 | ||
14380 | function Finite (value) { | |
14381 | return typeof value === 'number' && isFinite(value) | |
14382 | } | |
14383 | function Int8 (value) { return ((value << 24) >> 24) === value } | |
14384 | function Int16 (value) { return ((value << 16) >> 16) === value } | |
14385 | function Int32 (value) { return (value | 0) === value } | |
14386 | function UInt8 (value) { return (value & 0xff) === value } | |
14387 | function UInt16 (value) { return (value & 0xffff) === value } | |
14388 | function UInt32 (value) { return (value >>> 0) === value } | |
14389 | function UInt53 (value) { | |
14390 | return typeof value === 'number' && | |
14391 | value >= 0 && | |
14392 | value <= UINT53_MAX && | |
14393 | Math.floor(value) === value | |
14394 | } | |
14395 | ||
14396 | var types = { | |
14397 | ArrayN: _ArrayN, | |
14398 | Buffer: _Buffer, | |
14399 | BufferN: _BufferN, | |
14400 | Finite: Finite, | |
14401 | Hex: Hex, | |
14402 | HexN: _HexN, | |
14403 | Int8: Int8, | |
14404 | Int16: Int16, | |
14405 | Int32: Int32, | |
14406 | UInt8: UInt8, | |
14407 | UInt16: UInt16, | |
14408 | UInt32: UInt32, | |
14409 | UInt53: UInt53 | |
14410 | } | |
14411 | ||
14412 | for (var typeName in types) { | |
14413 | types[typeName].toJSON = function (t) { | |
14414 | return t | |
14415 | }.bind(null, typeName) | |
14416 | } | |
14417 | ||
14418 | module.exports = types | |
14419 | ||
14420 | }).call(this,{"isBuffer":require("../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js")}) | |
14421 | },{"../../../../../.nvm/versions/node/v6.0.0/lib/node_modules/browserify/node_modules/is-buffer/index.js":9,"./errors":107,"./native":110}],109:[function(require,module,exports){ | |
14422 | var ERRORS = require('./errors') | |
14423 | var NATIVE = require('./native') | |
14424 | ||
14425 | // short-hand | |
14426 | var tfJSON = ERRORS.tfJSON | |
14427 | var TfTypeError = ERRORS.TfTypeError | |
14428 | var TfPropertyTypeError = ERRORS.TfPropertyTypeError | |
14429 | var tfSubError = ERRORS.tfSubError | |
14430 | var getValueTypeName = ERRORS.getValueTypeName | |
14431 | ||
14432 | var TYPES = { | |
14433 | arrayOf: function arrayOf (type) { | |
14434 | type = compile(type) | |
14435 | ||
14436 | function _arrayOf (array, strict) { | |
14437 | if (!NATIVE.Array(array)) return false | |
14438 | ||
14439 | return array.every(function (value, i) { | |
14440 | try { | |
14441 | return typeforce(type, value, strict) | |
14442 | } catch (e) { | |
14443 | throw tfSubError(e, i) | |
14444 | } | |
14445 | }) | |
14446 | } | |
14447 | _arrayOf.toJSON = function () { return '[' + tfJSON(type) + ']' } | |
14448 | ||
14449 | return _arrayOf | |
14450 | }, | |
14451 | ||
14452 | maybe: function maybe (type) { | |
14453 | type = compile(type) | |
14454 | ||
14455 | function _maybe (value, strict) { | |
14456 | return NATIVE.Nil(value) || type(value, strict, maybe) | |
14457 | } | |
14458 | _maybe.toJSON = function () { return '?' + tfJSON(type) } | |
14459 | ||
14460 | return _maybe | |
14461 | }, | |
14462 | ||
14463 | map: function map (propertyType, propertyKeyType) { | |
14464 | propertyType = compile(propertyType) | |
14465 | if (propertyKeyType) propertyKeyType = compile(propertyKeyType) | |
14466 | ||
14467 | function _map (value, strict) { | |
14468 | if (!NATIVE.Object(value, strict)) return false | |
14469 | if (NATIVE.Nil(value, strict)) return false | |
14470 | ||
14471 | for (var propertyName in value) { | |
14472 | try { | |
14473 | if (propertyKeyType) { | |
14474 | typeforce(propertyKeyType, propertyName, strict) | |
14475 | } | |
14476 | } catch (e) { | |
14477 | throw tfSubError(e, propertyName, 'key') | |
14478 | } | |
14479 | ||
14480 | try { | |
14481 | var propertyValue = value[propertyName] | |
14482 | typeforce(propertyType, propertyValue, strict) | |
14483 | } catch (e) { | |
14484 | throw tfSubError(e, propertyName) | |
14485 | } | |
14486 | } | |
14487 | ||
14488 | return true | |
14489 | } | |
14490 | ||
14491 | if (propertyKeyType) { | |
14492 | _map.toJSON = function () { | |
14493 | return '{' + tfJSON(propertyKeyType) + ': ' + tfJSON(propertyType) + '}' | |
14494 | } | |
14495 | } else { | |
14496 | _map.toJSON = function () { return '{' + tfJSON(propertyType) + '}' } | |
14497 | } | |
14498 | ||
14499 | return _map | |
14500 | }, | |
14501 | ||
14502 | object: function object (uncompiled) { | |
14503 | var type = {} | |
14504 | ||
14505 | for (var typePropertyName in uncompiled) { | |
14506 | type[typePropertyName] = compile(uncompiled[typePropertyName]) | |
14507 | } | |
14508 | ||
14509 | function _object (value, strict) { | |
14510 | if (!NATIVE.Object(value)) return false | |
14511 | if (NATIVE.Nil(value)) return false | |
14512 | ||
14513 | var propertyName | |
14514 | ||
14515 | try { | |
14516 | for (propertyName in type) { | |
14517 | var propertyType = type[propertyName] | |
14518 | var propertyValue = value[propertyName] | |
14519 | ||
14520 | typeforce(propertyType, propertyValue, strict) | |
14521 | } | |
14522 | } catch (e) { | |
14523 | throw tfSubError(e, propertyName) | |
14524 | } | |
14525 | ||
14526 | if (strict) { | |
14527 | for (propertyName in value) { | |
14528 | if (type[propertyName]) continue | |
14529 | ||
14530 | throw new TfPropertyTypeError(undefined, propertyName) | |
14531 | } | |
14532 | } | |
14533 | ||
14534 | return true | |
14535 | } | |
14536 | _object.toJSON = function () { return tfJSON(type) } | |
14537 | ||
14538 | return _object | |
14539 | }, | |
14540 | ||
14541 | oneOf: function oneOf () { | |
14542 | var types = [].slice.call(arguments).map(compile) | |
14543 | ||
14544 | function _oneOf (value, strict) { | |
14545 | return types.some(function (type) { | |
14546 | try { | |
14547 | return typeforce(type, value, strict) | |
14548 | } catch (e) { | |
14549 | return false | |
14550 | } | |
14551 | }) | |
14552 | } | |
14553 | _oneOf.toJSON = function () { return types.map(tfJSON).join('|') } | |
14554 | ||
14555 | return _oneOf | |
14556 | }, | |
14557 | ||
14558 | quacksLike: function quacksLike (type) { | |
14559 | function _quacksLike (value) { | |
14560 | return type === getValueTypeName(value) | |
14561 | } | |
14562 | _quacksLike.toJSON = function () { return type } | |
14563 | ||
14564 | return _quacksLike | |
14565 | }, | |
14566 | ||
14567 | tuple: function tuple () { | |
14568 | var types = [].slice.call(arguments).map(compile) | |
14569 | ||
14570 | function _tuple (values, strict) { | |
14571 | return types.every(function (type, i) { | |
14572 | try { | |
14573 | return typeforce(type, values[i], strict) | |
14574 | } catch (e) { | |
14575 | throw tfSubError(e, i) | |
14576 | } | |
14577 | }) && (!strict || values.length === arguments.length) | |
14578 | } | |
14579 | _tuple.toJSON = function () { return '(' + types.map(tfJSON).join(', ') + ')' } | |
14580 | ||
14581 | return _tuple | |
14582 | }, | |
14583 | ||
14584 | value: function value (expected) { | |
14585 | function _value (actual) { | |
14586 | return actual === expected | |
14587 | } | |
14588 | _value.toJSON = function () { return expected } | |
14589 | ||
14590 | return _value | |
14591 | } | |
14592 | } | |
14593 | ||
14594 | function compile (type) { | |
14595 | if (NATIVE.String(type)) { | |
14596 | if (type[0] === '?') return TYPES.maybe(compile(type.slice(1))) | |
14597 | ||
14598 | return NATIVE[type] || TYPES.quacksLike(type) | |
14599 | } else if (type && NATIVE.Object(type)) { | |
14600 | if (NATIVE.Array(type)) return TYPES.arrayOf(compile(type[0])) | |
14601 | ||
14602 | return TYPES.object(type) | |
14603 | } else if (NATIVE.Function(type)) { | |
14604 | return type | |
14605 | } | |
14606 | ||
14607 | return TYPES.value(type) | |
14608 | } | |
14609 | ||
14610 | function typeforce (type, value, strict, surrogate) { | |
14611 | if (NATIVE.Function(type)) { | |
14612 | if (type(value, strict)) return true | |
14613 | ||
14614 | throw new TfTypeError(surrogate || type, value) | |
14615 | } | |
14616 | ||
14617 | // JIT | |
14618 | return typeforce(compile(type), value, strict) | |
14619 | } | |
14620 | ||
14621 | // assign types to typeforce function | |
14622 | for (var typeName in NATIVE) { | |
14623 | typeforce[typeName] = NATIVE[typeName] | |
14624 | } | |
14625 | ||
14626 | for (typeName in TYPES) { | |
14627 | typeforce[typeName] = TYPES[typeName] | |
14628 | } | |
14629 | ||
14630 | var EXTRA = require('./extra') | |
14631 | for (typeName in EXTRA) { | |
14632 | typeforce[typeName] = EXTRA[typeName] | |
14633 | } | |
14634 | ||
14635 | // async wrapper | |
14636 | function __async (type, value, strict, callback) { | |
14637 | // default to falsy strict if using shorthand overload | |
14638 | if (typeof strict === 'function') return __async(type, value, false, strict) | |
14639 | ||
14640 | try { | |
14641 | typeforce(type, value, strict) | |
14642 | } catch (e) { | |
14643 | return callback(e) | |
14644 | } | |
14645 | ||
14646 | callback() | |
14647 | } | |
14648 | ||
14649 | typeforce.async = __async | |
14650 | typeforce.compile = compile | |
14651 | typeforce.TfTypeError = TfTypeError | |
14652 | typeforce.TfPropertyTypeError = TfPropertyTypeError | |
14653 | ||
14654 | module.exports = typeforce | |
14655 | ||
14656 | },{"./errors":107,"./extra":108,"./native":110}],110:[function(require,module,exports){ | |
14657 | var types = { | |
14658 | Array: function (value) { return value !== null && value !== undefined && value.constructor === Array }, | |
14659 | Boolean: function (value) { return typeof value === 'boolean' }, | |
14660 | Function: function (value) { return typeof value === 'function' }, | |
14661 | Nil: function (value) { return value === undefined || value === null }, | |
14662 | Number: function (value) { return typeof value === 'number' }, | |
14663 | Object: function (value) { return typeof value === 'object' }, | |
14664 | String: function (value) { return typeof value === 'string' }, | |
14665 | '': function () { return true } | |
14666 | } | |
14667 | ||
14668 | // TODO: deprecate | |
14669 | types.Null = types.Nil | |
14670 | ||
14671 | for (var typeName in types) { | |
14672 | types[typeName].toJSON = function (t) { | |
14673 | return t | |
14674 | }.bind(null, typeName) | |
14675 | } | |
14676 | ||
14677 | module.exports = types | |
14678 | ||
14679 | },{}],111:[function(require,module,exports){ | |
14680 | (function (Buffer){ | |
14681 | 'use strict' | |
14682 | ||
14683 | // Number.MAX_SAFE_INTEGER | |
14684 | var MAX_SAFE_INTEGER = 9007199254740991 | |
14685 | ||
14686 | function checkUInt53 (n) { | |
14687 | if (n < 0 || n > MAX_SAFE_INTEGER || n % 1 !== 0) throw new RangeError('value out of range') | |
14688 | } | |
14689 | ||
14690 | function encode (number, buffer, offset) { | |
14691 | checkUInt53(number) | |
14692 | ||
14693 | if (!buffer) buffer = new Buffer(encodingLength(number)) | |
14694 | if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') | |
14695 | if (!offset) offset = 0 | |
14696 | ||
14697 | // 8 bit | |
14698 | if (number < 0xfd) { | |
14699 | buffer.writeUInt8(number, offset) | |
14700 | encode.bytes = 1 | |
14701 | ||
14702 | // 16 bit | |
14703 | } else if (number <= 0xffff) { | |
14704 | buffer.writeUInt8(0xfd, offset) | |
14705 | buffer.writeUInt16LE(number, offset + 1) | |
14706 | encode.bytes = 3 | |
14707 | ||
14708 | // 32 bit | |
14709 | } else if (number <= 0xffffffff) { | |
14710 | buffer.writeUInt8(0xfe, offset) | |
14711 | buffer.writeUInt32LE(number, offset + 1) | |
14712 | encode.bytes = 5 | |
14713 | ||
14714 | // 64 bit | |
14715 | } else { | |
14716 | buffer.writeUInt8(0xff, offset) | |
14717 | buffer.writeUInt32LE(number >>> 0, offset + 1) | |
14718 | buffer.writeUInt32LE((number / 0x100000000) | 0, offset + 5) | |
14719 | encode.bytes = 9 | |
14720 | } | |
14721 | ||
14722 | return buffer | |
14723 | } | |
14724 | ||
14725 | function decode (buffer, offset) { | |
14726 | if (!Buffer.isBuffer(buffer)) throw new TypeError('buffer must be a Buffer instance') | |
14727 | if (!offset) offset = 0 | |
14728 | ||
14729 | var first = buffer.readUInt8(offset) | |
14730 | ||
14731 | // 8 bit | |
14732 | if (first < 0xfd) { | |
14733 | decode.bytes = 1 | |
14734 | return first | |
14735 | ||
14736 | // 16 bit | |
14737 | } else if (first === 0xfd) { | |
14738 | decode.bytes = 3 | |
14739 | return buffer.readUInt16LE(offset + 1) | |
14740 | ||
14741 | // 32 bit | |
14742 | } else if (first === 0xfe) { | |
14743 | decode.bytes = 5 | |
14744 | return buffer.readUInt32LE(offset + 1) | |
14745 | ||
14746 | // 64 bit | |
14747 | } else { | |
14748 | decode.bytes = 9 | |
14749 | var lo = buffer.readUInt32LE(offset + 1) | |
14750 | var hi = buffer.readUInt32LE(offset + 5) | |
14751 | var number = hi * 0x0100000000 + lo | |
14752 | checkUInt53(number) | |
14753 | ||
14754 | return number | |
14755 | } | |
14756 | } | |
14757 | ||
14758 | function encodingLength (number) { | |
14759 | checkUInt53(number) | |
14760 | ||
14761 | return ( | |
14762 | number < 0xfd ? 1 | |
14763 | : number <= 0xffff ? 3 | |
14764 | : number <= 0xffffffff ? 5 | |
14765 | : 9 | |
14766 | ) | |
14767 | } | |
14768 | ||
14769 | module.exports = { encode: encode, decode: decode, encodingLength: encodingLength } | |
14770 | ||
14771 | }).call(this,require("buffer").Buffer) | |
14772 | },{"buffer":4}],112:[function(require,module,exports){ | |
14773 | (function (Buffer){ | |
14774 | var bs58check = require('bs58check') | |
14775 | ||
14776 | function decodeRaw (buffer, version) { | |
14777 | // check version only if defined | |
14778 | if (version !== undefined && buffer[0] !== version) throw new Error('Invalid network version') | |
14779 | ||
14780 | // uncompressed | |
14781 | if (buffer.length === 33) { | |
14782 | return { | |
14783 | version: buffer[0], | |
14784 | privateKey: buffer.slice(1, 33), | |
14785 | compressed: false | |
14786 | } | |
14787 | } | |
14788 | ||
14789 | // invalid length | |
14790 | if (buffer.length !== 34) throw new Error('Invalid WIF length') | |
14791 | ||
14792 | // invalid compression flag | |
14793 | if (buffer[33] !== 0x01) throw new Error('Invalid compression flag') | |
14794 | ||
14795 | return { | |
14796 | version: buffer[0], | |
14797 | privateKey: buffer.slice(1, 33), | |
14798 | compressed: true | |
14799 | } | |
14800 | } | |
14801 | ||
14802 | function encodeRaw (version, privateKey, compressed) { | |
14803 | var result = new Buffer(compressed ? 34 : 33) | |
14804 | ||
14805 | result.writeUInt8(version, 0) | |
14806 | privateKey.copy(result, 1) | |
14807 | ||
14808 | if (compressed) { | |
14809 | result[33] = 0x01 | |
14810 | } | |
14811 | ||
14812 | return result | |
14813 | } | |
14814 | ||
14815 | function decode (string, version) { | |
14816 | return decodeRaw(bs58check.decode(string), version) | |
14817 | } | |
14818 | ||
14819 | function encode (version, privateKey, compressed) { | |
14820 | if (typeof version === 'number') return bs58check.encode(encodeRaw(version, privateKey, compressed)) | |
14821 | ||
14822 | return bs58check.encode( | |
14823 | encodeRaw( | |
14824 | version.version, | |
14825 | version.privateKey, | |
14826 | version.compressed | |
14827 | ) | |
14828 | ) | |
14829 | } | |
14830 | ||
14831 | module.exports = { | |
14832 | decode: decode, | |
14833 | decodeRaw: decodeRaw, | |
14834 | encode: encode, | |
14835 | encodeRaw: encodeRaw | |
14836 | } | |
14837 | ||
14838 | }).call(this,require("buffer").Buffer) | |
14839 | },{"bs58check":80,"buffer":4}]},{},[33])(33) | |
14840 | }); |