UNPKG

1.93 MBJavaScriptView Raw
1require=(function(){function r(e,n,t){function o(i,f){if(!n[i]){if(!e[i]){var c="function"==typeof require&&require;if(!f&&c)return c(i,!0);if(u)return u(i,!0);var a=new Error("Cannot find module '"+i+"'");throw a.code="MODULE_NOT_FOUND",a}var p=n[i]={exports:{}};e[i][0].call(p.exports,function(r){var n=e[i][1][r];return o(n||r)},p,p.exports,r,e,n,t)}return n[i].exports}for(var u="function"==typeof require&&require,i=0;i<t.length;i++)o(t[i]);return o}return r})()({1:[function(require,module,exports){
2(function (Buffer){(function (){
3'use strict';
4
5var _ = require('lodash');
6var $ = require('./util/preconditions');
7var errors = require('./errors');
8var Base58Check = require('./encoding/base58check');
9var Bech32 = require('./encoding/bech32');
10var Networks = require('./networks');
11var Hash = require('./crypto/hash');
12var JSUtil = require('./util/js');
13var PublicKey = require('./publickey');
14
15/**
16 * Instantiate an address from an address String or Buffer, a public key or script hash Buffer,
17 * or an instance of {@link PublicKey} or {@link Script}.
18 *
19 * This is an immutable class, and if the first parameter provided to this constructor is an
20 * `Address` instance, the same argument will be returned.
21 *
22 * An address has two key properties: `network` and `type`. The type is one of
23 * `Address.PayToPublicKeyHash` (value is the `'pubkeyhash'` string),
24 * `Address.PayToScriptHash` (the string `'scripthash'`),
25 * `Address.PayToWitnessPublicKeyHash` (the string `'witnesspubkeyhash'`),
26 * or `Address.PayToWitnessScriptHash` (the string `'witnessscripthash'`).
27 * The network is an instance of {@link Network}.
28 * You can quickly check whether an address is of a given kind by using the methods
29 * `isPayToPublicKeyHash`, `isPayToScriptHash`, `isPayToWitnessPublicKeyHash`,
30 * and `isPayToWitnessScriptHash`.
31 *
32 * @example
33 * ```javascript
34 * // validate that an input field is valid
35 * var error = Address.getValidationError(input, 'testnet');
36 * if (!error) {
37 * var address = Address(input, 'testnet');
38 * } else {
39 * // invalid network or checksum (typo?)
40 * var message = error.messsage;
41 * }
42 *
43 * // get an address from a public key
44 * var address = Address(publicKey, 'testnet').toString();
45 * ```
46 *
47 * @param {*} data - The encoded data in various formats
48 * @param {Network|String|number=} network - The network: 'livenet' or 'testnet'
49 * @param {string=} type - The type of address: 'scripthash', 'pubkeyhash', witnessscripthash, 'witnesspubkeyhash', or 'taproot'
50 * @param {string=} multisigType - The type of multisig: 'scripthash' or 'witnessscripthash'
51 * @returns {Address} A new valid and frozen instance of an Address
52 * @constructor
53 */
54function Address(data, network, type, multisigType) {
55 /* jshint maxcomplexity: 12 */
56 /* jshint maxstatements: 20 */
57
58 if (!(this instanceof Address)) {
59 return new Address(data, network, type);
60 }
61
62 if (_.isArray(data) && _.isNumber(network)) {
63 return Address.createMultisig(data, network, type, false, multisigType);
64 }
65
66 if (data instanceof Address) {
67 // Immutable instance
68 return data;
69 }
70
71 $.checkArgument(data, 'First argument is required, please include address data.', 'guide/address.html');
72
73 if (network && !Networks.get(network)) {
74 throw new TypeError('Second argument must be "livenet" or "testnet".');
75 }
76
77 if (type && (
78 type !== Address.PayToPublicKeyHash
79 && type !== Address.PayToScriptHash
80 && type !== Address.PayToWitnessPublicKeyHash
81 && type !== Address.PayToWitnessScriptHash
82 && type !== Address.PayToTaproot)) {
83 throw new TypeError('Third argument must be "pubkeyhash", "scripthash", "witnesspubkeyhash", "witnessscripthash", or "taproot".');
84 }
85
86 var info = this._classifyArguments(data, network, type);
87
88 // set defaults if not set
89 info.network = info.network || Networks.get(network) || Networks.defaultNetwork;
90 info.type = info.type || type || Address.PayToPublicKeyHash;
91
92 JSUtil.defineImmutable(this, {
93 hashBuffer: info.hashBuffer,
94 network: info.network,
95 type: info.type
96 });
97
98 return this;
99}
100
101/**
102 * Internal function used to split different kinds of arguments of the constructor
103 * @param {*} data - The encoded data in various formats
104 * @param {Network|String|number=} network - The network: 'livenet' or 'testnet'
105 * @param {string=} type - The type of address: 'script' or 'pubkey'
106 * @returns {Object} An "info" object with "type", "network", and "hashBuffer"
107 */
108Address.prototype._classifyArguments = function(data, network, type) {
109 /* jshint maxcomplexity: 10 */
110 // transform and validate input data
111 if ((data instanceof Buffer || data instanceof Uint8Array) && (data.length === 20 || data.length === 32)) {
112 return Address._transformHash(data, network, type);
113 } else if ((data instanceof Buffer || data instanceof Uint8Array) && data.length >= 21) {
114 return Address._transformBuffer(data, network, type);
115 } else if (data instanceof PublicKey) {
116 return Address._transformPublicKey(data, network, type);
117 } else if (data instanceof Script) {
118 return Address._transformScript(data, network);
119 } else if (typeof(data) === 'string') {
120 return Address._transformString(data, network, type);
121 } else if (_.isObject(data)) {
122 return Address._transformObject(data);
123 } else {
124 throw new TypeError('First argument is an unrecognized data format.');
125 }
126};
127
128/** @static */
129Address.PayToPublicKeyHash = 'pubkeyhash';
130/** @static */
131Address.PayToScriptHash = 'scripthash';
132/** @static */
133Address.PayToWitnessPublicKeyHash = 'witnesspubkeyhash';
134/** @static */
135Address.PayToWitnessScriptHash = 'witnessscripthash';
136/** @static */
137Address.PayToTaproot = 'taproot';
138
139/**
140 * @param {Buffer} hash - An instance of a hash Buffer
141 * @param {string} type - either 'pubkeyhash', 'scripthash', 'witnesspubkeyhash', or 'witnessscripthash'
142 * @param {Network=} network - the name of the network associated
143 * @returns {Object} An object with keys: hashBuffer
144 * @private
145 */
146Address._transformHash = function(hash, network, type) {
147 var info = {};
148 if (!(hash instanceof Buffer) && !(hash instanceof Uint8Array)) {
149 throw new TypeError('Address supplied is not a buffer.');
150 }
151 if (hash.length !== 20 && hash.length !== 32) {
152 throw new TypeError('Address hashbuffers must be either 20 or 32 bytes.');
153 }
154 info.hashBuffer = hash;
155 info.network = Networks.get(network) || Networks.defaultNetwork;
156 info.type = type;
157 return info;
158};
159
160/**
161 * Deserializes an address serialized through `Address#toObject()`
162 * @param {Object} data
163 * @param {string} data.hash - the hash that this address encodes
164 * @param {string} data.type - either 'pubkeyhash', 'scripthash', 'witnesspubkeyhash', or 'witnessscripthash'
165 * @param {Network=} data.network - the name of the network associated
166 * @return {Address}
167 */
168Address._transformObject = function(data) {
169 $.checkArgument(data.hash || data.hashBuffer, 'Must provide a `hash` or `hashBuffer` property');
170 $.checkArgument(data.type, 'Must provide a `type` property');
171 return {
172 hashBuffer: data.hash ? Buffer.from(data.hash, 'hex') : data.hashBuffer,
173 network: Networks.get(data.network) || Networks.defaultNetwork,
174 type: data.type
175 };
176};
177
178/**
179 * Internal function to discover the network and type based on the first data byte
180 *
181 * @param {Buffer} buffer - An instance of a hex encoded address Buffer
182 * @returns {Object} An object with keys: network and type
183 * @private
184 */
185Address._classifyFromVersion = function(buffer) {
186 var version = {};
187
188 if (buffer.length > 21) {
189 var info = Bech32.decode(buffer.toString('utf8'));
190 if (info.version !== 0 && info.version !== 1) { // v1 == taproot
191 throw new TypeError('Only witness v0 and v1 addresses are supported.');
192 }
193
194 if (info.version === 0) {
195 if (info.data.length === 20) {
196 version.type = Address.PayToWitnessPublicKeyHash;
197 } else if (info.data.length === 32) {
198 version.type = Address.PayToWitnessScriptHash;
199 } else {
200 throw new TypeError('Witness data must be either 20 or 32 bytes.')
201 }
202 } else if (info.version === 1) {
203 if (info.data.length === 32) {
204 version.type = Address.PayToTaproot;
205 } else {
206 throw new TypeError('Witness data must be 32 bytes for v1');
207 }
208 } else {
209 }
210 version.network = Networks.get(info.prefix, 'bech32prefix');
211 } else {
212
213 var pubkeyhashNetwork = Networks.get(buffer[0], 'pubkeyhash');
214 var scripthashNetwork = Networks.get(buffer[0], 'scripthash');
215
216 if (pubkeyhashNetwork) {
217 version.network = pubkeyhashNetwork;
218 version.type = Address.PayToPublicKeyHash;
219 } else if (scripthashNetwork) {
220 version.network = scripthashNetwork;
221 version.type = Address.PayToScriptHash;
222 }
223 }
224
225 return version;
226};
227
228/**
229 * Internal function to transform a bitcoin address buffer
230 *
231 * @param {Buffer} buffer - An instance of a hex encoded address Buffer
232 * @param {string=} network - The network: 'livenet' or 'testnet'
233 * @param {string=} type - The type: 'pubkeyhash', 'scripthash', 'witnesspubkeyhash', or 'witnessscripthash'
234 * @returns {Object} An object with keys: hashBuffer, network and type
235 * @private
236 */
237Address._transformBuffer = function(buffer, network, type) {
238 /* jshint maxcomplexity: 9 */
239 var info = {};
240 if (!(buffer instanceof Buffer) && !(buffer instanceof Uint8Array)) {
241 throw new TypeError('Address supplied is not a buffer.');
242 }
243
244 if (buffer.length < 21) {
245 throw new TypeError('Address buffer is incorrect length.');
246 }
247
248 var networkObj = Networks.get(network);
249 var bufferVersion = Address._classifyFromVersion(buffer);
250
251 if (network && !networkObj) {
252 throw new TypeError('Unknown network');
253 }
254
255 if (!bufferVersion.network || (networkObj && networkObj.xpubkey !== bufferVersion.network.xpubkey)) {
256 throw new TypeError('Address has mismatched network type.');
257 }
258
259 if (!bufferVersion.type || (type && type !== bufferVersion.type)) {
260 throw new TypeError('Address has mismatched type.');
261 }
262
263 if (buffer.length > 21) {
264 info.hashBuffer = Bech32.decode(buffer.toString('utf8')).data;
265 } else {
266 info.hashBuffer = buffer.slice(1);
267 }
268 info.network = bufferVersion.network;
269 info.type = bufferVersion.type;
270 return info;
271};
272
273/**
274 * Internal function to transform a {@link PublicKey}
275 *
276 * @param {PublicKey} pubkey - An instance of PublicKey
277 * @param {string} type - Either 'pubkeyhash', 'witnesspubkeyhash', 'scripthash', or 'taproot'
278 * @returns {Object} An object with keys: hashBuffer, type
279 * @private
280 */
281Address._transformPublicKey = function(pubkey, network, type) {
282 var info = {};
283 if (!(pubkey instanceof PublicKey)) {
284 throw new TypeError('Address must be an instance of PublicKey.');
285 }
286 if (type && type !== Address.PayToScriptHash && type !== Address.PayToWitnessPublicKeyHash && type !== Address.PayToPublicKeyHash && type !== Address.PayToTaproot) {
287 throw new TypeError('Type must be either pubkeyhash, witnesspubkeyhash, scripthash, or taproot to transform public key.');
288 }
289 if (!pubkey.compressed && (type === Address.PayToScriptHash || type === Address.PayToWitnessPublicKeyHash)) {
290 throw new TypeError('Witness addresses must use compressed public keys.');
291 }
292 if (type === Address.PayToScriptHash) {
293 info.hashBuffer = Hash.sha256ripemd160(Script.buildWitnessV0Out(pubkey).toBuffer());
294 } else if (type === Address.PayToTaproot) {
295 info.hashBuffer = Hash.sha256ripemd160(Script.buildWitnessV1Out(pubkey).toBuffer());
296 } else {
297 info.hashBuffer = Hash.sha256ripemd160(pubkey.toBuffer());
298 }
299 info.type = type || Address.PayToPublicKeyHash;
300 return info;
301};
302
303/**
304 * Internal function to transform a {@link Script} into a `info` object.
305 *
306 * @param {Script} script - An instance of Script
307 * @returns {Object} An object with keys: hashBuffer, type
308 * @private
309 */
310Address._transformScript = function(script, network) {
311 $.checkArgument(script instanceof Script, 'script must be a Script instance');
312 var info = script.getAddressInfo(network);
313 if (!info) {
314 throw new errors.Script.CantDeriveAddress(script);
315 }
316 return info;
317};
318
319/**
320 * Creates a P2SH address from a set of public keys and a threshold.
321 *
322 * The addresses will be sorted lexicographically, as that is the trend in bitcoin.
323 * To create an address from unsorted public keys, use the {@link Script#buildMultisigOut}
324 * interface.
325 *
326 * @param {Array} publicKeys - a set of public keys to create an address
327 * @param {number} threshold - the number of signatures needed to release the funds
328 * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
329 * @param {boolean=} nestedWitness - if the address uses a nested p2sh witness
330 * @param {string} type - Either 'scripthash' or 'witnessscripthash'. If nestedWitness is set, then this is ignored
331 * @return {Address}
332 */
333Address.createMultisig = function(publicKeys, threshold, network, nestedWitness, type) {
334 network = network || publicKeys[0].network || Networks.defaultNetwork;
335 if (type && type !== Address.PayToScriptHash && type !== Address.PayToWitnessScriptHash) {
336 throw new TypeError('Type must be either scripthash or witnessscripthash to create multisig.');
337 }
338 if (nestedWitness || type === Address.PayToWitnessScriptHash) {
339 publicKeys = _.map(publicKeys, PublicKey);
340 for (var i = 0; i < publicKeys.length; i++) {
341 if (!publicKeys[i].compressed) {
342 throw new TypeError('Witness addresses must use compressed public keys.');
343 }
344 }
345 }
346 var redeemScript = Script.buildMultisigOut(publicKeys, threshold);
347 if (nestedWitness) {
348 return Address.payingTo(Script.buildWitnessMultisigOutFromScript(redeemScript), network);
349 }
350 return Address.payingTo(redeemScript, network, type);
351};
352
353/**
354 * Internal function to transform a bitcoin address string
355 *
356 * @param {string} data
357 * @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet'
358 * @param {string=} type - The type: 'pubkeyhash', 'scripthash', 'witnesspubkeyhash', or 'witnessscripthash'
359 * @returns {Object} An object with keys: hashBuffer, network and type
360 * @private
361 */
362Address._transformString = function(data, network, type) {
363 if (typeof(data) !== 'string') {
364 throw new TypeError('data parameter supplied is not a string.');
365 }
366
367 if(data.length > 100) {
368 throw new TypeError('address string is too long');
369 }
370
371 if (network && !Networks.get(network)) {
372 throw new TypeError('Unknown network');
373 }
374
375 data = data.trim();
376
377 try {
378 var info = Address._transformBuffer(Buffer.from(data, 'utf8'), network, type);
379 return info;
380 } catch (e) {
381 if (type === Address.PayToWitnessPublicKeyHash || type === Address.PayToWitnessScriptHash || type === Address.PayToTaproot) {
382 throw e;
383 }
384 }
385
386 var addressBuffer = Base58Check.decode(data);
387 var info = Address._transformBuffer(addressBuffer, network, type);
388 return info;
389};
390
391/**
392 * Instantiate an address from a PublicKey instance
393 *
394 * @param {PublicKey} data
395 * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
396 * @param {string} type - Either 'pubkeyhash', 'witnesspubkeyhash', or 'scripthash'
397 * @returns {Address} A new valid and frozen instance of an Address
398 */
399Address.fromPublicKey = function(data, network, type) {
400 var info = Address._transformPublicKey(data, network, type);
401 network = network || Networks.defaultNetwork;
402 return new Address(info.hashBuffer, network, info.type);
403};
404
405/**
406 * Instantiate an address from a ripemd160 public key hash
407 *
408 * @param {Buffer} hash - An instance of buffer of the hash
409 * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
410 * @returns {Address} A new valid and frozen instance of an Address
411 */
412Address.fromPublicKeyHash = function(hash, network) {
413 var info = Address._transformHash(hash);
414 return new Address(info.hashBuffer, network, Address.PayToPublicKeyHash);
415};
416
417/**
418 * Instantiate an address from a ripemd160 script hash
419 *
420 * @param {Buffer} hash - An instance of buffer of the hash
421 * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
422 * @param {string} type - Either 'scripthash' or 'witnessscripthash'
423 * @returns {Address} A new valid and frozen instance of an Address
424 */
425Address.fromScriptHash = function(hash, network, type) {
426 $.checkArgument(hash, 'hash parameter is required');
427 var info = Address._transformHash(hash);
428 if (type === Address.PayToWitnessScriptHash && hash.length !== 32) {
429 throw new TypeError('Address hashbuffer must be exactly 32 bytes for v0 witness script hash.');
430 }
431 var type = type || Address.PayToScriptHash;
432 return new Address(info.hashBuffer, network, type);
433};
434
435/**
436 * Builds a p2sh address paying to script. This will hash the script and
437 * use that to create the address.
438 * If you want to extract an address associated with a script instead,
439 * see {{Address#fromScript}}
440 *
441 * @param {Script} script - An instance of Script
442 * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
443 * @param {string} type - Either 'scripthash' or 'witnessscripthash'
444 * @returns {Address} A new valid and frozen instance of an Address
445 */
446Address.payingTo = function(script, network, type) {
447 $.checkArgument(script, 'script is required');
448 $.checkArgument(script instanceof Script, 'script must be instance of Script');
449 var hash;
450 if (type === Address.PayToWitnessScriptHash) {
451 hash = Hash.sha256(script.toBuffer());
452 } else {
453 hash = Hash.sha256ripemd160(script.toBuffer());
454 }
455 var type = type || Address.PayToScriptHash;
456 return Address.fromScriptHash(hash, network, type);
457};
458
459/**
460 * Extract address from a Script. The script must be of one
461 * of the following types: p2pkh input, p2pkh output, p2sh input
462 * or p2sh output.
463 * This will analyze the script and extract address information from it.
464 * If you want to transform any script to a p2sh Address paying
465 * to that script's hash instead, use {{Address#payingTo}}
466 *
467 * @param {Script} script - An instance of Script
468 * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
469 * @returns {Address} A new valid and frozen instance of an Address
470 */
471Address.fromScript = function(script, network) {
472 $.checkArgument(script instanceof Script, 'script must be a Script instance');
473 var info = Address._transformScript(script, network);
474 return new Address(info.hashBuffer, network, info.type);
475};
476
477/**
478 * Instantiate an address from a buffer of the address
479 *
480 * @param {Buffer} buffer - An instance of buffer of the address
481 * @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet'
482 * @param {string=} type - The type of address: 'script' or 'pubkey'
483 * @returns {Address} A new valid and frozen instance of an Address
484 */
485Address.fromBuffer = function(buffer, network, type) {
486 var info = Address._transformBuffer(buffer, network, type);
487 return new Address(info.hashBuffer, info.network, info.type);
488};
489
490/**
491 * Instantiate an address from an address string
492 *
493 * @param {string} str - An string of the bitcoin address
494 * @param {String|Network=} network - either a Network instance, 'livenet', or 'testnet'
495 * @param {string=} type - The type of address: 'script' or 'pubkey'
496 * @returns {Address} A new valid and frozen instance of an Address
497 */
498Address.fromString = function(str, network, type) {
499 var info = Address._transformString(str, network, type);
500 return new Address(info.hashBuffer, info.network, info.type);
501};
502
503/**
504 * Instantiate an address from an Object
505 *
506 * @param {string} json - An JSON string or Object with keys: hash, network and type
507 * @returns {Address} A new valid instance of an Address
508 */
509Address.fromObject = function fromObject(obj) {
510 $.checkState(
511 JSUtil.isHexa(obj.hash),
512 'Unexpected hash property, "' + obj.hash + '", expected to be hex.'
513 );
514 var hashBuffer = Buffer.from(obj.hash, 'hex');
515 return new Address(hashBuffer, obj.network, obj.type);
516};
517
518/**
519 * Will return a validation error if exists
520 *
521 * @example
522 * ```javascript
523 * // a network mismatch error
524 * var error = Address.getValidationError('15vkcKf7gB23wLAnZLmbVuMiiVDc1Nm4a2', 'testnet');
525 * ```
526 *
527 * @param {string} data - The encoded data
528 * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
529 * @param {string} type - The type of address: 'script' or 'pubkey'
530 * @returns {null|Error} The corresponding error message
531 */
532Address.getValidationError = function(data, network, type) {
533 var error;
534 try {
535 /* jshint nonew: false */
536 new Address(data, network, type);
537 } catch (e) {
538 error = e;
539 }
540 return error;
541};
542
543/**
544 * Will return a boolean if an address is valid
545 *
546 * @example
547 * ```javascript
548 * assert(Address.isValid('15vkcKf7gB23wLAnZLmbVuMiiVDc1Nm4a2', 'livenet'));
549 * ```
550 *
551 * @param {string} data - The encoded data
552 * @param {String|Network} network - either a Network instance, 'livenet', or 'testnet'
553 * @param {string} type - The type of address: 'script' or 'pubkey'
554 * @returns {boolean} The corresponding error message
555 */
556Address.isValid = function(data, network, type) {
557 return !Address.getValidationError(data, network, type);
558};
559
560/**
561 * Returns true if an address is of pay to public key hash type
562 * @return boolean
563 */
564Address.prototype.isPayToPublicKeyHash = function() {
565 return this.type === Address.PayToPublicKeyHash;
566};
567
568/**
569 * Returns true if an address is of pay to script hash type
570 * @return boolean
571 */
572Address.prototype.isPayToScriptHash = function() {
573 return this.type === Address.PayToScriptHash;
574};
575
576/**
577 * Returns true if an address is of pay to witness public key hash type
578 * @return boolean
579 */
580Address.prototype.isPayToWitnessPublicKeyHash = function() {
581 return this.type === Address.PayToWitnessPublicKeyHash;
582};
583
584/**
585 * Returns true if an address is of pay to witness script hash type
586 * @return boolean
587 */
588Address.prototype.isPayToWitnessScriptHash = function() {
589 return this.type === Address.PayToWitnessScriptHash;
590};
591
592/**
593 * Returns true if an address is of pay to Taproot script hash type
594 * @returns {boolean}
595 */
596Address.prototype.isPayToTaproot = function() {
597 return this.type === Address.PayToTaproot;
598}
599
600/**
601 * Will return a buffer representation of the address
602 *
603 * @returns {Buffer} Bitcoin address buffer
604 */
605Address.prototype.toBuffer = function() {
606 if (this.isPayToWitnessPublicKeyHash() || this.isPayToWitnessScriptHash()) {
607 return Buffer.from(this.toString(), 'utf8')
608 }
609 var version = Buffer.from([this.network[this.type]]);
610 return Buffer.concat([version, this.hashBuffer]);
611};
612
613/**
614 * @returns {Object} A plain object with the address information
615 */
616Address.prototype.toObject = Address.prototype.toJSON = function toObject() {
617 return {
618 hash: this.hashBuffer.toString('hex'),
619 type: this.type,
620 network: this.network.toString()
621 };
622};
623
624/**
625 * Will return a the string representation of the address
626 *
627 * @returns {string} Bitcoin address
628 */
629Address.prototype.toString = function() {
630 if (this.isPayToWitnessPublicKeyHash() || this.isPayToWitnessScriptHash() || this.isPayToTaproot()) {
631 let prefix = this.network.bech32prefix;
632 let version = 0;
633 let encoding = Bech32.encodings.BECH32;
634 if (this.isPayToTaproot()) {
635 version = 1;
636 encoding = Bech32.encodings.BECH32M;
637 }
638 return Bech32.encode(prefix, version, this.hashBuffer, encoding);
639 }
640 return Base58Check.encode(this.toBuffer());
641};
642
643/**
644 * Will return a string formatted for the console
645 *
646 * @returns {string} Bitcoin address
647 */
648Address.prototype.inspect = function() {
649 return '<Address: ' + this.toString() + ', type: ' + this.type + ', network: ' + this.network + '>';
650};
651
652module.exports = Address;
653
654var Script = require('./script');
655
656}).call(this)}).call(this,require("buffer").Buffer)
657},{"./crypto/hash":8,"./encoding/base58check":13,"./encoding/bech32":14,"./errors":18,"./networks":23,"./publickey":26,"./script":27,"./util/js":46,"./util/preconditions":47,"buffer":132,"lodash":210}],2:[function(require,module,exports){
658(function (Buffer){(function (){
659'use strict';
660
661var _ = require('lodash');
662var BlockHeader = require('./blockheader');
663var BN = require('../crypto/bn');
664var BufferUtil = require('../util/buffer');
665var BufferReader = require('../encoding/bufferreader');
666var BufferWriter = require('../encoding/bufferwriter');
667var Hash = require('../crypto/hash');
668var Transaction = require('../transaction');
669var $ = require('../util/preconditions');
670
671/**
672 * Instantiate a Block from a Buffer, JSON object, or Object with
673 * the properties of the Block
674 *
675 * @param {*} - A Buffer, JSON string, or Object
676 * @returns {Block}
677 * @constructor
678 */
679function Block(arg) {
680 if (!(this instanceof Block)) {
681 return new Block(arg);
682 }
683 _.extend(this, Block._from(arg));
684 return this;
685}
686
687// https://github.com/bitcoin/bitcoin/blob/b5fa132329f0377d787a4a21c1686609c2bfaece/src/primitives/block.h#L14
688Block.MAX_BLOCK_SIZE = 1000000;
689
690/**
691 * @param {*} - A Buffer, JSON string or Object
692 * @returns {Object} - An object representing block data
693 * @throws {TypeError} - If the argument was not recognized
694 * @private
695 */
696Block._from = function _from(arg) {
697 var info = {};
698 if (BufferUtil.isBuffer(arg)) {
699 info = Block._fromBufferReader(BufferReader(arg));
700 } else if (_.isObject(arg)) {
701 info = Block._fromObject(arg);
702 } else {
703 throw new TypeError('Unrecognized argument for Block');
704 }
705 return info;
706};
707
708/**
709 * @param {Object} - A plain JavaScript object
710 * @returns {Object} - An object representing block data
711 * @private
712 */
713Block._fromObject = function _fromObject(data) {
714 var transactions = [];
715 data.transactions.forEach(function(tx) {
716 if (tx instanceof Transaction) {
717 transactions.push(tx);
718 } else {
719 transactions.push(Transaction().fromObject(tx));
720 }
721 });
722 var info = {
723 header: BlockHeader.fromObject(data.header),
724 transactions: transactions
725 };
726 return info;
727};
728
729/**
730 * @param {Object} - A plain JavaScript object
731 * @returns {Block} - An instance of block
732 */
733Block.fromObject = function fromObject(obj) {
734 var info = Block._fromObject(obj);
735 return new Block(info);
736};
737
738/**
739 * @param {BufferReader} - Block data
740 * @returns {Object} - An object representing the block data
741 * @private
742 */
743Block._fromBufferReader = function _fromBufferReader(br) {
744 var info = {};
745 $.checkState(!br.finished(), 'No block data received');
746 info.header = BlockHeader.fromBufferReader(br);
747 var transactions = br.readVarintNum();
748 info.transactions = [];
749 for (var i = 0; i < transactions; i++) {
750 info.transactions.push(Transaction().fromBufferReader(br));
751 }
752 return info;
753};
754
755/**
756 * @param {BufferReader} - A buffer reader of the block
757 * @returns {Block} - An instance of block
758 */
759Block.fromBufferReader = function fromBufferReader(br) {
760 $.checkArgument(br, 'br is required');
761 var info = Block._fromBufferReader(br);
762 return new Block(info);
763};
764
765/**
766 * @param {Buffer} - A buffer of the block
767 * @returns {Block} - An instance of block
768 */
769Block.fromBuffer = function fromBuffer(buf) {
770 return Block.fromBufferReader(new BufferReader(buf));
771};
772
773/**
774 * @param {string} - str - A hex encoded string of the block
775 * @returns {Block} - A hex encoded string of the block
776 */
777Block.fromString = function fromString(str) {
778 var buf = Buffer.from(str, 'hex');
779 return Block.fromBuffer(buf);
780};
781
782/**
783 * @param {Binary} - Raw block binary data or buffer
784 * @returns {Block} - An instance of block
785 */
786Block.fromRawBlock = function fromRawBlock(data) {
787 if (!BufferUtil.isBuffer(data)) {
788 data = Buffer.from(data, 'binary');
789 }
790 var br = BufferReader(data);
791 br.pos = Block.Values.START_OF_BLOCK;
792 var info = Block._fromBufferReader(br);
793 return new Block(info);
794};
795
796/**
797 * @returns {Object} - A plain object with the block properties
798 */
799Block.prototype.toObject = Block.prototype.toJSON = function toObject() {
800 var transactions = [];
801 this.transactions.forEach(function(tx) {
802 transactions.push(tx.toObject());
803 });
804 return {
805 header: this.header.toObject(),
806 transactions: transactions
807 };
808};
809
810/**
811 * @returns {Buffer} - A buffer of the block
812 */
813Block.prototype.toBuffer = function toBuffer() {
814 return this.toBufferWriter().concat();
815};
816
817/**
818 * @returns {string} - A hex encoded string of the block
819 */
820Block.prototype.toString = function toString() {
821 return this.toBuffer().toString('hex');
822};
823
824/**
825 * @param {BufferWriter} - An existing instance of BufferWriter
826 * @returns {BufferWriter} - An instance of BufferWriter representation of the Block
827 */
828Block.prototype.toBufferWriter = function toBufferWriter(bw) {
829 if (!bw) {
830 bw = new BufferWriter();
831 }
832 bw.write(this.header.toBuffer());
833 bw.writeVarintNum(this.transactions.length);
834 for (var i = 0; i < this.transactions.length; i++) {
835 this.transactions[i].toBufferWriter(bw);
836 }
837 return bw;
838};
839
840/**
841 * Will iterate through each transaction and return an array of hashes
842 * @returns {Array} - An array with transaction hashes
843 */
844Block.prototype.getTransactionHashes = function getTransactionHashes() {
845 var hashes = [];
846 if (this.transactions.length === 0) {
847 return [Block.Values.NULL_HASH];
848 }
849 for (var t = 0; t < this.transactions.length; t++) {
850 hashes.push(this.transactions[t]._getHash());
851 }
852 return hashes;
853};
854
855/**
856 * Will build a merkle tree of all the transactions, ultimately arriving at
857 * a single point, the merkle root.
858 * @link https://en.bitcoin.it/wiki/Protocol_specification#Merkle_Trees
859 * @returns {Array} - An array with each level of the tree after the other.
860 */
861Block.prototype.getMerkleTree = function getMerkleTree() {
862
863 var tree = this.getTransactionHashes();
864
865 var j = 0;
866 for (var size = this.transactions.length; size > 1; size = Math.floor((size + 1) / 2)) {
867 for (var i = 0; i < size; i += 2) {
868 var i2 = Math.min(i + 1, size - 1);
869 var buf = Buffer.concat([tree[j + i], tree[j + i2]]);
870 tree.push(Hash.sha256sha256(buf));
871 }
872 j += size;
873 }
874
875 return tree;
876};
877
878/**
879 * Calculates the merkleRoot from the transactions.
880 * @returns {Buffer} - A buffer of the merkle root hash
881 */
882Block.prototype.getMerkleRoot = function getMerkleRoot() {
883 var tree = this.getMerkleTree();
884 return tree[tree.length - 1];
885};
886
887/**
888 * Verifies that the transactions in the block match the header merkle root
889 * @returns {Boolean} - If the merkle roots match
890 */
891Block.prototype.validMerkleRoot = function validMerkleRoot() {
892
893 var h = new BN(this.header.merkleRoot.toString('hex'), 'hex');
894 var c = new BN(this.getMerkleRoot().toString('hex'), 'hex');
895
896 if (h.cmp(c) !== 0) {
897 return false;
898 }
899
900 return true;
901};
902
903/**
904 * @returns {Buffer} - The little endian hash buffer of the header
905 */
906Block.prototype._getHash = function() {
907 return this.header._getHash();
908};
909
910var idProperty = {
911 configurable: false,
912 enumerable: true,
913 /**
914 * @returns {string} - The big endian hash buffer of the header
915 */
916 get: function() {
917 if (!this._id) {
918 this._id = this.header.id;
919 }
920 return this._id;
921 },
922 set: _.noop
923};
924Object.defineProperty(Block.prototype, 'id', idProperty);
925Object.defineProperty(Block.prototype, 'hash', idProperty);
926
927/**
928 * @returns {string} - A string formatted for the console
929 */
930Block.prototype.inspect = function inspect() {
931 return '<Block ' + this.id + '>';
932};
933
934Block.Values = {
935 START_OF_BLOCK: 8, // Start of block in raw block data
936 NULL_HASH: Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex')
937};
938
939module.exports = Block;
940
941}).call(this)}).call(this,require("buffer").Buffer)
942},{"../crypto/bn":6,"../crypto/hash":8,"../encoding/bufferreader":15,"../encoding/bufferwriter":16,"../transaction":30,"../util/buffer":45,"../util/preconditions":47,"./blockheader":3,"buffer":132,"lodash":210}],3:[function(require,module,exports){
943(function (Buffer){(function (){
944'use strict';
945
946var _ = require('lodash');
947var BN = require('../crypto/bn');
948var BufferUtil = require('../util/buffer');
949var BufferReader = require('../encoding/bufferreader');
950var BufferWriter = require('../encoding/bufferwriter');
951var Hash = require('../crypto/hash');
952var JSUtil = require('../util/js');
953var $ = require('../util/preconditions');
954
955var GENESIS_BITS = 0x1d00ffff;
956
957/**
958 * Instantiate a BlockHeader from a Buffer, JSON object, or Object with
959 * the properties of the BlockHeader
960 *
961 * @param {*} - A Buffer, JSON string, or Object
962 * @returns {BlockHeader} - An instance of block header
963 * @constructor
964 */
965var BlockHeader = function BlockHeader(arg) {
966 if (!(this instanceof BlockHeader)) {
967 return new BlockHeader(arg);
968 }
969 var info = BlockHeader._from(arg);
970 this.version = info.version;
971 this.prevHash = info.prevHash;
972 this.merkleRoot = info.merkleRoot;
973 this.time = info.time;
974 this.timestamp = info.time;
975 this.bits = info.bits;
976 this.nonce = info.nonce;
977
978 if (info.hash) {
979 $.checkState(
980 this.hash === info.hash,
981 'Argument object hash property does not match block hash.'
982 );
983 }
984
985 return this;
986};
987
988/**
989 * @param {*} - A Buffer, JSON string or Object
990 * @returns {Object} - An object representing block header data
991 * @throws {TypeError} - If the argument was not recognized
992 * @private
993 */
994BlockHeader._from = function _from(arg) {
995 var info = {};
996 if (BufferUtil.isBuffer(arg)) {
997 info = BlockHeader._fromBufferReader(BufferReader(arg));
998 } else if (_.isObject(arg)) {
999 info = BlockHeader._fromObject(arg);
1000 } else {
1001 throw new TypeError('Unrecognized argument for BlockHeader');
1002 }
1003 return info;
1004};
1005
1006/**
1007 * @param {Object} - A JSON string
1008 * @returns {Object} - An object representing block header data
1009 * @private
1010 */
1011BlockHeader._fromObject = function _fromObject(data) {
1012 $.checkArgument(data, 'data is required');
1013 var prevHash = data.prevHash;
1014 var merkleRoot = data.merkleRoot;
1015 if (_.isString(data.prevHash)) {
1016 prevHash = BufferUtil.reverse(Buffer.from(data.prevHash, 'hex'));
1017 }
1018 if (_.isString(data.merkleRoot)) {
1019 merkleRoot = BufferUtil.reverse(Buffer.from(data.merkleRoot, 'hex'));
1020 }
1021 var info = {
1022 hash: data.hash,
1023 version: data.version,
1024 prevHash: prevHash,
1025 merkleRoot: merkleRoot,
1026 time: data.time,
1027 timestamp: data.time,
1028 bits: data.bits,
1029 nonce: data.nonce
1030 };
1031 return info;
1032};
1033
1034/**
1035 * @param {Object} - A plain JavaScript object
1036 * @returns {BlockHeader} - An instance of block header
1037 */
1038BlockHeader.fromObject = function fromObject(obj) {
1039 var info = BlockHeader._fromObject(obj);
1040 return new BlockHeader(info);
1041};
1042
1043/**
1044 * @param {Binary} - Raw block binary data or buffer
1045 * @returns {BlockHeader} - An instance of block header
1046 */
1047BlockHeader.fromRawBlock = function fromRawBlock(data) {
1048 if (!BufferUtil.isBuffer(data)) {
1049 data = Buffer.from(data, 'binary');
1050 }
1051 var br = BufferReader(data);
1052 br.pos = BlockHeader.Constants.START_OF_HEADER;
1053 var info = BlockHeader._fromBufferReader(br);
1054 return new BlockHeader(info);
1055};
1056
1057/**
1058 * @param {Buffer} - A buffer of the block header
1059 * @returns {BlockHeader} - An instance of block header
1060 */
1061BlockHeader.fromBuffer = function fromBuffer(buf) {
1062 var info = BlockHeader._fromBufferReader(BufferReader(buf));
1063 return new BlockHeader(info);
1064};
1065
1066/**
1067 * @param {string} - A hex encoded buffer of the block header
1068 * @returns {BlockHeader} - An instance of block header
1069 */
1070BlockHeader.fromString = function fromString(str) {
1071 var buf = Buffer.from(str, 'hex');
1072 return BlockHeader.fromBuffer(buf);
1073};
1074
1075/**
1076 * @param {BufferReader} - A BufferReader of the block header
1077 * @returns {Object} - An object representing block header data
1078 * @private
1079 */
1080BlockHeader._fromBufferReader = function _fromBufferReader(br) {
1081 var info = {};
1082 info.version = br.readInt32LE();
1083 info.prevHash = br.read(32);
1084 info.merkleRoot = br.read(32);
1085 info.time = br.readUInt32LE();
1086 info.bits = br.readUInt32LE();
1087 info.nonce = br.readUInt32LE();
1088 return info;
1089};
1090
1091/**
1092 * @param {BufferReader} - A BufferReader of the block header
1093 * @returns {BlockHeader} - An instance of block header
1094 */
1095BlockHeader.fromBufferReader = function fromBufferReader(br) {
1096 var info = BlockHeader._fromBufferReader(br);
1097 return new BlockHeader(info);
1098};
1099
1100/**
1101 * @returns {Object} - A plain object of the BlockHeader
1102 */
1103BlockHeader.prototype.toObject = BlockHeader.prototype.toJSON = function toObject() {
1104 return {
1105 hash: this.hash,
1106 version: this.version,
1107 prevHash: BufferUtil.reverse(this.prevHash).toString('hex'),
1108 merkleRoot: BufferUtil.reverse(this.merkleRoot).toString('hex'),
1109 time: this.time,
1110 bits: this.bits,
1111 nonce: this.nonce
1112 };
1113};
1114
1115/**
1116 * @returns {Buffer} - A Buffer of the BlockHeader
1117 */
1118BlockHeader.prototype.toBuffer = function toBuffer() {
1119 return this.toBufferWriter().concat();
1120};
1121
1122/**
1123 * @returns {string} - A hex encoded string of the BlockHeader
1124 */
1125BlockHeader.prototype.toString = function toString() {
1126 return this.toBuffer().toString('hex');
1127};
1128
1129/**
1130 * @param {BufferWriter} - An existing instance BufferWriter
1131 * @returns {BufferWriter} - An instance of BufferWriter representation of the BlockHeader
1132 */
1133BlockHeader.prototype.toBufferWriter = function toBufferWriter(bw) {
1134 if (!bw) {
1135 bw = new BufferWriter();
1136 }
1137 bw.writeInt32LE(this.version);
1138 bw.write(this.prevHash);
1139 bw.write(this.merkleRoot);
1140 bw.writeUInt32LE(this.time);
1141 bw.writeUInt32LE(this.bits);
1142 bw.writeUInt32LE(this.nonce);
1143 return bw;
1144};
1145
1146/**
1147 * Returns the target difficulty for this block
1148 * @param {Number} bits
1149 * @returns {BN} An instance of BN with the decoded difficulty bits
1150 */
1151BlockHeader.prototype.getTargetDifficulty = function getTargetDifficulty(bits) {
1152 bits = bits || this.bits;
1153
1154 var target = new BN(bits & 0xffffff);
1155 var mov = 8 * ((bits >>> 24) - 3);
1156 while (mov-- > 0) {
1157 target = target.mul(new BN(2));
1158 }
1159 return target;
1160};
1161
1162/**
1163 * @link https://en.bitcoin.it/wiki/Difficulty
1164 * @return {Number}
1165 */
1166BlockHeader.prototype.getDifficulty = function getDifficulty() {
1167 var difficulty1TargetBN = this.getTargetDifficulty(GENESIS_BITS).mul(new BN(Math.pow(10, 8)));
1168 var currentTargetBN = this.getTargetDifficulty();
1169
1170 var difficultyString = difficulty1TargetBN.div(currentTargetBN).toString(10);
1171 var decimalPos = difficultyString.length - 8;
1172 difficultyString = difficultyString.slice(0, decimalPos) + '.' + difficultyString.slice(decimalPos);
1173
1174 return parseFloat(difficultyString);
1175};
1176
1177/**
1178 * @returns {Buffer} - The little endian hash buffer of the header
1179 */
1180BlockHeader.prototype._getHash = function hash() {
1181 var buf = this.toBuffer();
1182 return Hash.sha256sha256(buf);
1183};
1184
1185var idProperty = {
1186 configurable: false,
1187 enumerable: true,
1188 /**
1189 * @returns {string} - The big endian hash buffer of the header
1190 */
1191 get: function() {
1192 if (!this._id) {
1193 this._id = BufferReader(this._getHash()).readReverse().toString('hex');
1194 }
1195 return this._id;
1196 },
1197 set: _.noop
1198};
1199Object.defineProperty(BlockHeader.prototype, 'id', idProperty);
1200Object.defineProperty(BlockHeader.prototype, 'hash', idProperty);
1201
1202/**
1203 * @returns {Boolean} - If timestamp is not too far in the future
1204 */
1205BlockHeader.prototype.validTimestamp = function validTimestamp() {
1206 var currentTime = Math.round(new Date().getTime() / 1000);
1207 if (this.time > currentTime + BlockHeader.Constants.MAX_TIME_OFFSET) {
1208 return false;
1209 }
1210 return true;
1211};
1212
1213/**
1214 * @returns {Boolean} - If the proof-of-work hash satisfies the target difficulty
1215 */
1216BlockHeader.prototype.validProofOfWork = function validProofOfWork() {
1217 var pow = new BN(this.id, 'hex');
1218 var target = this.getTargetDifficulty();
1219
1220 if (pow.cmp(target) > 0) {
1221 return false;
1222 }
1223 return true;
1224};
1225
1226/**
1227 * @returns {string} - A string formatted for the console
1228 */
1229BlockHeader.prototype.inspect = function inspect() {
1230 return '<BlockHeader ' + this.id + '>';
1231};
1232
1233BlockHeader.Constants = {
1234 START_OF_HEADER: 8, // Start buffer position in raw block data
1235 MAX_TIME_OFFSET: 2 * 60 * 60, // The max a timestamp can be in the future
1236 LARGEST_HASH: new BN('10000000000000000000000000000000000000000000000000000000000000000', 'hex')
1237};
1238
1239module.exports = BlockHeader;
1240
1241}).call(this)}).call(this,require("buffer").Buffer)
1242},{"../crypto/bn":6,"../crypto/hash":8,"../encoding/bufferreader":15,"../encoding/bufferwriter":16,"../util/buffer":45,"../util/js":46,"../util/preconditions":47,"buffer":132,"lodash":210}],4:[function(require,module,exports){
1243module.exports = require('./block');
1244
1245module.exports.BlockHeader = require('./blockheader');
1246module.exports.MerkleBlock = require('./merkleblock');
1247
1248},{"./block":2,"./blockheader":3,"./merkleblock":5}],5:[function(require,module,exports){
1249(function (Buffer){(function (){
1250'use strict';
1251
1252var _ = require('lodash');
1253var BlockHeader = require('./blockheader');
1254var BufferUtil = require('../util/buffer');
1255var BufferReader = require('../encoding/bufferreader');
1256var BufferWriter = require('../encoding/bufferwriter');
1257var Hash = require('../crypto/hash');
1258var JSUtil = require('../util/js');
1259var Transaction = require('../transaction');
1260var errors = require('../errors');
1261var $ = require('../util/preconditions');
1262
1263/**
1264 * Instantiate a MerkleBlock from a Buffer, JSON object, or Object with
1265 * the properties of the Block
1266 *
1267 * @param {*} - A Buffer, JSON string, or Object representing a MerkleBlock
1268 * @returns {MerkleBlock}
1269 * @constructor
1270 */
1271function MerkleBlock(arg) {
1272 /* jshint maxstatements: 18 */
1273
1274 if (!(this instanceof MerkleBlock)) {
1275 return new MerkleBlock(arg);
1276 }
1277
1278 var info = {};
1279 if (BufferUtil.isBuffer(arg)) {
1280 info = MerkleBlock._fromBufferReader(BufferReader(arg));
1281 } else if (_.isObject(arg)) {
1282 var header;
1283 if(arg.header instanceof BlockHeader) {
1284 header = arg.header;
1285 } else {
1286 header = BlockHeader.fromObject(arg.header);
1287 }
1288 info = {
1289 /**
1290 * @name MerkleBlock#header
1291 * @type {BlockHeader}
1292 */
1293 header: header,
1294 /**
1295 * @name MerkleBlock#numTransactions
1296 * @type {Number}
1297 */
1298 numTransactions: arg.numTransactions,
1299 /**
1300 * @name MerkleBlock#hashes
1301 * @type {String[]}
1302 */
1303 hashes: arg.hashes,
1304 /**
1305 * @name MerkleBlock#flags
1306 * @type {Number[]}
1307 */
1308 flags: arg.flags
1309 };
1310 } else {
1311 throw new TypeError('Unrecognized argument for MerkleBlock');
1312 }
1313 _.extend(this,info);
1314 this._flagBitsUsed = 0;
1315 this._hashesUsed = 0;
1316
1317 return this;
1318}
1319
1320/**
1321 * @param {Buffer} - MerkleBlock data in a Buffer object
1322 * @returns {MerkleBlock} - A MerkleBlock object
1323 */
1324MerkleBlock.fromBuffer = function fromBuffer(buf) {
1325 return MerkleBlock.fromBufferReader(BufferReader(buf));
1326};
1327
1328/**
1329 * @param {BufferReader} - MerkleBlock data in a BufferReader object
1330 * @returns {MerkleBlock} - A MerkleBlock object
1331 */
1332MerkleBlock.fromBufferReader = function fromBufferReader(br) {
1333 return new MerkleBlock(MerkleBlock._fromBufferReader(br));
1334};
1335
1336/**
1337 * @returns {Buffer} - A buffer of the block
1338 */
1339MerkleBlock.prototype.toBuffer = function toBuffer() {
1340 return this.toBufferWriter().concat();
1341};
1342
1343/**
1344 * @param {BufferWriter} - An existing instance of BufferWriter
1345 * @returns {BufferWriter} - An instance of BufferWriter representation of the MerkleBlock
1346 */
1347MerkleBlock.prototype.toBufferWriter = function toBufferWriter(bw) {
1348 if (!bw) {
1349 bw = new BufferWriter();
1350 }
1351 bw.write(this.header.toBuffer());
1352 bw.writeUInt32LE(this.numTransactions);
1353 bw.writeVarintNum(this.hashes.length);
1354 for (var i = 0; i < this.hashes.length; i++) {
1355 bw.write(Buffer.from(this.hashes[i], 'hex'));
1356 }
1357 bw.writeVarintNum(this.flags.length);
1358 for (i = 0; i < this.flags.length; i++) {
1359 bw.writeUInt8(this.flags[i]);
1360 }
1361 return bw;
1362};
1363
1364/**
1365 * @returns {Object} - A plain object with the MerkleBlock properties
1366 */
1367MerkleBlock.prototype.toObject = MerkleBlock.prototype.toJSON = function toObject() {
1368 return {
1369 header: this.header.toObject(),
1370 numTransactions: this.numTransactions,
1371 hashes: this.hashes,
1372 flags: this.flags
1373 };
1374};
1375
1376/**
1377 * Verify that the MerkleBlock is valid
1378 * @returns {Boolean} - True/False whether this MerkleBlock is Valid
1379 */
1380MerkleBlock.prototype.validMerkleTree = function validMerkleTree() {
1381 $.checkState(_.isArray(this.flags), 'MerkleBlock flags is not an array');
1382 $.checkState(_.isArray(this.hashes), 'MerkleBlock hashes is not an array');
1383
1384 // Can't have more hashes than numTransactions
1385 if(this.hashes.length > this.numTransactions) {
1386 return false;
1387 }
1388
1389 // Can't have more flag bits than num hashes
1390 if(this.flags.length * 8 < this.hashes.length) {
1391 return false;
1392 }
1393
1394 var height = this._calcTreeHeight();
1395 var opts = { hashesUsed: 0, flagBitsUsed: 0 };
1396 var root = this._traverseMerkleTree(height, 0, opts);
1397 if(opts.hashesUsed !== this.hashes.length) {
1398 return false;
1399 }
1400 return BufferUtil.equals(root, this.header.merkleRoot);
1401};
1402
1403/**
1404 * Return a list of all the txs hash that match the filter
1405 * @returns {Array} - txs hash that match the filter
1406 */
1407MerkleBlock.prototype.filterdTxsHash = function filterdTxsHash() {
1408 $.checkState(_.isArray(this.flags), 'MerkleBlock flags is not an array');
1409 $.checkState(_.isArray(this.hashes), 'MerkleBlock hashes is not an array');
1410
1411 // Can't have more hashes than numTransactions
1412 if(this.hashes.length > this.numTransactions) {
1413 throw new errors.MerkleBlock.InvalidMerkleTree();
1414 }
1415
1416 // Can't have more flag bits than num hashes
1417 if(this.flags.length * 8 < this.hashes.length) {
1418 throw new errors.MerkleBlock.InvalidMerkleTree();
1419 }
1420
1421 // If there is only one hash the filter do not match any txs in the block
1422 if(this.hashes.length === 1) {
1423 return [];
1424 };
1425
1426 var height = this._calcTreeHeight();
1427 var opts = { hashesUsed: 0, flagBitsUsed: 0 };
1428 var txs = this._traverseMerkleTree(height, 0, opts, true);
1429 if(opts.hashesUsed !== this.hashes.length) {
1430 throw new errors.MerkleBlock.InvalidMerkleTree();
1431 }
1432 return txs;
1433};
1434
1435/**
1436 * Traverse a the tree in this MerkleBlock, validating it along the way
1437 * Modeled after Bitcoin Core merkleblock.cpp TraverseAndExtract()
1438 * @param {Number} - depth - Current height
1439 * @param {Number} - pos - Current position in the tree
1440 * @param {Object} - opts - Object with values that need to be mutated throughout the traversal
1441 * @param {Boolean} - checkForTxs - if true return opts.txs else return the Merkle Hash
1442 * @param {Number} - opts.flagBitsUsed - Number of flag bits used, should start at 0
1443 * @param {Number} - opts.hashesUsed - Number of hashes used, should start at 0
1444 * @param {Array} - opts.txs - Will finish populated by transactions found during traversal that match the filter
1445 * @returns {Buffer|null} - Buffer containing the Merkle Hash for that height
1446 * @returns {Array} - transactions found during traversal that match the filter
1447 * @private
1448 */
1449MerkleBlock.prototype._traverseMerkleTree = function traverseMerkleTree(depth, pos, opts, checkForTxs) {
1450 /* jshint maxcomplexity: 12*/
1451 /* jshint maxstatements: 20 */
1452
1453 opts = opts || {};
1454 opts.txs = opts.txs || [];
1455 opts.flagBitsUsed = opts.flagBitsUsed || 0;
1456 opts.hashesUsed = opts.hashesUsed || 0;
1457 var checkForTxs = checkForTxs || false;
1458
1459 if(opts.flagBitsUsed > this.flags.length * 8) {
1460 return null;
1461 }
1462 var isParentOfMatch = (this.flags[opts.flagBitsUsed >> 3] >>> (opts.flagBitsUsed++ & 7)) & 1;
1463 if(depth === 0 || !isParentOfMatch) {
1464 if(opts.hashesUsed >= this.hashes.length) {
1465 return null;
1466 }
1467 var hash = this.hashes[opts.hashesUsed++];
1468 if(depth === 0 && isParentOfMatch) {
1469 opts.txs.push(hash);
1470 }
1471 return Buffer.from(hash, 'hex');
1472 } else {
1473 var left = this._traverseMerkleTree(depth-1, pos*2, opts);
1474 var right = left;
1475 if(pos*2+1 < this._calcTreeWidth(depth-1)) {
1476 right = this._traverseMerkleTree(depth-1, pos*2+1, opts);
1477 }
1478 if (checkForTxs){
1479 return opts.txs;
1480 } else {
1481 return Hash.sha256sha256(new Buffer.concat([left, right]));
1482 };
1483 }
1484};
1485
1486/** Calculates the width of a merkle tree at a given height.
1487 * Modeled after Bitcoin Core merkleblock.h CalcTreeWidth()
1488 * @param {Number} - Height at which we want the tree width
1489 * @returns {Number} - Width of the tree at a given height
1490 * @private
1491 */
1492MerkleBlock.prototype._calcTreeWidth = function calcTreeWidth(height) {
1493 return (this.numTransactions + (1 << height) - 1) >> height;
1494};
1495
1496/** Calculates the height of the merkle tree in this MerkleBlock
1497 * @param {Number} - Height at which we want the tree width
1498 * @returns {Number} - Height of the merkle tree in this MerkleBlock
1499 * @private
1500 */
1501MerkleBlock.prototype._calcTreeHeight = function calcTreeHeight() {
1502 var height = 0;
1503 while (this._calcTreeWidth(height) > 1) {
1504 height++;
1505 }
1506 return height;
1507};
1508
1509/**
1510 * @param {Transaction|String} - Transaction or Transaction ID Hash
1511 * @returns {Boolean} - return true/false if this MerkleBlock has the TX or not
1512 * @private
1513 */
1514MerkleBlock.prototype.hasTransaction = function hasTransaction(tx) {
1515 $.checkArgument(!_.isUndefined(tx), 'tx cannot be undefined');
1516 $.checkArgument(tx instanceof Transaction || typeof tx === 'string',
1517 'Invalid tx given, tx must be a "string" or "Transaction"');
1518
1519 var hash = tx;
1520 if(tx instanceof Transaction) {
1521 // We need to reverse the id hash for the lookup
1522 hash = BufferUtil.reverse(Buffer.from(tx.id, 'hex')).toString('hex');
1523 }
1524
1525 var txs = [];
1526 var height = this._calcTreeHeight();
1527 this._traverseMerkleTree(height, 0, { txs: txs });
1528 return txs.indexOf(hash) !== -1;
1529};
1530
1531/**
1532 * @param {Buffer} - MerkleBlock data
1533 * @returns {Object} - An Object representing merkleblock data
1534 * @private
1535 */
1536MerkleBlock._fromBufferReader = function _fromBufferReader(br) {
1537 $.checkState(!br.finished(), 'No merkleblock data received');
1538 var info = {};
1539 info.header = BlockHeader.fromBufferReader(br);
1540 info.numTransactions = br.readUInt32LE();
1541 var numHashes = br.readVarintNum();
1542 info.hashes = [];
1543 for (var i = 0; i < numHashes; i++) {
1544 info.hashes.push(br.read(32).toString('hex'));
1545 }
1546 var numFlags = br.readVarintNum();
1547 info.flags = [];
1548 for (i = 0; i < numFlags; i++) {
1549 info.flags.push(br.readUInt8());
1550 }
1551 return info;
1552};
1553
1554/**
1555 * @param {Object} - A plain JavaScript object
1556 * @returns {Block} - An instance of block
1557 */
1558MerkleBlock.fromObject = function fromObject(obj) {
1559 return new MerkleBlock(obj);
1560};
1561
1562module.exports = MerkleBlock;
1563
1564}).call(this)}).call(this,require("buffer").Buffer)
1565},{"../crypto/hash":8,"../encoding/bufferreader":15,"../encoding/bufferwriter":16,"../errors":18,"../transaction":30,"../util/buffer":45,"../util/js":46,"../util/preconditions":47,"./blockheader":3,"buffer":132,"lodash":210}],6:[function(require,module,exports){
1566(function (Buffer){(function (){
1567'use strict';
1568
1569var BN = require('bn.js');
1570var $ = require('../util/preconditions');
1571var _ = require('lodash');
1572
1573var reversebuf = function(buf) {
1574 var buf2 = Buffer.alloc(buf.length);
1575 for (var i = 0; i < buf.length; i++) {
1576 buf2[i] = buf[buf.length - 1 - i];
1577 }
1578 return buf2;
1579};
1580
1581BN.Zero = new BN(0);
1582BN.One = new BN(1);
1583BN.Minus1 = new BN(-1);
1584
1585BN.fromNumber = function(n) {
1586 $.checkArgument(_.isNumber(n));
1587 return new BN(n);
1588};
1589
1590BN.fromString = function(str, base) {
1591 $.checkArgument(_.isString(str));
1592 return new BN(str, base);
1593};
1594
1595BN.fromBuffer = function(buf, opts) {
1596 if (typeof opts !== 'undefined' && opts.endian === 'little') {
1597 buf = reversebuf(buf);
1598 }
1599 var hex = buf.toString('hex');
1600 var bn = new BN(hex, 16);
1601 return bn;
1602};
1603
1604/**
1605 * Instantiate a BigNumber from a "signed magnitude buffer"
1606 * (a buffer where the most significant bit represents the sign (0 = positive, -1 = negative))
1607 */
1608BN.fromSM = function(buf, opts) {
1609 var ret;
1610 if (buf.length === 0) {
1611 return BN.fromBuffer(Buffer.from([0]));
1612 }
1613
1614 var endian = 'big';
1615 if (opts) {
1616 endian = opts.endian;
1617 }
1618 if (endian === 'little') {
1619 buf = reversebuf(buf);
1620 }
1621
1622 if (buf[0] & 0x80) {
1623 buf[0] = buf[0] & 0x7f;
1624 ret = BN.fromBuffer(buf);
1625 ret.neg().copy(ret);
1626 } else {
1627 ret = BN.fromBuffer(buf);
1628 }
1629 return ret;
1630};
1631
1632
1633BN.prototype.toNumber = function() {
1634 return parseInt(this.toString(10), 10);
1635};
1636
1637BN.prototype.toBuffer = function(opts) {
1638 var buf, hex;
1639 if (opts && opts.size) {
1640 hex = this.toString(16, 2);
1641 var natlen = hex.length / 2;
1642 buf = Buffer.from(hex, 'hex');
1643
1644 if (natlen === opts.size) {
1645 buf = buf;
1646 } else if (natlen > opts.size) {
1647 buf = BN.trim(buf, natlen);
1648 } else if (natlen < opts.size) {
1649 buf = BN.pad(buf, natlen, opts.size);
1650 }
1651 } else {
1652 hex = this.toString(16, 2);
1653 buf = Buffer.from(hex, 'hex');
1654 }
1655
1656 if (typeof opts !== 'undefined' && opts.endian === 'little') {
1657 buf = reversebuf(buf);
1658 }
1659
1660 return buf;
1661};
1662
1663BN.prototype.toSMBigEndian = function() {
1664 var buf;
1665 if (this.cmp(BN.Zero) === -1) {
1666 buf = this.neg().toBuffer();
1667 if (buf[0] & 0x80) {
1668 buf = Buffer.concat([Buffer.from([0x80]), buf]);
1669 } else {
1670 buf[0] = buf[0] | 0x80;
1671 }
1672 } else {
1673 buf = this.toBuffer();
1674 if (buf[0] & 0x80) {
1675 buf = Buffer.concat([Buffer.from([0x00]), buf]);
1676 }
1677 }
1678
1679 if (buf.length === 1 & buf[0] === 0) {
1680 buf = Buffer.from([]);
1681 }
1682 return buf;
1683};
1684
1685BN.prototype.toSM = function(opts) {
1686 var endian = opts ? opts.endian : 'big';
1687 var buf = this.toSMBigEndian();
1688
1689 if (endian === 'little') {
1690 buf = reversebuf(buf);
1691 }
1692 return buf;
1693};
1694
1695/**
1696 * Create a BN from a "ScriptNum":
1697 * This is analogous to the constructor for CScriptNum in bitcoind. Many ops in
1698 * bitcoind's script interpreter use CScriptNum, which is not really a proper
1699 * bignum. Instead, an error is thrown if trying to input a number bigger than
1700 * 4 bytes. We copy that behavior here. A third argument, `size`, is provided to
1701 * extend the hard limit of 4 bytes, as some usages require more than 4 bytes.
1702 */
1703BN.fromScriptNumBuffer = function(buf, fRequireMinimal, size) {
1704 var nMaxNumSize = size || 4;
1705 $.checkArgument(buf.length <= nMaxNumSize, new Error('script number overflow'));
1706 if (fRequireMinimal && buf.length > 0) {
1707 // Check that the number is encoded with the minimum possible
1708 // number of bytes.
1709 //
1710 // If the most-significant-byte - excluding the sign bit - is zero
1711 // then we're not minimal. Note how this test also rejects the
1712 // negative-zero encoding, 0x80.
1713 if ((buf[buf.length - 1] & 0x7f) === 0) {
1714 // One exception: if there's more than one byte and the most
1715 // significant bit of the second-most-significant-byte is set
1716 // it would conflict with the sign bit. An example of this case
1717 // is +-255, which encode to 0xff00 and 0xff80 respectively.
1718 // (big-endian).
1719 if (buf.length <= 1 || (buf[buf.length - 2] & 0x80) === 0) {
1720 throw new Error('non-minimally encoded script number');
1721 }
1722 }
1723 }
1724 return BN.fromSM(buf, {
1725 endian: 'little'
1726 });
1727};
1728
1729/**
1730 * The corollary to the above, with the notable exception that we do not throw
1731 * an error if the output is larger than four bytes. (Which can happen if
1732 * performing a numerical operation that results in an overflow to more than 4
1733 * bytes).
1734 */
1735BN.prototype.toScriptNumBuffer = function() {
1736 return this.toSM({
1737 endian: 'little'
1738 });
1739};
1740
1741BN.trim = function(buf, natlen) {
1742 return buf.slice(natlen - buf.length, buf.length);
1743};
1744
1745BN.pad = function(buf, natlen, size) {
1746 var rbuf = Buffer.alloc(size);
1747 for (var i = 0; i < buf.length; i++) {
1748 rbuf[rbuf.length - 1 - i] = buf[buf.length - 1 - i];
1749 }
1750 for (i = 0; i < size - natlen; i++) {
1751 rbuf[i] = 0;
1752 }
1753 return rbuf;
1754};
1755
1756module.exports = BN;
1757
1758}).call(this)}).call(this,require("buffer").Buffer)
1759},{"../util/preconditions":47,"bn.js":80,"buffer":132,"lodash":210}],7:[function(require,module,exports){
1760(function (Buffer){(function (){
1761'use strict';
1762
1763var BN = require('./bn');
1764var Point = require('./point');
1765var Signature = require('./signature');
1766var PublicKey = require('../publickey');
1767var Random = require('./random');
1768var Hash = require('./hash');
1769var BufferUtil = require('../util/buffer');
1770var _ = require('lodash');
1771var $ = require('../util/preconditions');
1772
1773var ECDSA = function ECDSA(obj) {
1774 if (!(this instanceof ECDSA)) {
1775 return new ECDSA(obj);
1776 }
1777 if (obj) {
1778 this.set(obj);
1779 }
1780};
1781
1782/* jshint maxcomplexity: 9 */
1783ECDSA.prototype.set = function(obj) {
1784 this.hashbuf = obj.hashbuf || this.hashbuf;
1785 this.endian = obj.endian || this.endian; //the endianness of hashbuf
1786 this.privkey = obj.privkey || this.privkey;
1787 this.pubkey = obj.pubkey || (this.privkey ? this.privkey.publicKey : this.pubkey);
1788 this.sig = obj.sig || this.sig;
1789 this.k = obj.k || this.k;
1790 this.verified = obj.verified || this.verified;
1791 return this;
1792};
1793
1794ECDSA.prototype.privkey2pubkey = function() {
1795 this.pubkey = this.privkey.toPublicKey();
1796};
1797
1798ECDSA.prototype.calci = function() {
1799 for (var i = 0; i < 4; i++) {
1800 this.sig.i = i;
1801 var Qprime;
1802 try {
1803 Qprime = this.toPublicKey();
1804 } catch (e) {
1805 console.error(e);
1806 continue;
1807 }
1808
1809 if (Qprime.point.eq(this.pubkey.point)) {
1810 this.sig.compressed = this.pubkey.compressed;
1811 return this;
1812 }
1813 }
1814
1815 this.sig.i = undefined;
1816 throw new Error('Unable to find valid recovery factor');
1817};
1818
1819ECDSA.fromString = function(str) {
1820 var obj = JSON.parse(str);
1821 return new ECDSA(obj);
1822};
1823
1824ECDSA.prototype.randomK = function() {
1825 var N = Point.getN();
1826 var k;
1827 do {
1828 k = BN.fromBuffer(Random.getRandomBuffer(32));
1829 } while (!(k.lt(N) && k.gt(BN.Zero)));
1830 this.k = k;
1831 return this;
1832};
1833
1834
1835// https://tools.ietf.org/html/rfc6979#section-3.2
1836ECDSA.prototype.deterministicK = function(badrs) {
1837 /* jshint maxstatements: 25 */
1838 // if r or s were invalid when this function was used in signing,
1839 // we do not want to actually compute r, s here for efficiency, so,
1840 // we can increment badrs. explained at end of RFC 6979 section 3.2
1841 if (_.isUndefined(badrs)) {
1842 badrs = 0;
1843 }
1844 var v = Buffer.alloc(32);
1845 v.fill(0x01);
1846 var k = Buffer.alloc(32);
1847 k.fill(0x00);
1848 var x = this.privkey.bn.toBuffer({
1849 size: 32
1850 });
1851 var hashbuf = this.endian === 'little' ? BufferUtil.reverse(this.hashbuf) : this.hashbuf
1852 k = Hash.sha256hmac(Buffer.concat([v, Buffer.from([0x00]), x, hashbuf]), k);
1853 v = Hash.sha256hmac(v, k);
1854 k = Hash.sha256hmac(Buffer.concat([v, Buffer.from([0x01]), x, hashbuf]), k);
1855 v = Hash.sha256hmac(v, k);
1856 v = Hash.sha256hmac(v, k);
1857 var T = BN.fromBuffer(v);
1858 var N = Point.getN();
1859
1860 // also explained in 3.2, we must ensure T is in the proper range (0, N)
1861 for (var i = 0; i < badrs || !(T.lt(N) && T.gt(BN.Zero)); i++) {
1862 k = Hash.sha256hmac(Buffer.concat([v, Buffer.from([0x00])]), k);
1863 v = Hash.sha256hmac(v, k);
1864 v = Hash.sha256hmac(v, k);
1865 T = BN.fromBuffer(v);
1866 }
1867
1868 this.k = T;
1869 return this;
1870};
1871
1872// Information about public key recovery:
1873// https://bitcointalk.org/index.php?topic=6430.0
1874// http://stackoverflow.com/questions/19665491/how-do-i-get-an-ecdsa-public-key-from-just-a-bitcoin-signature-sec1-4-1-6-k
1875ECDSA.prototype.toPublicKey = function() {
1876 /* jshint maxstatements: 25 */
1877 var i = this.sig.i;
1878 $.checkArgument(i === 0 || i === 1 || i === 2 || i === 3, new Error('i must be equal to 0, 1, 2, or 3'));
1879
1880 var e = BN.fromBuffer(this.hashbuf);
1881 var r = this.sig.r;
1882 var s = this.sig.s;
1883
1884 // A set LSB signifies that the y-coordinate is odd
1885 var isYOdd = i & 1;
1886
1887 // The more significant bit specifies whether we should use the
1888 // first or second candidate key.
1889 var isSecondKey = i >> 1;
1890
1891 var n = Point.getN();
1892 var G = Point.getG();
1893
1894 // 1.1 Let x = r + jn
1895 var x = isSecondKey ? r.add(n) : r;
1896 var R = Point.fromX(isYOdd, x);
1897
1898 // 1.4 Check that nR is at infinity
1899 var nR = R.mul(n);
1900
1901 if (!nR.isInfinity()) {
1902 throw new Error('nR is not a valid curve point');
1903 }
1904
1905 // Compute -e from e
1906 var eNeg = e.neg().umod(n);
1907
1908 // 1.6.1 Compute Q = r^-1 (sR - eG)
1909 // Q = r^-1 (sR + -eG)
1910 var rInv = r.invm(n);
1911
1912 //var Q = R.multiplyTwo(s, G, eNeg).mul(rInv);
1913 var Q = R.mul(s).add(G.mul(eNeg)).mul(rInv);
1914
1915 var pubkey = PublicKey.fromPoint(Q, this.sig.compressed);
1916
1917 return pubkey;
1918};
1919
1920ECDSA.prototype.sigError = function() {
1921 /* jshint maxstatements: 25 */
1922 if (!BufferUtil.isBuffer(this.hashbuf) || this.hashbuf.length !== 32) {
1923 return 'hashbuf must be a 32 byte buffer';
1924 }
1925
1926 var r = this.sig.r;
1927 var s = this.sig.s;
1928 if (!(r.gt(BN.Zero) && r.lt(Point.getN())) || !(s.gt(BN.Zero) && s.lt(Point.getN()))) {
1929 return 'r and s not in range';
1930 }
1931
1932 var e = BN.fromBuffer(this.hashbuf, this.endian ? {
1933 endian: this.endian
1934 } : undefined);
1935 var n = Point.getN();
1936 var sinv = s.invm(n);
1937 var u1 = sinv.mul(e).umod(n);
1938 var u2 = sinv.mul(r).umod(n);
1939
1940 var p = Point.getG().mulAdd(u1, this.pubkey.point, u2);
1941 if (p.isInfinity()) {
1942 return 'p is infinity';
1943 }
1944
1945 if (p.getX().umod(n).cmp(r) !== 0) {
1946 return 'Invalid signature';
1947 } else {
1948 return false;
1949 }
1950};
1951
1952ECDSA.toLowS = function(s) {
1953 //enforce low s
1954 //see BIP 62, "low S values in signatures"
1955 if (s.gt(BN.fromBuffer(Buffer.from('7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0', 'hex')))) {
1956 s = Point.getN().sub(s);
1957 }
1958 return s;
1959};
1960
1961ECDSA.prototype._findSignature = function(d, e) {
1962 var N = Point.getN();
1963 var G = Point.getG();
1964 // try different values of k until r, s are valid
1965 var badrs = 0;
1966 var k, Q, r, s;
1967 do {
1968 if (!this.k || badrs > 0) {
1969 this.deterministicK(badrs);
1970 }
1971 badrs++;
1972 k = this.k;
1973 Q = G.mul(k);
1974 r = Q.x.umod(N);
1975 s = k.invm(N).mul(e.add(d.mul(r))).umod(N);
1976 } while (r.cmp(BN.Zero) <= 0 || s.cmp(BN.Zero) <= 0);
1977
1978 s = ECDSA.toLowS(s);
1979 return {
1980 s: s,
1981 r: r
1982 };
1983
1984};
1985
1986ECDSA.prototype.sign = function() {
1987 var hashbuf = this.hashbuf;
1988 var privkey = this.privkey;
1989 var d = privkey.bn;
1990
1991 $.checkState(hashbuf && privkey && d, new Error('invalid parameters'));
1992 $.checkState(BufferUtil.isBuffer(hashbuf) && hashbuf.length === 32, new Error('hashbuf must be a 32 byte buffer'));
1993
1994 var e = BN.fromBuffer(hashbuf, this.endian ? {
1995 endian: this.endian
1996 } : undefined);
1997
1998 var obj = this._findSignature(d, e);
1999 obj.compressed = this.pubkey.compressed;
2000
2001 this.sig = new Signature(obj);
2002 return this;
2003};
2004
2005ECDSA.prototype.signRandomK = function() {
2006 this.randomK();
2007 return this.sign();
2008};
2009
2010ECDSA.prototype.toString = function() {
2011 var obj = {};
2012 if (this.hashbuf) {
2013 obj.hashbuf = this.hashbuf.toString('hex');
2014 }
2015 if (this.privkey) {
2016 obj.privkey = this.privkey.toString();
2017 }
2018 if (this.pubkey) {
2019 obj.pubkey = this.pubkey.toString();
2020 }
2021 if (this.sig) {
2022 obj.sig = this.sig.toString();
2023 }
2024 if (this.k) {
2025 obj.k = this.k.toString();
2026 }
2027 return JSON.stringify(obj);
2028};
2029
2030ECDSA.prototype.verify = function() {
2031 if (!this.sigError()) {
2032 this.verified = true;
2033 } else {
2034 this.verified = false;
2035 }
2036 return this;
2037};
2038
2039ECDSA.sign = function(hashbuf, privkey, endian) {
2040 return ECDSA().set({
2041 hashbuf: hashbuf,
2042 endian: endian,
2043 privkey: privkey
2044 }).sign().sig;
2045};
2046
2047ECDSA.verify = function(hashbuf, sig, pubkey, endian) {
2048 return ECDSA().set({
2049 hashbuf: hashbuf,
2050 endian: endian,
2051 sig: sig,
2052 pubkey: pubkey
2053 }).verify().verified;
2054};
2055
2056module.exports = ECDSA;
2057
2058}).call(this)}).call(this,require("buffer").Buffer)
2059},{"../publickey":26,"../util/buffer":45,"../util/preconditions":47,"./bn":6,"./hash":8,"./point":9,"./random":10,"./signature":11,"buffer":132,"lodash":210}],8:[function(require,module,exports){
2060(function (Buffer){(function (){
2061'use strict';
2062
2063var crypto = require('crypto');
2064var BufferUtil = require('../util/buffer');
2065var $ = require('../util/preconditions');
2066
2067var Hash = module.exports;
2068
2069Hash.sha1 = function(buf) {
2070 $.checkArgument(BufferUtil.isBuffer(buf));
2071 return crypto.createHash('sha1').update(buf).digest();
2072};
2073
2074Hash.sha1.blocksize = 512;
2075
2076Hash.sha256 = function(buf) {
2077 $.checkArgument(BufferUtil.isBuffer(buf));
2078 return crypto.createHash('sha256').update(buf).digest();
2079};
2080
2081Hash.sha256.blocksize = 512;
2082
2083Hash.sha256sha256 = function(buf) {
2084 $.checkArgument(BufferUtil.isBuffer(buf));
2085 return Hash.sha256(Hash.sha256(buf));
2086};
2087
2088Hash.ripemd160 = function(buf) {
2089 $.checkArgument(BufferUtil.isBuffer(buf));
2090 return crypto.createHash('ripemd160').update(buf).digest();
2091};
2092
2093Hash.sha256ripemd160 = function(buf) {
2094 $.checkArgument(BufferUtil.isBuffer(buf));
2095 return Hash.ripemd160(Hash.sha256(buf));
2096};
2097
2098Hash.sha512 = function(buf) {
2099 $.checkArgument(BufferUtil.isBuffer(buf));
2100 return crypto.createHash('sha512').update(buf).digest();
2101};
2102
2103Hash.sha512.blocksize = 1024;
2104
2105Hash.hmac = function(hashf, data, key) {
2106 //http://en.wikipedia.org/wiki/Hash-based_message_authentication_code
2107 //http://tools.ietf.org/html/rfc4868#section-2
2108 $.checkArgument(BufferUtil.isBuffer(data));
2109 $.checkArgument(BufferUtil.isBuffer(key));
2110 $.checkArgument(hashf.blocksize);
2111
2112 var blocksize = hashf.blocksize / 8;
2113
2114 if (key.length > blocksize) {
2115 key = hashf(key);
2116 } else if (key < blocksize) {
2117 var fill = Buffer.alloc(blocksize);
2118 fill.fill(0);
2119 key.copy(fill);
2120 key = fill;
2121 }
2122
2123 var o_key = Buffer.alloc(blocksize);
2124 o_key.fill(0x5c);
2125
2126 var i_key = Buffer.alloc(blocksize);
2127 i_key.fill(0x36);
2128
2129 var o_key_pad = Buffer.alloc(blocksize);
2130 var i_key_pad = Buffer.alloc(blocksize);
2131 for (var i = 0; i < blocksize; i++) {
2132 o_key_pad[i] = o_key[i] ^ key[i];
2133 i_key_pad[i] = i_key[i] ^ key[i];
2134 }
2135
2136 return hashf(Buffer.concat([o_key_pad, hashf(Buffer.concat([i_key_pad, data]))]));
2137};
2138
2139Hash.sha256hmac = function(data, key) {
2140 return Hash.hmac(Hash.sha256, data, key);
2141};
2142
2143Hash.sha512hmac = function(data, key) {
2144 return Hash.hmac(Hash.sha512, data, key);
2145};
2146
2147}).call(this)}).call(this,require("buffer").Buffer)
2148},{"../util/buffer":45,"../util/preconditions":47,"buffer":132,"crypto":140}],9:[function(require,module,exports){
2149(function (Buffer){(function (){
2150'use strict';
2151
2152var BN = require('./bn');
2153var BufferUtil = require('../util/buffer');
2154
2155var EC = require('elliptic').ec;
2156var ec = new EC('secp256k1');
2157var ecPoint = ec.curve.point.bind(ec.curve);
2158var ecPointFromX = ec.curve.pointFromX.bind(ec.curve);
2159
2160/**
2161 *
2162 * Instantiate a valid secp256k1 Point from the X and Y coordinates.
2163 *
2164 * @param {BN|String} x - The X coordinate
2165 * @param {BN|String} y - The Y coordinate
2166 * @link https://github.com/indutny/elliptic
2167 * @augments elliptic.curve.point
2168 * @throws {Error} A validation error if exists
2169 * @returns {Point} An instance of Point
2170 * @constructor
2171 */
2172var Point = function Point(x, y, isRed) {
2173 try {
2174 var point = ecPoint(x, y, isRed);
2175 } catch (e) {
2176 throw new Error('Invalid Point');
2177 }
2178 point.validate();
2179 return point;
2180};
2181
2182Point.prototype = Object.getPrototypeOf(ec.curve.point());
2183
2184/**
2185 *
2186 * Instantiate a valid secp256k1 Point from only the X coordinate
2187 *
2188 * @param {boolean} odd - If the Y coordinate is odd
2189 * @param {BN|String} x - The X coordinate
2190 * @throws {Error} A validation error if exists
2191 * @returns {Point} An instance of Point
2192 */
2193Point.fromX = function fromX(odd, x){
2194 try {
2195 var point = ecPointFromX(x, odd);
2196 } catch (e) {
2197 throw new Error('Invalid X');
2198 }
2199 point.validate();
2200 return point;
2201};
2202
2203/**
2204 *
2205 * Will return a secp256k1 ECDSA base point.
2206 *
2207 * @link https://en.bitcoin.it/wiki/Secp256k1
2208 * @returns {Point} An instance of the base point.
2209 */
2210Point.getG = function getG() {
2211 return ec.curve.g;
2212};
2213
2214/**
2215 *
2216 * Will return the max of range of valid private keys as governed by the secp256k1 ECDSA standard.
2217 *
2218 * @link https://en.bitcoin.it/wiki/Private_key#Range_of_valid_ECDSA_private_keys
2219 * @returns {BN} A BN instance of the number of points on the curve
2220 */
2221Point.getN = function getN() {
2222 return new BN(ec.curve.n.toArray());
2223};
2224
2225Point.prototype._getX = Point.prototype.getX;
2226
2227/**
2228 *
2229 * Will return the X coordinate of the Point
2230 *
2231 * @returns {BN} A BN instance of the X coordinate
2232 */
2233Point.prototype.getX = function getX() {
2234 return new BN(this._getX().toArray());
2235};
2236
2237Point.prototype._getY = Point.prototype.getY;
2238
2239/**
2240 *
2241 * Will return the Y coordinate of the Point
2242 *
2243 * @returns {BN} A BN instance of the Y coordinate
2244 */
2245Point.prototype.getY = function getY() {
2246 return new BN(this._getY().toArray());
2247};
2248
2249/**
2250 *
2251 * Will determine if the point is valid
2252 *
2253 * @link https://www.iacr.org/archive/pkc2003/25670211/25670211.pdf
2254 * @param {Point} An instance of Point
2255 * @throws {Error} A validation error if exists
2256 * @returns {Point} An instance of the same Point
2257 */
2258Point.prototype.validate = function validate() {
2259
2260 if (this.isInfinity()){
2261 throw new Error('Point cannot be equal to Infinity');
2262 }
2263
2264 var p2;
2265 try {
2266 p2 = ecPointFromX(this.getX(), this.getY().isOdd());
2267 } catch (e) {
2268 throw new Error('Point does not lie on the curve');
2269 }
2270
2271 if (p2.y.cmp(this.y) !== 0) {
2272 throw new Error('Invalid y value for curve.');
2273 }
2274
2275
2276 //todo: needs test case
2277 if (!(this.mul(Point.getN()).isInfinity())) {
2278 throw new Error('Point times N must be infinity');
2279 }
2280
2281 return this;
2282
2283};
2284
2285Point.pointToCompressed = function pointToCompressed(point) {
2286 var xbuf = point.getX().toBuffer({size: 32});
2287 var ybuf = point.getY().toBuffer({size: 32});
2288
2289 var prefix;
2290 var odd = ybuf[ybuf.length - 1] % 2;
2291 if (odd) {
2292 prefix = Buffer.from([0x03]);
2293 } else {
2294 prefix = Buffer.from([0x02]);
2295 }
2296 return BufferUtil.concat([prefix, xbuf]);
2297};
2298
2299module.exports = Point;
2300
2301}).call(this)}).call(this,require("buffer").Buffer)
2302},{"../util/buffer":45,"./bn":6,"buffer":132,"elliptic":156}],10:[function(require,module,exports){
2303(function (process,Buffer){(function (){
2304'use strict';
2305
2306function Random() {
2307}
2308
2309/* secure random bytes that sometimes throws an error due to lack of entropy */
2310Random.getRandomBuffer = function(size) {
2311 if (process.browser)
2312 return Random.getRandomBufferBrowser(size);
2313 else
2314 return Random.getRandomBufferNode(size);
2315};
2316
2317Random.getRandomBufferNode = function(size) {
2318 var crypto = require('crypto');
2319 return crypto.randomBytes(size);
2320};
2321
2322Random.getRandomBufferBrowser = function(size) {
2323 if (!window.crypto && !window.msCrypto)
2324 throw new Error('window.crypto not available');
2325
2326 if (window.crypto && window.crypto.getRandomValues)
2327 var crypto = window.crypto;
2328 else if (window.msCrypto && window.msCrypto.getRandomValues) //internet explorer
2329 var crypto = window.msCrypto;
2330 else
2331 throw new Error('window.crypto.getRandomValues not available');
2332
2333 var bbuf = new Uint8Array(size);
2334 crypto.getRandomValues(bbuf);
2335 var buf = Buffer.from(bbuf);
2336
2337 return buf;
2338};
2339
2340/* insecure random bytes, but it never fails */
2341Random.getPseudoRandomBuffer = function(size) {
2342 var b32 = 0x100000000;
2343 var b = Buffer.alloc(size);
2344 var r;
2345
2346 for (var i = 0; i <= size; i++) {
2347 var j = Math.floor(i / 4);
2348 var k = i - j * 4;
2349 if (k === 0) {
2350 r = Math.random() * b32;
2351 b[i] = r & 0xff;
2352 } else {
2353 b[i] = (r = r >>> 8) & 0xff;
2354 }
2355 }
2356
2357 return b;
2358};
2359
2360module.exports = Random;
2361
2362}).call(this)}).call(this,require('_process'),require("buffer").Buffer)
2363},{"_process":228,"buffer":132,"crypto":140}],11:[function(require,module,exports){
2364(function (Buffer){(function (){
2365'use strict';
2366
2367var BN = require('./bn');
2368var _ = require('lodash');
2369var $ = require('../util/preconditions');
2370var BufferUtil = require('../util/buffer');
2371var JSUtil = require('../util/js');
2372
2373var Signature = function Signature(r, s) {
2374 if (!(this instanceof Signature)) {
2375 return new Signature(r, s);
2376 }
2377 if (r instanceof BN) {
2378 this.set({
2379 r: r,
2380 s: s
2381 });
2382 } else if (r) {
2383 var obj = r;
2384 this.set(obj);
2385 }
2386};
2387
2388/* jshint maxcomplexity: 7 */
2389Signature.prototype.set = function(obj) {
2390 this.r = obj.r || this.r || undefined;
2391 this.s = obj.s || this.s || undefined;
2392
2393 this.i = typeof obj.i !== 'undefined' ? obj.i : this.i; //public key recovery parameter in range [0, 3]
2394 this.compressed = typeof obj.compressed !== 'undefined' ?
2395 obj.compressed : this.compressed; //whether the recovered pubkey is compressed
2396 this.nhashtype = obj.nhashtype || this.nhashtype || undefined;
2397 return this;
2398};
2399
2400Signature.fromCompact = function(buf) {
2401 $.checkArgument(BufferUtil.isBuffer(buf), 'Argument is expected to be a Buffer');
2402
2403 var sig = new Signature();
2404
2405 var compressed = true;
2406 var i = buf.slice(0, 1)[0] - 27 - 4;
2407 if (i < 0) {
2408 compressed = false;
2409 i = i + 4;
2410 }
2411
2412 var b2 = buf.slice(1, 33);
2413 var b3 = buf.slice(33, 65);
2414
2415 $.checkArgument(i === 0 || i === 1 || i === 2 || i === 3, new Error('i must be 0, 1, 2, or 3'));
2416 $.checkArgument(b2.length === 32, new Error('r must be 32 bytes'));
2417 $.checkArgument(b3.length === 32, new Error('s must be 32 bytes'));
2418
2419 sig.compressed = compressed;
2420 sig.i = i;
2421 sig.r = BN.fromBuffer(b2);
2422 sig.s = BN.fromBuffer(b3);
2423
2424 return sig;
2425};
2426
2427Signature.fromDER = Signature.fromBuffer = function(buf, strict) {
2428 var obj = Signature.parseDER(buf, strict);
2429 var sig = new Signature();
2430
2431 sig.r = obj.r;
2432 sig.s = obj.s;
2433
2434 return sig;
2435};
2436
2437// The format used in a tx
2438Signature.fromTxFormat = function(buf) {
2439 var nhashtype = buf.readUInt8(buf.length - 1);
2440 var derbuf = buf.slice(0, buf.length - 1);
2441 var sig = new Signature.fromDER(derbuf, false);
2442 sig.nhashtype = nhashtype;
2443 return sig;
2444};
2445
2446Signature.fromString = function(str) {
2447 var buf = Buffer.from(str, 'hex');
2448 return Signature.fromDER(buf);
2449};
2450
2451
2452/**
2453 * In order to mimic the non-strict DER encoding of OpenSSL, set strict = false.
2454 */
2455Signature.parseDER = function(buf, strict) {
2456 $.checkArgument(BufferUtil.isBuffer(buf), new Error('DER formatted signature should be a buffer'));
2457 if (_.isUndefined(strict)) {
2458 strict = true;
2459 }
2460
2461 var header = buf[0];
2462 $.checkArgument(header === 0x30, new Error('Header byte should be 0x30'));
2463
2464 var length = buf[1];
2465 var buflength = buf.slice(2).length;
2466 $.checkArgument(!strict || length === buflength, new Error('Length byte should length of what follows'));
2467
2468 length = length < buflength ? length : buflength;
2469
2470 var rheader = buf[2 + 0];
2471 $.checkArgument(rheader === 0x02, new Error('Integer byte for r should be 0x02'));
2472
2473 var rlength = buf[2 + 1];
2474 var rbuf = buf.slice(2 + 2, 2 + 2 + rlength);
2475 var r = BN.fromBuffer(rbuf);
2476 var rneg = buf[2 + 1 + 1] === 0x00 ? true : false;
2477 $.checkArgument(rlength === rbuf.length, new Error('Length of r incorrect'));
2478
2479 var sheader = buf[2 + 2 + rlength + 0];
2480 $.checkArgument(sheader === 0x02, new Error('Integer byte for s should be 0x02'));
2481
2482 var slength = buf[2 + 2 + rlength + 1];
2483 var sbuf = buf.slice(2 + 2 + rlength + 2, 2 + 2 + rlength + 2 + slength);
2484 var s = BN.fromBuffer(sbuf);
2485 var sneg = buf[2 + 2 + rlength + 2 + 2] === 0x00 ? true : false;
2486 $.checkArgument(slength === sbuf.length, new Error('Length of s incorrect'));
2487
2488 var sumlength = 2 + 2 + rlength + 2 + slength;
2489 $.checkArgument(length === sumlength - 2, new Error('Length of signature incorrect'));
2490
2491 var obj = {
2492 header: header,
2493 length: length,
2494 rheader: rheader,
2495 rlength: rlength,
2496 rneg: rneg,
2497 rbuf: rbuf,
2498 r: r,
2499 sheader: sheader,
2500 slength: slength,
2501 sneg: sneg,
2502 sbuf: sbuf,
2503 s: s
2504 };
2505
2506 return obj;
2507};
2508
2509
2510Signature.prototype.toCompact = function(i, compressed) {
2511 i = typeof i === 'number' ? i : this.i;
2512 compressed = typeof compressed === 'boolean' ? compressed : this.compressed;
2513
2514 if (!(i === 0 || i === 1 || i === 2 || i === 3)) {
2515 throw new Error('i must be equal to 0, 1, 2, or 3');
2516 }
2517
2518 var val = i + 27 + 4;
2519 if (compressed === false) {
2520 val = val - 4;
2521 }
2522 var b1 = Buffer.from([val]);
2523 var b2 = this.r.toBuffer({
2524 size: 32
2525 });
2526 var b3 = this.s.toBuffer({
2527 size: 32
2528 });
2529 return Buffer.concat([b1, b2, b3]);
2530};
2531
2532Signature.prototype.toBuffer = Signature.prototype.toDER = function() {
2533 var rnbuf = this.r.toBuffer();
2534 var snbuf = this.s.toBuffer();
2535
2536 var rneg = rnbuf[0] & 0x80 ? true : false;
2537 var sneg = snbuf[0] & 0x80 ? true : false;
2538
2539 var rbuf = rneg ? Buffer.concat([Buffer.from([0x00]), rnbuf]) : rnbuf;
2540 var sbuf = sneg ? Buffer.concat([Buffer.from([0x00]), snbuf]) : snbuf;
2541
2542 var rlength = rbuf.length;
2543 var slength = sbuf.length;
2544 var length = 2 + rlength + 2 + slength;
2545 var rheader = 0x02;
2546 var sheader = 0x02;
2547 var header = 0x30;
2548
2549 var der = Buffer.concat([Buffer.from([header, length, rheader, rlength]), rbuf, Buffer.from([sheader, slength]), sbuf]);
2550 return der;
2551};
2552
2553Signature.prototype.toString = function() {
2554 var buf = this.toDER();
2555 return buf.toString('hex');
2556};
2557
2558/**
2559 * This function is translated from bitcoind's IsDERSignature and is used in
2560 * the script interpreter. This "DER" format actually includes an extra byte,
2561 * the nhashtype, at the end. It is really the tx format, not DER format.
2562 *
2563 * A canonical signature exists of: [30] [total len] [02] [len R] [R] [02] [len S] [S] [hashtype]
2564 * Where R and S are not negative (their first byte has its highest bit not set), and not
2565 * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows,
2566 * in which case a single 0 byte is necessary and even required).
2567 *
2568 * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623
2569 */
2570Signature.isTxDER = function(buf) {
2571 if (buf.length < 9) {
2572 // Non-canonical signature: too short
2573 return false;
2574 }
2575 if (buf.length > 73) {
2576 // Non-canonical signature: too long
2577 return false;
2578 }
2579 if (buf[0] !== 0x30) {
2580 // Non-canonical signature: wrong type
2581 return false;
2582 }
2583 if (buf[1] !== buf.length - 3) {
2584 // Non-canonical signature: wrong length marker
2585 return false;
2586 }
2587 var nLenR = buf[3];
2588 if (5 + nLenR >= buf.length) {
2589 // Non-canonical signature: S length misplaced
2590 return false;
2591 }
2592 var nLenS = buf[5 + nLenR];
2593 if ((nLenR + nLenS + 7) !== buf.length) {
2594 // Non-canonical signature: R+S length mismatch
2595 return false;
2596 }
2597
2598 var R = buf.slice(4);
2599 if (buf[4 - 2] !== 0x02) {
2600 // Non-canonical signature: R value type mismatch
2601 return false;
2602 }
2603 if (nLenR === 0) {
2604 // Non-canonical signature: R length is zero
2605 return false;
2606 }
2607 if (R[0] & 0x80) {
2608 // Non-canonical signature: R value negative
2609 return false;
2610 }
2611 if (nLenR > 1 && (R[0] === 0x00) && !(R[1] & 0x80)) {
2612 // Non-canonical signature: R value excessively padded
2613 return false;
2614 }
2615
2616 var S = buf.slice(6 + nLenR);
2617 if (buf[6 + nLenR - 2] !== 0x02) {
2618 // Non-canonical signature: S value type mismatch
2619 return false;
2620 }
2621 if (nLenS === 0) {
2622 // Non-canonical signature: S length is zero
2623 return false;
2624 }
2625 if (S[0] & 0x80) {
2626 // Non-canonical signature: S value negative
2627 return false;
2628 }
2629 if (nLenS > 1 && (S[0] === 0x00) && !(S[1] & 0x80)) {
2630 // Non-canonical signature: S value excessively padded
2631 return false;
2632 }
2633 return true;
2634};
2635
2636/**
2637 * Compares to bitcoind's IsLowDERSignature
2638 * See also ECDSA signature algorithm which enforces this.
2639 * See also BIP 62, "low S values in signatures"
2640 */
2641Signature.prototype.hasLowS = function() {
2642 if (this.s.lt(new BN(1)) ||
2643 this.s.gt(new BN('7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0', 'hex'))) {
2644 return false;
2645 }
2646 return true;
2647};
2648
2649/**
2650 * @returns true if the nhashtype is exactly equal to one of the standard options or combinations thereof.
2651 * Translated from bitcoind's IsDefinedHashtypeSignature
2652 */
2653Signature.prototype.hasDefinedHashtype = function() {
2654 if (!JSUtil.isNaturalNumber(this.nhashtype)) {
2655 return false;
2656 }
2657 // accept with or without Signature.SIGHASH_ANYONECANPAY by ignoring the bit
2658 var temp = this.nhashtype & ~Signature.SIGHASH_ANYONECANPAY;
2659 if (temp < Signature.SIGHASH_ALL || temp > Signature.SIGHASH_SINGLE) {
2660 return false;
2661 }
2662 return true;
2663};
2664
2665Signature.prototype.toTxFormat = function() {
2666 var derbuf = this.toDER();
2667 var buf = Buffer.alloc(1);
2668 buf.writeUInt8(this.nhashtype, 0);
2669 return Buffer.concat([derbuf, buf]);
2670};
2671
2672Signature.SIGHASH_ALL = 0x01;
2673Signature.SIGHASH_NONE = 0x02;
2674Signature.SIGHASH_SINGLE = 0x03;
2675Signature.SIGHASH_ANYONECANPAY = 0x80;
2676
2677module.exports = Signature;
2678
2679}).call(this)}).call(this,require("buffer").Buffer)
2680},{"../util/buffer":45,"../util/js":46,"../util/preconditions":47,"./bn":6,"buffer":132,"lodash":210}],12:[function(require,module,exports){
2681(function (Buffer){(function (){
2682'use strict';
2683
2684var _ = require('lodash');
2685var bs58 = require('bs58');
2686var buffer = require('buffer');
2687
2688var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.split('');
2689
2690var Base58 = function Base58(obj) {
2691 /* jshint maxcomplexity: 8 */
2692 if (!(this instanceof Base58)) {
2693 return new Base58(obj);
2694 }
2695 if (Buffer.isBuffer(obj)) {
2696 var buf = obj;
2697 this.fromBuffer(buf);
2698 } else if (typeof obj === 'string') {
2699 var str = obj;
2700 this.fromString(str);
2701 } else if (obj) {
2702 this.set(obj);
2703 }
2704};
2705
2706Base58.validCharacters = function validCharacters(chars) {
2707 if (buffer.Buffer.isBuffer(chars)) {
2708 chars = chars.toString();
2709 }
2710 return _.every(_.map(chars, function(char) { return _.includes(ALPHABET, char); }));
2711};
2712
2713Base58.prototype.set = function(obj) {
2714 this.buf = obj.buf || this.buf || undefined;
2715 return this;
2716};
2717
2718Base58.encode = function(buf) {
2719 if (!buffer.Buffer.isBuffer(buf)) {
2720 throw new Error('Input should be a buffer');
2721 }
2722 return bs58.encode(buf);
2723};
2724
2725Base58.decode = function(str) {
2726 if (typeof str !== 'string') {
2727 throw new Error('Input should be a string');
2728 }
2729 return Buffer.from(bs58.decode(str));
2730};
2731
2732Base58.prototype.fromBuffer = function(buf) {
2733 this.buf = buf;
2734 return this;
2735};
2736
2737Base58.prototype.fromString = function(str) {
2738 var buf = Base58.decode(str);
2739 this.buf = buf;
2740 return this;
2741};
2742
2743Base58.prototype.toBuffer = function() {
2744 return this.buf;
2745};
2746
2747Base58.prototype.toString = function() {
2748 return Base58.encode(this.buf);
2749};
2750
2751module.exports = Base58;
2752
2753}).call(this)}).call(this,require("buffer").Buffer)
2754},{"bs58":129,"buffer":132,"lodash":210}],13:[function(require,module,exports){
2755(function (Buffer){(function (){
2756'use strict';
2757
2758var _ = require('lodash');
2759var Base58 = require('./base58');
2760var buffer = require('buffer');
2761var sha256sha256 = require('../crypto/hash').sha256sha256;
2762
2763var Base58Check = function Base58Check(obj) {
2764 if (!(this instanceof Base58Check))
2765 return new Base58Check(obj);
2766 if (Buffer.isBuffer(obj)) {
2767 var buf = obj;
2768 this.fromBuffer(buf);
2769 } else if (typeof obj === 'string') {
2770 var str = obj;
2771 this.fromString(str);
2772 } else if (obj) {
2773 this.set(obj);
2774 }
2775};
2776
2777Base58Check.prototype.set = function(obj) {
2778 this.buf = obj.buf || this.buf || undefined;
2779 return this;
2780};
2781
2782Base58Check.validChecksum = function validChecksum(data, checksum) {
2783 if (_.isString(data)) {
2784 data = Buffer.from(Base58.decode(data));
2785 }
2786 if (_.isString(checksum)) {
2787 checksum = Buffer.from(Base58.decode(checksum));
2788 }
2789 if (!checksum) {
2790 checksum = data.slice(-4);
2791 data = data.slice(0, -4);
2792 }
2793 return Base58Check.checksum(data).toString('hex') === checksum.toString('hex');
2794};
2795
2796Base58Check.decode = function(s) {
2797 if (typeof s !== 'string')
2798 throw new Error('Input must be a string');
2799
2800 var buf = Buffer.from(Base58.decode(s));
2801
2802 if (buf.length < 4)
2803 throw new Error("Input string too short");
2804
2805 var data = buf.slice(0, -4);
2806 var csum = buf.slice(-4);
2807
2808 var hash = sha256sha256(data);
2809 var hash4 = hash.slice(0, 4);
2810
2811 if (csum.toString('hex') !== hash4.toString('hex'))
2812 throw new Error("Checksum mismatch");
2813
2814 return data;
2815};
2816
2817Base58Check.checksum = function(buffer) {
2818 return sha256sha256(buffer).slice(0, 4);
2819};
2820
2821Base58Check.encode = function(buf) {
2822 if (!Buffer.isBuffer(buf))
2823 throw new Error('Input must be a buffer');
2824 var checkedBuf = Buffer.alloc(buf.length + 4);
2825 var hash = Base58Check.checksum(buf);
2826 buf.copy(checkedBuf);
2827 hash.copy(checkedBuf, buf.length);
2828 return Base58.encode(checkedBuf);
2829};
2830
2831Base58Check.prototype.fromBuffer = function(buf) {
2832 this.buf = buf;
2833 return this;
2834};
2835
2836Base58Check.prototype.fromString = function(str) {
2837 var buf = Base58Check.decode(str);
2838 this.buf = buf;
2839 return this;
2840};
2841
2842Base58Check.prototype.toBuffer = function() {
2843 return this.buf;
2844};
2845
2846Base58Check.prototype.toString = function() {
2847 return Base58Check.encode(this.buf);
2848};
2849
2850module.exports = Base58Check;
2851
2852}).call(this)}).call(this,require("buffer").Buffer)
2853},{"../crypto/hash":8,"./base58":12,"buffer":132,"lodash":210}],14:[function(require,module,exports){
2854(function (Buffer){(function (){
2855'use strict';
2856
2857var bech32 = require('bech32');
2858
2859/**
2860 * Decode bech32/bech32m string
2861 * @param {String} str String to decode
2862 * @returns {Object} Decoded string info
2863 */
2864var decode = function(str) {
2865 if (typeof str !== 'string') {
2866 throw new Error('Input should be a string');
2867 }
2868
2869 var decoded;
2870 let fromWords = bech32.bech32.fromWords;
2871 let encoding = encodings.BECH32;
2872 try {
2873 decoded = bech32.bech32.decode(str);
2874 } catch (e) {
2875 if (e.message.indexOf('Invalid checksum') > -1) {
2876 decoded = bech32.bech32m.decode(str);
2877 encoding = encodings.BECH32M;
2878 fromWords = bech32.bech32m.fromWords;
2879 } else {
2880 throw e;
2881 }
2882 }
2883
2884 const version = decoded.words[0];
2885 if (version >= 1 && encoding !== encodings.BECH32M) {
2886 throw new Error('Version 1+ witness address must use Bech32m checksum');
2887 }
2888
2889 return {
2890 prefix: decoded.prefix,
2891 data: Buffer.from(fromWords(decoded.words.slice(1))),
2892 version
2893 };
2894};
2895
2896/**
2897 * Encode using BECH32 encoding
2898 * @param {String} prefix bech32 prefix
2899 * @param {Number} version
2900 * @param {String|Buffer} data
2901 * @param {String|Number} encoding (optional, default=bech32) Valid encodings are 'bech32', 'bech32m', 0, and 1.
2902 * @returns {String} encoded string
2903 */
2904var encode = function(prefix, version, data, encoding) {
2905 if (typeof prefix !== 'string') {
2906 throw new Error('Prefix should be a string');
2907 }
2908 if (typeof version !== 'number') {
2909 throw new Error('version should be a number');
2910 }
2911 // convert string to number
2912 if (encoding && typeof encoding == 'string') {
2913 encoding = encodings[encoding.toUpperCase()] || -1; // fallback to -1 so it throws invalid encoding below
2914 }
2915 if (encoding && !(encoding == encodings.BECH32 || encoding == encodings.BECH32M)) {
2916 throw new Error('Invalid encoding specified');
2917 }
2918
2919 let b32Variety = encoding == encodings.BECH32M ? bech32.bech32m : bech32.bech32;
2920 let words = b32Variety.toWords(data);
2921
2922 words.unshift(version);
2923 return b32Variety.encode(prefix, words);
2924}
2925
2926const encodings = {
2927 BECH32: 1,
2928 BECH32M: 2
2929}
2930
2931module.exports = { decode: decode, encode: encode, encodings };
2932
2933}).call(this)}).call(this,require("buffer").Buffer)
2934},{"bech32":67,"buffer":132}],15:[function(require,module,exports){
2935(function (Buffer){(function (){
2936'use strict';
2937
2938var _ = require('lodash');
2939var $ = require('../util/preconditions');
2940var BufferUtil = require('../util/buffer');
2941var BN = require('../crypto/bn');
2942
2943var BufferReader = function BufferReader(buf) {
2944 if (!(this instanceof BufferReader)) {
2945 return new BufferReader(buf);
2946 }
2947 if (_.isUndefined(buf)) {
2948 return;
2949 }
2950 if (Buffer.isBuffer(buf)) {
2951 this.set({
2952 buf: buf
2953 });
2954 } else if (_.isString(buf)) {
2955 this.set({
2956 buf: Buffer.from(buf, 'hex'),
2957 });
2958 } else if (_.isObject(buf)) {
2959 var obj = buf;
2960 this.set(obj);
2961 } else {
2962 throw new TypeError('Unrecognized argument for BufferReader');
2963 }
2964};
2965
2966BufferReader.prototype.set = function(obj) {
2967 this.buf = obj.buf || this.buf || undefined;
2968 this.pos = obj.pos || this.pos || 0;
2969 return this;
2970};
2971
2972BufferReader.prototype.eof = function() {
2973 if(this.buf) {
2974 return this.pos >= this.buf.length;
2975 } else {
2976 return true;
2977 }
2978};
2979
2980BufferReader.prototype.finished = BufferReader.prototype.eof;
2981
2982BufferReader.prototype.read = function(len) {
2983 $.checkArgument(!_.isUndefined(len), 'Must specify a length');
2984 var buf = this.buf.slice(this.pos, this.pos + len);
2985 this.pos = this.pos + len;
2986 return buf;
2987};
2988
2989BufferReader.prototype.readAll = function() {
2990 var buf = this.buf.slice(this.pos, this.buf.length);
2991 this.pos = this.buf.length;
2992 return buf;
2993};
2994
2995BufferReader.prototype.readUInt8 = function() {
2996 var val = this.buf.readUInt8(this.pos);
2997 this.pos = this.pos + 1;
2998 return val;
2999};
3000
3001BufferReader.prototype.readUInt16BE = function() {
3002 var val = this.buf.readUInt16BE(this.pos);
3003 this.pos = this.pos + 2;
3004 return val;
3005};
3006
3007BufferReader.prototype.readUInt16LE = function() {
3008 var val = this.buf.readUInt16LE(this.pos);
3009 this.pos = this.pos + 2;
3010 return val;
3011};
3012
3013BufferReader.prototype.readUInt32BE = function() {
3014 var val = this.buf.readUInt32BE(this.pos);
3015 this.pos = this.pos + 4;
3016 return val;
3017};
3018
3019BufferReader.prototype.readUInt32LE = function() {
3020 var val = this.buf.readUInt32LE(this.pos);
3021 this.pos = this.pos + 4;
3022 return val;
3023};
3024
3025BufferReader.prototype.readInt32LE = function() {
3026 var val = this.buf.readInt32LE(this.pos);
3027 this.pos = this.pos + 4;
3028 return val;
3029};
3030
3031BufferReader.prototype.readUInt64BEBN = function() {
3032 var buf = this.buf.slice(this.pos, this.pos + 8);
3033 var bn = BN.fromBuffer(buf);
3034 this.pos = this.pos + 8;
3035 return bn;
3036};
3037
3038BufferReader.prototype.readUInt64LEBN = function() {
3039 var second = this.buf.readUInt32LE(this.pos);
3040 var first = this.buf.readUInt32LE(this.pos + 4);
3041 var combined = (first * 0x100000000) + second;
3042 // Instantiating an instance of BN with a number is faster than with an
3043 // array or string. However, the maximum safe number for a double precision
3044 // floating point is 2 ^ 52 - 1 (0x1fffffffffffff), thus we can safely use
3045 // non-floating point numbers less than this amount (52 bits). And in the case
3046 // that the number is larger, we can instatiate an instance of BN by passing
3047 // an array from the buffer (slower) and specifying the endianness.
3048 var bn;
3049 if (combined <= 0x1fffffffffffff) {
3050 bn = new BN(combined);
3051 } else {
3052 var data = Array.prototype.slice.call(this.buf, this.pos, this.pos + 8);
3053 bn = new BN(data, 10, 'le');
3054 }
3055 this.pos = this.pos + 8;
3056 return bn;
3057};
3058
3059BufferReader.prototype.readVarintNum = function() {
3060 var first = this.readUInt8();
3061 switch (first) {
3062 case 0xFD:
3063 return this.readUInt16LE();
3064 case 0xFE:
3065 return this.readUInt32LE();
3066 case 0xFF:
3067 var bn = this.readUInt64LEBN();
3068 var n = bn.toNumber();
3069 if (n <= Math.pow(2, 53)) {
3070 return n;
3071 } else {
3072 throw new Error('number too large to retain precision - use readVarintBN');
3073 }
3074 break;
3075 default:
3076 return first;
3077 }
3078};
3079
3080/**
3081 * reads a length prepended buffer
3082 */
3083BufferReader.prototype.readVarLengthBuffer = function() {
3084 var len = this.readVarintNum();
3085 var buf = this.read(len);
3086 $.checkState(buf.length === len, 'Invalid length while reading varlength buffer. ' +
3087 'Expected to read: ' + len + ' and read ' + buf.length);
3088 return buf;
3089};
3090
3091BufferReader.prototype.readVarintBuf = function() {
3092 var first = this.buf.readUInt8(this.pos);
3093 switch (first) {
3094 case 0xFD:
3095 return this.read(1 + 2);
3096 case 0xFE:
3097 return this.read(1 + 4);
3098 case 0xFF:
3099 return this.read(1 + 8);
3100 default:
3101 return this.read(1);
3102 }
3103};
3104
3105BufferReader.prototype.readVarintBN = function() {
3106 var first = this.readUInt8();
3107 switch (first) {
3108 case 0xFD:
3109 return new BN(this.readUInt16LE());
3110 case 0xFE:
3111 return new BN(this.readUInt32LE());
3112 case 0xFF:
3113 return this.readUInt64LEBN();
3114 default:
3115 return new BN(first);
3116 }
3117};
3118
3119BufferReader.prototype.reverse = function() {
3120 var buf = Buffer.alloc(this.buf.length);
3121 for (var i = 0; i < buf.length; i++) {
3122 buf[i] = this.buf[this.buf.length - 1 - i];
3123 }
3124 this.buf = buf;
3125 return this;
3126};
3127
3128BufferReader.prototype.readReverse = function(len) {
3129 if (_.isUndefined(len)) {
3130 len = this.buf.length;
3131 }
3132 var buf = this.buf.slice(this.pos, this.pos + len);
3133 this.pos = this.pos + len;
3134 return BufferUtil.reverse(buf);
3135};
3136
3137module.exports = BufferReader;
3138
3139}).call(this)}).call(this,require("buffer").Buffer)
3140},{"../crypto/bn":6,"../util/buffer":45,"../util/preconditions":47,"buffer":132,"lodash":210}],16:[function(require,module,exports){
3141(function (Buffer){(function (){
3142'use strict';
3143
3144var bufferUtil = require('../util/buffer');
3145var assert = require('assert');
3146
3147var BufferWriter = function BufferWriter(obj) {
3148 if (!(this instanceof BufferWriter))
3149 return new BufferWriter(obj);
3150 this.bufLen = 0;
3151 if (obj)
3152 this.set(obj);
3153 else
3154 this.bufs = [];
3155};
3156
3157BufferWriter.prototype.set = function(obj) {
3158 this.bufs = obj.bufs || this.bufs || [];
3159 this.bufLen = this.bufs.reduce(function(prev, buf){ return prev + buf.length; }, 0);
3160 return this;
3161};
3162
3163BufferWriter.prototype.toBuffer = function() {
3164 return this.concat();
3165};
3166
3167BufferWriter.prototype.concat = function() {
3168 return Buffer.concat(this.bufs, this.bufLen);
3169};
3170
3171BufferWriter.prototype.write = function(buf) {
3172 assert(bufferUtil.isBuffer(buf));
3173 this.bufs.push(buf);
3174 this.bufLen += buf.length;
3175 return this;
3176};
3177
3178BufferWriter.prototype.writeReverse = function(buf) {
3179 assert(bufferUtil.isBuffer(buf));
3180 this.bufs.push(bufferUtil.reverse(buf));
3181 this.bufLen += buf.length;
3182 return this;
3183};
3184
3185BufferWriter.prototype.writeUInt8 = function(n) {
3186 var buf = Buffer.alloc(1);
3187 buf.writeUInt8(n, 0);
3188 this.write(buf);
3189 return this;
3190};
3191
3192BufferWriter.prototype.writeUInt16BE = function(n) {
3193 var buf = Buffer.alloc(2);
3194 buf.writeUInt16BE(n, 0);
3195 this.write(buf);
3196 return this;
3197};
3198
3199BufferWriter.prototype.writeUInt16LE = function(n) {
3200 var buf = Buffer.alloc(2);
3201 buf.writeUInt16LE(n, 0);
3202 this.write(buf);
3203 return this;
3204};
3205
3206BufferWriter.prototype.writeUInt32BE = function(n) {
3207 var buf = Buffer.alloc(4);
3208 buf.writeUInt32BE(n, 0);
3209 this.write(buf);
3210 return this;
3211};
3212
3213BufferWriter.prototype.writeInt32LE = function(n) {
3214 var buf = Buffer.alloc(4);
3215 buf.writeInt32LE(n, 0);
3216 this.write(buf);
3217 return this;
3218};
3219
3220BufferWriter.prototype.writeUInt32LE = function(n) {
3221 var buf = Buffer.alloc(4);
3222 buf.writeUInt32LE(n, 0);
3223 this.write(buf);
3224 return this;
3225};
3226
3227BufferWriter.prototype.writeUInt64BEBN = function(bn) {
3228 var buf = bn.toBuffer({size: 8});
3229 this.write(buf);
3230 return this;
3231};
3232
3233BufferWriter.prototype.writeUInt64LEBN = function(bn) {
3234 var buf = bn.toBuffer({size: 8});
3235 this.writeReverse(buf);
3236 return this;
3237};
3238
3239BufferWriter.prototype.writeVarintNum = function(n) {
3240 var buf = BufferWriter.varintBufNum(n);
3241 this.write(buf);
3242 return this;
3243};
3244
3245BufferWriter.prototype.writeVarintBN = function(bn) {
3246 var buf = BufferWriter.varintBufBN(bn);
3247 this.write(buf);
3248 return this;
3249};
3250
3251BufferWriter.varintBufNum = function(n) {
3252 var buf = undefined;
3253 if (n < 253) {
3254 buf = Buffer.alloc(1);
3255 buf.writeUInt8(n, 0);
3256 } else if (n < 0x10000) {
3257 buf = Buffer.alloc(1 + 2);
3258 buf.writeUInt8(253, 0);
3259 buf.writeUInt16LE(n, 1);
3260 } else if (n < 0x100000000) {
3261 buf = Buffer.alloc(1 + 4);
3262 buf.writeUInt8(254, 0);
3263 buf.writeUInt32LE(n, 1);
3264 } else {
3265 buf = Buffer.alloc(1 + 8);
3266 buf.writeUInt8(255, 0);
3267 buf.writeInt32LE(n & -1, 1);
3268 buf.writeUInt32LE(Math.floor(n / 0x100000000), 5);
3269 }
3270 return buf;
3271};
3272
3273BufferWriter.varintBufBN = function(bn) {
3274 var buf = undefined;
3275 var n = bn.toNumber();
3276 if (n < 253) {
3277 buf = Buffer.alloc(1);
3278 buf.writeUInt8(n, 0);
3279 } else if (n < 0x10000) {
3280 buf = Buffer.alloc(1 + 2);
3281 buf.writeUInt8(253, 0);
3282 buf.writeUInt16LE(n, 1);
3283 } else if (n < 0x100000000) {
3284 buf = Buffer.alloc(1 + 4);
3285 buf.writeUInt8(254, 0);
3286 buf.writeUInt32LE(n, 1);
3287 } else {
3288 var bw = new BufferWriter();
3289 bw.writeUInt8(255);
3290 bw.writeUInt64LEBN(bn);
3291 var buf = bw.concat();
3292 }
3293 return buf;
3294};
3295
3296module.exports = BufferWriter;
3297
3298}).call(this)}).call(this,require("buffer").Buffer)
3299},{"../util/buffer":45,"assert":62,"buffer":132}],17:[function(require,module,exports){
3300(function (Buffer){(function (){
3301'use strict';
3302
3303var BufferWriter = require('./bufferwriter');
3304var BufferReader = require('./bufferreader');
3305var BN = require('../crypto/bn');
3306
3307var Varint = function Varint(buf) {
3308 if (!(this instanceof Varint))
3309 return new Varint(buf);
3310 if (Buffer.isBuffer(buf)) {
3311 this.buf = buf;
3312 } else if (typeof buf === 'number') {
3313 var num = buf;
3314 this.fromNumber(num);
3315 } else if (buf instanceof BN) {
3316 var bn = buf;
3317 this.fromBN(bn);
3318 } else if (buf) {
3319 var obj = buf;
3320 this.set(obj);
3321 }
3322};
3323
3324Varint.prototype.set = function(obj) {
3325 this.buf = obj.buf || this.buf;
3326 return this;
3327};
3328
3329Varint.prototype.fromString = function(str) {
3330 this.set({
3331 buf: Buffer.from(str, 'hex')
3332 });
3333 return this;
3334};
3335
3336Varint.prototype.toString = function() {
3337 return this.buf.toString('hex');
3338};
3339
3340Varint.prototype.fromBuffer = function(buf) {
3341 this.buf = buf;
3342 return this;
3343};
3344
3345Varint.prototype.fromBufferReader = function(br) {
3346 this.buf = br.readVarintBuf();
3347 return this;
3348};
3349
3350Varint.prototype.fromBN = function(bn) {
3351 this.buf = BufferWriter().writeVarintBN(bn).concat();
3352 return this;
3353};
3354
3355Varint.prototype.fromNumber = function(num) {
3356 this.buf = BufferWriter().writeVarintNum(num).concat();
3357 return this;
3358};
3359
3360Varint.prototype.toBuffer = function() {
3361 return this.buf;
3362};
3363
3364Varint.prototype.toBN = function() {
3365 return BufferReader(this.buf).readVarintBN();
3366};
3367
3368Varint.prototype.toNumber = function() {
3369 return BufferReader(this.buf).readVarintNum();
3370};
3371
3372module.exports = Varint;
3373
3374}).call(this)}).call(this,require("buffer").Buffer)
3375},{"../crypto/bn":6,"./bufferreader":15,"./bufferwriter":16,"buffer":132}],18:[function(require,module,exports){
3376'use strict';
3377
3378var _ = require('lodash');
3379
3380function format(message, args) {
3381 return message
3382 .replace('{0}', args[0])
3383 .replace('{1}', args[1])
3384 .replace('{2}', args[2]);
3385}
3386var traverseNode = function(parent, errorDefinition) {
3387 var NodeError = function() {
3388 if (_.isString(errorDefinition.message)) {
3389 this.message = format(errorDefinition.message, arguments);
3390 } else if (_.isFunction(errorDefinition.message)) {
3391 this.message = errorDefinition.message.apply(null, arguments);
3392 } else {
3393 throw new Error('Invalid error definition for ' + errorDefinition.name);
3394 }
3395 this.stack = this.message + '\n' + (new Error()).stack;
3396 };
3397 NodeError.prototype = Object.create(parent.prototype);
3398 NodeError.prototype.name = parent.prototype.name + errorDefinition.name;
3399 parent[errorDefinition.name] = NodeError;
3400 if (errorDefinition.errors) {
3401 childDefinitions(NodeError, errorDefinition.errors);
3402 }
3403 return NodeError;
3404};
3405
3406/* jshint latedef: false */
3407var childDefinitions = function(parent, childDefinitions) {
3408 _.each(childDefinitions, function(childDefinition) {
3409 traverseNode(parent, childDefinition);
3410 });
3411};
3412/* jshint latedef: true */
3413
3414var traverseRoot = function(parent, errorsDefinition) {
3415 childDefinitions(parent, errorsDefinition);
3416 return parent;
3417};
3418
3419
3420var bitcore = {};
3421bitcore.Error = function() {
3422 this.message = 'Internal error';
3423 this.stack = this.message + '\n' + (new Error()).stack;
3424};
3425bitcore.Error.prototype = Object.create(Error.prototype);
3426bitcore.Error.prototype.name = 'bitcore.Error';
3427
3428
3429var data = require('./spec');
3430traverseRoot(bitcore.Error, data);
3431
3432module.exports = bitcore.Error;
3433
3434module.exports.extend = function(spec) {
3435 return traverseNode(bitcore.Error, spec);
3436};
3437
3438},{"./spec":19,"lodash":210}],19:[function(require,module,exports){
3439'use strict';
3440
3441var docsURL = 'http://bitcore.io/';
3442
3443module.exports = [{
3444 name: 'InvalidB58Char',
3445 message: 'Invalid Base58 character: {0} in {1}'
3446}, {
3447 name: 'InvalidB58Checksum',
3448 message: 'Invalid Base58 checksum for {0}'
3449}, {
3450 name: 'InvalidNetwork',
3451 message: 'Invalid version for network: got {0}'
3452}, {
3453 name: 'InvalidState',
3454 message: 'Invalid state: {0}'
3455}, {
3456 name: 'NotImplemented',
3457 message: 'Function {0} was not implemented yet'
3458}, {
3459 name: 'InvalidNetworkArgument',
3460 message: 'Invalid network: must be "livenet" or "testnet", got {0}'
3461}, {
3462 name: 'InvalidArgument',
3463 message: function() {
3464 return 'Invalid Argument' + (arguments[0] ? (': ' + arguments[0]) : '') +
3465 (arguments[1] ? (' Documentation: ' + docsURL + arguments[1]) : '');
3466 }
3467}, {
3468 name: 'AbstractMethodInvoked',
3469 message: 'Abstract Method Invocation: {0}'
3470}, {
3471 name: 'InvalidArgumentType',
3472 message: function() {
3473 return 'Invalid Argument for ' + arguments[2] + ', expected ' + arguments[1] + ' but got ' + typeof arguments[0];
3474 }
3475}, {
3476 name: 'Unit',
3477 message: 'Internal Error on Unit {0}',
3478 errors: [{
3479 'name': 'UnknownCode',
3480 'message': 'Unrecognized unit code: {0}'
3481 }, {
3482 'name': 'InvalidRate',
3483 'message': 'Invalid exchange rate: {0}'
3484 }]
3485}, {
3486 name: 'MerkleBlock',
3487 message: 'Internal Error on MerkleBlock {0}',
3488 errors: [{
3489 'name': 'InvalidMerkleTree',
3490 'message': 'This MerkleBlock contain an invalid Merkle Tree'
3491 }]
3492}, {
3493 name: 'Transaction',
3494 message: 'Internal Error on Transaction {0}',
3495 errors: [{
3496 name: 'Input',
3497 message: 'Internal Error on Input {0}',
3498 errors: [{
3499 name: 'MissingScript',
3500 message: 'Need a script to create an input'
3501 }, {
3502 name: 'UnsupportedScript',
3503 message: 'Unsupported input script type: {0}'
3504 }, {
3505 name: 'MissingPreviousOutput',
3506 message: 'No previous output information.'
3507 }, {
3508 name: 'BlockHeightOutOfRange',
3509 message: 'Block Height can only be between 0 and 65535'
3510 } , {
3511 name: 'LockTimeRange',
3512 message: 'Seconds needs to be more that 0 and less that 33553920'
3513 }
3514 ]
3515 }, {
3516 name: 'NeedMoreInfo',
3517 message: '{0}'
3518 }, {
3519 name: 'InvalidSorting',
3520 message: 'The sorting function provided did not return the change output as one of the array elements'
3521 }, {
3522 name: 'InvalidOutputAmountSum',
3523 message: '{0}'
3524 }, {
3525 name: 'MissingSignatures',
3526 message: 'Some inputs have not been fully signed'
3527 }, {
3528 name: 'InvalidIndex',
3529 message: 'Invalid index: {0} is not between 0, {1}'
3530 }, {
3531 name: 'UnableToVerifySignature',
3532 message: 'Unable to verify signature: {0}'
3533 }, {
3534 name: 'DustOutputs',
3535 message: 'Dust amount detected in one output'
3536 }, {
3537 name: 'InvalidSatoshis',
3538 message: 'Output satoshis are invalid',
3539 }, {
3540 name: 'FeeError',
3541 message: 'Internal Error on Fee {0}',
3542 errors: [{
3543 name: 'TooSmall',
3544 message: 'Fee is too small: {0}',
3545 }, {
3546 name: 'TooLarge',
3547 message: 'Fee is too large: {0}',
3548 }, {
3549 name: 'Different',
3550 message: 'Unspent value is different from specified fee: {0}',
3551 }]
3552 }, {
3553 name: 'ChangeAddressMissing',
3554 message: 'Change address is missing'
3555 }, {
3556 name: 'BlockHeightTooHigh',
3557 message: 'Block Height can be at most 2^32 -1'
3558 }, {
3559 name: 'NLockTimeOutOfRange',
3560 message: 'Block Height can only be between 0 and 499 999 999'
3561 }, {
3562 name: 'LockTimeTooEarly',
3563 message: 'Lock Time can\'t be earlier than UNIX date 500 000 000'
3564 }]
3565}, {
3566 name: 'Script',
3567 message: 'Internal Error on Script {0}',
3568 errors: [{
3569 name: 'UnrecognizedAddress',
3570 message: 'Expected argument {0} to be an address'
3571 }, {
3572 name: 'CantDeriveAddress',
3573 message: 'Can\'t derive address associated with script {0}, needs to be p2pkh in, p2pkh out, p2sh in, or p2sh out.'
3574 }, {
3575 name: 'InvalidBuffer',
3576 message: 'Invalid script buffer: can\'t parse valid script from given buffer {0}'
3577 }]
3578}, {
3579 name: 'HDPrivateKey',
3580 message: 'Internal Error on HDPrivateKey {0}',
3581 errors: [{
3582 name: 'InvalidDerivationArgument',
3583 message: 'Invalid derivation argument {0}, expected string, or number and boolean'
3584 }, {
3585 name: 'InvalidEntropyArgument',
3586 message: 'Invalid entropy: must be an hexa string or binary buffer, got {0}',
3587 errors: [{
3588 name: 'TooMuchEntropy',
3589 message: 'Invalid entropy: more than 512 bits is non standard, got "{0}"'
3590 }, {
3591 name: 'NotEnoughEntropy',
3592 message: 'Invalid entropy: at least 128 bits needed, got "{0}"'
3593 }]
3594 }, {
3595 name: 'InvalidLength',
3596 message: 'Invalid length for xprivkey string in {0}'
3597 }, {
3598 name: 'InvalidPath',
3599 message: 'Invalid derivation path: {0}'
3600 }, {
3601 name: 'UnrecognizedArgument',
3602 message: 'Invalid argument: creating a HDPrivateKey requires a string, buffer, json or object, got "{0}"'
3603 }]
3604}, {
3605 name: 'HDPublicKey',
3606 message: 'Internal Error on HDPublicKey {0}',
3607 errors: [{
3608 name: 'ArgumentIsPrivateExtended',
3609 message: 'Argument is an extended private key: {0}'
3610 }, {
3611 name: 'InvalidDerivationArgument',
3612 message: 'Invalid derivation argument: got {0}'
3613 }, {
3614 name: 'InvalidLength',
3615 message: 'Invalid length for xpubkey: got "{0}"'
3616 }, {
3617 name: 'InvalidPath',
3618 message: 'Invalid derivation path, it should look like: "m/1/100", got "{0}"'
3619 }, {
3620 name: 'InvalidIndexCantDeriveHardened',
3621 message: 'Invalid argument: creating a hardened path requires an HDPrivateKey'
3622 }, {
3623 name: 'MustSupplyArgument',
3624 message: 'Must supply an argument to create a HDPublicKey'
3625 }, {
3626 name: 'UnrecognizedArgument',
3627 message: 'Invalid argument for creation, must be string, json, buffer, or object'
3628 }]
3629}];
3630
3631},{}],20:[function(require,module,exports){
3632(function (Buffer){(function (){
3633'use strict';
3634
3635
3636var assert = require('assert');
3637var buffer = require('buffer');
3638var _ = require('lodash');
3639var $ = require('./util/preconditions');
3640
3641var BN = require('./crypto/bn');
3642var Base58 = require('./encoding/base58');
3643var Base58Check = require('./encoding/base58check');
3644var Hash = require('./crypto/hash');
3645var Network = require('./networks');
3646var Point = require('./crypto/point');
3647var PrivateKey = require('./privatekey');
3648var Random = require('./crypto/random');
3649
3650var errors = require('./errors');
3651var hdErrors = errors.HDPrivateKey;
3652var BufferUtil = require('./util/buffer');
3653var JSUtil = require('./util/js');
3654
3655var MINIMUM_ENTROPY_BITS = 128;
3656var BITS_TO_BYTES = 1 / 8;
3657var MAXIMUM_ENTROPY_BITS = 512;
3658
3659
3660/**
3661 * Represents an instance of an hierarchically derived private key.
3662 *
3663 * More info on https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
3664 *
3665 * @constructor
3666 * @param {string|Buffer|Object} arg
3667 */
3668function HDPrivateKey(arg) {
3669 /* jshint maxcomplexity: 10 */
3670 if (arg instanceof HDPrivateKey) {
3671 return arg;
3672 }
3673 if (!(this instanceof HDPrivateKey)) {
3674 return new HDPrivateKey(arg);
3675 }
3676 if (!arg) {
3677 return this._generateRandomly();
3678 }
3679
3680 if (Network.get(arg)) {
3681 return this._generateRandomly(arg);
3682 } else if (_.isString(arg) || BufferUtil.isBuffer(arg)) {
3683 if (HDPrivateKey.isValidSerialized(arg)) {
3684 this._buildFromSerialized(arg);
3685 } else if (JSUtil.isValidJSON(arg)) {
3686 this._buildFromJSON(arg);
3687 } else if (BufferUtil.isBuffer(arg) && HDPrivateKey.isValidSerialized(arg.toString())) {
3688 this._buildFromSerialized(arg.toString());
3689 } else {
3690 throw HDPrivateKey.getSerializedError(arg);
3691 }
3692 } else if (_.isObject(arg)) {
3693 this._buildFromObject(arg);
3694 } else {
3695 throw new hdErrors.UnrecognizedArgument(arg);
3696 }
3697}
3698
3699/**
3700 * Verifies that a given path is valid.
3701 *
3702 * @param {string|number} arg
3703 * @param {boolean?} hardened
3704 * @return {boolean}
3705 */
3706HDPrivateKey.isValidPath = function(arg, hardened) {
3707 if (_.isString(arg)) {
3708 var indexes = HDPrivateKey._getDerivationIndexes(arg);
3709 return indexes !== null && _.every(indexes, HDPrivateKey.isValidPath);
3710 }
3711
3712 if (_.isNumber(arg)) {
3713 if (arg < HDPrivateKey.Hardened && hardened === true) {
3714 arg += HDPrivateKey.Hardened;
3715 }
3716 return arg >= 0 && arg < HDPrivateKey.MaxIndex;
3717 }
3718
3719 return false;
3720};
3721
3722/**
3723 * Internal function that splits a string path into a derivation index array.
3724 * It will return null if the string path is malformed.
3725 * It does not validate if indexes are in bounds.
3726 *
3727 * @param {string} path
3728 * @return {Array}
3729 */
3730HDPrivateKey._getDerivationIndexes = function(path) {
3731 var steps = path.split('/');
3732
3733 // Special cases:
3734 if (_.includes(HDPrivateKey.RootElementAlias, path)) {
3735 return [];
3736 }
3737
3738 if (!_.includes(HDPrivateKey.RootElementAlias, steps[0])) {
3739 return null;
3740 }
3741
3742 var indexes = steps.slice(1).map(function(step) {
3743 var isHardened = step.slice(-1) === '\'';
3744 if (isHardened) {
3745 step = step.slice(0, -1);
3746 }
3747 if (!step || step[0] === '-') {
3748 return NaN;
3749 }
3750 var index = +step; // cast to number
3751 if (isHardened) {
3752 index += HDPrivateKey.Hardened;
3753 }
3754
3755 return index;
3756 });
3757
3758 return _.some(indexes, isNaN) ? null : indexes;
3759};
3760
3761/**
3762 * WARNING: This method is deprecated. Use deriveChild or deriveNonCompliantChild instead. This is not BIP32 compliant
3763 *
3764 *
3765 * Get a derived child based on a string or number.
3766 *
3767 * If the first argument is a string, it's parsed as the full path of
3768 * derivation. Valid values for this argument include "m" (which returns the
3769 * same private key), "m/0/1/40/2'/1000", where the ' quote means a hardened
3770 * derivation.
3771 *
3772 * If the first argument is a number, the child with that index will be
3773 * derived. If the second argument is truthy, the hardened version will be
3774 * derived. See the example usage for clarification.
3775 *
3776 * @example
3777 * ```javascript
3778 * var parent = new HDPrivateKey('xprv...');
3779 * var child_0_1_2h = parent.derive(0).derive(1).derive(2, true);
3780 * var copy_of_child_0_1_2h = parent.derive("m/0/1/2'");
3781 * assert(child_0_1_2h.xprivkey === copy_of_child_0_1_2h);
3782 * ```
3783 *
3784 * @param {string|number} arg
3785 * @param {boolean?} hardened
3786 */
3787HDPrivateKey.prototype.derive = function(arg, hardened) {
3788 return this.deriveNonCompliantChild(arg, hardened);
3789};
3790
3791/**
3792 * WARNING: This method will not be officially supported until v1.0.0.
3793 *
3794 *
3795 * Get a derived child based on a string or number.
3796 *
3797 * If the first argument is a string, it's parsed as the full path of
3798 * derivation. Valid values for this argument include "m" (which returns the
3799 * same private key), "m/0/1/40/2'/1000", where the ' quote means a hardened
3800 * derivation.
3801 *
3802 * If the first argument is a number, the child with that index will be
3803 * derived. If the second argument is truthy, the hardened version will be
3804 * derived. See the example usage for clarification.
3805 *
3806 * WARNING: The `nonCompliant` option should NOT be used, except for older implementation
3807 * that used a derivation strategy that used a non-zero padded private key.
3808 *
3809 * @example
3810 * ```javascript
3811 * var parent = new HDPrivateKey('xprv...');
3812 * var child_0_1_2h = parent.deriveChild(0).deriveChild(1).deriveChild(2, true);
3813 * var copy_of_child_0_1_2h = parent.deriveChild("m/0/1/2'");
3814 * assert(child_0_1_2h.xprivkey === copy_of_child_0_1_2h);
3815 * ```
3816 *
3817 * @param {string|number} arg
3818 * @param {boolean?} hardened
3819 */
3820HDPrivateKey.prototype.deriveChild = function(arg, hardened) {
3821 if (_.isNumber(arg)) {
3822 return this._deriveWithNumber(arg, hardened);
3823 } else if (_.isString(arg)) {
3824 return this._deriveFromString(arg);
3825 } else {
3826 throw new hdErrors.InvalidDerivationArgument(arg);
3827 }
3828};
3829
3830/**
3831 * WARNING: This method will not be officially supported until v1.0.0
3832 *
3833 *
3834 * WARNING: If this is a new implementation you should NOT use this method, you should be using
3835 * `derive` instead.
3836 *
3837 * This method is explicitly for use and compatibility with an implementation that
3838 * was not compliant with BIP32 regarding the derivation algorithm. The private key
3839 * must be 32 bytes hashing, and this implementation will use the non-zero padded
3840 * serialization of a private key, such that it's still possible to derive the privateKey
3841 * to recover those funds.
3842 *
3843 * @param {string|number} arg
3844 * @param {boolean?} hardened
3845 */
3846HDPrivateKey.prototype.deriveNonCompliantChild = function(arg, hardened) {
3847 if (_.isNumber(arg)) {
3848 return this._deriveWithNumber(arg, hardened, true);
3849 } else if (_.isString(arg)) {
3850 return this._deriveFromString(arg, true);
3851 } else {
3852 throw new hdErrors.InvalidDerivationArgument(arg);
3853 }
3854};
3855
3856HDPrivateKey.prototype._deriveWithNumber = function(index, hardened, nonCompliant) {
3857 /* jshint maxstatements: 20 */
3858 /* jshint maxcomplexity: 10 */
3859 if (!HDPrivateKey.isValidPath(index, hardened)) {
3860 throw new hdErrors.InvalidPath(index);
3861 }
3862
3863 hardened = index >= HDPrivateKey.Hardened ? true : hardened;
3864 if (index < HDPrivateKey.Hardened && hardened === true) {
3865 index += HDPrivateKey.Hardened;
3866 }
3867
3868 var indexBuffer = BufferUtil.integerAsBuffer(index);
3869 var data;
3870 if (hardened && nonCompliant) {
3871 // The private key serialization in this case will not be exactly 32 bytes and can be
3872 // any value less, and the value is not zero-padded.
3873 var nonZeroPadded = this.privateKey.bn.toBuffer();
3874 data = BufferUtil.concat([Buffer.from([0]), nonZeroPadded, indexBuffer]);
3875 } else if (hardened) {
3876 // This will use a 32 byte zero padded serialization of the private key
3877 var privateKeyBuffer = this.privateKey.bn.toBuffer({size: 32});
3878 assert(privateKeyBuffer.length === 32, 'length of private key buffer is expected to be 32 bytes');
3879 data = BufferUtil.concat([Buffer.from([0]), privateKeyBuffer, indexBuffer]);
3880 } else {
3881 data = BufferUtil.concat([this.publicKey.toBuffer(), indexBuffer]);
3882 }
3883 var hash = Hash.sha512hmac(data, this._buffers.chainCode);
3884 var leftPart = BN.fromBuffer(hash.slice(0, 32), {
3885 size: 32
3886 });
3887 var chainCode = hash.slice(32, 64);
3888
3889 var privateKey = leftPart.add(this.privateKey.toBigNumber()).umod(Point.getN()).toBuffer({
3890 size: 32
3891 });
3892
3893 if (!PrivateKey.isValid(privateKey)) {
3894 // Index at this point is already hardened, we can pass null as the hardened arg
3895 return this._deriveWithNumber(index + 1, null, nonCompliant);
3896 }
3897
3898 var derived = new HDPrivateKey({
3899 network: this.network,
3900 depth: this.depth + 1,
3901 parentFingerPrint: this.fingerPrint,
3902 childIndex: index,
3903 chainCode: chainCode,
3904 privateKey: privateKey
3905 });
3906
3907 return derived;
3908};
3909
3910HDPrivateKey.prototype._deriveFromString = function(path, nonCompliant) {
3911 if (!HDPrivateKey.isValidPath(path)) {
3912 throw new hdErrors.InvalidPath(path);
3913 }
3914
3915 var indexes = HDPrivateKey._getDerivationIndexes(path);
3916 var derived = indexes.reduce(function(prev, index) {
3917 return prev._deriveWithNumber(index, null, nonCompliant);
3918 }, this);
3919
3920 return derived;
3921};
3922
3923/**
3924 * Verifies that a given serialized private key in base58 with checksum format
3925 * is valid.
3926 *
3927 * @param {string|Buffer} data - the serialized private key
3928 * @param {string|Network=} network - optional, if present, checks that the
3929 * network provided matches the network serialized.
3930 * @return {boolean}
3931 */
3932HDPrivateKey.isValidSerialized = function(data, network) {
3933 return !HDPrivateKey.getSerializedError(data, network);
3934};
3935
3936/**
3937 * Checks what's the error that causes the validation of a serialized private key
3938 * in base58 with checksum to fail.
3939 *
3940 * @param {string|Buffer} data - the serialized private key
3941 * @param {string|Network=} network - optional, if present, checks that the
3942 * network provided matches the network serialized.
3943 * @return {errors.InvalidArgument|null}
3944 */
3945HDPrivateKey.getSerializedError = function(data, network) {
3946 /* jshint maxcomplexity: 10 */
3947 if (!(_.isString(data) || BufferUtil.isBuffer(data))) {
3948 return new hdErrors.UnrecognizedArgument('Expected string or buffer');
3949 }
3950 if (!Base58.validCharacters(data)) {
3951 return new errors.InvalidB58Char('(unknown)', data);
3952 }
3953 try {
3954 data = Base58Check.decode(data);
3955 } catch (e) {
3956 return new errors.InvalidB58Checksum(data);
3957 }
3958 if (data.length !== HDPrivateKey.DataLength) {
3959 return new hdErrors.InvalidLength(data);
3960 }
3961 if (!_.isUndefined(network)) {
3962 var error = HDPrivateKey._validateNetwork(data, network);
3963 if (error) {
3964 return error;
3965 }
3966 }
3967 return null;
3968};
3969
3970HDPrivateKey._validateNetwork = function(data, networkArg) {
3971 var network = Network.get(networkArg);
3972 if (!network) {
3973 return new errors.InvalidNetworkArgument(networkArg);
3974 }
3975 var version = data.slice(0, 4);
3976 if (BufferUtil.integerFromBuffer(version) !== network.xprivkey) {
3977 return new errors.InvalidNetwork(version);
3978 }
3979 return null;
3980};
3981
3982HDPrivateKey.fromString = function(arg) {
3983 $.checkArgument(_.isString(arg), 'No valid string was provided');
3984 return new HDPrivateKey(arg);
3985};
3986
3987HDPrivateKey.fromObject = function(arg) {
3988 $.checkArgument(_.isObject(arg), 'No valid argument was provided');
3989 return new HDPrivateKey(arg);
3990};
3991
3992HDPrivateKey.prototype._buildFromJSON = function(arg) {
3993 return this._buildFromObject(JSON.parse(arg));
3994};
3995
3996HDPrivateKey.prototype._buildFromObject = function(arg) {
3997 /* jshint maxcomplexity: 12 */
3998 // TODO: Type validation
3999 var buffers = {
4000 version: arg.network ? BufferUtil.integerAsBuffer(Network.get(arg.network).xprivkey) : arg.version,
4001 depth: _.isNumber(arg.depth) ? BufferUtil.integerAsSingleByteBuffer(arg.depth) : arg.depth,
4002 parentFingerPrint: _.isNumber(arg.parentFingerPrint) ? BufferUtil.integerAsBuffer(arg.parentFingerPrint) : arg.parentFingerPrint,
4003 childIndex: _.isNumber(arg.childIndex) ? BufferUtil.integerAsBuffer(arg.childIndex) : arg.childIndex,
4004 chainCode: _.isString(arg.chainCode) ? Buffer.from(arg.chainCode,'hex') : arg.chainCode,
4005 privateKey: (_.isString(arg.privateKey) && JSUtil.isHexa(arg.privateKey)) ? Buffer.from(arg.privateKey,'hex') : arg.privateKey,
4006 checksum: arg.checksum ? (arg.checksum.length ? arg.checksum : BufferUtil.integerAsBuffer(arg.checksum)) : undefined
4007 };
4008 return this._buildFromBuffers(buffers);
4009};
4010
4011HDPrivateKey.prototype._buildFromSerialized = function(arg) {
4012 var decoded = Base58Check.decode(arg);
4013 var buffers = {
4014 version: decoded.slice(HDPrivateKey.VersionStart, HDPrivateKey.VersionEnd),
4015 depth: decoded.slice(HDPrivateKey.DepthStart, HDPrivateKey.DepthEnd),
4016 parentFingerPrint: decoded.slice(HDPrivateKey.ParentFingerPrintStart,
4017 HDPrivateKey.ParentFingerPrintEnd),
4018 childIndex: decoded.slice(HDPrivateKey.ChildIndexStart, HDPrivateKey.ChildIndexEnd),
4019 chainCode: decoded.slice(HDPrivateKey.ChainCodeStart, HDPrivateKey.ChainCodeEnd),
4020 privateKey: decoded.slice(HDPrivateKey.PrivateKeyStart, HDPrivateKey.PrivateKeyEnd),
4021 checksum: decoded.slice(HDPrivateKey.ChecksumStart, HDPrivateKey.ChecksumEnd),
4022 xprivkey: arg
4023 };
4024 return this._buildFromBuffers(buffers);
4025};
4026
4027HDPrivateKey.prototype._generateRandomly = function(network) {
4028 return HDPrivateKey.fromSeed(Random.getRandomBuffer(64), network);
4029};
4030
4031/**
4032 * Generate a private key from a seed, as described in BIP32
4033 *
4034 * @param {string|Buffer} hexa
4035 * @param {*} network
4036 * @return HDPrivateKey
4037 */
4038HDPrivateKey.fromSeed = function(hexa, network) {
4039 /* jshint maxcomplexity: 8 */
4040 if (JSUtil.isHexaString(hexa)) {
4041 hexa = Buffer.from(hexa, 'hex');
4042 }
4043 if (!Buffer.isBuffer(hexa)) {
4044 throw new hdErrors.InvalidEntropyArgument(hexa);
4045 }
4046 if (hexa.length < MINIMUM_ENTROPY_BITS * BITS_TO_BYTES) {
4047 throw new hdErrors.InvalidEntropyArgument.NotEnoughEntropy(hexa);
4048 }
4049 if (hexa.length > MAXIMUM_ENTROPY_BITS * BITS_TO_BYTES) {
4050 throw new hdErrors.InvalidEntropyArgument.TooMuchEntropy(hexa);
4051 }
4052 var hash = Hash.sha512hmac(hexa, Buffer.from('Bitcoin seed'));
4053
4054 return new HDPrivateKey({
4055 network: Network.get(network) || Network.defaultNetwork,
4056 depth: 0,
4057 parentFingerPrint: 0,
4058 childIndex: 0,
4059 privateKey: hash.slice(0, 32),
4060 chainCode: hash.slice(32, 64)
4061 });
4062};
4063
4064
4065
4066HDPrivateKey.prototype._calcHDPublicKey = function() {
4067 if (!this._hdPublicKey) {
4068 var HDPublicKey = require('./hdpublickey');
4069 this._hdPublicKey = new HDPublicKey(this);
4070 }
4071};
4072
4073/**
4074 * Receives a object with buffers in all the properties and populates the
4075 * internal structure
4076 *
4077 * @param {Object} arg
4078 * @param {buffer.Buffer} arg.version
4079 * @param {buffer.Buffer} arg.depth
4080 * @param {buffer.Buffer} arg.parentFingerPrint
4081 * @param {buffer.Buffer} arg.childIndex
4082 * @param {buffer.Buffer} arg.chainCode
4083 * @param {buffer.Buffer} arg.privateKey
4084 * @param {buffer.Buffer} arg.checksum
4085 * @param {string=} arg.xprivkey - if set, don't recalculate the base58
4086 * representation
4087 * @return {HDPrivateKey} this
4088 */
4089HDPrivateKey.prototype._buildFromBuffers = function(arg) {
4090 /* jshint maxcomplexity: 8 */
4091 /* jshint maxstatements: 20 */
4092
4093 HDPrivateKey._validateBufferArguments(arg);
4094
4095 JSUtil.defineImmutable(this, {
4096 _buffers: arg
4097 });
4098
4099 var sequence = [
4100 arg.version, arg.depth, arg.parentFingerPrint, arg.childIndex, arg.chainCode,
4101 BufferUtil.emptyBuffer(1), arg.privateKey
4102 ];
4103 var concat = buffer.Buffer.concat(sequence);
4104 if (!arg.checksum || !arg.checksum.length) {
4105 arg.checksum = Base58Check.checksum(concat);
4106 } else {
4107 if (arg.checksum.toString() !== Base58Check.checksum(concat).toString()) {
4108 throw new errors.InvalidB58Checksum(concat);
4109 }
4110 }
4111
4112 var network = Network.get(BufferUtil.integerFromBuffer(arg.version));
4113 var xprivkey;
4114 xprivkey = Base58Check.encode(buffer.Buffer.concat(sequence));
4115 arg.xprivkey = Buffer.from(xprivkey);
4116
4117 var privateKey = new PrivateKey(BN.fromBuffer(arg.privateKey), network);
4118 var publicKey = privateKey.toPublicKey();
4119 var size = HDPrivateKey.ParentFingerPrintSize;
4120 var fingerPrint = Hash.sha256ripemd160(publicKey.toBuffer()).slice(0, size);
4121
4122 JSUtil.defineImmutable(this, {
4123 xprivkey: xprivkey,
4124 network: network,
4125 depth: BufferUtil.integerFromSingleByteBuffer(arg.depth),
4126 privateKey: privateKey,
4127 publicKey: publicKey,
4128 fingerPrint: fingerPrint
4129 });
4130
4131 this._hdPublicKey = null;
4132
4133 Object.defineProperty(this, 'hdPublicKey', {
4134 configurable: false,
4135 enumerable: true,
4136 get: function() {
4137 this._calcHDPublicKey();
4138 return this._hdPublicKey;
4139 }
4140 });
4141 Object.defineProperty(this, 'xpubkey', {
4142 configurable: false,
4143 enumerable: true,
4144 get: function() {
4145 this._calcHDPublicKey();
4146 return this._hdPublicKey.xpubkey;
4147 }
4148 });
4149 return this;
4150};
4151
4152HDPrivateKey._validateBufferArguments = function(arg) {
4153 var checkBuffer = function(name, size) {
4154 var buff = arg[name];
4155 assert(BufferUtil.isBuffer(buff), name + ' argument is not a buffer');
4156 assert(
4157 buff.length === size,
4158 name + ' has not the expected size: found ' + buff.length + ', expected ' + size
4159 );
4160 };
4161 checkBuffer('version', HDPrivateKey.VersionSize);
4162 checkBuffer('depth', HDPrivateKey.DepthSize);
4163 checkBuffer('parentFingerPrint', HDPrivateKey.ParentFingerPrintSize);
4164 checkBuffer('childIndex', HDPrivateKey.ChildIndexSize);
4165 checkBuffer('chainCode', HDPrivateKey.ChainCodeSize);
4166 checkBuffer('privateKey', HDPrivateKey.PrivateKeySize);
4167 if (arg.checksum && arg.checksum.length) {
4168 checkBuffer('checksum', HDPrivateKey.CheckSumSize);
4169 }
4170};
4171
4172/**
4173 * Returns the string representation of this private key (a string starting
4174 * with "xprv..."
4175 *
4176 * @return string
4177 */
4178HDPrivateKey.prototype.toString = function() {
4179 return this.xprivkey;
4180};
4181
4182/**
4183 * Returns the console representation of this extended private key.
4184 * @return string
4185 */
4186HDPrivateKey.prototype.inspect = function() {
4187 return '<HDPrivateKey: ' + this.xprivkey + '>';
4188};
4189
4190/**
4191 * Returns a plain object with a representation of this private key.
4192 *
4193 * Fields include:<ul>
4194 * <li> network: either 'livenet' or 'testnet'
4195 * <li> depth: a number ranging from 0 to 255
4196 * <li> fingerPrint: a number ranging from 0 to 2^32-1, taken from the hash of the
4197 * <li> associated public key
4198 * <li> parentFingerPrint: a number ranging from 0 to 2^32-1, taken from the hash
4199 * <li> of this parent's associated public key or zero.
4200 * <li> childIndex: the index from which this child was derived (or zero)
4201 * <li> chainCode: an hexa string representing a number used in the derivation
4202 * <li> privateKey: the private key associated, in hexa representation
4203 * <li> xprivkey: the representation of this extended private key in checksum
4204 * <li> base58 format
4205 * <li> checksum: the base58 checksum of xprivkey
4206 * </ul>
4207 * @return {Object}
4208 */
4209HDPrivateKey.prototype.toObject = HDPrivateKey.prototype.toJSON = function toObject() {
4210 return {
4211 network: Network.get(BufferUtil.integerFromBuffer(this._buffers.version), 'xprivkey').name,
4212 depth: BufferUtil.integerFromSingleByteBuffer(this._buffers.depth),
4213 fingerPrint: BufferUtil.integerFromBuffer(this.fingerPrint),
4214 parentFingerPrint: BufferUtil.integerFromBuffer(this._buffers.parentFingerPrint),
4215 childIndex: BufferUtil.integerFromBuffer(this._buffers.childIndex),
4216 chainCode: BufferUtil.bufferToHex(this._buffers.chainCode),
4217 privateKey: this.privateKey.toBuffer().toString('hex'),
4218 checksum: BufferUtil.integerFromBuffer(this._buffers.checksum),
4219 xprivkey: this.xprivkey
4220 };
4221};
4222
4223/**
4224 * Build a HDPrivateKey from a buffer
4225 *
4226 * @param {Buffer} arg
4227 * @return {HDPrivateKey}
4228 */
4229HDPrivateKey.fromBuffer = function(arg) {
4230 return new HDPrivateKey(arg.toString());
4231};
4232
4233/**
4234 * Returns a buffer representation of the HDPrivateKey
4235 *
4236 * @return {string}
4237 */
4238HDPrivateKey.prototype.toBuffer = function() {
4239 return BufferUtil.copy(this._buffers.xprivkey);
4240};
4241
4242HDPrivateKey.DefaultDepth = 0;
4243HDPrivateKey.DefaultFingerprint = 0;
4244HDPrivateKey.DefaultChildIndex = 0;
4245HDPrivateKey.Hardened = 0x80000000;
4246HDPrivateKey.MaxIndex = 2 * HDPrivateKey.Hardened;
4247
4248HDPrivateKey.RootElementAlias = ['m', 'M', 'm\'', 'M\''];
4249
4250HDPrivateKey.VersionSize = 4;
4251HDPrivateKey.DepthSize = 1;
4252HDPrivateKey.ParentFingerPrintSize = 4;
4253HDPrivateKey.ChildIndexSize = 4;
4254HDPrivateKey.ChainCodeSize = 32;
4255HDPrivateKey.PrivateKeySize = 32;
4256HDPrivateKey.CheckSumSize = 4;
4257
4258HDPrivateKey.DataLength = 78;
4259HDPrivateKey.SerializedByteSize = 82;
4260
4261HDPrivateKey.VersionStart = 0;
4262HDPrivateKey.VersionEnd = HDPrivateKey.VersionStart + HDPrivateKey.VersionSize;
4263HDPrivateKey.DepthStart = HDPrivateKey.VersionEnd;
4264HDPrivateKey.DepthEnd = HDPrivateKey.DepthStart + HDPrivateKey.DepthSize;
4265HDPrivateKey.ParentFingerPrintStart = HDPrivateKey.DepthEnd;
4266HDPrivateKey.ParentFingerPrintEnd = HDPrivateKey.ParentFingerPrintStart + HDPrivateKey.ParentFingerPrintSize;
4267HDPrivateKey.ChildIndexStart = HDPrivateKey.ParentFingerPrintEnd;
4268HDPrivateKey.ChildIndexEnd = HDPrivateKey.ChildIndexStart + HDPrivateKey.ChildIndexSize;
4269HDPrivateKey.ChainCodeStart = HDPrivateKey.ChildIndexEnd;
4270HDPrivateKey.ChainCodeEnd = HDPrivateKey.ChainCodeStart + HDPrivateKey.ChainCodeSize;
4271HDPrivateKey.PrivateKeyStart = HDPrivateKey.ChainCodeEnd + 1;
4272HDPrivateKey.PrivateKeyEnd = HDPrivateKey.PrivateKeyStart + HDPrivateKey.PrivateKeySize;
4273HDPrivateKey.ChecksumStart = HDPrivateKey.PrivateKeyEnd;
4274HDPrivateKey.ChecksumEnd = HDPrivateKey.ChecksumStart + HDPrivateKey.CheckSumSize;
4275
4276assert(HDPrivateKey.ChecksumEnd === HDPrivateKey.SerializedByteSize);
4277
4278module.exports = HDPrivateKey;
4279
4280}).call(this)}).call(this,require("buffer").Buffer)
4281},{"./crypto/bn":6,"./crypto/hash":8,"./crypto/point":9,"./crypto/random":10,"./encoding/base58":12,"./encoding/base58check":13,"./errors":18,"./hdpublickey":21,"./networks":23,"./privatekey":25,"./util/buffer":45,"./util/js":46,"./util/preconditions":47,"assert":62,"buffer":132,"lodash":210}],21:[function(require,module,exports){
4282(function (Buffer){(function (){
4283'use strict';
4284
4285var _ = require('lodash');
4286var $ = require('./util/preconditions');
4287
4288var BN = require('./crypto/bn');
4289var Base58 = require('./encoding/base58');
4290var Base58Check = require('./encoding/base58check');
4291var Hash = require('./crypto/hash');
4292var HDPrivateKey = require('./hdprivatekey');
4293var Network = require('./networks');
4294var Point = require('./crypto/point');
4295var PublicKey = require('./publickey');
4296
4297var bitcoreErrors = require('./errors');
4298var errors = bitcoreErrors;
4299var hdErrors = bitcoreErrors.HDPublicKey;
4300var assert = require('assert');
4301
4302var JSUtil = require('./util/js');
4303var BufferUtil = require('./util/buffer');
4304
4305/**
4306 * The representation of an hierarchically derived public key.
4307 *
4308 * See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki
4309 *
4310 * @constructor
4311 * @param {Object|string|Buffer} arg
4312 */
4313function HDPublicKey(arg) {
4314 /* jshint maxcomplexity: 12 */
4315 /* jshint maxstatements: 20 */
4316 if (arg instanceof HDPublicKey) {
4317 return arg;
4318 }
4319 if (!(this instanceof HDPublicKey)) {
4320 return new HDPublicKey(arg);
4321 }
4322 if (arg) {
4323 if (_.isString(arg) || BufferUtil.isBuffer(arg)) {
4324 var error = HDPublicKey.getSerializedError(arg);
4325 if (!error) {
4326 return this._buildFromSerialized(arg);
4327 } else if (BufferUtil.isBuffer(arg) && !HDPublicKey.getSerializedError(arg.toString())) {
4328 return this._buildFromSerialized(arg.toString());
4329 } else {
4330 if (error instanceof hdErrors.ArgumentIsPrivateExtended) {
4331 return new HDPrivateKey(arg).hdPublicKey;
4332 }
4333 throw error;
4334 }
4335 } else {
4336 if (_.isObject(arg)) {
4337 if (arg instanceof HDPrivateKey) {
4338 return this._buildFromPrivate(arg);
4339 } else {
4340 return this._buildFromObject(arg);
4341 }
4342 } else {
4343 throw new hdErrors.UnrecognizedArgument(arg);
4344 }
4345 }
4346 } else {
4347 throw new hdErrors.MustSupplyArgument();
4348 }
4349}
4350
4351/**
4352 * Verifies that a given path is valid.
4353 *
4354 * @param {string|number} arg
4355 * @return {boolean}
4356 */
4357HDPublicKey.isValidPath = function(arg) {
4358 if (_.isString(arg)) {
4359 var indexes = HDPrivateKey._getDerivationIndexes(arg);
4360 return indexes !== null && _.every(indexes, HDPublicKey.isValidPath);
4361 }
4362
4363 if (_.isNumber(arg)) {
4364 return arg >= 0 && arg < HDPublicKey.Hardened;
4365 }
4366
4367 return false;
4368};
4369
4370/**
4371 * WARNING: This method is deprecated. Use deriveChild instead.
4372 *
4373 *
4374 * Get a derivated child based on a string or number.
4375 *
4376 * If the first argument is a string, it's parsed as the full path of
4377 * derivation. Valid values for this argument include "m" (which returns the
4378 * same public key), "m/0/1/40/2/1000".
4379 *
4380 * Note that hardened keys can't be derived from a public extended key.
4381 *
4382 * If the first argument is a number, the child with that index will be
4383 * derived. See the example usage for clarification.
4384 *
4385 * @example
4386 * ```javascript
4387 * var parent = new HDPublicKey('xpub...');
4388 * var child_0_1_2 = parent.derive(0).derive(1).derive(2);
4389 * var copy_of_child_0_1_2 = parent.derive("m/0/1/2");
4390 * assert(child_0_1_2.xprivkey === copy_of_child_0_1_2);
4391 * ```
4392 *
4393 * @param {string|number} arg
4394 */
4395HDPublicKey.prototype.derive = function(arg, hardened) {
4396 return this.deriveChild(arg, hardened);
4397};
4398
4399/**
4400 * WARNING: This method will not be officially supported until v1.0.0.
4401 *
4402 *
4403 * Get a derivated child based on a string or number.
4404 *
4405 * If the first argument is a string, it's parsed as the full path of
4406 * derivation. Valid values for this argument include "m" (which returns the
4407 * same public key), "m/0/1/40/2/1000".
4408 *
4409 * Note that hardened keys can't be derived from a public extended key.
4410 *
4411 * If the first argument is a number, the child with that index will be
4412 * derived. See the example usage for clarification.
4413 *
4414 * @example
4415 * ```javascript
4416 * var parent = new HDPublicKey('xpub...');
4417 * var child_0_1_2 = parent.deriveChild(0).deriveChild(1).deriveChild(2);
4418 * var copy_of_child_0_1_2 = parent.deriveChild("m/0/1/2");
4419 * assert(child_0_1_2.xprivkey === copy_of_child_0_1_2);
4420 * ```
4421 *
4422 * @param {string|number} arg
4423 */
4424HDPublicKey.prototype.deriveChild = function(arg, hardened) {
4425 if (_.isNumber(arg)) {
4426 return this._deriveWithNumber(arg, hardened);
4427 } else if (_.isString(arg)) {
4428 return this._deriveFromString(arg);
4429 } else {
4430 throw new hdErrors.InvalidDerivationArgument(arg);
4431 }
4432};
4433
4434HDPublicKey.prototype._deriveWithNumber = function(index, hardened) {
4435 if (index >= HDPublicKey.Hardened || hardened) {
4436 throw new hdErrors.InvalidIndexCantDeriveHardened();
4437 }
4438 if (index < 0) {
4439 throw new hdErrors.InvalidPath(index);
4440 }
4441
4442 var indexBuffer = BufferUtil.integerAsBuffer(index);
4443 var data = BufferUtil.concat([this.publicKey.toBuffer(), indexBuffer]);
4444 var hash = Hash.sha512hmac(data, this._buffers.chainCode);
4445 var leftPart = BN.fromBuffer(hash.slice(0, 32), {size: 32});
4446 var chainCode = hash.slice(32, 64);
4447
4448 var publicKey;
4449 try {
4450 publicKey = PublicKey.fromPoint(Point.getG().mul(leftPart).add(this.publicKey.point));
4451 } catch (e) {
4452 return this._deriveWithNumber(index + 1);
4453 }
4454
4455 var derived = new HDPublicKey({
4456 network: this.network,
4457 depth: this.depth + 1,
4458 parentFingerPrint: this.fingerPrint,
4459 childIndex: index,
4460 chainCode: chainCode,
4461 publicKey: publicKey
4462 });
4463
4464 return derived;
4465};
4466
4467HDPublicKey.prototype._deriveFromString = function(path) {
4468 /* jshint maxcomplexity: 8 */
4469 if (_.includes(path, "'")) {
4470 throw new hdErrors.InvalidIndexCantDeriveHardened();
4471 } else if (!HDPublicKey.isValidPath(path)) {
4472 throw new hdErrors.InvalidPath(path);
4473 }
4474
4475 var indexes = HDPrivateKey._getDerivationIndexes(path);
4476 var derived = indexes.reduce(function(prev, index) {
4477 return prev._deriveWithNumber(index);
4478 }, this);
4479
4480 return derived;
4481};
4482
4483/**
4484 * Verifies that a given serialized public key in base58 with checksum format
4485 * is valid.
4486 *
4487 * @param {string|Buffer} data - the serialized public key
4488 * @param {string|Network=} network - optional, if present, checks that the
4489 * network provided matches the network serialized.
4490 * @return {boolean}
4491 */
4492HDPublicKey.isValidSerialized = function(data, network) {
4493 return _.isNull(HDPublicKey.getSerializedError(data, network));
4494};
4495
4496/**
4497 * Checks what's the error that causes the validation of a serialized public key
4498 * in base58 with checksum to fail.
4499 *
4500 * @param {string|Buffer} data - the serialized public key
4501 * @param {string|Network=} network - optional, if present, checks that the
4502 * network provided matches the network serialized.
4503 * @return {errors|null}
4504 */
4505HDPublicKey.getSerializedError = function(data, network) {
4506 /* jshint maxcomplexity: 10 */
4507 /* jshint maxstatements: 20 */
4508 if (!(_.isString(data) || BufferUtil.isBuffer(data))) {
4509 return new hdErrors.UnrecognizedArgument('expected buffer or string');
4510 }
4511 if (!Base58.validCharacters(data)) {
4512 return new errors.InvalidB58Char('(unknown)', data);
4513 }
4514 try {
4515 data = Base58Check.decode(data);
4516 } catch (e) {
4517 return new errors.InvalidB58Checksum(data);
4518 }
4519 if (data.length !== HDPublicKey.DataSize) {
4520 return new hdErrors.InvalidLength(data);
4521 }
4522 if (!_.isUndefined(network)) {
4523 var error = HDPublicKey._validateNetwork(data, network);
4524 if (error) {
4525 return error;
4526 }
4527 }
4528 var version = BufferUtil.integerFromBuffer(data.slice(0, 4));
4529 if (version === Network.livenet.xprivkey || version === Network.testnet.xprivkey ) {
4530 return new hdErrors.ArgumentIsPrivateExtended();
4531 }
4532 return null;
4533};
4534
4535HDPublicKey._validateNetwork = function(data, networkArg) {
4536 var network = Network.get(networkArg);
4537 if (!network) {
4538 return new errors.InvalidNetworkArgument(networkArg);
4539 }
4540 var version = data.slice(HDPublicKey.VersionStart, HDPublicKey.VersionEnd);
4541 if (BufferUtil.integerFromBuffer(version) !== network.xpubkey) {
4542 return new errors.InvalidNetwork(version);
4543 }
4544 return null;
4545};
4546
4547HDPublicKey.prototype._buildFromPrivate = function (arg) {
4548 var args = _.clone(arg._buffers);
4549 var point = Point.getG().mul(BN.fromBuffer(args.privateKey));
4550 args.publicKey = Point.pointToCompressed(point);
4551 args.version = BufferUtil.integerAsBuffer(Network.get(BufferUtil.integerFromBuffer(args.version)).xpubkey);
4552 args.privateKey = undefined;
4553 args.checksum = undefined;
4554 args.xprivkey = undefined;
4555 return this._buildFromBuffers(args);
4556};
4557
4558HDPublicKey.prototype._buildFromObject = function(arg) {
4559 /* jshint maxcomplexity: 10 */
4560 // TODO: Type validation
4561 var buffers = {
4562 version: arg.network ? BufferUtil.integerAsBuffer(Network.get(arg.network).xpubkey) : arg.version,
4563 depth: _.isNumber(arg.depth) ? BufferUtil.integerAsSingleByteBuffer(arg.depth) : arg.depth,
4564 parentFingerPrint: _.isNumber(arg.parentFingerPrint) ? BufferUtil.integerAsBuffer(arg.parentFingerPrint) : arg.parentFingerPrint,
4565 childIndex: _.isNumber(arg.childIndex) ? BufferUtil.integerAsBuffer(arg.childIndex) : arg.childIndex,
4566 chainCode: _.isString(arg.chainCode) ? Buffer.from(arg.chainCode,'hex') : arg.chainCode,
4567 publicKey: _.isString(arg.publicKey) ? Buffer.from(arg.publicKey,'hex') :
4568 BufferUtil.isBuffer(arg.publicKey) ? arg.publicKey : arg.publicKey.toBuffer(),
4569 checksum: _.isNumber(arg.checksum) ? BufferUtil.integerAsBuffer(arg.checksum) : arg.checksum
4570 };
4571 return this._buildFromBuffers(buffers);
4572};
4573
4574HDPublicKey.prototype._buildFromSerialized = function(arg) {
4575 var decoded = Base58Check.decode(arg);
4576 var buffers = {
4577 version: decoded.slice(HDPublicKey.VersionStart, HDPublicKey.VersionEnd),
4578 depth: decoded.slice(HDPublicKey.DepthStart, HDPublicKey.DepthEnd),
4579 parentFingerPrint: decoded.slice(HDPublicKey.ParentFingerPrintStart,
4580 HDPublicKey.ParentFingerPrintEnd),
4581 childIndex: decoded.slice(HDPublicKey.ChildIndexStart, HDPublicKey.ChildIndexEnd),
4582 chainCode: decoded.slice(HDPublicKey.ChainCodeStart, HDPublicKey.ChainCodeEnd),
4583 publicKey: decoded.slice(HDPublicKey.PublicKeyStart, HDPublicKey.PublicKeyEnd),
4584 checksum: decoded.slice(HDPublicKey.ChecksumStart, HDPublicKey.ChecksumEnd),
4585 xpubkey: arg
4586 };
4587 return this._buildFromBuffers(buffers);
4588};
4589
4590/**
4591 * Receives a object with buffers in all the properties and populates the
4592 * internal structure
4593 *
4594 * @param {Object} arg
4595 * @param {buffer.Buffer} arg.version
4596 * @param {buffer.Buffer} arg.depth
4597 * @param {buffer.Buffer} arg.parentFingerPrint
4598 * @param {buffer.Buffer} arg.childIndex
4599 * @param {buffer.Buffer} arg.chainCode
4600 * @param {buffer.Buffer} arg.publicKey
4601 * @param {buffer.Buffer} arg.checksum
4602 * @param {string=} arg.xpubkey - if set, don't recalculate the base58
4603 * representation
4604 * @return {HDPublicKey} this
4605 */
4606HDPublicKey.prototype._buildFromBuffers = function(arg) {
4607 /* jshint maxcomplexity: 8 */
4608 /* jshint maxstatements: 20 */
4609
4610 HDPublicKey._validateBufferArguments(arg);
4611
4612 JSUtil.defineImmutable(this, {
4613 _buffers: arg
4614 });
4615
4616 var sequence = [
4617 arg.version, arg.depth, arg.parentFingerPrint, arg.childIndex, arg.chainCode,
4618 arg.publicKey
4619 ];
4620 var concat = BufferUtil.concat(sequence);
4621 var checksum = Base58Check.checksum(concat);
4622 if (!arg.checksum || !arg.checksum.length) {
4623 arg.checksum = checksum;
4624 } else {
4625 if (arg.checksum.toString('hex') !== checksum.toString('hex')) {
4626 throw new errors.InvalidB58Checksum(concat, checksum);
4627 }
4628 }
4629 var network = Network.get(BufferUtil.integerFromBuffer(arg.version));
4630
4631 var xpubkey;
4632 xpubkey = Base58Check.encode(BufferUtil.concat(sequence));
4633 arg.xpubkey = Buffer.from(xpubkey);
4634
4635 var publicKey = new PublicKey(arg.publicKey, {network: network});
4636 var size = HDPublicKey.ParentFingerPrintSize;
4637 var fingerPrint = Hash.sha256ripemd160(publicKey.toBuffer()).slice(0, size);
4638
4639 JSUtil.defineImmutable(this, {
4640 xpubkey: xpubkey,
4641 network: network,
4642 depth: BufferUtil.integerFromSingleByteBuffer(arg.depth),
4643 publicKey: publicKey,
4644 fingerPrint: fingerPrint
4645 });
4646
4647 return this;
4648};
4649
4650HDPublicKey._validateBufferArguments = function(arg) {
4651 var checkBuffer = function(name, size) {
4652 var buff = arg[name];
4653 assert(BufferUtil.isBuffer(buff), name + ' argument is not a buffer, it\'s ' + typeof buff);
4654 assert(
4655 buff.length === size,
4656 name + ' has not the expected size: found ' + buff.length + ', expected ' + size
4657 );
4658 };
4659 checkBuffer('version', HDPublicKey.VersionSize);
4660 checkBuffer('depth', HDPublicKey.DepthSize);
4661 checkBuffer('parentFingerPrint', HDPublicKey.ParentFingerPrintSize);
4662 checkBuffer('childIndex', HDPublicKey.ChildIndexSize);
4663 checkBuffer('chainCode', HDPublicKey.ChainCodeSize);
4664 checkBuffer('publicKey', HDPublicKey.PublicKeySize);
4665 if (arg.checksum && arg.checksum.length) {
4666 checkBuffer('checksum', HDPublicKey.CheckSumSize);
4667 }
4668};
4669
4670HDPublicKey.fromString = function(arg) {
4671 $.checkArgument(_.isString(arg), 'No valid string was provided');
4672 return new HDPublicKey(arg);
4673};
4674
4675HDPublicKey.fromObject = function(arg) {
4676 $.checkArgument(_.isObject(arg), 'No valid argument was provided');
4677 return new HDPublicKey(arg);
4678};
4679
4680/**
4681 * Returns the base58 checked representation of the public key
4682 * @return {string} a string starting with "xpub..." in livenet
4683 */
4684HDPublicKey.prototype.toString = function() {
4685 return this.xpubkey;
4686};
4687
4688/**
4689 * Returns the console representation of this extended public key.
4690 * @return string
4691 */
4692HDPublicKey.prototype.inspect = function() {
4693 return '<HDPublicKey: ' + this.xpubkey + '>';
4694};
4695
4696/**
4697 * Returns a plain JavaScript object with information to reconstruct a key.
4698 *
4699 * Fields are: <ul>
4700 * <li> network: 'livenet' or 'testnet'
4701 * <li> depth: a number from 0 to 255, the depth to the master extended key
4702 * <li> fingerPrint: a number of 32 bits taken from the hash of the public key
4703 * <li> fingerPrint: a number of 32 bits taken from the hash of this key's
4704 * <li> parent's public key
4705 * <li> childIndex: index with which this key was derived
4706 * <li> chainCode: string in hexa encoding used for derivation
4707 * <li> publicKey: string, hexa encoded, in compressed key format
4708 * <li> checksum: BufferUtil.integerFromBuffer(this._buffers.checksum),
4709 * <li> xpubkey: the string with the base58 representation of this extended key
4710 * <li> checksum: the base58 checksum of xpubkey
4711 * </ul>
4712 */
4713HDPublicKey.prototype.toObject = HDPublicKey.prototype.toJSON = function toObject() {
4714 return {
4715 network: Network.get(BufferUtil.integerFromBuffer(this._buffers.version)).name,
4716 depth: BufferUtil.integerFromSingleByteBuffer(this._buffers.depth),
4717 fingerPrint: BufferUtil.integerFromBuffer(this.fingerPrint),
4718 parentFingerPrint: BufferUtil.integerFromBuffer(this._buffers.parentFingerPrint),
4719 childIndex: BufferUtil.integerFromBuffer(this._buffers.childIndex),
4720 chainCode: BufferUtil.bufferToHex(this._buffers.chainCode),
4721 publicKey: this.publicKey.toString(),
4722 checksum: BufferUtil.integerFromBuffer(this._buffers.checksum),
4723 xpubkey: this.xpubkey
4724 };
4725};
4726
4727/**
4728 * Create a HDPublicKey from a buffer argument
4729 *
4730 * @param {Buffer} arg
4731 * @return {HDPublicKey}
4732 */
4733HDPublicKey.fromBuffer = function(arg) {
4734 return new HDPublicKey(arg);
4735};
4736
4737/**
4738 * Return a buffer representation of the xpubkey
4739 *
4740 * @return {Buffer}
4741 */
4742HDPublicKey.prototype.toBuffer = function() {
4743 return BufferUtil.copy(this._buffers.xpubkey);
4744};
4745
4746HDPublicKey.Hardened = 0x80000000;
4747HDPublicKey.RootElementAlias = ['m', 'M'];
4748
4749HDPublicKey.VersionSize = 4;
4750HDPublicKey.DepthSize = 1;
4751HDPublicKey.ParentFingerPrintSize = 4;
4752HDPublicKey.ChildIndexSize = 4;
4753HDPublicKey.ChainCodeSize = 32;
4754HDPublicKey.PublicKeySize = 33;
4755HDPublicKey.CheckSumSize = 4;
4756
4757HDPublicKey.DataSize = 78;
4758HDPublicKey.SerializedByteSize = 82;
4759
4760HDPublicKey.VersionStart = 0;
4761HDPublicKey.VersionEnd = HDPublicKey.VersionStart + HDPublicKey.VersionSize;
4762HDPublicKey.DepthStart = HDPublicKey.VersionEnd;
4763HDPublicKey.DepthEnd = HDPublicKey.DepthStart + HDPublicKey.DepthSize;
4764HDPublicKey.ParentFingerPrintStart = HDPublicKey.DepthEnd;
4765HDPublicKey.ParentFingerPrintEnd = HDPublicKey.ParentFingerPrintStart + HDPublicKey.ParentFingerPrintSize;
4766HDPublicKey.ChildIndexStart = HDPublicKey.ParentFingerPrintEnd;
4767HDPublicKey.ChildIndexEnd = HDPublicKey.ChildIndexStart + HDPublicKey.ChildIndexSize;
4768HDPublicKey.ChainCodeStart = HDPublicKey.ChildIndexEnd;
4769HDPublicKey.ChainCodeEnd = HDPublicKey.ChainCodeStart + HDPublicKey.ChainCodeSize;
4770HDPublicKey.PublicKeyStart = HDPublicKey.ChainCodeEnd;
4771HDPublicKey.PublicKeyEnd = HDPublicKey.PublicKeyStart + HDPublicKey.PublicKeySize;
4772HDPublicKey.ChecksumStart = HDPublicKey.PublicKeyEnd;
4773HDPublicKey.ChecksumEnd = HDPublicKey.ChecksumStart + HDPublicKey.CheckSumSize;
4774
4775assert(HDPublicKey.PublicKeyEnd === HDPublicKey.DataSize);
4776assert(HDPublicKey.ChecksumEnd === HDPublicKey.SerializedByteSize);
4777
4778module.exports = HDPublicKey;
4779
4780}).call(this)}).call(this,require("buffer").Buffer)
4781},{"./crypto/bn":6,"./crypto/hash":8,"./crypto/point":9,"./encoding/base58":12,"./encoding/base58check":13,"./errors":18,"./hdprivatekey":20,"./networks":23,"./publickey":26,"./util/buffer":45,"./util/js":46,"./util/preconditions":47,"assert":62,"buffer":132,"lodash":210}],22:[function(require,module,exports){
4782(function (Buffer){(function (){
4783'use strict';
4784
4785var _ = require('lodash');
4786var PrivateKey = require('./privatekey');
4787var PublicKey = require('./publickey');
4788var Address = require('./address');
4789var BufferWriter = require('./encoding/bufferwriter');
4790var ECDSA = require('./crypto/ecdsa');
4791var Signature = require('./crypto/signature');
4792var sha256sha256 = require('./crypto/hash').sha256sha256;
4793var JSUtil = require('./util/js');
4794var $ = require('./util/preconditions');
4795
4796function Message(message) {
4797 if (!(this instanceof Message)) {
4798 return new Message(message);
4799 }
4800 $.checkArgument(_.isString(message), 'First argument should be a string');
4801 this.message = message;
4802
4803 return this;
4804}
4805
4806Message.MAGIC_BYTES = Buffer.from('Bitcoin Signed Message:\n');
4807
4808Message.prototype.magicHash = function magicHash() {
4809 var prefix1 = BufferWriter.varintBufNum(Message.MAGIC_BYTES.length);
4810 var messageBuffer = Buffer.from(this.message);
4811 var prefix2 = BufferWriter.varintBufNum(messageBuffer.length);
4812 var buf = Buffer.concat([prefix1, Message.MAGIC_BYTES, prefix2, messageBuffer]);
4813 var hash = sha256sha256(buf);
4814 return hash;
4815};
4816
4817Message.prototype._sign = function _sign(privateKey) {
4818 $.checkArgument(privateKey instanceof PrivateKey, 'First argument should be an instance of PrivateKey');
4819 var hash = this.magicHash();
4820 var ecdsa = new ECDSA();
4821 ecdsa.hashbuf = hash;
4822 ecdsa.privkey = privateKey;
4823 ecdsa.pubkey = privateKey.toPublicKey();
4824 ecdsa.signRandomK();
4825 ecdsa.calci();
4826 return ecdsa.sig;
4827};
4828
4829/**
4830 * Will sign a message with a given bitcoin private key.
4831 *
4832 * @param {PrivateKey} privateKey - An instance of PrivateKey
4833 * @returns {String} A base64 encoded compact signature
4834 */
4835Message.prototype.sign = function sign(privateKey) {
4836 var signature = this._sign(privateKey);
4837 return signature.toCompact().toString('base64');
4838};
4839
4840Message.prototype._verify = function _verify(publicKey, signature) {
4841 $.checkArgument(publicKey instanceof PublicKey, 'First argument should be an instance of PublicKey');
4842 $.checkArgument(signature instanceof Signature, 'Second argument should be an instance of Signature');
4843 var hash = this.magicHash();
4844 var verified = ECDSA.verify(hash, signature, publicKey);
4845 if (!verified) {
4846 this.error = 'The signature was invalid';
4847 }
4848 return verified;
4849};
4850
4851/**
4852 * Will return a boolean of the signature is valid for a given bitcoin address.
4853 * If it isn't the specific reason is accessible via the "error" member.
4854 *
4855 * @param {Address|String} bitcoinAddress - A bitcoin address
4856 * @param {String} signatureString - A base64 encoded compact signature
4857 * @returns {Boolean}
4858 */
4859Message.prototype.verify = function verify(bitcoinAddress, signatureString) {
4860 $.checkArgument(bitcoinAddress);
4861 $.checkArgument(signatureString && _.isString(signatureString));
4862
4863 if (_.isString(bitcoinAddress)) {
4864 bitcoinAddress = Address.fromString(bitcoinAddress);
4865 }
4866 var signature = Signature.fromCompact(Buffer.from(signatureString, 'base64'));
4867
4868 // recover the public key
4869 var ecdsa = new ECDSA();
4870 ecdsa.hashbuf = this.magicHash();
4871 ecdsa.sig = signature;
4872 var publicKey = ecdsa.toPublicKey();
4873
4874 var signatureAddress = Address.fromPublicKey(publicKey, bitcoinAddress.network);
4875
4876 // check that the recovered address and specified address match
4877 if (bitcoinAddress.toString() !== signatureAddress.toString()) {
4878 this.error = 'The signature did not match the message digest';
4879 return false;
4880 }
4881
4882 return this._verify(publicKey, signature);
4883};
4884
4885/**
4886 * Will return a public key string if the provided signature and the message digest is correct
4887 * If it isn't the specific reason is accessible via the "error" member.
4888 *
4889 * @param {Address|String} bitcoinAddress - A bitcoin address
4890 * @param {String} signatureString - A base64 encoded compact signature
4891 * @returns {String}
4892 */
4893Message.prototype.recoverPublicKey = function recoverPublicKey(bitcoinAddress, signatureString) {
4894 $.checkArgument(bitcoinAddress);
4895 $.checkArgument(signatureString && _.isString(signatureString));
4896
4897 if (_.isString(bitcoinAddress)) {
4898 bitcoinAddress = Address.fromString(bitcoinAddress);
4899 }
4900 var signature = Signature.fromCompact(Buffer.from(signatureString, 'base64'));
4901
4902 // recover the public key
4903 var ecdsa = new ECDSA();
4904 ecdsa.hashbuf = this.magicHash();
4905 ecdsa.sig = signature;
4906 var publicKey = ecdsa.toPublicKey();
4907
4908 var signatureAddress = Address.fromPublicKey(publicKey, bitcoinAddress.network);
4909
4910 // check that the recovered address and specified address match
4911 if (bitcoinAddress.toString() !== signatureAddress.toString()) {
4912 this.error = 'The signature did not match the message digest';
4913 }
4914
4915 return publicKey.toString();
4916};
4917
4918/**
4919 * Instantiate a message from a message string
4920 *
4921 * @param {String} str - A string of the message
4922 * @returns {Message} A new instance of a Message
4923 */
4924Message.fromString = function(str) {
4925 return new Message(str);
4926};
4927
4928/**
4929 * Instantiate a message from JSON
4930 *
4931 * @param {String} json - An JSON string or Object with keys: message
4932 * @returns {Message} A new instance of a Message
4933 */
4934Message.fromJSON = function fromJSON(json) {
4935 if (JSUtil.isValidJSON(json)) {
4936 json = JSON.parse(json);
4937 }
4938 return new Message(json.message);
4939};
4940
4941/**
4942 * @returns {Object} A plain object with the message information
4943 */
4944Message.prototype.toObject = function toObject() {
4945 return {
4946 message: this.message
4947 };
4948};
4949
4950/**
4951 * @returns {String} A JSON representation of the message information
4952 */
4953Message.prototype.toJSON = function toJSON() {
4954 return JSON.stringify(this.toObject());
4955};
4956
4957/**
4958 * Will return a the string representation of the message
4959 *
4960 * @returns {String} Message
4961 */
4962Message.prototype.toString = function() {
4963 return this.message;
4964};
4965
4966/**
4967 * Will return a string formatted for the console
4968 *
4969 * @returns {String} Message
4970 */
4971Message.prototype.inspect = function() {
4972 return '<Message: ' + this.toString() + '>';
4973};
4974
4975module.exports = Message;
4976
4977var Script = require('./script');
4978
4979}).call(this)}).call(this,require("buffer").Buffer)
4980},{"./address":1,"./crypto/ecdsa":7,"./crypto/hash":8,"./crypto/signature":11,"./encoding/bufferwriter":16,"./privatekey":25,"./publickey":26,"./script":27,"./util/js":46,"./util/preconditions":47,"buffer":132,"lodash":210}],23:[function(require,module,exports){
4981'use strict';
4982var _ = require('lodash');
4983
4984var BufferUtil = require('./util/buffer');
4985var JSUtil = require('./util/js');
4986var networks = [];
4987var networkMaps = {};
4988
4989/**
4990 * A network is merely a map containing values that correspond to version
4991 * numbers for each bitcoin network. Currently only supporting "livenet"
4992 * (a.k.a. "mainnet") and "testnet".
4993 * @constructor
4994 */
4995function Network() {}
4996
4997Network.prototype.toString = function toString() {
4998 return this.name;
4999};
5000
5001/**
5002 * @function
5003 * @member Networks#get
5004 * Retrieves the network associated with a magic number or string.
5005 * @param {string|number|Network} arg
5006 * @param {string|Array} keys - if set, only check if the magic number associated with this name matches
5007 * @return Network
5008 */
5009function get(arg, keys) {
5010 if (~networks.indexOf(arg)) {
5011 return arg;
5012 }
5013 if (keys) {
5014 if (!_.isArray(keys)) {
5015 keys = [keys];
5016 }
5017 var containsArg = function(key) {
5018 return networks[index][key] === arg;
5019 };
5020 for (var index in networks) {
5021 if (_.some(keys, containsArg)) {
5022 return networks[index];
5023 }
5024 }
5025 return undefined;
5026 }
5027 if(networkMaps[arg] && networkMaps[arg].length >= 1) {
5028 return networkMaps[arg][0];
5029 } else {
5030 return networkMaps[arg];
5031 }
5032}
5033
5034/**
5035 * @function
5036 * @member Networks#add
5037 * Will add a custom Network
5038 * @param {Object} data
5039 * @param {string} data.name - The name of the network
5040 * @param {string} data.alias - The aliased name of the network
5041 * @param {Number} data.pubkeyhash - The publickey hash prefix
5042 * @param {Number} data.privatekey - The privatekey prefix
5043 * @param {Number} data.scripthash - The scripthash prefix
5044 * @param {string} data.bech32prefix - The native segwit prefix
5045 * @param {Number} data.xpubkey - The extended public key magic
5046 * @param {Number} data.xprivkey - The extended private key magic
5047 * @param {Number} data.networkMagic - The network magic number
5048 * @param {Number} data.port - The network port
5049 * @param {Array} data.dnsSeeds - An array of dns seeds
5050 * @return Network
5051 */
5052function addNetwork(data) {
5053
5054 var network = new Network();
5055
5056 JSUtil.defineImmutable(network, {
5057 name: data.name,
5058 alias: data.alias,
5059 pubkeyhash: data.pubkeyhash,
5060 privatekey: data.privatekey,
5061 scripthash: data.scripthash,
5062 bech32prefix: data.bech32prefix,
5063 xpubkey: data.xpubkey,
5064 xprivkey: data.xprivkey
5065 });
5066
5067 if (data.networkMagic) {
5068 JSUtil.defineImmutable(network, {
5069 networkMagic: BufferUtil.integerAsBuffer(data.networkMagic)
5070 });
5071 }
5072
5073 if (data.port) {
5074 JSUtil.defineImmutable(network, {
5075 port: data.port
5076 });
5077 }
5078
5079 if (data.dnsSeeds) {
5080 JSUtil.defineImmutable(network, {
5081 dnsSeeds: data.dnsSeeds
5082 });
5083 }
5084 _.each(network, function(value) {
5085 if (!_.isUndefined(value) && !_.isObject(value)) {
5086 if(!networkMaps[value]) {
5087 networkMaps[value] = [];
5088 }
5089 networkMaps[value].push(network);
5090 }
5091 });
5092
5093 networks.push(network);
5094
5095 return network;
5096
5097}
5098
5099/**
5100 * @function
5101 * @member Networks#remove
5102 * Will remove a custom network
5103 * @param {Network} network
5104 */
5105function removeNetwork(network) {
5106 for (var i = 0; i < networks.length; i++) {
5107 if (networks[i] === network) {
5108 networks.splice(i, 1);
5109 }
5110 }
5111 for (var key in networkMaps) {
5112 const index = networkMaps[key].indexOf(network);
5113 if (index >= 0) {
5114 delete networkMaps[key][index];
5115 }
5116 }
5117}
5118
5119addNetwork({
5120 name: 'livenet',
5121 alias: 'mainnet',
5122 pubkeyhash: 0x00,
5123 privatekey: 0x80,
5124 scripthash: 0x05,
5125 bech32prefix: 'bc',
5126 xpubkey: 0x0488b21e,
5127 xprivkey: 0x0488ade4,
5128 networkMagic: 0xf9beb4d9,
5129 port: 8333,
5130 dnsSeeds: [
5131 'seed.bitcoin.sipa.be',
5132 'dnsseed.bluematt.me',
5133 'dnsseed.bitcoin.dashjr.org',
5134 'seed.bitcoinstats.com',
5135 'seed.bitnodes.io',
5136 'bitseed.xf2.org'
5137 ]
5138});
5139
5140/**
5141 * @instance
5142 * @member Networks#livenet
5143 */
5144var livenet = get('livenet');
5145
5146addNetwork({
5147 name: 'testnet',
5148 alias: 'test',
5149 pubkeyhash: 0x6f,
5150 privatekey: 0xef,
5151 scripthash: 0xc4,
5152 bech32prefix: 'tb',
5153 xpubkey: 0x043587cf,
5154 xprivkey: 0x04358394,
5155 networkMagic: 0x0b110907,
5156 port: 18333,
5157 dnsSeeds: [
5158 'testnet-seed.bitcoin.petertodd.org',
5159 'testnet-seed.bluematt.me',
5160 'testnet-seed.alexykot.me',
5161 'testnet-seed.bitcoin.schildbach.de'
5162 ]
5163});
5164
5165/**
5166 * @instance
5167 * @member Networks#testnet
5168 */
5169var testnet = get('testnet');
5170
5171addNetwork({
5172 name: 'regtest',
5173 alias: 'dev',
5174 pubkeyhash: 0x6f,
5175 privatekey: 0xef,
5176 scripthash: 0xc4,
5177 bech32prefix: 'bcrt',
5178 xpubkey: 0x043587cf,
5179 xprivkey: 0x04358394,
5180 networkMagic: 0xfabfb5da,
5181 port: 18444,
5182 dnsSeeds: []
5183});
5184
5185/**
5186 * @instance
5187 * @member Networks#testnet
5188 */
5189var regtest = get('regtest');
5190
5191/**
5192 * @function
5193 * @deprecated
5194 * @member Networks#enableRegtest
5195 * Will enable regtest features for testnet
5196 */
5197function enableRegtest() {
5198 testnet.regtestEnabled = true;
5199}
5200
5201/**
5202 * @function
5203 * @deprecated
5204 * @member Networks#disableRegtest
5205 * Will disable regtest features for testnet
5206 */
5207function disableRegtest() {
5208 testnet.regtestEnabled = false;
5209}
5210
5211/**
5212 * @namespace Networks
5213 */
5214module.exports = {
5215 add: addNetwork,
5216 remove: removeNetwork,
5217 defaultNetwork: livenet,
5218 livenet: livenet,
5219 mainnet: livenet,
5220 testnet: testnet,
5221 regtest: regtest,
5222 get: get,
5223 enableRegtest: enableRegtest,
5224 disableRegtest: disableRegtest
5225};
5226
5227},{"./util/buffer":45,"./util/js":46,"lodash":210}],24:[function(require,module,exports){
5228(function (Buffer){(function (){
5229'use strict';
5230
5231var _ = require('lodash');
5232var $ = require('./util/preconditions');
5233var BufferUtil = require('./util/buffer');
5234var JSUtil = require('./util/js');
5235
5236function Opcode(num) {
5237 if (!(this instanceof Opcode)) {
5238 return new Opcode(num);
5239 }
5240
5241 var value;
5242
5243 if (_.isNumber(num)) {
5244 value = num;
5245 } else if (_.isString(num)) {
5246 value = Opcode.map[num];
5247 } else {
5248 throw new TypeError('Unrecognized num type: "' + typeof(num) + '" for Opcode');
5249 }
5250
5251 JSUtil.defineImmutable(this, {
5252 num: value
5253 });
5254
5255 return this;
5256}
5257
5258Opcode.fromBuffer = function(buf) {
5259 $.checkArgument(BufferUtil.isBuffer(buf));
5260 return new Opcode(Number('0x' + buf.toString('hex')));
5261};
5262
5263Opcode.fromNumber = function(num) {
5264 $.checkArgument(_.isNumber(num));
5265 return new Opcode(num);
5266};
5267
5268Opcode.fromString = function(str) {
5269 $.checkArgument(_.isString(str));
5270 var value = Opcode.map[str];
5271 if (typeof value === 'undefined') {
5272 throw new TypeError('Invalid opcodestr');
5273 }
5274 return new Opcode(value);
5275};
5276
5277Opcode.prototype.toHex = function() {
5278 return this.num.toString(16);
5279};
5280
5281Opcode.prototype.toBuffer = function() {
5282 return Buffer.from(this.toHex(), 'hex');
5283};
5284
5285Opcode.prototype.toNumber = function() {
5286 return this.num;
5287};
5288
5289Opcode.prototype.toString = function() {
5290 var str = Opcode.reverseMap[this.num];
5291 if (typeof str === 'undefined') {
5292 throw new Error('Opcode does not have a string representation');
5293 }
5294 return str;
5295};
5296
5297Opcode.smallInt = function(n) {
5298 $.checkArgument(_.isNumber(n), 'Invalid Argument: n should be number');
5299 $.checkArgument(n >= 0 && n <= 16, 'Invalid Argument: n must be between 0 and 16');
5300 if (n === 0) {
5301 return Opcode('OP_0');
5302 }
5303 return new Opcode(Opcode.map.OP_1 + n - 1);
5304};
5305
5306Opcode.map = {
5307 // push value
5308 OP_FALSE: 0,
5309 OP_0: 0,
5310 OP_PUSHDATA1: 76,
5311 OP_PUSHDATA2: 77,
5312 OP_PUSHDATA4: 78,
5313 OP_1NEGATE: 79,
5314 OP_RESERVED: 80,
5315 OP_TRUE: 81,
5316 OP_1: 81,
5317 OP_2: 82,
5318 OP_3: 83,
5319 OP_4: 84,
5320 OP_5: 85,
5321 OP_6: 86,
5322 OP_7: 87,
5323 OP_8: 88,
5324 OP_9: 89,
5325 OP_10: 90,
5326 OP_11: 91,
5327 OP_12: 92,
5328 OP_13: 93,
5329 OP_14: 94,
5330 OP_15: 95,
5331 OP_16: 96,
5332
5333 // control
5334 OP_NOP: 97,
5335 OP_VER: 98,
5336 OP_IF: 99,
5337 OP_NOTIF: 100,
5338 OP_VERIF: 101,
5339 OP_VERNOTIF: 102,
5340 OP_ELSE: 103,
5341 OP_ENDIF: 104,
5342 OP_VERIFY: 105,
5343 OP_RETURN: 106,
5344
5345 // stack ops
5346 OP_TOALTSTACK: 107,
5347 OP_FROMALTSTACK: 108,
5348 OP_2DROP: 109,
5349 OP_2DUP: 110,
5350 OP_3DUP: 111,
5351 OP_2OVER: 112,
5352 OP_2ROT: 113,
5353 OP_2SWAP: 114,
5354 OP_IFDUP: 115,
5355 OP_DEPTH: 116,
5356 OP_DROP: 117,
5357 OP_DUP: 118,
5358 OP_NIP: 119,
5359 OP_OVER: 120,
5360 OP_PICK: 121,
5361 OP_ROLL: 122,
5362 OP_ROT: 123,
5363 OP_SWAP: 124,
5364 OP_TUCK: 125,
5365
5366 // splice ops
5367 OP_CAT: 126,
5368 OP_SUBSTR: 127,
5369 OP_LEFT: 128,
5370 OP_RIGHT: 129,
5371 OP_SIZE: 130,
5372
5373 // bit logic
5374 OP_INVERT: 131,
5375 OP_AND: 132,
5376 OP_OR: 133,
5377 OP_XOR: 134,
5378 OP_EQUAL: 135,
5379 OP_EQUALVERIFY: 136,
5380 OP_RESERVED1: 137,
5381 OP_RESERVED2: 138,
5382
5383 // numeric
5384 OP_1ADD: 139,
5385 OP_1SUB: 140,
5386 OP_2MUL: 141,
5387 OP_2DIV: 142,
5388 OP_NEGATE: 143,
5389 OP_ABS: 144,
5390 OP_NOT: 145,
5391 OP_0NOTEQUAL: 146,
5392
5393 OP_ADD: 147,
5394 OP_SUB: 148,
5395 OP_MUL: 149,
5396 OP_DIV: 150,
5397 OP_MOD: 151,
5398 OP_LSHIFT: 152,
5399 OP_RSHIFT: 153,
5400
5401 OP_BOOLAND: 154,
5402 OP_BOOLOR: 155,
5403 OP_NUMEQUAL: 156,
5404 OP_NUMEQUALVERIFY: 157,
5405 OP_NUMNOTEQUAL: 158,
5406 OP_LESSTHAN: 159,
5407 OP_GREATERTHAN: 160,
5408 OP_LESSTHANOREQUAL: 161,
5409 OP_GREATERTHANOREQUAL: 162,
5410 OP_MIN: 163,
5411 OP_MAX: 164,
5412
5413 OP_WITHIN: 165,
5414
5415 // crypto
5416 OP_RIPEMD160: 166,
5417 OP_SHA1: 167,
5418 OP_SHA256: 168,
5419 OP_HASH160: 169,
5420 OP_HASH256: 170,
5421 OP_CODESEPARATOR: 171,
5422 OP_CHECKSIG: 172,
5423 OP_CHECKSIGVERIFY: 173,
5424 OP_CHECKMULTISIG: 174,
5425 OP_CHECKMULTISIGVERIFY: 175,
5426
5427 OP_CHECKLOCKTIMEVERIFY: 177,
5428 OP_CHECKSEQUENCEVERIFY: 178,
5429
5430 // expansion
5431 OP_NOP1: 176,
5432 OP_NOP2: 177,
5433 OP_NOP3: 178,
5434 OP_NOP4: 179,
5435 OP_NOP5: 180,
5436 OP_NOP6: 181,
5437 OP_NOP7: 182,
5438 OP_NOP8: 183,
5439 OP_NOP9: 184,
5440 OP_NOP10: 185,
5441
5442 // template matching params
5443 OP_PUBKEYHASH: 253,
5444 OP_PUBKEY: 254,
5445 OP_INVALIDOPCODE: 255
5446};
5447
5448Opcode.reverseMap = [];
5449
5450for (var k in Opcode.map) {
5451 Opcode.reverseMap[Opcode.map[k]] = k;
5452}
5453
5454// Easier access to opcodes
5455_.extend(Opcode, Opcode.map);
5456
5457/**
5458 * @returns true if opcode is one of OP_0, OP_1, ..., OP_16
5459 */
5460Opcode.isSmallIntOp = function(opcode) {
5461 if (opcode instanceof Opcode) {
5462 opcode = opcode.toNumber();
5463 }
5464 return ((opcode === Opcode.map.OP_0) ||
5465 ((opcode >= Opcode.map.OP_1) && (opcode <= Opcode.map.OP_16)));
5466};
5467
5468/**
5469 * Will return a string formatted for the console
5470 *
5471 * @returns {string} Script opcode
5472 */
5473Opcode.prototype.inspect = function() {
5474 return '<Opcode: ' + this.toString() + ', hex: '+this.toHex()+', decimal: '+this.num+'>';
5475};
5476
5477module.exports = Opcode;
5478
5479}).call(this)}).call(this,require("buffer").Buffer)
5480},{"./util/buffer":45,"./util/js":46,"./util/preconditions":47,"buffer":132,"lodash":210}],25:[function(require,module,exports){
5481(function (Buffer){(function (){
5482'use strict';
5483
5484var _ = require('lodash');
5485var Address = require('./address');
5486var Base58Check = require('./encoding/base58check');
5487var BN = require('./crypto/bn');
5488var JSUtil = require('./util/js');
5489var Networks = require('./networks');
5490var Point = require('./crypto/point');
5491var PublicKey = require('./publickey');
5492var Random = require('./crypto/random');
5493var $ = require('./util/preconditions');
5494
5495/**
5496 * Instantiate a PrivateKey from a BN, Buffer and WIF.
5497 *
5498 * @example
5499 * ```javascript
5500 * // generate a new random key
5501 * var key = PrivateKey();
5502 *
5503 * // get the associated address
5504 * var address = key.toAddress();
5505 *
5506 * // encode into wallet export format
5507 * var exported = key.toWIF();
5508 *
5509 * // instantiate from the exported (and saved) private key
5510 * var imported = PrivateKey.fromWIF(exported);
5511 * ```
5512 *
5513 * @param {string} data - The encoded data in various formats
5514 * @param {Network|string=} network - a {@link Network} object, or a string with the network name
5515 * @returns {PrivateKey} A new valid instance of an PrivateKey
5516 * @constructor
5517 */
5518function PrivateKey(data, network) {
5519 /* jshint maxstatements: 20 */
5520 /* jshint maxcomplexity: 8 */
5521
5522 if (!(this instanceof PrivateKey)) {
5523 return new PrivateKey(data, network);
5524 }
5525 if (data instanceof PrivateKey) {
5526 return data;
5527 }
5528
5529 var info = this._classifyArguments(data, network);
5530
5531 // validation
5532 if (!info.bn || info.bn.cmp(new BN(0)) === 0){
5533 throw new TypeError('Number can not be equal to zero, undefined, null or false');
5534 }
5535 if (!info.bn.lt(Point.getN())) {
5536 throw new TypeError('Number must be less than N');
5537 }
5538 if (typeof(info.network) === 'undefined') {
5539 throw new TypeError('Must specify the network ("livenet" or "testnet")');
5540 }
5541
5542 JSUtil.defineImmutable(this, {
5543 bn: info.bn,
5544 compressed: info.compressed,
5545 network: info.network
5546 });
5547
5548 Object.defineProperty(this, 'publicKey', {
5549 configurable: false,
5550 enumerable: true,
5551 get: this.toPublicKey.bind(this)
5552 });
5553
5554 return this;
5555
5556};
5557
5558/**
5559 * Internal helper to instantiate PrivateKey internal `info` object from
5560 * different kinds of arguments passed to the constructor.
5561 *
5562 * @param {*} data
5563 * @param {Network|string=} network - a {@link Network} object, or a string with the network name
5564 * @return {Object}
5565 */
5566PrivateKey.prototype._classifyArguments = function(data, network) {
5567 /* jshint maxcomplexity: 10 */
5568 var info = {
5569 compressed: true,
5570 network: network ? Networks.get(network) : Networks.defaultNetwork
5571 };
5572
5573 // detect type of data
5574 if (_.isUndefined(data) || _.isNull(data)){
5575 info.bn = PrivateKey._getRandomBN();
5576 } else if (data instanceof BN) {
5577 info.bn = data;
5578 } else if (data instanceof Buffer || data instanceof Uint8Array) {
5579 info = PrivateKey._transformBuffer(data, network);
5580 } else if (data.bn && data.network){
5581 info = PrivateKey._transformObject(data);
5582 } else if (!network && Networks.get(data)) {
5583 info.bn = PrivateKey._getRandomBN();
5584 info.network = Networks.get(data);
5585 } else if (typeof(data) === 'string'){
5586 if (JSUtil.isHexa(data)) {
5587 info.bn = new BN(Buffer.from(data, 'hex'));
5588 } else {
5589 info = PrivateKey._transformWIF(data, network);
5590 }
5591 } else {
5592 throw new TypeError('First argument is an unrecognized data type.');
5593 }
5594 return info;
5595};
5596
5597/**
5598 * Internal function to get a random Big Number (BN)
5599 *
5600 * @returns {BN} A new randomly generated BN
5601 * @private
5602 */
5603PrivateKey._getRandomBN = function(){
5604 var condition;
5605 var bn;
5606 do {
5607 var privbuf = Random.getRandomBuffer(32);
5608 bn = BN.fromBuffer(privbuf);
5609 condition = bn.lt(Point.getN());
5610 } while (!condition);
5611 return bn;
5612};
5613
5614/**
5615 * Internal function to transform a WIF Buffer into a private key
5616 *
5617 * @param {Buffer} buf - An WIF string
5618 * @param {Network|string=} network - a {@link Network} object, or a string with the network name
5619 * @returns {Object} An object with keys: bn, network and compressed
5620 * @private
5621 */
5622PrivateKey._transformBuffer = function(buf, network) {
5623
5624 var info = {};
5625
5626 if (buf.length === 32) {
5627 return PrivateKey._transformBNBuffer(buf, network);
5628 }
5629
5630 info.network = Networks.get(buf[0], 'privatekey');
5631
5632 if (!info.network) {
5633 throw new Error('Invalid network');
5634 }
5635
5636 if (network && info.network !== Networks.get(network)) {
5637 throw new TypeError('Private key network mismatch');
5638 }
5639
5640 if (buf.length === 1 + 32 + 1 && buf[1 + 32 + 1 - 1] === 1) {
5641 info.compressed = true;
5642 } else if (buf.length === 1 + 32) {
5643 info.compressed = false;
5644 } else {
5645 throw new Error('Length of buffer must be 33 (uncompressed) or 34 (compressed)');
5646 }
5647
5648 info.bn = BN.fromBuffer(buf.slice(1, 32 + 1));
5649
5650 return info;
5651};
5652
5653/**
5654 * Internal function to transform a BN buffer into a private key
5655 *
5656 * @param {Buffer} buf
5657 * @param {Network|string=} network - a {@link Network} object, or a string with the network name
5658 * @returns {object} an Object with keys: bn, network, and compressed
5659 * @private
5660 */
5661PrivateKey._transformBNBuffer = function(buf, network) {
5662 var info = {};
5663 info.network = Networks.get(network) || Networks.defaultNetwork;
5664 info.bn = BN.fromBuffer(buf);
5665 info.compressed = false;
5666 return info;
5667};
5668
5669/**
5670 * Internal function to transform a WIF string into a private key
5671 *
5672 * @param {string} buf - An WIF string
5673 * @returns {Object} An object with keys: bn, network and compressed
5674 * @private
5675 */
5676PrivateKey._transformWIF = function(str, network) {
5677 return PrivateKey._transformBuffer(Base58Check.decode(str), network);
5678};
5679
5680/**
5681 * Instantiate a PrivateKey from a Buffer with the DER or WIF representation
5682 *
5683 * @param {Buffer} arg
5684 * @param {Network} network
5685 * @return {PrivateKey}
5686 */
5687PrivateKey.fromBuffer = function(arg, network) {
5688 return new PrivateKey(arg, network);
5689};
5690
5691/**
5692 * Internal function to transform a JSON string on plain object into a private key
5693 * return this.
5694 *
5695 * @param {string} json - A JSON string or plain object
5696 * @returns {Object} An object with keys: bn, network and compressed
5697 * @private
5698 */
5699PrivateKey._transformObject = function(json) {
5700 var bn = new BN(json.bn, 'hex');
5701 var network = Networks.get(json.network);
5702 return {
5703 bn: bn,
5704 network: network,
5705 compressed: json.compressed
5706 };
5707};
5708
5709/**
5710 * Instantiate a PrivateKey from a WIF string
5711 *
5712 * @param {string} str - The WIF encoded private key string
5713 * @returns {PrivateKey} A new valid instance of PrivateKey
5714 */
5715PrivateKey.fromString = PrivateKey.fromWIF = function(str) {
5716 $.checkArgument(_.isString(str), 'First argument is expected to be a string.');
5717 return new PrivateKey(str);
5718};
5719
5720/**
5721 * Instantiate a PrivateKey from a plain JavaScript object
5722 *
5723 * @param {Object} obj - The output from privateKey.toObject()
5724 */
5725PrivateKey.fromObject = function(obj) {
5726 $.checkArgument(_.isObject(obj), 'First argument is expected to be an object.');
5727 return new PrivateKey(obj);
5728};
5729
5730/**
5731 * Instantiate a PrivateKey from random bytes
5732 *
5733 * @param {string=} network - Either "livenet" or "testnet"
5734 * @returns {PrivateKey} A new valid instance of PrivateKey
5735 */
5736PrivateKey.fromRandom = function(network) {
5737 var bn = PrivateKey._getRandomBN();
5738 return new PrivateKey(bn, network);
5739};
5740
5741/**
5742 * Check if there would be any errors when initializing a PrivateKey
5743 *
5744 * @param {string} data - The encoded data in various formats
5745 * @param {string=} network - Either "livenet" or "testnet"
5746 * @returns {null|Error} An error if exists
5747 */
5748
5749PrivateKey.getValidationError = function(data, network) {
5750 var error;
5751 try {
5752 /* jshint nonew: false */
5753 new PrivateKey(data, network);
5754 } catch (e) {
5755 error = e;
5756 }
5757 return error;
5758};
5759
5760/**
5761 * Check if the parameters are valid
5762 *
5763 * @param {string} data - The encoded data in various formats
5764 * @param {string=} network - Either "livenet" or "testnet"
5765 * @returns {Boolean} If the private key is would be valid
5766 */
5767PrivateKey.isValid = function(data, network){
5768 if (!data) {
5769 return false;
5770 }
5771 return !PrivateKey.getValidationError(data, network);
5772};
5773
5774/**
5775 * Will output the PrivateKey encoded as hex string
5776 *
5777 * @returns {string}
5778 */
5779PrivateKey.prototype.toString = function() {
5780 return this.toBuffer().toString('hex');
5781};
5782
5783/**
5784 * Will output the PrivateKey to a WIF string
5785 *
5786 * @returns {string} A WIP representation of the private key
5787 */
5788PrivateKey.prototype.toWIF = function() {
5789 var network = this.network;
5790 var compressed = this.compressed;
5791
5792 var buf;
5793 if (compressed) {
5794 buf = Buffer.concat([Buffer.from([network.privatekey]),
5795 this.bn.toBuffer({size: 32}),
5796 Buffer.from([0x01])]);
5797 } else {
5798 buf = Buffer.concat([Buffer.from([network.privatekey]),
5799 this.bn.toBuffer({size: 32})]);
5800 }
5801
5802 return Base58Check.encode(buf);
5803};
5804
5805/**
5806 * Will return the private key as a BN instance
5807 *
5808 * @returns {BN} A BN instance of the private key
5809 */
5810PrivateKey.prototype.toBigNumber = function(){
5811 return this.bn;
5812};
5813
5814/**
5815 * Will return the private key as a BN buffer
5816 *
5817 * @returns {Buffer} A buffer of the private key
5818 */
5819PrivateKey.prototype.toBuffer = function(){
5820 return this.bn.toBuffer({size: 32});
5821};
5822
5823/**
5824 * WARNING: This method will not be officially supported until v1.0.0.
5825 *
5826 *
5827 * Will return the private key as a BN buffer without leading zero padding
5828 *
5829 * @returns {Buffer} A buffer of the private key
5830 */
5831PrivateKey.prototype.toBufferNoPadding = function() {
5832 return this.bn.toBuffer();
5833};
5834
5835/**
5836 * Will return the corresponding public key
5837 *
5838 * @returns {PublicKey} A public key generated from the private key
5839 */
5840PrivateKey.prototype.toPublicKey = function(){
5841 if (!this._pubkey) {
5842 this._pubkey = PublicKey.fromPrivateKey(this);
5843 }
5844 return this._pubkey;
5845};
5846
5847/**
5848 * Will return an address for the private key
5849 * @param {Network=} network - optional parameter specifying
5850 * @param {string} type - Either 'pubkeyhash', 'witnesspubkeyhash', or 'scripthash'
5851 * the desired network for the address
5852 *
5853 * @returns {Address} An address generated from the private key
5854 */
5855PrivateKey.prototype.toAddress = function(network, type) {
5856 var pubkey = this.toPublicKey();
5857 return Address.fromPublicKey(pubkey, network || this.network, type);
5858};
5859
5860/**
5861 * @returns {Object} A plain object representation
5862 */
5863PrivateKey.prototype.toObject = PrivateKey.prototype.toJSON = function toObject() {
5864 return {
5865 bn: this.bn.toString('hex'),
5866 compressed: this.compressed,
5867 network: this.network.toString()
5868 };
5869};
5870
5871/**
5872 * Will return a string formatted for the console
5873 *
5874 * @returns {string} Private key
5875 */
5876PrivateKey.prototype.inspect = function() {
5877 var uncompressed = !this.compressed ? ', uncompressed' : '';
5878 return '<PrivateKey: ' + this.toString() + ', network: ' + this.network + uncompressed + '>';
5879};
5880
5881module.exports = PrivateKey;
5882
5883}).call(this)}).call(this,require("buffer").Buffer)
5884},{"./address":1,"./crypto/bn":6,"./crypto/point":9,"./crypto/random":10,"./encoding/base58check":13,"./networks":23,"./publickey":26,"./util/js":46,"./util/preconditions":47,"buffer":132,"lodash":210}],26:[function(require,module,exports){
5885(function (Buffer){(function (){
5886'use strict';
5887
5888var BN = require('./crypto/bn');
5889var Point = require('./crypto/point');
5890var Hash = require('./crypto/hash');
5891var JSUtil = require('./util/js');
5892var Network = require('./networks');
5893var _ = require('lodash');
5894var $ = require('./util/preconditions');
5895
5896/**
5897 * Instantiate a PublicKey from a {@link PrivateKey}, {@link Point}, `string`, or `Buffer`.
5898 *
5899 * There are two internal properties, `network` and `compressed`, that deal with importing
5900 * a PublicKey from a PrivateKey in WIF format. More details described on {@link PrivateKey}
5901 *
5902 * @example
5903 * ```javascript
5904 * // instantiate from a private key
5905 * var key = PublicKey(privateKey, true);
5906 *
5907 * // export to as a DER hex encoded string
5908 * var exported = key.toString();
5909 *
5910 * // import the public key
5911 * var imported = PublicKey.fromString(exported);
5912 * ```
5913 *
5914 * @param {string} data - The encoded data in various formats
5915 * @param {Object} extra - additional options
5916 * @param {Network=} extra.network - Which network should the address for this public key be for
5917 * @param {String=} extra.compressed - If the public key is compressed
5918 * @returns {PublicKey} A new valid instance of an PublicKey
5919 * @constructor
5920 */
5921function PublicKey(data, extra) {
5922
5923 if (!(this instanceof PublicKey)) {
5924 return new PublicKey(data, extra);
5925 }
5926
5927 $.checkArgument(data, 'First argument is required, please include public key data.');
5928
5929 if (data instanceof PublicKey) {
5930 // Return copy, but as it's an immutable object, return same argument
5931 return data;
5932 }
5933 extra = extra || {};
5934
5935 var info = this._classifyArgs(data, extra);
5936
5937 // validation
5938 info.point.validate();
5939
5940 JSUtil.defineImmutable(this, {
5941 point: info.point,
5942 compressed: info.compressed,
5943 network: info.network || Network.defaultNetwork
5944 });
5945
5946 return this;
5947};
5948
5949/**
5950 * Internal function to differentiate between arguments passed to the constructor
5951 * @param {*} data
5952 * @param {Object} extra
5953 */
5954PublicKey.prototype._classifyArgs = function(data, extra) {
5955 /* jshint maxcomplexity: 10 */
5956 var info = {
5957 compressed: _.isUndefined(extra.compressed) || extra.compressed
5958 };
5959
5960 // detect type of data
5961 if (data instanceof Point) {
5962 info.point = data;
5963 } else if (data.x && data.y) {
5964 info = PublicKey._transformObject(data);
5965 } else if (typeof(data) === 'string') {
5966 info = PublicKey._transformDER(Buffer.from(data, 'hex'));
5967 } else if (PublicKey._isBuffer(data)) {
5968 info = PublicKey._transformDER(data);
5969 } else if (PublicKey._isPrivateKey(data)) {
5970 info = PublicKey._transformPrivateKey(data);
5971 } else {
5972 throw new TypeError('First argument is an unrecognized data format.');
5973 }
5974 if (!info.network) {
5975 info.network = _.isUndefined(extra.network) ? undefined : Network.get(extra.network);
5976 }
5977 return info;
5978};
5979
5980/**
5981 * Internal function to detect if an object is a {@link PrivateKey}
5982 *
5983 * @param {*} param - object to test
5984 * @returns {boolean}
5985 * @private
5986 */
5987PublicKey._isPrivateKey = function(param) {
5988 var PrivateKey = require('./privatekey');
5989 return param instanceof PrivateKey;
5990};
5991
5992/**
5993 * Internal function to detect if an object is a Buffer
5994 *
5995 * @param {*} param - object to test
5996 * @returns {boolean}
5997 * @private
5998 */
5999PublicKey._isBuffer = function(param) {
6000 return (param instanceof Buffer) || (param instanceof Uint8Array);
6001};
6002
6003/**
6004 * Internal function to transform a private key into a public key point
6005 *
6006 * @param {PrivateKey} privkey - An instance of PrivateKey
6007 * @returns {Object} An object with keys: point and compressed
6008 * @private
6009 */
6010PublicKey._transformPrivateKey = function(privkey) {
6011 $.checkArgument(PublicKey._isPrivateKey(privkey), 'Must be an instance of PrivateKey');
6012 var info = {};
6013 info.point = Point.getG().mul(privkey.bn);
6014 info.compressed = privkey.compressed;
6015 info.network = privkey.network;
6016 return info;
6017};
6018
6019/**
6020 * Internal function to transform DER into a public key point
6021 *
6022 * @param {Buffer} buf - An hex encoded buffer
6023 * @param {bool=} strict - if set to false, will loosen some conditions
6024 * @returns {Object} An object with keys: point and compressed
6025 * @private
6026 */
6027PublicKey._transformDER = function(buf, strict) {
6028 /* jshint maxstatements: 30 */
6029 /* jshint maxcomplexity: 12 */
6030 $.checkArgument(PublicKey._isBuffer(buf), 'Must be a hex buffer of DER encoded public key');
6031 var info = {};
6032
6033 strict = _.isUndefined(strict) ? true : strict;
6034
6035 var x;
6036 var y;
6037 var xbuf;
6038 var ybuf;
6039
6040 if (buf[0] === 0x04 || (!strict && (buf[0] === 0x06 || buf[0] === 0x07))) {
6041 xbuf = buf.slice(1, 33);
6042 ybuf = buf.slice(33, 65);
6043 if (xbuf.length !== 32 || ybuf.length !== 32 || buf.length !== 65) {
6044 throw new TypeError('Length of x and y must be 32 bytes');
6045 }
6046 x = new BN(xbuf);
6047 y = new BN(ybuf);
6048 info.point = new Point(x, y);
6049 info.compressed = false;
6050 } else if (buf[0] === 0x03) {
6051 xbuf = buf.slice(1);
6052 x = new BN(xbuf);
6053 info = PublicKey._transformX(true, x);
6054 info.compressed = true;
6055 } else if (buf[0] === 0x02) {
6056 xbuf = buf.slice(1);
6057 x = new BN(xbuf);
6058 info = PublicKey._transformX(false, x);
6059 info.compressed = true;
6060 } else {
6061 throw new TypeError('Invalid DER format public key');
6062 }
6063 return info;
6064};
6065
6066/**
6067 * Internal function to transform X into a public key point
6068 *
6069 * @param {Boolean} odd - If the point is above or below the x axis
6070 * @param {Point} x - The x point
6071 * @returns {Object} An object with keys: point and compressed
6072 * @private
6073 */
6074PublicKey._transformX = function(odd, x) {
6075 $.checkArgument(typeof odd === 'boolean', 'Must specify whether y is odd or not (true or false)');
6076 var info = {};
6077 info.point = Point.fromX(odd, x);
6078 return info;
6079};
6080
6081/**
6082 * Internal function to transform a JSON into a public key point
6083 *
6084 * @param {String|Object} json - a JSON string or plain object
6085 * @returns {Object} An object with keys: point and compressed
6086 * @private
6087 */
6088PublicKey._transformObject = function(json) {
6089 var x = new BN(json.x, 'hex');
6090 var y = new BN(json.y, 'hex');
6091 var point = new Point(x, y);
6092 return new PublicKey(point, {
6093 compressed: json.compressed
6094 });
6095};
6096
6097/**
6098 * Instantiate a PublicKey from a PrivateKey
6099 *
6100 * @param {PrivateKey} privkey - An instance of PrivateKey
6101 * @returns {PublicKey} A new valid instance of PublicKey
6102 */
6103PublicKey.fromPrivateKey = function(privkey) {
6104 $.checkArgument(PublicKey._isPrivateKey(privkey), 'Must be an instance of PrivateKey');
6105 var info = PublicKey._transformPrivateKey(privkey);
6106 return new PublicKey(info.point, {
6107 compressed: info.compressed,
6108 network: info.network
6109 });
6110};
6111
6112/**
6113 * Instantiate a PublicKey from a Buffer
6114 * @param {Buffer} buf - A DER hex buffer
6115 * @param {bool=} strict - if set to false, will loosen some conditions
6116 * @returns {PublicKey} A new valid instance of PublicKey
6117 */
6118PublicKey.fromDER = PublicKey.fromBuffer = function(buf, strict) {
6119 $.checkArgument(PublicKey._isBuffer(buf), 'Must be a hex buffer of DER encoded public key');
6120 var info = PublicKey._transformDER(buf, strict);
6121 return new PublicKey(info.point, {
6122 compressed: info.compressed
6123 });
6124};
6125
6126/**
6127 * Instantiate a PublicKey from a Point
6128 *
6129 * @param {Point} point - A Point instance
6130 * @param {boolean=} compressed - whether to store this public key as compressed format
6131 * @returns {PublicKey} A new valid instance of PublicKey
6132 */
6133PublicKey.fromPoint = function(point, compressed) {
6134 $.checkArgument(point instanceof Point, 'First argument must be an instance of Point.');
6135 return new PublicKey(point, {
6136 compressed: compressed
6137 });
6138};
6139
6140/**
6141 * Instantiate a PublicKey from a DER hex encoded string
6142 *
6143 * @param {string} str - A DER hex string
6144 * @param {String=} encoding - The type of string encoding
6145 * @returns {PublicKey} A new valid instance of PublicKey
6146 */
6147PublicKey.fromString = function(str, encoding) {
6148 var buf = Buffer.from(str, encoding || 'hex');
6149 var info = PublicKey._transformDER(buf);
6150 return new PublicKey(info.point, {
6151 compressed: info.compressed
6152 });
6153};
6154
6155/**
6156 * Instantiate a PublicKey from an X Point
6157 *
6158 * @param {Boolean} odd - If the point is above or below the x axis
6159 * @param {Point} x - The x point
6160 * @returns {PublicKey} A new valid instance of PublicKey
6161 */
6162PublicKey.fromX = function(odd, x) {
6163 var info = PublicKey._transformX(odd, x);
6164 return new PublicKey(info.point, {
6165 compressed: info.compressed
6166 });
6167};
6168
6169/**
6170 * Check if there would be any errors when initializing a PublicKey
6171 *
6172 * @param {string} data - The encoded data in various formats
6173 * @returns {null|Error} An error if exists
6174 */
6175PublicKey.getValidationError = function(data) {
6176 var error;
6177 try {
6178 /* jshint nonew: false */
6179 new PublicKey(data);
6180 } catch (e) {
6181 error = e;
6182 }
6183 return error;
6184};
6185
6186/**
6187 * Check if the parameters are valid
6188 *
6189 * @param {string} data - The encoded data in various formats
6190 * @returns {Boolean} If the public key would be valid
6191 */
6192PublicKey.isValid = function(data) {
6193 return !PublicKey.getValidationError(data);
6194};
6195
6196/**
6197 * @returns {Object} A plain object of the PublicKey
6198 */
6199PublicKey.prototype.toObject = PublicKey.prototype.toJSON = function toObject() {
6200 return {
6201 x: this.point.getX().toString('hex', 2),
6202 y: this.point.getY().toString('hex', 2),
6203 compressed: this.compressed
6204 };
6205};
6206
6207/**
6208 * Will output the PublicKey to a DER Buffer
6209 *
6210 * @returns {Buffer} A DER hex encoded buffer
6211 */
6212PublicKey.prototype.toBuffer = PublicKey.prototype.toDER = function() {
6213 var x = this.point.getX();
6214 var y = this.point.getY();
6215
6216 var xbuf = x.toBuffer({
6217 size: 32
6218 });
6219 var ybuf = y.toBuffer({
6220 size: 32
6221 });
6222
6223 var prefix;
6224 if (!this.compressed) {
6225 prefix = Buffer.from([0x04]);
6226 return Buffer.concat([prefix, xbuf, ybuf]);
6227 } else {
6228 var odd = ybuf[ybuf.length - 1] % 2;
6229 if (odd) {
6230 prefix = Buffer.from([0x03]);
6231 } else {
6232 prefix = Buffer.from([0x02]);
6233 }
6234 return Buffer.concat([prefix, xbuf]);
6235 }
6236};
6237
6238/**
6239 * Will return a sha256 + ripemd160 hash of the serialized public key
6240 * @see https://github.com/bitcoin/bitcoin/blob/master/src/pubkey.h#L141
6241 * @returns {Buffer}
6242 */
6243PublicKey.prototype._getID = function _getID() {
6244 return Hash.sha256ripemd160(this.toBuffer());
6245};
6246
6247/**
6248 * Will return an address for the public key
6249 *
6250 * @param {String|Network=} network - Which network should the address be for
6251 * @param {string} type - Either 'pubkeyhash', 'witnesspubkeyhash', or 'scripthash'
6252 * @returns {Address} An address generated from the public key
6253 */
6254PublicKey.prototype.toAddress = function(network, type) {
6255 var Address = require('./address');
6256 return Address.fromPublicKey(this, network || this.network, type);
6257};
6258
6259/**
6260 * Will output the PublicKey to a DER encoded hex string
6261 *
6262 * @returns {string} A DER hex encoded string
6263 */
6264PublicKey.prototype.toString = function() {
6265 return this.toDER().toString('hex');
6266};
6267
6268/**
6269 * Will return a string formatted for the console
6270 *
6271 * @returns {string} Public key
6272 */
6273PublicKey.prototype.inspect = function() {
6274 return '<PublicKey: ' + this.toString() +
6275 (this.compressed ? '' : ', uncompressed') + '>';
6276};
6277
6278
6279module.exports = PublicKey;
6280
6281}).call(this)}).call(this,require("buffer").Buffer)
6282},{"./address":1,"./crypto/bn":6,"./crypto/hash":8,"./crypto/point":9,"./networks":23,"./privatekey":25,"./util/js":46,"./util/preconditions":47,"buffer":132,"lodash":210}],27:[function(require,module,exports){
6283module.exports = require('./script');
6284
6285module.exports.Interpreter = require('./interpreter');
6286
6287},{"./interpreter":28,"./script":29}],28:[function(require,module,exports){
6288(function (Buffer){(function (){
6289'use strict';
6290
6291var _ = require('lodash');
6292
6293var Script = require('./script');
6294var Opcode = require('../opcode');
6295var BN = require('../crypto/bn');
6296var Hash = require('../crypto/hash');
6297var Signature = require('../crypto/signature');
6298var PublicKey = require('../publickey');
6299
6300/**
6301 * Bitcoin transactions contain scripts. Each input has a script called the
6302 * scriptSig, and each output has a script called the scriptPubkey. To validate
6303 * an input, the input's script is concatenated with the referenced output script,
6304 * and the result is executed. If at the end of execution the stack contains a
6305 * "true" value, then the transaction is valid.
6306 *
6307 * The primary way to use this class is via the verify function.
6308 * e.g., Interpreter().verify( ... );
6309 */
6310var Interpreter = function Interpreter(obj) {
6311 if (!(this instanceof Interpreter)) {
6312 return new Interpreter(obj);
6313 }
6314 if (obj) {
6315 this.initialize();
6316 this.set(obj);
6317 } else {
6318 this.initialize();
6319 }
6320};
6321
6322Interpreter.SIGVERSION_BASE = 0;
6323Interpreter.SIGVERSION_WITNESS_V0 = 1;
6324Interpreter.SIGVERSION_TAPROOT = 2;
6325Interpreter.SIGVERSION_TAPSCRIPT = 3;
6326
6327Interpreter.prototype.verifyWitnessProgram = function(version, program, witness, satoshis, flags) {
6328
6329 var scriptPubKey = new Script();
6330 var stack = [];
6331
6332 if (version === 0) {
6333 if (program.length === 32) {
6334 if (witness.length === 0) {
6335 this.errstr = 'SCRIPT_ERR_WITNESS_PROGRAM_WITNESS_EMPTY';
6336 return false;
6337 }
6338
6339 var scriptPubKeyBuffer = witness[witness.length - 1];
6340 scriptPubKey = new Script(scriptPubKeyBuffer);
6341 var hash = Hash.sha256(scriptPubKeyBuffer);
6342 if (hash.toString('hex') !== program.toString('hex')) {
6343 this.errstr = 'SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH';
6344 return false;
6345 }
6346
6347 stack = witness.slice(0, -1);
6348 } else if (program.length === 20) {
6349 if (witness.length !== 2) {
6350 this.errstr = 'SCRIPT_ERR_WITNESS_PROGRAM_MISMATCH';
6351 return false;
6352 }
6353
6354 scriptPubKey.add(Opcode.OP_DUP);
6355 scriptPubKey.add(Opcode.OP_HASH160);
6356 scriptPubKey.add(program);
6357 scriptPubKey.add(Opcode.OP_EQUALVERIFY);
6358 scriptPubKey.add(Opcode.OP_CHECKSIG);
6359
6360 stack = witness;
6361
6362 } else {
6363 this.errstr = 'SCRIPT_ERR_WITNESS_PROGRAM_WRONG_LENGTH';
6364 return false;
6365 }
6366 } else if ((flags & Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM)) {
6367 this.errstr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM';
6368 return false;
6369 } else {
6370 return true;
6371 }
6372
6373 this.initialize();
6374
6375 this.set({
6376 script: scriptPubKey,
6377 stack: stack,
6378 sigversion: Interpreter.SIGVERSION_WITNESS_V0,
6379 satoshis: satoshis,
6380 flags: flags,
6381 });
6382
6383 if (!this.evaluate()) {
6384 return false;
6385 }
6386
6387 if (this.stack.length !== 1) {
6388 this.errstr = 'SCRIPT_ERR_EVAL_FALSE';
6389 return false;
6390 }
6391
6392 var buf = this.stack[this.stack.length - 1];
6393 if (!Interpreter.castToBool(buf)) {
6394 this.errstr = 'SCRIPT_ERR_EVAL_FALSE_IN_STACK';
6395 return false;
6396 }
6397
6398 return true;
6399};
6400
6401
6402
6403/**
6404 * Verifies a Script by executing it and returns true if it is valid.
6405 * This function needs to be provided with the scriptSig and the scriptPubkey
6406 * separately.
6407 * @param {Script} scriptSig - the script's first part (corresponding to the tx input)
6408 * @param {Script} scriptPubkey - the script's last part (corresponding to the tx output)
6409 * @param {Transaction=} tx - the Transaction containing the scriptSig in one input (used
6410 * to check signature validity for some opcodes like OP_CHECKSIG)
6411 * @param {number} nin - index of the transaction input containing the scriptSig verified.
6412 * @param {number} flags - evaluation flags. See Interpreter.SCRIPT_* constants
6413 * @param {number} witness - array of witness data
6414 * @param {number} satoshis - number of satoshis created by this output
6415 *
6416 * Translated from bitcoind's VerifyScript
6417 */
6418Interpreter.prototype.verify = function(scriptSig, scriptPubkey, tx, nin, flags, witness, satoshis) {
6419
6420 var Transaction = require('../transaction');
6421 if (_.isUndefined(tx)) {
6422 tx = new Transaction();
6423 }
6424 if (_.isUndefined(nin)) {
6425 nin = 0;
6426 }
6427 if (_.isUndefined(flags)) {
6428 flags = 0;
6429 }
6430 if (_.isUndefined(witness)) {
6431 witness = null;
6432 }
6433 if (_.isUndefined(satoshis)) {
6434 satoshis = 0;
6435 }
6436
6437 this.set({
6438 script: scriptSig,
6439 tx: tx,
6440 nin: nin,
6441 sigversion: Interpreter.SIGVERSION_BASE,
6442 satoshis: 0,
6443 flags: flags
6444 });
6445 var stackCopy;
6446
6447 if ((flags & Interpreter.SCRIPT_VERIFY_SIGPUSHONLY) !== 0 && !scriptSig.isPushOnly()) {
6448 this.errstr = 'SCRIPT_ERR_SIG_PUSHONLY';
6449 return false;
6450 }
6451
6452 // evaluate scriptSig
6453 if (!this.evaluate()) {
6454 return false;
6455 }
6456
6457 if (flags & Interpreter.SCRIPT_VERIFY_P2SH) {
6458 stackCopy = this.stack.slice();
6459 }
6460
6461 var stack = this.stack;
6462 this.initialize();
6463 this.set({
6464 script: scriptPubkey,
6465 stack: stack,
6466 tx: tx,
6467 nin: nin,
6468 flags: flags
6469 });
6470
6471 // evaluate scriptPubkey
6472 if (!this.evaluate()) {
6473 return false;
6474 }
6475
6476 if (this.stack.length === 0) {
6477 this.errstr = 'SCRIPT_ERR_EVAL_FALSE_NO_RESULT';
6478 return false;
6479 }
6480
6481 var buf = this.stack[this.stack.length - 1];
6482 if (!Interpreter.castToBool(buf)) {
6483 this.errstr = 'SCRIPT_ERR_EVAL_FALSE_IN_STACK';
6484 return false;
6485 }
6486
6487 var hadWitness = false;
6488 if ((flags & Interpreter.SCRIPT_VERIFY_WITNESS)) {
6489 var witnessValues = {};
6490 if (scriptPubkey.isWitnessProgram(witnessValues)) {
6491 hadWitness = true;
6492 if (scriptSig.toBuffer().length !== 0) {
6493 return false;
6494 }
6495 if (!this.verifyWitnessProgram(witnessValues.version, witnessValues.program, witness, satoshis, this.flags)) {
6496 return false;
6497 }
6498 }
6499 }
6500
6501 // Additional validation for spend-to-script-hash transactions:
6502 if ((flags & Interpreter.SCRIPT_VERIFY_P2SH) && scriptPubkey.isScriptHashOut()) {
6503 // scriptSig must be literals-only or validation fails
6504 if (!scriptSig.isPushOnly()) {
6505 this.errstr = 'SCRIPT_ERR_SIG_PUSHONLY';
6506 return false;
6507 }
6508
6509 // stackCopy cannot be empty here, because if it was the
6510 // P2SH HASH <> EQUAL scriptPubKey would be evaluated with
6511 // an empty stack and the EvalScript above would return false.
6512 if (stackCopy.length === 0) {
6513 throw new Error('internal error - stack copy empty');
6514 }
6515
6516 var redeemScriptSerialized = stackCopy[stackCopy.length - 1];
6517 var redeemScript = Script.fromBuffer(redeemScriptSerialized);
6518 stackCopy.pop();
6519
6520 this.initialize();
6521 this.set({
6522 script: redeemScript,
6523 stack: stackCopy,
6524 tx: tx,
6525 nin: nin,
6526 flags: flags
6527 });
6528
6529 // evaluate redeemScript
6530 if (!this.evaluate()) {
6531 return false;
6532 }
6533
6534 if (stackCopy.length === 0) {
6535 this.errstr = 'SCRIPT_ERR_EVAL_FALSE_NO_P2SH_STACK';
6536 return false;
6537 }
6538
6539 if (!Interpreter.castToBool(stackCopy[stackCopy.length - 1])) {
6540 this.errstr = 'SCRIPT_ERR_EVAL_FALSE_IN_P2SH_STACK';
6541 return false;
6542 }
6543 if ((flags & Interpreter.SCRIPT_VERIFY_WITNESS)) {
6544 var p2shWitnessValues = {};
6545 if (redeemScript.isWitnessProgram(p2shWitnessValues)) {
6546 hadWitness = true;
6547 var redeemScriptPush = new Script();
6548 redeemScriptPush.add(redeemScript.toBuffer());
6549 if (scriptSig.toHex() !== redeemScriptPush.toHex()) {
6550 this.errstr = 'SCRIPT_ERR_WITNESS_MALLEATED_P2SH';
6551 return false;
6552 }
6553
6554 if (!this.verifyWitnessProgram(p2shWitnessValues.version, p2shWitnessValues.program, witness, satoshis, this.flags)) {
6555 return false;
6556 }
6557 // Bypass the cleanstack check at the end. The actual stack is obviously not clean
6558 // for witness programs.
6559 stack = [stack[0]];
6560 }
6561 }
6562 }
6563
6564 // The CLEANSTACK check is only performed after potential P2SH evaluation,
6565 // as the non-P2SH evaluation of a P2SH script will obviously not result in
6566 // a clean stack (the P2SH inputs remain). The same holds for witness
6567 // evaluation.
6568 if ((this.flags & Interpreter.SCRIPT_VERIFY_CLEANSTACK) != 0) {
6569 // Disallow CLEANSTACK without P2SH, as otherwise a switch
6570 // CLEANSTACK->P2SH+CLEANSTACK would be possible, which is not a
6571 // softfork (and P2SH should be one).
6572 if ((this.flags & Interpreter.SCRIPT_VERIFY_P2SH) == 0)
6573 throw 'flags & SCRIPT_VERIFY_P2SH';
6574
6575 if (stackCopy.length != 1) {
6576 this.errstr = 'SCRIPT_ERR_CLEANSTACK';
6577 return false;
6578 }
6579 }
6580
6581 if ((this.flags & Interpreter.SCRIPT_VERIFY_WITNESS)) {
6582 if (!hadWitness && witness.length > 0) {
6583 this.errstr = 'SCRIPT_ERR_WITNESS_UNEXPECTED';
6584 return false;
6585 }
6586 }
6587
6588 return true;
6589};
6590
6591module.exports = Interpreter;
6592
6593Interpreter.prototype.initialize = function(obj) {
6594 this.stack = [];
6595 this.altstack = [];
6596 this.pc = 0;
6597 this.satoshis = 0;
6598 this.sigversion = Interpreter.SIGVERSION_BASE;
6599 this.pbegincodehash = 0;
6600 this.nOpCount = 0;
6601 this.vfExec = [];
6602 this.errstr = '';
6603 this.flags = 0;
6604};
6605
6606Interpreter.prototype.set = function(obj) {
6607 this.script = obj.script || this.script;
6608 this.tx = obj.tx || this.tx;
6609 this.nin = typeof obj.nin !== 'undefined' ? obj.nin : this.nin;
6610 this.stack = obj.stack || this.stack;
6611 this.altstack = obj.altack || this.altstack;
6612 this.pc = typeof obj.pc !== 'undefined' ? obj.pc : this.pc;
6613 this.pbegincodehash = typeof obj.pbegincodehash !== 'undefined' ? obj.pbegincodehash : this.pbegincodehash;
6614 this.sigversion = typeof obj.sigversion !== 'undefined' ? obj.sigversion : this.sigversion;
6615 this.satoshis = typeof obj.satoshis !== 'undefined' ? obj.satoshis : this.satoshis;
6616 this.nOpCount = typeof obj.nOpCount !== 'undefined' ? obj.nOpCount : this.nOpCount;
6617 this.vfExec = obj.vfExec || this.vfExec;
6618 this.errstr = obj.errstr || this.errstr;
6619 this.flags = typeof obj.flags !== 'undefined' ? obj.flags : this.flags;
6620};
6621
6622Interpreter.true = Buffer.from([1]);
6623Interpreter.false = Buffer.from([]);
6624
6625Interpreter.MAX_SCRIPT_ELEMENT_SIZE = 520;
6626
6627Interpreter.LOCKTIME_THRESHOLD = 500000000;
6628Interpreter.LOCKTIME_THRESHOLD_BN = new BN(Interpreter.LOCKTIME_THRESHOLD);
6629
6630// flags taken from bitcoind
6631// bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104
6632Interpreter.SCRIPT_VERIFY_NONE = 0;
6633
6634// Making v1-v16 witness program non-standard
6635Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_WITNESS_PROGRAM = (1 << 12);
6636
6637// Evaluate P2SH subscripts (softfork safe, BIP16).
6638Interpreter.SCRIPT_VERIFY_P2SH = (1 << 0);
6639
6640// Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure.
6641// Passing a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) to checksig causes that pubkey to be
6642// skipped (not softfork safe: this flag can widen the validity of OP_CHECKSIG OP_NOT).
6643Interpreter.SCRIPT_VERIFY_STRICTENC = (1 << 1);
6644
6645// Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP62 rule 1)
6646Interpreter.SCRIPT_VERIFY_DERSIG = (1 << 2);
6647
6648// Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure
6649// (softfork safe, BIP62 rule 5).
6650Interpreter.SCRIPT_VERIFY_LOW_S = (1 << 3);
6651
6652// verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7).
6653Interpreter.SCRIPT_VERIFY_NULLDUMMY = (1 << 4);
6654
6655// Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2).
6656Interpreter.SCRIPT_VERIFY_SIGPUSHONLY = (1 << 5);
6657
6658// Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct
6659// pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating
6660// any other push causes the script to fail (BIP62 rule 3).
6661// In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4).
6662// (softfork safe)
6663Interpreter.SCRIPT_VERIFY_MINIMALDATA = (1 << 6);
6664
6665// Discourage use of NOPs reserved for upgrades (NOP1-10)
6666//
6667// Provided so that nodes can avoid accepting or mining transactions
6668// containing executed NOP's whose meaning may change after a soft-fork,
6669// thus rendering the script invalid; with this flag set executing
6670// discouraged NOPs fails the script. This verification flag will never be
6671// a mandatory flag applied to scripts in a block. NOPs that are not
6672// executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected.
6673Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1 << 7);
6674
6675
6676// Require that only a single stack element remains after evaluation. This
6677// changes the success criterion from "At least one stack element must
6678// remain, and when interpreted as a boolean, it must be true" to "Exactly
6679// one stack element must remain, and when interpreted as a boolean, it must
6680// be true".
6681// (softfork safe, BIP62 rule 6)
6682// Note: CLEANSTACK should never be used without P2SH or WITNESS.
6683Interpreter.SCRIPT_VERIFY_CLEANSTACK = (1 << 8),
6684
6685// CLTV See BIP65 for details.
6686Interpreter.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY = (1 << 9);
6687Interpreter.SCRIPT_VERIFY_WITNESS = (1 << 10);
6688Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1 << 11);
6689
6690// support CHECKSEQUENCEVERIFY opcode
6691//
6692// See BIP112 for details
6693Interpreter.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY = (1 << 10);
6694
6695//
6696// Segwit script only: Require the argument of OP_IF/NOTIF to be exactly
6697// 0x01 or empty vector
6698//
6699Interpreter.SCRIPT_VERIFY_MINIMALIF = (1 << 13);
6700
6701
6702// Signature(s) must be empty vector if an CHECK(MULTI)SIG operation failed
6703//
6704Interpreter.SCRIPT_VERIFY_NULLFAIL = (1 << 14);
6705
6706// Public keys in scripts must be compressed
6707//
6708Interpreter.SCRIPT_VERIFY_WITNESS_PUBKEYTYPE = (1 << 15);
6709
6710// Do we accept signature using SIGHASH_FORKID
6711//
6712Interpreter.SCRIPT_ENABLE_SIGHASH_FORKID = (1 << 16);
6713
6714// Do we accept activate replay protection using a different fork id.
6715//
6716Interpreter.SCRIPT_ENABLE_REPLAY_PROTECTION = (1 << 17);
6717
6718// Enable new opcodes.
6719//
6720Interpreter.SCRIPT_ENABLE_MONOLITH_OPCODES = (1 << 18);
6721
6722
6723
6724/* Below flags apply in the context of BIP 68*/
6725/**
6726 * If this flag set, CTxIn::nSequence is NOT interpreted as a relative
6727 * lock-time.
6728 */
6729Interpreter.SEQUENCE_LOCKTIME_DISABLE_FLAG = (1 << 31);
6730
6731/**
6732 * If CTxIn::nSequence encodes a relative lock-time and this flag is set,
6733 * the relative lock-time has units of 512 seconds, otherwise it specifies
6734 * blocks with a granularity of 1.
6735 */
6736Interpreter.SEQUENCE_LOCKTIME_TYPE_FLAG = (1 << 22);
6737
6738/**
6739 * If CTxIn::nSequence encodes a relative lock-time, this mask is applied to
6740 * extract that lock-time from the sequence field.
6741 */
6742Interpreter.SEQUENCE_LOCKTIME_MASK = 0x0000ffff;
6743
6744
6745Interpreter.castToBool = function(buf) {
6746 for (var i = 0; i < buf.length; i++) {
6747 if (buf[i] !== 0) {
6748 // can be negative zero
6749 if (i === buf.length - 1 && buf[i] === 0x80) {
6750 return false;
6751 }
6752 return true;
6753 }
6754 }
6755 return false;
6756};
6757
6758/**
6759 * Translated from bitcoind's CheckSignatureEncoding
6760 */
6761Interpreter.prototype.checkSignatureEncoding = function(buf) {
6762 var sig;
6763
6764 // Empty signature. Not strictly DER encoded, but allowed to provide a
6765 // compact way to provide an invalid signature for use with CHECK(MULTI)SIG
6766 if (buf.length == 0) {
6767 return true;
6768 }
6769
6770 if ((this.flags & (Interpreter.SCRIPT_VERIFY_DERSIG | Interpreter.SCRIPT_VERIFY_LOW_S | Interpreter.SCRIPT_VERIFY_STRICTENC)) !== 0 && !Signature.isTxDER(buf)) {
6771 this.errstr = 'SCRIPT_ERR_SIG_DER_INVALID_FORMAT';
6772 return false;
6773 } else if ((this.flags & Interpreter.SCRIPT_VERIFY_LOW_S) !== 0) {
6774 sig = Signature.fromTxFormat(buf);
6775 if (!sig.hasLowS()) {
6776 this.errstr = 'SCRIPT_ERR_SIG_DER_HIGH_S';
6777 return false;
6778 }
6779 } else if ((this.flags & Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0) {
6780 sig = Signature.fromTxFormat(buf);
6781 if (!sig.hasDefinedHashtype()) {
6782 this.errstr = 'SCRIPT_ERR_SIG_HASHTYPE';
6783 return false;
6784 }
6785 }
6786
6787 return true;
6788};
6789
6790/**
6791 * Translated from bitcoind's CheckPubKeyEncoding
6792 */
6793Interpreter.prototype.checkPubkeyEncoding = function(buf) {
6794 if ((this.flags & Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0 && !PublicKey.isValid(buf)) {
6795 this.errstr = 'SCRIPT_ERR_PUBKEYTYPE';
6796 return false;
6797 }
6798
6799 // Only compressed keys are accepted in segwit
6800 if ((this.flags & Interpreter.SCRIPT_VERIFY_WITNESS_PUBKEYTYPE) != 0 && this.sigversion == Interpreter.SIGVERSION_WITNESS_V0 && !PublicKey.fromBuffer(buf).compressed) {
6801 this.errstr = 'SCRIPT_ERR_WITNESS_PUBKEYTYPE';
6802 return false;
6803 }
6804
6805 return true;
6806};
6807
6808/**
6809 * Based on bitcoind's EvalScript function, with the inner loop moved to
6810 * Interpreter.prototype.step()
6811 * bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104
6812 */
6813Interpreter.prototype.evaluate = function() {
6814 if (this.script.toBuffer().length > 10000) {
6815 this.errstr = 'SCRIPT_ERR_SCRIPT_SIZE';
6816 return false;
6817 }
6818
6819 try {
6820 while (this.pc < this.script.chunks.length) {
6821 var fSuccess = this.step();
6822 if (!fSuccess) {
6823 return false;
6824 }
6825 }
6826
6827 // Size limits
6828 if (this.stack.length + this.altstack.length > 1000) {
6829 this.errstr = 'SCRIPT_ERR_STACK_SIZE';
6830 return false;
6831 }
6832 } catch (e) {
6833 this.errstr = 'SCRIPT_ERR_UNKNOWN_ERROR: ' + e;
6834 return false;
6835 }
6836
6837 if (this.vfExec.length > 0) {
6838 this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL';
6839 return false;
6840 }
6841
6842 return true;
6843};
6844
6845/**
6846 * Checks a locktime parameter with the transaction's locktime.
6847 * There are two times of nLockTime: lock-by-blockheight and lock-by-blocktime,
6848 * distinguished by whether nLockTime < LOCKTIME_THRESHOLD = 500000000
6849 *
6850 * See the corresponding code on bitcoin core:
6851 * https://github.com/bitcoin/bitcoin/blob/ffd75adce01a78b3461b3ff05bcc2b530a9ce994/src/script/interpreter.cpp#L1129
6852 *
6853 * @param {BN} nLockTime the locktime read from the script
6854 * @return {boolean} true if the transaction's locktime is less than or equal to
6855 * the transaction's locktime
6856 */
6857Interpreter.prototype.checkLockTime = function(nLockTime) {
6858
6859 // We want to compare apples to apples, so fail the script
6860 // unless the type of nLockTime being tested is the same as
6861 // the nLockTime in the transaction.
6862 if (!(
6863 (this.tx.nLockTime < Interpreter.LOCKTIME_THRESHOLD && nLockTime.lt(Interpreter.LOCKTIME_THRESHOLD_BN)) ||
6864 (this.tx.nLockTime >= Interpreter.LOCKTIME_THRESHOLD && nLockTime.gte(Interpreter.LOCKTIME_THRESHOLD_BN))
6865 )) {
6866 return false;
6867 }
6868
6869 // Now that we know we're comparing apples-to-apples, the
6870 // comparison is a simple numeric one.
6871 if (nLockTime.gt(new BN(this.tx.nLockTime))) {
6872 return false;
6873 }
6874
6875 // Finally the nLockTime feature can be disabled and thus
6876 // CHECKLOCKTIMEVERIFY bypassed if every txin has been
6877 // finalized by setting nSequence to maxint. The
6878 // transaction would be allowed into the blockchain, making
6879 // the opcode ineffective.
6880 //
6881 // Testing if this vin is not final is sufficient to
6882 // prevent this condition. Alternatively we could test all
6883 // inputs, but testing just this input minimizes the data
6884 // required to prove correct CHECKLOCKTIMEVERIFY execution.
6885 if (!this.tx.inputs[this.nin].isFinal()) {
6886 return false;
6887 }
6888
6889 return true;
6890}
6891
6892
6893/**
6894 * Checks a sequence parameter with the transaction's sequence.
6895 * @param {BN} nSequence the sequence read from the script
6896 * @return {boolean} true if the transaction's sequence is less than or equal to
6897 * the transaction's sequence
6898 */
6899Interpreter.prototype.checkSequence = function(nSequence) {
6900
6901 // Relative lock times are supported by comparing the passed in operand to
6902 // the sequence number of the input.
6903 var txToSequence = this.tx.inputs[this.nin].sequenceNumber;
6904
6905 // Fail if the transaction's version number is not set high enough to
6906 // trigger BIP 68 rules.
6907 if (this.tx.version < 2) {
6908 return false;
6909 }
6910
6911 // Sequence numbers with their most significant bit set are not consensus
6912 // constrained. Testing that the transaction's sequence number do not have
6913 // this bit set prevents using this property to get around a
6914 // CHECKSEQUENCEVERIFY check.
6915 if (txToSequence & SEQUENCE_LOCKTIME_DISABLE_FLAG) {
6916 return false;
6917 }
6918
6919 // Mask off any bits that do not have consensus-enforced meaning before
6920 // doing the integer comparisons
6921 var nLockTimeMask =
6922 Interpreter.SEQUENCE_LOCKTIME_TYPE_FLAG | Interpreter.SEQUENCE_LOCKTIME_MASK;
6923 var txToSequenceMasked = new BN(txToSequence & nLockTimeMask);
6924 var nSequenceMasked = nSequence.and(nLockTimeMask);
6925
6926 // There are two kinds of nSequence: lock-by-blockheight and
6927 // lock-by-blocktime, distinguished by whether nSequenceMasked <
6928 // CTxIn::SEQUENCE_LOCKTIME_TYPE_FLAG.
6929 //
6930 // We want to compare apples to apples, so fail the script unless the type
6931 // of nSequenceMasked being tested is the same as the nSequenceMasked in the
6932 // transaction.
6933 var SEQUENCE_LOCKTIME_TYPE_FLAG_BN = new BN(Interpreter.SEQUENCE_LOCKTIME_TYPE_FLAG);
6934
6935 if (!((txToSequenceMasked.lt(SEQUENCE_LOCKTIME_TYPE_FLAG_BN) &&
6936 nSequenceMasked.lt(SEQUENCE_LOCKTIME_TYPE_FLAG_BN)) ||
6937 (txToSequenceMasked.gte(SEQUENCE_LOCKTIME_TYPE_FLAG_BN) &&
6938 nSequenceMasked.gte(SEQUENCE_LOCKTIME_TYPE_FLAG_BN)))) {
6939 return false;
6940 }
6941
6942 // Now that we know we're comparing apples-to-apples, the comparison is a
6943 // simple numeric one.
6944 if (nSequenceMasked.gt(txToSequenceMasked)) {
6945 return false;
6946 }
6947 return true;
6948 }
6949
6950/**
6951 * Based on the inner loop of bitcoind's EvalScript function
6952 * bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104
6953 */
6954Interpreter.prototype.step = function() {
6955 var fRequireMinimal = (this.flags & Interpreter.SCRIPT_VERIFY_MINIMALDATA) !== 0;
6956
6957 //bool fExec = !count(vfExec.begin(), vfExec.end(), false);
6958 var fExec = (this.vfExec.indexOf(false) === -1);
6959 var buf, buf1, buf2, spliced, n, x1, x2, bn, bn1, bn2, bufSig, bufPubkey, subscript;
6960 var sig, pubkey;
6961 var fValue, fSuccess;
6962
6963 // Read instruction
6964 var chunk = this.script.chunks[this.pc];
6965 this.pc++;
6966 var opcodenum = chunk.opcodenum;
6967 if (_.isUndefined(opcodenum)) {
6968 this.errstr = 'SCRIPT_ERR_UNDEFINED_OPCODE';
6969 return false;
6970 }
6971 if (chunk.buf && chunk.buf.length > Interpreter.MAX_SCRIPT_ELEMENT_SIZE) {
6972 this.errstr = 'SCRIPT_ERR_PUSH_SIZE';
6973 return false;
6974 }
6975
6976 // Note how Opcode.OP_RESERVED does not count towards the opcode limit.
6977 if (opcodenum > Opcode.OP_16 && ++(this.nOpCount) > 201) {
6978 this.errstr = 'SCRIPT_ERR_OP_COUNT';
6979 return false;
6980 }
6981
6982
6983 if (opcodenum === Opcode.OP_CAT ||
6984 opcodenum === Opcode.OP_SUBSTR ||
6985 opcodenum === Opcode.OP_LEFT ||
6986 opcodenum === Opcode.OP_RIGHT ||
6987 opcodenum === Opcode.OP_INVERT ||
6988 opcodenum === Opcode.OP_AND ||
6989 opcodenum === Opcode.OP_OR ||
6990 opcodenum === Opcode.OP_XOR ||
6991 opcodenum === Opcode.OP_2MUL ||
6992 opcodenum === Opcode.OP_2DIV ||
6993 opcodenum === Opcode.OP_MUL ||
6994 opcodenum === Opcode.OP_DIV ||
6995 opcodenum === Opcode.OP_MOD ||
6996 opcodenum === Opcode.OP_LSHIFT ||
6997 opcodenum === Opcode.OP_RSHIFT) {
6998 this.errstr = 'SCRIPT_ERR_DISABLED_OPCODE';
6999 return false;
7000 }
7001
7002 if (fExec && 0 <= opcodenum && opcodenum <= Opcode.OP_PUSHDATA4) {
7003 if (fRequireMinimal && !this.script.checkMinimalPush(this.pc - 1)) {
7004 this.errstr = 'SCRIPT_ERR_MINIMALDATA';
7005 return false;
7006 }
7007 if (!chunk.buf) {
7008 this.stack.push(Interpreter.false);
7009 } else if (chunk.len !== chunk.buf.length) {
7010 throw new Error('Length of push value not equal to length of data');
7011 } else {
7012 this.stack.push(chunk.buf);
7013 }
7014 } else if (fExec || (Opcode.OP_IF <= opcodenum && opcodenum <= Opcode.OP_ENDIF)) {
7015 switch (opcodenum) {
7016 // Push value
7017 case Opcode.OP_1NEGATE:
7018 case Opcode.OP_1:
7019 case Opcode.OP_2:
7020 case Opcode.OP_3:
7021 case Opcode.OP_4:
7022 case Opcode.OP_5:
7023 case Opcode.OP_6:
7024 case Opcode.OP_7:
7025 case Opcode.OP_8:
7026 case Opcode.OP_9:
7027 case Opcode.OP_10:
7028 case Opcode.OP_11:
7029 case Opcode.OP_12:
7030 case Opcode.OP_13:
7031 case Opcode.OP_14:
7032 case Opcode.OP_15:
7033 case Opcode.OP_16:
7034 {
7035 // ( -- value)
7036 // ScriptNum bn((int)opcode - (int)(Opcode.OP_1 - 1));
7037 n = opcodenum - (Opcode.OP_1 - 1);
7038 buf = new BN(n).toScriptNumBuffer();
7039 this.stack.push(buf);
7040 // The result of these opcodes should always be the minimal way to push the data
7041 // they push, so no need for a CheckMinimalPush here.
7042 }
7043 break;
7044
7045
7046 //
7047 // Control
7048 //
7049 case Opcode.OP_NOP:
7050 break;
7051
7052 case Opcode.OP_NOP2:
7053 case Opcode.OP_CHECKLOCKTIMEVERIFY:
7054
7055 if (!(this.flags & Interpreter.SCRIPT_VERIFY_CHECKLOCKTIMEVERIFY)) {
7056 // not enabled; treat as a NOP2
7057 if (this.flags & Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
7058 this.errstr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS';
7059 return false;
7060 }
7061 break;
7062 }
7063
7064 if (this.stack.length < 1) {
7065 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7066 return false;
7067 }
7068
7069 // Note that elsewhere numeric opcodes are limited to
7070 // operands in the range -2**31+1 to 2**31-1, however it is
7071 // legal for opcodes to produce results exceeding that
7072 // range. This limitation is implemented by CScriptNum's
7073 // default 4-byte limit.
7074 //
7075 // If we kept to that limit we'd have a year 2038 problem,
7076 // even though the nLockTime field in transactions
7077 // themselves is uint32 which only becomes meaningless
7078 // after the year 2106.
7079 //
7080 // Thus as a special case we tell CScriptNum to accept up
7081 // to 5-byte bignums, which are good until 2**39-1, well
7082 // beyond the 2**32-1 limit of the nLockTime field itself.
7083 var nLockTime = BN.fromScriptNumBuffer(this.stack[this.stack.length - 1], fRequireMinimal, 5);
7084
7085 // In the rare event that the argument may be < 0 due to
7086 // some arithmetic being done first, you can always use
7087 // 0 MAX CHECKLOCKTIMEVERIFY.
7088 if (nLockTime.lt(new BN(0))) {
7089 this.errstr = 'SCRIPT_ERR_NEGATIVE_LOCKTIME';
7090 return false;
7091 }
7092
7093 // Actually compare the specified lock time with the transaction.
7094 if (!this.checkLockTime(nLockTime)) {
7095 this.errstr = 'SCRIPT_ERR_UNSATISFIED_LOCKTIME';
7096 return false;
7097 }
7098 break;
7099
7100 case Opcode.OP_NOP3:
7101 case Opcode.OP_CHECKSEQUENCEVERIFY:
7102
7103 if (!(this.flags & Interpreter.SCRIPT_VERIFY_CHECKSEQUENCEVERIFY)) {
7104 // not enabled; treat as a NOP3
7105 if (this.flags & Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
7106 this.errstr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS';
7107 return false;
7108 }
7109 break;
7110 }
7111
7112 if (this.stack.length < 1) {
7113 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7114 return false;
7115 }
7116
7117
7118 // nSequence, like nLockTime, is a 32-bit unsigned
7119 // integer field. See the comment in CHECKLOCKTIMEVERIFY
7120 // regarding 5-byte numeric operands.
7121
7122 var nSequence = BN.fromScriptNumBuffer(this.stack[this.stack.length - 1], fRequireMinimal, 5);
7123
7124
7125 // In the rare event that the argument may be < 0 due to
7126 // some arithmetic being done first, you can always use
7127 // 0 MAX CHECKSEQUENCEVERIFY.
7128 if (nSequence.lt(new BN(0))) {
7129 this.errstr = 'SCRIPT_ERR_NEGATIVE_LOCKTIME';
7130 return false;
7131 }
7132
7133 // To provide for future soft-fork extensibility, if the
7134 // operand has the disabled lock-time flag set,
7135 // CHECKSEQUENCEVERIFY behaves as a NOP.
7136 if ((nSequence &
7137 Interpreter.SEQUENCE_LOCKTIME_DISABLE_FLAG) != 0) {
7138 break;
7139 }
7140
7141 // Actually compare the specified lock time with the transaction.
7142 if (!this.checkSequence(nSequence)) {
7143 this.errstr = 'SCRIPT_ERR_UNSATISFIED_LOCKTIME';
7144 return false;
7145 }
7146 break;
7147
7148
7149
7150 case Opcode.OP_NOP1:
7151 case Opcode.OP_NOP4:
7152 case Opcode.OP_NOP5:
7153 case Opcode.OP_NOP6:
7154 case Opcode.OP_NOP7:
7155 case Opcode.OP_NOP8:
7156 case Opcode.OP_NOP9:
7157 case Opcode.OP_NOP10:
7158 {
7159 if (this.flags & Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) {
7160 this.errstr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS';
7161 return false;
7162 }
7163 }
7164 break;
7165
7166 case Opcode.OP_IF:
7167 case Opcode.OP_NOTIF:
7168 {
7169 // <expression> if [statements] [else [statements]] endif
7170 // bool fValue = false;
7171 fValue = false;
7172 if (fExec) {
7173 if (this.stack.length < 1) {
7174 this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL';
7175 return false;
7176 }
7177
7178 buf = this.stack[this.stack.length - 1];
7179
7180 if (this.flags & Interpreter.SCRIPT_VERIFY_MINIMALIF) {
7181 buf = this.stack[this.stack.length - 1];
7182 if (buf.length > 1) {
7183 this.errstr = 'SCRIPT_ERR_MINIMALIF';
7184 return false;
7185 }
7186 if (buf.length == 1 && buf[0]!=1) {
7187 this.errstr = 'SCRIPT_ERR_MINIMALIF';
7188 return false;
7189 }
7190 }
7191 fValue = Interpreter.castToBool(buf);
7192 if (opcodenum === Opcode.OP_NOTIF) {
7193 fValue = !fValue;
7194 }
7195 this.stack.pop();
7196 }
7197 this.vfExec.push(fValue);
7198 }
7199 break;
7200
7201 case Opcode.OP_ELSE:
7202 {
7203 if (this.vfExec.length === 0) {
7204 this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL';
7205 return false;
7206 }
7207 this.vfExec[this.vfExec.length - 1] = !this.vfExec[this.vfExec.length - 1];
7208 }
7209 break;
7210
7211 case Opcode.OP_ENDIF:
7212 {
7213 if (this.vfExec.length === 0) {
7214 this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL';
7215 return false;
7216 }
7217 this.vfExec.pop();
7218 }
7219 break;
7220
7221 case Opcode.OP_VERIFY:
7222 {
7223 // (true -- ) or
7224 // (false -- false) and return
7225 if (this.stack.length < 1) {
7226 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7227 return false;
7228 }
7229 buf = this.stack[this.stack.length - 1];
7230 fValue = Interpreter.castToBool(buf);
7231 if (fValue) {
7232 this.stack.pop();
7233 } else {
7234 this.errstr = 'SCRIPT_ERR_VERIFY';
7235 return false;
7236 }
7237 }
7238 break;
7239
7240 case Opcode.OP_RETURN:
7241 {
7242 this.errstr = 'SCRIPT_ERR_OP_RETURN';
7243 return false;
7244 }
7245 break;
7246
7247
7248 //
7249 // Stack ops
7250 //
7251 case Opcode.OP_TOALTSTACK:
7252 {
7253 if (this.stack.length < 1) {
7254 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7255 return false;
7256 }
7257 this.altstack.push(this.stack.pop());
7258 }
7259 break;
7260
7261 case Opcode.OP_FROMALTSTACK:
7262 {
7263 if (this.altstack.length < 1) {
7264 this.errstr = 'SCRIPT_ERR_INVALID_ALTSTACK_OPERATION';
7265 return false;
7266 }
7267 this.stack.push(this.altstack.pop());
7268 }
7269 break;
7270
7271 case Opcode.OP_2DROP:
7272 {
7273 // (x1 x2 -- )
7274 if (this.stack.length < 2) {
7275 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7276 return false;
7277 }
7278 this.stack.pop();
7279 this.stack.pop();
7280 }
7281 break;
7282
7283 case Opcode.OP_2DUP:
7284 {
7285 // (x1 x2 -- x1 x2 x1 x2)
7286 if (this.stack.length < 2) {
7287 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7288 return false;
7289 }
7290 buf1 = this.stack[this.stack.length - 2];
7291 buf2 = this.stack[this.stack.length - 1];
7292 this.stack.push(buf1);
7293 this.stack.push(buf2);
7294 }
7295 break;
7296
7297 case Opcode.OP_3DUP:
7298 {
7299 // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3)
7300 if (this.stack.length < 3) {
7301 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7302 return false;
7303 }
7304 buf1 = this.stack[this.stack.length - 3];
7305 buf2 = this.stack[this.stack.length - 2];
7306 var buf3 = this.stack[this.stack.length - 1];
7307 this.stack.push(buf1);
7308 this.stack.push(buf2);
7309 this.stack.push(buf3);
7310 }
7311 break;
7312
7313 case Opcode.OP_2OVER:
7314 {
7315 // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2)
7316 if (this.stack.length < 4) {
7317 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7318 return false;
7319 }
7320 buf1 = this.stack[this.stack.length - 4];
7321 buf2 = this.stack[this.stack.length - 3];
7322 this.stack.push(buf1);
7323 this.stack.push(buf2);
7324 }
7325 break;
7326
7327 case Opcode.OP_2ROT:
7328 {
7329 // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2)
7330 if (this.stack.length < 6) {
7331 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7332 return false;
7333 }
7334 spliced = this.stack.splice(this.stack.length - 6, 2);
7335 this.stack.push(spliced[0]);
7336 this.stack.push(spliced[1]);
7337 }
7338 break;
7339
7340 case Opcode.OP_2SWAP:
7341 {
7342 // (x1 x2 x3 x4 -- x3 x4 x1 x2)
7343 if (this.stack.length < 4) {
7344 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7345 return false;
7346 }
7347 spliced = this.stack.splice(this.stack.length - 4, 2);
7348 this.stack.push(spliced[0]);
7349 this.stack.push(spliced[1]);
7350 }
7351 break;
7352
7353 case Opcode.OP_IFDUP:
7354 {
7355 // (x - 0 | x x)
7356 if (this.stack.length < 1) {
7357 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7358 return false;
7359 }
7360 buf = this.stack[this.stack.length - 1];
7361 fValue = Interpreter.castToBool(buf);
7362 if (fValue) {
7363 this.stack.push(buf);
7364 }
7365 }
7366 break;
7367
7368 case Opcode.OP_DEPTH:
7369 {
7370 // -- stacksize
7371 buf = new BN(this.stack.length).toScriptNumBuffer();
7372 this.stack.push(buf);
7373 }
7374 break;
7375
7376 case Opcode.OP_DROP:
7377 {
7378 // (x -- )
7379 if (this.stack.length < 1) {
7380 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7381 return false;
7382 }
7383 this.stack.pop();
7384 }
7385 break;
7386
7387 case Opcode.OP_DUP:
7388 {
7389 // (x -- x x)
7390 if (this.stack.length < 1) {
7391 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7392 return false;
7393 }
7394 this.stack.push(this.stack[this.stack.length - 1]);
7395 }
7396 break;
7397
7398 case Opcode.OP_NIP:
7399 {
7400 // (x1 x2 -- x2)
7401 if (this.stack.length < 2) {
7402 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7403 return false;
7404 }
7405 this.stack.splice(this.stack.length - 2, 1);
7406 }
7407 break;
7408
7409 case Opcode.OP_OVER:
7410 {
7411 // (x1 x2 -- x1 x2 x1)
7412 if (this.stack.length < 2) {
7413 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7414 return false;
7415 }
7416 this.stack.push(this.stack[this.stack.length - 2]);
7417 }
7418 break;
7419
7420 case Opcode.OP_PICK:
7421 case Opcode.OP_ROLL:
7422 {
7423 // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn)
7424 // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn)
7425 if (this.stack.length < 2) {
7426 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7427 return false;
7428 }
7429 buf = this.stack[this.stack.length - 1];
7430 bn = BN.fromScriptNumBuffer(buf, fRequireMinimal);
7431 n = bn.toNumber();
7432 this.stack.pop();
7433 if (n < 0 || n >= this.stack.length) {
7434 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7435 return false;
7436 }
7437 buf = this.stack[this.stack.length - n - 1];
7438 if (opcodenum === Opcode.OP_ROLL) {
7439 this.stack.splice(this.stack.length - n - 1, 1);
7440 }
7441 this.stack.push(buf);
7442 }
7443 break;
7444
7445 case Opcode.OP_ROT:
7446 {
7447 // (x1 x2 x3 -- x2 x3 x1)
7448 // x2 x1 x3 after first swap
7449 // x2 x3 x1 after second swap
7450 if (this.stack.length < 3) {
7451 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7452 return false;
7453 }
7454 x1 = this.stack[this.stack.length - 3];
7455 x2 = this.stack[this.stack.length - 2];
7456 var x3 = this.stack[this.stack.length - 1];
7457 this.stack[this.stack.length - 3] = x2;
7458 this.stack[this.stack.length - 2] = x3;
7459 this.stack[this.stack.length - 1] = x1;
7460 }
7461 break;
7462
7463 case Opcode.OP_SWAP:
7464 {
7465 // (x1 x2 -- x2 x1)
7466 if (this.stack.length < 2) {
7467 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7468 return false;
7469 }
7470 x1 = this.stack[this.stack.length - 2];
7471 x2 = this.stack[this.stack.length - 1];
7472 this.stack[this.stack.length - 2] = x2;
7473 this.stack[this.stack.length - 1] = x1;
7474 }
7475 break;
7476
7477 case Opcode.OP_TUCK:
7478 {
7479 // (x1 x2 -- x2 x1 x2)
7480 if (this.stack.length < 2) {
7481 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7482 return false;
7483 }
7484 this.stack.splice(this.stack.length - 2, 0, this.stack[this.stack.length - 1]);
7485 }
7486 break;
7487
7488
7489 case Opcode.OP_SIZE:
7490 {
7491 // (in -- in size)
7492 if (this.stack.length < 1) {
7493 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7494 return false;
7495 }
7496 bn = new BN(this.stack[this.stack.length - 1].length);
7497 this.stack.push(bn.toScriptNumBuffer());
7498 }
7499 break;
7500
7501
7502 //
7503 // Bitwise logic
7504 //
7505 case Opcode.OP_EQUAL:
7506 case Opcode.OP_EQUALVERIFY:
7507 //case Opcode.OP_NOTEQUAL: // use Opcode.OP_NUMNOTEQUAL
7508 {
7509 // (x1 x2 - bool)
7510 if (this.stack.length < 2) {
7511 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7512 return false;
7513 }
7514 buf1 = this.stack[this.stack.length - 2];
7515 buf2 = this.stack[this.stack.length - 1];
7516 var fEqual = buf1.toString('hex') === buf2.toString('hex');
7517 this.stack.pop();
7518 this.stack.pop();
7519 this.stack.push(fEqual ? Interpreter.true : Interpreter.false);
7520 if (opcodenum === Opcode.OP_EQUALVERIFY) {
7521 if (fEqual) {
7522 this.stack.pop();
7523 } else {
7524 this.errstr = 'SCRIPT_ERR_EQUALVERIFY';
7525 return false;
7526 }
7527 }
7528 }
7529 break;
7530
7531
7532 //
7533 // Numeric
7534 //
7535 case Opcode.OP_1ADD:
7536 case Opcode.OP_1SUB:
7537 case Opcode.OP_NEGATE:
7538 case Opcode.OP_ABS:
7539 case Opcode.OP_NOT:
7540 case Opcode.OP_0NOTEQUAL:
7541 {
7542 // (in -- out)
7543 if (this.stack.length < 1) {
7544 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7545 return false;
7546 }
7547 buf = this.stack[this.stack.length - 1];
7548 bn = BN.fromScriptNumBuffer(buf, fRequireMinimal);
7549 switch (opcodenum) {
7550 case Opcode.OP_1ADD:
7551 bn = bn.add(BN.One);
7552 break;
7553 case Opcode.OP_1SUB:
7554 bn = bn.sub(BN.One);
7555 break;
7556 case Opcode.OP_NEGATE:
7557 bn = bn.neg();
7558 break;
7559 case Opcode.OP_ABS:
7560 if (bn.cmp(BN.Zero) < 0) {
7561 bn = bn.neg();
7562 }
7563 break;
7564 case Opcode.OP_NOT:
7565 bn = new BN((bn.cmp(BN.Zero) === 0) + 0);
7566 break;
7567 case Opcode.OP_0NOTEQUAL:
7568 bn = new BN((bn.cmp(BN.Zero) !== 0) + 0);
7569 break;
7570 //default: assert(!'invalid opcode'); break; // TODO: does this ever occur?
7571 }
7572 this.stack.pop();
7573 this.stack.push(bn.toScriptNumBuffer());
7574 }
7575 break;
7576
7577 case Opcode.OP_ADD:
7578 case Opcode.OP_SUB:
7579 case Opcode.OP_BOOLAND:
7580 case Opcode.OP_BOOLOR:
7581 case Opcode.OP_NUMEQUAL:
7582 case Opcode.OP_NUMEQUALVERIFY:
7583 case Opcode.OP_NUMNOTEQUAL:
7584 case Opcode.OP_LESSTHAN:
7585 case Opcode.OP_GREATERTHAN:
7586 case Opcode.OP_LESSTHANOREQUAL:
7587 case Opcode.OP_GREATERTHANOREQUAL:
7588 case Opcode.OP_MIN:
7589 case Opcode.OP_MAX:
7590 {
7591 // (x1 x2 -- out)
7592 if (this.stack.length < 2) {
7593 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7594 return false;
7595 }
7596 bn1 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 2], fRequireMinimal);
7597 bn2 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 1], fRequireMinimal);
7598 bn = new BN(0);
7599
7600 switch (opcodenum) {
7601 case Opcode.OP_ADD:
7602 bn = bn1.add(bn2);
7603 break;
7604
7605 case Opcode.OP_SUB:
7606 bn = bn1.sub(bn2);
7607 break;
7608
7609 // case Opcode.OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break;
7610 case Opcode.OP_BOOLAND:
7611 bn = new BN(((bn1.cmp(BN.Zero) !== 0) && (bn2.cmp(BN.Zero) !== 0)) + 0);
7612 break;
7613 // case Opcode.OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break;
7614 case Opcode.OP_BOOLOR:
7615 bn = new BN(((bn1.cmp(BN.Zero) !== 0) || (bn2.cmp(BN.Zero) !== 0)) + 0);
7616 break;
7617 // case Opcode.OP_NUMEQUAL: bn = (bn1 == bn2); break;
7618 case Opcode.OP_NUMEQUAL:
7619 bn = new BN((bn1.cmp(bn2) === 0) + 0);
7620 break;
7621 // case Opcode.OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break;
7622 case Opcode.OP_NUMEQUALVERIFY:
7623 bn = new BN((bn1.cmp(bn2) === 0) + 0);
7624 break;
7625 // case Opcode.OP_NUMNOTEQUAL: bn = (bn1 != bn2); break;
7626 case Opcode.OP_NUMNOTEQUAL:
7627 bn = new BN((bn1.cmp(bn2) !== 0) + 0);
7628 break;
7629 // case Opcode.OP_LESSTHAN: bn = (bn1 < bn2); break;
7630 case Opcode.OP_LESSTHAN:
7631 bn = new BN((bn1.cmp(bn2) < 0) + 0);
7632 break;
7633 // case Opcode.OP_GREATERTHAN: bn = (bn1 > bn2); break;
7634 case Opcode.OP_GREATERTHAN:
7635 bn = new BN((bn1.cmp(bn2) > 0) + 0);
7636 break;
7637 // case Opcode.OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break;
7638 case Opcode.OP_LESSTHANOREQUAL:
7639 bn = new BN((bn1.cmp(bn2) <= 0) + 0);
7640 break;
7641 // case Opcode.OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break;
7642 case Opcode.OP_GREATERTHANOREQUAL:
7643 bn = new BN((bn1.cmp(bn2) >= 0) + 0);
7644 break;
7645 case Opcode.OP_MIN:
7646 bn = (bn1.cmp(bn2) < 0 ? bn1 : bn2);
7647 break;
7648 case Opcode.OP_MAX:
7649 bn = (bn1.cmp(bn2) > 0 ? bn1 : bn2);
7650 break;
7651 // default: assert(!'invalid opcode'); break; //TODO: does this ever occur?
7652 }
7653 this.stack.pop();
7654 this.stack.pop();
7655 this.stack.push(bn.toScriptNumBuffer());
7656
7657 if (opcodenum === Opcode.OP_NUMEQUALVERIFY) {
7658 // if (CastToBool(stacktop(-1)))
7659 if (Interpreter.castToBool(this.stack[this.stack.length - 1])) {
7660 this.stack.pop();
7661 } else {
7662 this.errstr = 'SCRIPT_ERR_NUMEQUALVERIFY';
7663 return false;
7664 }
7665 }
7666 }
7667 break;
7668
7669 case Opcode.OP_WITHIN:
7670 {
7671 // (x min max -- out)
7672 if (this.stack.length < 3) {
7673 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7674 return false;
7675 }
7676 bn1 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 3], fRequireMinimal);
7677 bn2 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 2], fRequireMinimal);
7678 var bn3 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 1], fRequireMinimal);
7679 //bool fValue = (bn2 <= bn1 && bn1 < bn3);
7680 fValue = (bn2.cmp(bn1) <= 0) && (bn1.cmp(bn3) < 0);
7681 this.stack.pop();
7682 this.stack.pop();
7683 this.stack.pop();
7684 this.stack.push(fValue ? Interpreter.true : Interpreter.false);
7685 }
7686 break;
7687
7688
7689 //
7690 // Crypto
7691 //
7692 case Opcode.OP_RIPEMD160:
7693 case Opcode.OP_SHA1:
7694 case Opcode.OP_SHA256:
7695 case Opcode.OP_HASH160:
7696 case Opcode.OP_HASH256:
7697 {
7698 // (in -- hash)
7699 if (this.stack.length < 1) {
7700 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7701 return false;
7702 }
7703 buf = this.stack[this.stack.length - 1];
7704 //valtype vchHash((opcode == Opcode.OP_RIPEMD160 ||
7705 // opcode == Opcode.OP_SHA1 || opcode == Opcode.OP_HASH160) ? 20 : 32);
7706 var bufHash;
7707 if (opcodenum === Opcode.OP_RIPEMD160) {
7708 bufHash = Hash.ripemd160(buf);
7709 } else if (opcodenum === Opcode.OP_SHA1) {
7710 bufHash = Hash.sha1(buf);
7711 } else if (opcodenum === Opcode.OP_SHA256) {
7712 bufHash = Hash.sha256(buf);
7713 } else if (opcodenum === Opcode.OP_HASH160) {
7714 bufHash = Hash.sha256ripemd160(buf);
7715 } else if (opcodenum === Opcode.OP_HASH256) {
7716 bufHash = Hash.sha256sha256(buf);
7717 }
7718 this.stack.pop();
7719 this.stack.push(bufHash);
7720 }
7721 break;
7722
7723 case Opcode.OP_CODESEPARATOR:
7724 {
7725 // Hash starts after the code separator
7726 this.pbegincodehash = this.pc;
7727 }
7728 break;
7729
7730 case Opcode.OP_CHECKSIG:
7731 case Opcode.OP_CHECKSIGVERIFY:
7732 {
7733 // (sig pubkey -- bool)
7734 if (this.stack.length < 2) {
7735 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7736 return false;
7737 }
7738
7739 bufSig = this.stack[this.stack.length - 2];
7740 bufPubkey = this.stack[this.stack.length - 1];
7741 if (!this.checkSignatureEncoding(bufSig) || !this.checkPubkeyEncoding(bufPubkey)) {
7742 return false;
7743 }
7744
7745 // Subset of script starting at the most recent codeseparator
7746 // CScript scriptCode(pbegincodehash, pend);
7747 subscript = new Script().set({
7748 chunks: this.script.chunks.slice(this.pbegincodehash)
7749 });
7750
7751 // Drop the signature, since there's no way for a signature to sign itself
7752 var tmpScript = new Script().add(bufSig);
7753 subscript.findAndDelete(tmpScript);
7754
7755 try {
7756 sig = Signature.fromTxFormat(bufSig);
7757 pubkey = PublicKey.fromBuffer(bufPubkey, false);
7758 fSuccess = this.tx.verifySignature(sig, pubkey, this.nin, subscript, this.sigversion, this.satoshis);
7759 } catch (e) {
7760 //invalid sig or pubkey
7761 fSuccess = false;
7762 }
7763
7764 if (!fSuccess && (this.flags & Interpreter.SCRIPT_VERIFY_NULLFAIL) &&
7765 bufSig.length) {
7766 this.errstr = 'SCRIPT_ERR_NULLFAIL';
7767 return false;
7768 }
7769
7770 this.stack.pop();
7771 this.stack.pop();
7772
7773 // stack.push_back(fSuccess ? vchTrue : vchFalse);
7774 this.stack.push(fSuccess ? Interpreter.true : Interpreter.false);
7775 if (opcodenum === Opcode.OP_CHECKSIGVERIFY) {
7776 if (fSuccess) {
7777 this.stack.pop();
7778 } else {
7779 this.errstr = 'SCRIPT_ERR_CHECKSIGVERIFY';
7780 return false;
7781 }
7782 }
7783 }
7784 break;
7785
7786 case Opcode.OP_CHECKMULTISIG:
7787 case Opcode.OP_CHECKMULTISIGVERIFY:
7788 {
7789 // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool)
7790
7791 var i = 1;
7792 if (this.stack.length < i) {
7793 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7794 return false;
7795 }
7796
7797 var nKeysCount = BN.fromScriptNumBuffer(this.stack[this.stack.length - i], fRequireMinimal).toNumber();
7798 if (nKeysCount < 0 || nKeysCount > 20) {
7799 this.errstr = 'SCRIPT_ERR_PUBKEY_COUNT';
7800 return false;
7801 }
7802 this.nOpCount += nKeysCount;
7803 if (this.nOpCount > 201) {
7804 this.errstr = 'SCRIPT_ERR_OP_COUNT';
7805 return false;
7806 }
7807 // int ikey = ++i;
7808 var ikey = ++i;
7809 i += nKeysCount;
7810
7811 // ikey2 is the position of last non-signature item in
7812 // the stack. Top stack item = 1. With
7813 // SCRIPT_VERIFY_NULLFAIL, this is used for cleanup if
7814 // operation fails.
7815 var ikey2 = nKeysCount + 2;
7816
7817 if (this.stack.length < i) {
7818 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7819 return false;
7820 }
7821
7822 var nSigsCount = BN.fromScriptNumBuffer(this.stack[this.stack.length - i], fRequireMinimal).toNumber();
7823 if (nSigsCount < 0 || nSigsCount > nKeysCount) {
7824 this.errstr = 'SCRIPT_ERR_SIG_COUNT';
7825 return false;
7826 }
7827 // int isig = ++i;
7828 var isig = ++i;
7829 i += nSigsCount;
7830 if (this.stack.length < i) {
7831 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7832 return false;
7833 }
7834
7835 // Subset of script starting at the most recent codeseparator
7836 subscript = new Script().set({
7837 chunks: this.script.chunks.slice(this.pbegincodehash)
7838 });
7839
7840 // Drop the signatures, since there's no way for a signature to sign itself
7841 for (var k = 0; k < nSigsCount; k++) {
7842 bufSig = this.stack[this.stack.length - isig - k];
7843 subscript.findAndDelete(new Script().add(bufSig));
7844 }
7845
7846 fSuccess = true;
7847 while (fSuccess && nSigsCount > 0) {
7848 // valtype& vchSig = stacktop(-isig);
7849 bufSig = this.stack[this.stack.length - isig];
7850 // valtype& vchPubKey = stacktop(-ikey);
7851 bufPubkey = this.stack[this.stack.length - ikey];
7852
7853 if (!this.checkSignatureEncoding(bufSig) || !this.checkPubkeyEncoding(bufPubkey)) {
7854 return false;
7855 }
7856
7857 var fOk;
7858 try {
7859 sig = Signature.fromTxFormat(bufSig);
7860 pubkey = PublicKey.fromBuffer(bufPubkey, false);
7861 fOk = this.tx.verifySignature(sig, pubkey, this.nin, subscript, this.sigversion, this.satoshis);
7862 } catch (e) {
7863 //invalid sig or pubkey
7864 fOk = false;
7865 }
7866
7867 if (fOk) {
7868 isig++;
7869 nSigsCount--;
7870 }
7871 ikey++;
7872 nKeysCount--;
7873
7874 // If there are more signatures left than keys left,
7875 // then too many signatures have failed
7876 if (nSigsCount > nKeysCount) {
7877 fSuccess = false;
7878 }
7879 }
7880
7881
7882 // Clean up stack of actual arguments
7883 while (i-- > 1) {
7884 if (!fSuccess && (this.flags & Interpreter.SCRIPT_VERIFY_NULLFAIL) &&
7885 !ikey2 && this.stack[this.stack.length - 1].length) {
7886
7887 this.errstr = 'SCRIPT_ERR_NULLFAIL';
7888 return false;
7889 }
7890
7891 if (ikey2 > 0) {
7892 ikey2--;
7893 }
7894
7895 this.stack.pop();
7896 }
7897
7898 // A bug causes CHECKMULTISIG to consume one extra argument
7899 // whose contents were not checked in any way.
7900 //
7901 // Unfortunately this is a potential source of mutability,
7902 // so optionally verify it is exactly equal to zero prior
7903 // to removing it from the stack.
7904 if (this.stack.length < 1) {
7905 this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION';
7906 return false;
7907 }
7908 if ((this.flags & Interpreter.SCRIPT_VERIFY_NULLDUMMY) && this.stack[this.stack.length - 1].length) {
7909 this.errstr = 'SCRIPT_ERR_SIG_NULLDUMMY';
7910 return false;
7911 }
7912 this.stack.pop();
7913
7914 this.stack.push(fSuccess ? Interpreter.true : Interpreter.false);
7915
7916 if (opcodenum === Opcode.OP_CHECKMULTISIGVERIFY) {
7917 if (fSuccess) {
7918 this.stack.pop();
7919 } else {
7920 this.errstr = 'SCRIPT_ERR_CHECKMULTISIGVERIFY';
7921 return false;
7922 }
7923 }
7924 }
7925 break;
7926
7927 default:
7928 this.errstr = 'SCRIPT_ERR_BAD_OPCODE';
7929 return false;
7930 }
7931 }
7932
7933 return true;
7934};
7935
7936
7937}).call(this)}).call(this,require("buffer").Buffer)
7938},{"../crypto/bn":6,"../crypto/hash":8,"../crypto/signature":11,"../opcode":24,"../publickey":26,"../transaction":30,"./script":29,"buffer":132,"lodash":210}],29:[function(require,module,exports){
7939(function (Buffer){(function (){
7940'use strict';
7941
7942var Address = require('../address');
7943var BufferReader = require('../encoding/bufferreader');
7944var BufferWriter = require('../encoding/bufferwriter');
7945var Hash = require('../crypto/hash');
7946var Opcode = require('../opcode');
7947var PublicKey = require('../publickey');
7948var Signature = require('../crypto/signature');
7949var Networks = require('../networks');
7950var $ = require('../util/preconditions');
7951var _ = require('lodash');
7952var errors = require('../errors');
7953var buffer = require('buffer');
7954var BufferUtil = require('../util/buffer');
7955var JSUtil = require('../util/js');
7956
7957/**
7958 * A bitcoin transaction script. Each transaction's inputs and outputs
7959 * has a script that is evaluated to validate it's spending.
7960 *
7961 * See https://en.bitcoin.it/wiki/Script
7962 *
7963 * @constructor
7964 * @param {Object|string|Buffer=} from optional data to populate script
7965 */
7966var Script = function Script(from) {
7967 if (!(this instanceof Script)) {
7968 return new Script(from);
7969 }
7970 this.chunks = [];
7971
7972 if (BufferUtil.isBuffer(from)) {
7973 return Script.fromBuffer(from);
7974 } else if (from instanceof Address) {
7975 return Script.fromAddress(from);
7976 } else if (from instanceof Script) {
7977 return Script.fromBuffer(from.toBuffer());
7978 } else if (_.isString(from)) {
7979 return Script.fromString(from);
7980 } else if (_.isObject(from) && _.isArray(from.chunks)) {
7981 this.set(from);
7982 }
7983};
7984
7985Script.VERIFY_TAPROOT = (1 << 17);
7986
7987
7988Script.prototype.set = function(obj) {
7989 $.checkArgument(_.isObject(obj));
7990 $.checkArgument(_.isArray(obj.chunks));
7991 this.chunks = obj.chunks;
7992 return this;
7993};
7994
7995Script.fromBuffer = function(buffer) {
7996 var script = new Script();
7997 script.chunks = [];
7998
7999 var br = new BufferReader(buffer);
8000 while (!br.finished()) {
8001 try {
8002 var opcodenum = br.readUInt8();
8003
8004 var len, buf;
8005 if (opcodenum > 0 && opcodenum < Opcode.OP_PUSHDATA1) {
8006 len = opcodenum;
8007 script.chunks.push({
8008 buf: br.read(len),
8009 len: len,
8010 opcodenum: opcodenum
8011 });
8012 } else if (opcodenum === Opcode.OP_PUSHDATA1) {
8013 len = br.readUInt8();
8014 buf = br.read(len);
8015 script.chunks.push({
8016 buf: buf,
8017 len: len,
8018 opcodenum: opcodenum
8019 });
8020 } else if (opcodenum === Opcode.OP_PUSHDATA2) {
8021 len = br.readUInt16LE();
8022 buf = br.read(len);
8023 script.chunks.push({
8024 buf: buf,
8025 len: len,
8026 opcodenum: opcodenum
8027 });
8028 } else if (opcodenum === Opcode.OP_PUSHDATA4) {
8029 len = br.readUInt32LE();
8030 buf = br.read(len);
8031 script.chunks.push({
8032 buf: buf,
8033 len: len,
8034 opcodenum: opcodenum
8035 });
8036 } else {
8037 script.chunks.push({
8038 opcodenum: opcodenum
8039 });
8040 }
8041 } catch (e) {
8042 if (e instanceof RangeError) {
8043 throw new errors.Script.InvalidBuffer(buffer.toString('hex'));
8044 }
8045 throw e;
8046 }
8047 }
8048
8049 return script;
8050};
8051
8052Script.prototype.toBuffer = function() {
8053 var bw = new BufferWriter();
8054
8055 for (var i = 0; i < this.chunks.length; i++) {
8056 var chunk = this.chunks[i];
8057 var opcodenum = chunk.opcodenum;
8058 bw.writeUInt8(chunk.opcodenum);
8059 if (chunk.buf) {
8060 if (opcodenum < Opcode.OP_PUSHDATA1) {
8061 bw.write(chunk.buf);
8062 } else if (opcodenum === Opcode.OP_PUSHDATA1) {
8063 bw.writeUInt8(chunk.len);
8064 bw.write(chunk.buf);
8065 } else if (opcodenum === Opcode.OP_PUSHDATA2) {
8066 bw.writeUInt16LE(chunk.len);
8067 bw.write(chunk.buf);
8068 } else if (opcodenum === Opcode.OP_PUSHDATA4) {
8069 bw.writeUInt32LE(chunk.len);
8070 bw.write(chunk.buf);
8071 }
8072 }
8073 }
8074
8075 return bw.concat();
8076};
8077
8078Script.fromASM = function(str) {
8079 var script = new Script();
8080 script.chunks = [];
8081
8082 var tokens = str.split(' ');
8083 var i = 0;
8084 while (i < tokens.length) {
8085 var token = tokens[i];
8086 var opcode = Opcode(token);
8087 var opcodenum = opcode.toNumber();
8088
8089 if (_.isUndefined(opcodenum)) {
8090 var buf = Buffer.from(tokens[i], 'hex');
8091 script.chunks.push({
8092 buf: buf,
8093 len: buf.length,
8094 opcodenum: buf.length
8095 });
8096 i = i + 1;
8097 } else if (opcodenum === Opcode.OP_PUSHDATA1 ||
8098 opcodenum === Opcode.OP_PUSHDATA2 ||
8099 opcodenum === Opcode.OP_PUSHDATA4) {
8100 script.chunks.push({
8101 buf: Buffer.from(tokens[i + 2], 'hex'),
8102 len: parseInt(tokens[i + 1]),
8103 opcodenum: opcodenum
8104 });
8105 i = i + 3;
8106 } else {
8107 script.chunks.push({
8108 opcodenum: opcodenum
8109 });
8110 i = i + 1;
8111 }
8112 }
8113 return script;
8114};
8115
8116Script.fromHex = function(str) {
8117 return new Script(Buffer.from(str, 'hex'));
8118};
8119
8120Script.fromString = function(str) {
8121 if (JSUtil.isHexa(str) || str.length === 0) {
8122 return new Script(Buffer.from(str, 'hex'));
8123 }
8124 var script = new Script();
8125 script.chunks = [];
8126
8127 var tokens = str.split(' ');
8128 var i = 0;
8129 while (i < tokens.length) {
8130 var token = tokens[i];
8131 var opcode = Opcode(token);
8132 var opcodenum = opcode.toNumber();
8133
8134 if (_.isUndefined(opcodenum)) {
8135 opcodenum = parseInt(token);
8136 if (opcodenum > 0 && opcodenum < Opcode.OP_PUSHDATA1) {
8137 script.chunks.push({
8138 buf: Buffer.from(tokens[i + 1].slice(2), 'hex'),
8139 len: opcodenum,
8140 opcodenum: opcodenum
8141 });
8142 i = i + 2;
8143 } else {
8144 throw new Error('Invalid script: ' + JSON.stringify(str));
8145 }
8146 } else if (opcodenum === Opcode.OP_PUSHDATA1 ||
8147 opcodenum === Opcode.OP_PUSHDATA2 ||
8148 opcodenum === Opcode.OP_PUSHDATA4) {
8149 if (tokens[i + 2].slice(0, 2) !== '0x') {
8150 throw new Error('Pushdata data must start with 0x');
8151 }
8152 script.chunks.push({
8153 buf: Buffer.from(tokens[i + 2].slice(2), 'hex'),
8154 len: parseInt(tokens[i + 1]),
8155 opcodenum: opcodenum
8156 });
8157 i = i + 3;
8158 } else {
8159 script.chunks.push({
8160 opcodenum: opcodenum
8161 });
8162 i = i + 1;
8163 }
8164 }
8165 return script;
8166};
8167
8168Script.prototype._chunkToString = function(chunk, type) {
8169 var opcodenum = chunk.opcodenum;
8170 var asm = (type === 'asm');
8171 var str = '';
8172 if (!chunk.buf) {
8173 // no data chunk
8174 if (typeof Opcode.reverseMap[opcodenum] !== 'undefined') {
8175 if (asm) {
8176 // A few cases where the opcode name differs from reverseMap
8177 // aside from 1 to 16 data pushes.
8178 if (opcodenum === 0) {
8179 // OP_0 -> 0
8180 str = str + ' 0';
8181 } else if(opcodenum === 79) {
8182 // OP_1NEGATE -> 1
8183 str = str + ' -1';
8184 } else {
8185 str = str + ' ' + Opcode(opcodenum).toString();
8186 }
8187 } else {
8188 str = str + ' ' + Opcode(opcodenum).toString();
8189 }
8190 } else {
8191 var numstr = opcodenum.toString(16);
8192 if (numstr.length % 2 !== 0) {
8193 numstr = '0' + numstr;
8194 }
8195 if (asm) {
8196 str = str + ' ' + numstr;
8197 } else {
8198 str = str + ' ' + '0x' + numstr;
8199 }
8200 }
8201 } else {
8202 // data chunk
8203 if (!asm && opcodenum === Opcode.OP_PUSHDATA1 ||
8204 opcodenum === Opcode.OP_PUSHDATA2 ||
8205 opcodenum === Opcode.OP_PUSHDATA4) {
8206 str = str + ' ' + Opcode(opcodenum).toString();
8207 }
8208 if (chunk.len > 0) {
8209 if (asm) {
8210 str = str + ' ' + chunk.buf.toString('hex');
8211 } else {
8212 str = str + ' ' + chunk.len + ' ' + '0x' + chunk.buf.toString('hex');
8213 }
8214 }
8215 }
8216 return str;
8217};
8218
8219Script.prototype.toASM = function() {
8220 var str = '';
8221 for (var i = 0; i < this.chunks.length; i++) {
8222 var chunk = this.chunks[i];
8223 str += this._chunkToString(chunk, 'asm');
8224 }
8225
8226 return str.substr(1);
8227};
8228
8229Script.prototype.toString = function() {
8230 var str = '';
8231 for (var i = 0; i < this.chunks.length; i++) {
8232 var chunk = this.chunks[i];
8233 str += this._chunkToString(chunk);
8234 }
8235
8236 return str.substr(1);
8237};
8238
8239Script.prototype.toHex = function() {
8240 return this.toBuffer().toString('hex');
8241};
8242
8243Script.prototype.inspect = function() {
8244 return '<Script: ' + this.toString() + '>';
8245};
8246
8247// script classification methods
8248
8249/**
8250 * @returns {boolean} if this is a pay to pubkey hash output script
8251 */
8252Script.prototype.isPublicKeyHashOut = function() {
8253 return !!(this.chunks.length === 5 &&
8254 this.chunks[0].opcodenum === Opcode.OP_DUP &&
8255 this.chunks[1].opcodenum === Opcode.OP_HASH160 &&
8256 this.chunks[2].buf &&
8257 this.chunks[2].buf.length === 20 &&
8258 this.chunks[3].opcodenum === Opcode.OP_EQUALVERIFY &&
8259 this.chunks[4].opcodenum === Opcode.OP_CHECKSIG);
8260};
8261
8262/**
8263 * @returns {boolean} if this is a pay to public key hash input script
8264 */
8265Script.prototype.isPublicKeyHashIn = function() {
8266 if (this.chunks.length === 2) {
8267 var signatureBuf = this.chunks[0].buf;
8268 var pubkeyBuf = this.chunks[1].buf;
8269 if (signatureBuf &&
8270 signatureBuf.length &&
8271 signatureBuf[0] === 0x30 &&
8272 pubkeyBuf &&
8273 pubkeyBuf.length
8274 ) {
8275 var version = pubkeyBuf[0];
8276 if ((version === 0x04 ||
8277 version === 0x06 ||
8278 version === 0x07) && pubkeyBuf.length === 65) {
8279 return true;
8280 } else if ((version === 0x03 || version === 0x02) && pubkeyBuf.length === 33) {
8281 return true;
8282 }
8283 }
8284 }
8285 return false;
8286};
8287
8288Script.prototype.getPublicKey = function() {
8289 $.checkState(this.isPublicKeyOut(), 'Can\'t retrieve PublicKey from a non-PK output');
8290 return this.chunks[0].buf;
8291};
8292
8293Script.prototype.getPublicKeyHash = function() {
8294 if (this.isPublicKeyHashOut()) {
8295 return this.chunks[2].buf;
8296 } else if (this.isWitnessPublicKeyHashOut()) {
8297 return this.chunks[1].buf;
8298 } else {
8299 throw new Error('Can\'t retrieve PublicKeyHash from a non-PKH output');
8300 }
8301};
8302
8303/**
8304 * @returns {boolean} if this is a public key output script
8305 */
8306Script.prototype.isPublicKeyOut = function() {
8307 if (this.chunks.length === 2 &&
8308 this.chunks[0].buf &&
8309 this.chunks[0].buf.length &&
8310 this.chunks[1].opcodenum === Opcode.OP_CHECKSIG) {
8311 var pubkeyBuf = this.chunks[0].buf;
8312 var version = pubkeyBuf[0];
8313 var isVersion = false;
8314 if ((version === 0x04 ||
8315 version === 0x06 ||
8316 version === 0x07) && pubkeyBuf.length === 65) {
8317 isVersion = true;
8318 } else if ((version === 0x03 || version === 0x02) && pubkeyBuf.length === 33) {
8319 isVersion = true;
8320 }
8321 if (isVersion) {
8322 return PublicKey.isValid(pubkeyBuf);
8323 }
8324 }
8325 return false;
8326};
8327
8328/**
8329 * @returns {boolean} if this is a pay to public key input script
8330 */
8331Script.prototype.isPublicKeyIn = function() {
8332 if (this.chunks.length === 1) {
8333 var signatureBuf = this.chunks[0].buf;
8334 if (signatureBuf &&
8335 signatureBuf.length &&
8336 signatureBuf[0] === 0x30) {
8337 return true;
8338 }
8339 }
8340 return false;
8341};
8342
8343/**
8344 * @returns {boolean} if this is a p2sh output script
8345 */
8346Script.prototype.isScriptHashOut = function() {
8347 var buf = this.toBuffer();
8348 return (buf.length === 23 &&
8349 buf[0] === Opcode.OP_HASH160 &&
8350 buf[1] === 0x14 &&
8351 buf[buf.length - 1] === Opcode.OP_EQUAL);
8352};
8353
8354/**
8355 * @returns {boolean} if this is a p2wsh output script
8356 */
8357Script.prototype.isWitnessScriptHashOut = function() {
8358 var buf = this.toBuffer();
8359 return (buf.length === 34 && buf[0] === Opcode.OP_0 && buf[1] === 32);
8360};
8361
8362/**
8363 * @returns {boolean} if this is a p2wpkh output script
8364 */
8365Script.prototype.isWitnessPublicKeyHashOut = function() {
8366 var buf = this.toBuffer();
8367 return (buf.length === 22 && buf[0] === Opcode.OP_0 && buf[1] === 20);
8368};
8369
8370/**
8371 * @returns {boolean} if this is a p2tr output script
8372 */
8373Script.prototype.isTaproot = function() {
8374 var buf = this.toBuffer();
8375 return (buf.length === 34 && buf[0] === Opcode.OP_1 && buf[1] === 32);
8376}
8377
8378/**
8379 * @param {Object=} values - The return values
8380 * @param {Number} values.version - Set with the witness version
8381 * @param {Buffer} values.program - Set with the witness program
8382 * @returns {boolean} if this is a p2wpkh output script
8383 */
8384Script.prototype.isWitnessProgram = function(values) {
8385 if (!values) {
8386 values = {};
8387 }
8388 var buf = this.toBuffer();
8389 if (buf.length < 4 || buf.length > 42) {
8390 return false;
8391 }
8392 if (buf[0] !== Opcode.OP_0 && !(buf[0] >= Opcode.OP_1 && buf[0] <= Opcode.OP_16)) {
8393 return false;
8394 }
8395
8396 if (buf.length === buf[1] + 2) {
8397 values.version = buf[0];
8398 values.program = buf.slice(2, buf.length);
8399 return true;
8400 }
8401
8402 return false;
8403};
8404
8405/**
8406 * @returns {boolean} if this is a p2sh input script
8407 * Note that these are frequently indistinguishable from pubkeyhashin
8408 */
8409Script.prototype.isScriptHashIn = function() {
8410 if (this.chunks.length <= 1) {
8411 return false;
8412 }
8413 var redeemChunk = this.chunks[this.chunks.length - 1];
8414 var redeemBuf = redeemChunk.buf;
8415 if (!redeemBuf) {
8416 return false;
8417 }
8418
8419 var redeemScript;
8420 try {
8421 redeemScript = Script.fromBuffer(redeemBuf);
8422 } catch (e) {
8423 if (e instanceof errors.Script.InvalidBuffer) {
8424 return false;
8425 }
8426 throw e;
8427 }
8428 var type = redeemScript.classify();
8429 return type !== Script.types.UNKNOWN;
8430};
8431
8432/**
8433 * @returns {boolean} if this is a mutlsig output script
8434 */
8435Script.prototype.isMultisigOut = function() {
8436 return (this.chunks.length > 3 &&
8437 Opcode.isSmallIntOp(this.chunks[0].opcodenum) &&
8438 this.chunks.slice(1, this.chunks.length - 2).every(function(obj) {
8439 return obj.buf && BufferUtil.isBuffer(obj.buf);
8440 }) &&
8441 Opcode.isSmallIntOp(this.chunks[this.chunks.length - 2].opcodenum) &&
8442 this.chunks[this.chunks.length - 1].opcodenum === Opcode.OP_CHECKMULTISIG);
8443};
8444
8445
8446/**
8447 * @returns {boolean} if this is a multisig input script
8448 */
8449Script.prototype.isMultisigIn = function() {
8450 return this.chunks.length >= 2 &&
8451 this.chunks[0].opcodenum === 0 &&
8452 this.chunks.slice(1, this.chunks.length).every(function(obj) {
8453 return obj.buf &&
8454 BufferUtil.isBuffer(obj.buf) &&
8455 Signature.isTxDER(obj.buf);
8456 });
8457};
8458
8459/**
8460 * @returns {boolean} true if this is a valid standard OP_RETURN output
8461 */
8462Script.prototype.isDataOut = function() {
8463 return this.chunks.length >= 1 &&
8464 this.chunks[0].opcodenum === Opcode.OP_RETURN &&
8465 (this.chunks.length === 1 ||
8466 (this.chunks.length === 2 &&
8467 this.chunks[1].buf &&
8468 this.chunks[1].buf.length <= Script.OP_RETURN_STANDARD_SIZE &&
8469 this.chunks[1].length === this.chunks.len));
8470};
8471
8472/**
8473 * Retrieve the associated data for this script.
8474 * In the case of a pay to public key hash, P2SH, P2WSH, or P2WPKH, return the hash.
8475 * In the case of a standard OP_RETURN, return the data
8476 * @returns {Buffer}
8477 */
8478Script.prototype.getData = function() {
8479 if (this.isDataOut() || this.isScriptHashOut() || this.isWitnessScriptHashOut() || this.isWitnessPublicKeyHashOut() || this.isTaproot()) {
8480 if (_.isUndefined(this.chunks[1])) {
8481 return Buffer.alloc(0);
8482 } else {
8483 return Buffer.from(this.chunks[1].buf);
8484 }
8485 }
8486 if (this.isPublicKeyHashOut()) {
8487 return Buffer.from(this.chunks[2].buf);
8488 }
8489 throw new Error('Unrecognized script type to get data from');
8490};
8491
8492/**
8493 * @returns {boolean} if the script is only composed of data pushing
8494 * opcodes or small int opcodes (OP_0, OP_1, ..., OP_16)
8495 */
8496Script.prototype.isPushOnly = function() {
8497 return _.every(this.chunks, function(chunk) {
8498 return chunk.opcodenum <= Opcode.OP_16;
8499 });
8500};
8501
8502
8503Script.types = {};
8504Script.types.UNKNOWN = 'Unknown';
8505Script.types.PUBKEY_OUT = 'Pay to public key';
8506Script.types.PUBKEY_IN = 'Spend from public key';
8507Script.types.PUBKEYHASH_OUT = 'Pay to public key hash';
8508Script.types.PUBKEYHASH_IN = 'Spend from public key hash';
8509Script.types.SCRIPTHASH_OUT = 'Pay to script hash';
8510Script.types.SCRIPTHASH_IN = 'Spend from script hash';
8511Script.types.MULTISIG_OUT = 'Pay to multisig';
8512Script.types.MULTISIG_IN = 'Spend from multisig';
8513Script.types.DATA_OUT = 'Data push';
8514
8515Script.OP_RETURN_STANDARD_SIZE = 80;
8516
8517/**
8518 * @returns {object} The Script type if it is a known form,
8519 * or Script.UNKNOWN if it isn't
8520 */
8521Script.prototype.classify = function() {
8522 if (this._isInput) {
8523 return this.classifyInput();
8524 } else if (this._isOutput) {
8525 return this.classifyOutput();
8526 } else {
8527 var outputType = this.classifyOutput();
8528 return outputType != Script.types.UNKNOWN ? outputType : this.classifyInput();
8529 }
8530};
8531
8532Script.outputIdentifiers = {};
8533Script.outputIdentifiers.PUBKEY_OUT = Script.prototype.isPublicKeyOut;
8534Script.outputIdentifiers.PUBKEYHASH_OUT = Script.prototype.isPublicKeyHashOut;
8535Script.outputIdentifiers.MULTISIG_OUT = Script.prototype.isMultisigOut;
8536Script.outputIdentifiers.SCRIPTHASH_OUT = Script.prototype.isScriptHashOut;
8537Script.outputIdentifiers.DATA_OUT = Script.prototype.isDataOut;
8538
8539/**
8540 * @returns {object} The Script type if it is a known form,
8541 * or Script.UNKNOWN if it isn't
8542 */
8543Script.prototype.classifyOutput = function() {
8544 for (var type in Script.outputIdentifiers) {
8545 if (Script.outputIdentifiers[type].bind(this)()) {
8546 return Script.types[type];
8547 }
8548 }
8549 return Script.types.UNKNOWN;
8550};
8551
8552Script.inputIdentifiers = {};
8553Script.inputIdentifiers.PUBKEY_IN = Script.prototype.isPublicKeyIn;
8554Script.inputIdentifiers.PUBKEYHASH_IN = Script.prototype.isPublicKeyHashIn;
8555Script.inputIdentifiers.MULTISIG_IN = Script.prototype.isMultisigIn;
8556Script.inputIdentifiers.SCRIPTHASH_IN = Script.prototype.isScriptHashIn;
8557
8558/**
8559 * @returns {object} The Script type if it is a known form,
8560 * or Script.UNKNOWN if it isn't
8561 */
8562Script.prototype.classifyInput = function() {
8563 for (var type in Script.inputIdentifiers) {
8564 if (Script.inputIdentifiers[type].bind(this)()) {
8565 return Script.types[type];
8566 }
8567 }
8568 return Script.types.UNKNOWN;
8569};
8570
8571
8572/**
8573 * @returns {boolean} if script is one of the known types
8574 */
8575Script.prototype.isStandard = function() {
8576 // TODO: Add BIP62 compliance
8577 return this.classify() !== Script.types.UNKNOWN;
8578};
8579
8580
8581// Script construction methods
8582
8583/**
8584 * Adds a script element at the start of the script.
8585 * @param {*} obj a string, number, Opcode, Buffer, or object to add
8586 * @returns {Script} this script instance
8587 */
8588Script.prototype.prepend = function(obj) {
8589 this._addByType(obj, true);
8590 return this;
8591};
8592
8593/**
8594 * Compares a script with another script
8595 */
8596Script.prototype.equals = function(script) {
8597 $.checkState(script instanceof Script, 'Must provide another script');
8598 if (this.chunks.length !== script.chunks.length) {
8599 return false;
8600 }
8601 var i;
8602 for (i = 0; i < this.chunks.length; i++) {
8603 if (BufferUtil.isBuffer(this.chunks[i].buf) && !BufferUtil.isBuffer(script.chunks[i].buf)) {
8604 return false;
8605 }
8606 if (BufferUtil.isBuffer(this.chunks[i].buf) && !BufferUtil.equals(this.chunks[i].buf, script.chunks[i].buf)) {
8607 return false;
8608 } else if (this.chunks[i].opcodenum !== script.chunks[i].opcodenum) {
8609 return false;
8610 }
8611 }
8612 return true;
8613};
8614
8615/**
8616 * Adds a script element to the end of the script.
8617 *
8618 * @param {*} obj a string, number, Opcode, Buffer, or object to add
8619 * @returns {Script} this script instance
8620 *
8621 */
8622Script.prototype.add = function(obj) {
8623 this._addByType(obj, false);
8624 return this;
8625};
8626
8627Script.prototype._addByType = function(obj, prepend) {
8628 if (typeof obj === 'string') {
8629 this._addOpcode(obj, prepend);
8630 } else if (typeof obj === 'number') {
8631 this._addOpcode(obj, prepend);
8632 } else if (obj instanceof Opcode) {
8633 this._addOpcode(obj, prepend);
8634 } else if (BufferUtil.isBuffer(obj)) {
8635 this._addBuffer(obj, prepend);
8636 } else if (obj instanceof Script) {
8637 this.chunks = this.chunks.concat(obj.chunks);
8638 } else if (typeof obj === 'object') {
8639 this._insertAtPosition(obj, prepend);
8640 } else {
8641 throw new Error('Invalid script chunk');
8642 }
8643};
8644
8645Script.prototype._insertAtPosition = function(op, prepend) {
8646 if (prepend) {
8647 this.chunks.unshift(op);
8648 } else {
8649 this.chunks.push(op);
8650 }
8651};
8652
8653Script.prototype._addOpcode = function(opcode, prepend) {
8654 var op;
8655 if (typeof opcode === 'number') {
8656 op = opcode;
8657 } else if (opcode instanceof Opcode) {
8658 op = opcode.toNumber();
8659 } else {
8660 op = Opcode(opcode).toNumber();
8661 }
8662 this._insertAtPosition({
8663 opcodenum: op
8664 }, prepend);
8665 return this;
8666};
8667
8668Script.prototype._addBuffer = function(buf, prepend) {
8669 var opcodenum;
8670 var len = buf.length;
8671 if (len >= 0 && len < Opcode.OP_PUSHDATA1) {
8672 opcodenum = len;
8673 } else if (len < Math.pow(2, 8)) {
8674 opcodenum = Opcode.OP_PUSHDATA1;
8675 } else if (len < Math.pow(2, 16)) {
8676 opcodenum = Opcode.OP_PUSHDATA2;
8677 } else if (len < Math.pow(2, 32)) {
8678 opcodenum = Opcode.OP_PUSHDATA4;
8679 } else {
8680 throw new Error('You can\'t push that much data');
8681 }
8682 this._insertAtPosition({
8683 buf: buf,
8684 len: len,
8685 opcodenum: opcodenum
8686 }, prepend);
8687 return this;
8688};
8689
8690Script.prototype.hasCodeseparators = function() {
8691 for (var i = 0; i < this.chunks.length; i++) {
8692 if (this.chunks[i].opcodenum === Opcode.OP_CODESEPARATOR) {
8693 return true;
8694 }
8695 }
8696 return false;
8697};
8698
8699Script.prototype.removeCodeseparators = function() {
8700 var chunks = [];
8701 for (var i = 0; i < this.chunks.length; i++) {
8702 if (this.chunks[i].opcodenum !== Opcode.OP_CODESEPARATOR) {
8703 chunks.push(this.chunks[i]);
8704 }
8705 }
8706 this.chunks = chunks;
8707 return this;
8708};
8709
8710// high level script builder methods
8711
8712/**
8713 * @returns {Script} a new Multisig output script for given public keys,
8714 * requiring m of those public keys to spend
8715 * @param {PublicKey[]} publicKeys - list of all public keys controlling the output
8716 * @param {number} threshold - amount of required signatures to spend the output
8717 * @param {Object=} opts - Several options:
8718 * - noSorting: defaults to false, if true, don't sort the given
8719 * public keys before creating the script
8720 */
8721Script.buildMultisigOut = function(publicKeys, threshold, opts) {
8722 $.checkArgument(threshold <= publicKeys.length,
8723 'Number of required signatures must be less than or equal to the number of public keys');
8724 opts = opts || {};
8725 var script = new Script();
8726 script.add(Opcode.smallInt(threshold));
8727 publicKeys = _.map(publicKeys, PublicKey);
8728 var sorted = publicKeys;
8729 if (!opts.noSorting) {
8730 sorted = _.sortBy(publicKeys, function(publicKey) {
8731 return publicKey.toString('hex');
8732 });
8733 }
8734 for (var i = 0; i < sorted.length; i++) {
8735 var publicKey = sorted[i];
8736 script.add(publicKey.toBuffer());
8737 }
8738 script.add(Opcode.smallInt(publicKeys.length));
8739 script.add(Opcode.OP_CHECKMULTISIG);
8740 return script;
8741};
8742
8743Script.buildWitnessMultisigOutFromScript = function(script) {
8744 if (script instanceof Script) {
8745 var s = new Script();
8746 s.add(Opcode.OP_0);
8747 s.add(Hash.sha256(script.toBuffer()));
8748 return s;
8749 } else {
8750 throw new TypeError('First argument is expected to be a p2sh script');
8751 }
8752};
8753
8754/**
8755 * A new Multisig input script for the given public keys, requiring m of those public keys to spend
8756 *
8757 * @param {PublicKey[]} pubkeys list of all public keys controlling the output
8758 * @param {number} threshold amount of required signatures to spend the output
8759 * @param {Array} signatures and array of signature buffers to append to the script
8760 * @param {Object=} opts
8761 * @param {boolean=} opts.noSorting don't sort the given public keys before creating the script (false by default)
8762 * @param {Script=} opts.cachedMultisig don't recalculate the redeemScript
8763 *
8764 * @returns {Script}
8765 */
8766Script.buildMultisigIn = function(pubkeys, threshold, signatures, opts) {
8767 $.checkArgument(_.isArray(pubkeys));
8768 $.checkArgument(_.isNumber(threshold));
8769 $.checkArgument(_.isArray(signatures));
8770 opts = opts || {};
8771 var s = new Script();
8772 s.add(Opcode.OP_0);
8773 _.each(signatures, function(signature) {
8774 $.checkArgument(BufferUtil.isBuffer(signature), 'Signatures must be an array of Buffers');
8775 // TODO: allow signatures to be an array of Signature objects
8776 s.add(signature);
8777 });
8778 return s;
8779};
8780
8781/**
8782 * A new P2SH Multisig input script for the given public keys, requiring m of those public keys to spend
8783 *
8784 * @param {PublicKey[]} pubkeys list of all public keys controlling the output
8785 * @param {number} threshold amount of required signatures to spend the output
8786 * @param {Array} signatures and array of signature buffers to append to the script
8787 * @param {Object=} opts
8788 * @param {boolean=} opts.noSorting don't sort the given public keys before creating the script (false by default)
8789 * @param {Script=} opts.cachedMultisig don't recalculate the redeemScript
8790 *
8791 * @returns {Script}
8792 */
8793Script.buildP2SHMultisigIn = function(pubkeys, threshold, signatures, opts) {
8794 $.checkArgument(_.isArray(pubkeys));
8795 $.checkArgument(_.isNumber(threshold));
8796 $.checkArgument(_.isArray(signatures));
8797 opts = opts || {};
8798 var s = new Script();
8799 s.add(Opcode.OP_0);
8800 _.each(signatures, function(signature) {
8801 $.checkArgument(BufferUtil.isBuffer(signature), 'Signatures must be an array of Buffers');
8802 // TODO: allow signatures to be an array of Signature objects
8803 s.add(signature);
8804 });
8805 s.add((opts.cachedMultisig || Script.buildMultisigOut(pubkeys, threshold, opts)).toBuffer());
8806 return s;
8807};
8808
8809/**
8810 * @returns {Script} a new pay to public key hash output for the given
8811 * address or public key
8812 * @param {(Address|PublicKey)} to - destination address or public key
8813 */
8814Script.buildPublicKeyHashOut = function(to) {
8815 $.checkArgument(!_.isUndefined(to));
8816 $.checkArgument(to instanceof PublicKey || to instanceof Address || _.isString(to));
8817 if (to instanceof PublicKey) {
8818 to = to.toAddress();
8819 } else if (_.isString(to)) {
8820 to = new Address(to);
8821 }
8822 var s = new Script();
8823 s.add(Opcode.OP_DUP)
8824 .add(Opcode.OP_HASH160)
8825 .add(to.hashBuffer)
8826 .add(Opcode.OP_EQUALVERIFY)
8827 .add(Opcode.OP_CHECKSIG);
8828 s._network = to.network;
8829 return s;
8830};
8831
8832/**
8833 * @returns {Script} a new pay to witness v0 output for the given
8834 * address
8835 * @param {(Address|PublicKey)} to - destination address
8836 */
8837Script.buildWitnessV0Out = function(to) {
8838 $.checkArgument(!_.isUndefined(to));
8839 $.checkArgument(to instanceof PublicKey || to instanceof Address || _.isString(to));
8840 if (to instanceof PublicKey) {
8841 to = to.toAddress(null, Address.PayToWitnessPublicKeyHash);
8842 } else if (_.isString(to)) {
8843 to = new Address(to);
8844 }
8845 var s = new Script();
8846 s.add(Opcode.OP_0)
8847 .add(to.hashBuffer);
8848 s._network = to.network;
8849 return s;
8850};
8851
8852/**
8853 * @returns {Script} a new pay to public key output for the given
8854 * public key
8855 */
8856Script.buildPublicKeyOut = function(pubkey) {
8857 $.checkArgument(pubkey instanceof PublicKey);
8858 var s = new Script();
8859 s.add(pubkey.toBuffer())
8860 .add(Opcode.OP_CHECKSIG);
8861 return s;
8862};
8863
8864/**
8865 * @returns {Script} a new OP_RETURN script with data
8866 * @param {(string|Buffer)} data - the data to embed in the output
8867 * @param {(string)} encoding - the type of encoding of the string
8868 */
8869Script.buildDataOut = function(data, encoding) {
8870 $.checkArgument(_.isUndefined(data) || _.isString(data) || BufferUtil.isBuffer(data));
8871 if (_.isString(data)) {
8872 data = Buffer.from(data, encoding);
8873 }
8874 var s = new Script();
8875 s.add(Opcode.OP_RETURN);
8876 if (!_.isUndefined(data)) {
8877 s.add(data);
8878 }
8879 return s;
8880};
8881
8882/**
8883 * @param {Script|Address} script - the redeemScript for the new p2sh output.
8884 * It can also be a p2sh address
8885 * @returns {Script} new pay to script hash script for given script
8886 */
8887Script.buildScriptHashOut = function(script) {
8888 $.checkArgument(script instanceof Script ||
8889 (script instanceof Address && script.isPayToScriptHash()));
8890 var s = new Script();
8891 s.add(Opcode.OP_HASH160)
8892 .add(script instanceof Address ? script.hashBuffer : Hash.sha256ripemd160(script.toBuffer()))
8893 .add(Opcode.OP_EQUAL);
8894
8895 s._network = script._network || script.network;
8896 return s;
8897};
8898
8899/**
8900 * Builds a scriptSig (a script for an input) that signs a public key output script.
8901 *
8902 * @param {Signature|Buffer} signature - a Signature object, or the signature in DER canonical encoding
8903 * @param {number=} sigtype - the type of the signature (defaults to SIGHASH_ALL)
8904 */
8905Script.buildPublicKeyIn = function(signature, sigtype) {
8906 $.checkArgument(signature instanceof Signature || BufferUtil.isBuffer(signature));
8907 $.checkArgument(_.isUndefined(sigtype) || _.isNumber(sigtype));
8908 if (signature instanceof Signature) {
8909 signature = signature.toBuffer();
8910 }
8911 var script = new Script();
8912 script.add(BufferUtil.concat([
8913 signature,
8914 BufferUtil.integerAsSingleByteBuffer(sigtype || Signature.SIGHASH_ALL)
8915 ]));
8916 return script;
8917};
8918
8919/**
8920 * Builds a scriptSig (a script for an input) that signs a public key hash
8921 * output script.
8922 *
8923 * @param {Buffer|string|PublicKey} publicKey
8924 * @param {Signature|Buffer} signature - a Signature object, or the signature in DER canonical encoding
8925 * @param {number=} sigtype - the type of the signature (defaults to SIGHASH_ALL)
8926 */
8927Script.buildPublicKeyHashIn = function(publicKey, signature, sigtype) {
8928 $.checkArgument(signature instanceof Signature || BufferUtil.isBuffer(signature));
8929 $.checkArgument(_.isUndefined(sigtype) || _.isNumber(sigtype));
8930 if (signature instanceof Signature) {
8931 signature = signature.toBuffer();
8932 }
8933 var script = new Script()
8934 .add(BufferUtil.concat([
8935 signature,
8936 BufferUtil.integerAsSingleByteBuffer(sigtype || Signature.SIGHASH_ALL)
8937 ]))
8938 .add(new PublicKey(publicKey).toBuffer());
8939 return script;
8940};
8941
8942/**
8943 * @returns {Script} an empty script
8944 */
8945Script.empty = function() {
8946 return new Script();
8947};
8948
8949/**
8950 * @returns {Script} a new pay to script hash script that pays to this script
8951 */
8952Script.prototype.toScriptHashOut = function() {
8953 return Script.buildScriptHashOut(this);
8954};
8955
8956/**
8957 * @return {Script} an output script built from the address
8958 */
8959Script.fromAddress = function(address) {
8960 address = Address(address);
8961 if (address.isPayToScriptHash()) {
8962 return Script.buildScriptHashOut(address);
8963 } else if (address.isPayToPublicKeyHash()) {
8964 return Script.buildPublicKeyHashOut(address);
8965 } else if (address.isPayToWitnessPublicKeyHash()) {
8966 return Script.buildWitnessV0Out(address);
8967 } else if (address.isPayToWitnessScriptHash()) {
8968 return Script.buildWitnessV0Out(address);
8969 }
8970 throw new errors.Script.UnrecognizedAddress(address);
8971};
8972
8973/**
8974 * Will return the associated address information object
8975 * @return {Address|boolean}
8976 */
8977Script.prototype.getAddressInfo = function(opts) {
8978 if (this._isInput) {
8979 return this._getInputAddressInfo();
8980 } else if (this._isOutput) {
8981 return this._getOutputAddressInfo();
8982 } else {
8983 var info = this._getOutputAddressInfo();
8984 if (!info) {
8985 return this._getInputAddressInfo();
8986 }
8987 return info;
8988 }
8989};
8990
8991/**
8992 * Will return the associated output scriptPubKey address information object
8993 * @return {Address|boolean}
8994 * @private
8995 */
8996Script.prototype._getOutputAddressInfo = function() {
8997 var info = {};
8998 if (this.isScriptHashOut()) {
8999 info.hashBuffer = this.getData();
9000 info.type = Address.PayToScriptHash;
9001 } else if (this.isPublicKeyHashOut()) {
9002 info.hashBuffer = this.getData();
9003 info.type = Address.PayToPublicKeyHash;
9004 } else if (this.isWitnessScriptHashOut()) {
9005 info.hashBuffer = this.getData();
9006 info.type = Address.PayToWitnessScriptHash;
9007 } else if (this.isWitnessPublicKeyHashOut()) {
9008 info.hashBuffer = this.getData();
9009 info.type = Address.PayToWitnessPublicKeyHash;
9010 } else if (this.isTaproot()) {
9011 info.hashBuffer = this.getData();
9012 info.type = Address.PayToTaproot;
9013 } else {
9014 return false;
9015 }
9016 return info;
9017};
9018
9019/**
9020 * Will return the associated input scriptSig address information object
9021 * @return {Address|boolean}
9022 * @private
9023 */
9024Script.prototype._getInputAddressInfo = function() {
9025 var info = {};
9026 if (this.isPublicKeyHashIn()) {
9027 // hash the publickey found in the scriptSig
9028 info.hashBuffer = Hash.sha256ripemd160(this.chunks[1].buf);
9029 info.type = Address.PayToPublicKeyHash;
9030 } else if (this.isScriptHashIn()) {
9031 // hash the redeemscript found at the end of the scriptSig
9032 info.hashBuffer = Hash.sha256ripemd160(this.chunks[this.chunks.length - 1].buf);
9033 info.type = Address.PayToScriptHash;
9034 } else {
9035 return false;
9036 }
9037 return info;
9038};
9039
9040/**
9041 * @param {Network=} network
9042 * @return {Address|boolean} the associated address for this script if possible, or false
9043 */
9044Script.prototype.toAddress = function(network) {
9045 var info = this.getAddressInfo();
9046 if (!info) {
9047 return false;
9048 }
9049 info.network = Networks.get(network) || this._network || Networks.defaultNetwork;
9050 return new Address(info);
9051};
9052
9053/**
9054 * Analogous to bitcoind's FindAndDelete. Find and delete equivalent chunks,
9055 * typically used with push data chunks. Note that this will find and delete
9056 * not just the same data, but the same data with the same push data op as
9057 * produced by default. i.e., if a pushdata in a tx does not use the minimal
9058 * pushdata op, then when you try to remove the data it is pushing, it will not
9059 * be removed, because they do not use the same pushdata op.
9060 */
9061Script.prototype.findAndDelete = function(script) {
9062 var buf = script.toBuffer();
9063 var hex = buf.toString('hex');
9064 for (var i = 0; i < this.chunks.length; i++) {
9065 var script2 = Script({
9066 chunks: [this.chunks[i]]
9067 });
9068 var buf2 = script2.toBuffer();
9069 var hex2 = buf2.toString('hex');
9070 if (hex === hex2) {
9071 this.chunks.splice(i, 1);
9072 }
9073 }
9074 return this;
9075};
9076
9077/**
9078 * Comes from bitcoind's script interpreter CheckMinimalPush function
9079 * @returns {boolean} if the chunk {i} is the smallest way to push that particular data.
9080 */
9081Script.prototype.checkMinimalPush = function(i) {
9082 var chunk = this.chunks[i];
9083 var buf = chunk.buf;
9084 var opcodenum = chunk.opcodenum;
9085 if (!buf) {
9086 return true;
9087 }
9088 if (buf.length === 0) {
9089 // Could have used OP_0.
9090 return opcodenum === Opcode.OP_0;
9091 } else if (buf.length === 1 && buf[0] >= 1 && buf[0] <= 16) {
9092 // Could have used OP_1 .. OP_16.
9093 return opcodenum === Opcode.OP_1 + (buf[0] - 1);
9094 } else if (buf.length === 1 && buf[0] === 0x81) {
9095 // Could have used OP_1NEGATE
9096 return opcodenum === Opcode.OP_1NEGATE;
9097 } else if (buf.length <= 75) {
9098 // Could have used a direct push (opcode indicating number of bytes pushed + those bytes).
9099 return opcodenum === buf.length;
9100 } else if (buf.length <= 255) {
9101 // Could have used OP_PUSHDATA.
9102 return opcodenum === Opcode.OP_PUSHDATA1;
9103 } else if (buf.length <= 65535) {
9104 // Could have used OP_PUSHDATA2.
9105 return opcodenum === Opcode.OP_PUSHDATA2;
9106 }
9107 return true;
9108};
9109
9110/**
9111 * Comes from bitcoind's script DecodeOP_N function
9112 * @param {number} opcode
9113 * @returns {number} numeric value in range of 0 to 16
9114 */
9115Script.prototype._decodeOP_N = function(opcode) {
9116 if (opcode === Opcode.OP_0) {
9117 return 0;
9118 } else if (opcode >= Opcode.OP_1 && opcode <= Opcode.OP_16) {
9119 return opcode - (Opcode.OP_1 - 1);
9120 } else {
9121 throw new Error('Invalid opcode: ' + JSON.stringify(opcode));
9122 }
9123};
9124
9125/**
9126 * Comes from bitcoind's script GetSigOpCount(boolean) function
9127 * @param {boolean} use current (true) or pre-version-0.6 (false) logic
9128 * @returns {number} number of signature operations required by this script
9129 */
9130Script.prototype.getSignatureOperationsCount = function(accurate) {
9131 accurate = (_.isUndefined(accurate) ? true : accurate);
9132 var self = this;
9133 var n = 0;
9134 var lastOpcode = Opcode.OP_INVALIDOPCODE;
9135 _.each(self.chunks, function getChunk(chunk) {
9136 var opcode = chunk.opcodenum;
9137 if (opcode == Opcode.OP_CHECKSIG || opcode == Opcode.OP_CHECKSIGVERIFY) {
9138 n++;
9139 } else if (opcode == Opcode.OP_CHECKMULTISIG || opcode == Opcode.OP_CHECKMULTISIGVERIFY) {
9140 if (accurate && lastOpcode >= Opcode.OP_1 && lastOpcode <= Opcode.OP_16) {
9141 n += self._decodeOP_N(lastOpcode);
9142 } else {
9143 n += 20;
9144 }
9145 }
9146 lastOpcode = opcode;
9147 });
9148 return n;
9149};
9150
9151module.exports = Script;
9152
9153}).call(this)}).call(this,require("buffer").Buffer)
9154},{"../address":1,"../crypto/hash":8,"../crypto/signature":11,"../encoding/bufferreader":15,"../encoding/bufferwriter":16,"../errors":18,"../networks":23,"../opcode":24,"../publickey":26,"../util/buffer":45,"../util/js":46,"../util/preconditions":47,"buffer":132,"lodash":210}],30:[function(require,module,exports){
9155module.exports = require('./transaction');
9156
9157module.exports.Input = require('./input');
9158module.exports.Output = require('./output');
9159module.exports.UnspentOutput = require('./unspentoutput');
9160module.exports.Signature = require('./signature');
9161module.exports.Sighash = require('./sighash');
9162module.exports.SighashWitness = require('./sighashwitness');
9163
9164},{"./input":31,"./output":37,"./sighash":38,"./sighashwitness":39,"./signature":40,"./transaction":41,"./unspentoutput":42}],31:[function(require,module,exports){
9165module.exports = require('./input');
9166
9167module.exports.PublicKey = require('./publickey');
9168module.exports.PublicKeyHash = require('./publickeyhash');
9169module.exports.MultiSig = require('./multisig.js');
9170module.exports.MultiSigScriptHash = require('./multisigscripthash.js');
9171
9172},{"./input":32,"./multisig.js":33,"./multisigscripthash.js":34,"./publickey":35,"./publickeyhash":36}],32:[function(require,module,exports){
9173(function (Buffer){(function (){
9174'use strict';
9175
9176var _ = require('lodash');
9177var $ = require('../../util/preconditions');
9178const errors = require('../../errors');
9179var BufferWriter = require('../../encoding/bufferwriter');
9180var buffer = require('buffer');
9181var BufferUtil = require('../../util/buffer');
9182var JSUtil = require('../../util/js');
9183var Script = require('../../script');
9184var Sighash = require('../sighash');
9185var Output = require('../output');
9186
9187var MAXINT = 0xffffffff; // Math.pow(2, 32) - 1;
9188var DEFAULT_SEQNUMBER = MAXINT;
9189var DEFAULT_LOCKTIME_SEQNUMBER = MAXINT - 1;
9190var DEFAULT_RBF_SEQNUMBER = MAXINT - 2;
9191const SEQUENCE_LOCKTIME_DISABLE_FLAG = Math.pow(2,31); // (1 << 31);
9192const SEQUENCE_LOCKTIME_TYPE_FLAG = Math.pow(2,22); // (1 << 22);
9193const SEQUENCE_LOCKTIME_MASK = 0xffff;
9194const SEQUENCE_LOCKTIME_GRANULARITY = 512; // 512 seconds
9195const SEQUENCE_BLOCKDIFF_LIMIT = Math.pow(2,16)-1; // 16 bits
9196
9197
9198function Input(params) {
9199 if (!(this instanceof Input)) {
9200 return new Input(params);
9201 }
9202 if (params) {
9203 return this._fromObject(params);
9204 }
9205}
9206
9207Input.MAXINT = MAXINT;
9208Input.DEFAULT_SEQNUMBER = DEFAULT_SEQNUMBER;
9209Input.DEFAULT_LOCKTIME_SEQNUMBER = DEFAULT_LOCKTIME_SEQNUMBER;
9210Input.DEFAULT_RBF_SEQNUMBER = DEFAULT_RBF_SEQNUMBER;
9211Input.SEQUENCE_LOCKTIME_TYPE_FLAG = SEQUENCE_LOCKTIME_TYPE_FLAG;
9212
9213Object.defineProperty(Input.prototype, 'script', {
9214 configurable: false,
9215 enumerable: true,
9216 get: function() {
9217 if (this.isNull()) {
9218 return null;
9219 }
9220 if (!this._script) {
9221 this._script = new Script(this._scriptBuffer);
9222 this._script._isInput = true;
9223 }
9224 return this._script;
9225 }
9226});
9227
9228Input.fromObject = function(obj) {
9229 $.checkArgument(_.isObject(obj));
9230 var input = new Input();
9231 return input._fromObject(obj);
9232};
9233
9234Input.prototype._fromObject = function(params) {
9235 var prevTxId;
9236 if (_.isString(params.prevTxId) && JSUtil.isHexa(params.prevTxId)) {
9237 prevTxId = Buffer.from(params.prevTxId, 'hex');
9238 } else {
9239 prevTxId = params.prevTxId;
9240 }
9241 this.witnesses = [];
9242 this.output = params.output ?
9243 (params.output instanceof Output ? params.output : new Output(params.output)) : undefined;
9244 this.prevTxId = prevTxId || params.txidbuf;
9245 this.outputIndex = _.isUndefined(params.outputIndex) ? params.txoutnum : params.outputIndex;
9246 this.sequenceNumber = _.isUndefined(params.sequenceNumber) ?
9247 (_.isUndefined(params.seqnum) ? DEFAULT_SEQNUMBER : params.seqnum) : params.sequenceNumber;
9248 if (_.isUndefined(params.script) && _.isUndefined(params.scriptBuffer)) {
9249 throw new errors.Transaction.Input.MissingScript();
9250 }
9251 this.setScript(params.scriptBuffer || params.script);
9252 return this;
9253};
9254
9255Input.prototype.toObject = Input.prototype.toJSON = function toObject() {
9256 var obj = {
9257 prevTxId: this.prevTxId.toString('hex'),
9258 outputIndex: this.outputIndex,
9259 sequenceNumber: this.sequenceNumber,
9260 script: this._scriptBuffer.toString('hex'),
9261 };
9262 // add human readable form if input contains valid script
9263 if (this.script) {
9264 obj.scriptString = this.script.toString();
9265 }
9266 if (this.output) {
9267 obj.output = this.output.toObject();
9268 }
9269 return obj;
9270};
9271
9272Input.fromBufferReader = function(br) {
9273 var input = new Input();
9274 input.prevTxId = br.readReverse(32);
9275 input.outputIndex = br.readUInt32LE();
9276 input._scriptBuffer = br.readVarLengthBuffer();
9277 input.sequenceNumber = br.readUInt32LE();
9278 // TODO: return different classes according to which input it is
9279 // e.g: CoinbaseInput, PublicKeyHashInput, MultiSigScriptHashInput, etc.
9280 return input;
9281};
9282
9283Input.prototype.toBufferWriter = function(writer) {
9284 if (!writer) {
9285 writer = new BufferWriter();
9286 }
9287 writer.writeReverse(this.prevTxId);
9288 writer.writeUInt32LE(this.outputIndex);
9289 var script = this._scriptBuffer;
9290 writer.writeVarintNum(script.length);
9291 writer.write(script);
9292 writer.writeUInt32LE(this.sequenceNumber);
9293 return writer;
9294};
9295
9296Input.prototype.setScript = function(script) {
9297 this._script = null;
9298 if (script instanceof Script) {
9299 this._script = script;
9300 this._script._isInput = true;
9301 this._scriptBuffer = script.toBuffer();
9302 } else if (JSUtil.isHexa(script)) {
9303 // hex string script
9304 this._scriptBuffer = Buffer.from(script, 'hex');
9305 } else if (_.isString(script)) {
9306 // human readable string script
9307 this._script = new Script(script);
9308 this._script._isInput = true;
9309 this._scriptBuffer = this._script.toBuffer();
9310 } else if (BufferUtil.isBuffer(script)) {
9311 // buffer script
9312 this._scriptBuffer = Buffer.from(script);
9313 } else {
9314 throw new TypeError('Invalid argument type: script');
9315 }
9316 return this;
9317};
9318
9319/**
9320 * Retrieve signatures for the provided PrivateKey.
9321 *
9322 * @param {Transaction} transaction - the transaction to be signed
9323 * @param {PrivateKey} privateKey - the private key to use when signing
9324 * @param {number} inputIndex - the index of this input in the provided transaction
9325 * @param {number} sigType - defaults to Signature.SIGHASH_ALL
9326 * @param {Buffer} addressHash - if provided, don't calculate the hash of the
9327 * public key associated with the private key provided
9328 * @abstract
9329 */
9330Input.prototype.getSignatures = function() {
9331 throw new errors.AbstractMethodInvoked(
9332 'Trying to sign unsupported output type (only P2PKH and P2SH multisig inputs are supported)' +
9333 ' for input: ' + JSON.stringify(this)
9334 );
9335};
9336
9337Input.prototype.getSatoshisBuffer = function() {
9338 $.checkState(this.output instanceof Output);
9339 $.checkState(this.output._satoshisBN);
9340 return new BufferWriter().writeUInt64LEBN(this.output._satoshisBN).toBuffer();
9341};
9342
9343
9344Input.prototype.isFullySigned = function() {
9345 throw new errors.AbstractMethodInvoked('Input#isFullySigned');
9346};
9347
9348Input.prototype.isFinal = function() {
9349 return this.sequenceNumber !== Input.MAXINT;
9350};
9351
9352Input.prototype.addSignature = function() {
9353 throw new errors.AbstractMethodInvoked('Input#addSignature');
9354};
9355
9356Input.prototype.clearSignatures = function() {
9357 throw new errors.AbstractMethodInvoked('Input#clearSignatures');
9358};
9359
9360Input.prototype.hasWitnesses = function() {
9361 if (this.witnesses && this.witnesses.length > 0) {
9362 return true;
9363 }
9364 return false;
9365};
9366
9367Input.prototype.getWitnesses = function() {
9368 return this.witnesses;
9369};
9370
9371Input.prototype.setWitnesses = function(witnesses) {
9372 this.witnesses = witnesses;
9373};
9374
9375Input.prototype.isValidSignature = function(transaction, signature, signingMethod) {
9376 // FIXME: Refactor signature so this is not necessary
9377 signingMethod = signingMethod || 'ecdsa';
9378 signature.signature.nhashtype = signature.sigtype;
9379 return Sighash.verify(
9380 transaction,
9381 signature.signature,
9382 signature.publicKey,
9383 signature.inputIndex,
9384 this.output.script,
9385 signingMethod
9386 );
9387};
9388
9389/**
9390 * @returns true if this is a coinbase input (represents no input)
9391 */
9392Input.prototype.isNull = function() {
9393 return this.prevTxId.toString('hex') === '0000000000000000000000000000000000000000000000000000000000000000' &&
9394 this.outputIndex === 0xffffffff;
9395};
9396
9397Input.prototype._estimateSize = function() {
9398 return this.toBufferWriter().toBuffer().length;
9399};
9400
9401
9402/**
9403 * Sets sequence number so that transaction is not valid until the desired seconds
9404 * since the transaction is mined
9405 *
9406 * @param {Number} time in seconds
9407 * @return {Transaction} this
9408 */
9409Input.prototype.lockForSeconds = function(seconds) {
9410 $.checkArgument(_.isNumber(seconds));
9411 if (seconds < 0 || seconds >= SEQUENCE_LOCKTIME_GRANULARITY * SEQUENCE_LOCKTIME_MASK) {
9412 throw new errors.Transaction.Input.LockTimeRange();
9413 }
9414 seconds = parseInt(Math.floor(seconds / SEQUENCE_LOCKTIME_GRANULARITY));
9415
9416 // SEQUENCE_LOCKTIME_DISABLE_FLAG = 1
9417 this.sequenceNumber = seconds | SEQUENCE_LOCKTIME_TYPE_FLAG ;
9418 return this;
9419};
9420
9421/**
9422 * Sets sequence number so that transaction is not valid until the desired block height differnece since the tx is mined
9423 *
9424 * @param {Number} height
9425 * @return {Transaction} this
9426 */
9427Input.prototype.lockUntilBlockHeight = function(heightDiff) {
9428 $.checkArgument(_.isNumber(heightDiff));
9429 if (heightDiff < 0 || heightDiff >= SEQUENCE_BLOCKDIFF_LIMIT) {
9430 throw new errors.Transaction.Input.BlockHeightOutOfRange();
9431 }
9432 // SEQUENCE_LOCKTIME_TYPE_FLAG = 0
9433 // SEQUENCE_LOCKTIME_DISABLE_FLAG = 0
9434 this.sequenceNumber = heightDiff ;
9435 return this;
9436};
9437
9438
9439/**
9440 * Returns a semantic version of the input's sequence nLockTime.
9441 * @return {Number|Date}
9442 * If sequence lock is disabled it returns null,
9443 * if is set to block height lock, returns a block height (number)
9444 * else it returns a Date object.
9445 */
9446Input.prototype.getLockTime = function() {
9447 if (this.sequenceNumber & SEQUENCE_LOCKTIME_DISABLE_FLAG) {
9448 return null;
9449 }
9450
9451 if (this.sequenceNumber & SEQUENCE_LOCKTIME_TYPE_FLAG) {
9452 var seconds = SEQUENCE_LOCKTIME_GRANULARITY * (this.sequenceNumber & SEQUENCE_LOCKTIME_MASK);
9453 return seconds;
9454 } else {
9455 var blockHeight = this.sequenceNumber & SEQUENCE_LOCKTIME_MASK;
9456 return blockHeight;
9457 }
9458};
9459
9460
9461
9462
9463module.exports = Input;
9464
9465}).call(this)}).call(this,require("buffer").Buffer)
9466},{"../../encoding/bufferwriter":16,"../../errors":18,"../../script":27,"../../util/buffer":45,"../../util/js":46,"../../util/preconditions":47,"../output":37,"../sighash":38,"buffer":132,"lodash":210}],33:[function(require,module,exports){
9467'use strict';
9468
9469var _ = require('lodash');
9470var inherits = require('inherits');
9471var Transaction = require('../transaction');
9472var Input = require('./input');
9473var Output = require('../output');
9474var $ = require('../../util/preconditions');
9475
9476var Script = require('../../script');
9477var Signature = require('../../crypto/signature');
9478var Sighash = require('../sighash');
9479var PublicKey = require('../../publickey');
9480var BufferUtil = require('../../util/buffer');
9481var TransactionSignature = require('../signature');
9482
9483/**
9484 * @constructor
9485 */
9486function MultiSigInput(input, pubkeys, threshold, signatures, opts) {
9487 opts = opts || {};
9488 Input.apply(this, arguments);
9489 var self = this;
9490 pubkeys = pubkeys || input.publicKeys;
9491 threshold = threshold || input.threshold;
9492 signatures = signatures || input.signatures;
9493 if (opts.noSorting) {
9494 this.publicKeys = pubkeys
9495 } else {
9496 this.publicKeys = _.sortBy(pubkeys, function(publicKey) { return publicKey.toString('hex'); });
9497 }
9498 $.checkState(Script.buildMultisigOut(this.publicKeys, threshold).equals(this.output.script),
9499 'Provided public keys don\'t match to the provided output script');
9500 this.publicKeyIndex = {};
9501 _.each(this.publicKeys, function(publicKey, index) {
9502 self.publicKeyIndex[publicKey.toString()] = index;
9503 });
9504 this.threshold = threshold;
9505 // Empty array of signatures
9506 this.signatures = signatures ? this._deserializeSignatures(signatures) : new Array(this.publicKeys.length);
9507}
9508inherits(MultiSigInput, Input);
9509
9510MultiSigInput.prototype.toObject = function() {
9511 var obj = Input.prototype.toObject.apply(this, arguments);
9512 obj.threshold = this.threshold;
9513 obj.publicKeys = _.map(this.publicKeys, function(publicKey) { return publicKey.toString(); });
9514 obj.signatures = this._serializeSignatures();
9515 return obj;
9516};
9517
9518MultiSigInput.prototype._deserializeSignatures = function(signatures) {
9519 return _.map(signatures, function(signature) {
9520 if (!signature) {
9521 return undefined;
9522 }
9523 return new TransactionSignature(signature);
9524 });
9525};
9526
9527MultiSigInput.prototype._serializeSignatures = function() {
9528 return _.map(this.signatures, function(signature) {
9529 if (!signature) {
9530 return undefined;
9531 }
9532 return signature.toObject();
9533 });
9534};
9535
9536MultiSigInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype, hashData, signingMethod) {
9537 $.checkState(this.output instanceof Output);
9538 sigtype = sigtype || Signature.SIGHASH_ALL;
9539 signingMethod = signingMethod || 'ecdsa';
9540
9541 var self = this;
9542 var results = [];
9543 _.each(this.publicKeys, function(publicKey) {
9544 if (publicKey.toString() === privateKey.publicKey.toString()) {
9545 results.push(new TransactionSignature({
9546 publicKey: privateKey.publicKey,
9547 prevTxId: self.prevTxId,
9548 outputIndex: self.outputIndex,
9549 inputIndex: index,
9550 signature: Sighash.sign(transaction, privateKey, sigtype, index, self.output.script, signingMethod),
9551 sigtype: sigtype
9552 }));
9553 }
9554 });
9555
9556 return results;
9557};
9558
9559MultiSigInput.prototype.addSignature = function(transaction, signature, signingMethod) {
9560 $.checkState(!this.isFullySigned(), 'All needed signatures have already been added');
9561 $.checkArgument(!_.isUndefined(this.publicKeyIndex[signature.publicKey.toString()], "Signature Undefined"),
9562 'Signature has no matching public key');
9563 $.checkState(this.isValidSignature(transaction, signature, signingMethod), "Invalid Signature");
9564 this.signatures[this.publicKeyIndex[signature.publicKey.toString()]] = signature;
9565 this._updateScript();
9566 return this;
9567};
9568
9569MultiSigInput.prototype._updateScript = function() {
9570 this.setScript(Script.buildMultisigIn(
9571 this.publicKeys,
9572 this.threshold,
9573 this._createSignatures()
9574 ));
9575 return this;
9576};
9577
9578MultiSigInput.prototype._createSignatures = function() {
9579 return _.map(
9580 _.filter(this.signatures, function(signature) { return !_.isUndefined(signature); }),
9581 // Future signature types may need refactor of toDER
9582 function(signature) {
9583 return BufferUtil.concat([
9584 signature.signature.toDER(),
9585 BufferUtil.integerAsSingleByteBuffer(signature.sigtype)
9586 ]);
9587 }
9588 );
9589};
9590
9591MultiSigInput.prototype.clearSignatures = function() {
9592 this.signatures = new Array(this.publicKeys.length);
9593 this._updateScript();
9594};
9595
9596MultiSigInput.prototype.isFullySigned = function() {
9597 return this.countSignatures() === this.threshold;
9598};
9599
9600MultiSigInput.prototype.countMissingSignatures = function() {
9601 return this.threshold - this.countSignatures();
9602};
9603
9604MultiSigInput.prototype.countSignatures = function() {
9605 return _.reduce(this.signatures, function(sum, signature) {
9606 return sum + (!!signature);
9607 }, 0);
9608};
9609
9610MultiSigInput.prototype.publicKeysWithoutSignature = function() {
9611 var self = this;
9612 return _.filter(this.publicKeys, function(publicKey) {
9613 return !(self.signatures[self.publicKeyIndex[publicKey.toString()]]);
9614 });
9615};
9616
9617MultiSigInput.prototype.isValidSignature = function(transaction, signature, signingMethod) {
9618 // FIXME: Refactor signature so this is not necessary
9619 signature.signature.nhashtype = signature.sigtype;
9620 return Sighash.verify(
9621 transaction,
9622 signature.signature,
9623 signature.publicKey,
9624 signature.inputIndex,
9625 this.output.script,
9626 signingMethod
9627 );
9628};
9629
9630/**
9631 *
9632 * @param {Buffer[]} signatures
9633 * @param {PublicKey[]} publicKeys
9634 * @param {Transaction} transaction
9635 * @param {Integer} inputIndex
9636 * @param {Input} input
9637 * @param {String} signingMethod - method used to sign - 'ecdsa' or 'schnorr' (future signing method)
9638 * @returns {TransactionSignature[]}
9639 */
9640MultiSigInput.normalizeSignatures = function(transaction, input, inputIndex, signatures, publicKeys, signingMethod) {
9641 return publicKeys.map(function (pubKey) {
9642 var signatureMatch = null;
9643 signatures = signatures.filter(function (signatureBuffer) {
9644 if (signatureMatch) {
9645 return true;
9646 }
9647
9648 var signature = new TransactionSignature({
9649 signature: Signature.fromTxFormat(signatureBuffer),
9650 publicKey: pubKey,
9651 prevTxId: input.prevTxId,
9652 outputIndex: input.outputIndex,
9653 inputIndex: inputIndex,
9654 sigtype: Signature.SIGHASH_ALL
9655 });
9656
9657 signature.signature.nhashtype = signature.sigtype;
9658 var isMatch = Sighash.verify(
9659 transaction,
9660 signature.signature,
9661 signature.publicKey,
9662 signature.inputIndex,
9663 input.output.script,
9664 signingMethod
9665 );
9666
9667 if (isMatch) {
9668 signatureMatch = signature;
9669 return false;
9670 }
9671
9672 return true;
9673 });
9674
9675 return signatureMatch ? signatureMatch : null;
9676 });
9677};
9678
9679MultiSigInput.OPCODES_SIZE = 1; // 0
9680MultiSigInput.SIGNATURE_SIZE = 73; // size (1) + DER (<=72)
9681
9682MultiSigInput.prototype._estimateSize = function() {
9683 return MultiSigInput.OPCODES_SIZE +
9684 this.threshold * MultiSigInput.SIGNATURE_SIZE;
9685};
9686
9687module.exports = MultiSigInput;
9688
9689},{"../../crypto/signature":11,"../../publickey":26,"../../script":27,"../../util/buffer":45,"../../util/preconditions":47,"../output":37,"../sighash":38,"../signature":40,"../transaction":41,"./input":32,"inherits":206,"lodash":210}],34:[function(require,module,exports){
9690(function (Buffer){(function (){
9691'use strict';
9692
9693/* jshint maxparams:5 */
9694
9695var _ = require('lodash');
9696var inherits = require('inherits');
9697var Input = require('./input');
9698var Output = require('../output');
9699var $ = require('../../util/preconditions');
9700
9701var Address = require('../../address');
9702var Script = require('../../script');
9703var Signature = require('../../crypto/signature');
9704var Sighash = require('../sighash');
9705var SighashWitness = require('../sighashwitness');
9706var BufferWriter = require('../../encoding/bufferwriter');
9707var BufferUtil = require('../../util/buffer');
9708var TransactionSignature = require('../signature');
9709
9710/**
9711 * @constructor
9712 */
9713function MultiSigScriptHashInput(input, pubkeys, threshold, signatures, opts) {
9714 /* jshint maxstatements:20 */
9715 opts = opts || {};
9716 Input.apply(this, arguments);
9717 var self = this;
9718 pubkeys = pubkeys || input.publicKeys;
9719 threshold = threshold || input.threshold;
9720 signatures = signatures || input.signatures;
9721 if (opts.noSorting) {
9722 this.publicKeys = pubkeys;
9723 } else {
9724 this.publicKeys = _.sortBy(pubkeys, function(publicKey) { return publicKey.toString('hex'); });
9725 }
9726 this.redeemScript = Script.buildMultisigOut(this.publicKeys, threshold, opts);
9727 var nested = Script.buildWitnessMultisigOutFromScript(this.redeemScript);
9728 if (nested.equals(this.output.script)) {
9729 this.nestedWitness = false;
9730 this.type = Address.PayToWitnessScriptHash;
9731 } else if (Script.buildScriptHashOut(nested).equals(this.output.script)) {
9732 this.nestedWitness = true;
9733 this.type = Address.PayToScriptHash;
9734 } else if (Script.buildScriptHashOut(this.redeemScript).equals(this.output.script)) {
9735 this.nestedWitness = false;
9736 this.type = Address.PayToScriptHash;
9737 } else {
9738 throw new Error('Provided public keys don\'t hash to the provided output');
9739 }
9740
9741 if (this.nestedWitness) {
9742 var scriptSig = new Script();
9743 scriptSig.add(nested.toBuffer());
9744 this.setScript(scriptSig);
9745 }
9746
9747 this.publicKeyIndex = {};
9748 _.each(this.publicKeys, function(publicKey, index) {
9749 self.publicKeyIndex[publicKey.toString()] = index;
9750 });
9751 this.threshold = threshold;
9752 // Empty array of signatures
9753 this.signatures = signatures ? this._deserializeSignatures(signatures) : new Array(this.publicKeys.length);
9754}
9755inherits(MultiSigScriptHashInput, Input);
9756
9757MultiSigScriptHashInput.prototype.toObject = function() {
9758 var obj = Input.prototype.toObject.apply(this, arguments);
9759 obj.threshold = this.threshold;
9760 obj.publicKeys = _.map(this.publicKeys, function(publicKey) { return publicKey.toString(); });
9761 obj.signatures = this._serializeSignatures();
9762 return obj;
9763};
9764
9765MultiSigScriptHashInput.prototype._deserializeSignatures = function(signatures) {
9766 return _.map(signatures, function(signature) {
9767 if (!signature) {
9768 return undefined;
9769 }
9770 return new TransactionSignature(signature);
9771 });
9772};
9773
9774MultiSigScriptHashInput.prototype._serializeSignatures = function() {
9775 return _.map(this.signatures, function(signature) {
9776 if (!signature) {
9777 return undefined;
9778 }
9779 return signature.toObject();
9780 });
9781};
9782
9783MultiSigScriptHashInput.prototype.getScriptCode = function() {
9784 var writer = new BufferWriter();
9785 if (!this.redeemScript.hasCodeseparators()) {
9786 var redeemScriptBuffer = this.redeemScript.toBuffer();
9787 writer.writeVarintNum(redeemScriptBuffer.length);
9788 writer.write(redeemScriptBuffer);
9789 } else {
9790 throw new Error('@TODO');
9791 }
9792 return writer.toBuffer();
9793};
9794
9795MultiSigScriptHashInput.prototype.getSighash = function(transaction, privateKey, index, sigtype) {
9796 var self = this;
9797 var hash;
9798 if (self.nestedWitness || self.type === Address.PayToWitnessScriptHash) {
9799 var scriptCode = self.getScriptCode();
9800 var satoshisBuffer = self.getSatoshisBuffer();
9801 hash = SighashWitness.sighash(transaction, sigtype, index, scriptCode, satoshisBuffer);
9802 } else {
9803 hash = Sighash.sighash(transaction, sigtype, index, self.redeemScript);
9804 }
9805 return hash;
9806};
9807
9808MultiSigScriptHashInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype, hashData, signingMethod) {
9809 $.checkState(this.output instanceof Output);
9810 sigtype = sigtype || Signature.SIGHASH_ALL;
9811 signingMethod = signingMethod || 'ecdsa';
9812
9813 var self = this;
9814 var results = [];
9815 _.each(this.publicKeys, function(publicKey) {
9816 if (publicKey.toString() === privateKey.publicKey.toString()) {
9817 var signature;
9818 if (self.nestedWitness || self.type === Address.PayToWitnessScriptHash) {
9819 var scriptCode = self.getScriptCode();
9820 var satoshisBuffer = self.getSatoshisBuffer();
9821 signature = SighashWitness.sign(transaction, privateKey, sigtype, index, scriptCode, satoshisBuffer, signingMethod);
9822 } else {
9823 signature = Sighash.sign(transaction, privateKey, sigtype, index, self.redeemScript, signingMethod);
9824 }
9825 results.push(new TransactionSignature({
9826 publicKey: privateKey.publicKey,
9827 prevTxId: self.prevTxId,
9828 outputIndex: self.outputIndex,
9829 inputIndex: index,
9830 signature: signature,
9831 sigtype: sigtype
9832 }));
9833 }
9834 });
9835 return results;
9836};
9837
9838MultiSigScriptHashInput.prototype.addSignature = function(transaction, signature, signingMethod) {
9839 $.checkState(!this.isFullySigned(), 'All needed signatures have already been added');
9840 $.checkArgument(!_.isUndefined(this.publicKeyIndex[signature.publicKey.toString()]),
9841 'Signature has no matching public key');
9842 $.checkState(this.isValidSignature(transaction, signature, signingMethod), "Invalid Signature!");
9843 this.signatures[this.publicKeyIndex[signature.publicKey.toString()]] = signature;
9844 this._updateScript();
9845 return this;
9846};
9847
9848MultiSigScriptHashInput.prototype._updateScript = function() {
9849 if (this.nestedWitness || this.type === Address.PayToWitnessScriptHash) {
9850 var stack = [
9851 Buffer.alloc(0),
9852 ];
9853 var signatures = this._createSignatures();
9854 for (var i = 0; i < signatures.length; i++) {
9855 stack.push(signatures[i]);
9856 }
9857 stack.push(this.redeemScript.toBuffer());
9858 this.setWitnesses(stack);
9859 } else {
9860 var scriptSig = Script.buildP2SHMultisigIn(
9861 this.publicKeys,
9862 this.threshold,
9863 this._createSignatures(),
9864 { cachedMultisig: this.redeemScript }
9865 );
9866 this.setScript(scriptSig);
9867 }
9868 return this;
9869};
9870
9871MultiSigScriptHashInput.prototype._createSignatures = function() {
9872 return _.map(
9873 _.filter(this.signatures, function(signature) { return !_.isUndefined(signature); }),
9874 function(signature) {
9875 return BufferUtil.concat([
9876 signature.signature.toDER(),
9877 BufferUtil.integerAsSingleByteBuffer(signature.sigtype)
9878 ]);
9879 }
9880 );
9881};
9882
9883MultiSigScriptHashInput.prototype.clearSignatures = function() {
9884 this.signatures = new Array(this.publicKeys.length);
9885 this._updateScript();
9886};
9887
9888MultiSigScriptHashInput.prototype.isFullySigned = function() {
9889 return this.countSignatures() === this.threshold;
9890};
9891
9892MultiSigScriptHashInput.prototype.countMissingSignatures = function() {
9893 return this.threshold - this.countSignatures();
9894};
9895
9896MultiSigScriptHashInput.prototype.countSignatures = function() {
9897 return _.reduce(this.signatures, function(sum, signature) {
9898 return sum + (!!signature);
9899 }, 0);
9900};
9901
9902MultiSigScriptHashInput.prototype.publicKeysWithoutSignature = function() {
9903 var self = this;
9904 return _.filter(this.publicKeys, function(publicKey) {
9905 return !(self.signatures[self.publicKeyIndex[publicKey.toString()]]);
9906 });
9907};
9908
9909MultiSigScriptHashInput.prototype.isValidSignature = function(transaction, signature, signingMethod) {
9910 signingMethod = signingMethod || 'ecdsa';
9911 if (this.nestedWitness || this.type === Address.PayToWitnessScriptHash) {
9912 signature.signature.nhashtype = signature.sigtype;
9913 var scriptCode = this.getScriptCode();
9914 var satoshisBuffer = this.getSatoshisBuffer();
9915 return SighashWitness.verify(
9916 transaction,
9917 signature.signature,
9918 signature.publicKey,
9919 signature.inputIndex,
9920 scriptCode,
9921 satoshisBuffer,
9922 signingMethod
9923 );
9924 } else {
9925 // FIXME: Refactor signature so this is not necessary
9926 signature.signature.nhashtype = signature.sigtype;
9927 return Sighash.verify(
9928 transaction,
9929 signature.signature,
9930 signature.publicKey,
9931 signature.inputIndex,
9932 this.redeemScript,
9933 signingMethod
9934 );
9935 }
9936};
9937
9938MultiSigScriptHashInput.OPCODES_SIZE = 7; // serialized size (<=3) + 0 .. N .. M OP_CHECKMULTISIG
9939MultiSigScriptHashInput.SIGNATURE_SIZE = 74; // size (1) + DER (<=72) + sighash (1)
9940MultiSigScriptHashInput.PUBKEY_SIZE = 34; // size (1) + DER (<=33)
9941MultiSigScriptHashInput.REDEEM_SCRIPT_SIZE = 34; // OP_0 (1) + scriptHash (1 + 32)
9942
9943MultiSigScriptHashInput.prototype._estimateSize = function() {
9944 var WITNESS_DISCOUNT = 4;
9945 var witnessSize = MultiSigScriptHashInput.OPCODES_SIZE +
9946 this.threshold * MultiSigScriptHashInput.SIGNATURE_SIZE +
9947 this.publicKeys.length * MultiSigScriptHashInput.PUBKEY_SIZE;
9948 if (this.type === Address.PayToWitnessScriptHash) {
9949 return witnessSize / WITNESS_DISCOUNT;
9950 } else if (this.nestedWitness) {
9951 return witnessSize / WITNESS_DISCOUNT + MultiSigScriptHashInput.REDEEM_SCRIPT_SIZE;
9952 } else {
9953 return witnessSize;
9954 }
9955};
9956
9957module.exports = MultiSigScriptHashInput;
9958
9959}).call(this)}).call(this,require("buffer").Buffer)
9960},{"../../address":1,"../../crypto/signature":11,"../../encoding/bufferwriter":16,"../../script":27,"../../util/buffer":45,"../../util/preconditions":47,"../output":37,"../sighash":38,"../sighashwitness":39,"../signature":40,"./input":32,"buffer":132,"inherits":206,"lodash":210}],35:[function(require,module,exports){
9961'use strict';
9962
9963var inherits = require('inherits');
9964
9965var $ = require('../../util/preconditions');
9966var BufferUtil = require('../../util/buffer');
9967
9968var Input = require('./input');
9969var Output = require('../output');
9970var Sighash = require('../sighash');
9971var Script = require('../../script');
9972var Signature = require('../../crypto/signature');
9973var TransactionSignature = require('../signature');
9974
9975/**
9976 * Represents a special kind of input of PayToPublicKey kind.
9977 * @constructor
9978 */
9979function PublicKeyInput() {
9980 Input.apply(this, arguments);
9981}
9982inherits(PublicKeyInput, Input);
9983
9984/**
9985 * @param {Transaction} transaction - the transaction to be signed
9986 * @param {PrivateKey} privateKey - the private key with which to sign the transaction
9987 * @param {number} index - the index of the input in the transaction input vector
9988 * @param {number=} sigtype - the type of signature, defaults to Signature.SIGHASH_ALL
9989 * @param {String} signingMethod - method used to sign input - 'ecdsa' or 'schnorr' (future signing method)
9990 * @return {Array} of objects that can be
9991 */
9992PublicKeyInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype, hashData, signingMethod) {
9993 $.checkState(this.output instanceof Output);
9994 sigtype = sigtype || Signature.SIGHASH_ALL;
9995 var publicKey = privateKey.toPublicKey();
9996 if (publicKey.toString() === this.output.script.getPublicKey().toString('hex')) {
9997 return [new TransactionSignature({
9998 publicKey: publicKey,
9999 prevTxId: this.prevTxId,
10000 outputIndex: this.outputIndex,
10001 inputIndex: index,
10002 signature: Sighash.sign(transaction, privateKey, sigtype, index, this.output.script, signingMethod),
10003 sigtype: sigtype
10004 })];
10005 }
10006 return [];
10007};
10008
10009/**
10010 * Add the provided signature
10011 *
10012 * @param {Object} signature
10013 * @param {PublicKey} signature.publicKey
10014 * @param {Signature} signature.signature
10015 * @param {number=} signature.sigtype
10016 * @param {String} signingMethod - method used to sign - 'ecdsa' or 'schnorr' (future signing method)
10017 * @return {PublicKeyInput} this, for chaining
10018 */
10019PublicKeyInput.prototype.addSignature = function(transaction, signature, signingMethod) {
10020 $.checkState(this.isValidSignature(transaction, signature, signingMethod), 'Signature is invalid');
10021 this.setScript(Script.buildPublicKeyIn(
10022 signature.signature.toDER(),
10023 signature.sigtype
10024 ));
10025 return this;
10026};
10027
10028/**
10029 * Clear the input's signature
10030 * @return {PublicKeyHashInput} this, for chaining
10031 */
10032PublicKeyInput.prototype.clearSignatures = function() {
10033 this.setScript(Script.empty());
10034 return this;
10035};
10036
10037/**
10038 * Query whether the input is signed
10039 * @return {boolean}
10040 */
10041PublicKeyInput.prototype.isFullySigned = function() {
10042 return this.script.isPublicKeyIn();
10043};
10044
10045PublicKeyInput.SCRIPT_MAX_SIZE = 73; // sigsize (1 + 72)
10046
10047PublicKeyInput.prototype._estimateSize = function() {
10048 return PublicKeyInput.SCRIPT_MAX_SIZE;
10049};
10050
10051module.exports = PublicKeyInput;
10052
10053},{"../../crypto/signature":11,"../../script":27,"../../util/buffer":45,"../../util/preconditions":47,"../output":37,"../sighash":38,"../signature":40,"./input":32,"inherits":206}],36:[function(require,module,exports){
10054'use strict';
10055
10056var inherits = require('inherits');
10057
10058var $ = require('../../util/preconditions');
10059var BufferUtil = require('../../util/buffer');
10060
10061var Address = require('../../address');
10062var Hash = require('../../crypto/hash');
10063var Input = require('./input');
10064var Output = require('../output');
10065var Sighash = require('../sighash');
10066var SighashWitness = require('../sighashwitness');
10067var BufferWriter = require('../../encoding/bufferwriter');
10068var BufferUtil = require('../../util/buffer');
10069var Script = require('../../script');
10070var Signature = require('../../crypto/signature');
10071var TransactionSignature = require('../signature');
10072
10073/**
10074 * Represents a special kind of input of PayToPublicKeyHash kind.
10075 * @constructor
10076 */
10077function PublicKeyHashInput() {
10078 Input.apply(this, arguments);
10079}
10080inherits(PublicKeyHashInput, Input);
10081
10082PublicKeyHashInput.prototype.getRedeemScript = function(publicKey) {
10083 if (!this.redeemScript) {
10084 var redeemScript = Script.buildWitnessV0Out(publicKey);
10085 if (Script.buildScriptHashOut(redeemScript).equals(this.output.script)) {
10086 var scriptSig = new Script();
10087 scriptSig.add(redeemScript.toBuffer());
10088 this.setScript(scriptSig);
10089 this.redeemScript = redeemScript;
10090 }
10091 }
10092 return this.redeemScript;
10093};
10094
10095PublicKeyHashInput.prototype.getScriptCode = function(publicKey) {
10096 var writer = new BufferWriter();
10097 var script;
10098 if (this.output.script.isScriptHashOut()) {
10099 script = this.getRedeemScript(publicKey);
10100 } else {
10101 script = this.output.script;
10102 }
10103 var scriptBuffer = Script.buildPublicKeyHashOut(script.toAddress()).toBuffer();
10104 writer.writeVarintNum(scriptBuffer.length);
10105 writer.write(scriptBuffer);
10106 return writer.toBuffer();
10107};
10108
10109PublicKeyHashInput.prototype.getSighash = function(transaction, privateKey, index, sigtype) {
10110 var scriptCode = this.getScriptCode(privateKey);
10111 var satoshisBuffer = this.getSatoshisBuffer();
10112 return SighashWitness.sighash(transaction, sigtype, index, scriptCode, satoshisBuffer);
10113};
10114
10115/* jshint maxparams: 5 */
10116/**
10117 * @param {Transaction} transaction - the transaction to be signed
10118 * @param {PrivateKey} privateKey - the private key with which to sign the transaction
10119 * @param {number} index - the index of the input in the transaction input vector
10120 * @param {number=} sigtype - the type of signature, defaults to Signature.SIGHASH_ALL
10121 * @param {Buffer=} hashData - the precalculated hash of the public key associated with the privateKey provided
10122 * @param {String} signingMethod - method used to sign - 'ecdsa' or 'schnorr' (future signing method)
10123 * @return {Array} of objects that can be
10124 */
10125PublicKeyHashInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype, hashData, signingMethod) {
10126 $.checkState(this.output instanceof Output);
10127 hashData = hashData || Hash.sha256ripemd160(privateKey.publicKey.toBuffer());
10128 sigtype = sigtype || Signature.SIGHASH_ALL;
10129 signingMethod = signingMethod || 'ecdsa';
10130
10131 var script;
10132 if (this.output.script.isScriptHashOut()) {
10133 script = this.getRedeemScript(privateKey.publicKey);
10134 } else {
10135 script = this.output.script;
10136 }
10137
10138 if (script && BufferUtil.equals(hashData, script.getPublicKeyHash())) {
10139 var signature;
10140 if (script.isWitnessPublicKeyHashOut()) {
10141 var satoshisBuffer = this.getSatoshisBuffer();
10142 var scriptCode = this.getScriptCode(privateKey.publicKey);
10143 signature = SighashWitness.sign(transaction, privateKey, sigtype, index, scriptCode, satoshisBuffer, signingMethod);
10144 } else {
10145 signature = Sighash.sign(transaction, privateKey, sigtype, index, this.output.script, signingMethod);
10146 }
10147
10148 return [new TransactionSignature({
10149 publicKey: privateKey.publicKey,
10150 prevTxId: this.prevTxId,
10151 outputIndex: this.outputIndex,
10152 inputIndex: index,
10153 signature: signature,
10154 sigtype: sigtype
10155 })];
10156 }
10157 return [];
10158};
10159/* jshint maxparams: 3 */
10160
10161/**
10162 * Add the provided signature
10163 *
10164 * @param {Object} signature
10165 * @param {PublicKey} signature.publicKey
10166 * @param {Signature} signature.signature
10167 * @param {number=} signature.sigtype
10168 * @param {String} signingMethod - method used to sign - 'ecdsa' or 'schnorr' (future signing method)
10169 * @return {PublicKeyHashInput} this, for chaining
10170 */
10171PublicKeyHashInput.prototype.addSignature = function(transaction, signature, signingMethod) {
10172 $.checkState(this.isValidSignature(transaction, signature, signingMethod), 'Signature is invalid');
10173
10174 if (this.output.script.isWitnessPublicKeyHashOut() || this.output.script.isScriptHashOut()) {
10175 this.setWitnesses([
10176 BufferUtil.concat([
10177 signature.signature.toDER(),
10178 BufferUtil.integerAsSingleByteBuffer(signature.sigtype)
10179 ]),
10180 signature.publicKey.toBuffer()
10181 ]);
10182 } else {
10183 this.setScript(Script.buildPublicKeyHashIn(
10184 signature.publicKey,
10185 signature.signature.toDER(),
10186 signature.sigtype
10187 ));
10188 }
10189 return this;
10190};
10191
10192/**
10193 * Clear the input's signature
10194 * @return {PublicKeyHashInput} this, for chaining
10195 */
10196PublicKeyHashInput.prototype.clearSignatures = function() {
10197 this.setScript(Script.empty());
10198 this.setWitnesses([]);
10199 return this;
10200};
10201
10202/**
10203 * Query whether the input is signed
10204 * @return {boolean}
10205 */
10206PublicKeyHashInput.prototype.isFullySigned = function() {
10207 return this.script.isPublicKeyHashIn() || this.hasWitnesses();
10208};
10209
10210PublicKeyHashInput.prototype.isValidSignature = function(transaction, signature, signingMethod) {
10211 // FIXME: Refactor signature so this is not necessary
10212 signature.signature.nhashtype = signature.sigtype;
10213 if (this.output.script.isWitnessPublicKeyHashOut() || this.output.script.isScriptHashOut()) {
10214 var scriptCode = this.getScriptCode();
10215 var satoshisBuffer = this.getSatoshisBuffer();
10216 return SighashWitness.verify(
10217 transaction,
10218 signature.signature,
10219 signature.publicKey,
10220 signature.inputIndex,
10221 scriptCode,
10222 satoshisBuffer,
10223 signingMethod
10224 );
10225 } else {
10226 return Sighash.verify(
10227 transaction,
10228 signature.signature,
10229 signature.publicKey,
10230 signature.inputIndex,
10231 this.output.script,
10232 signingMethod
10233 );
10234 }
10235};
10236
10237
10238PublicKeyHashInput.SCRIPT_MAX_SIZE = 73 + 34; // sigsize (1 + 72) + pubkey (1 + 33)
10239PublicKeyHashInput.REDEEM_SCRIPT_SIZE = 22; // OP_0 (1) pubkeyhash (1 + 20)
10240
10241PublicKeyHashInput.prototype._estimateSize = function() {
10242 var WITNESS_DISCOUNT = 4;
10243 const witnessSize = PublicKeyHashInput.SCRIPT_MAX_SIZE / WITNESS_DISCOUNT;
10244 if (this.output.script.isWitnessPublicKeyHashOut()) {
10245 return witnessSize;
10246 } else if (this.output.script.isScriptHashOut()) {
10247 return witnessSize + PublicKeyHashInput.REDEEM_SCRIPT_SIZE;
10248 } else {
10249 return PublicKeyHashInput.SCRIPT_MAX_SIZE;
10250 }
10251};
10252
10253module.exports = PublicKeyHashInput;
10254
10255},{"../../address":1,"../../crypto/hash":8,"../../crypto/signature":11,"../../encoding/bufferwriter":16,"../../script":27,"../../util/buffer":45,"../../util/preconditions":47,"../output":37,"../sighash":38,"../sighashwitness":39,"../signature":40,"./input":32,"inherits":206}],37:[function(require,module,exports){
10256(function (Buffer){(function (){
10257'use strict';
10258
10259var _ = require('lodash');
10260var BN = require('../crypto/bn');
10261var buffer = require('buffer');
10262var bufferUtil = require('../util/buffer');
10263var JSUtil = require('../util/js');
10264var BufferWriter = require('../encoding/bufferwriter');
10265var Script = require('../script');
10266var $ = require('../util/preconditions');
10267var errors = require('../errors');
10268
10269var MAX_SAFE_INTEGER = 0x1fffffffffffff;
10270
10271function Output(args) {
10272 if (!(this instanceof Output)) {
10273 return new Output(args);
10274 }
10275 if (_.isObject(args)) {
10276 this.satoshis = args.satoshis;
10277 if (bufferUtil.isBuffer(args.script)) {
10278 this._scriptBuffer = args.script;
10279 } else {
10280 var script;
10281 if (_.isString(args.script) && JSUtil.isHexa(args.script)) {
10282 script = Buffer.from(args.script, 'hex');
10283 } else {
10284 script = args.script;
10285 }
10286 this.setScript(script);
10287 }
10288 } else {
10289 throw new TypeError('Unrecognized argument for Output');
10290 }
10291}
10292
10293Object.defineProperty(Output.prototype, 'script', {
10294 configurable: false,
10295 enumerable: true,
10296 get: function() {
10297 if (this._script) {
10298 return this._script;
10299 } else {
10300 this.setScriptFromBuffer(this._scriptBuffer);
10301 return this._script;
10302 }
10303
10304 }
10305});
10306
10307Object.defineProperty(Output.prototype, 'satoshis', {
10308 configurable: false,
10309 enumerable: true,
10310 get: function() {
10311 return this._satoshis;
10312 },
10313 set: function(num) {
10314 if (num instanceof BN) {
10315 this._satoshisBN = num;
10316 this._satoshis = num.toNumber();
10317 } else if (_.isString(num)) {
10318 this._satoshis = parseInt(num);
10319 this._satoshisBN = BN.fromNumber(this._satoshis);
10320 } else {
10321 $.checkArgument(
10322 JSUtil.isNaturalNumber(num),
10323 'Output satoshis is not a natural number'
10324 );
10325 this._satoshisBN = BN.fromNumber(num);
10326 this._satoshis = num;
10327 }
10328 $.checkState(
10329 JSUtil.isNaturalNumber(this._satoshis),
10330 'Output satoshis is not a natural number'
10331 );
10332 }
10333});
10334
10335Output.prototype.invalidSatoshis = function() {
10336 if (this._satoshis > MAX_SAFE_INTEGER) {
10337 return 'transaction txout satoshis greater than max safe integer';
10338 }
10339 if (this._satoshis !== this._satoshisBN.toNumber()) {
10340 return 'transaction txout satoshis has corrupted value';
10341 }
10342 if (this._satoshis < 0) {
10343 return 'transaction txout negative';
10344 }
10345 return false;
10346};
10347
10348Output.prototype.toObject = Output.prototype.toJSON = function toObject() {
10349 var obj = {
10350 satoshis: this.satoshis
10351 };
10352 obj.script = this._scriptBuffer.toString('hex');
10353 return obj;
10354};
10355
10356Output.fromObject = function(data) {
10357 return new Output(data);
10358};
10359
10360Output.prototype.setScriptFromBuffer = function(buffer) {
10361 this._scriptBuffer = buffer;
10362 try {
10363 this._script = Script.fromBuffer(this._scriptBuffer);
10364 this._script._isOutput = true;
10365 } catch(e) {
10366 if (e instanceof errors.Script.InvalidBuffer) {
10367 this._script = null;
10368 } else {
10369 throw e;
10370 }
10371 }
10372};
10373
10374Output.prototype.setScript = function(script) {
10375 if (script instanceof Script) {
10376 this._scriptBuffer = script.toBuffer();
10377 this._script = script;
10378 this._script._isOutput = true;
10379 } else if (_.isString(script)) {
10380 this._script = Script.fromString(script);
10381 this._scriptBuffer = this._script.toBuffer();
10382 this._script._isOutput = true;
10383 } else if (bufferUtil.isBuffer(script)) {
10384 this.setScriptFromBuffer(script);
10385 } else {
10386 throw new TypeError('Invalid argument type: script');
10387 }
10388 return this;
10389};
10390
10391Output.prototype.inspect = function() {
10392 var scriptStr;
10393 if (this.script) {
10394 scriptStr = this.script.inspect();
10395 } else {
10396 scriptStr = this._scriptBuffer.toString('hex');
10397 }
10398 return '<Output (' + this.satoshis + ' sats) ' + scriptStr + '>';
10399};
10400
10401Output.fromBufferReader = function(br) {
10402 var obj = {};
10403 obj.satoshis = br.readUInt64LEBN();
10404 var size = br.readVarintNum();
10405 if (size !== 0) {
10406 obj.script = br.read(size);
10407 } else {
10408 obj.script = Buffer.from([]);
10409 }
10410 return new Output(obj);
10411};
10412
10413Output.prototype.toBufferWriter = function(writer) {
10414 if (!writer) {
10415 writer = new BufferWriter();
10416 }
10417 writer.writeUInt64LEBN(this._satoshisBN);
10418 var script = this._scriptBuffer;
10419 writer.writeVarintNum(script.length);
10420 writer.write(script);
10421 return writer;
10422};
10423
10424module.exports = Output;
10425
10426}).call(this)}).call(this,require("buffer").Buffer)
10427},{"../crypto/bn":6,"../encoding/bufferwriter":16,"../errors":18,"../script":27,"../util/buffer":45,"../util/js":46,"../util/preconditions":47,"buffer":132,"lodash":210}],38:[function(require,module,exports){
10428(function (Buffer){(function (){
10429'use strict';
10430
10431var Signature = require('../crypto/signature');
10432var Script = require('../script');
10433var Output = require('./output');
10434var BufferReader = require('../encoding/bufferreader');
10435var BufferWriter = require('../encoding/bufferwriter');
10436var BN = require('../crypto/bn');
10437var Hash = require('../crypto/hash');
10438var ECDSA = require('../crypto/ecdsa');
10439var $ = require('../util/preconditions');
10440var _ = require('lodash');
10441const schnorr = require('bip-schnorr');
10442
10443var SIGHASH_SINGLE_BUG = '0000000000000000000000000000000000000000000000000000000000000001';
10444var BITS_64_ON = 'ffffffffffffffff';
10445
10446/**
10447 * Returns a buffer of length 32 bytes with the hash that needs to be signed
10448 * for OP_CHECKSIG.
10449 *
10450 * @name Signing.sighash
10451 * @param {Transaction} transaction the transaction to sign
10452 * @param {number} sighashType the type of the hash
10453 * @param {number} inputNumber the input index for the signature
10454 * @param {Script} subscript the script that will be signed
10455 */
10456var sighash = function sighash(transaction, sighashType, inputNumber, subscript) {
10457 var Transaction = require('./transaction');
10458 var Input = require('./input');
10459
10460 var i;
10461 // Copy transaction
10462 var txcopy = Transaction.shallowCopy(transaction);
10463
10464 // Copy script
10465 subscript = new Script(subscript);
10466 subscript.removeCodeseparators();
10467
10468 for (i = 0; i < txcopy.inputs.length; i++) {
10469 // Blank signatures for other inputs
10470 txcopy.inputs[i] = new Input(txcopy.inputs[i]).setScript(Script.empty());
10471 }
10472
10473 txcopy.inputs[inputNumber] = new Input(txcopy.inputs[inputNumber]).setScript(subscript);
10474
10475 if ((sighashType & 31) === Signature.SIGHASH_NONE ||
10476 (sighashType & 31) === Signature.SIGHASH_SINGLE) {
10477
10478 // clear all sequenceNumbers
10479 for (i = 0; i < txcopy.inputs.length; i++) {
10480 if (i !== inputNumber) {
10481 txcopy.inputs[i].sequenceNumber = 0;
10482 }
10483 }
10484 }
10485
10486 if ((sighashType & 31) === Signature.SIGHASH_NONE) {
10487 txcopy.outputs = [];
10488
10489 } else if ((sighashType & 31) === Signature.SIGHASH_SINGLE) {
10490 // The SIGHASH_SINGLE bug.
10491 // https://bitcointalk.org/index.php?topic=260595.0
10492 if (inputNumber >= txcopy.outputs.length) {
10493 return Buffer.from(SIGHASH_SINGLE_BUG, 'hex');
10494 }
10495
10496 txcopy.outputs.length = inputNumber + 1;
10497
10498 for (i = 0; i < inputNumber; i++) {
10499 txcopy.outputs[i] = new Output({
10500 satoshis: BN.fromBuffer(Buffer.from(BITS_64_ON, 'hex')),
10501 script: Script.empty()
10502 });
10503 }
10504 }
10505
10506 if (sighashType & Signature.SIGHASH_ANYONECANPAY) {
10507 txcopy.inputs = [txcopy.inputs[inputNumber]];
10508 }
10509
10510 var buf = new BufferWriter()
10511 .write(txcopy.toBuffer())
10512 .writeInt32LE(sighashType)
10513 .toBuffer();
10514 var ret = Hash.sha256sha256(buf);
10515 ret = new BufferReader(ret).readReverse();
10516 return ret;
10517};
10518
10519/**
10520 * Create a signature
10521 *
10522 * @name Signing.sign
10523 * @param {Transaction} transaction
10524 * @param {PrivateKey} privateKey
10525 * @param {number} sighash
10526 * @param {number} inputIndex
10527 * @param {Script} subscript
10528 * @param {String} signingMethod - method used to sign - 'ecdsa' or 'schnorr' (future signing method)
10529 * @return {Signature}
10530 */
10531function sign(transaction, privateKey, sighashType, inputIndex, subscript, signingMethod) {
10532 signingMethod = signingMethod || 'ecdsa';
10533
10534 let hashbuf = sighash(transaction, sighashType, inputIndex, subscript);
10535 let sig;
10536 switch (signingMethod) {
10537 case 'ecdsa':
10538 sig = ECDSA.sign(hashbuf, privateKey, 'little').set({ nhashtype: sighashType });
10539 break;
10540 case 'schnorr':
10541 sig = schnorr.sign(privateKey.toString(), hashbuf);
10542 break;
10543 default:
10544 throw new Error("signingMethod not supported ", signingMethod);
10545 }
10546 return sig;
10547}
10548
10549/**
10550 * Verify a signature
10551 *
10552 * @name Signing.verify
10553 * @param {Transaction} transaction
10554 * @param {Signature} signature
10555 * @param {PublicKey} publicKey
10556 * @param {number} inputIndex
10557 * @param {Script} subscript
10558 * @param {String} signingMethod - method used to sign - 'ecdsa' or 'schnorr'
10559 * @return {boolean}
10560 */
10561function verify(transaction, signature, publicKey, inputIndex, subscript, signingMethod) {
10562 $.checkArgument(!_.isUndefined(transaction), "Transaction Undefined");
10563 $.checkArgument(!_.isUndefined(signature) && !_.isUndefined(signature.nhashtype), "Signature Undefined");
10564
10565 signingMethod = signingMethod || 'ecdsa';
10566 let hashbuf = sighash(transaction, signature.nhashtype, inputIndex, subscript);
10567 let verified = false;
10568
10569 switch (signingMethod) {
10570 case 'ecdsa':
10571 verified = ECDSA.verify(hashbuf, signature, publicKey, 'little');
10572 break;
10573 case 'schnorr':
10574 verified = schnorr.verify(publicKey, hashbuf, signature);
10575 break;
10576 default:
10577 throw new Error("signingMethod not supported ", signingMethod);
10578 }
10579 return verified;
10580}
10581
10582/**
10583 * @namespace Signing
10584 */
10585module.exports = {
10586 sighash: sighash,
10587 sign: sign,
10588 verify: verify
10589};
10590
10591}).call(this)}).call(this,require("buffer").Buffer)
10592},{"../crypto/bn":6,"../crypto/ecdsa":7,"../crypto/hash":8,"../crypto/signature":11,"../encoding/bufferreader":15,"../encoding/bufferwriter":16,"../script":27,"../util/preconditions":47,"./input":31,"./output":37,"./transaction":41,"bip-schnorr":75,"buffer":132,"lodash":210}],39:[function(require,module,exports){
10593(function (Buffer){(function (){
10594'use strict';
10595
10596/* jshint maxparams:5 */
10597
10598var Signature = require('../crypto/signature');
10599var Script = require('../script');
10600var Output = require('./output');
10601var BufferReader = require('../encoding/bufferreader');
10602var BufferWriter = require('../encoding/bufferwriter');
10603var BN = require('../crypto/bn');
10604var Hash = require('../crypto/hash');
10605var ECDSA = require('../crypto/ecdsa');
10606var $ = require('../util/preconditions');
10607var _ = require('lodash');
10608
10609/**
10610 * Returns a buffer of length 32 bytes with the hash that needs to be signed
10611 * for witness programs as defined by:
10612 * https://github.com/bitcoin/bips/blob/master/bip-0143.mediawiki
10613 *
10614 * @name Signing.sighash
10615 * @param {Transaction} transaction the transaction to sign
10616 * @param {number} sighashType the type of the hash
10617 * @param {number} inputNumber the input index for the signature
10618 * @param {Buffer} scriptCode
10619 * @param {Buffer} satoshisBuffer
10620 */
10621var sighash = function sighash(transaction, sighashType, inputNumber, scriptCode, satoshisBuffer) {
10622 /* jshint maxstatements: 50 */
10623
10624 var hashPrevouts;
10625 var hashSequence;
10626 var hashOutputs;
10627
10628 if (!(sighashType & Signature.SIGHASH_ANYONECANPAY)) {
10629 var buffers = [];
10630 for (var n = 0; n < transaction.inputs.length; n++) {
10631 var input = transaction.inputs[n];
10632 var prevTxIdBuffer = new BufferReader(input.prevTxId).readReverse();
10633 buffers.push(prevTxIdBuffer);
10634 var outputIndexBuffer = Buffer.alloc(4);
10635 outputIndexBuffer.writeUInt32LE(input.outputIndex, 0);
10636 buffers.push(outputIndexBuffer);
10637 }
10638 hashPrevouts = Hash.sha256sha256(Buffer.concat(buffers));
10639 }
10640
10641 if (!(sighashType & Signature.SIGHASH_ANYONECANPAY) &&
10642 (sighashType & 0x1f) !== Signature.SIGHASH_SINGLE && (sighashType & 0x1f) !== Signature.SIGHASH_NONE) {
10643
10644 var sequenceBuffers = [];
10645 for (var m = 0; m < transaction.inputs.length; m++) {
10646 var sequenceBuffer = Buffer.alloc(4);
10647 sequenceBuffer.writeUInt32LE(transaction.inputs[m].sequenceNumber, 0);
10648 sequenceBuffers.push(sequenceBuffer);
10649 }
10650 hashSequence = Hash.sha256sha256(Buffer.concat(sequenceBuffers));
10651 }
10652
10653 var outputWriter = new BufferWriter();
10654 if ((sighashType & 0x1f) !== Signature.SIGHASH_SINGLE && (sighashType & 0x1f) !== Signature.SIGHASH_NONE) {
10655 for (var p = 0; p < transaction.outputs.length; p++) {
10656 transaction.outputs[p].toBufferWriter(outputWriter);
10657 }
10658 hashOutputs = Hash.sha256sha256(outputWriter.toBuffer());
10659 } else if ((sighashType & 0x1f) === Signature.SIGHASH_SINGLE && inputNumber < transaction.outputs.length) {
10660 transaction.outputs[inputNumber].toBufferWriter(outputWriter);
10661 hashOutputs = Hash.sha256sha256(outputWriter.toBuffer());
10662 }
10663
10664 // Version
10665 var writer = new BufferWriter();
10666 writer.writeUInt32LE(transaction.version);
10667
10668 // Input prevouts/nSequence (none/all, depending on flags)
10669 writer.write(hashPrevouts);
10670 writer.write(hashSequence);
10671
10672 // The input being signed (replacing the scriptSig with scriptCode + amount)
10673 // The prevout may already be contained in hashPrevout, and the nSequence
10674 // may already be contain in hashSequence.
10675 var outpointId = new BufferReader(transaction.inputs[inputNumber].prevTxId).readReverse();
10676 writer.write(outpointId);
10677 writer.writeUInt32LE(transaction.inputs[inputNumber].outputIndex);
10678
10679 writer.write(scriptCode);
10680
10681 writer.write(satoshisBuffer);
10682
10683 writer.writeUInt32LE(transaction.inputs[inputNumber].sequenceNumber);
10684
10685 // Outputs (none/one/all, depending on flags)
10686 writer.write(hashOutputs);
10687
10688 // Locktime
10689 writer.writeUInt32LE(transaction.nLockTime);
10690
10691 // Sighash type
10692 writer.writeInt32LE(sighashType);
10693
10694 return Hash.sha256sha256(writer.toBuffer());
10695
10696};
10697
10698/**
10699 * Create a signature
10700 *
10701 * @name Signing.sign
10702 * @param {Transaction} transaction
10703 * @param {PrivateKey} privateKey
10704 * @param {number} sighash
10705 * @param {number} inputIndex
10706 * @param {Script} subscript
10707 * @param {String} signingMethod - method used to sign - 'ecdsa' or 'schnorr'
10708 * @return {Signature}
10709 */
10710function sign(transaction, privateKey, sighashType, inputIndex, scriptCode, satoshisBuffer, signingMethod) {
10711 signingMethod = signingMethod || 'ecdsa';
10712 var sig;
10713
10714 if (signingMethod === 'ecdsa') {
10715 let hashbuf = sighash(transaction, sighashType, inputIndex, scriptCode, satoshisBuffer);
10716 sig = ECDSA.sign(hashbuf, privateKey).set({
10717 nhashtype: sighashType
10718 });
10719 return sig;
10720 }
10721 throw new Error("signingMethod not supported ", signingMethod);
10722}
10723
10724/**
10725 * Verify a signature
10726 *
10727 * @name Signing.verify
10728 * @param {Transaction} transaction
10729 * @param {Signature} signature
10730 * @param {PublicKey} publicKey
10731 * @param {number} inputIndex
10732 * @param {Script} subscript
10733 * @param {String} signingMethod - method used to sign - 'ecdsa' or 'schnorr' (future signing method)
10734 * @return {boolean}
10735 */
10736function verify(transaction, signature, publicKey, inputIndex, scriptCode, satoshisBuffer, signingMethod) {
10737 $.checkArgument(!_.isUndefined(transaction));
10738 $.checkArgument(!_.isUndefined(signature) && !_.isUndefined(signature.nhashtype));
10739 signingMethod = signingMethod || 'ecdsa';
10740
10741 if (signingMethod === 'ecdsa') {
10742 let hashbuf = sighash(transaction, signature.nhashtype, inputIndex, scriptCode, satoshisBuffer);
10743 return ECDSA.verify(hashbuf, signature, publicKey);
10744 }
10745 throw new Error("signingMethod not supported ", signingMethod);
10746}
10747
10748/**
10749 * @namespace Signing
10750 */
10751module.exports = {
10752 sighash: sighash,
10753 sign: sign,
10754 verify: verify
10755};
10756
10757}).call(this)}).call(this,require("buffer").Buffer)
10758},{"../crypto/bn":6,"../crypto/ecdsa":7,"../crypto/hash":8,"../crypto/signature":11,"../encoding/bufferreader":15,"../encoding/bufferwriter":16,"../script":27,"../util/preconditions":47,"./output":37,"buffer":132,"lodash":210}],40:[function(require,module,exports){
10759(function (Buffer){(function (){
10760'use strict';
10761
10762var _ = require('lodash');
10763var $ = require('../util/preconditions');
10764var inherits = require('inherits');
10765var BufferUtil = require('../util/buffer');
10766var JSUtil = require('../util/js');
10767
10768var PublicKey = require('../publickey');
10769var errors = require('../errors');
10770var Signature = require('../crypto/signature');
10771
10772/**
10773 * @desc
10774 * Wrapper around Signature with fields related to signing a transaction specifically
10775 *
10776 * @param {Object|string|TransactionSignature} arg
10777 * @constructor
10778 */
10779function TransactionSignature(arg) {
10780 if (!(this instanceof TransactionSignature)) {
10781 return new TransactionSignature(arg);
10782 }
10783 if (arg instanceof TransactionSignature) {
10784 return arg;
10785 }
10786 if (_.isObject(arg)) {
10787 return this._fromObject(arg);
10788 }
10789 throw new errors.InvalidArgument('TransactionSignatures must be instantiated from an object');
10790}
10791inherits(TransactionSignature, Signature);
10792
10793TransactionSignature.prototype._fromObject = function(arg) {
10794 this._checkObjectArgs(arg);
10795 this.publicKey = new PublicKey(arg.publicKey);
10796 this.prevTxId = BufferUtil.isBuffer(arg.prevTxId) ? arg.prevTxId : Buffer.from(arg.prevTxId, 'hex');
10797 this.outputIndex = arg.outputIndex;
10798 this.inputIndex = arg.inputIndex;
10799 this.signature = (arg.signature instanceof Signature) ? arg.signature :
10800 BufferUtil.isBuffer(arg.signature) ? Signature.fromBuffer(arg.signature) :
10801 Signature.fromString(arg.signature);
10802 this.sigtype = arg.sigtype;
10803 return this;
10804};
10805
10806TransactionSignature.prototype._checkObjectArgs = function(arg) {
10807 $.checkArgument(PublicKey(arg.publicKey), 'publicKey');
10808 $.checkArgument(!_.isUndefined(arg.inputIndex), 'inputIndex');
10809 $.checkArgument(!_.isUndefined(arg.outputIndex), 'outputIndex');
10810 $.checkState(_.isNumber(arg.inputIndex), 'inputIndex must be a number');
10811 $.checkState(_.isNumber(arg.outputIndex), 'outputIndex must be a number');
10812 $.checkArgument(arg.signature, 'signature');
10813 $.checkArgument(arg.prevTxId, 'prevTxId');
10814 $.checkState(arg.signature instanceof Signature ||
10815 BufferUtil.isBuffer(arg.signature) ||
10816 JSUtil.isHexa(arg.signature), 'signature must be a buffer or hexa value');
10817 $.checkState(BufferUtil.isBuffer(arg.prevTxId) ||
10818 JSUtil.isHexa(arg.prevTxId), 'prevTxId must be a buffer or hexa value');
10819 $.checkArgument(arg.sigtype, 'sigtype');
10820 $.checkState(_.isNumber(arg.sigtype), 'sigtype must be a number');
10821};
10822
10823/**
10824 * Serializes a transaction to a plain JS object
10825 * @return {Object}
10826 */
10827TransactionSignature.prototype.toObject = TransactionSignature.prototype.toJSON = function toObject() {
10828 return {
10829 publicKey: this.publicKey.toString(),
10830 prevTxId: this.prevTxId.toString('hex'),
10831 outputIndex: this.outputIndex,
10832 inputIndex: this.inputIndex,
10833 signature: this.signature.toString(),
10834 sigtype: this.sigtype
10835 };
10836};
10837
10838/**
10839 * Builds a TransactionSignature from an object
10840 * @param {Object} object
10841 * @return {TransactionSignature}
10842 */
10843TransactionSignature.fromObject = function(object) {
10844 $.checkArgument(object);
10845 return new TransactionSignature(object);
10846};
10847
10848module.exports = TransactionSignature;
10849
10850}).call(this)}).call(this,require("buffer").Buffer)
10851},{"../crypto/signature":11,"../errors":18,"../publickey":26,"../util/buffer":45,"../util/js":46,"../util/preconditions":47,"buffer":132,"inherits":206,"lodash":210}],41:[function(require,module,exports){
10852(function (Buffer){(function (){
10853'use strict';
10854
10855var _ = require('lodash');
10856var $ = require('../util/preconditions');
10857var buffer = require('buffer');
10858var compare = Buffer.compare || require('buffer-compare');
10859
10860var errors = require('../errors');
10861var BufferUtil = require('../util/buffer');
10862var JSUtil = require('../util/js');
10863var BufferReader = require('../encoding/bufferreader');
10864var BufferWriter = require('../encoding/bufferwriter');
10865var Hash = require('../crypto/hash');
10866var Signature = require('../crypto/signature');
10867var Sighash = require('./sighash');
10868var SighashWitness = require('./sighashwitness');
10869
10870var Address = require('../address');
10871var UnspentOutput = require('./unspentoutput');
10872var Input = require('./input');
10873var PublicKeyHashInput = Input.PublicKeyHash;
10874var PublicKeyInput = Input.PublicKey;
10875var MultiSigScriptHashInput = Input.MultiSigScriptHash;
10876var MultiSigInput = Input.MultiSig;
10877var Output = require('./output');
10878var Script = require('../script');
10879var PrivateKey = require('../privatekey');
10880var BN = require('../crypto/bn');
10881
10882/**
10883 * Represents a transaction, a set of inputs and outputs to change ownership of tokens
10884 *
10885 * @param {*} serialized
10886 * @constructor
10887 */
10888function Transaction(serialized, opts) {
10889 if (!(this instanceof Transaction)) {
10890 return new Transaction(serialized);
10891 }
10892 this.inputs = [];
10893 this.outputs = [];
10894 this._inputAmount = undefined;
10895 this._outputAmount = undefined;
10896
10897 if (serialized) {
10898 if (serialized instanceof Transaction) {
10899 return Transaction.shallowCopy(serialized);
10900 } else if (JSUtil.isHexa(serialized)) {
10901 this.fromString(serialized);
10902 } else if (BufferUtil.isBuffer(serialized)) {
10903 this.fromBuffer(serialized);
10904 } else if (_.isObject(serialized)) {
10905 this.fromObject(serialized, opts);
10906 } else {
10907 throw new errors.InvalidArgument('Must provide an object or string to deserialize a transaction');
10908 }
10909 } else {
10910 this._newTransaction();
10911 }
10912}
10913var CURRENT_VERSION = 2;
10914var DEFAULT_NLOCKTIME = 0;
10915var MAX_BLOCK_SIZE = 1000000;
10916
10917// Minimum amount for an output for it not to be considered a dust output
10918Transaction.DUST_AMOUNT = 546;
10919
10920// Margin of error to allow fees in the vecinity of the expected value but doesn't allow a big difference
10921Transaction.FEE_SECURITY_MARGIN = 150;
10922
10923// max amount of satoshis in circulation
10924Transaction.MAX_MONEY = 21000000 * 1e8;
10925
10926// nlocktime limit to be considered block height rather than a timestamp
10927Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT = 5e8;
10928
10929// Max value for an unsigned 32 bit value
10930Transaction.NLOCKTIME_MAX_VALUE = 4294967295;
10931
10932// Value used for fee estimation (satoshis per kilobyte)
10933Transaction.FEE_PER_KB = 100000;
10934
10935// Safe upper bound for change address script size in bytes
10936Transaction.CHANGE_OUTPUT_MAX_SIZE = 20 + 4 + 34 + 4;
10937Transaction.MAXIMUM_EXTRA_SIZE = 4 + 9 + 9 + 4;
10938
10939/* Constructors and Serialization */
10940
10941/**
10942 * Create a 'shallow' copy of the transaction, by serializing and deserializing
10943 * it dropping any additional information that inputs and outputs may have hold
10944 *
10945 * @param {Transaction} transaction
10946 * @return {Transaction}
10947 */
10948Transaction.shallowCopy = function(transaction) {
10949 var copy = new Transaction(transaction.toBuffer());
10950 return copy;
10951};
10952
10953var hashProperty = {
10954 configurable: false,
10955 enumerable: true,
10956 get: function() {
10957 this._hash = new BufferReader(this._getHash()).readReverse().toString('hex');
10958 return this._hash;
10959 }
10960};
10961
10962var witnessHashProperty = {
10963 configurable: false,
10964 enumerable: true,
10965 get: function() {
10966 return new BufferReader(this._getWitnessHash()).readReverse().toString('hex');
10967 }
10968};
10969
10970Object.defineProperty(Transaction.prototype, 'witnessHash', witnessHashProperty);
10971Object.defineProperty(Transaction.prototype, 'hash', hashProperty);
10972Object.defineProperty(Transaction.prototype, 'id', hashProperty);
10973
10974var ioProperty = {
10975 configurable: false,
10976 enumerable: true,
10977 get: function() {
10978 return this._getInputAmount();
10979 }
10980};
10981Object.defineProperty(Transaction.prototype, 'inputAmount', ioProperty);
10982ioProperty.get = function() {
10983 return this._getOutputAmount();
10984};
10985Object.defineProperty(Transaction.prototype, 'outputAmount', ioProperty);
10986
10987/**
10988 * Retrieve the little endian hash of the transaction (used for serialization)
10989 * @return {Buffer}
10990 */
10991Transaction.prototype._getHash = function() {
10992 return Hash.sha256sha256(this.toBuffer(true));
10993};
10994
10995/**
10996 * Retrieve the little endian hash of the transaction including witness data
10997 * @return {Buffer}
10998 */
10999Transaction.prototype._getWitnessHash = function() {
11000 return Hash.sha256sha256(this.toBuffer(false));
11001};
11002
11003/**
11004 * Retrieve a hexa string that can be used with bitcoind's CLI interface
11005 * (decoderawtransaction, sendrawtransaction)
11006 *
11007 * @param {Object|boolean=} unsafe if true, skip all tests. if it's an object,
11008 * it's expected to contain a set of flags to skip certain tests:
11009 * * `disableAll`: disable all checks
11010 * * `disableSmallFees`: disable checking for fees that are too small
11011 * * `disableLargeFees`: disable checking for fees that are too large
11012 * * `disableIsFullySigned`: disable checking if all inputs are fully signed
11013 * * `disableDustOutputs`: disable checking if there are no outputs that are dust amounts
11014 * * `disableMoreOutputThanInput`: disable checking if the transaction spends more bitcoins than the sum of the input amounts
11015 * @return {string}
11016 */
11017Transaction.prototype.serialize = function(unsafe) {
11018 if (true === unsafe || unsafe && unsafe.disableAll) {
11019 return this.uncheckedSerialize();
11020 } else {
11021 return this.checkedSerialize(unsafe);
11022 }
11023};
11024
11025Transaction.prototype.uncheckedSerialize = Transaction.prototype.toString = function() {
11026 return this.toBuffer().toString('hex');
11027};
11028
11029/**
11030 * Retrieve a hexa string that can be used with bitcoind's CLI interface
11031 * (decoderawtransaction, sendrawtransaction)
11032 *
11033 * @param {Object} opts allows to skip certain tests. {@see Transaction#serialize}
11034 * @return {string}
11035 */
11036Transaction.prototype.checkedSerialize = function(opts) {
11037 var serializationError = this.getSerializationError(opts);
11038 if (serializationError) {
11039 serializationError.message += ' - For more information please see: ' +
11040 'https://bitcore.io/api/lib/transaction#serialization-checks';
11041 throw serializationError;
11042 }
11043 return this.uncheckedSerialize();
11044};
11045
11046Transaction.prototype.invalidSatoshis = function() {
11047 var invalid = false;
11048 for (var i = 0; i < this.outputs.length; i++) {
11049 if (this.outputs[i].invalidSatoshis()) {
11050 invalid = true;
11051 }
11052 }
11053 return invalid;
11054};
11055
11056/**
11057 * Retrieve a possible error that could appear when trying to serialize and
11058 * broadcast this transaction.
11059 *
11060 * @param {Object} opts allows to skip certain tests. {@see Transaction#serialize}
11061 * @return {bitcore.Error}
11062 */
11063Transaction.prototype.getSerializationError = function(opts) {
11064 opts = opts || {};
11065
11066 if (this.invalidSatoshis()) {
11067 return new errors.Transaction.InvalidSatoshis();
11068 }
11069
11070 var unspent = this._getUnspentValue();
11071 var unspentError;
11072 if (unspent < 0) {
11073 if (!opts.disableMoreOutputThanInput) {
11074 unspentError = new errors.Transaction.InvalidOutputAmountSum();
11075 }
11076 } else {
11077 unspentError = this._hasFeeError(opts, unspent);
11078 }
11079
11080 return unspentError ||
11081 this._hasDustOutputs(opts) ||
11082 this._isMissingSignatures(opts);
11083};
11084
11085Transaction.prototype._hasFeeError = function(opts, unspent) {
11086
11087 if (!_.isUndefined(this._fee) && this._fee !== unspent) {
11088 return new errors.Transaction.FeeError.Different(
11089 'Unspent value is ' + unspent + ' but specified fee is ' + this._fee
11090 );
11091 }
11092
11093 if (!opts.disableLargeFees) {
11094 var maximumFee = Math.floor(Transaction.FEE_SECURITY_MARGIN * this._estimateFee());
11095 if (unspent > maximumFee) {
11096 if (this._missingChange()) {
11097 return new errors.Transaction.ChangeAddressMissing(
11098 'Fee is too large and no change address was provided'
11099 );
11100 }
11101 return new errors.Transaction.FeeError.TooLarge(
11102 'expected less than ' + maximumFee + ' but got ' + unspent
11103 );
11104 }
11105 }
11106
11107 if (!opts.disableSmallFees) {
11108 var minimumFee = Math.ceil(this._estimateFee() / Transaction.FEE_SECURITY_MARGIN);
11109 if (unspent < minimumFee) {
11110 return new errors.Transaction.FeeError.TooSmall(
11111 'expected more than ' + minimumFee + ' but got ' + unspent
11112 );
11113 }
11114 }
11115};
11116
11117Transaction.prototype._missingChange = function() {
11118 return !this._changeScript;
11119};
11120
11121Transaction.prototype._hasDustOutputs = function(opts) {
11122 if (opts.disableDustOutputs) {
11123 return;
11124 }
11125 var index, output;
11126 for (index in this.outputs) {
11127 output = this.outputs[index];
11128 if (output.satoshis < Transaction.DUST_AMOUNT && !output.script.isDataOut()) {
11129 return new errors.Transaction.DustOutputs();
11130 }
11131 }
11132};
11133
11134Transaction.prototype._isMissingSignatures = function(opts) {
11135 if (opts.disableIsFullySigned) {
11136 return;
11137 }
11138 if (!this.isFullySigned()) {
11139 return new errors.Transaction.MissingSignatures();
11140 }
11141};
11142
11143Transaction.prototype.inspect = function() {
11144 return '<Transaction: ' + this.uncheckedSerialize() + '>';
11145};
11146
11147Transaction.prototype.toBuffer = function(noWitness) {
11148 var writer = new BufferWriter();
11149 return this.toBufferWriter(writer, noWitness).toBuffer();
11150};
11151
11152Transaction.prototype.hasWitnesses = function() {
11153 for (var i = 0; i < this.inputs.length; i++) {
11154 if (this.inputs[i].hasWitnesses()) {
11155 return true;
11156 }
11157 }
11158 return false;
11159};
11160
11161Transaction.prototype.toBufferWriter = function(writer, noWitness) {
11162 writer.writeInt32LE(this.version);
11163
11164 var hasWitnesses = this.hasWitnesses();
11165
11166 if (hasWitnesses && !noWitness) {
11167 writer.write(Buffer.from('0001', 'hex'));
11168 }
11169
11170 writer.writeVarintNum(this.inputs.length);
11171
11172 _.each(this.inputs, function(input) {
11173 input.toBufferWriter(writer);
11174 });
11175
11176 writer.writeVarintNum(this.outputs.length);
11177 _.each(this.outputs, function(output) {
11178 output.toBufferWriter(writer);
11179 });
11180
11181 if (hasWitnesses && !noWitness) {
11182 _.each(this.inputs, function(input) {
11183 var witnesses = input.getWitnesses();
11184 writer.writeVarintNum(witnesses.length);
11185 for (var j = 0; j < witnesses.length; j++) {
11186 writer.writeVarintNum(witnesses[j].length);
11187 writer.write(witnesses[j]);
11188 }
11189 });
11190 }
11191
11192 writer.writeUInt32LE(this.nLockTime);
11193 return writer;
11194};
11195
11196Transaction.prototype.fromBuffer = function(buffer) {
11197 var reader = new BufferReader(buffer);
11198 return this.fromBufferReader(reader);
11199};
11200
11201Transaction.prototype.fromBufferReader = function(reader) {
11202 $.checkArgument(!reader.finished(), 'No transaction data received');
11203
11204 this.version = reader.readInt32LE();
11205 var sizeTxIns = reader.readVarintNum();
11206
11207 // check for segwit
11208 var hasWitnesses = false;
11209 if (sizeTxIns === 0 && reader.buf[reader.pos] !== 0) {
11210 reader.pos += 1;
11211 hasWitnesses = true;
11212 sizeTxIns = reader.readVarintNum();
11213 }
11214
11215 for (var i = 0; i < sizeTxIns; i++) {
11216 var input = Input.fromBufferReader(reader);
11217 this.inputs.push(input);
11218 }
11219
11220 var sizeTxOuts = reader.readVarintNum();
11221 for (var j = 0; j < sizeTxOuts; j++) {
11222 this.outputs.push(Output.fromBufferReader(reader));
11223 }
11224
11225 if (hasWitnesses) {
11226 for (var k = 0; k < sizeTxIns; k++) {
11227 var itemCount = reader.readVarintNum();
11228 var witnesses = [];
11229 for (var l = 0; l < itemCount; l++) {
11230 var size = reader.readVarintNum();
11231 var item = reader.read(size);
11232 witnesses.push(item);
11233 }
11234 this.inputs[k].setWitnesses(witnesses);
11235 }
11236 }
11237
11238 this.nLockTime = reader.readUInt32LE();
11239 return this;
11240};
11241
11242
11243Transaction.prototype.toObject = Transaction.prototype.toJSON = function toObject() {
11244 var inputs = [];
11245 this.inputs.forEach(function(input) {
11246 inputs.push(input.toObject());
11247 });
11248 var outputs = [];
11249 this.outputs.forEach(function(output) {
11250 outputs.push(output.toObject());
11251 });
11252 var obj = {
11253 hash: this.hash,
11254 version: this.version,
11255 inputs: inputs,
11256 outputs: outputs,
11257 nLockTime: this.nLockTime
11258 };
11259 if (this._changeScript) {
11260 obj.changeScript = this._changeScript.toString();
11261 }
11262 if (!_.isUndefined(this._changeIndex)) {
11263 obj.changeIndex = this._changeIndex;
11264 }
11265 if (!_.isUndefined(this._fee)) {
11266 obj.fee = this._fee;
11267 }
11268 return obj;
11269};
11270
11271Transaction.prototype.fromObject = function fromObject(arg, opts) {
11272 /* jshint maxstatements: 20 */
11273 $.checkArgument(_.isObject(arg) || arg instanceof Transaction);
11274 var self = this;
11275 var transaction;
11276 if (arg instanceof Transaction) {
11277 transaction = transaction.toObject();
11278 } else {
11279 transaction = arg;
11280 }
11281 _.each(transaction.inputs, function(input) {
11282 if (!input.output || !input.output.script) {
11283 self.uncheckedAddInput(new Input(input));
11284 return;
11285 }
11286 var script = new Script(input.output.script);
11287 var txin;
11288 if ((script.isScriptHashOut() || script.isWitnessScriptHashOut()) && input.publicKeys && input.threshold) {
11289 txin = new Input.MultiSigScriptHash(
11290 input, input.publicKeys, input.threshold, input.signatures, opts
11291 );
11292 } else if (script.isPublicKeyHashOut() || script.isWitnessPublicKeyHashOut() || script.isScriptHashOut()) {
11293 txin = new Input.PublicKeyHash(input);
11294 } else if (script.isPublicKeyOut()) {
11295 txin = new Input.PublicKey(input);
11296 } else {
11297 throw new errors.Transaction.Input.UnsupportedScript(input.output.script);
11298 }
11299 self.addInput(txin);
11300 });
11301 _.each(transaction.outputs, function(output) {
11302 self.addOutput(new Output(output));
11303 });
11304 if (transaction.changeIndex) {
11305 this._changeIndex = transaction.changeIndex;
11306 }
11307 if (transaction.changeScript) {
11308 this._changeScript = new Script(transaction.changeScript);
11309 }
11310 if (transaction.fee) {
11311 this._fee = transaction.fee;
11312 }
11313 this.nLockTime = transaction.nLockTime;
11314 this.version = transaction.version;
11315 this._checkConsistency(arg);
11316 return this;
11317};
11318
11319Transaction.prototype._checkConsistency = function(arg) {
11320 if (!_.isUndefined(this._changeIndex)) {
11321 $.checkState(this._changeScript, 'Change script is expected.');
11322 $.checkState(this.outputs[this._changeIndex], 'Change index points to undefined output.');
11323 $.checkState(this.outputs[this._changeIndex].script.toString() ===
11324 this._changeScript.toString(), 'Change output has an unexpected script.');
11325 }
11326 if (arg && arg.hash) {
11327 $.checkState(arg.hash === this.hash, 'Hash in object does not match transaction hash.');
11328 }
11329};
11330
11331/**
11332 * Sets nLockTime so that transaction is not valid until the desired date(a
11333 * timestamp in seconds since UNIX epoch is also accepted)
11334 *
11335 * @param {Date | Number} time
11336 * @return {Transaction} this
11337 */
11338Transaction.prototype.lockUntilDate = function(time) {
11339 $.checkArgument(time);
11340 if (_.isNumber(time) && time < Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) {
11341 throw new errors.Transaction.LockTimeTooEarly();
11342 }
11343 if (_.isDate(time)) {
11344 time = time.getTime() / 1000;
11345 }
11346
11347 for (var i = 0; i < this.inputs.length; i++) {
11348 if (this.inputs[i].sequenceNumber === Input.DEFAULT_SEQNUMBER){
11349 this.inputs[i].sequenceNumber = Input.DEFAULT_LOCKTIME_SEQNUMBER;
11350 }
11351 }
11352
11353 this.nLockTime = time;
11354 return this;
11355};
11356
11357/**
11358 * Sets nLockTime so that transaction is not valid until the desired block
11359 * height.
11360 *
11361 * @param {Number} height
11362 * @return {Transaction} this
11363 */
11364Transaction.prototype.lockUntilBlockHeight = function(height) {
11365 $.checkArgument(_.isNumber(height));
11366 if (height >= Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) {
11367 throw new errors.Transaction.BlockHeightTooHigh();
11368 }
11369 if (height < 0) {
11370 throw new errors.Transaction.NLockTimeOutOfRange();
11371 }
11372
11373 for (var i = 0; i < this.inputs.length; i++) {
11374 if (this.inputs[i].sequenceNumber === Input.DEFAULT_SEQNUMBER){
11375 this.inputs[i].sequenceNumber = Input.DEFAULT_LOCKTIME_SEQNUMBER;
11376 }
11377 }
11378
11379
11380 this.nLockTime = height;
11381 return this;
11382};
11383
11384/**
11385 * Returns a semantic version of the transaction's nLockTime.
11386 * @return {Number|Date}
11387 * If nLockTime is 0, it returns null,
11388 * if it is < 500000000, it returns a block height (number)
11389 * else it returns a Date object.
11390 */
11391Transaction.prototype.getLockTime = function() {
11392 if (!this.nLockTime) {
11393 return null;
11394 }
11395 if (this.nLockTime < Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) {
11396 return this.nLockTime;
11397 }
11398 return new Date(1000 * this.nLockTime);
11399};
11400
11401Transaction.prototype.fromString = function(string) {
11402 this.fromBuffer(buffer.Buffer.from(string, 'hex'));
11403};
11404
11405Transaction.prototype._newTransaction = function() {
11406 this.version = CURRENT_VERSION;
11407 this.nLockTime = DEFAULT_NLOCKTIME;
11408};
11409
11410/* Transaction creation interface */
11411
11412/**
11413 * @typedef {Object} Transaction~fromObject
11414 * @property {string} prevTxId
11415 * @property {number} outputIndex
11416 * @property {(Buffer|string|Script)} script
11417 * @property {number} satoshis
11418 */
11419
11420/**
11421 * Add an input to this transaction. This is a high level interface
11422 * to add an input, for more control, use @{link Transaction#addInput}.
11423 *
11424 * Can receive, as output information, the output of bitcoind's `listunspent` command,
11425 * and a slightly fancier format recognized by bitcore:
11426 *
11427 * ```
11428 * {
11429 * address: 'mszYqVnqKoQx4jcTdJXxwKAissE3Jbrrc1',
11430 * txId: 'a477af6b2667c29670467e4e0728b685ee07b240235771862318e29ddbe58458',
11431 * outputIndex: 0,
11432 * script: Script.empty(),
11433 * satoshis: 1020000
11434 * }
11435 * ```
11436 * Where `address` can be either a string or a bitcore Address object. The
11437 * same is true for `script`, which can be a string or a bitcore Script.
11438 *
11439 * Beware that this resets all the signatures for inputs (in further versions,
11440 * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
11441 *
11442 * @example
11443 * ```javascript
11444 * var transaction = new Transaction();
11445 *
11446 * // From a pay to public key hash output from bitcoind's listunspent
11447 * transaction.from({'txid': '0000...', vout: 0, amount: 0.1, scriptPubKey: 'OP_DUP ...'});
11448 *
11449 * // From a pay to public key hash output
11450 * transaction.from({'txId': '0000...', outputIndex: 0, satoshis: 1000, script: 'OP_DUP ...'});
11451 *
11452 * // From a multisig P2SH output
11453 * transaction.from({'txId': '0000...', inputIndex: 0, satoshis: 1000, script: '... OP_HASH'},
11454 * ['03000...', '02000...'], 2);
11455 * ```
11456 *
11457 * @param {(Array.<Transaction~fromObject>|Transaction~fromObject)} utxo
11458 * @param {Array=} pubkeys
11459 * @param {number=} threshold
11460 * @param {Object=} opts - Several options:
11461 * - noSorting: defaults to false, if true and is multisig, don't
11462 * sort the given public keys before creating the script
11463 */
11464Transaction.prototype.from = function(utxo, pubkeys, threshold, opts) {
11465 if (_.isArray(utxo)) {
11466 var self = this;
11467 _.each(utxo, function(utxo) {
11468 self.from(utxo, pubkeys, threshold, opts);
11469 });
11470 return this;
11471 }
11472 var exists = _.some(this.inputs, function(input) {
11473 // TODO: Maybe prevTxId should be a string? Or defined as read only property?
11474 return input.prevTxId.toString('hex') === utxo.txId && input.outputIndex === utxo.outputIndex;
11475 });
11476 if (exists) {
11477 return this;
11478 }
11479 if (pubkeys && threshold) {
11480 this._fromMultisigUtxo(utxo, pubkeys, threshold, opts);
11481 } else {
11482 this._fromNonP2SH(utxo);
11483 }
11484 return this;
11485};
11486
11487/**
11488 * associateInputs - Update inputs with utxos, allowing you to specify value, and pubkey.
11489 * Populating these inputs allows for them to be signed with .sign(privKeys)
11490 *
11491 * @param {Array<Object>} utxos
11492 * @param {Array<string | PublicKey>} pubkeys
11493 * @param {number} threshold
11494 * @param {Object} opts
11495 * @returns {Array<number>}
11496 */
11497Transaction.prototype.associateInputs = function(utxos, pubkeys, threshold, opts) {
11498 let indexes = [];
11499 for(let utxo of utxos) {
11500 const index = this.inputs.findIndex(i => i.prevTxId.toString('hex') === utxo.txId && i.outputIndex === utxo.outputIndex);
11501 indexes.push(index);
11502 if(index >= 0) {
11503 this.inputs[index] = this._getInputFrom(utxo, pubkeys, threshold, opts);
11504 }
11505 }
11506 return indexes;
11507}
11508
11509
11510Transaction.prototype._selectInputType = function(utxo, pubkeys, threshold) {
11511 var clazz;
11512 utxo = new UnspentOutput(utxo);
11513 if(pubkeys && threshold) {
11514 if (utxo.script.isMultisigOut()) {
11515 clazz = MultiSigInput;
11516 } else if (utxo.script.isScriptHashOut() || utxo.script.isWitnessScriptHashOut()) {
11517 clazz = MultiSigScriptHashInput;
11518 }
11519 } else if (utxo.script.isPublicKeyHashOut() || utxo.script.isWitnessPublicKeyHashOut() || utxo.script.isScriptHashOut()) {
11520 clazz = PublicKeyHashInput;
11521 } else if (utxo.script.isPublicKeyOut()) {
11522 clazz = PublicKeyInput;
11523 } else {
11524 clazz = Input;
11525 }
11526 return clazz;
11527}
11528
11529
11530Transaction.prototype._getInputFrom = function(utxo, pubkeys, threshold, opts) {
11531 utxo = new UnspentOutput(utxo);
11532 const InputClass = this._selectInputType(utxo, pubkeys, threshold);
11533 const input = {
11534 output: new Output({
11535 script: utxo.script,
11536 satoshis: utxo.satoshis
11537 }),
11538 prevTxId: utxo.txId,
11539 outputIndex: utxo.outputIndex,
11540 sequenceNumber: utxo.sequenceNumber,
11541 script: Script.empty()
11542 };
11543 let args = pubkeys && threshold ? [pubkeys, threshold, false, opts] : []
11544 return new InputClass(input, ...args);
11545}
11546
11547Transaction.prototype._fromNonP2SH = function(utxo) {
11548 const input = this._getInputFrom(utxo);
11549 this.addInput(input);
11550};
11551
11552Transaction.prototype._fromMultisigUtxo = function(utxo, pubkeys, threshold, opts) {
11553 $.checkArgument(threshold <= pubkeys.length,
11554 'Number of required signatures must be greater than the number of public keys');
11555 const input = this._getInputFrom(utxo, pubkeys, threshold, opts);
11556 this.addInput(input);
11557};
11558
11559/**
11560 * Add an input to this transaction. The input must be an instance of the `Input` class.
11561 * It should have information about the Output that it's spending, but if it's not already
11562 * set, two additional parameters, `outputScript` and `satoshis` can be provided.
11563 *
11564 * @param {Input} input
11565 * @param {String|Script} outputScript
11566 * @param {number} satoshis
11567 * @return Transaction this, for chaining
11568 */
11569Transaction.prototype.addInput = function(input, outputScript, satoshis) {
11570 $.checkArgumentType(input, Input, 'input');
11571 if (!input.output && (_.isUndefined(outputScript) || _.isUndefined(satoshis))) {
11572 throw new errors.Transaction.NeedMoreInfo('Need information about the UTXO script and satoshis');
11573 }
11574 if (!input.output && outputScript && !_.isUndefined(satoshis)) {
11575 outputScript = outputScript instanceof Script ? outputScript : new Script(outputScript);
11576 $.checkArgumentType(satoshis, 'number', 'satoshis');
11577 input.output = new Output({
11578 script: outputScript,
11579 satoshis: satoshis
11580 });
11581 }
11582 return this.uncheckedAddInput(input);
11583};
11584
11585/**
11586 * Add an input to this transaction, without checking that the input has information about
11587 * the output that it's spending.
11588 *
11589 * @param {Input} input
11590 * @return Transaction this, for chaining
11591 */
11592Transaction.prototype.uncheckedAddInput = function(input) {
11593 $.checkArgumentType(input, Input, 'input');
11594 this.inputs.push(input);
11595 this._inputAmount = undefined;
11596 this._updateChangeOutput();
11597 return this;
11598};
11599
11600/**
11601 * Returns true if the transaction has enough info on all inputs to be correctly validated
11602 *
11603 * @return {boolean}
11604 */
11605Transaction.prototype.hasAllUtxoInfo = function() {
11606 return _.every(this.inputs.map(function(input) {
11607 return !!input.output;
11608 }));
11609};
11610
11611/**
11612 * Manually set the fee for this transaction. Beware that this resets all the signatures
11613 * for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not
11614 * be reset).
11615 *
11616 * @param {number} amount satoshis to be sent
11617 * @return {Transaction} this, for chaining
11618 */
11619Transaction.prototype.fee = function(amount) {
11620 $.checkArgument(_.isNumber(amount), 'amount must be a number');
11621 this._fee = amount;
11622 this._updateChangeOutput();
11623 return this;
11624};
11625
11626/**
11627 * Manually set the fee per KB for this transaction. Beware that this resets all the signatures
11628 * for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not
11629 * be reset).
11630 *
11631 * @param {number} amount satoshis per KB to be sent
11632 * @return {Transaction} this, for chaining
11633 */
11634Transaction.prototype.feePerKb = function(amount) {
11635 $.checkArgument(_.isNumber(amount), 'amount must be a number');
11636 this._feePerKb = amount;
11637 this._updateChangeOutput();
11638 return this;
11639};
11640
11641/**
11642 * Manually set the fee per Byte for this transaction. Beware that this resets all the signatures
11643 * for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not
11644 * be reset).
11645 * fee per Byte will be ignored if fee per KB is set
11646 *
11647 * @param {number} amount satoshis per Byte to be sent
11648 * @return {Transaction} this, for chaining
11649 */
11650Transaction.prototype.feePerByte = function (amount) {
11651 $.checkArgument(_.isNumber(amount), 'amount must be a number');
11652 this._feePerByte = amount;
11653 this._updateChangeOutput();
11654 return this;
11655};
11656
11657/* Output management */
11658
11659/**
11660 * Set the change address for this transaction
11661 *
11662 * Beware that this resets all the signatures for inputs (in further versions,
11663 * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
11664 *
11665 * @param {Address} address An address for change to be sent to.
11666 * @return {Transaction} this, for chaining
11667 */
11668Transaction.prototype.change = function(address) {
11669 $.checkArgument(address, 'address is required');
11670 this._changeScript = Script.fromAddress(address);
11671 this._updateChangeOutput();
11672 return this;
11673};
11674
11675
11676/**
11677 * @return {Output} change output, if it exists
11678 */
11679Transaction.prototype.getChangeOutput = function() {
11680 if (!_.isUndefined(this._changeIndex)) {
11681 return this.outputs[this._changeIndex];
11682 }
11683 return null;
11684};
11685
11686/**
11687 * @typedef {Object} Transaction~toObject
11688 * @property {(string|Address)} address
11689 * @property {number} satoshis
11690 */
11691
11692/**
11693 * Add an output to the transaction.
11694 *
11695 * Beware that this resets all the signatures for inputs (in further versions,
11696 * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
11697 *
11698 * @param {(string|Address|Array.<Transaction~toObject>)} address
11699 * @param {number} amount in satoshis
11700 * @return {Transaction} this, for chaining
11701 */
11702Transaction.prototype.to = function(address, amount) {
11703 if (_.isArray(address)) {
11704 var self = this;
11705 _.each(address, function(to) {
11706 self.to(to.address, to.satoshis);
11707 });
11708 return this;
11709 }
11710
11711 $.checkArgument(
11712 JSUtil.isNaturalNumber(amount),
11713 'Amount is expected to be a positive integer'
11714 );
11715 this.addOutput(new Output({
11716 script: Script(new Address(address)),
11717 satoshis: amount
11718 }));
11719 return this;
11720};
11721
11722/**
11723 * Add an OP_RETURN output to the transaction.
11724 *
11725 * Beware that this resets all the signatures for inputs (in further versions,
11726 * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset).
11727 *
11728 * @param {Buffer|string} value the data to be stored in the OP_RETURN output.
11729 * In case of a string, the UTF-8 representation will be stored
11730 * @return {Transaction} this, for chaining
11731 */
11732Transaction.prototype.addData = function(value) {
11733 this.addOutput(new Output({
11734 script: Script.buildDataOut(value),
11735 satoshis: 0
11736 }));
11737 return this;
11738};
11739
11740
11741/**
11742 * Add an output to the transaction.
11743 *
11744 * @param {Output} output the output to add.
11745 * @return {Transaction} this, for chaining
11746 */
11747Transaction.prototype.addOutput = function(output) {
11748 $.checkArgumentType(output, Output, 'output');
11749 this._addOutput(output);
11750 this._updateChangeOutput();
11751 return this;
11752};
11753
11754
11755/**
11756 * Remove all outputs from the transaction.
11757 *
11758 * @return {Transaction} this, for chaining
11759 */
11760Transaction.prototype.clearOutputs = function() {
11761 this.outputs = [];
11762 this._clearSignatures();
11763 this._outputAmount = undefined;
11764 this._changeIndex = undefined;
11765 this._updateChangeOutput();
11766 return this;
11767};
11768
11769
11770Transaction.prototype._addOutput = function(output) {
11771 this.outputs.push(output);
11772 this._outputAmount = undefined;
11773};
11774
11775
11776/**
11777 * Calculates or gets the total output amount in satoshis
11778 *
11779 * @return {Number} the transaction total output amount
11780 */
11781Transaction.prototype._getOutputAmount = function() {
11782 if (_.isUndefined(this._outputAmount)) {
11783 var self = this;
11784 this._outputAmount = 0;
11785 _.each(this.outputs, function(output) {
11786 self._outputAmount += output.satoshis;
11787 });
11788 }
11789 return this._outputAmount;
11790};
11791
11792
11793/**
11794 * Calculates or gets the total input amount in satoshis
11795 *
11796 * @return {Number} the transaction total input amount
11797 */
11798Transaction.prototype._getInputAmount = function() {
11799 if (_.isUndefined(this._inputAmount)) {
11800 this._inputAmount = _.sumBy(this.inputs, function(input) {
11801 if (_.isUndefined(input.output)) {
11802 throw new errors.Transaction.Input.MissingPreviousOutput();
11803 }
11804 return input.output.satoshis;
11805 });
11806 }
11807 return this._inputAmount;
11808};
11809
11810Transaction.prototype._updateChangeOutput = function() {
11811 if (!this._changeScript) {
11812 return;
11813 }
11814 this._clearSignatures();
11815 if (!_.isUndefined(this._changeIndex)) {
11816 this._removeOutput(this._changeIndex);
11817 }
11818 var available = this._getUnspentValue();
11819 var fee = this.getFee();
11820 var changeAmount = available - fee;
11821 if (changeAmount > Transaction.DUST_AMOUNT) {
11822 this._changeIndex = this.outputs.length;
11823 this._addOutput(new Output({
11824 script: this._changeScript,
11825 satoshis: changeAmount
11826 }));
11827 } else {
11828 this._changeIndex = undefined;
11829 }
11830};
11831/**
11832 * Calculates the fee of the transaction.
11833 *
11834 * If there's a fixed fee set, return that.
11835 *
11836 * If there is no change output set, the fee is the
11837 * total value of the outputs minus inputs. Note that
11838 * a serialized transaction only specifies the value
11839 * of its outputs. (The value of inputs are recorded
11840 * in the previous transaction outputs being spent.)
11841 * This method therefore raises a "MissingPreviousOutput"
11842 * error when called on a serialized transaction.
11843 *
11844 * If there's no fee set and no change address,
11845 * estimate the fee based on size.
11846 *
11847 * @return {Number} fee of this transaction in satoshis
11848 */
11849Transaction.prototype.getFee = function() {
11850 if (this.isCoinbase()) {
11851 return 0;
11852 }
11853 if (!_.isUndefined(this._fee)) {
11854 return this._fee;
11855 }
11856 // if no change output is set, fees should equal all the unspent amount
11857 if (!this._changeScript) {
11858 return this._getUnspentValue();
11859 }
11860 return this._estimateFee();
11861};
11862
11863/**
11864 * Estimates fee from serialized transaction size in bytes.
11865 */
11866Transaction.prototype._estimateFee = function () {
11867 var estimatedSize = this._estimateSize();
11868 var available = this._getUnspentValue();
11869 var feeRate = this._feePerByte || (this._feePerKb || Transaction.FEE_PER_KB) / 1000;
11870 function getFee(size) {
11871 return size * feeRate;
11872 }
11873 var fee = Math.ceil(getFee(estimatedSize));
11874 var feeWithChange = Math.ceil(getFee(estimatedSize) + getFee(Transaction.CHANGE_OUTPUT_MAX_SIZE));
11875 if (!this._changeScript || available <= feeWithChange) {
11876 return fee;
11877 }
11878 return feeWithChange;
11879};
11880
11881Transaction.prototype._getUnspentValue = function() {
11882 return this._getInputAmount() - this._getOutputAmount();
11883};
11884
11885Transaction.prototype._clearSignatures = function() {
11886 _.each(this.inputs, function(input) {
11887 input.clearSignatures();
11888 });
11889};
11890
11891Transaction.prototype._estimateSize = function() {
11892 var result = Transaction.MAXIMUM_EXTRA_SIZE;
11893 _.each(this.inputs, function(input) {
11894 result += 32 + 4; // prevout size:w
11895 result += input._estimateSize();
11896 });
11897 _.each(this.outputs, function(output) {
11898 result += output.script.toBuffer().length + 9;
11899 });
11900 return Math.ceil(result);
11901};
11902
11903Transaction.prototype._removeOutput = function(index) {
11904 var output = this.outputs[index];
11905 this.outputs = _.without(this.outputs, output);
11906 this._outputAmount = undefined;
11907};
11908
11909Transaction.prototype.removeOutput = function(index) {
11910 this._removeOutput(index);
11911 this._updateChangeOutput();
11912};
11913
11914/**
11915 * Sort a transaction's inputs and outputs according to BIP69
11916 *
11917 * @see {https://github.com/bitcoin/bips/blob/master/bip-0069.mediawiki}
11918 * @return {Transaction} this
11919 */
11920Transaction.prototype.sort = function() {
11921 this.sortInputs(function(inputs) {
11922 var copy = Array.prototype.concat.apply([], inputs);
11923 let i = 0;
11924 copy.forEach((x) => { x.i = i++});
11925 copy.sort(function(first, second) {
11926 return compare(first.prevTxId, second.prevTxId)
11927 || first.outputIndex - second.outputIndex
11928 || first.i - second.i; // to ensure stable sort
11929 });
11930 return copy;
11931 });
11932 this.sortOutputs(function(outputs) {
11933 var copy = Array.prototype.concat.apply([], outputs);
11934 let i = 0;
11935 copy.forEach((x) => { x.i = i++});
11936 copy.sort(function(first, second) {
11937 return first.satoshis - second.satoshis
11938 || compare(first.script.toBuffer(), second.script.toBuffer())
11939 || first.i - second.i; // to ensure stable sort
11940 });
11941 return copy;
11942 });
11943 return this;
11944};
11945
11946/**
11947 * Randomize this transaction's outputs ordering. The shuffling algorithm is a
11948 * version of the Fisher-Yates shuffle, provided by lodash's _.shuffle().
11949 *
11950 * @return {Transaction} this
11951 */
11952Transaction.prototype.shuffleOutputs = function() {
11953 return this.sortOutputs(_.shuffle);
11954};
11955
11956/**
11957 * Sort this transaction's outputs, according to a given sorting function that
11958 * takes an array as argument and returns a new array, with the same elements
11959 * but with a different order. The argument function MUST NOT modify the order
11960 * of the original array
11961 *
11962 * @param {Function} sortingFunction
11963 * @return {Transaction} this
11964 */
11965Transaction.prototype.sortOutputs = function(sortingFunction) {
11966 var outs = sortingFunction(this.outputs);
11967 return this._newOutputOrder(outs);
11968};
11969
11970/**
11971 * Sort this transaction's inputs, according to a given sorting function that
11972 * takes an array as argument and returns a new array, with the same elements
11973 * but with a different order.
11974 *
11975 * @param {Function} sortingFunction
11976 * @return {Transaction} this
11977 */
11978Transaction.prototype.sortInputs = function(sortingFunction) {
11979 this.inputs = sortingFunction(this.inputs);
11980 this._clearSignatures();
11981 return this;
11982};
11983
11984Transaction.prototype._newOutputOrder = function(newOutputs) {
11985 var isInvalidSorting = (this.outputs.length !== newOutputs.length ||
11986 _.difference(this.outputs, newOutputs).length !== 0);
11987 if (isInvalidSorting) {
11988 throw new errors.Transaction.InvalidSorting();
11989 }
11990
11991 if (!_.isUndefined(this._changeIndex)) {
11992 var changeOutput = this.outputs[this._changeIndex];
11993 this._changeIndex = _.findIndex(newOutputs, changeOutput);
11994 }
11995
11996 this.outputs = newOutputs;
11997 return this;
11998};
11999
12000Transaction.prototype.removeInput = function(txId, outputIndex) {
12001 var index;
12002 if (!outputIndex && _.isNumber(txId)) {
12003 index = txId;
12004 } else {
12005 index = _.findIndex(this.inputs, function(input) {
12006 return input.prevTxId.toString('hex') === txId && input.outputIndex === outputIndex;
12007 });
12008 }
12009 if (index < 0 || index >= this.inputs.length) {
12010 throw new errors.Transaction.InvalidIndex(index, this.inputs.length);
12011 }
12012 var input = this.inputs[index];
12013 this.inputs = _.without(this.inputs, input);
12014 this._inputAmount = undefined;
12015 this._updateChangeOutput();
12016};
12017
12018/* Signature handling */
12019
12020/**
12021 * Sign the transaction using one or more private keys.
12022 *
12023 * It tries to sign each input, verifying that the signature will be valid
12024 * (matches a public key).
12025 *
12026 * @param {Array|String|PrivateKey} privateKey
12027 * @param {number} sigtype
12028 * @param {String} signingMethod - method used to sign - 'ecdsa' or 'schnorr'
12029 * @return {Transaction} this, for chaining
12030 */
12031Transaction.prototype.sign = function(privateKey, sigtype, signingMethod) {
12032 $.checkState(this.hasAllUtxoInfo(), 'Not all utxo information is available to sign the transaction.');
12033 var self = this;
12034 if (_.isArray(privateKey)) {
12035 _.each(privateKey, function(privateKey) {
12036 self.sign(privateKey, sigtype, signingMethod);
12037 });
12038 return this;
12039 }
12040 _.each(this.getSignatures(privateKey, sigtype, signingMethod), function(signature) {
12041 self.applySignature(signature, signingMethod);
12042 });
12043 return this;
12044};
12045
12046Transaction.prototype.getSignatures = function(privKey, sigtype, signingMethod) {
12047 privKey = new PrivateKey(privKey);
12048 sigtype = sigtype || Signature.SIGHASH_ALL;
12049 var transaction = this;
12050 var results = [];
12051 var hashData = Hash.sha256ripemd160(privKey.publicKey.toBuffer());
12052 _.each(this.inputs, function forEachInput(input, index) {
12053 _.each(input.getSignatures(transaction, privKey, index, sigtype, hashData, signingMethod), function(signature) {
12054 results.push(signature);
12055 });
12056 });
12057 return results;
12058};
12059
12060/**
12061 * Add a signature to the transaction
12062 *
12063 * @param {Object} signature
12064 * @param {number} signature.inputIndex
12065 * @param {number} signature.sigtype
12066 * @param {PublicKey} signature.publicKey
12067 * @param {Signature} signature.signature
12068 * @param {String} signingMethod - 'ecdsa' to sign transaction
12069 * @return {Transaction} this, for chaining
12070 */
12071Transaction.prototype.applySignature = function(signature, signingMethod) {
12072 this.inputs[signature.inputIndex].addSignature(this, signature, signingMethod);
12073 return this;
12074};
12075
12076Transaction.prototype.isFullySigned = function() {
12077 _.each(this.inputs, function(input) {
12078 if (input.isFullySigned === Input.prototype.isFullySigned) {
12079 throw new errors.Transaction.UnableToVerifySignature(
12080 'Unrecognized script kind, or not enough information to execute script.' +
12081 'This usually happens when creating a transaction from a serialized transaction'
12082 );
12083 }
12084 });
12085 return _.every(_.map(this.inputs, function(input) {
12086 return input.isFullySigned();
12087 }));
12088};
12089
12090Transaction.prototype.isValidSignature = function(signature, signingMethod) {
12091 var self = this;
12092 if (this.inputs[signature.inputIndex].isValidSignature === Input.prototype.isValidSignature) {
12093 throw new errors.Transaction.UnableToVerifySignature(
12094 'Unrecognized script kind, or not enough information to execute script.' +
12095 'This usually happens when creating a transaction from a serialized transaction'
12096 );
12097 }
12098 return this.inputs[signature.inputIndex].isValidSignature(self, signature, signingMethod);
12099};
12100
12101/**
12102 * @param {String} signingMethod method used to sign - 'ecdsa' or 'schnorr' (future signing method)
12103 * @returns {bool} whether the signature is valid for this transaction input
12104 */
12105Transaction.prototype.verifySignature = function(sig, pubkey, nin, subscript, sigversion, satoshis, signingMethod) {
12106
12107 if (_.isUndefined(sigversion)) {
12108 sigversion = 0;
12109 }
12110
12111 if (sigversion === 1) {
12112 var subscriptBuffer = subscript.toBuffer();
12113 var scriptCodeWriter = new BufferWriter();
12114 scriptCodeWriter.writeVarintNum(subscriptBuffer.length);
12115 scriptCodeWriter.write(subscriptBuffer);
12116
12117 var satoshisBuffer;
12118 if (satoshis) {
12119 $.checkState(JSUtil.isNaturalNumber(satoshis));
12120 satoshisBuffer = new BufferWriter().writeUInt64LEBN(new BN(satoshis)).toBuffer();
12121 } else {
12122 satoshisBuffer = this.inputs[nin].getSatoshisBuffer();
12123 }
12124 var verified = SighashWitness.verify(
12125 this,
12126 sig,
12127 pubkey,
12128 nin,
12129 scriptCodeWriter.toBuffer(),
12130 satoshisBuffer,
12131 signingMethod
12132 );
12133 return verified;
12134 }
12135
12136 return Sighash.verify(this, sig, pubkey, nin, subscript, signingMethod);
12137};
12138
12139/**
12140 * Check that a transaction passes basic sanity tests. If not, return a string
12141 * describing the error. This function contains the same logic as
12142 * CheckTransaction in bitcoin core.
12143 */
12144Transaction.prototype.verify = function() {
12145 // Basic checks that don't depend on any context
12146 if (this.inputs.length === 0) {
12147 return 'transaction txins empty';
12148 }
12149
12150 if (this.outputs.length === 0) {
12151 return 'transaction txouts empty';
12152 }
12153
12154 // Check for negative or overflow output values
12155 var valueoutbn = new BN(0);
12156 for (var i = 0; i < this.outputs.length; i++) {
12157 var txout = this.outputs[i];
12158
12159 if (txout.invalidSatoshis()) {
12160 return 'transaction txout ' + i + ' satoshis is invalid';
12161 }
12162 if (txout._satoshisBN.gt(new BN(Transaction.MAX_MONEY, 10))) {
12163 return 'transaction txout ' + i + ' greater than MAX_MONEY';
12164 }
12165 valueoutbn = valueoutbn.add(txout._satoshisBN);
12166 if (valueoutbn.gt(new BN(Transaction.MAX_MONEY))) {
12167 return 'transaction txout ' + i + ' total output greater than MAX_MONEY';
12168 }
12169 }
12170
12171 // Size limits
12172 if (this.toBuffer().length > MAX_BLOCK_SIZE) {
12173 return 'transaction over the maximum block size';
12174 }
12175
12176 // Check for duplicate inputs
12177 var txinmap = {};
12178 for (i = 0; i < this.inputs.length; i++) {
12179 var txin = this.inputs[i];
12180
12181 var inputid = txin.prevTxId + ':' + txin.outputIndex;
12182 if (!_.isUndefined(txinmap[inputid])) {
12183 return 'transaction input ' + i + ' duplicate input';
12184 }
12185 txinmap[inputid] = true;
12186 }
12187
12188 var isCoinbase = this.isCoinbase();
12189 if (isCoinbase) {
12190 var buf = this.inputs[0]._scriptBuffer;
12191 if (buf.length < 2 || buf.length > 100) {
12192 return 'coinbase transaction script size invalid';
12193 }
12194 } else {
12195 for (i = 0; i < this.inputs.length; i++) {
12196 if (this.inputs[i].isNull()) {
12197 return 'transaction input ' + i + ' has null input';
12198 }
12199 }
12200 }
12201 return true;
12202};
12203
12204/**
12205 * Analogous to bitcoind's IsCoinBase function in transaction.h
12206 */
12207Transaction.prototype.isCoinbase = function() {
12208 return (this.inputs.length === 1 && this.inputs[0].isNull());
12209};
12210
12211/**
12212 * Determines if this transaction can be replaced in the mempool with another
12213 * transaction that provides a sufficiently higher fee (RBF).
12214 */
12215Transaction.prototype.isRBF = function() {
12216 for (var i = 0; i < this.inputs.length; i++) {
12217 var input = this.inputs[i];
12218 if (input.sequenceNumber < Input.MAXINT - 1) {
12219 return true;
12220 }
12221 }
12222 return false;
12223};
12224
12225/**
12226 * Enable this transaction to be replaced in the mempool (RBF) if a transaction
12227 * includes a sufficiently higher fee. It will set the sequenceNumber to
12228 * DEFAULT_RBF_SEQNUMBER for all inputs if the sequence number does not
12229 * already enable RBF.
12230 */
12231Transaction.prototype.enableRBF = function() {
12232 for (var i = 0; i < this.inputs.length; i++) {
12233 var input = this.inputs[i];
12234 if (input.sequenceNumber >= Input.MAXINT - 1) {
12235 input.sequenceNumber = Input.DEFAULT_RBF_SEQNUMBER;
12236 }
12237 }
12238 return this;
12239};
12240
12241Transaction.prototype.setVersion = function(version) {
12242 $.checkArgument(
12243 JSUtil.isNaturalNumber(version) && version <= CURRENT_VERSION,
12244 'Wrong version number');
12245 this.version = version;
12246 return this;
12247};
12248
12249
12250
12251module.exports = Transaction;
12252
12253}).call(this)}).call(this,require("buffer").Buffer)
12254},{"../address":1,"../crypto/bn":6,"../crypto/hash":8,"../crypto/signature":11,"../encoding/bufferreader":15,"../encoding/bufferwriter":16,"../errors":18,"../privatekey":25,"../script":27,"../util/buffer":45,"../util/js":46,"../util/preconditions":47,"./input":31,"./output":37,"./sighash":38,"./sighashwitness":39,"./unspentoutput":42,"buffer":132,"buffer-compare":130,"lodash":210}],42:[function(require,module,exports){
12255'use strict';
12256
12257var _ = require('lodash');
12258var $ = require('../util/preconditions');
12259var JSUtil = require('../util/js');
12260
12261var Script = require('../script');
12262var Address = require('../address');
12263var Unit = require('../unit');
12264
12265/**
12266 * Represents an unspent output information: its script, associated amount and address,
12267 * transaction id and output index.
12268 *
12269 * @constructor
12270 * @param {object} data
12271 * @param {string} data.txid the previous transaction id
12272 * @param {string=} data.txId alias for `txid`
12273 * @param {number} data.vout the index in the transaction
12274 * @param {number=} data.outputIndex alias for `vout`
12275 * @param {string|Script} data.scriptPubKey the script that must be resolved to release the funds
12276 * @param {string|Script=} data.script alias for `scriptPubKey`
12277 * @param {number} data.amount amount of bitcoins associated
12278 * @param {number=} data.satoshis alias for `amount`, but expressed in satoshis (1 BTC = 1e8 satoshis)
12279 * @param {string|Address=} data.address the associated address to the script, if provided
12280 */
12281function UnspentOutput(data) {
12282 /* jshint maxcomplexity: 20 */
12283 /* jshint maxstatements: 20 */
12284 if (!(this instanceof UnspentOutput)) {
12285 return new UnspentOutput(data);
12286 }
12287 $.checkArgument(_.isObject(data), 'Must provide an object from where to extract data');
12288 var address = data.address ? new Address(data.address) : undefined;
12289 var txId = data.txid ? data.txid : data.txId;
12290 if (!txId || !JSUtil.isHexaString(txId) || txId.length > 64) {
12291 // TODO: Use the errors library
12292 throw new Error('Invalid TXID in object', data);
12293 }
12294 var outputIndex = _.isUndefined(data.vout) ? data.outputIndex : data.vout;
12295 if (!_.isNumber(outputIndex)) {
12296 throw new Error('Invalid outputIndex, received ' + outputIndex);
12297 }
12298 $.checkArgument(!_.isUndefined(data.scriptPubKey) || !_.isUndefined(data.script),
12299 'Must provide the scriptPubKey for that output!');
12300 var script = new Script(data.scriptPubKey || data.script);
12301 $.checkArgument(!_.isUndefined(data.amount) || !_.isUndefined(data.satoshis),
12302 'Must provide an amount for the output');
12303 var amount = !_.isUndefined(data.amount) ? new Unit.fromBTC(data.amount).toSatoshis() : data.satoshis;
12304 $.checkArgument(_.isNumber(amount), 'Amount must be a number');
12305 JSUtil.defineImmutable(this, {
12306 address: address,
12307 txId: txId,
12308 outputIndex: outputIndex,
12309 script: script,
12310 satoshis: amount
12311 });
12312}
12313
12314/**
12315 * Provide an informative output when displaying this object in the console
12316 * @returns string
12317 */
12318UnspentOutput.prototype.inspect = function() {
12319 return '<UnspentOutput: ' + this.txId + ':' + this.outputIndex +
12320 ', satoshis: ' + this.satoshis + ', address: ' + this.address + '>';
12321};
12322
12323/**
12324 * String representation: just "txid:index"
12325 * @returns string
12326 */
12327UnspentOutput.prototype.toString = function() {
12328 return this.txId + ':' + this.outputIndex;
12329};
12330
12331/**
12332 * Deserialize an UnspentOutput from an object
12333 * @param {object|string} data
12334 * @return UnspentOutput
12335 */
12336UnspentOutput.fromObject = function(data) {
12337 return new UnspentOutput(data);
12338};
12339
12340/**
12341 * Returns a plain object (no prototype or methods) with the associated info for this output
12342 * @return {object}
12343 */
12344UnspentOutput.prototype.toObject = UnspentOutput.prototype.toJSON = function toObject() {
12345 return {
12346 address: this.address ? this.address.toString() : undefined,
12347 txid: this.txId,
12348 vout: this.outputIndex,
12349 scriptPubKey: this.script.toBuffer().toString('hex'),
12350 amount: Unit.fromSatoshis(this.satoshis).toBTC()
12351 };
12352};
12353
12354module.exports = UnspentOutput;
12355
12356},{"../address":1,"../script":27,"../unit":43,"../util/js":46,"../util/preconditions":47,"lodash":210}],43:[function(require,module,exports){
12357'use strict';
12358
12359var _ = require('lodash');
12360
12361var errors = require('./errors');
12362var $ = require('./util/preconditions');
12363
12364var UNITS = {
12365 'BTC' : [1e8, 8],
12366 'mBTC' : [1e5, 5],
12367 'uBTC' : [1e2, 2],
12368 'bits' : [1e2, 2],
12369 'satoshis' : [1, 0]
12370};
12371
12372/**
12373 * Utility for handling and converting bitcoins units. The supported units are
12374 * BTC, mBTC, bits (also named uBTC) and satoshis. A unit instance can be created with an
12375 * amount and a unit code, or alternatively using static methods like {fromBTC}.
12376 * It also allows to be created from a fiat amount and the exchange rate, or
12377 * alternatively using the {fromFiat} static method.
12378 * You can consult for different representation of a unit instance using it's
12379 * {to} method, the fixed unit methods like {toSatoshis} or alternatively using
12380 * the unit accessors. It also can be converted to a fiat amount by providing the
12381 * corresponding BTC/fiat exchange rate.
12382 *
12383 * @example
12384 * ```javascript
12385 * var sats = Unit.fromBTC(1.3).toSatoshis();
12386 * var mili = Unit.fromBits(1.3).to(Unit.mBTC);
12387 * var bits = Unit.fromFiat(1.3, 350).bits;
12388 * var btc = new Unit(1.3, Unit.bits).BTC;
12389 * ```
12390 *
12391 * @param {Number} amount - The amount to be represented
12392 * @param {String|Number} code - The unit of the amount or the exchange rate
12393 * @returns {Unit} A new instance of an Unit
12394 * @constructor
12395 */
12396function Unit(amount, code) {
12397 if (!(this instanceof Unit)) {
12398 return new Unit(amount, code);
12399 }
12400
12401 // convert fiat to BTC
12402 if (_.isNumber(code)) {
12403 if (code <= 0) {
12404 throw new errors.Unit.InvalidRate(code);
12405 }
12406 amount = amount / code;
12407 code = Unit.BTC;
12408 }
12409
12410 this._value = this._from(amount, code);
12411
12412 var self = this;
12413 var defineAccesor = function(key) {
12414 Object.defineProperty(self, key, {
12415 get: function() { return self.to(key); },
12416 enumerable: true,
12417 });
12418 };
12419
12420 Object.keys(UNITS).forEach(defineAccesor);
12421}
12422
12423Object.keys(UNITS).forEach(function(key) {
12424 Unit[key] = key;
12425});
12426
12427/**
12428 * Returns a Unit instance created from JSON string or object
12429 *
12430 * @param {String|Object} json - JSON with keys: amount and code
12431 * @returns {Unit} A Unit instance
12432 */
12433Unit.fromObject = function fromObject(data){
12434 $.checkArgument(_.isObject(data), 'Argument is expected to be an object');
12435 return new Unit(data.amount, data.code);
12436};
12437
12438/**
12439 * Returns a Unit instance created from an amount in BTC
12440 *
12441 * @param {Number} amount - The amount in BTC
12442 * @returns {Unit} A Unit instance
12443 */
12444Unit.fromBTC = function(amount) {
12445 return new Unit(amount, Unit.BTC);
12446};
12447
12448/**
12449 * Returns a Unit instance created from an amount in mBTC
12450 *
12451 * @param {Number} amount - The amount in mBTC
12452 * @returns {Unit} A Unit instance
12453 */
12454Unit.fromMillis = Unit.fromMilis = function(amount) {
12455 return new Unit(amount, Unit.mBTC);
12456};
12457
12458/**
12459 * Returns a Unit instance created from an amount in bits
12460 *
12461 * @param {Number} amount - The amount in bits
12462 * @returns {Unit} A Unit instance
12463 */
12464Unit.fromMicros = Unit.fromBits = function(amount) {
12465 return new Unit(amount, Unit.bits);
12466};
12467
12468/**
12469 * Returns a Unit instance created from an amount in satoshis
12470 *
12471 * @param {Number} amount - The amount in satoshis
12472 * @returns {Unit} A Unit instance
12473 */
12474Unit.fromSatoshis = function(amount) {
12475 return new Unit(amount, Unit.satoshis);
12476};
12477
12478/**
12479 * Returns a Unit instance created from a fiat amount and exchange rate.
12480 *
12481 * @param {Number} amount - The amount in fiat
12482 * @param {Number} rate - The exchange rate BTC/fiat
12483 * @returns {Unit} A Unit instance
12484 */
12485Unit.fromFiat = function(amount, rate) {
12486 return new Unit(amount, rate);
12487};
12488
12489Unit.prototype._from = function(amount, code) {
12490 if (!UNITS[code]) {
12491 throw new errors.Unit.UnknownCode(code);
12492 }
12493 return parseInt((amount * UNITS[code][0]).toFixed());
12494};
12495
12496/**
12497 * Returns the value represented in the specified unit
12498 *
12499 * @param {String|Number} code - The unit code or exchange rate
12500 * @returns {Number} The converted value
12501 */
12502Unit.prototype.to = function(code) {
12503 if (_.isNumber(code)) {
12504 if (code <= 0) {
12505 throw new errors.Unit.InvalidRate(code);
12506 }
12507 return parseFloat((this.BTC * code).toFixed(2));
12508 }
12509
12510 if (!UNITS[code]) {
12511 throw new errors.Unit.UnknownCode(code);
12512 }
12513
12514 var value = this._value / UNITS[code][0];
12515 return parseFloat(value.toFixed(UNITS[code][1]));
12516};
12517
12518/**
12519 * Returns the value represented in BTC
12520 *
12521 * @returns {Number} The value converted to BTC
12522 */
12523Unit.prototype.toBTC = function() {
12524 return this.to(Unit.BTC);
12525};
12526
12527/**
12528 * Returns the value represented in mBTC
12529 *
12530 * @returns {Number} The value converted to mBTC
12531 */
12532Unit.prototype.toMillis = Unit.prototype.toMilis = function() {
12533 return this.to(Unit.mBTC);
12534};
12535
12536/**
12537 * Returns the value represented in bits
12538 *
12539 * @returns {Number} The value converted to bits
12540 */
12541Unit.prototype.toMicros = Unit.prototype.toBits = function() {
12542 return this.to(Unit.bits);
12543};
12544
12545/**
12546 * Returns the value represented in satoshis
12547 *
12548 * @returns {Number} The value converted to satoshis
12549 */
12550Unit.prototype.toSatoshis = function() {
12551 return this.to(Unit.satoshis);
12552};
12553
12554/**
12555 * Returns the value represented in fiat
12556 *
12557 * @param {string} rate - The exchange rate between BTC/currency
12558 * @returns {Number} The value converted to satoshis
12559 */
12560Unit.prototype.atRate = function(rate) {
12561 return this.to(rate);
12562};
12563
12564/**
12565 * Returns a the string representation of the value in satoshis
12566 *
12567 * @returns {string} the value in satoshis
12568 */
12569Unit.prototype.toString = function() {
12570 return this.satoshis + ' satoshis';
12571};
12572
12573/**
12574 * Returns a plain object representation of the Unit
12575 *
12576 * @returns {Object} An object with the keys: amount and code
12577 */
12578Unit.prototype.toObject = Unit.prototype.toJSON = function toObject() {
12579 return {
12580 amount: this.BTC,
12581 code: Unit.BTC
12582 };
12583};
12584
12585/**
12586 * Returns a string formatted for the console
12587 *
12588 * @returns {string} the value in satoshis
12589 */
12590Unit.prototype.inspect = function() {
12591 return '<Unit: ' + this.toString() + '>';
12592};
12593
12594module.exports = Unit;
12595
12596},{"./errors":18,"./util/preconditions":47,"lodash":210}],44:[function(require,module,exports){
12597'use strict';
12598
12599var _ = require('lodash');
12600var URL = require('url');
12601
12602var Address = require('./address');
12603var Unit = require('./unit');
12604
12605/**
12606 * Bitcore URI
12607 *
12608 * Instantiate an URI from a bitcoin URI String or an Object. An URI instance
12609 * can be created with a bitcoin uri string or an object. All instances of
12610 * URI are valid, the static method isValid allows checking before instantiation.
12611 *
12612 * All standard parameters can be found as members of the class, the address
12613 * is represented using an {Address} instance and the amount is represented in
12614 * satoshis. Any other non-standard parameters can be found under the extra member.
12615 *
12616 * @example
12617 * ```javascript
12618 *
12619 * var uri = new URI('bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2');
12620 * console.log(uri.address, uri.amount);
12621 * ```
12622 *
12623 * @param {string|Object} data - A bitcoin URI string or an Object
12624 * @param {Array.<string>=} knownParams - Required non-standard params
12625 * @throws {TypeError} Invalid bitcoin address
12626 * @throws {TypeError} Invalid amount
12627 * @throws {Error} Unknown required argument
12628 * @returns {URI} A new valid and frozen instance of URI
12629 * @constructor
12630 */
12631var URI = function(data, knownParams) {
12632 if (!(this instanceof URI)) {
12633 return new URI(data, knownParams);
12634 }
12635
12636 this.extras = {};
12637 this.knownParams = knownParams || [];
12638 this.address = this.network = this.amount = this.message = null;
12639
12640 if (typeof(data) === 'string') {
12641 var params = URI.parse(data);
12642 if (params.amount) {
12643 params.amount = this._parseAmount(params.amount);
12644 }
12645 this._fromObject(params);
12646 } else if (typeof(data) === 'object') {
12647 this._fromObject(data);
12648 } else {
12649 throw new TypeError('Unrecognized data format.');
12650 }
12651};
12652
12653/**
12654 * Instantiate a URI from a String
12655 *
12656 * @param {string} str - JSON string or object of the URI
12657 * @returns {URI} A new instance of a URI
12658 */
12659URI.fromString = function fromString(str) {
12660 if (typeof(str) !== 'string') {
12661 throw new TypeError('Expected a string');
12662 }
12663 return new URI(str);
12664};
12665
12666/**
12667 * Instantiate a URI from an Object
12668 *
12669 * @param {Object} data - object of the URI
12670 * @returns {URI} A new instance of a URI
12671 */
12672URI.fromObject = function fromObject(json) {
12673 return new URI(json);
12674};
12675
12676/**
12677 * Check if an bitcoin URI string is valid
12678 *
12679 * @example
12680 * ```javascript
12681 *
12682 * var valid = URI.isValid('bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu');
12683 * // true
12684 * ```
12685 *
12686 * @param {string|Object} data - A bitcoin URI string or an Object
12687 * @param {Array.<string>=} knownParams - Required non-standard params
12688 * @returns {boolean} Result of uri validation
12689 */
12690URI.isValid = function(arg, knownParams) {
12691 try {
12692 new URI(arg, knownParams);
12693 } catch (err) {
12694 return false;
12695 }
12696 return true;
12697};
12698
12699/**
12700 * Convert a bitcoin URI string into a simple object.
12701 *
12702 * @param {string} uri - A bitcoin URI string
12703 * @throws {TypeError} Invalid bitcoin URI
12704 * @returns {Object} An object with the parsed params
12705 */
12706URI.parse = function(uri) {
12707 var info = URL.parse(uri, true);
12708
12709 if (info.protocol !== 'bitcoin:') {
12710 throw new TypeError('Invalid bitcoin URI');
12711 }
12712
12713 // workaround to host insensitiveness
12714 var group = /[^:]*:\/?\/?([^?]*)/.exec(uri);
12715 info.query.address = group && group[1] || undefined;
12716
12717 return info.query;
12718};
12719
12720URI.Members = ['address', 'amount', 'message', 'label', 'r'];
12721
12722/**
12723 * Internal function to load the URI instance with an object.
12724 *
12725 * @param {Object} obj - Object with the information
12726 * @throws {TypeError} Invalid bitcoin address
12727 * @throws {TypeError} Invalid amount
12728 * @throws {Error} Unknown required argument
12729 */
12730URI.prototype._fromObject = function(obj) {
12731 /* jshint maxcomplexity: 10 */
12732
12733 if (!Address.isValid(obj.address)) {
12734 throw new TypeError('Invalid bitcoin address');
12735 }
12736
12737 this.address = new Address(obj.address);
12738 this.network = this.address.network;
12739 this.amount = obj.amount;
12740
12741 for (var key in obj) {
12742 if (key === 'address' || key === 'amount') {
12743 continue;
12744 }
12745
12746 if (/^req-/.exec(key) && this.knownParams.indexOf(key) === -1) {
12747 throw Error('Unknown required argument ' + key);
12748 }
12749
12750 var destination = URI.Members.indexOf(key) > -1 ? this : this.extras;
12751 destination[key] = obj[key];
12752 }
12753};
12754
12755/**
12756 * Internal function to transform a BTC string amount into satoshis
12757 *
12758 * @param {string} amount - Amount BTC string
12759 * @throws {TypeError} Invalid amount
12760 * @returns {Object} Amount represented in satoshis
12761 */
12762URI.prototype._parseAmount = function(amount) {
12763 amount = Number(amount);
12764 if (isNaN(amount)) {
12765 throw new TypeError('Invalid amount');
12766 }
12767 return Unit.fromBTC(amount).toSatoshis();
12768};
12769
12770URI.prototype.toObject = URI.prototype.toJSON = function toObject() {
12771 var json = {};
12772 for (var i = 0; i < URI.Members.length; i++) {
12773 var m = URI.Members[i];
12774 if (this.hasOwnProperty(m) && typeof(this[m]) !== 'undefined') {
12775 json[m] = this[m].toString();
12776 }
12777 }
12778 _.extend(json, this.extras);
12779 return json;
12780};
12781
12782/**
12783 * Will return a the string representation of the URI
12784 *
12785 * @returns {string} Bitcoin URI string
12786 */
12787URI.prototype.toString = function() {
12788 var query = {};
12789 if (this.amount) {
12790 query.amount = Unit.fromSatoshis(this.amount).toBTC();
12791 }
12792 if (this.message) {
12793 query.message = this.message;
12794 }
12795 if (this.label) {
12796 query.label = this.label;
12797 }
12798 if (this.r) {
12799 query.r = this.r;
12800 }
12801 _.extend(query, this.extras);
12802
12803 return URL.format({
12804 protocol: 'bitcoin:',
12805 host: this.address,
12806 query: query
12807 });
12808};
12809
12810/**
12811 * Will return a string formatted for the console
12812 *
12813 * @returns {string} Bitcoin URI
12814 */
12815URI.prototype.inspect = function() {
12816 return '<URI: ' + this.toString() + '>';
12817};
12818
12819module.exports = URI;
12820
12821},{"./address":1,"./unit":43,"lodash":210,"url":270}],45:[function(require,module,exports){
12822(function (Buffer){(function (){
12823'use strict';
12824
12825var buffer = require('buffer');
12826var assert = require('assert');
12827
12828var js = require('./js');
12829var $ = require('./preconditions');
12830
12831function equals(a, b) {
12832 if (a.length !== b.length) {
12833 return false;
12834 }
12835 var length = a.length;
12836 for (var i = 0; i < length; i++) {
12837 if (a[i] !== b[i]) {
12838 return false;
12839 }
12840 }
12841 return true;
12842}
12843
12844module.exports = {
12845 /**
12846 * Fill a buffer with a value.
12847 *
12848 * @param {Buffer} buffer
12849 * @param {number} value
12850 * @return {Buffer}
12851 */
12852 fill: function fill(buffer, value) {
12853 $.checkArgumentType(buffer, 'Buffer', 'buffer');
12854 $.checkArgumentType(value, 'number', 'value');
12855 var length = buffer.length;
12856 for (var i = 0; i < length; i++) {
12857 buffer[i] = value;
12858 }
12859 return buffer;
12860 },
12861
12862 /**
12863 * Return a copy of a buffer
12864 *
12865 * @param {Buffer} original
12866 * @return {Buffer}
12867 */
12868 copy: function(original) {
12869 var buffer = Buffer.alloc(original.length);
12870 original.copy(buffer);
12871 return buffer;
12872 },
12873
12874 /**
12875 * Returns true if the given argument is an instance of a buffer. Tests for
12876 * both node's Buffer and Uint8Array
12877 *
12878 * @param {*} arg
12879 * @return {boolean}
12880 */
12881 isBuffer: function isBuffer(arg) {
12882 return buffer.Buffer.isBuffer(arg) || arg instanceof Uint8Array;
12883 },
12884
12885 /**
12886 * Returns a zero-filled byte array
12887 *
12888 * @param {number} bytes
12889 * @return {Buffer}
12890 */
12891 emptyBuffer: function emptyBuffer(bytes) {
12892 $.checkArgumentType(bytes, 'number', 'bytes');
12893 var result = Buffer.alloc(bytes);
12894 for (var i = 0; i < bytes; i++) {
12895 result.write('\0', i);
12896 }
12897 return result;
12898 },
12899
12900 /**
12901 * Concatenates a buffer
12902 *
12903 * Shortcut for <tt>buffer.Buffer.concat</tt>
12904 */
12905 concat: buffer.Buffer.concat,
12906
12907 equals: equals,
12908 equal: equals,
12909
12910 /**
12911 * Transforms a number from 0 to 255 into a Buffer of size 1 with that value
12912 *
12913 * @param {number} integer
12914 * @return {Buffer}
12915 */
12916 integerAsSingleByteBuffer: function integerAsSingleByteBuffer(integer) {
12917 $.checkArgumentType(integer, 'number', 'integer');
12918 return Buffer.from([integer & 0xff]);
12919 },
12920
12921 /**
12922 * Transform a 4-byte integer into a Buffer of length 4.
12923 *
12924 * @param {number} integer
12925 * @return {Buffer}
12926 */
12927 integerAsBuffer: function integerAsBuffer(integer) {
12928 $.checkArgumentType(integer, 'number', 'integer');
12929 var bytes = [];
12930 bytes.push((integer >> 24) & 0xff);
12931 bytes.push((integer >> 16) & 0xff);
12932 bytes.push((integer >> 8) & 0xff);
12933 bytes.push(integer & 0xff);
12934 return Buffer.from(bytes);
12935 },
12936
12937 /**
12938 * Transform the first 4 values of a Buffer into a number, in little endian encoding
12939 *
12940 * @param {Buffer} buffer
12941 * @return {number}
12942 */
12943 integerFromBuffer: function integerFromBuffer(buffer) {
12944 $.checkArgumentType(buffer, 'Buffer', 'buffer');
12945 return buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3];
12946 },
12947
12948 /**
12949 * Transforms the first byte of an array into a number ranging from -128 to 127
12950 * @param {Buffer} buffer
12951 * @return {number}
12952 */
12953 integerFromSingleByteBuffer: function integerFromBuffer(buffer) {
12954 $.checkArgumentType(buffer, 'Buffer', 'buffer');
12955 return buffer[0];
12956 },
12957
12958 /**
12959 * Transforms a buffer into a string with a number in hexa representation
12960 *
12961 * Shorthand for <tt>buffer.toString('hex')</tt>
12962 *
12963 * @param {Buffer} buffer
12964 * @return {string}
12965 */
12966 bufferToHex: function bufferToHex(buffer) {
12967 $.checkArgumentType(buffer, 'Buffer', 'buffer');
12968 return buffer.toString('hex');
12969 },
12970
12971 /**
12972 * Reverse a buffer
12973 * @param {Buffer} param
12974 * @return {Buffer}
12975 */
12976 reverse: function reverse(param) {
12977 return (Buffer.from(param)).reverse();
12978 },
12979};
12980
12981module.exports.NULL_HASH = module.exports.fill(Buffer.alloc(32), 0);
12982module.exports.EMPTY_BUFFER = Buffer.alloc(0);
12983
12984}).call(this)}).call(this,require("buffer").Buffer)
12985},{"./js":46,"./preconditions":47,"assert":62,"buffer":132}],46:[function(require,module,exports){
12986'use strict';
12987
12988var _ = require('lodash');
12989
12990/**
12991 * Determines whether a string contains only hexadecimal values
12992 *
12993 * @name JSUtil.isHexa
12994 * @param {string} value
12995 * @return {boolean} true if the string is the hexa representation of a number
12996 */
12997var isHexa = function isHexa(value) {
12998 if (!_.isString(value)) {
12999 return false;
13000 }
13001 return /^[0-9a-fA-F]+$/.test(value);
13002};
13003
13004/**
13005 * @namespace JSUtil
13006 */
13007module.exports = {
13008 /**
13009 * Test if an argument is a valid JSON object. If it is, returns a truthy
13010 * value (the json object decoded), so no double JSON.parse call is necessary
13011 *
13012 * @param {string} arg
13013 * @return {Object|boolean} false if the argument is not a JSON string.
13014 */
13015 isValidJSON: function isValidJSON(arg) {
13016 var parsed;
13017 if (!_.isString(arg)) {
13018 return false;
13019 }
13020 try {
13021 parsed = JSON.parse(arg);
13022 } catch (e) {
13023 return false;
13024 }
13025 if (typeof(parsed) === 'object') {
13026 return true;
13027 }
13028 return false;
13029 },
13030 isHexa: isHexa,
13031 isHexaString: isHexa,
13032
13033 /**
13034 * Clone an array
13035 */
13036 cloneArray: function(array) {
13037 return [].concat(array);
13038 },
13039
13040 /**
13041 * Define immutable properties on a target object
13042 *
13043 * @param {Object} target - An object to be extended
13044 * @param {Object} values - An object of properties
13045 * @return {Object} The target object
13046 */
13047 defineImmutable: function defineImmutable(target, values) {
13048 Object.keys(values).forEach(function(key){
13049 Object.defineProperty(target, key, {
13050 configurable: false,
13051 enumerable: true,
13052 value: values[key]
13053 });
13054 });
13055 return target;
13056 },
13057 /**
13058 * Checks that a value is a natural number, a positive integer or zero.
13059 *
13060 * @param {*} value
13061 * @return {Boolean}
13062 */
13063 isNaturalNumber: function isNaturalNumber(value) {
13064 return typeof value === 'number' &&
13065 isFinite(value) &&
13066 Math.floor(value) === value &&
13067 value >= 0;
13068 }
13069};
13070
13071},{"lodash":210}],47:[function(require,module,exports){
13072'use strict';
13073
13074var errors = require('../errors');
13075var _ = require('lodash');
13076
13077module.exports = {
13078 checkState: function(condition, message) {
13079 if (!condition) {
13080 throw new errors.InvalidState(message);
13081 }
13082 },
13083 checkArgument: function(condition, argumentName, message, docsPath) {
13084 if (!condition) {
13085 throw new errors.InvalidArgument(argumentName, message, docsPath);
13086 }
13087 },
13088 checkArgumentType: function(argument, type, argumentName) {
13089 argumentName = argumentName || '(unknown name)';
13090 if (_.isString(type)) {
13091 if (type === 'Buffer') {
13092 var buffer = require('buffer'); // './buffer' fails on cordova & RN
13093 if (!buffer.Buffer.isBuffer(argument)) {
13094 throw new errors.InvalidArgumentType(argument, type, argumentName);
13095 }
13096 } else if (typeof argument !== type) {
13097 throw new errors.InvalidArgumentType(argument, type, argumentName);
13098 }
13099 } else {
13100 if (!(argument instanceof type)) {
13101 throw new errors.InvalidArgumentType(argument, type.name, argumentName);
13102 }
13103 }
13104 }
13105};
13106
13107},{"../errors":18,"buffer":132,"lodash":210}],48:[function(require,module,exports){
13108'use strict';
13109
13110const asn1 = exports;
13111
13112asn1.bignum = require('bn.js');
13113
13114asn1.define = require('./asn1/api').define;
13115asn1.base = require('./asn1/base');
13116asn1.constants = require('./asn1/constants');
13117asn1.decoders = require('./asn1/decoders');
13118asn1.encoders = require('./asn1/encoders');
13119
13120},{"./asn1/api":49,"./asn1/base":51,"./asn1/constants":55,"./asn1/decoders":57,"./asn1/encoders":60,"bn.js":80}],49:[function(require,module,exports){
13121'use strict';
13122
13123const encoders = require('./encoders');
13124const decoders = require('./decoders');
13125const inherits = require('inherits');
13126
13127const api = exports;
13128
13129api.define = function define(name, body) {
13130 return new Entity(name, body);
13131};
13132
13133function Entity(name, body) {
13134 this.name = name;
13135 this.body = body;
13136
13137 this.decoders = {};
13138 this.encoders = {};
13139}
13140
13141Entity.prototype._createNamed = function createNamed(Base) {
13142 const name = this.name;
13143
13144 function Generated(entity) {
13145 this._initNamed(entity, name);
13146 }
13147 inherits(Generated, Base);
13148 Generated.prototype._initNamed = function _initNamed(entity, name) {
13149 Base.call(this, entity, name);
13150 };
13151
13152 return new Generated(this);
13153};
13154
13155Entity.prototype._getDecoder = function _getDecoder(enc) {
13156 enc = enc || 'der';
13157 // Lazily create decoder
13158 if (!this.decoders.hasOwnProperty(enc))
13159 this.decoders[enc] = this._createNamed(decoders[enc]);
13160 return this.decoders[enc];
13161};
13162
13163Entity.prototype.decode = function decode(data, enc, options) {
13164 return this._getDecoder(enc).decode(data, options);
13165};
13166
13167Entity.prototype._getEncoder = function _getEncoder(enc) {
13168 enc = enc || 'der';
13169 // Lazily create encoder
13170 if (!this.encoders.hasOwnProperty(enc))
13171 this.encoders[enc] = this._createNamed(encoders[enc]);
13172 return this.encoders[enc];
13173};
13174
13175Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
13176 return this._getEncoder(enc).encode(data, reporter);
13177};
13178
13179},{"./decoders":57,"./encoders":60,"inherits":206}],50:[function(require,module,exports){
13180'use strict';
13181
13182const inherits = require('inherits');
13183const Reporter = require('../base/reporter').Reporter;
13184const Buffer = require('safer-buffer').Buffer;
13185
13186function DecoderBuffer(base, options) {
13187 Reporter.call(this, options);
13188 if (!Buffer.isBuffer(base)) {
13189 this.error('Input not Buffer');
13190 return;
13191 }
13192
13193 this.base = base;
13194 this.offset = 0;
13195 this.length = base.length;
13196}
13197inherits(DecoderBuffer, Reporter);
13198exports.DecoderBuffer = DecoderBuffer;
13199
13200DecoderBuffer.isDecoderBuffer = function isDecoderBuffer(data) {
13201 if (data instanceof DecoderBuffer) {
13202 return true;
13203 }
13204
13205 // Or accept compatible API
13206 const isCompatible = typeof data === 'object' &&
13207 Buffer.isBuffer(data.base) &&
13208 data.constructor.name === 'DecoderBuffer' &&
13209 typeof data.offset === 'number' &&
13210 typeof data.length === 'number' &&
13211 typeof data.save === 'function' &&
13212 typeof data.restore === 'function' &&
13213 typeof data.isEmpty === 'function' &&
13214 typeof data.readUInt8 === 'function' &&
13215 typeof data.skip === 'function' &&
13216 typeof data.raw === 'function';
13217
13218 return isCompatible;
13219};
13220
13221DecoderBuffer.prototype.save = function save() {
13222 return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
13223};
13224
13225DecoderBuffer.prototype.restore = function restore(save) {
13226 // Return skipped data
13227 const res = new DecoderBuffer(this.base);
13228 res.offset = save.offset;
13229 res.length = this.offset;
13230
13231 this.offset = save.offset;
13232 Reporter.prototype.restore.call(this, save.reporter);
13233
13234 return res;
13235};
13236
13237DecoderBuffer.prototype.isEmpty = function isEmpty() {
13238 return this.offset === this.length;
13239};
13240
13241DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
13242 if (this.offset + 1 <= this.length)
13243 return this.base.readUInt8(this.offset++, true);
13244 else
13245 return this.error(fail || 'DecoderBuffer overrun');
13246};
13247
13248DecoderBuffer.prototype.skip = function skip(bytes, fail) {
13249 if (!(this.offset + bytes <= this.length))
13250 return this.error(fail || 'DecoderBuffer overrun');
13251
13252 const res = new DecoderBuffer(this.base);
13253
13254 // Share reporter state
13255 res._reporterState = this._reporterState;
13256
13257 res.offset = this.offset;
13258 res.length = this.offset + bytes;
13259 this.offset += bytes;
13260 return res;
13261};
13262
13263DecoderBuffer.prototype.raw = function raw(save) {
13264 return this.base.slice(save ? save.offset : this.offset, this.length);
13265};
13266
13267function EncoderBuffer(value, reporter) {
13268 if (Array.isArray(value)) {
13269 this.length = 0;
13270 this.value = value.map(function(item) {
13271 if (!EncoderBuffer.isEncoderBuffer(item))
13272 item = new EncoderBuffer(item, reporter);
13273 this.length += item.length;
13274 return item;
13275 }, this);
13276 } else if (typeof value === 'number') {
13277 if (!(0 <= value && value <= 0xff))
13278 return reporter.error('non-byte EncoderBuffer value');
13279 this.value = value;
13280 this.length = 1;
13281 } else if (typeof value === 'string') {
13282 this.value = value;
13283 this.length = Buffer.byteLength(value);
13284 } else if (Buffer.isBuffer(value)) {
13285 this.value = value;
13286 this.length = value.length;
13287 } else {
13288 return reporter.error('Unsupported type: ' + typeof value);
13289 }
13290}
13291exports.EncoderBuffer = EncoderBuffer;
13292
13293EncoderBuffer.isEncoderBuffer = function isEncoderBuffer(data) {
13294 if (data instanceof EncoderBuffer) {
13295 return true;
13296 }
13297
13298 // Or accept compatible API
13299 const isCompatible = typeof data === 'object' &&
13300 data.constructor.name === 'EncoderBuffer' &&
13301 typeof data.length === 'number' &&
13302 typeof data.join === 'function';
13303
13304 return isCompatible;
13305};
13306
13307EncoderBuffer.prototype.join = function join(out, offset) {
13308 if (!out)
13309 out = Buffer.alloc(this.length);
13310 if (!offset)
13311 offset = 0;
13312
13313 if (this.length === 0)
13314 return out;
13315
13316 if (Array.isArray(this.value)) {
13317 this.value.forEach(function(item) {
13318 item.join(out, offset);
13319 offset += item.length;
13320 });
13321 } else {
13322 if (typeof this.value === 'number')
13323 out[offset] = this.value;
13324 else if (typeof this.value === 'string')
13325 out.write(this.value, offset);
13326 else if (Buffer.isBuffer(this.value))
13327 this.value.copy(out, offset);
13328 offset += this.length;
13329 }
13330
13331 return out;
13332};
13333
13334},{"../base/reporter":53,"inherits":206,"safer-buffer":257}],51:[function(require,module,exports){
13335'use strict';
13336
13337const base = exports;
13338
13339base.Reporter = require('./reporter').Reporter;
13340base.DecoderBuffer = require('./buffer').DecoderBuffer;
13341base.EncoderBuffer = require('./buffer').EncoderBuffer;
13342base.Node = require('./node');
13343
13344},{"./buffer":50,"./node":52,"./reporter":53}],52:[function(require,module,exports){
13345'use strict';
13346
13347const Reporter = require('../base/reporter').Reporter;
13348const EncoderBuffer = require('../base/buffer').EncoderBuffer;
13349const DecoderBuffer = require('../base/buffer').DecoderBuffer;
13350const assert = require('minimalistic-assert');
13351
13352// Supported tags
13353const tags = [
13354 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
13355 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
13356 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
13357 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
13358];
13359
13360// Public methods list
13361const methods = [
13362 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
13363 'any', 'contains'
13364].concat(tags);
13365
13366// Overrided methods list
13367const overrided = [
13368 '_peekTag', '_decodeTag', '_use',
13369 '_decodeStr', '_decodeObjid', '_decodeTime',
13370 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
13371
13372 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
13373 '_encodeNull', '_encodeInt', '_encodeBool'
13374];
13375
13376function Node(enc, parent, name) {
13377 const state = {};
13378 this._baseState = state;
13379
13380 state.name = name;
13381 state.enc = enc;
13382
13383 state.parent = parent || null;
13384 state.children = null;
13385
13386 // State
13387 state.tag = null;
13388 state.args = null;
13389 state.reverseArgs = null;
13390 state.choice = null;
13391 state.optional = false;
13392 state.any = false;
13393 state.obj = false;
13394 state.use = null;
13395 state.useDecoder = null;
13396 state.key = null;
13397 state['default'] = null;
13398 state.explicit = null;
13399 state.implicit = null;
13400 state.contains = null;
13401
13402 // Should create new instance on each method
13403 if (!state.parent) {
13404 state.children = [];
13405 this._wrap();
13406 }
13407}
13408module.exports = Node;
13409
13410const stateProps = [
13411 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
13412 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
13413 'implicit', 'contains'
13414];
13415
13416Node.prototype.clone = function clone() {
13417 const state = this._baseState;
13418 const cstate = {};
13419 stateProps.forEach(function(prop) {
13420 cstate[prop] = state[prop];
13421 });
13422 const res = new this.constructor(cstate.parent);
13423 res._baseState = cstate;
13424 return res;
13425};
13426
13427Node.prototype._wrap = function wrap() {
13428 const state = this._baseState;
13429 methods.forEach(function(method) {
13430 this[method] = function _wrappedMethod() {
13431 const clone = new this.constructor(this);
13432 state.children.push(clone);
13433 return clone[method].apply(clone, arguments);
13434 };
13435 }, this);
13436};
13437
13438Node.prototype._init = function init(body) {
13439 const state = this._baseState;
13440
13441 assert(state.parent === null);
13442 body.call(this);
13443
13444 // Filter children
13445 state.children = state.children.filter(function(child) {
13446 return child._baseState.parent === this;
13447 }, this);
13448 assert.equal(state.children.length, 1, 'Root node can have only one child');
13449};
13450
13451Node.prototype._useArgs = function useArgs(args) {
13452 const state = this._baseState;
13453
13454 // Filter children and args
13455 const children = args.filter(function(arg) {
13456 return arg instanceof this.constructor;
13457 }, this);
13458 args = args.filter(function(arg) {
13459 return !(arg instanceof this.constructor);
13460 }, this);
13461
13462 if (children.length !== 0) {
13463 assert(state.children === null);
13464 state.children = children;
13465
13466 // Replace parent to maintain backward link
13467 children.forEach(function(child) {
13468 child._baseState.parent = this;
13469 }, this);
13470 }
13471 if (args.length !== 0) {
13472 assert(state.args === null);
13473 state.args = args;
13474 state.reverseArgs = args.map(function(arg) {
13475 if (typeof arg !== 'object' || arg.constructor !== Object)
13476 return arg;
13477
13478 const res = {};
13479 Object.keys(arg).forEach(function(key) {
13480 if (key == (key | 0))
13481 key |= 0;
13482 const value = arg[key];
13483 res[value] = key;
13484 });
13485 return res;
13486 });
13487 }
13488};
13489
13490//
13491// Overrided methods
13492//
13493
13494overrided.forEach(function(method) {
13495 Node.prototype[method] = function _overrided() {
13496 const state = this._baseState;
13497 throw new Error(method + ' not implemented for encoding: ' + state.enc);
13498 };
13499});
13500
13501//
13502// Public methods
13503//
13504
13505tags.forEach(function(tag) {
13506 Node.prototype[tag] = function _tagMethod() {
13507 const state = this._baseState;
13508 const args = Array.prototype.slice.call(arguments);
13509
13510 assert(state.tag === null);
13511 state.tag = tag;
13512
13513 this._useArgs(args);
13514
13515 return this;
13516 };
13517});
13518
13519Node.prototype.use = function use(item) {
13520 assert(item);
13521 const state = this._baseState;
13522
13523 assert(state.use === null);
13524 state.use = item;
13525
13526 return this;
13527};
13528
13529Node.prototype.optional = function optional() {
13530 const state = this._baseState;
13531
13532 state.optional = true;
13533
13534 return this;
13535};
13536
13537Node.prototype.def = function def(val) {
13538 const state = this._baseState;
13539
13540 assert(state['default'] === null);
13541 state['default'] = val;
13542 state.optional = true;
13543
13544 return this;
13545};
13546
13547Node.prototype.explicit = function explicit(num) {
13548 const state = this._baseState;
13549
13550 assert(state.explicit === null && state.implicit === null);
13551 state.explicit = num;
13552
13553 return this;
13554};
13555
13556Node.prototype.implicit = function implicit(num) {
13557 const state = this._baseState;
13558
13559 assert(state.explicit === null && state.implicit === null);
13560 state.implicit = num;
13561
13562 return this;
13563};
13564
13565Node.prototype.obj = function obj() {
13566 const state = this._baseState;
13567 const args = Array.prototype.slice.call(arguments);
13568
13569 state.obj = true;
13570
13571 if (args.length !== 0)
13572 this._useArgs(args);
13573
13574 return this;
13575};
13576
13577Node.prototype.key = function key(newKey) {
13578 const state = this._baseState;
13579
13580 assert(state.key === null);
13581 state.key = newKey;
13582
13583 return this;
13584};
13585
13586Node.prototype.any = function any() {
13587 const state = this._baseState;
13588
13589 state.any = true;
13590
13591 return this;
13592};
13593
13594Node.prototype.choice = function choice(obj) {
13595 const state = this._baseState;
13596
13597 assert(state.choice === null);
13598 state.choice = obj;
13599 this._useArgs(Object.keys(obj).map(function(key) {
13600 return obj[key];
13601 }));
13602
13603 return this;
13604};
13605
13606Node.prototype.contains = function contains(item) {
13607 const state = this._baseState;
13608
13609 assert(state.use === null);
13610 state.contains = item;
13611
13612 return this;
13613};
13614
13615//
13616// Decoding
13617//
13618
13619Node.prototype._decode = function decode(input, options) {
13620 const state = this._baseState;
13621
13622 // Decode root node
13623 if (state.parent === null)
13624 return input.wrapResult(state.children[0]._decode(input, options));
13625
13626 let result = state['default'];
13627 let present = true;
13628
13629 let prevKey = null;
13630 if (state.key !== null)
13631 prevKey = input.enterKey(state.key);
13632
13633 // Check if tag is there
13634 if (state.optional) {
13635 let tag = null;
13636 if (state.explicit !== null)
13637 tag = state.explicit;
13638 else if (state.implicit !== null)
13639 tag = state.implicit;
13640 else if (state.tag !== null)
13641 tag = state.tag;
13642
13643 if (tag === null && !state.any) {
13644 // Trial and Error
13645 const save = input.save();
13646 try {
13647 if (state.choice === null)
13648 this._decodeGeneric(state.tag, input, options);
13649 else
13650 this._decodeChoice(input, options);
13651 present = true;
13652 } catch (e) {
13653 present = false;
13654 }
13655 input.restore(save);
13656 } else {
13657 present = this._peekTag(input, tag, state.any);
13658
13659 if (input.isError(present))
13660 return present;
13661 }
13662 }
13663
13664 // Push object on stack
13665 let prevObj;
13666 if (state.obj && present)
13667 prevObj = input.enterObject();
13668
13669 if (present) {
13670 // Unwrap explicit values
13671 if (state.explicit !== null) {
13672 const explicit = this._decodeTag(input, state.explicit);
13673 if (input.isError(explicit))
13674 return explicit;
13675 input = explicit;
13676 }
13677
13678 const start = input.offset;
13679
13680 // Unwrap implicit and normal values
13681 if (state.use === null && state.choice === null) {
13682 let save;
13683 if (state.any)
13684 save = input.save();
13685 const body = this._decodeTag(
13686 input,
13687 state.implicit !== null ? state.implicit : state.tag,
13688 state.any
13689 );
13690 if (input.isError(body))
13691 return body;
13692
13693 if (state.any)
13694 result = input.raw(save);
13695 else
13696 input = body;
13697 }
13698
13699 if (options && options.track && state.tag !== null)
13700 options.track(input.path(), start, input.length, 'tagged');
13701
13702 if (options && options.track && state.tag !== null)
13703 options.track(input.path(), input.offset, input.length, 'content');
13704
13705 // Select proper method for tag
13706 if (state.any) {
13707 // no-op
13708 } else if (state.choice === null) {
13709 result = this._decodeGeneric(state.tag, input, options);
13710 } else {
13711 result = this._decodeChoice(input, options);
13712 }
13713
13714 if (input.isError(result))
13715 return result;
13716
13717 // Decode children
13718 if (!state.any && state.choice === null && state.children !== null) {
13719 state.children.forEach(function decodeChildren(child) {
13720 // NOTE: We are ignoring errors here, to let parser continue with other
13721 // parts of encoded data
13722 child._decode(input, options);
13723 });
13724 }
13725
13726 // Decode contained/encoded by schema, only in bit or octet strings
13727 if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
13728 const data = new DecoderBuffer(result);
13729 result = this._getUse(state.contains, input._reporterState.obj)
13730 ._decode(data, options);
13731 }
13732 }
13733
13734 // Pop object
13735 if (state.obj && present)
13736 result = input.leaveObject(prevObj);
13737
13738 // Set key
13739 if (state.key !== null && (result !== null || present === true))
13740 input.leaveKey(prevKey, state.key, result);
13741 else if (prevKey !== null)
13742 input.exitKey(prevKey);
13743
13744 return result;
13745};
13746
13747Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
13748 const state = this._baseState;
13749
13750 if (tag === 'seq' || tag === 'set')
13751 return null;
13752 if (tag === 'seqof' || tag === 'setof')
13753 return this._decodeList(input, tag, state.args[0], options);
13754 else if (/str$/.test(tag))
13755 return this._decodeStr(input, tag, options);
13756 else if (tag === 'objid' && state.args)
13757 return this._decodeObjid(input, state.args[0], state.args[1], options);
13758 else if (tag === 'objid')
13759 return this._decodeObjid(input, null, null, options);
13760 else if (tag === 'gentime' || tag === 'utctime')
13761 return this._decodeTime(input, tag, options);
13762 else if (tag === 'null_')
13763 return this._decodeNull(input, options);
13764 else if (tag === 'bool')
13765 return this._decodeBool(input, options);
13766 else if (tag === 'objDesc')
13767 return this._decodeStr(input, tag, options);
13768 else if (tag === 'int' || tag === 'enum')
13769 return this._decodeInt(input, state.args && state.args[0], options);
13770
13771 if (state.use !== null) {
13772 return this._getUse(state.use, input._reporterState.obj)
13773 ._decode(input, options);
13774 } else {
13775 return input.error('unknown tag: ' + tag);
13776 }
13777};
13778
13779Node.prototype._getUse = function _getUse(entity, obj) {
13780
13781 const state = this._baseState;
13782 // Create altered use decoder if implicit is set
13783 state.useDecoder = this._use(entity, obj);
13784 assert(state.useDecoder._baseState.parent === null);
13785 state.useDecoder = state.useDecoder._baseState.children[0];
13786 if (state.implicit !== state.useDecoder._baseState.implicit) {
13787 state.useDecoder = state.useDecoder.clone();
13788 state.useDecoder._baseState.implicit = state.implicit;
13789 }
13790 return state.useDecoder;
13791};
13792
13793Node.prototype._decodeChoice = function decodeChoice(input, options) {
13794 const state = this._baseState;
13795 let result = null;
13796 let match = false;
13797
13798 Object.keys(state.choice).some(function(key) {
13799 const save = input.save();
13800 const node = state.choice[key];
13801 try {
13802 const value = node._decode(input, options);
13803 if (input.isError(value))
13804 return false;
13805
13806 result = { type: key, value: value };
13807 match = true;
13808 } catch (e) {
13809 input.restore(save);
13810 return false;
13811 }
13812 return true;
13813 }, this);
13814
13815 if (!match)
13816 return input.error('Choice not matched');
13817
13818 return result;
13819};
13820
13821//
13822// Encoding
13823//
13824
13825Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
13826 return new EncoderBuffer(data, this.reporter);
13827};
13828
13829Node.prototype._encode = function encode(data, reporter, parent) {
13830 const state = this._baseState;
13831 if (state['default'] !== null && state['default'] === data)
13832 return;
13833
13834 const result = this._encodeValue(data, reporter, parent);
13835 if (result === undefined)
13836 return;
13837
13838 if (this._skipDefault(result, reporter, parent))
13839 return;
13840
13841 return result;
13842};
13843
13844Node.prototype._encodeValue = function encode(data, reporter, parent) {
13845 const state = this._baseState;
13846
13847 // Decode root node
13848 if (state.parent === null)
13849 return state.children[0]._encode(data, reporter || new Reporter());
13850
13851 let result = null;
13852
13853 // Set reporter to share it with a child class
13854 this.reporter = reporter;
13855
13856 // Check if data is there
13857 if (state.optional && data === undefined) {
13858 if (state['default'] !== null)
13859 data = state['default'];
13860 else
13861 return;
13862 }
13863
13864 // Encode children first
13865 let content = null;
13866 let primitive = false;
13867 if (state.any) {
13868 // Anything that was given is translated to buffer
13869 result = this._createEncoderBuffer(data);
13870 } else if (state.choice) {
13871 result = this._encodeChoice(data, reporter);
13872 } else if (state.contains) {
13873 content = this._getUse(state.contains, parent)._encode(data, reporter);
13874 primitive = true;
13875 } else if (state.children) {
13876 content = state.children.map(function(child) {
13877 if (child._baseState.tag === 'null_')
13878 return child._encode(null, reporter, data);
13879
13880 if (child._baseState.key === null)
13881 return reporter.error('Child should have a key');
13882 const prevKey = reporter.enterKey(child._baseState.key);
13883
13884 if (typeof data !== 'object')
13885 return reporter.error('Child expected, but input is not object');
13886
13887 const res = child._encode(data[child._baseState.key], reporter, data);
13888 reporter.leaveKey(prevKey);
13889
13890 return res;
13891 }, this).filter(function(child) {
13892 return child;
13893 });
13894 content = this._createEncoderBuffer(content);
13895 } else {
13896 if (state.tag === 'seqof' || state.tag === 'setof') {
13897 // TODO(indutny): this should be thrown on DSL level
13898 if (!(state.args && state.args.length === 1))
13899 return reporter.error('Too many args for : ' + state.tag);
13900
13901 if (!Array.isArray(data))
13902 return reporter.error('seqof/setof, but data is not Array');
13903
13904 const child = this.clone();
13905 child._baseState.implicit = null;
13906 content = this._createEncoderBuffer(data.map(function(item) {
13907 const state = this._baseState;
13908
13909 return this._getUse(state.args[0], data)._encode(item, reporter);
13910 }, child));
13911 } else if (state.use !== null) {
13912 result = this._getUse(state.use, parent)._encode(data, reporter);
13913 } else {
13914 content = this._encodePrimitive(state.tag, data);
13915 primitive = true;
13916 }
13917 }
13918
13919 // Encode data itself
13920 if (!state.any && state.choice === null) {
13921 const tag = state.implicit !== null ? state.implicit : state.tag;
13922 const cls = state.implicit === null ? 'universal' : 'context';
13923
13924 if (tag === null) {
13925 if (state.use === null)
13926 reporter.error('Tag could be omitted only for .use()');
13927 } else {
13928 if (state.use === null)
13929 result = this._encodeComposite(tag, primitive, cls, content);
13930 }
13931 }
13932
13933 // Wrap in explicit
13934 if (state.explicit !== null)
13935 result = this._encodeComposite(state.explicit, false, 'context', result);
13936
13937 return result;
13938};
13939
13940Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
13941 const state = this._baseState;
13942
13943 const node = state.choice[data.type];
13944 if (!node) {
13945 assert(
13946 false,
13947 data.type + ' not found in ' +
13948 JSON.stringify(Object.keys(state.choice)));
13949 }
13950 return node._encode(data.value, reporter);
13951};
13952
13953Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
13954 const state = this._baseState;
13955
13956 if (/str$/.test(tag))
13957 return this._encodeStr(data, tag);
13958 else if (tag === 'objid' && state.args)
13959 return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
13960 else if (tag === 'objid')
13961 return this._encodeObjid(data, null, null);
13962 else if (tag === 'gentime' || tag === 'utctime')
13963 return this._encodeTime(data, tag);
13964 else if (tag === 'null_')
13965 return this._encodeNull();
13966 else if (tag === 'int' || tag === 'enum')
13967 return this._encodeInt(data, state.args && state.reverseArgs[0]);
13968 else if (tag === 'bool')
13969 return this._encodeBool(data);
13970 else if (tag === 'objDesc')
13971 return this._encodeStr(data, tag);
13972 else
13973 throw new Error('Unsupported tag: ' + tag);
13974};
13975
13976Node.prototype._isNumstr = function isNumstr(str) {
13977 return /^[0-9 ]*$/.test(str);
13978};
13979
13980Node.prototype._isPrintstr = function isPrintstr(str) {
13981 return /^[A-Za-z0-9 '()+,-./:=?]*$/.test(str);
13982};
13983
13984},{"../base/buffer":50,"../base/reporter":53,"minimalistic-assert":213}],53:[function(require,module,exports){
13985'use strict';
13986
13987const inherits = require('inherits');
13988
13989function Reporter(options) {
13990 this._reporterState = {
13991 obj: null,
13992 path: [],
13993 options: options || {},
13994 errors: []
13995 };
13996}
13997exports.Reporter = Reporter;
13998
13999Reporter.prototype.isError = function isError(obj) {
14000 return obj instanceof ReporterError;
14001};
14002
14003Reporter.prototype.save = function save() {
14004 const state = this._reporterState;
14005
14006 return { obj: state.obj, pathLen: state.path.length };
14007};
14008
14009Reporter.prototype.restore = function restore(data) {
14010 const state = this._reporterState;
14011
14012 state.obj = data.obj;
14013 state.path = state.path.slice(0, data.pathLen);
14014};
14015
14016Reporter.prototype.enterKey = function enterKey(key) {
14017 return this._reporterState.path.push(key);
14018};
14019
14020Reporter.prototype.exitKey = function exitKey(index) {
14021 const state = this._reporterState;
14022
14023 state.path = state.path.slice(0, index - 1);
14024};
14025
14026Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
14027 const state = this._reporterState;
14028
14029 this.exitKey(index);
14030 if (state.obj !== null)
14031 state.obj[key] = value;
14032};
14033
14034Reporter.prototype.path = function path() {
14035 return this._reporterState.path.join('/');
14036};
14037
14038Reporter.prototype.enterObject = function enterObject() {
14039 const state = this._reporterState;
14040
14041 const prev = state.obj;
14042 state.obj = {};
14043 return prev;
14044};
14045
14046Reporter.prototype.leaveObject = function leaveObject(prev) {
14047 const state = this._reporterState;
14048
14049 const now = state.obj;
14050 state.obj = prev;
14051 return now;
14052};
14053
14054Reporter.prototype.error = function error(msg) {
14055 let err;
14056 const state = this._reporterState;
14057
14058 const inherited = msg instanceof ReporterError;
14059 if (inherited) {
14060 err = msg;
14061 } else {
14062 err = new ReporterError(state.path.map(function(elem) {
14063 return '[' + JSON.stringify(elem) + ']';
14064 }).join(''), msg.message || msg, msg.stack);
14065 }
14066
14067 if (!state.options.partial)
14068 throw err;
14069
14070 if (!inherited)
14071 state.errors.push(err);
14072
14073 return err;
14074};
14075
14076Reporter.prototype.wrapResult = function wrapResult(result) {
14077 const state = this._reporterState;
14078 if (!state.options.partial)
14079 return result;
14080
14081 return {
14082 result: this.isError(result) ? null : result,
14083 errors: state.errors
14084 };
14085};
14086
14087function ReporterError(path, msg) {
14088 this.path = path;
14089 this.rethrow(msg);
14090}
14091inherits(ReporterError, Error);
14092
14093ReporterError.prototype.rethrow = function rethrow(msg) {
14094 this.message = msg + ' at: ' + (this.path || '(shallow)');
14095 if (Error.captureStackTrace)
14096 Error.captureStackTrace(this, ReporterError);
14097
14098 if (!this.stack) {
14099 try {
14100 // IE only adds stack when thrown
14101 throw new Error(this.message);
14102 } catch (e) {
14103 this.stack = e.stack;
14104 }
14105 }
14106 return this;
14107};
14108
14109},{"inherits":206}],54:[function(require,module,exports){
14110'use strict';
14111
14112// Helper
14113function reverse(map) {
14114 const res = {};
14115
14116 Object.keys(map).forEach(function(key) {
14117 // Convert key to integer if it is stringified
14118 if ((key | 0) == key)
14119 key = key | 0;
14120
14121 const value = map[key];
14122 res[value] = key;
14123 });
14124
14125 return res;
14126}
14127
14128exports.tagClass = {
14129 0: 'universal',
14130 1: 'application',
14131 2: 'context',
14132 3: 'private'
14133};
14134exports.tagClassByName = reverse(exports.tagClass);
14135
14136exports.tag = {
14137 0x00: 'end',
14138 0x01: 'bool',
14139 0x02: 'int',
14140 0x03: 'bitstr',
14141 0x04: 'octstr',
14142 0x05: 'null_',
14143 0x06: 'objid',
14144 0x07: 'objDesc',
14145 0x08: 'external',
14146 0x09: 'real',
14147 0x0a: 'enum',
14148 0x0b: 'embed',
14149 0x0c: 'utf8str',
14150 0x0d: 'relativeOid',
14151 0x10: 'seq',
14152 0x11: 'set',
14153 0x12: 'numstr',
14154 0x13: 'printstr',
14155 0x14: 't61str',
14156 0x15: 'videostr',
14157 0x16: 'ia5str',
14158 0x17: 'utctime',
14159 0x18: 'gentime',
14160 0x19: 'graphstr',
14161 0x1a: 'iso646str',
14162 0x1b: 'genstr',
14163 0x1c: 'unistr',
14164 0x1d: 'charstr',
14165 0x1e: 'bmpstr'
14166};
14167exports.tagByName = reverse(exports.tag);
14168
14169},{}],55:[function(require,module,exports){
14170'use strict';
14171
14172const constants = exports;
14173
14174// Helper
14175constants._reverse = function reverse(map) {
14176 const res = {};
14177
14178 Object.keys(map).forEach(function(key) {
14179 // Convert key to integer if it is stringified
14180 if ((key | 0) == key)
14181 key = key | 0;
14182
14183 const value = map[key];
14184 res[value] = key;
14185 });
14186
14187 return res;
14188};
14189
14190constants.der = require('./der');
14191
14192},{"./der":54}],56:[function(require,module,exports){
14193'use strict';
14194
14195const inherits = require('inherits');
14196
14197const bignum = require('bn.js');
14198const DecoderBuffer = require('../base/buffer').DecoderBuffer;
14199const Node = require('../base/node');
14200
14201// Import DER constants
14202const der = require('../constants/der');
14203
14204function DERDecoder(entity) {
14205 this.enc = 'der';
14206 this.name = entity.name;
14207 this.entity = entity;
14208
14209 // Construct base tree
14210 this.tree = new DERNode();
14211 this.tree._init(entity.body);
14212}
14213module.exports = DERDecoder;
14214
14215DERDecoder.prototype.decode = function decode(data, options) {
14216 if (!DecoderBuffer.isDecoderBuffer(data)) {
14217 data = new DecoderBuffer(data, options);
14218 }
14219
14220 return this.tree._decode(data, options);
14221};
14222
14223// Tree methods
14224
14225function DERNode(parent) {
14226 Node.call(this, 'der', parent);
14227}
14228inherits(DERNode, Node);
14229
14230DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
14231 if (buffer.isEmpty())
14232 return false;
14233
14234 const state = buffer.save();
14235 const decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
14236 if (buffer.isError(decodedTag))
14237 return decodedTag;
14238
14239 buffer.restore(state);
14240
14241 return decodedTag.tag === tag || decodedTag.tagStr === tag ||
14242 (decodedTag.tagStr + 'of') === tag || any;
14243};
14244
14245DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
14246 const decodedTag = derDecodeTag(buffer,
14247 'Failed to decode tag of "' + tag + '"');
14248 if (buffer.isError(decodedTag))
14249 return decodedTag;
14250
14251 let len = derDecodeLen(buffer,
14252 decodedTag.primitive,
14253 'Failed to get length of "' + tag + '"');
14254
14255 // Failure
14256 if (buffer.isError(len))
14257 return len;
14258
14259 if (!any &&
14260 decodedTag.tag !== tag &&
14261 decodedTag.tagStr !== tag &&
14262 decodedTag.tagStr + 'of' !== tag) {
14263 return buffer.error('Failed to match tag: "' + tag + '"');
14264 }
14265
14266 if (decodedTag.primitive || len !== null)
14267 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
14268
14269 // Indefinite length... find END tag
14270 const state = buffer.save();
14271 const res = this._skipUntilEnd(
14272 buffer,
14273 'Failed to skip indefinite length body: "' + this.tag + '"');
14274 if (buffer.isError(res))
14275 return res;
14276
14277 len = buffer.offset - state.offset;
14278 buffer.restore(state);
14279 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
14280};
14281
14282DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
14283 for (;;) {
14284 const tag = derDecodeTag(buffer, fail);
14285 if (buffer.isError(tag))
14286 return tag;
14287 const len = derDecodeLen(buffer, tag.primitive, fail);
14288 if (buffer.isError(len))
14289 return len;
14290
14291 let res;
14292 if (tag.primitive || len !== null)
14293 res = buffer.skip(len);
14294 else
14295 res = this._skipUntilEnd(buffer, fail);
14296
14297 // Failure
14298 if (buffer.isError(res))
14299 return res;
14300
14301 if (tag.tagStr === 'end')
14302 break;
14303 }
14304};
14305
14306DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
14307 options) {
14308 const result = [];
14309 while (!buffer.isEmpty()) {
14310 const possibleEnd = this._peekTag(buffer, 'end');
14311 if (buffer.isError(possibleEnd))
14312 return possibleEnd;
14313
14314 const res = decoder.decode(buffer, 'der', options);
14315 if (buffer.isError(res) && possibleEnd)
14316 break;
14317 result.push(res);
14318 }
14319 return result;
14320};
14321
14322DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
14323 if (tag === 'bitstr') {
14324 const unused = buffer.readUInt8();
14325 if (buffer.isError(unused))
14326 return unused;
14327 return { unused: unused, data: buffer.raw() };
14328 } else if (tag === 'bmpstr') {
14329 const raw = buffer.raw();
14330 if (raw.length % 2 === 1)
14331 return buffer.error('Decoding of string type: bmpstr length mismatch');
14332
14333 let str = '';
14334 for (let i = 0; i < raw.length / 2; i++) {
14335 str += String.fromCharCode(raw.readUInt16BE(i * 2));
14336 }
14337 return str;
14338 } else if (tag === 'numstr') {
14339 const numstr = buffer.raw().toString('ascii');
14340 if (!this._isNumstr(numstr)) {
14341 return buffer.error('Decoding of string type: ' +
14342 'numstr unsupported characters');
14343 }
14344 return numstr;
14345 } else if (tag === 'octstr') {
14346 return buffer.raw();
14347 } else if (tag === 'objDesc') {
14348 return buffer.raw();
14349 } else if (tag === 'printstr') {
14350 const printstr = buffer.raw().toString('ascii');
14351 if (!this._isPrintstr(printstr)) {
14352 return buffer.error('Decoding of string type: ' +
14353 'printstr unsupported characters');
14354 }
14355 return printstr;
14356 } else if (/str$/.test(tag)) {
14357 return buffer.raw().toString();
14358 } else {
14359 return buffer.error('Decoding of string type: ' + tag + ' unsupported');
14360 }
14361};
14362
14363DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
14364 let result;
14365 const identifiers = [];
14366 let ident = 0;
14367 let subident = 0;
14368 while (!buffer.isEmpty()) {
14369 subident = buffer.readUInt8();
14370 ident <<= 7;
14371 ident |= subident & 0x7f;
14372 if ((subident & 0x80) === 0) {
14373 identifiers.push(ident);
14374 ident = 0;
14375 }
14376 }
14377 if (subident & 0x80)
14378 identifiers.push(ident);
14379
14380 const first = (identifiers[0] / 40) | 0;
14381 const second = identifiers[0] % 40;
14382
14383 if (relative)
14384 result = identifiers;
14385 else
14386 result = [first, second].concat(identifiers.slice(1));
14387
14388 if (values) {
14389 let tmp = values[result.join(' ')];
14390 if (tmp === undefined)
14391 tmp = values[result.join('.')];
14392 if (tmp !== undefined)
14393 result = tmp;
14394 }
14395
14396 return result;
14397};
14398
14399DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
14400 const str = buffer.raw().toString();
14401
14402 let year;
14403 let mon;
14404 let day;
14405 let hour;
14406 let min;
14407 let sec;
14408 if (tag === 'gentime') {
14409 year = str.slice(0, 4) | 0;
14410 mon = str.slice(4, 6) | 0;
14411 day = str.slice(6, 8) | 0;
14412 hour = str.slice(8, 10) | 0;
14413 min = str.slice(10, 12) | 0;
14414 sec = str.slice(12, 14) | 0;
14415 } else if (tag === 'utctime') {
14416 year = str.slice(0, 2) | 0;
14417 mon = str.slice(2, 4) | 0;
14418 day = str.slice(4, 6) | 0;
14419 hour = str.slice(6, 8) | 0;
14420 min = str.slice(8, 10) | 0;
14421 sec = str.slice(10, 12) | 0;
14422 if (year < 70)
14423 year = 2000 + year;
14424 else
14425 year = 1900 + year;
14426 } else {
14427 return buffer.error('Decoding ' + tag + ' time is not supported yet');
14428 }
14429
14430 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
14431};
14432
14433DERNode.prototype._decodeNull = function decodeNull() {
14434 return null;
14435};
14436
14437DERNode.prototype._decodeBool = function decodeBool(buffer) {
14438 const res = buffer.readUInt8();
14439 if (buffer.isError(res))
14440 return res;
14441 else
14442 return res !== 0;
14443};
14444
14445DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
14446 // Bigint, return as it is (assume big endian)
14447 const raw = buffer.raw();
14448 let res = new bignum(raw);
14449
14450 if (values)
14451 res = values[res.toString(10)] || res;
14452
14453 return res;
14454};
14455
14456DERNode.prototype._use = function use(entity, obj) {
14457 if (typeof entity === 'function')
14458 entity = entity(obj);
14459 return entity._getDecoder('der').tree;
14460};
14461
14462// Utility methods
14463
14464function derDecodeTag(buf, fail) {
14465 let tag = buf.readUInt8(fail);
14466 if (buf.isError(tag))
14467 return tag;
14468
14469 const cls = der.tagClass[tag >> 6];
14470 const primitive = (tag & 0x20) === 0;
14471
14472 // Multi-octet tag - load
14473 if ((tag & 0x1f) === 0x1f) {
14474 let oct = tag;
14475 tag = 0;
14476 while ((oct & 0x80) === 0x80) {
14477 oct = buf.readUInt8(fail);
14478 if (buf.isError(oct))
14479 return oct;
14480
14481 tag <<= 7;
14482 tag |= oct & 0x7f;
14483 }
14484 } else {
14485 tag &= 0x1f;
14486 }
14487 const tagStr = der.tag[tag];
14488
14489 return {
14490 cls: cls,
14491 primitive: primitive,
14492 tag: tag,
14493 tagStr: tagStr
14494 };
14495}
14496
14497function derDecodeLen(buf, primitive, fail) {
14498 let len = buf.readUInt8(fail);
14499 if (buf.isError(len))
14500 return len;
14501
14502 // Indefinite form
14503 if (!primitive && len === 0x80)
14504 return null;
14505
14506 // Definite form
14507 if ((len & 0x80) === 0) {
14508 // Short form
14509 return len;
14510 }
14511
14512 // Long form
14513 const num = len & 0x7f;
14514 if (num > 4)
14515 return buf.error('length octect is too long');
14516
14517 len = 0;
14518 for (let i = 0; i < num; i++) {
14519 len <<= 8;
14520 const j = buf.readUInt8(fail);
14521 if (buf.isError(j))
14522 return j;
14523 len |= j;
14524 }
14525
14526 return len;
14527}
14528
14529},{"../base/buffer":50,"../base/node":52,"../constants/der":54,"bn.js":80,"inherits":206}],57:[function(require,module,exports){
14530'use strict';
14531
14532const decoders = exports;
14533
14534decoders.der = require('./der');
14535decoders.pem = require('./pem');
14536
14537},{"./der":56,"./pem":58}],58:[function(require,module,exports){
14538'use strict';
14539
14540const inherits = require('inherits');
14541const Buffer = require('safer-buffer').Buffer;
14542
14543const DERDecoder = require('./der');
14544
14545function PEMDecoder(entity) {
14546 DERDecoder.call(this, entity);
14547 this.enc = 'pem';
14548}
14549inherits(PEMDecoder, DERDecoder);
14550module.exports = PEMDecoder;
14551
14552PEMDecoder.prototype.decode = function decode(data, options) {
14553 const lines = data.toString().split(/[\r\n]+/g);
14554
14555 const label = options.label.toUpperCase();
14556
14557 const re = /^-----(BEGIN|END) ([^-]+)-----$/;
14558 let start = -1;
14559 let end = -1;
14560 for (let i = 0; i < lines.length; i++) {
14561 const match = lines[i].match(re);
14562 if (match === null)
14563 continue;
14564
14565 if (match[2] !== label)
14566 continue;
14567
14568 if (start === -1) {
14569 if (match[1] !== 'BEGIN')
14570 break;
14571 start = i;
14572 } else {
14573 if (match[1] !== 'END')
14574 break;
14575 end = i;
14576 break;
14577 }
14578 }
14579 if (start === -1 || end === -1)
14580 throw new Error('PEM section not found for: ' + label);
14581
14582 const base64 = lines.slice(start + 1, end).join('');
14583 // Remove excessive symbols
14584 base64.replace(/[^a-z0-9+/=]+/gi, '');
14585
14586 const input = Buffer.from(base64, 'base64');
14587 return DERDecoder.prototype.decode.call(this, input, options);
14588};
14589
14590},{"./der":56,"inherits":206,"safer-buffer":257}],59:[function(require,module,exports){
14591'use strict';
14592
14593const inherits = require('inherits');
14594const Buffer = require('safer-buffer').Buffer;
14595const Node = require('../base/node');
14596
14597// Import DER constants
14598const der = require('../constants/der');
14599
14600function DEREncoder(entity) {
14601 this.enc = 'der';
14602 this.name = entity.name;
14603 this.entity = entity;
14604
14605 // Construct base tree
14606 this.tree = new DERNode();
14607 this.tree._init(entity.body);
14608}
14609module.exports = DEREncoder;
14610
14611DEREncoder.prototype.encode = function encode(data, reporter) {
14612 return this.tree._encode(data, reporter).join();
14613};
14614
14615// Tree methods
14616
14617function DERNode(parent) {
14618 Node.call(this, 'der', parent);
14619}
14620inherits(DERNode, Node);
14621
14622DERNode.prototype._encodeComposite = function encodeComposite(tag,
14623 primitive,
14624 cls,
14625 content) {
14626 const encodedTag = encodeTag(tag, primitive, cls, this.reporter);
14627
14628 // Short form
14629 if (content.length < 0x80) {
14630 const header = Buffer.alloc(2);
14631 header[0] = encodedTag;
14632 header[1] = content.length;
14633 return this._createEncoderBuffer([ header, content ]);
14634 }
14635
14636 // Long form
14637 // Count octets required to store length
14638 let lenOctets = 1;
14639 for (let i = content.length; i >= 0x100; i >>= 8)
14640 lenOctets++;
14641
14642 const header = Buffer.alloc(1 + 1 + lenOctets);
14643 header[0] = encodedTag;
14644 header[1] = 0x80 | lenOctets;
14645
14646 for (let i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
14647 header[i] = j & 0xff;
14648
14649 return this._createEncoderBuffer([ header, content ]);
14650};
14651
14652DERNode.prototype._encodeStr = function encodeStr(str, tag) {
14653 if (tag === 'bitstr') {
14654 return this._createEncoderBuffer([ str.unused | 0, str.data ]);
14655 } else if (tag === 'bmpstr') {
14656 const buf = Buffer.alloc(str.length * 2);
14657 for (let i = 0; i < str.length; i++) {
14658 buf.writeUInt16BE(str.charCodeAt(i), i * 2);
14659 }
14660 return this._createEncoderBuffer(buf);
14661 } else if (tag === 'numstr') {
14662 if (!this._isNumstr(str)) {
14663 return this.reporter.error('Encoding of string type: numstr supports ' +
14664 'only digits and space');
14665 }
14666 return this._createEncoderBuffer(str);
14667 } else if (tag === 'printstr') {
14668 if (!this._isPrintstr(str)) {
14669 return this.reporter.error('Encoding of string type: printstr supports ' +
14670 'only latin upper and lower case letters, ' +
14671 'digits, space, apostrophe, left and rigth ' +
14672 'parenthesis, plus sign, comma, hyphen, ' +
14673 'dot, slash, colon, equal sign, ' +
14674 'question mark');
14675 }
14676 return this._createEncoderBuffer(str);
14677 } else if (/str$/.test(tag)) {
14678 return this._createEncoderBuffer(str);
14679 } else if (tag === 'objDesc') {
14680 return this._createEncoderBuffer(str);
14681 } else {
14682 return this.reporter.error('Encoding of string type: ' + tag +
14683 ' unsupported');
14684 }
14685};
14686
14687DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
14688 if (typeof id === 'string') {
14689 if (!values)
14690 return this.reporter.error('string objid given, but no values map found');
14691 if (!values.hasOwnProperty(id))
14692 return this.reporter.error('objid not found in values map');
14693 id = values[id].split(/[\s.]+/g);
14694 for (let i = 0; i < id.length; i++)
14695 id[i] |= 0;
14696 } else if (Array.isArray(id)) {
14697 id = id.slice();
14698 for (let i = 0; i < id.length; i++)
14699 id[i] |= 0;
14700 }
14701
14702 if (!Array.isArray(id)) {
14703 return this.reporter.error('objid() should be either array or string, ' +
14704 'got: ' + JSON.stringify(id));
14705 }
14706
14707 if (!relative) {
14708 if (id[1] >= 40)
14709 return this.reporter.error('Second objid identifier OOB');
14710 id.splice(0, 2, id[0] * 40 + id[1]);
14711 }
14712
14713 // Count number of octets
14714 let size = 0;
14715 for (let i = 0; i < id.length; i++) {
14716 let ident = id[i];
14717 for (size++; ident >= 0x80; ident >>= 7)
14718 size++;
14719 }
14720
14721 const objid = Buffer.alloc(size);
14722 let offset = objid.length - 1;
14723 for (let i = id.length - 1; i >= 0; i--) {
14724 let ident = id[i];
14725 objid[offset--] = ident & 0x7f;
14726 while ((ident >>= 7) > 0)
14727 objid[offset--] = 0x80 | (ident & 0x7f);
14728 }
14729
14730 return this._createEncoderBuffer(objid);
14731};
14732
14733function two(num) {
14734 if (num < 10)
14735 return '0' + num;
14736 else
14737 return num;
14738}
14739
14740DERNode.prototype._encodeTime = function encodeTime(time, tag) {
14741 let str;
14742 const date = new Date(time);
14743
14744 if (tag === 'gentime') {
14745 str = [
14746 two(date.getUTCFullYear()),
14747 two(date.getUTCMonth() + 1),
14748 two(date.getUTCDate()),
14749 two(date.getUTCHours()),
14750 two(date.getUTCMinutes()),
14751 two(date.getUTCSeconds()),
14752 'Z'
14753 ].join('');
14754 } else if (tag === 'utctime') {
14755 str = [
14756 two(date.getUTCFullYear() % 100),
14757 two(date.getUTCMonth() + 1),
14758 two(date.getUTCDate()),
14759 two(date.getUTCHours()),
14760 two(date.getUTCMinutes()),
14761 two(date.getUTCSeconds()),
14762 'Z'
14763 ].join('');
14764 } else {
14765 this.reporter.error('Encoding ' + tag + ' time is not supported yet');
14766 }
14767
14768 return this._encodeStr(str, 'octstr');
14769};
14770
14771DERNode.prototype._encodeNull = function encodeNull() {
14772 return this._createEncoderBuffer('');
14773};
14774
14775DERNode.prototype._encodeInt = function encodeInt(num, values) {
14776 if (typeof num === 'string') {
14777 if (!values)
14778 return this.reporter.error('String int or enum given, but no values map');
14779 if (!values.hasOwnProperty(num)) {
14780 return this.reporter.error('Values map doesn\'t contain: ' +
14781 JSON.stringify(num));
14782 }
14783 num = values[num];
14784 }
14785
14786 // Bignum, assume big endian
14787 if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
14788 const numArray = num.toArray();
14789 if (!num.sign && numArray[0] & 0x80) {
14790 numArray.unshift(0);
14791 }
14792 num = Buffer.from(numArray);
14793 }
14794
14795 if (Buffer.isBuffer(num)) {
14796 let size = num.length;
14797 if (num.length === 0)
14798 size++;
14799
14800 const out = Buffer.alloc(size);
14801 num.copy(out);
14802 if (num.length === 0)
14803 out[0] = 0;
14804 return this._createEncoderBuffer(out);
14805 }
14806
14807 if (num < 0x80)
14808 return this._createEncoderBuffer(num);
14809
14810 if (num < 0x100)
14811 return this._createEncoderBuffer([0, num]);
14812
14813 let size = 1;
14814 for (let i = num; i >= 0x100; i >>= 8)
14815 size++;
14816
14817 const out = new Array(size);
14818 for (let i = out.length - 1; i >= 0; i--) {
14819 out[i] = num & 0xff;
14820 num >>= 8;
14821 }
14822 if(out[0] & 0x80) {
14823 out.unshift(0);
14824 }
14825
14826 return this._createEncoderBuffer(Buffer.from(out));
14827};
14828
14829DERNode.prototype._encodeBool = function encodeBool(value) {
14830 return this._createEncoderBuffer(value ? 0xff : 0);
14831};
14832
14833DERNode.prototype._use = function use(entity, obj) {
14834 if (typeof entity === 'function')
14835 entity = entity(obj);
14836 return entity._getEncoder('der').tree;
14837};
14838
14839DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
14840 const state = this._baseState;
14841 let i;
14842 if (state['default'] === null)
14843 return false;
14844
14845 const data = dataBuffer.join();
14846 if (state.defaultBuffer === undefined)
14847 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
14848
14849 if (data.length !== state.defaultBuffer.length)
14850 return false;
14851
14852 for (i=0; i < data.length; i++)
14853 if (data[i] !== state.defaultBuffer[i])
14854 return false;
14855
14856 return true;
14857};
14858
14859// Utility methods
14860
14861function encodeTag(tag, primitive, cls, reporter) {
14862 let res;
14863
14864 if (tag === 'seqof')
14865 tag = 'seq';
14866 else if (tag === 'setof')
14867 tag = 'set';
14868
14869 if (der.tagByName.hasOwnProperty(tag))
14870 res = der.tagByName[tag];
14871 else if (typeof tag === 'number' && (tag | 0) === tag)
14872 res = tag;
14873 else
14874 return reporter.error('Unknown tag: ' + tag);
14875
14876 if (res >= 0x1f)
14877 return reporter.error('Multi-octet tag encoding unsupported');
14878
14879 if (!primitive)
14880 res |= 0x20;
14881
14882 res |= (der.tagClassByName[cls || 'universal'] << 6);
14883
14884 return res;
14885}
14886
14887},{"../base/node":52,"../constants/der":54,"inherits":206,"safer-buffer":257}],60:[function(require,module,exports){
14888'use strict';
14889
14890const encoders = exports;
14891
14892encoders.der = require('./der');
14893encoders.pem = require('./pem');
14894
14895},{"./der":59,"./pem":61}],61:[function(require,module,exports){
14896'use strict';
14897
14898const inherits = require('inherits');
14899
14900const DEREncoder = require('./der');
14901
14902function PEMEncoder(entity) {
14903 DEREncoder.call(this, entity);
14904 this.enc = 'pem';
14905}
14906inherits(PEMEncoder, DEREncoder);
14907module.exports = PEMEncoder;
14908
14909PEMEncoder.prototype.encode = function encode(data, options) {
14910 const buf = DEREncoder.prototype.encode.call(this, data);
14911
14912 const p = buf.toString('base64');
14913 const out = [ '-----BEGIN ' + options.label + '-----' ];
14914 for (let i = 0; i < p.length; i += 64)
14915 out.push(p.slice(i, i + 64));
14916 out.push('-----END ' + options.label + '-----');
14917 return out.join('\n');
14918};
14919
14920},{"./der":59,"inherits":206}],62:[function(require,module,exports){
14921(function (global){(function (){
14922'use strict';
14923
14924var objectAssign = require('object-assign');
14925
14926// compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js
14927// original notice:
14928
14929/*!
14930 * The buffer module from node.js, for the browser.
14931 *
14932 * @author Feross Aboukhadijeh <feross@feross.org> <http://feross.org>
14933 * @license MIT
14934 */
14935function compare(a, b) {
14936 if (a === b) {
14937 return 0;
14938 }
14939
14940 var x = a.length;
14941 var y = b.length;
14942
14943 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
14944 if (a[i] !== b[i]) {
14945 x = a[i];
14946 y = b[i];
14947 break;
14948 }
14949 }
14950
14951 if (x < y) {
14952 return -1;
14953 }
14954 if (y < x) {
14955 return 1;
14956 }
14957 return 0;
14958}
14959function isBuffer(b) {
14960 if (global.Buffer && typeof global.Buffer.isBuffer === 'function') {
14961 return global.Buffer.isBuffer(b);
14962 }
14963 return !!(b != null && b._isBuffer);
14964}
14965
14966// based on node assert, original notice:
14967// NB: The URL to the CommonJS spec is kept just for tradition.
14968// node-assert has evolved a lot since then, both in API and behavior.
14969
14970// http://wiki.commonjs.org/wiki/Unit_Testing/1.0
14971//
14972// THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8!
14973//
14974// Originally from narwhal.js (http://narwhaljs.org)
14975// Copyright (c) 2009 Thomas Robinson <280north.com>
14976//
14977// Permission is hereby granted, free of charge, to any person obtaining a copy
14978// of this software and associated documentation files (the 'Software'), to
14979// deal in the Software without restriction, including without limitation the
14980// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
14981// sell copies of the Software, and to permit persons to whom the Software is
14982// furnished to do so, subject to the following conditions:
14983//
14984// The above copyright notice and this permission notice shall be included in
14985// all copies or substantial portions of the Software.
14986//
14987// THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14988// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
14989// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
14990// AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
14991// ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
14992// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
14993
14994var util = require('util/');
14995var hasOwn = Object.prototype.hasOwnProperty;
14996var pSlice = Array.prototype.slice;
14997var functionsHaveNames = (function () {
14998 return function foo() {}.name === 'foo';
14999}());
15000function pToString (obj) {
15001 return Object.prototype.toString.call(obj);
15002}
15003function isView(arrbuf) {
15004 if (isBuffer(arrbuf)) {
15005 return false;
15006 }
15007 if (typeof global.ArrayBuffer !== 'function') {
15008 return false;
15009 }
15010 if (typeof ArrayBuffer.isView === 'function') {
15011 return ArrayBuffer.isView(arrbuf);
15012 }
15013 if (!arrbuf) {
15014 return false;
15015 }
15016 if (arrbuf instanceof DataView) {
15017 return true;
15018 }
15019 if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) {
15020 return true;
15021 }
15022 return false;
15023}
15024// 1. The assert module provides functions that throw
15025// AssertionError's when particular conditions are not met. The
15026// assert module must conform to the following interface.
15027
15028var assert = module.exports = ok;
15029
15030// 2. The AssertionError is defined in assert.
15031// new assert.AssertionError({ message: message,
15032// actual: actual,
15033// expected: expected })
15034
15035var regex = /\s*function\s+([^\(\s]*)\s*/;
15036// based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js
15037function getName(func) {
15038 if (!util.isFunction(func)) {
15039 return;
15040 }
15041 if (functionsHaveNames) {
15042 return func.name;
15043 }
15044 var str = func.toString();
15045 var match = str.match(regex);
15046 return match && match[1];
15047}
15048assert.AssertionError = function AssertionError(options) {
15049 this.name = 'AssertionError';
15050 this.actual = options.actual;
15051 this.expected = options.expected;
15052 this.operator = options.operator;
15053 if (options.message) {
15054 this.message = options.message;
15055 this.generatedMessage = false;
15056 } else {
15057 this.message = getMessage(this);
15058 this.generatedMessage = true;
15059 }
15060 var stackStartFunction = options.stackStartFunction || fail;
15061 if (Error.captureStackTrace) {
15062 Error.captureStackTrace(this, stackStartFunction);
15063 } else {
15064 // non v8 browsers so we can have a stacktrace
15065 var err = new Error();
15066 if (err.stack) {
15067 var out = err.stack;
15068
15069 // try to strip useless frames
15070 var fn_name = getName(stackStartFunction);
15071 var idx = out.indexOf('\n' + fn_name);
15072 if (idx >= 0) {
15073 // once we have located the function frame
15074 // we need to strip out everything before it (and its line)
15075 var next_line = out.indexOf('\n', idx + 1);
15076 out = out.substring(next_line + 1);
15077 }
15078
15079 this.stack = out;
15080 }
15081 }
15082};
15083
15084// assert.AssertionError instanceof Error
15085util.inherits(assert.AssertionError, Error);
15086
15087function truncate(s, n) {
15088 if (typeof s === 'string') {
15089 return s.length < n ? s : s.slice(0, n);
15090 } else {
15091 return s;
15092 }
15093}
15094function inspect(something) {
15095 if (functionsHaveNames || !util.isFunction(something)) {
15096 return util.inspect(something);
15097 }
15098 var rawname = getName(something);
15099 var name = rawname ? ': ' + rawname : '';
15100 return '[Function' + name + ']';
15101}
15102function getMessage(self) {
15103 return truncate(inspect(self.actual), 128) + ' ' +
15104 self.operator + ' ' +
15105 truncate(inspect(self.expected), 128);
15106}
15107
15108// At present only the three keys mentioned above are used and
15109// understood by the spec. Implementations or sub modules can pass
15110// other keys to the AssertionError's constructor - they will be
15111// ignored.
15112
15113// 3. All of the following functions must throw an AssertionError
15114// when a corresponding condition is not met, with a message that
15115// may be undefined if not provided. All assertion methods provide
15116// both the actual and expected values to the assertion error for
15117// display purposes.
15118
15119function fail(actual, expected, message, operator, stackStartFunction) {
15120 throw new assert.AssertionError({
15121 message: message,
15122 actual: actual,
15123 expected: expected,
15124 operator: operator,
15125 stackStartFunction: stackStartFunction
15126 });
15127}
15128
15129// EXTENSION! allows for well behaved errors defined elsewhere.
15130assert.fail = fail;
15131
15132// 4. Pure assertion tests whether a value is truthy, as determined
15133// by !!guard.
15134// assert.ok(guard, message_opt);
15135// This statement is equivalent to assert.equal(true, !!guard,
15136// message_opt);. To test strictly for the value true, use
15137// assert.strictEqual(true, guard, message_opt);.
15138
15139function ok(value, message) {
15140 if (!value) fail(value, true, message, '==', assert.ok);
15141}
15142assert.ok = ok;
15143
15144// 5. The equality assertion tests shallow, coercive equality with
15145// ==.
15146// assert.equal(actual, expected, message_opt);
15147
15148assert.equal = function equal(actual, expected, message) {
15149 if (actual != expected) fail(actual, expected, message, '==', assert.equal);
15150};
15151
15152// 6. The non-equality assertion tests for whether two objects are not equal
15153// with != assert.notEqual(actual, expected, message_opt);
15154
15155assert.notEqual = function notEqual(actual, expected, message) {
15156 if (actual == expected) {
15157 fail(actual, expected, message, '!=', assert.notEqual);
15158 }
15159};
15160
15161// 7. The equivalence assertion tests a deep equality relation.
15162// assert.deepEqual(actual, expected, message_opt);
15163
15164assert.deepEqual = function deepEqual(actual, expected, message) {
15165 if (!_deepEqual(actual, expected, false)) {
15166 fail(actual, expected, message, 'deepEqual', assert.deepEqual);
15167 }
15168};
15169
15170assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) {
15171 if (!_deepEqual(actual, expected, true)) {
15172 fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual);
15173 }
15174};
15175
15176function _deepEqual(actual, expected, strict, memos) {
15177 // 7.1. All identical values are equivalent, as determined by ===.
15178 if (actual === expected) {
15179 return true;
15180 } else if (isBuffer(actual) && isBuffer(expected)) {
15181 return compare(actual, expected) === 0;
15182
15183 // 7.2. If the expected value is a Date object, the actual value is
15184 // equivalent if it is also a Date object that refers to the same time.
15185 } else if (util.isDate(actual) && util.isDate(expected)) {
15186 return actual.getTime() === expected.getTime();
15187
15188 // 7.3 If the expected value is a RegExp object, the actual value is
15189 // equivalent if it is also a RegExp object with the same source and
15190 // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`).
15191 } else if (util.isRegExp(actual) && util.isRegExp(expected)) {
15192 return actual.source === expected.source &&
15193 actual.global === expected.global &&
15194 actual.multiline === expected.multiline &&
15195 actual.lastIndex === expected.lastIndex &&
15196 actual.ignoreCase === expected.ignoreCase;
15197
15198 // 7.4. Other pairs that do not both pass typeof value == 'object',
15199 // equivalence is determined by ==.
15200 } else if ((actual === null || typeof actual !== 'object') &&
15201 (expected === null || typeof expected !== 'object')) {
15202 return strict ? actual === expected : actual == expected;
15203
15204 // If both values are instances of typed arrays, wrap their underlying
15205 // ArrayBuffers in a Buffer each to increase performance
15206 // This optimization requires the arrays to have the same type as checked by
15207 // Object.prototype.toString (aka pToString). Never perform binary
15208 // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their
15209 // bit patterns are not identical.
15210 } else if (isView(actual) && isView(expected) &&
15211 pToString(actual) === pToString(expected) &&
15212 !(actual instanceof Float32Array ||
15213 actual instanceof Float64Array)) {
15214 return compare(new Uint8Array(actual.buffer),
15215 new Uint8Array(expected.buffer)) === 0;
15216
15217 // 7.5 For all other Object pairs, including Array objects, equivalence is
15218 // determined by having the same number of owned properties (as verified
15219 // with Object.prototype.hasOwnProperty.call), the same set of keys
15220 // (although not necessarily the same order), equivalent values for every
15221 // corresponding key, and an identical 'prototype' property. Note: this
15222 // accounts for both named and indexed properties on Arrays.
15223 } else if (isBuffer(actual) !== isBuffer(expected)) {
15224 return false;
15225 } else {
15226 memos = memos || {actual: [], expected: []};
15227
15228 var actualIndex = memos.actual.indexOf(actual);
15229 if (actualIndex !== -1) {
15230 if (actualIndex === memos.expected.indexOf(expected)) {
15231 return true;
15232 }
15233 }
15234
15235 memos.actual.push(actual);
15236 memos.expected.push(expected);
15237
15238 return objEquiv(actual, expected, strict, memos);
15239 }
15240}
15241
15242function isArguments(object) {
15243 return Object.prototype.toString.call(object) == '[object Arguments]';
15244}
15245
15246function objEquiv(a, b, strict, actualVisitedObjects) {
15247 if (a === null || a === undefined || b === null || b === undefined)
15248 return false;
15249 // if one is a primitive, the other must be same
15250 if (util.isPrimitive(a) || util.isPrimitive(b))
15251 return a === b;
15252 if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b))
15253 return false;
15254 var aIsArgs = isArguments(a);
15255 var bIsArgs = isArguments(b);
15256 if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs))
15257 return false;
15258 if (aIsArgs) {
15259 a = pSlice.call(a);
15260 b = pSlice.call(b);
15261 return _deepEqual(a, b, strict);
15262 }
15263 var ka = objectKeys(a);
15264 var kb = objectKeys(b);
15265 var key, i;
15266 // having the same number of owned properties (keys incorporates
15267 // hasOwnProperty)
15268 if (ka.length !== kb.length)
15269 return false;
15270 //the same set of keys (although not necessarily the same order),
15271 ka.sort();
15272 kb.sort();
15273 //~~~cheap key test
15274 for (i = ka.length - 1; i >= 0; i--) {
15275 if (ka[i] !== kb[i])
15276 return false;
15277 }
15278 //equivalent values for every corresponding key, and
15279 //~~~possibly expensive deep test
15280 for (i = ka.length - 1; i >= 0; i--) {
15281 key = ka[i];
15282 if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects))
15283 return false;
15284 }
15285 return true;
15286}
15287
15288// 8. The non-equivalence assertion tests for any deep inequality.
15289// assert.notDeepEqual(actual, expected, message_opt);
15290
15291assert.notDeepEqual = function notDeepEqual(actual, expected, message) {
15292 if (_deepEqual(actual, expected, false)) {
15293 fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual);
15294 }
15295};
15296
15297assert.notDeepStrictEqual = notDeepStrictEqual;
15298function notDeepStrictEqual(actual, expected, message) {
15299 if (_deepEqual(actual, expected, true)) {
15300 fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual);
15301 }
15302}
15303
15304
15305// 9. The strict equality assertion tests strict equality, as determined by ===.
15306// assert.strictEqual(actual, expected, message_opt);
15307
15308assert.strictEqual = function strictEqual(actual, expected, message) {
15309 if (actual !== expected) {
15310 fail(actual, expected, message, '===', assert.strictEqual);
15311 }
15312};
15313
15314// 10. The strict non-equality assertion tests for strict inequality, as
15315// determined by !==. assert.notStrictEqual(actual, expected, message_opt);
15316
15317assert.notStrictEqual = function notStrictEqual(actual, expected, message) {
15318 if (actual === expected) {
15319 fail(actual, expected, message, '!==', assert.notStrictEqual);
15320 }
15321};
15322
15323function expectedException(actual, expected) {
15324 if (!actual || !expected) {
15325 return false;
15326 }
15327
15328 if (Object.prototype.toString.call(expected) == '[object RegExp]') {
15329 return expected.test(actual);
15330 }
15331
15332 try {
15333 if (actual instanceof expected) {
15334 return true;
15335 }
15336 } catch (e) {
15337 // Ignore. The instanceof check doesn't work for arrow functions.
15338 }
15339
15340 if (Error.isPrototypeOf(expected)) {
15341 return false;
15342 }
15343
15344 return expected.call({}, actual) === true;
15345}
15346
15347function _tryBlock(block) {
15348 var error;
15349 try {
15350 block();
15351 } catch (e) {
15352 error = e;
15353 }
15354 return error;
15355}
15356
15357function _throws(shouldThrow, block, expected, message) {
15358 var actual;
15359
15360 if (typeof block !== 'function') {
15361 throw new TypeError('"block" argument must be a function');
15362 }
15363
15364 if (typeof expected === 'string') {
15365 message = expected;
15366 expected = null;
15367 }
15368
15369 actual = _tryBlock(block);
15370
15371 message = (expected && expected.name ? ' (' + expected.name + ').' : '.') +
15372 (message ? ' ' + message : '.');
15373
15374 if (shouldThrow && !actual) {
15375 fail(actual, expected, 'Missing expected exception' + message);
15376 }
15377
15378 var userProvidedMessage = typeof message === 'string';
15379 var isUnwantedException = !shouldThrow && util.isError(actual);
15380 var isUnexpectedException = !shouldThrow && actual && !expected;
15381
15382 if ((isUnwantedException &&
15383 userProvidedMessage &&
15384 expectedException(actual, expected)) ||
15385 isUnexpectedException) {
15386 fail(actual, expected, 'Got unwanted exception' + message);
15387 }
15388
15389 if ((shouldThrow && actual && expected &&
15390 !expectedException(actual, expected)) || (!shouldThrow && actual)) {
15391 throw actual;
15392 }
15393}
15394
15395// 11. Expected to throw an error:
15396// assert.throws(block, Error_opt, message_opt);
15397
15398assert.throws = function(block, /*optional*/error, /*optional*/message) {
15399 _throws(true, block, error, message);
15400};
15401
15402// EXTENSION! This is annoying to write outside this module.
15403assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) {
15404 _throws(false, block, error, message);
15405};
15406
15407assert.ifError = function(err) { if (err) throw err; };
15408
15409// Expose a strict only variant of assert
15410function strict(value, message) {
15411 if (!value) fail(value, true, message, '==', strict);
15412}
15413assert.strict = objectAssign(strict, assert, {
15414 equal: assert.strictEqual,
15415 deepEqual: assert.deepStrictEqual,
15416 notEqual: assert.notStrictEqual,
15417 notDeepEqual: assert.notDeepStrictEqual
15418});
15419assert.strict.strict = assert.strict;
15420
15421var objectKeys = Object.keys || function (obj) {
15422 var keys = [];
15423 for (var key in obj) {
15424 if (hasOwn.call(obj, key)) keys.push(key);
15425 }
15426 return keys;
15427};
15428
15429}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
15430},{"object-assign":215,"util/":64}],63:[function(require,module,exports){
15431module.exports = function isBuffer(arg) {
15432 return arg && typeof arg === 'object'
15433 && typeof arg.copy === 'function'
15434 && typeof arg.fill === 'function'
15435 && typeof arg.readUInt8 === 'function';
15436}
15437},{}],64:[function(require,module,exports){
15438(function (process,global){(function (){
15439// Copyright Joyent, Inc. and other Node contributors.
15440//
15441// Permission is hereby granted, free of charge, to any person obtaining a
15442// copy of this software and associated documentation files (the
15443// "Software"), to deal in the Software without restriction, including
15444// without limitation the rights to use, copy, modify, merge, publish,
15445// distribute, sublicense, and/or sell copies of the Software, and to permit
15446// persons to whom the Software is furnished to do so, subject to the
15447// following conditions:
15448//
15449// The above copyright notice and this permission notice shall be included
15450// in all copies or substantial portions of the Software.
15451//
15452// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
15453// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
15454// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
15455// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
15456// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
15457// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
15458// USE OR OTHER DEALINGS IN THE SOFTWARE.
15459
15460var formatRegExp = /%[sdj%]/g;
15461exports.format = function(f) {
15462 if (!isString(f)) {
15463 var objects = [];
15464 for (var i = 0; i < arguments.length; i++) {
15465 objects.push(inspect(arguments[i]));
15466 }
15467 return objects.join(' ');
15468 }
15469
15470 var i = 1;
15471 var args = arguments;
15472 var len = args.length;
15473 var str = String(f).replace(formatRegExp, function(x) {
15474 if (x === '%%') return '%';
15475 if (i >= len) return x;
15476 switch (x) {
15477 case '%s': return String(args[i++]);
15478 case '%d': return Number(args[i++]);
15479 case '%j':
15480 try {
15481 return JSON.stringify(args[i++]);
15482 } catch (_) {
15483 return '[Circular]';
15484 }
15485 default:
15486 return x;
15487 }
15488 });
15489 for (var x = args[i]; i < len; x = args[++i]) {
15490 if (isNull(x) || !isObject(x)) {
15491 str += ' ' + x;
15492 } else {
15493 str += ' ' + inspect(x);
15494 }
15495 }
15496 return str;
15497};
15498
15499
15500// Mark that a method should not be used.
15501// Returns a modified function which warns once by default.
15502// If --no-deprecation is set, then it is a no-op.
15503exports.deprecate = function(fn, msg) {
15504 // Allow for deprecating things in the process of starting up.
15505 if (isUndefined(global.process)) {
15506 return function() {
15507 return exports.deprecate(fn, msg).apply(this, arguments);
15508 };
15509 }
15510
15511 if (process.noDeprecation === true) {
15512 return fn;
15513 }
15514
15515 var warned = false;
15516 function deprecated() {
15517 if (!warned) {
15518 if (process.throwDeprecation) {
15519 throw new Error(msg);
15520 } else if (process.traceDeprecation) {
15521 console.trace(msg);
15522 } else {
15523 console.error(msg);
15524 }
15525 warned = true;
15526 }
15527 return fn.apply(this, arguments);
15528 }
15529
15530 return deprecated;
15531};
15532
15533
15534var debugs = {};
15535var debugEnviron;
15536exports.debuglog = function(set) {
15537 if (isUndefined(debugEnviron))
15538 debugEnviron = process.env.NODE_DEBUG || '';
15539 set = set.toUpperCase();
15540 if (!debugs[set]) {
15541 if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) {
15542 var pid = process.pid;
15543 debugs[set] = function() {
15544 var msg = exports.format.apply(exports, arguments);
15545 console.error('%s %d: %s', set, pid, msg);
15546 };
15547 } else {
15548 debugs[set] = function() {};
15549 }
15550 }
15551 return debugs[set];
15552};
15553
15554
15555/**
15556 * Echos the value of a value. Trys to print the value out
15557 * in the best way possible given the different types.
15558 *
15559 * @param {Object} obj The object to print out.
15560 * @param {Object} opts Optional options object that alters the output.
15561 */
15562/* legacy: obj, showHidden, depth, colors*/
15563function inspect(obj, opts) {
15564 // default options
15565 var ctx = {
15566 seen: [],
15567 stylize: stylizeNoColor
15568 };
15569 // legacy...
15570 if (arguments.length >= 3) ctx.depth = arguments[2];
15571 if (arguments.length >= 4) ctx.colors = arguments[3];
15572 if (isBoolean(opts)) {
15573 // legacy...
15574 ctx.showHidden = opts;
15575 } else if (opts) {
15576 // got an "options" object
15577 exports._extend(ctx, opts);
15578 }
15579 // set default options
15580 if (isUndefined(ctx.showHidden)) ctx.showHidden = false;
15581 if (isUndefined(ctx.depth)) ctx.depth = 2;
15582 if (isUndefined(ctx.colors)) ctx.colors = false;
15583 if (isUndefined(ctx.customInspect)) ctx.customInspect = true;
15584 if (ctx.colors) ctx.stylize = stylizeWithColor;
15585 return formatValue(ctx, obj, ctx.depth);
15586}
15587exports.inspect = inspect;
15588
15589
15590// http://en.wikipedia.org/wiki/ANSI_escape_code#graphics
15591inspect.colors = {
15592 'bold' : [1, 22],
15593 'italic' : [3, 23],
15594 'underline' : [4, 24],
15595 'inverse' : [7, 27],
15596 'white' : [37, 39],
15597 'grey' : [90, 39],
15598 'black' : [30, 39],
15599 'blue' : [34, 39],
15600 'cyan' : [36, 39],
15601 'green' : [32, 39],
15602 'magenta' : [35, 39],
15603 'red' : [31, 39],
15604 'yellow' : [33, 39]
15605};
15606
15607// Don't use 'blue' not visible on cmd.exe
15608inspect.styles = {
15609 'special': 'cyan',
15610 'number': 'yellow',
15611 'boolean': 'yellow',
15612 'undefined': 'grey',
15613 'null': 'bold',
15614 'string': 'green',
15615 'date': 'magenta',
15616 // "name": intentionally not styling
15617 'regexp': 'red'
15618};
15619
15620
15621function stylizeWithColor(str, styleType) {
15622 var style = inspect.styles[styleType];
15623
15624 if (style) {
15625 return '\u001b[' + inspect.colors[style][0] + 'm' + str +
15626 '\u001b[' + inspect.colors[style][1] + 'm';
15627 } else {
15628 return str;
15629 }
15630}
15631
15632
15633function stylizeNoColor(str, styleType) {
15634 return str;
15635}
15636
15637
15638function arrayToHash(array) {
15639 var hash = {};
15640
15641 array.forEach(function(val, idx) {
15642 hash[val] = true;
15643 });
15644
15645 return hash;
15646}
15647
15648
15649function formatValue(ctx, value, recurseTimes) {
15650 // Provide a hook for user-specified inspect functions.
15651 // Check that value is an object with an inspect function on it
15652 if (ctx.customInspect &&
15653 value &&
15654 isFunction(value.inspect) &&
15655 // Filter out the util module, it's inspect function is special
15656 value.inspect !== exports.inspect &&
15657 // Also filter out any prototype objects using the circular check.
15658 !(value.constructor && value.constructor.prototype === value)) {
15659 var ret = value.inspect(recurseTimes, ctx);
15660 if (!isString(ret)) {
15661 ret = formatValue(ctx, ret, recurseTimes);
15662 }
15663 return ret;
15664 }
15665
15666 // Primitive types cannot have properties
15667 var primitive = formatPrimitive(ctx, value);
15668 if (primitive) {
15669 return primitive;
15670 }
15671
15672 // Look up the keys of the object.
15673 var keys = Object.keys(value);
15674 var visibleKeys = arrayToHash(keys);
15675
15676 if (ctx.showHidden) {
15677 keys = Object.getOwnPropertyNames(value);
15678 }
15679
15680 // IE doesn't make error fields non-enumerable
15681 // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx
15682 if (isError(value)
15683 && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) {
15684 return formatError(value);
15685 }
15686
15687 // Some type of object without properties can be shortcutted.
15688 if (keys.length === 0) {
15689 if (isFunction(value)) {
15690 var name = value.name ? ': ' + value.name : '';
15691 return ctx.stylize('[Function' + name + ']', 'special');
15692 }
15693 if (isRegExp(value)) {
15694 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
15695 }
15696 if (isDate(value)) {
15697 return ctx.stylize(Date.prototype.toString.call(value), 'date');
15698 }
15699 if (isError(value)) {
15700 return formatError(value);
15701 }
15702 }
15703
15704 var base = '', array = false, braces = ['{', '}'];
15705
15706 // Make Array say that they are Array
15707 if (isArray(value)) {
15708 array = true;
15709 braces = ['[', ']'];
15710 }
15711
15712 // Make functions say that they are functions
15713 if (isFunction(value)) {
15714 var n = value.name ? ': ' + value.name : '';
15715 base = ' [Function' + n + ']';
15716 }
15717
15718 // Make RegExps say that they are RegExps
15719 if (isRegExp(value)) {
15720 base = ' ' + RegExp.prototype.toString.call(value);
15721 }
15722
15723 // Make dates with properties first say the date
15724 if (isDate(value)) {
15725 base = ' ' + Date.prototype.toUTCString.call(value);
15726 }
15727
15728 // Make error with message first say the error
15729 if (isError(value)) {
15730 base = ' ' + formatError(value);
15731 }
15732
15733 if (keys.length === 0 && (!array || value.length == 0)) {
15734 return braces[0] + base + braces[1];
15735 }
15736
15737 if (recurseTimes < 0) {
15738 if (isRegExp(value)) {
15739 return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp');
15740 } else {
15741 return ctx.stylize('[Object]', 'special');
15742 }
15743 }
15744
15745 ctx.seen.push(value);
15746
15747 var output;
15748 if (array) {
15749 output = formatArray(ctx, value, recurseTimes, visibleKeys, keys);
15750 } else {
15751 output = keys.map(function(key) {
15752 return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array);
15753 });
15754 }
15755
15756 ctx.seen.pop();
15757
15758 return reduceToSingleString(output, base, braces);
15759}
15760
15761
15762function formatPrimitive(ctx, value) {
15763 if (isUndefined(value))
15764 return ctx.stylize('undefined', 'undefined');
15765 if (isString(value)) {
15766 var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '')
15767 .replace(/'/g, "\\'")
15768 .replace(/\\"/g, '"') + '\'';
15769 return ctx.stylize(simple, 'string');
15770 }
15771 if (isNumber(value))
15772 return ctx.stylize('' + value, 'number');
15773 if (isBoolean(value))
15774 return ctx.stylize('' + value, 'boolean');
15775 // For some reason typeof null is "object", so special case here.
15776 if (isNull(value))
15777 return ctx.stylize('null', 'null');
15778}
15779
15780
15781function formatError(value) {
15782 return '[' + Error.prototype.toString.call(value) + ']';
15783}
15784
15785
15786function formatArray(ctx, value, recurseTimes, visibleKeys, keys) {
15787 var output = [];
15788 for (var i = 0, l = value.length; i < l; ++i) {
15789 if (hasOwnProperty(value, String(i))) {
15790 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
15791 String(i), true));
15792 } else {
15793 output.push('');
15794 }
15795 }
15796 keys.forEach(function(key) {
15797 if (!key.match(/^\d+$/)) {
15798 output.push(formatProperty(ctx, value, recurseTimes, visibleKeys,
15799 key, true));
15800 }
15801 });
15802 return output;
15803}
15804
15805
15806function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) {
15807 var name, str, desc;
15808 desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] };
15809 if (desc.get) {
15810 if (desc.set) {
15811 str = ctx.stylize('[Getter/Setter]', 'special');
15812 } else {
15813 str = ctx.stylize('[Getter]', 'special');
15814 }
15815 } else {
15816 if (desc.set) {
15817 str = ctx.stylize('[Setter]', 'special');
15818 }
15819 }
15820 if (!hasOwnProperty(visibleKeys, key)) {
15821 name = '[' + key + ']';
15822 }
15823 if (!str) {
15824 if (ctx.seen.indexOf(desc.value) < 0) {
15825 if (isNull(recurseTimes)) {
15826 str = formatValue(ctx, desc.value, null);
15827 } else {
15828 str = formatValue(ctx, desc.value, recurseTimes - 1);
15829 }
15830 if (str.indexOf('\n') > -1) {
15831 if (array) {
15832 str = str.split('\n').map(function(line) {
15833 return ' ' + line;
15834 }).join('\n').substr(2);
15835 } else {
15836 str = '\n' + str.split('\n').map(function(line) {
15837 return ' ' + line;
15838 }).join('\n');
15839 }
15840 }
15841 } else {
15842 str = ctx.stylize('[Circular]', 'special');
15843 }
15844 }
15845 if (isUndefined(name)) {
15846 if (array && key.match(/^\d+$/)) {
15847 return str;
15848 }
15849 name = JSON.stringify('' + key);
15850 if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) {
15851 name = name.substr(1, name.length - 2);
15852 name = ctx.stylize(name, 'name');
15853 } else {
15854 name = name.replace(/'/g, "\\'")
15855 .replace(/\\"/g, '"')
15856 .replace(/(^"|"$)/g, "'");
15857 name = ctx.stylize(name, 'string');
15858 }
15859 }
15860
15861 return name + ': ' + str;
15862}
15863
15864
15865function reduceToSingleString(output, base, braces) {
15866 var numLinesEst = 0;
15867 var length = output.reduce(function(prev, cur) {
15868 numLinesEst++;
15869 if (cur.indexOf('\n') >= 0) numLinesEst++;
15870 return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1;
15871 }, 0);
15872
15873 if (length > 60) {
15874 return braces[0] +
15875 (base === '' ? '' : base + '\n ') +
15876 ' ' +
15877 output.join(',\n ') +
15878 ' ' +
15879 braces[1];
15880 }
15881
15882 return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1];
15883}
15884
15885
15886// NOTE: These type checking functions intentionally don't use `instanceof`
15887// because it is fragile and can be easily faked with `Object.create()`.
15888function isArray(ar) {
15889 return Array.isArray(ar);
15890}
15891exports.isArray = isArray;
15892
15893function isBoolean(arg) {
15894 return typeof arg === 'boolean';
15895}
15896exports.isBoolean = isBoolean;
15897
15898function isNull(arg) {
15899 return arg === null;
15900}
15901exports.isNull = isNull;
15902
15903function isNullOrUndefined(arg) {
15904 return arg == null;
15905}
15906exports.isNullOrUndefined = isNullOrUndefined;
15907
15908function isNumber(arg) {
15909 return typeof arg === 'number';
15910}
15911exports.isNumber = isNumber;
15912
15913function isString(arg) {
15914 return typeof arg === 'string';
15915}
15916exports.isString = isString;
15917
15918function isSymbol(arg) {
15919 return typeof arg === 'symbol';
15920}
15921exports.isSymbol = isSymbol;
15922
15923function isUndefined(arg) {
15924 return arg === void 0;
15925}
15926exports.isUndefined = isUndefined;
15927
15928function isRegExp(re) {
15929 return isObject(re) && objectToString(re) === '[object RegExp]';
15930}
15931exports.isRegExp = isRegExp;
15932
15933function isObject(arg) {
15934 return typeof arg === 'object' && arg !== null;
15935}
15936exports.isObject = isObject;
15937
15938function isDate(d) {
15939 return isObject(d) && objectToString(d) === '[object Date]';
15940}
15941exports.isDate = isDate;
15942
15943function isError(e) {
15944 return isObject(e) &&
15945 (objectToString(e) === '[object Error]' || e instanceof Error);
15946}
15947exports.isError = isError;
15948
15949function isFunction(arg) {
15950 return typeof arg === 'function';
15951}
15952exports.isFunction = isFunction;
15953
15954function isPrimitive(arg) {
15955 return arg === null ||
15956 typeof arg === 'boolean' ||
15957 typeof arg === 'number' ||
15958 typeof arg === 'string' ||
15959 typeof arg === 'symbol' || // ES6 symbol
15960 typeof arg === 'undefined';
15961}
15962exports.isPrimitive = isPrimitive;
15963
15964exports.isBuffer = require('./support/isBuffer');
15965
15966function objectToString(o) {
15967 return Object.prototype.toString.call(o);
15968}
15969
15970
15971function pad(n) {
15972 return n < 10 ? '0' + n.toString(10) : n.toString(10);
15973}
15974
15975
15976var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep',
15977 'Oct', 'Nov', 'Dec'];
15978
15979// 26 Feb 16:19:34
15980function timestamp() {
15981 var d = new Date();
15982 var time = [pad(d.getHours()),
15983 pad(d.getMinutes()),
15984 pad(d.getSeconds())].join(':');
15985 return [d.getDate(), months[d.getMonth()], time].join(' ');
15986}
15987
15988
15989// log is just a thin wrapper to console.log that prepends a timestamp
15990exports.log = function() {
15991 console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments));
15992};
15993
15994
15995/**
15996 * Inherit the prototype methods from one constructor into another.
15997 *
15998 * The Function.prototype.inherits from lang.js rewritten as a standalone
15999 * function (not on Function.prototype). NOTE: If this file is to be loaded
16000 * during bootstrapping this function needs to be rewritten using some native
16001 * functions as prototype setup using normal JavaScript does not work as
16002 * expected during bootstrapping (see mirror.js in r114903).
16003 *
16004 * @param {function} ctor Constructor function which needs to inherit the
16005 * prototype.
16006 * @param {function} superCtor Constructor function to inherit prototype from.
16007 */
16008exports.inherits = require('inherits');
16009
16010exports._extend = function(origin, add) {
16011 // Don't do anything if add isn't an object
16012 if (!add || !isObject(add)) return origin;
16013
16014 var keys = Object.keys(add);
16015 var i = keys.length;
16016 while (i--) {
16017 origin[keys[i]] = add[keys[i]];
16018 }
16019 return origin;
16020};
16021
16022function hasOwnProperty(obj, prop) {
16023 return Object.prototype.hasOwnProperty.call(obj, prop);
16024}
16025
16026}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
16027},{"./support/isBuffer":63,"_process":228,"inherits":206}],65:[function(require,module,exports){
16028'use strict'
16029// base-x encoding / decoding
16030// Copyright (c) 2018 base-x contributors
16031// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)
16032// Distributed under the MIT software license, see the accompanying
16033// file LICENSE or http://www.opensource.org/licenses/mit-license.php.
16034// @ts-ignore
16035var _Buffer = require('safe-buffer').Buffer
16036function base (ALPHABET) {
16037 if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }
16038 var BASE_MAP = new Uint8Array(256)
16039 for (var j = 0; j < BASE_MAP.length; j++) {
16040 BASE_MAP[j] = 255
16041 }
16042 for (var i = 0; i < ALPHABET.length; i++) {
16043 var x = ALPHABET.charAt(i)
16044 var xc = x.charCodeAt(0)
16045 if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }
16046 BASE_MAP[xc] = i
16047 }
16048 var BASE = ALPHABET.length
16049 var LEADER = ALPHABET.charAt(0)
16050 var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up
16051 var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up
16052 function encode (source) {
16053 if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }
16054 if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }
16055 if (source.length === 0) { return '' }
16056 // Skip & count leading zeroes.
16057 var zeroes = 0
16058 var length = 0
16059 var pbegin = 0
16060 var pend = source.length
16061 while (pbegin !== pend && source[pbegin] === 0) {
16062 pbegin++
16063 zeroes++
16064 }
16065 // Allocate enough space in big-endian base58 representation.
16066 var size = ((pend - pbegin) * iFACTOR + 1) >>> 0
16067 var b58 = new Uint8Array(size)
16068 // Process the bytes.
16069 while (pbegin !== pend) {
16070 var carry = source[pbegin]
16071 // Apply "b58 = b58 * 256 + ch".
16072 var i = 0
16073 for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {
16074 carry += (256 * b58[it1]) >>> 0
16075 b58[it1] = (carry % BASE) >>> 0
16076 carry = (carry / BASE) >>> 0
16077 }
16078 if (carry !== 0) { throw new Error('Non-zero carry') }
16079 length = i
16080 pbegin++
16081 }
16082 // Skip leading zeroes in base58 result.
16083 var it2 = size - length
16084 while (it2 !== size && b58[it2] === 0) {
16085 it2++
16086 }
16087 // Translate the result into a string.
16088 var str = LEADER.repeat(zeroes)
16089 for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }
16090 return str
16091 }
16092 function decodeUnsafe (source) {
16093 if (typeof source !== 'string') { throw new TypeError('Expected String') }
16094 if (source.length === 0) { return _Buffer.alloc(0) }
16095 var psz = 0
16096 // Skip leading spaces.
16097 if (source[psz] === ' ') { return }
16098 // Skip and count leading '1's.
16099 var zeroes = 0
16100 var length = 0
16101 while (source[psz] === LEADER) {
16102 zeroes++
16103 psz++
16104 }
16105 // Allocate enough space in big-endian base256 representation.
16106 var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.
16107 var b256 = new Uint8Array(size)
16108 // Process the characters.
16109 while (source[psz]) {
16110 // Decode character
16111 var carry = BASE_MAP[source.charCodeAt(psz)]
16112 // Invalid character
16113 if (carry === 255) { return }
16114 var i = 0
16115 for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {
16116 carry += (BASE * b256[it3]) >>> 0
16117 b256[it3] = (carry % 256) >>> 0
16118 carry = (carry / 256) >>> 0
16119 }
16120 if (carry !== 0) { throw new Error('Non-zero carry') }
16121 length = i
16122 psz++
16123 }
16124 // Skip trailing spaces.
16125 if (source[psz] === ' ') { return }
16126 // Skip leading zeroes in b256.
16127 var it4 = size - length
16128 while (it4 !== size && b256[it4] === 0) {
16129 it4++
16130 }
16131 var vch = _Buffer.allocUnsafe(zeroes + (size - it4))
16132 vch.fill(0x00, 0, zeroes)
16133 var j = zeroes
16134 while (it4 !== size) {
16135 vch[j++] = b256[it4++]
16136 }
16137 return vch
16138 }
16139 function decode (string) {
16140 var buffer = decodeUnsafe(string)
16141 if (buffer) { return buffer }
16142 throw new Error('Non-base' + BASE + ' character')
16143 }
16144 return {
16145 encode: encode,
16146 decodeUnsafe: decodeUnsafe,
16147 decode: decode
16148 }
16149}
16150module.exports = base
16151
16152},{"safe-buffer":256}],66:[function(require,module,exports){
16153'use strict'
16154
16155exports.byteLength = byteLength
16156exports.toByteArray = toByteArray
16157exports.fromByteArray = fromByteArray
16158
16159var lookup = []
16160var revLookup = []
16161var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
16162
16163var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
16164for (var i = 0, len = code.length; i < len; ++i) {
16165 lookup[i] = code[i]
16166 revLookup[code.charCodeAt(i)] = i
16167}
16168
16169// Support decoding URL-safe base64 strings, as Node.js does.
16170// See: https://en.wikipedia.org/wiki/Base64#URL_applications
16171revLookup['-'.charCodeAt(0)] = 62
16172revLookup['_'.charCodeAt(0)] = 63
16173
16174function getLens (b64) {
16175 var len = b64.length
16176
16177 if (len % 4 > 0) {
16178 throw new Error('Invalid string. Length must be a multiple of 4')
16179 }
16180
16181 // Trim off extra bytes after placeholder bytes are found
16182 // See: https://github.com/beatgammit/base64-js/issues/42
16183 var validLen = b64.indexOf('=')
16184 if (validLen === -1) validLen = len
16185
16186 var placeHoldersLen = validLen === len
16187 ? 0
16188 : 4 - (validLen % 4)
16189
16190 return [validLen, placeHoldersLen]
16191}
16192
16193// base64 is 4/3 + up to two characters of the original data
16194function byteLength (b64) {
16195 var lens = getLens(b64)
16196 var validLen = lens[0]
16197 var placeHoldersLen = lens[1]
16198 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
16199}
16200
16201function _byteLength (b64, validLen, placeHoldersLen) {
16202 return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen
16203}
16204
16205function toByteArray (b64) {
16206 var tmp
16207 var lens = getLens(b64)
16208 var validLen = lens[0]
16209 var placeHoldersLen = lens[1]
16210
16211 var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen))
16212
16213 var curByte = 0
16214
16215 // if there are placeholders, only get up to the last complete 4 chars
16216 var len = placeHoldersLen > 0
16217 ? validLen - 4
16218 : validLen
16219
16220 var i
16221 for (i = 0; i < len; i += 4) {
16222 tmp =
16223 (revLookup[b64.charCodeAt(i)] << 18) |
16224 (revLookup[b64.charCodeAt(i + 1)] << 12) |
16225 (revLookup[b64.charCodeAt(i + 2)] << 6) |
16226 revLookup[b64.charCodeAt(i + 3)]
16227 arr[curByte++] = (tmp >> 16) & 0xFF
16228 arr[curByte++] = (tmp >> 8) & 0xFF
16229 arr[curByte++] = tmp & 0xFF
16230 }
16231
16232 if (placeHoldersLen === 2) {
16233 tmp =
16234 (revLookup[b64.charCodeAt(i)] << 2) |
16235 (revLookup[b64.charCodeAt(i + 1)] >> 4)
16236 arr[curByte++] = tmp & 0xFF
16237 }
16238
16239 if (placeHoldersLen === 1) {
16240 tmp =
16241 (revLookup[b64.charCodeAt(i)] << 10) |
16242 (revLookup[b64.charCodeAt(i + 1)] << 4) |
16243 (revLookup[b64.charCodeAt(i + 2)] >> 2)
16244 arr[curByte++] = (tmp >> 8) & 0xFF
16245 arr[curByte++] = tmp & 0xFF
16246 }
16247
16248 return arr
16249}
16250
16251function tripletToBase64 (num) {
16252 return lookup[num >> 18 & 0x3F] +
16253 lookup[num >> 12 & 0x3F] +
16254 lookup[num >> 6 & 0x3F] +
16255 lookup[num & 0x3F]
16256}
16257
16258function encodeChunk (uint8, start, end) {
16259 var tmp
16260 var output = []
16261 for (var i = start; i < end; i += 3) {
16262 tmp =
16263 ((uint8[i] << 16) & 0xFF0000) +
16264 ((uint8[i + 1] << 8) & 0xFF00) +
16265 (uint8[i + 2] & 0xFF)
16266 output.push(tripletToBase64(tmp))
16267 }
16268 return output.join('')
16269}
16270
16271function fromByteArray (uint8) {
16272 var tmp
16273 var len = uint8.length
16274 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
16275 var parts = []
16276 var maxChunkLength = 16383 // must be multiple of 3
16277
16278 // go through the array every three bytes, we'll deal with trailing stuff later
16279 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
16280 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
16281 }
16282
16283 // pad the end with zeros, but make sure to not forget the extra bytes
16284 if (extraBytes === 1) {
16285 tmp = uint8[len - 1]
16286 parts.push(
16287 lookup[tmp >> 2] +
16288 lookup[(tmp << 4) & 0x3F] +
16289 '=='
16290 )
16291 } else if (extraBytes === 2) {
16292 tmp = (uint8[len - 2] << 8) + uint8[len - 1]
16293 parts.push(
16294 lookup[tmp >> 10] +
16295 lookup[(tmp >> 4) & 0x3F] +
16296 lookup[(tmp << 2) & 0x3F] +
16297 '='
16298 )
16299 }
16300
16301 return parts.join('')
16302}
16303
16304},{}],67:[function(require,module,exports){
16305'use strict';
16306Object.defineProperty(exports, "__esModule", { value: true });
16307exports.bech32m = exports.bech32 = void 0;
16308const ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l';
16309const ALPHABET_MAP = {};
16310for (let z = 0; z < ALPHABET.length; z++) {
16311 const x = ALPHABET.charAt(z);
16312 ALPHABET_MAP[x] = z;
16313}
16314function polymodStep(pre) {
16315 const b = pre >> 25;
16316 return (((pre & 0x1ffffff) << 5) ^
16317 (-((b >> 0) & 1) & 0x3b6a57b2) ^
16318 (-((b >> 1) & 1) & 0x26508e6d) ^
16319 (-((b >> 2) & 1) & 0x1ea119fa) ^
16320 (-((b >> 3) & 1) & 0x3d4233dd) ^
16321 (-((b >> 4) & 1) & 0x2a1462b3));
16322}
16323function prefixChk(prefix) {
16324 let chk = 1;
16325 for (let i = 0; i < prefix.length; ++i) {
16326 const c = prefix.charCodeAt(i);
16327 if (c < 33 || c > 126)
16328 return 'Invalid prefix (' + prefix + ')';
16329 chk = polymodStep(chk) ^ (c >> 5);
16330 }
16331 chk = polymodStep(chk);
16332 for (let i = 0; i < prefix.length; ++i) {
16333 const v = prefix.charCodeAt(i);
16334 chk = polymodStep(chk) ^ (v & 0x1f);
16335 }
16336 return chk;
16337}
16338function convert(data, inBits, outBits, pad) {
16339 let value = 0;
16340 let bits = 0;
16341 const maxV = (1 << outBits) - 1;
16342 const result = [];
16343 for (let i = 0; i < data.length; ++i) {
16344 value = (value << inBits) | data[i];
16345 bits += inBits;
16346 while (bits >= outBits) {
16347 bits -= outBits;
16348 result.push((value >> bits) & maxV);
16349 }
16350 }
16351 if (pad) {
16352 if (bits > 0) {
16353 result.push((value << (outBits - bits)) & maxV);
16354 }
16355 }
16356 else {
16357 if (bits >= inBits)
16358 return 'Excess padding';
16359 if ((value << (outBits - bits)) & maxV)
16360 return 'Non-zero padding';
16361 }
16362 return result;
16363}
16364function toWords(bytes) {
16365 return convert(bytes, 8, 5, true);
16366}
16367function fromWordsUnsafe(words) {
16368 const res = convert(words, 5, 8, false);
16369 if (Array.isArray(res))
16370 return res;
16371}
16372function fromWords(words) {
16373 const res = convert(words, 5, 8, false);
16374 if (Array.isArray(res))
16375 return res;
16376 throw new Error(res);
16377}
16378function getLibraryFromEncoding(encoding) {
16379 let ENCODING_CONST;
16380 if (encoding === 'bech32') {
16381 ENCODING_CONST = 1;
16382 }
16383 else {
16384 ENCODING_CONST = 0x2bc830a3;
16385 }
16386 function encode(prefix, words, LIMIT) {
16387 LIMIT = LIMIT || 90;
16388 if (prefix.length + 7 + words.length > LIMIT)
16389 throw new TypeError('Exceeds length limit');
16390 prefix = prefix.toLowerCase();
16391 // determine chk mod
16392 let chk = prefixChk(prefix);
16393 if (typeof chk === 'string')
16394 throw new Error(chk);
16395 let result = prefix + '1';
16396 for (let i = 0; i < words.length; ++i) {
16397 const x = words[i];
16398 if (x >> 5 !== 0)
16399 throw new Error('Non 5-bit word');
16400 chk = polymodStep(chk) ^ x;
16401 result += ALPHABET.charAt(x);
16402 }
16403 for (let i = 0; i < 6; ++i) {
16404 chk = polymodStep(chk);
16405 }
16406 chk ^= ENCODING_CONST;
16407 for (let i = 0; i < 6; ++i) {
16408 const v = (chk >> ((5 - i) * 5)) & 0x1f;
16409 result += ALPHABET.charAt(v);
16410 }
16411 return result;
16412 }
16413 function __decode(str, LIMIT) {
16414 LIMIT = LIMIT || 90;
16415 if (str.length < 8)
16416 return str + ' too short';
16417 if (str.length > LIMIT)
16418 return 'Exceeds length limit';
16419 // don't allow mixed case
16420 const lowered = str.toLowerCase();
16421 const uppered = str.toUpperCase();
16422 if (str !== lowered && str !== uppered)
16423 return 'Mixed-case string ' + str;
16424 str = lowered;
16425 const split = str.lastIndexOf('1');
16426 if (split === -1)
16427 return 'No separator character for ' + str;
16428 if (split === 0)
16429 return 'Missing prefix for ' + str;
16430 const prefix = str.slice(0, split);
16431 const wordChars = str.slice(split + 1);
16432 if (wordChars.length < 6)
16433 return 'Data too short';
16434 let chk = prefixChk(prefix);
16435 if (typeof chk === 'string')
16436 return chk;
16437 const words = [];
16438 for (let i = 0; i < wordChars.length; ++i) {
16439 const c = wordChars.charAt(i);
16440 const v = ALPHABET_MAP[c];
16441 if (v === undefined)
16442 return 'Unknown character ' + c;
16443 chk = polymodStep(chk) ^ v;
16444 // not in the checksum?
16445 if (i + 6 >= wordChars.length)
16446 continue;
16447 words.push(v);
16448 }
16449 if (chk !== ENCODING_CONST)
16450 return 'Invalid checksum for ' + str;
16451 return { prefix, words };
16452 }
16453 function decodeUnsafe(str, LIMIT) {
16454 const res = __decode(str, LIMIT);
16455 if (typeof res === 'object')
16456 return res;
16457 }
16458 function decode(str, LIMIT) {
16459 const res = __decode(str, LIMIT);
16460 if (typeof res === 'object')
16461 return res;
16462 throw new Error(res);
16463 }
16464 return {
16465 decodeUnsafe,
16466 decode,
16467 encode,
16468 toWords,
16469 fromWordsUnsafe,
16470 fromWords,
16471 };
16472}
16473exports.bech32 = getLibraryFromEncoding('bech32');
16474exports.bech32m = getLibraryFromEncoding('bech32m');
16475
16476},{}],68:[function(require,module,exports){
16477// (public) Constructor
16478function BigInteger(a, b, c) {
16479 if (!(this instanceof BigInteger))
16480 return new BigInteger(a, b, c)
16481
16482 if (a != null) {
16483 if ("number" == typeof a) this.fromNumber(a, b, c)
16484 else if (b == null && "string" != typeof a) this.fromString(a, 256)
16485 else this.fromString(a, b)
16486 }
16487}
16488
16489var proto = BigInteger.prototype
16490
16491// duck-typed isBigInteger
16492proto.__bigi = require('../package.json').version
16493BigInteger.isBigInteger = function (obj, check_ver) {
16494 return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi)
16495}
16496
16497// Bits per digit
16498var dbits
16499
16500// am: Compute w_j += (x*this_i), propagate carries,
16501// c is initial carry, returns final carry.
16502// c < 3*dvalue, x < 2*dvalue, this_i < dvalue
16503// We need to select the fastest one that works in this environment.
16504
16505// am1: use a single mult and divide to get the high bits,
16506// max digit bits should be 26 because
16507// max internal value = 2*dvalue^2-2*dvalue (< 2^53)
16508function am1(i, x, w, j, c, n) {
16509 while (--n >= 0) {
16510 var v = x * this[i++] + w[j] + c
16511 c = Math.floor(v / 0x4000000)
16512 w[j++] = v & 0x3ffffff
16513 }
16514 return c
16515}
16516// am2 avoids a big mult-and-extract completely.
16517// Max digit bits should be <= 30 because we do bitwise ops
16518// on values up to 2*hdvalue^2-hdvalue-1 (< 2^31)
16519function am2(i, x, w, j, c, n) {
16520 var xl = x & 0x7fff,
16521 xh = x >> 15
16522 while (--n >= 0) {
16523 var l = this[i] & 0x7fff
16524 var h = this[i++] >> 15
16525 var m = xh * l + h * xl
16526 l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff)
16527 c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30)
16528 w[j++] = l & 0x3fffffff
16529 }
16530 return c
16531}
16532// Alternately, set max digit bits to 28 since some
16533// browsers slow down when dealing with 32-bit numbers.
16534function am3(i, x, w, j, c, n) {
16535 var xl = x & 0x3fff,
16536 xh = x >> 14
16537 while (--n >= 0) {
16538 var l = this[i] & 0x3fff
16539 var h = this[i++] >> 14
16540 var m = xh * l + h * xl
16541 l = xl * l + ((m & 0x3fff) << 14) + w[j] + c
16542 c = (l >> 28) + (m >> 14) + xh * h
16543 w[j++] = l & 0xfffffff
16544 }
16545 return c
16546}
16547
16548// wtf?
16549BigInteger.prototype.am = am1
16550dbits = 26
16551
16552BigInteger.prototype.DB = dbits
16553BigInteger.prototype.DM = ((1 << dbits) - 1)
16554var DV = BigInteger.prototype.DV = (1 << dbits)
16555
16556var BI_FP = 52
16557BigInteger.prototype.FV = Math.pow(2, BI_FP)
16558BigInteger.prototype.F1 = BI_FP - dbits
16559BigInteger.prototype.F2 = 2 * dbits - BI_FP
16560
16561// Digit conversions
16562var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz"
16563var BI_RC = new Array()
16564var rr, vv
16565rr = "0".charCodeAt(0)
16566for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv
16567rr = "a".charCodeAt(0)
16568for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
16569rr = "A".charCodeAt(0)
16570for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv
16571
16572function int2char(n) {
16573 return BI_RM.charAt(n)
16574}
16575
16576function intAt(s, i) {
16577 var c = BI_RC[s.charCodeAt(i)]
16578 return (c == null) ? -1 : c
16579}
16580
16581// (protected) copy this to r
16582function bnpCopyTo(r) {
16583 for (var i = this.t - 1; i >= 0; --i) r[i] = this[i]
16584 r.t = this.t
16585 r.s = this.s
16586}
16587
16588// (protected) set from integer value x, -DV <= x < DV
16589function bnpFromInt(x) {
16590 this.t = 1
16591 this.s = (x < 0) ? -1 : 0
16592 if (x > 0) this[0] = x
16593 else if (x < -1) this[0] = x + DV
16594 else this.t = 0
16595}
16596
16597// return bigint initialized to value
16598function nbv(i) {
16599 var r = new BigInteger()
16600 r.fromInt(i)
16601 return r
16602}
16603
16604// (protected) set from string and radix
16605function bnpFromString(s, b) {
16606 var self = this
16607
16608 var k
16609 if (b == 16) k = 4
16610 else if (b == 8) k = 3
16611 else if (b == 256) k = 8; // byte array
16612 else if (b == 2) k = 1
16613 else if (b == 32) k = 5
16614 else if (b == 4) k = 2
16615 else {
16616 self.fromRadix(s, b)
16617 return
16618 }
16619 self.t = 0
16620 self.s = 0
16621 var i = s.length,
16622 mi = false,
16623 sh = 0
16624 while (--i >= 0) {
16625 var x = (k == 8) ? s[i] & 0xff : intAt(s, i)
16626 if (x < 0) {
16627 if (s.charAt(i) == "-") mi = true
16628 continue
16629 }
16630 mi = false
16631 if (sh == 0)
16632 self[self.t++] = x
16633 else if (sh + k > self.DB) {
16634 self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh
16635 self[self.t++] = (x >> (self.DB - sh))
16636 } else
16637 self[self.t - 1] |= x << sh
16638 sh += k
16639 if (sh >= self.DB) sh -= self.DB
16640 }
16641 if (k == 8 && (s[0] & 0x80) != 0) {
16642 self.s = -1
16643 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh
16644 }
16645 self.clamp()
16646 if (mi) BigInteger.ZERO.subTo(self, self)
16647}
16648
16649// (protected) clamp off excess high words
16650function bnpClamp() {
16651 var c = this.s & this.DM
16652 while (this.t > 0 && this[this.t - 1] == c)--this.t
16653}
16654
16655// (public) return string representation in given radix
16656function bnToString(b) {
16657 var self = this
16658 if (self.s < 0) return "-" + self.negate()
16659 .toString(b)
16660 var k
16661 if (b == 16) k = 4
16662 else if (b == 8) k = 3
16663 else if (b == 2) k = 1
16664 else if (b == 32) k = 5
16665 else if (b == 4) k = 2
16666 else return self.toRadix(b)
16667 var km = (1 << k) - 1,
16668 d, m = false,
16669 r = "",
16670 i = self.t
16671 var p = self.DB - (i * self.DB) % k
16672 if (i-- > 0) {
16673 if (p < self.DB && (d = self[i] >> p) > 0) {
16674 m = true
16675 r = int2char(d)
16676 }
16677 while (i >= 0) {
16678 if (p < k) {
16679 d = (self[i] & ((1 << p) - 1)) << (k - p)
16680 d |= self[--i] >> (p += self.DB - k)
16681 } else {
16682 d = (self[i] >> (p -= k)) & km
16683 if (p <= 0) {
16684 p += self.DB
16685 --i
16686 }
16687 }
16688 if (d > 0) m = true
16689 if (m) r += int2char(d)
16690 }
16691 }
16692 return m ? r : "0"
16693}
16694
16695// (public) -this
16696function bnNegate() {
16697 var r = new BigInteger()
16698 BigInteger.ZERO.subTo(this, r)
16699 return r
16700}
16701
16702// (public) |this|
16703function bnAbs() {
16704 return (this.s < 0) ? this.negate() : this
16705}
16706
16707// (public) return + if this > a, - if this < a, 0 if equal
16708function bnCompareTo(a) {
16709 var r = this.s - a.s
16710 if (r != 0) return r
16711 var i = this.t
16712 r = i - a.t
16713 if (r != 0) return (this.s < 0) ? -r : r
16714 while (--i >= 0)
16715 if ((r = this[i] - a[i]) != 0) return r
16716 return 0
16717}
16718
16719// returns bit length of the integer x
16720function nbits(x) {
16721 var r = 1,
16722 t
16723 if ((t = x >>> 16) != 0) {
16724 x = t
16725 r += 16
16726 }
16727 if ((t = x >> 8) != 0) {
16728 x = t
16729 r += 8
16730 }
16731 if ((t = x >> 4) != 0) {
16732 x = t
16733 r += 4
16734 }
16735 if ((t = x >> 2) != 0) {
16736 x = t
16737 r += 2
16738 }
16739 if ((t = x >> 1) != 0) {
16740 x = t
16741 r += 1
16742 }
16743 return r
16744}
16745
16746// (public) return the number of bits in "this"
16747function bnBitLength() {
16748 if (this.t <= 0) return 0
16749 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM))
16750}
16751
16752// (public) return the number of bytes in "this"
16753function bnByteLength() {
16754 return this.bitLength() >> 3
16755}
16756
16757// (protected) r = this << n*DB
16758function bnpDLShiftTo(n, r) {
16759 var i
16760 for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i]
16761 for (i = n - 1; i >= 0; --i) r[i] = 0
16762 r.t = this.t + n
16763 r.s = this.s
16764}
16765
16766// (protected) r = this >> n*DB
16767function bnpDRShiftTo(n, r) {
16768 for (var i = n; i < this.t; ++i) r[i - n] = this[i]
16769 r.t = Math.max(this.t - n, 0)
16770 r.s = this.s
16771}
16772
16773// (protected) r = this << n
16774function bnpLShiftTo(n, r) {
16775 var self = this
16776 var bs = n % self.DB
16777 var cbs = self.DB - bs
16778 var bm = (1 << cbs) - 1
16779 var ds = Math.floor(n / self.DB),
16780 c = (self.s << bs) & self.DM,
16781 i
16782 for (i = self.t - 1; i >= 0; --i) {
16783 r[i + ds + 1] = (self[i] >> cbs) | c
16784 c = (self[i] & bm) << bs
16785 }
16786 for (i = ds - 1; i >= 0; --i) r[i] = 0
16787 r[ds] = c
16788 r.t = self.t + ds + 1
16789 r.s = self.s
16790 r.clamp()
16791}
16792
16793// (protected) r = this >> n
16794function bnpRShiftTo(n, r) {
16795 var self = this
16796 r.s = self.s
16797 var ds = Math.floor(n / self.DB)
16798 if (ds >= self.t) {
16799 r.t = 0
16800 return
16801 }
16802 var bs = n % self.DB
16803 var cbs = self.DB - bs
16804 var bm = (1 << bs) - 1
16805 r[0] = self[ds] >> bs
16806 for (var i = ds + 1; i < self.t; ++i) {
16807 r[i - ds - 1] |= (self[i] & bm) << cbs
16808 r[i - ds] = self[i] >> bs
16809 }
16810 if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs
16811 r.t = self.t - ds
16812 r.clamp()
16813}
16814
16815// (protected) r = this - a
16816function bnpSubTo(a, r) {
16817 var self = this
16818 var i = 0,
16819 c = 0,
16820 m = Math.min(a.t, self.t)
16821 while (i < m) {
16822 c += self[i] - a[i]
16823 r[i++] = c & self.DM
16824 c >>= self.DB
16825 }
16826 if (a.t < self.t) {
16827 c -= a.s
16828 while (i < self.t) {
16829 c += self[i]
16830 r[i++] = c & self.DM
16831 c >>= self.DB
16832 }
16833 c += self.s
16834 } else {
16835 c += self.s
16836 while (i < a.t) {
16837 c -= a[i]
16838 r[i++] = c & self.DM
16839 c >>= self.DB
16840 }
16841 c -= a.s
16842 }
16843 r.s = (c < 0) ? -1 : 0
16844 if (c < -1) r[i++] = self.DV + c
16845 else if (c > 0) r[i++] = c
16846 r.t = i
16847 r.clamp()
16848}
16849
16850// (protected) r = this * a, r != this,a (HAC 14.12)
16851// "this" should be the larger one if appropriate.
16852function bnpMultiplyTo(a, r) {
16853 var x = this.abs(),
16854 y = a.abs()
16855 var i = x.t
16856 r.t = i + y.t
16857 while (--i >= 0) r[i] = 0
16858 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t)
16859 r.s = 0
16860 r.clamp()
16861 if (this.s != a.s) BigInteger.ZERO.subTo(r, r)
16862}
16863
16864// (protected) r = this^2, r != this (HAC 14.16)
16865function bnpSquareTo(r) {
16866 var x = this.abs()
16867 var i = r.t = 2 * x.t
16868 while (--i >= 0) r[i] = 0
16869 for (i = 0; i < x.t - 1; ++i) {
16870 var c = x.am(i, x[i], r, 2 * i, 0, 1)
16871 if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) {
16872 r[i + x.t] -= x.DV
16873 r[i + x.t + 1] = 1
16874 }
16875 }
16876 if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1)
16877 r.s = 0
16878 r.clamp()
16879}
16880
16881// (protected) divide this by m, quotient and remainder to q, r (HAC 14.20)
16882// r != q, this != m. q or r may be null.
16883function bnpDivRemTo(m, q, r) {
16884 var self = this
16885 var pm = m.abs()
16886 if (pm.t <= 0) return
16887 var pt = self.abs()
16888 if (pt.t < pm.t) {
16889 if (q != null) q.fromInt(0)
16890 if (r != null) self.copyTo(r)
16891 return
16892 }
16893 if (r == null) r = new BigInteger()
16894 var y = new BigInteger(),
16895 ts = self.s,
16896 ms = m.s
16897 var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus
16898 if (nsh > 0) {
16899 pm.lShiftTo(nsh, y)
16900 pt.lShiftTo(nsh, r)
16901 } else {
16902 pm.copyTo(y)
16903 pt.copyTo(r)
16904 }
16905 var ys = y.t
16906 var y0 = y[ys - 1]
16907 if (y0 == 0) return
16908 var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0)
16909 var d1 = self.FV / yt,
16910 d2 = (1 << self.F1) / yt,
16911 e = 1 << self.F2
16912 var i = r.t,
16913 j = i - ys,
16914 t = (q == null) ? new BigInteger() : q
16915 y.dlShiftTo(j, t)
16916 if (r.compareTo(t) >= 0) {
16917 r[r.t++] = 1
16918 r.subTo(t, r)
16919 }
16920 BigInteger.ONE.dlShiftTo(ys, t)
16921 t.subTo(y, y); // "negative" y so we can replace sub with am later
16922 while (y.t < ys) y[y.t++] = 0
16923 while (--j >= 0) {
16924 // Estimate quotient digit
16925 var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2)
16926 if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out
16927 y.dlShiftTo(j, t)
16928 r.subTo(t, r)
16929 while (r[i] < --qd) r.subTo(t, r)
16930 }
16931 }
16932 if (q != null) {
16933 r.drShiftTo(ys, q)
16934 if (ts != ms) BigInteger.ZERO.subTo(q, q)
16935 }
16936 r.t = ys
16937 r.clamp()
16938 if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder
16939 if (ts < 0) BigInteger.ZERO.subTo(r, r)
16940}
16941
16942// (public) this mod a
16943function bnMod(a) {
16944 var r = new BigInteger()
16945 this.abs()
16946 .divRemTo(a, null, r)
16947 if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r)
16948 return r
16949}
16950
16951// Modular reduction using "classic" algorithm
16952function Classic(m) {
16953 this.m = m
16954}
16955
16956function cConvert(x) {
16957 if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m)
16958 else return x
16959}
16960
16961function cRevert(x) {
16962 return x
16963}
16964
16965function cReduce(x) {
16966 x.divRemTo(this.m, null, x)
16967}
16968
16969function cMulTo(x, y, r) {
16970 x.multiplyTo(y, r)
16971 this.reduce(r)
16972}
16973
16974function cSqrTo(x, r) {
16975 x.squareTo(r)
16976 this.reduce(r)
16977}
16978
16979Classic.prototype.convert = cConvert
16980Classic.prototype.revert = cRevert
16981Classic.prototype.reduce = cReduce
16982Classic.prototype.mulTo = cMulTo
16983Classic.prototype.sqrTo = cSqrTo
16984
16985// (protected) return "-1/this % 2^DB"; useful for Mont. reduction
16986// justification:
16987// xy == 1 (mod m)
16988// xy = 1+km
16989// xy(2-xy) = (1+km)(1-km)
16990// x[y(2-xy)] = 1-k^2m^2
16991// x[y(2-xy)] == 1 (mod m^2)
16992// if y is 1/x mod m, then y(2-xy) is 1/x mod m^2
16993// should reduce x and y(2-xy) by m^2 at each step to keep size bounded.
16994// JS multiply "overflows" differently from C/C++, so care is needed here.
16995function bnpInvDigit() {
16996 if (this.t < 1) return 0
16997 var x = this[0]
16998 if ((x & 1) == 0) return 0
16999 var y = x & 3; // y == 1/x mod 2^2
17000 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4
17001 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8
17002 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16
17003 // last step - calculate inverse mod DV directly
17004 // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints
17005 y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits
17006 // we really want the negative inverse, and -DV < y < DV
17007 return (y > 0) ? this.DV - y : -y
17008}
17009
17010// Montgomery reduction
17011function Montgomery(m) {
17012 this.m = m
17013 this.mp = m.invDigit()
17014 this.mpl = this.mp & 0x7fff
17015 this.mph = this.mp >> 15
17016 this.um = (1 << (m.DB - 15)) - 1
17017 this.mt2 = 2 * m.t
17018}
17019
17020// xR mod m
17021function montConvert(x) {
17022 var r = new BigInteger()
17023 x.abs()
17024 .dlShiftTo(this.m.t, r)
17025 r.divRemTo(this.m, null, r)
17026 if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r)
17027 return r
17028}
17029
17030// x/R mod m
17031function montRevert(x) {
17032 var r = new BigInteger()
17033 x.copyTo(r)
17034 this.reduce(r)
17035 return r
17036}
17037
17038// x = x/R mod m (HAC 14.32)
17039function montReduce(x) {
17040 while (x.t <= this.mt2) // pad x so am has enough room later
17041 x[x.t++] = 0
17042 for (var i = 0; i < this.m.t; ++i) {
17043 // faster way of calculating u0 = x[i]*mp mod DV
17044 var j = x[i] & 0x7fff
17045 var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM
17046 // use am to combine the multiply-shift-add into one call
17047 j = i + this.m.t
17048 x[j] += this.m.am(0, u0, x, i, 0, this.m.t)
17049 // propagate carry
17050 while (x[j] >= x.DV) {
17051 x[j] -= x.DV
17052 x[++j]++
17053 }
17054 }
17055 x.clamp()
17056 x.drShiftTo(this.m.t, x)
17057 if (x.compareTo(this.m) >= 0) x.subTo(this.m, x)
17058}
17059
17060// r = "x^2/R mod m"; x != r
17061function montSqrTo(x, r) {
17062 x.squareTo(r)
17063 this.reduce(r)
17064}
17065
17066// r = "xy/R mod m"; x,y != r
17067function montMulTo(x, y, r) {
17068 x.multiplyTo(y, r)
17069 this.reduce(r)
17070}
17071
17072Montgomery.prototype.convert = montConvert
17073Montgomery.prototype.revert = montRevert
17074Montgomery.prototype.reduce = montReduce
17075Montgomery.prototype.mulTo = montMulTo
17076Montgomery.prototype.sqrTo = montSqrTo
17077
17078// (protected) true iff this is even
17079function bnpIsEven() {
17080 return ((this.t > 0) ? (this[0] & 1) : this.s) == 0
17081}
17082
17083// (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79)
17084function bnpExp(e, z) {
17085 if (e > 0xffffffff || e < 1) return BigInteger.ONE
17086 var r = new BigInteger(),
17087 r2 = new BigInteger(),
17088 g = z.convert(this),
17089 i = nbits(e) - 1
17090 g.copyTo(r)
17091 while (--i >= 0) {
17092 z.sqrTo(r, r2)
17093 if ((e & (1 << i)) > 0) z.mulTo(r2, g, r)
17094 else {
17095 var t = r
17096 r = r2
17097 r2 = t
17098 }
17099 }
17100 return z.revert(r)
17101}
17102
17103// (public) this^e % m, 0 <= e < 2^32
17104function bnModPowInt(e, m) {
17105 var z
17106 if (e < 256 || m.isEven()) z = new Classic(m)
17107 else z = new Montgomery(m)
17108 return this.exp(e, z)
17109}
17110
17111// protected
17112proto.copyTo = bnpCopyTo
17113proto.fromInt = bnpFromInt
17114proto.fromString = bnpFromString
17115proto.clamp = bnpClamp
17116proto.dlShiftTo = bnpDLShiftTo
17117proto.drShiftTo = bnpDRShiftTo
17118proto.lShiftTo = bnpLShiftTo
17119proto.rShiftTo = bnpRShiftTo
17120proto.subTo = bnpSubTo
17121proto.multiplyTo = bnpMultiplyTo
17122proto.squareTo = bnpSquareTo
17123proto.divRemTo = bnpDivRemTo
17124proto.invDigit = bnpInvDigit
17125proto.isEven = bnpIsEven
17126proto.exp = bnpExp
17127
17128// public
17129proto.toString = bnToString
17130proto.negate = bnNegate
17131proto.abs = bnAbs
17132proto.compareTo = bnCompareTo
17133proto.bitLength = bnBitLength
17134proto.byteLength = bnByteLength
17135proto.mod = bnMod
17136proto.modPowInt = bnModPowInt
17137
17138// (public)
17139function bnClone() {
17140 var r = new BigInteger()
17141 this.copyTo(r)
17142 return r
17143}
17144
17145// (public) return value as integer
17146function bnIntValue() {
17147 if (this.s < 0) {
17148 if (this.t == 1) return this[0] - this.DV
17149 else if (this.t == 0) return -1
17150 } else if (this.t == 1) return this[0]
17151 else if (this.t == 0) return 0
17152 // assumes 16 < DB < 32
17153 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0]
17154}
17155
17156// (public) return value as byte
17157function bnByteValue() {
17158 return (this.t == 0) ? this.s : (this[0] << 24) >> 24
17159}
17160
17161// (public) return value as short (assumes DB>=16)
17162function bnShortValue() {
17163 return (this.t == 0) ? this.s : (this[0] << 16) >> 16
17164}
17165
17166// (protected) return x s.t. r^x < DV
17167function bnpChunkSize(r) {
17168 return Math.floor(Math.LN2 * this.DB / Math.log(r))
17169}
17170
17171// (public) 0 if this == 0, 1 if this > 0
17172function bnSigNum() {
17173 if (this.s < 0) return -1
17174 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0
17175 else return 1
17176}
17177
17178// (protected) convert to radix string
17179function bnpToRadix(b) {
17180 if (b == null) b = 10
17181 if (this.signum() == 0 || b < 2 || b > 36) return "0"
17182 var cs = this.chunkSize(b)
17183 var a = Math.pow(b, cs)
17184 var d = nbv(a),
17185 y = new BigInteger(),
17186 z = new BigInteger(),
17187 r = ""
17188 this.divRemTo(d, y, z)
17189 while (y.signum() > 0) {
17190 r = (a + z.intValue())
17191 .toString(b)
17192 .substr(1) + r
17193 y.divRemTo(d, y, z)
17194 }
17195 return z.intValue()
17196 .toString(b) + r
17197}
17198
17199// (protected) convert from radix string
17200function bnpFromRadix(s, b) {
17201 var self = this
17202 self.fromInt(0)
17203 if (b == null) b = 10
17204 var cs = self.chunkSize(b)
17205 var d = Math.pow(b, cs),
17206 mi = false,
17207 j = 0,
17208 w = 0
17209 for (var i = 0; i < s.length; ++i) {
17210 var x = intAt(s, i)
17211 if (x < 0) {
17212 if (s.charAt(i) == "-" && self.signum() == 0) mi = true
17213 continue
17214 }
17215 w = b * w + x
17216 if (++j >= cs) {
17217 self.dMultiply(d)
17218 self.dAddOffset(w, 0)
17219 j = 0
17220 w = 0
17221 }
17222 }
17223 if (j > 0) {
17224 self.dMultiply(Math.pow(b, j))
17225 self.dAddOffset(w, 0)
17226 }
17227 if (mi) BigInteger.ZERO.subTo(self, self)
17228}
17229
17230// (protected) alternate constructor
17231function bnpFromNumber(a, b, c) {
17232 var self = this
17233 if ("number" == typeof b) {
17234 // new BigInteger(int,int,RNG)
17235 if (a < 2) self.fromInt(1)
17236 else {
17237 self.fromNumber(a, c)
17238 if (!self.testBit(a - 1)) // force MSB set
17239 self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self)
17240 if (self.isEven()) self.dAddOffset(1, 0); // force odd
17241 while (!self.isProbablePrime(b)) {
17242 self.dAddOffset(2, 0)
17243 if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self)
17244 }
17245 }
17246 } else {
17247 // new BigInteger(int,RNG)
17248 var x = new Array(),
17249 t = a & 7
17250 x.length = (a >> 3) + 1
17251 b.nextBytes(x)
17252 if (t > 0) x[0] &= ((1 << t) - 1)
17253 else x[0] = 0
17254 self.fromString(x, 256)
17255 }
17256}
17257
17258// (public) convert to bigendian byte array
17259function bnToByteArray() {
17260 var self = this
17261 var i = self.t,
17262 r = new Array()
17263 r[0] = self.s
17264 var p = self.DB - (i * self.DB) % 8,
17265 d, k = 0
17266 if (i-- > 0) {
17267 if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p)
17268 r[k++] = d | (self.s << (self.DB - p))
17269 while (i >= 0) {
17270 if (p < 8) {
17271 d = (self[i] & ((1 << p) - 1)) << (8 - p)
17272 d |= self[--i] >> (p += self.DB - 8)
17273 } else {
17274 d = (self[i] >> (p -= 8)) & 0xff
17275 if (p <= 0) {
17276 p += self.DB
17277 --i
17278 }
17279 }
17280 if ((d & 0x80) != 0) d |= -256
17281 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k
17282 if (k > 0 || d != self.s) r[k++] = d
17283 }
17284 }
17285 return r
17286}
17287
17288function bnEquals(a) {
17289 return (this.compareTo(a) == 0)
17290}
17291
17292function bnMin(a) {
17293 return (this.compareTo(a) < 0) ? this : a
17294}
17295
17296function bnMax(a) {
17297 return (this.compareTo(a) > 0) ? this : a
17298}
17299
17300// (protected) r = this op a (bitwise)
17301function bnpBitwiseTo(a, op, r) {
17302 var self = this
17303 var i, f, m = Math.min(a.t, self.t)
17304 for (i = 0; i < m; ++i) r[i] = op(self[i], a[i])
17305 if (a.t < self.t) {
17306 f = a.s & self.DM
17307 for (i = m; i < self.t; ++i) r[i] = op(self[i], f)
17308 r.t = self.t
17309 } else {
17310 f = self.s & self.DM
17311 for (i = m; i < a.t; ++i) r[i] = op(f, a[i])
17312 r.t = a.t
17313 }
17314 r.s = op(self.s, a.s)
17315 r.clamp()
17316}
17317
17318// (public) this & a
17319function op_and(x, y) {
17320 return x & y
17321}
17322
17323function bnAnd(a) {
17324 var r = new BigInteger()
17325 this.bitwiseTo(a, op_and, r)
17326 return r
17327}
17328
17329// (public) this | a
17330function op_or(x, y) {
17331 return x | y
17332}
17333
17334function bnOr(a) {
17335 var r = new BigInteger()
17336 this.bitwiseTo(a, op_or, r)
17337 return r
17338}
17339
17340// (public) this ^ a
17341function op_xor(x, y) {
17342 return x ^ y
17343}
17344
17345function bnXor(a) {
17346 var r = new BigInteger()
17347 this.bitwiseTo(a, op_xor, r)
17348 return r
17349}
17350
17351// (public) this & ~a
17352function op_andnot(x, y) {
17353 return x & ~y
17354}
17355
17356function bnAndNot(a) {
17357 var r = new BigInteger()
17358 this.bitwiseTo(a, op_andnot, r)
17359 return r
17360}
17361
17362// (public) ~this
17363function bnNot() {
17364 var r = new BigInteger()
17365 for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i]
17366 r.t = this.t
17367 r.s = ~this.s
17368 return r
17369}
17370
17371// (public) this << n
17372function bnShiftLeft(n) {
17373 var r = new BigInteger()
17374 if (n < 0) this.rShiftTo(-n, r)
17375 else this.lShiftTo(n, r)
17376 return r
17377}
17378
17379// (public) this >> n
17380function bnShiftRight(n) {
17381 var r = new BigInteger()
17382 if (n < 0) this.lShiftTo(-n, r)
17383 else this.rShiftTo(n, r)
17384 return r
17385}
17386
17387// return index of lowest 1-bit in x, x < 2^31
17388function lbit(x) {
17389 if (x == 0) return -1
17390 var r = 0
17391 if ((x & 0xffff) == 0) {
17392 x >>= 16
17393 r += 16
17394 }
17395 if ((x & 0xff) == 0) {
17396 x >>= 8
17397 r += 8
17398 }
17399 if ((x & 0xf) == 0) {
17400 x >>= 4
17401 r += 4
17402 }
17403 if ((x & 3) == 0) {
17404 x >>= 2
17405 r += 2
17406 }
17407 if ((x & 1) == 0)++r
17408 return r
17409}
17410
17411// (public) returns index of lowest 1-bit (or -1 if none)
17412function bnGetLowestSetBit() {
17413 for (var i = 0; i < this.t; ++i)
17414 if (this[i] != 0) return i * this.DB + lbit(this[i])
17415 if (this.s < 0) return this.t * this.DB
17416 return -1
17417}
17418
17419// return number of 1 bits in x
17420function cbit(x) {
17421 var r = 0
17422 while (x != 0) {
17423 x &= x - 1
17424 ++r
17425 }
17426 return r
17427}
17428
17429// (public) return number of set bits
17430function bnBitCount() {
17431 var r = 0,
17432 x = this.s & this.DM
17433 for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x)
17434 return r
17435}
17436
17437// (public) true iff nth bit is set
17438function bnTestBit(n) {
17439 var j = Math.floor(n / this.DB)
17440 if (j >= this.t) return (this.s != 0)
17441 return ((this[j] & (1 << (n % this.DB))) != 0)
17442}
17443
17444// (protected) this op (1<<n)
17445function bnpChangeBit(n, op) {
17446 var r = BigInteger.ONE.shiftLeft(n)
17447 this.bitwiseTo(r, op, r)
17448 return r
17449}
17450
17451// (public) this | (1<<n)
17452function bnSetBit(n) {
17453 return this.changeBit(n, op_or)
17454}
17455
17456// (public) this & ~(1<<n)
17457function bnClearBit(n) {
17458 return this.changeBit(n, op_andnot)
17459}
17460
17461// (public) this ^ (1<<n)
17462function bnFlipBit(n) {
17463 return this.changeBit(n, op_xor)
17464}
17465
17466// (protected) r = this + a
17467function bnpAddTo(a, r) {
17468 var self = this
17469
17470 var i = 0,
17471 c = 0,
17472 m = Math.min(a.t, self.t)
17473 while (i < m) {
17474 c += self[i] + a[i]
17475 r[i++] = c & self.DM
17476 c >>= self.DB
17477 }
17478 if (a.t < self.t) {
17479 c += a.s
17480 while (i < self.t) {
17481 c += self[i]
17482 r[i++] = c & self.DM
17483 c >>= self.DB
17484 }
17485 c += self.s
17486 } else {
17487 c += self.s
17488 while (i < a.t) {
17489 c += a[i]
17490 r[i++] = c & self.DM
17491 c >>= self.DB
17492 }
17493 c += a.s
17494 }
17495 r.s = (c < 0) ? -1 : 0
17496 if (c > 0) r[i++] = c
17497 else if (c < -1) r[i++] = self.DV + c
17498 r.t = i
17499 r.clamp()
17500}
17501
17502// (public) this + a
17503function bnAdd(a) {
17504 var r = new BigInteger()
17505 this.addTo(a, r)
17506 return r
17507}
17508
17509// (public) this - a
17510function bnSubtract(a) {
17511 var r = new BigInteger()
17512 this.subTo(a, r)
17513 return r
17514}
17515
17516// (public) this * a
17517function bnMultiply(a) {
17518 var r = new BigInteger()
17519 this.multiplyTo(a, r)
17520 return r
17521}
17522
17523// (public) this^2
17524function bnSquare() {
17525 var r = new BigInteger()
17526 this.squareTo(r)
17527 return r
17528}
17529
17530// (public) this / a
17531function bnDivide(a) {
17532 var r = new BigInteger()
17533 this.divRemTo(a, r, null)
17534 return r
17535}
17536
17537// (public) this % a
17538function bnRemainder(a) {
17539 var r = new BigInteger()
17540 this.divRemTo(a, null, r)
17541 return r
17542}
17543
17544// (public) [this/a,this%a]
17545function bnDivideAndRemainder(a) {
17546 var q = new BigInteger(),
17547 r = new BigInteger()
17548 this.divRemTo(a, q, r)
17549 return new Array(q, r)
17550}
17551
17552// (protected) this *= n, this >= 0, 1 < n < DV
17553function bnpDMultiply(n) {
17554 this[this.t] = this.am(0, n - 1, this, 0, 0, this.t)
17555 ++this.t
17556 this.clamp()
17557}
17558
17559// (protected) this += n << w words, this >= 0
17560function bnpDAddOffset(n, w) {
17561 if (n == 0) return
17562 while (this.t <= w) this[this.t++] = 0
17563 this[w] += n
17564 while (this[w] >= this.DV) {
17565 this[w] -= this.DV
17566 if (++w >= this.t) this[this.t++] = 0
17567 ++this[w]
17568 }
17569}
17570
17571// A "null" reducer
17572function NullExp() {}
17573
17574function nNop(x) {
17575 return x
17576}
17577
17578function nMulTo(x, y, r) {
17579 x.multiplyTo(y, r)
17580}
17581
17582function nSqrTo(x, r) {
17583 x.squareTo(r)
17584}
17585
17586NullExp.prototype.convert = nNop
17587NullExp.prototype.revert = nNop
17588NullExp.prototype.mulTo = nMulTo
17589NullExp.prototype.sqrTo = nSqrTo
17590
17591// (public) this^e
17592function bnPow(e) {
17593 return this.exp(e, new NullExp())
17594}
17595
17596// (protected) r = lower n words of "this * a", a.t <= n
17597// "this" should be the larger one if appropriate.
17598function bnpMultiplyLowerTo(a, n, r) {
17599 var i = Math.min(this.t + a.t, n)
17600 r.s = 0; // assumes a,this >= 0
17601 r.t = i
17602 while (i > 0) r[--i] = 0
17603 var j
17604 for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t)
17605 for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i)
17606 r.clamp()
17607}
17608
17609// (protected) r = "this * a" without lower n words, n > 0
17610// "this" should be the larger one if appropriate.
17611function bnpMultiplyUpperTo(a, n, r) {
17612 --n
17613 var i = r.t = this.t + a.t - n
17614 r.s = 0; // assumes a,this >= 0
17615 while (--i >= 0) r[i] = 0
17616 for (i = Math.max(n - this.t, 0); i < a.t; ++i)
17617 r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n)
17618 r.clamp()
17619 r.drShiftTo(1, r)
17620}
17621
17622// Barrett modular reduction
17623function Barrett(m) {
17624 // setup Barrett
17625 this.r2 = new BigInteger()
17626 this.q3 = new BigInteger()
17627 BigInteger.ONE.dlShiftTo(2 * m.t, this.r2)
17628 this.mu = this.r2.divide(m)
17629 this.m = m
17630}
17631
17632function barrettConvert(x) {
17633 if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m)
17634 else if (x.compareTo(this.m) < 0) return x
17635 else {
17636 var r = new BigInteger()
17637 x.copyTo(r)
17638 this.reduce(r)
17639 return r
17640 }
17641}
17642
17643function barrettRevert(x) {
17644 return x
17645}
17646
17647// x = x mod m (HAC 14.42)
17648function barrettReduce(x) {
17649 var self = this
17650 x.drShiftTo(self.m.t - 1, self.r2)
17651 if (x.t > self.m.t + 1) {
17652 x.t = self.m.t + 1
17653 x.clamp()
17654 }
17655 self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3)
17656 self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2)
17657 while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1)
17658 x.subTo(self.r2, x)
17659 while (x.compareTo(self.m) >= 0) x.subTo(self.m, x)
17660}
17661
17662// r = x^2 mod m; x != r
17663function barrettSqrTo(x, r) {
17664 x.squareTo(r)
17665 this.reduce(r)
17666}
17667
17668// r = x*y mod m; x,y != r
17669function barrettMulTo(x, y, r) {
17670 x.multiplyTo(y, r)
17671 this.reduce(r)
17672}
17673
17674Barrett.prototype.convert = barrettConvert
17675Barrett.prototype.revert = barrettRevert
17676Barrett.prototype.reduce = barrettReduce
17677Barrett.prototype.mulTo = barrettMulTo
17678Barrett.prototype.sqrTo = barrettSqrTo
17679
17680// (public) this^e % m (HAC 14.85)
17681function bnModPow(e, m) {
17682 var i = e.bitLength(),
17683 k, r = nbv(1),
17684 z
17685 if (i <= 0) return r
17686 else if (i < 18) k = 1
17687 else if (i < 48) k = 3
17688 else if (i < 144) k = 4
17689 else if (i < 768) k = 5
17690 else k = 6
17691 if (i < 8)
17692 z = new Classic(m)
17693 else if (m.isEven())
17694 z = new Barrett(m)
17695 else
17696 z = new Montgomery(m)
17697
17698 // precomputation
17699 var g = new Array(),
17700 n = 3,
17701 k1 = k - 1,
17702 km = (1 << k) - 1
17703 g[1] = z.convert(this)
17704 if (k > 1) {
17705 var g2 = new BigInteger()
17706 z.sqrTo(g[1], g2)
17707 while (n <= km) {
17708 g[n] = new BigInteger()
17709 z.mulTo(g2, g[n - 2], g[n])
17710 n += 2
17711 }
17712 }
17713
17714 var j = e.t - 1,
17715 w, is1 = true,
17716 r2 = new BigInteger(),
17717 t
17718 i = nbits(e[j]) - 1
17719 while (j >= 0) {
17720 if (i >= k1) w = (e[j] >> (i - k1)) & km
17721 else {
17722 w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i)
17723 if (j > 0) w |= e[j - 1] >> (this.DB + i - k1)
17724 }
17725
17726 n = k
17727 while ((w & 1) == 0) {
17728 w >>= 1
17729 --n
17730 }
17731 if ((i -= n) < 0) {
17732 i += this.DB
17733 --j
17734 }
17735 if (is1) { // ret == 1, don't bother squaring or multiplying it
17736 g[w].copyTo(r)
17737 is1 = false
17738 } else {
17739 while (n > 1) {
17740 z.sqrTo(r, r2)
17741 z.sqrTo(r2, r)
17742 n -= 2
17743 }
17744 if (n > 0) z.sqrTo(r, r2)
17745 else {
17746 t = r
17747 r = r2
17748 r2 = t
17749 }
17750 z.mulTo(r2, g[w], r)
17751 }
17752
17753 while (j >= 0 && (e[j] & (1 << i)) == 0) {
17754 z.sqrTo(r, r2)
17755 t = r
17756 r = r2
17757 r2 = t
17758 if (--i < 0) {
17759 i = this.DB - 1
17760 --j
17761 }
17762 }
17763 }
17764 return z.revert(r)
17765}
17766
17767// (public) gcd(this,a) (HAC 14.54)
17768function bnGCD(a) {
17769 var x = (this.s < 0) ? this.negate() : this.clone()
17770 var y = (a.s < 0) ? a.negate() : a.clone()
17771 if (x.compareTo(y) < 0) {
17772 var t = x
17773 x = y
17774 y = t
17775 }
17776 var i = x.getLowestSetBit(),
17777 g = y.getLowestSetBit()
17778 if (g < 0) return x
17779 if (i < g) g = i
17780 if (g > 0) {
17781 x.rShiftTo(g, x)
17782 y.rShiftTo(g, y)
17783 }
17784 while (x.signum() > 0) {
17785 if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x)
17786 if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y)
17787 if (x.compareTo(y) >= 0) {
17788 x.subTo(y, x)
17789 x.rShiftTo(1, x)
17790 } else {
17791 y.subTo(x, y)
17792 y.rShiftTo(1, y)
17793 }
17794 }
17795 if (g > 0) y.lShiftTo(g, y)
17796 return y
17797}
17798
17799// (protected) this % n, n < 2^26
17800function bnpModInt(n) {
17801 if (n <= 0) return 0
17802 var d = this.DV % n,
17803 r = (this.s < 0) ? n - 1 : 0
17804 if (this.t > 0)
17805 if (d == 0) r = this[0] % n
17806 else
17807 for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n
17808 return r
17809}
17810
17811// (public) 1/this % m (HAC 14.61)
17812function bnModInverse(m) {
17813 var ac = m.isEven()
17814 if (this.signum() === 0) throw new Error('division by zero')
17815 if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO
17816 var u = m.clone(),
17817 v = this.clone()
17818 var a = nbv(1),
17819 b = nbv(0),
17820 c = nbv(0),
17821 d = nbv(1)
17822 while (u.signum() != 0) {
17823 while (u.isEven()) {
17824 u.rShiftTo(1, u)
17825 if (ac) {
17826 if (!a.isEven() || !b.isEven()) {
17827 a.addTo(this, a)
17828 b.subTo(m, b)
17829 }
17830 a.rShiftTo(1, a)
17831 } else if (!b.isEven()) b.subTo(m, b)
17832 b.rShiftTo(1, b)
17833 }
17834 while (v.isEven()) {
17835 v.rShiftTo(1, v)
17836 if (ac) {
17837 if (!c.isEven() || !d.isEven()) {
17838 c.addTo(this, c)
17839 d.subTo(m, d)
17840 }
17841 c.rShiftTo(1, c)
17842 } else if (!d.isEven()) d.subTo(m, d)
17843 d.rShiftTo(1, d)
17844 }
17845 if (u.compareTo(v) >= 0) {
17846 u.subTo(v, u)
17847 if (ac) a.subTo(c, a)
17848 b.subTo(d, b)
17849 } else {
17850 v.subTo(u, v)
17851 if (ac) c.subTo(a, c)
17852 d.subTo(b, d)
17853 }
17854 }
17855 if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO
17856 while (d.compareTo(m) >= 0) d.subTo(m, d)
17857 while (d.signum() < 0) d.addTo(m, d)
17858 return d
17859}
17860
17861var lowprimes = [
17862 2, 3, 5, 7, 11, 13, 17, 19, 23, 29, 31, 37, 41, 43, 47, 53, 59, 61, 67, 71,
17863 73, 79, 83, 89, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139, 149, 151,
17864 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211, 223, 227, 229, 233,
17865 239, 241, 251, 257, 263, 269, 271, 277, 281, 283, 293, 307, 311, 313, 317,
17866 331, 337, 347, 349, 353, 359, 367, 373, 379, 383, 389, 397, 401, 409, 419,
17867 421, 431, 433, 439, 443, 449, 457, 461, 463, 467, 479, 487, 491, 499, 503,
17868 509, 521, 523, 541, 547, 557, 563, 569, 571, 577, 587, 593, 599, 601, 607,
17869 613, 617, 619, 631, 641, 643, 647, 653, 659, 661, 673, 677, 683, 691, 701,
17870 709, 719, 727, 733, 739, 743, 751, 757, 761, 769, 773, 787, 797, 809, 811,
17871 821, 823, 827, 829, 839, 853, 857, 859, 863, 877, 881, 883, 887, 907, 911,
17872 919, 929, 937, 941, 947, 953, 967, 971, 977, 983, 991, 997
17873]
17874
17875var lplim = (1 << 26) / lowprimes[lowprimes.length - 1]
17876
17877// (public) test primality with certainty >= 1-.5^t
17878function bnIsProbablePrime(t) {
17879 var i, x = this.abs()
17880 if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) {
17881 for (i = 0; i < lowprimes.length; ++i)
17882 if (x[0] == lowprimes[i]) return true
17883 return false
17884 }
17885 if (x.isEven()) return false
17886 i = 1
17887 while (i < lowprimes.length) {
17888 var m = lowprimes[i],
17889 j = i + 1
17890 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++]
17891 m = x.modInt(m)
17892 while (i < j) if (m % lowprimes[i++] == 0) return false
17893 }
17894 return x.millerRabin(t)
17895}
17896
17897// (protected) true if probably prime (HAC 4.24, Miller-Rabin)
17898function bnpMillerRabin(t) {
17899 var n1 = this.subtract(BigInteger.ONE)
17900 var k = n1.getLowestSetBit()
17901 if (k <= 0) return false
17902 var r = n1.shiftRight(k)
17903 t = (t + 1) >> 1
17904 if (t > lowprimes.length) t = lowprimes.length
17905 var a = new BigInteger(null)
17906 var j, bases = []
17907 for (var i = 0; i < t; ++i) {
17908 for (;;) {
17909 j = lowprimes[Math.floor(Math.random() * lowprimes.length)]
17910 if (bases.indexOf(j) == -1) break
17911 }
17912 bases.push(j)
17913 a.fromInt(j)
17914 var y = a.modPow(r, this)
17915 if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) {
17916 var j = 1
17917 while (j++ < k && y.compareTo(n1) != 0) {
17918 y = y.modPowInt(2, this)
17919 if (y.compareTo(BigInteger.ONE) == 0) return false
17920 }
17921 if (y.compareTo(n1) != 0) return false
17922 }
17923 }
17924 return true
17925}
17926
17927// protected
17928proto.chunkSize = bnpChunkSize
17929proto.toRadix = bnpToRadix
17930proto.fromRadix = bnpFromRadix
17931proto.fromNumber = bnpFromNumber
17932proto.bitwiseTo = bnpBitwiseTo
17933proto.changeBit = bnpChangeBit
17934proto.addTo = bnpAddTo
17935proto.dMultiply = bnpDMultiply
17936proto.dAddOffset = bnpDAddOffset
17937proto.multiplyLowerTo = bnpMultiplyLowerTo
17938proto.multiplyUpperTo = bnpMultiplyUpperTo
17939proto.modInt = bnpModInt
17940proto.millerRabin = bnpMillerRabin
17941
17942// public
17943proto.clone = bnClone
17944proto.intValue = bnIntValue
17945proto.byteValue = bnByteValue
17946proto.shortValue = bnShortValue
17947proto.signum = bnSigNum
17948proto.toByteArray = bnToByteArray
17949proto.equals = bnEquals
17950proto.min = bnMin
17951proto.max = bnMax
17952proto.and = bnAnd
17953proto.or = bnOr
17954proto.xor = bnXor
17955proto.andNot = bnAndNot
17956proto.not = bnNot
17957proto.shiftLeft = bnShiftLeft
17958proto.shiftRight = bnShiftRight
17959proto.getLowestSetBit = bnGetLowestSetBit
17960proto.bitCount = bnBitCount
17961proto.testBit = bnTestBit
17962proto.setBit = bnSetBit
17963proto.clearBit = bnClearBit
17964proto.flipBit = bnFlipBit
17965proto.add = bnAdd
17966proto.subtract = bnSubtract
17967proto.multiply = bnMultiply
17968proto.divide = bnDivide
17969proto.remainder = bnRemainder
17970proto.divideAndRemainder = bnDivideAndRemainder
17971proto.modPow = bnModPow
17972proto.modInverse = bnModInverse
17973proto.pow = bnPow
17974proto.gcd = bnGCD
17975proto.isProbablePrime = bnIsProbablePrime
17976
17977// JSBN-specific extension
17978proto.square = bnSquare
17979
17980// constants
17981BigInteger.ZERO = nbv(0)
17982BigInteger.ONE = nbv(1)
17983BigInteger.valueOf = nbv
17984
17985module.exports = BigInteger
17986
17987},{"../package.json":71}],69:[function(require,module,exports){
17988(function (Buffer){(function (){
17989// FIXME: Kind of a weird way to throw exceptions, consider removing
17990var assert = require('assert')
17991var BigInteger = require('./bigi')
17992
17993/**
17994 * Turns a byte array into a big integer.
17995 *
17996 * This function will interpret a byte array as a big integer in big
17997 * endian notation.
17998 */
17999BigInteger.fromByteArrayUnsigned = function(byteArray) {
18000 // BigInteger expects a DER integer conformant byte array
18001 if (byteArray[0] & 0x80) {
18002 return new BigInteger([0].concat(byteArray))
18003 }
18004
18005 return new BigInteger(byteArray)
18006}
18007
18008/**
18009 * Returns a byte array representation of the big integer.
18010 *
18011 * This returns the absolute of the contained value in big endian
18012 * form. A value of zero results in an empty array.
18013 */
18014BigInteger.prototype.toByteArrayUnsigned = function() {
18015 var byteArray = this.toByteArray()
18016 return byteArray[0] === 0 ? byteArray.slice(1) : byteArray
18017}
18018
18019BigInteger.fromDERInteger = function(byteArray) {
18020 return new BigInteger(byteArray)
18021}
18022
18023/*
18024 * Converts BigInteger to a DER integer representation.
18025 *
18026 * The format for this value uses the most significant bit as a sign
18027 * bit. If the most significant bit is already set and the integer is
18028 * positive, a 0x00 is prepended.
18029 *
18030 * Examples:
18031 *
18032 * 0 => 0x00
18033 * 1 => 0x01
18034 * -1 => 0xff
18035 * 127 => 0x7f
18036 * -127 => 0x81
18037 * 128 => 0x0080
18038 * -128 => 0x80
18039 * 255 => 0x00ff
18040 * -255 => 0xff01
18041 * 16300 => 0x3fac
18042 * -16300 => 0xc054
18043 * 62300 => 0x00f35c
18044 * -62300 => 0xff0ca4
18045*/
18046BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray
18047
18048BigInteger.fromBuffer = function(buffer) {
18049 // BigInteger expects a DER integer conformant byte array
18050 if (buffer[0] & 0x80) {
18051 var byteArray = Array.prototype.slice.call(buffer)
18052
18053 return new BigInteger([0].concat(byteArray))
18054 }
18055
18056 return new BigInteger(buffer)
18057}
18058
18059BigInteger.fromHex = function(hex) {
18060 if (hex === '') return BigInteger.ZERO
18061
18062 assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string')
18063 assert.equal(hex.length % 2, 0, 'Incomplete hex')
18064 return new BigInteger(hex, 16)
18065}
18066
18067BigInteger.prototype.toBuffer = function(size) {
18068 var byteArray = this.toByteArrayUnsigned()
18069 var zeros = []
18070
18071 var padding = size - byteArray.length
18072 while (zeros.length < padding) zeros.push(0)
18073
18074 return new Buffer(zeros.concat(byteArray))
18075}
18076
18077BigInteger.prototype.toHex = function(size) {
18078 return this.toBuffer(size).toString('hex')
18079}
18080
18081}).call(this)}).call(this,require("buffer").Buffer)
18082},{"./bigi":68,"assert":62,"buffer":132}],70:[function(require,module,exports){
18083var BigInteger = require('./bigi')
18084
18085//addons
18086require('./convert')
18087
18088module.exports = BigInteger
18089},{"./bigi":68,"./convert":69}],71:[function(require,module,exports){
18090module.exports={
18091 "_args": [
18092 [
18093 "bigi@1.4.2",
18094 "/home/justin/repos/bitcore/packages/bitcore-lib"
18095 ]
18096 ],
18097 "_from": "bigi@1.4.2",
18098 "_id": "bigi@1.4.2",
18099 "_inBundle": false,
18100 "_integrity": "sha1-nGZalfiLiwj8Bc/XMfVhhZ1yWCU=",
18101 "_location": "/bigi",
18102 "_phantomChildren": {},
18103 "_requested": {
18104 "type": "version",
18105 "registry": true,
18106 "raw": "bigi@1.4.2",
18107 "name": "bigi",
18108 "escapedName": "bigi",
18109 "rawSpec": "1.4.2",
18110 "saveSpec": null,
18111 "fetchSpec": "1.4.2"
18112 },
18113 "_requiredBy": [
18114 "/bip-schnorr",
18115 "/ecurve"
18116 ],
18117 "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz",
18118 "_spec": "1.4.2",
18119 "_where": "/home/justin/repos/bitcore/packages/bitcore-lib",
18120 "bugs": {
18121 "url": "https://github.com/cryptocoinjs/bigi/issues"
18122 },
18123 "dependencies": {},
18124 "description": "Big integers.",
18125 "devDependencies": {
18126 "coveralls": "^2.11.2",
18127 "istanbul": "^0.3.5",
18128 "jshint": "^2.5.1",
18129 "mocha": "^2.1.0",
18130 "mochify": "^2.1.0"
18131 },
18132 "homepage": "https://github.com/cryptocoinjs/bigi#readme",
18133 "keywords": [
18134 "cryptography",
18135 "math",
18136 "bitcoin",
18137 "arbitrary",
18138 "precision",
18139 "arithmetic",
18140 "big",
18141 "integer",
18142 "int",
18143 "number",
18144 "biginteger",
18145 "bigint",
18146 "bignumber",
18147 "decimal",
18148 "float"
18149 ],
18150 "main": "./lib/index.js",
18151 "name": "bigi",
18152 "repository": {
18153 "url": "git+https://github.com/cryptocoinjs/bigi.git",
18154 "type": "git"
18155 },
18156 "scripts": {
18157 "browser-test": "mochify --wd -R spec",
18158 "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js",
18159 "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info",
18160 "jshint": "jshint --config jshint.json lib/*.js ; true",
18161 "test": "_mocha -- test/*.js",
18162 "unit": "mocha"
18163 },
18164 "testling": {
18165 "files": "test/*.js",
18166 "harness": "mocha",
18167 "browsers": [
18168 "ie/9..latest",
18169 "firefox/latest",
18170 "chrome/latest",
18171 "safari/6.0..latest",
18172 "iphone/6.0..latest",
18173 "android-browser/4.2..latest"
18174 ]
18175 },
18176 "version": "1.4.2"
18177}
18178
18179},{}],72:[function(require,module,exports){
18180/*! safe-buffer. MIT License. Feross Aboukhadijeh <https://feross.org/opensource> */
18181/* eslint-disable node/no-deprecated-api */
18182var buffer = require('buffer')
18183var Buffer = buffer.Buffer
18184
18185// alternative to using Object.keys for old browsers
18186function copyProps (src, dst) {
18187 for (var key in src) {
18188 dst[key] = src[key]
18189 }
18190}
18191if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
18192 module.exports = buffer
18193} else {
18194 // Copy properties from require('buffer')
18195 copyProps(buffer, exports)
18196 exports.Buffer = SafeBuffer
18197}
18198
18199function SafeBuffer (arg, encodingOrOffset, length) {
18200 return Buffer(arg, encodingOrOffset, length)
18201}
18202
18203SafeBuffer.prototype = Object.create(Buffer.prototype)
18204
18205// Copy static methods from Buffer
18206copyProps(Buffer, SafeBuffer)
18207
18208SafeBuffer.from = function (arg, encodingOrOffset, length) {
18209 if (typeof arg === 'number') {
18210 throw new TypeError('Argument must not be a number')
18211 }
18212 return Buffer(arg, encodingOrOffset, length)
18213}
18214
18215SafeBuffer.alloc = function (size, fill, encoding) {
18216 if (typeof size !== 'number') {
18217 throw new TypeError('Argument must be a number')
18218 }
18219 var buf = Buffer(size)
18220 if (fill !== undefined) {
18221 if (typeof encoding === 'string') {
18222 buf.fill(fill, encoding)
18223 } else {
18224 buf.fill(fill)
18225 }
18226 } else {
18227 buf.fill(0)
18228 }
18229 return buf
18230}
18231
18232SafeBuffer.allocUnsafe = function (size) {
18233 if (typeof size !== 'number') {
18234 throw new TypeError('Argument must be a number')
18235 }
18236 return Buffer(size)
18237}
18238
18239SafeBuffer.allocUnsafeSlow = function (size) {
18240 if (typeof size !== 'number') {
18241 throw new TypeError('Argument must be a number')
18242 }
18243 return buffer.SlowBuffer(size)
18244}
18245
18246},{"buffer":132}],73:[function(require,module,exports){
18247const BigInteger = require('bigi');
18248const Buffer = require('safe-buffer').Buffer;
18249const ecurve = require('ecurve');
18250const curve = ecurve.getCurveByName('secp256k1');
18251
18252const one = BigInteger.ONE;
18253const n = curve.n;
18254const p = curve.p;
18255
18256function checkBuffer(name, buf, len, idx) {
18257 const idxStr = (idx !== undefined ? '[' + idx + ']' : '');
18258 if (!Buffer.isBuffer(buf)) {
18259 throw new Error(name + idxStr + ' must be a Buffer');
18260 }
18261 if (buf.length !== len) {
18262 throw new Error(name + idxStr + ' must be ' + len + ' bytes long');
18263 }
18264}
18265
18266function checkArray(name, arr) {
18267 if (!arr || !arr.length) {
18268 throw new Error(name + ' must be an array with one or more elements');
18269 }
18270}
18271
18272function checkPubKeyArr(pubKeys) {
18273 checkArray('pubKeys', pubKeys);
18274 for (let i = 0; i < pubKeys.length; i++) {
18275 checkBuffer('pubKey', pubKeys[i], 32, i);
18276 }
18277}
18278
18279function checkMessageArr(messages) {
18280 checkArray('messages', messages);
18281 for (let i = 0; i < messages.length; i++) {
18282 checkBuffer('message', messages[i], 32, i);
18283 }
18284}
18285
18286function checkSignatureArr(signatures) {
18287 checkArray('signatures', signatures);
18288 for (let i = 0; i < signatures.length; i++) {
18289 checkBuffer('signature', signatures[i], 64, i);
18290 }
18291}
18292
18293function checkNonceArr(nonces) {
18294 checkArray('nonces', nonces);
18295 for (let i = 0; i < nonces.length; i++) {
18296 checkBuffer('nonce', nonces[i], 32, i);
18297 }
18298}
18299
18300function checkPrivateKey(privateKey, idx) {
18301 const idxStr = (idx !== undefined ? '[' + idx + ']' : '');
18302 if (!BigInteger.isBigInteger(privateKey) && !(typeof privateKey == 'string')) {
18303 throw new Error('privateKey' + idxStr + ' must be a BigInteger or valid hex string');
18304 }
18305
18306 if (typeof(privateKey) == 'string') {
18307 if (privateKey.match(/[^a-f^A-F^0-9]+/)) {
18308 throw new Error('privateKey must be a BigInteger or valid hex string');
18309 }
18310
18311 checkRange('privateKey', BigInteger.fromHex(privateKey));
18312 return
18313 }
18314
18315 checkRange('privateKey', privateKey);
18316}
18317
18318function checkSignParams(privateKey, message) {
18319 checkPrivateKey(privateKey);
18320 checkBuffer('message', message, 32);
18321}
18322
18323function checkVerifyParams(pubKey, message, signature) {
18324 checkBuffer('pubKey', pubKey, 32);
18325 checkBuffer('message', message, 32);
18326 checkBuffer('signature', signature, 64);
18327}
18328
18329function checkBatchVerifyParams(pubKeys, messages, signatures) {
18330 checkPubKeyArr(pubKeys);
18331 checkMessageArr(messages);
18332 checkSignatureArr(signatures);
18333 if (pubKeys.length !== messages.length || messages.length !== signatures.length) {
18334 throw new Error('all parameters must be an array with the same length')
18335 }
18336}
18337
18338function checkSessionParams(sessionId, privateKey, message, pubKeyCombined, ell) {
18339 checkSignParams(privateKey, message);
18340 checkBuffer('sessionId', sessionId, 32);
18341 checkBuffer('pubKeyCombined', pubKeyCombined, 32);
18342 checkBuffer('ell', ell, 32);
18343}
18344
18345function checkRange(name, scalar) {
18346 if (scalar.compareTo(one) < 0 || scalar.compareTo(n.subtract(one)) > 0) {
18347 throw new Error(name + ' must be an integer in the range 1..n-1')
18348 }
18349}
18350
18351function checkSignatureInput(r, s) {
18352 if (r.compareTo(p) >= 0) {
18353 throw new Error('r is larger than or equal to field size');
18354 }
18355 if (s.compareTo(n) >= 0) {
18356 throw new Error('s is larger than or equal to curve order');
18357 }
18358}
18359
18360function checkPointExists(pubKeyEven, P) {
18361 if (P.curve.isInfinity(P)) {
18362 throw new Error('point is at infinity');
18363 }
18364 const pEven = P.affineY.isEven();
18365 if (pubKeyEven !== pEven) {
18366 throw new Error('point does not exist');
18367 }
18368}
18369
18370function checkAux(aux) {
18371 if (aux.length !== 32) {
18372 throw new Error('aux must be 32 bytes');
18373 }
18374}
18375
18376module.exports = {
18377 checkSessionParams,
18378 checkSignParams,
18379 checkVerifyParams,
18380 checkBatchVerifyParams,
18381 checkRange,
18382 checkSignatureInput,
18383 checkPointExists,
18384 checkPubKeyArr,
18385 checkArray,
18386 checkNonceArr,
18387 checkAux,
18388};
18389
18390},{"bigi":70,"ecurve":153,"safe-buffer":72}],74:[function(require,module,exports){
18391const BigInteger = require('bigi');
18392const Buffer = require('safe-buffer').Buffer;
18393const sha256 = require('js-sha256');
18394
18395function bufferToInt(buffer) {
18396 return BigInteger.fromBuffer(buffer);
18397}
18398
18399function intToBuffer(bigInteger) {
18400 return bigInteger.toBuffer(32);
18401}
18402
18403function hash(buffer) {
18404 return Buffer.from(sha256.create().update(buffer).array());
18405}
18406
18407module.exports = {
18408 bufferToInt,
18409 intToBuffer,
18410 hash,
18411};
18412
18413},{"bigi":70,"js-sha256":209,"safe-buffer":72}],75:[function(require,module,exports){
18414const schnorr = require('./schnorr');
18415schnorr.check = require('./check');
18416schnorr.convert = require('./convert');
18417schnorr.math = require('./math');
18418schnorr.muSig = require('./mu-sig');
18419schnorr.taproot = require('./taproot');
18420
18421module.exports = schnorr;
18422
18423},{"./check":73,"./convert":74,"./math":76,"./mu-sig":77,"./schnorr":78,"./taproot":79}],76:[function(require,module,exports){
18424const BigInteger = require('bigi');
18425const Buffer = require('safe-buffer').Buffer;
18426const ecurve = require('ecurve');
18427const randomBytes = require('randombytes');
18428const curve = ecurve.getCurveByName('secp256k1');
18429const check = require('./check');
18430const convert = require('./convert');
18431
18432const concat = Buffer.concat;
18433const G = curve.G;
18434const p = curve.p;
18435const n = curve.n;
18436const zero = BigInteger.ZERO;
18437const one = BigInteger.ONE;
18438const two = BigInteger.valueOf(2);
18439const three = BigInteger.valueOf(3);
18440const four = BigInteger.valueOf(4);
18441const seven = BigInteger.valueOf(7);
18442
18443function deterministicGetK0(privateKey, publicKey, message) {
18444 check.checkSignParams(privateKey, message);
18445
18446 const h = taggedHash('BIP0340/nonce', concat([convert.intToBuffer(privateKey), publicKey, message]));
18447 const i = convert.bufferToInt(h);
18448 return i.mod(n);
18449}
18450
18451function isEven(pubKey) {
18452 return pubKey.affineY.mod(two).equals(zero);
18453}
18454
18455function getEvenKey(pubKey, privateKey) {
18456 if (isEven(pubKey)) {
18457 return privateKey.clone();
18458 }
18459
18460 return n.subtract(privateKey);
18461}
18462
18463function getE(Rx, Px, m) {
18464 const hash = taggedHash('BIP0340/challenge', concat([Rx, Px, m]));
18465 return convert.bufferToInt(hash).mod(n);
18466}
18467
18468function getR(s, e, P) {
18469 const sG = G.multiply(s);
18470 const eP = P.multiply(e);
18471 return sG.add(eP.negate());
18472}
18473
18474function taggedHash(tag, msg) {
18475 const tagHash = convert.hash(tag);
18476 return convert.hash(concat([tagHash, tagHash, Buffer.from(msg)]));
18477}
18478
18479function liftX(Px) {
18480 const x = convert.bufferToInt(Px);
18481
18482 const c = x.pow(three).add(seven).mod(p);
18483 const y = c.modPow(p.add(one).divide(four), p);
18484 if (c.compareTo(y.modPow(two, p)) !== 0) {
18485 throw new Error('c is not equal to y^2');
18486 }
18487 let P = ecurve.Point.fromAffine(curve, x, y);
18488 if (!isEven(P)) {
18489 P = ecurve.Point.fromAffine(curve, x, p.subtract(y));
18490 }
18491
18492 check.checkPointExists(true, P);
18493 return P;
18494}
18495
18496function randomA() {
18497 let a = null;
18498 for (; ;) {
18499 a = convert.bufferToInt(Buffer.from(randomBytes(32)));
18500 try {
18501 check.checkRange('a', a);
18502 return a;
18503 } catch (e) {
18504 // out of range, generate another one
18505 }
18506 }
18507}
18508
18509module.exports = {
18510 deterministicGetK0,
18511 isEven,
18512 getEvenKey,
18513 getE,
18514 getR,
18515 taggedHash,
18516 liftX,
18517 randomA,
18518};
18519
18520},{"./check":73,"./convert":74,"bigi":70,"ecurve":153,"randombytes":238,"safe-buffer":72}],77:[function(require,module,exports){
18521const Buffer = require('safe-buffer').Buffer;
18522const ecurve = require('ecurve');
18523const curve = ecurve.getCurveByName('secp256k1');
18524const math = require('./math');
18525const check = require('./check');
18526const convert = require('./convert');
18527
18528const concat = Buffer.concat;
18529const G = curve.G;
18530const n = curve.n;
18531const MUSIG_TAG = convert.hash(Buffer.from('MuSig coefficient'));
18532
18533// Computes ell = SHA256(pubKeys[0], ..., pubKeys[pubKeys.length-1]) with
18534// pubKeys serialized in compressed form.
18535function computeEll(pubKeys) {
18536 check.checkPubKeyArr(pubKeys);
18537 return convert.hash(concat(pubKeys))
18538}
18539
18540function computeCoefficient(ell, idx) {
18541 const idxBuf = Buffer.alloc(4);
18542 idxBuf.writeUInt32LE(idx);
18543 const data = concat([MUSIG_TAG, MUSIG_TAG, ell, idxBuf]);
18544 return convert.bufferToInt(convert.hash(data)).mod(n);
18545}
18546
18547function pubKeyCombine(pubKeys, pubKeyHash) {
18548 const ell = pubKeyHash || computeEll(pubKeys);
18549 let X = null;
18550 for (let i = 0; i < pubKeys.length; i++) {
18551 const Xi = math.liftX(pubKeys[i]);
18552 const coefficient = computeCoefficient(ell, i);
18553 const summand = Xi.multiply(coefficient);
18554 if (X === null) {
18555 X = summand;
18556 } else {
18557 X = X.add(summand);
18558 }
18559 }
18560 return X;
18561}
18562
18563function sessionInitialize(sessionId, privateKey, message, pubKeyCombined, pkParity, ell, idx) {
18564 check.checkSessionParams(sessionId, privateKey, message, pubKeyCombined, ell);
18565
18566 const session = {
18567 sessionId,
18568 message,
18569 pubKeyCombined,
18570 pkParity,
18571 ell,
18572 idx,
18573 };
18574
18575 const coefficient = computeCoefficient(ell, idx);
18576 session.secretKey = privateKey.multiply(coefficient).mod(n);
18577 session.ownKeyParity = math.isEven(G.multiply(privateKey));
18578 if (session.pkParity !== session.ownKeyParity) {
18579 session.secretKey = n.subtract(session.secretKey);
18580 }
18581
18582 const nonceData = concat([sessionId, message, session.pubKeyCombined, convert.intToBuffer(privateKey)]);
18583 session.secretNonce = convert.bufferToInt(convert.hash(nonceData));
18584 check.checkRange('secretNonce', session.secretNonce);
18585 const R = G.multiply(session.secretNonce);
18586 session.nonce = convert.intToBuffer(R.affineX);
18587 session.nonceParity = math.isEven(R);
18588 session.commitment = convert.hash(session.nonce);
18589 return session;
18590}
18591
18592function sessionNonceCombine(session, nonces) {
18593 check.checkNonceArr(nonces);
18594 let R = math.liftX(nonces[0]);
18595 for (let i = 1; i < nonces.length; i++) {
18596 R = R.add(math.liftX(nonces[i]));
18597 }
18598 session.combinedNonceParity = math.isEven(R);
18599 return convert.intToBuffer(R.affineX);
18600}
18601
18602function partialSign(session, message, nonceCombined, pubKeyCombined) {
18603 const e = math.getE(nonceCombined, pubKeyCombined, message);
18604 const sk = session.secretKey;
18605 let k = session.secretNonce;
18606 if (session.nonceParity !== session.combinedNonceParity) {
18607 k = n.subtract(k);
18608 }
18609 return sk.multiply(e).add(k).mod(n);
18610}
18611
18612function partialSigVerify(session, partialSig, nonceCombined, idx, pubKey, nonce) {
18613 let e = math.getE(nonceCombined, session.pubKeyCombined, session.message);
18614 const coefficient = computeCoefficient(session.ell, idx);
18615 const Pj = math.liftX(pubKey);
18616 const Ri = math.liftX(nonce);
18617
18618 if (!session.pkParity) {
18619 e = n.subtract(e);
18620 }
18621
18622 let RP = math.getR(partialSig, e.multiply(coefficient).mod(n), Pj);
18623 if (session.combinedNonceParity) {
18624 RP = RP.negate();
18625 }
18626 const sum = RP.add(Ri);
18627 if (!sum.curve.isInfinity(sum)) {
18628 throw new Error('partial signature verification failed');
18629 }
18630}
18631
18632function partialSigCombine(nonceCombined, partialSigs) {
18633 const R = math.liftX(nonceCombined);
18634 check.checkArray('partialSigs', partialSigs);
18635 const Rx = convert.intToBuffer(R.affineX);
18636 let s = partialSigs[0];
18637 for (let i = 1; i < partialSigs.length; i++) {
18638 s = s.add(partialSigs[i]).mod(n);
18639 }
18640 return concat([Rx, convert.intToBuffer(s)]);
18641}
18642
18643module.exports = {
18644 computeEll,
18645 computeCoefficient,
18646 pubKeyCombine,
18647 sessionInitialize,
18648 sessionNonceCombine,
18649 partialSign,
18650 partialSigVerify,
18651 partialSigCombine,
18652};
18653
18654},{"./check":73,"./convert":74,"./math":76,"ecurve":153,"safe-buffer":72}],78:[function(require,module,exports){
18655const BigInteger = require('bigi');
18656const Buffer = require('safe-buffer').Buffer;
18657const ecurve = require('ecurve');
18658const curve = ecurve.getCurveByName('secp256k1');
18659const math = require('./math');
18660const check = require('./check');
18661const convert = require('./convert');
18662
18663const concat = Buffer.concat;
18664const G = curve.G;
18665const p = curve.p;
18666const n = curve.n;
18667const zero = BigInteger.ZERO;
18668
18669function sign(privateKey, message, aux) {
18670 // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#signing
18671 check.checkSignParams(privateKey, message);
18672 privateKey = typeof (privateKey) == 'string' ? BigInteger.fromHex(privateKey) : privateKey;
18673
18674 const P = G.multiply(privateKey);
18675 const Px = convert.intToBuffer(P.affineX);
18676
18677 const d = math.getEvenKey(P, privateKey);
18678 let kPrime
18679 if (aux) {
18680 check.checkAux(aux);
18681
18682 const t = convert.intToBuffer(d.xor(convert.bufferToInt(math.taggedHash('BIP0340/aux', aux))));
18683 const rand = math.taggedHash('BIP0340/nonce', concat([t, Px, message]))
18684 kPrime = convert.bufferToInt(rand).mod(n);
18685 } else {
18686 kPrime = math.deterministicGetK0(d, Px, message);
18687 }
18688
18689 if (kPrime.signum() === 0) {
18690 throw new Error('kPrime is zero');
18691 }
18692
18693 const R = G.multiply(kPrime);
18694 const k = math.getEvenKey(R, kPrime);
18695 const Rx = convert.intToBuffer(R.affineX);
18696 const e = math.getE(Rx, Px, message);
18697 return concat([Rx, convert.intToBuffer(k.add(e.multiply(d)).mod(n))]);
18698}
18699
18700function verify(pubKey, message, signature) {
18701 check.checkVerifyParams(pubKey, message, signature);
18702
18703 // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#verification
18704 const P = math.liftX(pubKey);
18705 const Px = convert.intToBuffer(P.affineX);
18706 const r = convert.bufferToInt(signature.slice(0, 32));
18707 const s = convert.bufferToInt(signature.slice(32, 64));
18708 check.checkSignatureInput(r, s);
18709 const e = math.getE(convert.intToBuffer(r), Px, message);
18710 const R = math.getR(s, e, P);
18711 if (R.curve.isInfinity(R) || !math.isEven(R) || !R.affineX.equals(r)) {
18712 throw new Error('signature verification failed');
18713 }
18714}
18715
18716function batchVerify(pubKeys, messages, signatures) {
18717 check.checkBatchVerifyParams(pubKeys, messages, signatures);
18718
18719 // https://github.com/bitcoin/bips/blob/master/bip-0340.mediawiki#Batch_Verification
18720 let leftSide = zero;
18721 let rightSide = null;
18722 for (let i = 0; i < pubKeys.length; i++) {
18723 const P = math.liftX(pubKeys[i]);
18724 const Px = convert.intToBuffer(P.affineX);
18725 const r = convert.bufferToInt(signatures[i].slice(0, 32));
18726 const s = convert.bufferToInt(signatures[i].slice(32, 64));
18727 check.checkSignatureInput(r, s);
18728 const e = math.getE(convert.intToBuffer(r), Px, messages[i]);
18729 const R = math.liftX(signatures[i].slice(0, 32));
18730
18731 if (i === 0) {
18732 leftSide = leftSide.add(s);
18733 rightSide = R;
18734 rightSide = rightSide.add(P.multiply(e));
18735 } else {
18736 const a = math.randomA();
18737 leftSide = leftSide.add(a.multiply(s));
18738 rightSide = rightSide.add(R.multiply(a));
18739 rightSide = rightSide.add(P.multiply(a.multiply(e)));
18740 }
18741 }
18742
18743 if (!G.multiply(leftSide).equals(rightSide)) {
18744 throw new Error('signature verification failed');
18745 }
18746}
18747
18748module.exports = {
18749 sign,
18750 verify,
18751 batchVerify,
18752};
18753
18754},{"./check":73,"./convert":74,"./math":76,"bigi":70,"ecurve":153,"safe-buffer":72}],79:[function(require,module,exports){
18755const Buffer = require('safe-buffer').Buffer;
18756const ecurve = require('ecurve');
18757const curve = ecurve.getCurveByName('secp256k1');
18758const math = require('./math');
18759const convert = require('./convert');
18760
18761const concat = Buffer.concat;
18762const G = curve.G;
18763
18764function taprootConstruct(pubKey, scripts) {
18765 // If the spending conditions do not require a script path, the output key should commit to an unspendable script path
18766 // instead of having no script path. This can be achieved by computing the output key point as
18767 // Q = P + int(hashTapTweak(bytes(P)))G.
18768 // https://en.bitcoin.it/wiki/BIP_0341#cite_note-22
18769 if (!scripts) {
18770 scripts = [];
18771 }
18772 const h = taprootTree(scripts);
18773 const Px = convert.intToBuffer(pubKey.affineX);
18774 const P = math.liftX(Px);
18775 const tweak = convert.bufferToInt(math.taggedHash('TapTweak', concat([Px, h])));
18776 const Q = P.add(G.multiply(tweak));
18777 return convert.intToBuffer(Q.affineX);
18778}
18779
18780function taprootTree(scripts) {
18781 let h = Buffer.alloc(32, 0);
18782 if (!scripts || scripts.length === 0) {
18783 return new Buffer(0);
18784 }
18785
18786 // TODO(guggero): Implement script part.
18787 return h;
18788}
18789
18790module.exports = {
18791 taprootConstruct,
18792};
18793
18794},{"./convert":74,"./math":76,"ecurve":153,"safe-buffer":72}],80:[function(require,module,exports){
18795(function (module, exports) {
18796 'use strict';
18797
18798 // Utils
18799 function assert (val, msg) {
18800 if (!val) throw new Error(msg || 'Assertion failed');
18801 }
18802
18803 // Could use `inherits` module, but don't want to move from single file
18804 // architecture yet.
18805 function inherits (ctor, superCtor) {
18806 ctor.super_ = superCtor;
18807 var TempCtor = function () {};
18808 TempCtor.prototype = superCtor.prototype;
18809 ctor.prototype = new TempCtor();
18810 ctor.prototype.constructor = ctor;
18811 }
18812
18813 // BN
18814
18815 function BN (number, base, endian) {
18816 if (BN.isBN(number)) {
18817 return number;
18818 }
18819
18820 this.negative = 0;
18821 this.words = null;
18822 this.length = 0;
18823
18824 // Reduction context
18825 this.red = null;
18826
18827 if (number !== null) {
18828 if (base === 'le' || base === 'be') {
18829 endian = base;
18830 base = 10;
18831 }
18832
18833 this._init(number || 0, base || 10, endian || 'be');
18834 }
18835 }
18836 if (typeof module === 'object') {
18837 module.exports = BN;
18838 } else {
18839 exports.BN = BN;
18840 }
18841
18842 BN.BN = BN;
18843 BN.wordSize = 26;
18844
18845 var Buffer;
18846 try {
18847 Buffer = require('buffer').Buffer;
18848 } catch (e) {
18849 }
18850
18851 BN.isBN = function isBN (num) {
18852 if (num instanceof BN) {
18853 return true;
18854 }
18855
18856 return num !== null && typeof num === 'object' &&
18857 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
18858 };
18859
18860 BN.max = function max (left, right) {
18861 if (left.cmp(right) > 0) return left;
18862 return right;
18863 };
18864
18865 BN.min = function min (left, right) {
18866 if (left.cmp(right) < 0) return left;
18867 return right;
18868 };
18869
18870 BN.prototype._init = function init (number, base, endian) {
18871 if (typeof number === 'number') {
18872 return this._initNumber(number, base, endian);
18873 }
18874
18875 if (typeof number === 'object') {
18876 return this._initArray(number, base, endian);
18877 }
18878
18879 if (base === 'hex') {
18880 base = 16;
18881 }
18882 assert(base === (base | 0) && base >= 2 && base <= 36);
18883
18884 number = number.toString().replace(/\s+/g, '');
18885 var start = 0;
18886 if (number[0] === '-') {
18887 start++;
18888 }
18889
18890 if (base === 16) {
18891 this._parseHex(number, start);
18892 } else {
18893 this._parseBase(number, base, start);
18894 }
18895
18896 if (number[0] === '-') {
18897 this.negative = 1;
18898 }
18899
18900 this.strip();
18901
18902 if (endian !== 'le') return;
18903
18904 this._initArray(this.toArray(), base, endian);
18905 };
18906
18907 BN.prototype._initNumber = function _initNumber (number, base, endian) {
18908 if (number < 0) {
18909 this.negative = 1;
18910 number = -number;
18911 }
18912 if (number < 0x4000000) {
18913 this.words = [ number & 0x3ffffff ];
18914 this.length = 1;
18915 } else if (number < 0x10000000000000) {
18916 this.words = [
18917 number & 0x3ffffff,
18918 (number / 0x4000000) & 0x3ffffff
18919 ];
18920 this.length = 2;
18921 } else {
18922 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
18923 this.words = [
18924 number & 0x3ffffff,
18925 (number / 0x4000000) & 0x3ffffff,
18926 1
18927 ];
18928 this.length = 3;
18929 }
18930
18931 if (endian !== 'le') return;
18932
18933 // Reverse the bytes
18934 this._initArray(this.toArray(), base, endian);
18935 };
18936
18937 BN.prototype._initArray = function _initArray (number, base, endian) {
18938 // Perhaps a Uint8Array
18939 assert(typeof number.length === 'number');
18940 if (number.length <= 0) {
18941 this.words = [ 0 ];
18942 this.length = 1;
18943 return this;
18944 }
18945
18946 this.length = Math.ceil(number.length / 3);
18947 this.words = new Array(this.length);
18948 for (var i = 0; i < this.length; i++) {
18949 this.words[i] = 0;
18950 }
18951
18952 var j, w;
18953 var off = 0;
18954 if (endian === 'be') {
18955 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
18956 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
18957 this.words[j] |= (w << off) & 0x3ffffff;
18958 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
18959 off += 24;
18960 if (off >= 26) {
18961 off -= 26;
18962 j++;
18963 }
18964 }
18965 } else if (endian === 'le') {
18966 for (i = 0, j = 0; i < number.length; i += 3) {
18967 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
18968 this.words[j] |= (w << off) & 0x3ffffff;
18969 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
18970 off += 24;
18971 if (off >= 26) {
18972 off -= 26;
18973 j++;
18974 }
18975 }
18976 }
18977 return this.strip();
18978 };
18979
18980 function parseHex (str, start, end) {
18981 var r = 0;
18982 var len = Math.min(str.length, end);
18983 for (var i = start; i < len; i++) {
18984 var c = str.charCodeAt(i) - 48;
18985
18986 r <<= 4;
18987
18988 // 'a' - 'f'
18989 if (c >= 49 && c <= 54) {
18990 r |= c - 49 + 0xa;
18991
18992 // 'A' - 'F'
18993 } else if (c >= 17 && c <= 22) {
18994 r |= c - 17 + 0xa;
18995
18996 // '0' - '9'
18997 } else {
18998 r |= c & 0xf;
18999 }
19000 }
19001 return r;
19002 }
19003
19004 BN.prototype._parseHex = function _parseHex (number, start) {
19005 // Create possibly bigger array to ensure that it fits the number
19006 this.length = Math.ceil((number.length - start) / 6);
19007 this.words = new Array(this.length);
19008 for (var i = 0; i < this.length; i++) {
19009 this.words[i] = 0;
19010 }
19011
19012 var j, w;
19013 // Scan 24-bit chunks and add them to the number
19014 var off = 0;
19015 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
19016 w = parseHex(number, i, i + 6);
19017 this.words[j] |= (w << off) & 0x3ffffff;
19018 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
19019 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
19020 off += 24;
19021 if (off >= 26) {
19022 off -= 26;
19023 j++;
19024 }
19025 }
19026 if (i + 6 !== start) {
19027 w = parseHex(number, start, i + 6);
19028 this.words[j] |= (w << off) & 0x3ffffff;
19029 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
19030 }
19031 this.strip();
19032 };
19033
19034 function parseBase (str, start, end, mul) {
19035 var r = 0;
19036 var len = Math.min(str.length, end);
19037 for (var i = start; i < len; i++) {
19038 var c = str.charCodeAt(i) - 48;
19039
19040 r *= mul;
19041
19042 // 'a'
19043 if (c >= 49) {
19044 r += c - 49 + 0xa;
19045
19046 // 'A'
19047 } else if (c >= 17) {
19048 r += c - 17 + 0xa;
19049
19050 // '0' - '9'
19051 } else {
19052 r += c;
19053 }
19054 }
19055 return r;
19056 }
19057
19058 BN.prototype._parseBase = function _parseBase (number, base, start) {
19059 // Initialize as zero
19060 this.words = [ 0 ];
19061 this.length = 1;
19062
19063 // Find length of limb in base
19064 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
19065 limbLen++;
19066 }
19067 limbLen--;
19068 limbPow = (limbPow / base) | 0;
19069
19070 var total = number.length - start;
19071 var mod = total % limbLen;
19072 var end = Math.min(total, total - mod) + start;
19073
19074 var word = 0;
19075 for (var i = start; i < end; i += limbLen) {
19076 word = parseBase(number, i, i + limbLen, base);
19077
19078 this.imuln(limbPow);
19079 if (this.words[0] + word < 0x4000000) {
19080 this.words[0] += word;
19081 } else {
19082 this._iaddn(word);
19083 }
19084 }
19085
19086 if (mod !== 0) {
19087 var pow = 1;
19088 word = parseBase(number, i, number.length, base);
19089
19090 for (i = 0; i < mod; i++) {
19091 pow *= base;
19092 }
19093
19094 this.imuln(pow);
19095 if (this.words[0] + word < 0x4000000) {
19096 this.words[0] += word;
19097 } else {
19098 this._iaddn(word);
19099 }
19100 }
19101 };
19102
19103 BN.prototype.copy = function copy (dest) {
19104 dest.words = new Array(this.length);
19105 for (var i = 0; i < this.length; i++) {
19106 dest.words[i] = this.words[i];
19107 }
19108 dest.length = this.length;
19109 dest.negative = this.negative;
19110 dest.red = this.red;
19111 };
19112
19113 BN.prototype.clone = function clone () {
19114 var r = new BN(null);
19115 this.copy(r);
19116 return r;
19117 };
19118
19119 BN.prototype._expand = function _expand (size) {
19120 while (this.length < size) {
19121 this.words[this.length++] = 0;
19122 }
19123 return this;
19124 };
19125
19126 // Remove leading `0` from `this`
19127 BN.prototype.strip = function strip () {
19128 while (this.length > 1 && this.words[this.length - 1] === 0) {
19129 this.length--;
19130 }
19131 return this._normSign();
19132 };
19133
19134 BN.prototype._normSign = function _normSign () {
19135 // -0 = 0
19136 if (this.length === 1 && this.words[0] === 0) {
19137 this.negative = 0;
19138 }
19139 return this;
19140 };
19141
19142 BN.prototype.inspect = function inspect () {
19143 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
19144 };
19145
19146 /*
19147
19148 var zeros = [];
19149 var groupSizes = [];
19150 var groupBases = [];
19151
19152 var s = '';
19153 var i = -1;
19154 while (++i < BN.wordSize) {
19155 zeros[i] = s;
19156 s += '0';
19157 }
19158 groupSizes[0] = 0;
19159 groupSizes[1] = 0;
19160 groupBases[0] = 0;
19161 groupBases[1] = 0;
19162 var base = 2 - 1;
19163 while (++base < 36 + 1) {
19164 var groupSize = 0;
19165 var groupBase = 1;
19166 while (groupBase < (1 << BN.wordSize) / base) {
19167 groupBase *= base;
19168 groupSize += 1;
19169 }
19170 groupSizes[base] = groupSize;
19171 groupBases[base] = groupBase;
19172 }
19173
19174 */
19175
19176 var zeros = [
19177 '',
19178 '0',
19179 '00',
19180 '000',
19181 '0000',
19182 '00000',
19183 '000000',
19184 '0000000',
19185 '00000000',
19186 '000000000',
19187 '0000000000',
19188 '00000000000',
19189 '000000000000',
19190 '0000000000000',
19191 '00000000000000',
19192 '000000000000000',
19193 '0000000000000000',
19194 '00000000000000000',
19195 '000000000000000000',
19196 '0000000000000000000',
19197 '00000000000000000000',
19198 '000000000000000000000',
19199 '0000000000000000000000',
19200 '00000000000000000000000',
19201 '000000000000000000000000',
19202 '0000000000000000000000000'
19203 ];
19204
19205 var groupSizes = [
19206 0, 0,
19207 25, 16, 12, 11, 10, 9, 8,
19208 8, 7, 7, 7, 7, 6, 6,
19209 6, 6, 6, 6, 6, 5, 5,
19210 5, 5, 5, 5, 5, 5, 5,
19211 5, 5, 5, 5, 5, 5, 5
19212 ];
19213
19214 var groupBases = [
19215 0, 0,
19216 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
19217 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
19218 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
19219 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
19220 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
19221 ];
19222
19223 BN.prototype.toString = function toString (base, padding) {
19224 base = base || 10;
19225 padding = padding | 0 || 1;
19226
19227 var out;
19228 if (base === 16 || base === 'hex') {
19229 out = '';
19230 var off = 0;
19231 var carry = 0;
19232 for (var i = 0; i < this.length; i++) {
19233 var w = this.words[i];
19234 var word = (((w << off) | carry) & 0xffffff).toString(16);
19235 carry = (w >>> (24 - off)) & 0xffffff;
19236 if (carry !== 0 || i !== this.length - 1) {
19237 out = zeros[6 - word.length] + word + out;
19238 } else {
19239 out = word + out;
19240 }
19241 off += 2;
19242 if (off >= 26) {
19243 off -= 26;
19244 i--;
19245 }
19246 }
19247 if (carry !== 0) {
19248 out = carry.toString(16) + out;
19249 }
19250 while (out.length % padding !== 0) {
19251 out = '0' + out;
19252 }
19253 if (this.negative !== 0) {
19254 out = '-' + out;
19255 }
19256 return out;
19257 }
19258
19259 if (base === (base | 0) && base >= 2 && base <= 36) {
19260 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
19261 var groupSize = groupSizes[base];
19262 // var groupBase = Math.pow(base, groupSize);
19263 var groupBase = groupBases[base];
19264 out = '';
19265 var c = this.clone();
19266 c.negative = 0;
19267 while (!c.isZero()) {
19268 var r = c.modn(groupBase).toString(base);
19269 c = c.idivn(groupBase);
19270
19271 if (!c.isZero()) {
19272 out = zeros[groupSize - r.length] + r + out;
19273 } else {
19274 out = r + out;
19275 }
19276 }
19277 if (this.isZero()) {
19278 out = '0' + out;
19279 }
19280 while (out.length % padding !== 0) {
19281 out = '0' + out;
19282 }
19283 if (this.negative !== 0) {
19284 out = '-' + out;
19285 }
19286 return out;
19287 }
19288
19289 assert(false, 'Base should be between 2 and 36');
19290 };
19291
19292 BN.prototype.toNumber = function toNumber () {
19293 var ret = this.words[0];
19294 if (this.length === 2) {
19295 ret += this.words[1] * 0x4000000;
19296 } else if (this.length === 3 && this.words[2] === 0x01) {
19297 // NOTE: at this stage it is known that the top bit is set
19298 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
19299 } else if (this.length > 2) {
19300 assert(false, 'Number can only safely store up to 53 bits');
19301 }
19302 return (this.negative !== 0) ? -ret : ret;
19303 };
19304
19305 BN.prototype.toJSON = function toJSON () {
19306 return this.toString(16);
19307 };
19308
19309 BN.prototype.toBuffer = function toBuffer (endian, length) {
19310 assert(typeof Buffer !== 'undefined');
19311 return this.toArrayLike(Buffer, endian, length);
19312 };
19313
19314 BN.prototype.toArray = function toArray (endian, length) {
19315 return this.toArrayLike(Array, endian, length);
19316 };
19317
19318 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
19319 var byteLength = this.byteLength();
19320 var reqLength = length || Math.max(1, byteLength);
19321 assert(byteLength <= reqLength, 'byte array longer than desired length');
19322 assert(reqLength > 0, 'Requested array length <= 0');
19323
19324 this.strip();
19325 var littleEndian = endian === 'le';
19326 var res = new ArrayType(reqLength);
19327
19328 var b, i;
19329 var q = this.clone();
19330 if (!littleEndian) {
19331 // Assume big-endian
19332 for (i = 0; i < reqLength - byteLength; i++) {
19333 res[i] = 0;
19334 }
19335
19336 for (i = 0; !q.isZero(); i++) {
19337 b = q.andln(0xff);
19338 q.iushrn(8);
19339
19340 res[reqLength - i - 1] = b;
19341 }
19342 } else {
19343 for (i = 0; !q.isZero(); i++) {
19344 b = q.andln(0xff);
19345 q.iushrn(8);
19346
19347 res[i] = b;
19348 }
19349
19350 for (; i < reqLength; i++) {
19351 res[i] = 0;
19352 }
19353 }
19354
19355 return res;
19356 };
19357
19358 if (Math.clz32) {
19359 BN.prototype._countBits = function _countBits (w) {
19360 return 32 - Math.clz32(w);
19361 };
19362 } else {
19363 BN.prototype._countBits = function _countBits (w) {
19364 var t = w;
19365 var r = 0;
19366 if (t >= 0x1000) {
19367 r += 13;
19368 t >>>= 13;
19369 }
19370 if (t >= 0x40) {
19371 r += 7;
19372 t >>>= 7;
19373 }
19374 if (t >= 0x8) {
19375 r += 4;
19376 t >>>= 4;
19377 }
19378 if (t >= 0x02) {
19379 r += 2;
19380 t >>>= 2;
19381 }
19382 return r + t;
19383 };
19384 }
19385
19386 BN.prototype._zeroBits = function _zeroBits (w) {
19387 // Short-cut
19388 if (w === 0) return 26;
19389
19390 var t = w;
19391 var r = 0;
19392 if ((t & 0x1fff) === 0) {
19393 r += 13;
19394 t >>>= 13;
19395 }
19396 if ((t & 0x7f) === 0) {
19397 r += 7;
19398 t >>>= 7;
19399 }
19400 if ((t & 0xf) === 0) {
19401 r += 4;
19402 t >>>= 4;
19403 }
19404 if ((t & 0x3) === 0) {
19405 r += 2;
19406 t >>>= 2;
19407 }
19408 if ((t & 0x1) === 0) {
19409 r++;
19410 }
19411 return r;
19412 };
19413
19414 // Return number of used bits in a BN
19415 BN.prototype.bitLength = function bitLength () {
19416 var w = this.words[this.length - 1];
19417 var hi = this._countBits(w);
19418 return (this.length - 1) * 26 + hi;
19419 };
19420
19421 function toBitArray (num) {
19422 var w = new Array(num.bitLength());
19423
19424 for (var bit = 0; bit < w.length; bit++) {
19425 var off = (bit / 26) | 0;
19426 var wbit = bit % 26;
19427
19428 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
19429 }
19430
19431 return w;
19432 }
19433
19434 // Number of trailing zero bits
19435 BN.prototype.zeroBits = function zeroBits () {
19436 if (this.isZero()) return 0;
19437
19438 var r = 0;
19439 for (var i = 0; i < this.length; i++) {
19440 var b = this._zeroBits(this.words[i]);
19441 r += b;
19442 if (b !== 26) break;
19443 }
19444 return r;
19445 };
19446
19447 BN.prototype.byteLength = function byteLength () {
19448 return Math.ceil(this.bitLength() / 8);
19449 };
19450
19451 BN.prototype.toTwos = function toTwos (width) {
19452 if (this.negative !== 0) {
19453 return this.abs().inotn(width).iaddn(1);
19454 }
19455 return this.clone();
19456 };
19457
19458 BN.prototype.fromTwos = function fromTwos (width) {
19459 if (this.testn(width - 1)) {
19460 return this.notn(width).iaddn(1).ineg();
19461 }
19462 return this.clone();
19463 };
19464
19465 BN.prototype.isNeg = function isNeg () {
19466 return this.negative !== 0;
19467 };
19468
19469 // Return negative clone of `this`
19470 BN.prototype.neg = function neg () {
19471 return this.clone().ineg();
19472 };
19473
19474 BN.prototype.ineg = function ineg () {
19475 if (!this.isZero()) {
19476 this.negative ^= 1;
19477 }
19478
19479 return this;
19480 };
19481
19482 // Or `num` with `this` in-place
19483 BN.prototype.iuor = function iuor (num) {
19484 while (this.length < num.length) {
19485 this.words[this.length++] = 0;
19486 }
19487
19488 for (var i = 0; i < num.length; i++) {
19489 this.words[i] = this.words[i] | num.words[i];
19490 }
19491
19492 return this.strip();
19493 };
19494
19495 BN.prototype.ior = function ior (num) {
19496 assert((this.negative | num.negative) === 0);
19497 return this.iuor(num);
19498 };
19499
19500 // Or `num` with `this`
19501 BN.prototype.or = function or (num) {
19502 if (this.length > num.length) return this.clone().ior(num);
19503 return num.clone().ior(this);
19504 };
19505
19506 BN.prototype.uor = function uor (num) {
19507 if (this.length > num.length) return this.clone().iuor(num);
19508 return num.clone().iuor(this);
19509 };
19510
19511 // And `num` with `this` in-place
19512 BN.prototype.iuand = function iuand (num) {
19513 // b = min-length(num, this)
19514 var b;
19515 if (this.length > num.length) {
19516 b = num;
19517 } else {
19518 b = this;
19519 }
19520
19521 for (var i = 0; i < b.length; i++) {
19522 this.words[i] = this.words[i] & num.words[i];
19523 }
19524
19525 this.length = b.length;
19526
19527 return this.strip();
19528 };
19529
19530 BN.prototype.iand = function iand (num) {
19531 assert((this.negative | num.negative) === 0);
19532 return this.iuand(num);
19533 };
19534
19535 // And `num` with `this`
19536 BN.prototype.and = function and (num) {
19537 if (this.length > num.length) return this.clone().iand(num);
19538 return num.clone().iand(this);
19539 };
19540
19541 BN.prototype.uand = function uand (num) {
19542 if (this.length > num.length) return this.clone().iuand(num);
19543 return num.clone().iuand(this);
19544 };
19545
19546 // Xor `num` with `this` in-place
19547 BN.prototype.iuxor = function iuxor (num) {
19548 // a.length > b.length
19549 var a;
19550 var b;
19551 if (this.length > num.length) {
19552 a = this;
19553 b = num;
19554 } else {
19555 a = num;
19556 b = this;
19557 }
19558
19559 for (var i = 0; i < b.length; i++) {
19560 this.words[i] = a.words[i] ^ b.words[i];
19561 }
19562
19563 if (this !== a) {
19564 for (; i < a.length; i++) {
19565 this.words[i] = a.words[i];
19566 }
19567 }
19568
19569 this.length = a.length;
19570
19571 return this.strip();
19572 };
19573
19574 BN.prototype.ixor = function ixor (num) {
19575 assert((this.negative | num.negative) === 0);
19576 return this.iuxor(num);
19577 };
19578
19579 // Xor `num` with `this`
19580 BN.prototype.xor = function xor (num) {
19581 if (this.length > num.length) return this.clone().ixor(num);
19582 return num.clone().ixor(this);
19583 };
19584
19585 BN.prototype.uxor = function uxor (num) {
19586 if (this.length > num.length) return this.clone().iuxor(num);
19587 return num.clone().iuxor(this);
19588 };
19589
19590 // Not ``this`` with ``width`` bitwidth
19591 BN.prototype.inotn = function inotn (width) {
19592 assert(typeof width === 'number' && width >= 0);
19593
19594 var bytesNeeded = Math.ceil(width / 26) | 0;
19595 var bitsLeft = width % 26;
19596
19597 // Extend the buffer with leading zeroes
19598 this._expand(bytesNeeded);
19599
19600 if (bitsLeft > 0) {
19601 bytesNeeded--;
19602 }
19603
19604 // Handle complete words
19605 for (var i = 0; i < bytesNeeded; i++) {
19606 this.words[i] = ~this.words[i] & 0x3ffffff;
19607 }
19608
19609 // Handle the residue
19610 if (bitsLeft > 0) {
19611 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
19612 }
19613
19614 // And remove leading zeroes
19615 return this.strip();
19616 };
19617
19618 BN.prototype.notn = function notn (width) {
19619 return this.clone().inotn(width);
19620 };
19621
19622 // Set `bit` of `this`
19623 BN.prototype.setn = function setn (bit, val) {
19624 assert(typeof bit === 'number' && bit >= 0);
19625
19626 var off = (bit / 26) | 0;
19627 var wbit = bit % 26;
19628
19629 this._expand(off + 1);
19630
19631 if (val) {
19632 this.words[off] = this.words[off] | (1 << wbit);
19633 } else {
19634 this.words[off] = this.words[off] & ~(1 << wbit);
19635 }
19636
19637 return this.strip();
19638 };
19639
19640 // Add `num` to `this` in-place
19641 BN.prototype.iadd = function iadd (num) {
19642 var r;
19643
19644 // negative + positive
19645 if (this.negative !== 0 && num.negative === 0) {
19646 this.negative = 0;
19647 r = this.isub(num);
19648 this.negative ^= 1;
19649 return this._normSign();
19650
19651 // positive + negative
19652 } else if (this.negative === 0 && num.negative !== 0) {
19653 num.negative = 0;
19654 r = this.isub(num);
19655 num.negative = 1;
19656 return r._normSign();
19657 }
19658
19659 // a.length > b.length
19660 var a, b;
19661 if (this.length > num.length) {
19662 a = this;
19663 b = num;
19664 } else {
19665 a = num;
19666 b = this;
19667 }
19668
19669 var carry = 0;
19670 for (var i = 0; i < b.length; i++) {
19671 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
19672 this.words[i] = r & 0x3ffffff;
19673 carry = r >>> 26;
19674 }
19675 for (; carry !== 0 && i < a.length; i++) {
19676 r = (a.words[i] | 0) + carry;
19677 this.words[i] = r & 0x3ffffff;
19678 carry = r >>> 26;
19679 }
19680
19681 this.length = a.length;
19682 if (carry !== 0) {
19683 this.words[this.length] = carry;
19684 this.length++;
19685 // Copy the rest of the words
19686 } else if (a !== this) {
19687 for (; i < a.length; i++) {
19688 this.words[i] = a.words[i];
19689 }
19690 }
19691
19692 return this;
19693 };
19694
19695 // Add `num` to `this`
19696 BN.prototype.add = function add (num) {
19697 var res;
19698 if (num.negative !== 0 && this.negative === 0) {
19699 num.negative = 0;
19700 res = this.sub(num);
19701 num.negative ^= 1;
19702 return res;
19703 } else if (num.negative === 0 && this.negative !== 0) {
19704 this.negative = 0;
19705 res = num.sub(this);
19706 this.negative = 1;
19707 return res;
19708 }
19709
19710 if (this.length > num.length) return this.clone().iadd(num);
19711
19712 return num.clone().iadd(this);
19713 };
19714
19715 // Subtract `num` from `this` in-place
19716 BN.prototype.isub = function isub (num) {
19717 // this - (-num) = this + num
19718 if (num.negative !== 0) {
19719 num.negative = 0;
19720 var r = this.iadd(num);
19721 num.negative = 1;
19722 return r._normSign();
19723
19724 // -this - num = -(this + num)
19725 } else if (this.negative !== 0) {
19726 this.negative = 0;
19727 this.iadd(num);
19728 this.negative = 1;
19729 return this._normSign();
19730 }
19731
19732 // At this point both numbers are positive
19733 var cmp = this.cmp(num);
19734
19735 // Optimization - zeroify
19736 if (cmp === 0) {
19737 this.negative = 0;
19738 this.length = 1;
19739 this.words[0] = 0;
19740 return this;
19741 }
19742
19743 // a > b
19744 var a, b;
19745 if (cmp > 0) {
19746 a = this;
19747 b = num;
19748 } else {
19749 a = num;
19750 b = this;
19751 }
19752
19753 var carry = 0;
19754 for (var i = 0; i < b.length; i++) {
19755 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
19756 carry = r >> 26;
19757 this.words[i] = r & 0x3ffffff;
19758 }
19759 for (; carry !== 0 && i < a.length; i++) {
19760 r = (a.words[i] | 0) + carry;
19761 carry = r >> 26;
19762 this.words[i] = r & 0x3ffffff;
19763 }
19764
19765 // Copy rest of the words
19766 if (carry === 0 && i < a.length && a !== this) {
19767 for (; i < a.length; i++) {
19768 this.words[i] = a.words[i];
19769 }
19770 }
19771
19772 this.length = Math.max(this.length, i);
19773
19774 if (a !== this) {
19775 this.negative = 1;
19776 }
19777
19778 return this.strip();
19779 };
19780
19781 // Subtract `num` from `this`
19782 BN.prototype.sub = function sub (num) {
19783 return this.clone().isub(num);
19784 };
19785
19786 function smallMulTo (self, num, out) {
19787 out.negative = num.negative ^ self.negative;
19788 var len = (self.length + num.length) | 0;
19789 out.length = len;
19790 len = (len - 1) | 0;
19791
19792 // Peel one iteration (compiler can't do it, because of code complexity)
19793 var a = self.words[0] | 0;
19794 var b = num.words[0] | 0;
19795 var r = a * b;
19796
19797 var lo = r & 0x3ffffff;
19798 var carry = (r / 0x4000000) | 0;
19799 out.words[0] = lo;
19800
19801 for (var k = 1; k < len; k++) {
19802 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
19803 // note that ncarry could be >= 0x3ffffff
19804 var ncarry = carry >>> 26;
19805 var rword = carry & 0x3ffffff;
19806 var maxJ = Math.min(k, num.length - 1);
19807 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
19808 var i = (k - j) | 0;
19809 a = self.words[i] | 0;
19810 b = num.words[j] | 0;
19811 r = a * b + rword;
19812 ncarry += (r / 0x4000000) | 0;
19813 rword = r & 0x3ffffff;
19814 }
19815 out.words[k] = rword | 0;
19816 carry = ncarry | 0;
19817 }
19818 if (carry !== 0) {
19819 out.words[k] = carry | 0;
19820 } else {
19821 out.length--;
19822 }
19823
19824 return out.strip();
19825 }
19826
19827 // TODO(indutny): it may be reasonable to omit it for users who don't need
19828 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
19829 // multiplication (like elliptic secp256k1).
19830 var comb10MulTo = function comb10MulTo (self, num, out) {
19831 var a = self.words;
19832 var b = num.words;
19833 var o = out.words;
19834 var c = 0;
19835 var lo;
19836 var mid;
19837 var hi;
19838 var a0 = a[0] | 0;
19839 var al0 = a0 & 0x1fff;
19840 var ah0 = a0 >>> 13;
19841 var a1 = a[1] | 0;
19842 var al1 = a1 & 0x1fff;
19843 var ah1 = a1 >>> 13;
19844 var a2 = a[2] | 0;
19845 var al2 = a2 & 0x1fff;
19846 var ah2 = a2 >>> 13;
19847 var a3 = a[3] | 0;
19848 var al3 = a3 & 0x1fff;
19849 var ah3 = a3 >>> 13;
19850 var a4 = a[4] | 0;
19851 var al4 = a4 & 0x1fff;
19852 var ah4 = a4 >>> 13;
19853 var a5 = a[5] | 0;
19854 var al5 = a5 & 0x1fff;
19855 var ah5 = a5 >>> 13;
19856 var a6 = a[6] | 0;
19857 var al6 = a6 & 0x1fff;
19858 var ah6 = a6 >>> 13;
19859 var a7 = a[7] | 0;
19860 var al7 = a7 & 0x1fff;
19861 var ah7 = a7 >>> 13;
19862 var a8 = a[8] | 0;
19863 var al8 = a8 & 0x1fff;
19864 var ah8 = a8 >>> 13;
19865 var a9 = a[9] | 0;
19866 var al9 = a9 & 0x1fff;
19867 var ah9 = a9 >>> 13;
19868 var b0 = b[0] | 0;
19869 var bl0 = b0 & 0x1fff;
19870 var bh0 = b0 >>> 13;
19871 var b1 = b[1] | 0;
19872 var bl1 = b1 & 0x1fff;
19873 var bh1 = b1 >>> 13;
19874 var b2 = b[2] | 0;
19875 var bl2 = b2 & 0x1fff;
19876 var bh2 = b2 >>> 13;
19877 var b3 = b[3] | 0;
19878 var bl3 = b3 & 0x1fff;
19879 var bh3 = b3 >>> 13;
19880 var b4 = b[4] | 0;
19881 var bl4 = b4 & 0x1fff;
19882 var bh4 = b4 >>> 13;
19883 var b5 = b[5] | 0;
19884 var bl5 = b5 & 0x1fff;
19885 var bh5 = b5 >>> 13;
19886 var b6 = b[6] | 0;
19887 var bl6 = b6 & 0x1fff;
19888 var bh6 = b6 >>> 13;
19889 var b7 = b[7] | 0;
19890 var bl7 = b7 & 0x1fff;
19891 var bh7 = b7 >>> 13;
19892 var b8 = b[8] | 0;
19893 var bl8 = b8 & 0x1fff;
19894 var bh8 = b8 >>> 13;
19895 var b9 = b[9] | 0;
19896 var bl9 = b9 & 0x1fff;
19897 var bh9 = b9 >>> 13;
19898
19899 out.negative = self.negative ^ num.negative;
19900 out.length = 19;
19901 /* k = 0 */
19902 lo = Math.imul(al0, bl0);
19903 mid = Math.imul(al0, bh0);
19904 mid = (mid + Math.imul(ah0, bl0)) | 0;
19905 hi = Math.imul(ah0, bh0);
19906 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19907 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
19908 w0 &= 0x3ffffff;
19909 /* k = 1 */
19910 lo = Math.imul(al1, bl0);
19911 mid = Math.imul(al1, bh0);
19912 mid = (mid + Math.imul(ah1, bl0)) | 0;
19913 hi = Math.imul(ah1, bh0);
19914 lo = (lo + Math.imul(al0, bl1)) | 0;
19915 mid = (mid + Math.imul(al0, bh1)) | 0;
19916 mid = (mid + Math.imul(ah0, bl1)) | 0;
19917 hi = (hi + Math.imul(ah0, bh1)) | 0;
19918 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19919 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
19920 w1 &= 0x3ffffff;
19921 /* k = 2 */
19922 lo = Math.imul(al2, bl0);
19923 mid = Math.imul(al2, bh0);
19924 mid = (mid + Math.imul(ah2, bl0)) | 0;
19925 hi = Math.imul(ah2, bh0);
19926 lo = (lo + Math.imul(al1, bl1)) | 0;
19927 mid = (mid + Math.imul(al1, bh1)) | 0;
19928 mid = (mid + Math.imul(ah1, bl1)) | 0;
19929 hi = (hi + Math.imul(ah1, bh1)) | 0;
19930 lo = (lo + Math.imul(al0, bl2)) | 0;
19931 mid = (mid + Math.imul(al0, bh2)) | 0;
19932 mid = (mid + Math.imul(ah0, bl2)) | 0;
19933 hi = (hi + Math.imul(ah0, bh2)) | 0;
19934 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19935 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
19936 w2 &= 0x3ffffff;
19937 /* k = 3 */
19938 lo = Math.imul(al3, bl0);
19939 mid = Math.imul(al3, bh0);
19940 mid = (mid + Math.imul(ah3, bl0)) | 0;
19941 hi = Math.imul(ah3, bh0);
19942 lo = (lo + Math.imul(al2, bl1)) | 0;
19943 mid = (mid + Math.imul(al2, bh1)) | 0;
19944 mid = (mid + Math.imul(ah2, bl1)) | 0;
19945 hi = (hi + Math.imul(ah2, bh1)) | 0;
19946 lo = (lo + Math.imul(al1, bl2)) | 0;
19947 mid = (mid + Math.imul(al1, bh2)) | 0;
19948 mid = (mid + Math.imul(ah1, bl2)) | 0;
19949 hi = (hi + Math.imul(ah1, bh2)) | 0;
19950 lo = (lo + Math.imul(al0, bl3)) | 0;
19951 mid = (mid + Math.imul(al0, bh3)) | 0;
19952 mid = (mid + Math.imul(ah0, bl3)) | 0;
19953 hi = (hi + Math.imul(ah0, bh3)) | 0;
19954 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19955 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
19956 w3 &= 0x3ffffff;
19957 /* k = 4 */
19958 lo = Math.imul(al4, bl0);
19959 mid = Math.imul(al4, bh0);
19960 mid = (mid + Math.imul(ah4, bl0)) | 0;
19961 hi = Math.imul(ah4, bh0);
19962 lo = (lo + Math.imul(al3, bl1)) | 0;
19963 mid = (mid + Math.imul(al3, bh1)) | 0;
19964 mid = (mid + Math.imul(ah3, bl1)) | 0;
19965 hi = (hi + Math.imul(ah3, bh1)) | 0;
19966 lo = (lo + Math.imul(al2, bl2)) | 0;
19967 mid = (mid + Math.imul(al2, bh2)) | 0;
19968 mid = (mid + Math.imul(ah2, bl2)) | 0;
19969 hi = (hi + Math.imul(ah2, bh2)) | 0;
19970 lo = (lo + Math.imul(al1, bl3)) | 0;
19971 mid = (mid + Math.imul(al1, bh3)) | 0;
19972 mid = (mid + Math.imul(ah1, bl3)) | 0;
19973 hi = (hi + Math.imul(ah1, bh3)) | 0;
19974 lo = (lo + Math.imul(al0, bl4)) | 0;
19975 mid = (mid + Math.imul(al0, bh4)) | 0;
19976 mid = (mid + Math.imul(ah0, bl4)) | 0;
19977 hi = (hi + Math.imul(ah0, bh4)) | 0;
19978 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
19979 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
19980 w4 &= 0x3ffffff;
19981 /* k = 5 */
19982 lo = Math.imul(al5, bl0);
19983 mid = Math.imul(al5, bh0);
19984 mid = (mid + Math.imul(ah5, bl0)) | 0;
19985 hi = Math.imul(ah5, bh0);
19986 lo = (lo + Math.imul(al4, bl1)) | 0;
19987 mid = (mid + Math.imul(al4, bh1)) | 0;
19988 mid = (mid + Math.imul(ah4, bl1)) | 0;
19989 hi = (hi + Math.imul(ah4, bh1)) | 0;
19990 lo = (lo + Math.imul(al3, bl2)) | 0;
19991 mid = (mid + Math.imul(al3, bh2)) | 0;
19992 mid = (mid + Math.imul(ah3, bl2)) | 0;
19993 hi = (hi + Math.imul(ah3, bh2)) | 0;
19994 lo = (lo + Math.imul(al2, bl3)) | 0;
19995 mid = (mid + Math.imul(al2, bh3)) | 0;
19996 mid = (mid + Math.imul(ah2, bl3)) | 0;
19997 hi = (hi + Math.imul(ah2, bh3)) | 0;
19998 lo = (lo + Math.imul(al1, bl4)) | 0;
19999 mid = (mid + Math.imul(al1, bh4)) | 0;
20000 mid = (mid + Math.imul(ah1, bl4)) | 0;
20001 hi = (hi + Math.imul(ah1, bh4)) | 0;
20002 lo = (lo + Math.imul(al0, bl5)) | 0;
20003 mid = (mid + Math.imul(al0, bh5)) | 0;
20004 mid = (mid + Math.imul(ah0, bl5)) | 0;
20005 hi = (hi + Math.imul(ah0, bh5)) | 0;
20006 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20007 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
20008 w5 &= 0x3ffffff;
20009 /* k = 6 */
20010 lo = Math.imul(al6, bl0);
20011 mid = Math.imul(al6, bh0);
20012 mid = (mid + Math.imul(ah6, bl0)) | 0;
20013 hi = Math.imul(ah6, bh0);
20014 lo = (lo + Math.imul(al5, bl1)) | 0;
20015 mid = (mid + Math.imul(al5, bh1)) | 0;
20016 mid = (mid + Math.imul(ah5, bl1)) | 0;
20017 hi = (hi + Math.imul(ah5, bh1)) | 0;
20018 lo = (lo + Math.imul(al4, bl2)) | 0;
20019 mid = (mid + Math.imul(al4, bh2)) | 0;
20020 mid = (mid + Math.imul(ah4, bl2)) | 0;
20021 hi = (hi + Math.imul(ah4, bh2)) | 0;
20022 lo = (lo + Math.imul(al3, bl3)) | 0;
20023 mid = (mid + Math.imul(al3, bh3)) | 0;
20024 mid = (mid + Math.imul(ah3, bl3)) | 0;
20025 hi = (hi + Math.imul(ah3, bh3)) | 0;
20026 lo = (lo + Math.imul(al2, bl4)) | 0;
20027 mid = (mid + Math.imul(al2, bh4)) | 0;
20028 mid = (mid + Math.imul(ah2, bl4)) | 0;
20029 hi = (hi + Math.imul(ah2, bh4)) | 0;
20030 lo = (lo + Math.imul(al1, bl5)) | 0;
20031 mid = (mid + Math.imul(al1, bh5)) | 0;
20032 mid = (mid + Math.imul(ah1, bl5)) | 0;
20033 hi = (hi + Math.imul(ah1, bh5)) | 0;
20034 lo = (lo + Math.imul(al0, bl6)) | 0;
20035 mid = (mid + Math.imul(al0, bh6)) | 0;
20036 mid = (mid + Math.imul(ah0, bl6)) | 0;
20037 hi = (hi + Math.imul(ah0, bh6)) | 0;
20038 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20039 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
20040 w6 &= 0x3ffffff;
20041 /* k = 7 */
20042 lo = Math.imul(al7, bl0);
20043 mid = Math.imul(al7, bh0);
20044 mid = (mid + Math.imul(ah7, bl0)) | 0;
20045 hi = Math.imul(ah7, bh0);
20046 lo = (lo + Math.imul(al6, bl1)) | 0;
20047 mid = (mid + Math.imul(al6, bh1)) | 0;
20048 mid = (mid + Math.imul(ah6, bl1)) | 0;
20049 hi = (hi + Math.imul(ah6, bh1)) | 0;
20050 lo = (lo + Math.imul(al5, bl2)) | 0;
20051 mid = (mid + Math.imul(al5, bh2)) | 0;
20052 mid = (mid + Math.imul(ah5, bl2)) | 0;
20053 hi = (hi + Math.imul(ah5, bh2)) | 0;
20054 lo = (lo + Math.imul(al4, bl3)) | 0;
20055 mid = (mid + Math.imul(al4, bh3)) | 0;
20056 mid = (mid + Math.imul(ah4, bl3)) | 0;
20057 hi = (hi + Math.imul(ah4, bh3)) | 0;
20058 lo = (lo + Math.imul(al3, bl4)) | 0;
20059 mid = (mid + Math.imul(al3, bh4)) | 0;
20060 mid = (mid + Math.imul(ah3, bl4)) | 0;
20061 hi = (hi + Math.imul(ah3, bh4)) | 0;
20062 lo = (lo + Math.imul(al2, bl5)) | 0;
20063 mid = (mid + Math.imul(al2, bh5)) | 0;
20064 mid = (mid + Math.imul(ah2, bl5)) | 0;
20065 hi = (hi + Math.imul(ah2, bh5)) | 0;
20066 lo = (lo + Math.imul(al1, bl6)) | 0;
20067 mid = (mid + Math.imul(al1, bh6)) | 0;
20068 mid = (mid + Math.imul(ah1, bl6)) | 0;
20069 hi = (hi + Math.imul(ah1, bh6)) | 0;
20070 lo = (lo + Math.imul(al0, bl7)) | 0;
20071 mid = (mid + Math.imul(al0, bh7)) | 0;
20072 mid = (mid + Math.imul(ah0, bl7)) | 0;
20073 hi = (hi + Math.imul(ah0, bh7)) | 0;
20074 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20075 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
20076 w7 &= 0x3ffffff;
20077 /* k = 8 */
20078 lo = Math.imul(al8, bl0);
20079 mid = Math.imul(al8, bh0);
20080 mid = (mid + Math.imul(ah8, bl0)) | 0;
20081 hi = Math.imul(ah8, bh0);
20082 lo = (lo + Math.imul(al7, bl1)) | 0;
20083 mid = (mid + Math.imul(al7, bh1)) | 0;
20084 mid = (mid + Math.imul(ah7, bl1)) | 0;
20085 hi = (hi + Math.imul(ah7, bh1)) | 0;
20086 lo = (lo + Math.imul(al6, bl2)) | 0;
20087 mid = (mid + Math.imul(al6, bh2)) | 0;
20088 mid = (mid + Math.imul(ah6, bl2)) | 0;
20089 hi = (hi + Math.imul(ah6, bh2)) | 0;
20090 lo = (lo + Math.imul(al5, bl3)) | 0;
20091 mid = (mid + Math.imul(al5, bh3)) | 0;
20092 mid = (mid + Math.imul(ah5, bl3)) | 0;
20093 hi = (hi + Math.imul(ah5, bh3)) | 0;
20094 lo = (lo + Math.imul(al4, bl4)) | 0;
20095 mid = (mid + Math.imul(al4, bh4)) | 0;
20096 mid = (mid + Math.imul(ah4, bl4)) | 0;
20097 hi = (hi + Math.imul(ah4, bh4)) | 0;
20098 lo = (lo + Math.imul(al3, bl5)) | 0;
20099 mid = (mid + Math.imul(al3, bh5)) | 0;
20100 mid = (mid + Math.imul(ah3, bl5)) | 0;
20101 hi = (hi + Math.imul(ah3, bh5)) | 0;
20102 lo = (lo + Math.imul(al2, bl6)) | 0;
20103 mid = (mid + Math.imul(al2, bh6)) | 0;
20104 mid = (mid + Math.imul(ah2, bl6)) | 0;
20105 hi = (hi + Math.imul(ah2, bh6)) | 0;
20106 lo = (lo + Math.imul(al1, bl7)) | 0;
20107 mid = (mid + Math.imul(al1, bh7)) | 0;
20108 mid = (mid + Math.imul(ah1, bl7)) | 0;
20109 hi = (hi + Math.imul(ah1, bh7)) | 0;
20110 lo = (lo + Math.imul(al0, bl8)) | 0;
20111 mid = (mid + Math.imul(al0, bh8)) | 0;
20112 mid = (mid + Math.imul(ah0, bl8)) | 0;
20113 hi = (hi + Math.imul(ah0, bh8)) | 0;
20114 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20115 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
20116 w8 &= 0x3ffffff;
20117 /* k = 9 */
20118 lo = Math.imul(al9, bl0);
20119 mid = Math.imul(al9, bh0);
20120 mid = (mid + Math.imul(ah9, bl0)) | 0;
20121 hi = Math.imul(ah9, bh0);
20122 lo = (lo + Math.imul(al8, bl1)) | 0;
20123 mid = (mid + Math.imul(al8, bh1)) | 0;
20124 mid = (mid + Math.imul(ah8, bl1)) | 0;
20125 hi = (hi + Math.imul(ah8, bh1)) | 0;
20126 lo = (lo + Math.imul(al7, bl2)) | 0;
20127 mid = (mid + Math.imul(al7, bh2)) | 0;
20128 mid = (mid + Math.imul(ah7, bl2)) | 0;
20129 hi = (hi + Math.imul(ah7, bh2)) | 0;
20130 lo = (lo + Math.imul(al6, bl3)) | 0;
20131 mid = (mid + Math.imul(al6, bh3)) | 0;
20132 mid = (mid + Math.imul(ah6, bl3)) | 0;
20133 hi = (hi + Math.imul(ah6, bh3)) | 0;
20134 lo = (lo + Math.imul(al5, bl4)) | 0;
20135 mid = (mid + Math.imul(al5, bh4)) | 0;
20136 mid = (mid + Math.imul(ah5, bl4)) | 0;
20137 hi = (hi + Math.imul(ah5, bh4)) | 0;
20138 lo = (lo + Math.imul(al4, bl5)) | 0;
20139 mid = (mid + Math.imul(al4, bh5)) | 0;
20140 mid = (mid + Math.imul(ah4, bl5)) | 0;
20141 hi = (hi + Math.imul(ah4, bh5)) | 0;
20142 lo = (lo + Math.imul(al3, bl6)) | 0;
20143 mid = (mid + Math.imul(al3, bh6)) | 0;
20144 mid = (mid + Math.imul(ah3, bl6)) | 0;
20145 hi = (hi + Math.imul(ah3, bh6)) | 0;
20146 lo = (lo + Math.imul(al2, bl7)) | 0;
20147 mid = (mid + Math.imul(al2, bh7)) | 0;
20148 mid = (mid + Math.imul(ah2, bl7)) | 0;
20149 hi = (hi + Math.imul(ah2, bh7)) | 0;
20150 lo = (lo + Math.imul(al1, bl8)) | 0;
20151 mid = (mid + Math.imul(al1, bh8)) | 0;
20152 mid = (mid + Math.imul(ah1, bl8)) | 0;
20153 hi = (hi + Math.imul(ah1, bh8)) | 0;
20154 lo = (lo + Math.imul(al0, bl9)) | 0;
20155 mid = (mid + Math.imul(al0, bh9)) | 0;
20156 mid = (mid + Math.imul(ah0, bl9)) | 0;
20157 hi = (hi + Math.imul(ah0, bh9)) | 0;
20158 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20159 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
20160 w9 &= 0x3ffffff;
20161 /* k = 10 */
20162 lo = Math.imul(al9, bl1);
20163 mid = Math.imul(al9, bh1);
20164 mid = (mid + Math.imul(ah9, bl1)) | 0;
20165 hi = Math.imul(ah9, bh1);
20166 lo = (lo + Math.imul(al8, bl2)) | 0;
20167 mid = (mid + Math.imul(al8, bh2)) | 0;
20168 mid = (mid + Math.imul(ah8, bl2)) | 0;
20169 hi = (hi + Math.imul(ah8, bh2)) | 0;
20170 lo = (lo + Math.imul(al7, bl3)) | 0;
20171 mid = (mid + Math.imul(al7, bh3)) | 0;
20172 mid = (mid + Math.imul(ah7, bl3)) | 0;
20173 hi = (hi + Math.imul(ah7, bh3)) | 0;
20174 lo = (lo + Math.imul(al6, bl4)) | 0;
20175 mid = (mid + Math.imul(al6, bh4)) | 0;
20176 mid = (mid + Math.imul(ah6, bl4)) | 0;
20177 hi = (hi + Math.imul(ah6, bh4)) | 0;
20178 lo = (lo + Math.imul(al5, bl5)) | 0;
20179 mid = (mid + Math.imul(al5, bh5)) | 0;
20180 mid = (mid + Math.imul(ah5, bl5)) | 0;
20181 hi = (hi + Math.imul(ah5, bh5)) | 0;
20182 lo = (lo + Math.imul(al4, bl6)) | 0;
20183 mid = (mid + Math.imul(al4, bh6)) | 0;
20184 mid = (mid + Math.imul(ah4, bl6)) | 0;
20185 hi = (hi + Math.imul(ah4, bh6)) | 0;
20186 lo = (lo + Math.imul(al3, bl7)) | 0;
20187 mid = (mid + Math.imul(al3, bh7)) | 0;
20188 mid = (mid + Math.imul(ah3, bl7)) | 0;
20189 hi = (hi + Math.imul(ah3, bh7)) | 0;
20190 lo = (lo + Math.imul(al2, bl8)) | 0;
20191 mid = (mid + Math.imul(al2, bh8)) | 0;
20192 mid = (mid + Math.imul(ah2, bl8)) | 0;
20193 hi = (hi + Math.imul(ah2, bh8)) | 0;
20194 lo = (lo + Math.imul(al1, bl9)) | 0;
20195 mid = (mid + Math.imul(al1, bh9)) | 0;
20196 mid = (mid + Math.imul(ah1, bl9)) | 0;
20197 hi = (hi + Math.imul(ah1, bh9)) | 0;
20198 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20199 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
20200 w10 &= 0x3ffffff;
20201 /* k = 11 */
20202 lo = Math.imul(al9, bl2);
20203 mid = Math.imul(al9, bh2);
20204 mid = (mid + Math.imul(ah9, bl2)) | 0;
20205 hi = Math.imul(ah9, bh2);
20206 lo = (lo + Math.imul(al8, bl3)) | 0;
20207 mid = (mid + Math.imul(al8, bh3)) | 0;
20208 mid = (mid + Math.imul(ah8, bl3)) | 0;
20209 hi = (hi + Math.imul(ah8, bh3)) | 0;
20210 lo = (lo + Math.imul(al7, bl4)) | 0;
20211 mid = (mid + Math.imul(al7, bh4)) | 0;
20212 mid = (mid + Math.imul(ah7, bl4)) | 0;
20213 hi = (hi + Math.imul(ah7, bh4)) | 0;
20214 lo = (lo + Math.imul(al6, bl5)) | 0;
20215 mid = (mid + Math.imul(al6, bh5)) | 0;
20216 mid = (mid + Math.imul(ah6, bl5)) | 0;
20217 hi = (hi + Math.imul(ah6, bh5)) | 0;
20218 lo = (lo + Math.imul(al5, bl6)) | 0;
20219 mid = (mid + Math.imul(al5, bh6)) | 0;
20220 mid = (mid + Math.imul(ah5, bl6)) | 0;
20221 hi = (hi + Math.imul(ah5, bh6)) | 0;
20222 lo = (lo + Math.imul(al4, bl7)) | 0;
20223 mid = (mid + Math.imul(al4, bh7)) | 0;
20224 mid = (mid + Math.imul(ah4, bl7)) | 0;
20225 hi = (hi + Math.imul(ah4, bh7)) | 0;
20226 lo = (lo + Math.imul(al3, bl8)) | 0;
20227 mid = (mid + Math.imul(al3, bh8)) | 0;
20228 mid = (mid + Math.imul(ah3, bl8)) | 0;
20229 hi = (hi + Math.imul(ah3, bh8)) | 0;
20230 lo = (lo + Math.imul(al2, bl9)) | 0;
20231 mid = (mid + Math.imul(al2, bh9)) | 0;
20232 mid = (mid + Math.imul(ah2, bl9)) | 0;
20233 hi = (hi + Math.imul(ah2, bh9)) | 0;
20234 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20235 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
20236 w11 &= 0x3ffffff;
20237 /* k = 12 */
20238 lo = Math.imul(al9, bl3);
20239 mid = Math.imul(al9, bh3);
20240 mid = (mid + Math.imul(ah9, bl3)) | 0;
20241 hi = Math.imul(ah9, bh3);
20242 lo = (lo + Math.imul(al8, bl4)) | 0;
20243 mid = (mid + Math.imul(al8, bh4)) | 0;
20244 mid = (mid + Math.imul(ah8, bl4)) | 0;
20245 hi = (hi + Math.imul(ah8, bh4)) | 0;
20246 lo = (lo + Math.imul(al7, bl5)) | 0;
20247 mid = (mid + Math.imul(al7, bh5)) | 0;
20248 mid = (mid + Math.imul(ah7, bl5)) | 0;
20249 hi = (hi + Math.imul(ah7, bh5)) | 0;
20250 lo = (lo + Math.imul(al6, bl6)) | 0;
20251 mid = (mid + Math.imul(al6, bh6)) | 0;
20252 mid = (mid + Math.imul(ah6, bl6)) | 0;
20253 hi = (hi + Math.imul(ah6, bh6)) | 0;
20254 lo = (lo + Math.imul(al5, bl7)) | 0;
20255 mid = (mid + Math.imul(al5, bh7)) | 0;
20256 mid = (mid + Math.imul(ah5, bl7)) | 0;
20257 hi = (hi + Math.imul(ah5, bh7)) | 0;
20258 lo = (lo + Math.imul(al4, bl8)) | 0;
20259 mid = (mid + Math.imul(al4, bh8)) | 0;
20260 mid = (mid + Math.imul(ah4, bl8)) | 0;
20261 hi = (hi + Math.imul(ah4, bh8)) | 0;
20262 lo = (lo + Math.imul(al3, bl9)) | 0;
20263 mid = (mid + Math.imul(al3, bh9)) | 0;
20264 mid = (mid + Math.imul(ah3, bl9)) | 0;
20265 hi = (hi + Math.imul(ah3, bh9)) | 0;
20266 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20267 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
20268 w12 &= 0x3ffffff;
20269 /* k = 13 */
20270 lo = Math.imul(al9, bl4);
20271 mid = Math.imul(al9, bh4);
20272 mid = (mid + Math.imul(ah9, bl4)) | 0;
20273 hi = Math.imul(ah9, bh4);
20274 lo = (lo + Math.imul(al8, bl5)) | 0;
20275 mid = (mid + Math.imul(al8, bh5)) | 0;
20276 mid = (mid + Math.imul(ah8, bl5)) | 0;
20277 hi = (hi + Math.imul(ah8, bh5)) | 0;
20278 lo = (lo + Math.imul(al7, bl6)) | 0;
20279 mid = (mid + Math.imul(al7, bh6)) | 0;
20280 mid = (mid + Math.imul(ah7, bl6)) | 0;
20281 hi = (hi + Math.imul(ah7, bh6)) | 0;
20282 lo = (lo + Math.imul(al6, bl7)) | 0;
20283 mid = (mid + Math.imul(al6, bh7)) | 0;
20284 mid = (mid + Math.imul(ah6, bl7)) | 0;
20285 hi = (hi + Math.imul(ah6, bh7)) | 0;
20286 lo = (lo + Math.imul(al5, bl8)) | 0;
20287 mid = (mid + Math.imul(al5, bh8)) | 0;
20288 mid = (mid + Math.imul(ah5, bl8)) | 0;
20289 hi = (hi + Math.imul(ah5, bh8)) | 0;
20290 lo = (lo + Math.imul(al4, bl9)) | 0;
20291 mid = (mid + Math.imul(al4, bh9)) | 0;
20292 mid = (mid + Math.imul(ah4, bl9)) | 0;
20293 hi = (hi + Math.imul(ah4, bh9)) | 0;
20294 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20295 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
20296 w13 &= 0x3ffffff;
20297 /* k = 14 */
20298 lo = Math.imul(al9, bl5);
20299 mid = Math.imul(al9, bh5);
20300 mid = (mid + Math.imul(ah9, bl5)) | 0;
20301 hi = Math.imul(ah9, bh5);
20302 lo = (lo + Math.imul(al8, bl6)) | 0;
20303 mid = (mid + Math.imul(al8, bh6)) | 0;
20304 mid = (mid + Math.imul(ah8, bl6)) | 0;
20305 hi = (hi + Math.imul(ah8, bh6)) | 0;
20306 lo = (lo + Math.imul(al7, bl7)) | 0;
20307 mid = (mid + Math.imul(al7, bh7)) | 0;
20308 mid = (mid + Math.imul(ah7, bl7)) | 0;
20309 hi = (hi + Math.imul(ah7, bh7)) | 0;
20310 lo = (lo + Math.imul(al6, bl8)) | 0;
20311 mid = (mid + Math.imul(al6, bh8)) | 0;
20312 mid = (mid + Math.imul(ah6, bl8)) | 0;
20313 hi = (hi + Math.imul(ah6, bh8)) | 0;
20314 lo = (lo + Math.imul(al5, bl9)) | 0;
20315 mid = (mid + Math.imul(al5, bh9)) | 0;
20316 mid = (mid + Math.imul(ah5, bl9)) | 0;
20317 hi = (hi + Math.imul(ah5, bh9)) | 0;
20318 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20319 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
20320 w14 &= 0x3ffffff;
20321 /* k = 15 */
20322 lo = Math.imul(al9, bl6);
20323 mid = Math.imul(al9, bh6);
20324 mid = (mid + Math.imul(ah9, bl6)) | 0;
20325 hi = Math.imul(ah9, bh6);
20326 lo = (lo + Math.imul(al8, bl7)) | 0;
20327 mid = (mid + Math.imul(al8, bh7)) | 0;
20328 mid = (mid + Math.imul(ah8, bl7)) | 0;
20329 hi = (hi + Math.imul(ah8, bh7)) | 0;
20330 lo = (lo + Math.imul(al7, bl8)) | 0;
20331 mid = (mid + Math.imul(al7, bh8)) | 0;
20332 mid = (mid + Math.imul(ah7, bl8)) | 0;
20333 hi = (hi + Math.imul(ah7, bh8)) | 0;
20334 lo = (lo + Math.imul(al6, bl9)) | 0;
20335 mid = (mid + Math.imul(al6, bh9)) | 0;
20336 mid = (mid + Math.imul(ah6, bl9)) | 0;
20337 hi = (hi + Math.imul(ah6, bh9)) | 0;
20338 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20339 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
20340 w15 &= 0x3ffffff;
20341 /* k = 16 */
20342 lo = Math.imul(al9, bl7);
20343 mid = Math.imul(al9, bh7);
20344 mid = (mid + Math.imul(ah9, bl7)) | 0;
20345 hi = Math.imul(ah9, bh7);
20346 lo = (lo + Math.imul(al8, bl8)) | 0;
20347 mid = (mid + Math.imul(al8, bh8)) | 0;
20348 mid = (mid + Math.imul(ah8, bl8)) | 0;
20349 hi = (hi + Math.imul(ah8, bh8)) | 0;
20350 lo = (lo + Math.imul(al7, bl9)) | 0;
20351 mid = (mid + Math.imul(al7, bh9)) | 0;
20352 mid = (mid + Math.imul(ah7, bl9)) | 0;
20353 hi = (hi + Math.imul(ah7, bh9)) | 0;
20354 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20355 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
20356 w16 &= 0x3ffffff;
20357 /* k = 17 */
20358 lo = Math.imul(al9, bl8);
20359 mid = Math.imul(al9, bh8);
20360 mid = (mid + Math.imul(ah9, bl8)) | 0;
20361 hi = Math.imul(ah9, bh8);
20362 lo = (lo + Math.imul(al8, bl9)) | 0;
20363 mid = (mid + Math.imul(al8, bh9)) | 0;
20364 mid = (mid + Math.imul(ah8, bl9)) | 0;
20365 hi = (hi + Math.imul(ah8, bh9)) | 0;
20366 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20367 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
20368 w17 &= 0x3ffffff;
20369 /* k = 18 */
20370 lo = Math.imul(al9, bl9);
20371 mid = Math.imul(al9, bh9);
20372 mid = (mid + Math.imul(ah9, bl9)) | 0;
20373 hi = Math.imul(ah9, bh9);
20374 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
20375 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
20376 w18 &= 0x3ffffff;
20377 o[0] = w0;
20378 o[1] = w1;
20379 o[2] = w2;
20380 o[3] = w3;
20381 o[4] = w4;
20382 o[5] = w5;
20383 o[6] = w6;
20384 o[7] = w7;
20385 o[8] = w8;
20386 o[9] = w9;
20387 o[10] = w10;
20388 o[11] = w11;
20389 o[12] = w12;
20390 o[13] = w13;
20391 o[14] = w14;
20392 o[15] = w15;
20393 o[16] = w16;
20394 o[17] = w17;
20395 o[18] = w18;
20396 if (c !== 0) {
20397 o[19] = c;
20398 out.length++;
20399 }
20400 return out;
20401 };
20402
20403 // Polyfill comb
20404 if (!Math.imul) {
20405 comb10MulTo = smallMulTo;
20406 }
20407
20408 function bigMulTo (self, num, out) {
20409 out.negative = num.negative ^ self.negative;
20410 out.length = self.length + num.length;
20411
20412 var carry = 0;
20413 var hncarry = 0;
20414 for (var k = 0; k < out.length - 1; k++) {
20415 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
20416 // note that ncarry could be >= 0x3ffffff
20417 var ncarry = hncarry;
20418 hncarry = 0;
20419 var rword = carry & 0x3ffffff;
20420 var maxJ = Math.min(k, num.length - 1);
20421 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
20422 var i = k - j;
20423 var a = self.words[i] | 0;
20424 var b = num.words[j] | 0;
20425 var r = a * b;
20426
20427 var lo = r & 0x3ffffff;
20428 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
20429 lo = (lo + rword) | 0;
20430 rword = lo & 0x3ffffff;
20431 ncarry = (ncarry + (lo >>> 26)) | 0;
20432
20433 hncarry += ncarry >>> 26;
20434 ncarry &= 0x3ffffff;
20435 }
20436 out.words[k] = rword;
20437 carry = ncarry;
20438 ncarry = hncarry;
20439 }
20440 if (carry !== 0) {
20441 out.words[k] = carry;
20442 } else {
20443 out.length--;
20444 }
20445
20446 return out.strip();
20447 }
20448
20449 function jumboMulTo (self, num, out) {
20450 var fftm = new FFTM();
20451 return fftm.mulp(self, num, out);
20452 }
20453
20454 BN.prototype.mulTo = function mulTo (num, out) {
20455 var res;
20456 var len = this.length + num.length;
20457 if (this.length === 10 && num.length === 10) {
20458 res = comb10MulTo(this, num, out);
20459 } else if (len < 63) {
20460 res = smallMulTo(this, num, out);
20461 } else if (len < 1024) {
20462 res = bigMulTo(this, num, out);
20463 } else {
20464 res = jumboMulTo(this, num, out);
20465 }
20466
20467 return res;
20468 };
20469
20470 // Cooley-Tukey algorithm for FFT
20471 // slightly revisited to rely on looping instead of recursion
20472
20473 function FFTM (x, y) {
20474 this.x = x;
20475 this.y = y;
20476 }
20477
20478 FFTM.prototype.makeRBT = function makeRBT (N) {
20479 var t = new Array(N);
20480 var l = BN.prototype._countBits(N) - 1;
20481 for (var i = 0; i < N; i++) {
20482 t[i] = this.revBin(i, l, N);
20483 }
20484
20485 return t;
20486 };
20487
20488 // Returns binary-reversed representation of `x`
20489 FFTM.prototype.revBin = function revBin (x, l, N) {
20490 if (x === 0 || x === N - 1) return x;
20491
20492 var rb = 0;
20493 for (var i = 0; i < l; i++) {
20494 rb |= (x & 1) << (l - i - 1);
20495 x >>= 1;
20496 }
20497
20498 return rb;
20499 };
20500
20501 // Performs "tweedling" phase, therefore 'emulating'
20502 // behaviour of the recursive algorithm
20503 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
20504 for (var i = 0; i < N; i++) {
20505 rtws[i] = rws[rbt[i]];
20506 itws[i] = iws[rbt[i]];
20507 }
20508 };
20509
20510 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
20511 this.permute(rbt, rws, iws, rtws, itws, N);
20512
20513 for (var s = 1; s < N; s <<= 1) {
20514 var l = s << 1;
20515
20516 var rtwdf = Math.cos(2 * Math.PI / l);
20517 var itwdf = Math.sin(2 * Math.PI / l);
20518
20519 for (var p = 0; p < N; p += l) {
20520 var rtwdf_ = rtwdf;
20521 var itwdf_ = itwdf;
20522
20523 for (var j = 0; j < s; j++) {
20524 var re = rtws[p + j];
20525 var ie = itws[p + j];
20526
20527 var ro = rtws[p + j + s];
20528 var io = itws[p + j + s];
20529
20530 var rx = rtwdf_ * ro - itwdf_ * io;
20531
20532 io = rtwdf_ * io + itwdf_ * ro;
20533 ro = rx;
20534
20535 rtws[p + j] = re + ro;
20536 itws[p + j] = ie + io;
20537
20538 rtws[p + j + s] = re - ro;
20539 itws[p + j + s] = ie - io;
20540
20541 /* jshint maxdepth : false */
20542 if (j !== l) {
20543 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
20544
20545 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
20546 rtwdf_ = rx;
20547 }
20548 }
20549 }
20550 }
20551 };
20552
20553 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
20554 var N = Math.max(m, n) | 1;
20555 var odd = N & 1;
20556 var i = 0;
20557 for (N = N / 2 | 0; N; N = N >>> 1) {
20558 i++;
20559 }
20560
20561 return 1 << i + 1 + odd;
20562 };
20563
20564 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
20565 if (N <= 1) return;
20566
20567 for (var i = 0; i < N / 2; i++) {
20568 var t = rws[i];
20569
20570 rws[i] = rws[N - i - 1];
20571 rws[N - i - 1] = t;
20572
20573 t = iws[i];
20574
20575 iws[i] = -iws[N - i - 1];
20576 iws[N - i - 1] = -t;
20577 }
20578 };
20579
20580 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
20581 var carry = 0;
20582 for (var i = 0; i < N / 2; i++) {
20583 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
20584 Math.round(ws[2 * i] / N) +
20585 carry;
20586
20587 ws[i] = w & 0x3ffffff;
20588
20589 if (w < 0x4000000) {
20590 carry = 0;
20591 } else {
20592 carry = w / 0x4000000 | 0;
20593 }
20594 }
20595
20596 return ws;
20597 };
20598
20599 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
20600 var carry = 0;
20601 for (var i = 0; i < len; i++) {
20602 carry = carry + (ws[i] | 0);
20603
20604 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
20605 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
20606 }
20607
20608 // Pad with zeroes
20609 for (i = 2 * len; i < N; ++i) {
20610 rws[i] = 0;
20611 }
20612
20613 assert(carry === 0);
20614 assert((carry & ~0x1fff) === 0);
20615 };
20616
20617 FFTM.prototype.stub = function stub (N) {
20618 var ph = new Array(N);
20619 for (var i = 0; i < N; i++) {
20620 ph[i] = 0;
20621 }
20622
20623 return ph;
20624 };
20625
20626 FFTM.prototype.mulp = function mulp (x, y, out) {
20627 var N = 2 * this.guessLen13b(x.length, y.length);
20628
20629 var rbt = this.makeRBT(N);
20630
20631 var _ = this.stub(N);
20632
20633 var rws = new Array(N);
20634 var rwst = new Array(N);
20635 var iwst = new Array(N);
20636
20637 var nrws = new Array(N);
20638 var nrwst = new Array(N);
20639 var niwst = new Array(N);
20640
20641 var rmws = out.words;
20642 rmws.length = N;
20643
20644 this.convert13b(x.words, x.length, rws, N);
20645 this.convert13b(y.words, y.length, nrws, N);
20646
20647 this.transform(rws, _, rwst, iwst, N, rbt);
20648 this.transform(nrws, _, nrwst, niwst, N, rbt);
20649
20650 for (var i = 0; i < N; i++) {
20651 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
20652 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
20653 rwst[i] = rx;
20654 }
20655
20656 this.conjugate(rwst, iwst, N);
20657 this.transform(rwst, iwst, rmws, _, N, rbt);
20658 this.conjugate(rmws, _, N);
20659 this.normalize13b(rmws, N);
20660
20661 out.negative = x.negative ^ y.negative;
20662 out.length = x.length + y.length;
20663 return out.strip();
20664 };
20665
20666 // Multiply `this` by `num`
20667 BN.prototype.mul = function mul (num) {
20668 var out = new BN(null);
20669 out.words = new Array(this.length + num.length);
20670 return this.mulTo(num, out);
20671 };
20672
20673 // Multiply employing FFT
20674 BN.prototype.mulf = function mulf (num) {
20675 var out = new BN(null);
20676 out.words = new Array(this.length + num.length);
20677 return jumboMulTo(this, num, out);
20678 };
20679
20680 // In-place Multiplication
20681 BN.prototype.imul = function imul (num) {
20682 return this.clone().mulTo(num, this);
20683 };
20684
20685 BN.prototype.imuln = function imuln (num) {
20686 assert(typeof num === 'number');
20687 assert(num < 0x4000000);
20688
20689 // Carry
20690 var carry = 0;
20691 for (var i = 0; i < this.length; i++) {
20692 var w = (this.words[i] | 0) * num;
20693 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
20694 carry >>= 26;
20695 carry += (w / 0x4000000) | 0;
20696 // NOTE: lo is 27bit maximum
20697 carry += lo >>> 26;
20698 this.words[i] = lo & 0x3ffffff;
20699 }
20700
20701 if (carry !== 0) {
20702 this.words[i] = carry;
20703 this.length++;
20704 }
20705
20706 return this;
20707 };
20708
20709 BN.prototype.muln = function muln (num) {
20710 return this.clone().imuln(num);
20711 };
20712
20713 // `this` * `this`
20714 BN.prototype.sqr = function sqr () {
20715 return this.mul(this);
20716 };
20717
20718 // `this` * `this` in-place
20719 BN.prototype.isqr = function isqr () {
20720 return this.imul(this.clone());
20721 };
20722
20723 // Math.pow(`this`, `num`)
20724 BN.prototype.pow = function pow (num) {
20725 var w = toBitArray(num);
20726 if (w.length === 0) return new BN(1);
20727
20728 // Skip leading zeroes
20729 var res = this;
20730 for (var i = 0; i < w.length; i++, res = res.sqr()) {
20731 if (w[i] !== 0) break;
20732 }
20733
20734 if (++i < w.length) {
20735 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
20736 if (w[i] === 0) continue;
20737
20738 res = res.mul(q);
20739 }
20740 }
20741
20742 return res;
20743 };
20744
20745 // Shift-left in-place
20746 BN.prototype.iushln = function iushln (bits) {
20747 assert(typeof bits === 'number' && bits >= 0);
20748 var r = bits % 26;
20749 var s = (bits - r) / 26;
20750 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
20751 var i;
20752
20753 if (r !== 0) {
20754 var carry = 0;
20755
20756 for (i = 0; i < this.length; i++) {
20757 var newCarry = this.words[i] & carryMask;
20758 var c = ((this.words[i] | 0) - newCarry) << r;
20759 this.words[i] = c | carry;
20760 carry = newCarry >>> (26 - r);
20761 }
20762
20763 if (carry) {
20764 this.words[i] = carry;
20765 this.length++;
20766 }
20767 }
20768
20769 if (s !== 0) {
20770 for (i = this.length - 1; i >= 0; i--) {
20771 this.words[i + s] = this.words[i];
20772 }
20773
20774 for (i = 0; i < s; i++) {
20775 this.words[i] = 0;
20776 }
20777
20778 this.length += s;
20779 }
20780
20781 return this.strip();
20782 };
20783
20784 BN.prototype.ishln = function ishln (bits) {
20785 // TODO(indutny): implement me
20786 assert(this.negative === 0);
20787 return this.iushln(bits);
20788 };
20789
20790 // Shift-right in-place
20791 // NOTE: `hint` is a lowest bit before trailing zeroes
20792 // NOTE: if `extended` is present - it will be filled with destroyed bits
20793 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
20794 assert(typeof bits === 'number' && bits >= 0);
20795 var h;
20796 if (hint) {
20797 h = (hint - (hint % 26)) / 26;
20798 } else {
20799 h = 0;
20800 }
20801
20802 var r = bits % 26;
20803 var s = Math.min((bits - r) / 26, this.length);
20804 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
20805 var maskedWords = extended;
20806
20807 h -= s;
20808 h = Math.max(0, h);
20809
20810 // Extended mode, copy masked part
20811 if (maskedWords) {
20812 for (var i = 0; i < s; i++) {
20813 maskedWords.words[i] = this.words[i];
20814 }
20815 maskedWords.length = s;
20816 }
20817
20818 if (s === 0) {
20819 // No-op, we should not move anything at all
20820 } else if (this.length > s) {
20821 this.length -= s;
20822 for (i = 0; i < this.length; i++) {
20823 this.words[i] = this.words[i + s];
20824 }
20825 } else {
20826 this.words[0] = 0;
20827 this.length = 1;
20828 }
20829
20830 var carry = 0;
20831 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
20832 var word = this.words[i] | 0;
20833 this.words[i] = (carry << (26 - r)) | (word >>> r);
20834 carry = word & mask;
20835 }
20836
20837 // Push carried bits as a mask
20838 if (maskedWords && carry !== 0) {
20839 maskedWords.words[maskedWords.length++] = carry;
20840 }
20841
20842 if (this.length === 0) {
20843 this.words[0] = 0;
20844 this.length = 1;
20845 }
20846
20847 return this.strip();
20848 };
20849
20850 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
20851 // TODO(indutny): implement me
20852 assert(this.negative === 0);
20853 return this.iushrn(bits, hint, extended);
20854 };
20855
20856 // Shift-left
20857 BN.prototype.shln = function shln (bits) {
20858 return this.clone().ishln(bits);
20859 };
20860
20861 BN.prototype.ushln = function ushln (bits) {
20862 return this.clone().iushln(bits);
20863 };
20864
20865 // Shift-right
20866 BN.prototype.shrn = function shrn (bits) {
20867 return this.clone().ishrn(bits);
20868 };
20869
20870 BN.prototype.ushrn = function ushrn (bits) {
20871 return this.clone().iushrn(bits);
20872 };
20873
20874 // Test if n bit is set
20875 BN.prototype.testn = function testn (bit) {
20876 assert(typeof bit === 'number' && bit >= 0);
20877 var r = bit % 26;
20878 var s = (bit - r) / 26;
20879 var q = 1 << r;
20880
20881 // Fast case: bit is much higher than all existing words
20882 if (this.length <= s) return false;
20883
20884 // Check bit and return
20885 var w = this.words[s];
20886
20887 return !!(w & q);
20888 };
20889
20890 // Return only lowers bits of number (in-place)
20891 BN.prototype.imaskn = function imaskn (bits) {
20892 assert(typeof bits === 'number' && bits >= 0);
20893 var r = bits % 26;
20894 var s = (bits - r) / 26;
20895
20896 assert(this.negative === 0, 'imaskn works only with positive numbers');
20897
20898 if (this.length <= s) {
20899 return this;
20900 }
20901
20902 if (r !== 0) {
20903 s++;
20904 }
20905 this.length = Math.min(s, this.length);
20906
20907 if (r !== 0) {
20908 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
20909 this.words[this.length - 1] &= mask;
20910 }
20911
20912 return this.strip();
20913 };
20914
20915 // Return only lowers bits of number
20916 BN.prototype.maskn = function maskn (bits) {
20917 return this.clone().imaskn(bits);
20918 };
20919
20920 // Add plain number `num` to `this`
20921 BN.prototype.iaddn = function iaddn (num) {
20922 assert(typeof num === 'number');
20923 assert(num < 0x4000000);
20924 if (num < 0) return this.isubn(-num);
20925
20926 // Possible sign change
20927 if (this.negative !== 0) {
20928 if (this.length === 1 && (this.words[0] | 0) < num) {
20929 this.words[0] = num - (this.words[0] | 0);
20930 this.negative = 0;
20931 return this;
20932 }
20933
20934 this.negative = 0;
20935 this.isubn(num);
20936 this.negative = 1;
20937 return this;
20938 }
20939
20940 // Add without checks
20941 return this._iaddn(num);
20942 };
20943
20944 BN.prototype._iaddn = function _iaddn (num) {
20945 this.words[0] += num;
20946
20947 // Carry
20948 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
20949 this.words[i] -= 0x4000000;
20950 if (i === this.length - 1) {
20951 this.words[i + 1] = 1;
20952 } else {
20953 this.words[i + 1]++;
20954 }
20955 }
20956 this.length = Math.max(this.length, i + 1);
20957
20958 return this;
20959 };
20960
20961 // Subtract plain number `num` from `this`
20962 BN.prototype.isubn = function isubn (num) {
20963 assert(typeof num === 'number');
20964 assert(num < 0x4000000);
20965 if (num < 0) return this.iaddn(-num);
20966
20967 if (this.negative !== 0) {
20968 this.negative = 0;
20969 this.iaddn(num);
20970 this.negative = 1;
20971 return this;
20972 }
20973
20974 this.words[0] -= num;
20975
20976 if (this.length === 1 && this.words[0] < 0) {
20977 this.words[0] = -this.words[0];
20978 this.negative = 1;
20979 } else {
20980 // Carry
20981 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
20982 this.words[i] += 0x4000000;
20983 this.words[i + 1] -= 1;
20984 }
20985 }
20986
20987 return this.strip();
20988 };
20989
20990 BN.prototype.addn = function addn (num) {
20991 return this.clone().iaddn(num);
20992 };
20993
20994 BN.prototype.subn = function subn (num) {
20995 return this.clone().isubn(num);
20996 };
20997
20998 BN.prototype.iabs = function iabs () {
20999 this.negative = 0;
21000
21001 return this;
21002 };
21003
21004 BN.prototype.abs = function abs () {
21005 return this.clone().iabs();
21006 };
21007
21008 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
21009 var len = num.length + shift;
21010 var i;
21011
21012 this._expand(len);
21013
21014 var w;
21015 var carry = 0;
21016 for (i = 0; i < num.length; i++) {
21017 w = (this.words[i + shift] | 0) + carry;
21018 var right = (num.words[i] | 0) * mul;
21019 w -= right & 0x3ffffff;
21020 carry = (w >> 26) - ((right / 0x4000000) | 0);
21021 this.words[i + shift] = w & 0x3ffffff;
21022 }
21023 for (; i < this.length - shift; i++) {
21024 w = (this.words[i + shift] | 0) + carry;
21025 carry = w >> 26;
21026 this.words[i + shift] = w & 0x3ffffff;
21027 }
21028
21029 if (carry === 0) return this.strip();
21030
21031 // Subtraction overflow
21032 assert(carry === -1);
21033 carry = 0;
21034 for (i = 0; i < this.length; i++) {
21035 w = -(this.words[i] | 0) + carry;
21036 carry = w >> 26;
21037 this.words[i] = w & 0x3ffffff;
21038 }
21039 this.negative = 1;
21040
21041 return this.strip();
21042 };
21043
21044 BN.prototype._wordDiv = function _wordDiv (num, mode) {
21045 var shift = this.length - num.length;
21046
21047 var a = this.clone();
21048 var b = num;
21049
21050 // Normalize
21051 var bhi = b.words[b.length - 1] | 0;
21052 var bhiBits = this._countBits(bhi);
21053 shift = 26 - bhiBits;
21054 if (shift !== 0) {
21055 b = b.ushln(shift);
21056 a.iushln(shift);
21057 bhi = b.words[b.length - 1] | 0;
21058 }
21059
21060 // Initialize quotient
21061 var m = a.length - b.length;
21062 var q;
21063
21064 if (mode !== 'mod') {
21065 q = new BN(null);
21066 q.length = m + 1;
21067 q.words = new Array(q.length);
21068 for (var i = 0; i < q.length; i++) {
21069 q.words[i] = 0;
21070 }
21071 }
21072
21073 var diff = a.clone()._ishlnsubmul(b, 1, m);
21074 if (diff.negative === 0) {
21075 a = diff;
21076 if (q) {
21077 q.words[m] = 1;
21078 }
21079 }
21080
21081 for (var j = m - 1; j >= 0; j--) {
21082 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
21083 (a.words[b.length + j - 1] | 0);
21084
21085 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
21086 // (0x7ffffff)
21087 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
21088
21089 a._ishlnsubmul(b, qj, j);
21090 while (a.negative !== 0) {
21091 qj--;
21092 a.negative = 0;
21093 a._ishlnsubmul(b, 1, j);
21094 if (!a.isZero()) {
21095 a.negative ^= 1;
21096 }
21097 }
21098 if (q) {
21099 q.words[j] = qj;
21100 }
21101 }
21102 if (q) {
21103 q.strip();
21104 }
21105 a.strip();
21106
21107 // Denormalize
21108 if (mode !== 'div' && shift !== 0) {
21109 a.iushrn(shift);
21110 }
21111
21112 return {
21113 div: q || null,
21114 mod: a
21115 };
21116 };
21117
21118 // NOTE: 1) `mode` can be set to `mod` to request mod only,
21119 // to `div` to request div only, or be absent to
21120 // request both div & mod
21121 // 2) `positive` is true if unsigned mod is requested
21122 BN.prototype.divmod = function divmod (num, mode, positive) {
21123 assert(!num.isZero());
21124
21125 if (this.isZero()) {
21126 return {
21127 div: new BN(0),
21128 mod: new BN(0)
21129 };
21130 }
21131
21132 var div, mod, res;
21133 if (this.negative !== 0 && num.negative === 0) {
21134 res = this.neg().divmod(num, mode);
21135
21136 if (mode !== 'mod') {
21137 div = res.div.neg();
21138 }
21139
21140 if (mode !== 'div') {
21141 mod = res.mod.neg();
21142 if (positive && mod.negative !== 0) {
21143 mod.iadd(num);
21144 }
21145 }
21146
21147 return {
21148 div: div,
21149 mod: mod
21150 };
21151 }
21152
21153 if (this.negative === 0 && num.negative !== 0) {
21154 res = this.divmod(num.neg(), mode);
21155
21156 if (mode !== 'mod') {
21157 div = res.div.neg();
21158 }
21159
21160 return {
21161 div: div,
21162 mod: res.mod
21163 };
21164 }
21165
21166 if ((this.negative & num.negative) !== 0) {
21167 res = this.neg().divmod(num.neg(), mode);
21168
21169 if (mode !== 'div') {
21170 mod = res.mod.neg();
21171 if (positive && mod.negative !== 0) {
21172 mod.isub(num);
21173 }
21174 }
21175
21176 return {
21177 div: res.div,
21178 mod: mod
21179 };
21180 }
21181
21182 // Both numbers are positive at this point
21183
21184 // Strip both numbers to approximate shift value
21185 if (num.length > this.length || this.cmp(num) < 0) {
21186 return {
21187 div: new BN(0),
21188 mod: this
21189 };
21190 }
21191
21192 // Very short reduction
21193 if (num.length === 1) {
21194 if (mode === 'div') {
21195 return {
21196 div: this.divn(num.words[0]),
21197 mod: null
21198 };
21199 }
21200
21201 if (mode === 'mod') {
21202 return {
21203 div: null,
21204 mod: new BN(this.modn(num.words[0]))
21205 };
21206 }
21207
21208 return {
21209 div: this.divn(num.words[0]),
21210 mod: new BN(this.modn(num.words[0]))
21211 };
21212 }
21213
21214 return this._wordDiv(num, mode);
21215 };
21216
21217 // Find `this` / `num`
21218 BN.prototype.div = function div (num) {
21219 return this.divmod(num, 'div', false).div;
21220 };
21221
21222 // Find `this` % `num`
21223 BN.prototype.mod = function mod (num) {
21224 return this.divmod(num, 'mod', false).mod;
21225 };
21226
21227 BN.prototype.umod = function umod (num) {
21228 return this.divmod(num, 'mod', true).mod;
21229 };
21230
21231 // Find Round(`this` / `num`)
21232 BN.prototype.divRound = function divRound (num) {
21233 var dm = this.divmod(num);
21234
21235 // Fast case - exact division
21236 if (dm.mod.isZero()) return dm.div;
21237
21238 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
21239
21240 var half = num.ushrn(1);
21241 var r2 = num.andln(1);
21242 var cmp = mod.cmp(half);
21243
21244 // Round down
21245 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
21246
21247 // Round up
21248 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
21249 };
21250
21251 BN.prototype.modn = function modn (num) {
21252 assert(num <= 0x3ffffff);
21253 var p = (1 << 26) % num;
21254
21255 var acc = 0;
21256 for (var i = this.length - 1; i >= 0; i--) {
21257 acc = (p * acc + (this.words[i] | 0)) % num;
21258 }
21259
21260 return acc;
21261 };
21262
21263 // In-place division by number
21264 BN.prototype.idivn = function idivn (num) {
21265 assert(num <= 0x3ffffff);
21266
21267 var carry = 0;
21268 for (var i = this.length - 1; i >= 0; i--) {
21269 var w = (this.words[i] | 0) + carry * 0x4000000;
21270 this.words[i] = (w / num) | 0;
21271 carry = w % num;
21272 }
21273
21274 return this.strip();
21275 };
21276
21277 BN.prototype.divn = function divn (num) {
21278 return this.clone().idivn(num);
21279 };
21280
21281 BN.prototype.egcd = function egcd (p) {
21282 assert(p.negative === 0);
21283 assert(!p.isZero());
21284
21285 var x = this;
21286 var y = p.clone();
21287
21288 if (x.negative !== 0) {
21289 x = x.umod(p);
21290 } else {
21291 x = x.clone();
21292 }
21293
21294 // A * x + B * y = x
21295 var A = new BN(1);
21296 var B = new BN(0);
21297
21298 // C * x + D * y = y
21299 var C = new BN(0);
21300 var D = new BN(1);
21301
21302 var g = 0;
21303
21304 while (x.isEven() && y.isEven()) {
21305 x.iushrn(1);
21306 y.iushrn(1);
21307 ++g;
21308 }
21309
21310 var yp = y.clone();
21311 var xp = x.clone();
21312
21313 while (!x.isZero()) {
21314 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
21315 if (i > 0) {
21316 x.iushrn(i);
21317 while (i-- > 0) {
21318 if (A.isOdd() || B.isOdd()) {
21319 A.iadd(yp);
21320 B.isub(xp);
21321 }
21322
21323 A.iushrn(1);
21324 B.iushrn(1);
21325 }
21326 }
21327
21328 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
21329 if (j > 0) {
21330 y.iushrn(j);
21331 while (j-- > 0) {
21332 if (C.isOdd() || D.isOdd()) {
21333 C.iadd(yp);
21334 D.isub(xp);
21335 }
21336
21337 C.iushrn(1);
21338 D.iushrn(1);
21339 }
21340 }
21341
21342 if (x.cmp(y) >= 0) {
21343 x.isub(y);
21344 A.isub(C);
21345 B.isub(D);
21346 } else {
21347 y.isub(x);
21348 C.isub(A);
21349 D.isub(B);
21350 }
21351 }
21352
21353 return {
21354 a: C,
21355 b: D,
21356 gcd: y.iushln(g)
21357 };
21358 };
21359
21360 // This is reduced incarnation of the binary EEA
21361 // above, designated to invert members of the
21362 // _prime_ fields F(p) at a maximal speed
21363 BN.prototype._invmp = function _invmp (p) {
21364 assert(p.negative === 0);
21365 assert(!p.isZero());
21366
21367 var a = this;
21368 var b = p.clone();
21369
21370 if (a.negative !== 0) {
21371 a = a.umod(p);
21372 } else {
21373 a = a.clone();
21374 }
21375
21376 var x1 = new BN(1);
21377 var x2 = new BN(0);
21378
21379 var delta = b.clone();
21380
21381 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
21382 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
21383 if (i > 0) {
21384 a.iushrn(i);
21385 while (i-- > 0) {
21386 if (x1.isOdd()) {
21387 x1.iadd(delta);
21388 }
21389
21390 x1.iushrn(1);
21391 }
21392 }
21393
21394 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
21395 if (j > 0) {
21396 b.iushrn(j);
21397 while (j-- > 0) {
21398 if (x2.isOdd()) {
21399 x2.iadd(delta);
21400 }
21401
21402 x2.iushrn(1);
21403 }
21404 }
21405
21406 if (a.cmp(b) >= 0) {
21407 a.isub(b);
21408 x1.isub(x2);
21409 } else {
21410 b.isub(a);
21411 x2.isub(x1);
21412 }
21413 }
21414
21415 var res;
21416 if (a.cmpn(1) === 0) {
21417 res = x1;
21418 } else {
21419 res = x2;
21420 }
21421
21422 if (res.cmpn(0) < 0) {
21423 res.iadd(p);
21424 }
21425
21426 return res;
21427 };
21428
21429 BN.prototype.gcd = function gcd (num) {
21430 if (this.isZero()) return num.abs();
21431 if (num.isZero()) return this.abs();
21432
21433 var a = this.clone();
21434 var b = num.clone();
21435 a.negative = 0;
21436 b.negative = 0;
21437
21438 // Remove common factor of two
21439 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
21440 a.iushrn(1);
21441 b.iushrn(1);
21442 }
21443
21444 do {
21445 while (a.isEven()) {
21446 a.iushrn(1);
21447 }
21448 while (b.isEven()) {
21449 b.iushrn(1);
21450 }
21451
21452 var r = a.cmp(b);
21453 if (r < 0) {
21454 // Swap `a` and `b` to make `a` always bigger than `b`
21455 var t = a;
21456 a = b;
21457 b = t;
21458 } else if (r === 0 || b.cmpn(1) === 0) {
21459 break;
21460 }
21461
21462 a.isub(b);
21463 } while (true);
21464
21465 return b.iushln(shift);
21466 };
21467
21468 // Invert number in the field F(num)
21469 BN.prototype.invm = function invm (num) {
21470 return this.egcd(num).a.umod(num);
21471 };
21472
21473 BN.prototype.isEven = function isEven () {
21474 return (this.words[0] & 1) === 0;
21475 };
21476
21477 BN.prototype.isOdd = function isOdd () {
21478 return (this.words[0] & 1) === 1;
21479 };
21480
21481 // And first word and num
21482 BN.prototype.andln = function andln (num) {
21483 return this.words[0] & num;
21484 };
21485
21486 // Increment at the bit position in-line
21487 BN.prototype.bincn = function bincn (bit) {
21488 assert(typeof bit === 'number');
21489 var r = bit % 26;
21490 var s = (bit - r) / 26;
21491 var q = 1 << r;
21492
21493 // Fast case: bit is much higher than all existing words
21494 if (this.length <= s) {
21495 this._expand(s + 1);
21496 this.words[s] |= q;
21497 return this;
21498 }
21499
21500 // Add bit and propagate, if needed
21501 var carry = q;
21502 for (var i = s; carry !== 0 && i < this.length; i++) {
21503 var w = this.words[i] | 0;
21504 w += carry;
21505 carry = w >>> 26;
21506 w &= 0x3ffffff;
21507 this.words[i] = w;
21508 }
21509 if (carry !== 0) {
21510 this.words[i] = carry;
21511 this.length++;
21512 }
21513 return this;
21514 };
21515
21516 BN.prototype.isZero = function isZero () {
21517 return this.length === 1 && this.words[0] === 0;
21518 };
21519
21520 BN.prototype.cmpn = function cmpn (num) {
21521 var negative = num < 0;
21522
21523 if (this.negative !== 0 && !negative) return -1;
21524 if (this.negative === 0 && negative) return 1;
21525
21526 this.strip();
21527
21528 var res;
21529 if (this.length > 1) {
21530 res = 1;
21531 } else {
21532 if (negative) {
21533 num = -num;
21534 }
21535
21536 assert(num <= 0x3ffffff, 'Number is too big');
21537
21538 var w = this.words[0] | 0;
21539 res = w === num ? 0 : w < num ? -1 : 1;
21540 }
21541 if (this.negative !== 0) return -res | 0;
21542 return res;
21543 };
21544
21545 // Compare two numbers and return:
21546 // 1 - if `this` > `num`
21547 // 0 - if `this` == `num`
21548 // -1 - if `this` < `num`
21549 BN.prototype.cmp = function cmp (num) {
21550 if (this.negative !== 0 && num.negative === 0) return -1;
21551 if (this.negative === 0 && num.negative !== 0) return 1;
21552
21553 var res = this.ucmp(num);
21554 if (this.negative !== 0) return -res | 0;
21555 return res;
21556 };
21557
21558 // Unsigned comparison
21559 BN.prototype.ucmp = function ucmp (num) {
21560 // At this point both numbers have the same sign
21561 if (this.length > num.length) return 1;
21562 if (this.length < num.length) return -1;
21563
21564 var res = 0;
21565 for (var i = this.length - 1; i >= 0; i--) {
21566 var a = this.words[i] | 0;
21567 var b = num.words[i] | 0;
21568
21569 if (a === b) continue;
21570 if (a < b) {
21571 res = -1;
21572 } else if (a > b) {
21573 res = 1;
21574 }
21575 break;
21576 }
21577 return res;
21578 };
21579
21580 BN.prototype.gtn = function gtn (num) {
21581 return this.cmpn(num) === 1;
21582 };
21583
21584 BN.prototype.gt = function gt (num) {
21585 return this.cmp(num) === 1;
21586 };
21587
21588 BN.prototype.gten = function gten (num) {
21589 return this.cmpn(num) >= 0;
21590 };
21591
21592 BN.prototype.gte = function gte (num) {
21593 return this.cmp(num) >= 0;
21594 };
21595
21596 BN.prototype.ltn = function ltn (num) {
21597 return this.cmpn(num) === -1;
21598 };
21599
21600 BN.prototype.lt = function lt (num) {
21601 return this.cmp(num) === -1;
21602 };
21603
21604 BN.prototype.lten = function lten (num) {
21605 return this.cmpn(num) <= 0;
21606 };
21607
21608 BN.prototype.lte = function lte (num) {
21609 return this.cmp(num) <= 0;
21610 };
21611
21612 BN.prototype.eqn = function eqn (num) {
21613 return this.cmpn(num) === 0;
21614 };
21615
21616 BN.prototype.eq = function eq (num) {
21617 return this.cmp(num) === 0;
21618 };
21619
21620 //
21621 // A reduce context, could be using montgomery or something better, depending
21622 // on the `m` itself.
21623 //
21624 BN.red = function red (num) {
21625 return new Red(num);
21626 };
21627
21628 BN.prototype.toRed = function toRed (ctx) {
21629 assert(!this.red, 'Already a number in reduction context');
21630 assert(this.negative === 0, 'red works only with positives');
21631 return ctx.convertTo(this)._forceRed(ctx);
21632 };
21633
21634 BN.prototype.fromRed = function fromRed () {
21635 assert(this.red, 'fromRed works only with numbers in reduction context');
21636 return this.red.convertFrom(this);
21637 };
21638
21639 BN.prototype._forceRed = function _forceRed (ctx) {
21640 this.red = ctx;
21641 return this;
21642 };
21643
21644 BN.prototype.forceRed = function forceRed (ctx) {
21645 assert(!this.red, 'Already a number in reduction context');
21646 return this._forceRed(ctx);
21647 };
21648
21649 BN.prototype.redAdd = function redAdd (num) {
21650 assert(this.red, 'redAdd works only with red numbers');
21651 return this.red.add(this, num);
21652 };
21653
21654 BN.prototype.redIAdd = function redIAdd (num) {
21655 assert(this.red, 'redIAdd works only with red numbers');
21656 return this.red.iadd(this, num);
21657 };
21658
21659 BN.prototype.redSub = function redSub (num) {
21660 assert(this.red, 'redSub works only with red numbers');
21661 return this.red.sub(this, num);
21662 };
21663
21664 BN.prototype.redISub = function redISub (num) {
21665 assert(this.red, 'redISub works only with red numbers');
21666 return this.red.isub(this, num);
21667 };
21668
21669 BN.prototype.redShl = function redShl (num) {
21670 assert(this.red, 'redShl works only with red numbers');
21671 return this.red.shl(this, num);
21672 };
21673
21674 BN.prototype.redMul = function redMul (num) {
21675 assert(this.red, 'redMul works only with red numbers');
21676 this.red._verify2(this, num);
21677 return this.red.mul(this, num);
21678 };
21679
21680 BN.prototype.redIMul = function redIMul (num) {
21681 assert(this.red, 'redMul works only with red numbers');
21682 this.red._verify2(this, num);
21683 return this.red.imul(this, num);
21684 };
21685
21686 BN.prototype.redSqr = function redSqr () {
21687 assert(this.red, 'redSqr works only with red numbers');
21688 this.red._verify1(this);
21689 return this.red.sqr(this);
21690 };
21691
21692 BN.prototype.redISqr = function redISqr () {
21693 assert(this.red, 'redISqr works only with red numbers');
21694 this.red._verify1(this);
21695 return this.red.isqr(this);
21696 };
21697
21698 // Square root over p
21699 BN.prototype.redSqrt = function redSqrt () {
21700 assert(this.red, 'redSqrt works only with red numbers');
21701 this.red._verify1(this);
21702 return this.red.sqrt(this);
21703 };
21704
21705 BN.prototype.redInvm = function redInvm () {
21706 assert(this.red, 'redInvm works only with red numbers');
21707 this.red._verify1(this);
21708 return this.red.invm(this);
21709 };
21710
21711 // Return negative clone of `this` % `red modulo`
21712 BN.prototype.redNeg = function redNeg () {
21713 assert(this.red, 'redNeg works only with red numbers');
21714 this.red._verify1(this);
21715 return this.red.neg(this);
21716 };
21717
21718 BN.prototype.redPow = function redPow (num) {
21719 assert(this.red && !num.red, 'redPow(normalNum)');
21720 this.red._verify1(this);
21721 return this.red.pow(this, num);
21722 };
21723
21724 // Prime numbers with efficient reduction
21725 var primes = {
21726 k256: null,
21727 p224: null,
21728 p192: null,
21729 p25519: null
21730 };
21731
21732 // Pseudo-Mersenne prime
21733 function MPrime (name, p) {
21734 // P = 2 ^ N - K
21735 this.name = name;
21736 this.p = new BN(p, 16);
21737 this.n = this.p.bitLength();
21738 this.k = new BN(1).iushln(this.n).isub(this.p);
21739
21740 this.tmp = this._tmp();
21741 }
21742
21743 MPrime.prototype._tmp = function _tmp () {
21744 var tmp = new BN(null);
21745 tmp.words = new Array(Math.ceil(this.n / 13));
21746 return tmp;
21747 };
21748
21749 MPrime.prototype.ireduce = function ireduce (num) {
21750 // Assumes that `num` is less than `P^2`
21751 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
21752 var r = num;
21753 var rlen;
21754
21755 do {
21756 this.split(r, this.tmp);
21757 r = this.imulK(r);
21758 r = r.iadd(this.tmp);
21759 rlen = r.bitLength();
21760 } while (rlen > this.n);
21761
21762 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
21763 if (cmp === 0) {
21764 r.words[0] = 0;
21765 r.length = 1;
21766 } else if (cmp > 0) {
21767 r.isub(this.p);
21768 } else {
21769 r.strip();
21770 }
21771
21772 return r;
21773 };
21774
21775 MPrime.prototype.split = function split (input, out) {
21776 input.iushrn(this.n, 0, out);
21777 };
21778
21779 MPrime.prototype.imulK = function imulK (num) {
21780 return num.imul(this.k);
21781 };
21782
21783 function K256 () {
21784 MPrime.call(
21785 this,
21786 'k256',
21787 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
21788 }
21789 inherits(K256, MPrime);
21790
21791 K256.prototype.split = function split (input, output) {
21792 // 256 = 9 * 26 + 22
21793 var mask = 0x3fffff;
21794
21795 var outLen = Math.min(input.length, 9);
21796 for (var i = 0; i < outLen; i++) {
21797 output.words[i] = input.words[i];
21798 }
21799 output.length = outLen;
21800
21801 if (input.length <= 9) {
21802 input.words[0] = 0;
21803 input.length = 1;
21804 return;
21805 }
21806
21807 // Shift by 9 limbs
21808 var prev = input.words[9];
21809 output.words[output.length++] = prev & mask;
21810
21811 for (i = 10; i < input.length; i++) {
21812 var next = input.words[i] | 0;
21813 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
21814 prev = next;
21815 }
21816 prev >>>= 22;
21817 input.words[i - 10] = prev;
21818 if (prev === 0 && input.length > 10) {
21819 input.length -= 10;
21820 } else {
21821 input.length -= 9;
21822 }
21823 };
21824
21825 K256.prototype.imulK = function imulK (num) {
21826 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
21827 num.words[num.length] = 0;
21828 num.words[num.length + 1] = 0;
21829 num.length += 2;
21830
21831 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
21832 var lo = 0;
21833 for (var i = 0; i < num.length; i++) {
21834 var w = num.words[i] | 0;
21835 lo += w * 0x3d1;
21836 num.words[i] = lo & 0x3ffffff;
21837 lo = w * 0x40 + ((lo / 0x4000000) | 0);
21838 }
21839
21840 // Fast length reduction
21841 if (num.words[num.length - 1] === 0) {
21842 num.length--;
21843 if (num.words[num.length - 1] === 0) {
21844 num.length--;
21845 }
21846 }
21847 return num;
21848 };
21849
21850 function P224 () {
21851 MPrime.call(
21852 this,
21853 'p224',
21854 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
21855 }
21856 inherits(P224, MPrime);
21857
21858 function P192 () {
21859 MPrime.call(
21860 this,
21861 'p192',
21862 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
21863 }
21864 inherits(P192, MPrime);
21865
21866 function P25519 () {
21867 // 2 ^ 255 - 19
21868 MPrime.call(
21869 this,
21870 '25519',
21871 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
21872 }
21873 inherits(P25519, MPrime);
21874
21875 P25519.prototype.imulK = function imulK (num) {
21876 // K = 0x13
21877 var carry = 0;
21878 for (var i = 0; i < num.length; i++) {
21879 var hi = (num.words[i] | 0) * 0x13 + carry;
21880 var lo = hi & 0x3ffffff;
21881 hi >>>= 26;
21882
21883 num.words[i] = lo;
21884 carry = hi;
21885 }
21886 if (carry !== 0) {
21887 num.words[num.length++] = carry;
21888 }
21889 return num;
21890 };
21891
21892 // Exported mostly for testing purposes, use plain name instead
21893 BN._prime = function prime (name) {
21894 // Cached version of prime
21895 if (primes[name]) return primes[name];
21896
21897 var prime;
21898 if (name === 'k256') {
21899 prime = new K256();
21900 } else if (name === 'p224') {
21901 prime = new P224();
21902 } else if (name === 'p192') {
21903 prime = new P192();
21904 } else if (name === 'p25519') {
21905 prime = new P25519();
21906 } else {
21907 throw new Error('Unknown prime ' + name);
21908 }
21909 primes[name] = prime;
21910
21911 return prime;
21912 };
21913
21914 //
21915 // Base reduction engine
21916 //
21917 function Red (m) {
21918 if (typeof m === 'string') {
21919 var prime = BN._prime(m);
21920 this.m = prime.p;
21921 this.prime = prime;
21922 } else {
21923 assert(m.gtn(1), 'modulus must be greater than 1');
21924 this.m = m;
21925 this.prime = null;
21926 }
21927 }
21928
21929 Red.prototype._verify1 = function _verify1 (a) {
21930 assert(a.negative === 0, 'red works only with positives');
21931 assert(a.red, 'red works only with red numbers');
21932 };
21933
21934 Red.prototype._verify2 = function _verify2 (a, b) {
21935 assert((a.negative | b.negative) === 0, 'red works only with positives');
21936 assert(a.red && a.red === b.red,
21937 'red works only with red numbers');
21938 };
21939
21940 Red.prototype.imod = function imod (a) {
21941 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
21942 return a.umod(this.m)._forceRed(this);
21943 };
21944
21945 Red.prototype.neg = function neg (a) {
21946 if (a.isZero()) {
21947 return a.clone();
21948 }
21949
21950 return this.m.sub(a)._forceRed(this);
21951 };
21952
21953 Red.prototype.add = function add (a, b) {
21954 this._verify2(a, b);
21955
21956 var res = a.add(b);
21957 if (res.cmp(this.m) >= 0) {
21958 res.isub(this.m);
21959 }
21960 return res._forceRed(this);
21961 };
21962
21963 Red.prototype.iadd = function iadd (a, b) {
21964 this._verify2(a, b);
21965
21966 var res = a.iadd(b);
21967 if (res.cmp(this.m) >= 0) {
21968 res.isub(this.m);
21969 }
21970 return res;
21971 };
21972
21973 Red.prototype.sub = function sub (a, b) {
21974 this._verify2(a, b);
21975
21976 var res = a.sub(b);
21977 if (res.cmpn(0) < 0) {
21978 res.iadd(this.m);
21979 }
21980 return res._forceRed(this);
21981 };
21982
21983 Red.prototype.isub = function isub (a, b) {
21984 this._verify2(a, b);
21985
21986 var res = a.isub(b);
21987 if (res.cmpn(0) < 0) {
21988 res.iadd(this.m);
21989 }
21990 return res;
21991 };
21992
21993 Red.prototype.shl = function shl (a, num) {
21994 this._verify1(a);
21995 return this.imod(a.ushln(num));
21996 };
21997
21998 Red.prototype.imul = function imul (a, b) {
21999 this._verify2(a, b);
22000 return this.imod(a.imul(b));
22001 };
22002
22003 Red.prototype.mul = function mul (a, b) {
22004 this._verify2(a, b);
22005 return this.imod(a.mul(b));
22006 };
22007
22008 Red.prototype.isqr = function isqr (a) {
22009 return this.imul(a, a.clone());
22010 };
22011
22012 Red.prototype.sqr = function sqr (a) {
22013 return this.mul(a, a);
22014 };
22015
22016 Red.prototype.sqrt = function sqrt (a) {
22017 if (a.isZero()) return a.clone();
22018
22019 var mod3 = this.m.andln(3);
22020 assert(mod3 % 2 === 1);
22021
22022 // Fast case
22023 if (mod3 === 3) {
22024 var pow = this.m.add(new BN(1)).iushrn(2);
22025 return this.pow(a, pow);
22026 }
22027
22028 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
22029 //
22030 // Find Q and S, that Q * 2 ^ S = (P - 1)
22031 var q = this.m.subn(1);
22032 var s = 0;
22033 while (!q.isZero() && q.andln(1) === 0) {
22034 s++;
22035 q.iushrn(1);
22036 }
22037 assert(!q.isZero());
22038
22039 var one = new BN(1).toRed(this);
22040 var nOne = one.redNeg();
22041
22042 // Find quadratic non-residue
22043 // NOTE: Max is such because of generalized Riemann hypothesis.
22044 var lpow = this.m.subn(1).iushrn(1);
22045 var z = this.m.bitLength();
22046 z = new BN(2 * z * z).toRed(this);
22047
22048 while (this.pow(z, lpow).cmp(nOne) !== 0) {
22049 z.redIAdd(nOne);
22050 }
22051
22052 var c = this.pow(z, q);
22053 var r = this.pow(a, q.addn(1).iushrn(1));
22054 var t = this.pow(a, q);
22055 var m = s;
22056 while (t.cmp(one) !== 0) {
22057 var tmp = t;
22058 for (var i = 0; tmp.cmp(one) !== 0; i++) {
22059 tmp = tmp.redSqr();
22060 }
22061 assert(i < m);
22062 var b = this.pow(c, new BN(1).iushln(m - i - 1));
22063
22064 r = r.redMul(b);
22065 c = b.redSqr();
22066 t = t.redMul(c);
22067 m = i;
22068 }
22069
22070 return r;
22071 };
22072
22073 Red.prototype.invm = function invm (a) {
22074 var inv = a._invmp(this.m);
22075 if (inv.negative !== 0) {
22076 inv.negative = 0;
22077 return this.imod(inv).redNeg();
22078 } else {
22079 return this.imod(inv);
22080 }
22081 };
22082
22083 Red.prototype.pow = function pow (a, num) {
22084 if (num.isZero()) return new BN(1).toRed(this);
22085 if (num.cmpn(1) === 0) return a.clone();
22086
22087 var windowSize = 4;
22088 var wnd = new Array(1 << windowSize);
22089 wnd[0] = new BN(1).toRed(this);
22090 wnd[1] = a;
22091 for (var i = 2; i < wnd.length; i++) {
22092 wnd[i] = this.mul(wnd[i - 1], a);
22093 }
22094
22095 var res = wnd[0];
22096 var current = 0;
22097 var currentLen = 0;
22098 var start = num.bitLength() % 26;
22099 if (start === 0) {
22100 start = 26;
22101 }
22102
22103 for (i = num.length - 1; i >= 0; i--) {
22104 var word = num.words[i];
22105 for (var j = start - 1; j >= 0; j--) {
22106 var bit = (word >> j) & 1;
22107 if (res !== wnd[0]) {
22108 res = this.sqr(res);
22109 }
22110
22111 if (bit === 0 && current === 0) {
22112 currentLen = 0;
22113 continue;
22114 }
22115
22116 current <<= 1;
22117 current |= bit;
22118 currentLen++;
22119 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
22120
22121 res = this.mul(res, wnd[current]);
22122 currentLen = 0;
22123 current = 0;
22124 }
22125 start = 26;
22126 }
22127
22128 return res;
22129 };
22130
22131 Red.prototype.convertTo = function convertTo (num) {
22132 var r = num.umod(this.m);
22133
22134 return r === num ? r.clone() : r;
22135 };
22136
22137 Red.prototype.convertFrom = function convertFrom (num) {
22138 var res = num.clone();
22139 res.red = null;
22140 return res;
22141 };
22142
22143 //
22144 // Montgomery method engine
22145 //
22146
22147 BN.mont = function mont (num) {
22148 return new Mont(num);
22149 };
22150
22151 function Mont (m) {
22152 Red.call(this, m);
22153
22154 this.shift = this.m.bitLength();
22155 if (this.shift % 26 !== 0) {
22156 this.shift += 26 - (this.shift % 26);
22157 }
22158
22159 this.r = new BN(1).iushln(this.shift);
22160 this.r2 = this.imod(this.r.sqr());
22161 this.rinv = this.r._invmp(this.m);
22162
22163 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
22164 this.minv = this.minv.umod(this.r);
22165 this.minv = this.r.sub(this.minv);
22166 }
22167 inherits(Mont, Red);
22168
22169 Mont.prototype.convertTo = function convertTo (num) {
22170 return this.imod(num.ushln(this.shift));
22171 };
22172
22173 Mont.prototype.convertFrom = function convertFrom (num) {
22174 var r = this.imod(num.mul(this.rinv));
22175 r.red = null;
22176 return r;
22177 };
22178
22179 Mont.prototype.imul = function imul (a, b) {
22180 if (a.isZero() || b.isZero()) {
22181 a.words[0] = 0;
22182 a.length = 1;
22183 return a;
22184 }
22185
22186 var t = a.imul(b);
22187 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
22188 var u = t.isub(c).iushrn(this.shift);
22189 var res = u;
22190
22191 if (u.cmp(this.m) >= 0) {
22192 res = u.isub(this.m);
22193 } else if (u.cmpn(0) < 0) {
22194 res = u.iadd(this.m);
22195 }
22196
22197 return res._forceRed(this);
22198 };
22199
22200 Mont.prototype.mul = function mul (a, b) {
22201 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
22202
22203 var t = a.mul(b);
22204 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
22205 var u = t.isub(c).iushrn(this.shift);
22206 var res = u;
22207 if (u.cmp(this.m) >= 0) {
22208 res = u.isub(this.m);
22209 } else if (u.cmpn(0) < 0) {
22210 res = u.iadd(this.m);
22211 }
22212
22213 return res._forceRed(this);
22214 };
22215
22216 Mont.prototype.invm = function invm (a) {
22217 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
22218 var res = this.imod(a._invmp(this.m).mul(this.r2));
22219 return res._forceRed(this);
22220 };
22221})(typeof module === 'undefined' || module, this);
22222
22223},{"buffer":82}],81:[function(require,module,exports){
22224var r;
22225
22226module.exports = function rand(len) {
22227 if (!r)
22228 r = new Rand(null);
22229
22230 return r.generate(len);
22231};
22232
22233function Rand(rand) {
22234 this.rand = rand;
22235}
22236module.exports.Rand = Rand;
22237
22238Rand.prototype.generate = function generate(len) {
22239 return this._rand(len);
22240};
22241
22242// Emulate crypto API using randy
22243Rand.prototype._rand = function _rand(n) {
22244 if (this.rand.getBytes)
22245 return this.rand.getBytes(n);
22246
22247 var res = new Uint8Array(n);
22248 for (var i = 0; i < res.length; i++)
22249 res[i] = this.rand.getByte();
22250 return res;
22251};
22252
22253if (typeof self === 'object') {
22254 if (self.crypto && self.crypto.getRandomValues) {
22255 // Modern browsers
22256 Rand.prototype._rand = function _rand(n) {
22257 var arr = new Uint8Array(n);
22258 self.crypto.getRandomValues(arr);
22259 return arr;
22260 };
22261 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
22262 // IE
22263 Rand.prototype._rand = function _rand(n) {
22264 var arr = new Uint8Array(n);
22265 self.msCrypto.getRandomValues(arr);
22266 return arr;
22267 };
22268
22269 // Safari's WebWorkers do not have `crypto`
22270 } else if (typeof window === 'object') {
22271 // Old junk
22272 Rand.prototype._rand = function() {
22273 throw new Error('Not implemented yet');
22274 };
22275 }
22276} else {
22277 // Node.js or Web worker with no crypto support
22278 try {
22279 var crypto = require('crypto');
22280 if (typeof crypto.randomBytes !== 'function')
22281 throw new Error('Not supported');
22282
22283 Rand.prototype._rand = function _rand(n) {
22284 return crypto.randomBytes(n);
22285 };
22286 } catch (e) {
22287 }
22288}
22289
22290},{"crypto":82}],82:[function(require,module,exports){
22291
22292},{}],83:[function(require,module,exports){
22293// based on the aes implimentation in triple sec
22294// https://github.com/keybase/triplesec
22295// which is in turn based on the one from crypto-js
22296// https://code.google.com/p/crypto-js/
22297
22298var Buffer = require('safe-buffer').Buffer
22299
22300function asUInt32Array (buf) {
22301 if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
22302
22303 var len = (buf.length / 4) | 0
22304 var out = new Array(len)
22305
22306 for (var i = 0; i < len; i++) {
22307 out[i] = buf.readUInt32BE(i * 4)
22308 }
22309
22310 return out
22311}
22312
22313function scrubVec (v) {
22314 for (var i = 0; i < v.length; v++) {
22315 v[i] = 0
22316 }
22317}
22318
22319function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
22320 var SUB_MIX0 = SUB_MIX[0]
22321 var SUB_MIX1 = SUB_MIX[1]
22322 var SUB_MIX2 = SUB_MIX[2]
22323 var SUB_MIX3 = SUB_MIX[3]
22324
22325 var s0 = M[0] ^ keySchedule[0]
22326 var s1 = M[1] ^ keySchedule[1]
22327 var s2 = M[2] ^ keySchedule[2]
22328 var s3 = M[3] ^ keySchedule[3]
22329 var t0, t1, t2, t3
22330 var ksRow = 4
22331
22332 for (var round = 1; round < nRounds; round++) {
22333 t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
22334 t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
22335 t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
22336 t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
22337 s0 = t0
22338 s1 = t1
22339 s2 = t2
22340 s3 = t3
22341 }
22342
22343 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
22344 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
22345 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
22346 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
22347 t0 = t0 >>> 0
22348 t1 = t1 >>> 0
22349 t2 = t2 >>> 0
22350 t3 = t3 >>> 0
22351
22352 return [t0, t1, t2, t3]
22353}
22354
22355// AES constants
22356var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
22357var G = (function () {
22358 // Compute double table
22359 var d = new Array(256)
22360 for (var j = 0; j < 256; j++) {
22361 if (j < 128) {
22362 d[j] = j << 1
22363 } else {
22364 d[j] = (j << 1) ^ 0x11b
22365 }
22366 }
22367
22368 var SBOX = []
22369 var INV_SBOX = []
22370 var SUB_MIX = [[], [], [], []]
22371 var INV_SUB_MIX = [[], [], [], []]
22372
22373 // Walk GF(2^8)
22374 var x = 0
22375 var xi = 0
22376 for (var i = 0; i < 256; ++i) {
22377 // Compute sbox
22378 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
22379 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
22380 SBOX[x] = sx
22381 INV_SBOX[sx] = x
22382
22383 // Compute multiplication
22384 var x2 = d[x]
22385 var x4 = d[x2]
22386 var x8 = d[x4]
22387
22388 // Compute sub bytes, mix columns tables
22389 var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
22390 SUB_MIX[0][x] = (t << 24) | (t >>> 8)
22391 SUB_MIX[1][x] = (t << 16) | (t >>> 16)
22392 SUB_MIX[2][x] = (t << 8) | (t >>> 24)
22393 SUB_MIX[3][x] = t
22394
22395 // Compute inv sub bytes, inv mix columns tables
22396 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
22397 INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
22398 INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
22399 INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
22400 INV_SUB_MIX[3][sx] = t
22401
22402 if (x === 0) {
22403 x = xi = 1
22404 } else {
22405 x = x2 ^ d[d[d[x8 ^ x2]]]
22406 xi ^= d[d[xi]]
22407 }
22408 }
22409
22410 return {
22411 SBOX: SBOX,
22412 INV_SBOX: INV_SBOX,
22413 SUB_MIX: SUB_MIX,
22414 INV_SUB_MIX: INV_SUB_MIX
22415 }
22416})()
22417
22418function AES (key) {
22419 this._key = asUInt32Array(key)
22420 this._reset()
22421}
22422
22423AES.blockSize = 4 * 4
22424AES.keySize = 256 / 8
22425AES.prototype.blockSize = AES.blockSize
22426AES.prototype.keySize = AES.keySize
22427AES.prototype._reset = function () {
22428 var keyWords = this._key
22429 var keySize = keyWords.length
22430 var nRounds = keySize + 6
22431 var ksRows = (nRounds + 1) * 4
22432
22433 var keySchedule = []
22434 for (var k = 0; k < keySize; k++) {
22435 keySchedule[k] = keyWords[k]
22436 }
22437
22438 for (k = keySize; k < ksRows; k++) {
22439 var t = keySchedule[k - 1]
22440
22441 if (k % keySize === 0) {
22442 t = (t << 8) | (t >>> 24)
22443 t =
22444 (G.SBOX[t >>> 24] << 24) |
22445 (G.SBOX[(t >>> 16) & 0xff] << 16) |
22446 (G.SBOX[(t >>> 8) & 0xff] << 8) |
22447 (G.SBOX[t & 0xff])
22448
22449 t ^= RCON[(k / keySize) | 0] << 24
22450 } else if (keySize > 6 && k % keySize === 4) {
22451 t =
22452 (G.SBOX[t >>> 24] << 24) |
22453 (G.SBOX[(t >>> 16) & 0xff] << 16) |
22454 (G.SBOX[(t >>> 8) & 0xff] << 8) |
22455 (G.SBOX[t & 0xff])
22456 }
22457
22458 keySchedule[k] = keySchedule[k - keySize] ^ t
22459 }
22460
22461 var invKeySchedule = []
22462 for (var ik = 0; ik < ksRows; ik++) {
22463 var ksR = ksRows - ik
22464 var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
22465
22466 if (ik < 4 || ksR <= 4) {
22467 invKeySchedule[ik] = tt
22468 } else {
22469 invKeySchedule[ik] =
22470 G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
22471 G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
22472 G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
22473 G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
22474 }
22475 }
22476
22477 this._nRounds = nRounds
22478 this._keySchedule = keySchedule
22479 this._invKeySchedule = invKeySchedule
22480}
22481
22482AES.prototype.encryptBlockRaw = function (M) {
22483 M = asUInt32Array(M)
22484 return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
22485}
22486
22487AES.prototype.encryptBlock = function (M) {
22488 var out = this.encryptBlockRaw(M)
22489 var buf = Buffer.allocUnsafe(16)
22490 buf.writeUInt32BE(out[0], 0)
22491 buf.writeUInt32BE(out[1], 4)
22492 buf.writeUInt32BE(out[2], 8)
22493 buf.writeUInt32BE(out[3], 12)
22494 return buf
22495}
22496
22497AES.prototype.decryptBlock = function (M) {
22498 M = asUInt32Array(M)
22499
22500 // swap
22501 var m1 = M[1]
22502 M[1] = M[3]
22503 M[3] = m1
22504
22505 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
22506 var buf = Buffer.allocUnsafe(16)
22507 buf.writeUInt32BE(out[0], 0)
22508 buf.writeUInt32BE(out[3], 4)
22509 buf.writeUInt32BE(out[2], 8)
22510 buf.writeUInt32BE(out[1], 12)
22511 return buf
22512}
22513
22514AES.prototype.scrub = function () {
22515 scrubVec(this._keySchedule)
22516 scrubVec(this._invKeySchedule)
22517 scrubVec(this._key)
22518}
22519
22520module.exports.AES = AES
22521
22522},{"safe-buffer":256}],84:[function(require,module,exports){
22523var aes = require('./aes')
22524var Buffer = require('safe-buffer').Buffer
22525var Transform = require('cipher-base')
22526var inherits = require('inherits')
22527var GHASH = require('./ghash')
22528var xor = require('buffer-xor')
22529var incr32 = require('./incr32')
22530
22531function xorTest (a, b) {
22532 var out = 0
22533 if (a.length !== b.length) out++
22534
22535 var len = Math.min(a.length, b.length)
22536 for (var i = 0; i < len; ++i) {
22537 out += (a[i] ^ b[i])
22538 }
22539
22540 return out
22541}
22542
22543function calcIv (self, iv, ck) {
22544 if (iv.length === 12) {
22545 self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
22546 return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
22547 }
22548 var ghash = new GHASH(ck)
22549 var len = iv.length
22550 var toPad = len % 16
22551 ghash.update(iv)
22552 if (toPad) {
22553 toPad = 16 - toPad
22554 ghash.update(Buffer.alloc(toPad, 0))
22555 }
22556 ghash.update(Buffer.alloc(8, 0))
22557 var ivBits = len * 8
22558 var tail = Buffer.alloc(8)
22559 tail.writeUIntBE(ivBits, 0, 8)
22560 ghash.update(tail)
22561 self._finID = ghash.state
22562 var out = Buffer.from(self._finID)
22563 incr32(out)
22564 return out
22565}
22566function StreamCipher (mode, key, iv, decrypt) {
22567 Transform.call(this)
22568
22569 var h = Buffer.alloc(4, 0)
22570
22571 this._cipher = new aes.AES(key)
22572 var ck = this._cipher.encryptBlock(h)
22573 this._ghash = new GHASH(ck)
22574 iv = calcIv(this, iv, ck)
22575
22576 this._prev = Buffer.from(iv)
22577 this._cache = Buffer.allocUnsafe(0)
22578 this._secCache = Buffer.allocUnsafe(0)
22579 this._decrypt = decrypt
22580 this._alen = 0
22581 this._len = 0
22582 this._mode = mode
22583
22584 this._authTag = null
22585 this._called = false
22586}
22587
22588inherits(StreamCipher, Transform)
22589
22590StreamCipher.prototype._update = function (chunk) {
22591 if (!this._called && this._alen) {
22592 var rump = 16 - (this._alen % 16)
22593 if (rump < 16) {
22594 rump = Buffer.alloc(rump, 0)
22595 this._ghash.update(rump)
22596 }
22597 }
22598
22599 this._called = true
22600 var out = this._mode.encrypt(this, chunk)
22601 if (this._decrypt) {
22602 this._ghash.update(chunk)
22603 } else {
22604 this._ghash.update(out)
22605 }
22606 this._len += chunk.length
22607 return out
22608}
22609
22610StreamCipher.prototype._final = function () {
22611 if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
22612
22613 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
22614 if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
22615
22616 this._authTag = tag
22617 this._cipher.scrub()
22618}
22619
22620StreamCipher.prototype.getAuthTag = function getAuthTag () {
22621 if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
22622
22623 return this._authTag
22624}
22625
22626StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
22627 if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
22628
22629 this._authTag = tag
22630}
22631
22632StreamCipher.prototype.setAAD = function setAAD (buf) {
22633 if (this._called) throw new Error('Attempting to set AAD in unsupported state')
22634
22635 this._ghash.update(buf)
22636 this._alen += buf.length
22637}
22638
22639module.exports = StreamCipher
22640
22641},{"./aes":83,"./ghash":88,"./incr32":89,"buffer-xor":131,"cipher-base":133,"inherits":206,"safe-buffer":256}],85:[function(require,module,exports){
22642var ciphers = require('./encrypter')
22643var deciphers = require('./decrypter')
22644var modes = require('./modes/list.json')
22645
22646function getCiphers () {
22647 return Object.keys(modes)
22648}
22649
22650exports.createCipher = exports.Cipher = ciphers.createCipher
22651exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
22652exports.createDecipher = exports.Decipher = deciphers.createDecipher
22653exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
22654exports.listCiphers = exports.getCiphers = getCiphers
22655
22656},{"./decrypter":86,"./encrypter":87,"./modes/list.json":97}],86:[function(require,module,exports){
22657var AuthCipher = require('./authCipher')
22658var Buffer = require('safe-buffer').Buffer
22659var MODES = require('./modes')
22660var StreamCipher = require('./streamCipher')
22661var Transform = require('cipher-base')
22662var aes = require('./aes')
22663var ebtk = require('evp_bytestokey')
22664var inherits = require('inherits')
22665
22666function Decipher (mode, key, iv) {
22667 Transform.call(this)
22668
22669 this._cache = new Splitter()
22670 this._last = void 0
22671 this._cipher = new aes.AES(key)
22672 this._prev = Buffer.from(iv)
22673 this._mode = mode
22674 this._autopadding = true
22675}
22676
22677inherits(Decipher, Transform)
22678
22679Decipher.prototype._update = function (data) {
22680 this._cache.add(data)
22681 var chunk
22682 var thing
22683 var out = []
22684 while ((chunk = this._cache.get(this._autopadding))) {
22685 thing = this._mode.decrypt(this, chunk)
22686 out.push(thing)
22687 }
22688 return Buffer.concat(out)
22689}
22690
22691Decipher.prototype._final = function () {
22692 var chunk = this._cache.flush()
22693 if (this._autopadding) {
22694 return unpad(this._mode.decrypt(this, chunk))
22695 } else if (chunk) {
22696 throw new Error('data not multiple of block length')
22697 }
22698}
22699
22700Decipher.prototype.setAutoPadding = function (setTo) {
22701 this._autopadding = !!setTo
22702 return this
22703}
22704
22705function Splitter () {
22706 this.cache = Buffer.allocUnsafe(0)
22707}
22708
22709Splitter.prototype.add = function (data) {
22710 this.cache = Buffer.concat([this.cache, data])
22711}
22712
22713Splitter.prototype.get = function (autoPadding) {
22714 var out
22715 if (autoPadding) {
22716 if (this.cache.length > 16) {
22717 out = this.cache.slice(0, 16)
22718 this.cache = this.cache.slice(16)
22719 return out
22720 }
22721 } else {
22722 if (this.cache.length >= 16) {
22723 out = this.cache.slice(0, 16)
22724 this.cache = this.cache.slice(16)
22725 return out
22726 }
22727 }
22728
22729 return null
22730}
22731
22732Splitter.prototype.flush = function () {
22733 if (this.cache.length) return this.cache
22734}
22735
22736function unpad (last) {
22737 var padded = last[15]
22738 if (padded < 1 || padded > 16) {
22739 throw new Error('unable to decrypt data')
22740 }
22741 var i = -1
22742 while (++i < padded) {
22743 if (last[(i + (16 - padded))] !== padded) {
22744 throw new Error('unable to decrypt data')
22745 }
22746 }
22747 if (padded === 16) return
22748
22749 return last.slice(0, 16 - padded)
22750}
22751
22752function createDecipheriv (suite, password, iv) {
22753 var config = MODES[suite.toLowerCase()]
22754 if (!config) throw new TypeError('invalid suite type')
22755
22756 if (typeof iv === 'string') iv = Buffer.from(iv)
22757 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
22758
22759 if (typeof password === 'string') password = Buffer.from(password)
22760 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
22761
22762 if (config.type === 'stream') {
22763 return new StreamCipher(config.module, password, iv, true)
22764 } else if (config.type === 'auth') {
22765 return new AuthCipher(config.module, password, iv, true)
22766 }
22767
22768 return new Decipher(config.module, password, iv)
22769}
22770
22771function createDecipher (suite, password) {
22772 var config = MODES[suite.toLowerCase()]
22773 if (!config) throw new TypeError('invalid suite type')
22774
22775 var keys = ebtk(password, false, config.key, config.iv)
22776 return createDecipheriv(suite, keys.key, keys.iv)
22777}
22778
22779exports.createDecipher = createDecipher
22780exports.createDecipheriv = createDecipheriv
22781
22782},{"./aes":83,"./authCipher":84,"./modes":96,"./streamCipher":99,"cipher-base":133,"evp_bytestokey":173,"inherits":206,"safe-buffer":256}],87:[function(require,module,exports){
22783var MODES = require('./modes')
22784var AuthCipher = require('./authCipher')
22785var Buffer = require('safe-buffer').Buffer
22786var StreamCipher = require('./streamCipher')
22787var Transform = require('cipher-base')
22788var aes = require('./aes')
22789var ebtk = require('evp_bytestokey')
22790var inherits = require('inherits')
22791
22792function Cipher (mode, key, iv) {
22793 Transform.call(this)
22794
22795 this._cache = new Splitter()
22796 this._cipher = new aes.AES(key)
22797 this._prev = Buffer.from(iv)
22798 this._mode = mode
22799 this._autopadding = true
22800}
22801
22802inherits(Cipher, Transform)
22803
22804Cipher.prototype._update = function (data) {
22805 this._cache.add(data)
22806 var chunk
22807 var thing
22808 var out = []
22809
22810 while ((chunk = this._cache.get())) {
22811 thing = this._mode.encrypt(this, chunk)
22812 out.push(thing)
22813 }
22814
22815 return Buffer.concat(out)
22816}
22817
22818var PADDING = Buffer.alloc(16, 0x10)
22819
22820Cipher.prototype._final = function () {
22821 var chunk = this._cache.flush()
22822 if (this._autopadding) {
22823 chunk = this._mode.encrypt(this, chunk)
22824 this._cipher.scrub()
22825 return chunk
22826 }
22827
22828 if (!chunk.equals(PADDING)) {
22829 this._cipher.scrub()
22830 throw new Error('data not multiple of block length')
22831 }
22832}
22833
22834Cipher.prototype.setAutoPadding = function (setTo) {
22835 this._autopadding = !!setTo
22836 return this
22837}
22838
22839function Splitter () {
22840 this.cache = Buffer.allocUnsafe(0)
22841}
22842
22843Splitter.prototype.add = function (data) {
22844 this.cache = Buffer.concat([this.cache, data])
22845}
22846
22847Splitter.prototype.get = function () {
22848 if (this.cache.length > 15) {
22849 var out = this.cache.slice(0, 16)
22850 this.cache = this.cache.slice(16)
22851 return out
22852 }
22853 return null
22854}
22855
22856Splitter.prototype.flush = function () {
22857 var len = 16 - this.cache.length
22858 var padBuff = Buffer.allocUnsafe(len)
22859
22860 var i = -1
22861 while (++i < len) {
22862 padBuff.writeUInt8(len, i)
22863 }
22864
22865 return Buffer.concat([this.cache, padBuff])
22866}
22867
22868function createCipheriv (suite, password, iv) {
22869 var config = MODES[suite.toLowerCase()]
22870 if (!config) throw new TypeError('invalid suite type')
22871
22872 if (typeof password === 'string') password = Buffer.from(password)
22873 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
22874
22875 if (typeof iv === 'string') iv = Buffer.from(iv)
22876 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
22877
22878 if (config.type === 'stream') {
22879 return new StreamCipher(config.module, password, iv)
22880 } else if (config.type === 'auth') {
22881 return new AuthCipher(config.module, password, iv)
22882 }
22883
22884 return new Cipher(config.module, password, iv)
22885}
22886
22887function createCipher (suite, password) {
22888 var config = MODES[suite.toLowerCase()]
22889 if (!config) throw new TypeError('invalid suite type')
22890
22891 var keys = ebtk(password, false, config.key, config.iv)
22892 return createCipheriv(suite, keys.key, keys.iv)
22893}
22894
22895exports.createCipheriv = createCipheriv
22896exports.createCipher = createCipher
22897
22898},{"./aes":83,"./authCipher":84,"./modes":96,"./streamCipher":99,"cipher-base":133,"evp_bytestokey":173,"inherits":206,"safe-buffer":256}],88:[function(require,module,exports){
22899var Buffer = require('safe-buffer').Buffer
22900var ZEROES = Buffer.alloc(16, 0)
22901
22902function toArray (buf) {
22903 return [
22904 buf.readUInt32BE(0),
22905 buf.readUInt32BE(4),
22906 buf.readUInt32BE(8),
22907 buf.readUInt32BE(12)
22908 ]
22909}
22910
22911function fromArray (out) {
22912 var buf = Buffer.allocUnsafe(16)
22913 buf.writeUInt32BE(out[0] >>> 0, 0)
22914 buf.writeUInt32BE(out[1] >>> 0, 4)
22915 buf.writeUInt32BE(out[2] >>> 0, 8)
22916 buf.writeUInt32BE(out[3] >>> 0, 12)
22917 return buf
22918}
22919
22920function GHASH (key) {
22921 this.h = key
22922 this.state = Buffer.alloc(16, 0)
22923 this.cache = Buffer.allocUnsafe(0)
22924}
22925
22926// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
22927// by Juho Vähä-Herttua
22928GHASH.prototype.ghash = function (block) {
22929 var i = -1
22930 while (++i < block.length) {
22931 this.state[i] ^= block[i]
22932 }
22933 this._multiply()
22934}
22935
22936GHASH.prototype._multiply = function () {
22937 var Vi = toArray(this.h)
22938 var Zi = [0, 0, 0, 0]
22939 var j, xi, lsbVi
22940 var i = -1
22941 while (++i < 128) {
22942 xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
22943 if (xi) {
22944 // Z_i+1 = Z_i ^ V_i
22945 Zi[0] ^= Vi[0]
22946 Zi[1] ^= Vi[1]
22947 Zi[2] ^= Vi[2]
22948 Zi[3] ^= Vi[3]
22949 }
22950
22951 // Store the value of LSB(V_i)
22952 lsbVi = (Vi[3] & 1) !== 0
22953
22954 // V_i+1 = V_i >> 1
22955 for (j = 3; j > 0; j--) {
22956 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
22957 }
22958 Vi[0] = Vi[0] >>> 1
22959
22960 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
22961 if (lsbVi) {
22962 Vi[0] = Vi[0] ^ (0xe1 << 24)
22963 }
22964 }
22965 this.state = fromArray(Zi)
22966}
22967
22968GHASH.prototype.update = function (buf) {
22969 this.cache = Buffer.concat([this.cache, buf])
22970 var chunk
22971 while (this.cache.length >= 16) {
22972 chunk = this.cache.slice(0, 16)
22973 this.cache = this.cache.slice(16)
22974 this.ghash(chunk)
22975 }
22976}
22977
22978GHASH.prototype.final = function (abl, bl) {
22979 if (this.cache.length) {
22980 this.ghash(Buffer.concat([this.cache, ZEROES], 16))
22981 }
22982
22983 this.ghash(fromArray([0, abl, 0, bl]))
22984 return this.state
22985}
22986
22987module.exports = GHASH
22988
22989},{"safe-buffer":256}],89:[function(require,module,exports){
22990function incr32 (iv) {
22991 var len = iv.length
22992 var item
22993 while (len--) {
22994 item = iv.readUInt8(len)
22995 if (item === 255) {
22996 iv.writeUInt8(0, len)
22997 } else {
22998 item++
22999 iv.writeUInt8(item, len)
23000 break
23001 }
23002 }
23003}
23004module.exports = incr32
23005
23006},{}],90:[function(require,module,exports){
23007var xor = require('buffer-xor')
23008
23009exports.encrypt = function (self, block) {
23010 var data = xor(block, self._prev)
23011
23012 self._prev = self._cipher.encryptBlock(data)
23013 return self._prev
23014}
23015
23016exports.decrypt = function (self, block) {
23017 var pad = self._prev
23018
23019 self._prev = block
23020 var out = self._cipher.decryptBlock(block)
23021
23022 return xor(out, pad)
23023}
23024
23025},{"buffer-xor":131}],91:[function(require,module,exports){
23026var Buffer = require('safe-buffer').Buffer
23027var xor = require('buffer-xor')
23028
23029function encryptStart (self, data, decrypt) {
23030 var len = data.length
23031 var out = xor(data, self._cache)
23032 self._cache = self._cache.slice(len)
23033 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
23034 return out
23035}
23036
23037exports.encrypt = function (self, data, decrypt) {
23038 var out = Buffer.allocUnsafe(0)
23039 var len
23040
23041 while (data.length) {
23042 if (self._cache.length === 0) {
23043 self._cache = self._cipher.encryptBlock(self._prev)
23044 self._prev = Buffer.allocUnsafe(0)
23045 }
23046
23047 if (self._cache.length <= data.length) {
23048 len = self._cache.length
23049 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
23050 data = data.slice(len)
23051 } else {
23052 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
23053 break
23054 }
23055 }
23056
23057 return out
23058}
23059
23060},{"buffer-xor":131,"safe-buffer":256}],92:[function(require,module,exports){
23061var Buffer = require('safe-buffer').Buffer
23062
23063function encryptByte (self, byteParam, decrypt) {
23064 var pad
23065 var i = -1
23066 var len = 8
23067 var out = 0
23068 var bit, value
23069 while (++i < len) {
23070 pad = self._cipher.encryptBlock(self._prev)
23071 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
23072 value = pad[0] ^ bit
23073 out += ((value & 0x80) >> (i % 8))
23074 self._prev = shiftIn(self._prev, decrypt ? bit : value)
23075 }
23076 return out
23077}
23078
23079function shiftIn (buffer, value) {
23080 var len = buffer.length
23081 var i = -1
23082 var out = Buffer.allocUnsafe(buffer.length)
23083 buffer = Buffer.concat([buffer, Buffer.from([value])])
23084
23085 while (++i < len) {
23086 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
23087 }
23088
23089 return out
23090}
23091
23092exports.encrypt = function (self, chunk, decrypt) {
23093 var len = chunk.length
23094 var out = Buffer.allocUnsafe(len)
23095 var i = -1
23096
23097 while (++i < len) {
23098 out[i] = encryptByte(self, chunk[i], decrypt)
23099 }
23100
23101 return out
23102}
23103
23104},{"safe-buffer":256}],93:[function(require,module,exports){
23105var Buffer = require('safe-buffer').Buffer
23106
23107function encryptByte (self, byteParam, decrypt) {
23108 var pad = self._cipher.encryptBlock(self._prev)
23109 var out = pad[0] ^ byteParam
23110
23111 self._prev = Buffer.concat([
23112 self._prev.slice(1),
23113 Buffer.from([decrypt ? byteParam : out])
23114 ])
23115
23116 return out
23117}
23118
23119exports.encrypt = function (self, chunk, decrypt) {
23120 var len = chunk.length
23121 var out = Buffer.allocUnsafe(len)
23122 var i = -1
23123
23124 while (++i < len) {
23125 out[i] = encryptByte(self, chunk[i], decrypt)
23126 }
23127
23128 return out
23129}
23130
23131},{"safe-buffer":256}],94:[function(require,module,exports){
23132var xor = require('buffer-xor')
23133var Buffer = require('safe-buffer').Buffer
23134var incr32 = require('../incr32')
23135
23136function getBlock (self) {
23137 var out = self._cipher.encryptBlockRaw(self._prev)
23138 incr32(self._prev)
23139 return out
23140}
23141
23142var blockSize = 16
23143exports.encrypt = function (self, chunk) {
23144 var chunkNum = Math.ceil(chunk.length / blockSize)
23145 var start = self._cache.length
23146 self._cache = Buffer.concat([
23147 self._cache,
23148 Buffer.allocUnsafe(chunkNum * blockSize)
23149 ])
23150 for (var i = 0; i < chunkNum; i++) {
23151 var out = getBlock(self)
23152 var offset = start + i * blockSize
23153 self._cache.writeUInt32BE(out[0], offset + 0)
23154 self._cache.writeUInt32BE(out[1], offset + 4)
23155 self._cache.writeUInt32BE(out[2], offset + 8)
23156 self._cache.writeUInt32BE(out[3], offset + 12)
23157 }
23158 var pad = self._cache.slice(0, chunk.length)
23159 self._cache = self._cache.slice(chunk.length)
23160 return xor(chunk, pad)
23161}
23162
23163},{"../incr32":89,"buffer-xor":131,"safe-buffer":256}],95:[function(require,module,exports){
23164exports.encrypt = function (self, block) {
23165 return self._cipher.encryptBlock(block)
23166}
23167
23168exports.decrypt = function (self, block) {
23169 return self._cipher.decryptBlock(block)
23170}
23171
23172},{}],96:[function(require,module,exports){
23173var modeModules = {
23174 ECB: require('./ecb'),
23175 CBC: require('./cbc'),
23176 CFB: require('./cfb'),
23177 CFB8: require('./cfb8'),
23178 CFB1: require('./cfb1'),
23179 OFB: require('./ofb'),
23180 CTR: require('./ctr'),
23181 GCM: require('./ctr')
23182}
23183
23184var modes = require('./list.json')
23185
23186for (var key in modes) {
23187 modes[key].module = modeModules[modes[key].mode]
23188}
23189
23190module.exports = modes
23191
23192},{"./cbc":90,"./cfb":91,"./cfb1":92,"./cfb8":93,"./ctr":94,"./ecb":95,"./list.json":97,"./ofb":98}],97:[function(require,module,exports){
23193module.exports={
23194 "aes-128-ecb": {
23195 "cipher": "AES",
23196 "key": 128,
23197 "iv": 0,
23198 "mode": "ECB",
23199 "type": "block"
23200 },
23201 "aes-192-ecb": {
23202 "cipher": "AES",
23203 "key": 192,
23204 "iv": 0,
23205 "mode": "ECB",
23206 "type": "block"
23207 },
23208 "aes-256-ecb": {
23209 "cipher": "AES",
23210 "key": 256,
23211 "iv": 0,
23212 "mode": "ECB",
23213 "type": "block"
23214 },
23215 "aes-128-cbc": {
23216 "cipher": "AES",
23217 "key": 128,
23218 "iv": 16,
23219 "mode": "CBC",
23220 "type": "block"
23221 },
23222 "aes-192-cbc": {
23223 "cipher": "AES",
23224 "key": 192,
23225 "iv": 16,
23226 "mode": "CBC",
23227 "type": "block"
23228 },
23229 "aes-256-cbc": {
23230 "cipher": "AES",
23231 "key": 256,
23232 "iv": 16,
23233 "mode": "CBC",
23234 "type": "block"
23235 },
23236 "aes128": {
23237 "cipher": "AES",
23238 "key": 128,
23239 "iv": 16,
23240 "mode": "CBC",
23241 "type": "block"
23242 },
23243 "aes192": {
23244 "cipher": "AES",
23245 "key": 192,
23246 "iv": 16,
23247 "mode": "CBC",
23248 "type": "block"
23249 },
23250 "aes256": {
23251 "cipher": "AES",
23252 "key": 256,
23253 "iv": 16,
23254 "mode": "CBC",
23255 "type": "block"
23256 },
23257 "aes-128-cfb": {
23258 "cipher": "AES",
23259 "key": 128,
23260 "iv": 16,
23261 "mode": "CFB",
23262 "type": "stream"
23263 },
23264 "aes-192-cfb": {
23265 "cipher": "AES",
23266 "key": 192,
23267 "iv": 16,
23268 "mode": "CFB",
23269 "type": "stream"
23270 },
23271 "aes-256-cfb": {
23272 "cipher": "AES",
23273 "key": 256,
23274 "iv": 16,
23275 "mode": "CFB",
23276 "type": "stream"
23277 },
23278 "aes-128-cfb8": {
23279 "cipher": "AES",
23280 "key": 128,
23281 "iv": 16,
23282 "mode": "CFB8",
23283 "type": "stream"
23284 },
23285 "aes-192-cfb8": {
23286 "cipher": "AES",
23287 "key": 192,
23288 "iv": 16,
23289 "mode": "CFB8",
23290 "type": "stream"
23291 },
23292 "aes-256-cfb8": {
23293 "cipher": "AES",
23294 "key": 256,
23295 "iv": 16,
23296 "mode": "CFB8",
23297 "type": "stream"
23298 },
23299 "aes-128-cfb1": {
23300 "cipher": "AES",
23301 "key": 128,
23302 "iv": 16,
23303 "mode": "CFB1",
23304 "type": "stream"
23305 },
23306 "aes-192-cfb1": {
23307 "cipher": "AES",
23308 "key": 192,
23309 "iv": 16,
23310 "mode": "CFB1",
23311 "type": "stream"
23312 },
23313 "aes-256-cfb1": {
23314 "cipher": "AES",
23315 "key": 256,
23316 "iv": 16,
23317 "mode": "CFB1",
23318 "type": "stream"
23319 },
23320 "aes-128-ofb": {
23321 "cipher": "AES",
23322 "key": 128,
23323 "iv": 16,
23324 "mode": "OFB",
23325 "type": "stream"
23326 },
23327 "aes-192-ofb": {
23328 "cipher": "AES",
23329 "key": 192,
23330 "iv": 16,
23331 "mode": "OFB",
23332 "type": "stream"
23333 },
23334 "aes-256-ofb": {
23335 "cipher": "AES",
23336 "key": 256,
23337 "iv": 16,
23338 "mode": "OFB",
23339 "type": "stream"
23340 },
23341 "aes-128-ctr": {
23342 "cipher": "AES",
23343 "key": 128,
23344 "iv": 16,
23345 "mode": "CTR",
23346 "type": "stream"
23347 },
23348 "aes-192-ctr": {
23349 "cipher": "AES",
23350 "key": 192,
23351 "iv": 16,
23352 "mode": "CTR",
23353 "type": "stream"
23354 },
23355 "aes-256-ctr": {
23356 "cipher": "AES",
23357 "key": 256,
23358 "iv": 16,
23359 "mode": "CTR",
23360 "type": "stream"
23361 },
23362 "aes-128-gcm": {
23363 "cipher": "AES",
23364 "key": 128,
23365 "iv": 12,
23366 "mode": "GCM",
23367 "type": "auth"
23368 },
23369 "aes-192-gcm": {
23370 "cipher": "AES",
23371 "key": 192,
23372 "iv": 12,
23373 "mode": "GCM",
23374 "type": "auth"
23375 },
23376 "aes-256-gcm": {
23377 "cipher": "AES",
23378 "key": 256,
23379 "iv": 12,
23380 "mode": "GCM",
23381 "type": "auth"
23382 }
23383}
23384
23385},{}],98:[function(require,module,exports){
23386(function (Buffer){(function (){
23387var xor = require('buffer-xor')
23388
23389function getBlock (self) {
23390 self._prev = self._cipher.encryptBlock(self._prev)
23391 return self._prev
23392}
23393
23394exports.encrypt = function (self, chunk) {
23395 while (self._cache.length < chunk.length) {
23396 self._cache = Buffer.concat([self._cache, getBlock(self)])
23397 }
23398
23399 var pad = self._cache.slice(0, chunk.length)
23400 self._cache = self._cache.slice(chunk.length)
23401 return xor(chunk, pad)
23402}
23403
23404}).call(this)}).call(this,require("buffer").Buffer)
23405},{"buffer":132,"buffer-xor":131}],99:[function(require,module,exports){
23406var aes = require('./aes')
23407var Buffer = require('safe-buffer').Buffer
23408var Transform = require('cipher-base')
23409var inherits = require('inherits')
23410
23411function StreamCipher (mode, key, iv, decrypt) {
23412 Transform.call(this)
23413
23414 this._cipher = new aes.AES(key)
23415 this._prev = Buffer.from(iv)
23416 this._cache = Buffer.allocUnsafe(0)
23417 this._secCache = Buffer.allocUnsafe(0)
23418 this._decrypt = decrypt
23419 this._mode = mode
23420}
23421
23422inherits(StreamCipher, Transform)
23423
23424StreamCipher.prototype._update = function (chunk) {
23425 return this._mode.encrypt(this, chunk, this._decrypt)
23426}
23427
23428StreamCipher.prototype._final = function () {
23429 this._cipher.scrub()
23430}
23431
23432module.exports = StreamCipher
23433
23434},{"./aes":83,"cipher-base":133,"inherits":206,"safe-buffer":256}],100:[function(require,module,exports){
23435var DES = require('browserify-des')
23436var aes = require('browserify-aes/browser')
23437var aesModes = require('browserify-aes/modes')
23438var desModes = require('browserify-des/modes')
23439var ebtk = require('evp_bytestokey')
23440
23441function createCipher (suite, password) {
23442 suite = suite.toLowerCase()
23443
23444 var keyLen, ivLen
23445 if (aesModes[suite]) {
23446 keyLen = aesModes[suite].key
23447 ivLen = aesModes[suite].iv
23448 } else if (desModes[suite]) {
23449 keyLen = desModes[suite].key * 8
23450 ivLen = desModes[suite].iv
23451 } else {
23452 throw new TypeError('invalid suite type')
23453 }
23454
23455 var keys = ebtk(password, false, keyLen, ivLen)
23456 return createCipheriv(suite, keys.key, keys.iv)
23457}
23458
23459function createDecipher (suite, password) {
23460 suite = suite.toLowerCase()
23461
23462 var keyLen, ivLen
23463 if (aesModes[suite]) {
23464 keyLen = aesModes[suite].key
23465 ivLen = aesModes[suite].iv
23466 } else if (desModes[suite]) {
23467 keyLen = desModes[suite].key * 8
23468 ivLen = desModes[suite].iv
23469 } else {
23470 throw new TypeError('invalid suite type')
23471 }
23472
23473 var keys = ebtk(password, false, keyLen, ivLen)
23474 return createDecipheriv(suite, keys.key, keys.iv)
23475}
23476
23477function createCipheriv (suite, key, iv) {
23478 suite = suite.toLowerCase()
23479 if (aesModes[suite]) return aes.createCipheriv(suite, key, iv)
23480 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite })
23481
23482 throw new TypeError('invalid suite type')
23483}
23484
23485function createDecipheriv (suite, key, iv) {
23486 suite = suite.toLowerCase()
23487 if (aesModes[suite]) return aes.createDecipheriv(suite, key, iv)
23488 if (desModes[suite]) return new DES({ key: key, iv: iv, mode: suite, decrypt: true })
23489
23490 throw new TypeError('invalid suite type')
23491}
23492
23493function getCiphers () {
23494 return Object.keys(desModes).concat(aes.getCiphers())
23495}
23496
23497exports.createCipher = exports.Cipher = createCipher
23498exports.createCipheriv = exports.Cipheriv = createCipheriv
23499exports.createDecipher = exports.Decipher = createDecipher
23500exports.createDecipheriv = exports.Decipheriv = createDecipheriv
23501exports.listCiphers = exports.getCiphers = getCiphers
23502
23503},{"browserify-aes/browser":85,"browserify-aes/modes":96,"browserify-des":101,"browserify-des/modes":102,"evp_bytestokey":173}],101:[function(require,module,exports){
23504var CipherBase = require('cipher-base')
23505var des = require('des.js')
23506var inherits = require('inherits')
23507var Buffer = require('safe-buffer').Buffer
23508
23509var modes = {
23510 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
23511 'des-ede3': des.EDE,
23512 'des-ede-cbc': des.CBC.instantiate(des.EDE),
23513 'des-ede': des.EDE,
23514 'des-cbc': des.CBC.instantiate(des.DES),
23515 'des-ecb': des.DES
23516}
23517modes.des = modes['des-cbc']
23518modes.des3 = modes['des-ede3-cbc']
23519module.exports = DES
23520inherits(DES, CipherBase)
23521function DES (opts) {
23522 CipherBase.call(this)
23523 var modeName = opts.mode.toLowerCase()
23524 var mode = modes[modeName]
23525 var type
23526 if (opts.decrypt) {
23527 type = 'decrypt'
23528 } else {
23529 type = 'encrypt'
23530 }
23531 var key = opts.key
23532 if (!Buffer.isBuffer(key)) {
23533 key = Buffer.from(key)
23534 }
23535 if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
23536 key = Buffer.concat([key, key.slice(0, 8)])
23537 }
23538 var iv = opts.iv
23539 if (!Buffer.isBuffer(iv)) {
23540 iv = Buffer.from(iv)
23541 }
23542 this._des = mode.create({
23543 key: key,
23544 iv: iv,
23545 type: type
23546 })
23547}
23548DES.prototype._update = function (data) {
23549 return Buffer.from(this._des.update(data))
23550}
23551DES.prototype._final = function () {
23552 return Buffer.from(this._des.final())
23553}
23554
23555},{"cipher-base":133,"des.js":141,"inherits":206,"safe-buffer":256}],102:[function(require,module,exports){
23556exports['des-ecb'] = {
23557 key: 8,
23558 iv: 0
23559}
23560exports['des-cbc'] = exports.des = {
23561 key: 8,
23562 iv: 8
23563}
23564exports['des-ede3-cbc'] = exports.des3 = {
23565 key: 24,
23566 iv: 8
23567}
23568exports['des-ede3'] = {
23569 key: 24,
23570 iv: 0
23571}
23572exports['des-ede-cbc'] = {
23573 key: 16,
23574 iv: 8
23575}
23576exports['des-ede'] = {
23577 key: 16,
23578 iv: 0
23579}
23580
23581},{}],103:[function(require,module,exports){
23582(function (Buffer){(function (){
23583var BN = require('bn.js')
23584var randomBytes = require('randombytes')
23585
23586function blind (priv) {
23587 var r = getr(priv)
23588 var blinder = r.toRed(BN.mont(priv.modulus)).redPow(new BN(priv.publicExponent)).fromRed()
23589 return { blinder: blinder, unblinder: r.invm(priv.modulus) }
23590}
23591
23592function getr (priv) {
23593 var len = priv.modulus.byteLength()
23594 var r
23595 do {
23596 r = new BN(randomBytes(len))
23597 } while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2))
23598 return r
23599}
23600
23601function crt (msg, priv) {
23602 var blinds = blind(priv)
23603 var len = priv.modulus.byteLength()
23604 var blinded = new BN(msg).mul(blinds.blinder).umod(priv.modulus)
23605 var c1 = blinded.toRed(BN.mont(priv.prime1))
23606 var c2 = blinded.toRed(BN.mont(priv.prime2))
23607 var qinv = priv.coefficient
23608 var p = priv.prime1
23609 var q = priv.prime2
23610 var m1 = c1.redPow(priv.exponent1).fromRed()
23611 var m2 = c2.redPow(priv.exponent2).fromRed()
23612 var h = m1.isub(m2).imul(qinv).umod(p).imul(q)
23613 return m2.iadd(h).imul(blinds.unblinder).umod(priv.modulus).toArrayLike(Buffer, 'be', len)
23614}
23615crt.getr = getr
23616
23617module.exports = crt
23618
23619}).call(this)}).call(this,require("buffer").Buffer)
23620},{"bn.js":104,"buffer":132,"randombytes":238}],104:[function(require,module,exports){
23621(function (module, exports) {
23622 'use strict';
23623
23624 // Utils
23625 function assert (val, msg) {
23626 if (!val) throw new Error(msg || 'Assertion failed');
23627 }
23628
23629 // Could use `inherits` module, but don't want to move from single file
23630 // architecture yet.
23631 function inherits (ctor, superCtor) {
23632 ctor.super_ = superCtor;
23633 var TempCtor = function () {};
23634 TempCtor.prototype = superCtor.prototype;
23635 ctor.prototype = new TempCtor();
23636 ctor.prototype.constructor = ctor;
23637 }
23638
23639 // BN
23640
23641 function BN (number, base, endian) {
23642 if (BN.isBN(number)) {
23643 return number;
23644 }
23645
23646 this.negative = 0;
23647 this.words = null;
23648 this.length = 0;
23649
23650 // Reduction context
23651 this.red = null;
23652
23653 if (number !== null) {
23654 if (base === 'le' || base === 'be') {
23655 endian = base;
23656 base = 10;
23657 }
23658
23659 this._init(number || 0, base || 10, endian || 'be');
23660 }
23661 }
23662 if (typeof module === 'object') {
23663 module.exports = BN;
23664 } else {
23665 exports.BN = BN;
23666 }
23667
23668 BN.BN = BN;
23669 BN.wordSize = 26;
23670
23671 var Buffer;
23672 try {
23673 if (typeof window !== 'undefined' && typeof window.Buffer !== 'undefined') {
23674 Buffer = window.Buffer;
23675 } else {
23676 Buffer = require('buffer').Buffer;
23677 }
23678 } catch (e) {
23679 }
23680
23681 BN.isBN = function isBN (num) {
23682 if (num instanceof BN) {
23683 return true;
23684 }
23685
23686 return num !== null && typeof num === 'object' &&
23687 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
23688 };
23689
23690 BN.max = function max (left, right) {
23691 if (left.cmp(right) > 0) return left;
23692 return right;
23693 };
23694
23695 BN.min = function min (left, right) {
23696 if (left.cmp(right) < 0) return left;
23697 return right;
23698 };
23699
23700 BN.prototype._init = function init (number, base, endian) {
23701 if (typeof number === 'number') {
23702 return this._initNumber(number, base, endian);
23703 }
23704
23705 if (typeof number === 'object') {
23706 return this._initArray(number, base, endian);
23707 }
23708
23709 if (base === 'hex') {
23710 base = 16;
23711 }
23712 assert(base === (base | 0) && base >= 2 && base <= 36);
23713
23714 number = number.toString().replace(/\s+/g, '');
23715 var start = 0;
23716 if (number[0] === '-') {
23717 start++;
23718 this.negative = 1;
23719 }
23720
23721 if (start < number.length) {
23722 if (base === 16) {
23723 this._parseHex(number, start, endian);
23724 } else {
23725 this._parseBase(number, base, start);
23726 if (endian === 'le') {
23727 this._initArray(this.toArray(), base, endian);
23728 }
23729 }
23730 }
23731 };
23732
23733 BN.prototype._initNumber = function _initNumber (number, base, endian) {
23734 if (number < 0) {
23735 this.negative = 1;
23736 number = -number;
23737 }
23738 if (number < 0x4000000) {
23739 this.words = [number & 0x3ffffff];
23740 this.length = 1;
23741 } else if (number < 0x10000000000000) {
23742 this.words = [
23743 number & 0x3ffffff,
23744 (number / 0x4000000) & 0x3ffffff
23745 ];
23746 this.length = 2;
23747 } else {
23748 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
23749 this.words = [
23750 number & 0x3ffffff,
23751 (number / 0x4000000) & 0x3ffffff,
23752 1
23753 ];
23754 this.length = 3;
23755 }
23756
23757 if (endian !== 'le') return;
23758
23759 // Reverse the bytes
23760 this._initArray(this.toArray(), base, endian);
23761 };
23762
23763 BN.prototype._initArray = function _initArray (number, base, endian) {
23764 // Perhaps a Uint8Array
23765 assert(typeof number.length === 'number');
23766 if (number.length <= 0) {
23767 this.words = [0];
23768 this.length = 1;
23769 return this;
23770 }
23771
23772 this.length = Math.ceil(number.length / 3);
23773 this.words = new Array(this.length);
23774 for (var i = 0; i < this.length; i++) {
23775 this.words[i] = 0;
23776 }
23777
23778 var j, w;
23779 var off = 0;
23780 if (endian === 'be') {
23781 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
23782 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
23783 this.words[j] |= (w << off) & 0x3ffffff;
23784 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
23785 off += 24;
23786 if (off >= 26) {
23787 off -= 26;
23788 j++;
23789 }
23790 }
23791 } else if (endian === 'le') {
23792 for (i = 0, j = 0; i < number.length; i += 3) {
23793 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
23794 this.words[j] |= (w << off) & 0x3ffffff;
23795 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
23796 off += 24;
23797 if (off >= 26) {
23798 off -= 26;
23799 j++;
23800 }
23801 }
23802 }
23803 return this._strip();
23804 };
23805
23806 function parseHex4Bits (string, index) {
23807 var c = string.charCodeAt(index);
23808 // '0' - '9'
23809 if (c >= 48 && c <= 57) {
23810 return c - 48;
23811 // 'A' - 'F'
23812 } else if (c >= 65 && c <= 70) {
23813 return c - 55;
23814 // 'a' - 'f'
23815 } else if (c >= 97 && c <= 102) {
23816 return c - 87;
23817 } else {
23818 assert(false, 'Invalid character in ' + string);
23819 }
23820 }
23821
23822 function parseHexByte (string, lowerBound, index) {
23823 var r = parseHex4Bits(string, index);
23824 if (index - 1 >= lowerBound) {
23825 r |= parseHex4Bits(string, index - 1) << 4;
23826 }
23827 return r;
23828 }
23829
23830 BN.prototype._parseHex = function _parseHex (number, start, endian) {
23831 // Create possibly bigger array to ensure that it fits the number
23832 this.length = Math.ceil((number.length - start) / 6);
23833 this.words = new Array(this.length);
23834 for (var i = 0; i < this.length; i++) {
23835 this.words[i] = 0;
23836 }
23837
23838 // 24-bits chunks
23839 var off = 0;
23840 var j = 0;
23841
23842 var w;
23843 if (endian === 'be') {
23844 for (i = number.length - 1; i >= start; i -= 2) {
23845 w = parseHexByte(number, start, i) << off;
23846 this.words[j] |= w & 0x3ffffff;
23847 if (off >= 18) {
23848 off -= 18;
23849 j += 1;
23850 this.words[j] |= w >>> 26;
23851 } else {
23852 off += 8;
23853 }
23854 }
23855 } else {
23856 var parseLength = number.length - start;
23857 for (i = parseLength % 2 === 0 ? start + 1 : start; i < number.length; i += 2) {
23858 w = parseHexByte(number, start, i) << off;
23859 this.words[j] |= w & 0x3ffffff;
23860 if (off >= 18) {
23861 off -= 18;
23862 j += 1;
23863 this.words[j] |= w >>> 26;
23864 } else {
23865 off += 8;
23866 }
23867 }
23868 }
23869
23870 this._strip();
23871 };
23872
23873 function parseBase (str, start, end, mul) {
23874 var r = 0;
23875 var b = 0;
23876 var len = Math.min(str.length, end);
23877 for (var i = start; i < len; i++) {
23878 var c = str.charCodeAt(i) - 48;
23879
23880 r *= mul;
23881
23882 // 'a'
23883 if (c >= 49) {
23884 b = c - 49 + 0xa;
23885
23886 // 'A'
23887 } else if (c >= 17) {
23888 b = c - 17 + 0xa;
23889
23890 // '0' - '9'
23891 } else {
23892 b = c;
23893 }
23894 assert(c >= 0 && b < mul, 'Invalid character');
23895 r += b;
23896 }
23897 return r;
23898 }
23899
23900 BN.prototype._parseBase = function _parseBase (number, base, start) {
23901 // Initialize as zero
23902 this.words = [0];
23903 this.length = 1;
23904
23905 // Find length of limb in base
23906 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
23907 limbLen++;
23908 }
23909 limbLen--;
23910 limbPow = (limbPow / base) | 0;
23911
23912 var total = number.length - start;
23913 var mod = total % limbLen;
23914 var end = Math.min(total, total - mod) + start;
23915
23916 var word = 0;
23917 for (var i = start; i < end; i += limbLen) {
23918 word = parseBase(number, i, i + limbLen, base);
23919
23920 this.imuln(limbPow);
23921 if (this.words[0] + word < 0x4000000) {
23922 this.words[0] += word;
23923 } else {
23924 this._iaddn(word);
23925 }
23926 }
23927
23928 if (mod !== 0) {
23929 var pow = 1;
23930 word = parseBase(number, i, number.length, base);
23931
23932 for (i = 0; i < mod; i++) {
23933 pow *= base;
23934 }
23935
23936 this.imuln(pow);
23937 if (this.words[0] + word < 0x4000000) {
23938 this.words[0] += word;
23939 } else {
23940 this._iaddn(word);
23941 }
23942 }
23943
23944 this._strip();
23945 };
23946
23947 BN.prototype.copy = function copy (dest) {
23948 dest.words = new Array(this.length);
23949 for (var i = 0; i < this.length; i++) {
23950 dest.words[i] = this.words[i];
23951 }
23952 dest.length = this.length;
23953 dest.negative = this.negative;
23954 dest.red = this.red;
23955 };
23956
23957 function move (dest, src) {
23958 dest.words = src.words;
23959 dest.length = src.length;
23960 dest.negative = src.negative;
23961 dest.red = src.red;
23962 }
23963
23964 BN.prototype._move = function _move (dest) {
23965 move(dest, this);
23966 };
23967
23968 BN.prototype.clone = function clone () {
23969 var r = new BN(null);
23970 this.copy(r);
23971 return r;
23972 };
23973
23974 BN.prototype._expand = function _expand (size) {
23975 while (this.length < size) {
23976 this.words[this.length++] = 0;
23977 }
23978 return this;
23979 };
23980
23981 // Remove leading `0` from `this`
23982 BN.prototype._strip = function strip () {
23983 while (this.length > 1 && this.words[this.length - 1] === 0) {
23984 this.length--;
23985 }
23986 return this._normSign();
23987 };
23988
23989 BN.prototype._normSign = function _normSign () {
23990 // -0 = 0
23991 if (this.length === 1 && this.words[0] === 0) {
23992 this.negative = 0;
23993 }
23994 return this;
23995 };
23996
23997 // Check Symbol.for because not everywhere where Symbol defined
23998 // See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Symbol#Browser_compatibility
23999 if (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function') {
24000 try {
24001 BN.prototype[Symbol.for('nodejs.util.inspect.custom')] = inspect;
24002 } catch (e) {
24003 BN.prototype.inspect = inspect;
24004 }
24005 } else {
24006 BN.prototype.inspect = inspect;
24007 }
24008
24009 function inspect () {
24010 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
24011 }
24012
24013 /*
24014
24015 var zeros = [];
24016 var groupSizes = [];
24017 var groupBases = [];
24018
24019 var s = '';
24020 var i = -1;
24021 while (++i < BN.wordSize) {
24022 zeros[i] = s;
24023 s += '0';
24024 }
24025 groupSizes[0] = 0;
24026 groupSizes[1] = 0;
24027 groupBases[0] = 0;
24028 groupBases[1] = 0;
24029 var base = 2 - 1;
24030 while (++base < 36 + 1) {
24031 var groupSize = 0;
24032 var groupBase = 1;
24033 while (groupBase < (1 << BN.wordSize) / base) {
24034 groupBase *= base;
24035 groupSize += 1;
24036 }
24037 groupSizes[base] = groupSize;
24038 groupBases[base] = groupBase;
24039 }
24040
24041 */
24042
24043 var zeros = [
24044 '',
24045 '0',
24046 '00',
24047 '000',
24048 '0000',
24049 '00000',
24050 '000000',
24051 '0000000',
24052 '00000000',
24053 '000000000',
24054 '0000000000',
24055 '00000000000',
24056 '000000000000',
24057 '0000000000000',
24058 '00000000000000',
24059 '000000000000000',
24060 '0000000000000000',
24061 '00000000000000000',
24062 '000000000000000000',
24063 '0000000000000000000',
24064 '00000000000000000000',
24065 '000000000000000000000',
24066 '0000000000000000000000',
24067 '00000000000000000000000',
24068 '000000000000000000000000',
24069 '0000000000000000000000000'
24070 ];
24071
24072 var groupSizes = [
24073 0, 0,
24074 25, 16, 12, 11, 10, 9, 8,
24075 8, 7, 7, 7, 7, 6, 6,
24076 6, 6, 6, 6, 6, 5, 5,
24077 5, 5, 5, 5, 5, 5, 5,
24078 5, 5, 5, 5, 5, 5, 5
24079 ];
24080
24081 var groupBases = [
24082 0, 0,
24083 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
24084 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
24085 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
24086 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
24087 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
24088 ];
24089
24090 BN.prototype.toString = function toString (base, padding) {
24091 base = base || 10;
24092 padding = padding | 0 || 1;
24093
24094 var out;
24095 if (base === 16 || base === 'hex') {
24096 out = '';
24097 var off = 0;
24098 var carry = 0;
24099 for (var i = 0; i < this.length; i++) {
24100 var w = this.words[i];
24101 var word = (((w << off) | carry) & 0xffffff).toString(16);
24102 carry = (w >>> (24 - off)) & 0xffffff;
24103 if (carry !== 0 || i !== this.length - 1) {
24104 out = zeros[6 - word.length] + word + out;
24105 } else {
24106 out = word + out;
24107 }
24108 off += 2;
24109 if (off >= 26) {
24110 off -= 26;
24111 i--;
24112 }
24113 }
24114 if (carry !== 0) {
24115 out = carry.toString(16) + out;
24116 }
24117 while (out.length % padding !== 0) {
24118 out = '0' + out;
24119 }
24120 if (this.negative !== 0) {
24121 out = '-' + out;
24122 }
24123 return out;
24124 }
24125
24126 if (base === (base | 0) && base >= 2 && base <= 36) {
24127 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
24128 var groupSize = groupSizes[base];
24129 // var groupBase = Math.pow(base, groupSize);
24130 var groupBase = groupBases[base];
24131 out = '';
24132 var c = this.clone();
24133 c.negative = 0;
24134 while (!c.isZero()) {
24135 var r = c.modrn(groupBase).toString(base);
24136 c = c.idivn(groupBase);
24137
24138 if (!c.isZero()) {
24139 out = zeros[groupSize - r.length] + r + out;
24140 } else {
24141 out = r + out;
24142 }
24143 }
24144 if (this.isZero()) {
24145 out = '0' + out;
24146 }
24147 while (out.length % padding !== 0) {
24148 out = '0' + out;
24149 }
24150 if (this.negative !== 0) {
24151 out = '-' + out;
24152 }
24153 return out;
24154 }
24155
24156 assert(false, 'Base should be between 2 and 36');
24157 };
24158
24159 BN.prototype.toNumber = function toNumber () {
24160 var ret = this.words[0];
24161 if (this.length === 2) {
24162 ret += this.words[1] * 0x4000000;
24163 } else if (this.length === 3 && this.words[2] === 0x01) {
24164 // NOTE: at this stage it is known that the top bit is set
24165 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
24166 } else if (this.length > 2) {
24167 assert(false, 'Number can only safely store up to 53 bits');
24168 }
24169 return (this.negative !== 0) ? -ret : ret;
24170 };
24171
24172 BN.prototype.toJSON = function toJSON () {
24173 return this.toString(16, 2);
24174 };
24175
24176 if (Buffer) {
24177 BN.prototype.toBuffer = function toBuffer (endian, length) {
24178 return this.toArrayLike(Buffer, endian, length);
24179 };
24180 }
24181
24182 BN.prototype.toArray = function toArray (endian, length) {
24183 return this.toArrayLike(Array, endian, length);
24184 };
24185
24186 var allocate = function allocate (ArrayType, size) {
24187 if (ArrayType.allocUnsafe) {
24188 return ArrayType.allocUnsafe(size);
24189 }
24190 return new ArrayType(size);
24191 };
24192
24193 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
24194 this._strip();
24195
24196 var byteLength = this.byteLength();
24197 var reqLength = length || Math.max(1, byteLength);
24198 assert(byteLength <= reqLength, 'byte array longer than desired length');
24199 assert(reqLength > 0, 'Requested array length <= 0');
24200
24201 var res = allocate(ArrayType, reqLength);
24202 var postfix = endian === 'le' ? 'LE' : 'BE';
24203 this['_toArrayLike' + postfix](res, byteLength);
24204 return res;
24205 };
24206
24207 BN.prototype._toArrayLikeLE = function _toArrayLikeLE (res, byteLength) {
24208 var position = 0;
24209 var carry = 0;
24210
24211 for (var i = 0, shift = 0; i < this.length; i++) {
24212 var word = (this.words[i] << shift) | carry;
24213
24214 res[position++] = word & 0xff;
24215 if (position < res.length) {
24216 res[position++] = (word >> 8) & 0xff;
24217 }
24218 if (position < res.length) {
24219 res[position++] = (word >> 16) & 0xff;
24220 }
24221
24222 if (shift === 6) {
24223 if (position < res.length) {
24224 res[position++] = (word >> 24) & 0xff;
24225 }
24226 carry = 0;
24227 shift = 0;
24228 } else {
24229 carry = word >>> 24;
24230 shift += 2;
24231 }
24232 }
24233
24234 if (position < res.length) {
24235 res[position++] = carry;
24236
24237 while (position < res.length) {
24238 res[position++] = 0;
24239 }
24240 }
24241 };
24242
24243 BN.prototype._toArrayLikeBE = function _toArrayLikeBE (res, byteLength) {
24244 var position = res.length - 1;
24245 var carry = 0;
24246
24247 for (var i = 0, shift = 0; i < this.length; i++) {
24248 var word = (this.words[i] << shift) | carry;
24249
24250 res[position--] = word & 0xff;
24251 if (position >= 0) {
24252 res[position--] = (word >> 8) & 0xff;
24253 }
24254 if (position >= 0) {
24255 res[position--] = (word >> 16) & 0xff;
24256 }
24257
24258 if (shift === 6) {
24259 if (position >= 0) {
24260 res[position--] = (word >> 24) & 0xff;
24261 }
24262 carry = 0;
24263 shift = 0;
24264 } else {
24265 carry = word >>> 24;
24266 shift += 2;
24267 }
24268 }
24269
24270 if (position >= 0) {
24271 res[position--] = carry;
24272
24273 while (position >= 0) {
24274 res[position--] = 0;
24275 }
24276 }
24277 };
24278
24279 if (Math.clz32) {
24280 BN.prototype._countBits = function _countBits (w) {
24281 return 32 - Math.clz32(w);
24282 };
24283 } else {
24284 BN.prototype._countBits = function _countBits (w) {
24285 var t = w;
24286 var r = 0;
24287 if (t >= 0x1000) {
24288 r += 13;
24289 t >>>= 13;
24290 }
24291 if (t >= 0x40) {
24292 r += 7;
24293 t >>>= 7;
24294 }
24295 if (t >= 0x8) {
24296 r += 4;
24297 t >>>= 4;
24298 }
24299 if (t >= 0x02) {
24300 r += 2;
24301 t >>>= 2;
24302 }
24303 return r + t;
24304 };
24305 }
24306
24307 BN.prototype._zeroBits = function _zeroBits (w) {
24308 // Short-cut
24309 if (w === 0) return 26;
24310
24311 var t = w;
24312 var r = 0;
24313 if ((t & 0x1fff) === 0) {
24314 r += 13;
24315 t >>>= 13;
24316 }
24317 if ((t & 0x7f) === 0) {
24318 r += 7;
24319 t >>>= 7;
24320 }
24321 if ((t & 0xf) === 0) {
24322 r += 4;
24323 t >>>= 4;
24324 }
24325 if ((t & 0x3) === 0) {
24326 r += 2;
24327 t >>>= 2;
24328 }
24329 if ((t & 0x1) === 0) {
24330 r++;
24331 }
24332 return r;
24333 };
24334
24335 // Return number of used bits in a BN
24336 BN.prototype.bitLength = function bitLength () {
24337 var w = this.words[this.length - 1];
24338 var hi = this._countBits(w);
24339 return (this.length - 1) * 26 + hi;
24340 };
24341
24342 function toBitArray (num) {
24343 var w = new Array(num.bitLength());
24344
24345 for (var bit = 0; bit < w.length; bit++) {
24346 var off = (bit / 26) | 0;
24347 var wbit = bit % 26;
24348
24349 w[bit] = (num.words[off] >>> wbit) & 0x01;
24350 }
24351
24352 return w;
24353 }
24354
24355 // Number of trailing zero bits
24356 BN.prototype.zeroBits = function zeroBits () {
24357 if (this.isZero()) return 0;
24358
24359 var r = 0;
24360 for (var i = 0; i < this.length; i++) {
24361 var b = this._zeroBits(this.words[i]);
24362 r += b;
24363 if (b !== 26) break;
24364 }
24365 return r;
24366 };
24367
24368 BN.prototype.byteLength = function byteLength () {
24369 return Math.ceil(this.bitLength() / 8);
24370 };
24371
24372 BN.prototype.toTwos = function toTwos (width) {
24373 if (this.negative !== 0) {
24374 return this.abs().inotn(width).iaddn(1);
24375 }
24376 return this.clone();
24377 };
24378
24379 BN.prototype.fromTwos = function fromTwos (width) {
24380 if (this.testn(width - 1)) {
24381 return this.notn(width).iaddn(1).ineg();
24382 }
24383 return this.clone();
24384 };
24385
24386 BN.prototype.isNeg = function isNeg () {
24387 return this.negative !== 0;
24388 };
24389
24390 // Return negative clone of `this`
24391 BN.prototype.neg = function neg () {
24392 return this.clone().ineg();
24393 };
24394
24395 BN.prototype.ineg = function ineg () {
24396 if (!this.isZero()) {
24397 this.negative ^= 1;
24398 }
24399
24400 return this;
24401 };
24402
24403 // Or `num` with `this` in-place
24404 BN.prototype.iuor = function iuor (num) {
24405 while (this.length < num.length) {
24406 this.words[this.length++] = 0;
24407 }
24408
24409 for (var i = 0; i < num.length; i++) {
24410 this.words[i] = this.words[i] | num.words[i];
24411 }
24412
24413 return this._strip();
24414 };
24415
24416 BN.prototype.ior = function ior (num) {
24417 assert((this.negative | num.negative) === 0);
24418 return this.iuor(num);
24419 };
24420
24421 // Or `num` with `this`
24422 BN.prototype.or = function or (num) {
24423 if (this.length > num.length) return this.clone().ior(num);
24424 return num.clone().ior(this);
24425 };
24426
24427 BN.prototype.uor = function uor (num) {
24428 if (this.length > num.length) return this.clone().iuor(num);
24429 return num.clone().iuor(this);
24430 };
24431
24432 // And `num` with `this` in-place
24433 BN.prototype.iuand = function iuand (num) {
24434 // b = min-length(num, this)
24435 var b;
24436 if (this.length > num.length) {
24437 b = num;
24438 } else {
24439 b = this;
24440 }
24441
24442 for (var i = 0; i < b.length; i++) {
24443 this.words[i] = this.words[i] & num.words[i];
24444 }
24445
24446 this.length = b.length;
24447
24448 return this._strip();
24449 };
24450
24451 BN.prototype.iand = function iand (num) {
24452 assert((this.negative | num.negative) === 0);
24453 return this.iuand(num);
24454 };
24455
24456 // And `num` with `this`
24457 BN.prototype.and = function and (num) {
24458 if (this.length > num.length) return this.clone().iand(num);
24459 return num.clone().iand(this);
24460 };
24461
24462 BN.prototype.uand = function uand (num) {
24463 if (this.length > num.length) return this.clone().iuand(num);
24464 return num.clone().iuand(this);
24465 };
24466
24467 // Xor `num` with `this` in-place
24468 BN.prototype.iuxor = function iuxor (num) {
24469 // a.length > b.length
24470 var a;
24471 var b;
24472 if (this.length > num.length) {
24473 a = this;
24474 b = num;
24475 } else {
24476 a = num;
24477 b = this;
24478 }
24479
24480 for (var i = 0; i < b.length; i++) {
24481 this.words[i] = a.words[i] ^ b.words[i];
24482 }
24483
24484 if (this !== a) {
24485 for (; i < a.length; i++) {
24486 this.words[i] = a.words[i];
24487 }
24488 }
24489
24490 this.length = a.length;
24491
24492 return this._strip();
24493 };
24494
24495 BN.prototype.ixor = function ixor (num) {
24496 assert((this.negative | num.negative) === 0);
24497 return this.iuxor(num);
24498 };
24499
24500 // Xor `num` with `this`
24501 BN.prototype.xor = function xor (num) {
24502 if (this.length > num.length) return this.clone().ixor(num);
24503 return num.clone().ixor(this);
24504 };
24505
24506 BN.prototype.uxor = function uxor (num) {
24507 if (this.length > num.length) return this.clone().iuxor(num);
24508 return num.clone().iuxor(this);
24509 };
24510
24511 // Not ``this`` with ``width`` bitwidth
24512 BN.prototype.inotn = function inotn (width) {
24513 assert(typeof width === 'number' && width >= 0);
24514
24515 var bytesNeeded = Math.ceil(width / 26) | 0;
24516 var bitsLeft = width % 26;
24517
24518 // Extend the buffer with leading zeroes
24519 this._expand(bytesNeeded);
24520
24521 if (bitsLeft > 0) {
24522 bytesNeeded--;
24523 }
24524
24525 // Handle complete words
24526 for (var i = 0; i < bytesNeeded; i++) {
24527 this.words[i] = ~this.words[i] & 0x3ffffff;
24528 }
24529
24530 // Handle the residue
24531 if (bitsLeft > 0) {
24532 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
24533 }
24534
24535 // And remove leading zeroes
24536 return this._strip();
24537 };
24538
24539 BN.prototype.notn = function notn (width) {
24540 return this.clone().inotn(width);
24541 };
24542
24543 // Set `bit` of `this`
24544 BN.prototype.setn = function setn (bit, val) {
24545 assert(typeof bit === 'number' && bit >= 0);
24546
24547 var off = (bit / 26) | 0;
24548 var wbit = bit % 26;
24549
24550 this._expand(off + 1);
24551
24552 if (val) {
24553 this.words[off] = this.words[off] | (1 << wbit);
24554 } else {
24555 this.words[off] = this.words[off] & ~(1 << wbit);
24556 }
24557
24558 return this._strip();
24559 };
24560
24561 // Add `num` to `this` in-place
24562 BN.prototype.iadd = function iadd (num) {
24563 var r;
24564
24565 // negative + positive
24566 if (this.negative !== 0 && num.negative === 0) {
24567 this.negative = 0;
24568 r = this.isub(num);
24569 this.negative ^= 1;
24570 return this._normSign();
24571
24572 // positive + negative
24573 } else if (this.negative === 0 && num.negative !== 0) {
24574 num.negative = 0;
24575 r = this.isub(num);
24576 num.negative = 1;
24577 return r._normSign();
24578 }
24579
24580 // a.length > b.length
24581 var a, b;
24582 if (this.length > num.length) {
24583 a = this;
24584 b = num;
24585 } else {
24586 a = num;
24587 b = this;
24588 }
24589
24590 var carry = 0;
24591 for (var i = 0; i < b.length; i++) {
24592 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
24593 this.words[i] = r & 0x3ffffff;
24594 carry = r >>> 26;
24595 }
24596 for (; carry !== 0 && i < a.length; i++) {
24597 r = (a.words[i] | 0) + carry;
24598 this.words[i] = r & 0x3ffffff;
24599 carry = r >>> 26;
24600 }
24601
24602 this.length = a.length;
24603 if (carry !== 0) {
24604 this.words[this.length] = carry;
24605 this.length++;
24606 // Copy the rest of the words
24607 } else if (a !== this) {
24608 for (; i < a.length; i++) {
24609 this.words[i] = a.words[i];
24610 }
24611 }
24612
24613 return this;
24614 };
24615
24616 // Add `num` to `this`
24617 BN.prototype.add = function add (num) {
24618 var res;
24619 if (num.negative !== 0 && this.negative === 0) {
24620 num.negative = 0;
24621 res = this.sub(num);
24622 num.negative ^= 1;
24623 return res;
24624 } else if (num.negative === 0 && this.negative !== 0) {
24625 this.negative = 0;
24626 res = num.sub(this);
24627 this.negative = 1;
24628 return res;
24629 }
24630
24631 if (this.length > num.length) return this.clone().iadd(num);
24632
24633 return num.clone().iadd(this);
24634 };
24635
24636 // Subtract `num` from `this` in-place
24637 BN.prototype.isub = function isub (num) {
24638 // this - (-num) = this + num
24639 if (num.negative !== 0) {
24640 num.negative = 0;
24641 var r = this.iadd(num);
24642 num.negative = 1;
24643 return r._normSign();
24644
24645 // -this - num = -(this + num)
24646 } else if (this.negative !== 0) {
24647 this.negative = 0;
24648 this.iadd(num);
24649 this.negative = 1;
24650 return this._normSign();
24651 }
24652
24653 // At this point both numbers are positive
24654 var cmp = this.cmp(num);
24655
24656 // Optimization - zeroify
24657 if (cmp === 0) {
24658 this.negative = 0;
24659 this.length = 1;
24660 this.words[0] = 0;
24661 return this;
24662 }
24663
24664 // a > b
24665 var a, b;
24666 if (cmp > 0) {
24667 a = this;
24668 b = num;
24669 } else {
24670 a = num;
24671 b = this;
24672 }
24673
24674 var carry = 0;
24675 for (var i = 0; i < b.length; i++) {
24676 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
24677 carry = r >> 26;
24678 this.words[i] = r & 0x3ffffff;
24679 }
24680 for (; carry !== 0 && i < a.length; i++) {
24681 r = (a.words[i] | 0) + carry;
24682 carry = r >> 26;
24683 this.words[i] = r & 0x3ffffff;
24684 }
24685
24686 // Copy rest of the words
24687 if (carry === 0 && i < a.length && a !== this) {
24688 for (; i < a.length; i++) {
24689 this.words[i] = a.words[i];
24690 }
24691 }
24692
24693 this.length = Math.max(this.length, i);
24694
24695 if (a !== this) {
24696 this.negative = 1;
24697 }
24698
24699 return this._strip();
24700 };
24701
24702 // Subtract `num` from `this`
24703 BN.prototype.sub = function sub (num) {
24704 return this.clone().isub(num);
24705 };
24706
24707 function smallMulTo (self, num, out) {
24708 out.negative = num.negative ^ self.negative;
24709 var len = (self.length + num.length) | 0;
24710 out.length = len;
24711 len = (len - 1) | 0;
24712
24713 // Peel one iteration (compiler can't do it, because of code complexity)
24714 var a = self.words[0] | 0;
24715 var b = num.words[0] | 0;
24716 var r = a * b;
24717
24718 var lo = r & 0x3ffffff;
24719 var carry = (r / 0x4000000) | 0;
24720 out.words[0] = lo;
24721
24722 for (var k = 1; k < len; k++) {
24723 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
24724 // note that ncarry could be >= 0x3ffffff
24725 var ncarry = carry >>> 26;
24726 var rword = carry & 0x3ffffff;
24727 var maxJ = Math.min(k, num.length - 1);
24728 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
24729 var i = (k - j) | 0;
24730 a = self.words[i] | 0;
24731 b = num.words[j] | 0;
24732 r = a * b + rword;
24733 ncarry += (r / 0x4000000) | 0;
24734 rword = r & 0x3ffffff;
24735 }
24736 out.words[k] = rword | 0;
24737 carry = ncarry | 0;
24738 }
24739 if (carry !== 0) {
24740 out.words[k] = carry | 0;
24741 } else {
24742 out.length--;
24743 }
24744
24745 return out._strip();
24746 }
24747
24748 // TODO(indutny): it may be reasonable to omit it for users who don't need
24749 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
24750 // multiplication (like elliptic secp256k1).
24751 var comb10MulTo = function comb10MulTo (self, num, out) {
24752 var a = self.words;
24753 var b = num.words;
24754 var o = out.words;
24755 var c = 0;
24756 var lo;
24757 var mid;
24758 var hi;
24759 var a0 = a[0] | 0;
24760 var al0 = a0 & 0x1fff;
24761 var ah0 = a0 >>> 13;
24762 var a1 = a[1] | 0;
24763 var al1 = a1 & 0x1fff;
24764 var ah1 = a1 >>> 13;
24765 var a2 = a[2] | 0;
24766 var al2 = a2 & 0x1fff;
24767 var ah2 = a2 >>> 13;
24768 var a3 = a[3] | 0;
24769 var al3 = a3 & 0x1fff;
24770 var ah3 = a3 >>> 13;
24771 var a4 = a[4] | 0;
24772 var al4 = a4 & 0x1fff;
24773 var ah4 = a4 >>> 13;
24774 var a5 = a[5] | 0;
24775 var al5 = a5 & 0x1fff;
24776 var ah5 = a5 >>> 13;
24777 var a6 = a[6] | 0;
24778 var al6 = a6 & 0x1fff;
24779 var ah6 = a6 >>> 13;
24780 var a7 = a[7] | 0;
24781 var al7 = a7 & 0x1fff;
24782 var ah7 = a7 >>> 13;
24783 var a8 = a[8] | 0;
24784 var al8 = a8 & 0x1fff;
24785 var ah8 = a8 >>> 13;
24786 var a9 = a[9] | 0;
24787 var al9 = a9 & 0x1fff;
24788 var ah9 = a9 >>> 13;
24789 var b0 = b[0] | 0;
24790 var bl0 = b0 & 0x1fff;
24791 var bh0 = b0 >>> 13;
24792 var b1 = b[1] | 0;
24793 var bl1 = b1 & 0x1fff;
24794 var bh1 = b1 >>> 13;
24795 var b2 = b[2] | 0;
24796 var bl2 = b2 & 0x1fff;
24797 var bh2 = b2 >>> 13;
24798 var b3 = b[3] | 0;
24799 var bl3 = b3 & 0x1fff;
24800 var bh3 = b3 >>> 13;
24801 var b4 = b[4] | 0;
24802 var bl4 = b4 & 0x1fff;
24803 var bh4 = b4 >>> 13;
24804 var b5 = b[5] | 0;
24805 var bl5 = b5 & 0x1fff;
24806 var bh5 = b5 >>> 13;
24807 var b6 = b[6] | 0;
24808 var bl6 = b6 & 0x1fff;
24809 var bh6 = b6 >>> 13;
24810 var b7 = b[7] | 0;
24811 var bl7 = b7 & 0x1fff;
24812 var bh7 = b7 >>> 13;
24813 var b8 = b[8] | 0;
24814 var bl8 = b8 & 0x1fff;
24815 var bh8 = b8 >>> 13;
24816 var b9 = b[9] | 0;
24817 var bl9 = b9 & 0x1fff;
24818 var bh9 = b9 >>> 13;
24819
24820 out.negative = self.negative ^ num.negative;
24821 out.length = 19;
24822 /* k = 0 */
24823 lo = Math.imul(al0, bl0);
24824 mid = Math.imul(al0, bh0);
24825 mid = (mid + Math.imul(ah0, bl0)) | 0;
24826 hi = Math.imul(ah0, bh0);
24827 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
24828 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
24829 w0 &= 0x3ffffff;
24830 /* k = 1 */
24831 lo = Math.imul(al1, bl0);
24832 mid = Math.imul(al1, bh0);
24833 mid = (mid + Math.imul(ah1, bl0)) | 0;
24834 hi = Math.imul(ah1, bh0);
24835 lo = (lo + Math.imul(al0, bl1)) | 0;
24836 mid = (mid + Math.imul(al0, bh1)) | 0;
24837 mid = (mid + Math.imul(ah0, bl1)) | 0;
24838 hi = (hi + Math.imul(ah0, bh1)) | 0;
24839 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
24840 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
24841 w1 &= 0x3ffffff;
24842 /* k = 2 */
24843 lo = Math.imul(al2, bl0);
24844 mid = Math.imul(al2, bh0);
24845 mid = (mid + Math.imul(ah2, bl0)) | 0;
24846 hi = Math.imul(ah2, bh0);
24847 lo = (lo + Math.imul(al1, bl1)) | 0;
24848 mid = (mid + Math.imul(al1, bh1)) | 0;
24849 mid = (mid + Math.imul(ah1, bl1)) | 0;
24850 hi = (hi + Math.imul(ah1, bh1)) | 0;
24851 lo = (lo + Math.imul(al0, bl2)) | 0;
24852 mid = (mid + Math.imul(al0, bh2)) | 0;
24853 mid = (mid + Math.imul(ah0, bl2)) | 0;
24854 hi = (hi + Math.imul(ah0, bh2)) | 0;
24855 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
24856 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
24857 w2 &= 0x3ffffff;
24858 /* k = 3 */
24859 lo = Math.imul(al3, bl0);
24860 mid = Math.imul(al3, bh0);
24861 mid = (mid + Math.imul(ah3, bl0)) | 0;
24862 hi = Math.imul(ah3, bh0);
24863 lo = (lo + Math.imul(al2, bl1)) | 0;
24864 mid = (mid + Math.imul(al2, bh1)) | 0;
24865 mid = (mid + Math.imul(ah2, bl1)) | 0;
24866 hi = (hi + Math.imul(ah2, bh1)) | 0;
24867 lo = (lo + Math.imul(al1, bl2)) | 0;
24868 mid = (mid + Math.imul(al1, bh2)) | 0;
24869 mid = (mid + Math.imul(ah1, bl2)) | 0;
24870 hi = (hi + Math.imul(ah1, bh2)) | 0;
24871 lo = (lo + Math.imul(al0, bl3)) | 0;
24872 mid = (mid + Math.imul(al0, bh3)) | 0;
24873 mid = (mid + Math.imul(ah0, bl3)) | 0;
24874 hi = (hi + Math.imul(ah0, bh3)) | 0;
24875 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
24876 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
24877 w3 &= 0x3ffffff;
24878 /* k = 4 */
24879 lo = Math.imul(al4, bl0);
24880 mid = Math.imul(al4, bh0);
24881 mid = (mid + Math.imul(ah4, bl0)) | 0;
24882 hi = Math.imul(ah4, bh0);
24883 lo = (lo + Math.imul(al3, bl1)) | 0;
24884 mid = (mid + Math.imul(al3, bh1)) | 0;
24885 mid = (mid + Math.imul(ah3, bl1)) | 0;
24886 hi = (hi + Math.imul(ah3, bh1)) | 0;
24887 lo = (lo + Math.imul(al2, bl2)) | 0;
24888 mid = (mid + Math.imul(al2, bh2)) | 0;
24889 mid = (mid + Math.imul(ah2, bl2)) | 0;
24890 hi = (hi + Math.imul(ah2, bh2)) | 0;
24891 lo = (lo + Math.imul(al1, bl3)) | 0;
24892 mid = (mid + Math.imul(al1, bh3)) | 0;
24893 mid = (mid + Math.imul(ah1, bl3)) | 0;
24894 hi = (hi + Math.imul(ah1, bh3)) | 0;
24895 lo = (lo + Math.imul(al0, bl4)) | 0;
24896 mid = (mid + Math.imul(al0, bh4)) | 0;
24897 mid = (mid + Math.imul(ah0, bl4)) | 0;
24898 hi = (hi + Math.imul(ah0, bh4)) | 0;
24899 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
24900 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
24901 w4 &= 0x3ffffff;
24902 /* k = 5 */
24903 lo = Math.imul(al5, bl0);
24904 mid = Math.imul(al5, bh0);
24905 mid = (mid + Math.imul(ah5, bl0)) | 0;
24906 hi = Math.imul(ah5, bh0);
24907 lo = (lo + Math.imul(al4, bl1)) | 0;
24908 mid = (mid + Math.imul(al4, bh1)) | 0;
24909 mid = (mid + Math.imul(ah4, bl1)) | 0;
24910 hi = (hi + Math.imul(ah4, bh1)) | 0;
24911 lo = (lo + Math.imul(al3, bl2)) | 0;
24912 mid = (mid + Math.imul(al3, bh2)) | 0;
24913 mid = (mid + Math.imul(ah3, bl2)) | 0;
24914 hi = (hi + Math.imul(ah3, bh2)) | 0;
24915 lo = (lo + Math.imul(al2, bl3)) | 0;
24916 mid = (mid + Math.imul(al2, bh3)) | 0;
24917 mid = (mid + Math.imul(ah2, bl3)) | 0;
24918 hi = (hi + Math.imul(ah2, bh3)) | 0;
24919 lo = (lo + Math.imul(al1, bl4)) | 0;
24920 mid = (mid + Math.imul(al1, bh4)) | 0;
24921 mid = (mid + Math.imul(ah1, bl4)) | 0;
24922 hi = (hi + Math.imul(ah1, bh4)) | 0;
24923 lo = (lo + Math.imul(al0, bl5)) | 0;
24924 mid = (mid + Math.imul(al0, bh5)) | 0;
24925 mid = (mid + Math.imul(ah0, bl5)) | 0;
24926 hi = (hi + Math.imul(ah0, bh5)) | 0;
24927 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
24928 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
24929 w5 &= 0x3ffffff;
24930 /* k = 6 */
24931 lo = Math.imul(al6, bl0);
24932 mid = Math.imul(al6, bh0);
24933 mid = (mid + Math.imul(ah6, bl0)) | 0;
24934 hi = Math.imul(ah6, bh0);
24935 lo = (lo + Math.imul(al5, bl1)) | 0;
24936 mid = (mid + Math.imul(al5, bh1)) | 0;
24937 mid = (mid + Math.imul(ah5, bl1)) | 0;
24938 hi = (hi + Math.imul(ah5, bh1)) | 0;
24939 lo = (lo + Math.imul(al4, bl2)) | 0;
24940 mid = (mid + Math.imul(al4, bh2)) | 0;
24941 mid = (mid + Math.imul(ah4, bl2)) | 0;
24942 hi = (hi + Math.imul(ah4, bh2)) | 0;
24943 lo = (lo + Math.imul(al3, bl3)) | 0;
24944 mid = (mid + Math.imul(al3, bh3)) | 0;
24945 mid = (mid + Math.imul(ah3, bl3)) | 0;
24946 hi = (hi + Math.imul(ah3, bh3)) | 0;
24947 lo = (lo + Math.imul(al2, bl4)) | 0;
24948 mid = (mid + Math.imul(al2, bh4)) | 0;
24949 mid = (mid + Math.imul(ah2, bl4)) | 0;
24950 hi = (hi + Math.imul(ah2, bh4)) | 0;
24951 lo = (lo + Math.imul(al1, bl5)) | 0;
24952 mid = (mid + Math.imul(al1, bh5)) | 0;
24953 mid = (mid + Math.imul(ah1, bl5)) | 0;
24954 hi = (hi + Math.imul(ah1, bh5)) | 0;
24955 lo = (lo + Math.imul(al0, bl6)) | 0;
24956 mid = (mid + Math.imul(al0, bh6)) | 0;
24957 mid = (mid + Math.imul(ah0, bl6)) | 0;
24958 hi = (hi + Math.imul(ah0, bh6)) | 0;
24959 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
24960 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
24961 w6 &= 0x3ffffff;
24962 /* k = 7 */
24963 lo = Math.imul(al7, bl0);
24964 mid = Math.imul(al7, bh0);
24965 mid = (mid + Math.imul(ah7, bl0)) | 0;
24966 hi = Math.imul(ah7, bh0);
24967 lo = (lo + Math.imul(al6, bl1)) | 0;
24968 mid = (mid + Math.imul(al6, bh1)) | 0;
24969 mid = (mid + Math.imul(ah6, bl1)) | 0;
24970 hi = (hi + Math.imul(ah6, bh1)) | 0;
24971 lo = (lo + Math.imul(al5, bl2)) | 0;
24972 mid = (mid + Math.imul(al5, bh2)) | 0;
24973 mid = (mid + Math.imul(ah5, bl2)) | 0;
24974 hi = (hi + Math.imul(ah5, bh2)) | 0;
24975 lo = (lo + Math.imul(al4, bl3)) | 0;
24976 mid = (mid + Math.imul(al4, bh3)) | 0;
24977 mid = (mid + Math.imul(ah4, bl3)) | 0;
24978 hi = (hi + Math.imul(ah4, bh3)) | 0;
24979 lo = (lo + Math.imul(al3, bl4)) | 0;
24980 mid = (mid + Math.imul(al3, bh4)) | 0;
24981 mid = (mid + Math.imul(ah3, bl4)) | 0;
24982 hi = (hi + Math.imul(ah3, bh4)) | 0;
24983 lo = (lo + Math.imul(al2, bl5)) | 0;
24984 mid = (mid + Math.imul(al2, bh5)) | 0;
24985 mid = (mid + Math.imul(ah2, bl5)) | 0;
24986 hi = (hi + Math.imul(ah2, bh5)) | 0;
24987 lo = (lo + Math.imul(al1, bl6)) | 0;
24988 mid = (mid + Math.imul(al1, bh6)) | 0;
24989 mid = (mid + Math.imul(ah1, bl6)) | 0;
24990 hi = (hi + Math.imul(ah1, bh6)) | 0;
24991 lo = (lo + Math.imul(al0, bl7)) | 0;
24992 mid = (mid + Math.imul(al0, bh7)) | 0;
24993 mid = (mid + Math.imul(ah0, bl7)) | 0;
24994 hi = (hi + Math.imul(ah0, bh7)) | 0;
24995 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
24996 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
24997 w7 &= 0x3ffffff;
24998 /* k = 8 */
24999 lo = Math.imul(al8, bl0);
25000 mid = Math.imul(al8, bh0);
25001 mid = (mid + Math.imul(ah8, bl0)) | 0;
25002 hi = Math.imul(ah8, bh0);
25003 lo = (lo + Math.imul(al7, bl1)) | 0;
25004 mid = (mid + Math.imul(al7, bh1)) | 0;
25005 mid = (mid + Math.imul(ah7, bl1)) | 0;
25006 hi = (hi + Math.imul(ah7, bh1)) | 0;
25007 lo = (lo + Math.imul(al6, bl2)) | 0;
25008 mid = (mid + Math.imul(al6, bh2)) | 0;
25009 mid = (mid + Math.imul(ah6, bl2)) | 0;
25010 hi = (hi + Math.imul(ah6, bh2)) | 0;
25011 lo = (lo + Math.imul(al5, bl3)) | 0;
25012 mid = (mid + Math.imul(al5, bh3)) | 0;
25013 mid = (mid + Math.imul(ah5, bl3)) | 0;
25014 hi = (hi + Math.imul(ah5, bh3)) | 0;
25015 lo = (lo + Math.imul(al4, bl4)) | 0;
25016 mid = (mid + Math.imul(al4, bh4)) | 0;
25017 mid = (mid + Math.imul(ah4, bl4)) | 0;
25018 hi = (hi + Math.imul(ah4, bh4)) | 0;
25019 lo = (lo + Math.imul(al3, bl5)) | 0;
25020 mid = (mid + Math.imul(al3, bh5)) | 0;
25021 mid = (mid + Math.imul(ah3, bl5)) | 0;
25022 hi = (hi + Math.imul(ah3, bh5)) | 0;
25023 lo = (lo + Math.imul(al2, bl6)) | 0;
25024 mid = (mid + Math.imul(al2, bh6)) | 0;
25025 mid = (mid + Math.imul(ah2, bl6)) | 0;
25026 hi = (hi + Math.imul(ah2, bh6)) | 0;
25027 lo = (lo + Math.imul(al1, bl7)) | 0;
25028 mid = (mid + Math.imul(al1, bh7)) | 0;
25029 mid = (mid + Math.imul(ah1, bl7)) | 0;
25030 hi = (hi + Math.imul(ah1, bh7)) | 0;
25031 lo = (lo + Math.imul(al0, bl8)) | 0;
25032 mid = (mid + Math.imul(al0, bh8)) | 0;
25033 mid = (mid + Math.imul(ah0, bl8)) | 0;
25034 hi = (hi + Math.imul(ah0, bh8)) | 0;
25035 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25036 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
25037 w8 &= 0x3ffffff;
25038 /* k = 9 */
25039 lo = Math.imul(al9, bl0);
25040 mid = Math.imul(al9, bh0);
25041 mid = (mid + Math.imul(ah9, bl0)) | 0;
25042 hi = Math.imul(ah9, bh0);
25043 lo = (lo + Math.imul(al8, bl1)) | 0;
25044 mid = (mid + Math.imul(al8, bh1)) | 0;
25045 mid = (mid + Math.imul(ah8, bl1)) | 0;
25046 hi = (hi + Math.imul(ah8, bh1)) | 0;
25047 lo = (lo + Math.imul(al7, bl2)) | 0;
25048 mid = (mid + Math.imul(al7, bh2)) | 0;
25049 mid = (mid + Math.imul(ah7, bl2)) | 0;
25050 hi = (hi + Math.imul(ah7, bh2)) | 0;
25051 lo = (lo + Math.imul(al6, bl3)) | 0;
25052 mid = (mid + Math.imul(al6, bh3)) | 0;
25053 mid = (mid + Math.imul(ah6, bl3)) | 0;
25054 hi = (hi + Math.imul(ah6, bh3)) | 0;
25055 lo = (lo + Math.imul(al5, bl4)) | 0;
25056 mid = (mid + Math.imul(al5, bh4)) | 0;
25057 mid = (mid + Math.imul(ah5, bl4)) | 0;
25058 hi = (hi + Math.imul(ah5, bh4)) | 0;
25059 lo = (lo + Math.imul(al4, bl5)) | 0;
25060 mid = (mid + Math.imul(al4, bh5)) | 0;
25061 mid = (mid + Math.imul(ah4, bl5)) | 0;
25062 hi = (hi + Math.imul(ah4, bh5)) | 0;
25063 lo = (lo + Math.imul(al3, bl6)) | 0;
25064 mid = (mid + Math.imul(al3, bh6)) | 0;
25065 mid = (mid + Math.imul(ah3, bl6)) | 0;
25066 hi = (hi + Math.imul(ah3, bh6)) | 0;
25067 lo = (lo + Math.imul(al2, bl7)) | 0;
25068 mid = (mid + Math.imul(al2, bh7)) | 0;
25069 mid = (mid + Math.imul(ah2, bl7)) | 0;
25070 hi = (hi + Math.imul(ah2, bh7)) | 0;
25071 lo = (lo + Math.imul(al1, bl8)) | 0;
25072 mid = (mid + Math.imul(al1, bh8)) | 0;
25073 mid = (mid + Math.imul(ah1, bl8)) | 0;
25074 hi = (hi + Math.imul(ah1, bh8)) | 0;
25075 lo = (lo + Math.imul(al0, bl9)) | 0;
25076 mid = (mid + Math.imul(al0, bh9)) | 0;
25077 mid = (mid + Math.imul(ah0, bl9)) | 0;
25078 hi = (hi + Math.imul(ah0, bh9)) | 0;
25079 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25080 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
25081 w9 &= 0x3ffffff;
25082 /* k = 10 */
25083 lo = Math.imul(al9, bl1);
25084 mid = Math.imul(al9, bh1);
25085 mid = (mid + Math.imul(ah9, bl1)) | 0;
25086 hi = Math.imul(ah9, bh1);
25087 lo = (lo + Math.imul(al8, bl2)) | 0;
25088 mid = (mid + Math.imul(al8, bh2)) | 0;
25089 mid = (mid + Math.imul(ah8, bl2)) | 0;
25090 hi = (hi + Math.imul(ah8, bh2)) | 0;
25091 lo = (lo + Math.imul(al7, bl3)) | 0;
25092 mid = (mid + Math.imul(al7, bh3)) | 0;
25093 mid = (mid + Math.imul(ah7, bl3)) | 0;
25094 hi = (hi + Math.imul(ah7, bh3)) | 0;
25095 lo = (lo + Math.imul(al6, bl4)) | 0;
25096 mid = (mid + Math.imul(al6, bh4)) | 0;
25097 mid = (mid + Math.imul(ah6, bl4)) | 0;
25098 hi = (hi + Math.imul(ah6, bh4)) | 0;
25099 lo = (lo + Math.imul(al5, bl5)) | 0;
25100 mid = (mid + Math.imul(al5, bh5)) | 0;
25101 mid = (mid + Math.imul(ah5, bl5)) | 0;
25102 hi = (hi + Math.imul(ah5, bh5)) | 0;
25103 lo = (lo + Math.imul(al4, bl6)) | 0;
25104 mid = (mid + Math.imul(al4, bh6)) | 0;
25105 mid = (mid + Math.imul(ah4, bl6)) | 0;
25106 hi = (hi + Math.imul(ah4, bh6)) | 0;
25107 lo = (lo + Math.imul(al3, bl7)) | 0;
25108 mid = (mid + Math.imul(al3, bh7)) | 0;
25109 mid = (mid + Math.imul(ah3, bl7)) | 0;
25110 hi = (hi + Math.imul(ah3, bh7)) | 0;
25111 lo = (lo + Math.imul(al2, bl8)) | 0;
25112 mid = (mid + Math.imul(al2, bh8)) | 0;
25113 mid = (mid + Math.imul(ah2, bl8)) | 0;
25114 hi = (hi + Math.imul(ah2, bh8)) | 0;
25115 lo = (lo + Math.imul(al1, bl9)) | 0;
25116 mid = (mid + Math.imul(al1, bh9)) | 0;
25117 mid = (mid + Math.imul(ah1, bl9)) | 0;
25118 hi = (hi + Math.imul(ah1, bh9)) | 0;
25119 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25120 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
25121 w10 &= 0x3ffffff;
25122 /* k = 11 */
25123 lo = Math.imul(al9, bl2);
25124 mid = Math.imul(al9, bh2);
25125 mid = (mid + Math.imul(ah9, bl2)) | 0;
25126 hi = Math.imul(ah9, bh2);
25127 lo = (lo + Math.imul(al8, bl3)) | 0;
25128 mid = (mid + Math.imul(al8, bh3)) | 0;
25129 mid = (mid + Math.imul(ah8, bl3)) | 0;
25130 hi = (hi + Math.imul(ah8, bh3)) | 0;
25131 lo = (lo + Math.imul(al7, bl4)) | 0;
25132 mid = (mid + Math.imul(al7, bh4)) | 0;
25133 mid = (mid + Math.imul(ah7, bl4)) | 0;
25134 hi = (hi + Math.imul(ah7, bh4)) | 0;
25135 lo = (lo + Math.imul(al6, bl5)) | 0;
25136 mid = (mid + Math.imul(al6, bh5)) | 0;
25137 mid = (mid + Math.imul(ah6, bl5)) | 0;
25138 hi = (hi + Math.imul(ah6, bh5)) | 0;
25139 lo = (lo + Math.imul(al5, bl6)) | 0;
25140 mid = (mid + Math.imul(al5, bh6)) | 0;
25141 mid = (mid + Math.imul(ah5, bl6)) | 0;
25142 hi = (hi + Math.imul(ah5, bh6)) | 0;
25143 lo = (lo + Math.imul(al4, bl7)) | 0;
25144 mid = (mid + Math.imul(al4, bh7)) | 0;
25145 mid = (mid + Math.imul(ah4, bl7)) | 0;
25146 hi = (hi + Math.imul(ah4, bh7)) | 0;
25147 lo = (lo + Math.imul(al3, bl8)) | 0;
25148 mid = (mid + Math.imul(al3, bh8)) | 0;
25149 mid = (mid + Math.imul(ah3, bl8)) | 0;
25150 hi = (hi + Math.imul(ah3, bh8)) | 0;
25151 lo = (lo + Math.imul(al2, bl9)) | 0;
25152 mid = (mid + Math.imul(al2, bh9)) | 0;
25153 mid = (mid + Math.imul(ah2, bl9)) | 0;
25154 hi = (hi + Math.imul(ah2, bh9)) | 0;
25155 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25156 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
25157 w11 &= 0x3ffffff;
25158 /* k = 12 */
25159 lo = Math.imul(al9, bl3);
25160 mid = Math.imul(al9, bh3);
25161 mid = (mid + Math.imul(ah9, bl3)) | 0;
25162 hi = Math.imul(ah9, bh3);
25163 lo = (lo + Math.imul(al8, bl4)) | 0;
25164 mid = (mid + Math.imul(al8, bh4)) | 0;
25165 mid = (mid + Math.imul(ah8, bl4)) | 0;
25166 hi = (hi + Math.imul(ah8, bh4)) | 0;
25167 lo = (lo + Math.imul(al7, bl5)) | 0;
25168 mid = (mid + Math.imul(al7, bh5)) | 0;
25169 mid = (mid + Math.imul(ah7, bl5)) | 0;
25170 hi = (hi + Math.imul(ah7, bh5)) | 0;
25171 lo = (lo + Math.imul(al6, bl6)) | 0;
25172 mid = (mid + Math.imul(al6, bh6)) | 0;
25173 mid = (mid + Math.imul(ah6, bl6)) | 0;
25174 hi = (hi + Math.imul(ah6, bh6)) | 0;
25175 lo = (lo + Math.imul(al5, bl7)) | 0;
25176 mid = (mid + Math.imul(al5, bh7)) | 0;
25177 mid = (mid + Math.imul(ah5, bl7)) | 0;
25178 hi = (hi + Math.imul(ah5, bh7)) | 0;
25179 lo = (lo + Math.imul(al4, bl8)) | 0;
25180 mid = (mid + Math.imul(al4, bh8)) | 0;
25181 mid = (mid + Math.imul(ah4, bl8)) | 0;
25182 hi = (hi + Math.imul(ah4, bh8)) | 0;
25183 lo = (lo + Math.imul(al3, bl9)) | 0;
25184 mid = (mid + Math.imul(al3, bh9)) | 0;
25185 mid = (mid + Math.imul(ah3, bl9)) | 0;
25186 hi = (hi + Math.imul(ah3, bh9)) | 0;
25187 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25188 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
25189 w12 &= 0x3ffffff;
25190 /* k = 13 */
25191 lo = Math.imul(al9, bl4);
25192 mid = Math.imul(al9, bh4);
25193 mid = (mid + Math.imul(ah9, bl4)) | 0;
25194 hi = Math.imul(ah9, bh4);
25195 lo = (lo + Math.imul(al8, bl5)) | 0;
25196 mid = (mid + Math.imul(al8, bh5)) | 0;
25197 mid = (mid + Math.imul(ah8, bl5)) | 0;
25198 hi = (hi + Math.imul(ah8, bh5)) | 0;
25199 lo = (lo + Math.imul(al7, bl6)) | 0;
25200 mid = (mid + Math.imul(al7, bh6)) | 0;
25201 mid = (mid + Math.imul(ah7, bl6)) | 0;
25202 hi = (hi + Math.imul(ah7, bh6)) | 0;
25203 lo = (lo + Math.imul(al6, bl7)) | 0;
25204 mid = (mid + Math.imul(al6, bh7)) | 0;
25205 mid = (mid + Math.imul(ah6, bl7)) | 0;
25206 hi = (hi + Math.imul(ah6, bh7)) | 0;
25207 lo = (lo + Math.imul(al5, bl8)) | 0;
25208 mid = (mid + Math.imul(al5, bh8)) | 0;
25209 mid = (mid + Math.imul(ah5, bl8)) | 0;
25210 hi = (hi + Math.imul(ah5, bh8)) | 0;
25211 lo = (lo + Math.imul(al4, bl9)) | 0;
25212 mid = (mid + Math.imul(al4, bh9)) | 0;
25213 mid = (mid + Math.imul(ah4, bl9)) | 0;
25214 hi = (hi + Math.imul(ah4, bh9)) | 0;
25215 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25216 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
25217 w13 &= 0x3ffffff;
25218 /* k = 14 */
25219 lo = Math.imul(al9, bl5);
25220 mid = Math.imul(al9, bh5);
25221 mid = (mid + Math.imul(ah9, bl5)) | 0;
25222 hi = Math.imul(ah9, bh5);
25223 lo = (lo + Math.imul(al8, bl6)) | 0;
25224 mid = (mid + Math.imul(al8, bh6)) | 0;
25225 mid = (mid + Math.imul(ah8, bl6)) | 0;
25226 hi = (hi + Math.imul(ah8, bh6)) | 0;
25227 lo = (lo + Math.imul(al7, bl7)) | 0;
25228 mid = (mid + Math.imul(al7, bh7)) | 0;
25229 mid = (mid + Math.imul(ah7, bl7)) | 0;
25230 hi = (hi + Math.imul(ah7, bh7)) | 0;
25231 lo = (lo + Math.imul(al6, bl8)) | 0;
25232 mid = (mid + Math.imul(al6, bh8)) | 0;
25233 mid = (mid + Math.imul(ah6, bl8)) | 0;
25234 hi = (hi + Math.imul(ah6, bh8)) | 0;
25235 lo = (lo + Math.imul(al5, bl9)) | 0;
25236 mid = (mid + Math.imul(al5, bh9)) | 0;
25237 mid = (mid + Math.imul(ah5, bl9)) | 0;
25238 hi = (hi + Math.imul(ah5, bh9)) | 0;
25239 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25240 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
25241 w14 &= 0x3ffffff;
25242 /* k = 15 */
25243 lo = Math.imul(al9, bl6);
25244 mid = Math.imul(al9, bh6);
25245 mid = (mid + Math.imul(ah9, bl6)) | 0;
25246 hi = Math.imul(ah9, bh6);
25247 lo = (lo + Math.imul(al8, bl7)) | 0;
25248 mid = (mid + Math.imul(al8, bh7)) | 0;
25249 mid = (mid + Math.imul(ah8, bl7)) | 0;
25250 hi = (hi + Math.imul(ah8, bh7)) | 0;
25251 lo = (lo + Math.imul(al7, bl8)) | 0;
25252 mid = (mid + Math.imul(al7, bh8)) | 0;
25253 mid = (mid + Math.imul(ah7, bl8)) | 0;
25254 hi = (hi + Math.imul(ah7, bh8)) | 0;
25255 lo = (lo + Math.imul(al6, bl9)) | 0;
25256 mid = (mid + Math.imul(al6, bh9)) | 0;
25257 mid = (mid + Math.imul(ah6, bl9)) | 0;
25258 hi = (hi + Math.imul(ah6, bh9)) | 0;
25259 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25260 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
25261 w15 &= 0x3ffffff;
25262 /* k = 16 */
25263 lo = Math.imul(al9, bl7);
25264 mid = Math.imul(al9, bh7);
25265 mid = (mid + Math.imul(ah9, bl7)) | 0;
25266 hi = Math.imul(ah9, bh7);
25267 lo = (lo + Math.imul(al8, bl8)) | 0;
25268 mid = (mid + Math.imul(al8, bh8)) | 0;
25269 mid = (mid + Math.imul(ah8, bl8)) | 0;
25270 hi = (hi + Math.imul(ah8, bh8)) | 0;
25271 lo = (lo + Math.imul(al7, bl9)) | 0;
25272 mid = (mid + Math.imul(al7, bh9)) | 0;
25273 mid = (mid + Math.imul(ah7, bl9)) | 0;
25274 hi = (hi + Math.imul(ah7, bh9)) | 0;
25275 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25276 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
25277 w16 &= 0x3ffffff;
25278 /* k = 17 */
25279 lo = Math.imul(al9, bl8);
25280 mid = Math.imul(al9, bh8);
25281 mid = (mid + Math.imul(ah9, bl8)) | 0;
25282 hi = Math.imul(ah9, bh8);
25283 lo = (lo + Math.imul(al8, bl9)) | 0;
25284 mid = (mid + Math.imul(al8, bh9)) | 0;
25285 mid = (mid + Math.imul(ah8, bl9)) | 0;
25286 hi = (hi + Math.imul(ah8, bh9)) | 0;
25287 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25288 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
25289 w17 &= 0x3ffffff;
25290 /* k = 18 */
25291 lo = Math.imul(al9, bl9);
25292 mid = Math.imul(al9, bh9);
25293 mid = (mid + Math.imul(ah9, bl9)) | 0;
25294 hi = Math.imul(ah9, bh9);
25295 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
25296 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
25297 w18 &= 0x3ffffff;
25298 o[0] = w0;
25299 o[1] = w1;
25300 o[2] = w2;
25301 o[3] = w3;
25302 o[4] = w4;
25303 o[5] = w5;
25304 o[6] = w6;
25305 o[7] = w7;
25306 o[8] = w8;
25307 o[9] = w9;
25308 o[10] = w10;
25309 o[11] = w11;
25310 o[12] = w12;
25311 o[13] = w13;
25312 o[14] = w14;
25313 o[15] = w15;
25314 o[16] = w16;
25315 o[17] = w17;
25316 o[18] = w18;
25317 if (c !== 0) {
25318 o[19] = c;
25319 out.length++;
25320 }
25321 return out;
25322 };
25323
25324 // Polyfill comb
25325 if (!Math.imul) {
25326 comb10MulTo = smallMulTo;
25327 }
25328
25329 function bigMulTo (self, num, out) {
25330 out.negative = num.negative ^ self.negative;
25331 out.length = self.length + num.length;
25332
25333 var carry = 0;
25334 var hncarry = 0;
25335 for (var k = 0; k < out.length - 1; k++) {
25336 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
25337 // note that ncarry could be >= 0x3ffffff
25338 var ncarry = hncarry;
25339 hncarry = 0;
25340 var rword = carry & 0x3ffffff;
25341 var maxJ = Math.min(k, num.length - 1);
25342 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
25343 var i = k - j;
25344 var a = self.words[i] | 0;
25345 var b = num.words[j] | 0;
25346 var r = a * b;
25347
25348 var lo = r & 0x3ffffff;
25349 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
25350 lo = (lo + rword) | 0;
25351 rword = lo & 0x3ffffff;
25352 ncarry = (ncarry + (lo >>> 26)) | 0;
25353
25354 hncarry += ncarry >>> 26;
25355 ncarry &= 0x3ffffff;
25356 }
25357 out.words[k] = rword;
25358 carry = ncarry;
25359 ncarry = hncarry;
25360 }
25361 if (carry !== 0) {
25362 out.words[k] = carry;
25363 } else {
25364 out.length--;
25365 }
25366
25367 return out._strip();
25368 }
25369
25370 function jumboMulTo (self, num, out) {
25371 // Temporary disable, see https://github.com/indutny/bn.js/issues/211
25372 // var fftm = new FFTM();
25373 // return fftm.mulp(self, num, out);
25374 return bigMulTo(self, num, out);
25375 }
25376
25377 BN.prototype.mulTo = function mulTo (num, out) {
25378 var res;
25379 var len = this.length + num.length;
25380 if (this.length === 10 && num.length === 10) {
25381 res = comb10MulTo(this, num, out);
25382 } else if (len < 63) {
25383 res = smallMulTo(this, num, out);
25384 } else if (len < 1024) {
25385 res = bigMulTo(this, num, out);
25386 } else {
25387 res = jumboMulTo(this, num, out);
25388 }
25389
25390 return res;
25391 };
25392
25393 // Cooley-Tukey algorithm for FFT
25394 // slightly revisited to rely on looping instead of recursion
25395
25396 function FFTM (x, y) {
25397 this.x = x;
25398 this.y = y;
25399 }
25400
25401 FFTM.prototype.makeRBT = function makeRBT (N) {
25402 var t = new Array(N);
25403 var l = BN.prototype._countBits(N) - 1;
25404 for (var i = 0; i < N; i++) {
25405 t[i] = this.revBin(i, l, N);
25406 }
25407
25408 return t;
25409 };
25410
25411 // Returns binary-reversed representation of `x`
25412 FFTM.prototype.revBin = function revBin (x, l, N) {
25413 if (x === 0 || x === N - 1) return x;
25414
25415 var rb = 0;
25416 for (var i = 0; i < l; i++) {
25417 rb |= (x & 1) << (l - i - 1);
25418 x >>= 1;
25419 }
25420
25421 return rb;
25422 };
25423
25424 // Performs "tweedling" phase, therefore 'emulating'
25425 // behaviour of the recursive algorithm
25426 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
25427 for (var i = 0; i < N; i++) {
25428 rtws[i] = rws[rbt[i]];
25429 itws[i] = iws[rbt[i]];
25430 }
25431 };
25432
25433 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
25434 this.permute(rbt, rws, iws, rtws, itws, N);
25435
25436 for (var s = 1; s < N; s <<= 1) {
25437 var l = s << 1;
25438
25439 var rtwdf = Math.cos(2 * Math.PI / l);
25440 var itwdf = Math.sin(2 * Math.PI / l);
25441
25442 for (var p = 0; p < N; p += l) {
25443 var rtwdf_ = rtwdf;
25444 var itwdf_ = itwdf;
25445
25446 for (var j = 0; j < s; j++) {
25447 var re = rtws[p + j];
25448 var ie = itws[p + j];
25449
25450 var ro = rtws[p + j + s];
25451 var io = itws[p + j + s];
25452
25453 var rx = rtwdf_ * ro - itwdf_ * io;
25454
25455 io = rtwdf_ * io + itwdf_ * ro;
25456 ro = rx;
25457
25458 rtws[p + j] = re + ro;
25459 itws[p + j] = ie + io;
25460
25461 rtws[p + j + s] = re - ro;
25462 itws[p + j + s] = ie - io;
25463
25464 /* jshint maxdepth : false */
25465 if (j !== l) {
25466 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
25467
25468 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
25469 rtwdf_ = rx;
25470 }
25471 }
25472 }
25473 }
25474 };
25475
25476 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
25477 var N = Math.max(m, n) | 1;
25478 var odd = N & 1;
25479 var i = 0;
25480 for (N = N / 2 | 0; N; N = N >>> 1) {
25481 i++;
25482 }
25483
25484 return 1 << i + 1 + odd;
25485 };
25486
25487 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
25488 if (N <= 1) return;
25489
25490 for (var i = 0; i < N / 2; i++) {
25491 var t = rws[i];
25492
25493 rws[i] = rws[N - i - 1];
25494 rws[N - i - 1] = t;
25495
25496 t = iws[i];
25497
25498 iws[i] = -iws[N - i - 1];
25499 iws[N - i - 1] = -t;
25500 }
25501 };
25502
25503 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
25504 var carry = 0;
25505 for (var i = 0; i < N / 2; i++) {
25506 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
25507 Math.round(ws[2 * i] / N) +
25508 carry;
25509
25510 ws[i] = w & 0x3ffffff;
25511
25512 if (w < 0x4000000) {
25513 carry = 0;
25514 } else {
25515 carry = w / 0x4000000 | 0;
25516 }
25517 }
25518
25519 return ws;
25520 };
25521
25522 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
25523 var carry = 0;
25524 for (var i = 0; i < len; i++) {
25525 carry = carry + (ws[i] | 0);
25526
25527 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
25528 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
25529 }
25530
25531 // Pad with zeroes
25532 for (i = 2 * len; i < N; ++i) {
25533 rws[i] = 0;
25534 }
25535
25536 assert(carry === 0);
25537 assert((carry & ~0x1fff) === 0);
25538 };
25539
25540 FFTM.prototype.stub = function stub (N) {
25541 var ph = new Array(N);
25542 for (var i = 0; i < N; i++) {
25543 ph[i] = 0;
25544 }
25545
25546 return ph;
25547 };
25548
25549 FFTM.prototype.mulp = function mulp (x, y, out) {
25550 var N = 2 * this.guessLen13b(x.length, y.length);
25551
25552 var rbt = this.makeRBT(N);
25553
25554 var _ = this.stub(N);
25555
25556 var rws = new Array(N);
25557 var rwst = new Array(N);
25558 var iwst = new Array(N);
25559
25560 var nrws = new Array(N);
25561 var nrwst = new Array(N);
25562 var niwst = new Array(N);
25563
25564 var rmws = out.words;
25565 rmws.length = N;
25566
25567 this.convert13b(x.words, x.length, rws, N);
25568 this.convert13b(y.words, y.length, nrws, N);
25569
25570 this.transform(rws, _, rwst, iwst, N, rbt);
25571 this.transform(nrws, _, nrwst, niwst, N, rbt);
25572
25573 for (var i = 0; i < N; i++) {
25574 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
25575 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
25576 rwst[i] = rx;
25577 }
25578
25579 this.conjugate(rwst, iwst, N);
25580 this.transform(rwst, iwst, rmws, _, N, rbt);
25581 this.conjugate(rmws, _, N);
25582 this.normalize13b(rmws, N);
25583
25584 out.negative = x.negative ^ y.negative;
25585 out.length = x.length + y.length;
25586 return out._strip();
25587 };
25588
25589 // Multiply `this` by `num`
25590 BN.prototype.mul = function mul (num) {
25591 var out = new BN(null);
25592 out.words = new Array(this.length + num.length);
25593 return this.mulTo(num, out);
25594 };
25595
25596 // Multiply employing FFT
25597 BN.prototype.mulf = function mulf (num) {
25598 var out = new BN(null);
25599 out.words = new Array(this.length + num.length);
25600 return jumboMulTo(this, num, out);
25601 };
25602
25603 // In-place Multiplication
25604 BN.prototype.imul = function imul (num) {
25605 return this.clone().mulTo(num, this);
25606 };
25607
25608 BN.prototype.imuln = function imuln (num) {
25609 var isNegNum = num < 0;
25610 if (isNegNum) num = -num;
25611
25612 assert(typeof num === 'number');
25613 assert(num < 0x4000000);
25614
25615 // Carry
25616 var carry = 0;
25617 for (var i = 0; i < this.length; i++) {
25618 var w = (this.words[i] | 0) * num;
25619 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
25620 carry >>= 26;
25621 carry += (w / 0x4000000) | 0;
25622 // NOTE: lo is 27bit maximum
25623 carry += lo >>> 26;
25624 this.words[i] = lo & 0x3ffffff;
25625 }
25626
25627 if (carry !== 0) {
25628 this.words[i] = carry;
25629 this.length++;
25630 }
25631
25632 return isNegNum ? this.ineg() : this;
25633 };
25634
25635 BN.prototype.muln = function muln (num) {
25636 return this.clone().imuln(num);
25637 };
25638
25639 // `this` * `this`
25640 BN.prototype.sqr = function sqr () {
25641 return this.mul(this);
25642 };
25643
25644 // `this` * `this` in-place
25645 BN.prototype.isqr = function isqr () {
25646 return this.imul(this.clone());
25647 };
25648
25649 // Math.pow(`this`, `num`)
25650 BN.prototype.pow = function pow (num) {
25651 var w = toBitArray(num);
25652 if (w.length === 0) return new BN(1);
25653
25654 // Skip leading zeroes
25655 var res = this;
25656 for (var i = 0; i < w.length; i++, res = res.sqr()) {
25657 if (w[i] !== 0) break;
25658 }
25659
25660 if (++i < w.length) {
25661 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
25662 if (w[i] === 0) continue;
25663
25664 res = res.mul(q);
25665 }
25666 }
25667
25668 return res;
25669 };
25670
25671 // Shift-left in-place
25672 BN.prototype.iushln = function iushln (bits) {
25673 assert(typeof bits === 'number' && bits >= 0);
25674 var r = bits % 26;
25675 var s = (bits - r) / 26;
25676 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
25677 var i;
25678
25679 if (r !== 0) {
25680 var carry = 0;
25681
25682 for (i = 0; i < this.length; i++) {
25683 var newCarry = this.words[i] & carryMask;
25684 var c = ((this.words[i] | 0) - newCarry) << r;
25685 this.words[i] = c | carry;
25686 carry = newCarry >>> (26 - r);
25687 }
25688
25689 if (carry) {
25690 this.words[i] = carry;
25691 this.length++;
25692 }
25693 }
25694
25695 if (s !== 0) {
25696 for (i = this.length - 1; i >= 0; i--) {
25697 this.words[i + s] = this.words[i];
25698 }
25699
25700 for (i = 0; i < s; i++) {
25701 this.words[i] = 0;
25702 }
25703
25704 this.length += s;
25705 }
25706
25707 return this._strip();
25708 };
25709
25710 BN.prototype.ishln = function ishln (bits) {
25711 // TODO(indutny): implement me
25712 assert(this.negative === 0);
25713 return this.iushln(bits);
25714 };
25715
25716 // Shift-right in-place
25717 // NOTE: `hint` is a lowest bit before trailing zeroes
25718 // NOTE: if `extended` is present - it will be filled with destroyed bits
25719 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
25720 assert(typeof bits === 'number' && bits >= 0);
25721 var h;
25722 if (hint) {
25723 h = (hint - (hint % 26)) / 26;
25724 } else {
25725 h = 0;
25726 }
25727
25728 var r = bits % 26;
25729 var s = Math.min((bits - r) / 26, this.length);
25730 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
25731 var maskedWords = extended;
25732
25733 h -= s;
25734 h = Math.max(0, h);
25735
25736 // Extended mode, copy masked part
25737 if (maskedWords) {
25738 for (var i = 0; i < s; i++) {
25739 maskedWords.words[i] = this.words[i];
25740 }
25741 maskedWords.length = s;
25742 }
25743
25744 if (s === 0) {
25745 // No-op, we should not move anything at all
25746 } else if (this.length > s) {
25747 this.length -= s;
25748 for (i = 0; i < this.length; i++) {
25749 this.words[i] = this.words[i + s];
25750 }
25751 } else {
25752 this.words[0] = 0;
25753 this.length = 1;
25754 }
25755
25756 var carry = 0;
25757 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
25758 var word = this.words[i] | 0;
25759 this.words[i] = (carry << (26 - r)) | (word >>> r);
25760 carry = word & mask;
25761 }
25762
25763 // Push carried bits as a mask
25764 if (maskedWords && carry !== 0) {
25765 maskedWords.words[maskedWords.length++] = carry;
25766 }
25767
25768 if (this.length === 0) {
25769 this.words[0] = 0;
25770 this.length = 1;
25771 }
25772
25773 return this._strip();
25774 };
25775
25776 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
25777 // TODO(indutny): implement me
25778 assert(this.negative === 0);
25779 return this.iushrn(bits, hint, extended);
25780 };
25781
25782 // Shift-left
25783 BN.prototype.shln = function shln (bits) {
25784 return this.clone().ishln(bits);
25785 };
25786
25787 BN.prototype.ushln = function ushln (bits) {
25788 return this.clone().iushln(bits);
25789 };
25790
25791 // Shift-right
25792 BN.prototype.shrn = function shrn (bits) {
25793 return this.clone().ishrn(bits);
25794 };
25795
25796 BN.prototype.ushrn = function ushrn (bits) {
25797 return this.clone().iushrn(bits);
25798 };
25799
25800 // Test if n bit is set
25801 BN.prototype.testn = function testn (bit) {
25802 assert(typeof bit === 'number' && bit >= 0);
25803 var r = bit % 26;
25804 var s = (bit - r) / 26;
25805 var q = 1 << r;
25806
25807 // Fast case: bit is much higher than all existing words
25808 if (this.length <= s) return false;
25809
25810 // Check bit and return
25811 var w = this.words[s];
25812
25813 return !!(w & q);
25814 };
25815
25816 // Return only lowers bits of number (in-place)
25817 BN.prototype.imaskn = function imaskn (bits) {
25818 assert(typeof bits === 'number' && bits >= 0);
25819 var r = bits % 26;
25820 var s = (bits - r) / 26;
25821
25822 assert(this.negative === 0, 'imaskn works only with positive numbers');
25823
25824 if (this.length <= s) {
25825 return this;
25826 }
25827
25828 if (r !== 0) {
25829 s++;
25830 }
25831 this.length = Math.min(s, this.length);
25832
25833 if (r !== 0) {
25834 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
25835 this.words[this.length - 1] &= mask;
25836 }
25837
25838 return this._strip();
25839 };
25840
25841 // Return only lowers bits of number
25842 BN.prototype.maskn = function maskn (bits) {
25843 return this.clone().imaskn(bits);
25844 };
25845
25846 // Add plain number `num` to `this`
25847 BN.prototype.iaddn = function iaddn (num) {
25848 assert(typeof num === 'number');
25849 assert(num < 0x4000000);
25850 if (num < 0) return this.isubn(-num);
25851
25852 // Possible sign change
25853 if (this.negative !== 0) {
25854 if (this.length === 1 && (this.words[0] | 0) <= num) {
25855 this.words[0] = num - (this.words[0] | 0);
25856 this.negative = 0;
25857 return this;
25858 }
25859
25860 this.negative = 0;
25861 this.isubn(num);
25862 this.negative = 1;
25863 return this;
25864 }
25865
25866 // Add without checks
25867 return this._iaddn(num);
25868 };
25869
25870 BN.prototype._iaddn = function _iaddn (num) {
25871 this.words[0] += num;
25872
25873 // Carry
25874 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
25875 this.words[i] -= 0x4000000;
25876 if (i === this.length - 1) {
25877 this.words[i + 1] = 1;
25878 } else {
25879 this.words[i + 1]++;
25880 }
25881 }
25882 this.length = Math.max(this.length, i + 1);
25883
25884 return this;
25885 };
25886
25887 // Subtract plain number `num` from `this`
25888 BN.prototype.isubn = function isubn (num) {
25889 assert(typeof num === 'number');
25890 assert(num < 0x4000000);
25891 if (num < 0) return this.iaddn(-num);
25892
25893 if (this.negative !== 0) {
25894 this.negative = 0;
25895 this.iaddn(num);
25896 this.negative = 1;
25897 return this;
25898 }
25899
25900 this.words[0] -= num;
25901
25902 if (this.length === 1 && this.words[0] < 0) {
25903 this.words[0] = -this.words[0];
25904 this.negative = 1;
25905 } else {
25906 // Carry
25907 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
25908 this.words[i] += 0x4000000;
25909 this.words[i + 1] -= 1;
25910 }
25911 }
25912
25913 return this._strip();
25914 };
25915
25916 BN.prototype.addn = function addn (num) {
25917 return this.clone().iaddn(num);
25918 };
25919
25920 BN.prototype.subn = function subn (num) {
25921 return this.clone().isubn(num);
25922 };
25923
25924 BN.prototype.iabs = function iabs () {
25925 this.negative = 0;
25926
25927 return this;
25928 };
25929
25930 BN.prototype.abs = function abs () {
25931 return this.clone().iabs();
25932 };
25933
25934 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
25935 var len = num.length + shift;
25936 var i;
25937
25938 this._expand(len);
25939
25940 var w;
25941 var carry = 0;
25942 for (i = 0; i < num.length; i++) {
25943 w = (this.words[i + shift] | 0) + carry;
25944 var right = (num.words[i] | 0) * mul;
25945 w -= right & 0x3ffffff;
25946 carry = (w >> 26) - ((right / 0x4000000) | 0);
25947 this.words[i + shift] = w & 0x3ffffff;
25948 }
25949 for (; i < this.length - shift; i++) {
25950 w = (this.words[i + shift] | 0) + carry;
25951 carry = w >> 26;
25952 this.words[i + shift] = w & 0x3ffffff;
25953 }
25954
25955 if (carry === 0) return this._strip();
25956
25957 // Subtraction overflow
25958 assert(carry === -1);
25959 carry = 0;
25960 for (i = 0; i < this.length; i++) {
25961 w = -(this.words[i] | 0) + carry;
25962 carry = w >> 26;
25963 this.words[i] = w & 0x3ffffff;
25964 }
25965 this.negative = 1;
25966
25967 return this._strip();
25968 };
25969
25970 BN.prototype._wordDiv = function _wordDiv (num, mode) {
25971 var shift = this.length - num.length;
25972
25973 var a = this.clone();
25974 var b = num;
25975
25976 // Normalize
25977 var bhi = b.words[b.length - 1] | 0;
25978 var bhiBits = this._countBits(bhi);
25979 shift = 26 - bhiBits;
25980 if (shift !== 0) {
25981 b = b.ushln(shift);
25982 a.iushln(shift);
25983 bhi = b.words[b.length - 1] | 0;
25984 }
25985
25986 // Initialize quotient
25987 var m = a.length - b.length;
25988 var q;
25989
25990 if (mode !== 'mod') {
25991 q = new BN(null);
25992 q.length = m + 1;
25993 q.words = new Array(q.length);
25994 for (var i = 0; i < q.length; i++) {
25995 q.words[i] = 0;
25996 }
25997 }
25998
25999 var diff = a.clone()._ishlnsubmul(b, 1, m);
26000 if (diff.negative === 0) {
26001 a = diff;
26002 if (q) {
26003 q.words[m] = 1;
26004 }
26005 }
26006
26007 for (var j = m - 1; j >= 0; j--) {
26008 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
26009 (a.words[b.length + j - 1] | 0);
26010
26011 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
26012 // (0x7ffffff)
26013 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
26014
26015 a._ishlnsubmul(b, qj, j);
26016 while (a.negative !== 0) {
26017 qj--;
26018 a.negative = 0;
26019 a._ishlnsubmul(b, 1, j);
26020 if (!a.isZero()) {
26021 a.negative ^= 1;
26022 }
26023 }
26024 if (q) {
26025 q.words[j] = qj;
26026 }
26027 }
26028 if (q) {
26029 q._strip();
26030 }
26031 a._strip();
26032
26033 // Denormalize
26034 if (mode !== 'div' && shift !== 0) {
26035 a.iushrn(shift);
26036 }
26037
26038 return {
26039 div: q || null,
26040 mod: a
26041 };
26042 };
26043
26044 // NOTE: 1) `mode` can be set to `mod` to request mod only,
26045 // to `div` to request div only, or be absent to
26046 // request both div & mod
26047 // 2) `positive` is true if unsigned mod is requested
26048 BN.prototype.divmod = function divmod (num, mode, positive) {
26049 assert(!num.isZero());
26050
26051 if (this.isZero()) {
26052 return {
26053 div: new BN(0),
26054 mod: new BN(0)
26055 };
26056 }
26057
26058 var div, mod, res;
26059 if (this.negative !== 0 && num.negative === 0) {
26060 res = this.neg().divmod(num, mode);
26061
26062 if (mode !== 'mod') {
26063 div = res.div.neg();
26064 }
26065
26066 if (mode !== 'div') {
26067 mod = res.mod.neg();
26068 if (positive && mod.negative !== 0) {
26069 mod.iadd(num);
26070 }
26071 }
26072
26073 return {
26074 div: div,
26075 mod: mod
26076 };
26077 }
26078
26079 if (this.negative === 0 && num.negative !== 0) {
26080 res = this.divmod(num.neg(), mode);
26081
26082 if (mode !== 'mod') {
26083 div = res.div.neg();
26084 }
26085
26086 return {
26087 div: div,
26088 mod: res.mod
26089 };
26090 }
26091
26092 if ((this.negative & num.negative) !== 0) {
26093 res = this.neg().divmod(num.neg(), mode);
26094
26095 if (mode !== 'div') {
26096 mod = res.mod.neg();
26097 if (positive && mod.negative !== 0) {
26098 mod.isub(num);
26099 }
26100 }
26101
26102 return {
26103 div: res.div,
26104 mod: mod
26105 };
26106 }
26107
26108 // Both numbers are positive at this point
26109
26110 // Strip both numbers to approximate shift value
26111 if (num.length > this.length || this.cmp(num) < 0) {
26112 return {
26113 div: new BN(0),
26114 mod: this
26115 };
26116 }
26117
26118 // Very short reduction
26119 if (num.length === 1) {
26120 if (mode === 'div') {
26121 return {
26122 div: this.divn(num.words[0]),
26123 mod: null
26124 };
26125 }
26126
26127 if (mode === 'mod') {
26128 return {
26129 div: null,
26130 mod: new BN(this.modrn(num.words[0]))
26131 };
26132 }
26133
26134 return {
26135 div: this.divn(num.words[0]),
26136 mod: new BN(this.modrn(num.words[0]))
26137 };
26138 }
26139
26140 return this._wordDiv(num, mode);
26141 };
26142
26143 // Find `this` / `num`
26144 BN.prototype.div = function div (num) {
26145 return this.divmod(num, 'div', false).div;
26146 };
26147
26148 // Find `this` % `num`
26149 BN.prototype.mod = function mod (num) {
26150 return this.divmod(num, 'mod', false).mod;
26151 };
26152
26153 BN.prototype.umod = function umod (num) {
26154 return this.divmod(num, 'mod', true).mod;
26155 };
26156
26157 // Find Round(`this` / `num`)
26158 BN.prototype.divRound = function divRound (num) {
26159 var dm = this.divmod(num);
26160
26161 // Fast case - exact division
26162 if (dm.mod.isZero()) return dm.div;
26163
26164 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
26165
26166 var half = num.ushrn(1);
26167 var r2 = num.andln(1);
26168 var cmp = mod.cmp(half);
26169
26170 // Round down
26171 if (cmp < 0 || (r2 === 1 && cmp === 0)) return dm.div;
26172
26173 // Round up
26174 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
26175 };
26176
26177 BN.prototype.modrn = function modrn (num) {
26178 var isNegNum = num < 0;
26179 if (isNegNum) num = -num;
26180
26181 assert(num <= 0x3ffffff);
26182 var p = (1 << 26) % num;
26183
26184 var acc = 0;
26185 for (var i = this.length - 1; i >= 0; i--) {
26186 acc = (p * acc + (this.words[i] | 0)) % num;
26187 }
26188
26189 return isNegNum ? -acc : acc;
26190 };
26191
26192 // WARNING: DEPRECATED
26193 BN.prototype.modn = function modn (num) {
26194 return this.modrn(num);
26195 };
26196
26197 // In-place division by number
26198 BN.prototype.idivn = function idivn (num) {
26199 var isNegNum = num < 0;
26200 if (isNegNum) num = -num;
26201
26202 assert(num <= 0x3ffffff);
26203
26204 var carry = 0;
26205 for (var i = this.length - 1; i >= 0; i--) {
26206 var w = (this.words[i] | 0) + carry * 0x4000000;
26207 this.words[i] = (w / num) | 0;
26208 carry = w % num;
26209 }
26210
26211 this._strip();
26212 return isNegNum ? this.ineg() : this;
26213 };
26214
26215 BN.prototype.divn = function divn (num) {
26216 return this.clone().idivn(num);
26217 };
26218
26219 BN.prototype.egcd = function egcd (p) {
26220 assert(p.negative === 0);
26221 assert(!p.isZero());
26222
26223 var x = this;
26224 var y = p.clone();
26225
26226 if (x.negative !== 0) {
26227 x = x.umod(p);
26228 } else {
26229 x = x.clone();
26230 }
26231
26232 // A * x + B * y = x
26233 var A = new BN(1);
26234 var B = new BN(0);
26235
26236 // C * x + D * y = y
26237 var C = new BN(0);
26238 var D = new BN(1);
26239
26240 var g = 0;
26241
26242 while (x.isEven() && y.isEven()) {
26243 x.iushrn(1);
26244 y.iushrn(1);
26245 ++g;
26246 }
26247
26248 var yp = y.clone();
26249 var xp = x.clone();
26250
26251 while (!x.isZero()) {
26252 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
26253 if (i > 0) {
26254 x.iushrn(i);
26255 while (i-- > 0) {
26256 if (A.isOdd() || B.isOdd()) {
26257 A.iadd(yp);
26258 B.isub(xp);
26259 }
26260
26261 A.iushrn(1);
26262 B.iushrn(1);
26263 }
26264 }
26265
26266 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
26267 if (j > 0) {
26268 y.iushrn(j);
26269 while (j-- > 0) {
26270 if (C.isOdd() || D.isOdd()) {
26271 C.iadd(yp);
26272 D.isub(xp);
26273 }
26274
26275 C.iushrn(1);
26276 D.iushrn(1);
26277 }
26278 }
26279
26280 if (x.cmp(y) >= 0) {
26281 x.isub(y);
26282 A.isub(C);
26283 B.isub(D);
26284 } else {
26285 y.isub(x);
26286 C.isub(A);
26287 D.isub(B);
26288 }
26289 }
26290
26291 return {
26292 a: C,
26293 b: D,
26294 gcd: y.iushln(g)
26295 };
26296 };
26297
26298 // This is reduced incarnation of the binary EEA
26299 // above, designated to invert members of the
26300 // _prime_ fields F(p) at a maximal speed
26301 BN.prototype._invmp = function _invmp (p) {
26302 assert(p.negative === 0);
26303 assert(!p.isZero());
26304
26305 var a = this;
26306 var b = p.clone();
26307
26308 if (a.negative !== 0) {
26309 a = a.umod(p);
26310 } else {
26311 a = a.clone();
26312 }
26313
26314 var x1 = new BN(1);
26315 var x2 = new BN(0);
26316
26317 var delta = b.clone();
26318
26319 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
26320 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
26321 if (i > 0) {
26322 a.iushrn(i);
26323 while (i-- > 0) {
26324 if (x1.isOdd()) {
26325 x1.iadd(delta);
26326 }
26327
26328 x1.iushrn(1);
26329 }
26330 }
26331
26332 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
26333 if (j > 0) {
26334 b.iushrn(j);
26335 while (j-- > 0) {
26336 if (x2.isOdd()) {
26337 x2.iadd(delta);
26338 }
26339
26340 x2.iushrn(1);
26341 }
26342 }
26343
26344 if (a.cmp(b) >= 0) {
26345 a.isub(b);
26346 x1.isub(x2);
26347 } else {
26348 b.isub(a);
26349 x2.isub(x1);
26350 }
26351 }
26352
26353 var res;
26354 if (a.cmpn(1) === 0) {
26355 res = x1;
26356 } else {
26357 res = x2;
26358 }
26359
26360 if (res.cmpn(0) < 0) {
26361 res.iadd(p);
26362 }
26363
26364 return res;
26365 };
26366
26367 BN.prototype.gcd = function gcd (num) {
26368 if (this.isZero()) return num.abs();
26369 if (num.isZero()) return this.abs();
26370
26371 var a = this.clone();
26372 var b = num.clone();
26373 a.negative = 0;
26374 b.negative = 0;
26375
26376 // Remove common factor of two
26377 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
26378 a.iushrn(1);
26379 b.iushrn(1);
26380 }
26381
26382 do {
26383 while (a.isEven()) {
26384 a.iushrn(1);
26385 }
26386 while (b.isEven()) {
26387 b.iushrn(1);
26388 }
26389
26390 var r = a.cmp(b);
26391 if (r < 0) {
26392 // Swap `a` and `b` to make `a` always bigger than `b`
26393 var t = a;
26394 a = b;
26395 b = t;
26396 } else if (r === 0 || b.cmpn(1) === 0) {
26397 break;
26398 }
26399
26400 a.isub(b);
26401 } while (true);
26402
26403 return b.iushln(shift);
26404 };
26405
26406 // Invert number in the field F(num)
26407 BN.prototype.invm = function invm (num) {
26408 return this.egcd(num).a.umod(num);
26409 };
26410
26411 BN.prototype.isEven = function isEven () {
26412 return (this.words[0] & 1) === 0;
26413 };
26414
26415 BN.prototype.isOdd = function isOdd () {
26416 return (this.words[0] & 1) === 1;
26417 };
26418
26419 // And first word and num
26420 BN.prototype.andln = function andln (num) {
26421 return this.words[0] & num;
26422 };
26423
26424 // Increment at the bit position in-line
26425 BN.prototype.bincn = function bincn (bit) {
26426 assert(typeof bit === 'number');
26427 var r = bit % 26;
26428 var s = (bit - r) / 26;
26429 var q = 1 << r;
26430
26431 // Fast case: bit is much higher than all existing words
26432 if (this.length <= s) {
26433 this._expand(s + 1);
26434 this.words[s] |= q;
26435 return this;
26436 }
26437
26438 // Add bit and propagate, if needed
26439 var carry = q;
26440 for (var i = s; carry !== 0 && i < this.length; i++) {
26441 var w = this.words[i] | 0;
26442 w += carry;
26443 carry = w >>> 26;
26444 w &= 0x3ffffff;
26445 this.words[i] = w;
26446 }
26447 if (carry !== 0) {
26448 this.words[i] = carry;
26449 this.length++;
26450 }
26451 return this;
26452 };
26453
26454 BN.prototype.isZero = function isZero () {
26455 return this.length === 1 && this.words[0] === 0;
26456 };
26457
26458 BN.prototype.cmpn = function cmpn (num) {
26459 var negative = num < 0;
26460
26461 if (this.negative !== 0 && !negative) return -1;
26462 if (this.negative === 0 && negative) return 1;
26463
26464 this._strip();
26465
26466 var res;
26467 if (this.length > 1) {
26468 res = 1;
26469 } else {
26470 if (negative) {
26471 num = -num;
26472 }
26473
26474 assert(num <= 0x3ffffff, 'Number is too big');
26475
26476 var w = this.words[0] | 0;
26477 res = w === num ? 0 : w < num ? -1 : 1;
26478 }
26479 if (this.negative !== 0) return -res | 0;
26480 return res;
26481 };
26482
26483 // Compare two numbers and return:
26484 // 1 - if `this` > `num`
26485 // 0 - if `this` == `num`
26486 // -1 - if `this` < `num`
26487 BN.prototype.cmp = function cmp (num) {
26488 if (this.negative !== 0 && num.negative === 0) return -1;
26489 if (this.negative === 0 && num.negative !== 0) return 1;
26490
26491 var res = this.ucmp(num);
26492 if (this.negative !== 0) return -res | 0;
26493 return res;
26494 };
26495
26496 // Unsigned comparison
26497 BN.prototype.ucmp = function ucmp (num) {
26498 // At this point both numbers have the same sign
26499 if (this.length > num.length) return 1;
26500 if (this.length < num.length) return -1;
26501
26502 var res = 0;
26503 for (var i = this.length - 1; i >= 0; i--) {
26504 var a = this.words[i] | 0;
26505 var b = num.words[i] | 0;
26506
26507 if (a === b) continue;
26508 if (a < b) {
26509 res = -1;
26510 } else if (a > b) {
26511 res = 1;
26512 }
26513 break;
26514 }
26515 return res;
26516 };
26517
26518 BN.prototype.gtn = function gtn (num) {
26519 return this.cmpn(num) === 1;
26520 };
26521
26522 BN.prototype.gt = function gt (num) {
26523 return this.cmp(num) === 1;
26524 };
26525
26526 BN.prototype.gten = function gten (num) {
26527 return this.cmpn(num) >= 0;
26528 };
26529
26530 BN.prototype.gte = function gte (num) {
26531 return this.cmp(num) >= 0;
26532 };
26533
26534 BN.prototype.ltn = function ltn (num) {
26535 return this.cmpn(num) === -1;
26536 };
26537
26538 BN.prototype.lt = function lt (num) {
26539 return this.cmp(num) === -1;
26540 };
26541
26542 BN.prototype.lten = function lten (num) {
26543 return this.cmpn(num) <= 0;
26544 };
26545
26546 BN.prototype.lte = function lte (num) {
26547 return this.cmp(num) <= 0;
26548 };
26549
26550 BN.prototype.eqn = function eqn (num) {
26551 return this.cmpn(num) === 0;
26552 };
26553
26554 BN.prototype.eq = function eq (num) {
26555 return this.cmp(num) === 0;
26556 };
26557
26558 //
26559 // A reduce context, could be using montgomery or something better, depending
26560 // on the `m` itself.
26561 //
26562 BN.red = function red (num) {
26563 return new Red(num);
26564 };
26565
26566 BN.prototype.toRed = function toRed (ctx) {
26567 assert(!this.red, 'Already a number in reduction context');
26568 assert(this.negative === 0, 'red works only with positives');
26569 return ctx.convertTo(this)._forceRed(ctx);
26570 };
26571
26572 BN.prototype.fromRed = function fromRed () {
26573 assert(this.red, 'fromRed works only with numbers in reduction context');
26574 return this.red.convertFrom(this);
26575 };
26576
26577 BN.prototype._forceRed = function _forceRed (ctx) {
26578 this.red = ctx;
26579 return this;
26580 };
26581
26582 BN.prototype.forceRed = function forceRed (ctx) {
26583 assert(!this.red, 'Already a number in reduction context');
26584 return this._forceRed(ctx);
26585 };
26586
26587 BN.prototype.redAdd = function redAdd (num) {
26588 assert(this.red, 'redAdd works only with red numbers');
26589 return this.red.add(this, num);
26590 };
26591
26592 BN.prototype.redIAdd = function redIAdd (num) {
26593 assert(this.red, 'redIAdd works only with red numbers');
26594 return this.red.iadd(this, num);
26595 };
26596
26597 BN.prototype.redSub = function redSub (num) {
26598 assert(this.red, 'redSub works only with red numbers');
26599 return this.red.sub(this, num);
26600 };
26601
26602 BN.prototype.redISub = function redISub (num) {
26603 assert(this.red, 'redISub works only with red numbers');
26604 return this.red.isub(this, num);
26605 };
26606
26607 BN.prototype.redShl = function redShl (num) {
26608 assert(this.red, 'redShl works only with red numbers');
26609 return this.red.shl(this, num);
26610 };
26611
26612 BN.prototype.redMul = function redMul (num) {
26613 assert(this.red, 'redMul works only with red numbers');
26614 this.red._verify2(this, num);
26615 return this.red.mul(this, num);
26616 };
26617
26618 BN.prototype.redIMul = function redIMul (num) {
26619 assert(this.red, 'redMul works only with red numbers');
26620 this.red._verify2(this, num);
26621 return this.red.imul(this, num);
26622 };
26623
26624 BN.prototype.redSqr = function redSqr () {
26625 assert(this.red, 'redSqr works only with red numbers');
26626 this.red._verify1(this);
26627 return this.red.sqr(this);
26628 };
26629
26630 BN.prototype.redISqr = function redISqr () {
26631 assert(this.red, 'redISqr works only with red numbers');
26632 this.red._verify1(this);
26633 return this.red.isqr(this);
26634 };
26635
26636 // Square root over p
26637 BN.prototype.redSqrt = function redSqrt () {
26638 assert(this.red, 'redSqrt works only with red numbers');
26639 this.red._verify1(this);
26640 return this.red.sqrt(this);
26641 };
26642
26643 BN.prototype.redInvm = function redInvm () {
26644 assert(this.red, 'redInvm works only with red numbers');
26645 this.red._verify1(this);
26646 return this.red.invm(this);
26647 };
26648
26649 // Return negative clone of `this` % `red modulo`
26650 BN.prototype.redNeg = function redNeg () {
26651 assert(this.red, 'redNeg works only with red numbers');
26652 this.red._verify1(this);
26653 return this.red.neg(this);
26654 };
26655
26656 BN.prototype.redPow = function redPow (num) {
26657 assert(this.red && !num.red, 'redPow(normalNum)');
26658 this.red._verify1(this);
26659 return this.red.pow(this, num);
26660 };
26661
26662 // Prime numbers with efficient reduction
26663 var primes = {
26664 k256: null,
26665 p224: null,
26666 p192: null,
26667 p25519: null
26668 };
26669
26670 // Pseudo-Mersenne prime
26671 function MPrime (name, p) {
26672 // P = 2 ^ N - K
26673 this.name = name;
26674 this.p = new BN(p, 16);
26675 this.n = this.p.bitLength();
26676 this.k = new BN(1).iushln(this.n).isub(this.p);
26677
26678 this.tmp = this._tmp();
26679 }
26680
26681 MPrime.prototype._tmp = function _tmp () {
26682 var tmp = new BN(null);
26683 tmp.words = new Array(Math.ceil(this.n / 13));
26684 return tmp;
26685 };
26686
26687 MPrime.prototype.ireduce = function ireduce (num) {
26688 // Assumes that `num` is less than `P^2`
26689 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
26690 var r = num;
26691 var rlen;
26692
26693 do {
26694 this.split(r, this.tmp);
26695 r = this.imulK(r);
26696 r = r.iadd(this.tmp);
26697 rlen = r.bitLength();
26698 } while (rlen > this.n);
26699
26700 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
26701 if (cmp === 0) {
26702 r.words[0] = 0;
26703 r.length = 1;
26704 } else if (cmp > 0) {
26705 r.isub(this.p);
26706 } else {
26707 if (r.strip !== undefined) {
26708 // r is a BN v4 instance
26709 r.strip();
26710 } else {
26711 // r is a BN v5 instance
26712 r._strip();
26713 }
26714 }
26715
26716 return r;
26717 };
26718
26719 MPrime.prototype.split = function split (input, out) {
26720 input.iushrn(this.n, 0, out);
26721 };
26722
26723 MPrime.prototype.imulK = function imulK (num) {
26724 return num.imul(this.k);
26725 };
26726
26727 function K256 () {
26728 MPrime.call(
26729 this,
26730 'k256',
26731 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
26732 }
26733 inherits(K256, MPrime);
26734
26735 K256.prototype.split = function split (input, output) {
26736 // 256 = 9 * 26 + 22
26737 var mask = 0x3fffff;
26738
26739 var outLen = Math.min(input.length, 9);
26740 for (var i = 0; i < outLen; i++) {
26741 output.words[i] = input.words[i];
26742 }
26743 output.length = outLen;
26744
26745 if (input.length <= 9) {
26746 input.words[0] = 0;
26747 input.length = 1;
26748 return;
26749 }
26750
26751 // Shift by 9 limbs
26752 var prev = input.words[9];
26753 output.words[output.length++] = prev & mask;
26754
26755 for (i = 10; i < input.length; i++) {
26756 var next = input.words[i] | 0;
26757 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
26758 prev = next;
26759 }
26760 prev >>>= 22;
26761 input.words[i - 10] = prev;
26762 if (prev === 0 && input.length > 10) {
26763 input.length -= 10;
26764 } else {
26765 input.length -= 9;
26766 }
26767 };
26768
26769 K256.prototype.imulK = function imulK (num) {
26770 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
26771 num.words[num.length] = 0;
26772 num.words[num.length + 1] = 0;
26773 num.length += 2;
26774
26775 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
26776 var lo = 0;
26777 for (var i = 0; i < num.length; i++) {
26778 var w = num.words[i] | 0;
26779 lo += w * 0x3d1;
26780 num.words[i] = lo & 0x3ffffff;
26781 lo = w * 0x40 + ((lo / 0x4000000) | 0);
26782 }
26783
26784 // Fast length reduction
26785 if (num.words[num.length - 1] === 0) {
26786 num.length--;
26787 if (num.words[num.length - 1] === 0) {
26788 num.length--;
26789 }
26790 }
26791 return num;
26792 };
26793
26794 function P224 () {
26795 MPrime.call(
26796 this,
26797 'p224',
26798 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
26799 }
26800 inherits(P224, MPrime);
26801
26802 function P192 () {
26803 MPrime.call(
26804 this,
26805 'p192',
26806 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
26807 }
26808 inherits(P192, MPrime);
26809
26810 function P25519 () {
26811 // 2 ^ 255 - 19
26812 MPrime.call(
26813 this,
26814 '25519',
26815 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
26816 }
26817 inherits(P25519, MPrime);
26818
26819 P25519.prototype.imulK = function imulK (num) {
26820 // K = 0x13
26821 var carry = 0;
26822 for (var i = 0; i < num.length; i++) {
26823 var hi = (num.words[i] | 0) * 0x13 + carry;
26824 var lo = hi & 0x3ffffff;
26825 hi >>>= 26;
26826
26827 num.words[i] = lo;
26828 carry = hi;
26829 }
26830 if (carry !== 0) {
26831 num.words[num.length++] = carry;
26832 }
26833 return num;
26834 };
26835
26836 // Exported mostly for testing purposes, use plain name instead
26837 BN._prime = function prime (name) {
26838 // Cached version of prime
26839 if (primes[name]) return primes[name];
26840
26841 var prime;
26842 if (name === 'k256') {
26843 prime = new K256();
26844 } else if (name === 'p224') {
26845 prime = new P224();
26846 } else if (name === 'p192') {
26847 prime = new P192();
26848 } else if (name === 'p25519') {
26849 prime = new P25519();
26850 } else {
26851 throw new Error('Unknown prime ' + name);
26852 }
26853 primes[name] = prime;
26854
26855 return prime;
26856 };
26857
26858 //
26859 // Base reduction engine
26860 //
26861 function Red (m) {
26862 if (typeof m === 'string') {
26863 var prime = BN._prime(m);
26864 this.m = prime.p;
26865 this.prime = prime;
26866 } else {
26867 assert(m.gtn(1), 'modulus must be greater than 1');
26868 this.m = m;
26869 this.prime = null;
26870 }
26871 }
26872
26873 Red.prototype._verify1 = function _verify1 (a) {
26874 assert(a.negative === 0, 'red works only with positives');
26875 assert(a.red, 'red works only with red numbers');
26876 };
26877
26878 Red.prototype._verify2 = function _verify2 (a, b) {
26879 assert((a.negative | b.negative) === 0, 'red works only with positives');
26880 assert(a.red && a.red === b.red,
26881 'red works only with red numbers');
26882 };
26883
26884 Red.prototype.imod = function imod (a) {
26885 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
26886
26887 move(a, a.umod(this.m)._forceRed(this));
26888 return a;
26889 };
26890
26891 Red.prototype.neg = function neg (a) {
26892 if (a.isZero()) {
26893 return a.clone();
26894 }
26895
26896 return this.m.sub(a)._forceRed(this);
26897 };
26898
26899 Red.prototype.add = function add (a, b) {
26900 this._verify2(a, b);
26901
26902 var res = a.add(b);
26903 if (res.cmp(this.m) >= 0) {
26904 res.isub(this.m);
26905 }
26906 return res._forceRed(this);
26907 };
26908
26909 Red.prototype.iadd = function iadd (a, b) {
26910 this._verify2(a, b);
26911
26912 var res = a.iadd(b);
26913 if (res.cmp(this.m) >= 0) {
26914 res.isub(this.m);
26915 }
26916 return res;
26917 };
26918
26919 Red.prototype.sub = function sub (a, b) {
26920 this._verify2(a, b);
26921
26922 var res = a.sub(b);
26923 if (res.cmpn(0) < 0) {
26924 res.iadd(this.m);
26925 }
26926 return res._forceRed(this);
26927 };
26928
26929 Red.prototype.isub = function isub (a, b) {
26930 this._verify2(a, b);
26931
26932 var res = a.isub(b);
26933 if (res.cmpn(0) < 0) {
26934 res.iadd(this.m);
26935 }
26936 return res;
26937 };
26938
26939 Red.prototype.shl = function shl (a, num) {
26940 this._verify1(a);
26941 return this.imod(a.ushln(num));
26942 };
26943
26944 Red.prototype.imul = function imul (a, b) {
26945 this._verify2(a, b);
26946 return this.imod(a.imul(b));
26947 };
26948
26949 Red.prototype.mul = function mul (a, b) {
26950 this._verify2(a, b);
26951 return this.imod(a.mul(b));
26952 };
26953
26954 Red.prototype.isqr = function isqr (a) {
26955 return this.imul(a, a.clone());
26956 };
26957
26958 Red.prototype.sqr = function sqr (a) {
26959 return this.mul(a, a);
26960 };
26961
26962 Red.prototype.sqrt = function sqrt (a) {
26963 if (a.isZero()) return a.clone();
26964
26965 var mod3 = this.m.andln(3);
26966 assert(mod3 % 2 === 1);
26967
26968 // Fast case
26969 if (mod3 === 3) {
26970 var pow = this.m.add(new BN(1)).iushrn(2);
26971 return this.pow(a, pow);
26972 }
26973
26974 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
26975 //
26976 // Find Q and S, that Q * 2 ^ S = (P - 1)
26977 var q = this.m.subn(1);
26978 var s = 0;
26979 while (!q.isZero() && q.andln(1) === 0) {
26980 s++;
26981 q.iushrn(1);
26982 }
26983 assert(!q.isZero());
26984
26985 var one = new BN(1).toRed(this);
26986 var nOne = one.redNeg();
26987
26988 // Find quadratic non-residue
26989 // NOTE: Max is such because of generalized Riemann hypothesis.
26990 var lpow = this.m.subn(1).iushrn(1);
26991 var z = this.m.bitLength();
26992 z = new BN(2 * z * z).toRed(this);
26993
26994 while (this.pow(z, lpow).cmp(nOne) !== 0) {
26995 z.redIAdd(nOne);
26996 }
26997
26998 var c = this.pow(z, q);
26999 var r = this.pow(a, q.addn(1).iushrn(1));
27000 var t = this.pow(a, q);
27001 var m = s;
27002 while (t.cmp(one) !== 0) {
27003 var tmp = t;
27004 for (var i = 0; tmp.cmp(one) !== 0; i++) {
27005 tmp = tmp.redSqr();
27006 }
27007 assert(i < m);
27008 var b = this.pow(c, new BN(1).iushln(m - i - 1));
27009
27010 r = r.redMul(b);
27011 c = b.redSqr();
27012 t = t.redMul(c);
27013 m = i;
27014 }
27015
27016 return r;
27017 };
27018
27019 Red.prototype.invm = function invm (a) {
27020 var inv = a._invmp(this.m);
27021 if (inv.negative !== 0) {
27022 inv.negative = 0;
27023 return this.imod(inv).redNeg();
27024 } else {
27025 return this.imod(inv);
27026 }
27027 };
27028
27029 Red.prototype.pow = function pow (a, num) {
27030 if (num.isZero()) return new BN(1).toRed(this);
27031 if (num.cmpn(1) === 0) return a.clone();
27032
27033 var windowSize = 4;
27034 var wnd = new Array(1 << windowSize);
27035 wnd[0] = new BN(1).toRed(this);
27036 wnd[1] = a;
27037 for (var i = 2; i < wnd.length; i++) {
27038 wnd[i] = this.mul(wnd[i - 1], a);
27039 }
27040
27041 var res = wnd[0];
27042 var current = 0;
27043 var currentLen = 0;
27044 var start = num.bitLength() % 26;
27045 if (start === 0) {
27046 start = 26;
27047 }
27048
27049 for (i = num.length - 1; i >= 0; i--) {
27050 var word = num.words[i];
27051 for (var j = start - 1; j >= 0; j--) {
27052 var bit = (word >> j) & 1;
27053 if (res !== wnd[0]) {
27054 res = this.sqr(res);
27055 }
27056
27057 if (bit === 0 && current === 0) {
27058 currentLen = 0;
27059 continue;
27060 }
27061
27062 current <<= 1;
27063 current |= bit;
27064 currentLen++;
27065 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
27066
27067 res = this.mul(res, wnd[current]);
27068 currentLen = 0;
27069 current = 0;
27070 }
27071 start = 26;
27072 }
27073
27074 return res;
27075 };
27076
27077 Red.prototype.convertTo = function convertTo (num) {
27078 var r = num.umod(this.m);
27079
27080 return r === num ? r.clone() : r;
27081 };
27082
27083 Red.prototype.convertFrom = function convertFrom (num) {
27084 var res = num.clone();
27085 res.red = null;
27086 return res;
27087 };
27088
27089 //
27090 // Montgomery method engine
27091 //
27092
27093 BN.mont = function mont (num) {
27094 return new Mont(num);
27095 };
27096
27097 function Mont (m) {
27098 Red.call(this, m);
27099
27100 this.shift = this.m.bitLength();
27101 if (this.shift % 26 !== 0) {
27102 this.shift += 26 - (this.shift % 26);
27103 }
27104
27105 this.r = new BN(1).iushln(this.shift);
27106 this.r2 = this.imod(this.r.sqr());
27107 this.rinv = this.r._invmp(this.m);
27108
27109 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
27110 this.minv = this.minv.umod(this.r);
27111 this.minv = this.r.sub(this.minv);
27112 }
27113 inherits(Mont, Red);
27114
27115 Mont.prototype.convertTo = function convertTo (num) {
27116 return this.imod(num.ushln(this.shift));
27117 };
27118
27119 Mont.prototype.convertFrom = function convertFrom (num) {
27120 var r = this.imod(num.mul(this.rinv));
27121 r.red = null;
27122 return r;
27123 };
27124
27125 Mont.prototype.imul = function imul (a, b) {
27126 if (a.isZero() || b.isZero()) {
27127 a.words[0] = 0;
27128 a.length = 1;
27129 return a;
27130 }
27131
27132 var t = a.imul(b);
27133 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
27134 var u = t.isub(c).iushrn(this.shift);
27135 var res = u;
27136
27137 if (u.cmp(this.m) >= 0) {
27138 res = u.isub(this.m);
27139 } else if (u.cmpn(0) < 0) {
27140 res = u.iadd(this.m);
27141 }
27142
27143 return res._forceRed(this);
27144 };
27145
27146 Mont.prototype.mul = function mul (a, b) {
27147 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
27148
27149 var t = a.mul(b);
27150 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
27151 var u = t.isub(c).iushrn(this.shift);
27152 var res = u;
27153 if (u.cmp(this.m) >= 0) {
27154 res = u.isub(this.m);
27155 } else if (u.cmpn(0) < 0) {
27156 res = u.iadd(this.m);
27157 }
27158
27159 return res._forceRed(this);
27160 };
27161
27162 Mont.prototype.invm = function invm (a) {
27163 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
27164 var res = this.imod(a._invmp(this.m).mul(this.r2));
27165 return res._forceRed(this);
27166 };
27167})(typeof module === 'undefined' || module, this);
27168
27169},{"buffer":82}],105:[function(require,module,exports){
27170module.exports = require('./browser/algorithms.json')
27171
27172},{"./browser/algorithms.json":106}],106:[function(require,module,exports){
27173module.exports={
27174 "sha224WithRSAEncryption": {
27175 "sign": "rsa",
27176 "hash": "sha224",
27177 "id": "302d300d06096086480165030402040500041c"
27178 },
27179 "RSA-SHA224": {
27180 "sign": "ecdsa/rsa",
27181 "hash": "sha224",
27182 "id": "302d300d06096086480165030402040500041c"
27183 },
27184 "sha256WithRSAEncryption": {
27185 "sign": "rsa",
27186 "hash": "sha256",
27187 "id": "3031300d060960864801650304020105000420"
27188 },
27189 "RSA-SHA256": {
27190 "sign": "ecdsa/rsa",
27191 "hash": "sha256",
27192 "id": "3031300d060960864801650304020105000420"
27193 },
27194 "sha384WithRSAEncryption": {
27195 "sign": "rsa",
27196 "hash": "sha384",
27197 "id": "3041300d060960864801650304020205000430"
27198 },
27199 "RSA-SHA384": {
27200 "sign": "ecdsa/rsa",
27201 "hash": "sha384",
27202 "id": "3041300d060960864801650304020205000430"
27203 },
27204 "sha512WithRSAEncryption": {
27205 "sign": "rsa",
27206 "hash": "sha512",
27207 "id": "3051300d060960864801650304020305000440"
27208 },
27209 "RSA-SHA512": {
27210 "sign": "ecdsa/rsa",
27211 "hash": "sha512",
27212 "id": "3051300d060960864801650304020305000440"
27213 },
27214 "RSA-SHA1": {
27215 "sign": "rsa",
27216 "hash": "sha1",
27217 "id": "3021300906052b0e03021a05000414"
27218 },
27219 "ecdsa-with-SHA1": {
27220 "sign": "ecdsa",
27221 "hash": "sha1",
27222 "id": ""
27223 },
27224 "sha256": {
27225 "sign": "ecdsa",
27226 "hash": "sha256",
27227 "id": ""
27228 },
27229 "sha224": {
27230 "sign": "ecdsa",
27231 "hash": "sha224",
27232 "id": ""
27233 },
27234 "sha384": {
27235 "sign": "ecdsa",
27236 "hash": "sha384",
27237 "id": ""
27238 },
27239 "sha512": {
27240 "sign": "ecdsa",
27241 "hash": "sha512",
27242 "id": ""
27243 },
27244 "DSA-SHA": {
27245 "sign": "dsa",
27246 "hash": "sha1",
27247 "id": ""
27248 },
27249 "DSA-SHA1": {
27250 "sign": "dsa",
27251 "hash": "sha1",
27252 "id": ""
27253 },
27254 "DSA": {
27255 "sign": "dsa",
27256 "hash": "sha1",
27257 "id": ""
27258 },
27259 "DSA-WITH-SHA224": {
27260 "sign": "dsa",
27261 "hash": "sha224",
27262 "id": ""
27263 },
27264 "DSA-SHA224": {
27265 "sign": "dsa",
27266 "hash": "sha224",
27267 "id": ""
27268 },
27269 "DSA-WITH-SHA256": {
27270 "sign": "dsa",
27271 "hash": "sha256",
27272 "id": ""
27273 },
27274 "DSA-SHA256": {
27275 "sign": "dsa",
27276 "hash": "sha256",
27277 "id": ""
27278 },
27279 "DSA-WITH-SHA384": {
27280 "sign": "dsa",
27281 "hash": "sha384",
27282 "id": ""
27283 },
27284 "DSA-SHA384": {
27285 "sign": "dsa",
27286 "hash": "sha384",
27287 "id": ""
27288 },
27289 "DSA-WITH-SHA512": {
27290 "sign": "dsa",
27291 "hash": "sha512",
27292 "id": ""
27293 },
27294 "DSA-SHA512": {
27295 "sign": "dsa",
27296 "hash": "sha512",
27297 "id": ""
27298 },
27299 "DSA-RIPEMD160": {
27300 "sign": "dsa",
27301 "hash": "rmd160",
27302 "id": ""
27303 },
27304 "ripemd160WithRSA": {
27305 "sign": "rsa",
27306 "hash": "rmd160",
27307 "id": "3021300906052b2403020105000414"
27308 },
27309 "RSA-RIPEMD160": {
27310 "sign": "rsa",
27311 "hash": "rmd160",
27312 "id": "3021300906052b2403020105000414"
27313 },
27314 "md5WithRSAEncryption": {
27315 "sign": "rsa",
27316 "hash": "md5",
27317 "id": "3020300c06082a864886f70d020505000410"
27318 },
27319 "RSA-MD5": {
27320 "sign": "rsa",
27321 "hash": "md5",
27322 "id": "3020300c06082a864886f70d020505000410"
27323 }
27324}
27325
27326},{}],107:[function(require,module,exports){
27327module.exports={
27328 "1.3.132.0.10": "secp256k1",
27329 "1.3.132.0.33": "p224",
27330 "1.2.840.10045.3.1.1": "p192",
27331 "1.2.840.10045.3.1.7": "p256",
27332 "1.3.132.0.34": "p384",
27333 "1.3.132.0.35": "p521"
27334}
27335
27336},{}],108:[function(require,module,exports){
27337var Buffer = require('safe-buffer').Buffer
27338var createHash = require('create-hash')
27339var stream = require('readable-stream')
27340var inherits = require('inherits')
27341var sign = require('./sign')
27342var verify = require('./verify')
27343
27344var algorithms = require('./algorithms.json')
27345Object.keys(algorithms).forEach(function (key) {
27346 algorithms[key].id = Buffer.from(algorithms[key].id, 'hex')
27347 algorithms[key.toLowerCase()] = algorithms[key]
27348})
27349
27350function Sign (algorithm) {
27351 stream.Writable.call(this)
27352
27353 var data = algorithms[algorithm]
27354 if (!data) throw new Error('Unknown message digest')
27355
27356 this._hashType = data.hash
27357 this._hash = createHash(data.hash)
27358 this._tag = data.id
27359 this._signType = data.sign
27360}
27361inherits(Sign, stream.Writable)
27362
27363Sign.prototype._write = function _write (data, _, done) {
27364 this._hash.update(data)
27365 done()
27366}
27367
27368Sign.prototype.update = function update (data, enc) {
27369 if (typeof data === 'string') data = Buffer.from(data, enc)
27370
27371 this._hash.update(data)
27372 return this
27373}
27374
27375Sign.prototype.sign = function signMethod (key, enc) {
27376 this.end()
27377 var hash = this._hash.digest()
27378 var sig = sign(hash, key, this._hashType, this._signType, this._tag)
27379
27380 return enc ? sig.toString(enc) : sig
27381}
27382
27383function Verify (algorithm) {
27384 stream.Writable.call(this)
27385
27386 var data = algorithms[algorithm]
27387 if (!data) throw new Error('Unknown message digest')
27388
27389 this._hash = createHash(data.hash)
27390 this._tag = data.id
27391 this._signType = data.sign
27392}
27393inherits(Verify, stream.Writable)
27394
27395Verify.prototype._write = function _write (data, _, done) {
27396 this._hash.update(data)
27397 done()
27398}
27399
27400Verify.prototype.update = function update (data, enc) {
27401 if (typeof data === 'string') data = Buffer.from(data, enc)
27402
27403 this._hash.update(data)
27404 return this
27405}
27406
27407Verify.prototype.verify = function verifyMethod (key, sig, enc) {
27408 if (typeof sig === 'string') sig = Buffer.from(sig, enc)
27409
27410 this.end()
27411 var hash = this._hash.digest()
27412 return verify(sig, hash, key, this._signType, this._tag)
27413}
27414
27415function createSign (algorithm) {
27416 return new Sign(algorithm)
27417}
27418
27419function createVerify (algorithm) {
27420 return new Verify(algorithm)
27421}
27422
27423module.exports = {
27424 Sign: createSign,
27425 Verify: createVerify,
27426 createSign: createSign,
27427 createVerify: createVerify
27428}
27429
27430},{"./algorithms.json":106,"./sign":109,"./verify":110,"create-hash":136,"inherits":112,"readable-stream":127,"safe-buffer":256}],109:[function(require,module,exports){
27431// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
27432var Buffer = require('safe-buffer').Buffer
27433var createHmac = require('create-hmac')
27434var crt = require('browserify-rsa')
27435var EC = require('elliptic').ec
27436var BN = require('bn.js')
27437var parseKeys = require('parse-asn1')
27438var curves = require('./curves.json')
27439
27440function sign (hash, key, hashType, signType, tag) {
27441 var priv = parseKeys(key)
27442 if (priv.curve) {
27443 // rsa keys can be interpreted as ecdsa ones in openssl
27444 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
27445 return ecSign(hash, priv)
27446 } else if (priv.type === 'dsa') {
27447 if (signType !== 'dsa') throw new Error('wrong private key type')
27448 return dsaSign(hash, priv, hashType)
27449 } else {
27450 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
27451 }
27452 hash = Buffer.concat([tag, hash])
27453 var len = priv.modulus.byteLength()
27454 var pad = [0, 1]
27455 while (hash.length + pad.length + 1 < len) pad.push(0xff)
27456 pad.push(0x00)
27457 var i = -1
27458 while (++i < hash.length) pad.push(hash[i])
27459
27460 var out = crt(pad, priv)
27461 return out
27462}
27463
27464function ecSign (hash, priv) {
27465 var curveId = curves[priv.curve.join('.')]
27466 if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
27467
27468 var curve = new EC(curveId)
27469 var key = curve.keyFromPrivate(priv.privateKey)
27470 var out = key.sign(hash)
27471
27472 return Buffer.from(out.toDER())
27473}
27474
27475function dsaSign (hash, priv, algo) {
27476 var x = priv.params.priv_key
27477 var p = priv.params.p
27478 var q = priv.params.q
27479 var g = priv.params.g
27480 var r = new BN(0)
27481 var k
27482 var H = bits2int(hash, q).mod(q)
27483 var s = false
27484 var kv = getKey(x, q, hash, algo)
27485 while (s === false) {
27486 k = makeKey(q, kv, algo)
27487 r = makeR(g, k, p, q)
27488 s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
27489 if (s.cmpn(0) === 0) {
27490 s = false
27491 r = new BN(0)
27492 }
27493 }
27494 return toDER(r, s)
27495}
27496
27497function toDER (r, s) {
27498 r = r.toArray()
27499 s = s.toArray()
27500
27501 // Pad values
27502 if (r[0] & 0x80) r = [0].concat(r)
27503 if (s[0] & 0x80) s = [0].concat(s)
27504
27505 var total = r.length + s.length + 4
27506 var res = [0x30, total, 0x02, r.length]
27507 res = res.concat(r, [0x02, s.length], s)
27508 return Buffer.from(res)
27509}
27510
27511function getKey (x, q, hash, algo) {
27512 x = Buffer.from(x.toArray())
27513 if (x.length < q.byteLength()) {
27514 var zeros = Buffer.alloc(q.byteLength() - x.length)
27515 x = Buffer.concat([zeros, x])
27516 }
27517 var hlen = hash.length
27518 var hbits = bits2octets(hash, q)
27519 var v = Buffer.alloc(hlen)
27520 v.fill(1)
27521 var k = Buffer.alloc(hlen)
27522 k = createHmac(algo, k).update(v).update(Buffer.from([0])).update(x).update(hbits).digest()
27523 v = createHmac(algo, k).update(v).digest()
27524 k = createHmac(algo, k).update(v).update(Buffer.from([1])).update(x).update(hbits).digest()
27525 v = createHmac(algo, k).update(v).digest()
27526 return { k: k, v: v }
27527}
27528
27529function bits2int (obits, q) {
27530 var bits = new BN(obits)
27531 var shift = (obits.length << 3) - q.bitLength()
27532 if (shift > 0) bits.ishrn(shift)
27533 return bits
27534}
27535
27536function bits2octets (bits, q) {
27537 bits = bits2int(bits, q)
27538 bits = bits.mod(q)
27539 var out = Buffer.from(bits.toArray())
27540 if (out.length < q.byteLength()) {
27541 var zeros = Buffer.alloc(q.byteLength() - out.length)
27542 out = Buffer.concat([zeros, out])
27543 }
27544 return out
27545}
27546
27547function makeKey (q, kv, algo) {
27548 var t
27549 var k
27550
27551 do {
27552 t = Buffer.alloc(0)
27553
27554 while (t.length * 8 < q.bitLength()) {
27555 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
27556 t = Buffer.concat([t, kv.v])
27557 }
27558
27559 k = bits2int(t, q)
27560 kv.k = createHmac(algo, kv.k).update(kv.v).update(Buffer.from([0])).digest()
27561 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
27562 } while (k.cmp(q) !== -1)
27563
27564 return k
27565}
27566
27567function makeR (g, k, p, q) {
27568 return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
27569}
27570
27571module.exports = sign
27572module.exports.getKey = getKey
27573module.exports.makeKey = makeKey
27574
27575},{"./curves.json":107,"bn.js":111,"browserify-rsa":103,"create-hmac":138,"elliptic":156,"parse-asn1":220,"safe-buffer":256}],110:[function(require,module,exports){
27576// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
27577var Buffer = require('safe-buffer').Buffer
27578var BN = require('bn.js')
27579var EC = require('elliptic').ec
27580var parseKeys = require('parse-asn1')
27581var curves = require('./curves.json')
27582
27583function verify (sig, hash, key, signType, tag) {
27584 var pub = parseKeys(key)
27585 if (pub.type === 'ec') {
27586 // rsa keys can be interpreted as ecdsa ones in openssl
27587 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
27588 return ecVerify(sig, hash, pub)
27589 } else if (pub.type === 'dsa') {
27590 if (signType !== 'dsa') throw new Error('wrong public key type')
27591 return dsaVerify(sig, hash, pub)
27592 } else {
27593 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
27594 }
27595 hash = Buffer.concat([tag, hash])
27596 var len = pub.modulus.byteLength()
27597 var pad = [1]
27598 var padNum = 0
27599 while (hash.length + pad.length + 2 < len) {
27600 pad.push(0xff)
27601 padNum++
27602 }
27603 pad.push(0x00)
27604 var i = -1
27605 while (++i < hash.length) {
27606 pad.push(hash[i])
27607 }
27608 pad = Buffer.from(pad)
27609 var red = BN.mont(pub.modulus)
27610 sig = new BN(sig).toRed(red)
27611
27612 sig = sig.redPow(new BN(pub.publicExponent))
27613 sig = Buffer.from(sig.fromRed().toArray())
27614 var out = padNum < 8 ? 1 : 0
27615 len = Math.min(sig.length, pad.length)
27616 if (sig.length !== pad.length) out = 1
27617
27618 i = -1
27619 while (++i < len) out |= sig[i] ^ pad[i]
27620 return out === 0
27621}
27622
27623function ecVerify (sig, hash, pub) {
27624 var curveId = curves[pub.data.algorithm.curve.join('.')]
27625 if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
27626
27627 var curve = new EC(curveId)
27628 var pubkey = pub.data.subjectPrivateKey.data
27629
27630 return curve.verify(hash, sig, pubkey)
27631}
27632
27633function dsaVerify (sig, hash, pub) {
27634 var p = pub.data.p
27635 var q = pub.data.q
27636 var g = pub.data.g
27637 var y = pub.data.pub_key
27638 var unpacked = parseKeys.signature.decode(sig, 'der')
27639 var s = unpacked.s
27640 var r = unpacked.r
27641 checkValue(s, q)
27642 checkValue(r, q)
27643 var montp = BN.mont(p)
27644 var w = s.invm(q)
27645 var v = g.toRed(montp)
27646 .redPow(new BN(hash).mul(w).mod(q))
27647 .fromRed()
27648 .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
27649 .mod(p)
27650 .mod(q)
27651 return v.cmp(r) === 0
27652}
27653
27654function checkValue (b, q) {
27655 if (b.cmpn(0) <= 0) throw new Error('invalid sig')
27656 if (b.cmp(q) >= q) throw new Error('invalid sig')
27657}
27658
27659module.exports = verify
27660
27661},{"./curves.json":107,"bn.js":111,"elliptic":156,"parse-asn1":220,"safe-buffer":256}],111:[function(require,module,exports){
27662arguments[4][104][0].apply(exports,arguments)
27663},{"buffer":82,"dup":104}],112:[function(require,module,exports){
27664if (typeof Object.create === 'function') {
27665 // implementation from standard node.js 'util' module
27666 module.exports = function inherits(ctor, superCtor) {
27667 if (superCtor) {
27668 ctor.super_ = superCtor
27669 ctor.prototype = Object.create(superCtor.prototype, {
27670 constructor: {
27671 value: ctor,
27672 enumerable: false,
27673 writable: true,
27674 configurable: true
27675 }
27676 })
27677 }
27678 };
27679} else {
27680 // old school shim for old browsers
27681 module.exports = function inherits(ctor, superCtor) {
27682 if (superCtor) {
27683 ctor.super_ = superCtor
27684 var TempCtor = function () {}
27685 TempCtor.prototype = superCtor.prototype
27686 ctor.prototype = new TempCtor()
27687 ctor.prototype.constructor = ctor
27688 }
27689 }
27690}
27691
27692},{}],113:[function(require,module,exports){
27693'use strict';
27694
27695function _inheritsLoose(subClass, superClass) { subClass.prototype = Object.create(superClass.prototype); subClass.prototype.constructor = subClass; subClass.__proto__ = superClass; }
27696
27697var codes = {};
27698
27699function createErrorType(code, message, Base) {
27700 if (!Base) {
27701 Base = Error;
27702 }
27703
27704 function getMessage(arg1, arg2, arg3) {
27705 if (typeof message === 'string') {
27706 return message;
27707 } else {
27708 return message(arg1, arg2, arg3);
27709 }
27710 }
27711
27712 var NodeError =
27713 /*#__PURE__*/
27714 function (_Base) {
27715 _inheritsLoose(NodeError, _Base);
27716
27717 function NodeError(arg1, arg2, arg3) {
27718 return _Base.call(this, getMessage(arg1, arg2, arg3)) || this;
27719 }
27720
27721 return NodeError;
27722 }(Base);
27723
27724 NodeError.prototype.name = Base.name;
27725 NodeError.prototype.code = code;
27726 codes[code] = NodeError;
27727} // https://github.com/nodejs/node/blob/v10.8.0/lib/internal/errors.js
27728
27729
27730function oneOf(expected, thing) {
27731 if (Array.isArray(expected)) {
27732 var len = expected.length;
27733 expected = expected.map(function (i) {
27734 return String(i);
27735 });
27736
27737 if (len > 2) {
27738 return "one of ".concat(thing, " ").concat(expected.slice(0, len - 1).join(', '), ", or ") + expected[len - 1];
27739 } else if (len === 2) {
27740 return "one of ".concat(thing, " ").concat(expected[0], " or ").concat(expected[1]);
27741 } else {
27742 return "of ".concat(thing, " ").concat(expected[0]);
27743 }
27744 } else {
27745 return "of ".concat(thing, " ").concat(String(expected));
27746 }
27747} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/startsWith
27748
27749
27750function startsWith(str, search, pos) {
27751 return str.substr(!pos || pos < 0 ? 0 : +pos, search.length) === search;
27752} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/endsWith
27753
27754
27755function endsWith(str, search, this_len) {
27756 if (this_len === undefined || this_len > str.length) {
27757 this_len = str.length;
27758 }
27759
27760 return str.substring(this_len - search.length, this_len) === search;
27761} // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/includes
27762
27763
27764function includes(str, search, start) {
27765 if (typeof start !== 'number') {
27766 start = 0;
27767 }
27768
27769 if (start + search.length > str.length) {
27770 return false;
27771 } else {
27772 return str.indexOf(search, start) !== -1;
27773 }
27774}
27775
27776createErrorType('ERR_INVALID_OPT_VALUE', function (name, value) {
27777 return 'The value "' + value + '" is invalid for option "' + name + '"';
27778}, TypeError);
27779createErrorType('ERR_INVALID_ARG_TYPE', function (name, expected, actual) {
27780 // determiner: 'must be' or 'must not be'
27781 var determiner;
27782
27783 if (typeof expected === 'string' && startsWith(expected, 'not ')) {
27784 determiner = 'must not be';
27785 expected = expected.replace(/^not /, '');
27786 } else {
27787 determiner = 'must be';
27788 }
27789
27790 var msg;
27791
27792 if (endsWith(name, ' argument')) {
27793 // For cases like 'first argument'
27794 msg = "The ".concat(name, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
27795 } else {
27796 var type = includes(name, '.') ? 'property' : 'argument';
27797 msg = "The \"".concat(name, "\" ").concat(type, " ").concat(determiner, " ").concat(oneOf(expected, 'type'));
27798 }
27799
27800 msg += ". Received type ".concat(typeof actual);
27801 return msg;
27802}, TypeError);
27803createErrorType('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF');
27804createErrorType('ERR_METHOD_NOT_IMPLEMENTED', function (name) {
27805 return 'The ' + name + ' method is not implemented';
27806});
27807createErrorType('ERR_STREAM_PREMATURE_CLOSE', 'Premature close');
27808createErrorType('ERR_STREAM_DESTROYED', function (name) {
27809 return 'Cannot call ' + name + ' after a stream was destroyed';
27810});
27811createErrorType('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times');
27812createErrorType('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable');
27813createErrorType('ERR_STREAM_WRITE_AFTER_END', 'write after end');
27814createErrorType('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError);
27815createErrorType('ERR_UNKNOWN_ENCODING', function (arg) {
27816 return 'Unknown encoding: ' + arg;
27817}, TypeError);
27818createErrorType('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event');
27819module.exports.codes = codes;
27820
27821},{}],114:[function(require,module,exports){
27822(function (process){(function (){
27823// Copyright Joyent, Inc. and other Node contributors.
27824//
27825// Permission is hereby granted, free of charge, to any person obtaining a
27826// copy of this software and associated documentation files (the
27827// "Software"), to deal in the Software without restriction, including
27828// without limitation the rights to use, copy, modify, merge, publish,
27829// distribute, sublicense, and/or sell copies of the Software, and to permit
27830// persons to whom the Software is furnished to do so, subject to the
27831// following conditions:
27832//
27833// The above copyright notice and this permission notice shall be included
27834// in all copies or substantial portions of the Software.
27835//
27836// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
27837// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27838// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
27839// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
27840// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
27841// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
27842// USE OR OTHER DEALINGS IN THE SOFTWARE.
27843// a duplex stream is just a stream that is both readable and writable.
27844// Since JS doesn't have multiple prototypal inheritance, this class
27845// prototypally inherits from Readable, and then parasitically from
27846// Writable.
27847'use strict';
27848/*<replacement>*/
27849
27850var objectKeys = Object.keys || function (obj) {
27851 var keys = [];
27852
27853 for (var key in obj) {
27854 keys.push(key);
27855 }
27856
27857 return keys;
27858};
27859/*</replacement>*/
27860
27861
27862module.exports = Duplex;
27863
27864var Readable = require('./_stream_readable');
27865
27866var Writable = require('./_stream_writable');
27867
27868require('inherits')(Duplex, Readable);
27869
27870{
27871 // Allow the keys array to be GC'ed.
27872 var keys = objectKeys(Writable.prototype);
27873
27874 for (var v = 0; v < keys.length; v++) {
27875 var method = keys[v];
27876 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
27877 }
27878}
27879
27880function Duplex(options) {
27881 if (!(this instanceof Duplex)) return new Duplex(options);
27882 Readable.call(this, options);
27883 Writable.call(this, options);
27884 this.allowHalfOpen = true;
27885
27886 if (options) {
27887 if (options.readable === false) this.readable = false;
27888 if (options.writable === false) this.writable = false;
27889
27890 if (options.allowHalfOpen === false) {
27891 this.allowHalfOpen = false;
27892 this.once('end', onend);
27893 }
27894 }
27895}
27896
27897Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
27898 // making it explicit this property is not enumerable
27899 // because otherwise some prototype manipulation in
27900 // userland will fail
27901 enumerable: false,
27902 get: function get() {
27903 return this._writableState.highWaterMark;
27904 }
27905});
27906Object.defineProperty(Duplex.prototype, 'writableBuffer', {
27907 // making it explicit this property is not enumerable
27908 // because otherwise some prototype manipulation in
27909 // userland will fail
27910 enumerable: false,
27911 get: function get() {
27912 return this._writableState && this._writableState.getBuffer();
27913 }
27914});
27915Object.defineProperty(Duplex.prototype, 'writableLength', {
27916 // making it explicit this property is not enumerable
27917 // because otherwise some prototype manipulation in
27918 // userland will fail
27919 enumerable: false,
27920 get: function get() {
27921 return this._writableState.length;
27922 }
27923}); // the no-half-open enforcer
27924
27925function onend() {
27926 // If the writable side ended, then we're ok.
27927 if (this._writableState.ended) return; // no more data can be written.
27928 // But allow more writes to happen in this tick.
27929
27930 process.nextTick(onEndNT, this);
27931}
27932
27933function onEndNT(self) {
27934 self.end();
27935}
27936
27937Object.defineProperty(Duplex.prototype, 'destroyed', {
27938 // making it explicit this property is not enumerable
27939 // because otherwise some prototype manipulation in
27940 // userland will fail
27941 enumerable: false,
27942 get: function get() {
27943 if (this._readableState === undefined || this._writableState === undefined) {
27944 return false;
27945 }
27946
27947 return this._readableState.destroyed && this._writableState.destroyed;
27948 },
27949 set: function set(value) {
27950 // we ignore the value if the stream
27951 // has not been initialized yet
27952 if (this._readableState === undefined || this._writableState === undefined) {
27953 return;
27954 } // backward compatibility, the user is explicitly
27955 // managing destroyed
27956
27957
27958 this._readableState.destroyed = value;
27959 this._writableState.destroyed = value;
27960 }
27961});
27962}).call(this)}).call(this,require('_process'))
27963},{"./_stream_readable":116,"./_stream_writable":118,"_process":228,"inherits":112}],115:[function(require,module,exports){
27964// Copyright Joyent, Inc. and other Node contributors.
27965//
27966// Permission is hereby granted, free of charge, to any person obtaining a
27967// copy of this software and associated documentation files (the
27968// "Software"), to deal in the Software without restriction, including
27969// without limitation the rights to use, copy, modify, merge, publish,
27970// distribute, sublicense, and/or sell copies of the Software, and to permit
27971// persons to whom the Software is furnished to do so, subject to the
27972// following conditions:
27973//
27974// The above copyright notice and this permission notice shall be included
27975// in all copies or substantial portions of the Software.
27976//
27977// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
27978// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
27979// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
27980// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
27981// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
27982// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
27983// USE OR OTHER DEALINGS IN THE SOFTWARE.
27984// a passthrough stream.
27985// basically just the most minimal sort of Transform stream.
27986// Every written chunk gets output as-is.
27987'use strict';
27988
27989module.exports = PassThrough;
27990
27991var Transform = require('./_stream_transform');
27992
27993require('inherits')(PassThrough, Transform);
27994
27995function PassThrough(options) {
27996 if (!(this instanceof PassThrough)) return new PassThrough(options);
27997 Transform.call(this, options);
27998}
27999
28000PassThrough.prototype._transform = function (chunk, encoding, cb) {
28001 cb(null, chunk);
28002};
28003},{"./_stream_transform":117,"inherits":112}],116:[function(require,module,exports){
28004(function (process,global){(function (){
28005// Copyright Joyent, Inc. and other Node contributors.
28006//
28007// Permission is hereby granted, free of charge, to any person obtaining a
28008// copy of this software and associated documentation files (the
28009// "Software"), to deal in the Software without restriction, including
28010// without limitation the rights to use, copy, modify, merge, publish,
28011// distribute, sublicense, and/or sell copies of the Software, and to permit
28012// persons to whom the Software is furnished to do so, subject to the
28013// following conditions:
28014//
28015// The above copyright notice and this permission notice shall be included
28016// in all copies or substantial portions of the Software.
28017//
28018// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
28019// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
28020// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
28021// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
28022// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
28023// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
28024// USE OR OTHER DEALINGS IN THE SOFTWARE.
28025'use strict';
28026
28027module.exports = Readable;
28028/*<replacement>*/
28029
28030var Duplex;
28031/*</replacement>*/
28032
28033Readable.ReadableState = ReadableState;
28034/*<replacement>*/
28035
28036var EE = require('events').EventEmitter;
28037
28038var EElistenerCount = function EElistenerCount(emitter, type) {
28039 return emitter.listeners(type).length;
28040};
28041/*</replacement>*/
28042
28043/*<replacement>*/
28044
28045
28046var Stream = require('./internal/streams/stream');
28047/*</replacement>*/
28048
28049
28050var Buffer = require('buffer').Buffer;
28051
28052var OurUint8Array = global.Uint8Array || function () {};
28053
28054function _uint8ArrayToBuffer(chunk) {
28055 return Buffer.from(chunk);
28056}
28057
28058function _isUint8Array(obj) {
28059 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
28060}
28061/*<replacement>*/
28062
28063
28064var debugUtil = require('util');
28065
28066var debug;
28067
28068if (debugUtil && debugUtil.debuglog) {
28069 debug = debugUtil.debuglog('stream');
28070} else {
28071 debug = function debug() {};
28072}
28073/*</replacement>*/
28074
28075
28076var BufferList = require('./internal/streams/buffer_list');
28077
28078var destroyImpl = require('./internal/streams/destroy');
28079
28080var _require = require('./internal/streams/state'),
28081 getHighWaterMark = _require.getHighWaterMark;
28082
28083var _require$codes = require('../errors').codes,
28084 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
28085 ERR_STREAM_PUSH_AFTER_EOF = _require$codes.ERR_STREAM_PUSH_AFTER_EOF,
28086 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
28087 ERR_STREAM_UNSHIFT_AFTER_END_EVENT = _require$codes.ERR_STREAM_UNSHIFT_AFTER_END_EVENT; // Lazy loaded to improve the startup performance.
28088
28089
28090var StringDecoder;
28091var createReadableStreamAsyncIterator;
28092var from;
28093
28094require('inherits')(Readable, Stream);
28095
28096var errorOrDestroy = destroyImpl.errorOrDestroy;
28097var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
28098
28099function prependListener(emitter, event, fn) {
28100 // Sadly this is not cacheable as some libraries bundle their own
28101 // event emitter implementation with them.
28102 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn); // This is a hack to make sure that our error handler is attached before any
28103 // userland ones. NEVER DO THIS. This is here only because this code needs
28104 // to continue to work with older versions of Node.js that do not include
28105 // the prependListener() method. The goal is to eventually remove this hack.
28106
28107 if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (Array.isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]];
28108}
28109
28110function ReadableState(options, stream, isDuplex) {
28111 Duplex = Duplex || require('./_stream_duplex');
28112 options = options || {}; // Duplex streams are both readable and writable, but share
28113 // the same options object.
28114 // However, some cases require setting options to different
28115 // values for the readable and the writable sides of the duplex stream.
28116 // These options can be provided separately as readableXXX and writableXXX.
28117
28118 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag. Used to make read(n) ignore n and to
28119 // make all the buffer merging and length checks go away
28120
28121 this.objectMode = !!options.objectMode;
28122 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer
28123 // Note: 0 is a valid value, means "don't call _read preemptively ever"
28124
28125 this.highWaterMark = getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex); // A linked list is used to store data chunks instead of an array because the
28126 // linked list can remove elements from the beginning faster than
28127 // array.shift()
28128
28129 this.buffer = new BufferList();
28130 this.length = 0;
28131 this.pipes = null;
28132 this.pipesCount = 0;
28133 this.flowing = null;
28134 this.ended = false;
28135 this.endEmitted = false;
28136 this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted
28137 // immediately, or on a later tick. We set this to true at first, because
28138 // any actions that shouldn't happen until "later" should generally also
28139 // not happen before the first read call.
28140
28141 this.sync = true; // whenever we return null, then we set a flag to say
28142 // that we're awaiting a 'readable' event emission.
28143
28144 this.needReadable = false;
28145 this.emittedReadable = false;
28146 this.readableListening = false;
28147 this.resumeScheduled = false;
28148 this.paused = true; // Should close be emitted on destroy. Defaults to true.
28149
28150 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'end' (and potentially 'finish')
28151
28152 this.autoDestroy = !!options.autoDestroy; // has it been destroyed
28153
28154 this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string
28155 // encoding is 'binary' so we have to make this configurable.
28156 // Everything else in the universe uses 'utf8', though.
28157
28158 this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s
28159
28160 this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled
28161
28162 this.readingMore = false;
28163 this.decoder = null;
28164 this.encoding = null;
28165
28166 if (options.encoding) {
28167 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
28168 this.decoder = new StringDecoder(options.encoding);
28169 this.encoding = options.encoding;
28170 }
28171}
28172
28173function Readable(options) {
28174 Duplex = Duplex || require('./_stream_duplex');
28175 if (!(this instanceof Readable)) return new Readable(options); // Checking for a Stream.Duplex instance is faster here instead of inside
28176 // the ReadableState constructor, at least with V8 6.5
28177
28178 var isDuplex = this instanceof Duplex;
28179 this._readableState = new ReadableState(options, this, isDuplex); // legacy
28180
28181 this.readable = true;
28182
28183 if (options) {
28184 if (typeof options.read === 'function') this._read = options.read;
28185 if (typeof options.destroy === 'function') this._destroy = options.destroy;
28186 }
28187
28188 Stream.call(this);
28189}
28190
28191Object.defineProperty(Readable.prototype, 'destroyed', {
28192 // making it explicit this property is not enumerable
28193 // because otherwise some prototype manipulation in
28194 // userland will fail
28195 enumerable: false,
28196 get: function get() {
28197 if (this._readableState === undefined) {
28198 return false;
28199 }
28200
28201 return this._readableState.destroyed;
28202 },
28203 set: function set(value) {
28204 // we ignore the value if the stream
28205 // has not been initialized yet
28206 if (!this._readableState) {
28207 return;
28208 } // backward compatibility, the user is explicitly
28209 // managing destroyed
28210
28211
28212 this._readableState.destroyed = value;
28213 }
28214});
28215Readable.prototype.destroy = destroyImpl.destroy;
28216Readable.prototype._undestroy = destroyImpl.undestroy;
28217
28218Readable.prototype._destroy = function (err, cb) {
28219 cb(err);
28220}; // Manually shove something into the read() buffer.
28221// This returns true if the highWaterMark has not been hit yet,
28222// similar to how Writable.write() returns true if you should
28223// write() some more.
28224
28225
28226Readable.prototype.push = function (chunk, encoding) {
28227 var state = this._readableState;
28228 var skipChunkCheck;
28229
28230 if (!state.objectMode) {
28231 if (typeof chunk === 'string') {
28232 encoding = encoding || state.defaultEncoding;
28233
28234 if (encoding !== state.encoding) {
28235 chunk = Buffer.from(chunk, encoding);
28236 encoding = '';
28237 }
28238
28239 skipChunkCheck = true;
28240 }
28241 } else {
28242 skipChunkCheck = true;
28243 }
28244
28245 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
28246}; // Unshift should *always* be something directly out of read()
28247
28248
28249Readable.prototype.unshift = function (chunk) {
28250 return readableAddChunk(this, chunk, null, true, false);
28251};
28252
28253function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
28254 debug('readableAddChunk', chunk);
28255 var state = stream._readableState;
28256
28257 if (chunk === null) {
28258 state.reading = false;
28259 onEofChunk(stream, state);
28260 } else {
28261 var er;
28262 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
28263
28264 if (er) {
28265 errorOrDestroy(stream, er);
28266 } else if (state.objectMode || chunk && chunk.length > 0) {
28267 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
28268 chunk = _uint8ArrayToBuffer(chunk);
28269 }
28270
28271 if (addToFront) {
28272 if (state.endEmitted) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT());else addChunk(stream, state, chunk, true);
28273 } else if (state.ended) {
28274 errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF());
28275 } else if (state.destroyed) {
28276 return false;
28277 } else {
28278 state.reading = false;
28279
28280 if (state.decoder && !encoding) {
28281 chunk = state.decoder.write(chunk);
28282 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
28283 } else {
28284 addChunk(stream, state, chunk, false);
28285 }
28286 }
28287 } else if (!addToFront) {
28288 state.reading = false;
28289 maybeReadMore(stream, state);
28290 }
28291 } // We can push more data if we are below the highWaterMark.
28292 // Also, if we have no data yet, we can stand some more bytes.
28293 // This is to work around cases where hwm=0, such as the repl.
28294
28295
28296 return !state.ended && (state.length < state.highWaterMark || state.length === 0);
28297}
28298
28299function addChunk(stream, state, chunk, addToFront) {
28300 if (state.flowing && state.length === 0 && !state.sync) {
28301 state.awaitDrain = 0;
28302 stream.emit('data', chunk);
28303 } else {
28304 // update the buffer info.
28305 state.length += state.objectMode ? 1 : chunk.length;
28306 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
28307 if (state.needReadable) emitReadable(stream);
28308 }
28309
28310 maybeReadMore(stream, state);
28311}
28312
28313function chunkInvalid(state, chunk) {
28314 var er;
28315
28316 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
28317 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk);
28318 }
28319
28320 return er;
28321}
28322
28323Readable.prototype.isPaused = function () {
28324 return this._readableState.flowing === false;
28325}; // backwards compatibility.
28326
28327
28328Readable.prototype.setEncoding = function (enc) {
28329 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
28330 var decoder = new StringDecoder(enc);
28331 this._readableState.decoder = decoder; // If setEncoding(null), decoder.encoding equals utf8
28332
28333 this._readableState.encoding = this._readableState.decoder.encoding; // Iterate over current buffer to convert already stored Buffers:
28334
28335 var p = this._readableState.buffer.head;
28336 var content = '';
28337
28338 while (p !== null) {
28339 content += decoder.write(p.data);
28340 p = p.next;
28341 }
28342
28343 this._readableState.buffer.clear();
28344
28345 if (content !== '') this._readableState.buffer.push(content);
28346 this._readableState.length = content.length;
28347 return this;
28348}; // Don't raise the hwm > 1GB
28349
28350
28351var MAX_HWM = 0x40000000;
28352
28353function computeNewHighWaterMark(n) {
28354 if (n >= MAX_HWM) {
28355 // TODO(ronag): Throw ERR_VALUE_OUT_OF_RANGE.
28356 n = MAX_HWM;
28357 } else {
28358 // Get the next highest power of 2 to prevent increasing hwm excessively in
28359 // tiny amounts
28360 n--;
28361 n |= n >>> 1;
28362 n |= n >>> 2;
28363 n |= n >>> 4;
28364 n |= n >>> 8;
28365 n |= n >>> 16;
28366 n++;
28367 }
28368
28369 return n;
28370} // This function is designed to be inlinable, so please take care when making
28371// changes to the function body.
28372
28373
28374function howMuchToRead(n, state) {
28375 if (n <= 0 || state.length === 0 && state.ended) return 0;
28376 if (state.objectMode) return 1;
28377
28378 if (n !== n) {
28379 // Only flow one buffer at a time
28380 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
28381 } // If we're asking for more than the current hwm, then raise the hwm.
28382
28383
28384 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
28385 if (n <= state.length) return n; // Don't have enough
28386
28387 if (!state.ended) {
28388 state.needReadable = true;
28389 return 0;
28390 }
28391
28392 return state.length;
28393} // you can override either this method, or the async _read(n) below.
28394
28395
28396Readable.prototype.read = function (n) {
28397 debug('read', n);
28398 n = parseInt(n, 10);
28399 var state = this._readableState;
28400 var nOrig = n;
28401 if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we
28402 // already have a bunch of data in the buffer, then just trigger
28403 // the 'readable' event and move on.
28404
28405 if (n === 0 && state.needReadable && ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended)) {
28406 debug('read: emitReadable', state.length, state.ended);
28407 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
28408 return null;
28409 }
28410
28411 n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up.
28412
28413 if (n === 0 && state.ended) {
28414 if (state.length === 0) endReadable(this);
28415 return null;
28416 } // All the actual chunk generation logic needs to be
28417 // *below* the call to _read. The reason is that in certain
28418 // synthetic stream cases, such as passthrough streams, _read
28419 // may be a completely synchronous operation which may change
28420 // the state of the read buffer, providing enough data when
28421 // before there was *not* enough.
28422 //
28423 // So, the steps are:
28424 // 1. Figure out what the state of things will be after we do
28425 // a read from the buffer.
28426 //
28427 // 2. If that resulting state will trigger a _read, then call _read.
28428 // Note that this may be asynchronous, or synchronous. Yes, it is
28429 // deeply ugly to write APIs this way, but that still doesn't mean
28430 // that the Readable class should behave improperly, as streams are
28431 // designed to be sync/async agnostic.
28432 // Take note if the _read call is sync or async (ie, if the read call
28433 // has returned yet), so that we know whether or not it's safe to emit
28434 // 'readable' etc.
28435 //
28436 // 3. Actually pull the requested chunks out of the buffer and return.
28437 // if we need a readable event, then we need to do some reading.
28438
28439
28440 var doRead = state.needReadable;
28441 debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some
28442
28443 if (state.length === 0 || state.length - n < state.highWaterMark) {
28444 doRead = true;
28445 debug('length less than watermark', doRead);
28446 } // however, if we've ended, then there's no point, and if we're already
28447 // reading, then it's unnecessary.
28448
28449
28450 if (state.ended || state.reading) {
28451 doRead = false;
28452 debug('reading or ended', doRead);
28453 } else if (doRead) {
28454 debug('do read');
28455 state.reading = true;
28456 state.sync = true; // if the length is currently zero, then we *need* a readable event.
28457
28458 if (state.length === 0) state.needReadable = true; // call internal read method
28459
28460 this._read(state.highWaterMark);
28461
28462 state.sync = false; // If _read pushed data synchronously, then `reading` will be false,
28463 // and we need to re-evaluate how much data we can return to the user.
28464
28465 if (!state.reading) n = howMuchToRead(nOrig, state);
28466 }
28467
28468 var ret;
28469 if (n > 0) ret = fromList(n, state);else ret = null;
28470
28471 if (ret === null) {
28472 state.needReadable = state.length <= state.highWaterMark;
28473 n = 0;
28474 } else {
28475 state.length -= n;
28476 state.awaitDrain = 0;
28477 }
28478
28479 if (state.length === 0) {
28480 // If we have nothing in the buffer, then we want to know
28481 // as soon as we *do* get something into the buffer.
28482 if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick.
28483
28484 if (nOrig !== n && state.ended) endReadable(this);
28485 }
28486
28487 if (ret !== null) this.emit('data', ret);
28488 return ret;
28489};
28490
28491function onEofChunk(stream, state) {
28492 debug('onEofChunk');
28493 if (state.ended) return;
28494
28495 if (state.decoder) {
28496 var chunk = state.decoder.end();
28497
28498 if (chunk && chunk.length) {
28499 state.buffer.push(chunk);
28500 state.length += state.objectMode ? 1 : chunk.length;
28501 }
28502 }
28503
28504 state.ended = true;
28505
28506 if (state.sync) {
28507 // if we are sync, wait until next tick to emit the data.
28508 // Otherwise we risk emitting data in the flow()
28509 // the readable code triggers during a read() call
28510 emitReadable(stream);
28511 } else {
28512 // emit 'readable' now to make sure it gets picked up.
28513 state.needReadable = false;
28514
28515 if (!state.emittedReadable) {
28516 state.emittedReadable = true;
28517 emitReadable_(stream);
28518 }
28519 }
28520} // Don't emit readable right away in sync mode, because this can trigger
28521// another read() call => stack overflow. This way, it might trigger
28522// a nextTick recursion warning, but that's not so bad.
28523
28524
28525function emitReadable(stream) {
28526 var state = stream._readableState;
28527 debug('emitReadable', state.needReadable, state.emittedReadable);
28528 state.needReadable = false;
28529
28530 if (!state.emittedReadable) {
28531 debug('emitReadable', state.flowing);
28532 state.emittedReadable = true;
28533 process.nextTick(emitReadable_, stream);
28534 }
28535}
28536
28537function emitReadable_(stream) {
28538 var state = stream._readableState;
28539 debug('emitReadable_', state.destroyed, state.length, state.ended);
28540
28541 if (!state.destroyed && (state.length || state.ended)) {
28542 stream.emit('readable');
28543 state.emittedReadable = false;
28544 } // The stream needs another readable event if
28545 // 1. It is not flowing, as the flow mechanism will take
28546 // care of it.
28547 // 2. It is not ended.
28548 // 3. It is below the highWaterMark, so we can schedule
28549 // another readable later.
28550
28551
28552 state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark;
28553 flow(stream);
28554} // at this point, the user has presumably seen the 'readable' event,
28555// and called read() to consume some data. that may have triggered
28556// in turn another _read(n) call, in which case reading = true if
28557// it's in progress.
28558// However, if we're not ended, or reading, and the length < hwm,
28559// then go ahead and try to read some more preemptively.
28560
28561
28562function maybeReadMore(stream, state) {
28563 if (!state.readingMore) {
28564 state.readingMore = true;
28565 process.nextTick(maybeReadMore_, stream, state);
28566 }
28567}
28568
28569function maybeReadMore_(stream, state) {
28570 // Attempt to read more data if we should.
28571 //
28572 // The conditions for reading more data are (one of):
28573 // - Not enough data buffered (state.length < state.highWaterMark). The loop
28574 // is responsible for filling the buffer with enough data if such data
28575 // is available. If highWaterMark is 0 and we are not in the flowing mode
28576 // we should _not_ attempt to buffer any extra data. We'll get more data
28577 // when the stream consumer calls read() instead.
28578 // - No data in the buffer, and the stream is in flowing mode. In this mode
28579 // the loop below is responsible for ensuring read() is called. Failing to
28580 // call read here would abort the flow and there's no other mechanism for
28581 // continuing the flow if the stream consumer has just subscribed to the
28582 // 'data' event.
28583 //
28584 // In addition to the above conditions to keep reading data, the following
28585 // conditions prevent the data from being read:
28586 // - The stream has ended (state.ended).
28587 // - There is already a pending 'read' operation (state.reading). This is a
28588 // case where the the stream has called the implementation defined _read()
28589 // method, but they are processing the call asynchronously and have _not_
28590 // called push() with new data. In this case we skip performing more
28591 // read()s. The execution ends in this method again after the _read() ends
28592 // up calling push() with more data.
28593 while (!state.reading && !state.ended && (state.length < state.highWaterMark || state.flowing && state.length === 0)) {
28594 var len = state.length;
28595 debug('maybeReadMore read 0');
28596 stream.read(0);
28597 if (len === state.length) // didn't get any data, stop spinning.
28598 break;
28599 }
28600
28601 state.readingMore = false;
28602} // abstract method. to be overridden in specific implementation classes.
28603// call cb(er, data) where data is <= n in length.
28604// for virtual (non-string, non-buffer) streams, "length" is somewhat
28605// arbitrary, and perhaps not very meaningful.
28606
28607
28608Readable.prototype._read = function (n) {
28609 errorOrDestroy(this, new ERR_METHOD_NOT_IMPLEMENTED('_read()'));
28610};
28611
28612Readable.prototype.pipe = function (dest, pipeOpts) {
28613 var src = this;
28614 var state = this._readableState;
28615
28616 switch (state.pipesCount) {
28617 case 0:
28618 state.pipes = dest;
28619 break;
28620
28621 case 1:
28622 state.pipes = [state.pipes, dest];
28623 break;
28624
28625 default:
28626 state.pipes.push(dest);
28627 break;
28628 }
28629
28630 state.pipesCount += 1;
28631 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
28632 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
28633 var endFn = doEnd ? onend : unpipe;
28634 if (state.endEmitted) process.nextTick(endFn);else src.once('end', endFn);
28635 dest.on('unpipe', onunpipe);
28636
28637 function onunpipe(readable, unpipeInfo) {
28638 debug('onunpipe');
28639
28640 if (readable === src) {
28641 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
28642 unpipeInfo.hasUnpiped = true;
28643 cleanup();
28644 }
28645 }
28646 }
28647
28648 function onend() {
28649 debug('onend');
28650 dest.end();
28651 } // when the dest drains, it reduces the awaitDrain counter
28652 // on the source. This would be more elegant with a .once()
28653 // handler in flow(), but adding and removing repeatedly is
28654 // too slow.
28655
28656
28657 var ondrain = pipeOnDrain(src);
28658 dest.on('drain', ondrain);
28659 var cleanedUp = false;
28660
28661 function cleanup() {
28662 debug('cleanup'); // cleanup event handlers once the pipe is broken
28663
28664 dest.removeListener('close', onclose);
28665 dest.removeListener('finish', onfinish);
28666 dest.removeListener('drain', ondrain);
28667 dest.removeListener('error', onerror);
28668 dest.removeListener('unpipe', onunpipe);
28669 src.removeListener('end', onend);
28670 src.removeListener('end', unpipe);
28671 src.removeListener('data', ondata);
28672 cleanedUp = true; // if the reader is waiting for a drain event from this
28673 // specific writer, then it would cause it to never start
28674 // flowing again.
28675 // So, if this is awaiting a drain, then we just call it now.
28676 // If we don't know, then assume that we are waiting for one.
28677
28678 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
28679 }
28680
28681 src.on('data', ondata);
28682
28683 function ondata(chunk) {
28684 debug('ondata');
28685 var ret = dest.write(chunk);
28686 debug('dest.write', ret);
28687
28688 if (ret === false) {
28689 // If the user unpiped during `dest.write()`, it is possible
28690 // to get stuck in a permanently paused state if that write
28691 // also returned false.
28692 // => Check whether `dest` is still a piping destination.
28693 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
28694 debug('false write response, pause', state.awaitDrain);
28695 state.awaitDrain++;
28696 }
28697
28698 src.pause();
28699 }
28700 } // if the dest has an error, then stop piping into it.
28701 // however, don't suppress the throwing behavior for this.
28702
28703
28704 function onerror(er) {
28705 debug('onerror', er);
28706 unpipe();
28707 dest.removeListener('error', onerror);
28708 if (EElistenerCount(dest, 'error') === 0) errorOrDestroy(dest, er);
28709 } // Make sure our error handler is attached before userland ones.
28710
28711
28712 prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once.
28713
28714 function onclose() {
28715 dest.removeListener('finish', onfinish);
28716 unpipe();
28717 }
28718
28719 dest.once('close', onclose);
28720
28721 function onfinish() {
28722 debug('onfinish');
28723 dest.removeListener('close', onclose);
28724 unpipe();
28725 }
28726
28727 dest.once('finish', onfinish);
28728
28729 function unpipe() {
28730 debug('unpipe');
28731 src.unpipe(dest);
28732 } // tell the dest that it's being piped to
28733
28734
28735 dest.emit('pipe', src); // start the flow if it hasn't been started already.
28736
28737 if (!state.flowing) {
28738 debug('pipe resume');
28739 src.resume();
28740 }
28741
28742 return dest;
28743};
28744
28745function pipeOnDrain(src) {
28746 return function pipeOnDrainFunctionResult() {
28747 var state = src._readableState;
28748 debug('pipeOnDrain', state.awaitDrain);
28749 if (state.awaitDrain) state.awaitDrain--;
28750
28751 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
28752 state.flowing = true;
28753 flow(src);
28754 }
28755 };
28756}
28757
28758Readable.prototype.unpipe = function (dest) {
28759 var state = this._readableState;
28760 var unpipeInfo = {
28761 hasUnpiped: false
28762 }; // if we're not piping anywhere, then do nothing.
28763
28764 if (state.pipesCount === 0) return this; // just one destination. most common case.
28765
28766 if (state.pipesCount === 1) {
28767 // passed in one, but it's not the right one.
28768 if (dest && dest !== state.pipes) return this;
28769 if (!dest) dest = state.pipes; // got a match.
28770
28771 state.pipes = null;
28772 state.pipesCount = 0;
28773 state.flowing = false;
28774 if (dest) dest.emit('unpipe', this, unpipeInfo);
28775 return this;
28776 } // slow case. multiple pipe destinations.
28777
28778
28779 if (!dest) {
28780 // remove all.
28781 var dests = state.pipes;
28782 var len = state.pipesCount;
28783 state.pipes = null;
28784 state.pipesCount = 0;
28785 state.flowing = false;
28786
28787 for (var i = 0; i < len; i++) {
28788 dests[i].emit('unpipe', this, {
28789 hasUnpiped: false
28790 });
28791 }
28792
28793 return this;
28794 } // try to find the right one.
28795
28796
28797 var index = indexOf(state.pipes, dest);
28798 if (index === -1) return this;
28799 state.pipes.splice(index, 1);
28800 state.pipesCount -= 1;
28801 if (state.pipesCount === 1) state.pipes = state.pipes[0];
28802 dest.emit('unpipe', this, unpipeInfo);
28803 return this;
28804}; // set up data events if they are asked for
28805// Ensure readable listeners eventually get something
28806
28807
28808Readable.prototype.on = function (ev, fn) {
28809 var res = Stream.prototype.on.call(this, ev, fn);
28810 var state = this._readableState;
28811
28812 if (ev === 'data') {
28813 // update readableListening so that resume() may be a no-op
28814 // a few lines down. This is needed to support once('readable').
28815 state.readableListening = this.listenerCount('readable') > 0; // Try start flowing on next tick if stream isn't explicitly paused
28816
28817 if (state.flowing !== false) this.resume();
28818 } else if (ev === 'readable') {
28819 if (!state.endEmitted && !state.readableListening) {
28820 state.readableListening = state.needReadable = true;
28821 state.flowing = false;
28822 state.emittedReadable = false;
28823 debug('on readable', state.length, state.reading);
28824
28825 if (state.length) {
28826 emitReadable(this);
28827 } else if (!state.reading) {
28828 process.nextTick(nReadingNextTick, this);
28829 }
28830 }
28831 }
28832
28833 return res;
28834};
28835
28836Readable.prototype.addListener = Readable.prototype.on;
28837
28838Readable.prototype.removeListener = function (ev, fn) {
28839 var res = Stream.prototype.removeListener.call(this, ev, fn);
28840
28841 if (ev === 'readable') {
28842 // We need to check if there is someone still listening to
28843 // readable and reset the state. However this needs to happen
28844 // after readable has been emitted but before I/O (nextTick) to
28845 // support once('readable', fn) cycles. This means that calling
28846 // resume within the same tick will have no
28847 // effect.
28848 process.nextTick(updateReadableListening, this);
28849 }
28850
28851 return res;
28852};
28853
28854Readable.prototype.removeAllListeners = function (ev) {
28855 var res = Stream.prototype.removeAllListeners.apply(this, arguments);
28856
28857 if (ev === 'readable' || ev === undefined) {
28858 // We need to check if there is someone still listening to
28859 // readable and reset the state. However this needs to happen
28860 // after readable has been emitted but before I/O (nextTick) to
28861 // support once('readable', fn) cycles. This means that calling
28862 // resume within the same tick will have no
28863 // effect.
28864 process.nextTick(updateReadableListening, this);
28865 }
28866
28867 return res;
28868};
28869
28870function updateReadableListening(self) {
28871 var state = self._readableState;
28872 state.readableListening = self.listenerCount('readable') > 0;
28873
28874 if (state.resumeScheduled && !state.paused) {
28875 // flowing needs to be set to true now, otherwise
28876 // the upcoming resume will not flow.
28877 state.flowing = true; // crude way to check if we should resume
28878 } else if (self.listenerCount('data') > 0) {
28879 self.resume();
28880 }
28881}
28882
28883function nReadingNextTick(self) {
28884 debug('readable nexttick read 0');
28885 self.read(0);
28886} // pause() and resume() are remnants of the legacy readable stream API
28887// If the user uses them, then switch into old mode.
28888
28889
28890Readable.prototype.resume = function () {
28891 var state = this._readableState;
28892
28893 if (!state.flowing) {
28894 debug('resume'); // we flow only if there is no one listening
28895 // for readable, but we still have to call
28896 // resume()
28897
28898 state.flowing = !state.readableListening;
28899 resume(this, state);
28900 }
28901
28902 state.paused = false;
28903 return this;
28904};
28905
28906function resume(stream, state) {
28907 if (!state.resumeScheduled) {
28908 state.resumeScheduled = true;
28909 process.nextTick(resume_, stream, state);
28910 }
28911}
28912
28913function resume_(stream, state) {
28914 debug('resume', state.reading);
28915
28916 if (!state.reading) {
28917 stream.read(0);
28918 }
28919
28920 state.resumeScheduled = false;
28921 stream.emit('resume');
28922 flow(stream);
28923 if (state.flowing && !state.reading) stream.read(0);
28924}
28925
28926Readable.prototype.pause = function () {
28927 debug('call pause flowing=%j', this._readableState.flowing);
28928
28929 if (this._readableState.flowing !== false) {
28930 debug('pause');
28931 this._readableState.flowing = false;
28932 this.emit('pause');
28933 }
28934
28935 this._readableState.paused = true;
28936 return this;
28937};
28938
28939function flow(stream) {
28940 var state = stream._readableState;
28941 debug('flow', state.flowing);
28942
28943 while (state.flowing && stream.read() !== null) {
28944 ;
28945 }
28946} // wrap an old-style stream as the async data source.
28947// This is *not* part of the readable stream interface.
28948// It is an ugly unfortunate mess of history.
28949
28950
28951Readable.prototype.wrap = function (stream) {
28952 var _this = this;
28953
28954 var state = this._readableState;
28955 var paused = false;
28956 stream.on('end', function () {
28957 debug('wrapped end');
28958
28959 if (state.decoder && !state.ended) {
28960 var chunk = state.decoder.end();
28961 if (chunk && chunk.length) _this.push(chunk);
28962 }
28963
28964 _this.push(null);
28965 });
28966 stream.on('data', function (chunk) {
28967 debug('wrapped data');
28968 if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode
28969
28970 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
28971
28972 var ret = _this.push(chunk);
28973
28974 if (!ret) {
28975 paused = true;
28976 stream.pause();
28977 }
28978 }); // proxy all the other methods.
28979 // important when wrapping filters and duplexes.
28980
28981 for (var i in stream) {
28982 if (this[i] === undefined && typeof stream[i] === 'function') {
28983 this[i] = function methodWrap(method) {
28984 return function methodWrapReturnFunction() {
28985 return stream[method].apply(stream, arguments);
28986 };
28987 }(i);
28988 }
28989 } // proxy certain important events.
28990
28991
28992 for (var n = 0; n < kProxyEvents.length; n++) {
28993 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
28994 } // when we try to consume some more bytes, simply unpause the
28995 // underlying stream.
28996
28997
28998 this._read = function (n) {
28999 debug('wrapped _read', n);
29000
29001 if (paused) {
29002 paused = false;
29003 stream.resume();
29004 }
29005 };
29006
29007 return this;
29008};
29009
29010if (typeof Symbol === 'function') {
29011 Readable.prototype[Symbol.asyncIterator] = function () {
29012 if (createReadableStreamAsyncIterator === undefined) {
29013 createReadableStreamAsyncIterator = require('./internal/streams/async_iterator');
29014 }
29015
29016 return createReadableStreamAsyncIterator(this);
29017 };
29018}
29019
29020Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
29021 // making it explicit this property is not enumerable
29022 // because otherwise some prototype manipulation in
29023 // userland will fail
29024 enumerable: false,
29025 get: function get() {
29026 return this._readableState.highWaterMark;
29027 }
29028});
29029Object.defineProperty(Readable.prototype, 'readableBuffer', {
29030 // making it explicit this property is not enumerable
29031 // because otherwise some prototype manipulation in
29032 // userland will fail
29033 enumerable: false,
29034 get: function get() {
29035 return this._readableState && this._readableState.buffer;
29036 }
29037});
29038Object.defineProperty(Readable.prototype, 'readableFlowing', {
29039 // making it explicit this property is not enumerable
29040 // because otherwise some prototype manipulation in
29041 // userland will fail
29042 enumerable: false,
29043 get: function get() {
29044 return this._readableState.flowing;
29045 },
29046 set: function set(state) {
29047 if (this._readableState) {
29048 this._readableState.flowing = state;
29049 }
29050 }
29051}); // exposed for testing purposes only.
29052
29053Readable._fromList = fromList;
29054Object.defineProperty(Readable.prototype, 'readableLength', {
29055 // making it explicit this property is not enumerable
29056 // because otherwise some prototype manipulation in
29057 // userland will fail
29058 enumerable: false,
29059 get: function get() {
29060 return this._readableState.length;
29061 }
29062}); // Pluck off n bytes from an array of buffers.
29063// Length is the combined lengths of all the buffers in the list.
29064// This function is designed to be inlinable, so please take care when making
29065// changes to the function body.
29066
29067function fromList(n, state) {
29068 // nothing buffered
29069 if (state.length === 0) return null;
29070 var ret;
29071 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
29072 // read it all, truncate the list
29073 if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.first();else ret = state.buffer.concat(state.length);
29074 state.buffer.clear();
29075 } else {
29076 // read part of list
29077 ret = state.buffer.consume(n, state.decoder);
29078 }
29079 return ret;
29080}
29081
29082function endReadable(stream) {
29083 var state = stream._readableState;
29084 debug('endReadable', state.endEmitted);
29085
29086 if (!state.endEmitted) {
29087 state.ended = true;
29088 process.nextTick(endReadableNT, state, stream);
29089 }
29090}
29091
29092function endReadableNT(state, stream) {
29093 debug('endReadableNT', state.endEmitted, state.length); // Check that we didn't get one last unshift.
29094
29095 if (!state.endEmitted && state.length === 0) {
29096 state.endEmitted = true;
29097 stream.readable = false;
29098 stream.emit('end');
29099
29100 if (state.autoDestroy) {
29101 // In case of duplex streams we need a way to detect
29102 // if the writable side is ready for autoDestroy as well
29103 var wState = stream._writableState;
29104
29105 if (!wState || wState.autoDestroy && wState.finished) {
29106 stream.destroy();
29107 }
29108 }
29109 }
29110}
29111
29112if (typeof Symbol === 'function') {
29113 Readable.from = function (iterable, opts) {
29114 if (from === undefined) {
29115 from = require('./internal/streams/from');
29116 }
29117
29118 return from(Readable, iterable, opts);
29119 };
29120}
29121
29122function indexOf(xs, x) {
29123 for (var i = 0, l = xs.length; i < l; i++) {
29124 if (xs[i] === x) return i;
29125 }
29126
29127 return -1;
29128}
29129}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
29130},{"../errors":113,"./_stream_duplex":114,"./internal/streams/async_iterator":119,"./internal/streams/buffer_list":120,"./internal/streams/destroy":121,"./internal/streams/from":123,"./internal/streams/state":125,"./internal/streams/stream":126,"_process":228,"buffer":132,"events":172,"inherits":112,"string_decoder/":267,"util":82}],117:[function(require,module,exports){
29131// Copyright Joyent, Inc. and other Node contributors.
29132//
29133// Permission is hereby granted, free of charge, to any person obtaining a
29134// copy of this software and associated documentation files (the
29135// "Software"), to deal in the Software without restriction, including
29136// without limitation the rights to use, copy, modify, merge, publish,
29137// distribute, sublicense, and/or sell copies of the Software, and to permit
29138// persons to whom the Software is furnished to do so, subject to the
29139// following conditions:
29140//
29141// The above copyright notice and this permission notice shall be included
29142// in all copies or substantial portions of the Software.
29143//
29144// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
29145// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29146// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
29147// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
29148// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
29149// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
29150// USE OR OTHER DEALINGS IN THE SOFTWARE.
29151// a transform stream is a readable/writable stream where you do
29152// something with the data. Sometimes it's called a "filter",
29153// but that's not a great name for it, since that implies a thing where
29154// some bits pass through, and others are simply ignored. (That would
29155// be a valid example of a transform, of course.)
29156//
29157// While the output is causally related to the input, it's not a
29158// necessarily symmetric or synchronous transformation. For example,
29159// a zlib stream might take multiple plain-text writes(), and then
29160// emit a single compressed chunk some time in the future.
29161//
29162// Here's how this works:
29163//
29164// The Transform stream has all the aspects of the readable and writable
29165// stream classes. When you write(chunk), that calls _write(chunk,cb)
29166// internally, and returns false if there's a lot of pending writes
29167// buffered up. When you call read(), that calls _read(n) until
29168// there's enough pending readable data buffered up.
29169//
29170// In a transform stream, the written data is placed in a buffer. When
29171// _read(n) is called, it transforms the queued up data, calling the
29172// buffered _write cb's as it consumes chunks. If consuming a single
29173// written chunk would result in multiple output chunks, then the first
29174// outputted bit calls the readcb, and subsequent chunks just go into
29175// the read buffer, and will cause it to emit 'readable' if necessary.
29176//
29177// This way, back-pressure is actually determined by the reading side,
29178// since _read has to be called to start processing a new chunk. However,
29179// a pathological inflate type of transform can cause excessive buffering
29180// here. For example, imagine a stream where every byte of input is
29181// interpreted as an integer from 0-255, and then results in that many
29182// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
29183// 1kb of data being output. In this case, you could write a very small
29184// amount of input, and end up with a very large amount of output. In
29185// such a pathological inflating mechanism, there'd be no way to tell
29186// the system to stop doing the transform. A single 4MB write could
29187// cause the system to run out of memory.
29188//
29189// However, even in such a pathological case, only a single written chunk
29190// would be consumed, and then the rest would wait (un-transformed) until
29191// the results of the previous transformed chunk were consumed.
29192'use strict';
29193
29194module.exports = Transform;
29195
29196var _require$codes = require('../errors').codes,
29197 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
29198 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
29199 ERR_TRANSFORM_ALREADY_TRANSFORMING = _require$codes.ERR_TRANSFORM_ALREADY_TRANSFORMING,
29200 ERR_TRANSFORM_WITH_LENGTH_0 = _require$codes.ERR_TRANSFORM_WITH_LENGTH_0;
29201
29202var Duplex = require('./_stream_duplex');
29203
29204require('inherits')(Transform, Duplex);
29205
29206function afterTransform(er, data) {
29207 var ts = this._transformState;
29208 ts.transforming = false;
29209 var cb = ts.writecb;
29210
29211 if (cb === null) {
29212 return this.emit('error', new ERR_MULTIPLE_CALLBACK());
29213 }
29214
29215 ts.writechunk = null;
29216 ts.writecb = null;
29217 if (data != null) // single equals check for both `null` and `undefined`
29218 this.push(data);
29219 cb(er);
29220 var rs = this._readableState;
29221 rs.reading = false;
29222
29223 if (rs.needReadable || rs.length < rs.highWaterMark) {
29224 this._read(rs.highWaterMark);
29225 }
29226}
29227
29228function Transform(options) {
29229 if (!(this instanceof Transform)) return new Transform(options);
29230 Duplex.call(this, options);
29231 this._transformState = {
29232 afterTransform: afterTransform.bind(this),
29233 needTransform: false,
29234 transforming: false,
29235 writecb: null,
29236 writechunk: null,
29237 writeencoding: null
29238 }; // start out asking for a readable event once data is transformed.
29239
29240 this._readableState.needReadable = true; // we have implemented the _read method, and done the other things
29241 // that Readable wants before the first _read call, so unset the
29242 // sync guard flag.
29243
29244 this._readableState.sync = false;
29245
29246 if (options) {
29247 if (typeof options.transform === 'function') this._transform = options.transform;
29248 if (typeof options.flush === 'function') this._flush = options.flush;
29249 } // When the writable side finishes, then flush out anything remaining.
29250
29251
29252 this.on('prefinish', prefinish);
29253}
29254
29255function prefinish() {
29256 var _this = this;
29257
29258 if (typeof this._flush === 'function' && !this._readableState.destroyed) {
29259 this._flush(function (er, data) {
29260 done(_this, er, data);
29261 });
29262 } else {
29263 done(this, null, null);
29264 }
29265}
29266
29267Transform.prototype.push = function (chunk, encoding) {
29268 this._transformState.needTransform = false;
29269 return Duplex.prototype.push.call(this, chunk, encoding);
29270}; // This is the part where you do stuff!
29271// override this function in implementation classes.
29272// 'chunk' is an input chunk.
29273//
29274// Call `push(newChunk)` to pass along transformed output
29275// to the readable side. You may call 'push' zero or more times.
29276//
29277// Call `cb(err)` when you are done with this chunk. If you pass
29278// an error, then that'll put the hurt on the whole operation. If you
29279// never call cb(), then you'll never get another chunk.
29280
29281
29282Transform.prototype._transform = function (chunk, encoding, cb) {
29283 cb(new ERR_METHOD_NOT_IMPLEMENTED('_transform()'));
29284};
29285
29286Transform.prototype._write = function (chunk, encoding, cb) {
29287 var ts = this._transformState;
29288 ts.writecb = cb;
29289 ts.writechunk = chunk;
29290 ts.writeencoding = encoding;
29291
29292 if (!ts.transforming) {
29293 var rs = this._readableState;
29294 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
29295 }
29296}; // Doesn't matter what the args are here.
29297// _transform does all the work.
29298// That we got here means that the readable side wants more data.
29299
29300
29301Transform.prototype._read = function (n) {
29302 var ts = this._transformState;
29303
29304 if (ts.writechunk !== null && !ts.transforming) {
29305 ts.transforming = true;
29306
29307 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
29308 } else {
29309 // mark that we need a transform, so that any data that comes in
29310 // will get processed, now that we've asked for it.
29311 ts.needTransform = true;
29312 }
29313};
29314
29315Transform.prototype._destroy = function (err, cb) {
29316 Duplex.prototype._destroy.call(this, err, function (err2) {
29317 cb(err2);
29318 });
29319};
29320
29321function done(stream, er, data) {
29322 if (er) return stream.emit('error', er);
29323 if (data != null) // single equals check for both `null` and `undefined`
29324 stream.push(data); // TODO(BridgeAR): Write a test for these two error cases
29325 // if there's nothing in the write buffer, then that means
29326 // that nothing more will ever be provided
29327
29328 if (stream._writableState.length) throw new ERR_TRANSFORM_WITH_LENGTH_0();
29329 if (stream._transformState.transforming) throw new ERR_TRANSFORM_ALREADY_TRANSFORMING();
29330 return stream.push(null);
29331}
29332},{"../errors":113,"./_stream_duplex":114,"inherits":112}],118:[function(require,module,exports){
29333(function (process,global){(function (){
29334// Copyright Joyent, Inc. and other Node contributors.
29335//
29336// Permission is hereby granted, free of charge, to any person obtaining a
29337// copy of this software and associated documentation files (the
29338// "Software"), to deal in the Software without restriction, including
29339// without limitation the rights to use, copy, modify, merge, publish,
29340// distribute, sublicense, and/or sell copies of the Software, and to permit
29341// persons to whom the Software is furnished to do so, subject to the
29342// following conditions:
29343//
29344// The above copyright notice and this permission notice shall be included
29345// in all copies or substantial portions of the Software.
29346//
29347// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
29348// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29349// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
29350// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
29351// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
29352// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
29353// USE OR OTHER DEALINGS IN THE SOFTWARE.
29354// A bit simpler than readable streams.
29355// Implement an async ._write(chunk, encoding, cb), and it'll handle all
29356// the drain event emission and buffering.
29357'use strict';
29358
29359module.exports = Writable;
29360/* <replacement> */
29361
29362function WriteReq(chunk, encoding, cb) {
29363 this.chunk = chunk;
29364 this.encoding = encoding;
29365 this.callback = cb;
29366 this.next = null;
29367} // It seems a linked list but it is not
29368// there will be only 2 of these for each stream
29369
29370
29371function CorkedRequest(state) {
29372 var _this = this;
29373
29374 this.next = null;
29375 this.entry = null;
29376
29377 this.finish = function () {
29378 onCorkedFinish(_this, state);
29379 };
29380}
29381/* </replacement> */
29382
29383/*<replacement>*/
29384
29385
29386var Duplex;
29387/*</replacement>*/
29388
29389Writable.WritableState = WritableState;
29390/*<replacement>*/
29391
29392var internalUtil = {
29393 deprecate: require('util-deprecate')
29394};
29395/*</replacement>*/
29396
29397/*<replacement>*/
29398
29399var Stream = require('./internal/streams/stream');
29400/*</replacement>*/
29401
29402
29403var Buffer = require('buffer').Buffer;
29404
29405var OurUint8Array = global.Uint8Array || function () {};
29406
29407function _uint8ArrayToBuffer(chunk) {
29408 return Buffer.from(chunk);
29409}
29410
29411function _isUint8Array(obj) {
29412 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
29413}
29414
29415var destroyImpl = require('./internal/streams/destroy');
29416
29417var _require = require('./internal/streams/state'),
29418 getHighWaterMark = _require.getHighWaterMark;
29419
29420var _require$codes = require('../errors').codes,
29421 ERR_INVALID_ARG_TYPE = _require$codes.ERR_INVALID_ARG_TYPE,
29422 ERR_METHOD_NOT_IMPLEMENTED = _require$codes.ERR_METHOD_NOT_IMPLEMENTED,
29423 ERR_MULTIPLE_CALLBACK = _require$codes.ERR_MULTIPLE_CALLBACK,
29424 ERR_STREAM_CANNOT_PIPE = _require$codes.ERR_STREAM_CANNOT_PIPE,
29425 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED,
29426 ERR_STREAM_NULL_VALUES = _require$codes.ERR_STREAM_NULL_VALUES,
29427 ERR_STREAM_WRITE_AFTER_END = _require$codes.ERR_STREAM_WRITE_AFTER_END,
29428 ERR_UNKNOWN_ENCODING = _require$codes.ERR_UNKNOWN_ENCODING;
29429
29430var errorOrDestroy = destroyImpl.errorOrDestroy;
29431
29432require('inherits')(Writable, Stream);
29433
29434function nop() {}
29435
29436function WritableState(options, stream, isDuplex) {
29437 Duplex = Duplex || require('./_stream_duplex');
29438 options = options || {}; // Duplex streams are both readable and writable, but share
29439 // the same options object.
29440 // However, some cases require setting options to different
29441 // values for the readable and the writable sides of the duplex stream,
29442 // e.g. options.readableObjectMode vs. options.writableObjectMode, etc.
29443
29444 if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof Duplex; // object stream flag to indicate whether or not this stream
29445 // contains buffers or objects.
29446
29447 this.objectMode = !!options.objectMode;
29448 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false
29449 // Note: 0 is a valid value, means that we always return false if
29450 // the entire buffer is not flushed immediately on write()
29451
29452 this.highWaterMark = getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex); // if _final has been called
29453
29454 this.finalCalled = false; // drain event flag.
29455
29456 this.needDrain = false; // at the start of calling end()
29457
29458 this.ending = false; // when end() has been called, and returned
29459
29460 this.ended = false; // when 'finish' is emitted
29461
29462 this.finished = false; // has it been destroyed
29463
29464 this.destroyed = false; // should we decode strings into buffers before passing to _write?
29465 // this is here so that some node-core streams can optimize string
29466 // handling at a lower level.
29467
29468 var noDecode = options.decodeStrings === false;
29469 this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string
29470 // encoding is 'binary' so we have to make this configurable.
29471 // Everything else in the universe uses 'utf8', though.
29472
29473 this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement
29474 // of how much we're waiting to get pushed to some underlying
29475 // socket or file.
29476
29477 this.length = 0; // a flag to see when we're in the middle of a write.
29478
29479 this.writing = false; // when true all writes will be buffered until .uncork() call
29480
29481 this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately,
29482 // or on a later tick. We set this to true at first, because any
29483 // actions that shouldn't happen until "later" should generally also
29484 // not happen before the first write call.
29485
29486 this.sync = true; // a flag to know if we're processing previously buffered items, which
29487 // may call the _write() callback in the same tick, so that we don't
29488 // end up in an overlapped onwrite situation.
29489
29490 this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb)
29491
29492 this.onwrite = function (er) {
29493 onwrite(stream, er);
29494 }; // the callback that the user supplies to write(chunk,encoding,cb)
29495
29496
29497 this.writecb = null; // the amount that is being written when _write is called.
29498
29499 this.writelen = 0;
29500 this.bufferedRequest = null;
29501 this.lastBufferedRequest = null; // number of pending user-supplied write callbacks
29502 // this must be 0 before 'finish' can be emitted
29503
29504 this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs
29505 // This is relevant for synchronous Transform streams
29506
29507 this.prefinished = false; // True if the error was already emitted and should not be thrown again
29508
29509 this.errorEmitted = false; // Should close be emitted on destroy. Defaults to true.
29510
29511 this.emitClose = options.emitClose !== false; // Should .destroy() be called after 'finish' (and potentially 'end')
29512
29513 this.autoDestroy = !!options.autoDestroy; // count buffered requests
29514
29515 this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always
29516 // one allocated and free to use, and we maintain at most two
29517
29518 this.corkedRequestsFree = new CorkedRequest(this);
29519}
29520
29521WritableState.prototype.getBuffer = function getBuffer() {
29522 var current = this.bufferedRequest;
29523 var out = [];
29524
29525 while (current) {
29526 out.push(current);
29527 current = current.next;
29528 }
29529
29530 return out;
29531};
29532
29533(function () {
29534 try {
29535 Object.defineProperty(WritableState.prototype, 'buffer', {
29536 get: internalUtil.deprecate(function writableStateBufferGetter() {
29537 return this.getBuffer();
29538 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
29539 });
29540 } catch (_) {}
29541})(); // Test _writableState for inheritance to account for Duplex streams,
29542// whose prototype chain only points to Readable.
29543
29544
29545var realHasInstance;
29546
29547if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
29548 realHasInstance = Function.prototype[Symbol.hasInstance];
29549 Object.defineProperty(Writable, Symbol.hasInstance, {
29550 value: function value(object) {
29551 if (realHasInstance.call(this, object)) return true;
29552 if (this !== Writable) return false;
29553 return object && object._writableState instanceof WritableState;
29554 }
29555 });
29556} else {
29557 realHasInstance = function realHasInstance(object) {
29558 return object instanceof this;
29559 };
29560}
29561
29562function Writable(options) {
29563 Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too.
29564 // `realHasInstance` is necessary because using plain `instanceof`
29565 // would return false, as no `_writableState` property is attached.
29566 // Trying to use the custom `instanceof` for Writable here will also break the
29567 // Node.js LazyTransform implementation, which has a non-trivial getter for
29568 // `_writableState` that would lead to infinite recursion.
29569 // Checking for a Stream.Duplex instance is faster here instead of inside
29570 // the WritableState constructor, at least with V8 6.5
29571
29572 var isDuplex = this instanceof Duplex;
29573 if (!isDuplex && !realHasInstance.call(Writable, this)) return new Writable(options);
29574 this._writableState = new WritableState(options, this, isDuplex); // legacy.
29575
29576 this.writable = true;
29577
29578 if (options) {
29579 if (typeof options.write === 'function') this._write = options.write;
29580 if (typeof options.writev === 'function') this._writev = options.writev;
29581 if (typeof options.destroy === 'function') this._destroy = options.destroy;
29582 if (typeof options.final === 'function') this._final = options.final;
29583 }
29584
29585 Stream.call(this);
29586} // Otherwise people can pipe Writable streams, which is just wrong.
29587
29588
29589Writable.prototype.pipe = function () {
29590 errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE());
29591};
29592
29593function writeAfterEnd(stream, cb) {
29594 var er = new ERR_STREAM_WRITE_AFTER_END(); // TODO: defer error events consistently everywhere, not just the cb
29595
29596 errorOrDestroy(stream, er);
29597 process.nextTick(cb, er);
29598} // Checks that a user-supplied chunk is valid, especially for the particular
29599// mode the stream is in. Currently this means that `null` is never accepted
29600// and undefined/non-string values are only allowed in object mode.
29601
29602
29603function validChunk(stream, state, chunk, cb) {
29604 var er;
29605
29606 if (chunk === null) {
29607 er = new ERR_STREAM_NULL_VALUES();
29608 } else if (typeof chunk !== 'string' && !state.objectMode) {
29609 er = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer'], chunk);
29610 }
29611
29612 if (er) {
29613 errorOrDestroy(stream, er);
29614 process.nextTick(cb, er);
29615 return false;
29616 }
29617
29618 return true;
29619}
29620
29621Writable.prototype.write = function (chunk, encoding, cb) {
29622 var state = this._writableState;
29623 var ret = false;
29624
29625 var isBuf = !state.objectMode && _isUint8Array(chunk);
29626
29627 if (isBuf && !Buffer.isBuffer(chunk)) {
29628 chunk = _uint8ArrayToBuffer(chunk);
29629 }
29630
29631 if (typeof encoding === 'function') {
29632 cb = encoding;
29633 encoding = null;
29634 }
29635
29636 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
29637 if (typeof cb !== 'function') cb = nop;
29638 if (state.ending) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
29639 state.pendingcb++;
29640 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
29641 }
29642 return ret;
29643};
29644
29645Writable.prototype.cork = function () {
29646 this._writableState.corked++;
29647};
29648
29649Writable.prototype.uncork = function () {
29650 var state = this._writableState;
29651
29652 if (state.corked) {
29653 state.corked--;
29654 if (!state.writing && !state.corked && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
29655 }
29656};
29657
29658Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
29659 // node::ParseEncoding() requires lower case.
29660 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
29661 if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new ERR_UNKNOWN_ENCODING(encoding);
29662 this._writableState.defaultEncoding = encoding;
29663 return this;
29664};
29665
29666Object.defineProperty(Writable.prototype, 'writableBuffer', {
29667 // making it explicit this property is not enumerable
29668 // because otherwise some prototype manipulation in
29669 // userland will fail
29670 enumerable: false,
29671 get: function get() {
29672 return this._writableState && this._writableState.getBuffer();
29673 }
29674});
29675
29676function decodeChunk(state, chunk, encoding) {
29677 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
29678 chunk = Buffer.from(chunk, encoding);
29679 }
29680
29681 return chunk;
29682}
29683
29684Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
29685 // making it explicit this property is not enumerable
29686 // because otherwise some prototype manipulation in
29687 // userland will fail
29688 enumerable: false,
29689 get: function get() {
29690 return this._writableState.highWaterMark;
29691 }
29692}); // if we're already writing something, then just put this
29693// in the queue, and wait our turn. Otherwise, call _write
29694// If we return false, then we need a drain event, so set that flag.
29695
29696function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
29697 if (!isBuf) {
29698 var newChunk = decodeChunk(state, chunk, encoding);
29699
29700 if (chunk !== newChunk) {
29701 isBuf = true;
29702 encoding = 'buffer';
29703 chunk = newChunk;
29704 }
29705 }
29706
29707 var len = state.objectMode ? 1 : chunk.length;
29708 state.length += len;
29709 var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false.
29710
29711 if (!ret) state.needDrain = true;
29712
29713 if (state.writing || state.corked) {
29714 var last = state.lastBufferedRequest;
29715 state.lastBufferedRequest = {
29716 chunk: chunk,
29717 encoding: encoding,
29718 isBuf: isBuf,
29719 callback: cb,
29720 next: null
29721 };
29722
29723 if (last) {
29724 last.next = state.lastBufferedRequest;
29725 } else {
29726 state.bufferedRequest = state.lastBufferedRequest;
29727 }
29728
29729 state.bufferedRequestCount += 1;
29730 } else {
29731 doWrite(stream, state, false, len, chunk, encoding, cb);
29732 }
29733
29734 return ret;
29735}
29736
29737function doWrite(stream, state, writev, len, chunk, encoding, cb) {
29738 state.writelen = len;
29739 state.writecb = cb;
29740 state.writing = true;
29741 state.sync = true;
29742 if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write'));else if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
29743 state.sync = false;
29744}
29745
29746function onwriteError(stream, state, sync, er, cb) {
29747 --state.pendingcb;
29748
29749 if (sync) {
29750 // defer the callback if we are being called synchronously
29751 // to avoid piling up things on the stack
29752 process.nextTick(cb, er); // this can emit finish, and it will always happen
29753 // after error
29754
29755 process.nextTick(finishMaybe, stream, state);
29756 stream._writableState.errorEmitted = true;
29757 errorOrDestroy(stream, er);
29758 } else {
29759 // the caller expect this to happen before if
29760 // it is async
29761 cb(er);
29762 stream._writableState.errorEmitted = true;
29763 errorOrDestroy(stream, er); // this can emit finish, but finish must
29764 // always follow error
29765
29766 finishMaybe(stream, state);
29767 }
29768}
29769
29770function onwriteStateUpdate(state) {
29771 state.writing = false;
29772 state.writecb = null;
29773 state.length -= state.writelen;
29774 state.writelen = 0;
29775}
29776
29777function onwrite(stream, er) {
29778 var state = stream._writableState;
29779 var sync = state.sync;
29780 var cb = state.writecb;
29781 if (typeof cb !== 'function') throw new ERR_MULTIPLE_CALLBACK();
29782 onwriteStateUpdate(state);
29783 if (er) onwriteError(stream, state, sync, er, cb);else {
29784 // Check if we're actually ready to finish, but don't emit yet
29785 var finished = needFinish(state) || stream.destroyed;
29786
29787 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
29788 clearBuffer(stream, state);
29789 }
29790
29791 if (sync) {
29792 process.nextTick(afterWrite, stream, state, finished, cb);
29793 } else {
29794 afterWrite(stream, state, finished, cb);
29795 }
29796 }
29797}
29798
29799function afterWrite(stream, state, finished, cb) {
29800 if (!finished) onwriteDrain(stream, state);
29801 state.pendingcb--;
29802 cb();
29803 finishMaybe(stream, state);
29804} // Must force callback to be called on nextTick, so that we don't
29805// emit 'drain' before the write() consumer gets the 'false' return
29806// value, and has a chance to attach a 'drain' listener.
29807
29808
29809function onwriteDrain(stream, state) {
29810 if (state.length === 0 && state.needDrain) {
29811 state.needDrain = false;
29812 stream.emit('drain');
29813 }
29814} // if there's something in the buffer waiting, then process it
29815
29816
29817function clearBuffer(stream, state) {
29818 state.bufferProcessing = true;
29819 var entry = state.bufferedRequest;
29820
29821 if (stream._writev && entry && entry.next) {
29822 // Fast case, write everything using _writev()
29823 var l = state.bufferedRequestCount;
29824 var buffer = new Array(l);
29825 var holder = state.corkedRequestsFree;
29826 holder.entry = entry;
29827 var count = 0;
29828 var allBuffers = true;
29829
29830 while (entry) {
29831 buffer[count] = entry;
29832 if (!entry.isBuf) allBuffers = false;
29833 entry = entry.next;
29834 count += 1;
29835 }
29836
29837 buffer.allBuffers = allBuffers;
29838 doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time
29839 // as the hot path ends with doWrite
29840
29841 state.pendingcb++;
29842 state.lastBufferedRequest = null;
29843
29844 if (holder.next) {
29845 state.corkedRequestsFree = holder.next;
29846 holder.next = null;
29847 } else {
29848 state.corkedRequestsFree = new CorkedRequest(state);
29849 }
29850
29851 state.bufferedRequestCount = 0;
29852 } else {
29853 // Slow case, write chunks one-by-one
29854 while (entry) {
29855 var chunk = entry.chunk;
29856 var encoding = entry.encoding;
29857 var cb = entry.callback;
29858 var len = state.objectMode ? 1 : chunk.length;
29859 doWrite(stream, state, false, len, chunk, encoding, cb);
29860 entry = entry.next;
29861 state.bufferedRequestCount--; // if we didn't call the onwrite immediately, then
29862 // it means that we need to wait until it does.
29863 // also, that means that the chunk and cb are currently
29864 // being processed, so move the buffer counter past them.
29865
29866 if (state.writing) {
29867 break;
29868 }
29869 }
29870
29871 if (entry === null) state.lastBufferedRequest = null;
29872 }
29873
29874 state.bufferedRequest = entry;
29875 state.bufferProcessing = false;
29876}
29877
29878Writable.prototype._write = function (chunk, encoding, cb) {
29879 cb(new ERR_METHOD_NOT_IMPLEMENTED('_write()'));
29880};
29881
29882Writable.prototype._writev = null;
29883
29884Writable.prototype.end = function (chunk, encoding, cb) {
29885 var state = this._writableState;
29886
29887 if (typeof chunk === 'function') {
29888 cb = chunk;
29889 chunk = null;
29890 encoding = null;
29891 } else if (typeof encoding === 'function') {
29892 cb = encoding;
29893 encoding = null;
29894 }
29895
29896 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks
29897
29898 if (state.corked) {
29899 state.corked = 1;
29900 this.uncork();
29901 } // ignore unnecessary end() calls.
29902
29903
29904 if (!state.ending) endWritable(this, state, cb);
29905 return this;
29906};
29907
29908Object.defineProperty(Writable.prototype, 'writableLength', {
29909 // making it explicit this property is not enumerable
29910 // because otherwise some prototype manipulation in
29911 // userland will fail
29912 enumerable: false,
29913 get: function get() {
29914 return this._writableState.length;
29915 }
29916});
29917
29918function needFinish(state) {
29919 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
29920}
29921
29922function callFinal(stream, state) {
29923 stream._final(function (err) {
29924 state.pendingcb--;
29925
29926 if (err) {
29927 errorOrDestroy(stream, err);
29928 }
29929
29930 state.prefinished = true;
29931 stream.emit('prefinish');
29932 finishMaybe(stream, state);
29933 });
29934}
29935
29936function prefinish(stream, state) {
29937 if (!state.prefinished && !state.finalCalled) {
29938 if (typeof stream._final === 'function' && !state.destroyed) {
29939 state.pendingcb++;
29940 state.finalCalled = true;
29941 process.nextTick(callFinal, stream, state);
29942 } else {
29943 state.prefinished = true;
29944 stream.emit('prefinish');
29945 }
29946 }
29947}
29948
29949function finishMaybe(stream, state) {
29950 var need = needFinish(state);
29951
29952 if (need) {
29953 prefinish(stream, state);
29954
29955 if (state.pendingcb === 0) {
29956 state.finished = true;
29957 stream.emit('finish');
29958
29959 if (state.autoDestroy) {
29960 // In case of duplex streams we need a way to detect
29961 // if the readable side is ready for autoDestroy as well
29962 var rState = stream._readableState;
29963
29964 if (!rState || rState.autoDestroy && rState.endEmitted) {
29965 stream.destroy();
29966 }
29967 }
29968 }
29969 }
29970
29971 return need;
29972}
29973
29974function endWritable(stream, state, cb) {
29975 state.ending = true;
29976 finishMaybe(stream, state);
29977
29978 if (cb) {
29979 if (state.finished) process.nextTick(cb);else stream.once('finish', cb);
29980 }
29981
29982 state.ended = true;
29983 stream.writable = false;
29984}
29985
29986function onCorkedFinish(corkReq, state, err) {
29987 var entry = corkReq.entry;
29988 corkReq.entry = null;
29989
29990 while (entry) {
29991 var cb = entry.callback;
29992 state.pendingcb--;
29993 cb(err);
29994 entry = entry.next;
29995 } // reuse the free corkReq.
29996
29997
29998 state.corkedRequestsFree.next = corkReq;
29999}
30000
30001Object.defineProperty(Writable.prototype, 'destroyed', {
30002 // making it explicit this property is not enumerable
30003 // because otherwise some prototype manipulation in
30004 // userland will fail
30005 enumerable: false,
30006 get: function get() {
30007 if (this._writableState === undefined) {
30008 return false;
30009 }
30010
30011 return this._writableState.destroyed;
30012 },
30013 set: function set(value) {
30014 // we ignore the value if the stream
30015 // has not been initialized yet
30016 if (!this._writableState) {
30017 return;
30018 } // backward compatibility, the user is explicitly
30019 // managing destroyed
30020
30021
30022 this._writableState.destroyed = value;
30023 }
30024});
30025Writable.prototype.destroy = destroyImpl.destroy;
30026Writable.prototype._undestroy = destroyImpl.undestroy;
30027
30028Writable.prototype._destroy = function (err, cb) {
30029 cb(err);
30030};
30031}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
30032},{"../errors":113,"./_stream_duplex":114,"./internal/streams/destroy":121,"./internal/streams/state":125,"./internal/streams/stream":126,"_process":228,"buffer":132,"inherits":112,"util-deprecate":272}],119:[function(require,module,exports){
30033(function (process){(function (){
30034'use strict';
30035
30036var _Object$setPrototypeO;
30037
30038function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
30039
30040var finished = require('./end-of-stream');
30041
30042var kLastResolve = Symbol('lastResolve');
30043var kLastReject = Symbol('lastReject');
30044var kError = Symbol('error');
30045var kEnded = Symbol('ended');
30046var kLastPromise = Symbol('lastPromise');
30047var kHandlePromise = Symbol('handlePromise');
30048var kStream = Symbol('stream');
30049
30050function createIterResult(value, done) {
30051 return {
30052 value: value,
30053 done: done
30054 };
30055}
30056
30057function readAndResolve(iter) {
30058 var resolve = iter[kLastResolve];
30059
30060 if (resolve !== null) {
30061 var data = iter[kStream].read(); // we defer if data is null
30062 // we can be expecting either 'end' or
30063 // 'error'
30064
30065 if (data !== null) {
30066 iter[kLastPromise] = null;
30067 iter[kLastResolve] = null;
30068 iter[kLastReject] = null;
30069 resolve(createIterResult(data, false));
30070 }
30071 }
30072}
30073
30074function onReadable(iter) {
30075 // we wait for the next tick, because it might
30076 // emit an error with process.nextTick
30077 process.nextTick(readAndResolve, iter);
30078}
30079
30080function wrapForNext(lastPromise, iter) {
30081 return function (resolve, reject) {
30082 lastPromise.then(function () {
30083 if (iter[kEnded]) {
30084 resolve(createIterResult(undefined, true));
30085 return;
30086 }
30087
30088 iter[kHandlePromise](resolve, reject);
30089 }, reject);
30090 };
30091}
30092
30093var AsyncIteratorPrototype = Object.getPrototypeOf(function () {});
30094var ReadableStreamAsyncIteratorPrototype = Object.setPrototypeOf((_Object$setPrototypeO = {
30095 get stream() {
30096 return this[kStream];
30097 },
30098
30099 next: function next() {
30100 var _this = this;
30101
30102 // if we have detected an error in the meanwhile
30103 // reject straight away
30104 var error = this[kError];
30105
30106 if (error !== null) {
30107 return Promise.reject(error);
30108 }
30109
30110 if (this[kEnded]) {
30111 return Promise.resolve(createIterResult(undefined, true));
30112 }
30113
30114 if (this[kStream].destroyed) {
30115 // We need to defer via nextTick because if .destroy(err) is
30116 // called, the error will be emitted via nextTick, and
30117 // we cannot guarantee that there is no error lingering around
30118 // waiting to be emitted.
30119 return new Promise(function (resolve, reject) {
30120 process.nextTick(function () {
30121 if (_this[kError]) {
30122 reject(_this[kError]);
30123 } else {
30124 resolve(createIterResult(undefined, true));
30125 }
30126 });
30127 });
30128 } // if we have multiple next() calls
30129 // we will wait for the previous Promise to finish
30130 // this logic is optimized to support for await loops,
30131 // where next() is only called once at a time
30132
30133
30134 var lastPromise = this[kLastPromise];
30135 var promise;
30136
30137 if (lastPromise) {
30138 promise = new Promise(wrapForNext(lastPromise, this));
30139 } else {
30140 // fast path needed to support multiple this.push()
30141 // without triggering the next() queue
30142 var data = this[kStream].read();
30143
30144 if (data !== null) {
30145 return Promise.resolve(createIterResult(data, false));
30146 }
30147
30148 promise = new Promise(this[kHandlePromise]);
30149 }
30150
30151 this[kLastPromise] = promise;
30152 return promise;
30153 }
30154}, _defineProperty(_Object$setPrototypeO, Symbol.asyncIterator, function () {
30155 return this;
30156}), _defineProperty(_Object$setPrototypeO, "return", function _return() {
30157 var _this2 = this;
30158
30159 // destroy(err, cb) is a private API
30160 // we can guarantee we have that here, because we control the
30161 // Readable class this is attached to
30162 return new Promise(function (resolve, reject) {
30163 _this2[kStream].destroy(null, function (err) {
30164 if (err) {
30165 reject(err);
30166 return;
30167 }
30168
30169 resolve(createIterResult(undefined, true));
30170 });
30171 });
30172}), _Object$setPrototypeO), AsyncIteratorPrototype);
30173
30174var createReadableStreamAsyncIterator = function createReadableStreamAsyncIterator(stream) {
30175 var _Object$create;
30176
30177 var iterator = Object.create(ReadableStreamAsyncIteratorPrototype, (_Object$create = {}, _defineProperty(_Object$create, kStream, {
30178 value: stream,
30179 writable: true
30180 }), _defineProperty(_Object$create, kLastResolve, {
30181 value: null,
30182 writable: true
30183 }), _defineProperty(_Object$create, kLastReject, {
30184 value: null,
30185 writable: true
30186 }), _defineProperty(_Object$create, kError, {
30187 value: null,
30188 writable: true
30189 }), _defineProperty(_Object$create, kEnded, {
30190 value: stream._readableState.endEmitted,
30191 writable: true
30192 }), _defineProperty(_Object$create, kHandlePromise, {
30193 value: function value(resolve, reject) {
30194 var data = iterator[kStream].read();
30195
30196 if (data) {
30197 iterator[kLastPromise] = null;
30198 iterator[kLastResolve] = null;
30199 iterator[kLastReject] = null;
30200 resolve(createIterResult(data, false));
30201 } else {
30202 iterator[kLastResolve] = resolve;
30203 iterator[kLastReject] = reject;
30204 }
30205 },
30206 writable: true
30207 }), _Object$create));
30208 iterator[kLastPromise] = null;
30209 finished(stream, function (err) {
30210 if (err && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') {
30211 var reject = iterator[kLastReject]; // reject if we are waiting for data in the Promise
30212 // returned by next() and store the error
30213
30214 if (reject !== null) {
30215 iterator[kLastPromise] = null;
30216 iterator[kLastResolve] = null;
30217 iterator[kLastReject] = null;
30218 reject(err);
30219 }
30220
30221 iterator[kError] = err;
30222 return;
30223 }
30224
30225 var resolve = iterator[kLastResolve];
30226
30227 if (resolve !== null) {
30228 iterator[kLastPromise] = null;
30229 iterator[kLastResolve] = null;
30230 iterator[kLastReject] = null;
30231 resolve(createIterResult(undefined, true));
30232 }
30233
30234 iterator[kEnded] = true;
30235 });
30236 stream.on('readable', onReadable.bind(null, iterator));
30237 return iterator;
30238};
30239
30240module.exports = createReadableStreamAsyncIterator;
30241}).call(this)}).call(this,require('_process'))
30242},{"./end-of-stream":122,"_process":228}],120:[function(require,module,exports){
30243'use strict';
30244
30245function ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }
30246
30247function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }
30248
30249function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }
30250
30251function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
30252
30253function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
30254
30255function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
30256
30257var _require = require('buffer'),
30258 Buffer = _require.Buffer;
30259
30260var _require2 = require('util'),
30261 inspect = _require2.inspect;
30262
30263var custom = inspect && inspect.custom || 'inspect';
30264
30265function copyBuffer(src, target, offset) {
30266 Buffer.prototype.copy.call(src, target, offset);
30267}
30268
30269module.exports =
30270/*#__PURE__*/
30271function () {
30272 function BufferList() {
30273 _classCallCheck(this, BufferList);
30274
30275 this.head = null;
30276 this.tail = null;
30277 this.length = 0;
30278 }
30279
30280 _createClass(BufferList, [{
30281 key: "push",
30282 value: function push(v) {
30283 var entry = {
30284 data: v,
30285 next: null
30286 };
30287 if (this.length > 0) this.tail.next = entry;else this.head = entry;
30288 this.tail = entry;
30289 ++this.length;
30290 }
30291 }, {
30292 key: "unshift",
30293 value: function unshift(v) {
30294 var entry = {
30295 data: v,
30296 next: this.head
30297 };
30298 if (this.length === 0) this.tail = entry;
30299 this.head = entry;
30300 ++this.length;
30301 }
30302 }, {
30303 key: "shift",
30304 value: function shift() {
30305 if (this.length === 0) return;
30306 var ret = this.head.data;
30307 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
30308 --this.length;
30309 return ret;
30310 }
30311 }, {
30312 key: "clear",
30313 value: function clear() {
30314 this.head = this.tail = null;
30315 this.length = 0;
30316 }
30317 }, {
30318 key: "join",
30319 value: function join(s) {
30320 if (this.length === 0) return '';
30321 var p = this.head;
30322 var ret = '' + p.data;
30323
30324 while (p = p.next) {
30325 ret += s + p.data;
30326 }
30327
30328 return ret;
30329 }
30330 }, {
30331 key: "concat",
30332 value: function concat(n) {
30333 if (this.length === 0) return Buffer.alloc(0);
30334 var ret = Buffer.allocUnsafe(n >>> 0);
30335 var p = this.head;
30336 var i = 0;
30337
30338 while (p) {
30339 copyBuffer(p.data, ret, i);
30340 i += p.data.length;
30341 p = p.next;
30342 }
30343
30344 return ret;
30345 } // Consumes a specified amount of bytes or characters from the buffered data.
30346
30347 }, {
30348 key: "consume",
30349 value: function consume(n, hasStrings) {
30350 var ret;
30351
30352 if (n < this.head.data.length) {
30353 // `slice` is the same for buffers and strings.
30354 ret = this.head.data.slice(0, n);
30355 this.head.data = this.head.data.slice(n);
30356 } else if (n === this.head.data.length) {
30357 // First chunk is a perfect match.
30358 ret = this.shift();
30359 } else {
30360 // Result spans more than one buffer.
30361 ret = hasStrings ? this._getString(n) : this._getBuffer(n);
30362 }
30363
30364 return ret;
30365 }
30366 }, {
30367 key: "first",
30368 value: function first() {
30369 return this.head.data;
30370 } // Consumes a specified amount of characters from the buffered data.
30371
30372 }, {
30373 key: "_getString",
30374 value: function _getString(n) {
30375 var p = this.head;
30376 var c = 1;
30377 var ret = p.data;
30378 n -= ret.length;
30379
30380 while (p = p.next) {
30381 var str = p.data;
30382 var nb = n > str.length ? str.length : n;
30383 if (nb === str.length) ret += str;else ret += str.slice(0, n);
30384 n -= nb;
30385
30386 if (n === 0) {
30387 if (nb === str.length) {
30388 ++c;
30389 if (p.next) this.head = p.next;else this.head = this.tail = null;
30390 } else {
30391 this.head = p;
30392 p.data = str.slice(nb);
30393 }
30394
30395 break;
30396 }
30397
30398 ++c;
30399 }
30400
30401 this.length -= c;
30402 return ret;
30403 } // Consumes a specified amount of bytes from the buffered data.
30404
30405 }, {
30406 key: "_getBuffer",
30407 value: function _getBuffer(n) {
30408 var ret = Buffer.allocUnsafe(n);
30409 var p = this.head;
30410 var c = 1;
30411 p.data.copy(ret);
30412 n -= p.data.length;
30413
30414 while (p = p.next) {
30415 var buf = p.data;
30416 var nb = n > buf.length ? buf.length : n;
30417 buf.copy(ret, ret.length - n, 0, nb);
30418 n -= nb;
30419
30420 if (n === 0) {
30421 if (nb === buf.length) {
30422 ++c;
30423 if (p.next) this.head = p.next;else this.head = this.tail = null;
30424 } else {
30425 this.head = p;
30426 p.data = buf.slice(nb);
30427 }
30428
30429 break;
30430 }
30431
30432 ++c;
30433 }
30434
30435 this.length -= c;
30436 return ret;
30437 } // Make sure the linked list only shows the minimal necessary information.
30438
30439 }, {
30440 key: custom,
30441 value: function value(_, options) {
30442 return inspect(this, _objectSpread({}, options, {
30443 // Only inspect one level.
30444 depth: 0,
30445 // It should not recurse.
30446 customInspect: false
30447 }));
30448 }
30449 }]);
30450
30451 return BufferList;
30452}();
30453},{"buffer":132,"util":82}],121:[function(require,module,exports){
30454(function (process){(function (){
30455'use strict'; // undocumented cb() API, needed for core, not for public API
30456
30457function destroy(err, cb) {
30458 var _this = this;
30459
30460 var readableDestroyed = this._readableState && this._readableState.destroyed;
30461 var writableDestroyed = this._writableState && this._writableState.destroyed;
30462
30463 if (readableDestroyed || writableDestroyed) {
30464 if (cb) {
30465 cb(err);
30466 } else if (err) {
30467 if (!this._writableState) {
30468 process.nextTick(emitErrorNT, this, err);
30469 } else if (!this._writableState.errorEmitted) {
30470 this._writableState.errorEmitted = true;
30471 process.nextTick(emitErrorNT, this, err);
30472 }
30473 }
30474
30475 return this;
30476 } // we set destroyed to true before firing error callbacks in order
30477 // to make it re-entrance safe in case destroy() is called within callbacks
30478
30479
30480 if (this._readableState) {
30481 this._readableState.destroyed = true;
30482 } // if this is a duplex stream mark the writable part as destroyed as well
30483
30484
30485 if (this._writableState) {
30486 this._writableState.destroyed = true;
30487 }
30488
30489 this._destroy(err || null, function (err) {
30490 if (!cb && err) {
30491 if (!_this._writableState) {
30492 process.nextTick(emitErrorAndCloseNT, _this, err);
30493 } else if (!_this._writableState.errorEmitted) {
30494 _this._writableState.errorEmitted = true;
30495 process.nextTick(emitErrorAndCloseNT, _this, err);
30496 } else {
30497 process.nextTick(emitCloseNT, _this);
30498 }
30499 } else if (cb) {
30500 process.nextTick(emitCloseNT, _this);
30501 cb(err);
30502 } else {
30503 process.nextTick(emitCloseNT, _this);
30504 }
30505 });
30506
30507 return this;
30508}
30509
30510function emitErrorAndCloseNT(self, err) {
30511 emitErrorNT(self, err);
30512 emitCloseNT(self);
30513}
30514
30515function emitCloseNT(self) {
30516 if (self._writableState && !self._writableState.emitClose) return;
30517 if (self._readableState && !self._readableState.emitClose) return;
30518 self.emit('close');
30519}
30520
30521function undestroy() {
30522 if (this._readableState) {
30523 this._readableState.destroyed = false;
30524 this._readableState.reading = false;
30525 this._readableState.ended = false;
30526 this._readableState.endEmitted = false;
30527 }
30528
30529 if (this._writableState) {
30530 this._writableState.destroyed = false;
30531 this._writableState.ended = false;
30532 this._writableState.ending = false;
30533 this._writableState.finalCalled = false;
30534 this._writableState.prefinished = false;
30535 this._writableState.finished = false;
30536 this._writableState.errorEmitted = false;
30537 }
30538}
30539
30540function emitErrorNT(self, err) {
30541 self.emit('error', err);
30542}
30543
30544function errorOrDestroy(stream, err) {
30545 // We have tests that rely on errors being emitted
30546 // in the same tick, so changing this is semver major.
30547 // For now when you opt-in to autoDestroy we allow
30548 // the error to be emitted nextTick. In a future
30549 // semver major update we should change the default to this.
30550 var rState = stream._readableState;
30551 var wState = stream._writableState;
30552 if (rState && rState.autoDestroy || wState && wState.autoDestroy) stream.destroy(err);else stream.emit('error', err);
30553}
30554
30555module.exports = {
30556 destroy: destroy,
30557 undestroy: undestroy,
30558 errorOrDestroy: errorOrDestroy
30559};
30560}).call(this)}).call(this,require('_process'))
30561},{"_process":228}],122:[function(require,module,exports){
30562// Ported from https://github.com/mafintosh/end-of-stream with
30563// permission from the author, Mathias Buus (@mafintosh).
30564'use strict';
30565
30566var ERR_STREAM_PREMATURE_CLOSE = require('../../../errors').codes.ERR_STREAM_PREMATURE_CLOSE;
30567
30568function once(callback) {
30569 var called = false;
30570 return function () {
30571 if (called) return;
30572 called = true;
30573
30574 for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
30575 args[_key] = arguments[_key];
30576 }
30577
30578 callback.apply(this, args);
30579 };
30580}
30581
30582function noop() {}
30583
30584function isRequest(stream) {
30585 return stream.setHeader && typeof stream.abort === 'function';
30586}
30587
30588function eos(stream, opts, callback) {
30589 if (typeof opts === 'function') return eos(stream, null, opts);
30590 if (!opts) opts = {};
30591 callback = once(callback || noop);
30592 var readable = opts.readable || opts.readable !== false && stream.readable;
30593 var writable = opts.writable || opts.writable !== false && stream.writable;
30594
30595 var onlegacyfinish = function onlegacyfinish() {
30596 if (!stream.writable) onfinish();
30597 };
30598
30599 var writableEnded = stream._writableState && stream._writableState.finished;
30600
30601 var onfinish = function onfinish() {
30602 writable = false;
30603 writableEnded = true;
30604 if (!readable) callback.call(stream);
30605 };
30606
30607 var readableEnded = stream._readableState && stream._readableState.endEmitted;
30608
30609 var onend = function onend() {
30610 readable = false;
30611 readableEnded = true;
30612 if (!writable) callback.call(stream);
30613 };
30614
30615 var onerror = function onerror(err) {
30616 callback.call(stream, err);
30617 };
30618
30619 var onclose = function onclose() {
30620 var err;
30621
30622 if (readable && !readableEnded) {
30623 if (!stream._readableState || !stream._readableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
30624 return callback.call(stream, err);
30625 }
30626
30627 if (writable && !writableEnded) {
30628 if (!stream._writableState || !stream._writableState.ended) err = new ERR_STREAM_PREMATURE_CLOSE();
30629 return callback.call(stream, err);
30630 }
30631 };
30632
30633 var onrequest = function onrequest() {
30634 stream.req.on('finish', onfinish);
30635 };
30636
30637 if (isRequest(stream)) {
30638 stream.on('complete', onfinish);
30639 stream.on('abort', onclose);
30640 if (stream.req) onrequest();else stream.on('request', onrequest);
30641 } else if (writable && !stream._writableState) {
30642 // legacy streams
30643 stream.on('end', onlegacyfinish);
30644 stream.on('close', onlegacyfinish);
30645 }
30646
30647 stream.on('end', onend);
30648 stream.on('finish', onfinish);
30649 if (opts.error !== false) stream.on('error', onerror);
30650 stream.on('close', onclose);
30651 return function () {
30652 stream.removeListener('complete', onfinish);
30653 stream.removeListener('abort', onclose);
30654 stream.removeListener('request', onrequest);
30655 if (stream.req) stream.req.removeListener('finish', onfinish);
30656 stream.removeListener('end', onlegacyfinish);
30657 stream.removeListener('close', onlegacyfinish);
30658 stream.removeListener('finish', onfinish);
30659 stream.removeListener('end', onend);
30660 stream.removeListener('error', onerror);
30661 stream.removeListener('close', onclose);
30662 };
30663}
30664
30665module.exports = eos;
30666},{"../../../errors":113}],123:[function(require,module,exports){
30667module.exports = function () {
30668 throw new Error('Readable.from is not available in the browser')
30669};
30670
30671},{}],124:[function(require,module,exports){
30672// Ported from https://github.com/mafintosh/pump with
30673// permission from the author, Mathias Buus (@mafintosh).
30674'use strict';
30675
30676var eos;
30677
30678function once(callback) {
30679 var called = false;
30680 return function () {
30681 if (called) return;
30682 called = true;
30683 callback.apply(void 0, arguments);
30684 };
30685}
30686
30687var _require$codes = require('../../../errors').codes,
30688 ERR_MISSING_ARGS = _require$codes.ERR_MISSING_ARGS,
30689 ERR_STREAM_DESTROYED = _require$codes.ERR_STREAM_DESTROYED;
30690
30691function noop(err) {
30692 // Rethrow the error if it exists to avoid swallowing it
30693 if (err) throw err;
30694}
30695
30696function isRequest(stream) {
30697 return stream.setHeader && typeof stream.abort === 'function';
30698}
30699
30700function destroyer(stream, reading, writing, callback) {
30701 callback = once(callback);
30702 var closed = false;
30703 stream.on('close', function () {
30704 closed = true;
30705 });
30706 if (eos === undefined) eos = require('./end-of-stream');
30707 eos(stream, {
30708 readable: reading,
30709 writable: writing
30710 }, function (err) {
30711 if (err) return callback(err);
30712 closed = true;
30713 callback();
30714 });
30715 var destroyed = false;
30716 return function (err) {
30717 if (closed) return;
30718 if (destroyed) return;
30719 destroyed = true; // request.destroy just do .end - .abort is what we want
30720
30721 if (isRequest(stream)) return stream.abort();
30722 if (typeof stream.destroy === 'function') return stream.destroy();
30723 callback(err || new ERR_STREAM_DESTROYED('pipe'));
30724 };
30725}
30726
30727function call(fn) {
30728 fn();
30729}
30730
30731function pipe(from, to) {
30732 return from.pipe(to);
30733}
30734
30735function popCallback(streams) {
30736 if (!streams.length) return noop;
30737 if (typeof streams[streams.length - 1] !== 'function') return noop;
30738 return streams.pop();
30739}
30740
30741function pipeline() {
30742 for (var _len = arguments.length, streams = new Array(_len), _key = 0; _key < _len; _key++) {
30743 streams[_key] = arguments[_key];
30744 }
30745
30746 var callback = popCallback(streams);
30747 if (Array.isArray(streams[0])) streams = streams[0];
30748
30749 if (streams.length < 2) {
30750 throw new ERR_MISSING_ARGS('streams');
30751 }
30752
30753 var error;
30754 var destroys = streams.map(function (stream, i) {
30755 var reading = i < streams.length - 1;
30756 var writing = i > 0;
30757 return destroyer(stream, reading, writing, function (err) {
30758 if (!error) error = err;
30759 if (err) destroys.forEach(call);
30760 if (reading) return;
30761 destroys.forEach(call);
30762 callback(error);
30763 });
30764 });
30765 return streams.reduce(pipe);
30766}
30767
30768module.exports = pipeline;
30769},{"../../../errors":113,"./end-of-stream":122}],125:[function(require,module,exports){
30770'use strict';
30771
30772var ERR_INVALID_OPT_VALUE = require('../../../errors').codes.ERR_INVALID_OPT_VALUE;
30773
30774function highWaterMarkFrom(options, isDuplex, duplexKey) {
30775 return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null;
30776}
30777
30778function getHighWaterMark(state, options, duplexKey, isDuplex) {
30779 var hwm = highWaterMarkFrom(options, isDuplex, duplexKey);
30780
30781 if (hwm != null) {
30782 if (!(isFinite(hwm) && Math.floor(hwm) === hwm) || hwm < 0) {
30783 var name = isDuplex ? duplexKey : 'highWaterMark';
30784 throw new ERR_INVALID_OPT_VALUE(name, hwm);
30785 }
30786
30787 return Math.floor(hwm);
30788 } // Default value
30789
30790
30791 return state.objectMode ? 16 : 16 * 1024;
30792}
30793
30794module.exports = {
30795 getHighWaterMark: getHighWaterMark
30796};
30797},{"../../../errors":113}],126:[function(require,module,exports){
30798module.exports = require('events').EventEmitter;
30799
30800},{"events":172}],127:[function(require,module,exports){
30801exports = module.exports = require('./lib/_stream_readable.js');
30802exports.Stream = exports;
30803exports.Readable = exports;
30804exports.Writable = require('./lib/_stream_writable.js');
30805exports.Duplex = require('./lib/_stream_duplex.js');
30806exports.Transform = require('./lib/_stream_transform.js');
30807exports.PassThrough = require('./lib/_stream_passthrough.js');
30808exports.finished = require('./lib/internal/streams/end-of-stream.js');
30809exports.pipeline = require('./lib/internal/streams/pipeline.js');
30810
30811},{"./lib/_stream_duplex.js":114,"./lib/_stream_passthrough.js":115,"./lib/_stream_readable.js":116,"./lib/_stream_transform.js":117,"./lib/_stream_writable.js":118,"./lib/internal/streams/end-of-stream.js":122,"./lib/internal/streams/pipeline.js":124}],128:[function(require,module,exports){
30812(function (global){(function (){
30813/*! https://mths.be/punycode v1.4.1 by @mathias */
30814;(function(root) {
30815
30816 /** Detect free variables */
30817 var freeExports = typeof exports == 'object' && exports &&
30818 !exports.nodeType && exports;
30819 var freeModule = typeof module == 'object' && module &&
30820 !module.nodeType && module;
30821 var freeGlobal = typeof global == 'object' && global;
30822 if (
30823 freeGlobal.global === freeGlobal ||
30824 freeGlobal.window === freeGlobal ||
30825 freeGlobal.self === freeGlobal
30826 ) {
30827 root = freeGlobal;
30828 }
30829
30830 /**
30831 * The `punycode` object.
30832 * @name punycode
30833 * @type Object
30834 */
30835 var punycode,
30836
30837 /** Highest positive signed 32-bit float value */
30838 maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1
30839
30840 /** Bootstring parameters */
30841 base = 36,
30842 tMin = 1,
30843 tMax = 26,
30844 skew = 38,
30845 damp = 700,
30846 initialBias = 72,
30847 initialN = 128, // 0x80
30848 delimiter = '-', // '\x2D'
30849
30850 /** Regular expressions */
30851 regexPunycode = /^xn--/,
30852 regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars
30853 regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators
30854
30855 /** Error messages */
30856 errors = {
30857 'overflow': 'Overflow: input needs wider integers to process',
30858 'not-basic': 'Illegal input >= 0x80 (not a basic code point)',
30859 'invalid-input': 'Invalid input'
30860 },
30861
30862 /** Convenience shortcuts */
30863 baseMinusTMin = base - tMin,
30864 floor = Math.floor,
30865 stringFromCharCode = String.fromCharCode,
30866
30867 /** Temporary variable */
30868 key;
30869
30870 /*--------------------------------------------------------------------------*/
30871
30872 /**
30873 * A generic error utility function.
30874 * @private
30875 * @param {String} type The error type.
30876 * @returns {Error} Throws a `RangeError` with the applicable error message.
30877 */
30878 function error(type) {
30879 throw new RangeError(errors[type]);
30880 }
30881
30882 /**
30883 * A generic `Array#map` utility function.
30884 * @private
30885 * @param {Array} array The array to iterate over.
30886 * @param {Function} callback The function that gets called for every array
30887 * item.
30888 * @returns {Array} A new array of values returned by the callback function.
30889 */
30890 function map(array, fn) {
30891 var length = array.length;
30892 var result = [];
30893 while (length--) {
30894 result[length] = fn(array[length]);
30895 }
30896 return result;
30897 }
30898
30899 /**
30900 * A simple `Array#map`-like wrapper to work with domain name strings or email
30901 * addresses.
30902 * @private
30903 * @param {String} domain The domain name or email address.
30904 * @param {Function} callback The function that gets called for every
30905 * character.
30906 * @returns {Array} A new string of characters returned by the callback
30907 * function.
30908 */
30909 function mapDomain(string, fn) {
30910 var parts = string.split('@');
30911 var result = '';
30912 if (parts.length > 1) {
30913 // In email addresses, only the domain name should be punycoded. Leave
30914 // the local part (i.e. everything up to `@`) intact.
30915 result = parts[0] + '@';
30916 string = parts[1];
30917 }
30918 // Avoid `split(regex)` for IE8 compatibility. See #17.
30919 string = string.replace(regexSeparators, '\x2E');
30920 var labels = string.split('.');
30921 var encoded = map(labels, fn).join('.');
30922 return result + encoded;
30923 }
30924
30925 /**
30926 * Creates an array containing the numeric code points of each Unicode
30927 * character in the string. While JavaScript uses UCS-2 internally,
30928 * this function will convert a pair of surrogate halves (each of which
30929 * UCS-2 exposes as separate characters) into a single code point,
30930 * matching UTF-16.
30931 * @see `punycode.ucs2.encode`
30932 * @see <https://mathiasbynens.be/notes/javascript-encoding>
30933 * @memberOf punycode.ucs2
30934 * @name decode
30935 * @param {String} string The Unicode input string (UCS-2).
30936 * @returns {Array} The new array of code points.
30937 */
30938 function ucs2decode(string) {
30939 var output = [],
30940 counter = 0,
30941 length = string.length,
30942 value,
30943 extra;
30944 while (counter < length) {
30945 value = string.charCodeAt(counter++);
30946 if (value >= 0xD800 && value <= 0xDBFF && counter < length) {
30947 // high surrogate, and there is a next character
30948 extra = string.charCodeAt(counter++);
30949 if ((extra & 0xFC00) == 0xDC00) { // low surrogate
30950 output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000);
30951 } else {
30952 // unmatched surrogate; only append this code unit, in case the next
30953 // code unit is the high surrogate of a surrogate pair
30954 output.push(value);
30955 counter--;
30956 }
30957 } else {
30958 output.push(value);
30959 }
30960 }
30961 return output;
30962 }
30963
30964 /**
30965 * Creates a string based on an array of numeric code points.
30966 * @see `punycode.ucs2.decode`
30967 * @memberOf punycode.ucs2
30968 * @name encode
30969 * @param {Array} codePoints The array of numeric code points.
30970 * @returns {String} The new Unicode string (UCS-2).
30971 */
30972 function ucs2encode(array) {
30973 return map(array, function(value) {
30974 var output = '';
30975 if (value > 0xFFFF) {
30976 value -= 0x10000;
30977 output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800);
30978 value = 0xDC00 | value & 0x3FF;
30979 }
30980 output += stringFromCharCode(value);
30981 return output;
30982 }).join('');
30983 }
30984
30985 /**
30986 * Converts a basic code point into a digit/integer.
30987 * @see `digitToBasic()`
30988 * @private
30989 * @param {Number} codePoint The basic numeric code point value.
30990 * @returns {Number} The numeric value of a basic code point (for use in
30991 * representing integers) in the range `0` to `base - 1`, or `base` if
30992 * the code point does not represent a value.
30993 */
30994 function basicToDigit(codePoint) {
30995 if (codePoint - 48 < 10) {
30996 return codePoint - 22;
30997 }
30998 if (codePoint - 65 < 26) {
30999 return codePoint - 65;
31000 }
31001 if (codePoint - 97 < 26) {
31002 return codePoint - 97;
31003 }
31004 return base;
31005 }
31006
31007 /**
31008 * Converts a digit/integer into a basic code point.
31009 * @see `basicToDigit()`
31010 * @private
31011 * @param {Number} digit The numeric value of a basic code point.
31012 * @returns {Number} The basic code point whose value (when used for
31013 * representing integers) is `digit`, which needs to be in the range
31014 * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is
31015 * used; else, the lowercase form is used. The behavior is undefined
31016 * if `flag` is non-zero and `digit` has no uppercase form.
31017 */
31018 function digitToBasic(digit, flag) {
31019 // 0..25 map to ASCII a..z or A..Z
31020 // 26..35 map to ASCII 0..9
31021 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5);
31022 }
31023
31024 /**
31025 * Bias adaptation function as per section 3.4 of RFC 3492.
31026 * https://tools.ietf.org/html/rfc3492#section-3.4
31027 * @private
31028 */
31029 function adapt(delta, numPoints, firstTime) {
31030 var k = 0;
31031 delta = firstTime ? floor(delta / damp) : delta >> 1;
31032 delta += floor(delta / numPoints);
31033 for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) {
31034 delta = floor(delta / baseMinusTMin);
31035 }
31036 return floor(k + (baseMinusTMin + 1) * delta / (delta + skew));
31037 }
31038
31039 /**
31040 * Converts a Punycode string of ASCII-only symbols to a string of Unicode
31041 * symbols.
31042 * @memberOf punycode
31043 * @param {String} input The Punycode string of ASCII-only symbols.
31044 * @returns {String} The resulting string of Unicode symbols.
31045 */
31046 function decode(input) {
31047 // Don't use UCS-2
31048 var output = [],
31049 inputLength = input.length,
31050 out,
31051 i = 0,
31052 n = initialN,
31053 bias = initialBias,
31054 basic,
31055 j,
31056 index,
31057 oldi,
31058 w,
31059 k,
31060 digit,
31061 t,
31062 /** Cached calculation results */
31063 baseMinusT;
31064
31065 // Handle the basic code points: let `basic` be the number of input code
31066 // points before the last delimiter, or `0` if there is none, then copy
31067 // the first basic code points to the output.
31068
31069 basic = input.lastIndexOf(delimiter);
31070 if (basic < 0) {
31071 basic = 0;
31072 }
31073
31074 for (j = 0; j < basic; ++j) {
31075 // if it's not a basic code point
31076 if (input.charCodeAt(j) >= 0x80) {
31077 error('not-basic');
31078 }
31079 output.push(input.charCodeAt(j));
31080 }
31081
31082 // Main decoding loop: start just after the last delimiter if any basic code
31083 // points were copied; start at the beginning otherwise.
31084
31085 for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) {
31086
31087 // `index` is the index of the next character to be consumed.
31088 // Decode a generalized variable-length integer into `delta`,
31089 // which gets added to `i`. The overflow checking is easier
31090 // if we increase `i` as we go, then subtract off its starting
31091 // value at the end to obtain `delta`.
31092 for (oldi = i, w = 1, k = base; /* no condition */; k += base) {
31093
31094 if (index >= inputLength) {
31095 error('invalid-input');
31096 }
31097
31098 digit = basicToDigit(input.charCodeAt(index++));
31099
31100 if (digit >= base || digit > floor((maxInt - i) / w)) {
31101 error('overflow');
31102 }
31103
31104 i += digit * w;
31105 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
31106
31107 if (digit < t) {
31108 break;
31109 }
31110
31111 baseMinusT = base - t;
31112 if (w > floor(maxInt / baseMinusT)) {
31113 error('overflow');
31114 }
31115
31116 w *= baseMinusT;
31117
31118 }
31119
31120 out = output.length + 1;
31121 bias = adapt(i - oldi, out, oldi == 0);
31122
31123 // `i` was supposed to wrap around from `out` to `0`,
31124 // incrementing `n` each time, so we'll fix that now:
31125 if (floor(i / out) > maxInt - n) {
31126 error('overflow');
31127 }
31128
31129 n += floor(i / out);
31130 i %= out;
31131
31132 // Insert `n` at position `i` of the output
31133 output.splice(i++, 0, n);
31134
31135 }
31136
31137 return ucs2encode(output);
31138 }
31139
31140 /**
31141 * Converts a string of Unicode symbols (e.g. a domain name label) to a
31142 * Punycode string of ASCII-only symbols.
31143 * @memberOf punycode
31144 * @param {String} input The string of Unicode symbols.
31145 * @returns {String} The resulting Punycode string of ASCII-only symbols.
31146 */
31147 function encode(input) {
31148 var n,
31149 delta,
31150 handledCPCount,
31151 basicLength,
31152 bias,
31153 j,
31154 m,
31155 q,
31156 k,
31157 t,
31158 currentValue,
31159 output = [],
31160 /** `inputLength` will hold the number of code points in `input`. */
31161 inputLength,
31162 /** Cached calculation results */
31163 handledCPCountPlusOne,
31164 baseMinusT,
31165 qMinusT;
31166
31167 // Convert the input in UCS-2 to Unicode
31168 input = ucs2decode(input);
31169
31170 // Cache the length
31171 inputLength = input.length;
31172
31173 // Initialize the state
31174 n = initialN;
31175 delta = 0;
31176 bias = initialBias;
31177
31178 // Handle the basic code points
31179 for (j = 0; j < inputLength; ++j) {
31180 currentValue = input[j];
31181 if (currentValue < 0x80) {
31182 output.push(stringFromCharCode(currentValue));
31183 }
31184 }
31185
31186 handledCPCount = basicLength = output.length;
31187
31188 // `handledCPCount` is the number of code points that have been handled;
31189 // `basicLength` is the number of basic code points.
31190
31191 // Finish the basic string - if it is not empty - with a delimiter
31192 if (basicLength) {
31193 output.push(delimiter);
31194 }
31195
31196 // Main encoding loop:
31197 while (handledCPCount < inputLength) {
31198
31199 // All non-basic code points < n have been handled already. Find the next
31200 // larger one:
31201 for (m = maxInt, j = 0; j < inputLength; ++j) {
31202 currentValue = input[j];
31203 if (currentValue >= n && currentValue < m) {
31204 m = currentValue;
31205 }
31206 }
31207
31208 // Increase `delta` enough to advance the decoder's <n,i> state to <m,0>,
31209 // but guard against overflow
31210 handledCPCountPlusOne = handledCPCount + 1;
31211 if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) {
31212 error('overflow');
31213 }
31214
31215 delta += (m - n) * handledCPCountPlusOne;
31216 n = m;
31217
31218 for (j = 0; j < inputLength; ++j) {
31219 currentValue = input[j];
31220
31221 if (currentValue < n && ++delta > maxInt) {
31222 error('overflow');
31223 }
31224
31225 if (currentValue == n) {
31226 // Represent delta as a generalized variable-length integer
31227 for (q = delta, k = base; /* no condition */; k += base) {
31228 t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias);
31229 if (q < t) {
31230 break;
31231 }
31232 qMinusT = q - t;
31233 baseMinusT = base - t;
31234 output.push(
31235 stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0))
31236 );
31237 q = floor(qMinusT / baseMinusT);
31238 }
31239
31240 output.push(stringFromCharCode(digitToBasic(q, 0)));
31241 bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength);
31242 delta = 0;
31243 ++handledCPCount;
31244 }
31245 }
31246
31247 ++delta;
31248 ++n;
31249
31250 }
31251 return output.join('');
31252 }
31253
31254 /**
31255 * Converts a Punycode string representing a domain name or an email address
31256 * to Unicode. Only the Punycoded parts of the input will be converted, i.e.
31257 * it doesn't matter if you call it on a string that has already been
31258 * converted to Unicode.
31259 * @memberOf punycode
31260 * @param {String} input The Punycoded domain name or email address to
31261 * convert to Unicode.
31262 * @returns {String} The Unicode representation of the given Punycode
31263 * string.
31264 */
31265 function toUnicode(input) {
31266 return mapDomain(input, function(string) {
31267 return regexPunycode.test(string)
31268 ? decode(string.slice(4).toLowerCase())
31269 : string;
31270 });
31271 }
31272
31273 /**
31274 * Converts a Unicode string representing a domain name or an email address to
31275 * Punycode. Only the non-ASCII parts of the domain name will be converted,
31276 * i.e. it doesn't matter if you call it with a domain that's already in
31277 * ASCII.
31278 * @memberOf punycode
31279 * @param {String} input The domain name or email address to convert, as a
31280 * Unicode string.
31281 * @returns {String} The Punycode representation of the given domain name or
31282 * email address.
31283 */
31284 function toASCII(input) {
31285 return mapDomain(input, function(string) {
31286 return regexNonASCII.test(string)
31287 ? 'xn--' + encode(string)
31288 : string;
31289 });
31290 }
31291
31292 /*--------------------------------------------------------------------------*/
31293
31294 /** Define the public API */
31295 punycode = {
31296 /**
31297 * A string representing the current Punycode.js version number.
31298 * @memberOf punycode
31299 * @type String
31300 */
31301 'version': '1.4.1',
31302 /**
31303 * An object of methods to convert from JavaScript's internal character
31304 * representation (UCS-2) to Unicode code points, and back.
31305 * @see <https://mathiasbynens.be/notes/javascript-encoding>
31306 * @memberOf punycode
31307 * @type Object
31308 */
31309 'ucs2': {
31310 'decode': ucs2decode,
31311 'encode': ucs2encode
31312 },
31313 'decode': decode,
31314 'encode': encode,
31315 'toASCII': toASCII,
31316 'toUnicode': toUnicode
31317 };
31318
31319 /** Expose `punycode` */
31320 // Some AMD build optimizers, like r.js, check for specific condition patterns
31321 // like the following:
31322 if (
31323 typeof define == 'function' &&
31324 typeof define.amd == 'object' &&
31325 define.amd
31326 ) {
31327 define('punycode', function() {
31328 return punycode;
31329 });
31330 } else if (freeExports && freeModule) {
31331 if (module.exports == freeExports) {
31332 // in Node.js, io.js, or RingoJS v0.8.0+
31333 freeModule.exports = punycode;
31334 } else {
31335 // in Narwhal or RingoJS v0.7.0-
31336 for (key in punycode) {
31337 punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]);
31338 }
31339 }
31340 } else {
31341 // in Rhino or a web browser
31342 root.punycode = punycode;
31343 }
31344
31345}(this));
31346
31347}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
31348},{}],129:[function(require,module,exports){
31349var basex = require('base-x')
31350var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
31351
31352module.exports = basex(ALPHABET)
31353
31354},{"base-x":65}],130:[function(require,module,exports){
31355module.exports = function(a, b) {
31356 if (typeof a.compare === 'function') return a.compare(b)
31357 if (a === b) return 0
31358
31359 var x = a.length
31360 var y = b.length
31361
31362 var i = 0
31363 var len = Math.min(x, y)
31364 while (i < len) {
31365 if (a[i] !== b[i]) break
31366
31367 ++i
31368 }
31369
31370 if (i !== len) {
31371 x = a[i]
31372 y = b[i]
31373 }
31374
31375 if (x < y) return -1
31376 if (y < x) return 1
31377 return 0
31378}
31379
31380
31381},{}],131:[function(require,module,exports){
31382(function (Buffer){(function (){
31383module.exports = function xor (a, b) {
31384 var length = Math.min(a.length, b.length)
31385 var buffer = new Buffer(length)
31386
31387 for (var i = 0; i < length; ++i) {
31388 buffer[i] = a[i] ^ b[i]
31389 }
31390
31391 return buffer
31392}
31393
31394}).call(this)}).call(this,require("buffer").Buffer)
31395},{"buffer":132}],132:[function(require,module,exports){
31396(function (Buffer){(function (){
31397/*!
31398 * The buffer module from node.js, for the browser.
31399 *
31400 * @author Feross Aboukhadijeh <https://feross.org>
31401 * @license MIT
31402 */
31403/* eslint-disable no-proto */
31404
31405'use strict'
31406
31407var base64 = require('base64-js')
31408var ieee754 = require('ieee754')
31409
31410exports.Buffer = Buffer
31411exports.SlowBuffer = SlowBuffer
31412exports.INSPECT_MAX_BYTES = 50
31413
31414var K_MAX_LENGTH = 0x7fffffff
31415exports.kMaxLength = K_MAX_LENGTH
31416
31417/**
31418 * If `Buffer.TYPED_ARRAY_SUPPORT`:
31419 * === true Use Uint8Array implementation (fastest)
31420 * === false Print warning and recommend using `buffer` v4.x which has an Object
31421 * implementation (most compatible, even IE6)
31422 *
31423 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
31424 * Opera 11.6+, iOS 4.2+.
31425 *
31426 * We report that the browser does not support typed arrays if the are not subclassable
31427 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
31428 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
31429 * for __proto__ and has a buggy typed array implementation.
31430 */
31431Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
31432
31433if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
31434 typeof console.error === 'function') {
31435 console.error(
31436 'This browser lacks typed array (Uint8Array) support which is required by ' +
31437 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
31438 )
31439}
31440
31441function typedArraySupport () {
31442 // Can typed array instances can be augmented?
31443 try {
31444 var arr = new Uint8Array(1)
31445 arr.__proto__ = { __proto__: Uint8Array.prototype, foo: function () { return 42 } }
31446 return arr.foo() === 42
31447 } catch (e) {
31448 return false
31449 }
31450}
31451
31452Object.defineProperty(Buffer.prototype, 'parent', {
31453 enumerable: true,
31454 get: function () {
31455 if (!Buffer.isBuffer(this)) return undefined
31456 return this.buffer
31457 }
31458})
31459
31460Object.defineProperty(Buffer.prototype, 'offset', {
31461 enumerable: true,
31462 get: function () {
31463 if (!Buffer.isBuffer(this)) return undefined
31464 return this.byteOffset
31465 }
31466})
31467
31468function createBuffer (length) {
31469 if (length > K_MAX_LENGTH) {
31470 throw new RangeError('The value "' + length + '" is invalid for option "size"')
31471 }
31472 // Return an augmented `Uint8Array` instance
31473 var buf = new Uint8Array(length)
31474 buf.__proto__ = Buffer.prototype
31475 return buf
31476}
31477
31478/**
31479 * The Buffer constructor returns instances of `Uint8Array` that have their
31480 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
31481 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
31482 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
31483 * returns a single octet.
31484 *
31485 * The `Uint8Array` prototype remains unmodified.
31486 */
31487
31488function Buffer (arg, encodingOrOffset, length) {
31489 // Common case.
31490 if (typeof arg === 'number') {
31491 if (typeof encodingOrOffset === 'string') {
31492 throw new TypeError(
31493 'The "string" argument must be of type string. Received type number'
31494 )
31495 }
31496 return allocUnsafe(arg)
31497 }
31498 return from(arg, encodingOrOffset, length)
31499}
31500
31501// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
31502if (typeof Symbol !== 'undefined' && Symbol.species != null &&
31503 Buffer[Symbol.species] === Buffer) {
31504 Object.defineProperty(Buffer, Symbol.species, {
31505 value: null,
31506 configurable: true,
31507 enumerable: false,
31508 writable: false
31509 })
31510}
31511
31512Buffer.poolSize = 8192 // not used by this implementation
31513
31514function from (value, encodingOrOffset, length) {
31515 if (typeof value === 'string') {
31516 return fromString(value, encodingOrOffset)
31517 }
31518
31519 if (ArrayBuffer.isView(value)) {
31520 return fromArrayLike(value)
31521 }
31522
31523 if (value == null) {
31524 throw TypeError(
31525 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
31526 'or Array-like Object. Received type ' + (typeof value)
31527 )
31528 }
31529
31530 if (isInstance(value, ArrayBuffer) ||
31531 (value && isInstance(value.buffer, ArrayBuffer))) {
31532 return fromArrayBuffer(value, encodingOrOffset, length)
31533 }
31534
31535 if (typeof value === 'number') {
31536 throw new TypeError(
31537 'The "value" argument must not be of type number. Received type number'
31538 )
31539 }
31540
31541 var valueOf = value.valueOf && value.valueOf()
31542 if (valueOf != null && valueOf !== value) {
31543 return Buffer.from(valueOf, encodingOrOffset, length)
31544 }
31545
31546 var b = fromObject(value)
31547 if (b) return b
31548
31549 if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null &&
31550 typeof value[Symbol.toPrimitive] === 'function') {
31551 return Buffer.from(
31552 value[Symbol.toPrimitive]('string'), encodingOrOffset, length
31553 )
31554 }
31555
31556 throw new TypeError(
31557 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' +
31558 'or Array-like Object. Received type ' + (typeof value)
31559 )
31560}
31561
31562/**
31563 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
31564 * if value is a number.
31565 * Buffer.from(str[, encoding])
31566 * Buffer.from(array)
31567 * Buffer.from(buffer)
31568 * Buffer.from(arrayBuffer[, byteOffset[, length]])
31569 **/
31570Buffer.from = function (value, encodingOrOffset, length) {
31571 return from(value, encodingOrOffset, length)
31572}
31573
31574// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
31575// https://github.com/feross/buffer/pull/148
31576Buffer.prototype.__proto__ = Uint8Array.prototype
31577Buffer.__proto__ = Uint8Array
31578
31579function assertSize (size) {
31580 if (typeof size !== 'number') {
31581 throw new TypeError('"size" argument must be of type number')
31582 } else if (size < 0) {
31583 throw new RangeError('The value "' + size + '" is invalid for option "size"')
31584 }
31585}
31586
31587function alloc (size, fill, encoding) {
31588 assertSize(size)
31589 if (size <= 0) {
31590 return createBuffer(size)
31591 }
31592 if (fill !== undefined) {
31593 // Only pay attention to encoding if it's a string. This
31594 // prevents accidentally sending in a number that would
31595 // be interpretted as a start offset.
31596 return typeof encoding === 'string'
31597 ? createBuffer(size).fill(fill, encoding)
31598 : createBuffer(size).fill(fill)
31599 }
31600 return createBuffer(size)
31601}
31602
31603/**
31604 * Creates a new filled Buffer instance.
31605 * alloc(size[, fill[, encoding]])
31606 **/
31607Buffer.alloc = function (size, fill, encoding) {
31608 return alloc(size, fill, encoding)
31609}
31610
31611function allocUnsafe (size) {
31612 assertSize(size)
31613 return createBuffer(size < 0 ? 0 : checked(size) | 0)
31614}
31615
31616/**
31617 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
31618 * */
31619Buffer.allocUnsafe = function (size) {
31620 return allocUnsafe(size)
31621}
31622/**
31623 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
31624 */
31625Buffer.allocUnsafeSlow = function (size) {
31626 return allocUnsafe(size)
31627}
31628
31629function fromString (string, encoding) {
31630 if (typeof encoding !== 'string' || encoding === '') {
31631 encoding = 'utf8'
31632 }
31633
31634 if (!Buffer.isEncoding(encoding)) {
31635 throw new TypeError('Unknown encoding: ' + encoding)
31636 }
31637
31638 var length = byteLength(string, encoding) | 0
31639 var buf = createBuffer(length)
31640
31641 var actual = buf.write(string, encoding)
31642
31643 if (actual !== length) {
31644 // Writing a hex string, for example, that contains invalid characters will
31645 // cause everything after the first invalid character to be ignored. (e.g.
31646 // 'abxxcd' will be treated as 'ab')
31647 buf = buf.slice(0, actual)
31648 }
31649
31650 return buf
31651}
31652
31653function fromArrayLike (array) {
31654 var length = array.length < 0 ? 0 : checked(array.length) | 0
31655 var buf = createBuffer(length)
31656 for (var i = 0; i < length; i += 1) {
31657 buf[i] = array[i] & 255
31658 }
31659 return buf
31660}
31661
31662function fromArrayBuffer (array, byteOffset, length) {
31663 if (byteOffset < 0 || array.byteLength < byteOffset) {
31664 throw new RangeError('"offset" is outside of buffer bounds')
31665 }
31666
31667 if (array.byteLength < byteOffset + (length || 0)) {
31668 throw new RangeError('"length" is outside of buffer bounds')
31669 }
31670
31671 var buf
31672 if (byteOffset === undefined && length === undefined) {
31673 buf = new Uint8Array(array)
31674 } else if (length === undefined) {
31675 buf = new Uint8Array(array, byteOffset)
31676 } else {
31677 buf = new Uint8Array(array, byteOffset, length)
31678 }
31679
31680 // Return an augmented `Uint8Array` instance
31681 buf.__proto__ = Buffer.prototype
31682 return buf
31683}
31684
31685function fromObject (obj) {
31686 if (Buffer.isBuffer(obj)) {
31687 var len = checked(obj.length) | 0
31688 var buf = createBuffer(len)
31689
31690 if (buf.length === 0) {
31691 return buf
31692 }
31693
31694 obj.copy(buf, 0, 0, len)
31695 return buf
31696 }
31697
31698 if (obj.length !== undefined) {
31699 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
31700 return createBuffer(0)
31701 }
31702 return fromArrayLike(obj)
31703 }
31704
31705 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
31706 return fromArrayLike(obj.data)
31707 }
31708}
31709
31710function checked (length) {
31711 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
31712 // length is NaN (which is otherwise coerced to zero.)
31713 if (length >= K_MAX_LENGTH) {
31714 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
31715 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
31716 }
31717 return length | 0
31718}
31719
31720function SlowBuffer (length) {
31721 if (+length != length) { // eslint-disable-line eqeqeq
31722 length = 0
31723 }
31724 return Buffer.alloc(+length)
31725}
31726
31727Buffer.isBuffer = function isBuffer (b) {
31728 return b != null && b._isBuffer === true &&
31729 b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false
31730}
31731
31732Buffer.compare = function compare (a, b) {
31733 if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength)
31734 if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength)
31735 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
31736 throw new TypeError(
31737 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array'
31738 )
31739 }
31740
31741 if (a === b) return 0
31742
31743 var x = a.length
31744 var y = b.length
31745
31746 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
31747 if (a[i] !== b[i]) {
31748 x = a[i]
31749 y = b[i]
31750 break
31751 }
31752 }
31753
31754 if (x < y) return -1
31755 if (y < x) return 1
31756 return 0
31757}
31758
31759Buffer.isEncoding = function isEncoding (encoding) {
31760 switch (String(encoding).toLowerCase()) {
31761 case 'hex':
31762 case 'utf8':
31763 case 'utf-8':
31764 case 'ascii':
31765 case 'latin1':
31766 case 'binary':
31767 case 'base64':
31768 case 'ucs2':
31769 case 'ucs-2':
31770 case 'utf16le':
31771 case 'utf-16le':
31772 return true
31773 default:
31774 return false
31775 }
31776}
31777
31778Buffer.concat = function concat (list, length) {
31779 if (!Array.isArray(list)) {
31780 throw new TypeError('"list" argument must be an Array of Buffers')
31781 }
31782
31783 if (list.length === 0) {
31784 return Buffer.alloc(0)
31785 }
31786
31787 var i
31788 if (length === undefined) {
31789 length = 0
31790 for (i = 0; i < list.length; ++i) {
31791 length += list[i].length
31792 }
31793 }
31794
31795 var buffer = Buffer.allocUnsafe(length)
31796 var pos = 0
31797 for (i = 0; i < list.length; ++i) {
31798 var buf = list[i]
31799 if (isInstance(buf, Uint8Array)) {
31800 buf = Buffer.from(buf)
31801 }
31802 if (!Buffer.isBuffer(buf)) {
31803 throw new TypeError('"list" argument must be an Array of Buffers')
31804 }
31805 buf.copy(buffer, pos)
31806 pos += buf.length
31807 }
31808 return buffer
31809}
31810
31811function byteLength (string, encoding) {
31812 if (Buffer.isBuffer(string)) {
31813 return string.length
31814 }
31815 if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) {
31816 return string.byteLength
31817 }
31818 if (typeof string !== 'string') {
31819 throw new TypeError(
31820 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' +
31821 'Received type ' + typeof string
31822 )
31823 }
31824
31825 var len = string.length
31826 var mustMatch = (arguments.length > 2 && arguments[2] === true)
31827 if (!mustMatch && len === 0) return 0
31828
31829 // Use a for loop to avoid recursion
31830 var loweredCase = false
31831 for (;;) {
31832 switch (encoding) {
31833 case 'ascii':
31834 case 'latin1':
31835 case 'binary':
31836 return len
31837 case 'utf8':
31838 case 'utf-8':
31839 return utf8ToBytes(string).length
31840 case 'ucs2':
31841 case 'ucs-2':
31842 case 'utf16le':
31843 case 'utf-16le':
31844 return len * 2
31845 case 'hex':
31846 return len >>> 1
31847 case 'base64':
31848 return base64ToBytes(string).length
31849 default:
31850 if (loweredCase) {
31851 return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8
31852 }
31853 encoding = ('' + encoding).toLowerCase()
31854 loweredCase = true
31855 }
31856 }
31857}
31858Buffer.byteLength = byteLength
31859
31860function slowToString (encoding, start, end) {
31861 var loweredCase = false
31862
31863 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
31864 // property of a typed array.
31865
31866 // This behaves neither like String nor Uint8Array in that we set start/end
31867 // to their upper/lower bounds if the value passed is out of range.
31868 // undefined is handled specially as per ECMA-262 6th Edition,
31869 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
31870 if (start === undefined || start < 0) {
31871 start = 0
31872 }
31873 // Return early if start > this.length. Done here to prevent potential uint32
31874 // coercion fail below.
31875 if (start > this.length) {
31876 return ''
31877 }
31878
31879 if (end === undefined || end > this.length) {
31880 end = this.length
31881 }
31882
31883 if (end <= 0) {
31884 return ''
31885 }
31886
31887 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
31888 end >>>= 0
31889 start >>>= 0
31890
31891 if (end <= start) {
31892 return ''
31893 }
31894
31895 if (!encoding) encoding = 'utf8'
31896
31897 while (true) {
31898 switch (encoding) {
31899 case 'hex':
31900 return hexSlice(this, start, end)
31901
31902 case 'utf8':
31903 case 'utf-8':
31904 return utf8Slice(this, start, end)
31905
31906 case 'ascii':
31907 return asciiSlice(this, start, end)
31908
31909 case 'latin1':
31910 case 'binary':
31911 return latin1Slice(this, start, end)
31912
31913 case 'base64':
31914 return base64Slice(this, start, end)
31915
31916 case 'ucs2':
31917 case 'ucs-2':
31918 case 'utf16le':
31919 case 'utf-16le':
31920 return utf16leSlice(this, start, end)
31921
31922 default:
31923 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
31924 encoding = (encoding + '').toLowerCase()
31925 loweredCase = true
31926 }
31927 }
31928}
31929
31930// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
31931// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
31932// reliably in a browserify context because there could be multiple different
31933// copies of the 'buffer' package in use. This method works even for Buffer
31934// instances that were created from another copy of the `buffer` package.
31935// See: https://github.com/feross/buffer/issues/154
31936Buffer.prototype._isBuffer = true
31937
31938function swap (b, n, m) {
31939 var i = b[n]
31940 b[n] = b[m]
31941 b[m] = i
31942}
31943
31944Buffer.prototype.swap16 = function swap16 () {
31945 var len = this.length
31946 if (len % 2 !== 0) {
31947 throw new RangeError('Buffer size must be a multiple of 16-bits')
31948 }
31949 for (var i = 0; i < len; i += 2) {
31950 swap(this, i, i + 1)
31951 }
31952 return this
31953}
31954
31955Buffer.prototype.swap32 = function swap32 () {
31956 var len = this.length
31957 if (len % 4 !== 0) {
31958 throw new RangeError('Buffer size must be a multiple of 32-bits')
31959 }
31960 for (var i = 0; i < len; i += 4) {
31961 swap(this, i, i + 3)
31962 swap(this, i + 1, i + 2)
31963 }
31964 return this
31965}
31966
31967Buffer.prototype.swap64 = function swap64 () {
31968 var len = this.length
31969 if (len % 8 !== 0) {
31970 throw new RangeError('Buffer size must be a multiple of 64-bits')
31971 }
31972 for (var i = 0; i < len; i += 8) {
31973 swap(this, i, i + 7)
31974 swap(this, i + 1, i + 6)
31975 swap(this, i + 2, i + 5)
31976 swap(this, i + 3, i + 4)
31977 }
31978 return this
31979}
31980
31981Buffer.prototype.toString = function toString () {
31982 var length = this.length
31983 if (length === 0) return ''
31984 if (arguments.length === 0) return utf8Slice(this, 0, length)
31985 return slowToString.apply(this, arguments)
31986}
31987
31988Buffer.prototype.toLocaleString = Buffer.prototype.toString
31989
31990Buffer.prototype.equals = function equals (b) {
31991 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
31992 if (this === b) return true
31993 return Buffer.compare(this, b) === 0
31994}
31995
31996Buffer.prototype.inspect = function inspect () {
31997 var str = ''
31998 var max = exports.INSPECT_MAX_BYTES
31999 str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim()
32000 if (this.length > max) str += ' ... '
32001 return '<Buffer ' + str + '>'
32002}
32003
32004Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
32005 if (isInstance(target, Uint8Array)) {
32006 target = Buffer.from(target, target.offset, target.byteLength)
32007 }
32008 if (!Buffer.isBuffer(target)) {
32009 throw new TypeError(
32010 'The "target" argument must be one of type Buffer or Uint8Array. ' +
32011 'Received type ' + (typeof target)
32012 )
32013 }
32014
32015 if (start === undefined) {
32016 start = 0
32017 }
32018 if (end === undefined) {
32019 end = target ? target.length : 0
32020 }
32021 if (thisStart === undefined) {
32022 thisStart = 0
32023 }
32024 if (thisEnd === undefined) {
32025 thisEnd = this.length
32026 }
32027
32028 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
32029 throw new RangeError('out of range index')
32030 }
32031
32032 if (thisStart >= thisEnd && start >= end) {
32033 return 0
32034 }
32035 if (thisStart >= thisEnd) {
32036 return -1
32037 }
32038 if (start >= end) {
32039 return 1
32040 }
32041
32042 start >>>= 0
32043 end >>>= 0
32044 thisStart >>>= 0
32045 thisEnd >>>= 0
32046
32047 if (this === target) return 0
32048
32049 var x = thisEnd - thisStart
32050 var y = end - start
32051 var len = Math.min(x, y)
32052
32053 var thisCopy = this.slice(thisStart, thisEnd)
32054 var targetCopy = target.slice(start, end)
32055
32056 for (var i = 0; i < len; ++i) {
32057 if (thisCopy[i] !== targetCopy[i]) {
32058 x = thisCopy[i]
32059 y = targetCopy[i]
32060 break
32061 }
32062 }
32063
32064 if (x < y) return -1
32065 if (y < x) return 1
32066 return 0
32067}
32068
32069// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
32070// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
32071//
32072// Arguments:
32073// - buffer - a Buffer to search
32074// - val - a string, Buffer, or number
32075// - byteOffset - an index into `buffer`; will be clamped to an int32
32076// - encoding - an optional encoding, relevant is val is a string
32077// - dir - true for indexOf, false for lastIndexOf
32078function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
32079 // Empty buffer means no match
32080 if (buffer.length === 0) return -1
32081
32082 // Normalize byteOffset
32083 if (typeof byteOffset === 'string') {
32084 encoding = byteOffset
32085 byteOffset = 0
32086 } else if (byteOffset > 0x7fffffff) {
32087 byteOffset = 0x7fffffff
32088 } else if (byteOffset < -0x80000000) {
32089 byteOffset = -0x80000000
32090 }
32091 byteOffset = +byteOffset // Coerce to Number.
32092 if (numberIsNaN(byteOffset)) {
32093 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
32094 byteOffset = dir ? 0 : (buffer.length - 1)
32095 }
32096
32097 // Normalize byteOffset: negative offsets start from the end of the buffer
32098 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
32099 if (byteOffset >= buffer.length) {
32100 if (dir) return -1
32101 else byteOffset = buffer.length - 1
32102 } else if (byteOffset < 0) {
32103 if (dir) byteOffset = 0
32104 else return -1
32105 }
32106
32107 // Normalize val
32108 if (typeof val === 'string') {
32109 val = Buffer.from(val, encoding)
32110 }
32111
32112 // Finally, search either indexOf (if dir is true) or lastIndexOf
32113 if (Buffer.isBuffer(val)) {
32114 // Special case: looking for empty string/buffer always fails
32115 if (val.length === 0) {
32116 return -1
32117 }
32118 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
32119 } else if (typeof val === 'number') {
32120 val = val & 0xFF // Search for a byte value [0-255]
32121 if (typeof Uint8Array.prototype.indexOf === 'function') {
32122 if (dir) {
32123 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
32124 } else {
32125 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
32126 }
32127 }
32128 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
32129 }
32130
32131 throw new TypeError('val must be string, number or Buffer')
32132}
32133
32134function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
32135 var indexSize = 1
32136 var arrLength = arr.length
32137 var valLength = val.length
32138
32139 if (encoding !== undefined) {
32140 encoding = String(encoding).toLowerCase()
32141 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
32142 encoding === 'utf16le' || encoding === 'utf-16le') {
32143 if (arr.length < 2 || val.length < 2) {
32144 return -1
32145 }
32146 indexSize = 2
32147 arrLength /= 2
32148 valLength /= 2
32149 byteOffset /= 2
32150 }
32151 }
32152
32153 function read (buf, i) {
32154 if (indexSize === 1) {
32155 return buf[i]
32156 } else {
32157 return buf.readUInt16BE(i * indexSize)
32158 }
32159 }
32160
32161 var i
32162 if (dir) {
32163 var foundIndex = -1
32164 for (i = byteOffset; i < arrLength; i++) {
32165 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
32166 if (foundIndex === -1) foundIndex = i
32167 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
32168 } else {
32169 if (foundIndex !== -1) i -= i - foundIndex
32170 foundIndex = -1
32171 }
32172 }
32173 } else {
32174 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
32175 for (i = byteOffset; i >= 0; i--) {
32176 var found = true
32177 for (var j = 0; j < valLength; j++) {
32178 if (read(arr, i + j) !== read(val, j)) {
32179 found = false
32180 break
32181 }
32182 }
32183 if (found) return i
32184 }
32185 }
32186
32187 return -1
32188}
32189
32190Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
32191 return this.indexOf(val, byteOffset, encoding) !== -1
32192}
32193
32194Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
32195 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
32196}
32197
32198Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
32199 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
32200}
32201
32202function hexWrite (buf, string, offset, length) {
32203 offset = Number(offset) || 0
32204 var remaining = buf.length - offset
32205 if (!length) {
32206 length = remaining
32207 } else {
32208 length = Number(length)
32209 if (length > remaining) {
32210 length = remaining
32211 }
32212 }
32213
32214 var strLen = string.length
32215
32216 if (length > strLen / 2) {
32217 length = strLen / 2
32218 }
32219 for (var i = 0; i < length; ++i) {
32220 var parsed = parseInt(string.substr(i * 2, 2), 16)
32221 if (numberIsNaN(parsed)) return i
32222 buf[offset + i] = parsed
32223 }
32224 return i
32225}
32226
32227function utf8Write (buf, string, offset, length) {
32228 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
32229}
32230
32231function asciiWrite (buf, string, offset, length) {
32232 return blitBuffer(asciiToBytes(string), buf, offset, length)
32233}
32234
32235function latin1Write (buf, string, offset, length) {
32236 return asciiWrite(buf, string, offset, length)
32237}
32238
32239function base64Write (buf, string, offset, length) {
32240 return blitBuffer(base64ToBytes(string), buf, offset, length)
32241}
32242
32243function ucs2Write (buf, string, offset, length) {
32244 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
32245}
32246
32247Buffer.prototype.write = function write (string, offset, length, encoding) {
32248 // Buffer#write(string)
32249 if (offset === undefined) {
32250 encoding = 'utf8'
32251 length = this.length
32252 offset = 0
32253 // Buffer#write(string, encoding)
32254 } else if (length === undefined && typeof offset === 'string') {
32255 encoding = offset
32256 length = this.length
32257 offset = 0
32258 // Buffer#write(string, offset[, length][, encoding])
32259 } else if (isFinite(offset)) {
32260 offset = offset >>> 0
32261 if (isFinite(length)) {
32262 length = length >>> 0
32263 if (encoding === undefined) encoding = 'utf8'
32264 } else {
32265 encoding = length
32266 length = undefined
32267 }
32268 } else {
32269 throw new Error(
32270 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
32271 )
32272 }
32273
32274 var remaining = this.length - offset
32275 if (length === undefined || length > remaining) length = remaining
32276
32277 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
32278 throw new RangeError('Attempt to write outside buffer bounds')
32279 }
32280
32281 if (!encoding) encoding = 'utf8'
32282
32283 var loweredCase = false
32284 for (;;) {
32285 switch (encoding) {
32286 case 'hex':
32287 return hexWrite(this, string, offset, length)
32288
32289 case 'utf8':
32290 case 'utf-8':
32291 return utf8Write(this, string, offset, length)
32292
32293 case 'ascii':
32294 return asciiWrite(this, string, offset, length)
32295
32296 case 'latin1':
32297 case 'binary':
32298 return latin1Write(this, string, offset, length)
32299
32300 case 'base64':
32301 // Warning: maxLength not taken into account in base64Write
32302 return base64Write(this, string, offset, length)
32303
32304 case 'ucs2':
32305 case 'ucs-2':
32306 case 'utf16le':
32307 case 'utf-16le':
32308 return ucs2Write(this, string, offset, length)
32309
32310 default:
32311 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
32312 encoding = ('' + encoding).toLowerCase()
32313 loweredCase = true
32314 }
32315 }
32316}
32317
32318Buffer.prototype.toJSON = function toJSON () {
32319 return {
32320 type: 'Buffer',
32321 data: Array.prototype.slice.call(this._arr || this, 0)
32322 }
32323}
32324
32325function base64Slice (buf, start, end) {
32326 if (start === 0 && end === buf.length) {
32327 return base64.fromByteArray(buf)
32328 } else {
32329 return base64.fromByteArray(buf.slice(start, end))
32330 }
32331}
32332
32333function utf8Slice (buf, start, end) {
32334 end = Math.min(buf.length, end)
32335 var res = []
32336
32337 var i = start
32338 while (i < end) {
32339 var firstByte = buf[i]
32340 var codePoint = null
32341 var bytesPerSequence = (firstByte > 0xEF) ? 4
32342 : (firstByte > 0xDF) ? 3
32343 : (firstByte > 0xBF) ? 2
32344 : 1
32345
32346 if (i + bytesPerSequence <= end) {
32347 var secondByte, thirdByte, fourthByte, tempCodePoint
32348
32349 switch (bytesPerSequence) {
32350 case 1:
32351 if (firstByte < 0x80) {
32352 codePoint = firstByte
32353 }
32354 break
32355 case 2:
32356 secondByte = buf[i + 1]
32357 if ((secondByte & 0xC0) === 0x80) {
32358 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
32359 if (tempCodePoint > 0x7F) {
32360 codePoint = tempCodePoint
32361 }
32362 }
32363 break
32364 case 3:
32365 secondByte = buf[i + 1]
32366 thirdByte = buf[i + 2]
32367 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
32368 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
32369 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
32370 codePoint = tempCodePoint
32371 }
32372 }
32373 break
32374 case 4:
32375 secondByte = buf[i + 1]
32376 thirdByte = buf[i + 2]
32377 fourthByte = buf[i + 3]
32378 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
32379 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
32380 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
32381 codePoint = tempCodePoint
32382 }
32383 }
32384 }
32385 }
32386
32387 if (codePoint === null) {
32388 // we did not generate a valid codePoint so insert a
32389 // replacement char (U+FFFD) and advance only 1 byte
32390 codePoint = 0xFFFD
32391 bytesPerSequence = 1
32392 } else if (codePoint > 0xFFFF) {
32393 // encode to utf16 (surrogate pair dance)
32394 codePoint -= 0x10000
32395 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
32396 codePoint = 0xDC00 | codePoint & 0x3FF
32397 }
32398
32399 res.push(codePoint)
32400 i += bytesPerSequence
32401 }
32402
32403 return decodeCodePointsArray(res)
32404}
32405
32406// Based on http://stackoverflow.com/a/22747272/680742, the browser with
32407// the lowest limit is Chrome, with 0x10000 args.
32408// We go 1 magnitude less, for safety
32409var MAX_ARGUMENTS_LENGTH = 0x1000
32410
32411function decodeCodePointsArray (codePoints) {
32412 var len = codePoints.length
32413 if (len <= MAX_ARGUMENTS_LENGTH) {
32414 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
32415 }
32416
32417 // Decode in chunks to avoid "call stack size exceeded".
32418 var res = ''
32419 var i = 0
32420 while (i < len) {
32421 res += String.fromCharCode.apply(
32422 String,
32423 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
32424 )
32425 }
32426 return res
32427}
32428
32429function asciiSlice (buf, start, end) {
32430 var ret = ''
32431 end = Math.min(buf.length, end)
32432
32433 for (var i = start; i < end; ++i) {
32434 ret += String.fromCharCode(buf[i] & 0x7F)
32435 }
32436 return ret
32437}
32438
32439function latin1Slice (buf, start, end) {
32440 var ret = ''
32441 end = Math.min(buf.length, end)
32442
32443 for (var i = start; i < end; ++i) {
32444 ret += String.fromCharCode(buf[i])
32445 }
32446 return ret
32447}
32448
32449function hexSlice (buf, start, end) {
32450 var len = buf.length
32451
32452 if (!start || start < 0) start = 0
32453 if (!end || end < 0 || end > len) end = len
32454
32455 var out = ''
32456 for (var i = start; i < end; ++i) {
32457 out += toHex(buf[i])
32458 }
32459 return out
32460}
32461
32462function utf16leSlice (buf, start, end) {
32463 var bytes = buf.slice(start, end)
32464 var res = ''
32465 for (var i = 0; i < bytes.length; i += 2) {
32466 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
32467 }
32468 return res
32469}
32470
32471Buffer.prototype.slice = function slice (start, end) {
32472 var len = this.length
32473 start = ~~start
32474 end = end === undefined ? len : ~~end
32475
32476 if (start < 0) {
32477 start += len
32478 if (start < 0) start = 0
32479 } else if (start > len) {
32480 start = len
32481 }
32482
32483 if (end < 0) {
32484 end += len
32485 if (end < 0) end = 0
32486 } else if (end > len) {
32487 end = len
32488 }
32489
32490 if (end < start) end = start
32491
32492 var newBuf = this.subarray(start, end)
32493 // Return an augmented `Uint8Array` instance
32494 newBuf.__proto__ = Buffer.prototype
32495 return newBuf
32496}
32497
32498/*
32499 * Need to make sure that buffer isn't trying to write out of bounds.
32500 */
32501function checkOffset (offset, ext, length) {
32502 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
32503 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
32504}
32505
32506Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
32507 offset = offset >>> 0
32508 byteLength = byteLength >>> 0
32509 if (!noAssert) checkOffset(offset, byteLength, this.length)
32510
32511 var val = this[offset]
32512 var mul = 1
32513 var i = 0
32514 while (++i < byteLength && (mul *= 0x100)) {
32515 val += this[offset + i] * mul
32516 }
32517
32518 return val
32519}
32520
32521Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
32522 offset = offset >>> 0
32523 byteLength = byteLength >>> 0
32524 if (!noAssert) {
32525 checkOffset(offset, byteLength, this.length)
32526 }
32527
32528 var val = this[offset + --byteLength]
32529 var mul = 1
32530 while (byteLength > 0 && (mul *= 0x100)) {
32531 val += this[offset + --byteLength] * mul
32532 }
32533
32534 return val
32535}
32536
32537Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
32538 offset = offset >>> 0
32539 if (!noAssert) checkOffset(offset, 1, this.length)
32540 return this[offset]
32541}
32542
32543Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
32544 offset = offset >>> 0
32545 if (!noAssert) checkOffset(offset, 2, this.length)
32546 return this[offset] | (this[offset + 1] << 8)
32547}
32548
32549Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
32550 offset = offset >>> 0
32551 if (!noAssert) checkOffset(offset, 2, this.length)
32552 return (this[offset] << 8) | this[offset + 1]
32553}
32554
32555Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
32556 offset = offset >>> 0
32557 if (!noAssert) checkOffset(offset, 4, this.length)
32558
32559 return ((this[offset]) |
32560 (this[offset + 1] << 8) |
32561 (this[offset + 2] << 16)) +
32562 (this[offset + 3] * 0x1000000)
32563}
32564
32565Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
32566 offset = offset >>> 0
32567 if (!noAssert) checkOffset(offset, 4, this.length)
32568
32569 return (this[offset] * 0x1000000) +
32570 ((this[offset + 1] << 16) |
32571 (this[offset + 2] << 8) |
32572 this[offset + 3])
32573}
32574
32575Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
32576 offset = offset >>> 0
32577 byteLength = byteLength >>> 0
32578 if (!noAssert) checkOffset(offset, byteLength, this.length)
32579
32580 var val = this[offset]
32581 var mul = 1
32582 var i = 0
32583 while (++i < byteLength && (mul *= 0x100)) {
32584 val += this[offset + i] * mul
32585 }
32586 mul *= 0x80
32587
32588 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
32589
32590 return val
32591}
32592
32593Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
32594 offset = offset >>> 0
32595 byteLength = byteLength >>> 0
32596 if (!noAssert) checkOffset(offset, byteLength, this.length)
32597
32598 var i = byteLength
32599 var mul = 1
32600 var val = this[offset + --i]
32601 while (i > 0 && (mul *= 0x100)) {
32602 val += this[offset + --i] * mul
32603 }
32604 mul *= 0x80
32605
32606 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
32607
32608 return val
32609}
32610
32611Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
32612 offset = offset >>> 0
32613 if (!noAssert) checkOffset(offset, 1, this.length)
32614 if (!(this[offset] & 0x80)) return (this[offset])
32615 return ((0xff - this[offset] + 1) * -1)
32616}
32617
32618Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
32619 offset = offset >>> 0
32620 if (!noAssert) checkOffset(offset, 2, this.length)
32621 var val = this[offset] | (this[offset + 1] << 8)
32622 return (val & 0x8000) ? val | 0xFFFF0000 : val
32623}
32624
32625Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
32626 offset = offset >>> 0
32627 if (!noAssert) checkOffset(offset, 2, this.length)
32628 var val = this[offset + 1] | (this[offset] << 8)
32629 return (val & 0x8000) ? val | 0xFFFF0000 : val
32630}
32631
32632Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
32633 offset = offset >>> 0
32634 if (!noAssert) checkOffset(offset, 4, this.length)
32635
32636 return (this[offset]) |
32637 (this[offset + 1] << 8) |
32638 (this[offset + 2] << 16) |
32639 (this[offset + 3] << 24)
32640}
32641
32642Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
32643 offset = offset >>> 0
32644 if (!noAssert) checkOffset(offset, 4, this.length)
32645
32646 return (this[offset] << 24) |
32647 (this[offset + 1] << 16) |
32648 (this[offset + 2] << 8) |
32649 (this[offset + 3])
32650}
32651
32652Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
32653 offset = offset >>> 0
32654 if (!noAssert) checkOffset(offset, 4, this.length)
32655 return ieee754.read(this, offset, true, 23, 4)
32656}
32657
32658Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
32659 offset = offset >>> 0
32660 if (!noAssert) checkOffset(offset, 4, this.length)
32661 return ieee754.read(this, offset, false, 23, 4)
32662}
32663
32664Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
32665 offset = offset >>> 0
32666 if (!noAssert) checkOffset(offset, 8, this.length)
32667 return ieee754.read(this, offset, true, 52, 8)
32668}
32669
32670Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
32671 offset = offset >>> 0
32672 if (!noAssert) checkOffset(offset, 8, this.length)
32673 return ieee754.read(this, offset, false, 52, 8)
32674}
32675
32676function checkInt (buf, value, offset, ext, max, min) {
32677 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
32678 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
32679 if (offset + ext > buf.length) throw new RangeError('Index out of range')
32680}
32681
32682Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
32683 value = +value
32684 offset = offset >>> 0
32685 byteLength = byteLength >>> 0
32686 if (!noAssert) {
32687 var maxBytes = Math.pow(2, 8 * byteLength) - 1
32688 checkInt(this, value, offset, byteLength, maxBytes, 0)
32689 }
32690
32691 var mul = 1
32692 var i = 0
32693 this[offset] = value & 0xFF
32694 while (++i < byteLength && (mul *= 0x100)) {
32695 this[offset + i] = (value / mul) & 0xFF
32696 }
32697
32698 return offset + byteLength
32699}
32700
32701Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
32702 value = +value
32703 offset = offset >>> 0
32704 byteLength = byteLength >>> 0
32705 if (!noAssert) {
32706 var maxBytes = Math.pow(2, 8 * byteLength) - 1
32707 checkInt(this, value, offset, byteLength, maxBytes, 0)
32708 }
32709
32710 var i = byteLength - 1
32711 var mul = 1
32712 this[offset + i] = value & 0xFF
32713 while (--i >= 0 && (mul *= 0x100)) {
32714 this[offset + i] = (value / mul) & 0xFF
32715 }
32716
32717 return offset + byteLength
32718}
32719
32720Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
32721 value = +value
32722 offset = offset >>> 0
32723 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
32724 this[offset] = (value & 0xff)
32725 return offset + 1
32726}
32727
32728Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
32729 value = +value
32730 offset = offset >>> 0
32731 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
32732 this[offset] = (value & 0xff)
32733 this[offset + 1] = (value >>> 8)
32734 return offset + 2
32735}
32736
32737Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
32738 value = +value
32739 offset = offset >>> 0
32740 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
32741 this[offset] = (value >>> 8)
32742 this[offset + 1] = (value & 0xff)
32743 return offset + 2
32744}
32745
32746Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
32747 value = +value
32748 offset = offset >>> 0
32749 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
32750 this[offset + 3] = (value >>> 24)
32751 this[offset + 2] = (value >>> 16)
32752 this[offset + 1] = (value >>> 8)
32753 this[offset] = (value & 0xff)
32754 return offset + 4
32755}
32756
32757Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
32758 value = +value
32759 offset = offset >>> 0
32760 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
32761 this[offset] = (value >>> 24)
32762 this[offset + 1] = (value >>> 16)
32763 this[offset + 2] = (value >>> 8)
32764 this[offset + 3] = (value & 0xff)
32765 return offset + 4
32766}
32767
32768Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
32769 value = +value
32770 offset = offset >>> 0
32771 if (!noAssert) {
32772 var limit = Math.pow(2, (8 * byteLength) - 1)
32773
32774 checkInt(this, value, offset, byteLength, limit - 1, -limit)
32775 }
32776
32777 var i = 0
32778 var mul = 1
32779 var sub = 0
32780 this[offset] = value & 0xFF
32781 while (++i < byteLength && (mul *= 0x100)) {
32782 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
32783 sub = 1
32784 }
32785 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
32786 }
32787
32788 return offset + byteLength
32789}
32790
32791Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
32792 value = +value
32793 offset = offset >>> 0
32794 if (!noAssert) {
32795 var limit = Math.pow(2, (8 * byteLength) - 1)
32796
32797 checkInt(this, value, offset, byteLength, limit - 1, -limit)
32798 }
32799
32800 var i = byteLength - 1
32801 var mul = 1
32802 var sub = 0
32803 this[offset + i] = value & 0xFF
32804 while (--i >= 0 && (mul *= 0x100)) {
32805 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
32806 sub = 1
32807 }
32808 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
32809 }
32810
32811 return offset + byteLength
32812}
32813
32814Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
32815 value = +value
32816 offset = offset >>> 0
32817 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
32818 if (value < 0) value = 0xff + value + 1
32819 this[offset] = (value & 0xff)
32820 return offset + 1
32821}
32822
32823Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
32824 value = +value
32825 offset = offset >>> 0
32826 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
32827 this[offset] = (value & 0xff)
32828 this[offset + 1] = (value >>> 8)
32829 return offset + 2
32830}
32831
32832Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
32833 value = +value
32834 offset = offset >>> 0
32835 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
32836 this[offset] = (value >>> 8)
32837 this[offset + 1] = (value & 0xff)
32838 return offset + 2
32839}
32840
32841Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
32842 value = +value
32843 offset = offset >>> 0
32844 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
32845 this[offset] = (value & 0xff)
32846 this[offset + 1] = (value >>> 8)
32847 this[offset + 2] = (value >>> 16)
32848 this[offset + 3] = (value >>> 24)
32849 return offset + 4
32850}
32851
32852Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
32853 value = +value
32854 offset = offset >>> 0
32855 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
32856 if (value < 0) value = 0xffffffff + value + 1
32857 this[offset] = (value >>> 24)
32858 this[offset + 1] = (value >>> 16)
32859 this[offset + 2] = (value >>> 8)
32860 this[offset + 3] = (value & 0xff)
32861 return offset + 4
32862}
32863
32864function checkIEEE754 (buf, value, offset, ext, max, min) {
32865 if (offset + ext > buf.length) throw new RangeError('Index out of range')
32866 if (offset < 0) throw new RangeError('Index out of range')
32867}
32868
32869function writeFloat (buf, value, offset, littleEndian, noAssert) {
32870 value = +value
32871 offset = offset >>> 0
32872 if (!noAssert) {
32873 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
32874 }
32875 ieee754.write(buf, value, offset, littleEndian, 23, 4)
32876 return offset + 4
32877}
32878
32879Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
32880 return writeFloat(this, value, offset, true, noAssert)
32881}
32882
32883Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
32884 return writeFloat(this, value, offset, false, noAssert)
32885}
32886
32887function writeDouble (buf, value, offset, littleEndian, noAssert) {
32888 value = +value
32889 offset = offset >>> 0
32890 if (!noAssert) {
32891 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
32892 }
32893 ieee754.write(buf, value, offset, littleEndian, 52, 8)
32894 return offset + 8
32895}
32896
32897Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
32898 return writeDouble(this, value, offset, true, noAssert)
32899}
32900
32901Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
32902 return writeDouble(this, value, offset, false, noAssert)
32903}
32904
32905// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
32906Buffer.prototype.copy = function copy (target, targetStart, start, end) {
32907 if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer')
32908 if (!start) start = 0
32909 if (!end && end !== 0) end = this.length
32910 if (targetStart >= target.length) targetStart = target.length
32911 if (!targetStart) targetStart = 0
32912 if (end > 0 && end < start) end = start
32913
32914 // Copy 0 bytes; we're done
32915 if (end === start) return 0
32916 if (target.length === 0 || this.length === 0) return 0
32917
32918 // Fatal error conditions
32919 if (targetStart < 0) {
32920 throw new RangeError('targetStart out of bounds')
32921 }
32922 if (start < 0 || start >= this.length) throw new RangeError('Index out of range')
32923 if (end < 0) throw new RangeError('sourceEnd out of bounds')
32924
32925 // Are we oob?
32926 if (end > this.length) end = this.length
32927 if (target.length - targetStart < end - start) {
32928 end = target.length - targetStart + start
32929 }
32930
32931 var len = end - start
32932
32933 if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') {
32934 // Use built-in when available, missing from IE11
32935 this.copyWithin(targetStart, start, end)
32936 } else if (this === target && start < targetStart && targetStart < end) {
32937 // descending copy from end
32938 for (var i = len - 1; i >= 0; --i) {
32939 target[i + targetStart] = this[i + start]
32940 }
32941 } else {
32942 Uint8Array.prototype.set.call(
32943 target,
32944 this.subarray(start, end),
32945 targetStart
32946 )
32947 }
32948
32949 return len
32950}
32951
32952// Usage:
32953// buffer.fill(number[, offset[, end]])
32954// buffer.fill(buffer[, offset[, end]])
32955// buffer.fill(string[, offset[, end]][, encoding])
32956Buffer.prototype.fill = function fill (val, start, end, encoding) {
32957 // Handle string cases:
32958 if (typeof val === 'string') {
32959 if (typeof start === 'string') {
32960 encoding = start
32961 start = 0
32962 end = this.length
32963 } else if (typeof end === 'string') {
32964 encoding = end
32965 end = this.length
32966 }
32967 if (encoding !== undefined && typeof encoding !== 'string') {
32968 throw new TypeError('encoding must be a string')
32969 }
32970 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
32971 throw new TypeError('Unknown encoding: ' + encoding)
32972 }
32973 if (val.length === 1) {
32974 var code = val.charCodeAt(0)
32975 if ((encoding === 'utf8' && code < 128) ||
32976 encoding === 'latin1') {
32977 // Fast path: If `val` fits into a single byte, use that numeric value.
32978 val = code
32979 }
32980 }
32981 } else if (typeof val === 'number') {
32982 val = val & 255
32983 }
32984
32985 // Invalid ranges are not set to a default, so can range check early.
32986 if (start < 0 || this.length < start || this.length < end) {
32987 throw new RangeError('Out of range index')
32988 }
32989
32990 if (end <= start) {
32991 return this
32992 }
32993
32994 start = start >>> 0
32995 end = end === undefined ? this.length : end >>> 0
32996
32997 if (!val) val = 0
32998
32999 var i
33000 if (typeof val === 'number') {
33001 for (i = start; i < end; ++i) {
33002 this[i] = val
33003 }
33004 } else {
33005 var bytes = Buffer.isBuffer(val)
33006 ? val
33007 : Buffer.from(val, encoding)
33008 var len = bytes.length
33009 if (len === 0) {
33010 throw new TypeError('The value "' + val +
33011 '" is invalid for argument "value"')
33012 }
33013 for (i = 0; i < end - start; ++i) {
33014 this[i + start] = bytes[i % len]
33015 }
33016 }
33017
33018 return this
33019}
33020
33021// HELPER FUNCTIONS
33022// ================
33023
33024var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
33025
33026function base64clean (str) {
33027 // Node takes equal signs as end of the Base64 encoding
33028 str = str.split('=')[0]
33029 // Node strips out invalid characters like \n and \t from the string, base64-js does not
33030 str = str.trim().replace(INVALID_BASE64_RE, '')
33031 // Node converts strings with length < 2 to ''
33032 if (str.length < 2) return ''
33033 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
33034 while (str.length % 4 !== 0) {
33035 str = str + '='
33036 }
33037 return str
33038}
33039
33040function toHex (n) {
33041 if (n < 16) return '0' + n.toString(16)
33042 return n.toString(16)
33043}
33044
33045function utf8ToBytes (string, units) {
33046 units = units || Infinity
33047 var codePoint
33048 var length = string.length
33049 var leadSurrogate = null
33050 var bytes = []
33051
33052 for (var i = 0; i < length; ++i) {
33053 codePoint = string.charCodeAt(i)
33054
33055 // is surrogate component
33056 if (codePoint > 0xD7FF && codePoint < 0xE000) {
33057 // last char was a lead
33058 if (!leadSurrogate) {
33059 // no lead yet
33060 if (codePoint > 0xDBFF) {
33061 // unexpected trail
33062 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
33063 continue
33064 } else if (i + 1 === length) {
33065 // unpaired lead
33066 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
33067 continue
33068 }
33069
33070 // valid lead
33071 leadSurrogate = codePoint
33072
33073 continue
33074 }
33075
33076 // 2 leads in a row
33077 if (codePoint < 0xDC00) {
33078 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
33079 leadSurrogate = codePoint
33080 continue
33081 }
33082
33083 // valid surrogate pair
33084 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
33085 } else if (leadSurrogate) {
33086 // valid bmp char, but last char was a lead
33087 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
33088 }
33089
33090 leadSurrogate = null
33091
33092 // encode utf8
33093 if (codePoint < 0x80) {
33094 if ((units -= 1) < 0) break
33095 bytes.push(codePoint)
33096 } else if (codePoint < 0x800) {
33097 if ((units -= 2) < 0) break
33098 bytes.push(
33099 codePoint >> 0x6 | 0xC0,
33100 codePoint & 0x3F | 0x80
33101 )
33102 } else if (codePoint < 0x10000) {
33103 if ((units -= 3) < 0) break
33104 bytes.push(
33105 codePoint >> 0xC | 0xE0,
33106 codePoint >> 0x6 & 0x3F | 0x80,
33107 codePoint & 0x3F | 0x80
33108 )
33109 } else if (codePoint < 0x110000) {
33110 if ((units -= 4) < 0) break
33111 bytes.push(
33112 codePoint >> 0x12 | 0xF0,
33113 codePoint >> 0xC & 0x3F | 0x80,
33114 codePoint >> 0x6 & 0x3F | 0x80,
33115 codePoint & 0x3F | 0x80
33116 )
33117 } else {
33118 throw new Error('Invalid code point')
33119 }
33120 }
33121
33122 return bytes
33123}
33124
33125function asciiToBytes (str) {
33126 var byteArray = []
33127 for (var i = 0; i < str.length; ++i) {
33128 // Node's code seems to be doing this and not & 0x7F..
33129 byteArray.push(str.charCodeAt(i) & 0xFF)
33130 }
33131 return byteArray
33132}
33133
33134function utf16leToBytes (str, units) {
33135 var c, hi, lo
33136 var byteArray = []
33137 for (var i = 0; i < str.length; ++i) {
33138 if ((units -= 2) < 0) break
33139
33140 c = str.charCodeAt(i)
33141 hi = c >> 8
33142 lo = c % 256
33143 byteArray.push(lo)
33144 byteArray.push(hi)
33145 }
33146
33147 return byteArray
33148}
33149
33150function base64ToBytes (str) {
33151 return base64.toByteArray(base64clean(str))
33152}
33153
33154function blitBuffer (src, dst, offset, length) {
33155 for (var i = 0; i < length; ++i) {
33156 if ((i + offset >= dst.length) || (i >= src.length)) break
33157 dst[i + offset] = src[i]
33158 }
33159 return i
33160}
33161
33162// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass
33163// the `instanceof` check but they should be treated as of that type.
33164// See: https://github.com/feross/buffer/issues/166
33165function isInstance (obj, type) {
33166 return obj instanceof type ||
33167 (obj != null && obj.constructor != null && obj.constructor.name != null &&
33168 obj.constructor.name === type.name)
33169}
33170function numberIsNaN (obj) {
33171 // For IE11 support
33172 return obj !== obj // eslint-disable-line no-self-compare
33173}
33174
33175}).call(this)}).call(this,require("buffer").Buffer)
33176},{"base64-js":66,"buffer":132,"ieee754":205}],133:[function(require,module,exports){
33177var Buffer = require('safe-buffer').Buffer
33178var Transform = require('stream').Transform
33179var StringDecoder = require('string_decoder').StringDecoder
33180var inherits = require('inherits')
33181
33182function CipherBase (hashMode) {
33183 Transform.call(this)
33184 this.hashMode = typeof hashMode === 'string'
33185 if (this.hashMode) {
33186 this[hashMode] = this._finalOrDigest
33187 } else {
33188 this.final = this._finalOrDigest
33189 }
33190 if (this._final) {
33191 this.__final = this._final
33192 this._final = null
33193 }
33194 this._decoder = null
33195 this._encoding = null
33196}
33197inherits(CipherBase, Transform)
33198
33199CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
33200 if (typeof data === 'string') {
33201 data = Buffer.from(data, inputEnc)
33202 }
33203
33204 var outData = this._update(data)
33205 if (this.hashMode) return this
33206
33207 if (outputEnc) {
33208 outData = this._toString(outData, outputEnc)
33209 }
33210
33211 return outData
33212}
33213
33214CipherBase.prototype.setAutoPadding = function () {}
33215CipherBase.prototype.getAuthTag = function () {
33216 throw new Error('trying to get auth tag in unsupported state')
33217}
33218
33219CipherBase.prototype.setAuthTag = function () {
33220 throw new Error('trying to set auth tag in unsupported state')
33221}
33222
33223CipherBase.prototype.setAAD = function () {
33224 throw new Error('trying to set aad in unsupported state')
33225}
33226
33227CipherBase.prototype._transform = function (data, _, next) {
33228 var err
33229 try {
33230 if (this.hashMode) {
33231 this._update(data)
33232 } else {
33233 this.push(this._update(data))
33234 }
33235 } catch (e) {
33236 err = e
33237 } finally {
33238 next(err)
33239 }
33240}
33241CipherBase.prototype._flush = function (done) {
33242 var err
33243 try {
33244 this.push(this.__final())
33245 } catch (e) {
33246 err = e
33247 }
33248
33249 done(err)
33250}
33251CipherBase.prototype._finalOrDigest = function (outputEnc) {
33252 var outData = this.__final() || Buffer.alloc(0)
33253 if (outputEnc) {
33254 outData = this._toString(outData, outputEnc, true)
33255 }
33256 return outData
33257}
33258
33259CipherBase.prototype._toString = function (value, enc, fin) {
33260 if (!this._decoder) {
33261 this._decoder = new StringDecoder(enc)
33262 this._encoding = enc
33263 }
33264
33265 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
33266
33267 var out = this._decoder.write(value)
33268 if (fin) {
33269 out += this._decoder.end()
33270 }
33271
33272 return out
33273}
33274
33275module.exports = CipherBase
33276
33277},{"inherits":206,"safe-buffer":256,"stream":266,"string_decoder":267}],134:[function(require,module,exports){
33278(function (Buffer){(function (){
33279// Copyright Joyent, Inc. and other Node contributors.
33280//
33281// Permission is hereby granted, free of charge, to any person obtaining a
33282// copy of this software and associated documentation files (the
33283// "Software"), to deal in the Software without restriction, including
33284// without limitation the rights to use, copy, modify, merge, publish,
33285// distribute, sublicense, and/or sell copies of the Software, and to permit
33286// persons to whom the Software is furnished to do so, subject to the
33287// following conditions:
33288//
33289// The above copyright notice and this permission notice shall be included
33290// in all copies or substantial portions of the Software.
33291//
33292// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
33293// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
33294// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
33295// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
33296// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
33297// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
33298// USE OR OTHER DEALINGS IN THE SOFTWARE.
33299
33300// NOTE: These type checking functions intentionally don't use `instanceof`
33301// because it is fragile and can be easily faked with `Object.create()`.
33302
33303function isArray(arg) {
33304 if (Array.isArray) {
33305 return Array.isArray(arg);
33306 }
33307 return objectToString(arg) === '[object Array]';
33308}
33309exports.isArray = isArray;
33310
33311function isBoolean(arg) {
33312 return typeof arg === 'boolean';
33313}
33314exports.isBoolean = isBoolean;
33315
33316function isNull(arg) {
33317 return arg === null;
33318}
33319exports.isNull = isNull;
33320
33321function isNullOrUndefined(arg) {
33322 return arg == null;
33323}
33324exports.isNullOrUndefined = isNullOrUndefined;
33325
33326function isNumber(arg) {
33327 return typeof arg === 'number';
33328}
33329exports.isNumber = isNumber;
33330
33331function isString(arg) {
33332 return typeof arg === 'string';
33333}
33334exports.isString = isString;
33335
33336function isSymbol(arg) {
33337 return typeof arg === 'symbol';
33338}
33339exports.isSymbol = isSymbol;
33340
33341function isUndefined(arg) {
33342 return arg === void 0;
33343}
33344exports.isUndefined = isUndefined;
33345
33346function isRegExp(re) {
33347 return objectToString(re) === '[object RegExp]';
33348}
33349exports.isRegExp = isRegExp;
33350
33351function isObject(arg) {
33352 return typeof arg === 'object' && arg !== null;
33353}
33354exports.isObject = isObject;
33355
33356function isDate(d) {
33357 return objectToString(d) === '[object Date]';
33358}
33359exports.isDate = isDate;
33360
33361function isError(e) {
33362 return (objectToString(e) === '[object Error]' || e instanceof Error);
33363}
33364exports.isError = isError;
33365
33366function isFunction(arg) {
33367 return typeof arg === 'function';
33368}
33369exports.isFunction = isFunction;
33370
33371function isPrimitive(arg) {
33372 return arg === null ||
33373 typeof arg === 'boolean' ||
33374 typeof arg === 'number' ||
33375 typeof arg === 'string' ||
33376 typeof arg === 'symbol' || // ES6 symbol
33377 typeof arg === 'undefined';
33378}
33379exports.isPrimitive = isPrimitive;
33380
33381exports.isBuffer = Buffer.isBuffer;
33382
33383function objectToString(o) {
33384 return Object.prototype.toString.call(o);
33385}
33386
33387}).call(this)}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
33388},{"../../is-buffer/index.js":207}],135:[function(require,module,exports){
33389(function (Buffer){(function (){
33390var elliptic = require('elliptic')
33391var BN = require('bn.js')
33392
33393module.exports = function createECDH (curve) {
33394 return new ECDH(curve)
33395}
33396
33397var aliases = {
33398 secp256k1: {
33399 name: 'secp256k1',
33400 byteLength: 32
33401 },
33402 secp224r1: {
33403 name: 'p224',
33404 byteLength: 28
33405 },
33406 prime256v1: {
33407 name: 'p256',
33408 byteLength: 32
33409 },
33410 prime192v1: {
33411 name: 'p192',
33412 byteLength: 24
33413 },
33414 ed25519: {
33415 name: 'ed25519',
33416 byteLength: 32
33417 },
33418 secp384r1: {
33419 name: 'p384',
33420 byteLength: 48
33421 },
33422 secp521r1: {
33423 name: 'p521',
33424 byteLength: 66
33425 }
33426}
33427
33428aliases.p224 = aliases.secp224r1
33429aliases.p256 = aliases.secp256r1 = aliases.prime256v1
33430aliases.p192 = aliases.secp192r1 = aliases.prime192v1
33431aliases.p384 = aliases.secp384r1
33432aliases.p521 = aliases.secp521r1
33433
33434function ECDH (curve) {
33435 this.curveType = aliases[curve]
33436 if (!this.curveType) {
33437 this.curveType = {
33438 name: curve
33439 }
33440 }
33441 this.curve = new elliptic.ec(this.curveType.name) // eslint-disable-line new-cap
33442 this.keys = void 0
33443}
33444
33445ECDH.prototype.generateKeys = function (enc, format) {
33446 this.keys = this.curve.genKeyPair()
33447 return this.getPublicKey(enc, format)
33448}
33449
33450ECDH.prototype.computeSecret = function (other, inenc, enc) {
33451 inenc = inenc || 'utf8'
33452 if (!Buffer.isBuffer(other)) {
33453 other = new Buffer(other, inenc)
33454 }
33455 var otherPub = this.curve.keyFromPublic(other).getPublic()
33456 var out = otherPub.mul(this.keys.getPrivate()).getX()
33457 return formatReturnValue(out, enc, this.curveType.byteLength)
33458}
33459
33460ECDH.prototype.getPublicKey = function (enc, format) {
33461 var key = this.keys.getPublic(format === 'compressed', true)
33462 if (format === 'hybrid') {
33463 if (key[key.length - 1] % 2) {
33464 key[0] = 7
33465 } else {
33466 key[0] = 6
33467 }
33468 }
33469 return formatReturnValue(key, enc)
33470}
33471
33472ECDH.prototype.getPrivateKey = function (enc) {
33473 return formatReturnValue(this.keys.getPrivate(), enc)
33474}
33475
33476ECDH.prototype.setPublicKey = function (pub, enc) {
33477 enc = enc || 'utf8'
33478 if (!Buffer.isBuffer(pub)) {
33479 pub = new Buffer(pub, enc)
33480 }
33481 this.keys._importPublic(pub)
33482 return this
33483}
33484
33485ECDH.prototype.setPrivateKey = function (priv, enc) {
33486 enc = enc || 'utf8'
33487 if (!Buffer.isBuffer(priv)) {
33488 priv = new Buffer(priv, enc)
33489 }
33490
33491 var _priv = new BN(priv)
33492 _priv = _priv.toString(16)
33493 this.keys = this.curve.genKeyPair()
33494 this.keys._importPrivate(_priv)
33495 return this
33496}
33497
33498function formatReturnValue (bn, enc, len) {
33499 if (!Array.isArray(bn)) {
33500 bn = bn.toArray()
33501 }
33502 var buf = new Buffer(bn)
33503 if (len && buf.length < len) {
33504 var zeros = new Buffer(len - buf.length)
33505 zeros.fill(0)
33506 buf = Buffer.concat([zeros, buf])
33507 }
33508 if (!enc) {
33509 return buf
33510 } else {
33511 return buf.toString(enc)
33512 }
33513}
33514
33515}).call(this)}).call(this,require("buffer").Buffer)
33516},{"bn.js":80,"buffer":132,"elliptic":156}],136:[function(require,module,exports){
33517'use strict'
33518var inherits = require('inherits')
33519var MD5 = require('md5.js')
33520var RIPEMD160 = require('ripemd160')
33521var sha = require('sha.js')
33522var Base = require('cipher-base')
33523
33524function Hash (hash) {
33525 Base.call(this, 'digest')
33526
33527 this._hash = hash
33528}
33529
33530inherits(Hash, Base)
33531
33532Hash.prototype._update = function (data) {
33533 this._hash.update(data)
33534}
33535
33536Hash.prototype._final = function () {
33537 return this._hash.digest()
33538}
33539
33540module.exports = function createHash (alg) {
33541 alg = alg.toLowerCase()
33542 if (alg === 'md5') return new MD5()
33543 if (alg === 'rmd160' || alg === 'ripemd160') return new RIPEMD160()
33544
33545 return new Hash(sha(alg))
33546}
33547
33548},{"cipher-base":133,"inherits":206,"md5.js":211,"ripemd160":255,"sha.js":259}],137:[function(require,module,exports){
33549var MD5 = require('md5.js')
33550
33551module.exports = function (buffer) {
33552 return new MD5().update(buffer).digest()
33553}
33554
33555},{"md5.js":211}],138:[function(require,module,exports){
33556'use strict'
33557var inherits = require('inherits')
33558var Legacy = require('./legacy')
33559var Base = require('cipher-base')
33560var Buffer = require('safe-buffer').Buffer
33561var md5 = require('create-hash/md5')
33562var RIPEMD160 = require('ripemd160')
33563
33564var sha = require('sha.js')
33565
33566var ZEROS = Buffer.alloc(128)
33567
33568function Hmac (alg, key) {
33569 Base.call(this, 'digest')
33570 if (typeof key === 'string') {
33571 key = Buffer.from(key)
33572 }
33573
33574 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
33575
33576 this._alg = alg
33577 this._key = key
33578 if (key.length > blocksize) {
33579 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
33580 key = hash.update(key).digest()
33581 } else if (key.length < blocksize) {
33582 key = Buffer.concat([key, ZEROS], blocksize)
33583 }
33584
33585 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
33586 var opad = this._opad = Buffer.allocUnsafe(blocksize)
33587
33588 for (var i = 0; i < blocksize; i++) {
33589 ipad[i] = key[i] ^ 0x36
33590 opad[i] = key[i] ^ 0x5C
33591 }
33592 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
33593 this._hash.update(ipad)
33594}
33595
33596inherits(Hmac, Base)
33597
33598Hmac.prototype._update = function (data) {
33599 this._hash.update(data)
33600}
33601
33602Hmac.prototype._final = function () {
33603 var h = this._hash.digest()
33604 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
33605 return hash.update(this._opad).update(h).digest()
33606}
33607
33608module.exports = function createHmac (alg, key) {
33609 alg = alg.toLowerCase()
33610 if (alg === 'rmd160' || alg === 'ripemd160') {
33611 return new Hmac('rmd160', key)
33612 }
33613 if (alg === 'md5') {
33614 return new Legacy(md5, key)
33615 }
33616 return new Hmac(alg, key)
33617}
33618
33619},{"./legacy":139,"cipher-base":133,"create-hash/md5":137,"inherits":206,"ripemd160":255,"safe-buffer":256,"sha.js":259}],139:[function(require,module,exports){
33620'use strict'
33621var inherits = require('inherits')
33622var Buffer = require('safe-buffer').Buffer
33623
33624var Base = require('cipher-base')
33625
33626var ZEROS = Buffer.alloc(128)
33627var blocksize = 64
33628
33629function Hmac (alg, key) {
33630 Base.call(this, 'digest')
33631 if (typeof key === 'string') {
33632 key = Buffer.from(key)
33633 }
33634
33635 this._alg = alg
33636 this._key = key
33637
33638 if (key.length > blocksize) {
33639 key = alg(key)
33640 } else if (key.length < blocksize) {
33641 key = Buffer.concat([key, ZEROS], blocksize)
33642 }
33643
33644 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
33645 var opad = this._opad = Buffer.allocUnsafe(blocksize)
33646
33647 for (var i = 0; i < blocksize; i++) {
33648 ipad[i] = key[i] ^ 0x36
33649 opad[i] = key[i] ^ 0x5C
33650 }
33651
33652 this._hash = [ipad]
33653}
33654
33655inherits(Hmac, Base)
33656
33657Hmac.prototype._update = function (data) {
33658 this._hash.push(data)
33659}
33660
33661Hmac.prototype._final = function () {
33662 var h = this._alg(Buffer.concat(this._hash))
33663 return this._alg(Buffer.concat([this._opad, h]))
33664}
33665module.exports = Hmac
33666
33667},{"cipher-base":133,"inherits":206,"safe-buffer":256}],140:[function(require,module,exports){
33668'use strict'
33669
33670exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
33671exports.createHash = exports.Hash = require('create-hash')
33672exports.createHmac = exports.Hmac = require('create-hmac')
33673
33674var algos = require('browserify-sign/algos')
33675var algoKeys = Object.keys(algos)
33676var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
33677exports.getHashes = function () {
33678 return hashes
33679}
33680
33681var p = require('pbkdf2')
33682exports.pbkdf2 = p.pbkdf2
33683exports.pbkdf2Sync = p.pbkdf2Sync
33684
33685var aes = require('browserify-cipher')
33686
33687exports.Cipher = aes.Cipher
33688exports.createCipher = aes.createCipher
33689exports.Cipheriv = aes.Cipheriv
33690exports.createCipheriv = aes.createCipheriv
33691exports.Decipher = aes.Decipher
33692exports.createDecipher = aes.createDecipher
33693exports.Decipheriv = aes.Decipheriv
33694exports.createDecipheriv = aes.createDecipheriv
33695exports.getCiphers = aes.getCiphers
33696exports.listCiphers = aes.listCiphers
33697
33698var dh = require('diffie-hellman')
33699
33700exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
33701exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
33702exports.getDiffieHellman = dh.getDiffieHellman
33703exports.createDiffieHellman = dh.createDiffieHellman
33704exports.DiffieHellman = dh.DiffieHellman
33705
33706var sign = require('browserify-sign')
33707
33708exports.createSign = sign.createSign
33709exports.Sign = sign.Sign
33710exports.createVerify = sign.createVerify
33711exports.Verify = sign.Verify
33712
33713exports.createECDH = require('create-ecdh')
33714
33715var publicEncrypt = require('public-encrypt')
33716
33717exports.publicEncrypt = publicEncrypt.publicEncrypt
33718exports.privateEncrypt = publicEncrypt.privateEncrypt
33719exports.publicDecrypt = publicEncrypt.publicDecrypt
33720exports.privateDecrypt = publicEncrypt.privateDecrypt
33721
33722// the least I can do is make error messages for the rest of the node.js/crypto api.
33723// ;[
33724// 'createCredentials'
33725// ].forEach(function (name) {
33726// exports[name] = function () {
33727// throw new Error([
33728// 'sorry, ' + name + ' is not implemented yet',
33729// 'we accept pull requests',
33730// 'https://github.com/crypto-browserify/crypto-browserify'
33731// ].join('\n'))
33732// }
33733// })
33734
33735var rf = require('randomfill')
33736
33737exports.randomFill = rf.randomFill
33738exports.randomFillSync = rf.randomFillSync
33739
33740exports.createCredentials = function () {
33741 throw new Error([
33742 'sorry, createCredentials is not implemented yet',
33743 'we accept pull requests',
33744 'https://github.com/crypto-browserify/crypto-browserify'
33745 ].join('\n'))
33746}
33747
33748exports.constants = {
33749 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
33750 'DH_CHECK_P_NOT_PRIME': 1,
33751 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
33752 'DH_NOT_SUITABLE_GENERATOR': 8,
33753 'NPN_ENABLED': 1,
33754 'ALPN_ENABLED': 1,
33755 'RSA_PKCS1_PADDING': 1,
33756 'RSA_SSLV23_PADDING': 2,
33757 'RSA_NO_PADDING': 3,
33758 'RSA_PKCS1_OAEP_PADDING': 4,
33759 'RSA_X931_PADDING': 5,
33760 'RSA_PKCS1_PSS_PADDING': 6,
33761 'POINT_CONVERSION_COMPRESSED': 2,
33762 'POINT_CONVERSION_UNCOMPRESSED': 4,
33763 'POINT_CONVERSION_HYBRID': 6
33764}
33765
33766},{"browserify-cipher":100,"browserify-sign":108,"browserify-sign/algos":105,"create-ecdh":135,"create-hash":136,"create-hmac":138,"diffie-hellman":147,"pbkdf2":221,"public-encrypt":229,"randombytes":238,"randomfill":239}],141:[function(require,module,exports){
33767'use strict';
33768
33769exports.utils = require('./des/utils');
33770exports.Cipher = require('./des/cipher');
33771exports.DES = require('./des/des');
33772exports.CBC = require('./des/cbc');
33773exports.EDE = require('./des/ede');
33774
33775},{"./des/cbc":142,"./des/cipher":143,"./des/des":144,"./des/ede":145,"./des/utils":146}],142:[function(require,module,exports){
33776'use strict';
33777
33778var assert = require('minimalistic-assert');
33779var inherits = require('inherits');
33780
33781var proto = {};
33782
33783function CBCState(iv) {
33784 assert.equal(iv.length, 8, 'Invalid IV length');
33785
33786 this.iv = new Array(8);
33787 for (var i = 0; i < this.iv.length; i++)
33788 this.iv[i] = iv[i];
33789}
33790
33791function instantiate(Base) {
33792 function CBC(options) {
33793 Base.call(this, options);
33794 this._cbcInit();
33795 }
33796 inherits(CBC, Base);
33797
33798 var keys = Object.keys(proto);
33799 for (var i = 0; i < keys.length; i++) {
33800 var key = keys[i];
33801 CBC.prototype[key] = proto[key];
33802 }
33803
33804 CBC.create = function create(options) {
33805 return new CBC(options);
33806 };
33807
33808 return CBC;
33809}
33810
33811exports.instantiate = instantiate;
33812
33813proto._cbcInit = function _cbcInit() {
33814 var state = new CBCState(this.options.iv);
33815 this._cbcState = state;
33816};
33817
33818proto._update = function _update(inp, inOff, out, outOff) {
33819 var state = this._cbcState;
33820 var superProto = this.constructor.super_.prototype;
33821
33822 var iv = state.iv;
33823 if (this.type === 'encrypt') {
33824 for (var i = 0; i < this.blockSize; i++)
33825 iv[i] ^= inp[inOff + i];
33826
33827 superProto._update.call(this, iv, 0, out, outOff);
33828
33829 for (var i = 0; i < this.blockSize; i++)
33830 iv[i] = out[outOff + i];
33831 } else {
33832 superProto._update.call(this, inp, inOff, out, outOff);
33833
33834 for (var i = 0; i < this.blockSize; i++)
33835 out[outOff + i] ^= iv[i];
33836
33837 for (var i = 0; i < this.blockSize; i++)
33838 iv[i] = inp[inOff + i];
33839 }
33840};
33841
33842},{"inherits":206,"minimalistic-assert":213}],143:[function(require,module,exports){
33843'use strict';
33844
33845var assert = require('minimalistic-assert');
33846
33847function Cipher(options) {
33848 this.options = options;
33849
33850 this.type = this.options.type;
33851 this.blockSize = 8;
33852 this._init();
33853
33854 this.buffer = new Array(this.blockSize);
33855 this.bufferOff = 0;
33856}
33857module.exports = Cipher;
33858
33859Cipher.prototype._init = function _init() {
33860 // Might be overrided
33861};
33862
33863Cipher.prototype.update = function update(data) {
33864 if (data.length === 0)
33865 return [];
33866
33867 if (this.type === 'decrypt')
33868 return this._updateDecrypt(data);
33869 else
33870 return this._updateEncrypt(data);
33871};
33872
33873Cipher.prototype._buffer = function _buffer(data, off) {
33874 // Append data to buffer
33875 var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
33876 for (var i = 0; i < min; i++)
33877 this.buffer[this.bufferOff + i] = data[off + i];
33878 this.bufferOff += min;
33879
33880 // Shift next
33881 return min;
33882};
33883
33884Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
33885 this._update(this.buffer, 0, out, off);
33886 this.bufferOff = 0;
33887 return this.blockSize;
33888};
33889
33890Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
33891 var inputOff = 0;
33892 var outputOff = 0;
33893
33894 var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
33895 var out = new Array(count * this.blockSize);
33896
33897 if (this.bufferOff !== 0) {
33898 inputOff += this._buffer(data, inputOff);
33899
33900 if (this.bufferOff === this.buffer.length)
33901 outputOff += this._flushBuffer(out, outputOff);
33902 }
33903
33904 // Write blocks
33905 var max = data.length - ((data.length - inputOff) % this.blockSize);
33906 for (; inputOff < max; inputOff += this.blockSize) {
33907 this._update(data, inputOff, out, outputOff);
33908 outputOff += this.blockSize;
33909 }
33910
33911 // Queue rest
33912 for (; inputOff < data.length; inputOff++, this.bufferOff++)
33913 this.buffer[this.bufferOff] = data[inputOff];
33914
33915 return out;
33916};
33917
33918Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
33919 var inputOff = 0;
33920 var outputOff = 0;
33921
33922 var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
33923 var out = new Array(count * this.blockSize);
33924
33925 // TODO(indutny): optimize it, this is far from optimal
33926 for (; count > 0; count--) {
33927 inputOff += this._buffer(data, inputOff);
33928 outputOff += this._flushBuffer(out, outputOff);
33929 }
33930
33931 // Buffer rest of the input
33932 inputOff += this._buffer(data, inputOff);
33933
33934 return out;
33935};
33936
33937Cipher.prototype.final = function final(buffer) {
33938 var first;
33939 if (buffer)
33940 first = this.update(buffer);
33941
33942 var last;
33943 if (this.type === 'encrypt')
33944 last = this._finalEncrypt();
33945 else
33946 last = this._finalDecrypt();
33947
33948 if (first)
33949 return first.concat(last);
33950 else
33951 return last;
33952};
33953
33954Cipher.prototype._pad = function _pad(buffer, off) {
33955 if (off === 0)
33956 return false;
33957
33958 while (off < buffer.length)
33959 buffer[off++] = 0;
33960
33961 return true;
33962};
33963
33964Cipher.prototype._finalEncrypt = function _finalEncrypt() {
33965 if (!this._pad(this.buffer, this.bufferOff))
33966 return [];
33967
33968 var out = new Array(this.blockSize);
33969 this._update(this.buffer, 0, out, 0);
33970 return out;
33971};
33972
33973Cipher.prototype._unpad = function _unpad(buffer) {
33974 return buffer;
33975};
33976
33977Cipher.prototype._finalDecrypt = function _finalDecrypt() {
33978 assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
33979 var out = new Array(this.blockSize);
33980 this._flushBuffer(out, 0);
33981
33982 return this._unpad(out);
33983};
33984
33985},{"minimalistic-assert":213}],144:[function(require,module,exports){
33986'use strict';
33987
33988var assert = require('minimalistic-assert');
33989var inherits = require('inherits');
33990
33991var utils = require('./utils');
33992var Cipher = require('./cipher');
33993
33994function DESState() {
33995 this.tmp = new Array(2);
33996 this.keys = null;
33997}
33998
33999function DES(options) {
34000 Cipher.call(this, options);
34001
34002 var state = new DESState();
34003 this._desState = state;
34004
34005 this.deriveKeys(state, options.key);
34006}
34007inherits(DES, Cipher);
34008module.exports = DES;
34009
34010DES.create = function create(options) {
34011 return new DES(options);
34012};
34013
34014var shiftTable = [
34015 1, 1, 2, 2, 2, 2, 2, 2,
34016 1, 2, 2, 2, 2, 2, 2, 1
34017];
34018
34019DES.prototype.deriveKeys = function deriveKeys(state, key) {
34020 state.keys = new Array(16 * 2);
34021
34022 assert.equal(key.length, this.blockSize, 'Invalid key length');
34023
34024 var kL = utils.readUInt32BE(key, 0);
34025 var kR = utils.readUInt32BE(key, 4);
34026
34027 utils.pc1(kL, kR, state.tmp, 0);
34028 kL = state.tmp[0];
34029 kR = state.tmp[1];
34030 for (var i = 0; i < state.keys.length; i += 2) {
34031 var shift = shiftTable[i >>> 1];
34032 kL = utils.r28shl(kL, shift);
34033 kR = utils.r28shl(kR, shift);
34034 utils.pc2(kL, kR, state.keys, i);
34035 }
34036};
34037
34038DES.prototype._update = function _update(inp, inOff, out, outOff) {
34039 var state = this._desState;
34040
34041 var l = utils.readUInt32BE(inp, inOff);
34042 var r = utils.readUInt32BE(inp, inOff + 4);
34043
34044 // Initial Permutation
34045 utils.ip(l, r, state.tmp, 0);
34046 l = state.tmp[0];
34047 r = state.tmp[1];
34048
34049 if (this.type === 'encrypt')
34050 this._encrypt(state, l, r, state.tmp, 0);
34051 else
34052 this._decrypt(state, l, r, state.tmp, 0);
34053
34054 l = state.tmp[0];
34055 r = state.tmp[1];
34056
34057 utils.writeUInt32BE(out, l, outOff);
34058 utils.writeUInt32BE(out, r, outOff + 4);
34059};
34060
34061DES.prototype._pad = function _pad(buffer, off) {
34062 var value = buffer.length - off;
34063 for (var i = off; i < buffer.length; i++)
34064 buffer[i] = value;
34065
34066 return true;
34067};
34068
34069DES.prototype._unpad = function _unpad(buffer) {
34070 var pad = buffer[buffer.length - 1];
34071 for (var i = buffer.length - pad; i < buffer.length; i++)
34072 assert.equal(buffer[i], pad);
34073
34074 return buffer.slice(0, buffer.length - pad);
34075};
34076
34077DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
34078 var l = lStart;
34079 var r = rStart;
34080
34081 // Apply f() x16 times
34082 for (var i = 0; i < state.keys.length; i += 2) {
34083 var keyL = state.keys[i];
34084 var keyR = state.keys[i + 1];
34085
34086 // f(r, k)
34087 utils.expand(r, state.tmp, 0);
34088
34089 keyL ^= state.tmp[0];
34090 keyR ^= state.tmp[1];
34091 var s = utils.substitute(keyL, keyR);
34092 var f = utils.permute(s);
34093
34094 var t = r;
34095 r = (l ^ f) >>> 0;
34096 l = t;
34097 }
34098
34099 // Reverse Initial Permutation
34100 utils.rip(r, l, out, off);
34101};
34102
34103DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
34104 var l = rStart;
34105 var r = lStart;
34106
34107 // Apply f() x16 times
34108 for (var i = state.keys.length - 2; i >= 0; i -= 2) {
34109 var keyL = state.keys[i];
34110 var keyR = state.keys[i + 1];
34111
34112 // f(r, k)
34113 utils.expand(l, state.tmp, 0);
34114
34115 keyL ^= state.tmp[0];
34116 keyR ^= state.tmp[1];
34117 var s = utils.substitute(keyL, keyR);
34118 var f = utils.permute(s);
34119
34120 var t = l;
34121 l = (r ^ f) >>> 0;
34122 r = t;
34123 }
34124
34125 // Reverse Initial Permutation
34126 utils.rip(l, r, out, off);
34127};
34128
34129},{"./cipher":143,"./utils":146,"inherits":206,"minimalistic-assert":213}],145:[function(require,module,exports){
34130'use strict';
34131
34132var assert = require('minimalistic-assert');
34133var inherits = require('inherits');
34134
34135var Cipher = require('./cipher');
34136var DES = require('./des');
34137
34138function EDEState(type, key) {
34139 assert.equal(key.length, 24, 'Invalid key length');
34140
34141 var k1 = key.slice(0, 8);
34142 var k2 = key.slice(8, 16);
34143 var k3 = key.slice(16, 24);
34144
34145 if (type === 'encrypt') {
34146 this.ciphers = [
34147 DES.create({ type: 'encrypt', key: k1 }),
34148 DES.create({ type: 'decrypt', key: k2 }),
34149 DES.create({ type: 'encrypt', key: k3 })
34150 ];
34151 } else {
34152 this.ciphers = [
34153 DES.create({ type: 'decrypt', key: k3 }),
34154 DES.create({ type: 'encrypt', key: k2 }),
34155 DES.create({ type: 'decrypt', key: k1 })
34156 ];
34157 }
34158}
34159
34160function EDE(options) {
34161 Cipher.call(this, options);
34162
34163 var state = new EDEState(this.type, this.options.key);
34164 this._edeState = state;
34165}
34166inherits(EDE, Cipher);
34167
34168module.exports = EDE;
34169
34170EDE.create = function create(options) {
34171 return new EDE(options);
34172};
34173
34174EDE.prototype._update = function _update(inp, inOff, out, outOff) {
34175 var state = this._edeState;
34176
34177 state.ciphers[0]._update(inp, inOff, out, outOff);
34178 state.ciphers[1]._update(out, outOff, out, outOff);
34179 state.ciphers[2]._update(out, outOff, out, outOff);
34180};
34181
34182EDE.prototype._pad = DES.prototype._pad;
34183EDE.prototype._unpad = DES.prototype._unpad;
34184
34185},{"./cipher":143,"./des":144,"inherits":206,"minimalistic-assert":213}],146:[function(require,module,exports){
34186'use strict';
34187
34188exports.readUInt32BE = function readUInt32BE(bytes, off) {
34189 var res = (bytes[0 + off] << 24) |
34190 (bytes[1 + off] << 16) |
34191 (bytes[2 + off] << 8) |
34192 bytes[3 + off];
34193 return res >>> 0;
34194};
34195
34196exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
34197 bytes[0 + off] = value >>> 24;
34198 bytes[1 + off] = (value >>> 16) & 0xff;
34199 bytes[2 + off] = (value >>> 8) & 0xff;
34200 bytes[3 + off] = value & 0xff;
34201};
34202
34203exports.ip = function ip(inL, inR, out, off) {
34204 var outL = 0;
34205 var outR = 0;
34206
34207 for (var i = 6; i >= 0; i -= 2) {
34208 for (var j = 0; j <= 24; j += 8) {
34209 outL <<= 1;
34210 outL |= (inR >>> (j + i)) & 1;
34211 }
34212 for (var j = 0; j <= 24; j += 8) {
34213 outL <<= 1;
34214 outL |= (inL >>> (j + i)) & 1;
34215 }
34216 }
34217
34218 for (var i = 6; i >= 0; i -= 2) {
34219 for (var j = 1; j <= 25; j += 8) {
34220 outR <<= 1;
34221 outR |= (inR >>> (j + i)) & 1;
34222 }
34223 for (var j = 1; j <= 25; j += 8) {
34224 outR <<= 1;
34225 outR |= (inL >>> (j + i)) & 1;
34226 }
34227 }
34228
34229 out[off + 0] = outL >>> 0;
34230 out[off + 1] = outR >>> 0;
34231};
34232
34233exports.rip = function rip(inL, inR, out, off) {
34234 var outL = 0;
34235 var outR = 0;
34236
34237 for (var i = 0; i < 4; i++) {
34238 for (var j = 24; j >= 0; j -= 8) {
34239 outL <<= 1;
34240 outL |= (inR >>> (j + i)) & 1;
34241 outL <<= 1;
34242 outL |= (inL >>> (j + i)) & 1;
34243 }
34244 }
34245 for (var i = 4; i < 8; i++) {
34246 for (var j = 24; j >= 0; j -= 8) {
34247 outR <<= 1;
34248 outR |= (inR >>> (j + i)) & 1;
34249 outR <<= 1;
34250 outR |= (inL >>> (j + i)) & 1;
34251 }
34252 }
34253
34254 out[off + 0] = outL >>> 0;
34255 out[off + 1] = outR >>> 0;
34256};
34257
34258exports.pc1 = function pc1(inL, inR, out, off) {
34259 var outL = 0;
34260 var outR = 0;
34261
34262 // 7, 15, 23, 31, 39, 47, 55, 63
34263 // 6, 14, 22, 30, 39, 47, 55, 63
34264 // 5, 13, 21, 29, 39, 47, 55, 63
34265 // 4, 12, 20, 28
34266 for (var i = 7; i >= 5; i--) {
34267 for (var j = 0; j <= 24; j += 8) {
34268 outL <<= 1;
34269 outL |= (inR >> (j + i)) & 1;
34270 }
34271 for (var j = 0; j <= 24; j += 8) {
34272 outL <<= 1;
34273 outL |= (inL >> (j + i)) & 1;
34274 }
34275 }
34276 for (var j = 0; j <= 24; j += 8) {
34277 outL <<= 1;
34278 outL |= (inR >> (j + i)) & 1;
34279 }
34280
34281 // 1, 9, 17, 25, 33, 41, 49, 57
34282 // 2, 10, 18, 26, 34, 42, 50, 58
34283 // 3, 11, 19, 27, 35, 43, 51, 59
34284 // 36, 44, 52, 60
34285 for (var i = 1; i <= 3; i++) {
34286 for (var j = 0; j <= 24; j += 8) {
34287 outR <<= 1;
34288 outR |= (inR >> (j + i)) & 1;
34289 }
34290 for (var j = 0; j <= 24; j += 8) {
34291 outR <<= 1;
34292 outR |= (inL >> (j + i)) & 1;
34293 }
34294 }
34295 for (var j = 0; j <= 24; j += 8) {
34296 outR <<= 1;
34297 outR |= (inL >> (j + i)) & 1;
34298 }
34299
34300 out[off + 0] = outL >>> 0;
34301 out[off + 1] = outR >>> 0;
34302};
34303
34304exports.r28shl = function r28shl(num, shift) {
34305 return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
34306};
34307
34308var pc2table = [
34309 // inL => outL
34310 14, 11, 17, 4, 27, 23, 25, 0,
34311 13, 22, 7, 18, 5, 9, 16, 24,
34312 2, 20, 12, 21, 1, 8, 15, 26,
34313
34314 // inR => outR
34315 15, 4, 25, 19, 9, 1, 26, 16,
34316 5, 11, 23, 8, 12, 7, 17, 0,
34317 22, 3, 10, 14, 6, 20, 27, 24
34318];
34319
34320exports.pc2 = function pc2(inL, inR, out, off) {
34321 var outL = 0;
34322 var outR = 0;
34323
34324 var len = pc2table.length >>> 1;
34325 for (var i = 0; i < len; i++) {
34326 outL <<= 1;
34327 outL |= (inL >>> pc2table[i]) & 0x1;
34328 }
34329 for (var i = len; i < pc2table.length; i++) {
34330 outR <<= 1;
34331 outR |= (inR >>> pc2table[i]) & 0x1;
34332 }
34333
34334 out[off + 0] = outL >>> 0;
34335 out[off + 1] = outR >>> 0;
34336};
34337
34338exports.expand = function expand(r, out, off) {
34339 var outL = 0;
34340 var outR = 0;
34341
34342 outL = ((r & 1) << 5) | (r >>> 27);
34343 for (var i = 23; i >= 15; i -= 4) {
34344 outL <<= 6;
34345 outL |= (r >>> i) & 0x3f;
34346 }
34347 for (var i = 11; i >= 3; i -= 4) {
34348 outR |= (r >>> i) & 0x3f;
34349 outR <<= 6;
34350 }
34351 outR |= ((r & 0x1f) << 1) | (r >>> 31);
34352
34353 out[off + 0] = outL >>> 0;
34354 out[off + 1] = outR >>> 0;
34355};
34356
34357var sTable = [
34358 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
34359 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
34360 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
34361 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
34362
34363 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
34364 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
34365 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
34366 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
34367
34368 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
34369 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
34370 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
34371 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
34372
34373 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
34374 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
34375 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
34376 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
34377
34378 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
34379 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
34380 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
34381 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
34382
34383 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
34384 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
34385 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
34386 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
34387
34388 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
34389 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
34390 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
34391 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
34392
34393 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
34394 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
34395 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
34396 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
34397];
34398
34399exports.substitute = function substitute(inL, inR) {
34400 var out = 0;
34401 for (var i = 0; i < 4; i++) {
34402 var b = (inL >>> (18 - i * 6)) & 0x3f;
34403 var sb = sTable[i * 0x40 + b];
34404
34405 out <<= 4;
34406 out |= sb;
34407 }
34408 for (var i = 0; i < 4; i++) {
34409 var b = (inR >>> (18 - i * 6)) & 0x3f;
34410 var sb = sTable[4 * 0x40 + i * 0x40 + b];
34411
34412 out <<= 4;
34413 out |= sb;
34414 }
34415 return out >>> 0;
34416};
34417
34418var permuteTable = [
34419 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
34420 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
34421];
34422
34423exports.permute = function permute(num) {
34424 var out = 0;
34425 for (var i = 0; i < permuteTable.length; i++) {
34426 out <<= 1;
34427 out |= (num >>> permuteTable[i]) & 0x1;
34428 }
34429 return out >>> 0;
34430};
34431
34432exports.padSplit = function padSplit(num, size, group) {
34433 var str = num.toString(2);
34434 while (str.length < size)
34435 str = '0' + str;
34436
34437 var out = [];
34438 for (var i = 0; i < size; i += group)
34439 out.push(str.slice(i, i + group));
34440 return out.join(' ');
34441};
34442
34443},{}],147:[function(require,module,exports){
34444(function (Buffer){(function (){
34445var generatePrime = require('./lib/generatePrime')
34446var primes = require('./lib/primes.json')
34447
34448var DH = require('./lib/dh')
34449
34450function getDiffieHellman (mod) {
34451 var prime = new Buffer(primes[mod].prime, 'hex')
34452 var gen = new Buffer(primes[mod].gen, 'hex')
34453
34454 return new DH(prime, gen)
34455}
34456
34457var ENCODINGS = {
34458 'binary': true, 'hex': true, 'base64': true
34459}
34460
34461function createDiffieHellman (prime, enc, generator, genc) {
34462 if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
34463 return createDiffieHellman(prime, 'binary', enc, generator)
34464 }
34465
34466 enc = enc || 'binary'
34467 genc = genc || 'binary'
34468 generator = generator || new Buffer([2])
34469
34470 if (!Buffer.isBuffer(generator)) {
34471 generator = new Buffer(generator, genc)
34472 }
34473
34474 if (typeof prime === 'number') {
34475 return new DH(generatePrime(prime, generator), generator, true)
34476 }
34477
34478 if (!Buffer.isBuffer(prime)) {
34479 prime = new Buffer(prime, enc)
34480 }
34481
34482 return new DH(prime, generator, true)
34483}
34484
34485exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
34486exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
34487
34488}).call(this)}).call(this,require("buffer").Buffer)
34489},{"./lib/dh":148,"./lib/generatePrime":149,"./lib/primes.json":150,"buffer":132}],148:[function(require,module,exports){
34490(function (Buffer){(function (){
34491var BN = require('bn.js');
34492var MillerRabin = require('miller-rabin');
34493var millerRabin = new MillerRabin();
34494var TWENTYFOUR = new BN(24);
34495var ELEVEN = new BN(11);
34496var TEN = new BN(10);
34497var THREE = new BN(3);
34498var SEVEN = new BN(7);
34499var primes = require('./generatePrime');
34500var randomBytes = require('randombytes');
34501module.exports = DH;
34502
34503function setPublicKey(pub, enc) {
34504 enc = enc || 'utf8';
34505 if (!Buffer.isBuffer(pub)) {
34506 pub = new Buffer(pub, enc);
34507 }
34508 this._pub = new BN(pub);
34509 return this;
34510}
34511
34512function setPrivateKey(priv, enc) {
34513 enc = enc || 'utf8';
34514 if (!Buffer.isBuffer(priv)) {
34515 priv = new Buffer(priv, enc);
34516 }
34517 this._priv = new BN(priv);
34518 return this;
34519}
34520
34521var primeCache = {};
34522function checkPrime(prime, generator) {
34523 var gen = generator.toString('hex');
34524 var hex = [gen, prime.toString(16)].join('_');
34525 if (hex in primeCache) {
34526 return primeCache[hex];
34527 }
34528 var error = 0;
34529
34530 if (prime.isEven() ||
34531 !primes.simpleSieve ||
34532 !primes.fermatTest(prime) ||
34533 !millerRabin.test(prime)) {
34534 //not a prime so +1
34535 error += 1;
34536
34537 if (gen === '02' || gen === '05') {
34538 // we'd be able to check the generator
34539 // it would fail so +8
34540 error += 8;
34541 } else {
34542 //we wouldn't be able to test the generator
34543 // so +4
34544 error += 4;
34545 }
34546 primeCache[hex] = error;
34547 return error;
34548 }
34549 if (!millerRabin.test(prime.shrn(1))) {
34550 //not a safe prime
34551 error += 2;
34552 }
34553 var rem;
34554 switch (gen) {
34555 case '02':
34556 if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
34557 // unsuidable generator
34558 error += 8;
34559 }
34560 break;
34561 case '05':
34562 rem = prime.mod(TEN);
34563 if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
34564 // prime mod 10 needs to equal 3 or 7
34565 error += 8;
34566 }
34567 break;
34568 default:
34569 error += 4;
34570 }
34571 primeCache[hex] = error;
34572 return error;
34573}
34574
34575function DH(prime, generator, malleable) {
34576 this.setGenerator(generator);
34577 this.__prime = new BN(prime);
34578 this._prime = BN.mont(this.__prime);
34579 this._primeLen = prime.length;
34580 this._pub = undefined;
34581 this._priv = undefined;
34582 this._primeCode = undefined;
34583 if (malleable) {
34584 this.setPublicKey = setPublicKey;
34585 this.setPrivateKey = setPrivateKey;
34586 } else {
34587 this._primeCode = 8;
34588 }
34589}
34590Object.defineProperty(DH.prototype, 'verifyError', {
34591 enumerable: true,
34592 get: function () {
34593 if (typeof this._primeCode !== 'number') {
34594 this._primeCode = checkPrime(this.__prime, this.__gen);
34595 }
34596 return this._primeCode;
34597 }
34598});
34599DH.prototype.generateKeys = function () {
34600 if (!this._priv) {
34601 this._priv = new BN(randomBytes(this._primeLen));
34602 }
34603 this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
34604 return this.getPublicKey();
34605};
34606
34607DH.prototype.computeSecret = function (other) {
34608 other = new BN(other);
34609 other = other.toRed(this._prime);
34610 var secret = other.redPow(this._priv).fromRed();
34611 var out = new Buffer(secret.toArray());
34612 var prime = this.getPrime();
34613 if (out.length < prime.length) {
34614 var front = new Buffer(prime.length - out.length);
34615 front.fill(0);
34616 out = Buffer.concat([front, out]);
34617 }
34618 return out;
34619};
34620
34621DH.prototype.getPublicKey = function getPublicKey(enc) {
34622 return formatReturnValue(this._pub, enc);
34623};
34624
34625DH.prototype.getPrivateKey = function getPrivateKey(enc) {
34626 return formatReturnValue(this._priv, enc);
34627};
34628
34629DH.prototype.getPrime = function (enc) {
34630 return formatReturnValue(this.__prime, enc);
34631};
34632
34633DH.prototype.getGenerator = function (enc) {
34634 return formatReturnValue(this._gen, enc);
34635};
34636
34637DH.prototype.setGenerator = function (gen, enc) {
34638 enc = enc || 'utf8';
34639 if (!Buffer.isBuffer(gen)) {
34640 gen = new Buffer(gen, enc);
34641 }
34642 this.__gen = gen;
34643 this._gen = new BN(gen);
34644 return this;
34645};
34646
34647function formatReturnValue(bn, enc) {
34648 var buf = new Buffer(bn.toArray());
34649 if (!enc) {
34650 return buf;
34651 } else {
34652 return buf.toString(enc);
34653 }
34654}
34655
34656}).call(this)}).call(this,require("buffer").Buffer)
34657},{"./generatePrime":149,"bn.js":80,"buffer":132,"miller-rabin":212,"randombytes":238}],149:[function(require,module,exports){
34658var randomBytes = require('randombytes');
34659module.exports = findPrime;
34660findPrime.simpleSieve = simpleSieve;
34661findPrime.fermatTest = fermatTest;
34662var BN = require('bn.js');
34663var TWENTYFOUR = new BN(24);
34664var MillerRabin = require('miller-rabin');
34665var millerRabin = new MillerRabin();
34666var ONE = new BN(1);
34667var TWO = new BN(2);
34668var FIVE = new BN(5);
34669var SIXTEEN = new BN(16);
34670var EIGHT = new BN(8);
34671var TEN = new BN(10);
34672var THREE = new BN(3);
34673var SEVEN = new BN(7);
34674var ELEVEN = new BN(11);
34675var FOUR = new BN(4);
34676var TWELVE = new BN(12);
34677var primes = null;
34678
34679function _getPrimes() {
34680 if (primes !== null)
34681 return primes;
34682
34683 var limit = 0x100000;
34684 var res = [];
34685 res[0] = 2;
34686 for (var i = 1, k = 3; k < limit; k += 2) {
34687 var sqrt = Math.ceil(Math.sqrt(k));
34688 for (var j = 0; j < i && res[j] <= sqrt; j++)
34689 if (k % res[j] === 0)
34690 break;
34691
34692 if (i !== j && res[j] <= sqrt)
34693 continue;
34694
34695 res[i++] = k;
34696 }
34697 primes = res;
34698 return res;
34699}
34700
34701function simpleSieve(p) {
34702 var primes = _getPrimes();
34703
34704 for (var i = 0; i < primes.length; i++)
34705 if (p.modn(primes[i]) === 0) {
34706 if (p.cmpn(primes[i]) === 0) {
34707 return true;
34708 } else {
34709 return false;
34710 }
34711 }
34712
34713 return true;
34714}
34715
34716function fermatTest(p) {
34717 var red = BN.mont(p);
34718 return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
34719}
34720
34721function findPrime(bits, gen) {
34722 if (bits < 16) {
34723 // this is what openssl does
34724 if (gen === 2 || gen === 5) {
34725 return new BN([0x8c, 0x7b]);
34726 } else {
34727 return new BN([0x8c, 0x27]);
34728 }
34729 }
34730 gen = new BN(gen);
34731
34732 var num, n2;
34733
34734 while (true) {
34735 num = new BN(randomBytes(Math.ceil(bits / 8)));
34736 while (num.bitLength() > bits) {
34737 num.ishrn(1);
34738 }
34739 if (num.isEven()) {
34740 num.iadd(ONE);
34741 }
34742 if (!num.testn(1)) {
34743 num.iadd(TWO);
34744 }
34745 if (!gen.cmp(TWO)) {
34746 while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
34747 num.iadd(FOUR);
34748 }
34749 } else if (!gen.cmp(FIVE)) {
34750 while (num.mod(TEN).cmp(THREE)) {
34751 num.iadd(FOUR);
34752 }
34753 }
34754 n2 = num.shrn(1);
34755 if (simpleSieve(n2) && simpleSieve(num) &&
34756 fermatTest(n2) && fermatTest(num) &&
34757 millerRabin.test(n2) && millerRabin.test(num)) {
34758 return num;
34759 }
34760 }
34761
34762}
34763
34764},{"bn.js":80,"miller-rabin":212,"randombytes":238}],150:[function(require,module,exports){
34765module.exports={
34766 "modp1": {
34767 "gen": "02",
34768 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
34769 },
34770 "modp2": {
34771 "gen": "02",
34772 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
34773 },
34774 "modp5": {
34775 "gen": "02",
34776 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
34777 },
34778 "modp14": {
34779 "gen": "02",
34780 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
34781 },
34782 "modp15": {
34783 "gen": "02",
34784 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
34785 },
34786 "modp16": {
34787 "gen": "02",
34788 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
34789 },
34790 "modp17": {
34791 "gen": "02",
34792 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
34793 },
34794 "modp18": {
34795 "gen": "02",
34796 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
34797 }
34798}
34799},{}],151:[function(require,module,exports){
34800var assert = require('assert')
34801var BigInteger = require('bigi')
34802
34803var Point = require('./point')
34804
34805function Curve (p, a, b, Gx, Gy, n, h) {
34806 this.p = p
34807 this.a = a
34808 this.b = b
34809 this.G = Point.fromAffine(this, Gx, Gy)
34810 this.n = n
34811 this.h = h
34812
34813 this.infinity = new Point(this, null, null, BigInteger.ZERO)
34814
34815 // result caching
34816 this.pOverFour = p.add(BigInteger.ONE).shiftRight(2)
34817
34818 // determine size of p in bytes
34819 this.pLength = Math.floor((this.p.bitLength() + 7) / 8)
34820}
34821
34822Curve.prototype.pointFromX = function (isOdd, x) {
34823 var alpha = x.pow(3).add(this.a.multiply(x)).add(this.b).mod(this.p)
34824 var beta = alpha.modPow(this.pOverFour, this.p) // XXX: not compatible with all curves
34825
34826 var y = beta
34827 if (beta.isEven() ^ !isOdd) {
34828 y = this.p.subtract(y) // -y % p
34829 }
34830
34831 return Point.fromAffine(this, x, y)
34832}
34833
34834Curve.prototype.isInfinity = function (Q) {
34835 if (Q === this.infinity) return true
34836
34837 return Q.z.signum() === 0 && Q.y.signum() !== 0
34838}
34839
34840Curve.prototype.isOnCurve = function (Q) {
34841 if (this.isInfinity(Q)) return true
34842
34843 var x = Q.affineX
34844 var y = Q.affineY
34845 var a = this.a
34846 var b = this.b
34847 var p = this.p
34848
34849 // Check that xQ and yQ are integers in the interval [0, p - 1]
34850 if (x.signum() < 0 || x.compareTo(p) >= 0) return false
34851 if (y.signum() < 0 || y.compareTo(p) >= 0) return false
34852
34853 // and check that y^2 = x^3 + ax + b (mod p)
34854 var lhs = y.square().mod(p)
34855 var rhs = x.pow(3).add(a.multiply(x)).add(b).mod(p)
34856 return lhs.equals(rhs)
34857}
34858
34859/**
34860 * Validate an elliptic curve point.
34861 *
34862 * See SEC 1, section 3.2.2.1: Elliptic Curve Public Key Validation Primitive
34863 */
34864Curve.prototype.validate = function (Q) {
34865 // Check Q != O
34866 assert(!this.isInfinity(Q), 'Point is at infinity')
34867 assert(this.isOnCurve(Q), 'Point is not on the curve')
34868
34869 // Check nQ = O (where Q is a scalar multiple of G)
34870 var nQ = Q.multiply(this.n)
34871 assert(this.isInfinity(nQ), 'Point is not a scalar multiple of G')
34872
34873 return true
34874}
34875
34876module.exports = Curve
34877
34878},{"./point":155,"assert":62,"bigi":70}],152:[function(require,module,exports){
34879module.exports={
34880 "secp128r1": {
34881 "p": "fffffffdffffffffffffffffffffffff",
34882 "a": "fffffffdfffffffffffffffffffffffc",
34883 "b": "e87579c11079f43dd824993c2cee5ed3",
34884 "n": "fffffffe0000000075a30d1b9038a115",
34885 "h": "01",
34886 "Gx": "161ff7528b899b2d0c28607ca52c5b86",
34887 "Gy": "cf5ac8395bafeb13c02da292dded7a83"
34888 },
34889 "secp160k1": {
34890 "p": "fffffffffffffffffffffffffffffffeffffac73",
34891 "a": "00",
34892 "b": "07",
34893 "n": "0100000000000000000001b8fa16dfab9aca16b6b3",
34894 "h": "01",
34895 "Gx": "3b4c382ce37aa192a4019e763036f4f5dd4d7ebb",
34896 "Gy": "938cf935318fdced6bc28286531733c3f03c4fee"
34897 },
34898 "secp160r1": {
34899 "p": "ffffffffffffffffffffffffffffffff7fffffff",
34900 "a": "ffffffffffffffffffffffffffffffff7ffffffc",
34901 "b": "1c97befc54bd7a8b65acf89f81d4d4adc565fa45",
34902 "n": "0100000000000000000001f4c8f927aed3ca752257",
34903 "h": "01",
34904 "Gx": "4a96b5688ef573284664698968c38bb913cbfc82",
34905 "Gy": "23a628553168947d59dcc912042351377ac5fb32"
34906 },
34907 "secp192k1": {
34908 "p": "fffffffffffffffffffffffffffffffffffffffeffffee37",
34909 "a": "00",
34910 "b": "03",
34911 "n": "fffffffffffffffffffffffe26f2fc170f69466a74defd8d",
34912 "h": "01",
34913 "Gx": "db4ff10ec057e9ae26b07d0280b7f4341da5d1b1eae06c7d",
34914 "Gy": "9b2f2f6d9c5628a7844163d015be86344082aa88d95e2f9d"
34915 },
34916 "secp192r1": {
34917 "p": "fffffffffffffffffffffffffffffffeffffffffffffffff",
34918 "a": "fffffffffffffffffffffffffffffffefffffffffffffffc",
34919 "b": "64210519e59c80e70fa7e9ab72243049feb8deecc146b9b1",
34920 "n": "ffffffffffffffffffffffff99def836146bc9b1b4d22831",
34921 "h": "01",
34922 "Gx": "188da80eb03090f67cbf20eb43a18800f4ff0afd82ff1012",
34923 "Gy": "07192b95ffc8da78631011ed6b24cdd573f977a11e794811"
34924 },
34925 "secp256k1": {
34926 "p": "fffffffffffffffffffffffffffffffffffffffffffffffffffffffefffffc2f",
34927 "a": "00",
34928 "b": "07",
34929 "n": "fffffffffffffffffffffffffffffffebaaedce6af48a03bbfd25e8cd0364141",
34930 "h": "01",
34931 "Gx": "79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798",
34932 "Gy": "483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8"
34933 },
34934 "secp256r1": {
34935 "p": "ffffffff00000001000000000000000000000000ffffffffffffffffffffffff",
34936 "a": "ffffffff00000001000000000000000000000000fffffffffffffffffffffffc",
34937 "b": "5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604b",
34938 "n": "ffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551",
34939 "h": "01",
34940 "Gx": "6b17d1f2e12c4247f8bce6e563a440f277037d812deb33a0f4a13945d898c296",
34941 "Gy": "4fe342e2fe1a7f9b8ee7eb4a7c0f9e162bce33576b315ececbb6406837bf51f5"
34942 }
34943}
34944
34945},{}],153:[function(require,module,exports){
34946var Point = require('./point')
34947var Curve = require('./curve')
34948
34949var getCurveByName = require('./names')
34950
34951module.exports = {
34952 Curve: Curve,
34953 Point: Point,
34954 getCurveByName: getCurveByName
34955}
34956
34957},{"./curve":151,"./names":154,"./point":155}],154:[function(require,module,exports){
34958var BigInteger = require('bigi')
34959
34960var curves = require('./curves.json')
34961var Curve = require('./curve')
34962
34963function getCurveByName (name) {
34964 var curve = curves[name]
34965 if (!curve) return null
34966
34967 var p = new BigInteger(curve.p, 16)
34968 var a = new BigInteger(curve.a, 16)
34969 var b = new BigInteger(curve.b, 16)
34970 var n = new BigInteger(curve.n, 16)
34971 var h = new BigInteger(curve.h, 16)
34972 var Gx = new BigInteger(curve.Gx, 16)
34973 var Gy = new BigInteger(curve.Gy, 16)
34974
34975 return new Curve(p, a, b, Gx, Gy, n, h)
34976}
34977
34978module.exports = getCurveByName
34979
34980},{"./curve":151,"./curves.json":152,"bigi":70}],155:[function(require,module,exports){
34981var assert = require('assert')
34982var Buffer = require('safe-buffer').Buffer
34983var BigInteger = require('bigi')
34984
34985var THREE = BigInteger.valueOf(3)
34986
34987function Point (curve, x, y, z) {
34988 assert.notStrictEqual(z, undefined, 'Missing Z coordinate')
34989
34990 this.curve = curve
34991 this.x = x
34992 this.y = y
34993 this.z = z
34994 this._zInv = null
34995
34996 this.compressed = true
34997}
34998
34999Object.defineProperty(Point.prototype, 'zInv', {
35000 get: function () {
35001 if (this._zInv === null) {
35002 this._zInv = this.z.modInverse(this.curve.p)
35003 }
35004
35005 return this._zInv
35006 }
35007})
35008
35009Object.defineProperty(Point.prototype, 'affineX', {
35010 get: function () {
35011 return this.x.multiply(this.zInv).mod(this.curve.p)
35012 }
35013})
35014
35015Object.defineProperty(Point.prototype, 'affineY', {
35016 get: function () {
35017 return this.y.multiply(this.zInv).mod(this.curve.p)
35018 }
35019})
35020
35021Point.fromAffine = function (curve, x, y) {
35022 return new Point(curve, x, y, BigInteger.ONE)
35023}
35024
35025Point.prototype.equals = function (other) {
35026 if (other === this) return true
35027 if (this.curve.isInfinity(this)) return this.curve.isInfinity(other)
35028 if (this.curve.isInfinity(other)) return this.curve.isInfinity(this)
35029
35030 // u = Y2 * Z1 - Y1 * Z2
35031 var u = other.y.multiply(this.z).subtract(this.y.multiply(other.z)).mod(this.curve.p)
35032
35033 if (u.signum() !== 0) return false
35034
35035 // v = X2 * Z1 - X1 * Z2
35036 var v = other.x.multiply(this.z).subtract(this.x.multiply(other.z)).mod(this.curve.p)
35037
35038 return v.signum() === 0
35039}
35040
35041Point.prototype.negate = function () {
35042 var y = this.curve.p.subtract(this.y)
35043
35044 return new Point(this.curve, this.x, y, this.z)
35045}
35046
35047Point.prototype.add = function (b) {
35048 if (this.curve.isInfinity(this)) return b
35049 if (this.curve.isInfinity(b)) return this
35050
35051 var x1 = this.x
35052 var y1 = this.y
35053 var x2 = b.x
35054 var y2 = b.y
35055
35056 // u = Y2 * Z1 - Y1 * Z2
35057 var u = y2.multiply(this.z).subtract(y1.multiply(b.z)).mod(this.curve.p)
35058 // v = X2 * Z1 - X1 * Z2
35059 var v = x2.multiply(this.z).subtract(x1.multiply(b.z)).mod(this.curve.p)
35060
35061 if (v.signum() === 0) {
35062 if (u.signum() === 0) {
35063 return this.twice() // this == b, so double
35064 }
35065
35066 return this.curve.infinity // this = -b, so infinity
35067 }
35068
35069 var v2 = v.square()
35070 var v3 = v2.multiply(v)
35071 var x1v2 = x1.multiply(v2)
35072 var zu2 = u.square().multiply(this.z)
35073
35074 // x3 = v * (z2 * (z1 * u^2 - 2 * x1 * v^2) - v^3)
35075 var x3 = zu2.subtract(x1v2.shiftLeft(1)).multiply(b.z).subtract(v3).multiply(v).mod(this.curve.p)
35076 // y3 = z2 * (3 * x1 * u * v^2 - y1 * v^3 - z1 * u^3) + u * v^3
35077 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)
35078 // z3 = v^3 * z1 * z2
35079 var z3 = v3.multiply(this.z).multiply(b.z).mod(this.curve.p)
35080
35081 return new Point(this.curve, x3, y3, z3)
35082}
35083
35084Point.prototype.twice = function () {
35085 if (this.curve.isInfinity(this)) return this
35086 if (this.y.signum() === 0) return this.curve.infinity
35087
35088 var x1 = this.x
35089 var y1 = this.y
35090
35091 var y1z1 = y1.multiply(this.z).mod(this.curve.p)
35092 var y1sqz1 = y1z1.multiply(y1).mod(this.curve.p)
35093 var a = this.curve.a
35094
35095 // w = 3 * x1^2 + a * z1^2
35096 var w = x1.square().multiply(THREE)
35097
35098 if (a.signum() !== 0) {
35099 w = w.add(this.z.square().multiply(a))
35100 }
35101
35102 w = w.mod(this.curve.p)
35103 // x3 = 2 * y1 * z1 * (w^2 - 8 * x1 * y1^2 * z1)
35104 var x3 = w.square().subtract(x1.shiftLeft(3).multiply(y1sqz1)).shiftLeft(1).multiply(y1z1).mod(this.curve.p)
35105 // y3 = 4 * y1^2 * z1 * (3 * w * x1 - 2 * y1^2 * z1) - w^3
35106 var y3 = w.multiply(THREE).multiply(x1).subtract(y1sqz1.shiftLeft(1)).shiftLeft(2).multiply(y1sqz1).subtract(w.pow(3)).mod(this.curve.p)
35107 // z3 = 8 * (y1 * z1)^3
35108 var z3 = y1z1.pow(3).shiftLeft(3).mod(this.curve.p)
35109
35110 return new Point(this.curve, x3, y3, z3)
35111}
35112
35113// Simple NAF (Non-Adjacent Form) multiplication algorithm
35114// TODO: modularize the multiplication algorithm
35115Point.prototype.multiply = function (k) {
35116 if (this.curve.isInfinity(this)) return this
35117 if (k.signum() === 0) return this.curve.infinity
35118
35119 var e = k
35120 var h = e.multiply(THREE)
35121
35122 var neg = this.negate()
35123 var R = this
35124
35125 for (var i = h.bitLength() - 2; i > 0; --i) {
35126 var hBit = h.testBit(i)
35127 var eBit = e.testBit(i)
35128
35129 R = R.twice()
35130
35131 if (hBit !== eBit) {
35132 R = R.add(hBit ? this : neg)
35133 }
35134 }
35135
35136 return R
35137}
35138
35139// Compute this*j + x*k (simultaneous multiplication)
35140Point.prototype.multiplyTwo = function (j, x, k) {
35141 var i = Math.max(j.bitLength(), k.bitLength()) - 1
35142 var R = this.curve.infinity
35143 var both = this.add(x)
35144
35145 while (i >= 0) {
35146 var jBit = j.testBit(i)
35147 var kBit = k.testBit(i)
35148
35149 R = R.twice()
35150
35151 if (jBit) {
35152 if (kBit) {
35153 R = R.add(both)
35154 } else {
35155 R = R.add(this)
35156 }
35157 } else if (kBit) {
35158 R = R.add(x)
35159 }
35160 --i
35161 }
35162
35163 return R
35164}
35165
35166Point.prototype.getEncoded = function (compressed) {
35167 if (compressed == null) compressed = this.compressed
35168 if (this.curve.isInfinity(this)) return Buffer.alloc(1, 0) // Infinity point encoded is simply '00'
35169
35170 var x = this.affineX
35171 var y = this.affineY
35172 var byteLength = this.curve.pLength
35173 var buffer
35174
35175 // 0x02/0x03 | X
35176 if (compressed) {
35177 buffer = Buffer.allocUnsafe(1 + byteLength)
35178 buffer.writeUInt8(y.isEven() ? 0x02 : 0x03, 0)
35179
35180 // 0x04 | X | Y
35181 } else {
35182 buffer = Buffer.allocUnsafe(1 + byteLength + byteLength)
35183 buffer.writeUInt8(0x04, 0)
35184
35185 y.toBuffer(byteLength).copy(buffer, 1 + byteLength)
35186 }
35187
35188 x.toBuffer(byteLength).copy(buffer, 1)
35189
35190 return buffer
35191}
35192
35193Point.decodeFrom = function (curve, buffer) {
35194 var type = buffer.readUInt8(0)
35195 var compressed = (type !== 4)
35196
35197 var byteLength = Math.floor((curve.p.bitLength() + 7) / 8)
35198 var x = BigInteger.fromBuffer(buffer.slice(1, 1 + byteLength))
35199
35200 var Q
35201 if (compressed) {
35202 assert.equal(buffer.length, byteLength + 1, 'Invalid sequence length')
35203 assert(type === 0x02 || type === 0x03, 'Invalid sequence tag')
35204
35205 var isOdd = (type === 0x03)
35206 Q = curve.pointFromX(isOdd, x)
35207 } else {
35208 assert.equal(buffer.length, 1 + byteLength + byteLength, 'Invalid sequence length')
35209
35210 var y = BigInteger.fromBuffer(buffer.slice(1 + byteLength))
35211 Q = Point.fromAffine(curve, x, y)
35212 }
35213
35214 Q.compressed = compressed
35215 return Q
35216}
35217
35218Point.prototype.toString = function () {
35219 if (this.curve.isInfinity(this)) return '(INFINITY)'
35220
35221 return '(' + this.affineX.toString() + ',' + this.affineY.toString() + ')'
35222}
35223
35224module.exports = Point
35225
35226},{"assert":62,"bigi":70,"safe-buffer":256}],156:[function(require,module,exports){
35227'use strict';
35228
35229var elliptic = exports;
35230
35231elliptic.version = require('../package.json').version;
35232elliptic.utils = require('./elliptic/utils');
35233elliptic.rand = require('brorand');
35234elliptic.curve = require('./elliptic/curve');
35235elliptic.curves = require('./elliptic/curves');
35236
35237// Protocols
35238elliptic.ec = require('./elliptic/ec');
35239elliptic.eddsa = require('./elliptic/eddsa');
35240
35241},{"../package.json":171,"./elliptic/curve":159,"./elliptic/curves":162,"./elliptic/ec":163,"./elliptic/eddsa":166,"./elliptic/utils":170,"brorand":81}],157:[function(require,module,exports){
35242'use strict';
35243
35244var BN = require('bn.js');
35245var utils = require('../utils');
35246var getNAF = utils.getNAF;
35247var getJSF = utils.getJSF;
35248var assert = utils.assert;
35249
35250function BaseCurve(type, conf) {
35251 this.type = type;
35252 this.p = new BN(conf.p, 16);
35253
35254 // Use Montgomery, when there is no fast reduction for the prime
35255 this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
35256
35257 // Useful for many curves
35258 this.zero = new BN(0).toRed(this.red);
35259 this.one = new BN(1).toRed(this.red);
35260 this.two = new BN(2).toRed(this.red);
35261
35262 // Curve configuration, optional
35263 this.n = conf.n && new BN(conf.n, 16);
35264 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
35265
35266 // Temporary arrays
35267 this._wnafT1 = new Array(4);
35268 this._wnafT2 = new Array(4);
35269 this._wnafT3 = new Array(4);
35270 this._wnafT4 = new Array(4);
35271
35272 this._bitLength = this.n ? this.n.bitLength() : 0;
35273
35274 // Generalized Greg Maxwell's trick
35275 var adjustCount = this.n && this.p.div(this.n);
35276 if (!adjustCount || adjustCount.cmpn(100) > 0) {
35277 this.redN = null;
35278 } else {
35279 this._maxwellTrick = true;
35280 this.redN = this.n.toRed(this.red);
35281 }
35282}
35283module.exports = BaseCurve;
35284
35285BaseCurve.prototype.point = function point() {
35286 throw new Error('Not implemented');
35287};
35288
35289BaseCurve.prototype.validate = function validate() {
35290 throw new Error('Not implemented');
35291};
35292
35293BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
35294 assert(p.precomputed);
35295 var doubles = p._getDoubles();
35296
35297 var naf = getNAF(k, 1, this._bitLength);
35298 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
35299 I /= 3;
35300
35301 // Translate into more windowed form
35302 var repr = [];
35303 for (var j = 0; j < naf.length; j += doubles.step) {
35304 var nafW = 0;
35305 for (var k = j + doubles.step - 1; k >= j; k--)
35306 nafW = (nafW << 1) + naf[k];
35307 repr.push(nafW);
35308 }
35309
35310 var a = this.jpoint(null, null, null);
35311 var b = this.jpoint(null, null, null);
35312 for (var i = I; i > 0; i--) {
35313 for (var j = 0; j < repr.length; j++) {
35314 var nafW = repr[j];
35315 if (nafW === i)
35316 b = b.mixedAdd(doubles.points[j]);
35317 else if (nafW === -i)
35318 b = b.mixedAdd(doubles.points[j].neg());
35319 }
35320 a = a.add(b);
35321 }
35322 return a.toP();
35323};
35324
35325BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
35326 var w = 4;
35327
35328 // Precompute window
35329 var nafPoints = p._getNAFPoints(w);
35330 w = nafPoints.wnd;
35331 var wnd = nafPoints.points;
35332
35333 // Get NAF form
35334 var naf = getNAF(k, w, this._bitLength);
35335
35336 // Add `this`*(N+1) for every w-NAF index
35337 var acc = this.jpoint(null, null, null);
35338 for (var i = naf.length - 1; i >= 0; i--) {
35339 // Count zeroes
35340 for (var k = 0; i >= 0 && naf[i] === 0; i--)
35341 k++;
35342 if (i >= 0)
35343 k++;
35344 acc = acc.dblp(k);
35345
35346 if (i < 0)
35347 break;
35348 var z = naf[i];
35349 assert(z !== 0);
35350 if (p.type === 'affine') {
35351 // J +- P
35352 if (z > 0)
35353 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
35354 else
35355 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
35356 } else {
35357 // J +- J
35358 if (z > 0)
35359 acc = acc.add(wnd[(z - 1) >> 1]);
35360 else
35361 acc = acc.add(wnd[(-z - 1) >> 1].neg());
35362 }
35363 }
35364 return p.type === 'affine' ? acc.toP() : acc;
35365};
35366
35367BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
35368 points,
35369 coeffs,
35370 len,
35371 jacobianResult) {
35372 var wndWidth = this._wnafT1;
35373 var wnd = this._wnafT2;
35374 var naf = this._wnafT3;
35375
35376 // Fill all arrays
35377 var max = 0;
35378 for (var i = 0; i < len; i++) {
35379 var p = points[i];
35380 var nafPoints = p._getNAFPoints(defW);
35381 wndWidth[i] = nafPoints.wnd;
35382 wnd[i] = nafPoints.points;
35383 }
35384
35385 // Comb small window NAFs
35386 for (var i = len - 1; i >= 1; i -= 2) {
35387 var a = i - 1;
35388 var b = i;
35389 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
35390 naf[a] = getNAF(coeffs[a], wndWidth[a], this._bitLength);
35391 naf[b] = getNAF(coeffs[b], wndWidth[b], this._bitLength);
35392 max = Math.max(naf[a].length, max);
35393 max = Math.max(naf[b].length, max);
35394 continue;
35395 }
35396
35397 var comb = [
35398 points[a], /* 1 */
35399 null, /* 3 */
35400 null, /* 5 */
35401 points[b] /* 7 */
35402 ];
35403
35404 // Try to avoid Projective points, if possible
35405 if (points[a].y.cmp(points[b].y) === 0) {
35406 comb[1] = points[a].add(points[b]);
35407 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
35408 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
35409 comb[1] = points[a].toJ().mixedAdd(points[b]);
35410 comb[2] = points[a].add(points[b].neg());
35411 } else {
35412 comb[1] = points[a].toJ().mixedAdd(points[b]);
35413 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
35414 }
35415
35416 var index = [
35417 -3, /* -1 -1 */
35418 -1, /* -1 0 */
35419 -5, /* -1 1 */
35420 -7, /* 0 -1 */
35421 0, /* 0 0 */
35422 7, /* 0 1 */
35423 5, /* 1 -1 */
35424 1, /* 1 0 */
35425 3 /* 1 1 */
35426 ];
35427
35428 var jsf = getJSF(coeffs[a], coeffs[b]);
35429 max = Math.max(jsf[0].length, max);
35430 naf[a] = new Array(max);
35431 naf[b] = new Array(max);
35432 for (var j = 0; j < max; j++) {
35433 var ja = jsf[0][j] | 0;
35434 var jb = jsf[1][j] | 0;
35435
35436 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
35437 naf[b][j] = 0;
35438 wnd[a] = comb;
35439 }
35440 }
35441
35442 var acc = this.jpoint(null, null, null);
35443 var tmp = this._wnafT4;
35444 for (var i = max; i >= 0; i--) {
35445 var k = 0;
35446
35447 while (i >= 0) {
35448 var zero = true;
35449 for (var j = 0; j < len; j++) {
35450 tmp[j] = naf[j][i] | 0;
35451 if (tmp[j] !== 0)
35452 zero = false;
35453 }
35454 if (!zero)
35455 break;
35456 k++;
35457 i--;
35458 }
35459 if (i >= 0)
35460 k++;
35461 acc = acc.dblp(k);
35462 if (i < 0)
35463 break;
35464
35465 for (var j = 0; j < len; j++) {
35466 var z = tmp[j];
35467 var p;
35468 if (z === 0)
35469 continue;
35470 else if (z > 0)
35471 p = wnd[j][(z - 1) >> 1];
35472 else if (z < 0)
35473 p = wnd[j][(-z - 1) >> 1].neg();
35474
35475 if (p.type === 'affine')
35476 acc = acc.mixedAdd(p);
35477 else
35478 acc = acc.add(p);
35479 }
35480 }
35481 // Zeroify references
35482 for (var i = 0; i < len; i++)
35483 wnd[i] = null;
35484
35485 if (jacobianResult)
35486 return acc;
35487 else
35488 return acc.toP();
35489};
35490
35491function BasePoint(curve, type) {
35492 this.curve = curve;
35493 this.type = type;
35494 this.precomputed = null;
35495}
35496BaseCurve.BasePoint = BasePoint;
35497
35498BasePoint.prototype.eq = function eq(/*other*/) {
35499 throw new Error('Not implemented');
35500};
35501
35502BasePoint.prototype.validate = function validate() {
35503 return this.curve.validate(this);
35504};
35505
35506BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
35507 bytes = utils.toArray(bytes, enc);
35508
35509 var len = this.p.byteLength();
35510
35511 // uncompressed, hybrid-odd, hybrid-even
35512 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
35513 bytes.length - 1 === 2 * len) {
35514 if (bytes[0] === 0x06)
35515 assert(bytes[bytes.length - 1] % 2 === 0);
35516 else if (bytes[0] === 0x07)
35517 assert(bytes[bytes.length - 1] % 2 === 1);
35518
35519 var res = this.point(bytes.slice(1, 1 + len),
35520 bytes.slice(1 + len, 1 + 2 * len));
35521
35522 return res;
35523 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
35524 bytes.length - 1 === len) {
35525 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
35526 }
35527 throw new Error('Unknown point format');
35528};
35529
35530BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
35531 return this.encode(enc, true);
35532};
35533
35534BasePoint.prototype._encode = function _encode(compact) {
35535 var len = this.curve.p.byteLength();
35536 var x = this.getX().toArray('be', len);
35537
35538 if (compact)
35539 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
35540
35541 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
35542};
35543
35544BasePoint.prototype.encode = function encode(enc, compact) {
35545 return utils.encode(this._encode(compact), enc);
35546};
35547
35548BasePoint.prototype.precompute = function precompute(power) {
35549 if (this.precomputed)
35550 return this;
35551
35552 var precomputed = {
35553 doubles: null,
35554 naf: null,
35555 beta: null
35556 };
35557 precomputed.naf = this._getNAFPoints(8);
35558 precomputed.doubles = this._getDoubles(4, power);
35559 precomputed.beta = this._getBeta();
35560 this.precomputed = precomputed;
35561
35562 return this;
35563};
35564
35565BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
35566 if (!this.precomputed)
35567 return false;
35568
35569 var doubles = this.precomputed.doubles;
35570 if (!doubles)
35571 return false;
35572
35573 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
35574};
35575
35576BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
35577 if (this.precomputed && this.precomputed.doubles)
35578 return this.precomputed.doubles;
35579
35580 var doubles = [ this ];
35581 var acc = this;
35582 for (var i = 0; i < power; i += step) {
35583 for (var j = 0; j < step; j++)
35584 acc = acc.dbl();
35585 doubles.push(acc);
35586 }
35587 return {
35588 step: step,
35589 points: doubles
35590 };
35591};
35592
35593BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
35594 if (this.precomputed && this.precomputed.naf)
35595 return this.precomputed.naf;
35596
35597 var res = [ this ];
35598 var max = (1 << wnd) - 1;
35599 var dbl = max === 1 ? null : this.dbl();
35600 for (var i = 1; i < max; i++)
35601 res[i] = res[i - 1].add(dbl);
35602 return {
35603 wnd: wnd,
35604 points: res
35605 };
35606};
35607
35608BasePoint.prototype._getBeta = function _getBeta() {
35609 return null;
35610};
35611
35612BasePoint.prototype.dblp = function dblp(k) {
35613 var r = this;
35614 for (var i = 0; i < k; i++)
35615 r = r.dbl();
35616 return r;
35617};
35618
35619},{"../utils":170,"bn.js":80}],158:[function(require,module,exports){
35620'use strict';
35621
35622var utils = require('../utils');
35623var BN = require('bn.js');
35624var inherits = require('inherits');
35625var Base = require('./base');
35626
35627var assert = utils.assert;
35628
35629function EdwardsCurve(conf) {
35630 // NOTE: Important as we are creating point in Base.call()
35631 this.twisted = (conf.a | 0) !== 1;
35632 this.mOneA = this.twisted && (conf.a | 0) === -1;
35633 this.extended = this.mOneA;
35634
35635 Base.call(this, 'edwards', conf);
35636
35637 this.a = new BN(conf.a, 16).umod(this.red.m);
35638 this.a = this.a.toRed(this.red);
35639 this.c = new BN(conf.c, 16).toRed(this.red);
35640 this.c2 = this.c.redSqr();
35641 this.d = new BN(conf.d, 16).toRed(this.red);
35642 this.dd = this.d.redAdd(this.d);
35643
35644 assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
35645 this.oneC = (conf.c | 0) === 1;
35646}
35647inherits(EdwardsCurve, Base);
35648module.exports = EdwardsCurve;
35649
35650EdwardsCurve.prototype._mulA = function _mulA(num) {
35651 if (this.mOneA)
35652 return num.redNeg();
35653 else
35654 return this.a.redMul(num);
35655};
35656
35657EdwardsCurve.prototype._mulC = function _mulC(num) {
35658 if (this.oneC)
35659 return num;
35660 else
35661 return this.c.redMul(num);
35662};
35663
35664// Just for compatibility with Short curve
35665EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
35666 return this.point(x, y, z, t);
35667};
35668
35669EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
35670 x = new BN(x, 16);
35671 if (!x.red)
35672 x = x.toRed(this.red);
35673
35674 var x2 = x.redSqr();
35675 var rhs = this.c2.redSub(this.a.redMul(x2));
35676 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
35677
35678 var y2 = rhs.redMul(lhs.redInvm());
35679 var y = y2.redSqrt();
35680 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
35681 throw new Error('invalid point');
35682
35683 var isOdd = y.fromRed().isOdd();
35684 if (odd && !isOdd || !odd && isOdd)
35685 y = y.redNeg();
35686
35687 return this.point(x, y);
35688};
35689
35690EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
35691 y = new BN(y, 16);
35692 if (!y.red)
35693 y = y.toRed(this.red);
35694
35695 // x^2 = (y^2 - c^2) / (c^2 d y^2 - a)
35696 var y2 = y.redSqr();
35697 var lhs = y2.redSub(this.c2);
35698 var rhs = y2.redMul(this.d).redMul(this.c2).redSub(this.a);
35699 var x2 = lhs.redMul(rhs.redInvm());
35700
35701 if (x2.cmp(this.zero) === 0) {
35702 if (odd)
35703 throw new Error('invalid point');
35704 else
35705 return this.point(this.zero, y);
35706 }
35707
35708 var x = x2.redSqrt();
35709 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
35710 throw new Error('invalid point');
35711
35712 if (x.fromRed().isOdd() !== odd)
35713 x = x.redNeg();
35714
35715 return this.point(x, y);
35716};
35717
35718EdwardsCurve.prototype.validate = function validate(point) {
35719 if (point.isInfinity())
35720 return true;
35721
35722 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
35723 point.normalize();
35724
35725 var x2 = point.x.redSqr();
35726 var y2 = point.y.redSqr();
35727 var lhs = x2.redMul(this.a).redAdd(y2);
35728 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
35729
35730 return lhs.cmp(rhs) === 0;
35731};
35732
35733function Point(curve, x, y, z, t) {
35734 Base.BasePoint.call(this, curve, 'projective');
35735 if (x === null && y === null && z === null) {
35736 this.x = this.curve.zero;
35737 this.y = this.curve.one;
35738 this.z = this.curve.one;
35739 this.t = this.curve.zero;
35740 this.zOne = true;
35741 } else {
35742 this.x = new BN(x, 16);
35743 this.y = new BN(y, 16);
35744 this.z = z ? new BN(z, 16) : this.curve.one;
35745 this.t = t && new BN(t, 16);
35746 if (!this.x.red)
35747 this.x = this.x.toRed(this.curve.red);
35748 if (!this.y.red)
35749 this.y = this.y.toRed(this.curve.red);
35750 if (!this.z.red)
35751 this.z = this.z.toRed(this.curve.red);
35752 if (this.t && !this.t.red)
35753 this.t = this.t.toRed(this.curve.red);
35754 this.zOne = this.z === this.curve.one;
35755
35756 // Use extended coordinates
35757 if (this.curve.extended && !this.t) {
35758 this.t = this.x.redMul(this.y);
35759 if (!this.zOne)
35760 this.t = this.t.redMul(this.z.redInvm());
35761 }
35762 }
35763}
35764inherits(Point, Base.BasePoint);
35765
35766EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
35767 return Point.fromJSON(this, obj);
35768};
35769
35770EdwardsCurve.prototype.point = function point(x, y, z, t) {
35771 return new Point(this, x, y, z, t);
35772};
35773
35774Point.fromJSON = function fromJSON(curve, obj) {
35775 return new Point(curve, obj[0], obj[1], obj[2]);
35776};
35777
35778Point.prototype.inspect = function inspect() {
35779 if (this.isInfinity())
35780 return '<EC Point Infinity>';
35781 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
35782 ' y: ' + this.y.fromRed().toString(16, 2) +
35783 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
35784};
35785
35786Point.prototype.isInfinity = function isInfinity() {
35787 // XXX This code assumes that zero is always zero in red
35788 return this.x.cmpn(0) === 0 &&
35789 (this.y.cmp(this.z) === 0 ||
35790 (this.zOne && this.y.cmp(this.curve.c) === 0));
35791};
35792
35793Point.prototype._extDbl = function _extDbl() {
35794 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
35795 // #doubling-dbl-2008-hwcd
35796 // 4M + 4S
35797
35798 // A = X1^2
35799 var a = this.x.redSqr();
35800 // B = Y1^2
35801 var b = this.y.redSqr();
35802 // C = 2 * Z1^2
35803 var c = this.z.redSqr();
35804 c = c.redIAdd(c);
35805 // D = a * A
35806 var d = this.curve._mulA(a);
35807 // E = (X1 + Y1)^2 - A - B
35808 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
35809 // G = D + B
35810 var g = d.redAdd(b);
35811 // F = G - C
35812 var f = g.redSub(c);
35813 // H = D - B
35814 var h = d.redSub(b);
35815 // X3 = E * F
35816 var nx = e.redMul(f);
35817 // Y3 = G * H
35818 var ny = g.redMul(h);
35819 // T3 = E * H
35820 var nt = e.redMul(h);
35821 // Z3 = F * G
35822 var nz = f.redMul(g);
35823 return this.curve.point(nx, ny, nz, nt);
35824};
35825
35826Point.prototype._projDbl = function _projDbl() {
35827 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
35828 // #doubling-dbl-2008-bbjlp
35829 // #doubling-dbl-2007-bl
35830 // and others
35831 // Generally 3M + 4S or 2M + 4S
35832
35833 // B = (X1 + Y1)^2
35834 var b = this.x.redAdd(this.y).redSqr();
35835 // C = X1^2
35836 var c = this.x.redSqr();
35837 // D = Y1^2
35838 var d = this.y.redSqr();
35839
35840 var nx;
35841 var ny;
35842 var nz;
35843 if (this.curve.twisted) {
35844 // E = a * C
35845 var e = this.curve._mulA(c);
35846 // F = E + D
35847 var f = e.redAdd(d);
35848 if (this.zOne) {
35849 // X3 = (B - C - D) * (F - 2)
35850 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
35851 // Y3 = F * (E - D)
35852 ny = f.redMul(e.redSub(d));
35853 // Z3 = F^2 - 2 * F
35854 nz = f.redSqr().redSub(f).redSub(f);
35855 } else {
35856 // H = Z1^2
35857 var h = this.z.redSqr();
35858 // J = F - 2 * H
35859 var j = f.redSub(h).redISub(h);
35860 // X3 = (B-C-D)*J
35861 nx = b.redSub(c).redISub(d).redMul(j);
35862 // Y3 = F * (E - D)
35863 ny = f.redMul(e.redSub(d));
35864 // Z3 = F * J
35865 nz = f.redMul(j);
35866 }
35867 } else {
35868 // E = C + D
35869 var e = c.redAdd(d);
35870 // H = (c * Z1)^2
35871 var h = this.curve._mulC(this.z).redSqr();
35872 // J = E - 2 * H
35873 var j = e.redSub(h).redSub(h);
35874 // X3 = c * (B - E) * J
35875 nx = this.curve._mulC(b.redISub(e)).redMul(j);
35876 // Y3 = c * E * (C - D)
35877 ny = this.curve._mulC(e).redMul(c.redISub(d));
35878 // Z3 = E * J
35879 nz = e.redMul(j);
35880 }
35881 return this.curve.point(nx, ny, nz);
35882};
35883
35884Point.prototype.dbl = function dbl() {
35885 if (this.isInfinity())
35886 return this;
35887
35888 // Double in extended coordinates
35889 if (this.curve.extended)
35890 return this._extDbl();
35891 else
35892 return this._projDbl();
35893};
35894
35895Point.prototype._extAdd = function _extAdd(p) {
35896 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
35897 // #addition-add-2008-hwcd-3
35898 // 8M
35899
35900 // A = (Y1 - X1) * (Y2 - X2)
35901 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
35902 // B = (Y1 + X1) * (Y2 + X2)
35903 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
35904 // C = T1 * k * T2
35905 var c = this.t.redMul(this.curve.dd).redMul(p.t);
35906 // D = Z1 * 2 * Z2
35907 var d = this.z.redMul(p.z.redAdd(p.z));
35908 // E = B - A
35909 var e = b.redSub(a);
35910 // F = D - C
35911 var f = d.redSub(c);
35912 // G = D + C
35913 var g = d.redAdd(c);
35914 // H = B + A
35915 var h = b.redAdd(a);
35916 // X3 = E * F
35917 var nx = e.redMul(f);
35918 // Y3 = G * H
35919 var ny = g.redMul(h);
35920 // T3 = E * H
35921 var nt = e.redMul(h);
35922 // Z3 = F * G
35923 var nz = f.redMul(g);
35924 return this.curve.point(nx, ny, nz, nt);
35925};
35926
35927Point.prototype._projAdd = function _projAdd(p) {
35928 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
35929 // #addition-add-2008-bbjlp
35930 // #addition-add-2007-bl
35931 // 10M + 1S
35932
35933 // A = Z1 * Z2
35934 var a = this.z.redMul(p.z);
35935 // B = A^2
35936 var b = a.redSqr();
35937 // C = X1 * X2
35938 var c = this.x.redMul(p.x);
35939 // D = Y1 * Y2
35940 var d = this.y.redMul(p.y);
35941 // E = d * C * D
35942 var e = this.curve.d.redMul(c).redMul(d);
35943 // F = B - E
35944 var f = b.redSub(e);
35945 // G = B + E
35946 var g = b.redAdd(e);
35947 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
35948 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
35949 var nx = a.redMul(f).redMul(tmp);
35950 var ny;
35951 var nz;
35952 if (this.curve.twisted) {
35953 // Y3 = A * G * (D - a * C)
35954 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
35955 // Z3 = F * G
35956 nz = f.redMul(g);
35957 } else {
35958 // Y3 = A * G * (D - C)
35959 ny = a.redMul(g).redMul(d.redSub(c));
35960 // Z3 = c * F * G
35961 nz = this.curve._mulC(f).redMul(g);
35962 }
35963 return this.curve.point(nx, ny, nz);
35964};
35965
35966Point.prototype.add = function add(p) {
35967 if (this.isInfinity())
35968 return p;
35969 if (p.isInfinity())
35970 return this;
35971
35972 if (this.curve.extended)
35973 return this._extAdd(p);
35974 else
35975 return this._projAdd(p);
35976};
35977
35978Point.prototype.mul = function mul(k) {
35979 if (this._hasDoubles(k))
35980 return this.curve._fixedNafMul(this, k);
35981 else
35982 return this.curve._wnafMul(this, k);
35983};
35984
35985Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
35986 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
35987};
35988
35989Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
35990 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
35991};
35992
35993Point.prototype.normalize = function normalize() {
35994 if (this.zOne)
35995 return this;
35996
35997 // Normalize coordinates
35998 var zi = this.z.redInvm();
35999 this.x = this.x.redMul(zi);
36000 this.y = this.y.redMul(zi);
36001 if (this.t)
36002 this.t = this.t.redMul(zi);
36003 this.z = this.curve.one;
36004 this.zOne = true;
36005 return this;
36006};
36007
36008Point.prototype.neg = function neg() {
36009 return this.curve.point(this.x.redNeg(),
36010 this.y,
36011 this.z,
36012 this.t && this.t.redNeg());
36013};
36014
36015Point.prototype.getX = function getX() {
36016 this.normalize();
36017 return this.x.fromRed();
36018};
36019
36020Point.prototype.getY = function getY() {
36021 this.normalize();
36022 return this.y.fromRed();
36023};
36024
36025Point.prototype.eq = function eq(other) {
36026 return this === other ||
36027 this.getX().cmp(other.getX()) === 0 &&
36028 this.getY().cmp(other.getY()) === 0;
36029};
36030
36031Point.prototype.eqXToP = function eqXToP(x) {
36032 var rx = x.toRed(this.curve.red).redMul(this.z);
36033 if (this.x.cmp(rx) === 0)
36034 return true;
36035
36036 var xc = x.clone();
36037 var t = this.curve.redN.redMul(this.z);
36038 for (;;) {
36039 xc.iadd(this.curve.n);
36040 if (xc.cmp(this.curve.p) >= 0)
36041 return false;
36042
36043 rx.redIAdd(t);
36044 if (this.x.cmp(rx) === 0)
36045 return true;
36046 }
36047};
36048
36049// Compatibility with BaseCurve
36050Point.prototype.toP = Point.prototype.normalize;
36051Point.prototype.mixedAdd = Point.prototype.add;
36052
36053},{"../utils":170,"./base":157,"bn.js":80,"inherits":206}],159:[function(require,module,exports){
36054'use strict';
36055
36056var curve = exports;
36057
36058curve.base = require('./base');
36059curve.short = require('./short');
36060curve.mont = require('./mont');
36061curve.edwards = require('./edwards');
36062
36063},{"./base":157,"./edwards":158,"./mont":160,"./short":161}],160:[function(require,module,exports){
36064'use strict';
36065
36066var BN = require('bn.js');
36067var inherits = require('inherits');
36068var Base = require('./base');
36069
36070var utils = require('../utils');
36071
36072function MontCurve(conf) {
36073 Base.call(this, 'mont', conf);
36074
36075 this.a = new BN(conf.a, 16).toRed(this.red);
36076 this.b = new BN(conf.b, 16).toRed(this.red);
36077 this.i4 = new BN(4).toRed(this.red).redInvm();
36078 this.two = new BN(2).toRed(this.red);
36079 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
36080}
36081inherits(MontCurve, Base);
36082module.exports = MontCurve;
36083
36084MontCurve.prototype.validate = function validate(point) {
36085 var x = point.normalize().x;
36086 var x2 = x.redSqr();
36087 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
36088 var y = rhs.redSqrt();
36089
36090 return y.redSqr().cmp(rhs) === 0;
36091};
36092
36093function Point(curve, x, z) {
36094 Base.BasePoint.call(this, curve, 'projective');
36095 if (x === null && z === null) {
36096 this.x = this.curve.one;
36097 this.z = this.curve.zero;
36098 } else {
36099 this.x = new BN(x, 16);
36100 this.z = new BN(z, 16);
36101 if (!this.x.red)
36102 this.x = this.x.toRed(this.curve.red);
36103 if (!this.z.red)
36104 this.z = this.z.toRed(this.curve.red);
36105 }
36106}
36107inherits(Point, Base.BasePoint);
36108
36109MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
36110 return this.point(utils.toArray(bytes, enc), 1);
36111};
36112
36113MontCurve.prototype.point = function point(x, z) {
36114 return new Point(this, x, z);
36115};
36116
36117MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
36118 return Point.fromJSON(this, obj);
36119};
36120
36121Point.prototype.precompute = function precompute() {
36122 // No-op
36123};
36124
36125Point.prototype._encode = function _encode() {
36126 return this.getX().toArray('be', this.curve.p.byteLength());
36127};
36128
36129Point.fromJSON = function fromJSON(curve, obj) {
36130 return new Point(curve, obj[0], obj[1] || curve.one);
36131};
36132
36133Point.prototype.inspect = function inspect() {
36134 if (this.isInfinity())
36135 return '<EC Point Infinity>';
36136 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
36137 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
36138};
36139
36140Point.prototype.isInfinity = function isInfinity() {
36141 // XXX This code assumes that zero is always zero in red
36142 return this.z.cmpn(0) === 0;
36143};
36144
36145Point.prototype.dbl = function dbl() {
36146 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
36147 // 2M + 2S + 4A
36148
36149 // A = X1 + Z1
36150 var a = this.x.redAdd(this.z);
36151 // AA = A^2
36152 var aa = a.redSqr();
36153 // B = X1 - Z1
36154 var b = this.x.redSub(this.z);
36155 // BB = B^2
36156 var bb = b.redSqr();
36157 // C = AA - BB
36158 var c = aa.redSub(bb);
36159 // X3 = AA * BB
36160 var nx = aa.redMul(bb);
36161 // Z3 = C * (BB + A24 * C)
36162 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
36163 return this.curve.point(nx, nz);
36164};
36165
36166Point.prototype.add = function add() {
36167 throw new Error('Not supported on Montgomery curve');
36168};
36169
36170Point.prototype.diffAdd = function diffAdd(p, diff) {
36171 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
36172 // 4M + 2S + 6A
36173
36174 // A = X2 + Z2
36175 var a = this.x.redAdd(this.z);
36176 // B = X2 - Z2
36177 var b = this.x.redSub(this.z);
36178 // C = X3 + Z3
36179 var c = p.x.redAdd(p.z);
36180 // D = X3 - Z3
36181 var d = p.x.redSub(p.z);
36182 // DA = D * A
36183 var da = d.redMul(a);
36184 // CB = C * B
36185 var cb = c.redMul(b);
36186 // X5 = Z1 * (DA + CB)^2
36187 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
36188 // Z5 = X1 * (DA - CB)^2
36189 var nz = diff.x.redMul(da.redISub(cb).redSqr());
36190 return this.curve.point(nx, nz);
36191};
36192
36193Point.prototype.mul = function mul(k) {
36194 var t = k.clone();
36195 var a = this; // (N / 2) * Q + Q
36196 var b = this.curve.point(null, null); // (N / 2) * Q
36197 var c = this; // Q
36198
36199 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
36200 bits.push(t.andln(1));
36201
36202 for (var i = bits.length - 1; i >= 0; i--) {
36203 if (bits[i] === 0) {
36204 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
36205 a = a.diffAdd(b, c);
36206 // N * Q = 2 * ((N / 2) * Q + Q))
36207 b = b.dbl();
36208 } else {
36209 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
36210 b = a.diffAdd(b, c);
36211 // N * Q + Q = 2 * ((N / 2) * Q + Q)
36212 a = a.dbl();
36213 }
36214 }
36215 return b;
36216};
36217
36218Point.prototype.mulAdd = function mulAdd() {
36219 throw new Error('Not supported on Montgomery curve');
36220};
36221
36222Point.prototype.jumlAdd = function jumlAdd() {
36223 throw new Error('Not supported on Montgomery curve');
36224};
36225
36226Point.prototype.eq = function eq(other) {
36227 return this.getX().cmp(other.getX()) === 0;
36228};
36229
36230Point.prototype.normalize = function normalize() {
36231 this.x = this.x.redMul(this.z.redInvm());
36232 this.z = this.curve.one;
36233 return this;
36234};
36235
36236Point.prototype.getX = function getX() {
36237 // Normalize coordinates
36238 this.normalize();
36239
36240 return this.x.fromRed();
36241};
36242
36243},{"../utils":170,"./base":157,"bn.js":80,"inherits":206}],161:[function(require,module,exports){
36244'use strict';
36245
36246var utils = require('../utils');
36247var BN = require('bn.js');
36248var inherits = require('inherits');
36249var Base = require('./base');
36250
36251var assert = utils.assert;
36252
36253function ShortCurve(conf) {
36254 Base.call(this, 'short', conf);
36255
36256 this.a = new BN(conf.a, 16).toRed(this.red);
36257 this.b = new BN(conf.b, 16).toRed(this.red);
36258 this.tinv = this.two.redInvm();
36259
36260 this.zeroA = this.a.fromRed().cmpn(0) === 0;
36261 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
36262
36263 // If the curve is endomorphic, precalculate beta and lambda
36264 this.endo = this._getEndomorphism(conf);
36265 this._endoWnafT1 = new Array(4);
36266 this._endoWnafT2 = new Array(4);
36267}
36268inherits(ShortCurve, Base);
36269module.exports = ShortCurve;
36270
36271ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
36272 // No efficient endomorphism
36273 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
36274 return;
36275
36276 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
36277 var beta;
36278 var lambda;
36279 if (conf.beta) {
36280 beta = new BN(conf.beta, 16).toRed(this.red);
36281 } else {
36282 var betas = this._getEndoRoots(this.p);
36283 // Choose the smallest beta
36284 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
36285 beta = beta.toRed(this.red);
36286 }
36287 if (conf.lambda) {
36288 lambda = new BN(conf.lambda, 16);
36289 } else {
36290 // Choose the lambda that is matching selected beta
36291 var lambdas = this._getEndoRoots(this.n);
36292 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
36293 lambda = lambdas[0];
36294 } else {
36295 lambda = lambdas[1];
36296 assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
36297 }
36298 }
36299
36300 // Get basis vectors, used for balanced length-two representation
36301 var basis;
36302 if (conf.basis) {
36303 basis = conf.basis.map(function(vec) {
36304 return {
36305 a: new BN(vec.a, 16),
36306 b: new BN(vec.b, 16)
36307 };
36308 });
36309 } else {
36310 basis = this._getEndoBasis(lambda);
36311 }
36312
36313 return {
36314 beta: beta,
36315 lambda: lambda,
36316 basis: basis
36317 };
36318};
36319
36320ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
36321 // Find roots of for x^2 + x + 1 in F
36322 // Root = (-1 +- Sqrt(-3)) / 2
36323 //
36324 var red = num === this.p ? this.red : BN.mont(num);
36325 var tinv = new BN(2).toRed(red).redInvm();
36326 var ntinv = tinv.redNeg();
36327
36328 var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
36329
36330 var l1 = ntinv.redAdd(s).fromRed();
36331 var l2 = ntinv.redSub(s).fromRed();
36332 return [ l1, l2 ];
36333};
36334
36335ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
36336 // aprxSqrt >= sqrt(this.n)
36337 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
36338
36339 // 3.74
36340 // Run EGCD, until r(L + 1) < aprxSqrt
36341 var u = lambda;
36342 var v = this.n.clone();
36343 var x1 = new BN(1);
36344 var y1 = new BN(0);
36345 var x2 = new BN(0);
36346 var y2 = new BN(1);
36347
36348 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
36349 var a0;
36350 var b0;
36351 // First vector
36352 var a1;
36353 var b1;
36354 // Second vector
36355 var a2;
36356 var b2;
36357
36358 var prevR;
36359 var i = 0;
36360 var r;
36361 var x;
36362 while (u.cmpn(0) !== 0) {
36363 var q = v.div(u);
36364 r = v.sub(q.mul(u));
36365 x = x2.sub(q.mul(x1));
36366 var y = y2.sub(q.mul(y1));
36367
36368 if (!a1 && r.cmp(aprxSqrt) < 0) {
36369 a0 = prevR.neg();
36370 b0 = x1;
36371 a1 = r.neg();
36372 b1 = x;
36373 } else if (a1 && ++i === 2) {
36374 break;
36375 }
36376 prevR = r;
36377
36378 v = u;
36379 u = r;
36380 x2 = x1;
36381 x1 = x;
36382 y2 = y1;
36383 y1 = y;
36384 }
36385 a2 = r.neg();
36386 b2 = x;
36387
36388 var len1 = a1.sqr().add(b1.sqr());
36389 var len2 = a2.sqr().add(b2.sqr());
36390 if (len2.cmp(len1) >= 0) {
36391 a2 = a0;
36392 b2 = b0;
36393 }
36394
36395 // Normalize signs
36396 if (a1.negative) {
36397 a1 = a1.neg();
36398 b1 = b1.neg();
36399 }
36400 if (a2.negative) {
36401 a2 = a2.neg();
36402 b2 = b2.neg();
36403 }
36404
36405 return [
36406 { a: a1, b: b1 },
36407 { a: a2, b: b2 }
36408 ];
36409};
36410
36411ShortCurve.prototype._endoSplit = function _endoSplit(k) {
36412 var basis = this.endo.basis;
36413 var v1 = basis[0];
36414 var v2 = basis[1];
36415
36416 var c1 = v2.b.mul(k).divRound(this.n);
36417 var c2 = v1.b.neg().mul(k).divRound(this.n);
36418
36419 var p1 = c1.mul(v1.a);
36420 var p2 = c2.mul(v2.a);
36421 var q1 = c1.mul(v1.b);
36422 var q2 = c2.mul(v2.b);
36423
36424 // Calculate answer
36425 var k1 = k.sub(p1).sub(p2);
36426 var k2 = q1.add(q2).neg();
36427 return { k1: k1, k2: k2 };
36428};
36429
36430ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
36431 x = new BN(x, 16);
36432 if (!x.red)
36433 x = x.toRed(this.red);
36434
36435 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
36436 var y = y2.redSqrt();
36437 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
36438 throw new Error('invalid point');
36439
36440 // XXX Is there any way to tell if the number is odd without converting it
36441 // to non-red form?
36442 var isOdd = y.fromRed().isOdd();
36443 if (odd && !isOdd || !odd && isOdd)
36444 y = y.redNeg();
36445
36446 return this.point(x, y);
36447};
36448
36449ShortCurve.prototype.validate = function validate(point) {
36450 if (point.inf)
36451 return true;
36452
36453 var x = point.x;
36454 var y = point.y;
36455
36456 var ax = this.a.redMul(x);
36457 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
36458 return y.redSqr().redISub(rhs).cmpn(0) === 0;
36459};
36460
36461ShortCurve.prototype._endoWnafMulAdd =
36462 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
36463 var npoints = this._endoWnafT1;
36464 var ncoeffs = this._endoWnafT2;
36465 for (var i = 0; i < points.length; i++) {
36466 var split = this._endoSplit(coeffs[i]);
36467 var p = points[i];
36468 var beta = p._getBeta();
36469
36470 if (split.k1.negative) {
36471 split.k1.ineg();
36472 p = p.neg(true);
36473 }
36474 if (split.k2.negative) {
36475 split.k2.ineg();
36476 beta = beta.neg(true);
36477 }
36478
36479 npoints[i * 2] = p;
36480 npoints[i * 2 + 1] = beta;
36481 ncoeffs[i * 2] = split.k1;
36482 ncoeffs[i * 2 + 1] = split.k2;
36483 }
36484 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
36485
36486 // Clean-up references to points and coefficients
36487 for (var j = 0; j < i * 2; j++) {
36488 npoints[j] = null;
36489 ncoeffs[j] = null;
36490 }
36491 return res;
36492};
36493
36494function Point(curve, x, y, isRed) {
36495 Base.BasePoint.call(this, curve, 'affine');
36496 if (x === null && y === null) {
36497 this.x = null;
36498 this.y = null;
36499 this.inf = true;
36500 } else {
36501 this.x = new BN(x, 16);
36502 this.y = new BN(y, 16);
36503 // Force redgomery representation when loading from JSON
36504 if (isRed) {
36505 this.x.forceRed(this.curve.red);
36506 this.y.forceRed(this.curve.red);
36507 }
36508 if (!this.x.red)
36509 this.x = this.x.toRed(this.curve.red);
36510 if (!this.y.red)
36511 this.y = this.y.toRed(this.curve.red);
36512 this.inf = false;
36513 }
36514}
36515inherits(Point, Base.BasePoint);
36516
36517ShortCurve.prototype.point = function point(x, y, isRed) {
36518 return new Point(this, x, y, isRed);
36519};
36520
36521ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
36522 return Point.fromJSON(this, obj, red);
36523};
36524
36525Point.prototype._getBeta = function _getBeta() {
36526 if (!this.curve.endo)
36527 return;
36528
36529 var pre = this.precomputed;
36530 if (pre && pre.beta)
36531 return pre.beta;
36532
36533 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
36534 if (pre) {
36535 var curve = this.curve;
36536 var endoMul = function(p) {
36537 return curve.point(p.x.redMul(curve.endo.beta), p.y);
36538 };
36539 pre.beta = beta;
36540 beta.precomputed = {
36541 beta: null,
36542 naf: pre.naf && {
36543 wnd: pre.naf.wnd,
36544 points: pre.naf.points.map(endoMul)
36545 },
36546 doubles: pre.doubles && {
36547 step: pre.doubles.step,
36548 points: pre.doubles.points.map(endoMul)
36549 }
36550 };
36551 }
36552 return beta;
36553};
36554
36555Point.prototype.toJSON = function toJSON() {
36556 if (!this.precomputed)
36557 return [ this.x, this.y ];
36558
36559 return [ this.x, this.y, this.precomputed && {
36560 doubles: this.precomputed.doubles && {
36561 step: this.precomputed.doubles.step,
36562 points: this.precomputed.doubles.points.slice(1)
36563 },
36564 naf: this.precomputed.naf && {
36565 wnd: this.precomputed.naf.wnd,
36566 points: this.precomputed.naf.points.slice(1)
36567 }
36568 } ];
36569};
36570
36571Point.fromJSON = function fromJSON(curve, obj, red) {
36572 if (typeof obj === 'string')
36573 obj = JSON.parse(obj);
36574 var res = curve.point(obj[0], obj[1], red);
36575 if (!obj[2])
36576 return res;
36577
36578 function obj2point(obj) {
36579 return curve.point(obj[0], obj[1], red);
36580 }
36581
36582 var pre = obj[2];
36583 res.precomputed = {
36584 beta: null,
36585 doubles: pre.doubles && {
36586 step: pre.doubles.step,
36587 points: [ res ].concat(pre.doubles.points.map(obj2point))
36588 },
36589 naf: pre.naf && {
36590 wnd: pre.naf.wnd,
36591 points: [ res ].concat(pre.naf.points.map(obj2point))
36592 }
36593 };
36594 return res;
36595};
36596
36597Point.prototype.inspect = function inspect() {
36598 if (this.isInfinity())
36599 return '<EC Point Infinity>';
36600 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
36601 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
36602};
36603
36604Point.prototype.isInfinity = function isInfinity() {
36605 return this.inf;
36606};
36607
36608Point.prototype.add = function add(p) {
36609 // O + P = P
36610 if (this.inf)
36611 return p;
36612
36613 // P + O = P
36614 if (p.inf)
36615 return this;
36616
36617 // P + P = 2P
36618 if (this.eq(p))
36619 return this.dbl();
36620
36621 // P + (-P) = O
36622 if (this.neg().eq(p))
36623 return this.curve.point(null, null);
36624
36625 // P + Q = O
36626 if (this.x.cmp(p.x) === 0)
36627 return this.curve.point(null, null);
36628
36629 var c = this.y.redSub(p.y);
36630 if (c.cmpn(0) !== 0)
36631 c = c.redMul(this.x.redSub(p.x).redInvm());
36632 var nx = c.redSqr().redISub(this.x).redISub(p.x);
36633 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
36634 return this.curve.point(nx, ny);
36635};
36636
36637Point.prototype.dbl = function dbl() {
36638 if (this.inf)
36639 return this;
36640
36641 // 2P = O
36642 var ys1 = this.y.redAdd(this.y);
36643 if (ys1.cmpn(0) === 0)
36644 return this.curve.point(null, null);
36645
36646 var a = this.curve.a;
36647
36648 var x2 = this.x.redSqr();
36649 var dyinv = ys1.redInvm();
36650 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
36651
36652 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
36653 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
36654 return this.curve.point(nx, ny);
36655};
36656
36657Point.prototype.getX = function getX() {
36658 return this.x.fromRed();
36659};
36660
36661Point.prototype.getY = function getY() {
36662 return this.y.fromRed();
36663};
36664
36665Point.prototype.mul = function mul(k) {
36666 k = new BN(k, 16);
36667 if (this.isInfinity())
36668 return this;
36669 else if (this._hasDoubles(k))
36670 return this.curve._fixedNafMul(this, k);
36671 else if (this.curve.endo)
36672 return this.curve._endoWnafMulAdd([ this ], [ k ]);
36673 else
36674 return this.curve._wnafMul(this, k);
36675};
36676
36677Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
36678 var points = [ this, p2 ];
36679 var coeffs = [ k1, k2 ];
36680 if (this.curve.endo)
36681 return this.curve._endoWnafMulAdd(points, coeffs);
36682 else
36683 return this.curve._wnafMulAdd(1, points, coeffs, 2);
36684};
36685
36686Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
36687 var points = [ this, p2 ];
36688 var coeffs = [ k1, k2 ];
36689 if (this.curve.endo)
36690 return this.curve._endoWnafMulAdd(points, coeffs, true);
36691 else
36692 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
36693};
36694
36695Point.prototype.eq = function eq(p) {
36696 return this === p ||
36697 this.inf === p.inf &&
36698 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
36699};
36700
36701Point.prototype.neg = function neg(_precompute) {
36702 if (this.inf)
36703 return this;
36704
36705 var res = this.curve.point(this.x, this.y.redNeg());
36706 if (_precompute && this.precomputed) {
36707 var pre = this.precomputed;
36708 var negate = function(p) {
36709 return p.neg();
36710 };
36711 res.precomputed = {
36712 naf: pre.naf && {
36713 wnd: pre.naf.wnd,
36714 points: pre.naf.points.map(negate)
36715 },
36716 doubles: pre.doubles && {
36717 step: pre.doubles.step,
36718 points: pre.doubles.points.map(negate)
36719 }
36720 };
36721 }
36722 return res;
36723};
36724
36725Point.prototype.toJ = function toJ() {
36726 if (this.inf)
36727 return this.curve.jpoint(null, null, null);
36728
36729 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
36730 return res;
36731};
36732
36733function JPoint(curve, x, y, z) {
36734 Base.BasePoint.call(this, curve, 'jacobian');
36735 if (x === null && y === null && z === null) {
36736 this.x = this.curve.one;
36737 this.y = this.curve.one;
36738 this.z = new BN(0);
36739 } else {
36740 this.x = new BN(x, 16);
36741 this.y = new BN(y, 16);
36742 this.z = new BN(z, 16);
36743 }
36744 if (!this.x.red)
36745 this.x = this.x.toRed(this.curve.red);
36746 if (!this.y.red)
36747 this.y = this.y.toRed(this.curve.red);
36748 if (!this.z.red)
36749 this.z = this.z.toRed(this.curve.red);
36750
36751 this.zOne = this.z === this.curve.one;
36752}
36753inherits(JPoint, Base.BasePoint);
36754
36755ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
36756 return new JPoint(this, x, y, z);
36757};
36758
36759JPoint.prototype.toP = function toP() {
36760 if (this.isInfinity())
36761 return this.curve.point(null, null);
36762
36763 var zinv = this.z.redInvm();
36764 var zinv2 = zinv.redSqr();
36765 var ax = this.x.redMul(zinv2);
36766 var ay = this.y.redMul(zinv2).redMul(zinv);
36767
36768 return this.curve.point(ax, ay);
36769};
36770
36771JPoint.prototype.neg = function neg() {
36772 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
36773};
36774
36775JPoint.prototype.add = function add(p) {
36776 // O + P = P
36777 if (this.isInfinity())
36778 return p;
36779
36780 // P + O = P
36781 if (p.isInfinity())
36782 return this;
36783
36784 // 12M + 4S + 7A
36785 var pz2 = p.z.redSqr();
36786 var z2 = this.z.redSqr();
36787 var u1 = this.x.redMul(pz2);
36788 var u2 = p.x.redMul(z2);
36789 var s1 = this.y.redMul(pz2.redMul(p.z));
36790 var s2 = p.y.redMul(z2.redMul(this.z));
36791
36792 var h = u1.redSub(u2);
36793 var r = s1.redSub(s2);
36794 if (h.cmpn(0) === 0) {
36795 if (r.cmpn(0) !== 0)
36796 return this.curve.jpoint(null, null, null);
36797 else
36798 return this.dbl();
36799 }
36800
36801 var h2 = h.redSqr();
36802 var h3 = h2.redMul(h);
36803 var v = u1.redMul(h2);
36804
36805 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
36806 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
36807 var nz = this.z.redMul(p.z).redMul(h);
36808
36809 return this.curve.jpoint(nx, ny, nz);
36810};
36811
36812JPoint.prototype.mixedAdd = function mixedAdd(p) {
36813 // O + P = P
36814 if (this.isInfinity())
36815 return p.toJ();
36816
36817 // P + O = P
36818 if (p.isInfinity())
36819 return this;
36820
36821 // 8M + 3S + 7A
36822 var z2 = this.z.redSqr();
36823 var u1 = this.x;
36824 var u2 = p.x.redMul(z2);
36825 var s1 = this.y;
36826 var s2 = p.y.redMul(z2).redMul(this.z);
36827
36828 var h = u1.redSub(u2);
36829 var r = s1.redSub(s2);
36830 if (h.cmpn(0) === 0) {
36831 if (r.cmpn(0) !== 0)
36832 return this.curve.jpoint(null, null, null);
36833 else
36834 return this.dbl();
36835 }
36836
36837 var h2 = h.redSqr();
36838 var h3 = h2.redMul(h);
36839 var v = u1.redMul(h2);
36840
36841 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
36842 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
36843 var nz = this.z.redMul(h);
36844
36845 return this.curve.jpoint(nx, ny, nz);
36846};
36847
36848JPoint.prototype.dblp = function dblp(pow) {
36849 if (pow === 0)
36850 return this;
36851 if (this.isInfinity())
36852 return this;
36853 if (!pow)
36854 return this.dbl();
36855
36856 if (this.curve.zeroA || this.curve.threeA) {
36857 var r = this;
36858 for (var i = 0; i < pow; i++)
36859 r = r.dbl();
36860 return r;
36861 }
36862
36863 // 1M + 2S + 1A + N * (4S + 5M + 8A)
36864 // N = 1 => 6M + 6S + 9A
36865 var a = this.curve.a;
36866 var tinv = this.curve.tinv;
36867
36868 var jx = this.x;
36869 var jy = this.y;
36870 var jz = this.z;
36871 var jz4 = jz.redSqr().redSqr();
36872
36873 // Reuse results
36874 var jyd = jy.redAdd(jy);
36875 for (var i = 0; i < pow; i++) {
36876 var jx2 = jx.redSqr();
36877 var jyd2 = jyd.redSqr();
36878 var jyd4 = jyd2.redSqr();
36879 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
36880
36881 var t1 = jx.redMul(jyd2);
36882 var nx = c.redSqr().redISub(t1.redAdd(t1));
36883 var t2 = t1.redISub(nx);
36884 var dny = c.redMul(t2);
36885 dny = dny.redIAdd(dny).redISub(jyd4);
36886 var nz = jyd.redMul(jz);
36887 if (i + 1 < pow)
36888 jz4 = jz4.redMul(jyd4);
36889
36890 jx = nx;
36891 jz = nz;
36892 jyd = dny;
36893 }
36894
36895 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
36896};
36897
36898JPoint.prototype.dbl = function dbl() {
36899 if (this.isInfinity())
36900 return this;
36901
36902 if (this.curve.zeroA)
36903 return this._zeroDbl();
36904 else if (this.curve.threeA)
36905 return this._threeDbl();
36906 else
36907 return this._dbl();
36908};
36909
36910JPoint.prototype._zeroDbl = function _zeroDbl() {
36911 var nx;
36912 var ny;
36913 var nz;
36914 // Z = 1
36915 if (this.zOne) {
36916 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
36917 // #doubling-mdbl-2007-bl
36918 // 1M + 5S + 14A
36919
36920 // XX = X1^2
36921 var xx = this.x.redSqr();
36922 // YY = Y1^2
36923 var yy = this.y.redSqr();
36924 // YYYY = YY^2
36925 var yyyy = yy.redSqr();
36926 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
36927 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
36928 s = s.redIAdd(s);
36929 // M = 3 * XX + a; a = 0
36930 var m = xx.redAdd(xx).redIAdd(xx);
36931 // T = M ^ 2 - 2*S
36932 var t = m.redSqr().redISub(s).redISub(s);
36933
36934 // 8 * YYYY
36935 var yyyy8 = yyyy.redIAdd(yyyy);
36936 yyyy8 = yyyy8.redIAdd(yyyy8);
36937 yyyy8 = yyyy8.redIAdd(yyyy8);
36938
36939 // X3 = T
36940 nx = t;
36941 // Y3 = M * (S - T) - 8 * YYYY
36942 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
36943 // Z3 = 2*Y1
36944 nz = this.y.redAdd(this.y);
36945 } else {
36946 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
36947 // #doubling-dbl-2009-l
36948 // 2M + 5S + 13A
36949
36950 // A = X1^2
36951 var a = this.x.redSqr();
36952 // B = Y1^2
36953 var b = this.y.redSqr();
36954 // C = B^2
36955 var c = b.redSqr();
36956 // D = 2 * ((X1 + B)^2 - A - C)
36957 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
36958 d = d.redIAdd(d);
36959 // E = 3 * A
36960 var e = a.redAdd(a).redIAdd(a);
36961 // F = E^2
36962 var f = e.redSqr();
36963
36964 // 8 * C
36965 var c8 = c.redIAdd(c);
36966 c8 = c8.redIAdd(c8);
36967 c8 = c8.redIAdd(c8);
36968
36969 // X3 = F - 2 * D
36970 nx = f.redISub(d).redISub(d);
36971 // Y3 = E * (D - X3) - 8 * C
36972 ny = e.redMul(d.redISub(nx)).redISub(c8);
36973 // Z3 = 2 * Y1 * Z1
36974 nz = this.y.redMul(this.z);
36975 nz = nz.redIAdd(nz);
36976 }
36977
36978 return this.curve.jpoint(nx, ny, nz);
36979};
36980
36981JPoint.prototype._threeDbl = function _threeDbl() {
36982 var nx;
36983 var ny;
36984 var nz;
36985 // Z = 1
36986 if (this.zOne) {
36987 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
36988 // #doubling-mdbl-2007-bl
36989 // 1M + 5S + 15A
36990
36991 // XX = X1^2
36992 var xx = this.x.redSqr();
36993 // YY = Y1^2
36994 var yy = this.y.redSqr();
36995 // YYYY = YY^2
36996 var yyyy = yy.redSqr();
36997 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
36998 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
36999 s = s.redIAdd(s);
37000 // M = 3 * XX + a
37001 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
37002 // T = M^2 - 2 * S
37003 var t = m.redSqr().redISub(s).redISub(s);
37004 // X3 = T
37005 nx = t;
37006 // Y3 = M * (S - T) - 8 * YYYY
37007 var yyyy8 = yyyy.redIAdd(yyyy);
37008 yyyy8 = yyyy8.redIAdd(yyyy8);
37009 yyyy8 = yyyy8.redIAdd(yyyy8);
37010 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
37011 // Z3 = 2 * Y1
37012 nz = this.y.redAdd(this.y);
37013 } else {
37014 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
37015 // 3M + 5S
37016
37017 // delta = Z1^2
37018 var delta = this.z.redSqr();
37019 // gamma = Y1^2
37020 var gamma = this.y.redSqr();
37021 // beta = X1 * gamma
37022 var beta = this.x.redMul(gamma);
37023 // alpha = 3 * (X1 - delta) * (X1 + delta)
37024 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
37025 alpha = alpha.redAdd(alpha).redIAdd(alpha);
37026 // X3 = alpha^2 - 8 * beta
37027 var beta4 = beta.redIAdd(beta);
37028 beta4 = beta4.redIAdd(beta4);
37029 var beta8 = beta4.redAdd(beta4);
37030 nx = alpha.redSqr().redISub(beta8);
37031 // Z3 = (Y1 + Z1)^2 - gamma - delta
37032 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
37033 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
37034 var ggamma8 = gamma.redSqr();
37035 ggamma8 = ggamma8.redIAdd(ggamma8);
37036 ggamma8 = ggamma8.redIAdd(ggamma8);
37037 ggamma8 = ggamma8.redIAdd(ggamma8);
37038 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
37039 }
37040
37041 return this.curve.jpoint(nx, ny, nz);
37042};
37043
37044JPoint.prototype._dbl = function _dbl() {
37045 var a = this.curve.a;
37046
37047 // 4M + 6S + 10A
37048 var jx = this.x;
37049 var jy = this.y;
37050 var jz = this.z;
37051 var jz4 = jz.redSqr().redSqr();
37052
37053 var jx2 = jx.redSqr();
37054 var jy2 = jy.redSqr();
37055
37056 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
37057
37058 var jxd4 = jx.redAdd(jx);
37059 jxd4 = jxd4.redIAdd(jxd4);
37060 var t1 = jxd4.redMul(jy2);
37061 var nx = c.redSqr().redISub(t1.redAdd(t1));
37062 var t2 = t1.redISub(nx);
37063
37064 var jyd8 = jy2.redSqr();
37065 jyd8 = jyd8.redIAdd(jyd8);
37066 jyd8 = jyd8.redIAdd(jyd8);
37067 jyd8 = jyd8.redIAdd(jyd8);
37068 var ny = c.redMul(t2).redISub(jyd8);
37069 var nz = jy.redAdd(jy).redMul(jz);
37070
37071 return this.curve.jpoint(nx, ny, nz);
37072};
37073
37074JPoint.prototype.trpl = function trpl() {
37075 if (!this.curve.zeroA)
37076 return this.dbl().add(this);
37077
37078 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
37079 // 5M + 10S + ...
37080
37081 // XX = X1^2
37082 var xx = this.x.redSqr();
37083 // YY = Y1^2
37084 var yy = this.y.redSqr();
37085 // ZZ = Z1^2
37086 var zz = this.z.redSqr();
37087 // YYYY = YY^2
37088 var yyyy = yy.redSqr();
37089 // M = 3 * XX + a * ZZ2; a = 0
37090 var m = xx.redAdd(xx).redIAdd(xx);
37091 // MM = M^2
37092 var mm = m.redSqr();
37093 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
37094 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
37095 e = e.redIAdd(e);
37096 e = e.redAdd(e).redIAdd(e);
37097 e = e.redISub(mm);
37098 // EE = E^2
37099 var ee = e.redSqr();
37100 // T = 16*YYYY
37101 var t = yyyy.redIAdd(yyyy);
37102 t = t.redIAdd(t);
37103 t = t.redIAdd(t);
37104 t = t.redIAdd(t);
37105 // U = (M + E)^2 - MM - EE - T
37106 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
37107 // X3 = 4 * (X1 * EE - 4 * YY * U)
37108 var yyu4 = yy.redMul(u);
37109 yyu4 = yyu4.redIAdd(yyu4);
37110 yyu4 = yyu4.redIAdd(yyu4);
37111 var nx = this.x.redMul(ee).redISub(yyu4);
37112 nx = nx.redIAdd(nx);
37113 nx = nx.redIAdd(nx);
37114 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
37115 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
37116 ny = ny.redIAdd(ny);
37117 ny = ny.redIAdd(ny);
37118 ny = ny.redIAdd(ny);
37119 // Z3 = (Z1 + E)^2 - ZZ - EE
37120 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
37121
37122 return this.curve.jpoint(nx, ny, nz);
37123};
37124
37125JPoint.prototype.mul = function mul(k, kbase) {
37126 k = new BN(k, kbase);
37127
37128 return this.curve._wnafMul(this, k);
37129};
37130
37131JPoint.prototype.eq = function eq(p) {
37132 if (p.type === 'affine')
37133 return this.eq(p.toJ());
37134
37135 if (this === p)
37136 return true;
37137
37138 // x1 * z2^2 == x2 * z1^2
37139 var z2 = this.z.redSqr();
37140 var pz2 = p.z.redSqr();
37141 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
37142 return false;
37143
37144 // y1 * z2^3 == y2 * z1^3
37145 var z3 = z2.redMul(this.z);
37146 var pz3 = pz2.redMul(p.z);
37147 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
37148};
37149
37150JPoint.prototype.eqXToP = function eqXToP(x) {
37151 var zs = this.z.redSqr();
37152 var rx = x.toRed(this.curve.red).redMul(zs);
37153 if (this.x.cmp(rx) === 0)
37154 return true;
37155
37156 var xc = x.clone();
37157 var t = this.curve.redN.redMul(zs);
37158 for (;;) {
37159 xc.iadd(this.curve.n);
37160 if (xc.cmp(this.curve.p) >= 0)
37161 return false;
37162
37163 rx.redIAdd(t);
37164 if (this.x.cmp(rx) === 0)
37165 return true;
37166 }
37167};
37168
37169JPoint.prototype.inspect = function inspect() {
37170 if (this.isInfinity())
37171 return '<EC JPoint Infinity>';
37172 return '<EC JPoint x: ' + this.x.toString(16, 2) +
37173 ' y: ' + this.y.toString(16, 2) +
37174 ' z: ' + this.z.toString(16, 2) + '>';
37175};
37176
37177JPoint.prototype.isInfinity = function isInfinity() {
37178 // XXX This code assumes that zero is always zero in red
37179 return this.z.cmpn(0) === 0;
37180};
37181
37182},{"../utils":170,"./base":157,"bn.js":80,"inherits":206}],162:[function(require,module,exports){
37183'use strict';
37184
37185var curves = exports;
37186
37187var hash = require('hash.js');
37188var curve = require('./curve');
37189var utils = require('./utils');
37190
37191var assert = utils.assert;
37192
37193function PresetCurve(options) {
37194 if (options.type === 'short')
37195 this.curve = new curve.short(options);
37196 else if (options.type === 'edwards')
37197 this.curve = new curve.edwards(options);
37198 else
37199 this.curve = new curve.mont(options);
37200 this.g = this.curve.g;
37201 this.n = this.curve.n;
37202 this.hash = options.hash;
37203
37204 assert(this.g.validate(), 'Invalid curve');
37205 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
37206}
37207curves.PresetCurve = PresetCurve;
37208
37209function defineCurve(name, options) {
37210 Object.defineProperty(curves, name, {
37211 configurable: true,
37212 enumerable: true,
37213 get: function() {
37214 var curve = new PresetCurve(options);
37215 Object.defineProperty(curves, name, {
37216 configurable: true,
37217 enumerable: true,
37218 value: curve
37219 });
37220 return curve;
37221 }
37222 });
37223}
37224
37225defineCurve('p192', {
37226 type: 'short',
37227 prime: 'p192',
37228 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
37229 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
37230 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
37231 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
37232 hash: hash.sha256,
37233 gRed: false,
37234 g: [
37235 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
37236 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
37237 ]
37238});
37239
37240defineCurve('p224', {
37241 type: 'short',
37242 prime: 'p224',
37243 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
37244 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
37245 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
37246 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
37247 hash: hash.sha256,
37248 gRed: false,
37249 g: [
37250 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
37251 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
37252 ]
37253});
37254
37255defineCurve('p256', {
37256 type: 'short',
37257 prime: null,
37258 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
37259 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
37260 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
37261 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
37262 hash: hash.sha256,
37263 gRed: false,
37264 g: [
37265 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
37266 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
37267 ]
37268});
37269
37270defineCurve('p384', {
37271 type: 'short',
37272 prime: null,
37273 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
37274 'fffffffe ffffffff 00000000 00000000 ffffffff',
37275 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
37276 'fffffffe ffffffff 00000000 00000000 fffffffc',
37277 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
37278 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
37279 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
37280 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
37281 hash: hash.sha384,
37282 gRed: false,
37283 g: [
37284 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
37285 '5502f25d bf55296c 3a545e38 72760ab7',
37286 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
37287 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
37288 ]
37289});
37290
37291defineCurve('p521', {
37292 type: 'short',
37293 prime: null,
37294 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
37295 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
37296 'ffffffff ffffffff ffffffff ffffffff ffffffff',
37297 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
37298 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
37299 'ffffffff ffffffff ffffffff ffffffff fffffffc',
37300 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
37301 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
37302 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
37303 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
37304 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
37305 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
37306 hash: hash.sha512,
37307 gRed: false,
37308 g: [
37309 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
37310 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
37311 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
37312 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
37313 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
37314 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
37315 ]
37316});
37317
37318defineCurve('curve25519', {
37319 type: 'mont',
37320 prime: 'p25519',
37321 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
37322 a: '76d06',
37323 b: '1',
37324 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
37325 hash: hash.sha256,
37326 gRed: false,
37327 g: [
37328 '9'
37329 ]
37330});
37331
37332defineCurve('ed25519', {
37333 type: 'edwards',
37334 prime: 'p25519',
37335 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
37336 a: '-1',
37337 c: '1',
37338 // -121665 * (121666^(-1)) (mod P)
37339 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
37340 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
37341 hash: hash.sha256,
37342 gRed: false,
37343 g: [
37344 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
37345
37346 // 4/5
37347 '6666666666666666666666666666666666666666666666666666666666666658'
37348 ]
37349});
37350
37351var pre;
37352try {
37353 pre = require('./precomputed/secp256k1');
37354} catch (e) {
37355 pre = undefined;
37356}
37357
37358defineCurve('secp256k1', {
37359 type: 'short',
37360 prime: 'k256',
37361 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
37362 a: '0',
37363 b: '7',
37364 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
37365 h: '1',
37366 hash: hash.sha256,
37367
37368 // Precomputed endomorphism
37369 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
37370 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
37371 basis: [
37372 {
37373 a: '3086d221a7d46bcde86c90e49284eb15',
37374 b: '-e4437ed6010e88286f547fa90abfe4c3'
37375 },
37376 {
37377 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
37378 b: '3086d221a7d46bcde86c90e49284eb15'
37379 }
37380 ],
37381
37382 gRed: false,
37383 g: [
37384 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
37385 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
37386 pre
37387 ]
37388});
37389
37390},{"./curve":159,"./precomputed/secp256k1":169,"./utils":170,"hash.js":191}],163:[function(require,module,exports){
37391'use strict';
37392
37393var BN = require('bn.js');
37394var HmacDRBG = require('hmac-drbg');
37395var utils = require('../utils');
37396var curves = require('../curves');
37397var rand = require('brorand');
37398var assert = utils.assert;
37399
37400var KeyPair = require('./key');
37401var Signature = require('./signature');
37402
37403function EC(options) {
37404 if (!(this instanceof EC))
37405 return new EC(options);
37406
37407 // Shortcut `elliptic.ec(curve-name)`
37408 if (typeof options === 'string') {
37409 assert(curves.hasOwnProperty(options), 'Unknown curve ' + options);
37410
37411 options = curves[options];
37412 }
37413
37414 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
37415 if (options instanceof curves.PresetCurve)
37416 options = { curve: options };
37417
37418 this.curve = options.curve.curve;
37419 this.n = this.curve.n;
37420 this.nh = this.n.ushrn(1);
37421 this.g = this.curve.g;
37422
37423 // Point on curve
37424 this.g = options.curve.g;
37425 this.g.precompute(options.curve.n.bitLength() + 1);
37426
37427 // Hash for function for DRBG
37428 this.hash = options.hash || options.curve.hash;
37429}
37430module.exports = EC;
37431
37432EC.prototype.keyPair = function keyPair(options) {
37433 return new KeyPair(this, options);
37434};
37435
37436EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
37437 return KeyPair.fromPrivate(this, priv, enc);
37438};
37439
37440EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
37441 return KeyPair.fromPublic(this, pub, enc);
37442};
37443
37444EC.prototype.genKeyPair = function genKeyPair(options) {
37445 if (!options)
37446 options = {};
37447
37448 // Instantiate Hmac_DRBG
37449 var drbg = new HmacDRBG({
37450 hash: this.hash,
37451 pers: options.pers,
37452 persEnc: options.persEnc || 'utf8',
37453 entropy: options.entropy || rand(this.hash.hmacStrength),
37454 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
37455 nonce: this.n.toArray()
37456 });
37457
37458 var bytes = this.n.byteLength();
37459 var ns2 = this.n.sub(new BN(2));
37460 do {
37461 var priv = new BN(drbg.generate(bytes));
37462 if (priv.cmp(ns2) > 0)
37463 continue;
37464
37465 priv.iaddn(1);
37466 return this.keyFromPrivate(priv);
37467 } while (true);
37468};
37469
37470EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
37471 var delta = msg.byteLength() * 8 - this.n.bitLength();
37472 if (delta > 0)
37473 msg = msg.ushrn(delta);
37474 if (!truncOnly && msg.cmp(this.n) >= 0)
37475 return msg.sub(this.n);
37476 else
37477 return msg;
37478};
37479
37480EC.prototype.sign = function sign(msg, key, enc, options) {
37481 if (typeof enc === 'object') {
37482 options = enc;
37483 enc = null;
37484 }
37485 if (!options)
37486 options = {};
37487
37488 key = this.keyFromPrivate(key, enc);
37489 msg = this._truncateToN(new BN(msg, 16));
37490
37491 // Zero-extend key to provide enough entropy
37492 var bytes = this.n.byteLength();
37493 var bkey = key.getPrivate().toArray('be', bytes);
37494
37495 // Zero-extend nonce to have the same byte size as N
37496 var nonce = msg.toArray('be', bytes);
37497
37498 // Instantiate Hmac_DRBG
37499 var drbg = new HmacDRBG({
37500 hash: this.hash,
37501 entropy: bkey,
37502 nonce: nonce,
37503 pers: options.pers,
37504 persEnc: options.persEnc || 'utf8'
37505 });
37506
37507 // Number of bytes to generate
37508 var ns1 = this.n.sub(new BN(1));
37509
37510 for (var iter = 0; true; iter++) {
37511 var k = options.k ?
37512 options.k(iter) :
37513 new BN(drbg.generate(this.n.byteLength()));
37514 k = this._truncateToN(k, true);
37515 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
37516 continue;
37517
37518 var kp = this.g.mul(k);
37519 if (kp.isInfinity())
37520 continue;
37521
37522 var kpX = kp.getX();
37523 var r = kpX.umod(this.n);
37524 if (r.cmpn(0) === 0)
37525 continue;
37526
37527 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
37528 s = s.umod(this.n);
37529 if (s.cmpn(0) === 0)
37530 continue;
37531
37532 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
37533 (kpX.cmp(r) !== 0 ? 2 : 0);
37534
37535 // Use complement of `s`, if it is > `n / 2`
37536 if (options.canonical && s.cmp(this.nh) > 0) {
37537 s = this.n.sub(s);
37538 recoveryParam ^= 1;
37539 }
37540
37541 return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
37542 }
37543};
37544
37545EC.prototype.verify = function verify(msg, signature, key, enc) {
37546 msg = this._truncateToN(new BN(msg, 16));
37547 key = this.keyFromPublic(key, enc);
37548 signature = new Signature(signature, 'hex');
37549
37550 // Perform primitive values validation
37551 var r = signature.r;
37552 var s = signature.s;
37553 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
37554 return false;
37555 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
37556 return false;
37557
37558 // Validate signature
37559 var sinv = s.invm(this.n);
37560 var u1 = sinv.mul(msg).umod(this.n);
37561 var u2 = sinv.mul(r).umod(this.n);
37562
37563 if (!this.curve._maxwellTrick) {
37564 var p = this.g.mulAdd(u1, key.getPublic(), u2);
37565 if (p.isInfinity())
37566 return false;
37567
37568 return p.getX().umod(this.n).cmp(r) === 0;
37569 }
37570
37571 // NOTE: Greg Maxwell's trick, inspired by:
37572 // https://git.io/vad3K
37573
37574 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
37575 if (p.isInfinity())
37576 return false;
37577
37578 // Compare `p.x` of Jacobian point with `r`,
37579 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
37580 // inverse of `p.z^2`
37581 return p.eqXToP(r);
37582};
37583
37584EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
37585 assert((3 & j) === j, 'The recovery param is more than two bits');
37586 signature = new Signature(signature, enc);
37587
37588 var n = this.n;
37589 var e = new BN(msg);
37590 var r = signature.r;
37591 var s = signature.s;
37592
37593 // A set LSB signifies that the y-coordinate is odd
37594 var isYOdd = j & 1;
37595 var isSecondKey = j >> 1;
37596 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
37597 throw new Error('Unable to find sencond key candinate');
37598
37599 // 1.1. Let x = r + jn.
37600 if (isSecondKey)
37601 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
37602 else
37603 r = this.curve.pointFromX(r, isYOdd);
37604
37605 var rInv = signature.r.invm(n);
37606 var s1 = n.sub(e).mul(rInv).umod(n);
37607 var s2 = s.mul(rInv).umod(n);
37608
37609 // 1.6.1 Compute Q = r^-1 (sR - eG)
37610 // Q = r^-1 (sR + -eG)
37611 return this.g.mulAdd(s1, r, s2);
37612};
37613
37614EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
37615 signature = new Signature(signature, enc);
37616 if (signature.recoveryParam !== null)
37617 return signature.recoveryParam;
37618
37619 for (var i = 0; i < 4; i++) {
37620 var Qprime;
37621 try {
37622 Qprime = this.recoverPubKey(e, signature, i);
37623 } catch (e) {
37624 continue;
37625 }
37626
37627 if (Qprime.eq(Q))
37628 return i;
37629 }
37630 throw new Error('Unable to find valid recovery factor');
37631};
37632
37633},{"../curves":162,"../utils":170,"./key":164,"./signature":165,"bn.js":80,"brorand":81,"hmac-drbg":204}],164:[function(require,module,exports){
37634'use strict';
37635
37636var BN = require('bn.js');
37637var utils = require('../utils');
37638var assert = utils.assert;
37639
37640function KeyPair(ec, options) {
37641 this.ec = ec;
37642 this.priv = null;
37643 this.pub = null;
37644
37645 // KeyPair(ec, { priv: ..., pub: ... })
37646 if (options.priv)
37647 this._importPrivate(options.priv, options.privEnc);
37648 if (options.pub)
37649 this._importPublic(options.pub, options.pubEnc);
37650}
37651module.exports = KeyPair;
37652
37653KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
37654 if (pub instanceof KeyPair)
37655 return pub;
37656
37657 return new KeyPair(ec, {
37658 pub: pub,
37659 pubEnc: enc
37660 });
37661};
37662
37663KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
37664 if (priv instanceof KeyPair)
37665 return priv;
37666
37667 return new KeyPair(ec, {
37668 priv: priv,
37669 privEnc: enc
37670 });
37671};
37672
37673KeyPair.prototype.validate = function validate() {
37674 var pub = this.getPublic();
37675
37676 if (pub.isInfinity())
37677 return { result: false, reason: 'Invalid public key' };
37678 if (!pub.validate())
37679 return { result: false, reason: 'Public key is not a point' };
37680 if (!pub.mul(this.ec.curve.n).isInfinity())
37681 return { result: false, reason: 'Public key * N != O' };
37682
37683 return { result: true, reason: null };
37684};
37685
37686KeyPair.prototype.getPublic = function getPublic(compact, enc) {
37687 // compact is optional argument
37688 if (typeof compact === 'string') {
37689 enc = compact;
37690 compact = null;
37691 }
37692
37693 if (!this.pub)
37694 this.pub = this.ec.g.mul(this.priv);
37695
37696 if (!enc)
37697 return this.pub;
37698
37699 return this.pub.encode(enc, compact);
37700};
37701
37702KeyPair.prototype.getPrivate = function getPrivate(enc) {
37703 if (enc === 'hex')
37704 return this.priv.toString(16, 2);
37705 else
37706 return this.priv;
37707};
37708
37709KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
37710 this.priv = new BN(key, enc || 16);
37711
37712 // Ensure that the priv won't be bigger than n, otherwise we may fail
37713 // in fixed multiplication method
37714 this.priv = this.priv.umod(this.ec.curve.n);
37715};
37716
37717KeyPair.prototype._importPublic = function _importPublic(key, enc) {
37718 if (key.x || key.y) {
37719 // Montgomery points only have an `x` coordinate.
37720 // Weierstrass/Edwards points on the other hand have both `x` and
37721 // `y` coordinates.
37722 if (this.ec.curve.type === 'mont') {
37723 assert(key.x, 'Need x coordinate');
37724 } else if (this.ec.curve.type === 'short' ||
37725 this.ec.curve.type === 'edwards') {
37726 assert(key.x && key.y, 'Need both x and y coordinate');
37727 }
37728 this.pub = this.ec.curve.point(key.x, key.y);
37729 return;
37730 }
37731 this.pub = this.ec.curve.decodePoint(key, enc);
37732};
37733
37734// ECDH
37735KeyPair.prototype.derive = function derive(pub) {
37736 return pub.mul(this.priv).getX();
37737};
37738
37739// ECDSA
37740KeyPair.prototype.sign = function sign(msg, enc, options) {
37741 return this.ec.sign(msg, this, enc, options);
37742};
37743
37744KeyPair.prototype.verify = function verify(msg, signature) {
37745 return this.ec.verify(msg, signature, this);
37746};
37747
37748KeyPair.prototype.inspect = function inspect() {
37749 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
37750 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
37751};
37752
37753},{"../utils":170,"bn.js":80}],165:[function(require,module,exports){
37754'use strict';
37755
37756var BN = require('bn.js');
37757
37758var utils = require('../utils');
37759var assert = utils.assert;
37760
37761function Signature(options, enc) {
37762 if (options instanceof Signature)
37763 return options;
37764
37765 if (this._importDER(options, enc))
37766 return;
37767
37768 assert(options.r && options.s, 'Signature without r or s');
37769 this.r = new BN(options.r, 16);
37770 this.s = new BN(options.s, 16);
37771 if (options.recoveryParam === undefined)
37772 this.recoveryParam = null;
37773 else
37774 this.recoveryParam = options.recoveryParam;
37775}
37776module.exports = Signature;
37777
37778function Position() {
37779 this.place = 0;
37780}
37781
37782function getLength(buf, p) {
37783 var initial = buf[p.place++];
37784 if (!(initial & 0x80)) {
37785 return initial;
37786 }
37787 var octetLen = initial & 0xf;
37788
37789 // Indefinite length or overflow
37790 if (octetLen === 0 || octetLen > 4) {
37791 return false;
37792 }
37793
37794 var val = 0;
37795 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
37796 val <<= 8;
37797 val |= buf[off];
37798 val >>>= 0;
37799 }
37800
37801 // Leading zeroes
37802 if (val <= 0x7f) {
37803 return false;
37804 }
37805
37806 p.place = off;
37807 return val;
37808}
37809
37810function rmPadding(buf) {
37811 var i = 0;
37812 var len = buf.length - 1;
37813 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
37814 i++;
37815 }
37816 if (i === 0) {
37817 return buf;
37818 }
37819 return buf.slice(i);
37820}
37821
37822Signature.prototype._importDER = function _importDER(data, enc) {
37823 data = utils.toArray(data, enc);
37824 var p = new Position();
37825 if (data[p.place++] !== 0x30) {
37826 return false;
37827 }
37828 var len = getLength(data, p);
37829 if (len === false) {
37830 return false;
37831 }
37832 if ((len + p.place) !== data.length) {
37833 return false;
37834 }
37835 if (data[p.place++] !== 0x02) {
37836 return false;
37837 }
37838 var rlen = getLength(data, p);
37839 if (rlen === false) {
37840 return false;
37841 }
37842 var r = data.slice(p.place, rlen + p.place);
37843 p.place += rlen;
37844 if (data[p.place++] !== 0x02) {
37845 return false;
37846 }
37847 var slen = getLength(data, p);
37848 if (slen === false) {
37849 return false;
37850 }
37851 if (data.length !== slen + p.place) {
37852 return false;
37853 }
37854 var s = data.slice(p.place, slen + p.place);
37855 if (r[0] === 0) {
37856 if (r[1] & 0x80) {
37857 r = r.slice(1);
37858 } else {
37859 // Leading zeroes
37860 return false;
37861 }
37862 }
37863 if (s[0] === 0) {
37864 if (s[1] & 0x80) {
37865 s = s.slice(1);
37866 } else {
37867 // Leading zeroes
37868 return false;
37869 }
37870 }
37871
37872 this.r = new BN(r);
37873 this.s = new BN(s);
37874 this.recoveryParam = null;
37875
37876 return true;
37877};
37878
37879function constructLength(arr, len) {
37880 if (len < 0x80) {
37881 arr.push(len);
37882 return;
37883 }
37884 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
37885 arr.push(octets | 0x80);
37886 while (--octets) {
37887 arr.push((len >>> (octets << 3)) & 0xff);
37888 }
37889 arr.push(len);
37890}
37891
37892Signature.prototype.toDER = function toDER(enc) {
37893 var r = this.r.toArray();
37894 var s = this.s.toArray();
37895
37896 // Pad values
37897 if (r[0] & 0x80)
37898 r = [ 0 ].concat(r);
37899 // Pad values
37900 if (s[0] & 0x80)
37901 s = [ 0 ].concat(s);
37902
37903 r = rmPadding(r);
37904 s = rmPadding(s);
37905
37906 while (!s[0] && !(s[1] & 0x80)) {
37907 s = s.slice(1);
37908 }
37909 var arr = [ 0x02 ];
37910 constructLength(arr, r.length);
37911 arr = arr.concat(r);
37912 arr.push(0x02);
37913 constructLength(arr, s.length);
37914 var backHalf = arr.concat(s);
37915 var res = [ 0x30 ];
37916 constructLength(res, backHalf.length);
37917 res = res.concat(backHalf);
37918 return utils.encode(res, enc);
37919};
37920
37921},{"../utils":170,"bn.js":80}],166:[function(require,module,exports){
37922'use strict';
37923
37924var hash = require('hash.js');
37925var curves = require('../curves');
37926var utils = require('../utils');
37927var assert = utils.assert;
37928var parseBytes = utils.parseBytes;
37929var KeyPair = require('./key');
37930var Signature = require('./signature');
37931
37932function EDDSA(curve) {
37933 assert(curve === 'ed25519', 'only tested with ed25519 so far');
37934
37935 if (!(this instanceof EDDSA))
37936 return new EDDSA(curve);
37937
37938 var curve = curves[curve].curve;
37939 this.curve = curve;
37940 this.g = curve.g;
37941 this.g.precompute(curve.n.bitLength() + 1);
37942
37943 this.pointClass = curve.point().constructor;
37944 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
37945 this.hash = hash.sha512;
37946}
37947
37948module.exports = EDDSA;
37949
37950/**
37951* @param {Array|String} message - message bytes
37952* @param {Array|String|KeyPair} secret - secret bytes or a keypair
37953* @returns {Signature} - signature
37954*/
37955EDDSA.prototype.sign = function sign(message, secret) {
37956 message = parseBytes(message);
37957 var key = this.keyFromSecret(secret);
37958 var r = this.hashInt(key.messagePrefix(), message);
37959 var R = this.g.mul(r);
37960 var Rencoded = this.encodePoint(R);
37961 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
37962 .mul(key.priv());
37963 var S = r.add(s_).umod(this.curve.n);
37964 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
37965};
37966
37967/**
37968* @param {Array} message - message bytes
37969* @param {Array|String|Signature} sig - sig bytes
37970* @param {Array|String|Point|KeyPair} pub - public key
37971* @returns {Boolean} - true if public key matches sig of message
37972*/
37973EDDSA.prototype.verify = function verify(message, sig, pub) {
37974 message = parseBytes(message);
37975 sig = this.makeSignature(sig);
37976 var key = this.keyFromPublic(pub);
37977 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
37978 var SG = this.g.mul(sig.S());
37979 var RplusAh = sig.R().add(key.pub().mul(h));
37980 return RplusAh.eq(SG);
37981};
37982
37983EDDSA.prototype.hashInt = function hashInt() {
37984 var hash = this.hash();
37985 for (var i = 0; i < arguments.length; i++)
37986 hash.update(arguments[i]);
37987 return utils.intFromLE(hash.digest()).umod(this.curve.n);
37988};
37989
37990EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
37991 return KeyPair.fromPublic(this, pub);
37992};
37993
37994EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
37995 return KeyPair.fromSecret(this, secret);
37996};
37997
37998EDDSA.prototype.makeSignature = function makeSignature(sig) {
37999 if (sig instanceof Signature)
38000 return sig;
38001 return new Signature(this, sig);
38002};
38003
38004/**
38005* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
38006*
38007* EDDSA defines methods for encoding and decoding points and integers. These are
38008* helper convenience methods, that pass along to utility functions implied
38009* parameters.
38010*
38011*/
38012EDDSA.prototype.encodePoint = function encodePoint(point) {
38013 var enc = point.getY().toArray('le', this.encodingLength);
38014 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
38015 return enc;
38016};
38017
38018EDDSA.prototype.decodePoint = function decodePoint(bytes) {
38019 bytes = utils.parseBytes(bytes);
38020
38021 var lastIx = bytes.length - 1;
38022 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
38023 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
38024
38025 var y = utils.intFromLE(normed);
38026 return this.curve.pointFromY(y, xIsOdd);
38027};
38028
38029EDDSA.prototype.encodeInt = function encodeInt(num) {
38030 return num.toArray('le', this.encodingLength);
38031};
38032
38033EDDSA.prototype.decodeInt = function decodeInt(bytes) {
38034 return utils.intFromLE(bytes);
38035};
38036
38037EDDSA.prototype.isPoint = function isPoint(val) {
38038 return val instanceof this.pointClass;
38039};
38040
38041},{"../curves":162,"../utils":170,"./key":167,"./signature":168,"hash.js":191}],167:[function(require,module,exports){
38042'use strict';
38043
38044var utils = require('../utils');
38045var assert = utils.assert;
38046var parseBytes = utils.parseBytes;
38047var cachedProperty = utils.cachedProperty;
38048
38049/**
38050* @param {EDDSA} eddsa - instance
38051* @param {Object} params - public/private key parameters
38052*
38053* @param {Array<Byte>} [params.secret] - secret seed bytes
38054* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
38055* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
38056*
38057*/
38058function KeyPair(eddsa, params) {
38059 this.eddsa = eddsa;
38060 this._secret = parseBytes(params.secret);
38061 if (eddsa.isPoint(params.pub))
38062 this._pub = params.pub;
38063 else
38064 this._pubBytes = parseBytes(params.pub);
38065}
38066
38067KeyPair.fromPublic = function fromPublic(eddsa, pub) {
38068 if (pub instanceof KeyPair)
38069 return pub;
38070 return new KeyPair(eddsa, { pub: pub });
38071};
38072
38073KeyPair.fromSecret = function fromSecret(eddsa, secret) {
38074 if (secret instanceof KeyPair)
38075 return secret;
38076 return new KeyPair(eddsa, { secret: secret });
38077};
38078
38079KeyPair.prototype.secret = function secret() {
38080 return this._secret;
38081};
38082
38083cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
38084 return this.eddsa.encodePoint(this.pub());
38085});
38086
38087cachedProperty(KeyPair, 'pub', function pub() {
38088 if (this._pubBytes)
38089 return this.eddsa.decodePoint(this._pubBytes);
38090 return this.eddsa.g.mul(this.priv());
38091});
38092
38093cachedProperty(KeyPair, 'privBytes', function privBytes() {
38094 var eddsa = this.eddsa;
38095 var hash = this.hash();
38096 var lastIx = eddsa.encodingLength - 1;
38097
38098 var a = hash.slice(0, eddsa.encodingLength);
38099 a[0] &= 248;
38100 a[lastIx] &= 127;
38101 a[lastIx] |= 64;
38102
38103 return a;
38104});
38105
38106cachedProperty(KeyPair, 'priv', function priv() {
38107 return this.eddsa.decodeInt(this.privBytes());
38108});
38109
38110cachedProperty(KeyPair, 'hash', function hash() {
38111 return this.eddsa.hash().update(this.secret()).digest();
38112});
38113
38114cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
38115 return this.hash().slice(this.eddsa.encodingLength);
38116});
38117
38118KeyPair.prototype.sign = function sign(message) {
38119 assert(this._secret, 'KeyPair can only verify');
38120 return this.eddsa.sign(message, this);
38121};
38122
38123KeyPair.prototype.verify = function verify(message, sig) {
38124 return this.eddsa.verify(message, sig, this);
38125};
38126
38127KeyPair.prototype.getSecret = function getSecret(enc) {
38128 assert(this._secret, 'KeyPair is public only');
38129 return utils.encode(this.secret(), enc);
38130};
38131
38132KeyPair.prototype.getPublic = function getPublic(enc) {
38133 return utils.encode(this.pubBytes(), enc);
38134};
38135
38136module.exports = KeyPair;
38137
38138},{"../utils":170}],168:[function(require,module,exports){
38139'use strict';
38140
38141var BN = require('bn.js');
38142var utils = require('../utils');
38143var assert = utils.assert;
38144var cachedProperty = utils.cachedProperty;
38145var parseBytes = utils.parseBytes;
38146
38147/**
38148* @param {EDDSA} eddsa - eddsa instance
38149* @param {Array<Bytes>|Object} sig -
38150* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
38151* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
38152* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
38153* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
38154*/
38155function Signature(eddsa, sig) {
38156 this.eddsa = eddsa;
38157
38158 if (typeof sig !== 'object')
38159 sig = parseBytes(sig);
38160
38161 if (Array.isArray(sig)) {
38162 sig = {
38163 R: sig.slice(0, eddsa.encodingLength),
38164 S: sig.slice(eddsa.encodingLength)
38165 };
38166 }
38167
38168 assert(sig.R && sig.S, 'Signature without R or S');
38169
38170 if (eddsa.isPoint(sig.R))
38171 this._R = sig.R;
38172 if (sig.S instanceof BN)
38173 this._S = sig.S;
38174
38175 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
38176 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
38177}
38178
38179cachedProperty(Signature, 'S', function S() {
38180 return this.eddsa.decodeInt(this.Sencoded());
38181});
38182
38183cachedProperty(Signature, 'R', function R() {
38184 return this.eddsa.decodePoint(this.Rencoded());
38185});
38186
38187cachedProperty(Signature, 'Rencoded', function Rencoded() {
38188 return this.eddsa.encodePoint(this.R());
38189});
38190
38191cachedProperty(Signature, 'Sencoded', function Sencoded() {
38192 return this.eddsa.encodeInt(this.S());
38193});
38194
38195Signature.prototype.toBytes = function toBytes() {
38196 return this.Rencoded().concat(this.Sencoded());
38197};
38198
38199Signature.prototype.toHex = function toHex() {
38200 return utils.encode(this.toBytes(), 'hex').toUpperCase();
38201};
38202
38203module.exports = Signature;
38204
38205},{"../utils":170,"bn.js":80}],169:[function(require,module,exports){
38206module.exports = {
38207 doubles: {
38208 step: 4,
38209 points: [
38210 [
38211 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
38212 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
38213 ],
38214 [
38215 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
38216 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
38217 ],
38218 [
38219 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
38220 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
38221 ],
38222 [
38223 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
38224 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
38225 ],
38226 [
38227 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
38228 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
38229 ],
38230 [
38231 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
38232 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
38233 ],
38234 [
38235 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
38236 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
38237 ],
38238 [
38239 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
38240 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
38241 ],
38242 [
38243 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
38244 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
38245 ],
38246 [
38247 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
38248 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
38249 ],
38250 [
38251 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
38252 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
38253 ],
38254 [
38255 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
38256 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
38257 ],
38258 [
38259 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
38260 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
38261 ],
38262 [
38263 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
38264 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
38265 ],
38266 [
38267 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
38268 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
38269 ],
38270 [
38271 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
38272 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
38273 ],
38274 [
38275 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
38276 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
38277 ],
38278 [
38279 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
38280 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
38281 ],
38282 [
38283 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
38284 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
38285 ],
38286 [
38287 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
38288 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
38289 ],
38290 [
38291 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
38292 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
38293 ],
38294 [
38295 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
38296 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
38297 ],
38298 [
38299 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
38300 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
38301 ],
38302 [
38303 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
38304 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
38305 ],
38306 [
38307 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
38308 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
38309 ],
38310 [
38311 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
38312 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
38313 ],
38314 [
38315 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
38316 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
38317 ],
38318 [
38319 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
38320 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
38321 ],
38322 [
38323 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
38324 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
38325 ],
38326 [
38327 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
38328 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
38329 ],
38330 [
38331 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
38332 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
38333 ],
38334 [
38335 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
38336 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
38337 ],
38338 [
38339 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
38340 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
38341 ],
38342 [
38343 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
38344 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
38345 ],
38346 [
38347 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
38348 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
38349 ],
38350 [
38351 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
38352 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
38353 ],
38354 [
38355 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
38356 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
38357 ],
38358 [
38359 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
38360 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
38361 ],
38362 [
38363 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
38364 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
38365 ],
38366 [
38367 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
38368 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
38369 ],
38370 [
38371 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
38372 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
38373 ],
38374 [
38375 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
38376 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
38377 ],
38378 [
38379 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
38380 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
38381 ],
38382 [
38383 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
38384 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
38385 ],
38386 [
38387 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
38388 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
38389 ],
38390 [
38391 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
38392 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
38393 ],
38394 [
38395 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
38396 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
38397 ],
38398 [
38399 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
38400 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
38401 ],
38402 [
38403 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
38404 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
38405 ],
38406 [
38407 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
38408 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
38409 ],
38410 [
38411 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
38412 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
38413 ],
38414 [
38415 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
38416 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
38417 ],
38418 [
38419 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
38420 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
38421 ],
38422 [
38423 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
38424 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
38425 ],
38426 [
38427 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
38428 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
38429 ],
38430 [
38431 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
38432 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
38433 ],
38434 [
38435 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
38436 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
38437 ],
38438 [
38439 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
38440 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
38441 ],
38442 [
38443 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
38444 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
38445 ],
38446 [
38447 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
38448 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
38449 ],
38450 [
38451 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
38452 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
38453 ],
38454 [
38455 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
38456 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
38457 ],
38458 [
38459 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
38460 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
38461 ],
38462 [
38463 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
38464 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
38465 ],
38466 [
38467 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
38468 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
38469 ]
38470 ]
38471 },
38472 naf: {
38473 wnd: 7,
38474 points: [
38475 [
38476 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
38477 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
38478 ],
38479 [
38480 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
38481 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
38482 ],
38483 [
38484 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
38485 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
38486 ],
38487 [
38488 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
38489 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
38490 ],
38491 [
38492 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
38493 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
38494 ],
38495 [
38496 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
38497 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
38498 ],
38499 [
38500 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
38501 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
38502 ],
38503 [
38504 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
38505 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
38506 ],
38507 [
38508 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
38509 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
38510 ],
38511 [
38512 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
38513 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
38514 ],
38515 [
38516 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
38517 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
38518 ],
38519 [
38520 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
38521 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
38522 ],
38523 [
38524 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
38525 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
38526 ],
38527 [
38528 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
38529 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
38530 ],
38531 [
38532 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
38533 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
38534 ],
38535 [
38536 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
38537 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
38538 ],
38539 [
38540 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
38541 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
38542 ],
38543 [
38544 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
38545 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
38546 ],
38547 [
38548 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
38549 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
38550 ],
38551 [
38552 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
38553 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
38554 ],
38555 [
38556 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
38557 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
38558 ],
38559 [
38560 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
38561 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
38562 ],
38563 [
38564 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
38565 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
38566 ],
38567 [
38568 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
38569 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
38570 ],
38571 [
38572 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
38573 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
38574 ],
38575 [
38576 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
38577 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
38578 ],
38579 [
38580 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
38581 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
38582 ],
38583 [
38584 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
38585 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
38586 ],
38587 [
38588 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
38589 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
38590 ],
38591 [
38592 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
38593 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
38594 ],
38595 [
38596 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
38597 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
38598 ],
38599 [
38600 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
38601 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
38602 ],
38603 [
38604 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
38605 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
38606 ],
38607 [
38608 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
38609 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
38610 ],
38611 [
38612 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
38613 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
38614 ],
38615 [
38616 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
38617 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
38618 ],
38619 [
38620 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
38621 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
38622 ],
38623 [
38624 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
38625 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
38626 ],
38627 [
38628 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
38629 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
38630 ],
38631 [
38632 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
38633 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
38634 ],
38635 [
38636 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
38637 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
38638 ],
38639 [
38640 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
38641 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
38642 ],
38643 [
38644 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
38645 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
38646 ],
38647 [
38648 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
38649 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
38650 ],
38651 [
38652 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
38653 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
38654 ],
38655 [
38656 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
38657 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
38658 ],
38659 [
38660 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
38661 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
38662 ],
38663 [
38664 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
38665 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
38666 ],
38667 [
38668 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
38669 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
38670 ],
38671 [
38672 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
38673 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
38674 ],
38675 [
38676 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
38677 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
38678 ],
38679 [
38680 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
38681 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
38682 ],
38683 [
38684 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
38685 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
38686 ],
38687 [
38688 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
38689 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
38690 ],
38691 [
38692 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
38693 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
38694 ],
38695 [
38696 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
38697 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
38698 ],
38699 [
38700 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
38701 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
38702 ],
38703 [
38704 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
38705 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
38706 ],
38707 [
38708 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
38709 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
38710 ],
38711 [
38712 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
38713 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
38714 ],
38715 [
38716 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
38717 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
38718 ],
38719 [
38720 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
38721 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
38722 ],
38723 [
38724 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
38725 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
38726 ],
38727 [
38728 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
38729 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
38730 ],
38731 [
38732 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
38733 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
38734 ],
38735 [
38736 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
38737 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
38738 ],
38739 [
38740 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
38741 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
38742 ],
38743 [
38744 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
38745 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
38746 ],
38747 [
38748 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
38749 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
38750 ],
38751 [
38752 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
38753 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
38754 ],
38755 [
38756 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
38757 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
38758 ],
38759 [
38760 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
38761 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
38762 ],
38763 [
38764 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
38765 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
38766 ],
38767 [
38768 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
38769 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
38770 ],
38771 [
38772 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
38773 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
38774 ],
38775 [
38776 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
38777 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
38778 ],
38779 [
38780 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
38781 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
38782 ],
38783 [
38784 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
38785 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
38786 ],
38787 [
38788 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
38789 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
38790 ],
38791 [
38792 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
38793 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
38794 ],
38795 [
38796 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
38797 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
38798 ],
38799 [
38800 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
38801 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
38802 ],
38803 [
38804 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
38805 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
38806 ],
38807 [
38808 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
38809 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
38810 ],
38811 [
38812 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
38813 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
38814 ],
38815 [
38816 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
38817 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
38818 ],
38819 [
38820 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
38821 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
38822 ],
38823 [
38824 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
38825 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
38826 ],
38827 [
38828 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
38829 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
38830 ],
38831 [
38832 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
38833 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
38834 ],
38835 [
38836 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
38837 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
38838 ],
38839 [
38840 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
38841 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
38842 ],
38843 [
38844 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
38845 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
38846 ],
38847 [
38848 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
38849 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
38850 ],
38851 [
38852 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
38853 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
38854 ],
38855 [
38856 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
38857 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
38858 ],
38859 [
38860 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
38861 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
38862 ],
38863 [
38864 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
38865 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
38866 ],
38867 [
38868 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
38869 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
38870 ],
38871 [
38872 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
38873 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
38874 ],
38875 [
38876 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
38877 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
38878 ],
38879 [
38880 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
38881 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
38882 ],
38883 [
38884 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
38885 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
38886 ],
38887 [
38888 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
38889 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
38890 ],
38891 [
38892 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
38893 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
38894 ],
38895 [
38896 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
38897 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
38898 ],
38899 [
38900 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
38901 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
38902 ],
38903 [
38904 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
38905 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
38906 ],
38907 [
38908 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
38909 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
38910 ],
38911 [
38912 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
38913 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
38914 ],
38915 [
38916 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
38917 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
38918 ],
38919 [
38920 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
38921 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
38922 ],
38923 [
38924 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
38925 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
38926 ],
38927 [
38928 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
38929 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
38930 ],
38931 [
38932 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
38933 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
38934 ],
38935 [
38936 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
38937 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
38938 ],
38939 [
38940 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
38941 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
38942 ],
38943 [
38944 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
38945 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
38946 ],
38947 [
38948 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
38949 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
38950 ],
38951 [
38952 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
38953 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
38954 ],
38955 [
38956 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
38957 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
38958 ],
38959 [
38960 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
38961 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
38962 ],
38963 [
38964 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
38965 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
38966 ],
38967 [
38968 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
38969 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
38970 ],
38971 [
38972 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
38973 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
38974 ],
38975 [
38976 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
38977 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
38978 ],
38979 [
38980 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
38981 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
38982 ]
38983 ]
38984 }
38985};
38986
38987},{}],170:[function(require,module,exports){
38988'use strict';
38989
38990var utils = exports;
38991var BN = require('bn.js');
38992var minAssert = require('minimalistic-assert');
38993var minUtils = require('minimalistic-crypto-utils');
38994
38995utils.assert = minAssert;
38996utils.toArray = minUtils.toArray;
38997utils.zero2 = minUtils.zero2;
38998utils.toHex = minUtils.toHex;
38999utils.encode = minUtils.encode;
39000
39001// Represent num in a w-NAF form
39002function getNAF(num, w, bits) {
39003 var naf = new Array(Math.max(num.bitLength(), bits) + 1);
39004 naf.fill(0);
39005
39006 var ws = 1 << (w + 1);
39007 var k = num.clone();
39008
39009 for (var i = 0; i < naf.length; i++) {
39010 var z;
39011 var mod = k.andln(ws - 1);
39012 if (k.isOdd()) {
39013 if (mod > (ws >> 1) - 1)
39014 z = (ws >> 1) - mod;
39015 else
39016 z = mod;
39017 k.isubn(z);
39018 } else {
39019 z = 0;
39020 }
39021
39022 naf[i] = z;
39023 k.iushrn(1);
39024 }
39025
39026 return naf;
39027}
39028utils.getNAF = getNAF;
39029
39030// Represent k1, k2 in a Joint Sparse Form
39031function getJSF(k1, k2) {
39032 var jsf = [
39033 [],
39034 []
39035 ];
39036
39037 k1 = k1.clone();
39038 k2 = k2.clone();
39039 var d1 = 0;
39040 var d2 = 0;
39041 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
39042
39043 // First phase
39044 var m14 = (k1.andln(3) + d1) & 3;
39045 var m24 = (k2.andln(3) + d2) & 3;
39046 if (m14 === 3)
39047 m14 = -1;
39048 if (m24 === 3)
39049 m24 = -1;
39050 var u1;
39051 if ((m14 & 1) === 0) {
39052 u1 = 0;
39053 } else {
39054 var m8 = (k1.andln(7) + d1) & 7;
39055 if ((m8 === 3 || m8 === 5) && m24 === 2)
39056 u1 = -m14;
39057 else
39058 u1 = m14;
39059 }
39060 jsf[0].push(u1);
39061
39062 var u2;
39063 if ((m24 & 1) === 0) {
39064 u2 = 0;
39065 } else {
39066 var m8 = (k2.andln(7) + d2) & 7;
39067 if ((m8 === 3 || m8 === 5) && m14 === 2)
39068 u2 = -m24;
39069 else
39070 u2 = m24;
39071 }
39072 jsf[1].push(u2);
39073
39074 // Second phase
39075 if (2 * d1 === u1 + 1)
39076 d1 = 1 - d1;
39077 if (2 * d2 === u2 + 1)
39078 d2 = 1 - d2;
39079 k1.iushrn(1);
39080 k2.iushrn(1);
39081 }
39082
39083 return jsf;
39084}
39085utils.getJSF = getJSF;
39086
39087function cachedProperty(obj, name, computer) {
39088 var key = '_' + name;
39089 obj.prototype[name] = function cachedProperty() {
39090 return this[key] !== undefined ? this[key] :
39091 this[key] = computer.call(this);
39092 };
39093}
39094utils.cachedProperty = cachedProperty;
39095
39096function parseBytes(bytes) {
39097 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
39098 bytes;
39099}
39100utils.parseBytes = parseBytes;
39101
39102function intFromLE(bytes) {
39103 return new BN(bytes, 'hex', 'le');
39104}
39105utils.intFromLE = intFromLE;
39106
39107
39108},{"bn.js":80,"minimalistic-assert":213,"minimalistic-crypto-utils":214}],171:[function(require,module,exports){
39109module.exports={
39110 "_args": [
39111 [
39112 "elliptic@6.5.3",
39113 "/home/justin/repos/bitcore/packages/bitcore-lib"
39114 ]
39115 ],
39116 "_from": "elliptic@6.5.3",
39117 "_id": "elliptic@6.5.3",
39118 "_inBundle": false,
39119 "_integrity": "sha512-IMqzv5wNQf+E6aHeIqATs0tOLeOTwj1QKbRcS3jBbYkl5oLAserA8yJTT7/VyHUYG91PRmPyeQDObKLPpeS4dw==",
39120 "_location": "/elliptic",
39121 "_phantomChildren": {},
39122 "_requested": {
39123 "type": "version",
39124 "registry": true,
39125 "raw": "elliptic@6.5.3",
39126 "name": "elliptic",
39127 "escapedName": "elliptic",
39128 "rawSpec": "6.5.3",
39129 "saveSpec": null,
39130 "fetchSpec": "6.5.3"
39131 },
39132 "_requiredBy": [
39133 "/"
39134 ],
39135 "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-6.5.3.tgz",
39136 "_spec": "6.5.3",
39137 "_where": "/home/justin/repos/bitcore/packages/bitcore-lib",
39138 "author": {
39139 "name": "Fedor Indutny",
39140 "email": "fedor@indutny.com"
39141 },
39142 "bugs": {
39143 "url": "https://github.com/indutny/elliptic/issues"
39144 },
39145 "dependencies": {
39146 "bn.js": "^4.4.0",
39147 "brorand": "^1.0.1",
39148 "hash.js": "^1.0.0",
39149 "hmac-drbg": "^1.0.0",
39150 "inherits": "^2.0.1",
39151 "minimalistic-assert": "^1.0.0",
39152 "minimalistic-crypto-utils": "^1.0.0"
39153 },
39154 "description": "EC cryptography",
39155 "devDependencies": {
39156 "brfs": "^1.4.3",
39157 "coveralls": "^3.0.8",
39158 "grunt": "^1.0.4",
39159 "grunt-browserify": "^5.0.0",
39160 "grunt-cli": "^1.2.0",
39161 "grunt-contrib-connect": "^1.0.0",
39162 "grunt-contrib-copy": "^1.0.0",
39163 "grunt-contrib-uglify": "^1.0.1",
39164 "grunt-mocha-istanbul": "^3.0.1",
39165 "grunt-saucelabs": "^9.0.1",
39166 "istanbul": "^0.4.2",
39167 "jscs": "^3.0.7",
39168 "jshint": "^2.10.3",
39169 "mocha": "^6.2.2"
39170 },
39171 "files": [
39172 "lib"
39173 ],
39174 "homepage": "https://github.com/indutny/elliptic",
39175 "keywords": [
39176 "EC",
39177 "Elliptic",
39178 "curve",
39179 "Cryptography"
39180 ],
39181 "license": "MIT",
39182 "main": "lib/elliptic.js",
39183 "name": "elliptic",
39184 "repository": {
39185 "type": "git",
39186 "url": "git+ssh://git@github.com/indutny/elliptic.git"
39187 },
39188 "scripts": {
39189 "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
39190 "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
39191 "lint": "npm run jscs && npm run jshint",
39192 "test": "npm run lint && npm run unit",
39193 "unit": "istanbul test _mocha --reporter=spec test/index.js",
39194 "version": "grunt dist && git add dist/"
39195 },
39196 "version": "6.5.3"
39197}
39198
39199},{}],172:[function(require,module,exports){
39200// Copyright Joyent, Inc. and other Node contributors.
39201//
39202// Permission is hereby granted, free of charge, to any person obtaining a
39203// copy of this software and associated documentation files (the
39204// "Software"), to deal in the Software without restriction, including
39205// without limitation the rights to use, copy, modify, merge, publish,
39206// distribute, sublicense, and/or sell copies of the Software, and to permit
39207// persons to whom the Software is furnished to do so, subject to the
39208// following conditions:
39209//
39210// The above copyright notice and this permission notice shall be included
39211// in all copies or substantial portions of the Software.
39212//
39213// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
39214// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
39215// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
39216// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
39217// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
39218// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
39219// USE OR OTHER DEALINGS IN THE SOFTWARE.
39220
39221var objectCreate = Object.create || objectCreatePolyfill
39222var objectKeys = Object.keys || objectKeysPolyfill
39223var bind = Function.prototype.bind || functionBindPolyfill
39224
39225function EventEmitter() {
39226 if (!this._events || !Object.prototype.hasOwnProperty.call(this, '_events')) {
39227 this._events = objectCreate(null);
39228 this._eventsCount = 0;
39229 }
39230
39231 this._maxListeners = this._maxListeners || undefined;
39232}
39233module.exports = EventEmitter;
39234
39235// Backwards-compat with node 0.10.x
39236EventEmitter.EventEmitter = EventEmitter;
39237
39238EventEmitter.prototype._events = undefined;
39239EventEmitter.prototype._maxListeners = undefined;
39240
39241// By default EventEmitters will print a warning if more than 10 listeners are
39242// added to it. This is a useful default which helps finding memory leaks.
39243var defaultMaxListeners = 10;
39244
39245var hasDefineProperty;
39246try {
39247 var o = {};
39248 if (Object.defineProperty) Object.defineProperty(o, 'x', { value: 0 });
39249 hasDefineProperty = o.x === 0;
39250} catch (err) { hasDefineProperty = false }
39251if (hasDefineProperty) {
39252 Object.defineProperty(EventEmitter, 'defaultMaxListeners', {
39253 enumerable: true,
39254 get: function() {
39255 return defaultMaxListeners;
39256 },
39257 set: function(arg) {
39258 // check whether the input is a positive number (whose value is zero or
39259 // greater and not a NaN).
39260 if (typeof arg !== 'number' || arg < 0 || arg !== arg)
39261 throw new TypeError('"defaultMaxListeners" must be a positive number');
39262 defaultMaxListeners = arg;
39263 }
39264 });
39265} else {
39266 EventEmitter.defaultMaxListeners = defaultMaxListeners;
39267}
39268
39269// Obviously not all Emitters should be limited to 10. This function allows
39270// that to be increased. Set to zero for unlimited.
39271EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) {
39272 if (typeof n !== 'number' || n < 0 || isNaN(n))
39273 throw new TypeError('"n" argument must be a positive number');
39274 this._maxListeners = n;
39275 return this;
39276};
39277
39278function $getMaxListeners(that) {
39279 if (that._maxListeners === undefined)
39280 return EventEmitter.defaultMaxListeners;
39281 return that._maxListeners;
39282}
39283
39284EventEmitter.prototype.getMaxListeners = function getMaxListeners() {
39285 return $getMaxListeners(this);
39286};
39287
39288// These standalone emit* functions are used to optimize calling of event
39289// handlers for fast cases because emit() itself often has a variable number of
39290// arguments and can be deoptimized because of that. These functions always have
39291// the same number of arguments and thus do not get deoptimized, so the code
39292// inside them can execute faster.
39293function emitNone(handler, isFn, self) {
39294 if (isFn)
39295 handler.call(self);
39296 else {
39297 var len = handler.length;
39298 var listeners = arrayClone(handler, len);
39299 for (var i = 0; i < len; ++i)
39300 listeners[i].call(self);
39301 }
39302}
39303function emitOne(handler, isFn, self, arg1) {
39304 if (isFn)
39305 handler.call(self, arg1);
39306 else {
39307 var len = handler.length;
39308 var listeners = arrayClone(handler, len);
39309 for (var i = 0; i < len; ++i)
39310 listeners[i].call(self, arg1);
39311 }
39312}
39313function emitTwo(handler, isFn, self, arg1, arg2) {
39314 if (isFn)
39315 handler.call(self, arg1, arg2);
39316 else {
39317 var len = handler.length;
39318 var listeners = arrayClone(handler, len);
39319 for (var i = 0; i < len; ++i)
39320 listeners[i].call(self, arg1, arg2);
39321 }
39322}
39323function emitThree(handler, isFn, self, arg1, arg2, arg3) {
39324 if (isFn)
39325 handler.call(self, arg1, arg2, arg3);
39326 else {
39327 var len = handler.length;
39328 var listeners = arrayClone(handler, len);
39329 for (var i = 0; i < len; ++i)
39330 listeners[i].call(self, arg1, arg2, arg3);
39331 }
39332}
39333
39334function emitMany(handler, isFn, self, args) {
39335 if (isFn)
39336 handler.apply(self, args);
39337 else {
39338 var len = handler.length;
39339 var listeners = arrayClone(handler, len);
39340 for (var i = 0; i < len; ++i)
39341 listeners[i].apply(self, args);
39342 }
39343}
39344
39345EventEmitter.prototype.emit = function emit(type) {
39346 var er, handler, len, args, i, events;
39347 var doError = (type === 'error');
39348
39349 events = this._events;
39350 if (events)
39351 doError = (doError && events.error == null);
39352 else if (!doError)
39353 return false;
39354
39355 // If there is no 'error' event listener then throw.
39356 if (doError) {
39357 if (arguments.length > 1)
39358 er = arguments[1];
39359 if (er instanceof Error) {
39360 throw er; // Unhandled 'error' event
39361 } else {
39362 // At least give some kind of context to the user
39363 var err = new Error('Unhandled "error" event. (' + er + ')');
39364 err.context = er;
39365 throw err;
39366 }
39367 return false;
39368 }
39369
39370 handler = events[type];
39371
39372 if (!handler)
39373 return false;
39374
39375 var isFn = typeof handler === 'function';
39376 len = arguments.length;
39377 switch (len) {
39378 // fast cases
39379 case 1:
39380 emitNone(handler, isFn, this);
39381 break;
39382 case 2:
39383 emitOne(handler, isFn, this, arguments[1]);
39384 break;
39385 case 3:
39386 emitTwo(handler, isFn, this, arguments[1], arguments[2]);
39387 break;
39388 case 4:
39389 emitThree(handler, isFn, this, arguments[1], arguments[2], arguments[3]);
39390 break;
39391 // slower
39392 default:
39393 args = new Array(len - 1);
39394 for (i = 1; i < len; i++)
39395 args[i - 1] = arguments[i];
39396 emitMany(handler, isFn, this, args);
39397 }
39398
39399 return true;
39400};
39401
39402function _addListener(target, type, listener, prepend) {
39403 var m;
39404 var events;
39405 var existing;
39406
39407 if (typeof listener !== 'function')
39408 throw new TypeError('"listener" argument must be a function');
39409
39410 events = target._events;
39411 if (!events) {
39412 events = target._events = objectCreate(null);
39413 target._eventsCount = 0;
39414 } else {
39415 // To avoid recursion in the case that type === "newListener"! Before
39416 // adding it to the listeners, first emit "newListener".
39417 if (events.newListener) {
39418 target.emit('newListener', type,
39419 listener.listener ? listener.listener : listener);
39420
39421 // Re-assign `events` because a newListener handler could have caused the
39422 // this._events to be assigned to a new object
39423 events = target._events;
39424 }
39425 existing = events[type];
39426 }
39427
39428 if (!existing) {
39429 // Optimize the case of one listener. Don't need the extra array object.
39430 existing = events[type] = listener;
39431 ++target._eventsCount;
39432 } else {
39433 if (typeof existing === 'function') {
39434 // Adding the second element, need to change to array.
39435 existing = events[type] =
39436 prepend ? [listener, existing] : [existing, listener];
39437 } else {
39438 // If we've already got an array, just append.
39439 if (prepend) {
39440 existing.unshift(listener);
39441 } else {
39442 existing.push(listener);
39443 }
39444 }
39445
39446 // Check for listener leak
39447 if (!existing.warned) {
39448 m = $getMaxListeners(target);
39449 if (m && m > 0 && existing.length > m) {
39450 existing.warned = true;
39451 var w = new Error('Possible EventEmitter memory leak detected. ' +
39452 existing.length + ' "' + String(type) + '" listeners ' +
39453 'added. Use emitter.setMaxListeners() to ' +
39454 'increase limit.');
39455 w.name = 'MaxListenersExceededWarning';
39456 w.emitter = target;
39457 w.type = type;
39458 w.count = existing.length;
39459 if (typeof console === 'object' && console.warn) {
39460 console.warn('%s: %s', w.name, w.message);
39461 }
39462 }
39463 }
39464 }
39465
39466 return target;
39467}
39468
39469EventEmitter.prototype.addListener = function addListener(type, listener) {
39470 return _addListener(this, type, listener, false);
39471};
39472
39473EventEmitter.prototype.on = EventEmitter.prototype.addListener;
39474
39475EventEmitter.prototype.prependListener =
39476 function prependListener(type, listener) {
39477 return _addListener(this, type, listener, true);
39478 };
39479
39480function onceWrapper() {
39481 if (!this.fired) {
39482 this.target.removeListener(this.type, this.wrapFn);
39483 this.fired = true;
39484 switch (arguments.length) {
39485 case 0:
39486 return this.listener.call(this.target);
39487 case 1:
39488 return this.listener.call(this.target, arguments[0]);
39489 case 2:
39490 return this.listener.call(this.target, arguments[0], arguments[1]);
39491 case 3:
39492 return this.listener.call(this.target, arguments[0], arguments[1],
39493 arguments[2]);
39494 default:
39495 var args = new Array(arguments.length);
39496 for (var i = 0; i < args.length; ++i)
39497 args[i] = arguments[i];
39498 this.listener.apply(this.target, args);
39499 }
39500 }
39501}
39502
39503function _onceWrap(target, type, listener) {
39504 var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener };
39505 var wrapped = bind.call(onceWrapper, state);
39506 wrapped.listener = listener;
39507 state.wrapFn = wrapped;
39508 return wrapped;
39509}
39510
39511EventEmitter.prototype.once = function once(type, listener) {
39512 if (typeof listener !== 'function')
39513 throw new TypeError('"listener" argument must be a function');
39514 this.on(type, _onceWrap(this, type, listener));
39515 return this;
39516};
39517
39518EventEmitter.prototype.prependOnceListener =
39519 function prependOnceListener(type, listener) {
39520 if (typeof listener !== 'function')
39521 throw new TypeError('"listener" argument must be a function');
39522 this.prependListener(type, _onceWrap(this, type, listener));
39523 return this;
39524 };
39525
39526// Emits a 'removeListener' event if and only if the listener was removed.
39527EventEmitter.prototype.removeListener =
39528 function removeListener(type, listener) {
39529 var list, events, position, i, originalListener;
39530
39531 if (typeof listener !== 'function')
39532 throw new TypeError('"listener" argument must be a function');
39533
39534 events = this._events;
39535 if (!events)
39536 return this;
39537
39538 list = events[type];
39539 if (!list)
39540 return this;
39541
39542 if (list === listener || list.listener === listener) {
39543 if (--this._eventsCount === 0)
39544 this._events = objectCreate(null);
39545 else {
39546 delete events[type];
39547 if (events.removeListener)
39548 this.emit('removeListener', type, list.listener || listener);
39549 }
39550 } else if (typeof list !== 'function') {
39551 position = -1;
39552
39553 for (i = list.length - 1; i >= 0; i--) {
39554 if (list[i] === listener || list[i].listener === listener) {
39555 originalListener = list[i].listener;
39556 position = i;
39557 break;
39558 }
39559 }
39560
39561 if (position < 0)
39562 return this;
39563
39564 if (position === 0)
39565 list.shift();
39566 else
39567 spliceOne(list, position);
39568
39569 if (list.length === 1)
39570 events[type] = list[0];
39571
39572 if (events.removeListener)
39573 this.emit('removeListener', type, originalListener || listener);
39574 }
39575
39576 return this;
39577 };
39578
39579EventEmitter.prototype.removeAllListeners =
39580 function removeAllListeners(type) {
39581 var listeners, events, i;
39582
39583 events = this._events;
39584 if (!events)
39585 return this;
39586
39587 // not listening for removeListener, no need to emit
39588 if (!events.removeListener) {
39589 if (arguments.length === 0) {
39590 this._events = objectCreate(null);
39591 this._eventsCount = 0;
39592 } else if (events[type]) {
39593 if (--this._eventsCount === 0)
39594 this._events = objectCreate(null);
39595 else
39596 delete events[type];
39597 }
39598 return this;
39599 }
39600
39601 // emit removeListener for all listeners on all events
39602 if (arguments.length === 0) {
39603 var keys = objectKeys(events);
39604 var key;
39605 for (i = 0; i < keys.length; ++i) {
39606 key = keys[i];
39607 if (key === 'removeListener') continue;
39608 this.removeAllListeners(key);
39609 }
39610 this.removeAllListeners('removeListener');
39611 this._events = objectCreate(null);
39612 this._eventsCount = 0;
39613 return this;
39614 }
39615
39616 listeners = events[type];
39617
39618 if (typeof listeners === 'function') {
39619 this.removeListener(type, listeners);
39620 } else if (listeners) {
39621 // LIFO order
39622 for (i = listeners.length - 1; i >= 0; i--) {
39623 this.removeListener(type, listeners[i]);
39624 }
39625 }
39626
39627 return this;
39628 };
39629
39630function _listeners(target, type, unwrap) {
39631 var events = target._events;
39632
39633 if (!events)
39634 return [];
39635
39636 var evlistener = events[type];
39637 if (!evlistener)
39638 return [];
39639
39640 if (typeof evlistener === 'function')
39641 return unwrap ? [evlistener.listener || evlistener] : [evlistener];
39642
39643 return unwrap ? unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length);
39644}
39645
39646EventEmitter.prototype.listeners = function listeners(type) {
39647 return _listeners(this, type, true);
39648};
39649
39650EventEmitter.prototype.rawListeners = function rawListeners(type) {
39651 return _listeners(this, type, false);
39652};
39653
39654EventEmitter.listenerCount = function(emitter, type) {
39655 if (typeof emitter.listenerCount === 'function') {
39656 return emitter.listenerCount(type);
39657 } else {
39658 return listenerCount.call(emitter, type);
39659 }
39660};
39661
39662EventEmitter.prototype.listenerCount = listenerCount;
39663function listenerCount(type) {
39664 var events = this._events;
39665
39666 if (events) {
39667 var evlistener = events[type];
39668
39669 if (typeof evlistener === 'function') {
39670 return 1;
39671 } else if (evlistener) {
39672 return evlistener.length;
39673 }
39674 }
39675
39676 return 0;
39677}
39678
39679EventEmitter.prototype.eventNames = function eventNames() {
39680 return this._eventsCount > 0 ? Reflect.ownKeys(this._events) : [];
39681};
39682
39683// About 1.5x faster than the two-arg version of Array#splice().
39684function spliceOne(list, index) {
39685 for (var i = index, k = i + 1, n = list.length; k < n; i += 1, k += 1)
39686 list[i] = list[k];
39687 list.pop();
39688}
39689
39690function arrayClone(arr, n) {
39691 var copy = new Array(n);
39692 for (var i = 0; i < n; ++i)
39693 copy[i] = arr[i];
39694 return copy;
39695}
39696
39697function unwrapListeners(arr) {
39698 var ret = new Array(arr.length);
39699 for (var i = 0; i < ret.length; ++i) {
39700 ret[i] = arr[i].listener || arr[i];
39701 }
39702 return ret;
39703}
39704
39705function objectCreatePolyfill(proto) {
39706 var F = function() {};
39707 F.prototype = proto;
39708 return new F;
39709}
39710function objectKeysPolyfill(obj) {
39711 var keys = [];
39712 for (var k in obj) if (Object.prototype.hasOwnProperty.call(obj, k)) {
39713 keys.push(k);
39714 }
39715 return k;
39716}
39717function functionBindPolyfill(context) {
39718 var fn = this;
39719 return function () {
39720 return fn.apply(context, arguments);
39721 };
39722}
39723
39724},{}],173:[function(require,module,exports){
39725var Buffer = require('safe-buffer').Buffer
39726var MD5 = require('md5.js')
39727
39728/* eslint-disable camelcase */
39729function EVP_BytesToKey (password, salt, keyBits, ivLen) {
39730 if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
39731 if (salt) {
39732 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
39733 if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
39734 }
39735
39736 var keyLen = keyBits / 8
39737 var key = Buffer.alloc(keyLen)
39738 var iv = Buffer.alloc(ivLen || 0)
39739 var tmp = Buffer.alloc(0)
39740
39741 while (keyLen > 0 || ivLen > 0) {
39742 var hash = new MD5()
39743 hash.update(tmp)
39744 hash.update(password)
39745 if (salt) hash.update(salt)
39746 tmp = hash.digest()
39747
39748 var used = 0
39749
39750 if (keyLen > 0) {
39751 var keyStart = key.length - keyLen
39752 used = Math.min(keyLen, tmp.length)
39753 tmp.copy(key, keyStart, 0, used)
39754 keyLen -= used
39755 }
39756
39757 if (used < tmp.length && ivLen > 0) {
39758 var ivStart = iv.length - ivLen
39759 var length = Math.min(ivLen, tmp.length - used)
39760 tmp.copy(iv, ivStart, used, used + length)
39761 ivLen -= length
39762 }
39763 }
39764
39765 tmp.fill(0)
39766 return { key: key, iv: iv }
39767}
39768
39769module.exports = EVP_BytesToKey
39770
39771},{"md5.js":211,"safe-buffer":256}],174:[function(require,module,exports){
39772'use strict'
39773var Buffer = require('safe-buffer').Buffer
39774var Transform = require('readable-stream').Transform
39775var inherits = require('inherits')
39776
39777function throwIfNotStringOrBuffer (val, prefix) {
39778 if (!Buffer.isBuffer(val) && typeof val !== 'string') {
39779 throw new TypeError(prefix + ' must be a string or a buffer')
39780 }
39781}
39782
39783function HashBase (blockSize) {
39784 Transform.call(this)
39785
39786 this._block = Buffer.allocUnsafe(blockSize)
39787 this._blockSize = blockSize
39788 this._blockOffset = 0
39789 this._length = [0, 0, 0, 0]
39790
39791 this._finalized = false
39792}
39793
39794inherits(HashBase, Transform)
39795
39796HashBase.prototype._transform = function (chunk, encoding, callback) {
39797 var error = null
39798 try {
39799 this.update(chunk, encoding)
39800 } catch (err) {
39801 error = err
39802 }
39803
39804 callback(error)
39805}
39806
39807HashBase.prototype._flush = function (callback) {
39808 var error = null
39809 try {
39810 this.push(this.digest())
39811 } catch (err) {
39812 error = err
39813 }
39814
39815 callback(error)
39816}
39817
39818HashBase.prototype.update = function (data, encoding) {
39819 throwIfNotStringOrBuffer(data, 'Data')
39820 if (this._finalized) throw new Error('Digest already called')
39821 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
39822
39823 // consume data
39824 var block = this._block
39825 var offset = 0
39826 while (this._blockOffset + data.length - offset >= this._blockSize) {
39827 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
39828 this._update()
39829 this._blockOffset = 0
39830 }
39831 while (offset < data.length) block[this._blockOffset++] = data[offset++]
39832
39833 // update length
39834 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
39835 this._length[j] += carry
39836 carry = (this._length[j] / 0x0100000000) | 0
39837 if (carry > 0) this._length[j] -= 0x0100000000 * carry
39838 }
39839
39840 return this
39841}
39842
39843HashBase.prototype._update = function () {
39844 throw new Error('_update is not implemented')
39845}
39846
39847HashBase.prototype.digest = function (encoding) {
39848 if (this._finalized) throw new Error('Digest already called')
39849 this._finalized = true
39850
39851 var digest = this._digest()
39852 if (encoding !== undefined) digest = digest.toString(encoding)
39853
39854 // reset state
39855 this._block.fill(0)
39856 this._blockOffset = 0
39857 for (var i = 0; i < 4; ++i) this._length[i] = 0
39858
39859 return digest
39860}
39861
39862HashBase.prototype._digest = function () {
39863 throw new Error('_digest is not implemented')
39864}
39865
39866module.exports = HashBase
39867
39868},{"inherits":175,"readable-stream":190,"safe-buffer":256}],175:[function(require,module,exports){
39869arguments[4][112][0].apply(exports,arguments)
39870},{"dup":112}],176:[function(require,module,exports){
39871arguments[4][113][0].apply(exports,arguments)
39872},{"dup":113}],177:[function(require,module,exports){
39873arguments[4][114][0].apply(exports,arguments)
39874},{"./_stream_readable":179,"./_stream_writable":181,"_process":228,"dup":114,"inherits":175}],178:[function(require,module,exports){
39875arguments[4][115][0].apply(exports,arguments)
39876},{"./_stream_transform":180,"dup":115,"inherits":175}],179:[function(require,module,exports){
39877arguments[4][116][0].apply(exports,arguments)
39878},{"../errors":176,"./_stream_duplex":177,"./internal/streams/async_iterator":182,"./internal/streams/buffer_list":183,"./internal/streams/destroy":184,"./internal/streams/from":186,"./internal/streams/state":188,"./internal/streams/stream":189,"_process":228,"buffer":132,"dup":116,"events":172,"inherits":175,"string_decoder/":267,"util":82}],180:[function(require,module,exports){
39879arguments[4][117][0].apply(exports,arguments)
39880},{"../errors":176,"./_stream_duplex":177,"dup":117,"inherits":175}],181:[function(require,module,exports){
39881arguments[4][118][0].apply(exports,arguments)
39882},{"../errors":176,"./_stream_duplex":177,"./internal/streams/destroy":184,"./internal/streams/state":188,"./internal/streams/stream":189,"_process":228,"buffer":132,"dup":118,"inherits":175,"util-deprecate":272}],182:[function(require,module,exports){
39883arguments[4][119][0].apply(exports,arguments)
39884},{"./end-of-stream":185,"_process":228,"dup":119}],183:[function(require,module,exports){
39885arguments[4][120][0].apply(exports,arguments)
39886},{"buffer":132,"dup":120,"util":82}],184:[function(require,module,exports){
39887arguments[4][121][0].apply(exports,arguments)
39888},{"_process":228,"dup":121}],185:[function(require,module,exports){
39889arguments[4][122][0].apply(exports,arguments)
39890},{"../../../errors":176,"dup":122}],186:[function(require,module,exports){
39891arguments[4][123][0].apply(exports,arguments)
39892},{"dup":123}],187:[function(require,module,exports){
39893arguments[4][124][0].apply(exports,arguments)
39894},{"../../../errors":176,"./end-of-stream":185,"dup":124}],188:[function(require,module,exports){
39895arguments[4][125][0].apply(exports,arguments)
39896},{"../../../errors":176,"dup":125}],189:[function(require,module,exports){
39897arguments[4][126][0].apply(exports,arguments)
39898},{"dup":126,"events":172}],190:[function(require,module,exports){
39899arguments[4][127][0].apply(exports,arguments)
39900},{"./lib/_stream_duplex.js":177,"./lib/_stream_passthrough.js":178,"./lib/_stream_readable.js":179,"./lib/_stream_transform.js":180,"./lib/_stream_writable.js":181,"./lib/internal/streams/end-of-stream.js":185,"./lib/internal/streams/pipeline.js":187,"dup":127}],191:[function(require,module,exports){
39901var hash = exports;
39902
39903hash.utils = require('./hash/utils');
39904hash.common = require('./hash/common');
39905hash.sha = require('./hash/sha');
39906hash.ripemd = require('./hash/ripemd');
39907hash.hmac = require('./hash/hmac');
39908
39909// Proxy hash functions to the main object
39910hash.sha1 = hash.sha.sha1;
39911hash.sha256 = hash.sha.sha256;
39912hash.sha224 = hash.sha.sha224;
39913hash.sha384 = hash.sha.sha384;
39914hash.sha512 = hash.sha.sha512;
39915hash.ripemd160 = hash.ripemd.ripemd160;
39916
39917},{"./hash/common":192,"./hash/hmac":193,"./hash/ripemd":194,"./hash/sha":195,"./hash/utils":202}],192:[function(require,module,exports){
39918'use strict';
39919
39920var utils = require('./utils');
39921var assert = require('minimalistic-assert');
39922
39923function BlockHash() {
39924 this.pending = null;
39925 this.pendingTotal = 0;
39926 this.blockSize = this.constructor.blockSize;
39927 this.outSize = this.constructor.outSize;
39928 this.hmacStrength = this.constructor.hmacStrength;
39929 this.padLength = this.constructor.padLength / 8;
39930 this.endian = 'big';
39931
39932 this._delta8 = this.blockSize / 8;
39933 this._delta32 = this.blockSize / 32;
39934}
39935exports.BlockHash = BlockHash;
39936
39937BlockHash.prototype.update = function update(msg, enc) {
39938 // Convert message to array, pad it, and join into 32bit blocks
39939 msg = utils.toArray(msg, enc);
39940 if (!this.pending)
39941 this.pending = msg;
39942 else
39943 this.pending = this.pending.concat(msg);
39944 this.pendingTotal += msg.length;
39945
39946 // Enough data, try updating
39947 if (this.pending.length >= this._delta8) {
39948 msg = this.pending;
39949
39950 // Process pending data in blocks
39951 var r = msg.length % this._delta8;
39952 this.pending = msg.slice(msg.length - r, msg.length);
39953 if (this.pending.length === 0)
39954 this.pending = null;
39955
39956 msg = utils.join32(msg, 0, msg.length - r, this.endian);
39957 for (var i = 0; i < msg.length; i += this._delta32)
39958 this._update(msg, i, i + this._delta32);
39959 }
39960
39961 return this;
39962};
39963
39964BlockHash.prototype.digest = function digest(enc) {
39965 this.update(this._pad());
39966 assert(this.pending === null);
39967
39968 return this._digest(enc);
39969};
39970
39971BlockHash.prototype._pad = function pad() {
39972 var len = this.pendingTotal;
39973 var bytes = this._delta8;
39974 var k = bytes - ((len + this.padLength) % bytes);
39975 var res = new Array(k + this.padLength);
39976 res[0] = 0x80;
39977 for (var i = 1; i < k; i++)
39978 res[i] = 0;
39979
39980 // Append length
39981 len <<= 3;
39982 if (this.endian === 'big') {
39983 for (var t = 8; t < this.padLength; t++)
39984 res[i++] = 0;
39985
39986 res[i++] = 0;
39987 res[i++] = 0;
39988 res[i++] = 0;
39989 res[i++] = 0;
39990 res[i++] = (len >>> 24) & 0xff;
39991 res[i++] = (len >>> 16) & 0xff;
39992 res[i++] = (len >>> 8) & 0xff;
39993 res[i++] = len & 0xff;
39994 } else {
39995 res[i++] = len & 0xff;
39996 res[i++] = (len >>> 8) & 0xff;
39997 res[i++] = (len >>> 16) & 0xff;
39998 res[i++] = (len >>> 24) & 0xff;
39999 res[i++] = 0;
40000 res[i++] = 0;
40001 res[i++] = 0;
40002 res[i++] = 0;
40003
40004 for (t = 8; t < this.padLength; t++)
40005 res[i++] = 0;
40006 }
40007
40008 return res;
40009};
40010
40011},{"./utils":202,"minimalistic-assert":213}],193:[function(require,module,exports){
40012'use strict';
40013
40014var utils = require('./utils');
40015var assert = require('minimalistic-assert');
40016
40017function Hmac(hash, key, enc) {
40018 if (!(this instanceof Hmac))
40019 return new Hmac(hash, key, enc);
40020 this.Hash = hash;
40021 this.blockSize = hash.blockSize / 8;
40022 this.outSize = hash.outSize / 8;
40023 this.inner = null;
40024 this.outer = null;
40025
40026 this._init(utils.toArray(key, enc));
40027}
40028module.exports = Hmac;
40029
40030Hmac.prototype._init = function init(key) {
40031 // Shorten key, if needed
40032 if (key.length > this.blockSize)
40033 key = new this.Hash().update(key).digest();
40034 assert(key.length <= this.blockSize);
40035
40036 // Add padding to key
40037 for (var i = key.length; i < this.blockSize; i++)
40038 key.push(0);
40039
40040 for (i = 0; i < key.length; i++)
40041 key[i] ^= 0x36;
40042 this.inner = new this.Hash().update(key);
40043
40044 // 0x36 ^ 0x5c = 0x6a
40045 for (i = 0; i < key.length; i++)
40046 key[i] ^= 0x6a;
40047 this.outer = new this.Hash().update(key);
40048};
40049
40050Hmac.prototype.update = function update(msg, enc) {
40051 this.inner.update(msg, enc);
40052 return this;
40053};
40054
40055Hmac.prototype.digest = function digest(enc) {
40056 this.outer.update(this.inner.digest());
40057 return this.outer.digest(enc);
40058};
40059
40060},{"./utils":202,"minimalistic-assert":213}],194:[function(require,module,exports){
40061'use strict';
40062
40063var utils = require('./utils');
40064var common = require('./common');
40065
40066var rotl32 = utils.rotl32;
40067var sum32 = utils.sum32;
40068var sum32_3 = utils.sum32_3;
40069var sum32_4 = utils.sum32_4;
40070var BlockHash = common.BlockHash;
40071
40072function RIPEMD160() {
40073 if (!(this instanceof RIPEMD160))
40074 return new RIPEMD160();
40075
40076 BlockHash.call(this);
40077
40078 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
40079 this.endian = 'little';
40080}
40081utils.inherits(RIPEMD160, BlockHash);
40082exports.ripemd160 = RIPEMD160;
40083
40084RIPEMD160.blockSize = 512;
40085RIPEMD160.outSize = 160;
40086RIPEMD160.hmacStrength = 192;
40087RIPEMD160.padLength = 64;
40088
40089RIPEMD160.prototype._update = function update(msg, start) {
40090 var A = this.h[0];
40091 var B = this.h[1];
40092 var C = this.h[2];
40093 var D = this.h[3];
40094 var E = this.h[4];
40095 var Ah = A;
40096 var Bh = B;
40097 var Ch = C;
40098 var Dh = D;
40099 var Eh = E;
40100 for (var j = 0; j < 80; j++) {
40101 var T = sum32(
40102 rotl32(
40103 sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
40104 s[j]),
40105 E);
40106 A = E;
40107 E = D;
40108 D = rotl32(C, 10);
40109 C = B;
40110 B = T;
40111 T = sum32(
40112 rotl32(
40113 sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
40114 sh[j]),
40115 Eh);
40116 Ah = Eh;
40117 Eh = Dh;
40118 Dh = rotl32(Ch, 10);
40119 Ch = Bh;
40120 Bh = T;
40121 }
40122 T = sum32_3(this.h[1], C, Dh);
40123 this.h[1] = sum32_3(this.h[2], D, Eh);
40124 this.h[2] = sum32_3(this.h[3], E, Ah);
40125 this.h[3] = sum32_3(this.h[4], A, Bh);
40126 this.h[4] = sum32_3(this.h[0], B, Ch);
40127 this.h[0] = T;
40128};
40129
40130RIPEMD160.prototype._digest = function digest(enc) {
40131 if (enc === 'hex')
40132 return utils.toHex32(this.h, 'little');
40133 else
40134 return utils.split32(this.h, 'little');
40135};
40136
40137function f(j, x, y, z) {
40138 if (j <= 15)
40139 return x ^ y ^ z;
40140 else if (j <= 31)
40141 return (x & y) | ((~x) & z);
40142 else if (j <= 47)
40143 return (x | (~y)) ^ z;
40144 else if (j <= 63)
40145 return (x & z) | (y & (~z));
40146 else
40147 return x ^ (y | (~z));
40148}
40149
40150function K(j) {
40151 if (j <= 15)
40152 return 0x00000000;
40153 else if (j <= 31)
40154 return 0x5a827999;
40155 else if (j <= 47)
40156 return 0x6ed9eba1;
40157 else if (j <= 63)
40158 return 0x8f1bbcdc;
40159 else
40160 return 0xa953fd4e;
40161}
40162
40163function Kh(j) {
40164 if (j <= 15)
40165 return 0x50a28be6;
40166 else if (j <= 31)
40167 return 0x5c4dd124;
40168 else if (j <= 47)
40169 return 0x6d703ef3;
40170 else if (j <= 63)
40171 return 0x7a6d76e9;
40172 else
40173 return 0x00000000;
40174}
40175
40176var r = [
40177 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
40178 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
40179 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
40180 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
40181 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
40182];
40183
40184var rh = [
40185 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
40186 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
40187 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
40188 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
40189 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
40190];
40191
40192var s = [
40193 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
40194 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
40195 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
40196 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
40197 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
40198];
40199
40200var sh = [
40201 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
40202 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
40203 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
40204 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
40205 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
40206];
40207
40208},{"./common":192,"./utils":202}],195:[function(require,module,exports){
40209'use strict';
40210
40211exports.sha1 = require('./sha/1');
40212exports.sha224 = require('./sha/224');
40213exports.sha256 = require('./sha/256');
40214exports.sha384 = require('./sha/384');
40215exports.sha512 = require('./sha/512');
40216
40217},{"./sha/1":196,"./sha/224":197,"./sha/256":198,"./sha/384":199,"./sha/512":200}],196:[function(require,module,exports){
40218'use strict';
40219
40220var utils = require('../utils');
40221var common = require('../common');
40222var shaCommon = require('./common');
40223
40224var rotl32 = utils.rotl32;
40225var sum32 = utils.sum32;
40226var sum32_5 = utils.sum32_5;
40227var ft_1 = shaCommon.ft_1;
40228var BlockHash = common.BlockHash;
40229
40230var sha1_K = [
40231 0x5A827999, 0x6ED9EBA1,
40232 0x8F1BBCDC, 0xCA62C1D6
40233];
40234
40235function SHA1() {
40236 if (!(this instanceof SHA1))
40237 return new SHA1();
40238
40239 BlockHash.call(this);
40240 this.h = [
40241 0x67452301, 0xefcdab89, 0x98badcfe,
40242 0x10325476, 0xc3d2e1f0 ];
40243 this.W = new Array(80);
40244}
40245
40246utils.inherits(SHA1, BlockHash);
40247module.exports = SHA1;
40248
40249SHA1.blockSize = 512;
40250SHA1.outSize = 160;
40251SHA1.hmacStrength = 80;
40252SHA1.padLength = 64;
40253
40254SHA1.prototype._update = function _update(msg, start) {
40255 var W = this.W;
40256
40257 for (var i = 0; i < 16; i++)
40258 W[i] = msg[start + i];
40259
40260 for(; i < W.length; i++)
40261 W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
40262
40263 var a = this.h[0];
40264 var b = this.h[1];
40265 var c = this.h[2];
40266 var d = this.h[3];
40267 var e = this.h[4];
40268
40269 for (i = 0; i < W.length; i++) {
40270 var s = ~~(i / 20);
40271 var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
40272 e = d;
40273 d = c;
40274 c = rotl32(b, 30);
40275 b = a;
40276 a = t;
40277 }
40278
40279 this.h[0] = sum32(this.h[0], a);
40280 this.h[1] = sum32(this.h[1], b);
40281 this.h[2] = sum32(this.h[2], c);
40282 this.h[3] = sum32(this.h[3], d);
40283 this.h[4] = sum32(this.h[4], e);
40284};
40285
40286SHA1.prototype._digest = function digest(enc) {
40287 if (enc === 'hex')
40288 return utils.toHex32(this.h, 'big');
40289 else
40290 return utils.split32(this.h, 'big');
40291};
40292
40293},{"../common":192,"../utils":202,"./common":201}],197:[function(require,module,exports){
40294'use strict';
40295
40296var utils = require('../utils');
40297var SHA256 = require('./256');
40298
40299function SHA224() {
40300 if (!(this instanceof SHA224))
40301 return new SHA224();
40302
40303 SHA256.call(this);
40304 this.h = [
40305 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
40306 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
40307}
40308utils.inherits(SHA224, SHA256);
40309module.exports = SHA224;
40310
40311SHA224.blockSize = 512;
40312SHA224.outSize = 224;
40313SHA224.hmacStrength = 192;
40314SHA224.padLength = 64;
40315
40316SHA224.prototype._digest = function digest(enc) {
40317 // Just truncate output
40318 if (enc === 'hex')
40319 return utils.toHex32(this.h.slice(0, 7), 'big');
40320 else
40321 return utils.split32(this.h.slice(0, 7), 'big');
40322};
40323
40324
40325},{"../utils":202,"./256":198}],198:[function(require,module,exports){
40326'use strict';
40327
40328var utils = require('../utils');
40329var common = require('../common');
40330var shaCommon = require('./common');
40331var assert = require('minimalistic-assert');
40332
40333var sum32 = utils.sum32;
40334var sum32_4 = utils.sum32_4;
40335var sum32_5 = utils.sum32_5;
40336var ch32 = shaCommon.ch32;
40337var maj32 = shaCommon.maj32;
40338var s0_256 = shaCommon.s0_256;
40339var s1_256 = shaCommon.s1_256;
40340var g0_256 = shaCommon.g0_256;
40341var g1_256 = shaCommon.g1_256;
40342
40343var BlockHash = common.BlockHash;
40344
40345var sha256_K = [
40346 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
40347 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
40348 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
40349 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
40350 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
40351 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
40352 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
40353 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
40354 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
40355 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
40356 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
40357 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
40358 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
40359 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
40360 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
40361 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
40362];
40363
40364function SHA256() {
40365 if (!(this instanceof SHA256))
40366 return new SHA256();
40367
40368 BlockHash.call(this);
40369 this.h = [
40370 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
40371 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
40372 ];
40373 this.k = sha256_K;
40374 this.W = new Array(64);
40375}
40376utils.inherits(SHA256, BlockHash);
40377module.exports = SHA256;
40378
40379SHA256.blockSize = 512;
40380SHA256.outSize = 256;
40381SHA256.hmacStrength = 192;
40382SHA256.padLength = 64;
40383
40384SHA256.prototype._update = function _update(msg, start) {
40385 var W = this.W;
40386
40387 for (var i = 0; i < 16; i++)
40388 W[i] = msg[start + i];
40389 for (; i < W.length; i++)
40390 W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
40391
40392 var a = this.h[0];
40393 var b = this.h[1];
40394 var c = this.h[2];
40395 var d = this.h[3];
40396 var e = this.h[4];
40397 var f = this.h[5];
40398 var g = this.h[6];
40399 var h = this.h[7];
40400
40401 assert(this.k.length === W.length);
40402 for (i = 0; i < W.length; i++) {
40403 var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
40404 var T2 = sum32(s0_256(a), maj32(a, b, c));
40405 h = g;
40406 g = f;
40407 f = e;
40408 e = sum32(d, T1);
40409 d = c;
40410 c = b;
40411 b = a;
40412 a = sum32(T1, T2);
40413 }
40414
40415 this.h[0] = sum32(this.h[0], a);
40416 this.h[1] = sum32(this.h[1], b);
40417 this.h[2] = sum32(this.h[2], c);
40418 this.h[3] = sum32(this.h[3], d);
40419 this.h[4] = sum32(this.h[4], e);
40420 this.h[5] = sum32(this.h[5], f);
40421 this.h[6] = sum32(this.h[6], g);
40422 this.h[7] = sum32(this.h[7], h);
40423};
40424
40425SHA256.prototype._digest = function digest(enc) {
40426 if (enc === 'hex')
40427 return utils.toHex32(this.h, 'big');
40428 else
40429 return utils.split32(this.h, 'big');
40430};
40431
40432},{"../common":192,"../utils":202,"./common":201,"minimalistic-assert":213}],199:[function(require,module,exports){
40433'use strict';
40434
40435var utils = require('../utils');
40436
40437var SHA512 = require('./512');
40438
40439function SHA384() {
40440 if (!(this instanceof SHA384))
40441 return new SHA384();
40442
40443 SHA512.call(this);
40444 this.h = [
40445 0xcbbb9d5d, 0xc1059ed8,
40446 0x629a292a, 0x367cd507,
40447 0x9159015a, 0x3070dd17,
40448 0x152fecd8, 0xf70e5939,
40449 0x67332667, 0xffc00b31,
40450 0x8eb44a87, 0x68581511,
40451 0xdb0c2e0d, 0x64f98fa7,
40452 0x47b5481d, 0xbefa4fa4 ];
40453}
40454utils.inherits(SHA384, SHA512);
40455module.exports = SHA384;
40456
40457SHA384.blockSize = 1024;
40458SHA384.outSize = 384;
40459SHA384.hmacStrength = 192;
40460SHA384.padLength = 128;
40461
40462SHA384.prototype._digest = function digest(enc) {
40463 if (enc === 'hex')
40464 return utils.toHex32(this.h.slice(0, 12), 'big');
40465 else
40466 return utils.split32(this.h.slice(0, 12), 'big');
40467};
40468
40469},{"../utils":202,"./512":200}],200:[function(require,module,exports){
40470'use strict';
40471
40472var utils = require('../utils');
40473var common = require('../common');
40474var assert = require('minimalistic-assert');
40475
40476var rotr64_hi = utils.rotr64_hi;
40477var rotr64_lo = utils.rotr64_lo;
40478var shr64_hi = utils.shr64_hi;
40479var shr64_lo = utils.shr64_lo;
40480var sum64 = utils.sum64;
40481var sum64_hi = utils.sum64_hi;
40482var sum64_lo = utils.sum64_lo;
40483var sum64_4_hi = utils.sum64_4_hi;
40484var sum64_4_lo = utils.sum64_4_lo;
40485var sum64_5_hi = utils.sum64_5_hi;
40486var sum64_5_lo = utils.sum64_5_lo;
40487
40488var BlockHash = common.BlockHash;
40489
40490var sha512_K = [
40491 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
40492 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
40493 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
40494 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
40495 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
40496 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
40497 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
40498 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
40499 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
40500 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
40501 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
40502 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
40503 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
40504 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
40505 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
40506 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
40507 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
40508 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
40509 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
40510 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
40511 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
40512 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
40513 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
40514 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
40515 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
40516 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
40517 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
40518 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
40519 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
40520 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
40521 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
40522 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
40523 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
40524 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
40525 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
40526 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
40527 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
40528 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
40529 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
40530 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
40531];
40532
40533function SHA512() {
40534 if (!(this instanceof SHA512))
40535 return new SHA512();
40536
40537 BlockHash.call(this);
40538 this.h = [
40539 0x6a09e667, 0xf3bcc908,
40540 0xbb67ae85, 0x84caa73b,
40541 0x3c6ef372, 0xfe94f82b,
40542 0xa54ff53a, 0x5f1d36f1,
40543 0x510e527f, 0xade682d1,
40544 0x9b05688c, 0x2b3e6c1f,
40545 0x1f83d9ab, 0xfb41bd6b,
40546 0x5be0cd19, 0x137e2179 ];
40547 this.k = sha512_K;
40548 this.W = new Array(160);
40549}
40550utils.inherits(SHA512, BlockHash);
40551module.exports = SHA512;
40552
40553SHA512.blockSize = 1024;
40554SHA512.outSize = 512;
40555SHA512.hmacStrength = 192;
40556SHA512.padLength = 128;
40557
40558SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
40559 var W = this.W;
40560
40561 // 32 x 32bit words
40562 for (var i = 0; i < 32; i++)
40563 W[i] = msg[start + i];
40564 for (; i < W.length; i += 2) {
40565 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
40566 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
40567 var c1_hi = W[i - 14]; // i - 7
40568 var c1_lo = W[i - 13];
40569 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
40570 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
40571 var c3_hi = W[i - 32]; // i - 16
40572 var c3_lo = W[i - 31];
40573
40574 W[i] = sum64_4_hi(
40575 c0_hi, c0_lo,
40576 c1_hi, c1_lo,
40577 c2_hi, c2_lo,
40578 c3_hi, c3_lo);
40579 W[i + 1] = sum64_4_lo(
40580 c0_hi, c0_lo,
40581 c1_hi, c1_lo,
40582 c2_hi, c2_lo,
40583 c3_hi, c3_lo);
40584 }
40585};
40586
40587SHA512.prototype._update = function _update(msg, start) {
40588 this._prepareBlock(msg, start);
40589
40590 var W = this.W;
40591
40592 var ah = this.h[0];
40593 var al = this.h[1];
40594 var bh = this.h[2];
40595 var bl = this.h[3];
40596 var ch = this.h[4];
40597 var cl = this.h[5];
40598 var dh = this.h[6];
40599 var dl = this.h[7];
40600 var eh = this.h[8];
40601 var el = this.h[9];
40602 var fh = this.h[10];
40603 var fl = this.h[11];
40604 var gh = this.h[12];
40605 var gl = this.h[13];
40606 var hh = this.h[14];
40607 var hl = this.h[15];
40608
40609 assert(this.k.length === W.length);
40610 for (var i = 0; i < W.length; i += 2) {
40611 var c0_hi = hh;
40612 var c0_lo = hl;
40613 var c1_hi = s1_512_hi(eh, el);
40614 var c1_lo = s1_512_lo(eh, el);
40615 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
40616 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
40617 var c3_hi = this.k[i];
40618 var c3_lo = this.k[i + 1];
40619 var c4_hi = W[i];
40620 var c4_lo = W[i + 1];
40621
40622 var T1_hi = sum64_5_hi(
40623 c0_hi, c0_lo,
40624 c1_hi, c1_lo,
40625 c2_hi, c2_lo,
40626 c3_hi, c3_lo,
40627 c4_hi, c4_lo);
40628 var T1_lo = sum64_5_lo(
40629 c0_hi, c0_lo,
40630 c1_hi, c1_lo,
40631 c2_hi, c2_lo,
40632 c3_hi, c3_lo,
40633 c4_hi, c4_lo);
40634
40635 c0_hi = s0_512_hi(ah, al);
40636 c0_lo = s0_512_lo(ah, al);
40637 c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
40638 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
40639
40640 var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
40641 var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
40642
40643 hh = gh;
40644 hl = gl;
40645
40646 gh = fh;
40647 gl = fl;
40648
40649 fh = eh;
40650 fl = el;
40651
40652 eh = sum64_hi(dh, dl, T1_hi, T1_lo);
40653 el = sum64_lo(dl, dl, T1_hi, T1_lo);
40654
40655 dh = ch;
40656 dl = cl;
40657
40658 ch = bh;
40659 cl = bl;
40660
40661 bh = ah;
40662 bl = al;
40663
40664 ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
40665 al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
40666 }
40667
40668 sum64(this.h, 0, ah, al);
40669 sum64(this.h, 2, bh, bl);
40670 sum64(this.h, 4, ch, cl);
40671 sum64(this.h, 6, dh, dl);
40672 sum64(this.h, 8, eh, el);
40673 sum64(this.h, 10, fh, fl);
40674 sum64(this.h, 12, gh, gl);
40675 sum64(this.h, 14, hh, hl);
40676};
40677
40678SHA512.prototype._digest = function digest(enc) {
40679 if (enc === 'hex')
40680 return utils.toHex32(this.h, 'big');
40681 else
40682 return utils.split32(this.h, 'big');
40683};
40684
40685function ch64_hi(xh, xl, yh, yl, zh) {
40686 var r = (xh & yh) ^ ((~xh) & zh);
40687 if (r < 0)
40688 r += 0x100000000;
40689 return r;
40690}
40691
40692function ch64_lo(xh, xl, yh, yl, zh, zl) {
40693 var r = (xl & yl) ^ ((~xl) & zl);
40694 if (r < 0)
40695 r += 0x100000000;
40696 return r;
40697}
40698
40699function maj64_hi(xh, xl, yh, yl, zh) {
40700 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
40701 if (r < 0)
40702 r += 0x100000000;
40703 return r;
40704}
40705
40706function maj64_lo(xh, xl, yh, yl, zh, zl) {
40707 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
40708 if (r < 0)
40709 r += 0x100000000;
40710 return r;
40711}
40712
40713function s0_512_hi(xh, xl) {
40714 var c0_hi = rotr64_hi(xh, xl, 28);
40715 var c1_hi = rotr64_hi(xl, xh, 2); // 34
40716 var c2_hi = rotr64_hi(xl, xh, 7); // 39
40717
40718 var r = c0_hi ^ c1_hi ^ c2_hi;
40719 if (r < 0)
40720 r += 0x100000000;
40721 return r;
40722}
40723
40724function s0_512_lo(xh, xl) {
40725 var c0_lo = rotr64_lo(xh, xl, 28);
40726 var c1_lo = rotr64_lo(xl, xh, 2); // 34
40727 var c2_lo = rotr64_lo(xl, xh, 7); // 39
40728
40729 var r = c0_lo ^ c1_lo ^ c2_lo;
40730 if (r < 0)
40731 r += 0x100000000;
40732 return r;
40733}
40734
40735function s1_512_hi(xh, xl) {
40736 var c0_hi = rotr64_hi(xh, xl, 14);
40737 var c1_hi = rotr64_hi(xh, xl, 18);
40738 var c2_hi = rotr64_hi(xl, xh, 9); // 41
40739
40740 var r = c0_hi ^ c1_hi ^ c2_hi;
40741 if (r < 0)
40742 r += 0x100000000;
40743 return r;
40744}
40745
40746function s1_512_lo(xh, xl) {
40747 var c0_lo = rotr64_lo(xh, xl, 14);
40748 var c1_lo = rotr64_lo(xh, xl, 18);
40749 var c2_lo = rotr64_lo(xl, xh, 9); // 41
40750
40751 var r = c0_lo ^ c1_lo ^ c2_lo;
40752 if (r < 0)
40753 r += 0x100000000;
40754 return r;
40755}
40756
40757function g0_512_hi(xh, xl) {
40758 var c0_hi = rotr64_hi(xh, xl, 1);
40759 var c1_hi = rotr64_hi(xh, xl, 8);
40760 var c2_hi = shr64_hi(xh, xl, 7);
40761
40762 var r = c0_hi ^ c1_hi ^ c2_hi;
40763 if (r < 0)
40764 r += 0x100000000;
40765 return r;
40766}
40767
40768function g0_512_lo(xh, xl) {
40769 var c0_lo = rotr64_lo(xh, xl, 1);
40770 var c1_lo = rotr64_lo(xh, xl, 8);
40771 var c2_lo = shr64_lo(xh, xl, 7);
40772
40773 var r = c0_lo ^ c1_lo ^ c2_lo;
40774 if (r < 0)
40775 r += 0x100000000;
40776 return r;
40777}
40778
40779function g1_512_hi(xh, xl) {
40780 var c0_hi = rotr64_hi(xh, xl, 19);
40781 var c1_hi = rotr64_hi(xl, xh, 29); // 61
40782 var c2_hi = shr64_hi(xh, xl, 6);
40783
40784 var r = c0_hi ^ c1_hi ^ c2_hi;
40785 if (r < 0)
40786 r += 0x100000000;
40787 return r;
40788}
40789
40790function g1_512_lo(xh, xl) {
40791 var c0_lo = rotr64_lo(xh, xl, 19);
40792 var c1_lo = rotr64_lo(xl, xh, 29); // 61
40793 var c2_lo = shr64_lo(xh, xl, 6);
40794
40795 var r = c0_lo ^ c1_lo ^ c2_lo;
40796 if (r < 0)
40797 r += 0x100000000;
40798 return r;
40799}
40800
40801},{"../common":192,"../utils":202,"minimalistic-assert":213}],201:[function(require,module,exports){
40802'use strict';
40803
40804var utils = require('../utils');
40805var rotr32 = utils.rotr32;
40806
40807function ft_1(s, x, y, z) {
40808 if (s === 0)
40809 return ch32(x, y, z);
40810 if (s === 1 || s === 3)
40811 return p32(x, y, z);
40812 if (s === 2)
40813 return maj32(x, y, z);
40814}
40815exports.ft_1 = ft_1;
40816
40817function ch32(x, y, z) {
40818 return (x & y) ^ ((~x) & z);
40819}
40820exports.ch32 = ch32;
40821
40822function maj32(x, y, z) {
40823 return (x & y) ^ (x & z) ^ (y & z);
40824}
40825exports.maj32 = maj32;
40826
40827function p32(x, y, z) {
40828 return x ^ y ^ z;
40829}
40830exports.p32 = p32;
40831
40832function s0_256(x) {
40833 return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
40834}
40835exports.s0_256 = s0_256;
40836
40837function s1_256(x) {
40838 return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
40839}
40840exports.s1_256 = s1_256;
40841
40842function g0_256(x) {
40843 return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
40844}
40845exports.g0_256 = g0_256;
40846
40847function g1_256(x) {
40848 return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
40849}
40850exports.g1_256 = g1_256;
40851
40852},{"../utils":202}],202:[function(require,module,exports){
40853'use strict';
40854
40855var assert = require('minimalistic-assert');
40856var inherits = require('inherits');
40857
40858exports.inherits = inherits;
40859
40860function isSurrogatePair(msg, i) {
40861 if ((msg.charCodeAt(i) & 0xFC00) !== 0xD800) {
40862 return false;
40863 }
40864 if (i < 0 || i + 1 >= msg.length) {
40865 return false;
40866 }
40867 return (msg.charCodeAt(i + 1) & 0xFC00) === 0xDC00;
40868}
40869
40870function toArray(msg, enc) {
40871 if (Array.isArray(msg))
40872 return msg.slice();
40873 if (!msg)
40874 return [];
40875 var res = [];
40876 if (typeof msg === 'string') {
40877 if (!enc) {
40878 // Inspired by stringToUtf8ByteArray() in closure-library by Google
40879 // https://github.com/google/closure-library/blob/8598d87242af59aac233270742c8984e2b2bdbe0/closure/goog/crypt/crypt.js#L117-L143
40880 // Apache License 2.0
40881 // https://github.com/google/closure-library/blob/master/LICENSE
40882 var p = 0;
40883 for (var i = 0; i < msg.length; i++) {
40884 var c = msg.charCodeAt(i);
40885 if (c < 128) {
40886 res[p++] = c;
40887 } else if (c < 2048) {
40888 res[p++] = (c >> 6) | 192;
40889 res[p++] = (c & 63) | 128;
40890 } else if (isSurrogatePair(msg, i)) {
40891 c = 0x10000 + ((c & 0x03FF) << 10) + (msg.charCodeAt(++i) & 0x03FF);
40892 res[p++] = (c >> 18) | 240;
40893 res[p++] = ((c >> 12) & 63) | 128;
40894 res[p++] = ((c >> 6) & 63) | 128;
40895 res[p++] = (c & 63) | 128;
40896 } else {
40897 res[p++] = (c >> 12) | 224;
40898 res[p++] = ((c >> 6) & 63) | 128;
40899 res[p++] = (c & 63) | 128;
40900 }
40901 }
40902 } else if (enc === 'hex') {
40903 msg = msg.replace(/[^a-z0-9]+/ig, '');
40904 if (msg.length % 2 !== 0)
40905 msg = '0' + msg;
40906 for (i = 0; i < msg.length; i += 2)
40907 res.push(parseInt(msg[i] + msg[i + 1], 16));
40908 }
40909 } else {
40910 for (i = 0; i < msg.length; i++)
40911 res[i] = msg[i] | 0;
40912 }
40913 return res;
40914}
40915exports.toArray = toArray;
40916
40917function toHex(msg) {
40918 var res = '';
40919 for (var i = 0; i < msg.length; i++)
40920 res += zero2(msg[i].toString(16));
40921 return res;
40922}
40923exports.toHex = toHex;
40924
40925function htonl(w) {
40926 var res = (w >>> 24) |
40927 ((w >>> 8) & 0xff00) |
40928 ((w << 8) & 0xff0000) |
40929 ((w & 0xff) << 24);
40930 return res >>> 0;
40931}
40932exports.htonl = htonl;
40933
40934function toHex32(msg, endian) {
40935 var res = '';
40936 for (var i = 0; i < msg.length; i++) {
40937 var w = msg[i];
40938 if (endian === 'little')
40939 w = htonl(w);
40940 res += zero8(w.toString(16));
40941 }
40942 return res;
40943}
40944exports.toHex32 = toHex32;
40945
40946function zero2(word) {
40947 if (word.length === 1)
40948 return '0' + word;
40949 else
40950 return word;
40951}
40952exports.zero2 = zero2;
40953
40954function zero8(word) {
40955 if (word.length === 7)
40956 return '0' + word;
40957 else if (word.length === 6)
40958 return '00' + word;
40959 else if (word.length === 5)
40960 return '000' + word;
40961 else if (word.length === 4)
40962 return '0000' + word;
40963 else if (word.length === 3)
40964 return '00000' + word;
40965 else if (word.length === 2)
40966 return '000000' + word;
40967 else if (word.length === 1)
40968 return '0000000' + word;
40969 else
40970 return word;
40971}
40972exports.zero8 = zero8;
40973
40974function join32(msg, start, end, endian) {
40975 var len = end - start;
40976 assert(len % 4 === 0);
40977 var res = new Array(len / 4);
40978 for (var i = 0, k = start; i < res.length; i++, k += 4) {
40979 var w;
40980 if (endian === 'big')
40981 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
40982 else
40983 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
40984 res[i] = w >>> 0;
40985 }
40986 return res;
40987}
40988exports.join32 = join32;
40989
40990function split32(msg, endian) {
40991 var res = new Array(msg.length * 4);
40992 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
40993 var m = msg[i];
40994 if (endian === 'big') {
40995 res[k] = m >>> 24;
40996 res[k + 1] = (m >>> 16) & 0xff;
40997 res[k + 2] = (m >>> 8) & 0xff;
40998 res[k + 3] = m & 0xff;
40999 } else {
41000 res[k + 3] = m >>> 24;
41001 res[k + 2] = (m >>> 16) & 0xff;
41002 res[k + 1] = (m >>> 8) & 0xff;
41003 res[k] = m & 0xff;
41004 }
41005 }
41006 return res;
41007}
41008exports.split32 = split32;
41009
41010function rotr32(w, b) {
41011 return (w >>> b) | (w << (32 - b));
41012}
41013exports.rotr32 = rotr32;
41014
41015function rotl32(w, b) {
41016 return (w << b) | (w >>> (32 - b));
41017}
41018exports.rotl32 = rotl32;
41019
41020function sum32(a, b) {
41021 return (a + b) >>> 0;
41022}
41023exports.sum32 = sum32;
41024
41025function sum32_3(a, b, c) {
41026 return (a + b + c) >>> 0;
41027}
41028exports.sum32_3 = sum32_3;
41029
41030function sum32_4(a, b, c, d) {
41031 return (a + b + c + d) >>> 0;
41032}
41033exports.sum32_4 = sum32_4;
41034
41035function sum32_5(a, b, c, d, e) {
41036 return (a + b + c + d + e) >>> 0;
41037}
41038exports.sum32_5 = sum32_5;
41039
41040function sum64(buf, pos, ah, al) {
41041 var bh = buf[pos];
41042 var bl = buf[pos + 1];
41043
41044 var lo = (al + bl) >>> 0;
41045 var hi = (lo < al ? 1 : 0) + ah + bh;
41046 buf[pos] = hi >>> 0;
41047 buf[pos + 1] = lo;
41048}
41049exports.sum64 = sum64;
41050
41051function sum64_hi(ah, al, bh, bl) {
41052 var lo = (al + bl) >>> 0;
41053 var hi = (lo < al ? 1 : 0) + ah + bh;
41054 return hi >>> 0;
41055}
41056exports.sum64_hi = sum64_hi;
41057
41058function sum64_lo(ah, al, bh, bl) {
41059 var lo = al + bl;
41060 return lo >>> 0;
41061}
41062exports.sum64_lo = sum64_lo;
41063
41064function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
41065 var carry = 0;
41066 var lo = al;
41067 lo = (lo + bl) >>> 0;
41068 carry += lo < al ? 1 : 0;
41069 lo = (lo + cl) >>> 0;
41070 carry += lo < cl ? 1 : 0;
41071 lo = (lo + dl) >>> 0;
41072 carry += lo < dl ? 1 : 0;
41073
41074 var hi = ah + bh + ch + dh + carry;
41075 return hi >>> 0;
41076}
41077exports.sum64_4_hi = sum64_4_hi;
41078
41079function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
41080 var lo = al + bl + cl + dl;
41081 return lo >>> 0;
41082}
41083exports.sum64_4_lo = sum64_4_lo;
41084
41085function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
41086 var carry = 0;
41087 var lo = al;
41088 lo = (lo + bl) >>> 0;
41089 carry += lo < al ? 1 : 0;
41090 lo = (lo + cl) >>> 0;
41091 carry += lo < cl ? 1 : 0;
41092 lo = (lo + dl) >>> 0;
41093 carry += lo < dl ? 1 : 0;
41094 lo = (lo + el) >>> 0;
41095 carry += lo < el ? 1 : 0;
41096
41097 var hi = ah + bh + ch + dh + eh + carry;
41098 return hi >>> 0;
41099}
41100exports.sum64_5_hi = sum64_5_hi;
41101
41102function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
41103 var lo = al + bl + cl + dl + el;
41104
41105 return lo >>> 0;
41106}
41107exports.sum64_5_lo = sum64_5_lo;
41108
41109function rotr64_hi(ah, al, num) {
41110 var r = (al << (32 - num)) | (ah >>> num);
41111 return r >>> 0;
41112}
41113exports.rotr64_hi = rotr64_hi;
41114
41115function rotr64_lo(ah, al, num) {
41116 var r = (ah << (32 - num)) | (al >>> num);
41117 return r >>> 0;
41118}
41119exports.rotr64_lo = rotr64_lo;
41120
41121function shr64_hi(ah, al, num) {
41122 return ah >>> num;
41123}
41124exports.shr64_hi = shr64_hi;
41125
41126function shr64_lo(ah, al, num) {
41127 var r = (ah << (32 - num)) | (al >>> num);
41128 return r >>> 0;
41129}
41130exports.shr64_lo = shr64_lo;
41131
41132},{"inherits":203,"minimalistic-assert":213}],203:[function(require,module,exports){
41133arguments[4][112][0].apply(exports,arguments)
41134},{"dup":112}],204:[function(require,module,exports){
41135'use strict';
41136
41137var hash = require('hash.js');
41138var utils = require('minimalistic-crypto-utils');
41139var assert = require('minimalistic-assert');
41140
41141function HmacDRBG(options) {
41142 if (!(this instanceof HmacDRBG))
41143 return new HmacDRBG(options);
41144 this.hash = options.hash;
41145 this.predResist = !!options.predResist;
41146
41147 this.outLen = this.hash.outSize;
41148 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
41149
41150 this._reseed = null;
41151 this.reseedInterval = null;
41152 this.K = null;
41153 this.V = null;
41154
41155 var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
41156 var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
41157 var pers = utils.toArray(options.pers, options.persEnc || 'hex');
41158 assert(entropy.length >= (this.minEntropy / 8),
41159 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
41160 this._init(entropy, nonce, pers);
41161}
41162module.exports = HmacDRBG;
41163
41164HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
41165 var seed = entropy.concat(nonce).concat(pers);
41166
41167 this.K = new Array(this.outLen / 8);
41168 this.V = new Array(this.outLen / 8);
41169 for (var i = 0; i < this.V.length; i++) {
41170 this.K[i] = 0x00;
41171 this.V[i] = 0x01;
41172 }
41173
41174 this._update(seed);
41175 this._reseed = 1;
41176 this.reseedInterval = 0x1000000000000; // 2^48
41177};
41178
41179HmacDRBG.prototype._hmac = function hmac() {
41180 return new hash.hmac(this.hash, this.K);
41181};
41182
41183HmacDRBG.prototype._update = function update(seed) {
41184 var kmac = this._hmac()
41185 .update(this.V)
41186 .update([ 0x00 ]);
41187 if (seed)
41188 kmac = kmac.update(seed);
41189 this.K = kmac.digest();
41190 this.V = this._hmac().update(this.V).digest();
41191 if (!seed)
41192 return;
41193
41194 this.K = this._hmac()
41195 .update(this.V)
41196 .update([ 0x01 ])
41197 .update(seed)
41198 .digest();
41199 this.V = this._hmac().update(this.V).digest();
41200};
41201
41202HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
41203 // Optional entropy enc
41204 if (typeof entropyEnc !== 'string') {
41205 addEnc = add;
41206 add = entropyEnc;
41207 entropyEnc = null;
41208 }
41209
41210 entropy = utils.toArray(entropy, entropyEnc);
41211 add = utils.toArray(add, addEnc);
41212
41213 assert(entropy.length >= (this.minEntropy / 8),
41214 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
41215
41216 this._update(entropy.concat(add || []));
41217 this._reseed = 1;
41218};
41219
41220HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
41221 if (this._reseed > this.reseedInterval)
41222 throw new Error('Reseed is required');
41223
41224 // Optional encoding
41225 if (typeof enc !== 'string') {
41226 addEnc = add;
41227 add = enc;
41228 enc = null;
41229 }
41230
41231 // Optional additional data
41232 if (add) {
41233 add = utils.toArray(add, addEnc || 'hex');
41234 this._update(add);
41235 }
41236
41237 var temp = [];
41238 while (temp.length < len) {
41239 this.V = this._hmac().update(this.V).digest();
41240 temp = temp.concat(this.V);
41241 }
41242
41243 var res = temp.slice(0, len);
41244 this._update(add);
41245 this._reseed++;
41246 return utils.encode(res, enc);
41247};
41248
41249},{"hash.js":191,"minimalistic-assert":213,"minimalistic-crypto-utils":214}],205:[function(require,module,exports){
41250/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh <https://feross.org/opensource> */
41251exports.read = function (buffer, offset, isLE, mLen, nBytes) {
41252 var e, m
41253 var eLen = (nBytes * 8) - mLen - 1
41254 var eMax = (1 << eLen) - 1
41255 var eBias = eMax >> 1
41256 var nBits = -7
41257 var i = isLE ? (nBytes - 1) : 0
41258 var d = isLE ? -1 : 1
41259 var s = buffer[offset + i]
41260
41261 i += d
41262
41263 e = s & ((1 << (-nBits)) - 1)
41264 s >>= (-nBits)
41265 nBits += eLen
41266 for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {}
41267
41268 m = e & ((1 << (-nBits)) - 1)
41269 e >>= (-nBits)
41270 nBits += mLen
41271 for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {}
41272
41273 if (e === 0) {
41274 e = 1 - eBias
41275 } else if (e === eMax) {
41276 return m ? NaN : ((s ? -1 : 1) * Infinity)
41277 } else {
41278 m = m + Math.pow(2, mLen)
41279 e = e - eBias
41280 }
41281 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
41282}
41283
41284exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
41285 var e, m, c
41286 var eLen = (nBytes * 8) - mLen - 1
41287 var eMax = (1 << eLen) - 1
41288 var eBias = eMax >> 1
41289 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
41290 var i = isLE ? 0 : (nBytes - 1)
41291 var d = isLE ? 1 : -1
41292 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
41293
41294 value = Math.abs(value)
41295
41296 if (isNaN(value) || value === Infinity) {
41297 m = isNaN(value) ? 1 : 0
41298 e = eMax
41299 } else {
41300 e = Math.floor(Math.log(value) / Math.LN2)
41301 if (value * (c = Math.pow(2, -e)) < 1) {
41302 e--
41303 c *= 2
41304 }
41305 if (e + eBias >= 1) {
41306 value += rt / c
41307 } else {
41308 value += rt * Math.pow(2, 1 - eBias)
41309 }
41310 if (value * c >= 2) {
41311 e++
41312 c /= 2
41313 }
41314
41315 if (e + eBias >= eMax) {
41316 m = 0
41317 e = eMax
41318 } else if (e + eBias >= 1) {
41319 m = ((value * c) - 1) * Math.pow(2, mLen)
41320 e = e + eBias
41321 } else {
41322 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
41323 e = 0
41324 }
41325 }
41326
41327 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
41328
41329 e = (e << mLen) | m
41330 eLen += mLen
41331 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
41332
41333 buffer[offset + i - d] |= s * 128
41334}
41335
41336},{}],206:[function(require,module,exports){
41337if (typeof Object.create === 'function') {
41338 // implementation from standard node.js 'util' module
41339 module.exports = function inherits(ctor, superCtor) {
41340 ctor.super_ = superCtor
41341 ctor.prototype = Object.create(superCtor.prototype, {
41342 constructor: {
41343 value: ctor,
41344 enumerable: false,
41345 writable: true,
41346 configurable: true
41347 }
41348 });
41349 };
41350} else {
41351 // old school shim for old browsers
41352 module.exports = function inherits(ctor, superCtor) {
41353 ctor.super_ = superCtor
41354 var TempCtor = function () {}
41355 TempCtor.prototype = superCtor.prototype
41356 ctor.prototype = new TempCtor()
41357 ctor.prototype.constructor = ctor
41358 }
41359}
41360
41361},{}],207:[function(require,module,exports){
41362/*!
41363 * Determine if an object is a Buffer
41364 *
41365 * @author Feross Aboukhadijeh <https://feross.org>
41366 * @license MIT
41367 */
41368
41369// The _isBuffer check is for Safari 5-7 support, because it's missing
41370// Object.prototype.constructor. Remove this eventually
41371module.exports = function (obj) {
41372 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
41373}
41374
41375function isBuffer (obj) {
41376 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
41377}
41378
41379// For Node v0.10 support. Remove this eventually.
41380function isSlowBuffer (obj) {
41381 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
41382}
41383
41384},{}],208:[function(require,module,exports){
41385var toString = {}.toString;
41386
41387module.exports = Array.isArray || function (arr) {
41388 return toString.call(arr) == '[object Array]';
41389};
41390
41391},{}],209:[function(require,module,exports){
41392(function (process,global){(function (){
41393/**
41394 * [js-sha256]{@link https://github.com/emn178/js-sha256}
41395 *
41396 * @version 0.9.0
41397 * @author Chen, Yi-Cyuan [emn178@gmail.com]
41398 * @copyright Chen, Yi-Cyuan 2014-2017
41399 * @license MIT
41400 */
41401/*jslint bitwise: true */
41402(function () {
41403 'use strict';
41404
41405 var ERROR = 'input is invalid type';
41406 var WINDOW = typeof window === 'object';
41407 var root = WINDOW ? window : {};
41408 if (root.JS_SHA256_NO_WINDOW) {
41409 WINDOW = false;
41410 }
41411 var WEB_WORKER = !WINDOW && typeof self === 'object';
41412 var NODE_JS = !root.JS_SHA256_NO_NODE_JS && typeof process === 'object' && process.versions && process.versions.node;
41413 if (NODE_JS) {
41414 root = global;
41415 } else if (WEB_WORKER) {
41416 root = self;
41417 }
41418 var COMMON_JS = !root.JS_SHA256_NO_COMMON_JS && typeof module === 'object' && module.exports;
41419 var AMD = typeof define === 'function' && define.amd;
41420 var ARRAY_BUFFER = !root.JS_SHA256_NO_ARRAY_BUFFER && typeof ArrayBuffer !== 'undefined';
41421 var HEX_CHARS = '0123456789abcdef'.split('');
41422 var EXTRA = [-2147483648, 8388608, 32768, 128];
41423 var SHIFT = [24, 16, 8, 0];
41424 var K = [
41425 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
41426 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
41427 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
41428 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
41429 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
41430 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
41431 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
41432 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
41433 ];
41434 var OUTPUT_TYPES = ['hex', 'array', 'digest', 'arrayBuffer'];
41435
41436 var blocks = [];
41437
41438 if (root.JS_SHA256_NO_NODE_JS || !Array.isArray) {
41439 Array.isArray = function (obj) {
41440 return Object.prototype.toString.call(obj) === '[object Array]';
41441 };
41442 }
41443
41444 if (ARRAY_BUFFER && (root.JS_SHA256_NO_ARRAY_BUFFER_IS_VIEW || !ArrayBuffer.isView)) {
41445 ArrayBuffer.isView = function (obj) {
41446 return typeof obj === 'object' && obj.buffer && obj.buffer.constructor === ArrayBuffer;
41447 };
41448 }
41449
41450 var createOutputMethod = function (outputType, is224) {
41451 return function (message) {
41452 return new Sha256(is224, true).update(message)[outputType]();
41453 };
41454 };
41455
41456 var createMethod = function (is224) {
41457 var method = createOutputMethod('hex', is224);
41458 if (NODE_JS) {
41459 method = nodeWrap(method, is224);
41460 }
41461 method.create = function () {
41462 return new Sha256(is224);
41463 };
41464 method.update = function (message) {
41465 return method.create().update(message);
41466 };
41467 for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
41468 var type = OUTPUT_TYPES[i];
41469 method[type] = createOutputMethod(type, is224);
41470 }
41471 return method;
41472 };
41473
41474 var nodeWrap = function (method, is224) {
41475 var crypto = eval("require('crypto')");
41476 var Buffer = eval("require('buffer').Buffer");
41477 var algorithm = is224 ? 'sha224' : 'sha256';
41478 var nodeMethod = function (message) {
41479 if (typeof message === 'string') {
41480 return crypto.createHash(algorithm).update(message, 'utf8').digest('hex');
41481 } else {
41482 if (message === null || message === undefined) {
41483 throw new Error(ERROR);
41484 } else if (message.constructor === ArrayBuffer) {
41485 message = new Uint8Array(message);
41486 }
41487 }
41488 if (Array.isArray(message) || ArrayBuffer.isView(message) ||
41489 message.constructor === Buffer) {
41490 return crypto.createHash(algorithm).update(new Buffer(message)).digest('hex');
41491 } else {
41492 return method(message);
41493 }
41494 };
41495 return nodeMethod;
41496 };
41497
41498 var createHmacOutputMethod = function (outputType, is224) {
41499 return function (key, message) {
41500 return new HmacSha256(key, is224, true).update(message)[outputType]();
41501 };
41502 };
41503
41504 var createHmacMethod = function (is224) {
41505 var method = createHmacOutputMethod('hex', is224);
41506 method.create = function (key) {
41507 return new HmacSha256(key, is224);
41508 };
41509 method.update = function (key, message) {
41510 return method.create(key).update(message);
41511 };
41512 for (var i = 0; i < OUTPUT_TYPES.length; ++i) {
41513 var type = OUTPUT_TYPES[i];
41514 method[type] = createHmacOutputMethod(type, is224);
41515 }
41516 return method;
41517 };
41518
41519 function Sha256(is224, sharedMemory) {
41520 if (sharedMemory) {
41521 blocks[0] = blocks[16] = blocks[1] = blocks[2] = blocks[3] =
41522 blocks[4] = blocks[5] = blocks[6] = blocks[7] =
41523 blocks[8] = blocks[9] = blocks[10] = blocks[11] =
41524 blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
41525 this.blocks = blocks;
41526 } else {
41527 this.blocks = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
41528 }
41529
41530 if (is224) {
41531 this.h0 = 0xc1059ed8;
41532 this.h1 = 0x367cd507;
41533 this.h2 = 0x3070dd17;
41534 this.h3 = 0xf70e5939;
41535 this.h4 = 0xffc00b31;
41536 this.h5 = 0x68581511;
41537 this.h6 = 0x64f98fa7;
41538 this.h7 = 0xbefa4fa4;
41539 } else { // 256
41540 this.h0 = 0x6a09e667;
41541 this.h1 = 0xbb67ae85;
41542 this.h2 = 0x3c6ef372;
41543 this.h3 = 0xa54ff53a;
41544 this.h4 = 0x510e527f;
41545 this.h5 = 0x9b05688c;
41546 this.h6 = 0x1f83d9ab;
41547 this.h7 = 0x5be0cd19;
41548 }
41549
41550 this.block = this.start = this.bytes = this.hBytes = 0;
41551 this.finalized = this.hashed = false;
41552 this.first = true;
41553 this.is224 = is224;
41554 }
41555
41556 Sha256.prototype.update = function (message) {
41557 if (this.finalized) {
41558 return;
41559 }
41560 var notString, type = typeof message;
41561 if (type !== 'string') {
41562 if (type === 'object') {
41563 if (message === null) {
41564 throw new Error(ERROR);
41565 } else if (ARRAY_BUFFER && message.constructor === ArrayBuffer) {
41566 message = new Uint8Array(message);
41567 } else if (!Array.isArray(message)) {
41568 if (!ARRAY_BUFFER || !ArrayBuffer.isView(message)) {
41569 throw new Error(ERROR);
41570 }
41571 }
41572 } else {
41573 throw new Error(ERROR);
41574 }
41575 notString = true;
41576 }
41577 var code, index = 0, i, length = message.length, blocks = this.blocks;
41578
41579 while (index < length) {
41580 if (this.hashed) {
41581 this.hashed = false;
41582 blocks[0] = this.block;
41583 blocks[16] = blocks[1] = blocks[2] = blocks[3] =
41584 blocks[4] = blocks[5] = blocks[6] = blocks[7] =
41585 blocks[8] = blocks[9] = blocks[10] = blocks[11] =
41586 blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
41587 }
41588
41589 if (notString) {
41590 for (i = this.start; index < length && i < 64; ++index) {
41591 blocks[i >> 2] |= message[index] << SHIFT[i++ & 3];
41592 }
41593 } else {
41594 for (i = this.start; index < length && i < 64; ++index) {
41595 code = message.charCodeAt(index);
41596 if (code < 0x80) {
41597 blocks[i >> 2] |= code << SHIFT[i++ & 3];
41598 } else if (code < 0x800) {
41599 blocks[i >> 2] |= (0xc0 | (code >> 6)) << SHIFT[i++ & 3];
41600 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
41601 } else if (code < 0xd800 || code >= 0xe000) {
41602 blocks[i >> 2] |= (0xe0 | (code >> 12)) << SHIFT[i++ & 3];
41603 blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
41604 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
41605 } else {
41606 code = 0x10000 + (((code & 0x3ff) << 10) | (message.charCodeAt(++index) & 0x3ff));
41607 blocks[i >> 2] |= (0xf0 | (code >> 18)) << SHIFT[i++ & 3];
41608 blocks[i >> 2] |= (0x80 | ((code >> 12) & 0x3f)) << SHIFT[i++ & 3];
41609 blocks[i >> 2] |= (0x80 | ((code >> 6) & 0x3f)) << SHIFT[i++ & 3];
41610 blocks[i >> 2] |= (0x80 | (code & 0x3f)) << SHIFT[i++ & 3];
41611 }
41612 }
41613 }
41614
41615 this.lastByteIndex = i;
41616 this.bytes += i - this.start;
41617 if (i >= 64) {
41618 this.block = blocks[16];
41619 this.start = i - 64;
41620 this.hash();
41621 this.hashed = true;
41622 } else {
41623 this.start = i;
41624 }
41625 }
41626 if (this.bytes > 4294967295) {
41627 this.hBytes += this.bytes / 4294967296 << 0;
41628 this.bytes = this.bytes % 4294967296;
41629 }
41630 return this;
41631 };
41632
41633 Sha256.prototype.finalize = function () {
41634 if (this.finalized) {
41635 return;
41636 }
41637 this.finalized = true;
41638 var blocks = this.blocks, i = this.lastByteIndex;
41639 blocks[16] = this.block;
41640 blocks[i >> 2] |= EXTRA[i & 3];
41641 this.block = blocks[16];
41642 if (i >= 56) {
41643 if (!this.hashed) {
41644 this.hash();
41645 }
41646 blocks[0] = this.block;
41647 blocks[16] = blocks[1] = blocks[2] = blocks[3] =
41648 blocks[4] = blocks[5] = blocks[6] = blocks[7] =
41649 blocks[8] = blocks[9] = blocks[10] = blocks[11] =
41650 blocks[12] = blocks[13] = blocks[14] = blocks[15] = 0;
41651 }
41652 blocks[14] = this.hBytes << 3 | this.bytes >>> 29;
41653 blocks[15] = this.bytes << 3;
41654 this.hash();
41655 };
41656
41657 Sha256.prototype.hash = function () {
41658 var a = this.h0, b = this.h1, c = this.h2, d = this.h3, e = this.h4, f = this.h5, g = this.h6,
41659 h = this.h7, blocks = this.blocks, j, s0, s1, maj, t1, t2, ch, ab, da, cd, bc;
41660
41661 for (j = 16; j < 64; ++j) {
41662 // rightrotate
41663 t1 = blocks[j - 15];
41664 s0 = ((t1 >>> 7) | (t1 << 25)) ^ ((t1 >>> 18) | (t1 << 14)) ^ (t1 >>> 3);
41665 t1 = blocks[j - 2];
41666 s1 = ((t1 >>> 17) | (t1 << 15)) ^ ((t1 >>> 19) | (t1 << 13)) ^ (t1 >>> 10);
41667 blocks[j] = blocks[j - 16] + s0 + blocks[j - 7] + s1 << 0;
41668 }
41669
41670 bc = b & c;
41671 for (j = 0; j < 64; j += 4) {
41672 if (this.first) {
41673 if (this.is224) {
41674 ab = 300032;
41675 t1 = blocks[0] - 1413257819;
41676 h = t1 - 150054599 << 0;
41677 d = t1 + 24177077 << 0;
41678 } else {
41679 ab = 704751109;
41680 t1 = blocks[0] - 210244248;
41681 h = t1 - 1521486534 << 0;
41682 d = t1 + 143694565 << 0;
41683 }
41684 this.first = false;
41685 } else {
41686 s0 = ((a >>> 2) | (a << 30)) ^ ((a >>> 13) | (a << 19)) ^ ((a >>> 22) | (a << 10));
41687 s1 = ((e >>> 6) | (e << 26)) ^ ((e >>> 11) | (e << 21)) ^ ((e >>> 25) | (e << 7));
41688 ab = a & b;
41689 maj = ab ^ (a & c) ^ bc;
41690 ch = (e & f) ^ (~e & g);
41691 t1 = h + s1 + ch + K[j] + blocks[j];
41692 t2 = s0 + maj;
41693 h = d + t1 << 0;
41694 d = t1 + t2 << 0;
41695 }
41696 s0 = ((d >>> 2) | (d << 30)) ^ ((d >>> 13) | (d << 19)) ^ ((d >>> 22) | (d << 10));
41697 s1 = ((h >>> 6) | (h << 26)) ^ ((h >>> 11) | (h << 21)) ^ ((h >>> 25) | (h << 7));
41698 da = d & a;
41699 maj = da ^ (d & b) ^ ab;
41700 ch = (h & e) ^ (~h & f);
41701 t1 = g + s1 + ch + K[j + 1] + blocks[j + 1];
41702 t2 = s0 + maj;
41703 g = c + t1 << 0;
41704 c = t1 + t2 << 0;
41705 s0 = ((c >>> 2) | (c << 30)) ^ ((c >>> 13) | (c << 19)) ^ ((c >>> 22) | (c << 10));
41706 s1 = ((g >>> 6) | (g << 26)) ^ ((g >>> 11) | (g << 21)) ^ ((g >>> 25) | (g << 7));
41707 cd = c & d;
41708 maj = cd ^ (c & a) ^ da;
41709 ch = (g & h) ^ (~g & e);
41710 t1 = f + s1 + ch + K[j + 2] + blocks[j + 2];
41711 t2 = s0 + maj;
41712 f = b + t1 << 0;
41713 b = t1 + t2 << 0;
41714 s0 = ((b >>> 2) | (b << 30)) ^ ((b >>> 13) | (b << 19)) ^ ((b >>> 22) | (b << 10));
41715 s1 = ((f >>> 6) | (f << 26)) ^ ((f >>> 11) | (f << 21)) ^ ((f >>> 25) | (f << 7));
41716 bc = b & c;
41717 maj = bc ^ (b & d) ^ cd;
41718 ch = (f & g) ^ (~f & h);
41719 t1 = e + s1 + ch + K[j + 3] + blocks[j + 3];
41720 t2 = s0 + maj;
41721 e = a + t1 << 0;
41722 a = t1 + t2 << 0;
41723 }
41724
41725 this.h0 = this.h0 + a << 0;
41726 this.h1 = this.h1 + b << 0;
41727 this.h2 = this.h2 + c << 0;
41728 this.h3 = this.h3 + d << 0;
41729 this.h4 = this.h4 + e << 0;
41730 this.h5 = this.h5 + f << 0;
41731 this.h6 = this.h6 + g << 0;
41732 this.h7 = this.h7 + h << 0;
41733 };
41734
41735 Sha256.prototype.hex = function () {
41736 this.finalize();
41737
41738 var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5,
41739 h6 = this.h6, h7 = this.h7;
41740
41741 var hex = HEX_CHARS[(h0 >> 28) & 0x0F] + HEX_CHARS[(h0 >> 24) & 0x0F] +
41742 HEX_CHARS[(h0 >> 20) & 0x0F] + HEX_CHARS[(h0 >> 16) & 0x0F] +
41743 HEX_CHARS[(h0 >> 12) & 0x0F] + HEX_CHARS[(h0 >> 8) & 0x0F] +
41744 HEX_CHARS[(h0 >> 4) & 0x0F] + HEX_CHARS[h0 & 0x0F] +
41745 HEX_CHARS[(h1 >> 28) & 0x0F] + HEX_CHARS[(h1 >> 24) & 0x0F] +
41746 HEX_CHARS[(h1 >> 20) & 0x0F] + HEX_CHARS[(h1 >> 16) & 0x0F] +
41747 HEX_CHARS[(h1 >> 12) & 0x0F] + HEX_CHARS[(h1 >> 8) & 0x0F] +
41748 HEX_CHARS[(h1 >> 4) & 0x0F] + HEX_CHARS[h1 & 0x0F] +
41749 HEX_CHARS[(h2 >> 28) & 0x0F] + HEX_CHARS[(h2 >> 24) & 0x0F] +
41750 HEX_CHARS[(h2 >> 20) & 0x0F] + HEX_CHARS[(h2 >> 16) & 0x0F] +
41751 HEX_CHARS[(h2 >> 12) & 0x0F] + HEX_CHARS[(h2 >> 8) & 0x0F] +
41752 HEX_CHARS[(h2 >> 4) & 0x0F] + HEX_CHARS[h2 & 0x0F] +
41753 HEX_CHARS[(h3 >> 28) & 0x0F] + HEX_CHARS[(h3 >> 24) & 0x0F] +
41754 HEX_CHARS[(h3 >> 20) & 0x0F] + HEX_CHARS[(h3 >> 16) & 0x0F] +
41755 HEX_CHARS[(h3 >> 12) & 0x0F] + HEX_CHARS[(h3 >> 8) & 0x0F] +
41756 HEX_CHARS[(h3 >> 4) & 0x0F] + HEX_CHARS[h3 & 0x0F] +
41757 HEX_CHARS[(h4 >> 28) & 0x0F] + HEX_CHARS[(h4 >> 24) & 0x0F] +
41758 HEX_CHARS[(h4 >> 20) & 0x0F] + HEX_CHARS[(h4 >> 16) & 0x0F] +
41759 HEX_CHARS[(h4 >> 12) & 0x0F] + HEX_CHARS[(h4 >> 8) & 0x0F] +
41760 HEX_CHARS[(h4 >> 4) & 0x0F] + HEX_CHARS[h4 & 0x0F] +
41761 HEX_CHARS[(h5 >> 28) & 0x0F] + HEX_CHARS[(h5 >> 24) & 0x0F] +
41762 HEX_CHARS[(h5 >> 20) & 0x0F] + HEX_CHARS[(h5 >> 16) & 0x0F] +
41763 HEX_CHARS[(h5 >> 12) & 0x0F] + HEX_CHARS[(h5 >> 8) & 0x0F] +
41764 HEX_CHARS[(h5 >> 4) & 0x0F] + HEX_CHARS[h5 & 0x0F] +
41765 HEX_CHARS[(h6 >> 28) & 0x0F] + HEX_CHARS[(h6 >> 24) & 0x0F] +
41766 HEX_CHARS[(h6 >> 20) & 0x0F] + HEX_CHARS[(h6 >> 16) & 0x0F] +
41767 HEX_CHARS[(h6 >> 12) & 0x0F] + HEX_CHARS[(h6 >> 8) & 0x0F] +
41768 HEX_CHARS[(h6 >> 4) & 0x0F] + HEX_CHARS[h6 & 0x0F];
41769 if (!this.is224) {
41770 hex += HEX_CHARS[(h7 >> 28) & 0x0F] + HEX_CHARS[(h7 >> 24) & 0x0F] +
41771 HEX_CHARS[(h7 >> 20) & 0x0F] + HEX_CHARS[(h7 >> 16) & 0x0F] +
41772 HEX_CHARS[(h7 >> 12) & 0x0F] + HEX_CHARS[(h7 >> 8) & 0x0F] +
41773 HEX_CHARS[(h7 >> 4) & 0x0F] + HEX_CHARS[h7 & 0x0F];
41774 }
41775 return hex;
41776 };
41777
41778 Sha256.prototype.toString = Sha256.prototype.hex;
41779
41780 Sha256.prototype.digest = function () {
41781 this.finalize();
41782
41783 var h0 = this.h0, h1 = this.h1, h2 = this.h2, h3 = this.h3, h4 = this.h4, h5 = this.h5,
41784 h6 = this.h6, h7 = this.h7;
41785
41786 var arr = [
41787 (h0 >> 24) & 0xFF, (h0 >> 16) & 0xFF, (h0 >> 8) & 0xFF, h0 & 0xFF,
41788 (h1 >> 24) & 0xFF, (h1 >> 16) & 0xFF, (h1 >> 8) & 0xFF, h1 & 0xFF,
41789 (h2 >> 24) & 0xFF, (h2 >> 16) & 0xFF, (h2 >> 8) & 0xFF, h2 & 0xFF,
41790 (h3 >> 24) & 0xFF, (h3 >> 16) & 0xFF, (h3 >> 8) & 0xFF, h3 & 0xFF,
41791 (h4 >> 24) & 0xFF, (h4 >> 16) & 0xFF, (h4 >> 8) & 0xFF, h4 & 0xFF,
41792 (h5 >> 24) & 0xFF, (h5 >> 16) & 0xFF, (h5 >> 8) & 0xFF, h5 & 0xFF,
41793 (h6 >> 24) & 0xFF, (h6 >> 16) & 0xFF, (h6 >> 8) & 0xFF, h6 & 0xFF
41794 ];
41795 if (!this.is224) {
41796 arr.push((h7 >> 24) & 0xFF, (h7 >> 16) & 0xFF, (h7 >> 8) & 0xFF, h7 & 0xFF);
41797 }
41798 return arr;
41799 };
41800
41801 Sha256.prototype.array = Sha256.prototype.digest;
41802
41803 Sha256.prototype.arrayBuffer = function () {
41804 this.finalize();
41805
41806 var buffer = new ArrayBuffer(this.is224 ? 28 : 32);
41807 var dataView = new DataView(buffer);
41808 dataView.setUint32(0, this.h0);
41809 dataView.setUint32(4, this.h1);
41810 dataView.setUint32(8, this.h2);
41811 dataView.setUint32(12, this.h3);
41812 dataView.setUint32(16, this.h4);
41813 dataView.setUint32(20, this.h5);
41814 dataView.setUint32(24, this.h6);
41815 if (!this.is224) {
41816 dataView.setUint32(28, this.h7);
41817 }
41818 return buffer;
41819 };
41820
41821 function HmacSha256(key, is224, sharedMemory) {
41822 var i, type = typeof key;
41823 if (type === 'string') {
41824 var bytes = [], length = key.length, index = 0, code;
41825 for (i = 0; i < length; ++i) {
41826 code = key.charCodeAt(i);
41827 if (code < 0x80) {
41828 bytes[index++] = code;
41829 } else if (code < 0x800) {
41830 bytes[index++] = (0xc0 | (code >> 6));
41831 bytes[index++] = (0x80 | (code & 0x3f));
41832 } else if (code < 0xd800 || code >= 0xe000) {
41833 bytes[index++] = (0xe0 | (code >> 12));
41834 bytes[index++] = (0x80 | ((code >> 6) & 0x3f));
41835 bytes[index++] = (0x80 | (code & 0x3f));
41836 } else {
41837 code = 0x10000 + (((code & 0x3ff) << 10) | (key.charCodeAt(++i) & 0x3ff));
41838 bytes[index++] = (0xf0 | (code >> 18));
41839 bytes[index++] = (0x80 | ((code >> 12) & 0x3f));
41840 bytes[index++] = (0x80 | ((code >> 6) & 0x3f));
41841 bytes[index++] = (0x80 | (code & 0x3f));
41842 }
41843 }
41844 key = bytes;
41845 } else {
41846 if (type === 'object') {
41847 if (key === null) {
41848 throw new Error(ERROR);
41849 } else if (ARRAY_BUFFER && key.constructor === ArrayBuffer) {
41850 key = new Uint8Array(key);
41851 } else if (!Array.isArray(key)) {
41852 if (!ARRAY_BUFFER || !ArrayBuffer.isView(key)) {
41853 throw new Error(ERROR);
41854 }
41855 }
41856 } else {
41857 throw new Error(ERROR);
41858 }
41859 }
41860
41861 if (key.length > 64) {
41862 key = (new Sha256(is224, true)).update(key).array();
41863 }
41864
41865 var oKeyPad = [], iKeyPad = [];
41866 for (i = 0; i < 64; ++i) {
41867 var b = key[i] || 0;
41868 oKeyPad[i] = 0x5c ^ b;
41869 iKeyPad[i] = 0x36 ^ b;
41870 }
41871
41872 Sha256.call(this, is224, sharedMemory);
41873
41874 this.update(iKeyPad);
41875 this.oKeyPad = oKeyPad;
41876 this.inner = true;
41877 this.sharedMemory = sharedMemory;
41878 }
41879 HmacSha256.prototype = new Sha256();
41880
41881 HmacSha256.prototype.finalize = function () {
41882 Sha256.prototype.finalize.call(this);
41883 if (this.inner) {
41884 this.inner = false;
41885 var innerHash = this.array();
41886 Sha256.call(this, this.is224, this.sharedMemory);
41887 this.update(this.oKeyPad);
41888 this.update(innerHash);
41889 Sha256.prototype.finalize.call(this);
41890 }
41891 };
41892
41893 var exports = createMethod();
41894 exports.sha256 = exports;
41895 exports.sha224 = createMethod(true);
41896 exports.sha256.hmac = createHmacMethod();
41897 exports.sha224.hmac = createHmacMethod(true);
41898
41899 if (COMMON_JS) {
41900 module.exports = exports;
41901 } else {
41902 root.sha256 = exports.sha256;
41903 root.sha224 = exports.sha224;
41904 if (AMD) {
41905 define(function () {
41906 return exports;
41907 });
41908 }
41909 }
41910})();
41911
41912}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
41913},{"_process":228}],210:[function(require,module,exports){
41914(function (global){(function (){
41915/**
41916 * @license
41917 * Lodash <https://lodash.com/>
41918 * Copyright OpenJS Foundation and other contributors <https://openjsf.org/>
41919 * Released under MIT license <https://lodash.com/license>
41920 * Based on Underscore.js 1.8.3 <http://underscorejs.org/LICENSE>
41921 * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors
41922 */
41923;(function() {
41924
41925 /** Used as a safe reference for `undefined` in pre-ES5 environments. */
41926 var undefined;
41927
41928 /** Used as the semantic version number. */
41929 var VERSION = '4.17.20';
41930
41931 /** Used as the size to enable large array optimizations. */
41932 var LARGE_ARRAY_SIZE = 200;
41933
41934 /** Error message constants. */
41935 var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.',
41936 FUNC_ERROR_TEXT = 'Expected a function';
41937
41938 /** Used to stand-in for `undefined` hash values. */
41939 var HASH_UNDEFINED = '__lodash_hash_undefined__';
41940
41941 /** Used as the maximum memoize cache size. */
41942 var MAX_MEMOIZE_SIZE = 500;
41943
41944 /** Used as the internal argument placeholder. */
41945 var PLACEHOLDER = '__lodash_placeholder__';
41946
41947 /** Used to compose bitmasks for cloning. */
41948 var CLONE_DEEP_FLAG = 1,
41949 CLONE_FLAT_FLAG = 2,
41950 CLONE_SYMBOLS_FLAG = 4;
41951
41952 /** Used to compose bitmasks for value comparisons. */
41953 var COMPARE_PARTIAL_FLAG = 1,
41954 COMPARE_UNORDERED_FLAG = 2;
41955
41956 /** Used to compose bitmasks for function metadata. */
41957 var WRAP_BIND_FLAG = 1,
41958 WRAP_BIND_KEY_FLAG = 2,
41959 WRAP_CURRY_BOUND_FLAG = 4,
41960 WRAP_CURRY_FLAG = 8,
41961 WRAP_CURRY_RIGHT_FLAG = 16,
41962 WRAP_PARTIAL_FLAG = 32,
41963 WRAP_PARTIAL_RIGHT_FLAG = 64,
41964 WRAP_ARY_FLAG = 128,
41965 WRAP_REARG_FLAG = 256,
41966 WRAP_FLIP_FLAG = 512;
41967
41968 /** Used as default options for `_.truncate`. */
41969 var DEFAULT_TRUNC_LENGTH = 30,
41970 DEFAULT_TRUNC_OMISSION = '...';
41971
41972 /** Used to detect hot functions by number of calls within a span of milliseconds. */
41973 var HOT_COUNT = 800,
41974 HOT_SPAN = 16;
41975
41976 /** Used to indicate the type of lazy iteratees. */
41977 var LAZY_FILTER_FLAG = 1,
41978 LAZY_MAP_FLAG = 2,
41979 LAZY_WHILE_FLAG = 3;
41980
41981 /** Used as references for various `Number` constants. */
41982 var INFINITY = 1 / 0,
41983 MAX_SAFE_INTEGER = 9007199254740991,
41984 MAX_INTEGER = 1.7976931348623157e+308,
41985 NAN = 0 / 0;
41986
41987 /** Used as references for the maximum length and index of an array. */
41988 var MAX_ARRAY_LENGTH = 4294967295,
41989 MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH - 1,
41990 HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH >>> 1;
41991
41992 /** Used to associate wrap methods with their bit flags. */
41993 var wrapFlags = [
41994 ['ary', WRAP_ARY_FLAG],
41995 ['bind', WRAP_BIND_FLAG],
41996 ['bindKey', WRAP_BIND_KEY_FLAG],
41997 ['curry', WRAP_CURRY_FLAG],
41998 ['curryRight', WRAP_CURRY_RIGHT_FLAG],
41999 ['flip', WRAP_FLIP_FLAG],
42000 ['partial', WRAP_PARTIAL_FLAG],
42001 ['partialRight', WRAP_PARTIAL_RIGHT_FLAG],
42002 ['rearg', WRAP_REARG_FLAG]
42003 ];
42004
42005 /** `Object#toString` result references. */
42006 var argsTag = '[object Arguments]',
42007 arrayTag = '[object Array]',
42008 asyncTag = '[object AsyncFunction]',
42009 boolTag = '[object Boolean]',
42010 dateTag = '[object Date]',
42011 domExcTag = '[object DOMException]',
42012 errorTag = '[object Error]',
42013 funcTag = '[object Function]',
42014 genTag = '[object GeneratorFunction]',
42015 mapTag = '[object Map]',
42016 numberTag = '[object Number]',
42017 nullTag = '[object Null]',
42018 objectTag = '[object Object]',
42019 promiseTag = '[object Promise]',
42020 proxyTag = '[object Proxy]',
42021 regexpTag = '[object RegExp]',
42022 setTag = '[object Set]',
42023 stringTag = '[object String]',
42024 symbolTag = '[object Symbol]',
42025 undefinedTag = '[object Undefined]',
42026 weakMapTag = '[object WeakMap]',
42027 weakSetTag = '[object WeakSet]';
42028
42029 var arrayBufferTag = '[object ArrayBuffer]',
42030 dataViewTag = '[object DataView]',
42031 float32Tag = '[object Float32Array]',
42032 float64Tag = '[object Float64Array]',
42033 int8Tag = '[object Int8Array]',
42034 int16Tag = '[object Int16Array]',
42035 int32Tag = '[object Int32Array]',
42036 uint8Tag = '[object Uint8Array]',
42037 uint8ClampedTag = '[object Uint8ClampedArray]',
42038 uint16Tag = '[object Uint16Array]',
42039 uint32Tag = '[object Uint32Array]';
42040
42041 /** Used to match empty string literals in compiled template source. */
42042 var reEmptyStringLeading = /\b__p \+= '';/g,
42043 reEmptyStringMiddle = /\b(__p \+=) '' \+/g,
42044 reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g;
42045
42046 /** Used to match HTML entities and HTML characters. */
42047 var reEscapedHtml = /&(?:amp|lt|gt|quot|#39);/g,
42048 reUnescapedHtml = /[&<>"']/g,
42049 reHasEscapedHtml = RegExp(reEscapedHtml.source),
42050 reHasUnescapedHtml = RegExp(reUnescapedHtml.source);
42051
42052 /** Used to match template delimiters. */
42053 var reEscape = /<%-([\s\S]+?)%>/g,
42054 reEvaluate = /<%([\s\S]+?)%>/g,
42055 reInterpolate = /<%=([\s\S]+?)%>/g;
42056
42057 /** Used to match property names within property paths. */
42058 var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/,
42059 reIsPlainProp = /^\w*$/,
42060 rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g;
42061
42062 /**
42063 * Used to match `RegExp`
42064 * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns).
42065 */
42066 var reRegExpChar = /[\\^$.*+?()[\]{}|]/g,
42067 reHasRegExpChar = RegExp(reRegExpChar.source);
42068
42069 /** Used to match leading and trailing whitespace. */
42070 var reTrim = /^\s+|\s+$/g,
42071 reTrimStart = /^\s+/,
42072 reTrimEnd = /\s+$/;
42073
42074 /** Used to match wrap detail comments. */
42075 var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/,
42076 reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/,
42077 reSplitDetails = /,? & /;
42078
42079 /** Used to match words composed of alphanumeric characters. */
42080 var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g;
42081
42082 /** Used to match backslashes in property paths. */
42083 var reEscapeChar = /\\(\\)?/g;
42084
42085 /**
42086 * Used to match
42087 * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components).
42088 */
42089 var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g;
42090
42091 /** Used to match `RegExp` flags from their coerced string values. */
42092 var reFlags = /\w*$/;
42093
42094 /** Used to detect bad signed hexadecimal string values. */
42095 var reIsBadHex = /^[-+]0x[0-9a-f]+$/i;
42096
42097 /** Used to detect binary string values. */
42098 var reIsBinary = /^0b[01]+$/i;
42099
42100 /** Used to detect host constructors (Safari). */
42101 var reIsHostCtor = /^\[object .+?Constructor\]$/;
42102
42103 /** Used to detect octal string values. */
42104 var reIsOctal = /^0o[0-7]+$/i;
42105
42106 /** Used to detect unsigned integer values. */
42107 var reIsUint = /^(?:0|[1-9]\d*)$/;
42108
42109 /** Used to match Latin Unicode letters (excluding mathematical operators). */
42110 var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g;
42111
42112 /** Used to ensure capturing order of template delimiters. */
42113 var reNoMatch = /($^)/;
42114
42115 /** Used to match unescaped characters in compiled string literals. */
42116 var reUnescapedString = /['\n\r\u2028\u2029\\]/g;
42117
42118 /** Used to compose unicode character classes. */
42119 var rsAstralRange = '\\ud800-\\udfff',
42120 rsComboMarksRange = '\\u0300-\\u036f',
42121 reComboHalfMarksRange = '\\ufe20-\\ufe2f',
42122 rsComboSymbolsRange = '\\u20d0-\\u20ff',
42123 rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange,
42124 rsDingbatRange = '\\u2700-\\u27bf',
42125 rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff',
42126 rsMathOpRange = '\\xac\\xb1\\xd7\\xf7',
42127 rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf',
42128 rsPunctuationRange = '\\u2000-\\u206f',
42129 rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000',
42130 rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde',
42131 rsVarRange = '\\ufe0e\\ufe0f',
42132 rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange;
42133
42134 /** Used to compose unicode capture groups. */
42135 var rsApos = "['\u2019]",
42136 rsAstral = '[' + rsAstralRange + ']',
42137 rsBreak = '[' + rsBreakRange + ']',
42138 rsCombo = '[' + rsComboRange + ']',
42139 rsDigits = '\\d+',
42140 rsDingbat = '[' + rsDingbatRange + ']',
42141 rsLower = '[' + rsLowerRange + ']',
42142 rsMisc = '[^' + rsAstralRange + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']',
42143 rsFitz = '\\ud83c[\\udffb-\\udfff]',
42144 rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')',
42145 rsNonAstral = '[^' + rsAstralRange + ']',
42146 rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}',
42147 rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]',
42148 rsUpper = '[' + rsUpperRange + ']',
42149 rsZWJ = '\\u200d';
42150
42151 /** Used to compose unicode regexes. */
42152 var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')',
42153 rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')',
42154 rsOptContrLower = '(?:' + rsApos + '(?:d|ll|m|re|s|t|ve))?',
42155 rsOptContrUpper = '(?:' + rsApos + '(?:D|LL|M|RE|S|T|VE))?',
42156 reOptMod = rsModifier + '?',
42157 rsOptVar = '[' + rsVarRange + ']?',
42158 rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*',
42159 rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])',
42160 rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])',
42161 rsSeq = rsOptVar + reOptMod + rsOptJoin,
42162 rsEmoji = '(?:' + [rsDingbat, rsRegional, rsSurrPair].join('|') + ')' + rsSeq,
42163 rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')';
42164
42165 /** Used to match apostrophes. */
42166 var reApos = RegExp(rsApos, 'g');
42167
42168 /**
42169 * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and
42170 * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols).
42171 */
42172 var reComboMark = RegExp(rsCombo, 'g');
42173
42174 /** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */
42175 var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g');
42176
42177 /** Used to match complex or compound words. */
42178 var reUnicodeWord = RegExp([
42179 rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')',
42180 rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')',
42181 rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower,
42182 rsUpper + '+' + rsOptContrUpper,
42183 rsOrdUpper,
42184 rsOrdLower,
42185 rsDigits,
42186 rsEmoji
42187 ].join('|'), 'g');
42188
42189 /** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */
42190 var reHasUnicode = RegExp('[' + rsZWJ + rsAstralRange + rsComboRange + rsVarRange + ']');
42191
42192 /** Used to detect strings that need a more robust regexp to match words. */
42193 var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/;
42194
42195 /** Used to assign default `context` object properties. */
42196 var contextProps = [
42197 'Array', 'Buffer', 'DataView', 'Date', 'Error', 'Float32Array', 'Float64Array',
42198 'Function', 'Int8Array', 'Int16Array', 'Int32Array', 'Map', 'Math', 'Object',
42199 'Promise', 'RegExp', 'Set', 'String', 'Symbol', 'TypeError', 'Uint8Array',
42200 'Uint8ClampedArray', 'Uint16Array', 'Uint32Array', 'WeakMap',
42201 '_', 'clearTimeout', 'isFinite', 'parseInt', 'setTimeout'
42202 ];
42203
42204 /** Used to make template sourceURLs easier to identify. */
42205 var templateCounter = -1;
42206
42207 /** Used to identify `toStringTag` values of typed arrays. */
42208 var typedArrayTags = {};
42209 typedArrayTags[float32Tag] = typedArrayTags[float64Tag] =
42210 typedArrayTags[int8Tag] = typedArrayTags[int16Tag] =
42211 typedArrayTags[int32Tag] = typedArrayTags[uint8Tag] =
42212 typedArrayTags[uint8ClampedTag] = typedArrayTags[uint16Tag] =
42213 typedArrayTags[uint32Tag] = true;
42214 typedArrayTags[argsTag] = typedArrayTags[arrayTag] =
42215 typedArrayTags[arrayBufferTag] = typedArrayTags[boolTag] =
42216 typedArrayTags[dataViewTag] = typedArrayTags[dateTag] =
42217 typedArrayTags[errorTag] = typedArrayTags[funcTag] =
42218 typedArrayTags[mapTag] = typedArrayTags[numberTag] =
42219 typedArrayTags[objectTag] = typedArrayTags[regexpTag] =
42220 typedArrayTags[setTag] = typedArrayTags[stringTag] =
42221 typedArrayTags[weakMapTag] = false;
42222
42223 /** Used to identify `toStringTag` values supported by `_.clone`. */
42224 var cloneableTags = {};
42225 cloneableTags[argsTag] = cloneableTags[arrayTag] =
42226 cloneableTags[arrayBufferTag] = cloneableTags[dataViewTag] =
42227 cloneableTags[boolTag] = cloneableTags[dateTag] =
42228 cloneableTags[float32Tag] = cloneableTags[float64Tag] =
42229 cloneableTags[int8Tag] = cloneableTags[int16Tag] =
42230 cloneableTags[int32Tag] = cloneableTags[mapTag] =
42231 cloneableTags[numberTag] = cloneableTags[objectTag] =
42232 cloneableTags[regexpTag] = cloneableTags[setTag] =
42233 cloneableTags[stringTag] = cloneableTags[symbolTag] =
42234 cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] =
42235 cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true;
42236 cloneableTags[errorTag] = cloneableTags[funcTag] =
42237 cloneableTags[weakMapTag] = false;
42238
42239 /** Used to map Latin Unicode letters to basic Latin letters. */
42240 var deburredLetters = {
42241 // Latin-1 Supplement block.
42242 '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A',
42243 '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a',
42244 '\xc7': 'C', '\xe7': 'c',
42245 '\xd0': 'D', '\xf0': 'd',
42246 '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E',
42247 '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e',
42248 '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I',
42249 '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i',
42250 '\xd1': 'N', '\xf1': 'n',
42251 '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O',
42252 '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o',
42253 '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U',
42254 '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u',
42255 '\xdd': 'Y', '\xfd': 'y', '\xff': 'y',
42256 '\xc6': 'Ae', '\xe6': 'ae',
42257 '\xde': 'Th', '\xfe': 'th',
42258 '\xdf': 'ss',
42259 // Latin Extended-A block.
42260 '\u0100': 'A', '\u0102': 'A', '\u0104': 'A',
42261 '\u0101': 'a', '\u0103': 'a', '\u0105': 'a',
42262 '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C',
42263 '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c',
42264 '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd',
42265 '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E',
42266 '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e',
42267 '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G',
42268 '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g',
42269 '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h',
42270 '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I',
42271 '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i',
42272 '\u0134': 'J', '\u0135': 'j',
42273 '\u0136': 'K', '\u0137': 'k', '\u0138': 'k',
42274 '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L',
42275 '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l',
42276 '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N',
42277 '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n',
42278 '\u014c': 'O', '\u014e': 'O', '\u0150': 'O',
42279 '\u014d': 'o', '\u014f': 'o', '\u0151': 'o',
42280 '\u0154': 'R', '\u0156': 'R', '\u0158': 'R',
42281 '\u0155': 'r', '\u0157': 'r', '\u0159': 'r',
42282 '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S',
42283 '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's',
42284 '\u0162': 'T', '\u0164': 'T', '\u0166': 'T',
42285 '\u0163': 't', '\u0165': 't', '\u0167': 't',
42286 '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U',
42287 '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u',
42288 '\u0174': 'W', '\u0175': 'w',
42289 '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y',
42290 '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z',
42291 '\u017a': 'z', '\u017c': 'z', '\u017e': 'z',
42292 '\u0132': 'IJ', '\u0133': 'ij',
42293 '\u0152': 'Oe', '\u0153': 'oe',
42294 '\u0149': "'n", '\u017f': 's'
42295 };
42296
42297 /** Used to map characters to HTML entities. */
42298 var htmlEscapes = {
42299 '&': '&amp;',
42300 '<': '&lt;',
42301 '>': '&gt;',
42302 '"': '&quot;',
42303 "'": '&#39;'
42304 };
42305
42306 /** Used to map HTML entities to characters. */
42307 var htmlUnescapes = {
42308 '&amp;': '&',
42309 '&lt;': '<',
42310 '&gt;': '>',
42311 '&quot;': '"',
42312 '&#39;': "'"
42313 };
42314
42315 /** Used to escape characters for inclusion in compiled string literals. */
42316 var stringEscapes = {
42317 '\\': '\\',
42318 "'": "'",
42319 '\n': 'n',
42320 '\r': 'r',
42321 '\u2028': 'u2028',
42322 '\u2029': 'u2029'
42323 };
42324
42325 /** Built-in method references without a dependency on `root`. */
42326 var freeParseFloat = parseFloat,
42327 freeParseInt = parseInt;
42328
42329 /** Detect free variable `global` from Node.js. */
42330 var freeGlobal = typeof global == 'object' && global && global.Object === Object && global;
42331
42332 /** Detect free variable `self`. */
42333 var freeSelf = typeof self == 'object' && self && self.Object === Object && self;
42334
42335 /** Used as a reference to the global object. */
42336 var root = freeGlobal || freeSelf || Function('return this')();
42337
42338 /** Detect free variable `exports`. */
42339 var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports;
42340
42341 /** Detect free variable `module`. */
42342 var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module;
42343
42344 /** Detect the popular CommonJS extension `module.exports`. */
42345 var moduleExports = freeModule && freeModule.exports === freeExports;
42346
42347 /** Detect free variable `process` from Node.js. */
42348 var freeProcess = moduleExports && freeGlobal.process;
42349
42350 /** Used to access faster Node.js helpers. */
42351 var nodeUtil = (function() {
42352 try {
42353 // Use `util.types` for Node.js 10+.
42354 var types = freeModule && freeModule.require && freeModule.require('util').types;
42355
42356 if (types) {
42357 return types;
42358 }
42359
42360 // Legacy `process.binding('util')` for Node.js < 10.
42361 return freeProcess && freeProcess.binding && freeProcess.binding('util');
42362 } catch (e) {}
42363 }());
42364
42365 /* Node.js helper references. */
42366 var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer,
42367 nodeIsDate = nodeUtil && nodeUtil.isDate,
42368 nodeIsMap = nodeUtil && nodeUtil.isMap,
42369 nodeIsRegExp = nodeUtil && nodeUtil.isRegExp,
42370 nodeIsSet = nodeUtil && nodeUtil.isSet,
42371 nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray;
42372
42373 /*--------------------------------------------------------------------------*/
42374
42375 /**
42376 * A faster alternative to `Function#apply`, this function invokes `func`
42377 * with the `this` binding of `thisArg` and the arguments of `args`.
42378 *
42379 * @private
42380 * @param {Function} func The function to invoke.
42381 * @param {*} thisArg The `this` binding of `func`.
42382 * @param {Array} args The arguments to invoke `func` with.
42383 * @returns {*} Returns the result of `func`.
42384 */
42385 function apply(func, thisArg, args) {
42386 switch (args.length) {
42387 case 0: return func.call(thisArg);
42388 case 1: return func.call(thisArg, args[0]);
42389 case 2: return func.call(thisArg, args[0], args[1]);
42390 case 3: return func.call(thisArg, args[0], args[1], args[2]);
42391 }
42392 return func.apply(thisArg, args);
42393 }
42394
42395 /**
42396 * A specialized version of `baseAggregator` for arrays.
42397 *
42398 * @private
42399 * @param {Array} [array] The array to iterate over.
42400 * @param {Function} setter The function to set `accumulator` values.
42401 * @param {Function} iteratee The iteratee to transform keys.
42402 * @param {Object} accumulator The initial aggregated object.
42403 * @returns {Function} Returns `accumulator`.
42404 */
42405 function arrayAggregator(array, setter, iteratee, accumulator) {
42406 var index = -1,
42407 length = array == null ? 0 : array.length;
42408
42409 while (++index < length) {
42410 var value = array[index];
42411 setter(accumulator, value, iteratee(value), array);
42412 }
42413 return accumulator;
42414 }
42415
42416 /**
42417 * A specialized version of `_.forEach` for arrays without support for
42418 * iteratee shorthands.
42419 *
42420 * @private
42421 * @param {Array} [array] The array to iterate over.
42422 * @param {Function} iteratee The function invoked per iteration.
42423 * @returns {Array} Returns `array`.
42424 */
42425 function arrayEach(array, iteratee) {
42426 var index = -1,
42427 length = array == null ? 0 : array.length;
42428
42429 while (++index < length) {
42430 if (iteratee(array[index], index, array) === false) {
42431 break;
42432 }
42433 }
42434 return array;
42435 }
42436
42437 /**
42438 * A specialized version of `_.forEachRight` for arrays without support for
42439 * iteratee shorthands.
42440 *
42441 * @private
42442 * @param {Array} [array] The array to iterate over.
42443 * @param {Function} iteratee The function invoked per iteration.
42444 * @returns {Array} Returns `array`.
42445 */
42446 function arrayEachRight(array, iteratee) {
42447 var length = array == null ? 0 : array.length;
42448
42449 while (length--) {
42450 if (iteratee(array[length], length, array) === false) {
42451 break;
42452 }
42453 }
42454 return array;
42455 }
42456
42457 /**
42458 * A specialized version of `_.every` for arrays without support for
42459 * iteratee shorthands.
42460 *
42461 * @private
42462 * @param {Array} [array] The array to iterate over.
42463 * @param {Function} predicate The function invoked per iteration.
42464 * @returns {boolean} Returns `true` if all elements pass the predicate check,
42465 * else `false`.
42466 */
42467 function arrayEvery(array, predicate) {
42468 var index = -1,
42469 length = array == null ? 0 : array.length;
42470
42471 while (++index < length) {
42472 if (!predicate(array[index], index, array)) {
42473 return false;
42474 }
42475 }
42476 return true;
42477 }
42478
42479 /**
42480 * A specialized version of `_.filter` for arrays without support for
42481 * iteratee shorthands.
42482 *
42483 * @private
42484 * @param {Array} [array] The array to iterate over.
42485 * @param {Function} predicate The function invoked per iteration.
42486 * @returns {Array} Returns the new filtered array.
42487 */
42488 function arrayFilter(array, predicate) {
42489 var index = -1,
42490 length = array == null ? 0 : array.length,
42491 resIndex = 0,
42492 result = [];
42493
42494 while (++index < length) {
42495 var value = array[index];
42496 if (predicate(value, index, array)) {
42497 result[resIndex++] = value;
42498 }
42499 }
42500 return result;
42501 }
42502
42503 /**
42504 * A specialized version of `_.includes` for arrays without support for
42505 * specifying an index to search from.
42506 *
42507 * @private
42508 * @param {Array} [array] The array to inspect.
42509 * @param {*} target The value to search for.
42510 * @returns {boolean} Returns `true` if `target` is found, else `false`.
42511 */
42512 function arrayIncludes(array, value) {
42513 var length = array == null ? 0 : array.length;
42514 return !!length && baseIndexOf(array, value, 0) > -1;
42515 }
42516
42517 /**
42518 * This function is like `arrayIncludes` except that it accepts a comparator.
42519 *
42520 * @private
42521 * @param {Array} [array] The array to inspect.
42522 * @param {*} target The value to search for.
42523 * @param {Function} comparator The comparator invoked per element.
42524 * @returns {boolean} Returns `true` if `target` is found, else `false`.
42525 */
42526 function arrayIncludesWith(array, value, comparator) {
42527 var index = -1,
42528 length = array == null ? 0 : array.length;
42529
42530 while (++index < length) {
42531 if (comparator(value, array[index])) {
42532 return true;
42533 }
42534 }
42535 return false;
42536 }
42537
42538 /**
42539 * A specialized version of `_.map` for arrays without support for iteratee
42540 * shorthands.
42541 *
42542 * @private
42543 * @param {Array} [array] The array to iterate over.
42544 * @param {Function} iteratee The function invoked per iteration.
42545 * @returns {Array} Returns the new mapped array.
42546 */
42547 function arrayMap(array, iteratee) {
42548 var index = -1,
42549 length = array == null ? 0 : array.length,
42550 result = Array(length);
42551
42552 while (++index < length) {
42553 result[index] = iteratee(array[index], index, array);
42554 }
42555 return result;
42556 }
42557
42558 /**
42559 * Appends the elements of `values` to `array`.
42560 *
42561 * @private
42562 * @param {Array} array The array to modify.
42563 * @param {Array} values The values to append.
42564 * @returns {Array} Returns `array`.
42565 */
42566 function arrayPush(array, values) {
42567 var index = -1,
42568 length = values.length,
42569 offset = array.length;
42570
42571 while (++index < length) {
42572 array[offset + index] = values[index];
42573 }
42574 return array;
42575 }
42576
42577 /**
42578 * A specialized version of `_.reduce` for arrays without support for
42579 * iteratee shorthands.
42580 *
42581 * @private
42582 * @param {Array} [array] The array to iterate over.
42583 * @param {Function} iteratee The function invoked per iteration.
42584 * @param {*} [accumulator] The initial value.
42585 * @param {boolean} [initAccum] Specify using the first element of `array` as
42586 * the initial value.
42587 * @returns {*} Returns the accumulated value.
42588 */
42589 function arrayReduce(array, iteratee, accumulator, initAccum) {
42590 var index = -1,
42591 length = array == null ? 0 : array.length;
42592
42593 if (initAccum && length) {
42594 accumulator = array[++index];
42595 }
42596 while (++index < length) {
42597 accumulator = iteratee(accumulator, array[index], index, array);
42598 }
42599 return accumulator;
42600 }
42601
42602 /**
42603 * A specialized version of `_.reduceRight` for arrays without support for
42604 * iteratee shorthands.
42605 *
42606 * @private
42607 * @param {Array} [array] The array to iterate over.
42608 * @param {Function} iteratee The function invoked per iteration.
42609 * @param {*} [accumulator] The initial value.
42610 * @param {boolean} [initAccum] Specify using the last element of `array` as
42611 * the initial value.
42612 * @returns {*} Returns the accumulated value.
42613 */
42614 function arrayReduceRight(array, iteratee, accumulator, initAccum) {
42615 var length = array == null ? 0 : array.length;
42616 if (initAccum && length) {
42617 accumulator = array[--length];
42618 }
42619 while (length--) {
42620 accumulator = iteratee(accumulator, array[length], length, array);
42621 }
42622 return accumulator;
42623 }
42624
42625 /**
42626 * A specialized version of `_.some` for arrays without support for iteratee
42627 * shorthands.
42628 *
42629 * @private
42630 * @param {Array} [array] The array to iterate over.
42631 * @param {Function} predicate The function invoked per iteration.
42632 * @returns {boolean} Returns `true` if any element passes the predicate check,
42633 * else `false`.
42634 */
42635 function arraySome(array, predicate) {
42636 var index = -1,
42637 length = array == null ? 0 : array.length;
42638
42639 while (++index < length) {
42640 if (predicate(array[index], index, array)) {
42641 return true;
42642 }
42643 }
42644 return false;
42645 }
42646
42647 /**
42648 * Gets the size of an ASCII `string`.
42649 *
42650 * @private
42651 * @param {string} string The string inspect.
42652 * @returns {number} Returns the string size.
42653 */
42654 var asciiSize = baseProperty('length');
42655
42656 /**
42657 * Converts an ASCII `string` to an array.
42658 *
42659 * @private
42660 * @param {string} string The string to convert.
42661 * @returns {Array} Returns the converted array.
42662 */
42663 function asciiToArray(string) {
42664 return string.split('');
42665 }
42666
42667 /**
42668 * Splits an ASCII `string` into an array of its words.
42669 *
42670 * @private
42671 * @param {string} The string to inspect.
42672 * @returns {Array} Returns the words of `string`.
42673 */
42674 function asciiWords(string) {
42675 return string.match(reAsciiWord) || [];
42676 }
42677
42678 /**
42679 * The base implementation of methods like `_.findKey` and `_.findLastKey`,
42680 * without support for iteratee shorthands, which iterates over `collection`
42681 * using `eachFunc`.
42682 *
42683 * @private
42684 * @param {Array|Object} collection The collection to inspect.
42685 * @param {Function} predicate The function invoked per iteration.
42686 * @param {Function} eachFunc The function to iterate over `collection`.
42687 * @returns {*} Returns the found element or its key, else `undefined`.
42688 */
42689 function baseFindKey(collection, predicate, eachFunc) {
42690 var result;
42691 eachFunc(collection, function(value, key, collection) {
42692 if (predicate(value, key, collection)) {
42693 result = key;
42694 return false;
42695 }
42696 });
42697 return result;
42698 }
42699
42700 /**
42701 * The base implementation of `_.findIndex` and `_.findLastIndex` without
42702 * support for iteratee shorthands.
42703 *
42704 * @private
42705 * @param {Array} array The array to inspect.
42706 * @param {Function} predicate The function invoked per iteration.
42707 * @param {number} fromIndex The index to search from.
42708 * @param {boolean} [fromRight] Specify iterating from right to left.
42709 * @returns {number} Returns the index of the matched value, else `-1`.
42710 */
42711 function baseFindIndex(array, predicate, fromIndex, fromRight) {
42712 var length = array.length,
42713 index = fromIndex + (fromRight ? 1 : -1);
42714
42715 while ((fromRight ? index-- : ++index < length)) {
42716 if (predicate(array[index], index, array)) {
42717 return index;
42718 }
42719 }
42720 return -1;
42721 }
42722
42723 /**
42724 * The base implementation of `_.indexOf` without `fromIndex` bounds checks.
42725 *
42726 * @private
42727 * @param {Array} array The array to inspect.
42728 * @param {*} value The value to search for.
42729 * @param {number} fromIndex The index to search from.
42730 * @returns {number} Returns the index of the matched value, else `-1`.
42731 */
42732 function baseIndexOf(array, value, fromIndex) {
42733 return value === value
42734 ? strictIndexOf(array, value, fromIndex)
42735 : baseFindIndex(array, baseIsNaN, fromIndex);
42736 }
42737
42738 /**
42739 * This function is like `baseIndexOf` except that it accepts a comparator.
42740 *
42741 * @private
42742 * @param {Array} array The array to inspect.
42743 * @param {*} value The value to search for.
42744 * @param {number} fromIndex The index to search from.
42745 * @param {Function} comparator The comparator invoked per element.
42746 * @returns {number} Returns the index of the matched value, else `-1`.
42747 */
42748 function baseIndexOfWith(array, value, fromIndex, comparator) {
42749 var index = fromIndex - 1,
42750 length = array.length;
42751
42752 while (++index < length) {
42753 if (comparator(array[index], value)) {
42754 return index;
42755 }
42756 }
42757 return -1;
42758 }
42759
42760 /**
42761 * The base implementation of `_.isNaN` without support for number objects.
42762 *
42763 * @private
42764 * @param {*} value The value to check.
42765 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
42766 */
42767 function baseIsNaN(value) {
42768 return value !== value;
42769 }
42770
42771 /**
42772 * The base implementation of `_.mean` and `_.meanBy` without support for
42773 * iteratee shorthands.
42774 *
42775 * @private
42776 * @param {Array} array The array to iterate over.
42777 * @param {Function} iteratee The function invoked per iteration.
42778 * @returns {number} Returns the mean.
42779 */
42780 function baseMean(array, iteratee) {
42781 var length = array == null ? 0 : array.length;
42782 return length ? (baseSum(array, iteratee) / length) : NAN;
42783 }
42784
42785 /**
42786 * The base implementation of `_.property` without support for deep paths.
42787 *
42788 * @private
42789 * @param {string} key The key of the property to get.
42790 * @returns {Function} Returns the new accessor function.
42791 */
42792 function baseProperty(key) {
42793 return function(object) {
42794 return object == null ? undefined : object[key];
42795 };
42796 }
42797
42798 /**
42799 * The base implementation of `_.propertyOf` without support for deep paths.
42800 *
42801 * @private
42802 * @param {Object} object The object to query.
42803 * @returns {Function} Returns the new accessor function.
42804 */
42805 function basePropertyOf(object) {
42806 return function(key) {
42807 return object == null ? undefined : object[key];
42808 };
42809 }
42810
42811 /**
42812 * The base implementation of `_.reduce` and `_.reduceRight`, without support
42813 * for iteratee shorthands, which iterates over `collection` using `eachFunc`.
42814 *
42815 * @private
42816 * @param {Array|Object} collection The collection to iterate over.
42817 * @param {Function} iteratee The function invoked per iteration.
42818 * @param {*} accumulator The initial value.
42819 * @param {boolean} initAccum Specify using the first or last element of
42820 * `collection` as the initial value.
42821 * @param {Function} eachFunc The function to iterate over `collection`.
42822 * @returns {*} Returns the accumulated value.
42823 */
42824 function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) {
42825 eachFunc(collection, function(value, index, collection) {
42826 accumulator = initAccum
42827 ? (initAccum = false, value)
42828 : iteratee(accumulator, value, index, collection);
42829 });
42830 return accumulator;
42831 }
42832
42833 /**
42834 * The base implementation of `_.sortBy` which uses `comparer` to define the
42835 * sort order of `array` and replaces criteria objects with their corresponding
42836 * values.
42837 *
42838 * @private
42839 * @param {Array} array The array to sort.
42840 * @param {Function} comparer The function to define sort order.
42841 * @returns {Array} Returns `array`.
42842 */
42843 function baseSortBy(array, comparer) {
42844 var length = array.length;
42845
42846 array.sort(comparer);
42847 while (length--) {
42848 array[length] = array[length].value;
42849 }
42850 return array;
42851 }
42852
42853 /**
42854 * The base implementation of `_.sum` and `_.sumBy` without support for
42855 * iteratee shorthands.
42856 *
42857 * @private
42858 * @param {Array} array The array to iterate over.
42859 * @param {Function} iteratee The function invoked per iteration.
42860 * @returns {number} Returns the sum.
42861 */
42862 function baseSum(array, iteratee) {
42863 var result,
42864 index = -1,
42865 length = array.length;
42866
42867 while (++index < length) {
42868 var current = iteratee(array[index]);
42869 if (current !== undefined) {
42870 result = result === undefined ? current : (result + current);
42871 }
42872 }
42873 return result;
42874 }
42875
42876 /**
42877 * The base implementation of `_.times` without support for iteratee shorthands
42878 * or max array length checks.
42879 *
42880 * @private
42881 * @param {number} n The number of times to invoke `iteratee`.
42882 * @param {Function} iteratee The function invoked per iteration.
42883 * @returns {Array} Returns the array of results.
42884 */
42885 function baseTimes(n, iteratee) {
42886 var index = -1,
42887 result = Array(n);
42888
42889 while (++index < n) {
42890 result[index] = iteratee(index);
42891 }
42892 return result;
42893 }
42894
42895 /**
42896 * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array
42897 * of key-value pairs for `object` corresponding to the property names of `props`.
42898 *
42899 * @private
42900 * @param {Object} object The object to query.
42901 * @param {Array} props The property names to get values for.
42902 * @returns {Object} Returns the key-value pairs.
42903 */
42904 function baseToPairs(object, props) {
42905 return arrayMap(props, function(key) {
42906 return [key, object[key]];
42907 });
42908 }
42909
42910 /**
42911 * The base implementation of `_.unary` without support for storing metadata.
42912 *
42913 * @private
42914 * @param {Function} func The function to cap arguments for.
42915 * @returns {Function} Returns the new capped function.
42916 */
42917 function baseUnary(func) {
42918 return function(value) {
42919 return func(value);
42920 };
42921 }
42922
42923 /**
42924 * The base implementation of `_.values` and `_.valuesIn` which creates an
42925 * array of `object` property values corresponding to the property names
42926 * of `props`.
42927 *
42928 * @private
42929 * @param {Object} object The object to query.
42930 * @param {Array} props The property names to get values for.
42931 * @returns {Object} Returns the array of property values.
42932 */
42933 function baseValues(object, props) {
42934 return arrayMap(props, function(key) {
42935 return object[key];
42936 });
42937 }
42938
42939 /**
42940 * Checks if a `cache` value for `key` exists.
42941 *
42942 * @private
42943 * @param {Object} cache The cache to query.
42944 * @param {string} key The key of the entry to check.
42945 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
42946 */
42947 function cacheHas(cache, key) {
42948 return cache.has(key);
42949 }
42950
42951 /**
42952 * Used by `_.trim` and `_.trimStart` to get the index of the first string symbol
42953 * that is not found in the character symbols.
42954 *
42955 * @private
42956 * @param {Array} strSymbols The string symbols to inspect.
42957 * @param {Array} chrSymbols The character symbols to find.
42958 * @returns {number} Returns the index of the first unmatched string symbol.
42959 */
42960 function charsStartIndex(strSymbols, chrSymbols) {
42961 var index = -1,
42962 length = strSymbols.length;
42963
42964 while (++index < length && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
42965 return index;
42966 }
42967
42968 /**
42969 * Used by `_.trim` and `_.trimEnd` to get the index of the last string symbol
42970 * that is not found in the character symbols.
42971 *
42972 * @private
42973 * @param {Array} strSymbols The string symbols to inspect.
42974 * @param {Array} chrSymbols The character symbols to find.
42975 * @returns {number} Returns the index of the last unmatched string symbol.
42976 */
42977 function charsEndIndex(strSymbols, chrSymbols) {
42978 var index = strSymbols.length;
42979
42980 while (index-- && baseIndexOf(chrSymbols, strSymbols[index], 0) > -1) {}
42981 return index;
42982 }
42983
42984 /**
42985 * Gets the number of `placeholder` occurrences in `array`.
42986 *
42987 * @private
42988 * @param {Array} array The array to inspect.
42989 * @param {*} placeholder The placeholder to search for.
42990 * @returns {number} Returns the placeholder count.
42991 */
42992 function countHolders(array, placeholder) {
42993 var length = array.length,
42994 result = 0;
42995
42996 while (length--) {
42997 if (array[length] === placeholder) {
42998 ++result;
42999 }
43000 }
43001 return result;
43002 }
43003
43004 /**
43005 * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A
43006 * letters to basic Latin letters.
43007 *
43008 * @private
43009 * @param {string} letter The matched letter to deburr.
43010 * @returns {string} Returns the deburred letter.
43011 */
43012 var deburrLetter = basePropertyOf(deburredLetters);
43013
43014 /**
43015 * Used by `_.escape` to convert characters to HTML entities.
43016 *
43017 * @private
43018 * @param {string} chr The matched character to escape.
43019 * @returns {string} Returns the escaped character.
43020 */
43021 var escapeHtmlChar = basePropertyOf(htmlEscapes);
43022
43023 /**
43024 * Used by `_.template` to escape characters for inclusion in compiled string literals.
43025 *
43026 * @private
43027 * @param {string} chr The matched character to escape.
43028 * @returns {string} Returns the escaped character.
43029 */
43030 function escapeStringChar(chr) {
43031 return '\\' + stringEscapes[chr];
43032 }
43033
43034 /**
43035 * Gets the value at `key` of `object`.
43036 *
43037 * @private
43038 * @param {Object} [object] The object to query.
43039 * @param {string} key The key of the property to get.
43040 * @returns {*} Returns the property value.
43041 */
43042 function getValue(object, key) {
43043 return object == null ? undefined : object[key];
43044 }
43045
43046 /**
43047 * Checks if `string` contains Unicode symbols.
43048 *
43049 * @private
43050 * @param {string} string The string to inspect.
43051 * @returns {boolean} Returns `true` if a symbol is found, else `false`.
43052 */
43053 function hasUnicode(string) {
43054 return reHasUnicode.test(string);
43055 }
43056
43057 /**
43058 * Checks if `string` contains a word composed of Unicode symbols.
43059 *
43060 * @private
43061 * @param {string} string The string to inspect.
43062 * @returns {boolean} Returns `true` if a word is found, else `false`.
43063 */
43064 function hasUnicodeWord(string) {
43065 return reHasUnicodeWord.test(string);
43066 }
43067
43068 /**
43069 * Converts `iterator` to an array.
43070 *
43071 * @private
43072 * @param {Object} iterator The iterator to convert.
43073 * @returns {Array} Returns the converted array.
43074 */
43075 function iteratorToArray(iterator) {
43076 var data,
43077 result = [];
43078
43079 while (!(data = iterator.next()).done) {
43080 result.push(data.value);
43081 }
43082 return result;
43083 }
43084
43085 /**
43086 * Converts `map` to its key-value pairs.
43087 *
43088 * @private
43089 * @param {Object} map The map to convert.
43090 * @returns {Array} Returns the key-value pairs.
43091 */
43092 function mapToArray(map) {
43093 var index = -1,
43094 result = Array(map.size);
43095
43096 map.forEach(function(value, key) {
43097 result[++index] = [key, value];
43098 });
43099 return result;
43100 }
43101
43102 /**
43103 * Creates a unary function that invokes `func` with its argument transformed.
43104 *
43105 * @private
43106 * @param {Function} func The function to wrap.
43107 * @param {Function} transform The argument transform.
43108 * @returns {Function} Returns the new function.
43109 */
43110 function overArg(func, transform) {
43111 return function(arg) {
43112 return func(transform(arg));
43113 };
43114 }
43115
43116 /**
43117 * Replaces all `placeholder` elements in `array` with an internal placeholder
43118 * and returns an array of their indexes.
43119 *
43120 * @private
43121 * @param {Array} array The array to modify.
43122 * @param {*} placeholder The placeholder to replace.
43123 * @returns {Array} Returns the new array of placeholder indexes.
43124 */
43125 function replaceHolders(array, placeholder) {
43126 var index = -1,
43127 length = array.length,
43128 resIndex = 0,
43129 result = [];
43130
43131 while (++index < length) {
43132 var value = array[index];
43133 if (value === placeholder || value === PLACEHOLDER) {
43134 array[index] = PLACEHOLDER;
43135 result[resIndex++] = index;
43136 }
43137 }
43138 return result;
43139 }
43140
43141 /**
43142 * Converts `set` to an array of its values.
43143 *
43144 * @private
43145 * @param {Object} set The set to convert.
43146 * @returns {Array} Returns the values.
43147 */
43148 function setToArray(set) {
43149 var index = -1,
43150 result = Array(set.size);
43151
43152 set.forEach(function(value) {
43153 result[++index] = value;
43154 });
43155 return result;
43156 }
43157
43158 /**
43159 * Converts `set` to its value-value pairs.
43160 *
43161 * @private
43162 * @param {Object} set The set to convert.
43163 * @returns {Array} Returns the value-value pairs.
43164 */
43165 function setToPairs(set) {
43166 var index = -1,
43167 result = Array(set.size);
43168
43169 set.forEach(function(value) {
43170 result[++index] = [value, value];
43171 });
43172 return result;
43173 }
43174
43175 /**
43176 * A specialized version of `_.indexOf` which performs strict equality
43177 * comparisons of values, i.e. `===`.
43178 *
43179 * @private
43180 * @param {Array} array The array to inspect.
43181 * @param {*} value The value to search for.
43182 * @param {number} fromIndex The index to search from.
43183 * @returns {number} Returns the index of the matched value, else `-1`.
43184 */
43185 function strictIndexOf(array, value, fromIndex) {
43186 var index = fromIndex - 1,
43187 length = array.length;
43188
43189 while (++index < length) {
43190 if (array[index] === value) {
43191 return index;
43192 }
43193 }
43194 return -1;
43195 }
43196
43197 /**
43198 * A specialized version of `_.lastIndexOf` which performs strict equality
43199 * comparisons of values, i.e. `===`.
43200 *
43201 * @private
43202 * @param {Array} array The array to inspect.
43203 * @param {*} value The value to search for.
43204 * @param {number} fromIndex The index to search from.
43205 * @returns {number} Returns the index of the matched value, else `-1`.
43206 */
43207 function strictLastIndexOf(array, value, fromIndex) {
43208 var index = fromIndex + 1;
43209 while (index--) {
43210 if (array[index] === value) {
43211 return index;
43212 }
43213 }
43214 return index;
43215 }
43216
43217 /**
43218 * Gets the number of symbols in `string`.
43219 *
43220 * @private
43221 * @param {string} string The string to inspect.
43222 * @returns {number} Returns the string size.
43223 */
43224 function stringSize(string) {
43225 return hasUnicode(string)
43226 ? unicodeSize(string)
43227 : asciiSize(string);
43228 }
43229
43230 /**
43231 * Converts `string` to an array.
43232 *
43233 * @private
43234 * @param {string} string The string to convert.
43235 * @returns {Array} Returns the converted array.
43236 */
43237 function stringToArray(string) {
43238 return hasUnicode(string)
43239 ? unicodeToArray(string)
43240 : asciiToArray(string);
43241 }
43242
43243 /**
43244 * Used by `_.unescape` to convert HTML entities to characters.
43245 *
43246 * @private
43247 * @param {string} chr The matched character to unescape.
43248 * @returns {string} Returns the unescaped character.
43249 */
43250 var unescapeHtmlChar = basePropertyOf(htmlUnescapes);
43251
43252 /**
43253 * Gets the size of a Unicode `string`.
43254 *
43255 * @private
43256 * @param {string} string The string inspect.
43257 * @returns {number} Returns the string size.
43258 */
43259 function unicodeSize(string) {
43260 var result = reUnicode.lastIndex = 0;
43261 while (reUnicode.test(string)) {
43262 ++result;
43263 }
43264 return result;
43265 }
43266
43267 /**
43268 * Converts a Unicode `string` to an array.
43269 *
43270 * @private
43271 * @param {string} string The string to convert.
43272 * @returns {Array} Returns the converted array.
43273 */
43274 function unicodeToArray(string) {
43275 return string.match(reUnicode) || [];
43276 }
43277
43278 /**
43279 * Splits a Unicode `string` into an array of its words.
43280 *
43281 * @private
43282 * @param {string} The string to inspect.
43283 * @returns {Array} Returns the words of `string`.
43284 */
43285 function unicodeWords(string) {
43286 return string.match(reUnicodeWord) || [];
43287 }
43288
43289 /*--------------------------------------------------------------------------*/
43290
43291 /**
43292 * Create a new pristine `lodash` function using the `context` object.
43293 *
43294 * @static
43295 * @memberOf _
43296 * @since 1.1.0
43297 * @category Util
43298 * @param {Object} [context=root] The context object.
43299 * @returns {Function} Returns a new `lodash` function.
43300 * @example
43301 *
43302 * _.mixin({ 'foo': _.constant('foo') });
43303 *
43304 * var lodash = _.runInContext();
43305 * lodash.mixin({ 'bar': lodash.constant('bar') });
43306 *
43307 * _.isFunction(_.foo);
43308 * // => true
43309 * _.isFunction(_.bar);
43310 * // => false
43311 *
43312 * lodash.isFunction(lodash.foo);
43313 * // => false
43314 * lodash.isFunction(lodash.bar);
43315 * // => true
43316 *
43317 * // Create a suped-up `defer` in Node.js.
43318 * var defer = _.runInContext({ 'setTimeout': setImmediate }).defer;
43319 */
43320 var runInContext = (function runInContext(context) {
43321 context = context == null ? root : _.defaults(root.Object(), context, _.pick(root, contextProps));
43322
43323 /** Built-in constructor references. */
43324 var Array = context.Array,
43325 Date = context.Date,
43326 Error = context.Error,
43327 Function = context.Function,
43328 Math = context.Math,
43329 Object = context.Object,
43330 RegExp = context.RegExp,
43331 String = context.String,
43332 TypeError = context.TypeError;
43333
43334 /** Used for built-in method references. */
43335 var arrayProto = Array.prototype,
43336 funcProto = Function.prototype,
43337 objectProto = Object.prototype;
43338
43339 /** Used to detect overreaching core-js shims. */
43340 var coreJsData = context['__core-js_shared__'];
43341
43342 /** Used to resolve the decompiled source of functions. */
43343 var funcToString = funcProto.toString;
43344
43345 /** Used to check objects for own properties. */
43346 var hasOwnProperty = objectProto.hasOwnProperty;
43347
43348 /** Used to generate unique IDs. */
43349 var idCounter = 0;
43350
43351 /** Used to detect methods masquerading as native. */
43352 var maskSrcKey = (function() {
43353 var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || '');
43354 return uid ? ('Symbol(src)_1.' + uid) : '';
43355 }());
43356
43357 /**
43358 * Used to resolve the
43359 * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring)
43360 * of values.
43361 */
43362 var nativeObjectToString = objectProto.toString;
43363
43364 /** Used to infer the `Object` constructor. */
43365 var objectCtorString = funcToString.call(Object);
43366
43367 /** Used to restore the original `_` reference in `_.noConflict`. */
43368 var oldDash = root._;
43369
43370 /** Used to detect if a method is native. */
43371 var reIsNative = RegExp('^' +
43372 funcToString.call(hasOwnProperty).replace(reRegExpChar, '\\$&')
43373 .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$'
43374 );
43375
43376 /** Built-in value references. */
43377 var Buffer = moduleExports ? context.Buffer : undefined,
43378 Symbol = context.Symbol,
43379 Uint8Array = context.Uint8Array,
43380 allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined,
43381 getPrototype = overArg(Object.getPrototypeOf, Object),
43382 objectCreate = Object.create,
43383 propertyIsEnumerable = objectProto.propertyIsEnumerable,
43384 splice = arrayProto.splice,
43385 spreadableSymbol = Symbol ? Symbol.isConcatSpreadable : undefined,
43386 symIterator = Symbol ? Symbol.iterator : undefined,
43387 symToStringTag = Symbol ? Symbol.toStringTag : undefined;
43388
43389 var defineProperty = (function() {
43390 try {
43391 var func = getNative(Object, 'defineProperty');
43392 func({}, '', {});
43393 return func;
43394 } catch (e) {}
43395 }());
43396
43397 /** Mocked built-ins. */
43398 var ctxClearTimeout = context.clearTimeout !== root.clearTimeout && context.clearTimeout,
43399 ctxNow = Date && Date.now !== root.Date.now && Date.now,
43400 ctxSetTimeout = context.setTimeout !== root.setTimeout && context.setTimeout;
43401
43402 /* Built-in method references for those with the same name as other `lodash` methods. */
43403 var nativeCeil = Math.ceil,
43404 nativeFloor = Math.floor,
43405 nativeGetSymbols = Object.getOwnPropertySymbols,
43406 nativeIsBuffer = Buffer ? Buffer.isBuffer : undefined,
43407 nativeIsFinite = context.isFinite,
43408 nativeJoin = arrayProto.join,
43409 nativeKeys = overArg(Object.keys, Object),
43410 nativeMax = Math.max,
43411 nativeMin = Math.min,
43412 nativeNow = Date.now,
43413 nativeParseInt = context.parseInt,
43414 nativeRandom = Math.random,
43415 nativeReverse = arrayProto.reverse;
43416
43417 /* Built-in method references that are verified to be native. */
43418 var DataView = getNative(context, 'DataView'),
43419 Map = getNative(context, 'Map'),
43420 Promise = getNative(context, 'Promise'),
43421 Set = getNative(context, 'Set'),
43422 WeakMap = getNative(context, 'WeakMap'),
43423 nativeCreate = getNative(Object, 'create');
43424
43425 /** Used to store function metadata. */
43426 var metaMap = WeakMap && new WeakMap;
43427
43428 /** Used to lookup unminified function names. */
43429 var realNames = {};
43430
43431 /** Used to detect maps, sets, and weakmaps. */
43432 var dataViewCtorString = toSource(DataView),
43433 mapCtorString = toSource(Map),
43434 promiseCtorString = toSource(Promise),
43435 setCtorString = toSource(Set),
43436 weakMapCtorString = toSource(WeakMap);
43437
43438 /** Used to convert symbols to primitives and strings. */
43439 var symbolProto = Symbol ? Symbol.prototype : undefined,
43440 symbolValueOf = symbolProto ? symbolProto.valueOf : undefined,
43441 symbolToString = symbolProto ? symbolProto.toString : undefined;
43442
43443 /*------------------------------------------------------------------------*/
43444
43445 /**
43446 * Creates a `lodash` object which wraps `value` to enable implicit method
43447 * chain sequences. Methods that operate on and return arrays, collections,
43448 * and functions can be chained together. Methods that retrieve a single value
43449 * or may return a primitive value will automatically end the chain sequence
43450 * and return the unwrapped value. Otherwise, the value must be unwrapped
43451 * with `_#value`.
43452 *
43453 * Explicit chain sequences, which must be unwrapped with `_#value`, may be
43454 * enabled using `_.chain`.
43455 *
43456 * The execution of chained methods is lazy, that is, it's deferred until
43457 * `_#value` is implicitly or explicitly called.
43458 *
43459 * Lazy evaluation allows several methods to support shortcut fusion.
43460 * Shortcut fusion is an optimization to merge iteratee calls; this avoids
43461 * the creation of intermediate arrays and can greatly reduce the number of
43462 * iteratee executions. Sections of a chain sequence qualify for shortcut
43463 * fusion if the section is applied to an array and iteratees accept only
43464 * one argument. The heuristic for whether a section qualifies for shortcut
43465 * fusion is subject to change.
43466 *
43467 * Chaining is supported in custom builds as long as the `_#value` method is
43468 * directly or indirectly included in the build.
43469 *
43470 * In addition to lodash methods, wrappers have `Array` and `String` methods.
43471 *
43472 * The wrapper `Array` methods are:
43473 * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift`
43474 *
43475 * The wrapper `String` methods are:
43476 * `replace` and `split`
43477 *
43478 * The wrapper methods that support shortcut fusion are:
43479 * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`,
43480 * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`,
43481 * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray`
43482 *
43483 * The chainable wrapper methods are:
43484 * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`,
43485 * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`,
43486 * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`,
43487 * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`,
43488 * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`,
43489 * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`,
43490 * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`,
43491 * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`,
43492 * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`,
43493 * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`,
43494 * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`,
43495 * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`,
43496 * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`,
43497 * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`,
43498 * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`,
43499 * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`,
43500 * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`,
43501 * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`,
43502 * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`,
43503 * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`,
43504 * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`,
43505 * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`,
43506 * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`,
43507 * `zipObject`, `zipObjectDeep`, and `zipWith`
43508 *
43509 * The wrapper methods that are **not** chainable by default are:
43510 * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`,
43511 * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`,
43512 * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`,
43513 * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`,
43514 * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`,
43515 * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`,
43516 * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`,
43517 * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`,
43518 * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`,
43519 * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`,
43520 * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`,
43521 * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`,
43522 * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`,
43523 * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`,
43524 * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`,
43525 * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`,
43526 * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`,
43527 * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`,
43528 * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`,
43529 * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`,
43530 * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`,
43531 * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`,
43532 * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`,
43533 * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`,
43534 * `upperFirst`, `value`, and `words`
43535 *
43536 * @name _
43537 * @constructor
43538 * @category Seq
43539 * @param {*} value The value to wrap in a `lodash` instance.
43540 * @returns {Object} Returns the new `lodash` wrapper instance.
43541 * @example
43542 *
43543 * function square(n) {
43544 * return n * n;
43545 * }
43546 *
43547 * var wrapped = _([1, 2, 3]);
43548 *
43549 * // Returns an unwrapped value.
43550 * wrapped.reduce(_.add);
43551 * // => 6
43552 *
43553 * // Returns a wrapped value.
43554 * var squares = wrapped.map(square);
43555 *
43556 * _.isArray(squares);
43557 * // => false
43558 *
43559 * _.isArray(squares.value());
43560 * // => true
43561 */
43562 function lodash(value) {
43563 if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) {
43564 if (value instanceof LodashWrapper) {
43565 return value;
43566 }
43567 if (hasOwnProperty.call(value, '__wrapped__')) {
43568 return wrapperClone(value);
43569 }
43570 }
43571 return new LodashWrapper(value);
43572 }
43573
43574 /**
43575 * The base implementation of `_.create` without support for assigning
43576 * properties to the created object.
43577 *
43578 * @private
43579 * @param {Object} proto The object to inherit from.
43580 * @returns {Object} Returns the new object.
43581 */
43582 var baseCreate = (function() {
43583 function object() {}
43584 return function(proto) {
43585 if (!isObject(proto)) {
43586 return {};
43587 }
43588 if (objectCreate) {
43589 return objectCreate(proto);
43590 }
43591 object.prototype = proto;
43592 var result = new object;
43593 object.prototype = undefined;
43594 return result;
43595 };
43596 }());
43597
43598 /**
43599 * The function whose prototype chain sequence wrappers inherit from.
43600 *
43601 * @private
43602 */
43603 function baseLodash() {
43604 // No operation performed.
43605 }
43606
43607 /**
43608 * The base constructor for creating `lodash` wrapper objects.
43609 *
43610 * @private
43611 * @param {*} value The value to wrap.
43612 * @param {boolean} [chainAll] Enable explicit method chain sequences.
43613 */
43614 function LodashWrapper(value, chainAll) {
43615 this.__wrapped__ = value;
43616 this.__actions__ = [];
43617 this.__chain__ = !!chainAll;
43618 this.__index__ = 0;
43619 this.__values__ = undefined;
43620 }
43621
43622 /**
43623 * By default, the template delimiters used by lodash are like those in
43624 * embedded Ruby (ERB) as well as ES2015 template strings. Change the
43625 * following template settings to use alternative delimiters.
43626 *
43627 * @static
43628 * @memberOf _
43629 * @type {Object}
43630 */
43631 lodash.templateSettings = {
43632
43633 /**
43634 * Used to detect `data` property values to be HTML-escaped.
43635 *
43636 * @memberOf _.templateSettings
43637 * @type {RegExp}
43638 */
43639 'escape': reEscape,
43640
43641 /**
43642 * Used to detect code to be evaluated.
43643 *
43644 * @memberOf _.templateSettings
43645 * @type {RegExp}
43646 */
43647 'evaluate': reEvaluate,
43648
43649 /**
43650 * Used to detect `data` property values to inject.
43651 *
43652 * @memberOf _.templateSettings
43653 * @type {RegExp}
43654 */
43655 'interpolate': reInterpolate,
43656
43657 /**
43658 * Used to reference the data object in the template text.
43659 *
43660 * @memberOf _.templateSettings
43661 * @type {string}
43662 */
43663 'variable': '',
43664
43665 /**
43666 * Used to import variables into the compiled template.
43667 *
43668 * @memberOf _.templateSettings
43669 * @type {Object}
43670 */
43671 'imports': {
43672
43673 /**
43674 * A reference to the `lodash` function.
43675 *
43676 * @memberOf _.templateSettings.imports
43677 * @type {Function}
43678 */
43679 '_': lodash
43680 }
43681 };
43682
43683 // Ensure wrappers are instances of `baseLodash`.
43684 lodash.prototype = baseLodash.prototype;
43685 lodash.prototype.constructor = lodash;
43686
43687 LodashWrapper.prototype = baseCreate(baseLodash.prototype);
43688 LodashWrapper.prototype.constructor = LodashWrapper;
43689
43690 /*------------------------------------------------------------------------*/
43691
43692 /**
43693 * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation.
43694 *
43695 * @private
43696 * @constructor
43697 * @param {*} value The value to wrap.
43698 */
43699 function LazyWrapper(value) {
43700 this.__wrapped__ = value;
43701 this.__actions__ = [];
43702 this.__dir__ = 1;
43703 this.__filtered__ = false;
43704 this.__iteratees__ = [];
43705 this.__takeCount__ = MAX_ARRAY_LENGTH;
43706 this.__views__ = [];
43707 }
43708
43709 /**
43710 * Creates a clone of the lazy wrapper object.
43711 *
43712 * @private
43713 * @name clone
43714 * @memberOf LazyWrapper
43715 * @returns {Object} Returns the cloned `LazyWrapper` object.
43716 */
43717 function lazyClone() {
43718 var result = new LazyWrapper(this.__wrapped__);
43719 result.__actions__ = copyArray(this.__actions__);
43720 result.__dir__ = this.__dir__;
43721 result.__filtered__ = this.__filtered__;
43722 result.__iteratees__ = copyArray(this.__iteratees__);
43723 result.__takeCount__ = this.__takeCount__;
43724 result.__views__ = copyArray(this.__views__);
43725 return result;
43726 }
43727
43728 /**
43729 * Reverses the direction of lazy iteration.
43730 *
43731 * @private
43732 * @name reverse
43733 * @memberOf LazyWrapper
43734 * @returns {Object} Returns the new reversed `LazyWrapper` object.
43735 */
43736 function lazyReverse() {
43737 if (this.__filtered__) {
43738 var result = new LazyWrapper(this);
43739 result.__dir__ = -1;
43740 result.__filtered__ = true;
43741 } else {
43742 result = this.clone();
43743 result.__dir__ *= -1;
43744 }
43745 return result;
43746 }
43747
43748 /**
43749 * Extracts the unwrapped value from its lazy wrapper.
43750 *
43751 * @private
43752 * @name value
43753 * @memberOf LazyWrapper
43754 * @returns {*} Returns the unwrapped value.
43755 */
43756 function lazyValue() {
43757 var array = this.__wrapped__.value(),
43758 dir = this.__dir__,
43759 isArr = isArray(array),
43760 isRight = dir < 0,
43761 arrLength = isArr ? array.length : 0,
43762 view = getView(0, arrLength, this.__views__),
43763 start = view.start,
43764 end = view.end,
43765 length = end - start,
43766 index = isRight ? end : (start - 1),
43767 iteratees = this.__iteratees__,
43768 iterLength = iteratees.length,
43769 resIndex = 0,
43770 takeCount = nativeMin(length, this.__takeCount__);
43771
43772 if (!isArr || (!isRight && arrLength == length && takeCount == length)) {
43773 return baseWrapperValue(array, this.__actions__);
43774 }
43775 var result = [];
43776
43777 outer:
43778 while (length-- && resIndex < takeCount) {
43779 index += dir;
43780
43781 var iterIndex = -1,
43782 value = array[index];
43783
43784 while (++iterIndex < iterLength) {
43785 var data = iteratees[iterIndex],
43786 iteratee = data.iteratee,
43787 type = data.type,
43788 computed = iteratee(value);
43789
43790 if (type == LAZY_MAP_FLAG) {
43791 value = computed;
43792 } else if (!computed) {
43793 if (type == LAZY_FILTER_FLAG) {
43794 continue outer;
43795 } else {
43796 break outer;
43797 }
43798 }
43799 }
43800 result[resIndex++] = value;
43801 }
43802 return result;
43803 }
43804
43805 // Ensure `LazyWrapper` is an instance of `baseLodash`.
43806 LazyWrapper.prototype = baseCreate(baseLodash.prototype);
43807 LazyWrapper.prototype.constructor = LazyWrapper;
43808
43809 /*------------------------------------------------------------------------*/
43810
43811 /**
43812 * Creates a hash object.
43813 *
43814 * @private
43815 * @constructor
43816 * @param {Array} [entries] The key-value pairs to cache.
43817 */
43818 function Hash(entries) {
43819 var index = -1,
43820 length = entries == null ? 0 : entries.length;
43821
43822 this.clear();
43823 while (++index < length) {
43824 var entry = entries[index];
43825 this.set(entry[0], entry[1]);
43826 }
43827 }
43828
43829 /**
43830 * Removes all key-value entries from the hash.
43831 *
43832 * @private
43833 * @name clear
43834 * @memberOf Hash
43835 */
43836 function hashClear() {
43837 this.__data__ = nativeCreate ? nativeCreate(null) : {};
43838 this.size = 0;
43839 }
43840
43841 /**
43842 * Removes `key` and its value from the hash.
43843 *
43844 * @private
43845 * @name delete
43846 * @memberOf Hash
43847 * @param {Object} hash The hash to modify.
43848 * @param {string} key The key of the value to remove.
43849 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
43850 */
43851 function hashDelete(key) {
43852 var result = this.has(key) && delete this.__data__[key];
43853 this.size -= result ? 1 : 0;
43854 return result;
43855 }
43856
43857 /**
43858 * Gets the hash value for `key`.
43859 *
43860 * @private
43861 * @name get
43862 * @memberOf Hash
43863 * @param {string} key The key of the value to get.
43864 * @returns {*} Returns the entry value.
43865 */
43866 function hashGet(key) {
43867 var data = this.__data__;
43868 if (nativeCreate) {
43869 var result = data[key];
43870 return result === HASH_UNDEFINED ? undefined : result;
43871 }
43872 return hasOwnProperty.call(data, key) ? data[key] : undefined;
43873 }
43874
43875 /**
43876 * Checks if a hash value for `key` exists.
43877 *
43878 * @private
43879 * @name has
43880 * @memberOf Hash
43881 * @param {string} key The key of the entry to check.
43882 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
43883 */
43884 function hashHas(key) {
43885 var data = this.__data__;
43886 return nativeCreate ? (data[key] !== undefined) : hasOwnProperty.call(data, key);
43887 }
43888
43889 /**
43890 * Sets the hash `key` to `value`.
43891 *
43892 * @private
43893 * @name set
43894 * @memberOf Hash
43895 * @param {string} key The key of the value to set.
43896 * @param {*} value The value to set.
43897 * @returns {Object} Returns the hash instance.
43898 */
43899 function hashSet(key, value) {
43900 var data = this.__data__;
43901 this.size += this.has(key) ? 0 : 1;
43902 data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED : value;
43903 return this;
43904 }
43905
43906 // Add methods to `Hash`.
43907 Hash.prototype.clear = hashClear;
43908 Hash.prototype['delete'] = hashDelete;
43909 Hash.prototype.get = hashGet;
43910 Hash.prototype.has = hashHas;
43911 Hash.prototype.set = hashSet;
43912
43913 /*------------------------------------------------------------------------*/
43914
43915 /**
43916 * Creates an list cache object.
43917 *
43918 * @private
43919 * @constructor
43920 * @param {Array} [entries] The key-value pairs to cache.
43921 */
43922 function ListCache(entries) {
43923 var index = -1,
43924 length = entries == null ? 0 : entries.length;
43925
43926 this.clear();
43927 while (++index < length) {
43928 var entry = entries[index];
43929 this.set(entry[0], entry[1]);
43930 }
43931 }
43932
43933 /**
43934 * Removes all key-value entries from the list cache.
43935 *
43936 * @private
43937 * @name clear
43938 * @memberOf ListCache
43939 */
43940 function listCacheClear() {
43941 this.__data__ = [];
43942 this.size = 0;
43943 }
43944
43945 /**
43946 * Removes `key` and its value from the list cache.
43947 *
43948 * @private
43949 * @name delete
43950 * @memberOf ListCache
43951 * @param {string} key The key of the value to remove.
43952 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
43953 */
43954 function listCacheDelete(key) {
43955 var data = this.__data__,
43956 index = assocIndexOf(data, key);
43957
43958 if (index < 0) {
43959 return false;
43960 }
43961 var lastIndex = data.length - 1;
43962 if (index == lastIndex) {
43963 data.pop();
43964 } else {
43965 splice.call(data, index, 1);
43966 }
43967 --this.size;
43968 return true;
43969 }
43970
43971 /**
43972 * Gets the list cache value for `key`.
43973 *
43974 * @private
43975 * @name get
43976 * @memberOf ListCache
43977 * @param {string} key The key of the value to get.
43978 * @returns {*} Returns the entry value.
43979 */
43980 function listCacheGet(key) {
43981 var data = this.__data__,
43982 index = assocIndexOf(data, key);
43983
43984 return index < 0 ? undefined : data[index][1];
43985 }
43986
43987 /**
43988 * Checks if a list cache value for `key` exists.
43989 *
43990 * @private
43991 * @name has
43992 * @memberOf ListCache
43993 * @param {string} key The key of the entry to check.
43994 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
43995 */
43996 function listCacheHas(key) {
43997 return assocIndexOf(this.__data__, key) > -1;
43998 }
43999
44000 /**
44001 * Sets the list cache `key` to `value`.
44002 *
44003 * @private
44004 * @name set
44005 * @memberOf ListCache
44006 * @param {string} key The key of the value to set.
44007 * @param {*} value The value to set.
44008 * @returns {Object} Returns the list cache instance.
44009 */
44010 function listCacheSet(key, value) {
44011 var data = this.__data__,
44012 index = assocIndexOf(data, key);
44013
44014 if (index < 0) {
44015 ++this.size;
44016 data.push([key, value]);
44017 } else {
44018 data[index][1] = value;
44019 }
44020 return this;
44021 }
44022
44023 // Add methods to `ListCache`.
44024 ListCache.prototype.clear = listCacheClear;
44025 ListCache.prototype['delete'] = listCacheDelete;
44026 ListCache.prototype.get = listCacheGet;
44027 ListCache.prototype.has = listCacheHas;
44028 ListCache.prototype.set = listCacheSet;
44029
44030 /*------------------------------------------------------------------------*/
44031
44032 /**
44033 * Creates a map cache object to store key-value pairs.
44034 *
44035 * @private
44036 * @constructor
44037 * @param {Array} [entries] The key-value pairs to cache.
44038 */
44039 function MapCache(entries) {
44040 var index = -1,
44041 length = entries == null ? 0 : entries.length;
44042
44043 this.clear();
44044 while (++index < length) {
44045 var entry = entries[index];
44046 this.set(entry[0], entry[1]);
44047 }
44048 }
44049
44050 /**
44051 * Removes all key-value entries from the map.
44052 *
44053 * @private
44054 * @name clear
44055 * @memberOf MapCache
44056 */
44057 function mapCacheClear() {
44058 this.size = 0;
44059 this.__data__ = {
44060 'hash': new Hash,
44061 'map': new (Map || ListCache),
44062 'string': new Hash
44063 };
44064 }
44065
44066 /**
44067 * Removes `key` and its value from the map.
44068 *
44069 * @private
44070 * @name delete
44071 * @memberOf MapCache
44072 * @param {string} key The key of the value to remove.
44073 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
44074 */
44075 function mapCacheDelete(key) {
44076 var result = getMapData(this, key)['delete'](key);
44077 this.size -= result ? 1 : 0;
44078 return result;
44079 }
44080
44081 /**
44082 * Gets the map value for `key`.
44083 *
44084 * @private
44085 * @name get
44086 * @memberOf MapCache
44087 * @param {string} key The key of the value to get.
44088 * @returns {*} Returns the entry value.
44089 */
44090 function mapCacheGet(key) {
44091 return getMapData(this, key).get(key);
44092 }
44093
44094 /**
44095 * Checks if a map value for `key` exists.
44096 *
44097 * @private
44098 * @name has
44099 * @memberOf MapCache
44100 * @param {string} key The key of the entry to check.
44101 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
44102 */
44103 function mapCacheHas(key) {
44104 return getMapData(this, key).has(key);
44105 }
44106
44107 /**
44108 * Sets the map `key` to `value`.
44109 *
44110 * @private
44111 * @name set
44112 * @memberOf MapCache
44113 * @param {string} key The key of the value to set.
44114 * @param {*} value The value to set.
44115 * @returns {Object} Returns the map cache instance.
44116 */
44117 function mapCacheSet(key, value) {
44118 var data = getMapData(this, key),
44119 size = data.size;
44120
44121 data.set(key, value);
44122 this.size += data.size == size ? 0 : 1;
44123 return this;
44124 }
44125
44126 // Add methods to `MapCache`.
44127 MapCache.prototype.clear = mapCacheClear;
44128 MapCache.prototype['delete'] = mapCacheDelete;
44129 MapCache.prototype.get = mapCacheGet;
44130 MapCache.prototype.has = mapCacheHas;
44131 MapCache.prototype.set = mapCacheSet;
44132
44133 /*------------------------------------------------------------------------*/
44134
44135 /**
44136 *
44137 * Creates an array cache object to store unique values.
44138 *
44139 * @private
44140 * @constructor
44141 * @param {Array} [values] The values to cache.
44142 */
44143 function SetCache(values) {
44144 var index = -1,
44145 length = values == null ? 0 : values.length;
44146
44147 this.__data__ = new MapCache;
44148 while (++index < length) {
44149 this.add(values[index]);
44150 }
44151 }
44152
44153 /**
44154 * Adds `value` to the array cache.
44155 *
44156 * @private
44157 * @name add
44158 * @memberOf SetCache
44159 * @alias push
44160 * @param {*} value The value to cache.
44161 * @returns {Object} Returns the cache instance.
44162 */
44163 function setCacheAdd(value) {
44164 this.__data__.set(value, HASH_UNDEFINED);
44165 return this;
44166 }
44167
44168 /**
44169 * Checks if `value` is in the array cache.
44170 *
44171 * @private
44172 * @name has
44173 * @memberOf SetCache
44174 * @param {*} value The value to search for.
44175 * @returns {number} Returns `true` if `value` is found, else `false`.
44176 */
44177 function setCacheHas(value) {
44178 return this.__data__.has(value);
44179 }
44180
44181 // Add methods to `SetCache`.
44182 SetCache.prototype.add = SetCache.prototype.push = setCacheAdd;
44183 SetCache.prototype.has = setCacheHas;
44184
44185 /*------------------------------------------------------------------------*/
44186
44187 /**
44188 * Creates a stack cache object to store key-value pairs.
44189 *
44190 * @private
44191 * @constructor
44192 * @param {Array} [entries] The key-value pairs to cache.
44193 */
44194 function Stack(entries) {
44195 var data = this.__data__ = new ListCache(entries);
44196 this.size = data.size;
44197 }
44198
44199 /**
44200 * Removes all key-value entries from the stack.
44201 *
44202 * @private
44203 * @name clear
44204 * @memberOf Stack
44205 */
44206 function stackClear() {
44207 this.__data__ = new ListCache;
44208 this.size = 0;
44209 }
44210
44211 /**
44212 * Removes `key` and its value from the stack.
44213 *
44214 * @private
44215 * @name delete
44216 * @memberOf Stack
44217 * @param {string} key The key of the value to remove.
44218 * @returns {boolean} Returns `true` if the entry was removed, else `false`.
44219 */
44220 function stackDelete(key) {
44221 var data = this.__data__,
44222 result = data['delete'](key);
44223
44224 this.size = data.size;
44225 return result;
44226 }
44227
44228 /**
44229 * Gets the stack value for `key`.
44230 *
44231 * @private
44232 * @name get
44233 * @memberOf Stack
44234 * @param {string} key The key of the value to get.
44235 * @returns {*} Returns the entry value.
44236 */
44237 function stackGet(key) {
44238 return this.__data__.get(key);
44239 }
44240
44241 /**
44242 * Checks if a stack value for `key` exists.
44243 *
44244 * @private
44245 * @name has
44246 * @memberOf Stack
44247 * @param {string} key The key of the entry to check.
44248 * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`.
44249 */
44250 function stackHas(key) {
44251 return this.__data__.has(key);
44252 }
44253
44254 /**
44255 * Sets the stack `key` to `value`.
44256 *
44257 * @private
44258 * @name set
44259 * @memberOf Stack
44260 * @param {string} key The key of the value to set.
44261 * @param {*} value The value to set.
44262 * @returns {Object} Returns the stack cache instance.
44263 */
44264 function stackSet(key, value) {
44265 var data = this.__data__;
44266 if (data instanceof ListCache) {
44267 var pairs = data.__data__;
44268 if (!Map || (pairs.length < LARGE_ARRAY_SIZE - 1)) {
44269 pairs.push([key, value]);
44270 this.size = ++data.size;
44271 return this;
44272 }
44273 data = this.__data__ = new MapCache(pairs);
44274 }
44275 data.set(key, value);
44276 this.size = data.size;
44277 return this;
44278 }
44279
44280 // Add methods to `Stack`.
44281 Stack.prototype.clear = stackClear;
44282 Stack.prototype['delete'] = stackDelete;
44283 Stack.prototype.get = stackGet;
44284 Stack.prototype.has = stackHas;
44285 Stack.prototype.set = stackSet;
44286
44287 /*------------------------------------------------------------------------*/
44288
44289 /**
44290 * Creates an array of the enumerable property names of the array-like `value`.
44291 *
44292 * @private
44293 * @param {*} value The value to query.
44294 * @param {boolean} inherited Specify returning inherited property names.
44295 * @returns {Array} Returns the array of property names.
44296 */
44297 function arrayLikeKeys(value, inherited) {
44298 var isArr = isArray(value),
44299 isArg = !isArr && isArguments(value),
44300 isBuff = !isArr && !isArg && isBuffer(value),
44301 isType = !isArr && !isArg && !isBuff && isTypedArray(value),
44302 skipIndexes = isArr || isArg || isBuff || isType,
44303 result = skipIndexes ? baseTimes(value.length, String) : [],
44304 length = result.length;
44305
44306 for (var key in value) {
44307 if ((inherited || hasOwnProperty.call(value, key)) &&
44308 !(skipIndexes && (
44309 // Safari 9 has enumerable `arguments.length` in strict mode.
44310 key == 'length' ||
44311 // Node.js 0.10 has enumerable non-index properties on buffers.
44312 (isBuff && (key == 'offset' || key == 'parent')) ||
44313 // PhantomJS 2 has enumerable non-index properties on typed arrays.
44314 (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) ||
44315 // Skip index properties.
44316 isIndex(key, length)
44317 ))) {
44318 result.push(key);
44319 }
44320 }
44321 return result;
44322 }
44323
44324 /**
44325 * A specialized version of `_.sample` for arrays.
44326 *
44327 * @private
44328 * @param {Array} array The array to sample.
44329 * @returns {*} Returns the random element.
44330 */
44331 function arraySample(array) {
44332 var length = array.length;
44333 return length ? array[baseRandom(0, length - 1)] : undefined;
44334 }
44335
44336 /**
44337 * A specialized version of `_.sampleSize` for arrays.
44338 *
44339 * @private
44340 * @param {Array} array The array to sample.
44341 * @param {number} n The number of elements to sample.
44342 * @returns {Array} Returns the random elements.
44343 */
44344 function arraySampleSize(array, n) {
44345 return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length));
44346 }
44347
44348 /**
44349 * A specialized version of `_.shuffle` for arrays.
44350 *
44351 * @private
44352 * @param {Array} array The array to shuffle.
44353 * @returns {Array} Returns the new shuffled array.
44354 */
44355 function arrayShuffle(array) {
44356 return shuffleSelf(copyArray(array));
44357 }
44358
44359 /**
44360 * This function is like `assignValue` except that it doesn't assign
44361 * `undefined` values.
44362 *
44363 * @private
44364 * @param {Object} object The object to modify.
44365 * @param {string} key The key of the property to assign.
44366 * @param {*} value The value to assign.
44367 */
44368 function assignMergeValue(object, key, value) {
44369 if ((value !== undefined && !eq(object[key], value)) ||
44370 (value === undefined && !(key in object))) {
44371 baseAssignValue(object, key, value);
44372 }
44373 }
44374
44375 /**
44376 * Assigns `value` to `key` of `object` if the existing value is not equivalent
44377 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
44378 * for equality comparisons.
44379 *
44380 * @private
44381 * @param {Object} object The object to modify.
44382 * @param {string} key The key of the property to assign.
44383 * @param {*} value The value to assign.
44384 */
44385 function assignValue(object, key, value) {
44386 var objValue = object[key];
44387 if (!(hasOwnProperty.call(object, key) && eq(objValue, value)) ||
44388 (value === undefined && !(key in object))) {
44389 baseAssignValue(object, key, value);
44390 }
44391 }
44392
44393 /**
44394 * Gets the index at which the `key` is found in `array` of key-value pairs.
44395 *
44396 * @private
44397 * @param {Array} array The array to inspect.
44398 * @param {*} key The key to search for.
44399 * @returns {number} Returns the index of the matched value, else `-1`.
44400 */
44401 function assocIndexOf(array, key) {
44402 var length = array.length;
44403 while (length--) {
44404 if (eq(array[length][0], key)) {
44405 return length;
44406 }
44407 }
44408 return -1;
44409 }
44410
44411 /**
44412 * Aggregates elements of `collection` on `accumulator` with keys transformed
44413 * by `iteratee` and values set by `setter`.
44414 *
44415 * @private
44416 * @param {Array|Object} collection The collection to iterate over.
44417 * @param {Function} setter The function to set `accumulator` values.
44418 * @param {Function} iteratee The iteratee to transform keys.
44419 * @param {Object} accumulator The initial aggregated object.
44420 * @returns {Function} Returns `accumulator`.
44421 */
44422 function baseAggregator(collection, setter, iteratee, accumulator) {
44423 baseEach(collection, function(value, key, collection) {
44424 setter(accumulator, value, iteratee(value), collection);
44425 });
44426 return accumulator;
44427 }
44428
44429 /**
44430 * The base implementation of `_.assign` without support for multiple sources
44431 * or `customizer` functions.
44432 *
44433 * @private
44434 * @param {Object} object The destination object.
44435 * @param {Object} source The source object.
44436 * @returns {Object} Returns `object`.
44437 */
44438 function baseAssign(object, source) {
44439 return object && copyObject(source, keys(source), object);
44440 }
44441
44442 /**
44443 * The base implementation of `_.assignIn` without support for multiple sources
44444 * or `customizer` functions.
44445 *
44446 * @private
44447 * @param {Object} object The destination object.
44448 * @param {Object} source The source object.
44449 * @returns {Object} Returns `object`.
44450 */
44451 function baseAssignIn(object, source) {
44452 return object && copyObject(source, keysIn(source), object);
44453 }
44454
44455 /**
44456 * The base implementation of `assignValue` and `assignMergeValue` without
44457 * value checks.
44458 *
44459 * @private
44460 * @param {Object} object The object to modify.
44461 * @param {string} key The key of the property to assign.
44462 * @param {*} value The value to assign.
44463 */
44464 function baseAssignValue(object, key, value) {
44465 if (key == '__proto__' && defineProperty) {
44466 defineProperty(object, key, {
44467 'configurable': true,
44468 'enumerable': true,
44469 'value': value,
44470 'writable': true
44471 });
44472 } else {
44473 object[key] = value;
44474 }
44475 }
44476
44477 /**
44478 * The base implementation of `_.at` without support for individual paths.
44479 *
44480 * @private
44481 * @param {Object} object The object to iterate over.
44482 * @param {string[]} paths The property paths to pick.
44483 * @returns {Array} Returns the picked elements.
44484 */
44485 function baseAt(object, paths) {
44486 var index = -1,
44487 length = paths.length,
44488 result = Array(length),
44489 skip = object == null;
44490
44491 while (++index < length) {
44492 result[index] = skip ? undefined : get(object, paths[index]);
44493 }
44494 return result;
44495 }
44496
44497 /**
44498 * The base implementation of `_.clamp` which doesn't coerce arguments.
44499 *
44500 * @private
44501 * @param {number} number The number to clamp.
44502 * @param {number} [lower] The lower bound.
44503 * @param {number} upper The upper bound.
44504 * @returns {number} Returns the clamped number.
44505 */
44506 function baseClamp(number, lower, upper) {
44507 if (number === number) {
44508 if (upper !== undefined) {
44509 number = number <= upper ? number : upper;
44510 }
44511 if (lower !== undefined) {
44512 number = number >= lower ? number : lower;
44513 }
44514 }
44515 return number;
44516 }
44517
44518 /**
44519 * The base implementation of `_.clone` and `_.cloneDeep` which tracks
44520 * traversed objects.
44521 *
44522 * @private
44523 * @param {*} value The value to clone.
44524 * @param {boolean} bitmask The bitmask flags.
44525 * 1 - Deep clone
44526 * 2 - Flatten inherited properties
44527 * 4 - Clone symbols
44528 * @param {Function} [customizer] The function to customize cloning.
44529 * @param {string} [key] The key of `value`.
44530 * @param {Object} [object] The parent object of `value`.
44531 * @param {Object} [stack] Tracks traversed objects and their clone counterparts.
44532 * @returns {*} Returns the cloned value.
44533 */
44534 function baseClone(value, bitmask, customizer, key, object, stack) {
44535 var result,
44536 isDeep = bitmask & CLONE_DEEP_FLAG,
44537 isFlat = bitmask & CLONE_FLAT_FLAG,
44538 isFull = bitmask & CLONE_SYMBOLS_FLAG;
44539
44540 if (customizer) {
44541 result = object ? customizer(value, key, object, stack) : customizer(value);
44542 }
44543 if (result !== undefined) {
44544 return result;
44545 }
44546 if (!isObject(value)) {
44547 return value;
44548 }
44549 var isArr = isArray(value);
44550 if (isArr) {
44551 result = initCloneArray(value);
44552 if (!isDeep) {
44553 return copyArray(value, result);
44554 }
44555 } else {
44556 var tag = getTag(value),
44557 isFunc = tag == funcTag || tag == genTag;
44558
44559 if (isBuffer(value)) {
44560 return cloneBuffer(value, isDeep);
44561 }
44562 if (tag == objectTag || tag == argsTag || (isFunc && !object)) {
44563 result = (isFlat || isFunc) ? {} : initCloneObject(value);
44564 if (!isDeep) {
44565 return isFlat
44566 ? copySymbolsIn(value, baseAssignIn(result, value))
44567 : copySymbols(value, baseAssign(result, value));
44568 }
44569 } else {
44570 if (!cloneableTags[tag]) {
44571 return object ? value : {};
44572 }
44573 result = initCloneByTag(value, tag, isDeep);
44574 }
44575 }
44576 // Check for circular references and return its corresponding clone.
44577 stack || (stack = new Stack);
44578 var stacked = stack.get(value);
44579 if (stacked) {
44580 return stacked;
44581 }
44582 stack.set(value, result);
44583
44584 if (isSet(value)) {
44585 value.forEach(function(subValue) {
44586 result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack));
44587 });
44588 } else if (isMap(value)) {
44589 value.forEach(function(subValue, key) {
44590 result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack));
44591 });
44592 }
44593
44594 var keysFunc = isFull
44595 ? (isFlat ? getAllKeysIn : getAllKeys)
44596 : (isFlat ? keysIn : keys);
44597
44598 var props = isArr ? undefined : keysFunc(value);
44599 arrayEach(props || value, function(subValue, key) {
44600 if (props) {
44601 key = subValue;
44602 subValue = value[key];
44603 }
44604 // Recursively populate clone (susceptible to call stack limits).
44605 assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack));
44606 });
44607 return result;
44608 }
44609
44610 /**
44611 * The base implementation of `_.conforms` which doesn't clone `source`.
44612 *
44613 * @private
44614 * @param {Object} source The object of property predicates to conform to.
44615 * @returns {Function} Returns the new spec function.
44616 */
44617 function baseConforms(source) {
44618 var props = keys(source);
44619 return function(object) {
44620 return baseConformsTo(object, source, props);
44621 };
44622 }
44623
44624 /**
44625 * The base implementation of `_.conformsTo` which accepts `props` to check.
44626 *
44627 * @private
44628 * @param {Object} object The object to inspect.
44629 * @param {Object} source The object of property predicates to conform to.
44630 * @returns {boolean} Returns `true` if `object` conforms, else `false`.
44631 */
44632 function baseConformsTo(object, source, props) {
44633 var length = props.length;
44634 if (object == null) {
44635 return !length;
44636 }
44637 object = Object(object);
44638 while (length--) {
44639 var key = props[length],
44640 predicate = source[key],
44641 value = object[key];
44642
44643 if ((value === undefined && !(key in object)) || !predicate(value)) {
44644 return false;
44645 }
44646 }
44647 return true;
44648 }
44649
44650 /**
44651 * The base implementation of `_.delay` and `_.defer` which accepts `args`
44652 * to provide to `func`.
44653 *
44654 * @private
44655 * @param {Function} func The function to delay.
44656 * @param {number} wait The number of milliseconds to delay invocation.
44657 * @param {Array} args The arguments to provide to `func`.
44658 * @returns {number|Object} Returns the timer id or timeout object.
44659 */
44660 function baseDelay(func, wait, args) {
44661 if (typeof func != 'function') {
44662 throw new TypeError(FUNC_ERROR_TEXT);
44663 }
44664 return setTimeout(function() { func.apply(undefined, args); }, wait);
44665 }
44666
44667 /**
44668 * The base implementation of methods like `_.difference` without support
44669 * for excluding multiple arrays or iteratee shorthands.
44670 *
44671 * @private
44672 * @param {Array} array The array to inspect.
44673 * @param {Array} values The values to exclude.
44674 * @param {Function} [iteratee] The iteratee invoked per element.
44675 * @param {Function} [comparator] The comparator invoked per element.
44676 * @returns {Array} Returns the new array of filtered values.
44677 */
44678 function baseDifference(array, values, iteratee, comparator) {
44679 var index = -1,
44680 includes = arrayIncludes,
44681 isCommon = true,
44682 length = array.length,
44683 result = [],
44684 valuesLength = values.length;
44685
44686 if (!length) {
44687 return result;
44688 }
44689 if (iteratee) {
44690 values = arrayMap(values, baseUnary(iteratee));
44691 }
44692 if (comparator) {
44693 includes = arrayIncludesWith;
44694 isCommon = false;
44695 }
44696 else if (values.length >= LARGE_ARRAY_SIZE) {
44697 includes = cacheHas;
44698 isCommon = false;
44699 values = new SetCache(values);
44700 }
44701 outer:
44702 while (++index < length) {
44703 var value = array[index],
44704 computed = iteratee == null ? value : iteratee(value);
44705
44706 value = (comparator || value !== 0) ? value : 0;
44707 if (isCommon && computed === computed) {
44708 var valuesIndex = valuesLength;
44709 while (valuesIndex--) {
44710 if (values[valuesIndex] === computed) {
44711 continue outer;
44712 }
44713 }
44714 result.push(value);
44715 }
44716 else if (!includes(values, computed, comparator)) {
44717 result.push(value);
44718 }
44719 }
44720 return result;
44721 }
44722
44723 /**
44724 * The base implementation of `_.forEach` without support for iteratee shorthands.
44725 *
44726 * @private
44727 * @param {Array|Object} collection The collection to iterate over.
44728 * @param {Function} iteratee The function invoked per iteration.
44729 * @returns {Array|Object} Returns `collection`.
44730 */
44731 var baseEach = createBaseEach(baseForOwn);
44732
44733 /**
44734 * The base implementation of `_.forEachRight` without support for iteratee shorthands.
44735 *
44736 * @private
44737 * @param {Array|Object} collection The collection to iterate over.
44738 * @param {Function} iteratee The function invoked per iteration.
44739 * @returns {Array|Object} Returns `collection`.
44740 */
44741 var baseEachRight = createBaseEach(baseForOwnRight, true);
44742
44743 /**
44744 * The base implementation of `_.every` without support for iteratee shorthands.
44745 *
44746 * @private
44747 * @param {Array|Object} collection The collection to iterate over.
44748 * @param {Function} predicate The function invoked per iteration.
44749 * @returns {boolean} Returns `true` if all elements pass the predicate check,
44750 * else `false`
44751 */
44752 function baseEvery(collection, predicate) {
44753 var result = true;
44754 baseEach(collection, function(value, index, collection) {
44755 result = !!predicate(value, index, collection);
44756 return result;
44757 });
44758 return result;
44759 }
44760
44761 /**
44762 * The base implementation of methods like `_.max` and `_.min` which accepts a
44763 * `comparator` to determine the extremum value.
44764 *
44765 * @private
44766 * @param {Array} array The array to iterate over.
44767 * @param {Function} iteratee The iteratee invoked per iteration.
44768 * @param {Function} comparator The comparator used to compare values.
44769 * @returns {*} Returns the extremum value.
44770 */
44771 function baseExtremum(array, iteratee, comparator) {
44772 var index = -1,
44773 length = array.length;
44774
44775 while (++index < length) {
44776 var value = array[index],
44777 current = iteratee(value);
44778
44779 if (current != null && (computed === undefined
44780 ? (current === current && !isSymbol(current))
44781 : comparator(current, computed)
44782 )) {
44783 var computed = current,
44784 result = value;
44785 }
44786 }
44787 return result;
44788 }
44789
44790 /**
44791 * The base implementation of `_.fill` without an iteratee call guard.
44792 *
44793 * @private
44794 * @param {Array} array The array to fill.
44795 * @param {*} value The value to fill `array` with.
44796 * @param {number} [start=0] The start position.
44797 * @param {number} [end=array.length] The end position.
44798 * @returns {Array} Returns `array`.
44799 */
44800 function baseFill(array, value, start, end) {
44801 var length = array.length;
44802
44803 start = toInteger(start);
44804 if (start < 0) {
44805 start = -start > length ? 0 : (length + start);
44806 }
44807 end = (end === undefined || end > length) ? length : toInteger(end);
44808 if (end < 0) {
44809 end += length;
44810 }
44811 end = start > end ? 0 : toLength(end);
44812 while (start < end) {
44813 array[start++] = value;
44814 }
44815 return array;
44816 }
44817
44818 /**
44819 * The base implementation of `_.filter` without support for iteratee shorthands.
44820 *
44821 * @private
44822 * @param {Array|Object} collection The collection to iterate over.
44823 * @param {Function} predicate The function invoked per iteration.
44824 * @returns {Array} Returns the new filtered array.
44825 */
44826 function baseFilter(collection, predicate) {
44827 var result = [];
44828 baseEach(collection, function(value, index, collection) {
44829 if (predicate(value, index, collection)) {
44830 result.push(value);
44831 }
44832 });
44833 return result;
44834 }
44835
44836 /**
44837 * The base implementation of `_.flatten` with support for restricting flattening.
44838 *
44839 * @private
44840 * @param {Array} array The array to flatten.
44841 * @param {number} depth The maximum recursion depth.
44842 * @param {boolean} [predicate=isFlattenable] The function invoked per iteration.
44843 * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks.
44844 * @param {Array} [result=[]] The initial result value.
44845 * @returns {Array} Returns the new flattened array.
44846 */
44847 function baseFlatten(array, depth, predicate, isStrict, result) {
44848 var index = -1,
44849 length = array.length;
44850
44851 predicate || (predicate = isFlattenable);
44852 result || (result = []);
44853
44854 while (++index < length) {
44855 var value = array[index];
44856 if (depth > 0 && predicate(value)) {
44857 if (depth > 1) {
44858 // Recursively flatten arrays (susceptible to call stack limits).
44859 baseFlatten(value, depth - 1, predicate, isStrict, result);
44860 } else {
44861 arrayPush(result, value);
44862 }
44863 } else if (!isStrict) {
44864 result[result.length] = value;
44865 }
44866 }
44867 return result;
44868 }
44869
44870 /**
44871 * The base implementation of `baseForOwn` which iterates over `object`
44872 * properties returned by `keysFunc` and invokes `iteratee` for each property.
44873 * Iteratee functions may exit iteration early by explicitly returning `false`.
44874 *
44875 * @private
44876 * @param {Object} object The object to iterate over.
44877 * @param {Function} iteratee The function invoked per iteration.
44878 * @param {Function} keysFunc The function to get the keys of `object`.
44879 * @returns {Object} Returns `object`.
44880 */
44881 var baseFor = createBaseFor();
44882
44883 /**
44884 * This function is like `baseFor` except that it iterates over properties
44885 * in the opposite order.
44886 *
44887 * @private
44888 * @param {Object} object The object to iterate over.
44889 * @param {Function} iteratee The function invoked per iteration.
44890 * @param {Function} keysFunc The function to get the keys of `object`.
44891 * @returns {Object} Returns `object`.
44892 */
44893 var baseForRight = createBaseFor(true);
44894
44895 /**
44896 * The base implementation of `_.forOwn` without support for iteratee shorthands.
44897 *
44898 * @private
44899 * @param {Object} object The object to iterate over.
44900 * @param {Function} iteratee The function invoked per iteration.
44901 * @returns {Object} Returns `object`.
44902 */
44903 function baseForOwn(object, iteratee) {
44904 return object && baseFor(object, iteratee, keys);
44905 }
44906
44907 /**
44908 * The base implementation of `_.forOwnRight` without support for iteratee shorthands.
44909 *
44910 * @private
44911 * @param {Object} object The object to iterate over.
44912 * @param {Function} iteratee The function invoked per iteration.
44913 * @returns {Object} Returns `object`.
44914 */
44915 function baseForOwnRight(object, iteratee) {
44916 return object && baseForRight(object, iteratee, keys);
44917 }
44918
44919 /**
44920 * The base implementation of `_.functions` which creates an array of
44921 * `object` function property names filtered from `props`.
44922 *
44923 * @private
44924 * @param {Object} object The object to inspect.
44925 * @param {Array} props The property names to filter.
44926 * @returns {Array} Returns the function names.
44927 */
44928 function baseFunctions(object, props) {
44929 return arrayFilter(props, function(key) {
44930 return isFunction(object[key]);
44931 });
44932 }
44933
44934 /**
44935 * The base implementation of `_.get` without support for default values.
44936 *
44937 * @private
44938 * @param {Object} object The object to query.
44939 * @param {Array|string} path The path of the property to get.
44940 * @returns {*} Returns the resolved value.
44941 */
44942 function baseGet(object, path) {
44943 path = castPath(path, object);
44944
44945 var index = 0,
44946 length = path.length;
44947
44948 while (object != null && index < length) {
44949 object = object[toKey(path[index++])];
44950 }
44951 return (index && index == length) ? object : undefined;
44952 }
44953
44954 /**
44955 * The base implementation of `getAllKeys` and `getAllKeysIn` which uses
44956 * `keysFunc` and `symbolsFunc` to get the enumerable property names and
44957 * symbols of `object`.
44958 *
44959 * @private
44960 * @param {Object} object The object to query.
44961 * @param {Function} keysFunc The function to get the keys of `object`.
44962 * @param {Function} symbolsFunc The function to get the symbols of `object`.
44963 * @returns {Array} Returns the array of property names and symbols.
44964 */
44965 function baseGetAllKeys(object, keysFunc, symbolsFunc) {
44966 var result = keysFunc(object);
44967 return isArray(object) ? result : arrayPush(result, symbolsFunc(object));
44968 }
44969
44970 /**
44971 * The base implementation of `getTag` without fallbacks for buggy environments.
44972 *
44973 * @private
44974 * @param {*} value The value to query.
44975 * @returns {string} Returns the `toStringTag`.
44976 */
44977 function baseGetTag(value) {
44978 if (value == null) {
44979 return value === undefined ? undefinedTag : nullTag;
44980 }
44981 return (symToStringTag && symToStringTag in Object(value))
44982 ? getRawTag(value)
44983 : objectToString(value);
44984 }
44985
44986 /**
44987 * The base implementation of `_.gt` which doesn't coerce arguments.
44988 *
44989 * @private
44990 * @param {*} value The value to compare.
44991 * @param {*} other The other value to compare.
44992 * @returns {boolean} Returns `true` if `value` is greater than `other`,
44993 * else `false`.
44994 */
44995 function baseGt(value, other) {
44996 return value > other;
44997 }
44998
44999 /**
45000 * The base implementation of `_.has` without support for deep paths.
45001 *
45002 * @private
45003 * @param {Object} [object] The object to query.
45004 * @param {Array|string} key The key to check.
45005 * @returns {boolean} Returns `true` if `key` exists, else `false`.
45006 */
45007 function baseHas(object, key) {
45008 return object != null && hasOwnProperty.call(object, key);
45009 }
45010
45011 /**
45012 * The base implementation of `_.hasIn` without support for deep paths.
45013 *
45014 * @private
45015 * @param {Object} [object] The object to query.
45016 * @param {Array|string} key The key to check.
45017 * @returns {boolean} Returns `true` if `key` exists, else `false`.
45018 */
45019 function baseHasIn(object, key) {
45020 return object != null && key in Object(object);
45021 }
45022
45023 /**
45024 * The base implementation of `_.inRange` which doesn't coerce arguments.
45025 *
45026 * @private
45027 * @param {number} number The number to check.
45028 * @param {number} start The start of the range.
45029 * @param {number} end The end of the range.
45030 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
45031 */
45032 function baseInRange(number, start, end) {
45033 return number >= nativeMin(start, end) && number < nativeMax(start, end);
45034 }
45035
45036 /**
45037 * The base implementation of methods like `_.intersection`, without support
45038 * for iteratee shorthands, that accepts an array of arrays to inspect.
45039 *
45040 * @private
45041 * @param {Array} arrays The arrays to inspect.
45042 * @param {Function} [iteratee] The iteratee invoked per element.
45043 * @param {Function} [comparator] The comparator invoked per element.
45044 * @returns {Array} Returns the new array of shared values.
45045 */
45046 function baseIntersection(arrays, iteratee, comparator) {
45047 var includes = comparator ? arrayIncludesWith : arrayIncludes,
45048 length = arrays[0].length,
45049 othLength = arrays.length,
45050 othIndex = othLength,
45051 caches = Array(othLength),
45052 maxLength = Infinity,
45053 result = [];
45054
45055 while (othIndex--) {
45056 var array = arrays[othIndex];
45057 if (othIndex && iteratee) {
45058 array = arrayMap(array, baseUnary(iteratee));
45059 }
45060 maxLength = nativeMin(array.length, maxLength);
45061 caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120))
45062 ? new SetCache(othIndex && array)
45063 : undefined;
45064 }
45065 array = arrays[0];
45066
45067 var index = -1,
45068 seen = caches[0];
45069
45070 outer:
45071 while (++index < length && result.length < maxLength) {
45072 var value = array[index],
45073 computed = iteratee ? iteratee(value) : value;
45074
45075 value = (comparator || value !== 0) ? value : 0;
45076 if (!(seen
45077 ? cacheHas(seen, computed)
45078 : includes(result, computed, comparator)
45079 )) {
45080 othIndex = othLength;
45081 while (--othIndex) {
45082 var cache = caches[othIndex];
45083 if (!(cache
45084 ? cacheHas(cache, computed)
45085 : includes(arrays[othIndex], computed, comparator))
45086 ) {
45087 continue outer;
45088 }
45089 }
45090 if (seen) {
45091 seen.push(computed);
45092 }
45093 result.push(value);
45094 }
45095 }
45096 return result;
45097 }
45098
45099 /**
45100 * The base implementation of `_.invert` and `_.invertBy` which inverts
45101 * `object` with values transformed by `iteratee` and set by `setter`.
45102 *
45103 * @private
45104 * @param {Object} object The object to iterate over.
45105 * @param {Function} setter The function to set `accumulator` values.
45106 * @param {Function} iteratee The iteratee to transform values.
45107 * @param {Object} accumulator The initial inverted object.
45108 * @returns {Function} Returns `accumulator`.
45109 */
45110 function baseInverter(object, setter, iteratee, accumulator) {
45111 baseForOwn(object, function(value, key, object) {
45112 setter(accumulator, iteratee(value), key, object);
45113 });
45114 return accumulator;
45115 }
45116
45117 /**
45118 * The base implementation of `_.invoke` without support for individual
45119 * method arguments.
45120 *
45121 * @private
45122 * @param {Object} object The object to query.
45123 * @param {Array|string} path The path of the method to invoke.
45124 * @param {Array} args The arguments to invoke the method with.
45125 * @returns {*} Returns the result of the invoked method.
45126 */
45127 function baseInvoke(object, path, args) {
45128 path = castPath(path, object);
45129 object = parent(object, path);
45130 var func = object == null ? object : object[toKey(last(path))];
45131 return func == null ? undefined : apply(func, object, args);
45132 }
45133
45134 /**
45135 * The base implementation of `_.isArguments`.
45136 *
45137 * @private
45138 * @param {*} value The value to check.
45139 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
45140 */
45141 function baseIsArguments(value) {
45142 return isObjectLike(value) && baseGetTag(value) == argsTag;
45143 }
45144
45145 /**
45146 * The base implementation of `_.isArrayBuffer` without Node.js optimizations.
45147 *
45148 * @private
45149 * @param {*} value The value to check.
45150 * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
45151 */
45152 function baseIsArrayBuffer(value) {
45153 return isObjectLike(value) && baseGetTag(value) == arrayBufferTag;
45154 }
45155
45156 /**
45157 * The base implementation of `_.isDate` without Node.js optimizations.
45158 *
45159 * @private
45160 * @param {*} value The value to check.
45161 * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
45162 */
45163 function baseIsDate(value) {
45164 return isObjectLike(value) && baseGetTag(value) == dateTag;
45165 }
45166
45167 /**
45168 * The base implementation of `_.isEqual` which supports partial comparisons
45169 * and tracks traversed objects.
45170 *
45171 * @private
45172 * @param {*} value The value to compare.
45173 * @param {*} other The other value to compare.
45174 * @param {boolean} bitmask The bitmask flags.
45175 * 1 - Unordered comparison
45176 * 2 - Partial comparison
45177 * @param {Function} [customizer] The function to customize comparisons.
45178 * @param {Object} [stack] Tracks traversed `value` and `other` objects.
45179 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
45180 */
45181 function baseIsEqual(value, other, bitmask, customizer, stack) {
45182 if (value === other) {
45183 return true;
45184 }
45185 if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) {
45186 return value !== value && other !== other;
45187 }
45188 return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack);
45189 }
45190
45191 /**
45192 * A specialized version of `baseIsEqual` for arrays and objects which performs
45193 * deep comparisons and tracks traversed objects enabling objects with circular
45194 * references to be compared.
45195 *
45196 * @private
45197 * @param {Object} object The object to compare.
45198 * @param {Object} other The other object to compare.
45199 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
45200 * @param {Function} customizer The function to customize comparisons.
45201 * @param {Function} equalFunc The function to determine equivalents of values.
45202 * @param {Object} [stack] Tracks traversed `object` and `other` objects.
45203 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
45204 */
45205 function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) {
45206 var objIsArr = isArray(object),
45207 othIsArr = isArray(other),
45208 objTag = objIsArr ? arrayTag : getTag(object),
45209 othTag = othIsArr ? arrayTag : getTag(other);
45210
45211 objTag = objTag == argsTag ? objectTag : objTag;
45212 othTag = othTag == argsTag ? objectTag : othTag;
45213
45214 var objIsObj = objTag == objectTag,
45215 othIsObj = othTag == objectTag,
45216 isSameTag = objTag == othTag;
45217
45218 if (isSameTag && isBuffer(object)) {
45219 if (!isBuffer(other)) {
45220 return false;
45221 }
45222 objIsArr = true;
45223 objIsObj = false;
45224 }
45225 if (isSameTag && !objIsObj) {
45226 stack || (stack = new Stack);
45227 return (objIsArr || isTypedArray(object))
45228 ? equalArrays(object, other, bitmask, customizer, equalFunc, stack)
45229 : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack);
45230 }
45231 if (!(bitmask & COMPARE_PARTIAL_FLAG)) {
45232 var objIsWrapped = objIsObj && hasOwnProperty.call(object, '__wrapped__'),
45233 othIsWrapped = othIsObj && hasOwnProperty.call(other, '__wrapped__');
45234
45235 if (objIsWrapped || othIsWrapped) {
45236 var objUnwrapped = objIsWrapped ? object.value() : object,
45237 othUnwrapped = othIsWrapped ? other.value() : other;
45238
45239 stack || (stack = new Stack);
45240 return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack);
45241 }
45242 }
45243 if (!isSameTag) {
45244 return false;
45245 }
45246 stack || (stack = new Stack);
45247 return equalObjects(object, other, bitmask, customizer, equalFunc, stack);
45248 }
45249
45250 /**
45251 * The base implementation of `_.isMap` without Node.js optimizations.
45252 *
45253 * @private
45254 * @param {*} value The value to check.
45255 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
45256 */
45257 function baseIsMap(value) {
45258 return isObjectLike(value) && getTag(value) == mapTag;
45259 }
45260
45261 /**
45262 * The base implementation of `_.isMatch` without support for iteratee shorthands.
45263 *
45264 * @private
45265 * @param {Object} object The object to inspect.
45266 * @param {Object} source The object of property values to match.
45267 * @param {Array} matchData The property names, values, and compare flags to match.
45268 * @param {Function} [customizer] The function to customize comparisons.
45269 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
45270 */
45271 function baseIsMatch(object, source, matchData, customizer) {
45272 var index = matchData.length,
45273 length = index,
45274 noCustomizer = !customizer;
45275
45276 if (object == null) {
45277 return !length;
45278 }
45279 object = Object(object);
45280 while (index--) {
45281 var data = matchData[index];
45282 if ((noCustomizer && data[2])
45283 ? data[1] !== object[data[0]]
45284 : !(data[0] in object)
45285 ) {
45286 return false;
45287 }
45288 }
45289 while (++index < length) {
45290 data = matchData[index];
45291 var key = data[0],
45292 objValue = object[key],
45293 srcValue = data[1];
45294
45295 if (noCustomizer && data[2]) {
45296 if (objValue === undefined && !(key in object)) {
45297 return false;
45298 }
45299 } else {
45300 var stack = new Stack;
45301 if (customizer) {
45302 var result = customizer(objValue, srcValue, key, object, source, stack);
45303 }
45304 if (!(result === undefined
45305 ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG, customizer, stack)
45306 : result
45307 )) {
45308 return false;
45309 }
45310 }
45311 }
45312 return true;
45313 }
45314
45315 /**
45316 * The base implementation of `_.isNative` without bad shim checks.
45317 *
45318 * @private
45319 * @param {*} value The value to check.
45320 * @returns {boolean} Returns `true` if `value` is a native function,
45321 * else `false`.
45322 */
45323 function baseIsNative(value) {
45324 if (!isObject(value) || isMasked(value)) {
45325 return false;
45326 }
45327 var pattern = isFunction(value) ? reIsNative : reIsHostCtor;
45328 return pattern.test(toSource(value));
45329 }
45330
45331 /**
45332 * The base implementation of `_.isRegExp` without Node.js optimizations.
45333 *
45334 * @private
45335 * @param {*} value The value to check.
45336 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
45337 */
45338 function baseIsRegExp(value) {
45339 return isObjectLike(value) && baseGetTag(value) == regexpTag;
45340 }
45341
45342 /**
45343 * The base implementation of `_.isSet` without Node.js optimizations.
45344 *
45345 * @private
45346 * @param {*} value The value to check.
45347 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
45348 */
45349 function baseIsSet(value) {
45350 return isObjectLike(value) && getTag(value) == setTag;
45351 }
45352
45353 /**
45354 * The base implementation of `_.isTypedArray` without Node.js optimizations.
45355 *
45356 * @private
45357 * @param {*} value The value to check.
45358 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
45359 */
45360 function baseIsTypedArray(value) {
45361 return isObjectLike(value) &&
45362 isLength(value.length) && !!typedArrayTags[baseGetTag(value)];
45363 }
45364
45365 /**
45366 * The base implementation of `_.iteratee`.
45367 *
45368 * @private
45369 * @param {*} [value=_.identity] The value to convert to an iteratee.
45370 * @returns {Function} Returns the iteratee.
45371 */
45372 function baseIteratee(value) {
45373 // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9.
45374 // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details.
45375 if (typeof value == 'function') {
45376 return value;
45377 }
45378 if (value == null) {
45379 return identity;
45380 }
45381 if (typeof value == 'object') {
45382 return isArray(value)
45383 ? baseMatchesProperty(value[0], value[1])
45384 : baseMatches(value);
45385 }
45386 return property(value);
45387 }
45388
45389 /**
45390 * The base implementation of `_.keys` which doesn't treat sparse arrays as dense.
45391 *
45392 * @private
45393 * @param {Object} object The object to query.
45394 * @returns {Array} Returns the array of property names.
45395 */
45396 function baseKeys(object) {
45397 if (!isPrototype(object)) {
45398 return nativeKeys(object);
45399 }
45400 var result = [];
45401 for (var key in Object(object)) {
45402 if (hasOwnProperty.call(object, key) && key != 'constructor') {
45403 result.push(key);
45404 }
45405 }
45406 return result;
45407 }
45408
45409 /**
45410 * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense.
45411 *
45412 * @private
45413 * @param {Object} object The object to query.
45414 * @returns {Array} Returns the array of property names.
45415 */
45416 function baseKeysIn(object) {
45417 if (!isObject(object)) {
45418 return nativeKeysIn(object);
45419 }
45420 var isProto = isPrototype(object),
45421 result = [];
45422
45423 for (var key in object) {
45424 if (!(key == 'constructor' && (isProto || !hasOwnProperty.call(object, key)))) {
45425 result.push(key);
45426 }
45427 }
45428 return result;
45429 }
45430
45431 /**
45432 * The base implementation of `_.lt` which doesn't coerce arguments.
45433 *
45434 * @private
45435 * @param {*} value The value to compare.
45436 * @param {*} other The other value to compare.
45437 * @returns {boolean} Returns `true` if `value` is less than `other`,
45438 * else `false`.
45439 */
45440 function baseLt(value, other) {
45441 return value < other;
45442 }
45443
45444 /**
45445 * The base implementation of `_.map` without support for iteratee shorthands.
45446 *
45447 * @private
45448 * @param {Array|Object} collection The collection to iterate over.
45449 * @param {Function} iteratee The function invoked per iteration.
45450 * @returns {Array} Returns the new mapped array.
45451 */
45452 function baseMap(collection, iteratee) {
45453 var index = -1,
45454 result = isArrayLike(collection) ? Array(collection.length) : [];
45455
45456 baseEach(collection, function(value, key, collection) {
45457 result[++index] = iteratee(value, key, collection);
45458 });
45459 return result;
45460 }
45461
45462 /**
45463 * The base implementation of `_.matches` which doesn't clone `source`.
45464 *
45465 * @private
45466 * @param {Object} source The object of property values to match.
45467 * @returns {Function} Returns the new spec function.
45468 */
45469 function baseMatches(source) {
45470 var matchData = getMatchData(source);
45471 if (matchData.length == 1 && matchData[0][2]) {
45472 return matchesStrictComparable(matchData[0][0], matchData[0][1]);
45473 }
45474 return function(object) {
45475 return object === source || baseIsMatch(object, source, matchData);
45476 };
45477 }
45478
45479 /**
45480 * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`.
45481 *
45482 * @private
45483 * @param {string} path The path of the property to get.
45484 * @param {*} srcValue The value to match.
45485 * @returns {Function} Returns the new spec function.
45486 */
45487 function baseMatchesProperty(path, srcValue) {
45488 if (isKey(path) && isStrictComparable(srcValue)) {
45489 return matchesStrictComparable(toKey(path), srcValue);
45490 }
45491 return function(object) {
45492 var objValue = get(object, path);
45493 return (objValue === undefined && objValue === srcValue)
45494 ? hasIn(object, path)
45495 : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG);
45496 };
45497 }
45498
45499 /**
45500 * The base implementation of `_.merge` without support for multiple sources.
45501 *
45502 * @private
45503 * @param {Object} object The destination object.
45504 * @param {Object} source The source object.
45505 * @param {number} srcIndex The index of `source`.
45506 * @param {Function} [customizer] The function to customize merged values.
45507 * @param {Object} [stack] Tracks traversed source values and their merged
45508 * counterparts.
45509 */
45510 function baseMerge(object, source, srcIndex, customizer, stack) {
45511 if (object === source) {
45512 return;
45513 }
45514 baseFor(source, function(srcValue, key) {
45515 stack || (stack = new Stack);
45516 if (isObject(srcValue)) {
45517 baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack);
45518 }
45519 else {
45520 var newValue = customizer
45521 ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack)
45522 : undefined;
45523
45524 if (newValue === undefined) {
45525 newValue = srcValue;
45526 }
45527 assignMergeValue(object, key, newValue);
45528 }
45529 }, keysIn);
45530 }
45531
45532 /**
45533 * A specialized version of `baseMerge` for arrays and objects which performs
45534 * deep merges and tracks traversed objects enabling objects with circular
45535 * references to be merged.
45536 *
45537 * @private
45538 * @param {Object} object The destination object.
45539 * @param {Object} source The source object.
45540 * @param {string} key The key of the value to merge.
45541 * @param {number} srcIndex The index of `source`.
45542 * @param {Function} mergeFunc The function to merge values.
45543 * @param {Function} [customizer] The function to customize assigned values.
45544 * @param {Object} [stack] Tracks traversed source values and their merged
45545 * counterparts.
45546 */
45547 function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) {
45548 var objValue = safeGet(object, key),
45549 srcValue = safeGet(source, key),
45550 stacked = stack.get(srcValue);
45551
45552 if (stacked) {
45553 assignMergeValue(object, key, stacked);
45554 return;
45555 }
45556 var newValue = customizer
45557 ? customizer(objValue, srcValue, (key + ''), object, source, stack)
45558 : undefined;
45559
45560 var isCommon = newValue === undefined;
45561
45562 if (isCommon) {
45563 var isArr = isArray(srcValue),
45564 isBuff = !isArr && isBuffer(srcValue),
45565 isTyped = !isArr && !isBuff && isTypedArray(srcValue);
45566
45567 newValue = srcValue;
45568 if (isArr || isBuff || isTyped) {
45569 if (isArray(objValue)) {
45570 newValue = objValue;
45571 }
45572 else if (isArrayLikeObject(objValue)) {
45573 newValue = copyArray(objValue);
45574 }
45575 else if (isBuff) {
45576 isCommon = false;
45577 newValue = cloneBuffer(srcValue, true);
45578 }
45579 else if (isTyped) {
45580 isCommon = false;
45581 newValue = cloneTypedArray(srcValue, true);
45582 }
45583 else {
45584 newValue = [];
45585 }
45586 }
45587 else if (isPlainObject(srcValue) || isArguments(srcValue)) {
45588 newValue = objValue;
45589 if (isArguments(objValue)) {
45590 newValue = toPlainObject(objValue);
45591 }
45592 else if (!isObject(objValue) || isFunction(objValue)) {
45593 newValue = initCloneObject(srcValue);
45594 }
45595 }
45596 else {
45597 isCommon = false;
45598 }
45599 }
45600 if (isCommon) {
45601 // Recursively merge objects and arrays (susceptible to call stack limits).
45602 stack.set(srcValue, newValue);
45603 mergeFunc(newValue, srcValue, srcIndex, customizer, stack);
45604 stack['delete'](srcValue);
45605 }
45606 assignMergeValue(object, key, newValue);
45607 }
45608
45609 /**
45610 * The base implementation of `_.nth` which doesn't coerce arguments.
45611 *
45612 * @private
45613 * @param {Array} array The array to query.
45614 * @param {number} n The index of the element to return.
45615 * @returns {*} Returns the nth element of `array`.
45616 */
45617 function baseNth(array, n) {
45618 var length = array.length;
45619 if (!length) {
45620 return;
45621 }
45622 n += n < 0 ? length : 0;
45623 return isIndex(n, length) ? array[n] : undefined;
45624 }
45625
45626 /**
45627 * The base implementation of `_.orderBy` without param guards.
45628 *
45629 * @private
45630 * @param {Array|Object} collection The collection to iterate over.
45631 * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by.
45632 * @param {string[]} orders The sort orders of `iteratees`.
45633 * @returns {Array} Returns the new sorted array.
45634 */
45635 function baseOrderBy(collection, iteratees, orders) {
45636 if (iteratees.length) {
45637 iteratees = arrayMap(iteratees, function(iteratee) {
45638 if (isArray(iteratee)) {
45639 return function(value) {
45640 return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee);
45641 }
45642 }
45643 return iteratee;
45644 });
45645 } else {
45646 iteratees = [identity];
45647 }
45648
45649 var index = -1;
45650 iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
45651
45652 var result = baseMap(collection, function(value, key, collection) {
45653 var criteria = arrayMap(iteratees, function(iteratee) {
45654 return iteratee(value);
45655 });
45656 return { 'criteria': criteria, 'index': ++index, 'value': value };
45657 });
45658
45659 return baseSortBy(result, function(object, other) {
45660 return compareMultiple(object, other, orders);
45661 });
45662 }
45663
45664 /**
45665 * The base implementation of `_.pick` without support for individual
45666 * property identifiers.
45667 *
45668 * @private
45669 * @param {Object} object The source object.
45670 * @param {string[]} paths The property paths to pick.
45671 * @returns {Object} Returns the new object.
45672 */
45673 function basePick(object, paths) {
45674 return basePickBy(object, paths, function(value, path) {
45675 return hasIn(object, path);
45676 });
45677 }
45678
45679 /**
45680 * The base implementation of `_.pickBy` without support for iteratee shorthands.
45681 *
45682 * @private
45683 * @param {Object} object The source object.
45684 * @param {string[]} paths The property paths to pick.
45685 * @param {Function} predicate The function invoked per property.
45686 * @returns {Object} Returns the new object.
45687 */
45688 function basePickBy(object, paths, predicate) {
45689 var index = -1,
45690 length = paths.length,
45691 result = {};
45692
45693 while (++index < length) {
45694 var path = paths[index],
45695 value = baseGet(object, path);
45696
45697 if (predicate(value, path)) {
45698 baseSet(result, castPath(path, object), value);
45699 }
45700 }
45701 return result;
45702 }
45703
45704 /**
45705 * A specialized version of `baseProperty` which supports deep paths.
45706 *
45707 * @private
45708 * @param {Array|string} path The path of the property to get.
45709 * @returns {Function} Returns the new accessor function.
45710 */
45711 function basePropertyDeep(path) {
45712 return function(object) {
45713 return baseGet(object, path);
45714 };
45715 }
45716
45717 /**
45718 * The base implementation of `_.pullAllBy` without support for iteratee
45719 * shorthands.
45720 *
45721 * @private
45722 * @param {Array} array The array to modify.
45723 * @param {Array} values The values to remove.
45724 * @param {Function} [iteratee] The iteratee invoked per element.
45725 * @param {Function} [comparator] The comparator invoked per element.
45726 * @returns {Array} Returns `array`.
45727 */
45728 function basePullAll(array, values, iteratee, comparator) {
45729 var indexOf = comparator ? baseIndexOfWith : baseIndexOf,
45730 index = -1,
45731 length = values.length,
45732 seen = array;
45733
45734 if (array === values) {
45735 values = copyArray(values);
45736 }
45737 if (iteratee) {
45738 seen = arrayMap(array, baseUnary(iteratee));
45739 }
45740 while (++index < length) {
45741 var fromIndex = 0,
45742 value = values[index],
45743 computed = iteratee ? iteratee(value) : value;
45744
45745 while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) {
45746 if (seen !== array) {
45747 splice.call(seen, fromIndex, 1);
45748 }
45749 splice.call(array, fromIndex, 1);
45750 }
45751 }
45752 return array;
45753 }
45754
45755 /**
45756 * The base implementation of `_.pullAt` without support for individual
45757 * indexes or capturing the removed elements.
45758 *
45759 * @private
45760 * @param {Array} array The array to modify.
45761 * @param {number[]} indexes The indexes of elements to remove.
45762 * @returns {Array} Returns `array`.
45763 */
45764 function basePullAt(array, indexes) {
45765 var length = array ? indexes.length : 0,
45766 lastIndex = length - 1;
45767
45768 while (length--) {
45769 var index = indexes[length];
45770 if (length == lastIndex || index !== previous) {
45771 var previous = index;
45772 if (isIndex(index)) {
45773 splice.call(array, index, 1);
45774 } else {
45775 baseUnset(array, index);
45776 }
45777 }
45778 }
45779 return array;
45780 }
45781
45782 /**
45783 * The base implementation of `_.random` without support for returning
45784 * floating-point numbers.
45785 *
45786 * @private
45787 * @param {number} lower The lower bound.
45788 * @param {number} upper The upper bound.
45789 * @returns {number} Returns the random number.
45790 */
45791 function baseRandom(lower, upper) {
45792 return lower + nativeFloor(nativeRandom() * (upper - lower + 1));
45793 }
45794
45795 /**
45796 * The base implementation of `_.range` and `_.rangeRight` which doesn't
45797 * coerce arguments.
45798 *
45799 * @private
45800 * @param {number} start The start of the range.
45801 * @param {number} end The end of the range.
45802 * @param {number} step The value to increment or decrement by.
45803 * @param {boolean} [fromRight] Specify iterating from right to left.
45804 * @returns {Array} Returns the range of numbers.
45805 */
45806 function baseRange(start, end, step, fromRight) {
45807 var index = -1,
45808 length = nativeMax(nativeCeil((end - start) / (step || 1)), 0),
45809 result = Array(length);
45810
45811 while (length--) {
45812 result[fromRight ? length : ++index] = start;
45813 start += step;
45814 }
45815 return result;
45816 }
45817
45818 /**
45819 * The base implementation of `_.repeat` which doesn't coerce arguments.
45820 *
45821 * @private
45822 * @param {string} string The string to repeat.
45823 * @param {number} n The number of times to repeat the string.
45824 * @returns {string} Returns the repeated string.
45825 */
45826 function baseRepeat(string, n) {
45827 var result = '';
45828 if (!string || n < 1 || n > MAX_SAFE_INTEGER) {
45829 return result;
45830 }
45831 // Leverage the exponentiation by squaring algorithm for a faster repeat.
45832 // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details.
45833 do {
45834 if (n % 2) {
45835 result += string;
45836 }
45837 n = nativeFloor(n / 2);
45838 if (n) {
45839 string += string;
45840 }
45841 } while (n);
45842
45843 return result;
45844 }
45845
45846 /**
45847 * The base implementation of `_.rest` which doesn't validate or coerce arguments.
45848 *
45849 * @private
45850 * @param {Function} func The function to apply a rest parameter to.
45851 * @param {number} [start=func.length-1] The start position of the rest parameter.
45852 * @returns {Function} Returns the new function.
45853 */
45854 function baseRest(func, start) {
45855 return setToString(overRest(func, start, identity), func + '');
45856 }
45857
45858 /**
45859 * The base implementation of `_.sample`.
45860 *
45861 * @private
45862 * @param {Array|Object} collection The collection to sample.
45863 * @returns {*} Returns the random element.
45864 */
45865 function baseSample(collection) {
45866 return arraySample(values(collection));
45867 }
45868
45869 /**
45870 * The base implementation of `_.sampleSize` without param guards.
45871 *
45872 * @private
45873 * @param {Array|Object} collection The collection to sample.
45874 * @param {number} n The number of elements to sample.
45875 * @returns {Array} Returns the random elements.
45876 */
45877 function baseSampleSize(collection, n) {
45878 var array = values(collection);
45879 return shuffleSelf(array, baseClamp(n, 0, array.length));
45880 }
45881
45882 /**
45883 * The base implementation of `_.set`.
45884 *
45885 * @private
45886 * @param {Object} object The object to modify.
45887 * @param {Array|string} path The path of the property to set.
45888 * @param {*} value The value to set.
45889 * @param {Function} [customizer] The function to customize path creation.
45890 * @returns {Object} Returns `object`.
45891 */
45892 function baseSet(object, path, value, customizer) {
45893 if (!isObject(object)) {
45894 return object;
45895 }
45896 path = castPath(path, object);
45897
45898 var index = -1,
45899 length = path.length,
45900 lastIndex = length - 1,
45901 nested = object;
45902
45903 while (nested != null && ++index < length) {
45904 var key = toKey(path[index]),
45905 newValue = value;
45906
45907 if (key === '__proto__' || key === 'constructor' || key === 'prototype') {
45908 return object;
45909 }
45910
45911 if (index != lastIndex) {
45912 var objValue = nested[key];
45913 newValue = customizer ? customizer(objValue, key, nested) : undefined;
45914 if (newValue === undefined) {
45915 newValue = isObject(objValue)
45916 ? objValue
45917 : (isIndex(path[index + 1]) ? [] : {});
45918 }
45919 }
45920 assignValue(nested, key, newValue);
45921 nested = nested[key];
45922 }
45923 return object;
45924 }
45925
45926 /**
45927 * The base implementation of `setData` without support for hot loop shorting.
45928 *
45929 * @private
45930 * @param {Function} func The function to associate metadata with.
45931 * @param {*} data The metadata.
45932 * @returns {Function} Returns `func`.
45933 */
45934 var baseSetData = !metaMap ? identity : function(func, data) {
45935 metaMap.set(func, data);
45936 return func;
45937 };
45938
45939 /**
45940 * The base implementation of `setToString` without support for hot loop shorting.
45941 *
45942 * @private
45943 * @param {Function} func The function to modify.
45944 * @param {Function} string The `toString` result.
45945 * @returns {Function} Returns `func`.
45946 */
45947 var baseSetToString = !defineProperty ? identity : function(func, string) {
45948 return defineProperty(func, 'toString', {
45949 'configurable': true,
45950 'enumerable': false,
45951 'value': constant(string),
45952 'writable': true
45953 });
45954 };
45955
45956 /**
45957 * The base implementation of `_.shuffle`.
45958 *
45959 * @private
45960 * @param {Array|Object} collection The collection to shuffle.
45961 * @returns {Array} Returns the new shuffled array.
45962 */
45963 function baseShuffle(collection) {
45964 return shuffleSelf(values(collection));
45965 }
45966
45967 /**
45968 * The base implementation of `_.slice` without an iteratee call guard.
45969 *
45970 * @private
45971 * @param {Array} array The array to slice.
45972 * @param {number} [start=0] The start position.
45973 * @param {number} [end=array.length] The end position.
45974 * @returns {Array} Returns the slice of `array`.
45975 */
45976 function baseSlice(array, start, end) {
45977 var index = -1,
45978 length = array.length;
45979
45980 if (start < 0) {
45981 start = -start > length ? 0 : (length + start);
45982 }
45983 end = end > length ? length : end;
45984 if (end < 0) {
45985 end += length;
45986 }
45987 length = start > end ? 0 : ((end - start) >>> 0);
45988 start >>>= 0;
45989
45990 var result = Array(length);
45991 while (++index < length) {
45992 result[index] = array[index + start];
45993 }
45994 return result;
45995 }
45996
45997 /**
45998 * The base implementation of `_.some` without support for iteratee shorthands.
45999 *
46000 * @private
46001 * @param {Array|Object} collection The collection to iterate over.
46002 * @param {Function} predicate The function invoked per iteration.
46003 * @returns {boolean} Returns `true` if any element passes the predicate check,
46004 * else `false`.
46005 */
46006 function baseSome(collection, predicate) {
46007 var result;
46008
46009 baseEach(collection, function(value, index, collection) {
46010 result = predicate(value, index, collection);
46011 return !result;
46012 });
46013 return !!result;
46014 }
46015
46016 /**
46017 * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which
46018 * performs a binary search of `array` to determine the index at which `value`
46019 * should be inserted into `array` in order to maintain its sort order.
46020 *
46021 * @private
46022 * @param {Array} array The sorted array to inspect.
46023 * @param {*} value The value to evaluate.
46024 * @param {boolean} [retHighest] Specify returning the highest qualified index.
46025 * @returns {number} Returns the index at which `value` should be inserted
46026 * into `array`.
46027 */
46028 function baseSortedIndex(array, value, retHighest) {
46029 var low = 0,
46030 high = array == null ? low : array.length;
46031
46032 if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) {
46033 while (low < high) {
46034 var mid = (low + high) >>> 1,
46035 computed = array[mid];
46036
46037 if (computed !== null && !isSymbol(computed) &&
46038 (retHighest ? (computed <= value) : (computed < value))) {
46039 low = mid + 1;
46040 } else {
46041 high = mid;
46042 }
46043 }
46044 return high;
46045 }
46046 return baseSortedIndexBy(array, value, identity, retHighest);
46047 }
46048
46049 /**
46050 * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy`
46051 * which invokes `iteratee` for `value` and each element of `array` to compute
46052 * their sort ranking. The iteratee is invoked with one argument; (value).
46053 *
46054 * @private
46055 * @param {Array} array The sorted array to inspect.
46056 * @param {*} value The value to evaluate.
46057 * @param {Function} iteratee The iteratee invoked per element.
46058 * @param {boolean} [retHighest] Specify returning the highest qualified index.
46059 * @returns {number} Returns the index at which `value` should be inserted
46060 * into `array`.
46061 */
46062 function baseSortedIndexBy(array, value, iteratee, retHighest) {
46063 var low = 0,
46064 high = array == null ? 0 : array.length;
46065 if (high === 0) {
46066 return 0;
46067 }
46068
46069 value = iteratee(value);
46070 var valIsNaN = value !== value,
46071 valIsNull = value === null,
46072 valIsSymbol = isSymbol(value),
46073 valIsUndefined = value === undefined;
46074
46075 while (low < high) {
46076 var mid = nativeFloor((low + high) / 2),
46077 computed = iteratee(array[mid]),
46078 othIsDefined = computed !== undefined,
46079 othIsNull = computed === null,
46080 othIsReflexive = computed === computed,
46081 othIsSymbol = isSymbol(computed);
46082
46083 if (valIsNaN) {
46084 var setLow = retHighest || othIsReflexive;
46085 } else if (valIsUndefined) {
46086 setLow = othIsReflexive && (retHighest || othIsDefined);
46087 } else if (valIsNull) {
46088 setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull);
46089 } else if (valIsSymbol) {
46090 setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol);
46091 } else if (othIsNull || othIsSymbol) {
46092 setLow = false;
46093 } else {
46094 setLow = retHighest ? (computed <= value) : (computed < value);
46095 }
46096 if (setLow) {
46097 low = mid + 1;
46098 } else {
46099 high = mid;
46100 }
46101 }
46102 return nativeMin(high, MAX_ARRAY_INDEX);
46103 }
46104
46105 /**
46106 * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without
46107 * support for iteratee shorthands.
46108 *
46109 * @private
46110 * @param {Array} array The array to inspect.
46111 * @param {Function} [iteratee] The iteratee invoked per element.
46112 * @returns {Array} Returns the new duplicate free array.
46113 */
46114 function baseSortedUniq(array, iteratee) {
46115 var index = -1,
46116 length = array.length,
46117 resIndex = 0,
46118 result = [];
46119
46120 while (++index < length) {
46121 var value = array[index],
46122 computed = iteratee ? iteratee(value) : value;
46123
46124 if (!index || !eq(computed, seen)) {
46125 var seen = computed;
46126 result[resIndex++] = value === 0 ? 0 : value;
46127 }
46128 }
46129 return result;
46130 }
46131
46132 /**
46133 * The base implementation of `_.toNumber` which doesn't ensure correct
46134 * conversions of binary, hexadecimal, or octal string values.
46135 *
46136 * @private
46137 * @param {*} value The value to process.
46138 * @returns {number} Returns the number.
46139 */
46140 function baseToNumber(value) {
46141 if (typeof value == 'number') {
46142 return value;
46143 }
46144 if (isSymbol(value)) {
46145 return NAN;
46146 }
46147 return +value;
46148 }
46149
46150 /**
46151 * The base implementation of `_.toString` which doesn't convert nullish
46152 * values to empty strings.
46153 *
46154 * @private
46155 * @param {*} value The value to process.
46156 * @returns {string} Returns the string.
46157 */
46158 function baseToString(value) {
46159 // Exit early for strings to avoid a performance hit in some environments.
46160 if (typeof value == 'string') {
46161 return value;
46162 }
46163 if (isArray(value)) {
46164 // Recursively convert values (susceptible to call stack limits).
46165 return arrayMap(value, baseToString) + '';
46166 }
46167 if (isSymbol(value)) {
46168 return symbolToString ? symbolToString.call(value) : '';
46169 }
46170 var result = (value + '');
46171 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
46172 }
46173
46174 /**
46175 * The base implementation of `_.uniqBy` without support for iteratee shorthands.
46176 *
46177 * @private
46178 * @param {Array} array The array to inspect.
46179 * @param {Function} [iteratee] The iteratee invoked per element.
46180 * @param {Function} [comparator] The comparator invoked per element.
46181 * @returns {Array} Returns the new duplicate free array.
46182 */
46183 function baseUniq(array, iteratee, comparator) {
46184 var index = -1,
46185 includes = arrayIncludes,
46186 length = array.length,
46187 isCommon = true,
46188 result = [],
46189 seen = result;
46190
46191 if (comparator) {
46192 isCommon = false;
46193 includes = arrayIncludesWith;
46194 }
46195 else if (length >= LARGE_ARRAY_SIZE) {
46196 var set = iteratee ? null : createSet(array);
46197 if (set) {
46198 return setToArray(set);
46199 }
46200 isCommon = false;
46201 includes = cacheHas;
46202 seen = new SetCache;
46203 }
46204 else {
46205 seen = iteratee ? [] : result;
46206 }
46207 outer:
46208 while (++index < length) {
46209 var value = array[index],
46210 computed = iteratee ? iteratee(value) : value;
46211
46212 value = (comparator || value !== 0) ? value : 0;
46213 if (isCommon && computed === computed) {
46214 var seenIndex = seen.length;
46215 while (seenIndex--) {
46216 if (seen[seenIndex] === computed) {
46217 continue outer;
46218 }
46219 }
46220 if (iteratee) {
46221 seen.push(computed);
46222 }
46223 result.push(value);
46224 }
46225 else if (!includes(seen, computed, comparator)) {
46226 if (seen !== result) {
46227 seen.push(computed);
46228 }
46229 result.push(value);
46230 }
46231 }
46232 return result;
46233 }
46234
46235 /**
46236 * The base implementation of `_.unset`.
46237 *
46238 * @private
46239 * @param {Object} object The object to modify.
46240 * @param {Array|string} path The property path to unset.
46241 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
46242 */
46243 function baseUnset(object, path) {
46244 path = castPath(path, object);
46245 object = parent(object, path);
46246 return object == null || delete object[toKey(last(path))];
46247 }
46248
46249 /**
46250 * The base implementation of `_.update`.
46251 *
46252 * @private
46253 * @param {Object} object The object to modify.
46254 * @param {Array|string} path The path of the property to update.
46255 * @param {Function} updater The function to produce the updated value.
46256 * @param {Function} [customizer] The function to customize path creation.
46257 * @returns {Object} Returns `object`.
46258 */
46259 function baseUpdate(object, path, updater, customizer) {
46260 return baseSet(object, path, updater(baseGet(object, path)), customizer);
46261 }
46262
46263 /**
46264 * The base implementation of methods like `_.dropWhile` and `_.takeWhile`
46265 * without support for iteratee shorthands.
46266 *
46267 * @private
46268 * @param {Array} array The array to query.
46269 * @param {Function} predicate The function invoked per iteration.
46270 * @param {boolean} [isDrop] Specify dropping elements instead of taking them.
46271 * @param {boolean} [fromRight] Specify iterating from right to left.
46272 * @returns {Array} Returns the slice of `array`.
46273 */
46274 function baseWhile(array, predicate, isDrop, fromRight) {
46275 var length = array.length,
46276 index = fromRight ? length : -1;
46277
46278 while ((fromRight ? index-- : ++index < length) &&
46279 predicate(array[index], index, array)) {}
46280
46281 return isDrop
46282 ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length))
46283 : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index));
46284 }
46285
46286 /**
46287 * The base implementation of `wrapperValue` which returns the result of
46288 * performing a sequence of actions on the unwrapped `value`, where each
46289 * successive action is supplied the return value of the previous.
46290 *
46291 * @private
46292 * @param {*} value The unwrapped value.
46293 * @param {Array} actions Actions to perform to resolve the unwrapped value.
46294 * @returns {*} Returns the resolved value.
46295 */
46296 function baseWrapperValue(value, actions) {
46297 var result = value;
46298 if (result instanceof LazyWrapper) {
46299 result = result.value();
46300 }
46301 return arrayReduce(actions, function(result, action) {
46302 return action.func.apply(action.thisArg, arrayPush([result], action.args));
46303 }, result);
46304 }
46305
46306 /**
46307 * The base implementation of methods like `_.xor`, without support for
46308 * iteratee shorthands, that accepts an array of arrays to inspect.
46309 *
46310 * @private
46311 * @param {Array} arrays The arrays to inspect.
46312 * @param {Function} [iteratee] The iteratee invoked per element.
46313 * @param {Function} [comparator] The comparator invoked per element.
46314 * @returns {Array} Returns the new array of values.
46315 */
46316 function baseXor(arrays, iteratee, comparator) {
46317 var length = arrays.length;
46318 if (length < 2) {
46319 return length ? baseUniq(arrays[0]) : [];
46320 }
46321 var index = -1,
46322 result = Array(length);
46323
46324 while (++index < length) {
46325 var array = arrays[index],
46326 othIndex = -1;
46327
46328 while (++othIndex < length) {
46329 if (othIndex != index) {
46330 result[index] = baseDifference(result[index] || array, arrays[othIndex], iteratee, comparator);
46331 }
46332 }
46333 }
46334 return baseUniq(baseFlatten(result, 1), iteratee, comparator);
46335 }
46336
46337 /**
46338 * This base implementation of `_.zipObject` which assigns values using `assignFunc`.
46339 *
46340 * @private
46341 * @param {Array} props The property identifiers.
46342 * @param {Array} values The property values.
46343 * @param {Function} assignFunc The function to assign values.
46344 * @returns {Object} Returns the new object.
46345 */
46346 function baseZipObject(props, values, assignFunc) {
46347 var index = -1,
46348 length = props.length,
46349 valsLength = values.length,
46350 result = {};
46351
46352 while (++index < length) {
46353 var value = index < valsLength ? values[index] : undefined;
46354 assignFunc(result, props[index], value);
46355 }
46356 return result;
46357 }
46358
46359 /**
46360 * Casts `value` to an empty array if it's not an array like object.
46361 *
46362 * @private
46363 * @param {*} value The value to inspect.
46364 * @returns {Array|Object} Returns the cast array-like object.
46365 */
46366 function castArrayLikeObject(value) {
46367 return isArrayLikeObject(value) ? value : [];
46368 }
46369
46370 /**
46371 * Casts `value` to `identity` if it's not a function.
46372 *
46373 * @private
46374 * @param {*} value The value to inspect.
46375 * @returns {Function} Returns cast function.
46376 */
46377 function castFunction(value) {
46378 return typeof value == 'function' ? value : identity;
46379 }
46380
46381 /**
46382 * Casts `value` to a path array if it's not one.
46383 *
46384 * @private
46385 * @param {*} value The value to inspect.
46386 * @param {Object} [object] The object to query keys on.
46387 * @returns {Array} Returns the cast property path array.
46388 */
46389 function castPath(value, object) {
46390 if (isArray(value)) {
46391 return value;
46392 }
46393 return isKey(value, object) ? [value] : stringToPath(toString(value));
46394 }
46395
46396 /**
46397 * A `baseRest` alias which can be replaced with `identity` by module
46398 * replacement plugins.
46399 *
46400 * @private
46401 * @type {Function}
46402 * @param {Function} func The function to apply a rest parameter to.
46403 * @returns {Function} Returns the new function.
46404 */
46405 var castRest = baseRest;
46406
46407 /**
46408 * Casts `array` to a slice if it's needed.
46409 *
46410 * @private
46411 * @param {Array} array The array to inspect.
46412 * @param {number} start The start position.
46413 * @param {number} [end=array.length] The end position.
46414 * @returns {Array} Returns the cast slice.
46415 */
46416 function castSlice(array, start, end) {
46417 var length = array.length;
46418 end = end === undefined ? length : end;
46419 return (!start && end >= length) ? array : baseSlice(array, start, end);
46420 }
46421
46422 /**
46423 * A simple wrapper around the global [`clearTimeout`](https://mdn.io/clearTimeout).
46424 *
46425 * @private
46426 * @param {number|Object} id The timer id or timeout object of the timer to clear.
46427 */
46428 var clearTimeout = ctxClearTimeout || function(id) {
46429 return root.clearTimeout(id);
46430 };
46431
46432 /**
46433 * Creates a clone of `buffer`.
46434 *
46435 * @private
46436 * @param {Buffer} buffer The buffer to clone.
46437 * @param {boolean} [isDeep] Specify a deep clone.
46438 * @returns {Buffer} Returns the cloned buffer.
46439 */
46440 function cloneBuffer(buffer, isDeep) {
46441 if (isDeep) {
46442 return buffer.slice();
46443 }
46444 var length = buffer.length,
46445 result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length);
46446
46447 buffer.copy(result);
46448 return result;
46449 }
46450
46451 /**
46452 * Creates a clone of `arrayBuffer`.
46453 *
46454 * @private
46455 * @param {ArrayBuffer} arrayBuffer The array buffer to clone.
46456 * @returns {ArrayBuffer} Returns the cloned array buffer.
46457 */
46458 function cloneArrayBuffer(arrayBuffer) {
46459 var result = new arrayBuffer.constructor(arrayBuffer.byteLength);
46460 new Uint8Array(result).set(new Uint8Array(arrayBuffer));
46461 return result;
46462 }
46463
46464 /**
46465 * Creates a clone of `dataView`.
46466 *
46467 * @private
46468 * @param {Object} dataView The data view to clone.
46469 * @param {boolean} [isDeep] Specify a deep clone.
46470 * @returns {Object} Returns the cloned data view.
46471 */
46472 function cloneDataView(dataView, isDeep) {
46473 var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer;
46474 return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength);
46475 }
46476
46477 /**
46478 * Creates a clone of `regexp`.
46479 *
46480 * @private
46481 * @param {Object} regexp The regexp to clone.
46482 * @returns {Object} Returns the cloned regexp.
46483 */
46484 function cloneRegExp(regexp) {
46485 var result = new regexp.constructor(regexp.source, reFlags.exec(regexp));
46486 result.lastIndex = regexp.lastIndex;
46487 return result;
46488 }
46489
46490 /**
46491 * Creates a clone of the `symbol` object.
46492 *
46493 * @private
46494 * @param {Object} symbol The symbol object to clone.
46495 * @returns {Object} Returns the cloned symbol object.
46496 */
46497 function cloneSymbol(symbol) {
46498 return symbolValueOf ? Object(symbolValueOf.call(symbol)) : {};
46499 }
46500
46501 /**
46502 * Creates a clone of `typedArray`.
46503 *
46504 * @private
46505 * @param {Object} typedArray The typed array to clone.
46506 * @param {boolean} [isDeep] Specify a deep clone.
46507 * @returns {Object} Returns the cloned typed array.
46508 */
46509 function cloneTypedArray(typedArray, isDeep) {
46510 var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer;
46511 return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length);
46512 }
46513
46514 /**
46515 * Compares values to sort them in ascending order.
46516 *
46517 * @private
46518 * @param {*} value The value to compare.
46519 * @param {*} other The other value to compare.
46520 * @returns {number} Returns the sort order indicator for `value`.
46521 */
46522 function compareAscending(value, other) {
46523 if (value !== other) {
46524 var valIsDefined = value !== undefined,
46525 valIsNull = value === null,
46526 valIsReflexive = value === value,
46527 valIsSymbol = isSymbol(value);
46528
46529 var othIsDefined = other !== undefined,
46530 othIsNull = other === null,
46531 othIsReflexive = other === other,
46532 othIsSymbol = isSymbol(other);
46533
46534 if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) ||
46535 (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) ||
46536 (valIsNull && othIsDefined && othIsReflexive) ||
46537 (!valIsDefined && othIsReflexive) ||
46538 !valIsReflexive) {
46539 return 1;
46540 }
46541 if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) ||
46542 (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) ||
46543 (othIsNull && valIsDefined && valIsReflexive) ||
46544 (!othIsDefined && valIsReflexive) ||
46545 !othIsReflexive) {
46546 return -1;
46547 }
46548 }
46549 return 0;
46550 }
46551
46552 /**
46553 * Used by `_.orderBy` to compare multiple properties of a value to another
46554 * and stable sort them.
46555 *
46556 * If `orders` is unspecified, all values are sorted in ascending order. Otherwise,
46557 * specify an order of "desc" for descending or "asc" for ascending sort order
46558 * of corresponding values.
46559 *
46560 * @private
46561 * @param {Object} object The object to compare.
46562 * @param {Object} other The other object to compare.
46563 * @param {boolean[]|string[]} orders The order to sort by for each property.
46564 * @returns {number} Returns the sort order indicator for `object`.
46565 */
46566 function compareMultiple(object, other, orders) {
46567 var index = -1,
46568 objCriteria = object.criteria,
46569 othCriteria = other.criteria,
46570 length = objCriteria.length,
46571 ordersLength = orders.length;
46572
46573 while (++index < length) {
46574 var result = compareAscending(objCriteria[index], othCriteria[index]);
46575 if (result) {
46576 if (index >= ordersLength) {
46577 return result;
46578 }
46579 var order = orders[index];
46580 return result * (order == 'desc' ? -1 : 1);
46581 }
46582 }
46583 // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications
46584 // that causes it, under certain circumstances, to provide the same value for
46585 // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247
46586 // for more details.
46587 //
46588 // This also ensures a stable sort in V8 and other engines.
46589 // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details.
46590 return object.index - other.index;
46591 }
46592
46593 /**
46594 * Creates an array that is the composition of partially applied arguments,
46595 * placeholders, and provided arguments into a single array of arguments.
46596 *
46597 * @private
46598 * @param {Array} args The provided arguments.
46599 * @param {Array} partials The arguments to prepend to those provided.
46600 * @param {Array} holders The `partials` placeholder indexes.
46601 * @params {boolean} [isCurried] Specify composing for a curried function.
46602 * @returns {Array} Returns the new array of composed arguments.
46603 */
46604 function composeArgs(args, partials, holders, isCurried) {
46605 var argsIndex = -1,
46606 argsLength = args.length,
46607 holdersLength = holders.length,
46608 leftIndex = -1,
46609 leftLength = partials.length,
46610 rangeLength = nativeMax(argsLength - holdersLength, 0),
46611 result = Array(leftLength + rangeLength),
46612 isUncurried = !isCurried;
46613
46614 while (++leftIndex < leftLength) {
46615 result[leftIndex] = partials[leftIndex];
46616 }
46617 while (++argsIndex < holdersLength) {
46618 if (isUncurried || argsIndex < argsLength) {
46619 result[holders[argsIndex]] = args[argsIndex];
46620 }
46621 }
46622 while (rangeLength--) {
46623 result[leftIndex++] = args[argsIndex++];
46624 }
46625 return result;
46626 }
46627
46628 /**
46629 * This function is like `composeArgs` except that the arguments composition
46630 * is tailored for `_.partialRight`.
46631 *
46632 * @private
46633 * @param {Array} args The provided arguments.
46634 * @param {Array} partials The arguments to append to those provided.
46635 * @param {Array} holders The `partials` placeholder indexes.
46636 * @params {boolean} [isCurried] Specify composing for a curried function.
46637 * @returns {Array} Returns the new array of composed arguments.
46638 */
46639 function composeArgsRight(args, partials, holders, isCurried) {
46640 var argsIndex = -1,
46641 argsLength = args.length,
46642 holdersIndex = -1,
46643 holdersLength = holders.length,
46644 rightIndex = -1,
46645 rightLength = partials.length,
46646 rangeLength = nativeMax(argsLength - holdersLength, 0),
46647 result = Array(rangeLength + rightLength),
46648 isUncurried = !isCurried;
46649
46650 while (++argsIndex < rangeLength) {
46651 result[argsIndex] = args[argsIndex];
46652 }
46653 var offset = argsIndex;
46654 while (++rightIndex < rightLength) {
46655 result[offset + rightIndex] = partials[rightIndex];
46656 }
46657 while (++holdersIndex < holdersLength) {
46658 if (isUncurried || argsIndex < argsLength) {
46659 result[offset + holders[holdersIndex]] = args[argsIndex++];
46660 }
46661 }
46662 return result;
46663 }
46664
46665 /**
46666 * Copies the values of `source` to `array`.
46667 *
46668 * @private
46669 * @param {Array} source The array to copy values from.
46670 * @param {Array} [array=[]] The array to copy values to.
46671 * @returns {Array} Returns `array`.
46672 */
46673 function copyArray(source, array) {
46674 var index = -1,
46675 length = source.length;
46676
46677 array || (array = Array(length));
46678 while (++index < length) {
46679 array[index] = source[index];
46680 }
46681 return array;
46682 }
46683
46684 /**
46685 * Copies properties of `source` to `object`.
46686 *
46687 * @private
46688 * @param {Object} source The object to copy properties from.
46689 * @param {Array} props The property identifiers to copy.
46690 * @param {Object} [object={}] The object to copy properties to.
46691 * @param {Function} [customizer] The function to customize copied values.
46692 * @returns {Object} Returns `object`.
46693 */
46694 function copyObject(source, props, object, customizer) {
46695 var isNew = !object;
46696 object || (object = {});
46697
46698 var index = -1,
46699 length = props.length;
46700
46701 while (++index < length) {
46702 var key = props[index];
46703
46704 var newValue = customizer
46705 ? customizer(object[key], source[key], key, object, source)
46706 : undefined;
46707
46708 if (newValue === undefined) {
46709 newValue = source[key];
46710 }
46711 if (isNew) {
46712 baseAssignValue(object, key, newValue);
46713 } else {
46714 assignValue(object, key, newValue);
46715 }
46716 }
46717 return object;
46718 }
46719
46720 /**
46721 * Copies own symbols of `source` to `object`.
46722 *
46723 * @private
46724 * @param {Object} source The object to copy symbols from.
46725 * @param {Object} [object={}] The object to copy symbols to.
46726 * @returns {Object} Returns `object`.
46727 */
46728 function copySymbols(source, object) {
46729 return copyObject(source, getSymbols(source), object);
46730 }
46731
46732 /**
46733 * Copies own and inherited symbols of `source` to `object`.
46734 *
46735 * @private
46736 * @param {Object} source The object to copy symbols from.
46737 * @param {Object} [object={}] The object to copy symbols to.
46738 * @returns {Object} Returns `object`.
46739 */
46740 function copySymbolsIn(source, object) {
46741 return copyObject(source, getSymbolsIn(source), object);
46742 }
46743
46744 /**
46745 * Creates a function like `_.groupBy`.
46746 *
46747 * @private
46748 * @param {Function} setter The function to set accumulator values.
46749 * @param {Function} [initializer] The accumulator object initializer.
46750 * @returns {Function} Returns the new aggregator function.
46751 */
46752 function createAggregator(setter, initializer) {
46753 return function(collection, iteratee) {
46754 var func = isArray(collection) ? arrayAggregator : baseAggregator,
46755 accumulator = initializer ? initializer() : {};
46756
46757 return func(collection, setter, getIteratee(iteratee, 2), accumulator);
46758 };
46759 }
46760
46761 /**
46762 * Creates a function like `_.assign`.
46763 *
46764 * @private
46765 * @param {Function} assigner The function to assign values.
46766 * @returns {Function} Returns the new assigner function.
46767 */
46768 function createAssigner(assigner) {
46769 return baseRest(function(object, sources) {
46770 var index = -1,
46771 length = sources.length,
46772 customizer = length > 1 ? sources[length - 1] : undefined,
46773 guard = length > 2 ? sources[2] : undefined;
46774
46775 customizer = (assigner.length > 3 && typeof customizer == 'function')
46776 ? (length--, customizer)
46777 : undefined;
46778
46779 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
46780 customizer = length < 3 ? undefined : customizer;
46781 length = 1;
46782 }
46783 object = Object(object);
46784 while (++index < length) {
46785 var source = sources[index];
46786 if (source) {
46787 assigner(object, source, index, customizer);
46788 }
46789 }
46790 return object;
46791 });
46792 }
46793
46794 /**
46795 * Creates a `baseEach` or `baseEachRight` function.
46796 *
46797 * @private
46798 * @param {Function} eachFunc The function to iterate over a collection.
46799 * @param {boolean} [fromRight] Specify iterating from right to left.
46800 * @returns {Function} Returns the new base function.
46801 */
46802 function createBaseEach(eachFunc, fromRight) {
46803 return function(collection, iteratee) {
46804 if (collection == null) {
46805 return collection;
46806 }
46807 if (!isArrayLike(collection)) {
46808 return eachFunc(collection, iteratee);
46809 }
46810 var length = collection.length,
46811 index = fromRight ? length : -1,
46812 iterable = Object(collection);
46813
46814 while ((fromRight ? index-- : ++index < length)) {
46815 if (iteratee(iterable[index], index, iterable) === false) {
46816 break;
46817 }
46818 }
46819 return collection;
46820 };
46821 }
46822
46823 /**
46824 * Creates a base function for methods like `_.forIn` and `_.forOwn`.
46825 *
46826 * @private
46827 * @param {boolean} [fromRight] Specify iterating from right to left.
46828 * @returns {Function} Returns the new base function.
46829 */
46830 function createBaseFor(fromRight) {
46831 return function(object, iteratee, keysFunc) {
46832 var index = -1,
46833 iterable = Object(object),
46834 props = keysFunc(object),
46835 length = props.length;
46836
46837 while (length--) {
46838 var key = props[fromRight ? length : ++index];
46839 if (iteratee(iterable[key], key, iterable) === false) {
46840 break;
46841 }
46842 }
46843 return object;
46844 };
46845 }
46846
46847 /**
46848 * Creates a function that wraps `func` to invoke it with the optional `this`
46849 * binding of `thisArg`.
46850 *
46851 * @private
46852 * @param {Function} func The function to wrap.
46853 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
46854 * @param {*} [thisArg] The `this` binding of `func`.
46855 * @returns {Function} Returns the new wrapped function.
46856 */
46857 function createBind(func, bitmask, thisArg) {
46858 var isBind = bitmask & WRAP_BIND_FLAG,
46859 Ctor = createCtor(func);
46860
46861 function wrapper() {
46862 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
46863 return fn.apply(isBind ? thisArg : this, arguments);
46864 }
46865 return wrapper;
46866 }
46867
46868 /**
46869 * Creates a function like `_.lowerFirst`.
46870 *
46871 * @private
46872 * @param {string} methodName The name of the `String` case method to use.
46873 * @returns {Function} Returns the new case function.
46874 */
46875 function createCaseFirst(methodName) {
46876 return function(string) {
46877 string = toString(string);
46878
46879 var strSymbols = hasUnicode(string)
46880 ? stringToArray(string)
46881 : undefined;
46882
46883 var chr = strSymbols
46884 ? strSymbols[0]
46885 : string.charAt(0);
46886
46887 var trailing = strSymbols
46888 ? castSlice(strSymbols, 1).join('')
46889 : string.slice(1);
46890
46891 return chr[methodName]() + trailing;
46892 };
46893 }
46894
46895 /**
46896 * Creates a function like `_.camelCase`.
46897 *
46898 * @private
46899 * @param {Function} callback The function to combine each word.
46900 * @returns {Function} Returns the new compounder function.
46901 */
46902 function createCompounder(callback) {
46903 return function(string) {
46904 return arrayReduce(words(deburr(string).replace(reApos, '')), callback, '');
46905 };
46906 }
46907
46908 /**
46909 * Creates a function that produces an instance of `Ctor` regardless of
46910 * whether it was invoked as part of a `new` expression or by `call` or `apply`.
46911 *
46912 * @private
46913 * @param {Function} Ctor The constructor to wrap.
46914 * @returns {Function} Returns the new wrapped function.
46915 */
46916 function createCtor(Ctor) {
46917 return function() {
46918 // Use a `switch` statement to work with class constructors. See
46919 // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist
46920 // for more details.
46921 var args = arguments;
46922 switch (args.length) {
46923 case 0: return new Ctor;
46924 case 1: return new Ctor(args[0]);
46925 case 2: return new Ctor(args[0], args[1]);
46926 case 3: return new Ctor(args[0], args[1], args[2]);
46927 case 4: return new Ctor(args[0], args[1], args[2], args[3]);
46928 case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]);
46929 case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]);
46930 case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
46931 }
46932 var thisBinding = baseCreate(Ctor.prototype),
46933 result = Ctor.apply(thisBinding, args);
46934
46935 // Mimic the constructor's `return` behavior.
46936 // See https://es5.github.io/#x13.2.2 for more details.
46937 return isObject(result) ? result : thisBinding;
46938 };
46939 }
46940
46941 /**
46942 * Creates a function that wraps `func` to enable currying.
46943 *
46944 * @private
46945 * @param {Function} func The function to wrap.
46946 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
46947 * @param {number} arity The arity of `func`.
46948 * @returns {Function} Returns the new wrapped function.
46949 */
46950 function createCurry(func, bitmask, arity) {
46951 var Ctor = createCtor(func);
46952
46953 function wrapper() {
46954 var length = arguments.length,
46955 args = Array(length),
46956 index = length,
46957 placeholder = getHolder(wrapper);
46958
46959 while (index--) {
46960 args[index] = arguments[index];
46961 }
46962 var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder)
46963 ? []
46964 : replaceHolders(args, placeholder);
46965
46966 length -= holders.length;
46967 if (length < arity) {
46968 return createRecurry(
46969 func, bitmask, createHybrid, wrapper.placeholder, undefined,
46970 args, holders, undefined, undefined, arity - length);
46971 }
46972 var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
46973 return apply(fn, this, args);
46974 }
46975 return wrapper;
46976 }
46977
46978 /**
46979 * Creates a `_.find` or `_.findLast` function.
46980 *
46981 * @private
46982 * @param {Function} findIndexFunc The function to find the collection index.
46983 * @returns {Function} Returns the new find function.
46984 */
46985 function createFind(findIndexFunc) {
46986 return function(collection, predicate, fromIndex) {
46987 var iterable = Object(collection);
46988 if (!isArrayLike(collection)) {
46989 var iteratee = getIteratee(predicate, 3);
46990 collection = keys(collection);
46991 predicate = function(key) { return iteratee(iterable[key], key, iterable); };
46992 }
46993 var index = findIndexFunc(collection, predicate, fromIndex);
46994 return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined;
46995 };
46996 }
46997
46998 /**
46999 * Creates a `_.flow` or `_.flowRight` function.
47000 *
47001 * @private
47002 * @param {boolean} [fromRight] Specify iterating from right to left.
47003 * @returns {Function} Returns the new flow function.
47004 */
47005 function createFlow(fromRight) {
47006 return flatRest(function(funcs) {
47007 var length = funcs.length,
47008 index = length,
47009 prereq = LodashWrapper.prototype.thru;
47010
47011 if (fromRight) {
47012 funcs.reverse();
47013 }
47014 while (index--) {
47015 var func = funcs[index];
47016 if (typeof func != 'function') {
47017 throw new TypeError(FUNC_ERROR_TEXT);
47018 }
47019 if (prereq && !wrapper && getFuncName(func) == 'wrapper') {
47020 var wrapper = new LodashWrapper([], true);
47021 }
47022 }
47023 index = wrapper ? index : length;
47024 while (++index < length) {
47025 func = funcs[index];
47026
47027 var funcName = getFuncName(func),
47028 data = funcName == 'wrapper' ? getData(func) : undefined;
47029
47030 if (data && isLaziable(data[0]) &&
47031 data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG | WRAP_REARG_FLAG) &&
47032 !data[4].length && data[9] == 1
47033 ) {
47034 wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]);
47035 } else {
47036 wrapper = (func.length == 1 && isLaziable(func))
47037 ? wrapper[funcName]()
47038 : wrapper.thru(func);
47039 }
47040 }
47041 return function() {
47042 var args = arguments,
47043 value = args[0];
47044
47045 if (wrapper && args.length == 1 && isArray(value)) {
47046 return wrapper.plant(value).value();
47047 }
47048 var index = 0,
47049 result = length ? funcs[index].apply(this, args) : value;
47050
47051 while (++index < length) {
47052 result = funcs[index].call(this, result);
47053 }
47054 return result;
47055 };
47056 });
47057 }
47058
47059 /**
47060 * Creates a function that wraps `func` to invoke it with optional `this`
47061 * binding of `thisArg`, partial application, and currying.
47062 *
47063 * @private
47064 * @param {Function|string} func The function or method name to wrap.
47065 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
47066 * @param {*} [thisArg] The `this` binding of `func`.
47067 * @param {Array} [partials] The arguments to prepend to those provided to
47068 * the new function.
47069 * @param {Array} [holders] The `partials` placeholder indexes.
47070 * @param {Array} [partialsRight] The arguments to append to those provided
47071 * to the new function.
47072 * @param {Array} [holdersRight] The `partialsRight` placeholder indexes.
47073 * @param {Array} [argPos] The argument positions of the new function.
47074 * @param {number} [ary] The arity cap of `func`.
47075 * @param {number} [arity] The arity of `func`.
47076 * @returns {Function} Returns the new wrapped function.
47077 */
47078 function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) {
47079 var isAry = bitmask & WRAP_ARY_FLAG,
47080 isBind = bitmask & WRAP_BIND_FLAG,
47081 isBindKey = bitmask & WRAP_BIND_KEY_FLAG,
47082 isCurried = bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG),
47083 isFlip = bitmask & WRAP_FLIP_FLAG,
47084 Ctor = isBindKey ? undefined : createCtor(func);
47085
47086 function wrapper() {
47087 var length = arguments.length,
47088 args = Array(length),
47089 index = length;
47090
47091 while (index--) {
47092 args[index] = arguments[index];
47093 }
47094 if (isCurried) {
47095 var placeholder = getHolder(wrapper),
47096 holdersCount = countHolders(args, placeholder);
47097 }
47098 if (partials) {
47099 args = composeArgs(args, partials, holders, isCurried);
47100 }
47101 if (partialsRight) {
47102 args = composeArgsRight(args, partialsRight, holdersRight, isCurried);
47103 }
47104 length -= holdersCount;
47105 if (isCurried && length < arity) {
47106 var newHolders = replaceHolders(args, placeholder);
47107 return createRecurry(
47108 func, bitmask, createHybrid, wrapper.placeholder, thisArg,
47109 args, newHolders, argPos, ary, arity - length
47110 );
47111 }
47112 var thisBinding = isBind ? thisArg : this,
47113 fn = isBindKey ? thisBinding[func] : func;
47114
47115 length = args.length;
47116 if (argPos) {
47117 args = reorder(args, argPos);
47118 } else if (isFlip && length > 1) {
47119 args.reverse();
47120 }
47121 if (isAry && ary < length) {
47122 args.length = ary;
47123 }
47124 if (this && this !== root && this instanceof wrapper) {
47125 fn = Ctor || createCtor(fn);
47126 }
47127 return fn.apply(thisBinding, args);
47128 }
47129 return wrapper;
47130 }
47131
47132 /**
47133 * Creates a function like `_.invertBy`.
47134 *
47135 * @private
47136 * @param {Function} setter The function to set accumulator values.
47137 * @param {Function} toIteratee The function to resolve iteratees.
47138 * @returns {Function} Returns the new inverter function.
47139 */
47140 function createInverter(setter, toIteratee) {
47141 return function(object, iteratee) {
47142 return baseInverter(object, setter, toIteratee(iteratee), {});
47143 };
47144 }
47145
47146 /**
47147 * Creates a function that performs a mathematical operation on two values.
47148 *
47149 * @private
47150 * @param {Function} operator The function to perform the operation.
47151 * @param {number} [defaultValue] The value used for `undefined` arguments.
47152 * @returns {Function} Returns the new mathematical operation function.
47153 */
47154 function createMathOperation(operator, defaultValue) {
47155 return function(value, other) {
47156 var result;
47157 if (value === undefined && other === undefined) {
47158 return defaultValue;
47159 }
47160 if (value !== undefined) {
47161 result = value;
47162 }
47163 if (other !== undefined) {
47164 if (result === undefined) {
47165 return other;
47166 }
47167 if (typeof value == 'string' || typeof other == 'string') {
47168 value = baseToString(value);
47169 other = baseToString(other);
47170 } else {
47171 value = baseToNumber(value);
47172 other = baseToNumber(other);
47173 }
47174 result = operator(value, other);
47175 }
47176 return result;
47177 };
47178 }
47179
47180 /**
47181 * Creates a function like `_.over`.
47182 *
47183 * @private
47184 * @param {Function} arrayFunc The function to iterate over iteratees.
47185 * @returns {Function} Returns the new over function.
47186 */
47187 function createOver(arrayFunc) {
47188 return flatRest(function(iteratees) {
47189 iteratees = arrayMap(iteratees, baseUnary(getIteratee()));
47190 return baseRest(function(args) {
47191 var thisArg = this;
47192 return arrayFunc(iteratees, function(iteratee) {
47193 return apply(iteratee, thisArg, args);
47194 });
47195 });
47196 });
47197 }
47198
47199 /**
47200 * Creates the padding for `string` based on `length`. The `chars` string
47201 * is truncated if the number of characters exceeds `length`.
47202 *
47203 * @private
47204 * @param {number} length The padding length.
47205 * @param {string} [chars=' '] The string used as padding.
47206 * @returns {string} Returns the padding for `string`.
47207 */
47208 function createPadding(length, chars) {
47209 chars = chars === undefined ? ' ' : baseToString(chars);
47210
47211 var charsLength = chars.length;
47212 if (charsLength < 2) {
47213 return charsLength ? baseRepeat(chars, length) : chars;
47214 }
47215 var result = baseRepeat(chars, nativeCeil(length / stringSize(chars)));
47216 return hasUnicode(chars)
47217 ? castSlice(stringToArray(result), 0, length).join('')
47218 : result.slice(0, length);
47219 }
47220
47221 /**
47222 * Creates a function that wraps `func` to invoke it with the `this` binding
47223 * of `thisArg` and `partials` prepended to the arguments it receives.
47224 *
47225 * @private
47226 * @param {Function} func The function to wrap.
47227 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
47228 * @param {*} thisArg The `this` binding of `func`.
47229 * @param {Array} partials The arguments to prepend to those provided to
47230 * the new function.
47231 * @returns {Function} Returns the new wrapped function.
47232 */
47233 function createPartial(func, bitmask, thisArg, partials) {
47234 var isBind = bitmask & WRAP_BIND_FLAG,
47235 Ctor = createCtor(func);
47236
47237 function wrapper() {
47238 var argsIndex = -1,
47239 argsLength = arguments.length,
47240 leftIndex = -1,
47241 leftLength = partials.length,
47242 args = Array(leftLength + argsLength),
47243 fn = (this && this !== root && this instanceof wrapper) ? Ctor : func;
47244
47245 while (++leftIndex < leftLength) {
47246 args[leftIndex] = partials[leftIndex];
47247 }
47248 while (argsLength--) {
47249 args[leftIndex++] = arguments[++argsIndex];
47250 }
47251 return apply(fn, isBind ? thisArg : this, args);
47252 }
47253 return wrapper;
47254 }
47255
47256 /**
47257 * Creates a `_.range` or `_.rangeRight` function.
47258 *
47259 * @private
47260 * @param {boolean} [fromRight] Specify iterating from right to left.
47261 * @returns {Function} Returns the new range function.
47262 */
47263 function createRange(fromRight) {
47264 return function(start, end, step) {
47265 if (step && typeof step != 'number' && isIterateeCall(start, end, step)) {
47266 end = step = undefined;
47267 }
47268 // Ensure the sign of `-0` is preserved.
47269 start = toFinite(start);
47270 if (end === undefined) {
47271 end = start;
47272 start = 0;
47273 } else {
47274 end = toFinite(end);
47275 }
47276 step = step === undefined ? (start < end ? 1 : -1) : toFinite(step);
47277 return baseRange(start, end, step, fromRight);
47278 };
47279 }
47280
47281 /**
47282 * Creates a function that performs a relational operation on two values.
47283 *
47284 * @private
47285 * @param {Function} operator The function to perform the operation.
47286 * @returns {Function} Returns the new relational operation function.
47287 */
47288 function createRelationalOperation(operator) {
47289 return function(value, other) {
47290 if (!(typeof value == 'string' && typeof other == 'string')) {
47291 value = toNumber(value);
47292 other = toNumber(other);
47293 }
47294 return operator(value, other);
47295 };
47296 }
47297
47298 /**
47299 * Creates a function that wraps `func` to continue currying.
47300 *
47301 * @private
47302 * @param {Function} func The function to wrap.
47303 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
47304 * @param {Function} wrapFunc The function to create the `func` wrapper.
47305 * @param {*} placeholder The placeholder value.
47306 * @param {*} [thisArg] The `this` binding of `func`.
47307 * @param {Array} [partials] The arguments to prepend to those provided to
47308 * the new function.
47309 * @param {Array} [holders] The `partials` placeholder indexes.
47310 * @param {Array} [argPos] The argument positions of the new function.
47311 * @param {number} [ary] The arity cap of `func`.
47312 * @param {number} [arity] The arity of `func`.
47313 * @returns {Function} Returns the new wrapped function.
47314 */
47315 function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) {
47316 var isCurry = bitmask & WRAP_CURRY_FLAG,
47317 newHolders = isCurry ? holders : undefined,
47318 newHoldersRight = isCurry ? undefined : holders,
47319 newPartials = isCurry ? partials : undefined,
47320 newPartialsRight = isCurry ? undefined : partials;
47321
47322 bitmask |= (isCurry ? WRAP_PARTIAL_FLAG : WRAP_PARTIAL_RIGHT_FLAG);
47323 bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG : WRAP_PARTIAL_FLAG);
47324
47325 if (!(bitmask & WRAP_CURRY_BOUND_FLAG)) {
47326 bitmask &= ~(WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG);
47327 }
47328 var newData = [
47329 func, bitmask, thisArg, newPartials, newHolders, newPartialsRight,
47330 newHoldersRight, argPos, ary, arity
47331 ];
47332
47333 var result = wrapFunc.apply(undefined, newData);
47334 if (isLaziable(func)) {
47335 setData(result, newData);
47336 }
47337 result.placeholder = placeholder;
47338 return setWrapToString(result, func, bitmask);
47339 }
47340
47341 /**
47342 * Creates a function like `_.round`.
47343 *
47344 * @private
47345 * @param {string} methodName The name of the `Math` method to use when rounding.
47346 * @returns {Function} Returns the new round function.
47347 */
47348 function createRound(methodName) {
47349 var func = Math[methodName];
47350 return function(number, precision) {
47351 number = toNumber(number);
47352 precision = precision == null ? 0 : nativeMin(toInteger(precision), 292);
47353 if (precision && nativeIsFinite(number)) {
47354 // Shift with exponential notation to avoid floating-point issues.
47355 // See [MDN](https://mdn.io/round#Examples) for more details.
47356 var pair = (toString(number) + 'e').split('e'),
47357 value = func(pair[0] + 'e' + (+pair[1] + precision));
47358
47359 pair = (toString(value) + 'e').split('e');
47360 return +(pair[0] + 'e' + (+pair[1] - precision));
47361 }
47362 return func(number);
47363 };
47364 }
47365
47366 /**
47367 * Creates a set object of `values`.
47368 *
47369 * @private
47370 * @param {Array} values The values to add to the set.
47371 * @returns {Object} Returns the new set.
47372 */
47373 var createSet = !(Set && (1 / setToArray(new Set([,-0]))[1]) == INFINITY) ? noop : function(values) {
47374 return new Set(values);
47375 };
47376
47377 /**
47378 * Creates a `_.toPairs` or `_.toPairsIn` function.
47379 *
47380 * @private
47381 * @param {Function} keysFunc The function to get the keys of a given object.
47382 * @returns {Function} Returns the new pairs function.
47383 */
47384 function createToPairs(keysFunc) {
47385 return function(object) {
47386 var tag = getTag(object);
47387 if (tag == mapTag) {
47388 return mapToArray(object);
47389 }
47390 if (tag == setTag) {
47391 return setToPairs(object);
47392 }
47393 return baseToPairs(object, keysFunc(object));
47394 };
47395 }
47396
47397 /**
47398 * Creates a function that either curries or invokes `func` with optional
47399 * `this` binding and partially applied arguments.
47400 *
47401 * @private
47402 * @param {Function|string} func The function or method name to wrap.
47403 * @param {number} bitmask The bitmask flags.
47404 * 1 - `_.bind`
47405 * 2 - `_.bindKey`
47406 * 4 - `_.curry` or `_.curryRight` of a bound function
47407 * 8 - `_.curry`
47408 * 16 - `_.curryRight`
47409 * 32 - `_.partial`
47410 * 64 - `_.partialRight`
47411 * 128 - `_.rearg`
47412 * 256 - `_.ary`
47413 * 512 - `_.flip`
47414 * @param {*} [thisArg] The `this` binding of `func`.
47415 * @param {Array} [partials] The arguments to be partially applied.
47416 * @param {Array} [holders] The `partials` placeholder indexes.
47417 * @param {Array} [argPos] The argument positions of the new function.
47418 * @param {number} [ary] The arity cap of `func`.
47419 * @param {number} [arity] The arity of `func`.
47420 * @returns {Function} Returns the new wrapped function.
47421 */
47422 function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) {
47423 var isBindKey = bitmask & WRAP_BIND_KEY_FLAG;
47424 if (!isBindKey && typeof func != 'function') {
47425 throw new TypeError(FUNC_ERROR_TEXT);
47426 }
47427 var length = partials ? partials.length : 0;
47428 if (!length) {
47429 bitmask &= ~(WRAP_PARTIAL_FLAG | WRAP_PARTIAL_RIGHT_FLAG);
47430 partials = holders = undefined;
47431 }
47432 ary = ary === undefined ? ary : nativeMax(toInteger(ary), 0);
47433 arity = arity === undefined ? arity : toInteger(arity);
47434 length -= holders ? holders.length : 0;
47435
47436 if (bitmask & WRAP_PARTIAL_RIGHT_FLAG) {
47437 var partialsRight = partials,
47438 holdersRight = holders;
47439
47440 partials = holders = undefined;
47441 }
47442 var data = isBindKey ? undefined : getData(func);
47443
47444 var newData = [
47445 func, bitmask, thisArg, partials, holders, partialsRight, holdersRight,
47446 argPos, ary, arity
47447 ];
47448
47449 if (data) {
47450 mergeData(newData, data);
47451 }
47452 func = newData[0];
47453 bitmask = newData[1];
47454 thisArg = newData[2];
47455 partials = newData[3];
47456 holders = newData[4];
47457 arity = newData[9] = newData[9] === undefined
47458 ? (isBindKey ? 0 : func.length)
47459 : nativeMax(newData[9] - length, 0);
47460
47461 if (!arity && bitmask & (WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG)) {
47462 bitmask &= ~(WRAP_CURRY_FLAG | WRAP_CURRY_RIGHT_FLAG);
47463 }
47464 if (!bitmask || bitmask == WRAP_BIND_FLAG) {
47465 var result = createBind(func, bitmask, thisArg);
47466 } else if (bitmask == WRAP_CURRY_FLAG || bitmask == WRAP_CURRY_RIGHT_FLAG) {
47467 result = createCurry(func, bitmask, arity);
47468 } else if ((bitmask == WRAP_PARTIAL_FLAG || bitmask == (WRAP_BIND_FLAG | WRAP_PARTIAL_FLAG)) && !holders.length) {
47469 result = createPartial(func, bitmask, thisArg, partials);
47470 } else {
47471 result = createHybrid.apply(undefined, newData);
47472 }
47473 var setter = data ? baseSetData : setData;
47474 return setWrapToString(setter(result, newData), func, bitmask);
47475 }
47476
47477 /**
47478 * Used by `_.defaults` to customize its `_.assignIn` use to assign properties
47479 * of source objects to the destination object for all destination properties
47480 * that resolve to `undefined`.
47481 *
47482 * @private
47483 * @param {*} objValue The destination value.
47484 * @param {*} srcValue The source value.
47485 * @param {string} key The key of the property to assign.
47486 * @param {Object} object The parent object of `objValue`.
47487 * @returns {*} Returns the value to assign.
47488 */
47489 function customDefaultsAssignIn(objValue, srcValue, key, object) {
47490 if (objValue === undefined ||
47491 (eq(objValue, objectProto[key]) && !hasOwnProperty.call(object, key))) {
47492 return srcValue;
47493 }
47494 return objValue;
47495 }
47496
47497 /**
47498 * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source
47499 * objects into destination objects that are passed thru.
47500 *
47501 * @private
47502 * @param {*} objValue The destination value.
47503 * @param {*} srcValue The source value.
47504 * @param {string} key The key of the property to merge.
47505 * @param {Object} object The parent object of `objValue`.
47506 * @param {Object} source The parent object of `srcValue`.
47507 * @param {Object} [stack] Tracks traversed source values and their merged
47508 * counterparts.
47509 * @returns {*} Returns the value to assign.
47510 */
47511 function customDefaultsMerge(objValue, srcValue, key, object, source, stack) {
47512 if (isObject(objValue) && isObject(srcValue)) {
47513 // Recursively merge objects and arrays (susceptible to call stack limits).
47514 stack.set(srcValue, objValue);
47515 baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack);
47516 stack['delete'](srcValue);
47517 }
47518 return objValue;
47519 }
47520
47521 /**
47522 * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain
47523 * objects.
47524 *
47525 * @private
47526 * @param {*} value The value to inspect.
47527 * @param {string} key The key of the property to inspect.
47528 * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`.
47529 */
47530 function customOmitClone(value) {
47531 return isPlainObject(value) ? undefined : value;
47532 }
47533
47534 /**
47535 * A specialized version of `baseIsEqualDeep` for arrays with support for
47536 * partial deep comparisons.
47537 *
47538 * @private
47539 * @param {Array} array The array to compare.
47540 * @param {Array} other The other array to compare.
47541 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
47542 * @param {Function} customizer The function to customize comparisons.
47543 * @param {Function} equalFunc The function to determine equivalents of values.
47544 * @param {Object} stack Tracks traversed `array` and `other` objects.
47545 * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`.
47546 */
47547 function equalArrays(array, other, bitmask, customizer, equalFunc, stack) {
47548 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
47549 arrLength = array.length,
47550 othLength = other.length;
47551
47552 if (arrLength != othLength && !(isPartial && othLength > arrLength)) {
47553 return false;
47554 }
47555 // Check that cyclic values are equal.
47556 var arrStacked = stack.get(array);
47557 var othStacked = stack.get(other);
47558 if (arrStacked && othStacked) {
47559 return arrStacked == other && othStacked == array;
47560 }
47561 var index = -1,
47562 result = true,
47563 seen = (bitmask & COMPARE_UNORDERED_FLAG) ? new SetCache : undefined;
47564
47565 stack.set(array, other);
47566 stack.set(other, array);
47567
47568 // Ignore non-index properties.
47569 while (++index < arrLength) {
47570 var arrValue = array[index],
47571 othValue = other[index];
47572
47573 if (customizer) {
47574 var compared = isPartial
47575 ? customizer(othValue, arrValue, index, other, array, stack)
47576 : customizer(arrValue, othValue, index, array, other, stack);
47577 }
47578 if (compared !== undefined) {
47579 if (compared) {
47580 continue;
47581 }
47582 result = false;
47583 break;
47584 }
47585 // Recursively compare arrays (susceptible to call stack limits).
47586 if (seen) {
47587 if (!arraySome(other, function(othValue, othIndex) {
47588 if (!cacheHas(seen, othIndex) &&
47589 (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) {
47590 return seen.push(othIndex);
47591 }
47592 })) {
47593 result = false;
47594 break;
47595 }
47596 } else if (!(
47597 arrValue === othValue ||
47598 equalFunc(arrValue, othValue, bitmask, customizer, stack)
47599 )) {
47600 result = false;
47601 break;
47602 }
47603 }
47604 stack['delete'](array);
47605 stack['delete'](other);
47606 return result;
47607 }
47608
47609 /**
47610 * A specialized version of `baseIsEqualDeep` for comparing objects of
47611 * the same `toStringTag`.
47612 *
47613 * **Note:** This function only supports comparing values with tags of
47614 * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`.
47615 *
47616 * @private
47617 * @param {Object} object The object to compare.
47618 * @param {Object} other The other object to compare.
47619 * @param {string} tag The `toStringTag` of the objects to compare.
47620 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
47621 * @param {Function} customizer The function to customize comparisons.
47622 * @param {Function} equalFunc The function to determine equivalents of values.
47623 * @param {Object} stack Tracks traversed `object` and `other` objects.
47624 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
47625 */
47626 function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) {
47627 switch (tag) {
47628 case dataViewTag:
47629 if ((object.byteLength != other.byteLength) ||
47630 (object.byteOffset != other.byteOffset)) {
47631 return false;
47632 }
47633 object = object.buffer;
47634 other = other.buffer;
47635
47636 case arrayBufferTag:
47637 if ((object.byteLength != other.byteLength) ||
47638 !equalFunc(new Uint8Array(object), new Uint8Array(other))) {
47639 return false;
47640 }
47641 return true;
47642
47643 case boolTag:
47644 case dateTag:
47645 case numberTag:
47646 // Coerce booleans to `1` or `0` and dates to milliseconds.
47647 // Invalid dates are coerced to `NaN`.
47648 return eq(+object, +other);
47649
47650 case errorTag:
47651 return object.name == other.name && object.message == other.message;
47652
47653 case regexpTag:
47654 case stringTag:
47655 // Coerce regexes to strings and treat strings, primitives and objects,
47656 // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring
47657 // for more details.
47658 return object == (other + '');
47659
47660 case mapTag:
47661 var convert = mapToArray;
47662
47663 case setTag:
47664 var isPartial = bitmask & COMPARE_PARTIAL_FLAG;
47665 convert || (convert = setToArray);
47666
47667 if (object.size != other.size && !isPartial) {
47668 return false;
47669 }
47670 // Assume cyclic values are equal.
47671 var stacked = stack.get(object);
47672 if (stacked) {
47673 return stacked == other;
47674 }
47675 bitmask |= COMPARE_UNORDERED_FLAG;
47676
47677 // Recursively compare objects (susceptible to call stack limits).
47678 stack.set(object, other);
47679 var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack);
47680 stack['delete'](object);
47681 return result;
47682
47683 case symbolTag:
47684 if (symbolValueOf) {
47685 return symbolValueOf.call(object) == symbolValueOf.call(other);
47686 }
47687 }
47688 return false;
47689 }
47690
47691 /**
47692 * A specialized version of `baseIsEqualDeep` for objects with support for
47693 * partial deep comparisons.
47694 *
47695 * @private
47696 * @param {Object} object The object to compare.
47697 * @param {Object} other The other object to compare.
47698 * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details.
47699 * @param {Function} customizer The function to customize comparisons.
47700 * @param {Function} equalFunc The function to determine equivalents of values.
47701 * @param {Object} stack Tracks traversed `object` and `other` objects.
47702 * @returns {boolean} Returns `true` if the objects are equivalent, else `false`.
47703 */
47704 function equalObjects(object, other, bitmask, customizer, equalFunc, stack) {
47705 var isPartial = bitmask & COMPARE_PARTIAL_FLAG,
47706 objProps = getAllKeys(object),
47707 objLength = objProps.length,
47708 othProps = getAllKeys(other),
47709 othLength = othProps.length;
47710
47711 if (objLength != othLength && !isPartial) {
47712 return false;
47713 }
47714 var index = objLength;
47715 while (index--) {
47716 var key = objProps[index];
47717 if (!(isPartial ? key in other : hasOwnProperty.call(other, key))) {
47718 return false;
47719 }
47720 }
47721 // Check that cyclic values are equal.
47722 var objStacked = stack.get(object);
47723 var othStacked = stack.get(other);
47724 if (objStacked && othStacked) {
47725 return objStacked == other && othStacked == object;
47726 }
47727 var result = true;
47728 stack.set(object, other);
47729 stack.set(other, object);
47730
47731 var skipCtor = isPartial;
47732 while (++index < objLength) {
47733 key = objProps[index];
47734 var objValue = object[key],
47735 othValue = other[key];
47736
47737 if (customizer) {
47738 var compared = isPartial
47739 ? customizer(othValue, objValue, key, other, object, stack)
47740 : customizer(objValue, othValue, key, object, other, stack);
47741 }
47742 // Recursively compare objects (susceptible to call stack limits).
47743 if (!(compared === undefined
47744 ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack))
47745 : compared
47746 )) {
47747 result = false;
47748 break;
47749 }
47750 skipCtor || (skipCtor = key == 'constructor');
47751 }
47752 if (result && !skipCtor) {
47753 var objCtor = object.constructor,
47754 othCtor = other.constructor;
47755
47756 // Non `Object` object instances with different constructors are not equal.
47757 if (objCtor != othCtor &&
47758 ('constructor' in object && 'constructor' in other) &&
47759 !(typeof objCtor == 'function' && objCtor instanceof objCtor &&
47760 typeof othCtor == 'function' && othCtor instanceof othCtor)) {
47761 result = false;
47762 }
47763 }
47764 stack['delete'](object);
47765 stack['delete'](other);
47766 return result;
47767 }
47768
47769 /**
47770 * A specialized version of `baseRest` which flattens the rest array.
47771 *
47772 * @private
47773 * @param {Function} func The function to apply a rest parameter to.
47774 * @returns {Function} Returns the new function.
47775 */
47776 function flatRest(func) {
47777 return setToString(overRest(func, undefined, flatten), func + '');
47778 }
47779
47780 /**
47781 * Creates an array of own enumerable property names and symbols of `object`.
47782 *
47783 * @private
47784 * @param {Object} object The object to query.
47785 * @returns {Array} Returns the array of property names and symbols.
47786 */
47787 function getAllKeys(object) {
47788 return baseGetAllKeys(object, keys, getSymbols);
47789 }
47790
47791 /**
47792 * Creates an array of own and inherited enumerable property names and
47793 * symbols of `object`.
47794 *
47795 * @private
47796 * @param {Object} object The object to query.
47797 * @returns {Array} Returns the array of property names and symbols.
47798 */
47799 function getAllKeysIn(object) {
47800 return baseGetAllKeys(object, keysIn, getSymbolsIn);
47801 }
47802
47803 /**
47804 * Gets metadata for `func`.
47805 *
47806 * @private
47807 * @param {Function} func The function to query.
47808 * @returns {*} Returns the metadata for `func`.
47809 */
47810 var getData = !metaMap ? noop : function(func) {
47811 return metaMap.get(func);
47812 };
47813
47814 /**
47815 * Gets the name of `func`.
47816 *
47817 * @private
47818 * @param {Function} func The function to query.
47819 * @returns {string} Returns the function name.
47820 */
47821 function getFuncName(func) {
47822 var result = (func.name + ''),
47823 array = realNames[result],
47824 length = hasOwnProperty.call(realNames, result) ? array.length : 0;
47825
47826 while (length--) {
47827 var data = array[length],
47828 otherFunc = data.func;
47829 if (otherFunc == null || otherFunc == func) {
47830 return data.name;
47831 }
47832 }
47833 return result;
47834 }
47835
47836 /**
47837 * Gets the argument placeholder value for `func`.
47838 *
47839 * @private
47840 * @param {Function} func The function to inspect.
47841 * @returns {*} Returns the placeholder value.
47842 */
47843 function getHolder(func) {
47844 var object = hasOwnProperty.call(lodash, 'placeholder') ? lodash : func;
47845 return object.placeholder;
47846 }
47847
47848 /**
47849 * Gets the appropriate "iteratee" function. If `_.iteratee` is customized,
47850 * this function returns the custom method, otherwise it returns `baseIteratee`.
47851 * If arguments are provided, the chosen function is invoked with them and
47852 * its result is returned.
47853 *
47854 * @private
47855 * @param {*} [value] The value to convert to an iteratee.
47856 * @param {number} [arity] The arity of the created iteratee.
47857 * @returns {Function} Returns the chosen function or its result.
47858 */
47859 function getIteratee() {
47860 var result = lodash.iteratee || iteratee;
47861 result = result === iteratee ? baseIteratee : result;
47862 return arguments.length ? result(arguments[0], arguments[1]) : result;
47863 }
47864
47865 /**
47866 * Gets the data for `map`.
47867 *
47868 * @private
47869 * @param {Object} map The map to query.
47870 * @param {string} key The reference key.
47871 * @returns {*} Returns the map data.
47872 */
47873 function getMapData(map, key) {
47874 var data = map.__data__;
47875 return isKeyable(key)
47876 ? data[typeof key == 'string' ? 'string' : 'hash']
47877 : data.map;
47878 }
47879
47880 /**
47881 * Gets the property names, values, and compare flags of `object`.
47882 *
47883 * @private
47884 * @param {Object} object The object to query.
47885 * @returns {Array} Returns the match data of `object`.
47886 */
47887 function getMatchData(object) {
47888 var result = keys(object),
47889 length = result.length;
47890
47891 while (length--) {
47892 var key = result[length],
47893 value = object[key];
47894
47895 result[length] = [key, value, isStrictComparable(value)];
47896 }
47897 return result;
47898 }
47899
47900 /**
47901 * Gets the native function at `key` of `object`.
47902 *
47903 * @private
47904 * @param {Object} object The object to query.
47905 * @param {string} key The key of the method to get.
47906 * @returns {*} Returns the function if it's native, else `undefined`.
47907 */
47908 function getNative(object, key) {
47909 var value = getValue(object, key);
47910 return baseIsNative(value) ? value : undefined;
47911 }
47912
47913 /**
47914 * A specialized version of `baseGetTag` which ignores `Symbol.toStringTag` values.
47915 *
47916 * @private
47917 * @param {*} value The value to query.
47918 * @returns {string} Returns the raw `toStringTag`.
47919 */
47920 function getRawTag(value) {
47921 var isOwn = hasOwnProperty.call(value, symToStringTag),
47922 tag = value[symToStringTag];
47923
47924 try {
47925 value[symToStringTag] = undefined;
47926 var unmasked = true;
47927 } catch (e) {}
47928
47929 var result = nativeObjectToString.call(value);
47930 if (unmasked) {
47931 if (isOwn) {
47932 value[symToStringTag] = tag;
47933 } else {
47934 delete value[symToStringTag];
47935 }
47936 }
47937 return result;
47938 }
47939
47940 /**
47941 * Creates an array of the own enumerable symbols of `object`.
47942 *
47943 * @private
47944 * @param {Object} object The object to query.
47945 * @returns {Array} Returns the array of symbols.
47946 */
47947 var getSymbols = !nativeGetSymbols ? stubArray : function(object) {
47948 if (object == null) {
47949 return [];
47950 }
47951 object = Object(object);
47952 return arrayFilter(nativeGetSymbols(object), function(symbol) {
47953 return propertyIsEnumerable.call(object, symbol);
47954 });
47955 };
47956
47957 /**
47958 * Creates an array of the own and inherited enumerable symbols of `object`.
47959 *
47960 * @private
47961 * @param {Object} object The object to query.
47962 * @returns {Array} Returns the array of symbols.
47963 */
47964 var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) {
47965 var result = [];
47966 while (object) {
47967 arrayPush(result, getSymbols(object));
47968 object = getPrototype(object);
47969 }
47970 return result;
47971 };
47972
47973 /**
47974 * Gets the `toStringTag` of `value`.
47975 *
47976 * @private
47977 * @param {*} value The value to query.
47978 * @returns {string} Returns the `toStringTag`.
47979 */
47980 var getTag = baseGetTag;
47981
47982 // Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6.
47983 if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag) ||
47984 (Map && getTag(new Map) != mapTag) ||
47985 (Promise && getTag(Promise.resolve()) != promiseTag) ||
47986 (Set && getTag(new Set) != setTag) ||
47987 (WeakMap && getTag(new WeakMap) != weakMapTag)) {
47988 getTag = function(value) {
47989 var result = baseGetTag(value),
47990 Ctor = result == objectTag ? value.constructor : undefined,
47991 ctorString = Ctor ? toSource(Ctor) : '';
47992
47993 if (ctorString) {
47994 switch (ctorString) {
47995 case dataViewCtorString: return dataViewTag;
47996 case mapCtorString: return mapTag;
47997 case promiseCtorString: return promiseTag;
47998 case setCtorString: return setTag;
47999 case weakMapCtorString: return weakMapTag;
48000 }
48001 }
48002 return result;
48003 };
48004 }
48005
48006 /**
48007 * Gets the view, applying any `transforms` to the `start` and `end` positions.
48008 *
48009 * @private
48010 * @param {number} start The start of the view.
48011 * @param {number} end The end of the view.
48012 * @param {Array} transforms The transformations to apply to the view.
48013 * @returns {Object} Returns an object containing the `start` and `end`
48014 * positions of the view.
48015 */
48016 function getView(start, end, transforms) {
48017 var index = -1,
48018 length = transforms.length;
48019
48020 while (++index < length) {
48021 var data = transforms[index],
48022 size = data.size;
48023
48024 switch (data.type) {
48025 case 'drop': start += size; break;
48026 case 'dropRight': end -= size; break;
48027 case 'take': end = nativeMin(end, start + size); break;
48028 case 'takeRight': start = nativeMax(start, end - size); break;
48029 }
48030 }
48031 return { 'start': start, 'end': end };
48032 }
48033
48034 /**
48035 * Extracts wrapper details from the `source` body comment.
48036 *
48037 * @private
48038 * @param {string} source The source to inspect.
48039 * @returns {Array} Returns the wrapper details.
48040 */
48041 function getWrapDetails(source) {
48042 var match = source.match(reWrapDetails);
48043 return match ? match[1].split(reSplitDetails) : [];
48044 }
48045
48046 /**
48047 * Checks if `path` exists on `object`.
48048 *
48049 * @private
48050 * @param {Object} object The object to query.
48051 * @param {Array|string} path The path to check.
48052 * @param {Function} hasFunc The function to check properties.
48053 * @returns {boolean} Returns `true` if `path` exists, else `false`.
48054 */
48055 function hasPath(object, path, hasFunc) {
48056 path = castPath(path, object);
48057
48058 var index = -1,
48059 length = path.length,
48060 result = false;
48061
48062 while (++index < length) {
48063 var key = toKey(path[index]);
48064 if (!(result = object != null && hasFunc(object, key))) {
48065 break;
48066 }
48067 object = object[key];
48068 }
48069 if (result || ++index != length) {
48070 return result;
48071 }
48072 length = object == null ? 0 : object.length;
48073 return !!length && isLength(length) && isIndex(key, length) &&
48074 (isArray(object) || isArguments(object));
48075 }
48076
48077 /**
48078 * Initializes an array clone.
48079 *
48080 * @private
48081 * @param {Array} array The array to clone.
48082 * @returns {Array} Returns the initialized clone.
48083 */
48084 function initCloneArray(array) {
48085 var length = array.length,
48086 result = new array.constructor(length);
48087
48088 // Add properties assigned by `RegExp#exec`.
48089 if (length && typeof array[0] == 'string' && hasOwnProperty.call(array, 'index')) {
48090 result.index = array.index;
48091 result.input = array.input;
48092 }
48093 return result;
48094 }
48095
48096 /**
48097 * Initializes an object clone.
48098 *
48099 * @private
48100 * @param {Object} object The object to clone.
48101 * @returns {Object} Returns the initialized clone.
48102 */
48103 function initCloneObject(object) {
48104 return (typeof object.constructor == 'function' && !isPrototype(object))
48105 ? baseCreate(getPrototype(object))
48106 : {};
48107 }
48108
48109 /**
48110 * Initializes an object clone based on its `toStringTag`.
48111 *
48112 * **Note:** This function only supports cloning values with tags of
48113 * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`.
48114 *
48115 * @private
48116 * @param {Object} object The object to clone.
48117 * @param {string} tag The `toStringTag` of the object to clone.
48118 * @param {boolean} [isDeep] Specify a deep clone.
48119 * @returns {Object} Returns the initialized clone.
48120 */
48121 function initCloneByTag(object, tag, isDeep) {
48122 var Ctor = object.constructor;
48123 switch (tag) {
48124 case arrayBufferTag:
48125 return cloneArrayBuffer(object);
48126
48127 case boolTag:
48128 case dateTag:
48129 return new Ctor(+object);
48130
48131 case dataViewTag:
48132 return cloneDataView(object, isDeep);
48133
48134 case float32Tag: case float64Tag:
48135 case int8Tag: case int16Tag: case int32Tag:
48136 case uint8Tag: case uint8ClampedTag: case uint16Tag: case uint32Tag:
48137 return cloneTypedArray(object, isDeep);
48138
48139 case mapTag:
48140 return new Ctor;
48141
48142 case numberTag:
48143 case stringTag:
48144 return new Ctor(object);
48145
48146 case regexpTag:
48147 return cloneRegExp(object);
48148
48149 case setTag:
48150 return new Ctor;
48151
48152 case symbolTag:
48153 return cloneSymbol(object);
48154 }
48155 }
48156
48157 /**
48158 * Inserts wrapper `details` in a comment at the top of the `source` body.
48159 *
48160 * @private
48161 * @param {string} source The source to modify.
48162 * @returns {Array} details The details to insert.
48163 * @returns {string} Returns the modified source.
48164 */
48165 function insertWrapDetails(source, details) {
48166 var length = details.length;
48167 if (!length) {
48168 return source;
48169 }
48170 var lastIndex = length - 1;
48171 details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex];
48172 details = details.join(length > 2 ? ', ' : ' ');
48173 return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n');
48174 }
48175
48176 /**
48177 * Checks if `value` is a flattenable `arguments` object or array.
48178 *
48179 * @private
48180 * @param {*} value The value to check.
48181 * @returns {boolean} Returns `true` if `value` is flattenable, else `false`.
48182 */
48183 function isFlattenable(value) {
48184 return isArray(value) || isArguments(value) ||
48185 !!(spreadableSymbol && value && value[spreadableSymbol]);
48186 }
48187
48188 /**
48189 * Checks if `value` is a valid array-like index.
48190 *
48191 * @private
48192 * @param {*} value The value to check.
48193 * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index.
48194 * @returns {boolean} Returns `true` if `value` is a valid index, else `false`.
48195 */
48196 function isIndex(value, length) {
48197 var type = typeof value;
48198 length = length == null ? MAX_SAFE_INTEGER : length;
48199
48200 return !!length &&
48201 (type == 'number' ||
48202 (type != 'symbol' && reIsUint.test(value))) &&
48203 (value > -1 && value % 1 == 0 && value < length);
48204 }
48205
48206 /**
48207 * Checks if the given arguments are from an iteratee call.
48208 *
48209 * @private
48210 * @param {*} value The potential iteratee value argument.
48211 * @param {*} index The potential iteratee index or key argument.
48212 * @param {*} object The potential iteratee object argument.
48213 * @returns {boolean} Returns `true` if the arguments are from an iteratee call,
48214 * else `false`.
48215 */
48216 function isIterateeCall(value, index, object) {
48217 if (!isObject(object)) {
48218 return false;
48219 }
48220 var type = typeof index;
48221 if (type == 'number'
48222 ? (isArrayLike(object) && isIndex(index, object.length))
48223 : (type == 'string' && index in object)
48224 ) {
48225 return eq(object[index], value);
48226 }
48227 return false;
48228 }
48229
48230 /**
48231 * Checks if `value` is a property name and not a property path.
48232 *
48233 * @private
48234 * @param {*} value The value to check.
48235 * @param {Object} [object] The object to query keys on.
48236 * @returns {boolean} Returns `true` if `value` is a property name, else `false`.
48237 */
48238 function isKey(value, object) {
48239 if (isArray(value)) {
48240 return false;
48241 }
48242 var type = typeof value;
48243 if (type == 'number' || type == 'symbol' || type == 'boolean' ||
48244 value == null || isSymbol(value)) {
48245 return true;
48246 }
48247 return reIsPlainProp.test(value) || !reIsDeepProp.test(value) ||
48248 (object != null && value in Object(object));
48249 }
48250
48251 /**
48252 * Checks if `value` is suitable for use as unique object key.
48253 *
48254 * @private
48255 * @param {*} value The value to check.
48256 * @returns {boolean} Returns `true` if `value` is suitable, else `false`.
48257 */
48258 function isKeyable(value) {
48259 var type = typeof value;
48260 return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean')
48261 ? (value !== '__proto__')
48262 : (value === null);
48263 }
48264
48265 /**
48266 * Checks if `func` has a lazy counterpart.
48267 *
48268 * @private
48269 * @param {Function} func The function to check.
48270 * @returns {boolean} Returns `true` if `func` has a lazy counterpart,
48271 * else `false`.
48272 */
48273 function isLaziable(func) {
48274 var funcName = getFuncName(func),
48275 other = lodash[funcName];
48276
48277 if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) {
48278 return false;
48279 }
48280 if (func === other) {
48281 return true;
48282 }
48283 var data = getData(other);
48284 return !!data && func === data[0];
48285 }
48286
48287 /**
48288 * Checks if `func` has its source masked.
48289 *
48290 * @private
48291 * @param {Function} func The function to check.
48292 * @returns {boolean} Returns `true` if `func` is masked, else `false`.
48293 */
48294 function isMasked(func) {
48295 return !!maskSrcKey && (maskSrcKey in func);
48296 }
48297
48298 /**
48299 * Checks if `func` is capable of being masked.
48300 *
48301 * @private
48302 * @param {*} value The value to check.
48303 * @returns {boolean} Returns `true` if `func` is maskable, else `false`.
48304 */
48305 var isMaskable = coreJsData ? isFunction : stubFalse;
48306
48307 /**
48308 * Checks if `value` is likely a prototype object.
48309 *
48310 * @private
48311 * @param {*} value The value to check.
48312 * @returns {boolean} Returns `true` if `value` is a prototype, else `false`.
48313 */
48314 function isPrototype(value) {
48315 var Ctor = value && value.constructor,
48316 proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto;
48317
48318 return value === proto;
48319 }
48320
48321 /**
48322 * Checks if `value` is suitable for strict equality comparisons, i.e. `===`.
48323 *
48324 * @private
48325 * @param {*} value The value to check.
48326 * @returns {boolean} Returns `true` if `value` if suitable for strict
48327 * equality comparisons, else `false`.
48328 */
48329 function isStrictComparable(value) {
48330 return value === value && !isObject(value);
48331 }
48332
48333 /**
48334 * A specialized version of `matchesProperty` for source values suitable
48335 * for strict equality comparisons, i.e. `===`.
48336 *
48337 * @private
48338 * @param {string} key The key of the property to get.
48339 * @param {*} srcValue The value to match.
48340 * @returns {Function} Returns the new spec function.
48341 */
48342 function matchesStrictComparable(key, srcValue) {
48343 return function(object) {
48344 if (object == null) {
48345 return false;
48346 }
48347 return object[key] === srcValue &&
48348 (srcValue !== undefined || (key in Object(object)));
48349 };
48350 }
48351
48352 /**
48353 * A specialized version of `_.memoize` which clears the memoized function's
48354 * cache when it exceeds `MAX_MEMOIZE_SIZE`.
48355 *
48356 * @private
48357 * @param {Function} func The function to have its output memoized.
48358 * @returns {Function} Returns the new memoized function.
48359 */
48360 function memoizeCapped(func) {
48361 var result = memoize(func, function(key) {
48362 if (cache.size === MAX_MEMOIZE_SIZE) {
48363 cache.clear();
48364 }
48365 return key;
48366 });
48367
48368 var cache = result.cache;
48369 return result;
48370 }
48371
48372 /**
48373 * Merges the function metadata of `source` into `data`.
48374 *
48375 * Merging metadata reduces the number of wrappers used to invoke a function.
48376 * This is possible because methods like `_.bind`, `_.curry`, and `_.partial`
48377 * may be applied regardless of execution order. Methods like `_.ary` and
48378 * `_.rearg` modify function arguments, making the order in which they are
48379 * executed important, preventing the merging of metadata. However, we make
48380 * an exception for a safe combined case where curried functions have `_.ary`
48381 * and or `_.rearg` applied.
48382 *
48383 * @private
48384 * @param {Array} data The destination metadata.
48385 * @param {Array} source The source metadata.
48386 * @returns {Array} Returns `data`.
48387 */
48388 function mergeData(data, source) {
48389 var bitmask = data[1],
48390 srcBitmask = source[1],
48391 newBitmask = bitmask | srcBitmask,
48392 isCommon = newBitmask < (WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG | WRAP_ARY_FLAG);
48393
48394 var isCombo =
48395 ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_CURRY_FLAG)) ||
48396 ((srcBitmask == WRAP_ARY_FLAG) && (bitmask == WRAP_REARG_FLAG) && (data[7].length <= source[8])) ||
48397 ((srcBitmask == (WRAP_ARY_FLAG | WRAP_REARG_FLAG)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG));
48398
48399 // Exit early if metadata can't be merged.
48400 if (!(isCommon || isCombo)) {
48401 return data;
48402 }
48403 // Use source `thisArg` if available.
48404 if (srcBitmask & WRAP_BIND_FLAG) {
48405 data[2] = source[2];
48406 // Set when currying a bound function.
48407 newBitmask |= bitmask & WRAP_BIND_FLAG ? 0 : WRAP_CURRY_BOUND_FLAG;
48408 }
48409 // Compose partial arguments.
48410 var value = source[3];
48411 if (value) {
48412 var partials = data[3];
48413 data[3] = partials ? composeArgs(partials, value, source[4]) : value;
48414 data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4];
48415 }
48416 // Compose partial right arguments.
48417 value = source[5];
48418 if (value) {
48419 partials = data[5];
48420 data[5] = partials ? composeArgsRight(partials, value, source[6]) : value;
48421 data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6];
48422 }
48423 // Use source `argPos` if available.
48424 value = source[7];
48425 if (value) {
48426 data[7] = value;
48427 }
48428 // Use source `ary` if it's smaller.
48429 if (srcBitmask & WRAP_ARY_FLAG) {
48430 data[8] = data[8] == null ? source[8] : nativeMin(data[8], source[8]);
48431 }
48432 // Use source `arity` if one is not provided.
48433 if (data[9] == null) {
48434 data[9] = source[9];
48435 }
48436 // Use source `func` and merge bitmasks.
48437 data[0] = source[0];
48438 data[1] = newBitmask;
48439
48440 return data;
48441 }
48442
48443 /**
48444 * This function is like
48445 * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
48446 * except that it includes inherited enumerable properties.
48447 *
48448 * @private
48449 * @param {Object} object The object to query.
48450 * @returns {Array} Returns the array of property names.
48451 */
48452 function nativeKeysIn(object) {
48453 var result = [];
48454 if (object != null) {
48455 for (var key in Object(object)) {
48456 result.push(key);
48457 }
48458 }
48459 return result;
48460 }
48461
48462 /**
48463 * Converts `value` to a string using `Object.prototype.toString`.
48464 *
48465 * @private
48466 * @param {*} value The value to convert.
48467 * @returns {string} Returns the converted string.
48468 */
48469 function objectToString(value) {
48470 return nativeObjectToString.call(value);
48471 }
48472
48473 /**
48474 * A specialized version of `baseRest` which transforms the rest array.
48475 *
48476 * @private
48477 * @param {Function} func The function to apply a rest parameter to.
48478 * @param {number} [start=func.length-1] The start position of the rest parameter.
48479 * @param {Function} transform The rest array transform.
48480 * @returns {Function} Returns the new function.
48481 */
48482 function overRest(func, start, transform) {
48483 start = nativeMax(start === undefined ? (func.length - 1) : start, 0);
48484 return function() {
48485 var args = arguments,
48486 index = -1,
48487 length = nativeMax(args.length - start, 0),
48488 array = Array(length);
48489
48490 while (++index < length) {
48491 array[index] = args[start + index];
48492 }
48493 index = -1;
48494 var otherArgs = Array(start + 1);
48495 while (++index < start) {
48496 otherArgs[index] = args[index];
48497 }
48498 otherArgs[start] = transform(array);
48499 return apply(func, this, otherArgs);
48500 };
48501 }
48502
48503 /**
48504 * Gets the parent value at `path` of `object`.
48505 *
48506 * @private
48507 * @param {Object} object The object to query.
48508 * @param {Array} path The path to get the parent value of.
48509 * @returns {*} Returns the parent value.
48510 */
48511 function parent(object, path) {
48512 return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1));
48513 }
48514
48515 /**
48516 * Reorder `array` according to the specified indexes where the element at
48517 * the first index is assigned as the first element, the element at
48518 * the second index is assigned as the second element, and so on.
48519 *
48520 * @private
48521 * @param {Array} array The array to reorder.
48522 * @param {Array} indexes The arranged array indexes.
48523 * @returns {Array} Returns `array`.
48524 */
48525 function reorder(array, indexes) {
48526 var arrLength = array.length,
48527 length = nativeMin(indexes.length, arrLength),
48528 oldArray = copyArray(array);
48529
48530 while (length--) {
48531 var index = indexes[length];
48532 array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined;
48533 }
48534 return array;
48535 }
48536
48537 /**
48538 * Gets the value at `key`, unless `key` is "__proto__" or "constructor".
48539 *
48540 * @private
48541 * @param {Object} object The object to query.
48542 * @param {string} key The key of the property to get.
48543 * @returns {*} Returns the property value.
48544 */
48545 function safeGet(object, key) {
48546 if (key === 'constructor' && typeof object[key] === 'function') {
48547 return;
48548 }
48549
48550 if (key == '__proto__') {
48551 return;
48552 }
48553
48554 return object[key];
48555 }
48556
48557 /**
48558 * Sets metadata for `func`.
48559 *
48560 * **Note:** If this function becomes hot, i.e. is invoked a lot in a short
48561 * period of time, it will trip its breaker and transition to an identity
48562 * function to avoid garbage collection pauses in V8. See
48563 * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070)
48564 * for more details.
48565 *
48566 * @private
48567 * @param {Function} func The function to associate metadata with.
48568 * @param {*} data The metadata.
48569 * @returns {Function} Returns `func`.
48570 */
48571 var setData = shortOut(baseSetData);
48572
48573 /**
48574 * A simple wrapper around the global [`setTimeout`](https://mdn.io/setTimeout).
48575 *
48576 * @private
48577 * @param {Function} func The function to delay.
48578 * @param {number} wait The number of milliseconds to delay invocation.
48579 * @returns {number|Object} Returns the timer id or timeout object.
48580 */
48581 var setTimeout = ctxSetTimeout || function(func, wait) {
48582 return root.setTimeout(func, wait);
48583 };
48584
48585 /**
48586 * Sets the `toString` method of `func` to return `string`.
48587 *
48588 * @private
48589 * @param {Function} func The function to modify.
48590 * @param {Function} string The `toString` result.
48591 * @returns {Function} Returns `func`.
48592 */
48593 var setToString = shortOut(baseSetToString);
48594
48595 /**
48596 * Sets the `toString` method of `wrapper` to mimic the source of `reference`
48597 * with wrapper details in a comment at the top of the source body.
48598 *
48599 * @private
48600 * @param {Function} wrapper The function to modify.
48601 * @param {Function} reference The reference function.
48602 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
48603 * @returns {Function} Returns `wrapper`.
48604 */
48605 function setWrapToString(wrapper, reference, bitmask) {
48606 var source = (reference + '');
48607 return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask)));
48608 }
48609
48610 /**
48611 * Creates a function that'll short out and invoke `identity` instead
48612 * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN`
48613 * milliseconds.
48614 *
48615 * @private
48616 * @param {Function} func The function to restrict.
48617 * @returns {Function} Returns the new shortable function.
48618 */
48619 function shortOut(func) {
48620 var count = 0,
48621 lastCalled = 0;
48622
48623 return function() {
48624 var stamp = nativeNow(),
48625 remaining = HOT_SPAN - (stamp - lastCalled);
48626
48627 lastCalled = stamp;
48628 if (remaining > 0) {
48629 if (++count >= HOT_COUNT) {
48630 return arguments[0];
48631 }
48632 } else {
48633 count = 0;
48634 }
48635 return func.apply(undefined, arguments);
48636 };
48637 }
48638
48639 /**
48640 * A specialized version of `_.shuffle` which mutates and sets the size of `array`.
48641 *
48642 * @private
48643 * @param {Array} array The array to shuffle.
48644 * @param {number} [size=array.length] The size of `array`.
48645 * @returns {Array} Returns `array`.
48646 */
48647 function shuffleSelf(array, size) {
48648 var index = -1,
48649 length = array.length,
48650 lastIndex = length - 1;
48651
48652 size = size === undefined ? length : size;
48653 while (++index < size) {
48654 var rand = baseRandom(index, lastIndex),
48655 value = array[rand];
48656
48657 array[rand] = array[index];
48658 array[index] = value;
48659 }
48660 array.length = size;
48661 return array;
48662 }
48663
48664 /**
48665 * Converts `string` to a property path array.
48666 *
48667 * @private
48668 * @param {string} string The string to convert.
48669 * @returns {Array} Returns the property path array.
48670 */
48671 var stringToPath = memoizeCapped(function(string) {
48672 var result = [];
48673 if (string.charCodeAt(0) === 46 /* . */) {
48674 result.push('');
48675 }
48676 string.replace(rePropName, function(match, number, quote, subString) {
48677 result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match));
48678 });
48679 return result;
48680 });
48681
48682 /**
48683 * Converts `value` to a string key if it's not a string or symbol.
48684 *
48685 * @private
48686 * @param {*} value The value to inspect.
48687 * @returns {string|symbol} Returns the key.
48688 */
48689 function toKey(value) {
48690 if (typeof value == 'string' || isSymbol(value)) {
48691 return value;
48692 }
48693 var result = (value + '');
48694 return (result == '0' && (1 / value) == -INFINITY) ? '-0' : result;
48695 }
48696
48697 /**
48698 * Converts `func` to its source code.
48699 *
48700 * @private
48701 * @param {Function} func The function to convert.
48702 * @returns {string} Returns the source code.
48703 */
48704 function toSource(func) {
48705 if (func != null) {
48706 try {
48707 return funcToString.call(func);
48708 } catch (e) {}
48709 try {
48710 return (func + '');
48711 } catch (e) {}
48712 }
48713 return '';
48714 }
48715
48716 /**
48717 * Updates wrapper `details` based on `bitmask` flags.
48718 *
48719 * @private
48720 * @returns {Array} details The details to modify.
48721 * @param {number} bitmask The bitmask flags. See `createWrap` for more details.
48722 * @returns {Array} Returns `details`.
48723 */
48724 function updateWrapDetails(details, bitmask) {
48725 arrayEach(wrapFlags, function(pair) {
48726 var value = '_.' + pair[0];
48727 if ((bitmask & pair[1]) && !arrayIncludes(details, value)) {
48728 details.push(value);
48729 }
48730 });
48731 return details.sort();
48732 }
48733
48734 /**
48735 * Creates a clone of `wrapper`.
48736 *
48737 * @private
48738 * @param {Object} wrapper The wrapper to clone.
48739 * @returns {Object} Returns the cloned wrapper.
48740 */
48741 function wrapperClone(wrapper) {
48742 if (wrapper instanceof LazyWrapper) {
48743 return wrapper.clone();
48744 }
48745 var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__);
48746 result.__actions__ = copyArray(wrapper.__actions__);
48747 result.__index__ = wrapper.__index__;
48748 result.__values__ = wrapper.__values__;
48749 return result;
48750 }
48751
48752 /*------------------------------------------------------------------------*/
48753
48754 /**
48755 * Creates an array of elements split into groups the length of `size`.
48756 * If `array` can't be split evenly, the final chunk will be the remaining
48757 * elements.
48758 *
48759 * @static
48760 * @memberOf _
48761 * @since 3.0.0
48762 * @category Array
48763 * @param {Array} array The array to process.
48764 * @param {number} [size=1] The length of each chunk
48765 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
48766 * @returns {Array} Returns the new array of chunks.
48767 * @example
48768 *
48769 * _.chunk(['a', 'b', 'c', 'd'], 2);
48770 * // => [['a', 'b'], ['c', 'd']]
48771 *
48772 * _.chunk(['a', 'b', 'c', 'd'], 3);
48773 * // => [['a', 'b', 'c'], ['d']]
48774 */
48775 function chunk(array, size, guard) {
48776 if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) {
48777 size = 1;
48778 } else {
48779 size = nativeMax(toInteger(size), 0);
48780 }
48781 var length = array == null ? 0 : array.length;
48782 if (!length || size < 1) {
48783 return [];
48784 }
48785 var index = 0,
48786 resIndex = 0,
48787 result = Array(nativeCeil(length / size));
48788
48789 while (index < length) {
48790 result[resIndex++] = baseSlice(array, index, (index += size));
48791 }
48792 return result;
48793 }
48794
48795 /**
48796 * Creates an array with all falsey values removed. The values `false`, `null`,
48797 * `0`, `""`, `undefined`, and `NaN` are falsey.
48798 *
48799 * @static
48800 * @memberOf _
48801 * @since 0.1.0
48802 * @category Array
48803 * @param {Array} array The array to compact.
48804 * @returns {Array} Returns the new array of filtered values.
48805 * @example
48806 *
48807 * _.compact([0, 1, false, 2, '', 3]);
48808 * // => [1, 2, 3]
48809 */
48810 function compact(array) {
48811 var index = -1,
48812 length = array == null ? 0 : array.length,
48813 resIndex = 0,
48814 result = [];
48815
48816 while (++index < length) {
48817 var value = array[index];
48818 if (value) {
48819 result[resIndex++] = value;
48820 }
48821 }
48822 return result;
48823 }
48824
48825 /**
48826 * Creates a new array concatenating `array` with any additional arrays
48827 * and/or values.
48828 *
48829 * @static
48830 * @memberOf _
48831 * @since 4.0.0
48832 * @category Array
48833 * @param {Array} array The array to concatenate.
48834 * @param {...*} [values] The values to concatenate.
48835 * @returns {Array} Returns the new concatenated array.
48836 * @example
48837 *
48838 * var array = [1];
48839 * var other = _.concat(array, 2, [3], [[4]]);
48840 *
48841 * console.log(other);
48842 * // => [1, 2, 3, [4]]
48843 *
48844 * console.log(array);
48845 * // => [1]
48846 */
48847 function concat() {
48848 var length = arguments.length;
48849 if (!length) {
48850 return [];
48851 }
48852 var args = Array(length - 1),
48853 array = arguments[0],
48854 index = length;
48855
48856 while (index--) {
48857 args[index - 1] = arguments[index];
48858 }
48859 return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1));
48860 }
48861
48862 /**
48863 * Creates an array of `array` values not included in the other given arrays
48864 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
48865 * for equality comparisons. The order and references of result values are
48866 * determined by the first array.
48867 *
48868 * **Note:** Unlike `_.pullAll`, this method returns a new array.
48869 *
48870 * @static
48871 * @memberOf _
48872 * @since 0.1.0
48873 * @category Array
48874 * @param {Array} array The array to inspect.
48875 * @param {...Array} [values] The values to exclude.
48876 * @returns {Array} Returns the new array of filtered values.
48877 * @see _.without, _.xor
48878 * @example
48879 *
48880 * _.difference([2, 1], [2, 3]);
48881 * // => [1]
48882 */
48883 var difference = baseRest(function(array, values) {
48884 return isArrayLikeObject(array)
48885 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true))
48886 : [];
48887 });
48888
48889 /**
48890 * This method is like `_.difference` except that it accepts `iteratee` which
48891 * is invoked for each element of `array` and `values` to generate the criterion
48892 * by which they're compared. The order and references of result values are
48893 * determined by the first array. The iteratee is invoked with one argument:
48894 * (value).
48895 *
48896 * **Note:** Unlike `_.pullAllBy`, this method returns a new array.
48897 *
48898 * @static
48899 * @memberOf _
48900 * @since 4.0.0
48901 * @category Array
48902 * @param {Array} array The array to inspect.
48903 * @param {...Array} [values] The values to exclude.
48904 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
48905 * @returns {Array} Returns the new array of filtered values.
48906 * @example
48907 *
48908 * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
48909 * // => [1.2]
48910 *
48911 * // The `_.property` iteratee shorthand.
48912 * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x');
48913 * // => [{ 'x': 2 }]
48914 */
48915 var differenceBy = baseRest(function(array, values) {
48916 var iteratee = last(values);
48917 if (isArrayLikeObject(iteratee)) {
48918 iteratee = undefined;
48919 }
48920 return isArrayLikeObject(array)
48921 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), getIteratee(iteratee, 2))
48922 : [];
48923 });
48924
48925 /**
48926 * This method is like `_.difference` except that it accepts `comparator`
48927 * which is invoked to compare elements of `array` to `values`. The order and
48928 * references of result values are determined by the first array. The comparator
48929 * is invoked with two arguments: (arrVal, othVal).
48930 *
48931 * **Note:** Unlike `_.pullAllWith`, this method returns a new array.
48932 *
48933 * @static
48934 * @memberOf _
48935 * @since 4.0.0
48936 * @category Array
48937 * @param {Array} array The array to inspect.
48938 * @param {...Array} [values] The values to exclude.
48939 * @param {Function} [comparator] The comparator invoked per element.
48940 * @returns {Array} Returns the new array of filtered values.
48941 * @example
48942 *
48943 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
48944 *
48945 * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual);
48946 * // => [{ 'x': 2, 'y': 1 }]
48947 */
48948 var differenceWith = baseRest(function(array, values) {
48949 var comparator = last(values);
48950 if (isArrayLikeObject(comparator)) {
48951 comparator = undefined;
48952 }
48953 return isArrayLikeObject(array)
48954 ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator)
48955 : [];
48956 });
48957
48958 /**
48959 * Creates a slice of `array` with `n` elements dropped from the beginning.
48960 *
48961 * @static
48962 * @memberOf _
48963 * @since 0.5.0
48964 * @category Array
48965 * @param {Array} array The array to query.
48966 * @param {number} [n=1] The number of elements to drop.
48967 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
48968 * @returns {Array} Returns the slice of `array`.
48969 * @example
48970 *
48971 * _.drop([1, 2, 3]);
48972 * // => [2, 3]
48973 *
48974 * _.drop([1, 2, 3], 2);
48975 * // => [3]
48976 *
48977 * _.drop([1, 2, 3], 5);
48978 * // => []
48979 *
48980 * _.drop([1, 2, 3], 0);
48981 * // => [1, 2, 3]
48982 */
48983 function drop(array, n, guard) {
48984 var length = array == null ? 0 : array.length;
48985 if (!length) {
48986 return [];
48987 }
48988 n = (guard || n === undefined) ? 1 : toInteger(n);
48989 return baseSlice(array, n < 0 ? 0 : n, length);
48990 }
48991
48992 /**
48993 * Creates a slice of `array` with `n` elements dropped from the end.
48994 *
48995 * @static
48996 * @memberOf _
48997 * @since 3.0.0
48998 * @category Array
48999 * @param {Array} array The array to query.
49000 * @param {number} [n=1] The number of elements to drop.
49001 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
49002 * @returns {Array} Returns the slice of `array`.
49003 * @example
49004 *
49005 * _.dropRight([1, 2, 3]);
49006 * // => [1, 2]
49007 *
49008 * _.dropRight([1, 2, 3], 2);
49009 * // => [1]
49010 *
49011 * _.dropRight([1, 2, 3], 5);
49012 * // => []
49013 *
49014 * _.dropRight([1, 2, 3], 0);
49015 * // => [1, 2, 3]
49016 */
49017 function dropRight(array, n, guard) {
49018 var length = array == null ? 0 : array.length;
49019 if (!length) {
49020 return [];
49021 }
49022 n = (guard || n === undefined) ? 1 : toInteger(n);
49023 n = length - n;
49024 return baseSlice(array, 0, n < 0 ? 0 : n);
49025 }
49026
49027 /**
49028 * Creates a slice of `array` excluding elements dropped from the end.
49029 * Elements are dropped until `predicate` returns falsey. The predicate is
49030 * invoked with three arguments: (value, index, array).
49031 *
49032 * @static
49033 * @memberOf _
49034 * @since 3.0.0
49035 * @category Array
49036 * @param {Array} array The array to query.
49037 * @param {Function} [predicate=_.identity] The function invoked per iteration.
49038 * @returns {Array} Returns the slice of `array`.
49039 * @example
49040 *
49041 * var users = [
49042 * { 'user': 'barney', 'active': true },
49043 * { 'user': 'fred', 'active': false },
49044 * { 'user': 'pebbles', 'active': false }
49045 * ];
49046 *
49047 * _.dropRightWhile(users, function(o) { return !o.active; });
49048 * // => objects for ['barney']
49049 *
49050 * // The `_.matches` iteratee shorthand.
49051 * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false });
49052 * // => objects for ['barney', 'fred']
49053 *
49054 * // The `_.matchesProperty` iteratee shorthand.
49055 * _.dropRightWhile(users, ['active', false]);
49056 * // => objects for ['barney']
49057 *
49058 * // The `_.property` iteratee shorthand.
49059 * _.dropRightWhile(users, 'active');
49060 * // => objects for ['barney', 'fred', 'pebbles']
49061 */
49062 function dropRightWhile(array, predicate) {
49063 return (array && array.length)
49064 ? baseWhile(array, getIteratee(predicate, 3), true, true)
49065 : [];
49066 }
49067
49068 /**
49069 * Creates a slice of `array` excluding elements dropped from the beginning.
49070 * Elements are dropped until `predicate` returns falsey. The predicate is
49071 * invoked with three arguments: (value, index, array).
49072 *
49073 * @static
49074 * @memberOf _
49075 * @since 3.0.0
49076 * @category Array
49077 * @param {Array} array The array to query.
49078 * @param {Function} [predicate=_.identity] The function invoked per iteration.
49079 * @returns {Array} Returns the slice of `array`.
49080 * @example
49081 *
49082 * var users = [
49083 * { 'user': 'barney', 'active': false },
49084 * { 'user': 'fred', 'active': false },
49085 * { 'user': 'pebbles', 'active': true }
49086 * ];
49087 *
49088 * _.dropWhile(users, function(o) { return !o.active; });
49089 * // => objects for ['pebbles']
49090 *
49091 * // The `_.matches` iteratee shorthand.
49092 * _.dropWhile(users, { 'user': 'barney', 'active': false });
49093 * // => objects for ['fred', 'pebbles']
49094 *
49095 * // The `_.matchesProperty` iteratee shorthand.
49096 * _.dropWhile(users, ['active', false]);
49097 * // => objects for ['pebbles']
49098 *
49099 * // The `_.property` iteratee shorthand.
49100 * _.dropWhile(users, 'active');
49101 * // => objects for ['barney', 'fred', 'pebbles']
49102 */
49103 function dropWhile(array, predicate) {
49104 return (array && array.length)
49105 ? baseWhile(array, getIteratee(predicate, 3), true)
49106 : [];
49107 }
49108
49109 /**
49110 * Fills elements of `array` with `value` from `start` up to, but not
49111 * including, `end`.
49112 *
49113 * **Note:** This method mutates `array`.
49114 *
49115 * @static
49116 * @memberOf _
49117 * @since 3.2.0
49118 * @category Array
49119 * @param {Array} array The array to fill.
49120 * @param {*} value The value to fill `array` with.
49121 * @param {number} [start=0] The start position.
49122 * @param {number} [end=array.length] The end position.
49123 * @returns {Array} Returns `array`.
49124 * @example
49125 *
49126 * var array = [1, 2, 3];
49127 *
49128 * _.fill(array, 'a');
49129 * console.log(array);
49130 * // => ['a', 'a', 'a']
49131 *
49132 * _.fill(Array(3), 2);
49133 * // => [2, 2, 2]
49134 *
49135 * _.fill([4, 6, 8, 10], '*', 1, 3);
49136 * // => [4, '*', '*', 10]
49137 */
49138 function fill(array, value, start, end) {
49139 var length = array == null ? 0 : array.length;
49140 if (!length) {
49141 return [];
49142 }
49143 if (start && typeof start != 'number' && isIterateeCall(array, value, start)) {
49144 start = 0;
49145 end = length;
49146 }
49147 return baseFill(array, value, start, end);
49148 }
49149
49150 /**
49151 * This method is like `_.find` except that it returns the index of the first
49152 * element `predicate` returns truthy for instead of the element itself.
49153 *
49154 * @static
49155 * @memberOf _
49156 * @since 1.1.0
49157 * @category Array
49158 * @param {Array} array The array to inspect.
49159 * @param {Function} [predicate=_.identity] The function invoked per iteration.
49160 * @param {number} [fromIndex=0] The index to search from.
49161 * @returns {number} Returns the index of the found element, else `-1`.
49162 * @example
49163 *
49164 * var users = [
49165 * { 'user': 'barney', 'active': false },
49166 * { 'user': 'fred', 'active': false },
49167 * { 'user': 'pebbles', 'active': true }
49168 * ];
49169 *
49170 * _.findIndex(users, function(o) { return o.user == 'barney'; });
49171 * // => 0
49172 *
49173 * // The `_.matches` iteratee shorthand.
49174 * _.findIndex(users, { 'user': 'fred', 'active': false });
49175 * // => 1
49176 *
49177 * // The `_.matchesProperty` iteratee shorthand.
49178 * _.findIndex(users, ['active', false]);
49179 * // => 0
49180 *
49181 * // The `_.property` iteratee shorthand.
49182 * _.findIndex(users, 'active');
49183 * // => 2
49184 */
49185 function findIndex(array, predicate, fromIndex) {
49186 var length = array == null ? 0 : array.length;
49187 if (!length) {
49188 return -1;
49189 }
49190 var index = fromIndex == null ? 0 : toInteger(fromIndex);
49191 if (index < 0) {
49192 index = nativeMax(length + index, 0);
49193 }
49194 return baseFindIndex(array, getIteratee(predicate, 3), index);
49195 }
49196
49197 /**
49198 * This method is like `_.findIndex` except that it iterates over elements
49199 * of `collection` from right to left.
49200 *
49201 * @static
49202 * @memberOf _
49203 * @since 2.0.0
49204 * @category Array
49205 * @param {Array} array The array to inspect.
49206 * @param {Function} [predicate=_.identity] The function invoked per iteration.
49207 * @param {number} [fromIndex=array.length-1] The index to search from.
49208 * @returns {number} Returns the index of the found element, else `-1`.
49209 * @example
49210 *
49211 * var users = [
49212 * { 'user': 'barney', 'active': true },
49213 * { 'user': 'fred', 'active': false },
49214 * { 'user': 'pebbles', 'active': false }
49215 * ];
49216 *
49217 * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; });
49218 * // => 2
49219 *
49220 * // The `_.matches` iteratee shorthand.
49221 * _.findLastIndex(users, { 'user': 'barney', 'active': true });
49222 * // => 0
49223 *
49224 * // The `_.matchesProperty` iteratee shorthand.
49225 * _.findLastIndex(users, ['active', false]);
49226 * // => 2
49227 *
49228 * // The `_.property` iteratee shorthand.
49229 * _.findLastIndex(users, 'active');
49230 * // => 0
49231 */
49232 function findLastIndex(array, predicate, fromIndex) {
49233 var length = array == null ? 0 : array.length;
49234 if (!length) {
49235 return -1;
49236 }
49237 var index = length - 1;
49238 if (fromIndex !== undefined) {
49239 index = toInteger(fromIndex);
49240 index = fromIndex < 0
49241 ? nativeMax(length + index, 0)
49242 : nativeMin(index, length - 1);
49243 }
49244 return baseFindIndex(array, getIteratee(predicate, 3), index, true);
49245 }
49246
49247 /**
49248 * Flattens `array` a single level deep.
49249 *
49250 * @static
49251 * @memberOf _
49252 * @since 0.1.0
49253 * @category Array
49254 * @param {Array} array The array to flatten.
49255 * @returns {Array} Returns the new flattened array.
49256 * @example
49257 *
49258 * _.flatten([1, [2, [3, [4]], 5]]);
49259 * // => [1, 2, [3, [4]], 5]
49260 */
49261 function flatten(array) {
49262 var length = array == null ? 0 : array.length;
49263 return length ? baseFlatten(array, 1) : [];
49264 }
49265
49266 /**
49267 * Recursively flattens `array`.
49268 *
49269 * @static
49270 * @memberOf _
49271 * @since 3.0.0
49272 * @category Array
49273 * @param {Array} array The array to flatten.
49274 * @returns {Array} Returns the new flattened array.
49275 * @example
49276 *
49277 * _.flattenDeep([1, [2, [3, [4]], 5]]);
49278 * // => [1, 2, 3, 4, 5]
49279 */
49280 function flattenDeep(array) {
49281 var length = array == null ? 0 : array.length;
49282 return length ? baseFlatten(array, INFINITY) : [];
49283 }
49284
49285 /**
49286 * Recursively flatten `array` up to `depth` times.
49287 *
49288 * @static
49289 * @memberOf _
49290 * @since 4.4.0
49291 * @category Array
49292 * @param {Array} array The array to flatten.
49293 * @param {number} [depth=1] The maximum recursion depth.
49294 * @returns {Array} Returns the new flattened array.
49295 * @example
49296 *
49297 * var array = [1, [2, [3, [4]], 5]];
49298 *
49299 * _.flattenDepth(array, 1);
49300 * // => [1, 2, [3, [4]], 5]
49301 *
49302 * _.flattenDepth(array, 2);
49303 * // => [1, 2, 3, [4], 5]
49304 */
49305 function flattenDepth(array, depth) {
49306 var length = array == null ? 0 : array.length;
49307 if (!length) {
49308 return [];
49309 }
49310 depth = depth === undefined ? 1 : toInteger(depth);
49311 return baseFlatten(array, depth);
49312 }
49313
49314 /**
49315 * The inverse of `_.toPairs`; this method returns an object composed
49316 * from key-value `pairs`.
49317 *
49318 * @static
49319 * @memberOf _
49320 * @since 4.0.0
49321 * @category Array
49322 * @param {Array} pairs The key-value pairs.
49323 * @returns {Object} Returns the new object.
49324 * @example
49325 *
49326 * _.fromPairs([['a', 1], ['b', 2]]);
49327 * // => { 'a': 1, 'b': 2 }
49328 */
49329 function fromPairs(pairs) {
49330 var index = -1,
49331 length = pairs == null ? 0 : pairs.length,
49332 result = {};
49333
49334 while (++index < length) {
49335 var pair = pairs[index];
49336 result[pair[0]] = pair[1];
49337 }
49338 return result;
49339 }
49340
49341 /**
49342 * Gets the first element of `array`.
49343 *
49344 * @static
49345 * @memberOf _
49346 * @since 0.1.0
49347 * @alias first
49348 * @category Array
49349 * @param {Array} array The array to query.
49350 * @returns {*} Returns the first element of `array`.
49351 * @example
49352 *
49353 * _.head([1, 2, 3]);
49354 * // => 1
49355 *
49356 * _.head([]);
49357 * // => undefined
49358 */
49359 function head(array) {
49360 return (array && array.length) ? array[0] : undefined;
49361 }
49362
49363 /**
49364 * Gets the index at which the first occurrence of `value` is found in `array`
49365 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
49366 * for equality comparisons. If `fromIndex` is negative, it's used as the
49367 * offset from the end of `array`.
49368 *
49369 * @static
49370 * @memberOf _
49371 * @since 0.1.0
49372 * @category Array
49373 * @param {Array} array The array to inspect.
49374 * @param {*} value The value to search for.
49375 * @param {number} [fromIndex=0] The index to search from.
49376 * @returns {number} Returns the index of the matched value, else `-1`.
49377 * @example
49378 *
49379 * _.indexOf([1, 2, 1, 2], 2);
49380 * // => 1
49381 *
49382 * // Search from the `fromIndex`.
49383 * _.indexOf([1, 2, 1, 2], 2, 2);
49384 * // => 3
49385 */
49386 function indexOf(array, value, fromIndex) {
49387 var length = array == null ? 0 : array.length;
49388 if (!length) {
49389 return -1;
49390 }
49391 var index = fromIndex == null ? 0 : toInteger(fromIndex);
49392 if (index < 0) {
49393 index = nativeMax(length + index, 0);
49394 }
49395 return baseIndexOf(array, value, index);
49396 }
49397
49398 /**
49399 * Gets all but the last element of `array`.
49400 *
49401 * @static
49402 * @memberOf _
49403 * @since 0.1.0
49404 * @category Array
49405 * @param {Array} array The array to query.
49406 * @returns {Array} Returns the slice of `array`.
49407 * @example
49408 *
49409 * _.initial([1, 2, 3]);
49410 * // => [1, 2]
49411 */
49412 function initial(array) {
49413 var length = array == null ? 0 : array.length;
49414 return length ? baseSlice(array, 0, -1) : [];
49415 }
49416
49417 /**
49418 * Creates an array of unique values that are included in all given arrays
49419 * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
49420 * for equality comparisons. The order and references of result values are
49421 * determined by the first array.
49422 *
49423 * @static
49424 * @memberOf _
49425 * @since 0.1.0
49426 * @category Array
49427 * @param {...Array} [arrays] The arrays to inspect.
49428 * @returns {Array} Returns the new array of intersecting values.
49429 * @example
49430 *
49431 * _.intersection([2, 1], [2, 3]);
49432 * // => [2]
49433 */
49434 var intersection = baseRest(function(arrays) {
49435 var mapped = arrayMap(arrays, castArrayLikeObject);
49436 return (mapped.length && mapped[0] === arrays[0])
49437 ? baseIntersection(mapped)
49438 : [];
49439 });
49440
49441 /**
49442 * This method is like `_.intersection` except that it accepts `iteratee`
49443 * which is invoked for each element of each `arrays` to generate the criterion
49444 * by which they're compared. The order and references of result values are
49445 * determined by the first array. The iteratee is invoked with one argument:
49446 * (value).
49447 *
49448 * @static
49449 * @memberOf _
49450 * @since 4.0.0
49451 * @category Array
49452 * @param {...Array} [arrays] The arrays to inspect.
49453 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
49454 * @returns {Array} Returns the new array of intersecting values.
49455 * @example
49456 *
49457 * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
49458 * // => [2.1]
49459 *
49460 * // The `_.property` iteratee shorthand.
49461 * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
49462 * // => [{ 'x': 1 }]
49463 */
49464 var intersectionBy = baseRest(function(arrays) {
49465 var iteratee = last(arrays),
49466 mapped = arrayMap(arrays, castArrayLikeObject);
49467
49468 if (iteratee === last(mapped)) {
49469 iteratee = undefined;
49470 } else {
49471 mapped.pop();
49472 }
49473 return (mapped.length && mapped[0] === arrays[0])
49474 ? baseIntersection(mapped, getIteratee(iteratee, 2))
49475 : [];
49476 });
49477
49478 /**
49479 * This method is like `_.intersection` except that it accepts `comparator`
49480 * which is invoked to compare elements of `arrays`. The order and references
49481 * of result values are determined by the first array. The comparator is
49482 * invoked with two arguments: (arrVal, othVal).
49483 *
49484 * @static
49485 * @memberOf _
49486 * @since 4.0.0
49487 * @category Array
49488 * @param {...Array} [arrays] The arrays to inspect.
49489 * @param {Function} [comparator] The comparator invoked per element.
49490 * @returns {Array} Returns the new array of intersecting values.
49491 * @example
49492 *
49493 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
49494 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
49495 *
49496 * _.intersectionWith(objects, others, _.isEqual);
49497 * // => [{ 'x': 1, 'y': 2 }]
49498 */
49499 var intersectionWith = baseRest(function(arrays) {
49500 var comparator = last(arrays),
49501 mapped = arrayMap(arrays, castArrayLikeObject);
49502
49503 comparator = typeof comparator == 'function' ? comparator : undefined;
49504 if (comparator) {
49505 mapped.pop();
49506 }
49507 return (mapped.length && mapped[0] === arrays[0])
49508 ? baseIntersection(mapped, undefined, comparator)
49509 : [];
49510 });
49511
49512 /**
49513 * Converts all elements in `array` into a string separated by `separator`.
49514 *
49515 * @static
49516 * @memberOf _
49517 * @since 4.0.0
49518 * @category Array
49519 * @param {Array} array The array to convert.
49520 * @param {string} [separator=','] The element separator.
49521 * @returns {string} Returns the joined string.
49522 * @example
49523 *
49524 * _.join(['a', 'b', 'c'], '~');
49525 * // => 'a~b~c'
49526 */
49527 function join(array, separator) {
49528 return array == null ? '' : nativeJoin.call(array, separator);
49529 }
49530
49531 /**
49532 * Gets the last element of `array`.
49533 *
49534 * @static
49535 * @memberOf _
49536 * @since 0.1.0
49537 * @category Array
49538 * @param {Array} array The array to query.
49539 * @returns {*} Returns the last element of `array`.
49540 * @example
49541 *
49542 * _.last([1, 2, 3]);
49543 * // => 3
49544 */
49545 function last(array) {
49546 var length = array == null ? 0 : array.length;
49547 return length ? array[length - 1] : undefined;
49548 }
49549
49550 /**
49551 * This method is like `_.indexOf` except that it iterates over elements of
49552 * `array` from right to left.
49553 *
49554 * @static
49555 * @memberOf _
49556 * @since 0.1.0
49557 * @category Array
49558 * @param {Array} array The array to inspect.
49559 * @param {*} value The value to search for.
49560 * @param {number} [fromIndex=array.length-1] The index to search from.
49561 * @returns {number} Returns the index of the matched value, else `-1`.
49562 * @example
49563 *
49564 * _.lastIndexOf([1, 2, 1, 2], 2);
49565 * // => 3
49566 *
49567 * // Search from the `fromIndex`.
49568 * _.lastIndexOf([1, 2, 1, 2], 2, 2);
49569 * // => 1
49570 */
49571 function lastIndexOf(array, value, fromIndex) {
49572 var length = array == null ? 0 : array.length;
49573 if (!length) {
49574 return -1;
49575 }
49576 var index = length;
49577 if (fromIndex !== undefined) {
49578 index = toInteger(fromIndex);
49579 index = index < 0 ? nativeMax(length + index, 0) : nativeMin(index, length - 1);
49580 }
49581 return value === value
49582 ? strictLastIndexOf(array, value, index)
49583 : baseFindIndex(array, baseIsNaN, index, true);
49584 }
49585
49586 /**
49587 * Gets the element at index `n` of `array`. If `n` is negative, the nth
49588 * element from the end is returned.
49589 *
49590 * @static
49591 * @memberOf _
49592 * @since 4.11.0
49593 * @category Array
49594 * @param {Array} array The array to query.
49595 * @param {number} [n=0] The index of the element to return.
49596 * @returns {*} Returns the nth element of `array`.
49597 * @example
49598 *
49599 * var array = ['a', 'b', 'c', 'd'];
49600 *
49601 * _.nth(array, 1);
49602 * // => 'b'
49603 *
49604 * _.nth(array, -2);
49605 * // => 'c';
49606 */
49607 function nth(array, n) {
49608 return (array && array.length) ? baseNth(array, toInteger(n)) : undefined;
49609 }
49610
49611 /**
49612 * Removes all given values from `array` using
49613 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
49614 * for equality comparisons.
49615 *
49616 * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove`
49617 * to remove elements from an array by predicate.
49618 *
49619 * @static
49620 * @memberOf _
49621 * @since 2.0.0
49622 * @category Array
49623 * @param {Array} array The array to modify.
49624 * @param {...*} [values] The values to remove.
49625 * @returns {Array} Returns `array`.
49626 * @example
49627 *
49628 * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
49629 *
49630 * _.pull(array, 'a', 'c');
49631 * console.log(array);
49632 * // => ['b', 'b']
49633 */
49634 var pull = baseRest(pullAll);
49635
49636 /**
49637 * This method is like `_.pull` except that it accepts an array of values to remove.
49638 *
49639 * **Note:** Unlike `_.difference`, this method mutates `array`.
49640 *
49641 * @static
49642 * @memberOf _
49643 * @since 4.0.0
49644 * @category Array
49645 * @param {Array} array The array to modify.
49646 * @param {Array} values The values to remove.
49647 * @returns {Array} Returns `array`.
49648 * @example
49649 *
49650 * var array = ['a', 'b', 'c', 'a', 'b', 'c'];
49651 *
49652 * _.pullAll(array, ['a', 'c']);
49653 * console.log(array);
49654 * // => ['b', 'b']
49655 */
49656 function pullAll(array, values) {
49657 return (array && array.length && values && values.length)
49658 ? basePullAll(array, values)
49659 : array;
49660 }
49661
49662 /**
49663 * This method is like `_.pullAll` except that it accepts `iteratee` which is
49664 * invoked for each element of `array` and `values` to generate the criterion
49665 * by which they're compared. The iteratee is invoked with one argument: (value).
49666 *
49667 * **Note:** Unlike `_.differenceBy`, this method mutates `array`.
49668 *
49669 * @static
49670 * @memberOf _
49671 * @since 4.0.0
49672 * @category Array
49673 * @param {Array} array The array to modify.
49674 * @param {Array} values The values to remove.
49675 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
49676 * @returns {Array} Returns `array`.
49677 * @example
49678 *
49679 * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }];
49680 *
49681 * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x');
49682 * console.log(array);
49683 * // => [{ 'x': 2 }]
49684 */
49685 function pullAllBy(array, values, iteratee) {
49686 return (array && array.length && values && values.length)
49687 ? basePullAll(array, values, getIteratee(iteratee, 2))
49688 : array;
49689 }
49690
49691 /**
49692 * This method is like `_.pullAll` except that it accepts `comparator` which
49693 * is invoked to compare elements of `array` to `values`. The comparator is
49694 * invoked with two arguments: (arrVal, othVal).
49695 *
49696 * **Note:** Unlike `_.differenceWith`, this method mutates `array`.
49697 *
49698 * @static
49699 * @memberOf _
49700 * @since 4.6.0
49701 * @category Array
49702 * @param {Array} array The array to modify.
49703 * @param {Array} values The values to remove.
49704 * @param {Function} [comparator] The comparator invoked per element.
49705 * @returns {Array} Returns `array`.
49706 * @example
49707 *
49708 * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }];
49709 *
49710 * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual);
49711 * console.log(array);
49712 * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]
49713 */
49714 function pullAllWith(array, values, comparator) {
49715 return (array && array.length && values && values.length)
49716 ? basePullAll(array, values, undefined, comparator)
49717 : array;
49718 }
49719
49720 /**
49721 * Removes elements from `array` corresponding to `indexes` and returns an
49722 * array of removed elements.
49723 *
49724 * **Note:** Unlike `_.at`, this method mutates `array`.
49725 *
49726 * @static
49727 * @memberOf _
49728 * @since 3.0.0
49729 * @category Array
49730 * @param {Array} array The array to modify.
49731 * @param {...(number|number[])} [indexes] The indexes of elements to remove.
49732 * @returns {Array} Returns the new array of removed elements.
49733 * @example
49734 *
49735 * var array = ['a', 'b', 'c', 'd'];
49736 * var pulled = _.pullAt(array, [1, 3]);
49737 *
49738 * console.log(array);
49739 * // => ['a', 'c']
49740 *
49741 * console.log(pulled);
49742 * // => ['b', 'd']
49743 */
49744 var pullAt = flatRest(function(array, indexes) {
49745 var length = array == null ? 0 : array.length,
49746 result = baseAt(array, indexes);
49747
49748 basePullAt(array, arrayMap(indexes, function(index) {
49749 return isIndex(index, length) ? +index : index;
49750 }).sort(compareAscending));
49751
49752 return result;
49753 });
49754
49755 /**
49756 * Removes all elements from `array` that `predicate` returns truthy for
49757 * and returns an array of the removed elements. The predicate is invoked
49758 * with three arguments: (value, index, array).
49759 *
49760 * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull`
49761 * to pull elements from an array by value.
49762 *
49763 * @static
49764 * @memberOf _
49765 * @since 2.0.0
49766 * @category Array
49767 * @param {Array} array The array to modify.
49768 * @param {Function} [predicate=_.identity] The function invoked per iteration.
49769 * @returns {Array} Returns the new array of removed elements.
49770 * @example
49771 *
49772 * var array = [1, 2, 3, 4];
49773 * var evens = _.remove(array, function(n) {
49774 * return n % 2 == 0;
49775 * });
49776 *
49777 * console.log(array);
49778 * // => [1, 3]
49779 *
49780 * console.log(evens);
49781 * // => [2, 4]
49782 */
49783 function remove(array, predicate) {
49784 var result = [];
49785 if (!(array && array.length)) {
49786 return result;
49787 }
49788 var index = -1,
49789 indexes = [],
49790 length = array.length;
49791
49792 predicate = getIteratee(predicate, 3);
49793 while (++index < length) {
49794 var value = array[index];
49795 if (predicate(value, index, array)) {
49796 result.push(value);
49797 indexes.push(index);
49798 }
49799 }
49800 basePullAt(array, indexes);
49801 return result;
49802 }
49803
49804 /**
49805 * Reverses `array` so that the first element becomes the last, the second
49806 * element becomes the second to last, and so on.
49807 *
49808 * **Note:** This method mutates `array` and is based on
49809 * [`Array#reverse`](https://mdn.io/Array/reverse).
49810 *
49811 * @static
49812 * @memberOf _
49813 * @since 4.0.0
49814 * @category Array
49815 * @param {Array} array The array to modify.
49816 * @returns {Array} Returns `array`.
49817 * @example
49818 *
49819 * var array = [1, 2, 3];
49820 *
49821 * _.reverse(array);
49822 * // => [3, 2, 1]
49823 *
49824 * console.log(array);
49825 * // => [3, 2, 1]
49826 */
49827 function reverse(array) {
49828 return array == null ? array : nativeReverse.call(array);
49829 }
49830
49831 /**
49832 * Creates a slice of `array` from `start` up to, but not including, `end`.
49833 *
49834 * **Note:** This method is used instead of
49835 * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are
49836 * returned.
49837 *
49838 * @static
49839 * @memberOf _
49840 * @since 3.0.0
49841 * @category Array
49842 * @param {Array} array The array to slice.
49843 * @param {number} [start=0] The start position.
49844 * @param {number} [end=array.length] The end position.
49845 * @returns {Array} Returns the slice of `array`.
49846 */
49847 function slice(array, start, end) {
49848 var length = array == null ? 0 : array.length;
49849 if (!length) {
49850 return [];
49851 }
49852 if (end && typeof end != 'number' && isIterateeCall(array, start, end)) {
49853 start = 0;
49854 end = length;
49855 }
49856 else {
49857 start = start == null ? 0 : toInteger(start);
49858 end = end === undefined ? length : toInteger(end);
49859 }
49860 return baseSlice(array, start, end);
49861 }
49862
49863 /**
49864 * Uses a binary search to determine the lowest index at which `value`
49865 * should be inserted into `array` in order to maintain its sort order.
49866 *
49867 * @static
49868 * @memberOf _
49869 * @since 0.1.0
49870 * @category Array
49871 * @param {Array} array The sorted array to inspect.
49872 * @param {*} value The value to evaluate.
49873 * @returns {number} Returns the index at which `value` should be inserted
49874 * into `array`.
49875 * @example
49876 *
49877 * _.sortedIndex([30, 50], 40);
49878 * // => 1
49879 */
49880 function sortedIndex(array, value) {
49881 return baseSortedIndex(array, value);
49882 }
49883
49884 /**
49885 * This method is like `_.sortedIndex` except that it accepts `iteratee`
49886 * which is invoked for `value` and each element of `array` to compute their
49887 * sort ranking. The iteratee is invoked with one argument: (value).
49888 *
49889 * @static
49890 * @memberOf _
49891 * @since 4.0.0
49892 * @category Array
49893 * @param {Array} array The sorted array to inspect.
49894 * @param {*} value The value to evaluate.
49895 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
49896 * @returns {number} Returns the index at which `value` should be inserted
49897 * into `array`.
49898 * @example
49899 *
49900 * var objects = [{ 'x': 4 }, { 'x': 5 }];
49901 *
49902 * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
49903 * // => 0
49904 *
49905 * // The `_.property` iteratee shorthand.
49906 * _.sortedIndexBy(objects, { 'x': 4 }, 'x');
49907 * // => 0
49908 */
49909 function sortedIndexBy(array, value, iteratee) {
49910 return baseSortedIndexBy(array, value, getIteratee(iteratee, 2));
49911 }
49912
49913 /**
49914 * This method is like `_.indexOf` except that it performs a binary
49915 * search on a sorted `array`.
49916 *
49917 * @static
49918 * @memberOf _
49919 * @since 4.0.0
49920 * @category Array
49921 * @param {Array} array The array to inspect.
49922 * @param {*} value The value to search for.
49923 * @returns {number} Returns the index of the matched value, else `-1`.
49924 * @example
49925 *
49926 * _.sortedIndexOf([4, 5, 5, 5, 6], 5);
49927 * // => 1
49928 */
49929 function sortedIndexOf(array, value) {
49930 var length = array == null ? 0 : array.length;
49931 if (length) {
49932 var index = baseSortedIndex(array, value);
49933 if (index < length && eq(array[index], value)) {
49934 return index;
49935 }
49936 }
49937 return -1;
49938 }
49939
49940 /**
49941 * This method is like `_.sortedIndex` except that it returns the highest
49942 * index at which `value` should be inserted into `array` in order to
49943 * maintain its sort order.
49944 *
49945 * @static
49946 * @memberOf _
49947 * @since 3.0.0
49948 * @category Array
49949 * @param {Array} array The sorted array to inspect.
49950 * @param {*} value The value to evaluate.
49951 * @returns {number} Returns the index at which `value` should be inserted
49952 * into `array`.
49953 * @example
49954 *
49955 * _.sortedLastIndex([4, 5, 5, 5, 6], 5);
49956 * // => 4
49957 */
49958 function sortedLastIndex(array, value) {
49959 return baseSortedIndex(array, value, true);
49960 }
49961
49962 /**
49963 * This method is like `_.sortedLastIndex` except that it accepts `iteratee`
49964 * which is invoked for `value` and each element of `array` to compute their
49965 * sort ranking. The iteratee is invoked with one argument: (value).
49966 *
49967 * @static
49968 * @memberOf _
49969 * @since 4.0.0
49970 * @category Array
49971 * @param {Array} array The sorted array to inspect.
49972 * @param {*} value The value to evaluate.
49973 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
49974 * @returns {number} Returns the index at which `value` should be inserted
49975 * into `array`.
49976 * @example
49977 *
49978 * var objects = [{ 'x': 4 }, { 'x': 5 }];
49979 *
49980 * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; });
49981 * // => 1
49982 *
49983 * // The `_.property` iteratee shorthand.
49984 * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x');
49985 * // => 1
49986 */
49987 function sortedLastIndexBy(array, value, iteratee) {
49988 return baseSortedIndexBy(array, value, getIteratee(iteratee, 2), true);
49989 }
49990
49991 /**
49992 * This method is like `_.lastIndexOf` except that it performs a binary
49993 * search on a sorted `array`.
49994 *
49995 * @static
49996 * @memberOf _
49997 * @since 4.0.0
49998 * @category Array
49999 * @param {Array} array The array to inspect.
50000 * @param {*} value The value to search for.
50001 * @returns {number} Returns the index of the matched value, else `-1`.
50002 * @example
50003 *
50004 * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
50005 * // => 3
50006 */
50007 function sortedLastIndexOf(array, value) {
50008 var length = array == null ? 0 : array.length;
50009 if (length) {
50010 var index = baseSortedIndex(array, value, true) - 1;
50011 if (eq(array[index], value)) {
50012 return index;
50013 }
50014 }
50015 return -1;
50016 }
50017
50018 /**
50019 * This method is like `_.uniq` except that it's designed and optimized
50020 * for sorted arrays.
50021 *
50022 * @static
50023 * @memberOf _
50024 * @since 4.0.0
50025 * @category Array
50026 * @param {Array} array The array to inspect.
50027 * @returns {Array} Returns the new duplicate free array.
50028 * @example
50029 *
50030 * _.sortedUniq([1, 1, 2]);
50031 * // => [1, 2]
50032 */
50033 function sortedUniq(array) {
50034 return (array && array.length)
50035 ? baseSortedUniq(array)
50036 : [];
50037 }
50038
50039 /**
50040 * This method is like `_.uniqBy` except that it's designed and optimized
50041 * for sorted arrays.
50042 *
50043 * @static
50044 * @memberOf _
50045 * @since 4.0.0
50046 * @category Array
50047 * @param {Array} array The array to inspect.
50048 * @param {Function} [iteratee] The iteratee invoked per element.
50049 * @returns {Array} Returns the new duplicate free array.
50050 * @example
50051 *
50052 * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
50053 * // => [1.1, 2.3]
50054 */
50055 function sortedUniqBy(array, iteratee) {
50056 return (array && array.length)
50057 ? baseSortedUniq(array, getIteratee(iteratee, 2))
50058 : [];
50059 }
50060
50061 /**
50062 * Gets all but the first element of `array`.
50063 *
50064 * @static
50065 * @memberOf _
50066 * @since 4.0.0
50067 * @category Array
50068 * @param {Array} array The array to query.
50069 * @returns {Array} Returns the slice of `array`.
50070 * @example
50071 *
50072 * _.tail([1, 2, 3]);
50073 * // => [2, 3]
50074 */
50075 function tail(array) {
50076 var length = array == null ? 0 : array.length;
50077 return length ? baseSlice(array, 1, length) : [];
50078 }
50079
50080 /**
50081 * Creates a slice of `array` with `n` elements taken from the beginning.
50082 *
50083 * @static
50084 * @memberOf _
50085 * @since 0.1.0
50086 * @category Array
50087 * @param {Array} array The array to query.
50088 * @param {number} [n=1] The number of elements to take.
50089 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
50090 * @returns {Array} Returns the slice of `array`.
50091 * @example
50092 *
50093 * _.take([1, 2, 3]);
50094 * // => [1]
50095 *
50096 * _.take([1, 2, 3], 2);
50097 * // => [1, 2]
50098 *
50099 * _.take([1, 2, 3], 5);
50100 * // => [1, 2, 3]
50101 *
50102 * _.take([1, 2, 3], 0);
50103 * // => []
50104 */
50105 function take(array, n, guard) {
50106 if (!(array && array.length)) {
50107 return [];
50108 }
50109 n = (guard || n === undefined) ? 1 : toInteger(n);
50110 return baseSlice(array, 0, n < 0 ? 0 : n);
50111 }
50112
50113 /**
50114 * Creates a slice of `array` with `n` elements taken from the end.
50115 *
50116 * @static
50117 * @memberOf _
50118 * @since 3.0.0
50119 * @category Array
50120 * @param {Array} array The array to query.
50121 * @param {number} [n=1] The number of elements to take.
50122 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
50123 * @returns {Array} Returns the slice of `array`.
50124 * @example
50125 *
50126 * _.takeRight([1, 2, 3]);
50127 * // => [3]
50128 *
50129 * _.takeRight([1, 2, 3], 2);
50130 * // => [2, 3]
50131 *
50132 * _.takeRight([1, 2, 3], 5);
50133 * // => [1, 2, 3]
50134 *
50135 * _.takeRight([1, 2, 3], 0);
50136 * // => []
50137 */
50138 function takeRight(array, n, guard) {
50139 var length = array == null ? 0 : array.length;
50140 if (!length) {
50141 return [];
50142 }
50143 n = (guard || n === undefined) ? 1 : toInteger(n);
50144 n = length - n;
50145 return baseSlice(array, n < 0 ? 0 : n, length);
50146 }
50147
50148 /**
50149 * Creates a slice of `array` with elements taken from the end. Elements are
50150 * taken until `predicate` returns falsey. The predicate is invoked with
50151 * three arguments: (value, index, array).
50152 *
50153 * @static
50154 * @memberOf _
50155 * @since 3.0.0
50156 * @category Array
50157 * @param {Array} array The array to query.
50158 * @param {Function} [predicate=_.identity] The function invoked per iteration.
50159 * @returns {Array} Returns the slice of `array`.
50160 * @example
50161 *
50162 * var users = [
50163 * { 'user': 'barney', 'active': true },
50164 * { 'user': 'fred', 'active': false },
50165 * { 'user': 'pebbles', 'active': false }
50166 * ];
50167 *
50168 * _.takeRightWhile(users, function(o) { return !o.active; });
50169 * // => objects for ['fred', 'pebbles']
50170 *
50171 * // The `_.matches` iteratee shorthand.
50172 * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false });
50173 * // => objects for ['pebbles']
50174 *
50175 * // The `_.matchesProperty` iteratee shorthand.
50176 * _.takeRightWhile(users, ['active', false]);
50177 * // => objects for ['fred', 'pebbles']
50178 *
50179 * // The `_.property` iteratee shorthand.
50180 * _.takeRightWhile(users, 'active');
50181 * // => []
50182 */
50183 function takeRightWhile(array, predicate) {
50184 return (array && array.length)
50185 ? baseWhile(array, getIteratee(predicate, 3), false, true)
50186 : [];
50187 }
50188
50189 /**
50190 * Creates a slice of `array` with elements taken from the beginning. Elements
50191 * are taken until `predicate` returns falsey. The predicate is invoked with
50192 * three arguments: (value, index, array).
50193 *
50194 * @static
50195 * @memberOf _
50196 * @since 3.0.0
50197 * @category Array
50198 * @param {Array} array The array to query.
50199 * @param {Function} [predicate=_.identity] The function invoked per iteration.
50200 * @returns {Array} Returns the slice of `array`.
50201 * @example
50202 *
50203 * var users = [
50204 * { 'user': 'barney', 'active': false },
50205 * { 'user': 'fred', 'active': false },
50206 * { 'user': 'pebbles', 'active': true }
50207 * ];
50208 *
50209 * _.takeWhile(users, function(o) { return !o.active; });
50210 * // => objects for ['barney', 'fred']
50211 *
50212 * // The `_.matches` iteratee shorthand.
50213 * _.takeWhile(users, { 'user': 'barney', 'active': false });
50214 * // => objects for ['barney']
50215 *
50216 * // The `_.matchesProperty` iteratee shorthand.
50217 * _.takeWhile(users, ['active', false]);
50218 * // => objects for ['barney', 'fred']
50219 *
50220 * // The `_.property` iteratee shorthand.
50221 * _.takeWhile(users, 'active');
50222 * // => []
50223 */
50224 function takeWhile(array, predicate) {
50225 return (array && array.length)
50226 ? baseWhile(array, getIteratee(predicate, 3))
50227 : [];
50228 }
50229
50230 /**
50231 * Creates an array of unique values, in order, from all given arrays using
50232 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
50233 * for equality comparisons.
50234 *
50235 * @static
50236 * @memberOf _
50237 * @since 0.1.0
50238 * @category Array
50239 * @param {...Array} [arrays] The arrays to inspect.
50240 * @returns {Array} Returns the new array of combined values.
50241 * @example
50242 *
50243 * _.union([2], [1, 2]);
50244 * // => [2, 1]
50245 */
50246 var union = baseRest(function(arrays) {
50247 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true));
50248 });
50249
50250 /**
50251 * This method is like `_.union` except that it accepts `iteratee` which is
50252 * invoked for each element of each `arrays` to generate the criterion by
50253 * which uniqueness is computed. Result values are chosen from the first
50254 * array in which the value occurs. The iteratee is invoked with one argument:
50255 * (value).
50256 *
50257 * @static
50258 * @memberOf _
50259 * @since 4.0.0
50260 * @category Array
50261 * @param {...Array} [arrays] The arrays to inspect.
50262 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
50263 * @returns {Array} Returns the new array of combined values.
50264 * @example
50265 *
50266 * _.unionBy([2.1], [1.2, 2.3], Math.floor);
50267 * // => [2.1, 1.2]
50268 *
50269 * // The `_.property` iteratee shorthand.
50270 * _.unionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
50271 * // => [{ 'x': 1 }, { 'x': 2 }]
50272 */
50273 var unionBy = baseRest(function(arrays) {
50274 var iteratee = last(arrays);
50275 if (isArrayLikeObject(iteratee)) {
50276 iteratee = undefined;
50277 }
50278 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), getIteratee(iteratee, 2));
50279 });
50280
50281 /**
50282 * This method is like `_.union` except that it accepts `comparator` which
50283 * is invoked to compare elements of `arrays`. Result values are chosen from
50284 * the first array in which the value occurs. The comparator is invoked
50285 * with two arguments: (arrVal, othVal).
50286 *
50287 * @static
50288 * @memberOf _
50289 * @since 4.0.0
50290 * @category Array
50291 * @param {...Array} [arrays] The arrays to inspect.
50292 * @param {Function} [comparator] The comparator invoked per element.
50293 * @returns {Array} Returns the new array of combined values.
50294 * @example
50295 *
50296 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
50297 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
50298 *
50299 * _.unionWith(objects, others, _.isEqual);
50300 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
50301 */
50302 var unionWith = baseRest(function(arrays) {
50303 var comparator = last(arrays);
50304 comparator = typeof comparator == 'function' ? comparator : undefined;
50305 return baseUniq(baseFlatten(arrays, 1, isArrayLikeObject, true), undefined, comparator);
50306 });
50307
50308 /**
50309 * Creates a duplicate-free version of an array, using
50310 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
50311 * for equality comparisons, in which only the first occurrence of each element
50312 * is kept. The order of result values is determined by the order they occur
50313 * in the array.
50314 *
50315 * @static
50316 * @memberOf _
50317 * @since 0.1.0
50318 * @category Array
50319 * @param {Array} array The array to inspect.
50320 * @returns {Array} Returns the new duplicate free array.
50321 * @example
50322 *
50323 * _.uniq([2, 1, 2]);
50324 * // => [2, 1]
50325 */
50326 function uniq(array) {
50327 return (array && array.length) ? baseUniq(array) : [];
50328 }
50329
50330 /**
50331 * This method is like `_.uniq` except that it accepts `iteratee` which is
50332 * invoked for each element in `array` to generate the criterion by which
50333 * uniqueness is computed. The order of result values is determined by the
50334 * order they occur in the array. The iteratee is invoked with one argument:
50335 * (value).
50336 *
50337 * @static
50338 * @memberOf _
50339 * @since 4.0.0
50340 * @category Array
50341 * @param {Array} array The array to inspect.
50342 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
50343 * @returns {Array} Returns the new duplicate free array.
50344 * @example
50345 *
50346 * _.uniqBy([2.1, 1.2, 2.3], Math.floor);
50347 * // => [2.1, 1.2]
50348 *
50349 * // The `_.property` iteratee shorthand.
50350 * _.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
50351 * // => [{ 'x': 1 }, { 'x': 2 }]
50352 */
50353 function uniqBy(array, iteratee) {
50354 return (array && array.length) ? baseUniq(array, getIteratee(iteratee, 2)) : [];
50355 }
50356
50357 /**
50358 * This method is like `_.uniq` except that it accepts `comparator` which
50359 * is invoked to compare elements of `array`. The order of result values is
50360 * determined by the order they occur in the array.The comparator is invoked
50361 * with two arguments: (arrVal, othVal).
50362 *
50363 * @static
50364 * @memberOf _
50365 * @since 4.0.0
50366 * @category Array
50367 * @param {Array} array The array to inspect.
50368 * @param {Function} [comparator] The comparator invoked per element.
50369 * @returns {Array} Returns the new duplicate free array.
50370 * @example
50371 *
50372 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
50373 *
50374 * _.uniqWith(objects, _.isEqual);
50375 * // => [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]
50376 */
50377 function uniqWith(array, comparator) {
50378 comparator = typeof comparator == 'function' ? comparator : undefined;
50379 return (array && array.length) ? baseUniq(array, undefined, comparator) : [];
50380 }
50381
50382 /**
50383 * This method is like `_.zip` except that it accepts an array of grouped
50384 * elements and creates an array regrouping the elements to their pre-zip
50385 * configuration.
50386 *
50387 * @static
50388 * @memberOf _
50389 * @since 1.2.0
50390 * @category Array
50391 * @param {Array} array The array of grouped elements to process.
50392 * @returns {Array} Returns the new array of regrouped elements.
50393 * @example
50394 *
50395 * var zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
50396 * // => [['a', 1, true], ['b', 2, false]]
50397 *
50398 * _.unzip(zipped);
50399 * // => [['a', 'b'], [1, 2], [true, false]]
50400 */
50401 function unzip(array) {
50402 if (!(array && array.length)) {
50403 return [];
50404 }
50405 var length = 0;
50406 array = arrayFilter(array, function(group) {
50407 if (isArrayLikeObject(group)) {
50408 length = nativeMax(group.length, length);
50409 return true;
50410 }
50411 });
50412 return baseTimes(length, function(index) {
50413 return arrayMap(array, baseProperty(index));
50414 });
50415 }
50416
50417 /**
50418 * This method is like `_.unzip` except that it accepts `iteratee` to specify
50419 * how regrouped values should be combined. The iteratee is invoked with the
50420 * elements of each group: (...group).
50421 *
50422 * @static
50423 * @memberOf _
50424 * @since 3.8.0
50425 * @category Array
50426 * @param {Array} array The array of grouped elements to process.
50427 * @param {Function} [iteratee=_.identity] The function to combine
50428 * regrouped values.
50429 * @returns {Array} Returns the new array of regrouped elements.
50430 * @example
50431 *
50432 * var zipped = _.zip([1, 2], [10, 20], [100, 200]);
50433 * // => [[1, 10, 100], [2, 20, 200]]
50434 *
50435 * _.unzipWith(zipped, _.add);
50436 * // => [3, 30, 300]
50437 */
50438 function unzipWith(array, iteratee) {
50439 if (!(array && array.length)) {
50440 return [];
50441 }
50442 var result = unzip(array);
50443 if (iteratee == null) {
50444 return result;
50445 }
50446 return arrayMap(result, function(group) {
50447 return apply(iteratee, undefined, group);
50448 });
50449 }
50450
50451 /**
50452 * Creates an array excluding all given values using
50453 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
50454 * for equality comparisons.
50455 *
50456 * **Note:** Unlike `_.pull`, this method returns a new array.
50457 *
50458 * @static
50459 * @memberOf _
50460 * @since 0.1.0
50461 * @category Array
50462 * @param {Array} array The array to inspect.
50463 * @param {...*} [values] The values to exclude.
50464 * @returns {Array} Returns the new array of filtered values.
50465 * @see _.difference, _.xor
50466 * @example
50467 *
50468 * _.without([2, 1, 2, 3], 1, 2);
50469 * // => [3]
50470 */
50471 var without = baseRest(function(array, values) {
50472 return isArrayLikeObject(array)
50473 ? baseDifference(array, values)
50474 : [];
50475 });
50476
50477 /**
50478 * Creates an array of unique values that is the
50479 * [symmetric difference](https://en.wikipedia.org/wiki/Symmetric_difference)
50480 * of the given arrays. The order of result values is determined by the order
50481 * they occur in the arrays.
50482 *
50483 * @static
50484 * @memberOf _
50485 * @since 2.4.0
50486 * @category Array
50487 * @param {...Array} [arrays] The arrays to inspect.
50488 * @returns {Array} Returns the new array of filtered values.
50489 * @see _.difference, _.without
50490 * @example
50491 *
50492 * _.xor([2, 1], [2, 3]);
50493 * // => [1, 3]
50494 */
50495 var xor = baseRest(function(arrays) {
50496 return baseXor(arrayFilter(arrays, isArrayLikeObject));
50497 });
50498
50499 /**
50500 * This method is like `_.xor` except that it accepts `iteratee` which is
50501 * invoked for each element of each `arrays` to generate the criterion by
50502 * which by which they're compared. The order of result values is determined
50503 * by the order they occur in the arrays. The iteratee is invoked with one
50504 * argument: (value).
50505 *
50506 * @static
50507 * @memberOf _
50508 * @since 4.0.0
50509 * @category Array
50510 * @param {...Array} [arrays] The arrays to inspect.
50511 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
50512 * @returns {Array} Returns the new array of filtered values.
50513 * @example
50514 *
50515 * _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
50516 * // => [1.2, 3.4]
50517 *
50518 * // The `_.property` iteratee shorthand.
50519 * _.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
50520 * // => [{ 'x': 2 }]
50521 */
50522 var xorBy = baseRest(function(arrays) {
50523 var iteratee = last(arrays);
50524 if (isArrayLikeObject(iteratee)) {
50525 iteratee = undefined;
50526 }
50527 return baseXor(arrayFilter(arrays, isArrayLikeObject), getIteratee(iteratee, 2));
50528 });
50529
50530 /**
50531 * This method is like `_.xor` except that it accepts `comparator` which is
50532 * invoked to compare elements of `arrays`. The order of result values is
50533 * determined by the order they occur in the arrays. The comparator is invoked
50534 * with two arguments: (arrVal, othVal).
50535 *
50536 * @static
50537 * @memberOf _
50538 * @since 4.0.0
50539 * @category Array
50540 * @param {...Array} [arrays] The arrays to inspect.
50541 * @param {Function} [comparator] The comparator invoked per element.
50542 * @returns {Array} Returns the new array of filtered values.
50543 * @example
50544 *
50545 * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
50546 * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
50547 *
50548 * _.xorWith(objects, others, _.isEqual);
50549 * // => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]
50550 */
50551 var xorWith = baseRest(function(arrays) {
50552 var comparator = last(arrays);
50553 comparator = typeof comparator == 'function' ? comparator : undefined;
50554 return baseXor(arrayFilter(arrays, isArrayLikeObject), undefined, comparator);
50555 });
50556
50557 /**
50558 * Creates an array of grouped elements, the first of which contains the
50559 * first elements of the given arrays, the second of which contains the
50560 * second elements of the given arrays, and so on.
50561 *
50562 * @static
50563 * @memberOf _
50564 * @since 0.1.0
50565 * @category Array
50566 * @param {...Array} [arrays] The arrays to process.
50567 * @returns {Array} Returns the new array of grouped elements.
50568 * @example
50569 *
50570 * _.zip(['a', 'b'], [1, 2], [true, false]);
50571 * // => [['a', 1, true], ['b', 2, false]]
50572 */
50573 var zip = baseRest(unzip);
50574
50575 /**
50576 * This method is like `_.fromPairs` except that it accepts two arrays,
50577 * one of property identifiers and one of corresponding values.
50578 *
50579 * @static
50580 * @memberOf _
50581 * @since 0.4.0
50582 * @category Array
50583 * @param {Array} [props=[]] The property identifiers.
50584 * @param {Array} [values=[]] The property values.
50585 * @returns {Object} Returns the new object.
50586 * @example
50587 *
50588 * _.zipObject(['a', 'b'], [1, 2]);
50589 * // => { 'a': 1, 'b': 2 }
50590 */
50591 function zipObject(props, values) {
50592 return baseZipObject(props || [], values || [], assignValue);
50593 }
50594
50595 /**
50596 * This method is like `_.zipObject` except that it supports property paths.
50597 *
50598 * @static
50599 * @memberOf _
50600 * @since 4.1.0
50601 * @category Array
50602 * @param {Array} [props=[]] The property identifiers.
50603 * @param {Array} [values=[]] The property values.
50604 * @returns {Object} Returns the new object.
50605 * @example
50606 *
50607 * _.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
50608 * // => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
50609 */
50610 function zipObjectDeep(props, values) {
50611 return baseZipObject(props || [], values || [], baseSet);
50612 }
50613
50614 /**
50615 * This method is like `_.zip` except that it accepts `iteratee` to specify
50616 * how grouped values should be combined. The iteratee is invoked with the
50617 * elements of each group: (...group).
50618 *
50619 * @static
50620 * @memberOf _
50621 * @since 3.8.0
50622 * @category Array
50623 * @param {...Array} [arrays] The arrays to process.
50624 * @param {Function} [iteratee=_.identity] The function to combine
50625 * grouped values.
50626 * @returns {Array} Returns the new array of grouped elements.
50627 * @example
50628 *
50629 * _.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
50630 * return a + b + c;
50631 * });
50632 * // => [111, 222]
50633 */
50634 var zipWith = baseRest(function(arrays) {
50635 var length = arrays.length,
50636 iteratee = length > 1 ? arrays[length - 1] : undefined;
50637
50638 iteratee = typeof iteratee == 'function' ? (arrays.pop(), iteratee) : undefined;
50639 return unzipWith(arrays, iteratee);
50640 });
50641
50642 /*------------------------------------------------------------------------*/
50643
50644 /**
50645 * Creates a `lodash` wrapper instance that wraps `value` with explicit method
50646 * chain sequences enabled. The result of such sequences must be unwrapped
50647 * with `_#value`.
50648 *
50649 * @static
50650 * @memberOf _
50651 * @since 1.3.0
50652 * @category Seq
50653 * @param {*} value The value to wrap.
50654 * @returns {Object} Returns the new `lodash` wrapper instance.
50655 * @example
50656 *
50657 * var users = [
50658 * { 'user': 'barney', 'age': 36 },
50659 * { 'user': 'fred', 'age': 40 },
50660 * { 'user': 'pebbles', 'age': 1 }
50661 * ];
50662 *
50663 * var youngest = _
50664 * .chain(users)
50665 * .sortBy('age')
50666 * .map(function(o) {
50667 * return o.user + ' is ' + o.age;
50668 * })
50669 * .head()
50670 * .value();
50671 * // => 'pebbles is 1'
50672 */
50673 function chain(value) {
50674 var result = lodash(value);
50675 result.__chain__ = true;
50676 return result;
50677 }
50678
50679 /**
50680 * This method invokes `interceptor` and returns `value`. The interceptor
50681 * is invoked with one argument; (value). The purpose of this method is to
50682 * "tap into" a method chain sequence in order to modify intermediate results.
50683 *
50684 * @static
50685 * @memberOf _
50686 * @since 0.1.0
50687 * @category Seq
50688 * @param {*} value The value to provide to `interceptor`.
50689 * @param {Function} interceptor The function to invoke.
50690 * @returns {*} Returns `value`.
50691 * @example
50692 *
50693 * _([1, 2, 3])
50694 * .tap(function(array) {
50695 * // Mutate input array.
50696 * array.pop();
50697 * })
50698 * .reverse()
50699 * .value();
50700 * // => [2, 1]
50701 */
50702 function tap(value, interceptor) {
50703 interceptor(value);
50704 return value;
50705 }
50706
50707 /**
50708 * This method is like `_.tap` except that it returns the result of `interceptor`.
50709 * The purpose of this method is to "pass thru" values replacing intermediate
50710 * results in a method chain sequence.
50711 *
50712 * @static
50713 * @memberOf _
50714 * @since 3.0.0
50715 * @category Seq
50716 * @param {*} value The value to provide to `interceptor`.
50717 * @param {Function} interceptor The function to invoke.
50718 * @returns {*} Returns the result of `interceptor`.
50719 * @example
50720 *
50721 * _(' abc ')
50722 * .chain()
50723 * .trim()
50724 * .thru(function(value) {
50725 * return [value];
50726 * })
50727 * .value();
50728 * // => ['abc']
50729 */
50730 function thru(value, interceptor) {
50731 return interceptor(value);
50732 }
50733
50734 /**
50735 * This method is the wrapper version of `_.at`.
50736 *
50737 * @name at
50738 * @memberOf _
50739 * @since 1.0.0
50740 * @category Seq
50741 * @param {...(string|string[])} [paths] The property paths to pick.
50742 * @returns {Object} Returns the new `lodash` wrapper instance.
50743 * @example
50744 *
50745 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
50746 *
50747 * _(object).at(['a[0].b.c', 'a[1]']).value();
50748 * // => [3, 4]
50749 */
50750 var wrapperAt = flatRest(function(paths) {
50751 var length = paths.length,
50752 start = length ? paths[0] : 0,
50753 value = this.__wrapped__,
50754 interceptor = function(object) { return baseAt(object, paths); };
50755
50756 if (length > 1 || this.__actions__.length ||
50757 !(value instanceof LazyWrapper) || !isIndex(start)) {
50758 return this.thru(interceptor);
50759 }
50760 value = value.slice(start, +start + (length ? 1 : 0));
50761 value.__actions__.push({
50762 'func': thru,
50763 'args': [interceptor],
50764 'thisArg': undefined
50765 });
50766 return new LodashWrapper(value, this.__chain__).thru(function(array) {
50767 if (length && !array.length) {
50768 array.push(undefined);
50769 }
50770 return array;
50771 });
50772 });
50773
50774 /**
50775 * Creates a `lodash` wrapper instance with explicit method chain sequences enabled.
50776 *
50777 * @name chain
50778 * @memberOf _
50779 * @since 0.1.0
50780 * @category Seq
50781 * @returns {Object} Returns the new `lodash` wrapper instance.
50782 * @example
50783 *
50784 * var users = [
50785 * { 'user': 'barney', 'age': 36 },
50786 * { 'user': 'fred', 'age': 40 }
50787 * ];
50788 *
50789 * // A sequence without explicit chaining.
50790 * _(users).head();
50791 * // => { 'user': 'barney', 'age': 36 }
50792 *
50793 * // A sequence with explicit chaining.
50794 * _(users)
50795 * .chain()
50796 * .head()
50797 * .pick('user')
50798 * .value();
50799 * // => { 'user': 'barney' }
50800 */
50801 function wrapperChain() {
50802 return chain(this);
50803 }
50804
50805 /**
50806 * Executes the chain sequence and returns the wrapped result.
50807 *
50808 * @name commit
50809 * @memberOf _
50810 * @since 3.2.0
50811 * @category Seq
50812 * @returns {Object} Returns the new `lodash` wrapper instance.
50813 * @example
50814 *
50815 * var array = [1, 2];
50816 * var wrapped = _(array).push(3);
50817 *
50818 * console.log(array);
50819 * // => [1, 2]
50820 *
50821 * wrapped = wrapped.commit();
50822 * console.log(array);
50823 * // => [1, 2, 3]
50824 *
50825 * wrapped.last();
50826 * // => 3
50827 *
50828 * console.log(array);
50829 * // => [1, 2, 3]
50830 */
50831 function wrapperCommit() {
50832 return new LodashWrapper(this.value(), this.__chain__);
50833 }
50834
50835 /**
50836 * Gets the next value on a wrapped object following the
50837 * [iterator protocol](https://mdn.io/iteration_protocols#iterator).
50838 *
50839 * @name next
50840 * @memberOf _
50841 * @since 4.0.0
50842 * @category Seq
50843 * @returns {Object} Returns the next iterator value.
50844 * @example
50845 *
50846 * var wrapped = _([1, 2]);
50847 *
50848 * wrapped.next();
50849 * // => { 'done': false, 'value': 1 }
50850 *
50851 * wrapped.next();
50852 * // => { 'done': false, 'value': 2 }
50853 *
50854 * wrapped.next();
50855 * // => { 'done': true, 'value': undefined }
50856 */
50857 function wrapperNext() {
50858 if (this.__values__ === undefined) {
50859 this.__values__ = toArray(this.value());
50860 }
50861 var done = this.__index__ >= this.__values__.length,
50862 value = done ? undefined : this.__values__[this.__index__++];
50863
50864 return { 'done': done, 'value': value };
50865 }
50866
50867 /**
50868 * Enables the wrapper to be iterable.
50869 *
50870 * @name Symbol.iterator
50871 * @memberOf _
50872 * @since 4.0.0
50873 * @category Seq
50874 * @returns {Object} Returns the wrapper object.
50875 * @example
50876 *
50877 * var wrapped = _([1, 2]);
50878 *
50879 * wrapped[Symbol.iterator]() === wrapped;
50880 * // => true
50881 *
50882 * Array.from(wrapped);
50883 * // => [1, 2]
50884 */
50885 function wrapperToIterator() {
50886 return this;
50887 }
50888
50889 /**
50890 * Creates a clone of the chain sequence planting `value` as the wrapped value.
50891 *
50892 * @name plant
50893 * @memberOf _
50894 * @since 3.2.0
50895 * @category Seq
50896 * @param {*} value The value to plant.
50897 * @returns {Object} Returns the new `lodash` wrapper instance.
50898 * @example
50899 *
50900 * function square(n) {
50901 * return n * n;
50902 * }
50903 *
50904 * var wrapped = _([1, 2]).map(square);
50905 * var other = wrapped.plant([3, 4]);
50906 *
50907 * other.value();
50908 * // => [9, 16]
50909 *
50910 * wrapped.value();
50911 * // => [1, 4]
50912 */
50913 function wrapperPlant(value) {
50914 var result,
50915 parent = this;
50916
50917 while (parent instanceof baseLodash) {
50918 var clone = wrapperClone(parent);
50919 clone.__index__ = 0;
50920 clone.__values__ = undefined;
50921 if (result) {
50922 previous.__wrapped__ = clone;
50923 } else {
50924 result = clone;
50925 }
50926 var previous = clone;
50927 parent = parent.__wrapped__;
50928 }
50929 previous.__wrapped__ = value;
50930 return result;
50931 }
50932
50933 /**
50934 * This method is the wrapper version of `_.reverse`.
50935 *
50936 * **Note:** This method mutates the wrapped array.
50937 *
50938 * @name reverse
50939 * @memberOf _
50940 * @since 0.1.0
50941 * @category Seq
50942 * @returns {Object} Returns the new `lodash` wrapper instance.
50943 * @example
50944 *
50945 * var array = [1, 2, 3];
50946 *
50947 * _(array).reverse().value()
50948 * // => [3, 2, 1]
50949 *
50950 * console.log(array);
50951 * // => [3, 2, 1]
50952 */
50953 function wrapperReverse() {
50954 var value = this.__wrapped__;
50955 if (value instanceof LazyWrapper) {
50956 var wrapped = value;
50957 if (this.__actions__.length) {
50958 wrapped = new LazyWrapper(this);
50959 }
50960 wrapped = wrapped.reverse();
50961 wrapped.__actions__.push({
50962 'func': thru,
50963 'args': [reverse],
50964 'thisArg': undefined
50965 });
50966 return new LodashWrapper(wrapped, this.__chain__);
50967 }
50968 return this.thru(reverse);
50969 }
50970
50971 /**
50972 * Executes the chain sequence to resolve the unwrapped value.
50973 *
50974 * @name value
50975 * @memberOf _
50976 * @since 0.1.0
50977 * @alias toJSON, valueOf
50978 * @category Seq
50979 * @returns {*} Returns the resolved unwrapped value.
50980 * @example
50981 *
50982 * _([1, 2, 3]).value();
50983 * // => [1, 2, 3]
50984 */
50985 function wrapperValue() {
50986 return baseWrapperValue(this.__wrapped__, this.__actions__);
50987 }
50988
50989 /*------------------------------------------------------------------------*/
50990
50991 /**
50992 * Creates an object composed of keys generated from the results of running
50993 * each element of `collection` thru `iteratee`. The corresponding value of
50994 * each key is the number of times the key was returned by `iteratee`. The
50995 * iteratee is invoked with one argument: (value).
50996 *
50997 * @static
50998 * @memberOf _
50999 * @since 0.5.0
51000 * @category Collection
51001 * @param {Array|Object} collection The collection to iterate over.
51002 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
51003 * @returns {Object} Returns the composed aggregate object.
51004 * @example
51005 *
51006 * _.countBy([6.1, 4.2, 6.3], Math.floor);
51007 * // => { '4': 1, '6': 2 }
51008 *
51009 * // The `_.property` iteratee shorthand.
51010 * _.countBy(['one', 'two', 'three'], 'length');
51011 * // => { '3': 2, '5': 1 }
51012 */
51013 var countBy = createAggregator(function(result, value, key) {
51014 if (hasOwnProperty.call(result, key)) {
51015 ++result[key];
51016 } else {
51017 baseAssignValue(result, key, 1);
51018 }
51019 });
51020
51021 /**
51022 * Checks if `predicate` returns truthy for **all** elements of `collection`.
51023 * Iteration is stopped once `predicate` returns falsey. The predicate is
51024 * invoked with three arguments: (value, index|key, collection).
51025 *
51026 * **Note:** This method returns `true` for
51027 * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because
51028 * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of
51029 * elements of empty collections.
51030 *
51031 * @static
51032 * @memberOf _
51033 * @since 0.1.0
51034 * @category Collection
51035 * @param {Array|Object} collection The collection to iterate over.
51036 * @param {Function} [predicate=_.identity] The function invoked per iteration.
51037 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
51038 * @returns {boolean} Returns `true` if all elements pass the predicate check,
51039 * else `false`.
51040 * @example
51041 *
51042 * _.every([true, 1, null, 'yes'], Boolean);
51043 * // => false
51044 *
51045 * var users = [
51046 * { 'user': 'barney', 'age': 36, 'active': false },
51047 * { 'user': 'fred', 'age': 40, 'active': false }
51048 * ];
51049 *
51050 * // The `_.matches` iteratee shorthand.
51051 * _.every(users, { 'user': 'barney', 'active': false });
51052 * // => false
51053 *
51054 * // The `_.matchesProperty` iteratee shorthand.
51055 * _.every(users, ['active', false]);
51056 * // => true
51057 *
51058 * // The `_.property` iteratee shorthand.
51059 * _.every(users, 'active');
51060 * // => false
51061 */
51062 function every(collection, predicate, guard) {
51063 var func = isArray(collection) ? arrayEvery : baseEvery;
51064 if (guard && isIterateeCall(collection, predicate, guard)) {
51065 predicate = undefined;
51066 }
51067 return func(collection, getIteratee(predicate, 3));
51068 }
51069
51070 /**
51071 * Iterates over elements of `collection`, returning an array of all elements
51072 * `predicate` returns truthy for. The predicate is invoked with three
51073 * arguments: (value, index|key, collection).
51074 *
51075 * **Note:** Unlike `_.remove`, this method returns a new array.
51076 *
51077 * @static
51078 * @memberOf _
51079 * @since 0.1.0
51080 * @category Collection
51081 * @param {Array|Object} collection The collection to iterate over.
51082 * @param {Function} [predicate=_.identity] The function invoked per iteration.
51083 * @returns {Array} Returns the new filtered array.
51084 * @see _.reject
51085 * @example
51086 *
51087 * var users = [
51088 * { 'user': 'barney', 'age': 36, 'active': true },
51089 * { 'user': 'fred', 'age': 40, 'active': false }
51090 * ];
51091 *
51092 * _.filter(users, function(o) { return !o.active; });
51093 * // => objects for ['fred']
51094 *
51095 * // The `_.matches` iteratee shorthand.
51096 * _.filter(users, { 'age': 36, 'active': true });
51097 * // => objects for ['barney']
51098 *
51099 * // The `_.matchesProperty` iteratee shorthand.
51100 * _.filter(users, ['active', false]);
51101 * // => objects for ['fred']
51102 *
51103 * // The `_.property` iteratee shorthand.
51104 * _.filter(users, 'active');
51105 * // => objects for ['barney']
51106 *
51107 * // Combining several predicates using `_.overEvery` or `_.overSome`.
51108 * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]]));
51109 * // => objects for ['fred', 'barney']
51110 */
51111 function filter(collection, predicate) {
51112 var func = isArray(collection) ? arrayFilter : baseFilter;
51113 return func(collection, getIteratee(predicate, 3));
51114 }
51115
51116 /**
51117 * Iterates over elements of `collection`, returning the first element
51118 * `predicate` returns truthy for. The predicate is invoked with three
51119 * arguments: (value, index|key, collection).
51120 *
51121 * @static
51122 * @memberOf _
51123 * @since 0.1.0
51124 * @category Collection
51125 * @param {Array|Object} collection The collection to inspect.
51126 * @param {Function} [predicate=_.identity] The function invoked per iteration.
51127 * @param {number} [fromIndex=0] The index to search from.
51128 * @returns {*} Returns the matched element, else `undefined`.
51129 * @example
51130 *
51131 * var users = [
51132 * { 'user': 'barney', 'age': 36, 'active': true },
51133 * { 'user': 'fred', 'age': 40, 'active': false },
51134 * { 'user': 'pebbles', 'age': 1, 'active': true }
51135 * ];
51136 *
51137 * _.find(users, function(o) { return o.age < 40; });
51138 * // => object for 'barney'
51139 *
51140 * // The `_.matches` iteratee shorthand.
51141 * _.find(users, { 'age': 1, 'active': true });
51142 * // => object for 'pebbles'
51143 *
51144 * // The `_.matchesProperty` iteratee shorthand.
51145 * _.find(users, ['active', false]);
51146 * // => object for 'fred'
51147 *
51148 * // The `_.property` iteratee shorthand.
51149 * _.find(users, 'active');
51150 * // => object for 'barney'
51151 */
51152 var find = createFind(findIndex);
51153
51154 /**
51155 * This method is like `_.find` except that it iterates over elements of
51156 * `collection` from right to left.
51157 *
51158 * @static
51159 * @memberOf _
51160 * @since 2.0.0
51161 * @category Collection
51162 * @param {Array|Object} collection The collection to inspect.
51163 * @param {Function} [predicate=_.identity] The function invoked per iteration.
51164 * @param {number} [fromIndex=collection.length-1] The index to search from.
51165 * @returns {*} Returns the matched element, else `undefined`.
51166 * @example
51167 *
51168 * _.findLast([1, 2, 3, 4], function(n) {
51169 * return n % 2 == 1;
51170 * });
51171 * // => 3
51172 */
51173 var findLast = createFind(findLastIndex);
51174
51175 /**
51176 * Creates a flattened array of values by running each element in `collection`
51177 * thru `iteratee` and flattening the mapped results. The iteratee is invoked
51178 * with three arguments: (value, index|key, collection).
51179 *
51180 * @static
51181 * @memberOf _
51182 * @since 4.0.0
51183 * @category Collection
51184 * @param {Array|Object} collection The collection to iterate over.
51185 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
51186 * @returns {Array} Returns the new flattened array.
51187 * @example
51188 *
51189 * function duplicate(n) {
51190 * return [n, n];
51191 * }
51192 *
51193 * _.flatMap([1, 2], duplicate);
51194 * // => [1, 1, 2, 2]
51195 */
51196 function flatMap(collection, iteratee) {
51197 return baseFlatten(map(collection, iteratee), 1);
51198 }
51199
51200 /**
51201 * This method is like `_.flatMap` except that it recursively flattens the
51202 * mapped results.
51203 *
51204 * @static
51205 * @memberOf _
51206 * @since 4.7.0
51207 * @category Collection
51208 * @param {Array|Object} collection The collection to iterate over.
51209 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
51210 * @returns {Array} Returns the new flattened array.
51211 * @example
51212 *
51213 * function duplicate(n) {
51214 * return [[[n, n]]];
51215 * }
51216 *
51217 * _.flatMapDeep([1, 2], duplicate);
51218 * // => [1, 1, 2, 2]
51219 */
51220 function flatMapDeep(collection, iteratee) {
51221 return baseFlatten(map(collection, iteratee), INFINITY);
51222 }
51223
51224 /**
51225 * This method is like `_.flatMap` except that it recursively flattens the
51226 * mapped results up to `depth` times.
51227 *
51228 * @static
51229 * @memberOf _
51230 * @since 4.7.0
51231 * @category Collection
51232 * @param {Array|Object} collection The collection to iterate over.
51233 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
51234 * @param {number} [depth=1] The maximum recursion depth.
51235 * @returns {Array} Returns the new flattened array.
51236 * @example
51237 *
51238 * function duplicate(n) {
51239 * return [[[n, n]]];
51240 * }
51241 *
51242 * _.flatMapDepth([1, 2], duplicate, 2);
51243 * // => [[1, 1], [2, 2]]
51244 */
51245 function flatMapDepth(collection, iteratee, depth) {
51246 depth = depth === undefined ? 1 : toInteger(depth);
51247 return baseFlatten(map(collection, iteratee), depth);
51248 }
51249
51250 /**
51251 * Iterates over elements of `collection` and invokes `iteratee` for each element.
51252 * The iteratee is invoked with three arguments: (value, index|key, collection).
51253 * Iteratee functions may exit iteration early by explicitly returning `false`.
51254 *
51255 * **Note:** As with other "Collections" methods, objects with a "length"
51256 * property are iterated like arrays. To avoid this behavior use `_.forIn`
51257 * or `_.forOwn` for object iteration.
51258 *
51259 * @static
51260 * @memberOf _
51261 * @since 0.1.0
51262 * @alias each
51263 * @category Collection
51264 * @param {Array|Object} collection The collection to iterate over.
51265 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
51266 * @returns {Array|Object} Returns `collection`.
51267 * @see _.forEachRight
51268 * @example
51269 *
51270 * _.forEach([1, 2], function(value) {
51271 * console.log(value);
51272 * });
51273 * // => Logs `1` then `2`.
51274 *
51275 * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) {
51276 * console.log(key);
51277 * });
51278 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
51279 */
51280 function forEach(collection, iteratee) {
51281 var func = isArray(collection) ? arrayEach : baseEach;
51282 return func(collection, getIteratee(iteratee, 3));
51283 }
51284
51285 /**
51286 * This method is like `_.forEach` except that it iterates over elements of
51287 * `collection` from right to left.
51288 *
51289 * @static
51290 * @memberOf _
51291 * @since 2.0.0
51292 * @alias eachRight
51293 * @category Collection
51294 * @param {Array|Object} collection The collection to iterate over.
51295 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
51296 * @returns {Array|Object} Returns `collection`.
51297 * @see _.forEach
51298 * @example
51299 *
51300 * _.forEachRight([1, 2], function(value) {
51301 * console.log(value);
51302 * });
51303 * // => Logs `2` then `1`.
51304 */
51305 function forEachRight(collection, iteratee) {
51306 var func = isArray(collection) ? arrayEachRight : baseEachRight;
51307 return func(collection, getIteratee(iteratee, 3));
51308 }
51309
51310 /**
51311 * Creates an object composed of keys generated from the results of running
51312 * each element of `collection` thru `iteratee`. The order of grouped values
51313 * is determined by the order they occur in `collection`. The corresponding
51314 * value of each key is an array of elements responsible for generating the
51315 * key. The iteratee is invoked with one argument: (value).
51316 *
51317 * @static
51318 * @memberOf _
51319 * @since 0.1.0
51320 * @category Collection
51321 * @param {Array|Object} collection The collection to iterate over.
51322 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
51323 * @returns {Object} Returns the composed aggregate object.
51324 * @example
51325 *
51326 * _.groupBy([6.1, 4.2, 6.3], Math.floor);
51327 * // => { '4': [4.2], '6': [6.1, 6.3] }
51328 *
51329 * // The `_.property` iteratee shorthand.
51330 * _.groupBy(['one', 'two', 'three'], 'length');
51331 * // => { '3': ['one', 'two'], '5': ['three'] }
51332 */
51333 var groupBy = createAggregator(function(result, value, key) {
51334 if (hasOwnProperty.call(result, key)) {
51335 result[key].push(value);
51336 } else {
51337 baseAssignValue(result, key, [value]);
51338 }
51339 });
51340
51341 /**
51342 * Checks if `value` is in `collection`. If `collection` is a string, it's
51343 * checked for a substring of `value`, otherwise
51344 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
51345 * is used for equality comparisons. If `fromIndex` is negative, it's used as
51346 * the offset from the end of `collection`.
51347 *
51348 * @static
51349 * @memberOf _
51350 * @since 0.1.0
51351 * @category Collection
51352 * @param {Array|Object|string} collection The collection to inspect.
51353 * @param {*} value The value to search for.
51354 * @param {number} [fromIndex=0] The index to search from.
51355 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
51356 * @returns {boolean} Returns `true` if `value` is found, else `false`.
51357 * @example
51358 *
51359 * _.includes([1, 2, 3], 1);
51360 * // => true
51361 *
51362 * _.includes([1, 2, 3], 1, 2);
51363 * // => false
51364 *
51365 * _.includes({ 'a': 1, 'b': 2 }, 1);
51366 * // => true
51367 *
51368 * _.includes('abcd', 'bc');
51369 * // => true
51370 */
51371 function includes(collection, value, fromIndex, guard) {
51372 collection = isArrayLike(collection) ? collection : values(collection);
51373 fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0;
51374
51375 var length = collection.length;
51376 if (fromIndex < 0) {
51377 fromIndex = nativeMax(length + fromIndex, 0);
51378 }
51379 return isString(collection)
51380 ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1)
51381 : (!!length && baseIndexOf(collection, value, fromIndex) > -1);
51382 }
51383
51384 /**
51385 * Invokes the method at `path` of each element in `collection`, returning
51386 * an array of the results of each invoked method. Any additional arguments
51387 * are provided to each invoked method. If `path` is a function, it's invoked
51388 * for, and `this` bound to, each element in `collection`.
51389 *
51390 * @static
51391 * @memberOf _
51392 * @since 4.0.0
51393 * @category Collection
51394 * @param {Array|Object} collection The collection to iterate over.
51395 * @param {Array|Function|string} path The path of the method to invoke or
51396 * the function invoked per iteration.
51397 * @param {...*} [args] The arguments to invoke each method with.
51398 * @returns {Array} Returns the array of results.
51399 * @example
51400 *
51401 * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort');
51402 * // => [[1, 5, 7], [1, 2, 3]]
51403 *
51404 * _.invokeMap([123, 456], String.prototype.split, '');
51405 * // => [['1', '2', '3'], ['4', '5', '6']]
51406 */
51407 var invokeMap = baseRest(function(collection, path, args) {
51408 var index = -1,
51409 isFunc = typeof path == 'function',
51410 result = isArrayLike(collection) ? Array(collection.length) : [];
51411
51412 baseEach(collection, function(value) {
51413 result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args);
51414 });
51415 return result;
51416 });
51417
51418 /**
51419 * Creates an object composed of keys generated from the results of running
51420 * each element of `collection` thru `iteratee`. The corresponding value of
51421 * each key is the last element responsible for generating the key. The
51422 * iteratee is invoked with one argument: (value).
51423 *
51424 * @static
51425 * @memberOf _
51426 * @since 4.0.0
51427 * @category Collection
51428 * @param {Array|Object} collection The collection to iterate over.
51429 * @param {Function} [iteratee=_.identity] The iteratee to transform keys.
51430 * @returns {Object} Returns the composed aggregate object.
51431 * @example
51432 *
51433 * var array = [
51434 * { 'dir': 'left', 'code': 97 },
51435 * { 'dir': 'right', 'code': 100 }
51436 * ];
51437 *
51438 * _.keyBy(array, function(o) {
51439 * return String.fromCharCode(o.code);
51440 * });
51441 * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } }
51442 *
51443 * _.keyBy(array, 'dir');
51444 * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } }
51445 */
51446 var keyBy = createAggregator(function(result, value, key) {
51447 baseAssignValue(result, key, value);
51448 });
51449
51450 /**
51451 * Creates an array of values by running each element in `collection` thru
51452 * `iteratee`. The iteratee is invoked with three arguments:
51453 * (value, index|key, collection).
51454 *
51455 * Many lodash methods are guarded to work as iteratees for methods like
51456 * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`.
51457 *
51458 * The guarded methods are:
51459 * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`,
51460 * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`,
51461 * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`,
51462 * `template`, `trim`, `trimEnd`, `trimStart`, and `words`
51463 *
51464 * @static
51465 * @memberOf _
51466 * @since 0.1.0
51467 * @category Collection
51468 * @param {Array|Object} collection The collection to iterate over.
51469 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
51470 * @returns {Array} Returns the new mapped array.
51471 * @example
51472 *
51473 * function square(n) {
51474 * return n * n;
51475 * }
51476 *
51477 * _.map([4, 8], square);
51478 * // => [16, 64]
51479 *
51480 * _.map({ 'a': 4, 'b': 8 }, square);
51481 * // => [16, 64] (iteration order is not guaranteed)
51482 *
51483 * var users = [
51484 * { 'user': 'barney' },
51485 * { 'user': 'fred' }
51486 * ];
51487 *
51488 * // The `_.property` iteratee shorthand.
51489 * _.map(users, 'user');
51490 * // => ['barney', 'fred']
51491 */
51492 function map(collection, iteratee) {
51493 var func = isArray(collection) ? arrayMap : baseMap;
51494 return func(collection, getIteratee(iteratee, 3));
51495 }
51496
51497 /**
51498 * This method is like `_.sortBy` except that it allows specifying the sort
51499 * orders of the iteratees to sort by. If `orders` is unspecified, all values
51500 * are sorted in ascending order. Otherwise, specify an order of "desc" for
51501 * descending or "asc" for ascending sort order of corresponding values.
51502 *
51503 * @static
51504 * @memberOf _
51505 * @since 4.0.0
51506 * @category Collection
51507 * @param {Array|Object} collection The collection to iterate over.
51508 * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]]
51509 * The iteratees to sort by.
51510 * @param {string[]} [orders] The sort orders of `iteratees`.
51511 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`.
51512 * @returns {Array} Returns the new sorted array.
51513 * @example
51514 *
51515 * var users = [
51516 * { 'user': 'fred', 'age': 48 },
51517 * { 'user': 'barney', 'age': 34 },
51518 * { 'user': 'fred', 'age': 40 },
51519 * { 'user': 'barney', 'age': 36 }
51520 * ];
51521 *
51522 * // Sort by `user` in ascending order and by `age` in descending order.
51523 * _.orderBy(users, ['user', 'age'], ['asc', 'desc']);
51524 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]]
51525 */
51526 function orderBy(collection, iteratees, orders, guard) {
51527 if (collection == null) {
51528 return [];
51529 }
51530 if (!isArray(iteratees)) {
51531 iteratees = iteratees == null ? [] : [iteratees];
51532 }
51533 orders = guard ? undefined : orders;
51534 if (!isArray(orders)) {
51535 orders = orders == null ? [] : [orders];
51536 }
51537 return baseOrderBy(collection, iteratees, orders);
51538 }
51539
51540 /**
51541 * Creates an array of elements split into two groups, the first of which
51542 * contains elements `predicate` returns truthy for, the second of which
51543 * contains elements `predicate` returns falsey for. The predicate is
51544 * invoked with one argument: (value).
51545 *
51546 * @static
51547 * @memberOf _
51548 * @since 3.0.0
51549 * @category Collection
51550 * @param {Array|Object} collection The collection to iterate over.
51551 * @param {Function} [predicate=_.identity] The function invoked per iteration.
51552 * @returns {Array} Returns the array of grouped elements.
51553 * @example
51554 *
51555 * var users = [
51556 * { 'user': 'barney', 'age': 36, 'active': false },
51557 * { 'user': 'fred', 'age': 40, 'active': true },
51558 * { 'user': 'pebbles', 'age': 1, 'active': false }
51559 * ];
51560 *
51561 * _.partition(users, function(o) { return o.active; });
51562 * // => objects for [['fred'], ['barney', 'pebbles']]
51563 *
51564 * // The `_.matches` iteratee shorthand.
51565 * _.partition(users, { 'age': 1, 'active': false });
51566 * // => objects for [['pebbles'], ['barney', 'fred']]
51567 *
51568 * // The `_.matchesProperty` iteratee shorthand.
51569 * _.partition(users, ['active', false]);
51570 * // => objects for [['barney', 'pebbles'], ['fred']]
51571 *
51572 * // The `_.property` iteratee shorthand.
51573 * _.partition(users, 'active');
51574 * // => objects for [['fred'], ['barney', 'pebbles']]
51575 */
51576 var partition = createAggregator(function(result, value, key) {
51577 result[key ? 0 : 1].push(value);
51578 }, function() { return [[], []]; });
51579
51580 /**
51581 * Reduces `collection` to a value which is the accumulated result of running
51582 * each element in `collection` thru `iteratee`, where each successive
51583 * invocation is supplied the return value of the previous. If `accumulator`
51584 * is not given, the first element of `collection` is used as the initial
51585 * value. The iteratee is invoked with four arguments:
51586 * (accumulator, value, index|key, collection).
51587 *
51588 * Many lodash methods are guarded to work as iteratees for methods like
51589 * `_.reduce`, `_.reduceRight`, and `_.transform`.
51590 *
51591 * The guarded methods are:
51592 * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`,
51593 * and `sortBy`
51594 *
51595 * @static
51596 * @memberOf _
51597 * @since 0.1.0
51598 * @category Collection
51599 * @param {Array|Object} collection The collection to iterate over.
51600 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
51601 * @param {*} [accumulator] The initial value.
51602 * @returns {*} Returns the accumulated value.
51603 * @see _.reduceRight
51604 * @example
51605 *
51606 * _.reduce([1, 2], function(sum, n) {
51607 * return sum + n;
51608 * }, 0);
51609 * // => 3
51610 *
51611 * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
51612 * (result[value] || (result[value] = [])).push(key);
51613 * return result;
51614 * }, {});
51615 * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed)
51616 */
51617 function reduce(collection, iteratee, accumulator) {
51618 var func = isArray(collection) ? arrayReduce : baseReduce,
51619 initAccum = arguments.length < 3;
51620
51621 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEach);
51622 }
51623
51624 /**
51625 * This method is like `_.reduce` except that it iterates over elements of
51626 * `collection` from right to left.
51627 *
51628 * @static
51629 * @memberOf _
51630 * @since 0.1.0
51631 * @category Collection
51632 * @param {Array|Object} collection The collection to iterate over.
51633 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
51634 * @param {*} [accumulator] The initial value.
51635 * @returns {*} Returns the accumulated value.
51636 * @see _.reduce
51637 * @example
51638 *
51639 * var array = [[0, 1], [2, 3], [4, 5]];
51640 *
51641 * _.reduceRight(array, function(flattened, other) {
51642 * return flattened.concat(other);
51643 * }, []);
51644 * // => [4, 5, 2, 3, 0, 1]
51645 */
51646 function reduceRight(collection, iteratee, accumulator) {
51647 var func = isArray(collection) ? arrayReduceRight : baseReduce,
51648 initAccum = arguments.length < 3;
51649
51650 return func(collection, getIteratee(iteratee, 4), accumulator, initAccum, baseEachRight);
51651 }
51652
51653 /**
51654 * The opposite of `_.filter`; this method returns the elements of `collection`
51655 * that `predicate` does **not** return truthy for.
51656 *
51657 * @static
51658 * @memberOf _
51659 * @since 0.1.0
51660 * @category Collection
51661 * @param {Array|Object} collection The collection to iterate over.
51662 * @param {Function} [predicate=_.identity] The function invoked per iteration.
51663 * @returns {Array} Returns the new filtered array.
51664 * @see _.filter
51665 * @example
51666 *
51667 * var users = [
51668 * { 'user': 'barney', 'age': 36, 'active': false },
51669 * { 'user': 'fred', 'age': 40, 'active': true }
51670 * ];
51671 *
51672 * _.reject(users, function(o) { return !o.active; });
51673 * // => objects for ['fred']
51674 *
51675 * // The `_.matches` iteratee shorthand.
51676 * _.reject(users, { 'age': 40, 'active': true });
51677 * // => objects for ['barney']
51678 *
51679 * // The `_.matchesProperty` iteratee shorthand.
51680 * _.reject(users, ['active', false]);
51681 * // => objects for ['fred']
51682 *
51683 * // The `_.property` iteratee shorthand.
51684 * _.reject(users, 'active');
51685 * // => objects for ['barney']
51686 */
51687 function reject(collection, predicate) {
51688 var func = isArray(collection) ? arrayFilter : baseFilter;
51689 return func(collection, negate(getIteratee(predicate, 3)));
51690 }
51691
51692 /**
51693 * Gets a random element from `collection`.
51694 *
51695 * @static
51696 * @memberOf _
51697 * @since 2.0.0
51698 * @category Collection
51699 * @param {Array|Object} collection The collection to sample.
51700 * @returns {*} Returns the random element.
51701 * @example
51702 *
51703 * _.sample([1, 2, 3, 4]);
51704 * // => 2
51705 */
51706 function sample(collection) {
51707 var func = isArray(collection) ? arraySample : baseSample;
51708 return func(collection);
51709 }
51710
51711 /**
51712 * Gets `n` random elements at unique keys from `collection` up to the
51713 * size of `collection`.
51714 *
51715 * @static
51716 * @memberOf _
51717 * @since 4.0.0
51718 * @category Collection
51719 * @param {Array|Object} collection The collection to sample.
51720 * @param {number} [n=1] The number of elements to sample.
51721 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
51722 * @returns {Array} Returns the random elements.
51723 * @example
51724 *
51725 * _.sampleSize([1, 2, 3], 2);
51726 * // => [3, 1]
51727 *
51728 * _.sampleSize([1, 2, 3], 4);
51729 * // => [2, 3, 1]
51730 */
51731 function sampleSize(collection, n, guard) {
51732 if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) {
51733 n = 1;
51734 } else {
51735 n = toInteger(n);
51736 }
51737 var func = isArray(collection) ? arraySampleSize : baseSampleSize;
51738 return func(collection, n);
51739 }
51740
51741 /**
51742 * Creates an array of shuffled values, using a version of the
51743 * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle).
51744 *
51745 * @static
51746 * @memberOf _
51747 * @since 0.1.0
51748 * @category Collection
51749 * @param {Array|Object} collection The collection to shuffle.
51750 * @returns {Array} Returns the new shuffled array.
51751 * @example
51752 *
51753 * _.shuffle([1, 2, 3, 4]);
51754 * // => [4, 1, 3, 2]
51755 */
51756 function shuffle(collection) {
51757 var func = isArray(collection) ? arrayShuffle : baseShuffle;
51758 return func(collection);
51759 }
51760
51761 /**
51762 * Gets the size of `collection` by returning its length for array-like
51763 * values or the number of own enumerable string keyed properties for objects.
51764 *
51765 * @static
51766 * @memberOf _
51767 * @since 0.1.0
51768 * @category Collection
51769 * @param {Array|Object|string} collection The collection to inspect.
51770 * @returns {number} Returns the collection size.
51771 * @example
51772 *
51773 * _.size([1, 2, 3]);
51774 * // => 3
51775 *
51776 * _.size({ 'a': 1, 'b': 2 });
51777 * // => 2
51778 *
51779 * _.size('pebbles');
51780 * // => 7
51781 */
51782 function size(collection) {
51783 if (collection == null) {
51784 return 0;
51785 }
51786 if (isArrayLike(collection)) {
51787 return isString(collection) ? stringSize(collection) : collection.length;
51788 }
51789 var tag = getTag(collection);
51790 if (tag == mapTag || tag == setTag) {
51791 return collection.size;
51792 }
51793 return baseKeys(collection).length;
51794 }
51795
51796 /**
51797 * Checks if `predicate` returns truthy for **any** element of `collection`.
51798 * Iteration is stopped once `predicate` returns truthy. The predicate is
51799 * invoked with three arguments: (value, index|key, collection).
51800 *
51801 * @static
51802 * @memberOf _
51803 * @since 0.1.0
51804 * @category Collection
51805 * @param {Array|Object} collection The collection to iterate over.
51806 * @param {Function} [predicate=_.identity] The function invoked per iteration.
51807 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
51808 * @returns {boolean} Returns `true` if any element passes the predicate check,
51809 * else `false`.
51810 * @example
51811 *
51812 * _.some([null, 0, 'yes', false], Boolean);
51813 * // => true
51814 *
51815 * var users = [
51816 * { 'user': 'barney', 'active': true },
51817 * { 'user': 'fred', 'active': false }
51818 * ];
51819 *
51820 * // The `_.matches` iteratee shorthand.
51821 * _.some(users, { 'user': 'barney', 'active': false });
51822 * // => false
51823 *
51824 * // The `_.matchesProperty` iteratee shorthand.
51825 * _.some(users, ['active', false]);
51826 * // => true
51827 *
51828 * // The `_.property` iteratee shorthand.
51829 * _.some(users, 'active');
51830 * // => true
51831 */
51832 function some(collection, predicate, guard) {
51833 var func = isArray(collection) ? arraySome : baseSome;
51834 if (guard && isIterateeCall(collection, predicate, guard)) {
51835 predicate = undefined;
51836 }
51837 return func(collection, getIteratee(predicate, 3));
51838 }
51839
51840 /**
51841 * Creates an array of elements, sorted in ascending order by the results of
51842 * running each element in a collection thru each iteratee. This method
51843 * performs a stable sort, that is, it preserves the original sort order of
51844 * equal elements. The iteratees are invoked with one argument: (value).
51845 *
51846 * @static
51847 * @memberOf _
51848 * @since 0.1.0
51849 * @category Collection
51850 * @param {Array|Object} collection The collection to iterate over.
51851 * @param {...(Function|Function[])} [iteratees=[_.identity]]
51852 * The iteratees to sort by.
51853 * @returns {Array} Returns the new sorted array.
51854 * @example
51855 *
51856 * var users = [
51857 * { 'user': 'fred', 'age': 48 },
51858 * { 'user': 'barney', 'age': 36 },
51859 * { 'user': 'fred', 'age': 30 },
51860 * { 'user': 'barney', 'age': 34 }
51861 * ];
51862 *
51863 * _.sortBy(users, [function(o) { return o.user; }]);
51864 * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]]
51865 *
51866 * _.sortBy(users, ['user', 'age']);
51867 * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]]
51868 */
51869 var sortBy = baseRest(function(collection, iteratees) {
51870 if (collection == null) {
51871 return [];
51872 }
51873 var length = iteratees.length;
51874 if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) {
51875 iteratees = [];
51876 } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) {
51877 iteratees = [iteratees[0]];
51878 }
51879 return baseOrderBy(collection, baseFlatten(iteratees, 1), []);
51880 });
51881
51882 /*------------------------------------------------------------------------*/
51883
51884 /**
51885 * Gets the timestamp of the number of milliseconds that have elapsed since
51886 * the Unix epoch (1 January 1970 00:00:00 UTC).
51887 *
51888 * @static
51889 * @memberOf _
51890 * @since 2.4.0
51891 * @category Date
51892 * @returns {number} Returns the timestamp.
51893 * @example
51894 *
51895 * _.defer(function(stamp) {
51896 * console.log(_.now() - stamp);
51897 * }, _.now());
51898 * // => Logs the number of milliseconds it took for the deferred invocation.
51899 */
51900 var now = ctxNow || function() {
51901 return root.Date.now();
51902 };
51903
51904 /*------------------------------------------------------------------------*/
51905
51906 /**
51907 * The opposite of `_.before`; this method creates a function that invokes
51908 * `func` once it's called `n` or more times.
51909 *
51910 * @static
51911 * @memberOf _
51912 * @since 0.1.0
51913 * @category Function
51914 * @param {number} n The number of calls before `func` is invoked.
51915 * @param {Function} func The function to restrict.
51916 * @returns {Function} Returns the new restricted function.
51917 * @example
51918 *
51919 * var saves = ['profile', 'settings'];
51920 *
51921 * var done = _.after(saves.length, function() {
51922 * console.log('done saving!');
51923 * });
51924 *
51925 * _.forEach(saves, function(type) {
51926 * asyncSave({ 'type': type, 'complete': done });
51927 * });
51928 * // => Logs 'done saving!' after the two async saves have completed.
51929 */
51930 function after(n, func) {
51931 if (typeof func != 'function') {
51932 throw new TypeError(FUNC_ERROR_TEXT);
51933 }
51934 n = toInteger(n);
51935 return function() {
51936 if (--n < 1) {
51937 return func.apply(this, arguments);
51938 }
51939 };
51940 }
51941
51942 /**
51943 * Creates a function that invokes `func`, with up to `n` arguments,
51944 * ignoring any additional arguments.
51945 *
51946 * @static
51947 * @memberOf _
51948 * @since 3.0.0
51949 * @category Function
51950 * @param {Function} func The function to cap arguments for.
51951 * @param {number} [n=func.length] The arity cap.
51952 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
51953 * @returns {Function} Returns the new capped function.
51954 * @example
51955 *
51956 * _.map(['6', '8', '10'], _.ary(parseInt, 1));
51957 * // => [6, 8, 10]
51958 */
51959 function ary(func, n, guard) {
51960 n = guard ? undefined : n;
51961 n = (func && n == null) ? func.length : n;
51962 return createWrap(func, WRAP_ARY_FLAG, undefined, undefined, undefined, undefined, n);
51963 }
51964
51965 /**
51966 * Creates a function that invokes `func`, with the `this` binding and arguments
51967 * of the created function, while it's called less than `n` times. Subsequent
51968 * calls to the created function return the result of the last `func` invocation.
51969 *
51970 * @static
51971 * @memberOf _
51972 * @since 3.0.0
51973 * @category Function
51974 * @param {number} n The number of calls at which `func` is no longer invoked.
51975 * @param {Function} func The function to restrict.
51976 * @returns {Function} Returns the new restricted function.
51977 * @example
51978 *
51979 * jQuery(element).on('click', _.before(5, addContactToList));
51980 * // => Allows adding up to 4 contacts to the list.
51981 */
51982 function before(n, func) {
51983 var result;
51984 if (typeof func != 'function') {
51985 throw new TypeError(FUNC_ERROR_TEXT);
51986 }
51987 n = toInteger(n);
51988 return function() {
51989 if (--n > 0) {
51990 result = func.apply(this, arguments);
51991 }
51992 if (n <= 1) {
51993 func = undefined;
51994 }
51995 return result;
51996 };
51997 }
51998
51999 /**
52000 * Creates a function that invokes `func` with the `this` binding of `thisArg`
52001 * and `partials` prepended to the arguments it receives.
52002 *
52003 * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds,
52004 * may be used as a placeholder for partially applied arguments.
52005 *
52006 * **Note:** Unlike native `Function#bind`, this method doesn't set the "length"
52007 * property of bound functions.
52008 *
52009 * @static
52010 * @memberOf _
52011 * @since 0.1.0
52012 * @category Function
52013 * @param {Function} func The function to bind.
52014 * @param {*} thisArg The `this` binding of `func`.
52015 * @param {...*} [partials] The arguments to be partially applied.
52016 * @returns {Function} Returns the new bound function.
52017 * @example
52018 *
52019 * function greet(greeting, punctuation) {
52020 * return greeting + ' ' + this.user + punctuation;
52021 * }
52022 *
52023 * var object = { 'user': 'fred' };
52024 *
52025 * var bound = _.bind(greet, object, 'hi');
52026 * bound('!');
52027 * // => 'hi fred!'
52028 *
52029 * // Bound with placeholders.
52030 * var bound = _.bind(greet, object, _, '!');
52031 * bound('hi');
52032 * // => 'hi fred!'
52033 */
52034 var bind = baseRest(function(func, thisArg, partials) {
52035 var bitmask = WRAP_BIND_FLAG;
52036 if (partials.length) {
52037 var holders = replaceHolders(partials, getHolder(bind));
52038 bitmask |= WRAP_PARTIAL_FLAG;
52039 }
52040 return createWrap(func, bitmask, thisArg, partials, holders);
52041 });
52042
52043 /**
52044 * Creates a function that invokes the method at `object[key]` with `partials`
52045 * prepended to the arguments it receives.
52046 *
52047 * This method differs from `_.bind` by allowing bound functions to reference
52048 * methods that may be redefined or don't yet exist. See
52049 * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern)
52050 * for more details.
52051 *
52052 * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic
52053 * builds, may be used as a placeholder for partially applied arguments.
52054 *
52055 * @static
52056 * @memberOf _
52057 * @since 0.10.0
52058 * @category Function
52059 * @param {Object} object The object to invoke the method on.
52060 * @param {string} key The key of the method.
52061 * @param {...*} [partials] The arguments to be partially applied.
52062 * @returns {Function} Returns the new bound function.
52063 * @example
52064 *
52065 * var object = {
52066 * 'user': 'fred',
52067 * 'greet': function(greeting, punctuation) {
52068 * return greeting + ' ' + this.user + punctuation;
52069 * }
52070 * };
52071 *
52072 * var bound = _.bindKey(object, 'greet', 'hi');
52073 * bound('!');
52074 * // => 'hi fred!'
52075 *
52076 * object.greet = function(greeting, punctuation) {
52077 * return greeting + 'ya ' + this.user + punctuation;
52078 * };
52079 *
52080 * bound('!');
52081 * // => 'hiya fred!'
52082 *
52083 * // Bound with placeholders.
52084 * var bound = _.bindKey(object, 'greet', _, '!');
52085 * bound('hi');
52086 * // => 'hiya fred!'
52087 */
52088 var bindKey = baseRest(function(object, key, partials) {
52089 var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG;
52090 if (partials.length) {
52091 var holders = replaceHolders(partials, getHolder(bindKey));
52092 bitmask |= WRAP_PARTIAL_FLAG;
52093 }
52094 return createWrap(key, bitmask, object, partials, holders);
52095 });
52096
52097 /**
52098 * Creates a function that accepts arguments of `func` and either invokes
52099 * `func` returning its result, if at least `arity` number of arguments have
52100 * been provided, or returns a function that accepts the remaining `func`
52101 * arguments, and so on. The arity of `func` may be specified if `func.length`
52102 * is not sufficient.
52103 *
52104 * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds,
52105 * may be used as a placeholder for provided arguments.
52106 *
52107 * **Note:** This method doesn't set the "length" property of curried functions.
52108 *
52109 * @static
52110 * @memberOf _
52111 * @since 2.0.0
52112 * @category Function
52113 * @param {Function} func The function to curry.
52114 * @param {number} [arity=func.length] The arity of `func`.
52115 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
52116 * @returns {Function} Returns the new curried function.
52117 * @example
52118 *
52119 * var abc = function(a, b, c) {
52120 * return [a, b, c];
52121 * };
52122 *
52123 * var curried = _.curry(abc);
52124 *
52125 * curried(1)(2)(3);
52126 * // => [1, 2, 3]
52127 *
52128 * curried(1, 2)(3);
52129 * // => [1, 2, 3]
52130 *
52131 * curried(1, 2, 3);
52132 * // => [1, 2, 3]
52133 *
52134 * // Curried with placeholders.
52135 * curried(1)(_, 3)(2);
52136 * // => [1, 2, 3]
52137 */
52138 function curry(func, arity, guard) {
52139 arity = guard ? undefined : arity;
52140 var result = createWrap(func, WRAP_CURRY_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
52141 result.placeholder = curry.placeholder;
52142 return result;
52143 }
52144
52145 /**
52146 * This method is like `_.curry` except that arguments are applied to `func`
52147 * in the manner of `_.partialRight` instead of `_.partial`.
52148 *
52149 * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic
52150 * builds, may be used as a placeholder for provided arguments.
52151 *
52152 * **Note:** This method doesn't set the "length" property of curried functions.
52153 *
52154 * @static
52155 * @memberOf _
52156 * @since 3.0.0
52157 * @category Function
52158 * @param {Function} func The function to curry.
52159 * @param {number} [arity=func.length] The arity of `func`.
52160 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
52161 * @returns {Function} Returns the new curried function.
52162 * @example
52163 *
52164 * var abc = function(a, b, c) {
52165 * return [a, b, c];
52166 * };
52167 *
52168 * var curried = _.curryRight(abc);
52169 *
52170 * curried(3)(2)(1);
52171 * // => [1, 2, 3]
52172 *
52173 * curried(2, 3)(1);
52174 * // => [1, 2, 3]
52175 *
52176 * curried(1, 2, 3);
52177 * // => [1, 2, 3]
52178 *
52179 * // Curried with placeholders.
52180 * curried(3)(1, _)(2);
52181 * // => [1, 2, 3]
52182 */
52183 function curryRight(func, arity, guard) {
52184 arity = guard ? undefined : arity;
52185 var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity);
52186 result.placeholder = curryRight.placeholder;
52187 return result;
52188 }
52189
52190 /**
52191 * Creates a debounced function that delays invoking `func` until after `wait`
52192 * milliseconds have elapsed since the last time the debounced function was
52193 * invoked. The debounced function comes with a `cancel` method to cancel
52194 * delayed `func` invocations and a `flush` method to immediately invoke them.
52195 * Provide `options` to indicate whether `func` should be invoked on the
52196 * leading and/or trailing edge of the `wait` timeout. The `func` is invoked
52197 * with the last arguments provided to the debounced function. Subsequent
52198 * calls to the debounced function return the result of the last `func`
52199 * invocation.
52200 *
52201 * **Note:** If `leading` and `trailing` options are `true`, `func` is
52202 * invoked on the trailing edge of the timeout only if the debounced function
52203 * is invoked more than once during the `wait` timeout.
52204 *
52205 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
52206 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
52207 *
52208 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
52209 * for details over the differences between `_.debounce` and `_.throttle`.
52210 *
52211 * @static
52212 * @memberOf _
52213 * @since 0.1.0
52214 * @category Function
52215 * @param {Function} func The function to debounce.
52216 * @param {number} [wait=0] The number of milliseconds to delay.
52217 * @param {Object} [options={}] The options object.
52218 * @param {boolean} [options.leading=false]
52219 * Specify invoking on the leading edge of the timeout.
52220 * @param {number} [options.maxWait]
52221 * The maximum time `func` is allowed to be delayed before it's invoked.
52222 * @param {boolean} [options.trailing=true]
52223 * Specify invoking on the trailing edge of the timeout.
52224 * @returns {Function} Returns the new debounced function.
52225 * @example
52226 *
52227 * // Avoid costly calculations while the window size is in flux.
52228 * jQuery(window).on('resize', _.debounce(calculateLayout, 150));
52229 *
52230 * // Invoke `sendMail` when clicked, debouncing subsequent calls.
52231 * jQuery(element).on('click', _.debounce(sendMail, 300, {
52232 * 'leading': true,
52233 * 'trailing': false
52234 * }));
52235 *
52236 * // Ensure `batchLog` is invoked once after 1 second of debounced calls.
52237 * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 });
52238 * var source = new EventSource('/stream');
52239 * jQuery(source).on('message', debounced);
52240 *
52241 * // Cancel the trailing debounced invocation.
52242 * jQuery(window).on('popstate', debounced.cancel);
52243 */
52244 function debounce(func, wait, options) {
52245 var lastArgs,
52246 lastThis,
52247 maxWait,
52248 result,
52249 timerId,
52250 lastCallTime,
52251 lastInvokeTime = 0,
52252 leading = false,
52253 maxing = false,
52254 trailing = true;
52255
52256 if (typeof func != 'function') {
52257 throw new TypeError(FUNC_ERROR_TEXT);
52258 }
52259 wait = toNumber(wait) || 0;
52260 if (isObject(options)) {
52261 leading = !!options.leading;
52262 maxing = 'maxWait' in options;
52263 maxWait = maxing ? nativeMax(toNumber(options.maxWait) || 0, wait) : maxWait;
52264 trailing = 'trailing' in options ? !!options.trailing : trailing;
52265 }
52266
52267 function invokeFunc(time) {
52268 var args = lastArgs,
52269 thisArg = lastThis;
52270
52271 lastArgs = lastThis = undefined;
52272 lastInvokeTime = time;
52273 result = func.apply(thisArg, args);
52274 return result;
52275 }
52276
52277 function leadingEdge(time) {
52278 // Reset any `maxWait` timer.
52279 lastInvokeTime = time;
52280 // Start the timer for the trailing edge.
52281 timerId = setTimeout(timerExpired, wait);
52282 // Invoke the leading edge.
52283 return leading ? invokeFunc(time) : result;
52284 }
52285
52286 function remainingWait(time) {
52287 var timeSinceLastCall = time - lastCallTime,
52288 timeSinceLastInvoke = time - lastInvokeTime,
52289 timeWaiting = wait - timeSinceLastCall;
52290
52291 return maxing
52292 ? nativeMin(timeWaiting, maxWait - timeSinceLastInvoke)
52293 : timeWaiting;
52294 }
52295
52296 function shouldInvoke(time) {
52297 var timeSinceLastCall = time - lastCallTime,
52298 timeSinceLastInvoke = time - lastInvokeTime;
52299
52300 // Either this is the first call, activity has stopped and we're at the
52301 // trailing edge, the system time has gone backwards and we're treating
52302 // it as the trailing edge, or we've hit the `maxWait` limit.
52303 return (lastCallTime === undefined || (timeSinceLastCall >= wait) ||
52304 (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait));
52305 }
52306
52307 function timerExpired() {
52308 var time = now();
52309 if (shouldInvoke(time)) {
52310 return trailingEdge(time);
52311 }
52312 // Restart the timer.
52313 timerId = setTimeout(timerExpired, remainingWait(time));
52314 }
52315
52316 function trailingEdge(time) {
52317 timerId = undefined;
52318
52319 // Only invoke if we have `lastArgs` which means `func` has been
52320 // debounced at least once.
52321 if (trailing && lastArgs) {
52322 return invokeFunc(time);
52323 }
52324 lastArgs = lastThis = undefined;
52325 return result;
52326 }
52327
52328 function cancel() {
52329 if (timerId !== undefined) {
52330 clearTimeout(timerId);
52331 }
52332 lastInvokeTime = 0;
52333 lastArgs = lastCallTime = lastThis = timerId = undefined;
52334 }
52335
52336 function flush() {
52337 return timerId === undefined ? result : trailingEdge(now());
52338 }
52339
52340 function debounced() {
52341 var time = now(),
52342 isInvoking = shouldInvoke(time);
52343
52344 lastArgs = arguments;
52345 lastThis = this;
52346 lastCallTime = time;
52347
52348 if (isInvoking) {
52349 if (timerId === undefined) {
52350 return leadingEdge(lastCallTime);
52351 }
52352 if (maxing) {
52353 // Handle invocations in a tight loop.
52354 clearTimeout(timerId);
52355 timerId = setTimeout(timerExpired, wait);
52356 return invokeFunc(lastCallTime);
52357 }
52358 }
52359 if (timerId === undefined) {
52360 timerId = setTimeout(timerExpired, wait);
52361 }
52362 return result;
52363 }
52364 debounced.cancel = cancel;
52365 debounced.flush = flush;
52366 return debounced;
52367 }
52368
52369 /**
52370 * Defers invoking the `func` until the current call stack has cleared. Any
52371 * additional arguments are provided to `func` when it's invoked.
52372 *
52373 * @static
52374 * @memberOf _
52375 * @since 0.1.0
52376 * @category Function
52377 * @param {Function} func The function to defer.
52378 * @param {...*} [args] The arguments to invoke `func` with.
52379 * @returns {number} Returns the timer id.
52380 * @example
52381 *
52382 * _.defer(function(text) {
52383 * console.log(text);
52384 * }, 'deferred');
52385 * // => Logs 'deferred' after one millisecond.
52386 */
52387 var defer = baseRest(function(func, args) {
52388 return baseDelay(func, 1, args);
52389 });
52390
52391 /**
52392 * Invokes `func` after `wait` milliseconds. Any additional arguments are
52393 * provided to `func` when it's invoked.
52394 *
52395 * @static
52396 * @memberOf _
52397 * @since 0.1.0
52398 * @category Function
52399 * @param {Function} func The function to delay.
52400 * @param {number} wait The number of milliseconds to delay invocation.
52401 * @param {...*} [args] The arguments to invoke `func` with.
52402 * @returns {number} Returns the timer id.
52403 * @example
52404 *
52405 * _.delay(function(text) {
52406 * console.log(text);
52407 * }, 1000, 'later');
52408 * // => Logs 'later' after one second.
52409 */
52410 var delay = baseRest(function(func, wait, args) {
52411 return baseDelay(func, toNumber(wait) || 0, args);
52412 });
52413
52414 /**
52415 * Creates a function that invokes `func` with arguments reversed.
52416 *
52417 * @static
52418 * @memberOf _
52419 * @since 4.0.0
52420 * @category Function
52421 * @param {Function} func The function to flip arguments for.
52422 * @returns {Function} Returns the new flipped function.
52423 * @example
52424 *
52425 * var flipped = _.flip(function() {
52426 * return _.toArray(arguments);
52427 * });
52428 *
52429 * flipped('a', 'b', 'c', 'd');
52430 * // => ['d', 'c', 'b', 'a']
52431 */
52432 function flip(func) {
52433 return createWrap(func, WRAP_FLIP_FLAG);
52434 }
52435
52436 /**
52437 * Creates a function that memoizes the result of `func`. If `resolver` is
52438 * provided, it determines the cache key for storing the result based on the
52439 * arguments provided to the memoized function. By default, the first argument
52440 * provided to the memoized function is used as the map cache key. The `func`
52441 * is invoked with the `this` binding of the memoized function.
52442 *
52443 * **Note:** The cache is exposed as the `cache` property on the memoized
52444 * function. Its creation may be customized by replacing the `_.memoize.Cache`
52445 * constructor with one whose instances implement the
52446 * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object)
52447 * method interface of `clear`, `delete`, `get`, `has`, and `set`.
52448 *
52449 * @static
52450 * @memberOf _
52451 * @since 0.1.0
52452 * @category Function
52453 * @param {Function} func The function to have its output memoized.
52454 * @param {Function} [resolver] The function to resolve the cache key.
52455 * @returns {Function} Returns the new memoized function.
52456 * @example
52457 *
52458 * var object = { 'a': 1, 'b': 2 };
52459 * var other = { 'c': 3, 'd': 4 };
52460 *
52461 * var values = _.memoize(_.values);
52462 * values(object);
52463 * // => [1, 2]
52464 *
52465 * values(other);
52466 * // => [3, 4]
52467 *
52468 * object.a = 2;
52469 * values(object);
52470 * // => [1, 2]
52471 *
52472 * // Modify the result cache.
52473 * values.cache.set(object, ['a', 'b']);
52474 * values(object);
52475 * // => ['a', 'b']
52476 *
52477 * // Replace `_.memoize.Cache`.
52478 * _.memoize.Cache = WeakMap;
52479 */
52480 function memoize(func, resolver) {
52481 if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) {
52482 throw new TypeError(FUNC_ERROR_TEXT);
52483 }
52484 var memoized = function() {
52485 var args = arguments,
52486 key = resolver ? resolver.apply(this, args) : args[0],
52487 cache = memoized.cache;
52488
52489 if (cache.has(key)) {
52490 return cache.get(key);
52491 }
52492 var result = func.apply(this, args);
52493 memoized.cache = cache.set(key, result) || cache;
52494 return result;
52495 };
52496 memoized.cache = new (memoize.Cache || MapCache);
52497 return memoized;
52498 }
52499
52500 // Expose `MapCache`.
52501 memoize.Cache = MapCache;
52502
52503 /**
52504 * Creates a function that negates the result of the predicate `func`. The
52505 * `func` predicate is invoked with the `this` binding and arguments of the
52506 * created function.
52507 *
52508 * @static
52509 * @memberOf _
52510 * @since 3.0.0
52511 * @category Function
52512 * @param {Function} predicate The predicate to negate.
52513 * @returns {Function} Returns the new negated function.
52514 * @example
52515 *
52516 * function isEven(n) {
52517 * return n % 2 == 0;
52518 * }
52519 *
52520 * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven));
52521 * // => [1, 3, 5]
52522 */
52523 function negate(predicate) {
52524 if (typeof predicate != 'function') {
52525 throw new TypeError(FUNC_ERROR_TEXT);
52526 }
52527 return function() {
52528 var args = arguments;
52529 switch (args.length) {
52530 case 0: return !predicate.call(this);
52531 case 1: return !predicate.call(this, args[0]);
52532 case 2: return !predicate.call(this, args[0], args[1]);
52533 case 3: return !predicate.call(this, args[0], args[1], args[2]);
52534 }
52535 return !predicate.apply(this, args);
52536 };
52537 }
52538
52539 /**
52540 * Creates a function that is restricted to invoking `func` once. Repeat calls
52541 * to the function return the value of the first invocation. The `func` is
52542 * invoked with the `this` binding and arguments of the created function.
52543 *
52544 * @static
52545 * @memberOf _
52546 * @since 0.1.0
52547 * @category Function
52548 * @param {Function} func The function to restrict.
52549 * @returns {Function} Returns the new restricted function.
52550 * @example
52551 *
52552 * var initialize = _.once(createApplication);
52553 * initialize();
52554 * initialize();
52555 * // => `createApplication` is invoked once
52556 */
52557 function once(func) {
52558 return before(2, func);
52559 }
52560
52561 /**
52562 * Creates a function that invokes `func` with its arguments transformed.
52563 *
52564 * @static
52565 * @since 4.0.0
52566 * @memberOf _
52567 * @category Function
52568 * @param {Function} func The function to wrap.
52569 * @param {...(Function|Function[])} [transforms=[_.identity]]
52570 * The argument transforms.
52571 * @returns {Function} Returns the new function.
52572 * @example
52573 *
52574 * function doubled(n) {
52575 * return n * 2;
52576 * }
52577 *
52578 * function square(n) {
52579 * return n * n;
52580 * }
52581 *
52582 * var func = _.overArgs(function(x, y) {
52583 * return [x, y];
52584 * }, [square, doubled]);
52585 *
52586 * func(9, 3);
52587 * // => [81, 6]
52588 *
52589 * func(10, 5);
52590 * // => [100, 10]
52591 */
52592 var overArgs = castRest(function(func, transforms) {
52593 transforms = (transforms.length == 1 && isArray(transforms[0]))
52594 ? arrayMap(transforms[0], baseUnary(getIteratee()))
52595 : arrayMap(baseFlatten(transforms, 1), baseUnary(getIteratee()));
52596
52597 var funcsLength = transforms.length;
52598 return baseRest(function(args) {
52599 var index = -1,
52600 length = nativeMin(args.length, funcsLength);
52601
52602 while (++index < length) {
52603 args[index] = transforms[index].call(this, args[index]);
52604 }
52605 return apply(func, this, args);
52606 });
52607 });
52608
52609 /**
52610 * Creates a function that invokes `func` with `partials` prepended to the
52611 * arguments it receives. This method is like `_.bind` except it does **not**
52612 * alter the `this` binding.
52613 *
52614 * The `_.partial.placeholder` value, which defaults to `_` in monolithic
52615 * builds, may be used as a placeholder for partially applied arguments.
52616 *
52617 * **Note:** This method doesn't set the "length" property of partially
52618 * applied functions.
52619 *
52620 * @static
52621 * @memberOf _
52622 * @since 0.2.0
52623 * @category Function
52624 * @param {Function} func The function to partially apply arguments to.
52625 * @param {...*} [partials] The arguments to be partially applied.
52626 * @returns {Function} Returns the new partially applied function.
52627 * @example
52628 *
52629 * function greet(greeting, name) {
52630 * return greeting + ' ' + name;
52631 * }
52632 *
52633 * var sayHelloTo = _.partial(greet, 'hello');
52634 * sayHelloTo('fred');
52635 * // => 'hello fred'
52636 *
52637 * // Partially applied with placeholders.
52638 * var greetFred = _.partial(greet, _, 'fred');
52639 * greetFred('hi');
52640 * // => 'hi fred'
52641 */
52642 var partial = baseRest(function(func, partials) {
52643 var holders = replaceHolders(partials, getHolder(partial));
52644 return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders);
52645 });
52646
52647 /**
52648 * This method is like `_.partial` except that partially applied arguments
52649 * are appended to the arguments it receives.
52650 *
52651 * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic
52652 * builds, may be used as a placeholder for partially applied arguments.
52653 *
52654 * **Note:** This method doesn't set the "length" property of partially
52655 * applied functions.
52656 *
52657 * @static
52658 * @memberOf _
52659 * @since 1.0.0
52660 * @category Function
52661 * @param {Function} func The function to partially apply arguments to.
52662 * @param {...*} [partials] The arguments to be partially applied.
52663 * @returns {Function} Returns the new partially applied function.
52664 * @example
52665 *
52666 * function greet(greeting, name) {
52667 * return greeting + ' ' + name;
52668 * }
52669 *
52670 * var greetFred = _.partialRight(greet, 'fred');
52671 * greetFred('hi');
52672 * // => 'hi fred'
52673 *
52674 * // Partially applied with placeholders.
52675 * var sayHelloTo = _.partialRight(greet, 'hello', _);
52676 * sayHelloTo('fred');
52677 * // => 'hello fred'
52678 */
52679 var partialRight = baseRest(function(func, partials) {
52680 var holders = replaceHolders(partials, getHolder(partialRight));
52681 return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders);
52682 });
52683
52684 /**
52685 * Creates a function that invokes `func` with arguments arranged according
52686 * to the specified `indexes` where the argument value at the first index is
52687 * provided as the first argument, the argument value at the second index is
52688 * provided as the second argument, and so on.
52689 *
52690 * @static
52691 * @memberOf _
52692 * @since 3.0.0
52693 * @category Function
52694 * @param {Function} func The function to rearrange arguments for.
52695 * @param {...(number|number[])} indexes The arranged argument indexes.
52696 * @returns {Function} Returns the new function.
52697 * @example
52698 *
52699 * var rearged = _.rearg(function(a, b, c) {
52700 * return [a, b, c];
52701 * }, [2, 0, 1]);
52702 *
52703 * rearged('b', 'c', 'a')
52704 * // => ['a', 'b', 'c']
52705 */
52706 var rearg = flatRest(function(func, indexes) {
52707 return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes);
52708 });
52709
52710 /**
52711 * Creates a function that invokes `func` with the `this` binding of the
52712 * created function and arguments from `start` and beyond provided as
52713 * an array.
52714 *
52715 * **Note:** This method is based on the
52716 * [rest parameter](https://mdn.io/rest_parameters).
52717 *
52718 * @static
52719 * @memberOf _
52720 * @since 4.0.0
52721 * @category Function
52722 * @param {Function} func The function to apply a rest parameter to.
52723 * @param {number} [start=func.length-1] The start position of the rest parameter.
52724 * @returns {Function} Returns the new function.
52725 * @example
52726 *
52727 * var say = _.rest(function(what, names) {
52728 * return what + ' ' + _.initial(names).join(', ') +
52729 * (_.size(names) > 1 ? ', & ' : '') + _.last(names);
52730 * });
52731 *
52732 * say('hello', 'fred', 'barney', 'pebbles');
52733 * // => 'hello fred, barney, & pebbles'
52734 */
52735 function rest(func, start) {
52736 if (typeof func != 'function') {
52737 throw new TypeError(FUNC_ERROR_TEXT);
52738 }
52739 start = start === undefined ? start : toInteger(start);
52740 return baseRest(func, start);
52741 }
52742
52743 /**
52744 * Creates a function that invokes `func` with the `this` binding of the
52745 * create function and an array of arguments much like
52746 * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply).
52747 *
52748 * **Note:** This method is based on the
52749 * [spread operator](https://mdn.io/spread_operator).
52750 *
52751 * @static
52752 * @memberOf _
52753 * @since 3.2.0
52754 * @category Function
52755 * @param {Function} func The function to spread arguments over.
52756 * @param {number} [start=0] The start position of the spread.
52757 * @returns {Function} Returns the new function.
52758 * @example
52759 *
52760 * var say = _.spread(function(who, what) {
52761 * return who + ' says ' + what;
52762 * });
52763 *
52764 * say(['fred', 'hello']);
52765 * // => 'fred says hello'
52766 *
52767 * var numbers = Promise.all([
52768 * Promise.resolve(40),
52769 * Promise.resolve(36)
52770 * ]);
52771 *
52772 * numbers.then(_.spread(function(x, y) {
52773 * return x + y;
52774 * }));
52775 * // => a Promise of 76
52776 */
52777 function spread(func, start) {
52778 if (typeof func != 'function') {
52779 throw new TypeError(FUNC_ERROR_TEXT);
52780 }
52781 start = start == null ? 0 : nativeMax(toInteger(start), 0);
52782 return baseRest(function(args) {
52783 var array = args[start],
52784 otherArgs = castSlice(args, 0, start);
52785
52786 if (array) {
52787 arrayPush(otherArgs, array);
52788 }
52789 return apply(func, this, otherArgs);
52790 });
52791 }
52792
52793 /**
52794 * Creates a throttled function that only invokes `func` at most once per
52795 * every `wait` milliseconds. The throttled function comes with a `cancel`
52796 * method to cancel delayed `func` invocations and a `flush` method to
52797 * immediately invoke them. Provide `options` to indicate whether `func`
52798 * should be invoked on the leading and/or trailing edge of the `wait`
52799 * timeout. The `func` is invoked with the last arguments provided to the
52800 * throttled function. Subsequent calls to the throttled function return the
52801 * result of the last `func` invocation.
52802 *
52803 * **Note:** If `leading` and `trailing` options are `true`, `func` is
52804 * invoked on the trailing edge of the timeout only if the throttled function
52805 * is invoked more than once during the `wait` timeout.
52806 *
52807 * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred
52808 * until to the next tick, similar to `setTimeout` with a timeout of `0`.
52809 *
52810 * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/)
52811 * for details over the differences between `_.throttle` and `_.debounce`.
52812 *
52813 * @static
52814 * @memberOf _
52815 * @since 0.1.0
52816 * @category Function
52817 * @param {Function} func The function to throttle.
52818 * @param {number} [wait=0] The number of milliseconds to throttle invocations to.
52819 * @param {Object} [options={}] The options object.
52820 * @param {boolean} [options.leading=true]
52821 * Specify invoking on the leading edge of the timeout.
52822 * @param {boolean} [options.trailing=true]
52823 * Specify invoking on the trailing edge of the timeout.
52824 * @returns {Function} Returns the new throttled function.
52825 * @example
52826 *
52827 * // Avoid excessively updating the position while scrolling.
52828 * jQuery(window).on('scroll', _.throttle(updatePosition, 100));
52829 *
52830 * // Invoke `renewToken` when the click event is fired, but not more than once every 5 minutes.
52831 * var throttled = _.throttle(renewToken, 300000, { 'trailing': false });
52832 * jQuery(element).on('click', throttled);
52833 *
52834 * // Cancel the trailing throttled invocation.
52835 * jQuery(window).on('popstate', throttled.cancel);
52836 */
52837 function throttle(func, wait, options) {
52838 var leading = true,
52839 trailing = true;
52840
52841 if (typeof func != 'function') {
52842 throw new TypeError(FUNC_ERROR_TEXT);
52843 }
52844 if (isObject(options)) {
52845 leading = 'leading' in options ? !!options.leading : leading;
52846 trailing = 'trailing' in options ? !!options.trailing : trailing;
52847 }
52848 return debounce(func, wait, {
52849 'leading': leading,
52850 'maxWait': wait,
52851 'trailing': trailing
52852 });
52853 }
52854
52855 /**
52856 * Creates a function that accepts up to one argument, ignoring any
52857 * additional arguments.
52858 *
52859 * @static
52860 * @memberOf _
52861 * @since 4.0.0
52862 * @category Function
52863 * @param {Function} func The function to cap arguments for.
52864 * @returns {Function} Returns the new capped function.
52865 * @example
52866 *
52867 * _.map(['6', '8', '10'], _.unary(parseInt));
52868 * // => [6, 8, 10]
52869 */
52870 function unary(func) {
52871 return ary(func, 1);
52872 }
52873
52874 /**
52875 * Creates a function that provides `value` to `wrapper` as its first
52876 * argument. Any additional arguments provided to the function are appended
52877 * to those provided to the `wrapper`. The wrapper is invoked with the `this`
52878 * binding of the created function.
52879 *
52880 * @static
52881 * @memberOf _
52882 * @since 0.1.0
52883 * @category Function
52884 * @param {*} value The value to wrap.
52885 * @param {Function} [wrapper=identity] The wrapper function.
52886 * @returns {Function} Returns the new function.
52887 * @example
52888 *
52889 * var p = _.wrap(_.escape, function(func, text) {
52890 * return '<p>' + func(text) + '</p>';
52891 * });
52892 *
52893 * p('fred, barney, & pebbles');
52894 * // => '<p>fred, barney, &amp; pebbles</p>'
52895 */
52896 function wrap(value, wrapper) {
52897 return partial(castFunction(wrapper), value);
52898 }
52899
52900 /*------------------------------------------------------------------------*/
52901
52902 /**
52903 * Casts `value` as an array if it's not one.
52904 *
52905 * @static
52906 * @memberOf _
52907 * @since 4.4.0
52908 * @category Lang
52909 * @param {*} value The value to inspect.
52910 * @returns {Array} Returns the cast array.
52911 * @example
52912 *
52913 * _.castArray(1);
52914 * // => [1]
52915 *
52916 * _.castArray({ 'a': 1 });
52917 * // => [{ 'a': 1 }]
52918 *
52919 * _.castArray('abc');
52920 * // => ['abc']
52921 *
52922 * _.castArray(null);
52923 * // => [null]
52924 *
52925 * _.castArray(undefined);
52926 * // => [undefined]
52927 *
52928 * _.castArray();
52929 * // => []
52930 *
52931 * var array = [1, 2, 3];
52932 * console.log(_.castArray(array) === array);
52933 * // => true
52934 */
52935 function castArray() {
52936 if (!arguments.length) {
52937 return [];
52938 }
52939 var value = arguments[0];
52940 return isArray(value) ? value : [value];
52941 }
52942
52943 /**
52944 * Creates a shallow clone of `value`.
52945 *
52946 * **Note:** This method is loosely based on the
52947 * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm)
52948 * and supports cloning arrays, array buffers, booleans, date objects, maps,
52949 * numbers, `Object` objects, regexes, sets, strings, symbols, and typed
52950 * arrays. The own enumerable properties of `arguments` objects are cloned
52951 * as plain objects. An empty object is returned for uncloneable values such
52952 * as error objects, functions, DOM nodes, and WeakMaps.
52953 *
52954 * @static
52955 * @memberOf _
52956 * @since 0.1.0
52957 * @category Lang
52958 * @param {*} value The value to clone.
52959 * @returns {*} Returns the cloned value.
52960 * @see _.cloneDeep
52961 * @example
52962 *
52963 * var objects = [{ 'a': 1 }, { 'b': 2 }];
52964 *
52965 * var shallow = _.clone(objects);
52966 * console.log(shallow[0] === objects[0]);
52967 * // => true
52968 */
52969 function clone(value) {
52970 return baseClone(value, CLONE_SYMBOLS_FLAG);
52971 }
52972
52973 /**
52974 * This method is like `_.clone` except that it accepts `customizer` which
52975 * is invoked to produce the cloned value. If `customizer` returns `undefined`,
52976 * cloning is handled by the method instead. The `customizer` is invoked with
52977 * up to four arguments; (value [, index|key, object, stack]).
52978 *
52979 * @static
52980 * @memberOf _
52981 * @since 4.0.0
52982 * @category Lang
52983 * @param {*} value The value to clone.
52984 * @param {Function} [customizer] The function to customize cloning.
52985 * @returns {*} Returns the cloned value.
52986 * @see _.cloneDeepWith
52987 * @example
52988 *
52989 * function customizer(value) {
52990 * if (_.isElement(value)) {
52991 * return value.cloneNode(false);
52992 * }
52993 * }
52994 *
52995 * var el = _.cloneWith(document.body, customizer);
52996 *
52997 * console.log(el === document.body);
52998 * // => false
52999 * console.log(el.nodeName);
53000 * // => 'BODY'
53001 * console.log(el.childNodes.length);
53002 * // => 0
53003 */
53004 function cloneWith(value, customizer) {
53005 customizer = typeof customizer == 'function' ? customizer : undefined;
53006 return baseClone(value, CLONE_SYMBOLS_FLAG, customizer);
53007 }
53008
53009 /**
53010 * This method is like `_.clone` except that it recursively clones `value`.
53011 *
53012 * @static
53013 * @memberOf _
53014 * @since 1.0.0
53015 * @category Lang
53016 * @param {*} value The value to recursively clone.
53017 * @returns {*} Returns the deep cloned value.
53018 * @see _.clone
53019 * @example
53020 *
53021 * var objects = [{ 'a': 1 }, { 'b': 2 }];
53022 *
53023 * var deep = _.cloneDeep(objects);
53024 * console.log(deep[0] === objects[0]);
53025 * // => false
53026 */
53027 function cloneDeep(value) {
53028 return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG);
53029 }
53030
53031 /**
53032 * This method is like `_.cloneWith` except that it recursively clones `value`.
53033 *
53034 * @static
53035 * @memberOf _
53036 * @since 4.0.0
53037 * @category Lang
53038 * @param {*} value The value to recursively clone.
53039 * @param {Function} [customizer] The function to customize cloning.
53040 * @returns {*} Returns the deep cloned value.
53041 * @see _.cloneWith
53042 * @example
53043 *
53044 * function customizer(value) {
53045 * if (_.isElement(value)) {
53046 * return value.cloneNode(true);
53047 * }
53048 * }
53049 *
53050 * var el = _.cloneDeepWith(document.body, customizer);
53051 *
53052 * console.log(el === document.body);
53053 * // => false
53054 * console.log(el.nodeName);
53055 * // => 'BODY'
53056 * console.log(el.childNodes.length);
53057 * // => 20
53058 */
53059 function cloneDeepWith(value, customizer) {
53060 customizer = typeof customizer == 'function' ? customizer : undefined;
53061 return baseClone(value, CLONE_DEEP_FLAG | CLONE_SYMBOLS_FLAG, customizer);
53062 }
53063
53064 /**
53065 * Checks if `object` conforms to `source` by invoking the predicate
53066 * properties of `source` with the corresponding property values of `object`.
53067 *
53068 * **Note:** This method is equivalent to `_.conforms` when `source` is
53069 * partially applied.
53070 *
53071 * @static
53072 * @memberOf _
53073 * @since 4.14.0
53074 * @category Lang
53075 * @param {Object} object The object to inspect.
53076 * @param {Object} source The object of property predicates to conform to.
53077 * @returns {boolean} Returns `true` if `object` conforms, else `false`.
53078 * @example
53079 *
53080 * var object = { 'a': 1, 'b': 2 };
53081 *
53082 * _.conformsTo(object, { 'b': function(n) { return n > 1; } });
53083 * // => true
53084 *
53085 * _.conformsTo(object, { 'b': function(n) { return n > 2; } });
53086 * // => false
53087 */
53088 function conformsTo(object, source) {
53089 return source == null || baseConformsTo(object, source, keys(source));
53090 }
53091
53092 /**
53093 * Performs a
53094 * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero)
53095 * comparison between two values to determine if they are equivalent.
53096 *
53097 * @static
53098 * @memberOf _
53099 * @since 4.0.0
53100 * @category Lang
53101 * @param {*} value The value to compare.
53102 * @param {*} other The other value to compare.
53103 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
53104 * @example
53105 *
53106 * var object = { 'a': 1 };
53107 * var other = { 'a': 1 };
53108 *
53109 * _.eq(object, object);
53110 * // => true
53111 *
53112 * _.eq(object, other);
53113 * // => false
53114 *
53115 * _.eq('a', 'a');
53116 * // => true
53117 *
53118 * _.eq('a', Object('a'));
53119 * // => false
53120 *
53121 * _.eq(NaN, NaN);
53122 * // => true
53123 */
53124 function eq(value, other) {
53125 return value === other || (value !== value && other !== other);
53126 }
53127
53128 /**
53129 * Checks if `value` is greater than `other`.
53130 *
53131 * @static
53132 * @memberOf _
53133 * @since 3.9.0
53134 * @category Lang
53135 * @param {*} value The value to compare.
53136 * @param {*} other The other value to compare.
53137 * @returns {boolean} Returns `true` if `value` is greater than `other`,
53138 * else `false`.
53139 * @see _.lt
53140 * @example
53141 *
53142 * _.gt(3, 1);
53143 * // => true
53144 *
53145 * _.gt(3, 3);
53146 * // => false
53147 *
53148 * _.gt(1, 3);
53149 * // => false
53150 */
53151 var gt = createRelationalOperation(baseGt);
53152
53153 /**
53154 * Checks if `value` is greater than or equal to `other`.
53155 *
53156 * @static
53157 * @memberOf _
53158 * @since 3.9.0
53159 * @category Lang
53160 * @param {*} value The value to compare.
53161 * @param {*} other The other value to compare.
53162 * @returns {boolean} Returns `true` if `value` is greater than or equal to
53163 * `other`, else `false`.
53164 * @see _.lte
53165 * @example
53166 *
53167 * _.gte(3, 1);
53168 * // => true
53169 *
53170 * _.gte(3, 3);
53171 * // => true
53172 *
53173 * _.gte(1, 3);
53174 * // => false
53175 */
53176 var gte = createRelationalOperation(function(value, other) {
53177 return value >= other;
53178 });
53179
53180 /**
53181 * Checks if `value` is likely an `arguments` object.
53182 *
53183 * @static
53184 * @memberOf _
53185 * @since 0.1.0
53186 * @category Lang
53187 * @param {*} value The value to check.
53188 * @returns {boolean} Returns `true` if `value` is an `arguments` object,
53189 * else `false`.
53190 * @example
53191 *
53192 * _.isArguments(function() { return arguments; }());
53193 * // => true
53194 *
53195 * _.isArguments([1, 2, 3]);
53196 * // => false
53197 */
53198 var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) {
53199 return isObjectLike(value) && hasOwnProperty.call(value, 'callee') &&
53200 !propertyIsEnumerable.call(value, 'callee');
53201 };
53202
53203 /**
53204 * Checks if `value` is classified as an `Array` object.
53205 *
53206 * @static
53207 * @memberOf _
53208 * @since 0.1.0
53209 * @category Lang
53210 * @param {*} value The value to check.
53211 * @returns {boolean} Returns `true` if `value` is an array, else `false`.
53212 * @example
53213 *
53214 * _.isArray([1, 2, 3]);
53215 * // => true
53216 *
53217 * _.isArray(document.body.children);
53218 * // => false
53219 *
53220 * _.isArray('abc');
53221 * // => false
53222 *
53223 * _.isArray(_.noop);
53224 * // => false
53225 */
53226 var isArray = Array.isArray;
53227
53228 /**
53229 * Checks if `value` is classified as an `ArrayBuffer` object.
53230 *
53231 * @static
53232 * @memberOf _
53233 * @since 4.3.0
53234 * @category Lang
53235 * @param {*} value The value to check.
53236 * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`.
53237 * @example
53238 *
53239 * _.isArrayBuffer(new ArrayBuffer(2));
53240 * // => true
53241 *
53242 * _.isArrayBuffer(new Array(2));
53243 * // => false
53244 */
53245 var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer;
53246
53247 /**
53248 * Checks if `value` is array-like. A value is considered array-like if it's
53249 * not a function and has a `value.length` that's an integer greater than or
53250 * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`.
53251 *
53252 * @static
53253 * @memberOf _
53254 * @since 4.0.0
53255 * @category Lang
53256 * @param {*} value The value to check.
53257 * @returns {boolean} Returns `true` if `value` is array-like, else `false`.
53258 * @example
53259 *
53260 * _.isArrayLike([1, 2, 3]);
53261 * // => true
53262 *
53263 * _.isArrayLike(document.body.children);
53264 * // => true
53265 *
53266 * _.isArrayLike('abc');
53267 * // => true
53268 *
53269 * _.isArrayLike(_.noop);
53270 * // => false
53271 */
53272 function isArrayLike(value) {
53273 return value != null && isLength(value.length) && !isFunction(value);
53274 }
53275
53276 /**
53277 * This method is like `_.isArrayLike` except that it also checks if `value`
53278 * is an object.
53279 *
53280 * @static
53281 * @memberOf _
53282 * @since 4.0.0
53283 * @category Lang
53284 * @param {*} value The value to check.
53285 * @returns {boolean} Returns `true` if `value` is an array-like object,
53286 * else `false`.
53287 * @example
53288 *
53289 * _.isArrayLikeObject([1, 2, 3]);
53290 * // => true
53291 *
53292 * _.isArrayLikeObject(document.body.children);
53293 * // => true
53294 *
53295 * _.isArrayLikeObject('abc');
53296 * // => false
53297 *
53298 * _.isArrayLikeObject(_.noop);
53299 * // => false
53300 */
53301 function isArrayLikeObject(value) {
53302 return isObjectLike(value) && isArrayLike(value);
53303 }
53304
53305 /**
53306 * Checks if `value` is classified as a boolean primitive or object.
53307 *
53308 * @static
53309 * @memberOf _
53310 * @since 0.1.0
53311 * @category Lang
53312 * @param {*} value The value to check.
53313 * @returns {boolean} Returns `true` if `value` is a boolean, else `false`.
53314 * @example
53315 *
53316 * _.isBoolean(false);
53317 * // => true
53318 *
53319 * _.isBoolean(null);
53320 * // => false
53321 */
53322 function isBoolean(value) {
53323 return value === true || value === false ||
53324 (isObjectLike(value) && baseGetTag(value) == boolTag);
53325 }
53326
53327 /**
53328 * Checks if `value` is a buffer.
53329 *
53330 * @static
53331 * @memberOf _
53332 * @since 4.3.0
53333 * @category Lang
53334 * @param {*} value The value to check.
53335 * @returns {boolean} Returns `true` if `value` is a buffer, else `false`.
53336 * @example
53337 *
53338 * _.isBuffer(new Buffer(2));
53339 * // => true
53340 *
53341 * _.isBuffer(new Uint8Array(2));
53342 * // => false
53343 */
53344 var isBuffer = nativeIsBuffer || stubFalse;
53345
53346 /**
53347 * Checks if `value` is classified as a `Date` object.
53348 *
53349 * @static
53350 * @memberOf _
53351 * @since 0.1.0
53352 * @category Lang
53353 * @param {*} value The value to check.
53354 * @returns {boolean} Returns `true` if `value` is a date object, else `false`.
53355 * @example
53356 *
53357 * _.isDate(new Date);
53358 * // => true
53359 *
53360 * _.isDate('Mon April 23 2012');
53361 * // => false
53362 */
53363 var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate;
53364
53365 /**
53366 * Checks if `value` is likely a DOM element.
53367 *
53368 * @static
53369 * @memberOf _
53370 * @since 0.1.0
53371 * @category Lang
53372 * @param {*} value The value to check.
53373 * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`.
53374 * @example
53375 *
53376 * _.isElement(document.body);
53377 * // => true
53378 *
53379 * _.isElement('<body>');
53380 * // => false
53381 */
53382 function isElement(value) {
53383 return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value);
53384 }
53385
53386 /**
53387 * Checks if `value` is an empty object, collection, map, or set.
53388 *
53389 * Objects are considered empty if they have no own enumerable string keyed
53390 * properties.
53391 *
53392 * Array-like values such as `arguments` objects, arrays, buffers, strings, or
53393 * jQuery-like collections are considered empty if they have a `length` of `0`.
53394 * Similarly, maps and sets are considered empty if they have a `size` of `0`.
53395 *
53396 * @static
53397 * @memberOf _
53398 * @since 0.1.0
53399 * @category Lang
53400 * @param {*} value The value to check.
53401 * @returns {boolean} Returns `true` if `value` is empty, else `false`.
53402 * @example
53403 *
53404 * _.isEmpty(null);
53405 * // => true
53406 *
53407 * _.isEmpty(true);
53408 * // => true
53409 *
53410 * _.isEmpty(1);
53411 * // => true
53412 *
53413 * _.isEmpty([1, 2, 3]);
53414 * // => false
53415 *
53416 * _.isEmpty({ 'a': 1 });
53417 * // => false
53418 */
53419 function isEmpty(value) {
53420 if (value == null) {
53421 return true;
53422 }
53423 if (isArrayLike(value) &&
53424 (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' ||
53425 isBuffer(value) || isTypedArray(value) || isArguments(value))) {
53426 return !value.length;
53427 }
53428 var tag = getTag(value);
53429 if (tag == mapTag || tag == setTag) {
53430 return !value.size;
53431 }
53432 if (isPrototype(value)) {
53433 return !baseKeys(value).length;
53434 }
53435 for (var key in value) {
53436 if (hasOwnProperty.call(value, key)) {
53437 return false;
53438 }
53439 }
53440 return true;
53441 }
53442
53443 /**
53444 * Performs a deep comparison between two values to determine if they are
53445 * equivalent.
53446 *
53447 * **Note:** This method supports comparing arrays, array buffers, booleans,
53448 * date objects, error objects, maps, numbers, `Object` objects, regexes,
53449 * sets, strings, symbols, and typed arrays. `Object` objects are compared
53450 * by their own, not inherited, enumerable properties. Functions and DOM
53451 * nodes are compared by strict equality, i.e. `===`.
53452 *
53453 * @static
53454 * @memberOf _
53455 * @since 0.1.0
53456 * @category Lang
53457 * @param {*} value The value to compare.
53458 * @param {*} other The other value to compare.
53459 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
53460 * @example
53461 *
53462 * var object = { 'a': 1 };
53463 * var other = { 'a': 1 };
53464 *
53465 * _.isEqual(object, other);
53466 * // => true
53467 *
53468 * object === other;
53469 * // => false
53470 */
53471 function isEqual(value, other) {
53472 return baseIsEqual(value, other);
53473 }
53474
53475 /**
53476 * This method is like `_.isEqual` except that it accepts `customizer` which
53477 * is invoked to compare values. If `customizer` returns `undefined`, comparisons
53478 * are handled by the method instead. The `customizer` is invoked with up to
53479 * six arguments: (objValue, othValue [, index|key, object, other, stack]).
53480 *
53481 * @static
53482 * @memberOf _
53483 * @since 4.0.0
53484 * @category Lang
53485 * @param {*} value The value to compare.
53486 * @param {*} other The other value to compare.
53487 * @param {Function} [customizer] The function to customize comparisons.
53488 * @returns {boolean} Returns `true` if the values are equivalent, else `false`.
53489 * @example
53490 *
53491 * function isGreeting(value) {
53492 * return /^h(?:i|ello)$/.test(value);
53493 * }
53494 *
53495 * function customizer(objValue, othValue) {
53496 * if (isGreeting(objValue) && isGreeting(othValue)) {
53497 * return true;
53498 * }
53499 * }
53500 *
53501 * var array = ['hello', 'goodbye'];
53502 * var other = ['hi', 'goodbye'];
53503 *
53504 * _.isEqualWith(array, other, customizer);
53505 * // => true
53506 */
53507 function isEqualWith(value, other, customizer) {
53508 customizer = typeof customizer == 'function' ? customizer : undefined;
53509 var result = customizer ? customizer(value, other) : undefined;
53510 return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result;
53511 }
53512
53513 /**
53514 * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`,
53515 * `SyntaxError`, `TypeError`, or `URIError` object.
53516 *
53517 * @static
53518 * @memberOf _
53519 * @since 3.0.0
53520 * @category Lang
53521 * @param {*} value The value to check.
53522 * @returns {boolean} Returns `true` if `value` is an error object, else `false`.
53523 * @example
53524 *
53525 * _.isError(new Error);
53526 * // => true
53527 *
53528 * _.isError(Error);
53529 * // => false
53530 */
53531 function isError(value) {
53532 if (!isObjectLike(value)) {
53533 return false;
53534 }
53535 var tag = baseGetTag(value);
53536 return tag == errorTag || tag == domExcTag ||
53537 (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value));
53538 }
53539
53540 /**
53541 * Checks if `value` is a finite primitive number.
53542 *
53543 * **Note:** This method is based on
53544 * [`Number.isFinite`](https://mdn.io/Number/isFinite).
53545 *
53546 * @static
53547 * @memberOf _
53548 * @since 0.1.0
53549 * @category Lang
53550 * @param {*} value The value to check.
53551 * @returns {boolean} Returns `true` if `value` is a finite number, else `false`.
53552 * @example
53553 *
53554 * _.isFinite(3);
53555 * // => true
53556 *
53557 * _.isFinite(Number.MIN_VALUE);
53558 * // => true
53559 *
53560 * _.isFinite(Infinity);
53561 * // => false
53562 *
53563 * _.isFinite('3');
53564 * // => false
53565 */
53566 function isFinite(value) {
53567 return typeof value == 'number' && nativeIsFinite(value);
53568 }
53569
53570 /**
53571 * Checks if `value` is classified as a `Function` object.
53572 *
53573 * @static
53574 * @memberOf _
53575 * @since 0.1.0
53576 * @category Lang
53577 * @param {*} value The value to check.
53578 * @returns {boolean} Returns `true` if `value` is a function, else `false`.
53579 * @example
53580 *
53581 * _.isFunction(_);
53582 * // => true
53583 *
53584 * _.isFunction(/abc/);
53585 * // => false
53586 */
53587 function isFunction(value) {
53588 if (!isObject(value)) {
53589 return false;
53590 }
53591 // The use of `Object#toString` avoids issues with the `typeof` operator
53592 // in Safari 9 which returns 'object' for typed arrays and other constructors.
53593 var tag = baseGetTag(value);
53594 return tag == funcTag || tag == genTag || tag == asyncTag || tag == proxyTag;
53595 }
53596
53597 /**
53598 * Checks if `value` is an integer.
53599 *
53600 * **Note:** This method is based on
53601 * [`Number.isInteger`](https://mdn.io/Number/isInteger).
53602 *
53603 * @static
53604 * @memberOf _
53605 * @since 4.0.0
53606 * @category Lang
53607 * @param {*} value The value to check.
53608 * @returns {boolean} Returns `true` if `value` is an integer, else `false`.
53609 * @example
53610 *
53611 * _.isInteger(3);
53612 * // => true
53613 *
53614 * _.isInteger(Number.MIN_VALUE);
53615 * // => false
53616 *
53617 * _.isInteger(Infinity);
53618 * // => false
53619 *
53620 * _.isInteger('3');
53621 * // => false
53622 */
53623 function isInteger(value) {
53624 return typeof value == 'number' && value == toInteger(value);
53625 }
53626
53627 /**
53628 * Checks if `value` is a valid array-like length.
53629 *
53630 * **Note:** This method is loosely based on
53631 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
53632 *
53633 * @static
53634 * @memberOf _
53635 * @since 4.0.0
53636 * @category Lang
53637 * @param {*} value The value to check.
53638 * @returns {boolean} Returns `true` if `value` is a valid length, else `false`.
53639 * @example
53640 *
53641 * _.isLength(3);
53642 * // => true
53643 *
53644 * _.isLength(Number.MIN_VALUE);
53645 * // => false
53646 *
53647 * _.isLength(Infinity);
53648 * // => false
53649 *
53650 * _.isLength('3');
53651 * // => false
53652 */
53653 function isLength(value) {
53654 return typeof value == 'number' &&
53655 value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER;
53656 }
53657
53658 /**
53659 * Checks if `value` is the
53660 * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types)
53661 * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`)
53662 *
53663 * @static
53664 * @memberOf _
53665 * @since 0.1.0
53666 * @category Lang
53667 * @param {*} value The value to check.
53668 * @returns {boolean} Returns `true` if `value` is an object, else `false`.
53669 * @example
53670 *
53671 * _.isObject({});
53672 * // => true
53673 *
53674 * _.isObject([1, 2, 3]);
53675 * // => true
53676 *
53677 * _.isObject(_.noop);
53678 * // => true
53679 *
53680 * _.isObject(null);
53681 * // => false
53682 */
53683 function isObject(value) {
53684 var type = typeof value;
53685 return value != null && (type == 'object' || type == 'function');
53686 }
53687
53688 /**
53689 * Checks if `value` is object-like. A value is object-like if it's not `null`
53690 * and has a `typeof` result of "object".
53691 *
53692 * @static
53693 * @memberOf _
53694 * @since 4.0.0
53695 * @category Lang
53696 * @param {*} value The value to check.
53697 * @returns {boolean} Returns `true` if `value` is object-like, else `false`.
53698 * @example
53699 *
53700 * _.isObjectLike({});
53701 * // => true
53702 *
53703 * _.isObjectLike([1, 2, 3]);
53704 * // => true
53705 *
53706 * _.isObjectLike(_.noop);
53707 * // => false
53708 *
53709 * _.isObjectLike(null);
53710 * // => false
53711 */
53712 function isObjectLike(value) {
53713 return value != null && typeof value == 'object';
53714 }
53715
53716 /**
53717 * Checks if `value` is classified as a `Map` object.
53718 *
53719 * @static
53720 * @memberOf _
53721 * @since 4.3.0
53722 * @category Lang
53723 * @param {*} value The value to check.
53724 * @returns {boolean} Returns `true` if `value` is a map, else `false`.
53725 * @example
53726 *
53727 * _.isMap(new Map);
53728 * // => true
53729 *
53730 * _.isMap(new WeakMap);
53731 * // => false
53732 */
53733 var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap;
53734
53735 /**
53736 * Performs a partial deep comparison between `object` and `source` to
53737 * determine if `object` contains equivalent property values.
53738 *
53739 * **Note:** This method is equivalent to `_.matches` when `source` is
53740 * partially applied.
53741 *
53742 * Partial comparisons will match empty array and empty object `source`
53743 * values against any array or object value, respectively. See `_.isEqual`
53744 * for a list of supported value comparisons.
53745 *
53746 * @static
53747 * @memberOf _
53748 * @since 3.0.0
53749 * @category Lang
53750 * @param {Object} object The object to inspect.
53751 * @param {Object} source The object of property values to match.
53752 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
53753 * @example
53754 *
53755 * var object = { 'a': 1, 'b': 2 };
53756 *
53757 * _.isMatch(object, { 'b': 2 });
53758 * // => true
53759 *
53760 * _.isMatch(object, { 'b': 1 });
53761 * // => false
53762 */
53763 function isMatch(object, source) {
53764 return object === source || baseIsMatch(object, source, getMatchData(source));
53765 }
53766
53767 /**
53768 * This method is like `_.isMatch` except that it accepts `customizer` which
53769 * is invoked to compare values. If `customizer` returns `undefined`, comparisons
53770 * are handled by the method instead. The `customizer` is invoked with five
53771 * arguments: (objValue, srcValue, index|key, object, source).
53772 *
53773 * @static
53774 * @memberOf _
53775 * @since 4.0.0
53776 * @category Lang
53777 * @param {Object} object The object to inspect.
53778 * @param {Object} source The object of property values to match.
53779 * @param {Function} [customizer] The function to customize comparisons.
53780 * @returns {boolean} Returns `true` if `object` is a match, else `false`.
53781 * @example
53782 *
53783 * function isGreeting(value) {
53784 * return /^h(?:i|ello)$/.test(value);
53785 * }
53786 *
53787 * function customizer(objValue, srcValue) {
53788 * if (isGreeting(objValue) && isGreeting(srcValue)) {
53789 * return true;
53790 * }
53791 * }
53792 *
53793 * var object = { 'greeting': 'hello' };
53794 * var source = { 'greeting': 'hi' };
53795 *
53796 * _.isMatchWith(object, source, customizer);
53797 * // => true
53798 */
53799 function isMatchWith(object, source, customizer) {
53800 customizer = typeof customizer == 'function' ? customizer : undefined;
53801 return baseIsMatch(object, source, getMatchData(source), customizer);
53802 }
53803
53804 /**
53805 * Checks if `value` is `NaN`.
53806 *
53807 * **Note:** This method is based on
53808 * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as
53809 * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for
53810 * `undefined` and other non-number values.
53811 *
53812 * @static
53813 * @memberOf _
53814 * @since 0.1.0
53815 * @category Lang
53816 * @param {*} value The value to check.
53817 * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`.
53818 * @example
53819 *
53820 * _.isNaN(NaN);
53821 * // => true
53822 *
53823 * _.isNaN(new Number(NaN));
53824 * // => true
53825 *
53826 * isNaN(undefined);
53827 * // => true
53828 *
53829 * _.isNaN(undefined);
53830 * // => false
53831 */
53832 function isNaN(value) {
53833 // An `NaN` primitive is the only value that is not equal to itself.
53834 // Perform the `toStringTag` check first to avoid errors with some
53835 // ActiveX objects in IE.
53836 return isNumber(value) && value != +value;
53837 }
53838
53839 /**
53840 * Checks if `value` is a pristine native function.
53841 *
53842 * **Note:** This method can't reliably detect native functions in the presence
53843 * of the core-js package because core-js circumvents this kind of detection.
53844 * Despite multiple requests, the core-js maintainer has made it clear: any
53845 * attempt to fix the detection will be obstructed. As a result, we're left
53846 * with little choice but to throw an error. Unfortunately, this also affects
53847 * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill),
53848 * which rely on core-js.
53849 *
53850 * @static
53851 * @memberOf _
53852 * @since 3.0.0
53853 * @category Lang
53854 * @param {*} value The value to check.
53855 * @returns {boolean} Returns `true` if `value` is a native function,
53856 * else `false`.
53857 * @example
53858 *
53859 * _.isNative(Array.prototype.push);
53860 * // => true
53861 *
53862 * _.isNative(_);
53863 * // => false
53864 */
53865 function isNative(value) {
53866 if (isMaskable(value)) {
53867 throw new Error(CORE_ERROR_TEXT);
53868 }
53869 return baseIsNative(value);
53870 }
53871
53872 /**
53873 * Checks if `value` is `null`.
53874 *
53875 * @static
53876 * @memberOf _
53877 * @since 0.1.0
53878 * @category Lang
53879 * @param {*} value The value to check.
53880 * @returns {boolean} Returns `true` if `value` is `null`, else `false`.
53881 * @example
53882 *
53883 * _.isNull(null);
53884 * // => true
53885 *
53886 * _.isNull(void 0);
53887 * // => false
53888 */
53889 function isNull(value) {
53890 return value === null;
53891 }
53892
53893 /**
53894 * Checks if `value` is `null` or `undefined`.
53895 *
53896 * @static
53897 * @memberOf _
53898 * @since 4.0.0
53899 * @category Lang
53900 * @param {*} value The value to check.
53901 * @returns {boolean} Returns `true` if `value` is nullish, else `false`.
53902 * @example
53903 *
53904 * _.isNil(null);
53905 * // => true
53906 *
53907 * _.isNil(void 0);
53908 * // => true
53909 *
53910 * _.isNil(NaN);
53911 * // => false
53912 */
53913 function isNil(value) {
53914 return value == null;
53915 }
53916
53917 /**
53918 * Checks if `value` is classified as a `Number` primitive or object.
53919 *
53920 * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are
53921 * classified as numbers, use the `_.isFinite` method.
53922 *
53923 * @static
53924 * @memberOf _
53925 * @since 0.1.0
53926 * @category Lang
53927 * @param {*} value The value to check.
53928 * @returns {boolean} Returns `true` if `value` is a number, else `false`.
53929 * @example
53930 *
53931 * _.isNumber(3);
53932 * // => true
53933 *
53934 * _.isNumber(Number.MIN_VALUE);
53935 * // => true
53936 *
53937 * _.isNumber(Infinity);
53938 * // => true
53939 *
53940 * _.isNumber('3');
53941 * // => false
53942 */
53943 function isNumber(value) {
53944 return typeof value == 'number' ||
53945 (isObjectLike(value) && baseGetTag(value) == numberTag);
53946 }
53947
53948 /**
53949 * Checks if `value` is a plain object, that is, an object created by the
53950 * `Object` constructor or one with a `[[Prototype]]` of `null`.
53951 *
53952 * @static
53953 * @memberOf _
53954 * @since 0.8.0
53955 * @category Lang
53956 * @param {*} value The value to check.
53957 * @returns {boolean} Returns `true` if `value` is a plain object, else `false`.
53958 * @example
53959 *
53960 * function Foo() {
53961 * this.a = 1;
53962 * }
53963 *
53964 * _.isPlainObject(new Foo);
53965 * // => false
53966 *
53967 * _.isPlainObject([1, 2, 3]);
53968 * // => false
53969 *
53970 * _.isPlainObject({ 'x': 0, 'y': 0 });
53971 * // => true
53972 *
53973 * _.isPlainObject(Object.create(null));
53974 * // => true
53975 */
53976 function isPlainObject(value) {
53977 if (!isObjectLike(value) || baseGetTag(value) != objectTag) {
53978 return false;
53979 }
53980 var proto = getPrototype(value);
53981 if (proto === null) {
53982 return true;
53983 }
53984 var Ctor = hasOwnProperty.call(proto, 'constructor') && proto.constructor;
53985 return typeof Ctor == 'function' && Ctor instanceof Ctor &&
53986 funcToString.call(Ctor) == objectCtorString;
53987 }
53988
53989 /**
53990 * Checks if `value` is classified as a `RegExp` object.
53991 *
53992 * @static
53993 * @memberOf _
53994 * @since 0.1.0
53995 * @category Lang
53996 * @param {*} value The value to check.
53997 * @returns {boolean} Returns `true` if `value` is a regexp, else `false`.
53998 * @example
53999 *
54000 * _.isRegExp(/abc/);
54001 * // => true
54002 *
54003 * _.isRegExp('/abc/');
54004 * // => false
54005 */
54006 var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp;
54007
54008 /**
54009 * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754
54010 * double precision number which isn't the result of a rounded unsafe integer.
54011 *
54012 * **Note:** This method is based on
54013 * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger).
54014 *
54015 * @static
54016 * @memberOf _
54017 * @since 4.0.0
54018 * @category Lang
54019 * @param {*} value The value to check.
54020 * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`.
54021 * @example
54022 *
54023 * _.isSafeInteger(3);
54024 * // => true
54025 *
54026 * _.isSafeInteger(Number.MIN_VALUE);
54027 * // => false
54028 *
54029 * _.isSafeInteger(Infinity);
54030 * // => false
54031 *
54032 * _.isSafeInteger('3');
54033 * // => false
54034 */
54035 function isSafeInteger(value) {
54036 return isInteger(value) && value >= -MAX_SAFE_INTEGER && value <= MAX_SAFE_INTEGER;
54037 }
54038
54039 /**
54040 * Checks if `value` is classified as a `Set` object.
54041 *
54042 * @static
54043 * @memberOf _
54044 * @since 4.3.0
54045 * @category Lang
54046 * @param {*} value The value to check.
54047 * @returns {boolean} Returns `true` if `value` is a set, else `false`.
54048 * @example
54049 *
54050 * _.isSet(new Set);
54051 * // => true
54052 *
54053 * _.isSet(new WeakSet);
54054 * // => false
54055 */
54056 var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet;
54057
54058 /**
54059 * Checks if `value` is classified as a `String` primitive or object.
54060 *
54061 * @static
54062 * @since 0.1.0
54063 * @memberOf _
54064 * @category Lang
54065 * @param {*} value The value to check.
54066 * @returns {boolean} Returns `true` if `value` is a string, else `false`.
54067 * @example
54068 *
54069 * _.isString('abc');
54070 * // => true
54071 *
54072 * _.isString(1);
54073 * // => false
54074 */
54075 function isString(value) {
54076 return typeof value == 'string' ||
54077 (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag);
54078 }
54079
54080 /**
54081 * Checks if `value` is classified as a `Symbol` primitive or object.
54082 *
54083 * @static
54084 * @memberOf _
54085 * @since 4.0.0
54086 * @category Lang
54087 * @param {*} value The value to check.
54088 * @returns {boolean} Returns `true` if `value` is a symbol, else `false`.
54089 * @example
54090 *
54091 * _.isSymbol(Symbol.iterator);
54092 * // => true
54093 *
54094 * _.isSymbol('abc');
54095 * // => false
54096 */
54097 function isSymbol(value) {
54098 return typeof value == 'symbol' ||
54099 (isObjectLike(value) && baseGetTag(value) == symbolTag);
54100 }
54101
54102 /**
54103 * Checks if `value` is classified as a typed array.
54104 *
54105 * @static
54106 * @memberOf _
54107 * @since 3.0.0
54108 * @category Lang
54109 * @param {*} value The value to check.
54110 * @returns {boolean} Returns `true` if `value` is a typed array, else `false`.
54111 * @example
54112 *
54113 * _.isTypedArray(new Uint8Array);
54114 * // => true
54115 *
54116 * _.isTypedArray([]);
54117 * // => false
54118 */
54119 var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray;
54120
54121 /**
54122 * Checks if `value` is `undefined`.
54123 *
54124 * @static
54125 * @since 0.1.0
54126 * @memberOf _
54127 * @category Lang
54128 * @param {*} value The value to check.
54129 * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`.
54130 * @example
54131 *
54132 * _.isUndefined(void 0);
54133 * // => true
54134 *
54135 * _.isUndefined(null);
54136 * // => false
54137 */
54138 function isUndefined(value) {
54139 return value === undefined;
54140 }
54141
54142 /**
54143 * Checks if `value` is classified as a `WeakMap` object.
54144 *
54145 * @static
54146 * @memberOf _
54147 * @since 4.3.0
54148 * @category Lang
54149 * @param {*} value The value to check.
54150 * @returns {boolean} Returns `true` if `value` is a weak map, else `false`.
54151 * @example
54152 *
54153 * _.isWeakMap(new WeakMap);
54154 * // => true
54155 *
54156 * _.isWeakMap(new Map);
54157 * // => false
54158 */
54159 function isWeakMap(value) {
54160 return isObjectLike(value) && getTag(value) == weakMapTag;
54161 }
54162
54163 /**
54164 * Checks if `value` is classified as a `WeakSet` object.
54165 *
54166 * @static
54167 * @memberOf _
54168 * @since 4.3.0
54169 * @category Lang
54170 * @param {*} value The value to check.
54171 * @returns {boolean} Returns `true` if `value` is a weak set, else `false`.
54172 * @example
54173 *
54174 * _.isWeakSet(new WeakSet);
54175 * // => true
54176 *
54177 * _.isWeakSet(new Set);
54178 * // => false
54179 */
54180 function isWeakSet(value) {
54181 return isObjectLike(value) && baseGetTag(value) == weakSetTag;
54182 }
54183
54184 /**
54185 * Checks if `value` is less than `other`.
54186 *
54187 * @static
54188 * @memberOf _
54189 * @since 3.9.0
54190 * @category Lang
54191 * @param {*} value The value to compare.
54192 * @param {*} other The other value to compare.
54193 * @returns {boolean} Returns `true` if `value` is less than `other`,
54194 * else `false`.
54195 * @see _.gt
54196 * @example
54197 *
54198 * _.lt(1, 3);
54199 * // => true
54200 *
54201 * _.lt(3, 3);
54202 * // => false
54203 *
54204 * _.lt(3, 1);
54205 * // => false
54206 */
54207 var lt = createRelationalOperation(baseLt);
54208
54209 /**
54210 * Checks if `value` is less than or equal to `other`.
54211 *
54212 * @static
54213 * @memberOf _
54214 * @since 3.9.0
54215 * @category Lang
54216 * @param {*} value The value to compare.
54217 * @param {*} other The other value to compare.
54218 * @returns {boolean} Returns `true` if `value` is less than or equal to
54219 * `other`, else `false`.
54220 * @see _.gte
54221 * @example
54222 *
54223 * _.lte(1, 3);
54224 * // => true
54225 *
54226 * _.lte(3, 3);
54227 * // => true
54228 *
54229 * _.lte(3, 1);
54230 * // => false
54231 */
54232 var lte = createRelationalOperation(function(value, other) {
54233 return value <= other;
54234 });
54235
54236 /**
54237 * Converts `value` to an array.
54238 *
54239 * @static
54240 * @since 0.1.0
54241 * @memberOf _
54242 * @category Lang
54243 * @param {*} value The value to convert.
54244 * @returns {Array} Returns the converted array.
54245 * @example
54246 *
54247 * _.toArray({ 'a': 1, 'b': 2 });
54248 * // => [1, 2]
54249 *
54250 * _.toArray('abc');
54251 * // => ['a', 'b', 'c']
54252 *
54253 * _.toArray(1);
54254 * // => []
54255 *
54256 * _.toArray(null);
54257 * // => []
54258 */
54259 function toArray(value) {
54260 if (!value) {
54261 return [];
54262 }
54263 if (isArrayLike(value)) {
54264 return isString(value) ? stringToArray(value) : copyArray(value);
54265 }
54266 if (symIterator && value[symIterator]) {
54267 return iteratorToArray(value[symIterator]());
54268 }
54269 var tag = getTag(value),
54270 func = tag == mapTag ? mapToArray : (tag == setTag ? setToArray : values);
54271
54272 return func(value);
54273 }
54274
54275 /**
54276 * Converts `value` to a finite number.
54277 *
54278 * @static
54279 * @memberOf _
54280 * @since 4.12.0
54281 * @category Lang
54282 * @param {*} value The value to convert.
54283 * @returns {number} Returns the converted number.
54284 * @example
54285 *
54286 * _.toFinite(3.2);
54287 * // => 3.2
54288 *
54289 * _.toFinite(Number.MIN_VALUE);
54290 * // => 5e-324
54291 *
54292 * _.toFinite(Infinity);
54293 * // => 1.7976931348623157e+308
54294 *
54295 * _.toFinite('3.2');
54296 * // => 3.2
54297 */
54298 function toFinite(value) {
54299 if (!value) {
54300 return value === 0 ? value : 0;
54301 }
54302 value = toNumber(value);
54303 if (value === INFINITY || value === -INFINITY) {
54304 var sign = (value < 0 ? -1 : 1);
54305 return sign * MAX_INTEGER;
54306 }
54307 return value === value ? value : 0;
54308 }
54309
54310 /**
54311 * Converts `value` to an integer.
54312 *
54313 * **Note:** This method is loosely based on
54314 * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger).
54315 *
54316 * @static
54317 * @memberOf _
54318 * @since 4.0.0
54319 * @category Lang
54320 * @param {*} value The value to convert.
54321 * @returns {number} Returns the converted integer.
54322 * @example
54323 *
54324 * _.toInteger(3.2);
54325 * // => 3
54326 *
54327 * _.toInteger(Number.MIN_VALUE);
54328 * // => 0
54329 *
54330 * _.toInteger(Infinity);
54331 * // => 1.7976931348623157e+308
54332 *
54333 * _.toInteger('3.2');
54334 * // => 3
54335 */
54336 function toInteger(value) {
54337 var result = toFinite(value),
54338 remainder = result % 1;
54339
54340 return result === result ? (remainder ? result - remainder : result) : 0;
54341 }
54342
54343 /**
54344 * Converts `value` to an integer suitable for use as the length of an
54345 * array-like object.
54346 *
54347 * **Note:** This method is based on
54348 * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength).
54349 *
54350 * @static
54351 * @memberOf _
54352 * @since 4.0.0
54353 * @category Lang
54354 * @param {*} value The value to convert.
54355 * @returns {number} Returns the converted integer.
54356 * @example
54357 *
54358 * _.toLength(3.2);
54359 * // => 3
54360 *
54361 * _.toLength(Number.MIN_VALUE);
54362 * // => 0
54363 *
54364 * _.toLength(Infinity);
54365 * // => 4294967295
54366 *
54367 * _.toLength('3.2');
54368 * // => 3
54369 */
54370 function toLength(value) {
54371 return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH) : 0;
54372 }
54373
54374 /**
54375 * Converts `value` to a number.
54376 *
54377 * @static
54378 * @memberOf _
54379 * @since 4.0.0
54380 * @category Lang
54381 * @param {*} value The value to process.
54382 * @returns {number} Returns the number.
54383 * @example
54384 *
54385 * _.toNumber(3.2);
54386 * // => 3.2
54387 *
54388 * _.toNumber(Number.MIN_VALUE);
54389 * // => 5e-324
54390 *
54391 * _.toNumber(Infinity);
54392 * // => Infinity
54393 *
54394 * _.toNumber('3.2');
54395 * // => 3.2
54396 */
54397 function toNumber(value) {
54398 if (typeof value == 'number') {
54399 return value;
54400 }
54401 if (isSymbol(value)) {
54402 return NAN;
54403 }
54404 if (isObject(value)) {
54405 var other = typeof value.valueOf == 'function' ? value.valueOf() : value;
54406 value = isObject(other) ? (other + '') : other;
54407 }
54408 if (typeof value != 'string') {
54409 return value === 0 ? value : +value;
54410 }
54411 value = value.replace(reTrim, '');
54412 var isBinary = reIsBinary.test(value);
54413 return (isBinary || reIsOctal.test(value))
54414 ? freeParseInt(value.slice(2), isBinary ? 2 : 8)
54415 : (reIsBadHex.test(value) ? NAN : +value);
54416 }
54417
54418 /**
54419 * Converts `value` to a plain object flattening inherited enumerable string
54420 * keyed properties of `value` to own properties of the plain object.
54421 *
54422 * @static
54423 * @memberOf _
54424 * @since 3.0.0
54425 * @category Lang
54426 * @param {*} value The value to convert.
54427 * @returns {Object} Returns the converted plain object.
54428 * @example
54429 *
54430 * function Foo() {
54431 * this.b = 2;
54432 * }
54433 *
54434 * Foo.prototype.c = 3;
54435 *
54436 * _.assign({ 'a': 1 }, new Foo);
54437 * // => { 'a': 1, 'b': 2 }
54438 *
54439 * _.assign({ 'a': 1 }, _.toPlainObject(new Foo));
54440 * // => { 'a': 1, 'b': 2, 'c': 3 }
54441 */
54442 function toPlainObject(value) {
54443 return copyObject(value, keysIn(value));
54444 }
54445
54446 /**
54447 * Converts `value` to a safe integer. A safe integer can be compared and
54448 * represented correctly.
54449 *
54450 * @static
54451 * @memberOf _
54452 * @since 4.0.0
54453 * @category Lang
54454 * @param {*} value The value to convert.
54455 * @returns {number} Returns the converted integer.
54456 * @example
54457 *
54458 * _.toSafeInteger(3.2);
54459 * // => 3
54460 *
54461 * _.toSafeInteger(Number.MIN_VALUE);
54462 * // => 0
54463 *
54464 * _.toSafeInteger(Infinity);
54465 * // => 9007199254740991
54466 *
54467 * _.toSafeInteger('3.2');
54468 * // => 3
54469 */
54470 function toSafeInteger(value) {
54471 return value
54472 ? baseClamp(toInteger(value), -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER)
54473 : (value === 0 ? value : 0);
54474 }
54475
54476 /**
54477 * Converts `value` to a string. An empty string is returned for `null`
54478 * and `undefined` values. The sign of `-0` is preserved.
54479 *
54480 * @static
54481 * @memberOf _
54482 * @since 4.0.0
54483 * @category Lang
54484 * @param {*} value The value to convert.
54485 * @returns {string} Returns the converted string.
54486 * @example
54487 *
54488 * _.toString(null);
54489 * // => ''
54490 *
54491 * _.toString(-0);
54492 * // => '-0'
54493 *
54494 * _.toString([1, 2, 3]);
54495 * // => '1,2,3'
54496 */
54497 function toString(value) {
54498 return value == null ? '' : baseToString(value);
54499 }
54500
54501 /*------------------------------------------------------------------------*/
54502
54503 /**
54504 * Assigns own enumerable string keyed properties of source objects to the
54505 * destination object. Source objects are applied from left to right.
54506 * Subsequent sources overwrite property assignments of previous sources.
54507 *
54508 * **Note:** This method mutates `object` and is loosely based on
54509 * [`Object.assign`](https://mdn.io/Object/assign).
54510 *
54511 * @static
54512 * @memberOf _
54513 * @since 0.10.0
54514 * @category Object
54515 * @param {Object} object The destination object.
54516 * @param {...Object} [sources] The source objects.
54517 * @returns {Object} Returns `object`.
54518 * @see _.assignIn
54519 * @example
54520 *
54521 * function Foo() {
54522 * this.a = 1;
54523 * }
54524 *
54525 * function Bar() {
54526 * this.c = 3;
54527 * }
54528 *
54529 * Foo.prototype.b = 2;
54530 * Bar.prototype.d = 4;
54531 *
54532 * _.assign({ 'a': 0 }, new Foo, new Bar);
54533 * // => { 'a': 1, 'c': 3 }
54534 */
54535 var assign = createAssigner(function(object, source) {
54536 if (isPrototype(source) || isArrayLike(source)) {
54537 copyObject(source, keys(source), object);
54538 return;
54539 }
54540 for (var key in source) {
54541 if (hasOwnProperty.call(source, key)) {
54542 assignValue(object, key, source[key]);
54543 }
54544 }
54545 });
54546
54547 /**
54548 * This method is like `_.assign` except that it iterates over own and
54549 * inherited source properties.
54550 *
54551 * **Note:** This method mutates `object`.
54552 *
54553 * @static
54554 * @memberOf _
54555 * @since 4.0.0
54556 * @alias extend
54557 * @category Object
54558 * @param {Object} object The destination object.
54559 * @param {...Object} [sources] The source objects.
54560 * @returns {Object} Returns `object`.
54561 * @see _.assign
54562 * @example
54563 *
54564 * function Foo() {
54565 * this.a = 1;
54566 * }
54567 *
54568 * function Bar() {
54569 * this.c = 3;
54570 * }
54571 *
54572 * Foo.prototype.b = 2;
54573 * Bar.prototype.d = 4;
54574 *
54575 * _.assignIn({ 'a': 0 }, new Foo, new Bar);
54576 * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 }
54577 */
54578 var assignIn = createAssigner(function(object, source) {
54579 copyObject(source, keysIn(source), object);
54580 });
54581
54582 /**
54583 * This method is like `_.assignIn` except that it accepts `customizer`
54584 * which is invoked to produce the assigned values. If `customizer` returns
54585 * `undefined`, assignment is handled by the method instead. The `customizer`
54586 * is invoked with five arguments: (objValue, srcValue, key, object, source).
54587 *
54588 * **Note:** This method mutates `object`.
54589 *
54590 * @static
54591 * @memberOf _
54592 * @since 4.0.0
54593 * @alias extendWith
54594 * @category Object
54595 * @param {Object} object The destination object.
54596 * @param {...Object} sources The source objects.
54597 * @param {Function} [customizer] The function to customize assigned values.
54598 * @returns {Object} Returns `object`.
54599 * @see _.assignWith
54600 * @example
54601 *
54602 * function customizer(objValue, srcValue) {
54603 * return _.isUndefined(objValue) ? srcValue : objValue;
54604 * }
54605 *
54606 * var defaults = _.partialRight(_.assignInWith, customizer);
54607 *
54608 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
54609 * // => { 'a': 1, 'b': 2 }
54610 */
54611 var assignInWith = createAssigner(function(object, source, srcIndex, customizer) {
54612 copyObject(source, keysIn(source), object, customizer);
54613 });
54614
54615 /**
54616 * This method is like `_.assign` except that it accepts `customizer`
54617 * which is invoked to produce the assigned values. If `customizer` returns
54618 * `undefined`, assignment is handled by the method instead. The `customizer`
54619 * is invoked with five arguments: (objValue, srcValue, key, object, source).
54620 *
54621 * **Note:** This method mutates `object`.
54622 *
54623 * @static
54624 * @memberOf _
54625 * @since 4.0.0
54626 * @category Object
54627 * @param {Object} object The destination object.
54628 * @param {...Object} sources The source objects.
54629 * @param {Function} [customizer] The function to customize assigned values.
54630 * @returns {Object} Returns `object`.
54631 * @see _.assignInWith
54632 * @example
54633 *
54634 * function customizer(objValue, srcValue) {
54635 * return _.isUndefined(objValue) ? srcValue : objValue;
54636 * }
54637 *
54638 * var defaults = _.partialRight(_.assignWith, customizer);
54639 *
54640 * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
54641 * // => { 'a': 1, 'b': 2 }
54642 */
54643 var assignWith = createAssigner(function(object, source, srcIndex, customizer) {
54644 copyObject(source, keys(source), object, customizer);
54645 });
54646
54647 /**
54648 * Creates an array of values corresponding to `paths` of `object`.
54649 *
54650 * @static
54651 * @memberOf _
54652 * @since 1.0.0
54653 * @category Object
54654 * @param {Object} object The object to iterate over.
54655 * @param {...(string|string[])} [paths] The property paths to pick.
54656 * @returns {Array} Returns the picked values.
54657 * @example
54658 *
54659 * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] };
54660 *
54661 * _.at(object, ['a[0].b.c', 'a[1]']);
54662 * // => [3, 4]
54663 */
54664 var at = flatRest(baseAt);
54665
54666 /**
54667 * Creates an object that inherits from the `prototype` object. If a
54668 * `properties` object is given, its own enumerable string keyed properties
54669 * are assigned to the created object.
54670 *
54671 * @static
54672 * @memberOf _
54673 * @since 2.3.0
54674 * @category Object
54675 * @param {Object} prototype The object to inherit from.
54676 * @param {Object} [properties] The properties to assign to the object.
54677 * @returns {Object} Returns the new object.
54678 * @example
54679 *
54680 * function Shape() {
54681 * this.x = 0;
54682 * this.y = 0;
54683 * }
54684 *
54685 * function Circle() {
54686 * Shape.call(this);
54687 * }
54688 *
54689 * Circle.prototype = _.create(Shape.prototype, {
54690 * 'constructor': Circle
54691 * });
54692 *
54693 * var circle = new Circle;
54694 * circle instanceof Circle;
54695 * // => true
54696 *
54697 * circle instanceof Shape;
54698 * // => true
54699 */
54700 function create(prototype, properties) {
54701 var result = baseCreate(prototype);
54702 return properties == null ? result : baseAssign(result, properties);
54703 }
54704
54705 /**
54706 * Assigns own and inherited enumerable string keyed properties of source
54707 * objects to the destination object for all destination properties that
54708 * resolve to `undefined`. Source objects are applied from left to right.
54709 * Once a property is set, additional values of the same property are ignored.
54710 *
54711 * **Note:** This method mutates `object`.
54712 *
54713 * @static
54714 * @since 0.1.0
54715 * @memberOf _
54716 * @category Object
54717 * @param {Object} object The destination object.
54718 * @param {...Object} [sources] The source objects.
54719 * @returns {Object} Returns `object`.
54720 * @see _.defaultsDeep
54721 * @example
54722 *
54723 * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 });
54724 * // => { 'a': 1, 'b': 2 }
54725 */
54726 var defaults = baseRest(function(object, sources) {
54727 object = Object(object);
54728
54729 var index = -1;
54730 var length = sources.length;
54731 var guard = length > 2 ? sources[2] : undefined;
54732
54733 if (guard && isIterateeCall(sources[0], sources[1], guard)) {
54734 length = 1;
54735 }
54736
54737 while (++index < length) {
54738 var source = sources[index];
54739 var props = keysIn(source);
54740 var propsIndex = -1;
54741 var propsLength = props.length;
54742
54743 while (++propsIndex < propsLength) {
54744 var key = props[propsIndex];
54745 var value = object[key];
54746
54747 if (value === undefined ||
54748 (eq(value, objectProto[key]) && !hasOwnProperty.call(object, key))) {
54749 object[key] = source[key];
54750 }
54751 }
54752 }
54753
54754 return object;
54755 });
54756
54757 /**
54758 * This method is like `_.defaults` except that it recursively assigns
54759 * default properties.
54760 *
54761 * **Note:** This method mutates `object`.
54762 *
54763 * @static
54764 * @memberOf _
54765 * @since 3.10.0
54766 * @category Object
54767 * @param {Object} object The destination object.
54768 * @param {...Object} [sources] The source objects.
54769 * @returns {Object} Returns `object`.
54770 * @see _.defaults
54771 * @example
54772 *
54773 * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } });
54774 * // => { 'a': { 'b': 2, 'c': 3 } }
54775 */
54776 var defaultsDeep = baseRest(function(args) {
54777 args.push(undefined, customDefaultsMerge);
54778 return apply(mergeWith, undefined, args);
54779 });
54780
54781 /**
54782 * This method is like `_.find` except that it returns the key of the first
54783 * element `predicate` returns truthy for instead of the element itself.
54784 *
54785 * @static
54786 * @memberOf _
54787 * @since 1.1.0
54788 * @category Object
54789 * @param {Object} object The object to inspect.
54790 * @param {Function} [predicate=_.identity] The function invoked per iteration.
54791 * @returns {string|undefined} Returns the key of the matched element,
54792 * else `undefined`.
54793 * @example
54794 *
54795 * var users = {
54796 * 'barney': { 'age': 36, 'active': true },
54797 * 'fred': { 'age': 40, 'active': false },
54798 * 'pebbles': { 'age': 1, 'active': true }
54799 * };
54800 *
54801 * _.findKey(users, function(o) { return o.age < 40; });
54802 * // => 'barney' (iteration order is not guaranteed)
54803 *
54804 * // The `_.matches` iteratee shorthand.
54805 * _.findKey(users, { 'age': 1, 'active': true });
54806 * // => 'pebbles'
54807 *
54808 * // The `_.matchesProperty` iteratee shorthand.
54809 * _.findKey(users, ['active', false]);
54810 * // => 'fred'
54811 *
54812 * // The `_.property` iteratee shorthand.
54813 * _.findKey(users, 'active');
54814 * // => 'barney'
54815 */
54816 function findKey(object, predicate) {
54817 return baseFindKey(object, getIteratee(predicate, 3), baseForOwn);
54818 }
54819
54820 /**
54821 * This method is like `_.findKey` except that it iterates over elements of
54822 * a collection in the opposite order.
54823 *
54824 * @static
54825 * @memberOf _
54826 * @since 2.0.0
54827 * @category Object
54828 * @param {Object} object The object to inspect.
54829 * @param {Function} [predicate=_.identity] The function invoked per iteration.
54830 * @returns {string|undefined} Returns the key of the matched element,
54831 * else `undefined`.
54832 * @example
54833 *
54834 * var users = {
54835 * 'barney': { 'age': 36, 'active': true },
54836 * 'fred': { 'age': 40, 'active': false },
54837 * 'pebbles': { 'age': 1, 'active': true }
54838 * };
54839 *
54840 * _.findLastKey(users, function(o) { return o.age < 40; });
54841 * // => returns 'pebbles' assuming `_.findKey` returns 'barney'
54842 *
54843 * // The `_.matches` iteratee shorthand.
54844 * _.findLastKey(users, { 'age': 36, 'active': true });
54845 * // => 'barney'
54846 *
54847 * // The `_.matchesProperty` iteratee shorthand.
54848 * _.findLastKey(users, ['active', false]);
54849 * // => 'fred'
54850 *
54851 * // The `_.property` iteratee shorthand.
54852 * _.findLastKey(users, 'active');
54853 * // => 'pebbles'
54854 */
54855 function findLastKey(object, predicate) {
54856 return baseFindKey(object, getIteratee(predicate, 3), baseForOwnRight);
54857 }
54858
54859 /**
54860 * Iterates over own and inherited enumerable string keyed properties of an
54861 * object and invokes `iteratee` for each property. The iteratee is invoked
54862 * with three arguments: (value, key, object). Iteratee functions may exit
54863 * iteration early by explicitly returning `false`.
54864 *
54865 * @static
54866 * @memberOf _
54867 * @since 0.3.0
54868 * @category Object
54869 * @param {Object} object The object to iterate over.
54870 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
54871 * @returns {Object} Returns `object`.
54872 * @see _.forInRight
54873 * @example
54874 *
54875 * function Foo() {
54876 * this.a = 1;
54877 * this.b = 2;
54878 * }
54879 *
54880 * Foo.prototype.c = 3;
54881 *
54882 * _.forIn(new Foo, function(value, key) {
54883 * console.log(key);
54884 * });
54885 * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed).
54886 */
54887 function forIn(object, iteratee) {
54888 return object == null
54889 ? object
54890 : baseFor(object, getIteratee(iteratee, 3), keysIn);
54891 }
54892
54893 /**
54894 * This method is like `_.forIn` except that it iterates over properties of
54895 * `object` in the opposite order.
54896 *
54897 * @static
54898 * @memberOf _
54899 * @since 2.0.0
54900 * @category Object
54901 * @param {Object} object The object to iterate over.
54902 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
54903 * @returns {Object} Returns `object`.
54904 * @see _.forIn
54905 * @example
54906 *
54907 * function Foo() {
54908 * this.a = 1;
54909 * this.b = 2;
54910 * }
54911 *
54912 * Foo.prototype.c = 3;
54913 *
54914 * _.forInRight(new Foo, function(value, key) {
54915 * console.log(key);
54916 * });
54917 * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'.
54918 */
54919 function forInRight(object, iteratee) {
54920 return object == null
54921 ? object
54922 : baseForRight(object, getIteratee(iteratee, 3), keysIn);
54923 }
54924
54925 /**
54926 * Iterates over own enumerable string keyed properties of an object and
54927 * invokes `iteratee` for each property. The iteratee is invoked with three
54928 * arguments: (value, key, object). Iteratee functions may exit iteration
54929 * early by explicitly returning `false`.
54930 *
54931 * @static
54932 * @memberOf _
54933 * @since 0.3.0
54934 * @category Object
54935 * @param {Object} object The object to iterate over.
54936 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
54937 * @returns {Object} Returns `object`.
54938 * @see _.forOwnRight
54939 * @example
54940 *
54941 * function Foo() {
54942 * this.a = 1;
54943 * this.b = 2;
54944 * }
54945 *
54946 * Foo.prototype.c = 3;
54947 *
54948 * _.forOwn(new Foo, function(value, key) {
54949 * console.log(key);
54950 * });
54951 * // => Logs 'a' then 'b' (iteration order is not guaranteed).
54952 */
54953 function forOwn(object, iteratee) {
54954 return object && baseForOwn(object, getIteratee(iteratee, 3));
54955 }
54956
54957 /**
54958 * This method is like `_.forOwn` except that it iterates over properties of
54959 * `object` in the opposite order.
54960 *
54961 * @static
54962 * @memberOf _
54963 * @since 2.0.0
54964 * @category Object
54965 * @param {Object} object The object to iterate over.
54966 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
54967 * @returns {Object} Returns `object`.
54968 * @see _.forOwn
54969 * @example
54970 *
54971 * function Foo() {
54972 * this.a = 1;
54973 * this.b = 2;
54974 * }
54975 *
54976 * Foo.prototype.c = 3;
54977 *
54978 * _.forOwnRight(new Foo, function(value, key) {
54979 * console.log(key);
54980 * });
54981 * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'.
54982 */
54983 function forOwnRight(object, iteratee) {
54984 return object && baseForOwnRight(object, getIteratee(iteratee, 3));
54985 }
54986
54987 /**
54988 * Creates an array of function property names from own enumerable properties
54989 * of `object`.
54990 *
54991 * @static
54992 * @since 0.1.0
54993 * @memberOf _
54994 * @category Object
54995 * @param {Object} object The object to inspect.
54996 * @returns {Array} Returns the function names.
54997 * @see _.functionsIn
54998 * @example
54999 *
55000 * function Foo() {
55001 * this.a = _.constant('a');
55002 * this.b = _.constant('b');
55003 * }
55004 *
55005 * Foo.prototype.c = _.constant('c');
55006 *
55007 * _.functions(new Foo);
55008 * // => ['a', 'b']
55009 */
55010 function functions(object) {
55011 return object == null ? [] : baseFunctions(object, keys(object));
55012 }
55013
55014 /**
55015 * Creates an array of function property names from own and inherited
55016 * enumerable properties of `object`.
55017 *
55018 * @static
55019 * @memberOf _
55020 * @since 4.0.0
55021 * @category Object
55022 * @param {Object} object The object to inspect.
55023 * @returns {Array} Returns the function names.
55024 * @see _.functions
55025 * @example
55026 *
55027 * function Foo() {
55028 * this.a = _.constant('a');
55029 * this.b = _.constant('b');
55030 * }
55031 *
55032 * Foo.prototype.c = _.constant('c');
55033 *
55034 * _.functionsIn(new Foo);
55035 * // => ['a', 'b', 'c']
55036 */
55037 function functionsIn(object) {
55038 return object == null ? [] : baseFunctions(object, keysIn(object));
55039 }
55040
55041 /**
55042 * Gets the value at `path` of `object`. If the resolved value is
55043 * `undefined`, the `defaultValue` is returned in its place.
55044 *
55045 * @static
55046 * @memberOf _
55047 * @since 3.7.0
55048 * @category Object
55049 * @param {Object} object The object to query.
55050 * @param {Array|string} path The path of the property to get.
55051 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
55052 * @returns {*} Returns the resolved value.
55053 * @example
55054 *
55055 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
55056 *
55057 * _.get(object, 'a[0].b.c');
55058 * // => 3
55059 *
55060 * _.get(object, ['a', '0', 'b', 'c']);
55061 * // => 3
55062 *
55063 * _.get(object, 'a.b.c', 'default');
55064 * // => 'default'
55065 */
55066 function get(object, path, defaultValue) {
55067 var result = object == null ? undefined : baseGet(object, path);
55068 return result === undefined ? defaultValue : result;
55069 }
55070
55071 /**
55072 * Checks if `path` is a direct property of `object`.
55073 *
55074 * @static
55075 * @since 0.1.0
55076 * @memberOf _
55077 * @category Object
55078 * @param {Object} object The object to query.
55079 * @param {Array|string} path The path to check.
55080 * @returns {boolean} Returns `true` if `path` exists, else `false`.
55081 * @example
55082 *
55083 * var object = { 'a': { 'b': 2 } };
55084 * var other = _.create({ 'a': _.create({ 'b': 2 }) });
55085 *
55086 * _.has(object, 'a');
55087 * // => true
55088 *
55089 * _.has(object, 'a.b');
55090 * // => true
55091 *
55092 * _.has(object, ['a', 'b']);
55093 * // => true
55094 *
55095 * _.has(other, 'a');
55096 * // => false
55097 */
55098 function has(object, path) {
55099 return object != null && hasPath(object, path, baseHas);
55100 }
55101
55102 /**
55103 * Checks if `path` is a direct or inherited property of `object`.
55104 *
55105 * @static
55106 * @memberOf _
55107 * @since 4.0.0
55108 * @category Object
55109 * @param {Object} object The object to query.
55110 * @param {Array|string} path The path to check.
55111 * @returns {boolean} Returns `true` if `path` exists, else `false`.
55112 * @example
55113 *
55114 * var object = _.create({ 'a': _.create({ 'b': 2 }) });
55115 *
55116 * _.hasIn(object, 'a');
55117 * // => true
55118 *
55119 * _.hasIn(object, 'a.b');
55120 * // => true
55121 *
55122 * _.hasIn(object, ['a', 'b']);
55123 * // => true
55124 *
55125 * _.hasIn(object, 'b');
55126 * // => false
55127 */
55128 function hasIn(object, path) {
55129 return object != null && hasPath(object, path, baseHasIn);
55130 }
55131
55132 /**
55133 * Creates an object composed of the inverted keys and values of `object`.
55134 * If `object` contains duplicate values, subsequent values overwrite
55135 * property assignments of previous values.
55136 *
55137 * @static
55138 * @memberOf _
55139 * @since 0.7.0
55140 * @category Object
55141 * @param {Object} object The object to invert.
55142 * @returns {Object} Returns the new inverted object.
55143 * @example
55144 *
55145 * var object = { 'a': 1, 'b': 2, 'c': 1 };
55146 *
55147 * _.invert(object);
55148 * // => { '1': 'c', '2': 'b' }
55149 */
55150 var invert = createInverter(function(result, value, key) {
55151 if (value != null &&
55152 typeof value.toString != 'function') {
55153 value = nativeObjectToString.call(value);
55154 }
55155
55156 result[value] = key;
55157 }, constant(identity));
55158
55159 /**
55160 * This method is like `_.invert` except that the inverted object is generated
55161 * from the results of running each element of `object` thru `iteratee`. The
55162 * corresponding inverted value of each inverted key is an array of keys
55163 * responsible for generating the inverted value. The iteratee is invoked
55164 * with one argument: (value).
55165 *
55166 * @static
55167 * @memberOf _
55168 * @since 4.1.0
55169 * @category Object
55170 * @param {Object} object The object to invert.
55171 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
55172 * @returns {Object} Returns the new inverted object.
55173 * @example
55174 *
55175 * var object = { 'a': 1, 'b': 2, 'c': 1 };
55176 *
55177 * _.invertBy(object);
55178 * // => { '1': ['a', 'c'], '2': ['b'] }
55179 *
55180 * _.invertBy(object, function(value) {
55181 * return 'group' + value;
55182 * });
55183 * // => { 'group1': ['a', 'c'], 'group2': ['b'] }
55184 */
55185 var invertBy = createInverter(function(result, value, key) {
55186 if (value != null &&
55187 typeof value.toString != 'function') {
55188 value = nativeObjectToString.call(value);
55189 }
55190
55191 if (hasOwnProperty.call(result, value)) {
55192 result[value].push(key);
55193 } else {
55194 result[value] = [key];
55195 }
55196 }, getIteratee);
55197
55198 /**
55199 * Invokes the method at `path` of `object`.
55200 *
55201 * @static
55202 * @memberOf _
55203 * @since 4.0.0
55204 * @category Object
55205 * @param {Object} object The object to query.
55206 * @param {Array|string} path The path of the method to invoke.
55207 * @param {...*} [args] The arguments to invoke the method with.
55208 * @returns {*} Returns the result of the invoked method.
55209 * @example
55210 *
55211 * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] };
55212 *
55213 * _.invoke(object, 'a[0].b.c.slice', 1, 3);
55214 * // => [2, 3]
55215 */
55216 var invoke = baseRest(baseInvoke);
55217
55218 /**
55219 * Creates an array of the own enumerable property names of `object`.
55220 *
55221 * **Note:** Non-object values are coerced to objects. See the
55222 * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys)
55223 * for more details.
55224 *
55225 * @static
55226 * @since 0.1.0
55227 * @memberOf _
55228 * @category Object
55229 * @param {Object} object The object to query.
55230 * @returns {Array} Returns the array of property names.
55231 * @example
55232 *
55233 * function Foo() {
55234 * this.a = 1;
55235 * this.b = 2;
55236 * }
55237 *
55238 * Foo.prototype.c = 3;
55239 *
55240 * _.keys(new Foo);
55241 * // => ['a', 'b'] (iteration order is not guaranteed)
55242 *
55243 * _.keys('hi');
55244 * // => ['0', '1']
55245 */
55246 function keys(object) {
55247 return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object);
55248 }
55249
55250 /**
55251 * Creates an array of the own and inherited enumerable property names of `object`.
55252 *
55253 * **Note:** Non-object values are coerced to objects.
55254 *
55255 * @static
55256 * @memberOf _
55257 * @since 3.0.0
55258 * @category Object
55259 * @param {Object} object The object to query.
55260 * @returns {Array} Returns the array of property names.
55261 * @example
55262 *
55263 * function Foo() {
55264 * this.a = 1;
55265 * this.b = 2;
55266 * }
55267 *
55268 * Foo.prototype.c = 3;
55269 *
55270 * _.keysIn(new Foo);
55271 * // => ['a', 'b', 'c'] (iteration order is not guaranteed)
55272 */
55273 function keysIn(object) {
55274 return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object);
55275 }
55276
55277 /**
55278 * The opposite of `_.mapValues`; this method creates an object with the
55279 * same values as `object` and keys generated by running each own enumerable
55280 * string keyed property of `object` thru `iteratee`. The iteratee is invoked
55281 * with three arguments: (value, key, object).
55282 *
55283 * @static
55284 * @memberOf _
55285 * @since 3.8.0
55286 * @category Object
55287 * @param {Object} object The object to iterate over.
55288 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
55289 * @returns {Object} Returns the new mapped object.
55290 * @see _.mapValues
55291 * @example
55292 *
55293 * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) {
55294 * return key + value;
55295 * });
55296 * // => { 'a1': 1, 'b2': 2 }
55297 */
55298 function mapKeys(object, iteratee) {
55299 var result = {};
55300 iteratee = getIteratee(iteratee, 3);
55301
55302 baseForOwn(object, function(value, key, object) {
55303 baseAssignValue(result, iteratee(value, key, object), value);
55304 });
55305 return result;
55306 }
55307
55308 /**
55309 * Creates an object with the same keys as `object` and values generated
55310 * by running each own enumerable string keyed property of `object` thru
55311 * `iteratee`. The iteratee is invoked with three arguments:
55312 * (value, key, object).
55313 *
55314 * @static
55315 * @memberOf _
55316 * @since 2.4.0
55317 * @category Object
55318 * @param {Object} object The object to iterate over.
55319 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
55320 * @returns {Object} Returns the new mapped object.
55321 * @see _.mapKeys
55322 * @example
55323 *
55324 * var users = {
55325 * 'fred': { 'user': 'fred', 'age': 40 },
55326 * 'pebbles': { 'user': 'pebbles', 'age': 1 }
55327 * };
55328 *
55329 * _.mapValues(users, function(o) { return o.age; });
55330 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
55331 *
55332 * // The `_.property` iteratee shorthand.
55333 * _.mapValues(users, 'age');
55334 * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed)
55335 */
55336 function mapValues(object, iteratee) {
55337 var result = {};
55338 iteratee = getIteratee(iteratee, 3);
55339
55340 baseForOwn(object, function(value, key, object) {
55341 baseAssignValue(result, key, iteratee(value, key, object));
55342 });
55343 return result;
55344 }
55345
55346 /**
55347 * This method is like `_.assign` except that it recursively merges own and
55348 * inherited enumerable string keyed properties of source objects into the
55349 * destination object. Source properties that resolve to `undefined` are
55350 * skipped if a destination value exists. Array and plain object properties
55351 * are merged recursively. Other objects and value types are overridden by
55352 * assignment. Source objects are applied from left to right. Subsequent
55353 * sources overwrite property assignments of previous sources.
55354 *
55355 * **Note:** This method mutates `object`.
55356 *
55357 * @static
55358 * @memberOf _
55359 * @since 0.5.0
55360 * @category Object
55361 * @param {Object} object The destination object.
55362 * @param {...Object} [sources] The source objects.
55363 * @returns {Object} Returns `object`.
55364 * @example
55365 *
55366 * var object = {
55367 * 'a': [{ 'b': 2 }, { 'd': 4 }]
55368 * };
55369 *
55370 * var other = {
55371 * 'a': [{ 'c': 3 }, { 'e': 5 }]
55372 * };
55373 *
55374 * _.merge(object, other);
55375 * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] }
55376 */
55377 var merge = createAssigner(function(object, source, srcIndex) {
55378 baseMerge(object, source, srcIndex);
55379 });
55380
55381 /**
55382 * This method is like `_.merge` except that it accepts `customizer` which
55383 * is invoked to produce the merged values of the destination and source
55384 * properties. If `customizer` returns `undefined`, merging is handled by the
55385 * method instead. The `customizer` is invoked with six arguments:
55386 * (objValue, srcValue, key, object, source, stack).
55387 *
55388 * **Note:** This method mutates `object`.
55389 *
55390 * @static
55391 * @memberOf _
55392 * @since 4.0.0
55393 * @category Object
55394 * @param {Object} object The destination object.
55395 * @param {...Object} sources The source objects.
55396 * @param {Function} customizer The function to customize assigned values.
55397 * @returns {Object} Returns `object`.
55398 * @example
55399 *
55400 * function customizer(objValue, srcValue) {
55401 * if (_.isArray(objValue)) {
55402 * return objValue.concat(srcValue);
55403 * }
55404 * }
55405 *
55406 * var object = { 'a': [1], 'b': [2] };
55407 * var other = { 'a': [3], 'b': [4] };
55408 *
55409 * _.mergeWith(object, other, customizer);
55410 * // => { 'a': [1, 3], 'b': [2, 4] }
55411 */
55412 var mergeWith = createAssigner(function(object, source, srcIndex, customizer) {
55413 baseMerge(object, source, srcIndex, customizer);
55414 });
55415
55416 /**
55417 * The opposite of `_.pick`; this method creates an object composed of the
55418 * own and inherited enumerable property paths of `object` that are not omitted.
55419 *
55420 * **Note:** This method is considerably slower than `_.pick`.
55421 *
55422 * @static
55423 * @since 0.1.0
55424 * @memberOf _
55425 * @category Object
55426 * @param {Object} object The source object.
55427 * @param {...(string|string[])} [paths] The property paths to omit.
55428 * @returns {Object} Returns the new object.
55429 * @example
55430 *
55431 * var object = { 'a': 1, 'b': '2', 'c': 3 };
55432 *
55433 * _.omit(object, ['a', 'c']);
55434 * // => { 'b': '2' }
55435 */
55436 var omit = flatRest(function(object, paths) {
55437 var result = {};
55438 if (object == null) {
55439 return result;
55440 }
55441 var isDeep = false;
55442 paths = arrayMap(paths, function(path) {
55443 path = castPath(path, object);
55444 isDeep || (isDeep = path.length > 1);
55445 return path;
55446 });
55447 copyObject(object, getAllKeysIn(object), result);
55448 if (isDeep) {
55449 result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone);
55450 }
55451 var length = paths.length;
55452 while (length--) {
55453 baseUnset(result, paths[length]);
55454 }
55455 return result;
55456 });
55457
55458 /**
55459 * The opposite of `_.pickBy`; this method creates an object composed of
55460 * the own and inherited enumerable string keyed properties of `object` that
55461 * `predicate` doesn't return truthy for. The predicate is invoked with two
55462 * arguments: (value, key).
55463 *
55464 * @static
55465 * @memberOf _
55466 * @since 4.0.0
55467 * @category Object
55468 * @param {Object} object The source object.
55469 * @param {Function} [predicate=_.identity] The function invoked per property.
55470 * @returns {Object} Returns the new object.
55471 * @example
55472 *
55473 * var object = { 'a': 1, 'b': '2', 'c': 3 };
55474 *
55475 * _.omitBy(object, _.isNumber);
55476 * // => { 'b': '2' }
55477 */
55478 function omitBy(object, predicate) {
55479 return pickBy(object, negate(getIteratee(predicate)));
55480 }
55481
55482 /**
55483 * Creates an object composed of the picked `object` properties.
55484 *
55485 * @static
55486 * @since 0.1.0
55487 * @memberOf _
55488 * @category Object
55489 * @param {Object} object The source object.
55490 * @param {...(string|string[])} [paths] The property paths to pick.
55491 * @returns {Object} Returns the new object.
55492 * @example
55493 *
55494 * var object = { 'a': 1, 'b': '2', 'c': 3 };
55495 *
55496 * _.pick(object, ['a', 'c']);
55497 * // => { 'a': 1, 'c': 3 }
55498 */
55499 var pick = flatRest(function(object, paths) {
55500 return object == null ? {} : basePick(object, paths);
55501 });
55502
55503 /**
55504 * Creates an object composed of the `object` properties `predicate` returns
55505 * truthy for. The predicate is invoked with two arguments: (value, key).
55506 *
55507 * @static
55508 * @memberOf _
55509 * @since 4.0.0
55510 * @category Object
55511 * @param {Object} object The source object.
55512 * @param {Function} [predicate=_.identity] The function invoked per property.
55513 * @returns {Object} Returns the new object.
55514 * @example
55515 *
55516 * var object = { 'a': 1, 'b': '2', 'c': 3 };
55517 *
55518 * _.pickBy(object, _.isNumber);
55519 * // => { 'a': 1, 'c': 3 }
55520 */
55521 function pickBy(object, predicate) {
55522 if (object == null) {
55523 return {};
55524 }
55525 var props = arrayMap(getAllKeysIn(object), function(prop) {
55526 return [prop];
55527 });
55528 predicate = getIteratee(predicate);
55529 return basePickBy(object, props, function(value, path) {
55530 return predicate(value, path[0]);
55531 });
55532 }
55533
55534 /**
55535 * This method is like `_.get` except that if the resolved value is a
55536 * function it's invoked with the `this` binding of its parent object and
55537 * its result is returned.
55538 *
55539 * @static
55540 * @since 0.1.0
55541 * @memberOf _
55542 * @category Object
55543 * @param {Object} object The object to query.
55544 * @param {Array|string} path The path of the property to resolve.
55545 * @param {*} [defaultValue] The value returned for `undefined` resolved values.
55546 * @returns {*} Returns the resolved value.
55547 * @example
55548 *
55549 * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] };
55550 *
55551 * _.result(object, 'a[0].b.c1');
55552 * // => 3
55553 *
55554 * _.result(object, 'a[0].b.c2');
55555 * // => 4
55556 *
55557 * _.result(object, 'a[0].b.c3', 'default');
55558 * // => 'default'
55559 *
55560 * _.result(object, 'a[0].b.c3', _.constant('default'));
55561 * // => 'default'
55562 */
55563 function result(object, path, defaultValue) {
55564 path = castPath(path, object);
55565
55566 var index = -1,
55567 length = path.length;
55568
55569 // Ensure the loop is entered when path is empty.
55570 if (!length) {
55571 length = 1;
55572 object = undefined;
55573 }
55574 while (++index < length) {
55575 var value = object == null ? undefined : object[toKey(path[index])];
55576 if (value === undefined) {
55577 index = length;
55578 value = defaultValue;
55579 }
55580 object = isFunction(value) ? value.call(object) : value;
55581 }
55582 return object;
55583 }
55584
55585 /**
55586 * Sets the value at `path` of `object`. If a portion of `path` doesn't exist,
55587 * it's created. Arrays are created for missing index properties while objects
55588 * are created for all other missing properties. Use `_.setWith` to customize
55589 * `path` creation.
55590 *
55591 * **Note:** This method mutates `object`.
55592 *
55593 * @static
55594 * @memberOf _
55595 * @since 3.7.0
55596 * @category Object
55597 * @param {Object} object The object to modify.
55598 * @param {Array|string} path The path of the property to set.
55599 * @param {*} value The value to set.
55600 * @returns {Object} Returns `object`.
55601 * @example
55602 *
55603 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
55604 *
55605 * _.set(object, 'a[0].b.c', 4);
55606 * console.log(object.a[0].b.c);
55607 * // => 4
55608 *
55609 * _.set(object, ['x', '0', 'y', 'z'], 5);
55610 * console.log(object.x[0].y.z);
55611 * // => 5
55612 */
55613 function set(object, path, value) {
55614 return object == null ? object : baseSet(object, path, value);
55615 }
55616
55617 /**
55618 * This method is like `_.set` except that it accepts `customizer` which is
55619 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
55620 * path creation is handled by the method instead. The `customizer` is invoked
55621 * with three arguments: (nsValue, key, nsObject).
55622 *
55623 * **Note:** This method mutates `object`.
55624 *
55625 * @static
55626 * @memberOf _
55627 * @since 4.0.0
55628 * @category Object
55629 * @param {Object} object The object to modify.
55630 * @param {Array|string} path The path of the property to set.
55631 * @param {*} value The value to set.
55632 * @param {Function} [customizer] The function to customize assigned values.
55633 * @returns {Object} Returns `object`.
55634 * @example
55635 *
55636 * var object = {};
55637 *
55638 * _.setWith(object, '[0][1]', 'a', Object);
55639 * // => { '0': { '1': 'a' } }
55640 */
55641 function setWith(object, path, value, customizer) {
55642 customizer = typeof customizer == 'function' ? customizer : undefined;
55643 return object == null ? object : baseSet(object, path, value, customizer);
55644 }
55645
55646 /**
55647 * Creates an array of own enumerable string keyed-value pairs for `object`
55648 * which can be consumed by `_.fromPairs`. If `object` is a map or set, its
55649 * entries are returned.
55650 *
55651 * @static
55652 * @memberOf _
55653 * @since 4.0.0
55654 * @alias entries
55655 * @category Object
55656 * @param {Object} object The object to query.
55657 * @returns {Array} Returns the key-value pairs.
55658 * @example
55659 *
55660 * function Foo() {
55661 * this.a = 1;
55662 * this.b = 2;
55663 * }
55664 *
55665 * Foo.prototype.c = 3;
55666 *
55667 * _.toPairs(new Foo);
55668 * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed)
55669 */
55670 var toPairs = createToPairs(keys);
55671
55672 /**
55673 * Creates an array of own and inherited enumerable string keyed-value pairs
55674 * for `object` which can be consumed by `_.fromPairs`. If `object` is a map
55675 * or set, its entries are returned.
55676 *
55677 * @static
55678 * @memberOf _
55679 * @since 4.0.0
55680 * @alias entriesIn
55681 * @category Object
55682 * @param {Object} object The object to query.
55683 * @returns {Array} Returns the key-value pairs.
55684 * @example
55685 *
55686 * function Foo() {
55687 * this.a = 1;
55688 * this.b = 2;
55689 * }
55690 *
55691 * Foo.prototype.c = 3;
55692 *
55693 * _.toPairsIn(new Foo);
55694 * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed)
55695 */
55696 var toPairsIn = createToPairs(keysIn);
55697
55698 /**
55699 * An alternative to `_.reduce`; this method transforms `object` to a new
55700 * `accumulator` object which is the result of running each of its own
55701 * enumerable string keyed properties thru `iteratee`, with each invocation
55702 * potentially mutating the `accumulator` object. If `accumulator` is not
55703 * provided, a new object with the same `[[Prototype]]` will be used. The
55704 * iteratee is invoked with four arguments: (accumulator, value, key, object).
55705 * Iteratee functions may exit iteration early by explicitly returning `false`.
55706 *
55707 * @static
55708 * @memberOf _
55709 * @since 1.3.0
55710 * @category Object
55711 * @param {Object} object The object to iterate over.
55712 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
55713 * @param {*} [accumulator] The custom accumulator value.
55714 * @returns {*} Returns the accumulated value.
55715 * @example
55716 *
55717 * _.transform([2, 3, 4], function(result, n) {
55718 * result.push(n *= n);
55719 * return n % 2 == 0;
55720 * }, []);
55721 * // => [4, 9]
55722 *
55723 * _.transform({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) {
55724 * (result[value] || (result[value] = [])).push(key);
55725 * }, {});
55726 * // => { '1': ['a', 'c'], '2': ['b'] }
55727 */
55728 function transform(object, iteratee, accumulator) {
55729 var isArr = isArray(object),
55730 isArrLike = isArr || isBuffer(object) || isTypedArray(object);
55731
55732 iteratee = getIteratee(iteratee, 4);
55733 if (accumulator == null) {
55734 var Ctor = object && object.constructor;
55735 if (isArrLike) {
55736 accumulator = isArr ? new Ctor : [];
55737 }
55738 else if (isObject(object)) {
55739 accumulator = isFunction(Ctor) ? baseCreate(getPrototype(object)) : {};
55740 }
55741 else {
55742 accumulator = {};
55743 }
55744 }
55745 (isArrLike ? arrayEach : baseForOwn)(object, function(value, index, object) {
55746 return iteratee(accumulator, value, index, object);
55747 });
55748 return accumulator;
55749 }
55750
55751 /**
55752 * Removes the property at `path` of `object`.
55753 *
55754 * **Note:** This method mutates `object`.
55755 *
55756 * @static
55757 * @memberOf _
55758 * @since 4.0.0
55759 * @category Object
55760 * @param {Object} object The object to modify.
55761 * @param {Array|string} path The path of the property to unset.
55762 * @returns {boolean} Returns `true` if the property is deleted, else `false`.
55763 * @example
55764 *
55765 * var object = { 'a': [{ 'b': { 'c': 7 } }] };
55766 * _.unset(object, 'a[0].b.c');
55767 * // => true
55768 *
55769 * console.log(object);
55770 * // => { 'a': [{ 'b': {} }] };
55771 *
55772 * _.unset(object, ['a', '0', 'b', 'c']);
55773 * // => true
55774 *
55775 * console.log(object);
55776 * // => { 'a': [{ 'b': {} }] };
55777 */
55778 function unset(object, path) {
55779 return object == null ? true : baseUnset(object, path);
55780 }
55781
55782 /**
55783 * This method is like `_.set` except that accepts `updater` to produce the
55784 * value to set. Use `_.updateWith` to customize `path` creation. The `updater`
55785 * is invoked with one argument: (value).
55786 *
55787 * **Note:** This method mutates `object`.
55788 *
55789 * @static
55790 * @memberOf _
55791 * @since 4.6.0
55792 * @category Object
55793 * @param {Object} object The object to modify.
55794 * @param {Array|string} path The path of the property to set.
55795 * @param {Function} updater The function to produce the updated value.
55796 * @returns {Object} Returns `object`.
55797 * @example
55798 *
55799 * var object = { 'a': [{ 'b': { 'c': 3 } }] };
55800 *
55801 * _.update(object, 'a[0].b.c', function(n) { return n * n; });
55802 * console.log(object.a[0].b.c);
55803 * // => 9
55804 *
55805 * _.update(object, 'x[0].y.z', function(n) { return n ? n + 1 : 0; });
55806 * console.log(object.x[0].y.z);
55807 * // => 0
55808 */
55809 function update(object, path, updater) {
55810 return object == null ? object : baseUpdate(object, path, castFunction(updater));
55811 }
55812
55813 /**
55814 * This method is like `_.update` except that it accepts `customizer` which is
55815 * invoked to produce the objects of `path`. If `customizer` returns `undefined`
55816 * path creation is handled by the method instead. The `customizer` is invoked
55817 * with three arguments: (nsValue, key, nsObject).
55818 *
55819 * **Note:** This method mutates `object`.
55820 *
55821 * @static
55822 * @memberOf _
55823 * @since 4.6.0
55824 * @category Object
55825 * @param {Object} object The object to modify.
55826 * @param {Array|string} path The path of the property to set.
55827 * @param {Function} updater The function to produce the updated value.
55828 * @param {Function} [customizer] The function to customize assigned values.
55829 * @returns {Object} Returns `object`.
55830 * @example
55831 *
55832 * var object = {};
55833 *
55834 * _.updateWith(object, '[0][1]', _.constant('a'), Object);
55835 * // => { '0': { '1': 'a' } }
55836 */
55837 function updateWith(object, path, updater, customizer) {
55838 customizer = typeof customizer == 'function' ? customizer : undefined;
55839 return object == null ? object : baseUpdate(object, path, castFunction(updater), customizer);
55840 }
55841
55842 /**
55843 * Creates an array of the own enumerable string keyed property values of `object`.
55844 *
55845 * **Note:** Non-object values are coerced to objects.
55846 *
55847 * @static
55848 * @since 0.1.0
55849 * @memberOf _
55850 * @category Object
55851 * @param {Object} object The object to query.
55852 * @returns {Array} Returns the array of property values.
55853 * @example
55854 *
55855 * function Foo() {
55856 * this.a = 1;
55857 * this.b = 2;
55858 * }
55859 *
55860 * Foo.prototype.c = 3;
55861 *
55862 * _.values(new Foo);
55863 * // => [1, 2] (iteration order is not guaranteed)
55864 *
55865 * _.values('hi');
55866 * // => ['h', 'i']
55867 */
55868 function values(object) {
55869 return object == null ? [] : baseValues(object, keys(object));
55870 }
55871
55872 /**
55873 * Creates an array of the own and inherited enumerable string keyed property
55874 * values of `object`.
55875 *
55876 * **Note:** Non-object values are coerced to objects.
55877 *
55878 * @static
55879 * @memberOf _
55880 * @since 3.0.0
55881 * @category Object
55882 * @param {Object} object The object to query.
55883 * @returns {Array} Returns the array of property values.
55884 * @example
55885 *
55886 * function Foo() {
55887 * this.a = 1;
55888 * this.b = 2;
55889 * }
55890 *
55891 * Foo.prototype.c = 3;
55892 *
55893 * _.valuesIn(new Foo);
55894 * // => [1, 2, 3] (iteration order is not guaranteed)
55895 */
55896 function valuesIn(object) {
55897 return object == null ? [] : baseValues(object, keysIn(object));
55898 }
55899
55900 /*------------------------------------------------------------------------*/
55901
55902 /**
55903 * Clamps `number` within the inclusive `lower` and `upper` bounds.
55904 *
55905 * @static
55906 * @memberOf _
55907 * @since 4.0.0
55908 * @category Number
55909 * @param {number} number The number to clamp.
55910 * @param {number} [lower] The lower bound.
55911 * @param {number} upper The upper bound.
55912 * @returns {number} Returns the clamped number.
55913 * @example
55914 *
55915 * _.clamp(-10, -5, 5);
55916 * // => -5
55917 *
55918 * _.clamp(10, -5, 5);
55919 * // => 5
55920 */
55921 function clamp(number, lower, upper) {
55922 if (upper === undefined) {
55923 upper = lower;
55924 lower = undefined;
55925 }
55926 if (upper !== undefined) {
55927 upper = toNumber(upper);
55928 upper = upper === upper ? upper : 0;
55929 }
55930 if (lower !== undefined) {
55931 lower = toNumber(lower);
55932 lower = lower === lower ? lower : 0;
55933 }
55934 return baseClamp(toNumber(number), lower, upper);
55935 }
55936
55937 /**
55938 * Checks if `n` is between `start` and up to, but not including, `end`. If
55939 * `end` is not specified, it's set to `start` with `start` then set to `0`.
55940 * If `start` is greater than `end` the params are swapped to support
55941 * negative ranges.
55942 *
55943 * @static
55944 * @memberOf _
55945 * @since 3.3.0
55946 * @category Number
55947 * @param {number} number The number to check.
55948 * @param {number} [start=0] The start of the range.
55949 * @param {number} end The end of the range.
55950 * @returns {boolean} Returns `true` if `number` is in the range, else `false`.
55951 * @see _.range, _.rangeRight
55952 * @example
55953 *
55954 * _.inRange(3, 2, 4);
55955 * // => true
55956 *
55957 * _.inRange(4, 8);
55958 * // => true
55959 *
55960 * _.inRange(4, 2);
55961 * // => false
55962 *
55963 * _.inRange(2, 2);
55964 * // => false
55965 *
55966 * _.inRange(1.2, 2);
55967 * // => true
55968 *
55969 * _.inRange(5.2, 4);
55970 * // => false
55971 *
55972 * _.inRange(-3, -2, -6);
55973 * // => true
55974 */
55975 function inRange(number, start, end) {
55976 start = toFinite(start);
55977 if (end === undefined) {
55978 end = start;
55979 start = 0;
55980 } else {
55981 end = toFinite(end);
55982 }
55983 number = toNumber(number);
55984 return baseInRange(number, start, end);
55985 }
55986
55987 /**
55988 * Produces a random number between the inclusive `lower` and `upper` bounds.
55989 * If only one argument is provided a number between `0` and the given number
55990 * is returned. If `floating` is `true`, or either `lower` or `upper` are
55991 * floats, a floating-point number is returned instead of an integer.
55992 *
55993 * **Note:** JavaScript follows the IEEE-754 standard for resolving
55994 * floating-point values which can produce unexpected results.
55995 *
55996 * @static
55997 * @memberOf _
55998 * @since 0.7.0
55999 * @category Number
56000 * @param {number} [lower=0] The lower bound.
56001 * @param {number} [upper=1] The upper bound.
56002 * @param {boolean} [floating] Specify returning a floating-point number.
56003 * @returns {number} Returns the random number.
56004 * @example
56005 *
56006 * _.random(0, 5);
56007 * // => an integer between 0 and 5
56008 *
56009 * _.random(5);
56010 * // => also an integer between 0 and 5
56011 *
56012 * _.random(5, true);
56013 * // => a floating-point number between 0 and 5
56014 *
56015 * _.random(1.2, 5.2);
56016 * // => a floating-point number between 1.2 and 5.2
56017 */
56018 function random(lower, upper, floating) {
56019 if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) {
56020 upper = floating = undefined;
56021 }
56022 if (floating === undefined) {
56023 if (typeof upper == 'boolean') {
56024 floating = upper;
56025 upper = undefined;
56026 }
56027 else if (typeof lower == 'boolean') {
56028 floating = lower;
56029 lower = undefined;
56030 }
56031 }
56032 if (lower === undefined && upper === undefined) {
56033 lower = 0;
56034 upper = 1;
56035 }
56036 else {
56037 lower = toFinite(lower);
56038 if (upper === undefined) {
56039 upper = lower;
56040 lower = 0;
56041 } else {
56042 upper = toFinite(upper);
56043 }
56044 }
56045 if (lower > upper) {
56046 var temp = lower;
56047 lower = upper;
56048 upper = temp;
56049 }
56050 if (floating || lower % 1 || upper % 1) {
56051 var rand = nativeRandom();
56052 return nativeMin(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper);
56053 }
56054 return baseRandom(lower, upper);
56055 }
56056
56057 /*------------------------------------------------------------------------*/
56058
56059 /**
56060 * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase).
56061 *
56062 * @static
56063 * @memberOf _
56064 * @since 3.0.0
56065 * @category String
56066 * @param {string} [string=''] The string to convert.
56067 * @returns {string} Returns the camel cased string.
56068 * @example
56069 *
56070 * _.camelCase('Foo Bar');
56071 * // => 'fooBar'
56072 *
56073 * _.camelCase('--foo-bar--');
56074 * // => 'fooBar'
56075 *
56076 * _.camelCase('__FOO_BAR__');
56077 * // => 'fooBar'
56078 */
56079 var camelCase = createCompounder(function(result, word, index) {
56080 word = word.toLowerCase();
56081 return result + (index ? capitalize(word) : word);
56082 });
56083
56084 /**
56085 * Converts the first character of `string` to upper case and the remaining
56086 * to lower case.
56087 *
56088 * @static
56089 * @memberOf _
56090 * @since 3.0.0
56091 * @category String
56092 * @param {string} [string=''] The string to capitalize.
56093 * @returns {string} Returns the capitalized string.
56094 * @example
56095 *
56096 * _.capitalize('FRED');
56097 * // => 'Fred'
56098 */
56099 function capitalize(string) {
56100 return upperFirst(toString(string).toLowerCase());
56101 }
56102
56103 /**
56104 * Deburrs `string` by converting
56105 * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table)
56106 * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A)
56107 * letters to basic Latin letters and removing
56108 * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks).
56109 *
56110 * @static
56111 * @memberOf _
56112 * @since 3.0.0
56113 * @category String
56114 * @param {string} [string=''] The string to deburr.
56115 * @returns {string} Returns the deburred string.
56116 * @example
56117 *
56118 * _.deburr('déjà vu');
56119 * // => 'deja vu'
56120 */
56121 function deburr(string) {
56122 string = toString(string);
56123 return string && string.replace(reLatin, deburrLetter).replace(reComboMark, '');
56124 }
56125
56126 /**
56127 * Checks if `string` ends with the given target string.
56128 *
56129 * @static
56130 * @memberOf _
56131 * @since 3.0.0
56132 * @category String
56133 * @param {string} [string=''] The string to inspect.
56134 * @param {string} [target] The string to search for.
56135 * @param {number} [position=string.length] The position to search up to.
56136 * @returns {boolean} Returns `true` if `string` ends with `target`,
56137 * else `false`.
56138 * @example
56139 *
56140 * _.endsWith('abc', 'c');
56141 * // => true
56142 *
56143 * _.endsWith('abc', 'b');
56144 * // => false
56145 *
56146 * _.endsWith('abc', 'b', 2);
56147 * // => true
56148 */
56149 function endsWith(string, target, position) {
56150 string = toString(string);
56151 target = baseToString(target);
56152
56153 var length = string.length;
56154 position = position === undefined
56155 ? length
56156 : baseClamp(toInteger(position), 0, length);
56157
56158 var end = position;
56159 position -= target.length;
56160 return position >= 0 && string.slice(position, end) == target;
56161 }
56162
56163 /**
56164 * Converts the characters "&", "<", ">", '"', and "'" in `string` to their
56165 * corresponding HTML entities.
56166 *
56167 * **Note:** No other characters are escaped. To escape additional
56168 * characters use a third-party library like [_he_](https://mths.be/he).
56169 *
56170 * Though the ">" character is escaped for symmetry, characters like
56171 * ">" and "/" don't need escaping in HTML and have no special meaning
56172 * unless they're part of a tag or unquoted attribute value. See
56173 * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands)
56174 * (under "semi-related fun fact") for more details.
56175 *
56176 * When working with HTML you should always
56177 * [quote attribute values](http://wonko.com/post/html-escaping) to reduce
56178 * XSS vectors.
56179 *
56180 * @static
56181 * @since 0.1.0
56182 * @memberOf _
56183 * @category String
56184 * @param {string} [string=''] The string to escape.
56185 * @returns {string} Returns the escaped string.
56186 * @example
56187 *
56188 * _.escape('fred, barney, & pebbles');
56189 * // => 'fred, barney, &amp; pebbles'
56190 */
56191 function escape(string) {
56192 string = toString(string);
56193 return (string && reHasUnescapedHtml.test(string))
56194 ? string.replace(reUnescapedHtml, escapeHtmlChar)
56195 : string;
56196 }
56197
56198 /**
56199 * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+",
56200 * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`.
56201 *
56202 * @static
56203 * @memberOf _
56204 * @since 3.0.0
56205 * @category String
56206 * @param {string} [string=''] The string to escape.
56207 * @returns {string} Returns the escaped string.
56208 * @example
56209 *
56210 * _.escapeRegExp('[lodash](https://lodash.com/)');
56211 * // => '\[lodash\]\(https://lodash\.com/\)'
56212 */
56213 function escapeRegExp(string) {
56214 string = toString(string);
56215 return (string && reHasRegExpChar.test(string))
56216 ? string.replace(reRegExpChar, '\\$&')
56217 : string;
56218 }
56219
56220 /**
56221 * Converts `string` to
56222 * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles).
56223 *
56224 * @static
56225 * @memberOf _
56226 * @since 3.0.0
56227 * @category String
56228 * @param {string} [string=''] The string to convert.
56229 * @returns {string} Returns the kebab cased string.
56230 * @example
56231 *
56232 * _.kebabCase('Foo Bar');
56233 * // => 'foo-bar'
56234 *
56235 * _.kebabCase('fooBar');
56236 * // => 'foo-bar'
56237 *
56238 * _.kebabCase('__FOO_BAR__');
56239 * // => 'foo-bar'
56240 */
56241 var kebabCase = createCompounder(function(result, word, index) {
56242 return result + (index ? '-' : '') + word.toLowerCase();
56243 });
56244
56245 /**
56246 * Converts `string`, as space separated words, to lower case.
56247 *
56248 * @static
56249 * @memberOf _
56250 * @since 4.0.0
56251 * @category String
56252 * @param {string} [string=''] The string to convert.
56253 * @returns {string} Returns the lower cased string.
56254 * @example
56255 *
56256 * _.lowerCase('--Foo-Bar--');
56257 * // => 'foo bar'
56258 *
56259 * _.lowerCase('fooBar');
56260 * // => 'foo bar'
56261 *
56262 * _.lowerCase('__FOO_BAR__');
56263 * // => 'foo bar'
56264 */
56265 var lowerCase = createCompounder(function(result, word, index) {
56266 return result + (index ? ' ' : '') + word.toLowerCase();
56267 });
56268
56269 /**
56270 * Converts the first character of `string` to lower case.
56271 *
56272 * @static
56273 * @memberOf _
56274 * @since 4.0.0
56275 * @category String
56276 * @param {string} [string=''] The string to convert.
56277 * @returns {string} Returns the converted string.
56278 * @example
56279 *
56280 * _.lowerFirst('Fred');
56281 * // => 'fred'
56282 *
56283 * _.lowerFirst('FRED');
56284 * // => 'fRED'
56285 */
56286 var lowerFirst = createCaseFirst('toLowerCase');
56287
56288 /**
56289 * Pads `string` on the left and right sides if it's shorter than `length`.
56290 * Padding characters are truncated if they can't be evenly divided by `length`.
56291 *
56292 * @static
56293 * @memberOf _
56294 * @since 3.0.0
56295 * @category String
56296 * @param {string} [string=''] The string to pad.
56297 * @param {number} [length=0] The padding length.
56298 * @param {string} [chars=' '] The string used as padding.
56299 * @returns {string} Returns the padded string.
56300 * @example
56301 *
56302 * _.pad('abc', 8);
56303 * // => ' abc '
56304 *
56305 * _.pad('abc', 8, '_-');
56306 * // => '_-abc_-_'
56307 *
56308 * _.pad('abc', 3);
56309 * // => 'abc'
56310 */
56311 function pad(string, length, chars) {
56312 string = toString(string);
56313 length = toInteger(length);
56314
56315 var strLength = length ? stringSize(string) : 0;
56316 if (!length || strLength >= length) {
56317 return string;
56318 }
56319 var mid = (length - strLength) / 2;
56320 return (
56321 createPadding(nativeFloor(mid), chars) +
56322 string +
56323 createPadding(nativeCeil(mid), chars)
56324 );
56325 }
56326
56327 /**
56328 * Pads `string` on the right side if it's shorter than `length`. Padding
56329 * characters are truncated if they exceed `length`.
56330 *
56331 * @static
56332 * @memberOf _
56333 * @since 4.0.0
56334 * @category String
56335 * @param {string} [string=''] The string to pad.
56336 * @param {number} [length=0] The padding length.
56337 * @param {string} [chars=' '] The string used as padding.
56338 * @returns {string} Returns the padded string.
56339 * @example
56340 *
56341 * _.padEnd('abc', 6);
56342 * // => 'abc '
56343 *
56344 * _.padEnd('abc', 6, '_-');
56345 * // => 'abc_-_'
56346 *
56347 * _.padEnd('abc', 3);
56348 * // => 'abc'
56349 */
56350 function padEnd(string, length, chars) {
56351 string = toString(string);
56352 length = toInteger(length);
56353
56354 var strLength = length ? stringSize(string) : 0;
56355 return (length && strLength < length)
56356 ? (string + createPadding(length - strLength, chars))
56357 : string;
56358 }
56359
56360 /**
56361 * Pads `string` on the left side if it's shorter than `length`. Padding
56362 * characters are truncated if they exceed `length`.
56363 *
56364 * @static
56365 * @memberOf _
56366 * @since 4.0.0
56367 * @category String
56368 * @param {string} [string=''] The string to pad.
56369 * @param {number} [length=0] The padding length.
56370 * @param {string} [chars=' '] The string used as padding.
56371 * @returns {string} Returns the padded string.
56372 * @example
56373 *
56374 * _.padStart('abc', 6);
56375 * // => ' abc'
56376 *
56377 * _.padStart('abc', 6, '_-');
56378 * // => '_-_abc'
56379 *
56380 * _.padStart('abc', 3);
56381 * // => 'abc'
56382 */
56383 function padStart(string, length, chars) {
56384 string = toString(string);
56385 length = toInteger(length);
56386
56387 var strLength = length ? stringSize(string) : 0;
56388 return (length && strLength < length)
56389 ? (createPadding(length - strLength, chars) + string)
56390 : string;
56391 }
56392
56393 /**
56394 * Converts `string` to an integer of the specified radix. If `radix` is
56395 * `undefined` or `0`, a `radix` of `10` is used unless `value` is a
56396 * hexadecimal, in which case a `radix` of `16` is used.
56397 *
56398 * **Note:** This method aligns with the
56399 * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`.
56400 *
56401 * @static
56402 * @memberOf _
56403 * @since 1.1.0
56404 * @category String
56405 * @param {string} string The string to convert.
56406 * @param {number} [radix=10] The radix to interpret `value` by.
56407 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
56408 * @returns {number} Returns the converted integer.
56409 * @example
56410 *
56411 * _.parseInt('08');
56412 * // => 8
56413 *
56414 * _.map(['6', '08', '10'], _.parseInt);
56415 * // => [6, 8, 10]
56416 */
56417 function parseInt(string, radix, guard) {
56418 if (guard || radix == null) {
56419 radix = 0;
56420 } else if (radix) {
56421 radix = +radix;
56422 }
56423 return nativeParseInt(toString(string).replace(reTrimStart, ''), radix || 0);
56424 }
56425
56426 /**
56427 * Repeats the given string `n` times.
56428 *
56429 * @static
56430 * @memberOf _
56431 * @since 3.0.0
56432 * @category String
56433 * @param {string} [string=''] The string to repeat.
56434 * @param {number} [n=1] The number of times to repeat the string.
56435 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
56436 * @returns {string} Returns the repeated string.
56437 * @example
56438 *
56439 * _.repeat('*', 3);
56440 * // => '***'
56441 *
56442 * _.repeat('abc', 2);
56443 * // => 'abcabc'
56444 *
56445 * _.repeat('abc', 0);
56446 * // => ''
56447 */
56448 function repeat(string, n, guard) {
56449 if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) {
56450 n = 1;
56451 } else {
56452 n = toInteger(n);
56453 }
56454 return baseRepeat(toString(string), n);
56455 }
56456
56457 /**
56458 * Replaces matches for `pattern` in `string` with `replacement`.
56459 *
56460 * **Note:** This method is based on
56461 * [`String#replace`](https://mdn.io/String/replace).
56462 *
56463 * @static
56464 * @memberOf _
56465 * @since 4.0.0
56466 * @category String
56467 * @param {string} [string=''] The string to modify.
56468 * @param {RegExp|string} pattern The pattern to replace.
56469 * @param {Function|string} replacement The match replacement.
56470 * @returns {string} Returns the modified string.
56471 * @example
56472 *
56473 * _.replace('Hi Fred', 'Fred', 'Barney');
56474 * // => 'Hi Barney'
56475 */
56476 function replace() {
56477 var args = arguments,
56478 string = toString(args[0]);
56479
56480 return args.length < 3 ? string : string.replace(args[1], args[2]);
56481 }
56482
56483 /**
56484 * Converts `string` to
56485 * [snake case](https://en.wikipedia.org/wiki/Snake_case).
56486 *
56487 * @static
56488 * @memberOf _
56489 * @since 3.0.0
56490 * @category String
56491 * @param {string} [string=''] The string to convert.
56492 * @returns {string} Returns the snake cased string.
56493 * @example
56494 *
56495 * _.snakeCase('Foo Bar');
56496 * // => 'foo_bar'
56497 *
56498 * _.snakeCase('fooBar');
56499 * // => 'foo_bar'
56500 *
56501 * _.snakeCase('--FOO-BAR--');
56502 * // => 'foo_bar'
56503 */
56504 var snakeCase = createCompounder(function(result, word, index) {
56505 return result + (index ? '_' : '') + word.toLowerCase();
56506 });
56507
56508 /**
56509 * Splits `string` by `separator`.
56510 *
56511 * **Note:** This method is based on
56512 * [`String#split`](https://mdn.io/String/split).
56513 *
56514 * @static
56515 * @memberOf _
56516 * @since 4.0.0
56517 * @category String
56518 * @param {string} [string=''] The string to split.
56519 * @param {RegExp|string} separator The separator pattern to split by.
56520 * @param {number} [limit] The length to truncate results to.
56521 * @returns {Array} Returns the string segments.
56522 * @example
56523 *
56524 * _.split('a-b-c', '-', 2);
56525 * // => ['a', 'b']
56526 */
56527 function split(string, separator, limit) {
56528 if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) {
56529 separator = limit = undefined;
56530 }
56531 limit = limit === undefined ? MAX_ARRAY_LENGTH : limit >>> 0;
56532 if (!limit) {
56533 return [];
56534 }
56535 string = toString(string);
56536 if (string && (
56537 typeof separator == 'string' ||
56538 (separator != null && !isRegExp(separator))
56539 )) {
56540 separator = baseToString(separator);
56541 if (!separator && hasUnicode(string)) {
56542 return castSlice(stringToArray(string), 0, limit);
56543 }
56544 }
56545 return string.split(separator, limit);
56546 }
56547
56548 /**
56549 * Converts `string` to
56550 * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage).
56551 *
56552 * @static
56553 * @memberOf _
56554 * @since 3.1.0
56555 * @category String
56556 * @param {string} [string=''] The string to convert.
56557 * @returns {string} Returns the start cased string.
56558 * @example
56559 *
56560 * _.startCase('--foo-bar--');
56561 * // => 'Foo Bar'
56562 *
56563 * _.startCase('fooBar');
56564 * // => 'Foo Bar'
56565 *
56566 * _.startCase('__FOO_BAR__');
56567 * // => 'FOO BAR'
56568 */
56569 var startCase = createCompounder(function(result, word, index) {
56570 return result + (index ? ' ' : '') + upperFirst(word);
56571 });
56572
56573 /**
56574 * Checks if `string` starts with the given target string.
56575 *
56576 * @static
56577 * @memberOf _
56578 * @since 3.0.0
56579 * @category String
56580 * @param {string} [string=''] The string to inspect.
56581 * @param {string} [target] The string to search for.
56582 * @param {number} [position=0] The position to search from.
56583 * @returns {boolean} Returns `true` if `string` starts with `target`,
56584 * else `false`.
56585 * @example
56586 *
56587 * _.startsWith('abc', 'a');
56588 * // => true
56589 *
56590 * _.startsWith('abc', 'b');
56591 * // => false
56592 *
56593 * _.startsWith('abc', 'b', 1);
56594 * // => true
56595 */
56596 function startsWith(string, target, position) {
56597 string = toString(string);
56598 position = position == null
56599 ? 0
56600 : baseClamp(toInteger(position), 0, string.length);
56601
56602 target = baseToString(target);
56603 return string.slice(position, position + target.length) == target;
56604 }
56605
56606 /**
56607 * Creates a compiled template function that can interpolate data properties
56608 * in "interpolate" delimiters, HTML-escape interpolated data properties in
56609 * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data
56610 * properties may be accessed as free variables in the template. If a setting
56611 * object is given, it takes precedence over `_.templateSettings` values.
56612 *
56613 * **Note:** In the development build `_.template` utilizes
56614 * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl)
56615 * for easier debugging.
56616 *
56617 * For more information on precompiling templates see
56618 * [lodash's custom builds documentation](https://lodash.com/custom-builds).
56619 *
56620 * For more information on Chrome extension sandboxes see
56621 * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval).
56622 *
56623 * @static
56624 * @since 0.1.0
56625 * @memberOf _
56626 * @category String
56627 * @param {string} [string=''] The template string.
56628 * @param {Object} [options={}] The options object.
56629 * @param {RegExp} [options.escape=_.templateSettings.escape]
56630 * The HTML "escape" delimiter.
56631 * @param {RegExp} [options.evaluate=_.templateSettings.evaluate]
56632 * The "evaluate" delimiter.
56633 * @param {Object} [options.imports=_.templateSettings.imports]
56634 * An object to import into the template as free variables.
56635 * @param {RegExp} [options.interpolate=_.templateSettings.interpolate]
56636 * The "interpolate" delimiter.
56637 * @param {string} [options.sourceURL='lodash.templateSources[n]']
56638 * The sourceURL of the compiled template.
56639 * @param {string} [options.variable='obj']
56640 * The data object variable name.
56641 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
56642 * @returns {Function} Returns the compiled template function.
56643 * @example
56644 *
56645 * // Use the "interpolate" delimiter to create a compiled template.
56646 * var compiled = _.template('hello <%= user %>!');
56647 * compiled({ 'user': 'fred' });
56648 * // => 'hello fred!'
56649 *
56650 * // Use the HTML "escape" delimiter to escape data property values.
56651 * var compiled = _.template('<b><%- value %></b>');
56652 * compiled({ 'value': '<script>' });
56653 * // => '<b>&lt;script&gt;</b>'
56654 *
56655 * // Use the "evaluate" delimiter to execute JavaScript and generate HTML.
56656 * var compiled = _.template('<% _.forEach(users, function(user) { %><li><%- user %></li><% }); %>');
56657 * compiled({ 'users': ['fred', 'barney'] });
56658 * // => '<li>fred</li><li>barney</li>'
56659 *
56660 * // Use the internal `print` function in "evaluate" delimiters.
56661 * var compiled = _.template('<% print("hello " + user); %>!');
56662 * compiled({ 'user': 'barney' });
56663 * // => 'hello barney!'
56664 *
56665 * // Use the ES template literal delimiter as an "interpolate" delimiter.
56666 * // Disable support by replacing the "interpolate" delimiter.
56667 * var compiled = _.template('hello ${ user }!');
56668 * compiled({ 'user': 'pebbles' });
56669 * // => 'hello pebbles!'
56670 *
56671 * // Use backslashes to treat delimiters as plain text.
56672 * var compiled = _.template('<%= "\\<%- value %\\>" %>');
56673 * compiled({ 'value': 'ignored' });
56674 * // => '<%- value %>'
56675 *
56676 * // Use the `imports` option to import `jQuery` as `jq`.
56677 * var text = '<% jq.each(users, function(user) { %><li><%- user %></li><% }); %>';
56678 * var compiled = _.template(text, { 'imports': { 'jq': jQuery } });
56679 * compiled({ 'users': ['fred', 'barney'] });
56680 * // => '<li>fred</li><li>barney</li>'
56681 *
56682 * // Use the `sourceURL` option to specify a custom sourceURL for the template.
56683 * var compiled = _.template('hello <%= user %>!', { 'sourceURL': '/basic/greeting.jst' });
56684 * compiled(data);
56685 * // => Find the source of "greeting.jst" under the Sources tab or Resources panel of the web inspector.
56686 *
56687 * // Use the `variable` option to ensure a with-statement isn't used in the compiled template.
56688 * var compiled = _.template('hi <%= data.user %>!', { 'variable': 'data' });
56689 * compiled.source;
56690 * // => function(data) {
56691 * // var __t, __p = '';
56692 * // __p += 'hi ' + ((__t = ( data.user )) == null ? '' : __t) + '!';
56693 * // return __p;
56694 * // }
56695 *
56696 * // Use custom template delimiters.
56697 * _.templateSettings.interpolate = /{{([\s\S]+?)}}/g;
56698 * var compiled = _.template('hello {{ user }}!');
56699 * compiled({ 'user': 'mustache' });
56700 * // => 'hello mustache!'
56701 *
56702 * // Use the `source` property to inline compiled templates for meaningful
56703 * // line numbers in error messages and stack traces.
56704 * fs.writeFileSync(path.join(process.cwd(), 'jst.js'), '\
56705 * var JST = {\
56706 * "main": ' + _.template(mainText).source + '\
56707 * };\
56708 * ');
56709 */
56710 function template(string, options, guard) {
56711 // Based on John Resig's `tmpl` implementation
56712 // (http://ejohn.org/blog/javascript-micro-templating/)
56713 // and Laura Doktorova's doT.js (https://github.com/olado/doT).
56714 var settings = lodash.templateSettings;
56715
56716 if (guard && isIterateeCall(string, options, guard)) {
56717 options = undefined;
56718 }
56719 string = toString(string);
56720 options = assignInWith({}, options, settings, customDefaultsAssignIn);
56721
56722 var imports = assignInWith({}, options.imports, settings.imports, customDefaultsAssignIn),
56723 importsKeys = keys(imports),
56724 importsValues = baseValues(imports, importsKeys);
56725
56726 var isEscaping,
56727 isEvaluating,
56728 index = 0,
56729 interpolate = options.interpolate || reNoMatch,
56730 source = "__p += '";
56731
56732 // Compile the regexp to match each delimiter.
56733 var reDelimiters = RegExp(
56734 (options.escape || reNoMatch).source + '|' +
56735 interpolate.source + '|' +
56736 (interpolate === reInterpolate ? reEsTemplate : reNoMatch).source + '|' +
56737 (options.evaluate || reNoMatch).source + '|$'
56738 , 'g');
56739
56740 // Use a sourceURL for easier debugging.
56741 // The sourceURL gets injected into the source that's eval-ed, so be careful
56742 // to normalize all kinds of whitespace, so e.g. newlines (and unicode versions of it) can't sneak in
56743 // and escape the comment, thus injecting code that gets evaled.
56744 var sourceURL = '//# sourceURL=' +
56745 (hasOwnProperty.call(options, 'sourceURL')
56746 ? (options.sourceURL + '').replace(/\s/g, ' ')
56747 : ('lodash.templateSources[' + (++templateCounter) + ']')
56748 ) + '\n';
56749
56750 string.replace(reDelimiters, function(match, escapeValue, interpolateValue, esTemplateValue, evaluateValue, offset) {
56751 interpolateValue || (interpolateValue = esTemplateValue);
56752
56753 // Escape characters that can't be included in string literals.
56754 source += string.slice(index, offset).replace(reUnescapedString, escapeStringChar);
56755
56756 // Replace delimiters with snippets.
56757 if (escapeValue) {
56758 isEscaping = true;
56759 source += "' +\n__e(" + escapeValue + ") +\n'";
56760 }
56761 if (evaluateValue) {
56762 isEvaluating = true;
56763 source += "';\n" + evaluateValue + ";\n__p += '";
56764 }
56765 if (interpolateValue) {
56766 source += "' +\n((__t = (" + interpolateValue + ")) == null ? '' : __t) +\n'";
56767 }
56768 index = offset + match.length;
56769
56770 // The JS engine embedded in Adobe products needs `match` returned in
56771 // order to produce the correct `offset` value.
56772 return match;
56773 });
56774
56775 source += "';\n";
56776
56777 // If `variable` is not specified wrap a with-statement around the generated
56778 // code to add the data object to the top of the scope chain.
56779 var variable = hasOwnProperty.call(options, 'variable') && options.variable;
56780 if (!variable) {
56781 source = 'with (obj) {\n' + source + '\n}\n';
56782 }
56783 // Cleanup code by stripping empty strings.
56784 source = (isEvaluating ? source.replace(reEmptyStringLeading, '') : source)
56785 .replace(reEmptyStringMiddle, '$1')
56786 .replace(reEmptyStringTrailing, '$1;');
56787
56788 // Frame code as the function body.
56789 source = 'function(' + (variable || 'obj') + ') {\n' +
56790 (variable
56791 ? ''
56792 : 'obj || (obj = {});\n'
56793 ) +
56794 "var __t, __p = ''" +
56795 (isEscaping
56796 ? ', __e = _.escape'
56797 : ''
56798 ) +
56799 (isEvaluating
56800 ? ', __j = Array.prototype.join;\n' +
56801 "function print() { __p += __j.call(arguments, '') }\n"
56802 : ';\n'
56803 ) +
56804 source +
56805 'return __p\n}';
56806
56807 var result = attempt(function() {
56808 return Function(importsKeys, sourceURL + 'return ' + source)
56809 .apply(undefined, importsValues);
56810 });
56811
56812 // Provide the compiled function's source by its `toString` method or
56813 // the `source` property as a convenience for inlining compiled templates.
56814 result.source = source;
56815 if (isError(result)) {
56816 throw result;
56817 }
56818 return result;
56819 }
56820
56821 /**
56822 * Converts `string`, as a whole, to lower case just like
56823 * [String#toLowerCase](https://mdn.io/toLowerCase).
56824 *
56825 * @static
56826 * @memberOf _
56827 * @since 4.0.0
56828 * @category String
56829 * @param {string} [string=''] The string to convert.
56830 * @returns {string} Returns the lower cased string.
56831 * @example
56832 *
56833 * _.toLower('--Foo-Bar--');
56834 * // => '--foo-bar--'
56835 *
56836 * _.toLower('fooBar');
56837 * // => 'foobar'
56838 *
56839 * _.toLower('__FOO_BAR__');
56840 * // => '__foo_bar__'
56841 */
56842 function toLower(value) {
56843 return toString(value).toLowerCase();
56844 }
56845
56846 /**
56847 * Converts `string`, as a whole, to upper case just like
56848 * [String#toUpperCase](https://mdn.io/toUpperCase).
56849 *
56850 * @static
56851 * @memberOf _
56852 * @since 4.0.0
56853 * @category String
56854 * @param {string} [string=''] The string to convert.
56855 * @returns {string} Returns the upper cased string.
56856 * @example
56857 *
56858 * _.toUpper('--foo-bar--');
56859 * // => '--FOO-BAR--'
56860 *
56861 * _.toUpper('fooBar');
56862 * // => 'FOOBAR'
56863 *
56864 * _.toUpper('__foo_bar__');
56865 * // => '__FOO_BAR__'
56866 */
56867 function toUpper(value) {
56868 return toString(value).toUpperCase();
56869 }
56870
56871 /**
56872 * Removes leading and trailing whitespace or specified characters from `string`.
56873 *
56874 * @static
56875 * @memberOf _
56876 * @since 3.0.0
56877 * @category String
56878 * @param {string} [string=''] The string to trim.
56879 * @param {string} [chars=whitespace] The characters to trim.
56880 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
56881 * @returns {string} Returns the trimmed string.
56882 * @example
56883 *
56884 * _.trim(' abc ');
56885 * // => 'abc'
56886 *
56887 * _.trim('-_-abc-_-', '_-');
56888 * // => 'abc'
56889 *
56890 * _.map([' foo ', ' bar '], _.trim);
56891 * // => ['foo', 'bar']
56892 */
56893 function trim(string, chars, guard) {
56894 string = toString(string);
56895 if (string && (guard || chars === undefined)) {
56896 return string.replace(reTrim, '');
56897 }
56898 if (!string || !(chars = baseToString(chars))) {
56899 return string;
56900 }
56901 var strSymbols = stringToArray(string),
56902 chrSymbols = stringToArray(chars),
56903 start = charsStartIndex(strSymbols, chrSymbols),
56904 end = charsEndIndex(strSymbols, chrSymbols) + 1;
56905
56906 return castSlice(strSymbols, start, end).join('');
56907 }
56908
56909 /**
56910 * Removes trailing whitespace or specified characters from `string`.
56911 *
56912 * @static
56913 * @memberOf _
56914 * @since 4.0.0
56915 * @category String
56916 * @param {string} [string=''] The string to trim.
56917 * @param {string} [chars=whitespace] The characters to trim.
56918 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
56919 * @returns {string} Returns the trimmed string.
56920 * @example
56921 *
56922 * _.trimEnd(' abc ');
56923 * // => ' abc'
56924 *
56925 * _.trimEnd('-_-abc-_-', '_-');
56926 * // => '-_-abc'
56927 */
56928 function trimEnd(string, chars, guard) {
56929 string = toString(string);
56930 if (string && (guard || chars === undefined)) {
56931 return string.replace(reTrimEnd, '');
56932 }
56933 if (!string || !(chars = baseToString(chars))) {
56934 return string;
56935 }
56936 var strSymbols = stringToArray(string),
56937 end = charsEndIndex(strSymbols, stringToArray(chars)) + 1;
56938
56939 return castSlice(strSymbols, 0, end).join('');
56940 }
56941
56942 /**
56943 * Removes leading whitespace or specified characters from `string`.
56944 *
56945 * @static
56946 * @memberOf _
56947 * @since 4.0.0
56948 * @category String
56949 * @param {string} [string=''] The string to trim.
56950 * @param {string} [chars=whitespace] The characters to trim.
56951 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
56952 * @returns {string} Returns the trimmed string.
56953 * @example
56954 *
56955 * _.trimStart(' abc ');
56956 * // => 'abc '
56957 *
56958 * _.trimStart('-_-abc-_-', '_-');
56959 * // => 'abc-_-'
56960 */
56961 function trimStart(string, chars, guard) {
56962 string = toString(string);
56963 if (string && (guard || chars === undefined)) {
56964 return string.replace(reTrimStart, '');
56965 }
56966 if (!string || !(chars = baseToString(chars))) {
56967 return string;
56968 }
56969 var strSymbols = stringToArray(string),
56970 start = charsStartIndex(strSymbols, stringToArray(chars));
56971
56972 return castSlice(strSymbols, start).join('');
56973 }
56974
56975 /**
56976 * Truncates `string` if it's longer than the given maximum string length.
56977 * The last characters of the truncated string are replaced with the omission
56978 * string which defaults to "...".
56979 *
56980 * @static
56981 * @memberOf _
56982 * @since 4.0.0
56983 * @category String
56984 * @param {string} [string=''] The string to truncate.
56985 * @param {Object} [options={}] The options object.
56986 * @param {number} [options.length=30] The maximum string length.
56987 * @param {string} [options.omission='...'] The string to indicate text is omitted.
56988 * @param {RegExp|string} [options.separator] The separator pattern to truncate to.
56989 * @returns {string} Returns the truncated string.
56990 * @example
56991 *
56992 * _.truncate('hi-diddly-ho there, neighborino');
56993 * // => 'hi-diddly-ho there, neighbo...'
56994 *
56995 * _.truncate('hi-diddly-ho there, neighborino', {
56996 * 'length': 24,
56997 * 'separator': ' '
56998 * });
56999 * // => 'hi-diddly-ho there,...'
57000 *
57001 * _.truncate('hi-diddly-ho there, neighborino', {
57002 * 'length': 24,
57003 * 'separator': /,? +/
57004 * });
57005 * // => 'hi-diddly-ho there...'
57006 *
57007 * _.truncate('hi-diddly-ho there, neighborino', {
57008 * 'omission': ' [...]'
57009 * });
57010 * // => 'hi-diddly-ho there, neig [...]'
57011 */
57012 function truncate(string, options) {
57013 var length = DEFAULT_TRUNC_LENGTH,
57014 omission = DEFAULT_TRUNC_OMISSION;
57015
57016 if (isObject(options)) {
57017 var separator = 'separator' in options ? options.separator : separator;
57018 length = 'length' in options ? toInteger(options.length) : length;
57019 omission = 'omission' in options ? baseToString(options.omission) : omission;
57020 }
57021 string = toString(string);
57022
57023 var strLength = string.length;
57024 if (hasUnicode(string)) {
57025 var strSymbols = stringToArray(string);
57026 strLength = strSymbols.length;
57027 }
57028 if (length >= strLength) {
57029 return string;
57030 }
57031 var end = length - stringSize(omission);
57032 if (end < 1) {
57033 return omission;
57034 }
57035 var result = strSymbols
57036 ? castSlice(strSymbols, 0, end).join('')
57037 : string.slice(0, end);
57038
57039 if (separator === undefined) {
57040 return result + omission;
57041 }
57042 if (strSymbols) {
57043 end += (result.length - end);
57044 }
57045 if (isRegExp(separator)) {
57046 if (string.slice(end).search(separator)) {
57047 var match,
57048 substring = result;
57049
57050 if (!separator.global) {
57051 separator = RegExp(separator.source, toString(reFlags.exec(separator)) + 'g');
57052 }
57053 separator.lastIndex = 0;
57054 while ((match = separator.exec(substring))) {
57055 var newEnd = match.index;
57056 }
57057 result = result.slice(0, newEnd === undefined ? end : newEnd);
57058 }
57059 } else if (string.indexOf(baseToString(separator), end) != end) {
57060 var index = result.lastIndexOf(separator);
57061 if (index > -1) {
57062 result = result.slice(0, index);
57063 }
57064 }
57065 return result + omission;
57066 }
57067
57068 /**
57069 * The inverse of `_.escape`; this method converts the HTML entities
57070 * `&amp;`, `&lt;`, `&gt;`, `&quot;`, and `&#39;` in `string` to
57071 * their corresponding characters.
57072 *
57073 * **Note:** No other HTML entities are unescaped. To unescape additional
57074 * HTML entities use a third-party library like [_he_](https://mths.be/he).
57075 *
57076 * @static
57077 * @memberOf _
57078 * @since 0.6.0
57079 * @category String
57080 * @param {string} [string=''] The string to unescape.
57081 * @returns {string} Returns the unescaped string.
57082 * @example
57083 *
57084 * _.unescape('fred, barney, &amp; pebbles');
57085 * // => 'fred, barney, & pebbles'
57086 */
57087 function unescape(string) {
57088 string = toString(string);
57089 return (string && reHasEscapedHtml.test(string))
57090 ? string.replace(reEscapedHtml, unescapeHtmlChar)
57091 : string;
57092 }
57093
57094 /**
57095 * Converts `string`, as space separated words, to upper case.
57096 *
57097 * @static
57098 * @memberOf _
57099 * @since 4.0.0
57100 * @category String
57101 * @param {string} [string=''] The string to convert.
57102 * @returns {string} Returns the upper cased string.
57103 * @example
57104 *
57105 * _.upperCase('--foo-bar');
57106 * // => 'FOO BAR'
57107 *
57108 * _.upperCase('fooBar');
57109 * // => 'FOO BAR'
57110 *
57111 * _.upperCase('__foo_bar__');
57112 * // => 'FOO BAR'
57113 */
57114 var upperCase = createCompounder(function(result, word, index) {
57115 return result + (index ? ' ' : '') + word.toUpperCase();
57116 });
57117
57118 /**
57119 * Converts the first character of `string` to upper case.
57120 *
57121 * @static
57122 * @memberOf _
57123 * @since 4.0.0
57124 * @category String
57125 * @param {string} [string=''] The string to convert.
57126 * @returns {string} Returns the converted string.
57127 * @example
57128 *
57129 * _.upperFirst('fred');
57130 * // => 'Fred'
57131 *
57132 * _.upperFirst('FRED');
57133 * // => 'FRED'
57134 */
57135 var upperFirst = createCaseFirst('toUpperCase');
57136
57137 /**
57138 * Splits `string` into an array of its words.
57139 *
57140 * @static
57141 * @memberOf _
57142 * @since 3.0.0
57143 * @category String
57144 * @param {string} [string=''] The string to inspect.
57145 * @param {RegExp|string} [pattern] The pattern to match words.
57146 * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`.
57147 * @returns {Array} Returns the words of `string`.
57148 * @example
57149 *
57150 * _.words('fred, barney, & pebbles');
57151 * // => ['fred', 'barney', 'pebbles']
57152 *
57153 * _.words('fred, barney, & pebbles', /[^, ]+/g);
57154 * // => ['fred', 'barney', '&', 'pebbles']
57155 */
57156 function words(string, pattern, guard) {
57157 string = toString(string);
57158 pattern = guard ? undefined : pattern;
57159
57160 if (pattern === undefined) {
57161 return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string);
57162 }
57163 return string.match(pattern) || [];
57164 }
57165
57166 /*------------------------------------------------------------------------*/
57167
57168 /**
57169 * Attempts to invoke `func`, returning either the result or the caught error
57170 * object. Any additional arguments are provided to `func` when it's invoked.
57171 *
57172 * @static
57173 * @memberOf _
57174 * @since 3.0.0
57175 * @category Util
57176 * @param {Function} func The function to attempt.
57177 * @param {...*} [args] The arguments to invoke `func` with.
57178 * @returns {*} Returns the `func` result or error object.
57179 * @example
57180 *
57181 * // Avoid throwing errors for invalid selectors.
57182 * var elements = _.attempt(function(selector) {
57183 * return document.querySelectorAll(selector);
57184 * }, '>_>');
57185 *
57186 * if (_.isError(elements)) {
57187 * elements = [];
57188 * }
57189 */
57190 var attempt = baseRest(function(func, args) {
57191 try {
57192 return apply(func, undefined, args);
57193 } catch (e) {
57194 return isError(e) ? e : new Error(e);
57195 }
57196 });
57197
57198 /**
57199 * Binds methods of an object to the object itself, overwriting the existing
57200 * method.
57201 *
57202 * **Note:** This method doesn't set the "length" property of bound functions.
57203 *
57204 * @static
57205 * @since 0.1.0
57206 * @memberOf _
57207 * @category Util
57208 * @param {Object} object The object to bind and assign the bound methods to.
57209 * @param {...(string|string[])} methodNames The object method names to bind.
57210 * @returns {Object} Returns `object`.
57211 * @example
57212 *
57213 * var view = {
57214 * 'label': 'docs',
57215 * 'click': function() {
57216 * console.log('clicked ' + this.label);
57217 * }
57218 * };
57219 *
57220 * _.bindAll(view, ['click']);
57221 * jQuery(element).on('click', view.click);
57222 * // => Logs 'clicked docs' when clicked.
57223 */
57224 var bindAll = flatRest(function(object, methodNames) {
57225 arrayEach(methodNames, function(key) {
57226 key = toKey(key);
57227 baseAssignValue(object, key, bind(object[key], object));
57228 });
57229 return object;
57230 });
57231
57232 /**
57233 * Creates a function that iterates over `pairs` and invokes the corresponding
57234 * function of the first predicate to return truthy. The predicate-function
57235 * pairs are invoked with the `this` binding and arguments of the created
57236 * function.
57237 *
57238 * @static
57239 * @memberOf _
57240 * @since 4.0.0
57241 * @category Util
57242 * @param {Array} pairs The predicate-function pairs.
57243 * @returns {Function} Returns the new composite function.
57244 * @example
57245 *
57246 * var func = _.cond([
57247 * [_.matches({ 'a': 1 }), _.constant('matches A')],
57248 * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')],
57249 * [_.stubTrue, _.constant('no match')]
57250 * ]);
57251 *
57252 * func({ 'a': 1, 'b': 2 });
57253 * // => 'matches A'
57254 *
57255 * func({ 'a': 0, 'b': 1 });
57256 * // => 'matches B'
57257 *
57258 * func({ 'a': '1', 'b': '2' });
57259 * // => 'no match'
57260 */
57261 function cond(pairs) {
57262 var length = pairs == null ? 0 : pairs.length,
57263 toIteratee = getIteratee();
57264
57265 pairs = !length ? [] : arrayMap(pairs, function(pair) {
57266 if (typeof pair[1] != 'function') {
57267 throw new TypeError(FUNC_ERROR_TEXT);
57268 }
57269 return [toIteratee(pair[0]), pair[1]];
57270 });
57271
57272 return baseRest(function(args) {
57273 var index = -1;
57274 while (++index < length) {
57275 var pair = pairs[index];
57276 if (apply(pair[0], this, args)) {
57277 return apply(pair[1], this, args);
57278 }
57279 }
57280 });
57281 }
57282
57283 /**
57284 * Creates a function that invokes the predicate properties of `source` with
57285 * the corresponding property values of a given object, returning `true` if
57286 * all predicates return truthy, else `false`.
57287 *
57288 * **Note:** The created function is equivalent to `_.conformsTo` with
57289 * `source` partially applied.
57290 *
57291 * @static
57292 * @memberOf _
57293 * @since 4.0.0
57294 * @category Util
57295 * @param {Object} source The object of property predicates to conform to.
57296 * @returns {Function} Returns the new spec function.
57297 * @example
57298 *
57299 * var objects = [
57300 * { 'a': 2, 'b': 1 },
57301 * { 'a': 1, 'b': 2 }
57302 * ];
57303 *
57304 * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } }));
57305 * // => [{ 'a': 1, 'b': 2 }]
57306 */
57307 function conforms(source) {
57308 return baseConforms(baseClone(source, CLONE_DEEP_FLAG));
57309 }
57310
57311 /**
57312 * Creates a function that returns `value`.
57313 *
57314 * @static
57315 * @memberOf _
57316 * @since 2.4.0
57317 * @category Util
57318 * @param {*} value The value to return from the new function.
57319 * @returns {Function} Returns the new constant function.
57320 * @example
57321 *
57322 * var objects = _.times(2, _.constant({ 'a': 1 }));
57323 *
57324 * console.log(objects);
57325 * // => [{ 'a': 1 }, { 'a': 1 }]
57326 *
57327 * console.log(objects[0] === objects[1]);
57328 * // => true
57329 */
57330 function constant(value) {
57331 return function() {
57332 return value;
57333 };
57334 }
57335
57336 /**
57337 * Checks `value` to determine whether a default value should be returned in
57338 * its place. The `defaultValue` is returned if `value` is `NaN`, `null`,
57339 * or `undefined`.
57340 *
57341 * @static
57342 * @memberOf _
57343 * @since 4.14.0
57344 * @category Util
57345 * @param {*} value The value to check.
57346 * @param {*} defaultValue The default value.
57347 * @returns {*} Returns the resolved value.
57348 * @example
57349 *
57350 * _.defaultTo(1, 10);
57351 * // => 1
57352 *
57353 * _.defaultTo(undefined, 10);
57354 * // => 10
57355 */
57356 function defaultTo(value, defaultValue) {
57357 return (value == null || value !== value) ? defaultValue : value;
57358 }
57359
57360 /**
57361 * Creates a function that returns the result of invoking the given functions
57362 * with the `this` binding of the created function, where each successive
57363 * invocation is supplied the return value of the previous.
57364 *
57365 * @static
57366 * @memberOf _
57367 * @since 3.0.0
57368 * @category Util
57369 * @param {...(Function|Function[])} [funcs] The functions to invoke.
57370 * @returns {Function} Returns the new composite function.
57371 * @see _.flowRight
57372 * @example
57373 *
57374 * function square(n) {
57375 * return n * n;
57376 * }
57377 *
57378 * var addSquare = _.flow([_.add, square]);
57379 * addSquare(1, 2);
57380 * // => 9
57381 */
57382 var flow = createFlow();
57383
57384 /**
57385 * This method is like `_.flow` except that it creates a function that
57386 * invokes the given functions from right to left.
57387 *
57388 * @static
57389 * @since 3.0.0
57390 * @memberOf _
57391 * @category Util
57392 * @param {...(Function|Function[])} [funcs] The functions to invoke.
57393 * @returns {Function} Returns the new composite function.
57394 * @see _.flow
57395 * @example
57396 *
57397 * function square(n) {
57398 * return n * n;
57399 * }
57400 *
57401 * var addSquare = _.flowRight([square, _.add]);
57402 * addSquare(1, 2);
57403 * // => 9
57404 */
57405 var flowRight = createFlow(true);
57406
57407 /**
57408 * This method returns the first argument it receives.
57409 *
57410 * @static
57411 * @since 0.1.0
57412 * @memberOf _
57413 * @category Util
57414 * @param {*} value Any value.
57415 * @returns {*} Returns `value`.
57416 * @example
57417 *
57418 * var object = { 'a': 1 };
57419 *
57420 * console.log(_.identity(object) === object);
57421 * // => true
57422 */
57423 function identity(value) {
57424 return value;
57425 }
57426
57427 /**
57428 * Creates a function that invokes `func` with the arguments of the created
57429 * function. If `func` is a property name, the created function returns the
57430 * property value for a given element. If `func` is an array or object, the
57431 * created function returns `true` for elements that contain the equivalent
57432 * source properties, otherwise it returns `false`.
57433 *
57434 * @static
57435 * @since 4.0.0
57436 * @memberOf _
57437 * @category Util
57438 * @param {*} [func=_.identity] The value to convert to a callback.
57439 * @returns {Function} Returns the callback.
57440 * @example
57441 *
57442 * var users = [
57443 * { 'user': 'barney', 'age': 36, 'active': true },
57444 * { 'user': 'fred', 'age': 40, 'active': false }
57445 * ];
57446 *
57447 * // The `_.matches` iteratee shorthand.
57448 * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true }));
57449 * // => [{ 'user': 'barney', 'age': 36, 'active': true }]
57450 *
57451 * // The `_.matchesProperty` iteratee shorthand.
57452 * _.filter(users, _.iteratee(['user', 'fred']));
57453 * // => [{ 'user': 'fred', 'age': 40 }]
57454 *
57455 * // The `_.property` iteratee shorthand.
57456 * _.map(users, _.iteratee('user'));
57457 * // => ['barney', 'fred']
57458 *
57459 * // Create custom iteratee shorthands.
57460 * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) {
57461 * return !_.isRegExp(func) ? iteratee(func) : function(string) {
57462 * return func.test(string);
57463 * };
57464 * });
57465 *
57466 * _.filter(['abc', 'def'], /ef/);
57467 * // => ['def']
57468 */
57469 function iteratee(func) {
57470 return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG));
57471 }
57472
57473 /**
57474 * Creates a function that performs a partial deep comparison between a given
57475 * object and `source`, returning `true` if the given object has equivalent
57476 * property values, else `false`.
57477 *
57478 * **Note:** The created function is equivalent to `_.isMatch` with `source`
57479 * partially applied.
57480 *
57481 * Partial comparisons will match empty array and empty object `source`
57482 * values against any array or object value, respectively. See `_.isEqual`
57483 * for a list of supported value comparisons.
57484 *
57485 * **Note:** Multiple values can be checked by combining several matchers
57486 * using `_.overSome`
57487 *
57488 * @static
57489 * @memberOf _
57490 * @since 3.0.0
57491 * @category Util
57492 * @param {Object} source The object of property values to match.
57493 * @returns {Function} Returns the new spec function.
57494 * @example
57495 *
57496 * var objects = [
57497 * { 'a': 1, 'b': 2, 'c': 3 },
57498 * { 'a': 4, 'b': 5, 'c': 6 }
57499 * ];
57500 *
57501 * _.filter(objects, _.matches({ 'a': 4, 'c': 6 }));
57502 * // => [{ 'a': 4, 'b': 5, 'c': 6 }]
57503 *
57504 * // Checking for several possible values
57505 * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })]));
57506 * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
57507 */
57508 function matches(source) {
57509 return baseMatches(baseClone(source, CLONE_DEEP_FLAG));
57510 }
57511
57512 /**
57513 * Creates a function that performs a partial deep comparison between the
57514 * value at `path` of a given object to `srcValue`, returning `true` if the
57515 * object value is equivalent, else `false`.
57516 *
57517 * **Note:** Partial comparisons will match empty array and empty object
57518 * `srcValue` values against any array or object value, respectively. See
57519 * `_.isEqual` for a list of supported value comparisons.
57520 *
57521 * **Note:** Multiple values can be checked by combining several matchers
57522 * using `_.overSome`
57523 *
57524 * @static
57525 * @memberOf _
57526 * @since 3.2.0
57527 * @category Util
57528 * @param {Array|string} path The path of the property to get.
57529 * @param {*} srcValue The value to match.
57530 * @returns {Function} Returns the new spec function.
57531 * @example
57532 *
57533 * var objects = [
57534 * { 'a': 1, 'b': 2, 'c': 3 },
57535 * { 'a': 4, 'b': 5, 'c': 6 }
57536 * ];
57537 *
57538 * _.find(objects, _.matchesProperty('a', 4));
57539 * // => { 'a': 4, 'b': 5, 'c': 6 }
57540 *
57541 * // Checking for several possible values
57542 * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)]));
57543 * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }]
57544 */
57545 function matchesProperty(path, srcValue) {
57546 return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG));
57547 }
57548
57549 /**
57550 * Creates a function that invokes the method at `path` of a given object.
57551 * Any additional arguments are provided to the invoked method.
57552 *
57553 * @static
57554 * @memberOf _
57555 * @since 3.7.0
57556 * @category Util
57557 * @param {Array|string} path The path of the method to invoke.
57558 * @param {...*} [args] The arguments to invoke the method with.
57559 * @returns {Function} Returns the new invoker function.
57560 * @example
57561 *
57562 * var objects = [
57563 * { 'a': { 'b': _.constant(2) } },
57564 * { 'a': { 'b': _.constant(1) } }
57565 * ];
57566 *
57567 * _.map(objects, _.method('a.b'));
57568 * // => [2, 1]
57569 *
57570 * _.map(objects, _.method(['a', 'b']));
57571 * // => [2, 1]
57572 */
57573 var method = baseRest(function(path, args) {
57574 return function(object) {
57575 return baseInvoke(object, path, args);
57576 };
57577 });
57578
57579 /**
57580 * The opposite of `_.method`; this method creates a function that invokes
57581 * the method at a given path of `object`. Any additional arguments are
57582 * provided to the invoked method.
57583 *
57584 * @static
57585 * @memberOf _
57586 * @since 3.7.0
57587 * @category Util
57588 * @param {Object} object The object to query.
57589 * @param {...*} [args] The arguments to invoke the method with.
57590 * @returns {Function} Returns the new invoker function.
57591 * @example
57592 *
57593 * var array = _.times(3, _.constant),
57594 * object = { 'a': array, 'b': array, 'c': array };
57595 *
57596 * _.map(['a[2]', 'c[0]'], _.methodOf(object));
57597 * // => [2, 0]
57598 *
57599 * _.map([['a', '2'], ['c', '0']], _.methodOf(object));
57600 * // => [2, 0]
57601 */
57602 var methodOf = baseRest(function(object, args) {
57603 return function(path) {
57604 return baseInvoke(object, path, args);
57605 };
57606 });
57607
57608 /**
57609 * Adds all own enumerable string keyed function properties of a source
57610 * object to the destination object. If `object` is a function, then methods
57611 * are added to its prototype as well.
57612 *
57613 * **Note:** Use `_.runInContext` to create a pristine `lodash` function to
57614 * avoid conflicts caused by modifying the original.
57615 *
57616 * @static
57617 * @since 0.1.0
57618 * @memberOf _
57619 * @category Util
57620 * @param {Function|Object} [object=lodash] The destination object.
57621 * @param {Object} source The object of functions to add.
57622 * @param {Object} [options={}] The options object.
57623 * @param {boolean} [options.chain=true] Specify whether mixins are chainable.
57624 * @returns {Function|Object} Returns `object`.
57625 * @example
57626 *
57627 * function vowels(string) {
57628 * return _.filter(string, function(v) {
57629 * return /[aeiou]/i.test(v);
57630 * });
57631 * }
57632 *
57633 * _.mixin({ 'vowels': vowels });
57634 * _.vowels('fred');
57635 * // => ['e']
57636 *
57637 * _('fred').vowels().value();
57638 * // => ['e']
57639 *
57640 * _.mixin({ 'vowels': vowels }, { 'chain': false });
57641 * _('fred').vowels();
57642 * // => ['e']
57643 */
57644 function mixin(object, source, options) {
57645 var props = keys(source),
57646 methodNames = baseFunctions(source, props);
57647
57648 if (options == null &&
57649 !(isObject(source) && (methodNames.length || !props.length))) {
57650 options = source;
57651 source = object;
57652 object = this;
57653 methodNames = baseFunctions(source, keys(source));
57654 }
57655 var chain = !(isObject(options) && 'chain' in options) || !!options.chain,
57656 isFunc = isFunction(object);
57657
57658 arrayEach(methodNames, function(methodName) {
57659 var func = source[methodName];
57660 object[methodName] = func;
57661 if (isFunc) {
57662 object.prototype[methodName] = function() {
57663 var chainAll = this.__chain__;
57664 if (chain || chainAll) {
57665 var result = object(this.__wrapped__),
57666 actions = result.__actions__ = copyArray(this.__actions__);
57667
57668 actions.push({ 'func': func, 'args': arguments, 'thisArg': object });
57669 result.__chain__ = chainAll;
57670 return result;
57671 }
57672 return func.apply(object, arrayPush([this.value()], arguments));
57673 };
57674 }
57675 });
57676
57677 return object;
57678 }
57679
57680 /**
57681 * Reverts the `_` variable to its previous value and returns a reference to
57682 * the `lodash` function.
57683 *
57684 * @static
57685 * @since 0.1.0
57686 * @memberOf _
57687 * @category Util
57688 * @returns {Function} Returns the `lodash` function.
57689 * @example
57690 *
57691 * var lodash = _.noConflict();
57692 */
57693 function noConflict() {
57694 if (root._ === this) {
57695 root._ = oldDash;
57696 }
57697 return this;
57698 }
57699
57700 /**
57701 * This method returns `undefined`.
57702 *
57703 * @static
57704 * @memberOf _
57705 * @since 2.3.0
57706 * @category Util
57707 * @example
57708 *
57709 * _.times(2, _.noop);
57710 * // => [undefined, undefined]
57711 */
57712 function noop() {
57713 // No operation performed.
57714 }
57715
57716 /**
57717 * Creates a function that gets the argument at index `n`. If `n` is negative,
57718 * the nth argument from the end is returned.
57719 *
57720 * @static
57721 * @memberOf _
57722 * @since 4.0.0
57723 * @category Util
57724 * @param {number} [n=0] The index of the argument to return.
57725 * @returns {Function} Returns the new pass-thru function.
57726 * @example
57727 *
57728 * var func = _.nthArg(1);
57729 * func('a', 'b', 'c', 'd');
57730 * // => 'b'
57731 *
57732 * var func = _.nthArg(-2);
57733 * func('a', 'b', 'c', 'd');
57734 * // => 'c'
57735 */
57736 function nthArg(n) {
57737 n = toInteger(n);
57738 return baseRest(function(args) {
57739 return baseNth(args, n);
57740 });
57741 }
57742
57743 /**
57744 * Creates a function that invokes `iteratees` with the arguments it receives
57745 * and returns their results.
57746 *
57747 * @static
57748 * @memberOf _
57749 * @since 4.0.0
57750 * @category Util
57751 * @param {...(Function|Function[])} [iteratees=[_.identity]]
57752 * The iteratees to invoke.
57753 * @returns {Function} Returns the new function.
57754 * @example
57755 *
57756 * var func = _.over([Math.max, Math.min]);
57757 *
57758 * func(1, 2, 3, 4);
57759 * // => [4, 1]
57760 */
57761 var over = createOver(arrayMap);
57762
57763 /**
57764 * Creates a function that checks if **all** of the `predicates` return
57765 * truthy when invoked with the arguments it receives.
57766 *
57767 * Following shorthands are possible for providing predicates.
57768 * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
57769 * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
57770 *
57771 * @static
57772 * @memberOf _
57773 * @since 4.0.0
57774 * @category Util
57775 * @param {...(Function|Function[])} [predicates=[_.identity]]
57776 * The predicates to check.
57777 * @returns {Function} Returns the new function.
57778 * @example
57779 *
57780 * var func = _.overEvery([Boolean, isFinite]);
57781 *
57782 * func('1');
57783 * // => true
57784 *
57785 * func(null);
57786 * // => false
57787 *
57788 * func(NaN);
57789 * // => false
57790 */
57791 var overEvery = createOver(arrayEvery);
57792
57793 /**
57794 * Creates a function that checks if **any** of the `predicates` return
57795 * truthy when invoked with the arguments it receives.
57796 *
57797 * Following shorthands are possible for providing predicates.
57798 * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate.
57799 * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them.
57800 *
57801 * @static
57802 * @memberOf _
57803 * @since 4.0.0
57804 * @category Util
57805 * @param {...(Function|Function[])} [predicates=[_.identity]]
57806 * The predicates to check.
57807 * @returns {Function} Returns the new function.
57808 * @example
57809 *
57810 * var func = _.overSome([Boolean, isFinite]);
57811 *
57812 * func('1');
57813 * // => true
57814 *
57815 * func(null);
57816 * // => true
57817 *
57818 * func(NaN);
57819 * // => false
57820 *
57821 * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }])
57822 * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]])
57823 */
57824 var overSome = createOver(arraySome);
57825
57826 /**
57827 * Creates a function that returns the value at `path` of a given object.
57828 *
57829 * @static
57830 * @memberOf _
57831 * @since 2.4.0
57832 * @category Util
57833 * @param {Array|string} path The path of the property to get.
57834 * @returns {Function} Returns the new accessor function.
57835 * @example
57836 *
57837 * var objects = [
57838 * { 'a': { 'b': 2 } },
57839 * { 'a': { 'b': 1 } }
57840 * ];
57841 *
57842 * _.map(objects, _.property('a.b'));
57843 * // => [2, 1]
57844 *
57845 * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b');
57846 * // => [1, 2]
57847 */
57848 function property(path) {
57849 return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path);
57850 }
57851
57852 /**
57853 * The opposite of `_.property`; this method creates a function that returns
57854 * the value at a given path of `object`.
57855 *
57856 * @static
57857 * @memberOf _
57858 * @since 3.0.0
57859 * @category Util
57860 * @param {Object} object The object to query.
57861 * @returns {Function} Returns the new accessor function.
57862 * @example
57863 *
57864 * var array = [0, 1, 2],
57865 * object = { 'a': array, 'b': array, 'c': array };
57866 *
57867 * _.map(['a[2]', 'c[0]'], _.propertyOf(object));
57868 * // => [2, 0]
57869 *
57870 * _.map([['a', '2'], ['c', '0']], _.propertyOf(object));
57871 * // => [2, 0]
57872 */
57873 function propertyOf(object) {
57874 return function(path) {
57875 return object == null ? undefined : baseGet(object, path);
57876 };
57877 }
57878
57879 /**
57880 * Creates an array of numbers (positive and/or negative) progressing from
57881 * `start` up to, but not including, `end`. A step of `-1` is used if a negative
57882 * `start` is specified without an `end` or `step`. If `end` is not specified,
57883 * it's set to `start` with `start` then set to `0`.
57884 *
57885 * **Note:** JavaScript follows the IEEE-754 standard for resolving
57886 * floating-point values which can produce unexpected results.
57887 *
57888 * @static
57889 * @since 0.1.0
57890 * @memberOf _
57891 * @category Util
57892 * @param {number} [start=0] The start of the range.
57893 * @param {number} end The end of the range.
57894 * @param {number} [step=1] The value to increment or decrement by.
57895 * @returns {Array} Returns the range of numbers.
57896 * @see _.inRange, _.rangeRight
57897 * @example
57898 *
57899 * _.range(4);
57900 * // => [0, 1, 2, 3]
57901 *
57902 * _.range(-4);
57903 * // => [0, -1, -2, -3]
57904 *
57905 * _.range(1, 5);
57906 * // => [1, 2, 3, 4]
57907 *
57908 * _.range(0, 20, 5);
57909 * // => [0, 5, 10, 15]
57910 *
57911 * _.range(0, -4, -1);
57912 * // => [0, -1, -2, -3]
57913 *
57914 * _.range(1, 4, 0);
57915 * // => [1, 1, 1]
57916 *
57917 * _.range(0);
57918 * // => []
57919 */
57920 var range = createRange();
57921
57922 /**
57923 * This method is like `_.range` except that it populates values in
57924 * descending order.
57925 *
57926 * @static
57927 * @memberOf _
57928 * @since 4.0.0
57929 * @category Util
57930 * @param {number} [start=0] The start of the range.
57931 * @param {number} end The end of the range.
57932 * @param {number} [step=1] The value to increment or decrement by.
57933 * @returns {Array} Returns the range of numbers.
57934 * @see _.inRange, _.range
57935 * @example
57936 *
57937 * _.rangeRight(4);
57938 * // => [3, 2, 1, 0]
57939 *
57940 * _.rangeRight(-4);
57941 * // => [-3, -2, -1, 0]
57942 *
57943 * _.rangeRight(1, 5);
57944 * // => [4, 3, 2, 1]
57945 *
57946 * _.rangeRight(0, 20, 5);
57947 * // => [15, 10, 5, 0]
57948 *
57949 * _.rangeRight(0, -4, -1);
57950 * // => [-3, -2, -1, 0]
57951 *
57952 * _.rangeRight(1, 4, 0);
57953 * // => [1, 1, 1]
57954 *
57955 * _.rangeRight(0);
57956 * // => []
57957 */
57958 var rangeRight = createRange(true);
57959
57960 /**
57961 * This method returns a new empty array.
57962 *
57963 * @static
57964 * @memberOf _
57965 * @since 4.13.0
57966 * @category Util
57967 * @returns {Array} Returns the new empty array.
57968 * @example
57969 *
57970 * var arrays = _.times(2, _.stubArray);
57971 *
57972 * console.log(arrays);
57973 * // => [[], []]
57974 *
57975 * console.log(arrays[0] === arrays[1]);
57976 * // => false
57977 */
57978 function stubArray() {
57979 return [];
57980 }
57981
57982 /**
57983 * This method returns `false`.
57984 *
57985 * @static
57986 * @memberOf _
57987 * @since 4.13.0
57988 * @category Util
57989 * @returns {boolean} Returns `false`.
57990 * @example
57991 *
57992 * _.times(2, _.stubFalse);
57993 * // => [false, false]
57994 */
57995 function stubFalse() {
57996 return false;
57997 }
57998
57999 /**
58000 * This method returns a new empty object.
58001 *
58002 * @static
58003 * @memberOf _
58004 * @since 4.13.0
58005 * @category Util
58006 * @returns {Object} Returns the new empty object.
58007 * @example
58008 *
58009 * var objects = _.times(2, _.stubObject);
58010 *
58011 * console.log(objects);
58012 * // => [{}, {}]
58013 *
58014 * console.log(objects[0] === objects[1]);
58015 * // => false
58016 */
58017 function stubObject() {
58018 return {};
58019 }
58020
58021 /**
58022 * This method returns an empty string.
58023 *
58024 * @static
58025 * @memberOf _
58026 * @since 4.13.0
58027 * @category Util
58028 * @returns {string} Returns the empty string.
58029 * @example
58030 *
58031 * _.times(2, _.stubString);
58032 * // => ['', '']
58033 */
58034 function stubString() {
58035 return '';
58036 }
58037
58038 /**
58039 * This method returns `true`.
58040 *
58041 * @static
58042 * @memberOf _
58043 * @since 4.13.0
58044 * @category Util
58045 * @returns {boolean} Returns `true`.
58046 * @example
58047 *
58048 * _.times(2, _.stubTrue);
58049 * // => [true, true]
58050 */
58051 function stubTrue() {
58052 return true;
58053 }
58054
58055 /**
58056 * Invokes the iteratee `n` times, returning an array of the results of
58057 * each invocation. The iteratee is invoked with one argument; (index).
58058 *
58059 * @static
58060 * @since 0.1.0
58061 * @memberOf _
58062 * @category Util
58063 * @param {number} n The number of times to invoke `iteratee`.
58064 * @param {Function} [iteratee=_.identity] The function invoked per iteration.
58065 * @returns {Array} Returns the array of results.
58066 * @example
58067 *
58068 * _.times(3, String);
58069 * // => ['0', '1', '2']
58070 *
58071 * _.times(4, _.constant(0));
58072 * // => [0, 0, 0, 0]
58073 */
58074 function times(n, iteratee) {
58075 n = toInteger(n);
58076 if (n < 1 || n > MAX_SAFE_INTEGER) {
58077 return [];
58078 }
58079 var index = MAX_ARRAY_LENGTH,
58080 length = nativeMin(n, MAX_ARRAY_LENGTH);
58081
58082 iteratee = getIteratee(iteratee);
58083 n -= MAX_ARRAY_LENGTH;
58084
58085 var result = baseTimes(length, iteratee);
58086 while (++index < n) {
58087 iteratee(index);
58088 }
58089 return result;
58090 }
58091
58092 /**
58093 * Converts `value` to a property path array.
58094 *
58095 * @static
58096 * @memberOf _
58097 * @since 4.0.0
58098 * @category Util
58099 * @param {*} value The value to convert.
58100 * @returns {Array} Returns the new property path array.
58101 * @example
58102 *
58103 * _.toPath('a.b.c');
58104 * // => ['a', 'b', 'c']
58105 *
58106 * _.toPath('a[0].b.c');
58107 * // => ['a', '0', 'b', 'c']
58108 */
58109 function toPath(value) {
58110 if (isArray(value)) {
58111 return arrayMap(value, toKey);
58112 }
58113 return isSymbol(value) ? [value] : copyArray(stringToPath(toString(value)));
58114 }
58115
58116 /**
58117 * Generates a unique ID. If `prefix` is given, the ID is appended to it.
58118 *
58119 * @static
58120 * @since 0.1.0
58121 * @memberOf _
58122 * @category Util
58123 * @param {string} [prefix=''] The value to prefix the ID with.
58124 * @returns {string} Returns the unique ID.
58125 * @example
58126 *
58127 * _.uniqueId('contact_');
58128 * // => 'contact_104'
58129 *
58130 * _.uniqueId();
58131 * // => '105'
58132 */
58133 function uniqueId(prefix) {
58134 var id = ++idCounter;
58135 return toString(prefix) + id;
58136 }
58137
58138 /*------------------------------------------------------------------------*/
58139
58140 /**
58141 * Adds two numbers.
58142 *
58143 * @static
58144 * @memberOf _
58145 * @since 3.4.0
58146 * @category Math
58147 * @param {number} augend The first number in an addition.
58148 * @param {number} addend The second number in an addition.
58149 * @returns {number} Returns the total.
58150 * @example
58151 *
58152 * _.add(6, 4);
58153 * // => 10
58154 */
58155 var add = createMathOperation(function(augend, addend) {
58156 return augend + addend;
58157 }, 0);
58158
58159 /**
58160 * Computes `number` rounded up to `precision`.
58161 *
58162 * @static
58163 * @memberOf _
58164 * @since 3.10.0
58165 * @category Math
58166 * @param {number} number The number to round up.
58167 * @param {number} [precision=0] The precision to round up to.
58168 * @returns {number} Returns the rounded up number.
58169 * @example
58170 *
58171 * _.ceil(4.006);
58172 * // => 5
58173 *
58174 * _.ceil(6.004, 2);
58175 * // => 6.01
58176 *
58177 * _.ceil(6040, -2);
58178 * // => 6100
58179 */
58180 var ceil = createRound('ceil');
58181
58182 /**
58183 * Divide two numbers.
58184 *
58185 * @static
58186 * @memberOf _
58187 * @since 4.7.0
58188 * @category Math
58189 * @param {number} dividend The first number in a division.
58190 * @param {number} divisor The second number in a division.
58191 * @returns {number} Returns the quotient.
58192 * @example
58193 *
58194 * _.divide(6, 4);
58195 * // => 1.5
58196 */
58197 var divide = createMathOperation(function(dividend, divisor) {
58198 return dividend / divisor;
58199 }, 1);
58200
58201 /**
58202 * Computes `number` rounded down to `precision`.
58203 *
58204 * @static
58205 * @memberOf _
58206 * @since 3.10.0
58207 * @category Math
58208 * @param {number} number The number to round down.
58209 * @param {number} [precision=0] The precision to round down to.
58210 * @returns {number} Returns the rounded down number.
58211 * @example
58212 *
58213 * _.floor(4.006);
58214 * // => 4
58215 *
58216 * _.floor(0.046, 2);
58217 * // => 0.04
58218 *
58219 * _.floor(4060, -2);
58220 * // => 4000
58221 */
58222 var floor = createRound('floor');
58223
58224 /**
58225 * Computes the maximum value of `array`. If `array` is empty or falsey,
58226 * `undefined` is returned.
58227 *
58228 * @static
58229 * @since 0.1.0
58230 * @memberOf _
58231 * @category Math
58232 * @param {Array} array The array to iterate over.
58233 * @returns {*} Returns the maximum value.
58234 * @example
58235 *
58236 * _.max([4, 2, 8, 6]);
58237 * // => 8
58238 *
58239 * _.max([]);
58240 * // => undefined
58241 */
58242 function max(array) {
58243 return (array && array.length)
58244 ? baseExtremum(array, identity, baseGt)
58245 : undefined;
58246 }
58247
58248 /**
58249 * This method is like `_.max` except that it accepts `iteratee` which is
58250 * invoked for each element in `array` to generate the criterion by which
58251 * the value is ranked. The iteratee is invoked with one argument: (value).
58252 *
58253 * @static
58254 * @memberOf _
58255 * @since 4.0.0
58256 * @category Math
58257 * @param {Array} array The array to iterate over.
58258 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
58259 * @returns {*} Returns the maximum value.
58260 * @example
58261 *
58262 * var objects = [{ 'n': 1 }, { 'n': 2 }];
58263 *
58264 * _.maxBy(objects, function(o) { return o.n; });
58265 * // => { 'n': 2 }
58266 *
58267 * // The `_.property` iteratee shorthand.
58268 * _.maxBy(objects, 'n');
58269 * // => { 'n': 2 }
58270 */
58271 function maxBy(array, iteratee) {
58272 return (array && array.length)
58273 ? baseExtremum(array, getIteratee(iteratee, 2), baseGt)
58274 : undefined;
58275 }
58276
58277 /**
58278 * Computes the mean of the values in `array`.
58279 *
58280 * @static
58281 * @memberOf _
58282 * @since 4.0.0
58283 * @category Math
58284 * @param {Array} array The array to iterate over.
58285 * @returns {number} Returns the mean.
58286 * @example
58287 *
58288 * _.mean([4, 2, 8, 6]);
58289 * // => 5
58290 */
58291 function mean(array) {
58292 return baseMean(array, identity);
58293 }
58294
58295 /**
58296 * This method is like `_.mean` except that it accepts `iteratee` which is
58297 * invoked for each element in `array` to generate the value to be averaged.
58298 * The iteratee is invoked with one argument: (value).
58299 *
58300 * @static
58301 * @memberOf _
58302 * @since 4.7.0
58303 * @category Math
58304 * @param {Array} array The array to iterate over.
58305 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
58306 * @returns {number} Returns the mean.
58307 * @example
58308 *
58309 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
58310 *
58311 * _.meanBy(objects, function(o) { return o.n; });
58312 * // => 5
58313 *
58314 * // The `_.property` iteratee shorthand.
58315 * _.meanBy(objects, 'n');
58316 * // => 5
58317 */
58318 function meanBy(array, iteratee) {
58319 return baseMean(array, getIteratee(iteratee, 2));
58320 }
58321
58322 /**
58323 * Computes the minimum value of `array`. If `array` is empty or falsey,
58324 * `undefined` is returned.
58325 *
58326 * @static
58327 * @since 0.1.0
58328 * @memberOf _
58329 * @category Math
58330 * @param {Array} array The array to iterate over.
58331 * @returns {*} Returns the minimum value.
58332 * @example
58333 *
58334 * _.min([4, 2, 8, 6]);
58335 * // => 2
58336 *
58337 * _.min([]);
58338 * // => undefined
58339 */
58340 function min(array) {
58341 return (array && array.length)
58342 ? baseExtremum(array, identity, baseLt)
58343 : undefined;
58344 }
58345
58346 /**
58347 * This method is like `_.min` except that it accepts `iteratee` which is
58348 * invoked for each element in `array` to generate the criterion by which
58349 * the value is ranked. The iteratee is invoked with one argument: (value).
58350 *
58351 * @static
58352 * @memberOf _
58353 * @since 4.0.0
58354 * @category Math
58355 * @param {Array} array The array to iterate over.
58356 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
58357 * @returns {*} Returns the minimum value.
58358 * @example
58359 *
58360 * var objects = [{ 'n': 1 }, { 'n': 2 }];
58361 *
58362 * _.minBy(objects, function(o) { return o.n; });
58363 * // => { 'n': 1 }
58364 *
58365 * // The `_.property` iteratee shorthand.
58366 * _.minBy(objects, 'n');
58367 * // => { 'n': 1 }
58368 */
58369 function minBy(array, iteratee) {
58370 return (array && array.length)
58371 ? baseExtremum(array, getIteratee(iteratee, 2), baseLt)
58372 : undefined;
58373 }
58374
58375 /**
58376 * Multiply two numbers.
58377 *
58378 * @static
58379 * @memberOf _
58380 * @since 4.7.0
58381 * @category Math
58382 * @param {number} multiplier The first number in a multiplication.
58383 * @param {number} multiplicand The second number in a multiplication.
58384 * @returns {number} Returns the product.
58385 * @example
58386 *
58387 * _.multiply(6, 4);
58388 * // => 24
58389 */
58390 var multiply = createMathOperation(function(multiplier, multiplicand) {
58391 return multiplier * multiplicand;
58392 }, 1);
58393
58394 /**
58395 * Computes `number` rounded to `precision`.
58396 *
58397 * @static
58398 * @memberOf _
58399 * @since 3.10.0
58400 * @category Math
58401 * @param {number} number The number to round.
58402 * @param {number} [precision=0] The precision to round to.
58403 * @returns {number} Returns the rounded number.
58404 * @example
58405 *
58406 * _.round(4.006);
58407 * // => 4
58408 *
58409 * _.round(4.006, 2);
58410 * // => 4.01
58411 *
58412 * _.round(4060, -2);
58413 * // => 4100
58414 */
58415 var round = createRound('round');
58416
58417 /**
58418 * Subtract two numbers.
58419 *
58420 * @static
58421 * @memberOf _
58422 * @since 4.0.0
58423 * @category Math
58424 * @param {number} minuend The first number in a subtraction.
58425 * @param {number} subtrahend The second number in a subtraction.
58426 * @returns {number} Returns the difference.
58427 * @example
58428 *
58429 * _.subtract(6, 4);
58430 * // => 2
58431 */
58432 var subtract = createMathOperation(function(minuend, subtrahend) {
58433 return minuend - subtrahend;
58434 }, 0);
58435
58436 /**
58437 * Computes the sum of the values in `array`.
58438 *
58439 * @static
58440 * @memberOf _
58441 * @since 3.4.0
58442 * @category Math
58443 * @param {Array} array The array to iterate over.
58444 * @returns {number} Returns the sum.
58445 * @example
58446 *
58447 * _.sum([4, 2, 8, 6]);
58448 * // => 20
58449 */
58450 function sum(array) {
58451 return (array && array.length)
58452 ? baseSum(array, identity)
58453 : 0;
58454 }
58455
58456 /**
58457 * This method is like `_.sum` except that it accepts `iteratee` which is
58458 * invoked for each element in `array` to generate the value to be summed.
58459 * The iteratee is invoked with one argument: (value).
58460 *
58461 * @static
58462 * @memberOf _
58463 * @since 4.0.0
58464 * @category Math
58465 * @param {Array} array The array to iterate over.
58466 * @param {Function} [iteratee=_.identity] The iteratee invoked per element.
58467 * @returns {number} Returns the sum.
58468 * @example
58469 *
58470 * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }];
58471 *
58472 * _.sumBy(objects, function(o) { return o.n; });
58473 * // => 20
58474 *
58475 * // The `_.property` iteratee shorthand.
58476 * _.sumBy(objects, 'n');
58477 * // => 20
58478 */
58479 function sumBy(array, iteratee) {
58480 return (array && array.length)
58481 ? baseSum(array, getIteratee(iteratee, 2))
58482 : 0;
58483 }
58484
58485 /*------------------------------------------------------------------------*/
58486
58487 // Add methods that return wrapped values in chain sequences.
58488 lodash.after = after;
58489 lodash.ary = ary;
58490 lodash.assign = assign;
58491 lodash.assignIn = assignIn;
58492 lodash.assignInWith = assignInWith;
58493 lodash.assignWith = assignWith;
58494 lodash.at = at;
58495 lodash.before = before;
58496 lodash.bind = bind;
58497 lodash.bindAll = bindAll;
58498 lodash.bindKey = bindKey;
58499 lodash.castArray = castArray;
58500 lodash.chain = chain;
58501 lodash.chunk = chunk;
58502 lodash.compact = compact;
58503 lodash.concat = concat;
58504 lodash.cond = cond;
58505 lodash.conforms = conforms;
58506 lodash.constant = constant;
58507 lodash.countBy = countBy;
58508 lodash.create = create;
58509 lodash.curry = curry;
58510 lodash.curryRight = curryRight;
58511 lodash.debounce = debounce;
58512 lodash.defaults = defaults;
58513 lodash.defaultsDeep = defaultsDeep;
58514 lodash.defer = defer;
58515 lodash.delay = delay;
58516 lodash.difference = difference;
58517 lodash.differenceBy = differenceBy;
58518 lodash.differenceWith = differenceWith;
58519 lodash.drop = drop;
58520 lodash.dropRight = dropRight;
58521 lodash.dropRightWhile = dropRightWhile;
58522 lodash.dropWhile = dropWhile;
58523 lodash.fill = fill;
58524 lodash.filter = filter;
58525 lodash.flatMap = flatMap;
58526 lodash.flatMapDeep = flatMapDeep;
58527 lodash.flatMapDepth = flatMapDepth;
58528 lodash.flatten = flatten;
58529 lodash.flattenDeep = flattenDeep;
58530 lodash.flattenDepth = flattenDepth;
58531 lodash.flip = flip;
58532 lodash.flow = flow;
58533 lodash.flowRight = flowRight;
58534 lodash.fromPairs = fromPairs;
58535 lodash.functions = functions;
58536 lodash.functionsIn = functionsIn;
58537 lodash.groupBy = groupBy;
58538 lodash.initial = initial;
58539 lodash.intersection = intersection;
58540 lodash.intersectionBy = intersectionBy;
58541 lodash.intersectionWith = intersectionWith;
58542 lodash.invert = invert;
58543 lodash.invertBy = invertBy;
58544 lodash.invokeMap = invokeMap;
58545 lodash.iteratee = iteratee;
58546 lodash.keyBy = keyBy;
58547 lodash.keys = keys;
58548 lodash.keysIn = keysIn;
58549 lodash.map = map;
58550 lodash.mapKeys = mapKeys;
58551 lodash.mapValues = mapValues;
58552 lodash.matches = matches;
58553 lodash.matchesProperty = matchesProperty;
58554 lodash.memoize = memoize;
58555 lodash.merge = merge;
58556 lodash.mergeWith = mergeWith;
58557 lodash.method = method;
58558 lodash.methodOf = methodOf;
58559 lodash.mixin = mixin;
58560 lodash.negate = negate;
58561 lodash.nthArg = nthArg;
58562 lodash.omit = omit;
58563 lodash.omitBy = omitBy;
58564 lodash.once = once;
58565 lodash.orderBy = orderBy;
58566 lodash.over = over;
58567 lodash.overArgs = overArgs;
58568 lodash.overEvery = overEvery;
58569 lodash.overSome = overSome;
58570 lodash.partial = partial;
58571 lodash.partialRight = partialRight;
58572 lodash.partition = partition;
58573 lodash.pick = pick;
58574 lodash.pickBy = pickBy;
58575 lodash.property = property;
58576 lodash.propertyOf = propertyOf;
58577 lodash.pull = pull;
58578 lodash.pullAll = pullAll;
58579 lodash.pullAllBy = pullAllBy;
58580 lodash.pullAllWith = pullAllWith;
58581 lodash.pullAt = pullAt;
58582 lodash.range = range;
58583 lodash.rangeRight = rangeRight;
58584 lodash.rearg = rearg;
58585 lodash.reject = reject;
58586 lodash.remove = remove;
58587 lodash.rest = rest;
58588 lodash.reverse = reverse;
58589 lodash.sampleSize = sampleSize;
58590 lodash.set = set;
58591 lodash.setWith = setWith;
58592 lodash.shuffle = shuffle;
58593 lodash.slice = slice;
58594 lodash.sortBy = sortBy;
58595 lodash.sortedUniq = sortedUniq;
58596 lodash.sortedUniqBy = sortedUniqBy;
58597 lodash.split = split;
58598 lodash.spread = spread;
58599 lodash.tail = tail;
58600 lodash.take = take;
58601 lodash.takeRight = takeRight;
58602 lodash.takeRightWhile = takeRightWhile;
58603 lodash.takeWhile = takeWhile;
58604 lodash.tap = tap;
58605 lodash.throttle = throttle;
58606 lodash.thru = thru;
58607 lodash.toArray = toArray;
58608 lodash.toPairs = toPairs;
58609 lodash.toPairsIn = toPairsIn;
58610 lodash.toPath = toPath;
58611 lodash.toPlainObject = toPlainObject;
58612 lodash.transform = transform;
58613 lodash.unary = unary;
58614 lodash.union = union;
58615 lodash.unionBy = unionBy;
58616 lodash.unionWith = unionWith;
58617 lodash.uniq = uniq;
58618 lodash.uniqBy = uniqBy;
58619 lodash.uniqWith = uniqWith;
58620 lodash.unset = unset;
58621 lodash.unzip = unzip;
58622 lodash.unzipWith = unzipWith;
58623 lodash.update = update;
58624 lodash.updateWith = updateWith;
58625 lodash.values = values;
58626 lodash.valuesIn = valuesIn;
58627 lodash.without = without;
58628 lodash.words = words;
58629 lodash.wrap = wrap;
58630 lodash.xor = xor;
58631 lodash.xorBy = xorBy;
58632 lodash.xorWith = xorWith;
58633 lodash.zip = zip;
58634 lodash.zipObject = zipObject;
58635 lodash.zipObjectDeep = zipObjectDeep;
58636 lodash.zipWith = zipWith;
58637
58638 // Add aliases.
58639 lodash.entries = toPairs;
58640 lodash.entriesIn = toPairsIn;
58641 lodash.extend = assignIn;
58642 lodash.extendWith = assignInWith;
58643
58644 // Add methods to `lodash.prototype`.
58645 mixin(lodash, lodash);
58646
58647 /*------------------------------------------------------------------------*/
58648
58649 // Add methods that return unwrapped values in chain sequences.
58650 lodash.add = add;
58651 lodash.attempt = attempt;
58652 lodash.camelCase = camelCase;
58653 lodash.capitalize = capitalize;
58654 lodash.ceil = ceil;
58655 lodash.clamp = clamp;
58656 lodash.clone = clone;
58657 lodash.cloneDeep = cloneDeep;
58658 lodash.cloneDeepWith = cloneDeepWith;
58659 lodash.cloneWith = cloneWith;
58660 lodash.conformsTo = conformsTo;
58661 lodash.deburr = deburr;
58662 lodash.defaultTo = defaultTo;
58663 lodash.divide = divide;
58664 lodash.endsWith = endsWith;
58665 lodash.eq = eq;
58666 lodash.escape = escape;
58667 lodash.escapeRegExp = escapeRegExp;
58668 lodash.every = every;
58669 lodash.find = find;
58670 lodash.findIndex = findIndex;
58671 lodash.findKey = findKey;
58672 lodash.findLast = findLast;
58673 lodash.findLastIndex = findLastIndex;
58674 lodash.findLastKey = findLastKey;
58675 lodash.floor = floor;
58676 lodash.forEach = forEach;
58677 lodash.forEachRight = forEachRight;
58678 lodash.forIn = forIn;
58679 lodash.forInRight = forInRight;
58680 lodash.forOwn = forOwn;
58681 lodash.forOwnRight = forOwnRight;
58682 lodash.get = get;
58683 lodash.gt = gt;
58684 lodash.gte = gte;
58685 lodash.has = has;
58686 lodash.hasIn = hasIn;
58687 lodash.head = head;
58688 lodash.identity = identity;
58689 lodash.includes = includes;
58690 lodash.indexOf = indexOf;
58691 lodash.inRange = inRange;
58692 lodash.invoke = invoke;
58693 lodash.isArguments = isArguments;
58694 lodash.isArray = isArray;
58695 lodash.isArrayBuffer = isArrayBuffer;
58696 lodash.isArrayLike = isArrayLike;
58697 lodash.isArrayLikeObject = isArrayLikeObject;
58698 lodash.isBoolean = isBoolean;
58699 lodash.isBuffer = isBuffer;
58700 lodash.isDate = isDate;
58701 lodash.isElement = isElement;
58702 lodash.isEmpty = isEmpty;
58703 lodash.isEqual = isEqual;
58704 lodash.isEqualWith = isEqualWith;
58705 lodash.isError = isError;
58706 lodash.isFinite = isFinite;
58707 lodash.isFunction = isFunction;
58708 lodash.isInteger = isInteger;
58709 lodash.isLength = isLength;
58710 lodash.isMap = isMap;
58711 lodash.isMatch = isMatch;
58712 lodash.isMatchWith = isMatchWith;
58713 lodash.isNaN = isNaN;
58714 lodash.isNative = isNative;
58715 lodash.isNil = isNil;
58716 lodash.isNull = isNull;
58717 lodash.isNumber = isNumber;
58718 lodash.isObject = isObject;
58719 lodash.isObjectLike = isObjectLike;
58720 lodash.isPlainObject = isPlainObject;
58721 lodash.isRegExp = isRegExp;
58722 lodash.isSafeInteger = isSafeInteger;
58723 lodash.isSet = isSet;
58724 lodash.isString = isString;
58725 lodash.isSymbol = isSymbol;
58726 lodash.isTypedArray = isTypedArray;
58727 lodash.isUndefined = isUndefined;
58728 lodash.isWeakMap = isWeakMap;
58729 lodash.isWeakSet = isWeakSet;
58730 lodash.join = join;
58731 lodash.kebabCase = kebabCase;
58732 lodash.last = last;
58733 lodash.lastIndexOf = lastIndexOf;
58734 lodash.lowerCase = lowerCase;
58735 lodash.lowerFirst = lowerFirst;
58736 lodash.lt = lt;
58737 lodash.lte = lte;
58738 lodash.max = max;
58739 lodash.maxBy = maxBy;
58740 lodash.mean = mean;
58741 lodash.meanBy = meanBy;
58742 lodash.min = min;
58743 lodash.minBy = minBy;
58744 lodash.stubArray = stubArray;
58745 lodash.stubFalse = stubFalse;
58746 lodash.stubObject = stubObject;
58747 lodash.stubString = stubString;
58748 lodash.stubTrue = stubTrue;
58749 lodash.multiply = multiply;
58750 lodash.nth = nth;
58751 lodash.noConflict = noConflict;
58752 lodash.noop = noop;
58753 lodash.now = now;
58754 lodash.pad = pad;
58755 lodash.padEnd = padEnd;
58756 lodash.padStart = padStart;
58757 lodash.parseInt = parseInt;
58758 lodash.random = random;
58759 lodash.reduce = reduce;
58760 lodash.reduceRight = reduceRight;
58761 lodash.repeat = repeat;
58762 lodash.replace = replace;
58763 lodash.result = result;
58764 lodash.round = round;
58765 lodash.runInContext = runInContext;
58766 lodash.sample = sample;
58767 lodash.size = size;
58768 lodash.snakeCase = snakeCase;
58769 lodash.some = some;
58770 lodash.sortedIndex = sortedIndex;
58771 lodash.sortedIndexBy = sortedIndexBy;
58772 lodash.sortedIndexOf = sortedIndexOf;
58773 lodash.sortedLastIndex = sortedLastIndex;
58774 lodash.sortedLastIndexBy = sortedLastIndexBy;
58775 lodash.sortedLastIndexOf = sortedLastIndexOf;
58776 lodash.startCase = startCase;
58777 lodash.startsWith = startsWith;
58778 lodash.subtract = subtract;
58779 lodash.sum = sum;
58780 lodash.sumBy = sumBy;
58781 lodash.template = template;
58782 lodash.times = times;
58783 lodash.toFinite = toFinite;
58784 lodash.toInteger = toInteger;
58785 lodash.toLength = toLength;
58786 lodash.toLower = toLower;
58787 lodash.toNumber = toNumber;
58788 lodash.toSafeInteger = toSafeInteger;
58789 lodash.toString = toString;
58790 lodash.toUpper = toUpper;
58791 lodash.trim = trim;
58792 lodash.trimEnd = trimEnd;
58793 lodash.trimStart = trimStart;
58794 lodash.truncate = truncate;
58795 lodash.unescape = unescape;
58796 lodash.uniqueId = uniqueId;
58797 lodash.upperCase = upperCase;
58798 lodash.upperFirst = upperFirst;
58799
58800 // Add aliases.
58801 lodash.each = forEach;
58802 lodash.eachRight = forEachRight;
58803 lodash.first = head;
58804
58805 mixin(lodash, (function() {
58806 var source = {};
58807 baseForOwn(lodash, function(func, methodName) {
58808 if (!hasOwnProperty.call(lodash.prototype, methodName)) {
58809 source[methodName] = func;
58810 }
58811 });
58812 return source;
58813 }()), { 'chain': false });
58814
58815 /*------------------------------------------------------------------------*/
58816
58817 /**
58818 * The semantic version number.
58819 *
58820 * @static
58821 * @memberOf _
58822 * @type {string}
58823 */
58824 lodash.VERSION = VERSION;
58825
58826 // Assign default placeholders.
58827 arrayEach(['bind', 'bindKey', 'curry', 'curryRight', 'partial', 'partialRight'], function(methodName) {
58828 lodash[methodName].placeholder = lodash;
58829 });
58830
58831 // Add `LazyWrapper` methods for `_.drop` and `_.take` variants.
58832 arrayEach(['drop', 'take'], function(methodName, index) {
58833 LazyWrapper.prototype[methodName] = function(n) {
58834 n = n === undefined ? 1 : nativeMax(toInteger(n), 0);
58835
58836 var result = (this.__filtered__ && !index)
58837 ? new LazyWrapper(this)
58838 : this.clone();
58839
58840 if (result.__filtered__) {
58841 result.__takeCount__ = nativeMin(n, result.__takeCount__);
58842 } else {
58843 result.__views__.push({
58844 'size': nativeMin(n, MAX_ARRAY_LENGTH),
58845 'type': methodName + (result.__dir__ < 0 ? 'Right' : '')
58846 });
58847 }
58848 return result;
58849 };
58850
58851 LazyWrapper.prototype[methodName + 'Right'] = function(n) {
58852 return this.reverse()[methodName](n).reverse();
58853 };
58854 });
58855
58856 // Add `LazyWrapper` methods that accept an `iteratee` value.
58857 arrayEach(['filter', 'map', 'takeWhile'], function(methodName, index) {
58858 var type = index + 1,
58859 isFilter = type == LAZY_FILTER_FLAG || type == LAZY_WHILE_FLAG;
58860
58861 LazyWrapper.prototype[methodName] = function(iteratee) {
58862 var result = this.clone();
58863 result.__iteratees__.push({
58864 'iteratee': getIteratee(iteratee, 3),
58865 'type': type
58866 });
58867 result.__filtered__ = result.__filtered__ || isFilter;
58868 return result;
58869 };
58870 });
58871
58872 // Add `LazyWrapper` methods for `_.head` and `_.last`.
58873 arrayEach(['head', 'last'], function(methodName, index) {
58874 var takeName = 'take' + (index ? 'Right' : '');
58875
58876 LazyWrapper.prototype[methodName] = function() {
58877 return this[takeName](1).value()[0];
58878 };
58879 });
58880
58881 // Add `LazyWrapper` methods for `_.initial` and `_.tail`.
58882 arrayEach(['initial', 'tail'], function(methodName, index) {
58883 var dropName = 'drop' + (index ? '' : 'Right');
58884
58885 LazyWrapper.prototype[methodName] = function() {
58886 return this.__filtered__ ? new LazyWrapper(this) : this[dropName](1);
58887 };
58888 });
58889
58890 LazyWrapper.prototype.compact = function() {
58891 return this.filter(identity);
58892 };
58893
58894 LazyWrapper.prototype.find = function(predicate) {
58895 return this.filter(predicate).head();
58896 };
58897
58898 LazyWrapper.prototype.findLast = function(predicate) {
58899 return this.reverse().find(predicate);
58900 };
58901
58902 LazyWrapper.prototype.invokeMap = baseRest(function(path, args) {
58903 if (typeof path == 'function') {
58904 return new LazyWrapper(this);
58905 }
58906 return this.map(function(value) {
58907 return baseInvoke(value, path, args);
58908 });
58909 });
58910
58911 LazyWrapper.prototype.reject = function(predicate) {
58912 return this.filter(negate(getIteratee(predicate)));
58913 };
58914
58915 LazyWrapper.prototype.slice = function(start, end) {
58916 start = toInteger(start);
58917
58918 var result = this;
58919 if (result.__filtered__ && (start > 0 || end < 0)) {
58920 return new LazyWrapper(result);
58921 }
58922 if (start < 0) {
58923 result = result.takeRight(-start);
58924 } else if (start) {
58925 result = result.drop(start);
58926 }
58927 if (end !== undefined) {
58928 end = toInteger(end);
58929 result = end < 0 ? result.dropRight(-end) : result.take(end - start);
58930 }
58931 return result;
58932 };
58933
58934 LazyWrapper.prototype.takeRightWhile = function(predicate) {
58935 return this.reverse().takeWhile(predicate).reverse();
58936 };
58937
58938 LazyWrapper.prototype.toArray = function() {
58939 return this.take(MAX_ARRAY_LENGTH);
58940 };
58941
58942 // Add `LazyWrapper` methods to `lodash.prototype`.
58943 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
58944 var checkIteratee = /^(?:filter|find|map|reject)|While$/.test(methodName),
58945 isTaker = /^(?:head|last)$/.test(methodName),
58946 lodashFunc = lodash[isTaker ? ('take' + (methodName == 'last' ? 'Right' : '')) : methodName],
58947 retUnwrapped = isTaker || /^find/.test(methodName);
58948
58949 if (!lodashFunc) {
58950 return;
58951 }
58952 lodash.prototype[methodName] = function() {
58953 var value = this.__wrapped__,
58954 args = isTaker ? [1] : arguments,
58955 isLazy = value instanceof LazyWrapper,
58956 iteratee = args[0],
58957 useLazy = isLazy || isArray(value);
58958
58959 var interceptor = function(value) {
58960 var result = lodashFunc.apply(lodash, arrayPush([value], args));
58961 return (isTaker && chainAll) ? result[0] : result;
58962 };
58963
58964 if (useLazy && checkIteratee && typeof iteratee == 'function' && iteratee.length != 1) {
58965 // Avoid lazy use if the iteratee has a "length" value other than `1`.
58966 isLazy = useLazy = false;
58967 }
58968 var chainAll = this.__chain__,
58969 isHybrid = !!this.__actions__.length,
58970 isUnwrapped = retUnwrapped && !chainAll,
58971 onlyLazy = isLazy && !isHybrid;
58972
58973 if (!retUnwrapped && useLazy) {
58974 value = onlyLazy ? value : new LazyWrapper(this);
58975 var result = func.apply(value, args);
58976 result.__actions__.push({ 'func': thru, 'args': [interceptor], 'thisArg': undefined });
58977 return new LodashWrapper(result, chainAll);
58978 }
58979 if (isUnwrapped && onlyLazy) {
58980 return func.apply(this, args);
58981 }
58982 result = this.thru(interceptor);
58983 return isUnwrapped ? (isTaker ? result.value()[0] : result.value()) : result;
58984 };
58985 });
58986
58987 // Add `Array` methods to `lodash.prototype`.
58988 arrayEach(['pop', 'push', 'shift', 'sort', 'splice', 'unshift'], function(methodName) {
58989 var func = arrayProto[methodName],
58990 chainName = /^(?:push|sort|unshift)$/.test(methodName) ? 'tap' : 'thru',
58991 retUnwrapped = /^(?:pop|shift)$/.test(methodName);
58992
58993 lodash.prototype[methodName] = function() {
58994 var args = arguments;
58995 if (retUnwrapped && !this.__chain__) {
58996 var value = this.value();
58997 return func.apply(isArray(value) ? value : [], args);
58998 }
58999 return this[chainName](function(value) {
59000 return func.apply(isArray(value) ? value : [], args);
59001 });
59002 };
59003 });
59004
59005 // Map minified method names to their real names.
59006 baseForOwn(LazyWrapper.prototype, function(func, methodName) {
59007 var lodashFunc = lodash[methodName];
59008 if (lodashFunc) {
59009 var key = lodashFunc.name + '';
59010 if (!hasOwnProperty.call(realNames, key)) {
59011 realNames[key] = [];
59012 }
59013 realNames[key].push({ 'name': methodName, 'func': lodashFunc });
59014 }
59015 });
59016
59017 realNames[createHybrid(undefined, WRAP_BIND_KEY_FLAG).name] = [{
59018 'name': 'wrapper',
59019 'func': undefined
59020 }];
59021
59022 // Add methods to `LazyWrapper`.
59023 LazyWrapper.prototype.clone = lazyClone;
59024 LazyWrapper.prototype.reverse = lazyReverse;
59025 LazyWrapper.prototype.value = lazyValue;
59026
59027 // Add chain sequence methods to the `lodash` wrapper.
59028 lodash.prototype.at = wrapperAt;
59029 lodash.prototype.chain = wrapperChain;
59030 lodash.prototype.commit = wrapperCommit;
59031 lodash.prototype.next = wrapperNext;
59032 lodash.prototype.plant = wrapperPlant;
59033 lodash.prototype.reverse = wrapperReverse;
59034 lodash.prototype.toJSON = lodash.prototype.valueOf = lodash.prototype.value = wrapperValue;
59035
59036 // Add lazy aliases.
59037 lodash.prototype.first = lodash.prototype.head;
59038
59039 if (symIterator) {
59040 lodash.prototype[symIterator] = wrapperToIterator;
59041 }
59042 return lodash;
59043 });
59044
59045 /*--------------------------------------------------------------------------*/
59046
59047 // Export lodash.
59048 var _ = runInContext();
59049
59050 // Some AMD build optimizers, like r.js, check for condition patterns like:
59051 if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
59052 // Expose Lodash on the global object to prevent errors when Lodash is
59053 // loaded by a script tag in the presence of an AMD loader.
59054 // See http://requirejs.org/docs/errors.html#mismatch for more details.
59055 // Use `_.noConflict` to remove Lodash from the global object.
59056 root._ = _;
59057
59058 // Define as an anonymous module so, through path mapping, it can be
59059 // referenced as the "underscore" module.
59060 define(function() {
59061 return _;
59062 });
59063 }
59064 // Check for `exports` after `define` in case a build optimizer adds it.
59065 else if (freeModule) {
59066 // Export for Node.js.
59067 (freeModule.exports = _)._ = _;
59068 // Export for CommonJS support.
59069 freeExports._ = _;
59070 }
59071 else {
59072 // Export to the global object.
59073 root._ = _;
59074 }
59075}.call(this));
59076
59077}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
59078},{}],211:[function(require,module,exports){
59079'use strict'
59080var inherits = require('inherits')
59081var HashBase = require('hash-base')
59082var Buffer = require('safe-buffer').Buffer
59083
59084var ARRAY16 = new Array(16)
59085
59086function MD5 () {
59087 HashBase.call(this, 64)
59088
59089 // state
59090 this._a = 0x67452301
59091 this._b = 0xefcdab89
59092 this._c = 0x98badcfe
59093 this._d = 0x10325476
59094}
59095
59096inherits(MD5, HashBase)
59097
59098MD5.prototype._update = function () {
59099 var M = ARRAY16
59100 for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
59101
59102 var a = this._a
59103 var b = this._b
59104 var c = this._c
59105 var d = this._d
59106
59107 a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
59108 d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
59109 c = fnF(c, d, a, b, M[2], 0x242070db, 17)
59110 b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
59111 a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
59112 d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
59113 c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
59114 b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
59115 a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
59116 d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
59117 c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
59118 b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
59119 a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
59120 d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
59121 c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
59122 b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
59123
59124 a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
59125 d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
59126 c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
59127 b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
59128 a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
59129 d = fnG(d, a, b, c, M[10], 0x02441453, 9)
59130 c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
59131 b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
59132 a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
59133 d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
59134 c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
59135 b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
59136 a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
59137 d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
59138 c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
59139 b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
59140
59141 a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
59142 d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
59143 c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
59144 b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
59145 a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
59146 d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
59147 c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
59148 b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
59149 a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
59150 d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
59151 c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
59152 b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
59153 a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
59154 d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
59155 c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
59156 b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
59157
59158 a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
59159 d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
59160 c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
59161 b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
59162 a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
59163 d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
59164 c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
59165 b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
59166 a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
59167 d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
59168 c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
59169 b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
59170 a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
59171 d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
59172 c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
59173 b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
59174
59175 this._a = (this._a + a) | 0
59176 this._b = (this._b + b) | 0
59177 this._c = (this._c + c) | 0
59178 this._d = (this._d + d) | 0
59179}
59180
59181MD5.prototype._digest = function () {
59182 // create padding and handle blocks
59183 this._block[this._blockOffset++] = 0x80
59184 if (this._blockOffset > 56) {
59185 this._block.fill(0, this._blockOffset, 64)
59186 this._update()
59187 this._blockOffset = 0
59188 }
59189
59190 this._block.fill(0, this._blockOffset, 56)
59191 this._block.writeUInt32LE(this._length[0], 56)
59192 this._block.writeUInt32LE(this._length[1], 60)
59193 this._update()
59194
59195 // produce result
59196 var buffer = Buffer.allocUnsafe(16)
59197 buffer.writeInt32LE(this._a, 0)
59198 buffer.writeInt32LE(this._b, 4)
59199 buffer.writeInt32LE(this._c, 8)
59200 buffer.writeInt32LE(this._d, 12)
59201 return buffer
59202}
59203
59204function rotl (x, n) {
59205 return (x << n) | (x >>> (32 - n))
59206}
59207
59208function fnF (a, b, c, d, m, k, s) {
59209 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
59210}
59211
59212function fnG (a, b, c, d, m, k, s) {
59213 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
59214}
59215
59216function fnH (a, b, c, d, m, k, s) {
59217 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
59218}
59219
59220function fnI (a, b, c, d, m, k, s) {
59221 return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
59222}
59223
59224module.exports = MD5
59225
59226},{"hash-base":174,"inherits":206,"safe-buffer":256}],212:[function(require,module,exports){
59227var bn = require('bn.js');
59228var brorand = require('brorand');
59229
59230function MillerRabin(rand) {
59231 this.rand = rand || new brorand.Rand();
59232}
59233module.exports = MillerRabin;
59234
59235MillerRabin.create = function create(rand) {
59236 return new MillerRabin(rand);
59237};
59238
59239MillerRabin.prototype._randbelow = function _randbelow(n) {
59240 var len = n.bitLength();
59241 var min_bytes = Math.ceil(len / 8);
59242
59243 // Generage random bytes until a number less than n is found.
59244 // This ensures that 0..n-1 have an equal probability of being selected.
59245 do
59246 var a = new bn(this.rand.generate(min_bytes));
59247 while (a.cmp(n) >= 0);
59248
59249 return a;
59250};
59251
59252MillerRabin.prototype._randrange = function _randrange(start, stop) {
59253 // Generate a random number greater than or equal to start and less than stop.
59254 var size = stop.sub(start);
59255 return start.add(this._randbelow(size));
59256};
59257
59258MillerRabin.prototype.test = function test(n, k, cb) {
59259 var len = n.bitLength();
59260 var red = bn.mont(n);
59261 var rone = new bn(1).toRed(red);
59262
59263 if (!k)
59264 k = Math.max(1, (len / 48) | 0);
59265
59266 // Find d and s, (n - 1) = (2 ^ s) * d;
59267 var n1 = n.subn(1);
59268 for (var s = 0; !n1.testn(s); s++) {}
59269 var d = n.shrn(s);
59270
59271 var rn1 = n1.toRed(red);
59272
59273 var prime = true;
59274 for (; k > 0; k--) {
59275 var a = this._randrange(new bn(2), n1);
59276 if (cb)
59277 cb(a);
59278
59279 var x = a.toRed(red).redPow(d);
59280 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
59281 continue;
59282
59283 for (var i = 1; i < s; i++) {
59284 x = x.redSqr();
59285
59286 if (x.cmp(rone) === 0)
59287 return false;
59288 if (x.cmp(rn1) === 0)
59289 break;
59290 }
59291
59292 if (i === s)
59293 return false;
59294 }
59295
59296 return prime;
59297};
59298
59299MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
59300 var len = n.bitLength();
59301 var red = bn.mont(n);
59302 var rone = new bn(1).toRed(red);
59303
59304 if (!k)
59305 k = Math.max(1, (len / 48) | 0);
59306
59307 // Find d and s, (n - 1) = (2 ^ s) * d;
59308 var n1 = n.subn(1);
59309 for (var s = 0; !n1.testn(s); s++) {}
59310 var d = n.shrn(s);
59311
59312 var rn1 = n1.toRed(red);
59313
59314 for (; k > 0; k--) {
59315 var a = this._randrange(new bn(2), n1);
59316
59317 var g = n.gcd(a);
59318 if (g.cmpn(1) !== 0)
59319 return g;
59320
59321 var x = a.toRed(red).redPow(d);
59322 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
59323 continue;
59324
59325 for (var i = 1; i < s; i++) {
59326 x = x.redSqr();
59327
59328 if (x.cmp(rone) === 0)
59329 return x.fromRed().subn(1).gcd(n);
59330 if (x.cmp(rn1) === 0)
59331 break;
59332 }
59333
59334 if (i === s) {
59335 x = x.redSqr();
59336 return x.fromRed().subn(1).gcd(n);
59337 }
59338 }
59339
59340 return false;
59341};
59342
59343},{"bn.js":80,"brorand":81}],213:[function(require,module,exports){
59344module.exports = assert;
59345
59346function assert(val, msg) {
59347 if (!val)
59348 throw new Error(msg || 'Assertion failed');
59349}
59350
59351assert.equal = function assertEqual(l, r, msg) {
59352 if (l != r)
59353 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
59354};
59355
59356},{}],214:[function(require,module,exports){
59357'use strict';
59358
59359var utils = exports;
59360
59361function toArray(msg, enc) {
59362 if (Array.isArray(msg))
59363 return msg.slice();
59364 if (!msg)
59365 return [];
59366 var res = [];
59367 if (typeof msg !== 'string') {
59368 for (var i = 0; i < msg.length; i++)
59369 res[i] = msg[i] | 0;
59370 return res;
59371 }
59372 if (enc === 'hex') {
59373 msg = msg.replace(/[^a-z0-9]+/ig, '');
59374 if (msg.length % 2 !== 0)
59375 msg = '0' + msg;
59376 for (var i = 0; i < msg.length; i += 2)
59377 res.push(parseInt(msg[i] + msg[i + 1], 16));
59378 } else {
59379 for (var i = 0; i < msg.length; i++) {
59380 var c = msg.charCodeAt(i);
59381 var hi = c >> 8;
59382 var lo = c & 0xff;
59383 if (hi)
59384 res.push(hi, lo);
59385 else
59386 res.push(lo);
59387 }
59388 }
59389 return res;
59390}
59391utils.toArray = toArray;
59392
59393function zero2(word) {
59394 if (word.length === 1)
59395 return '0' + word;
59396 else
59397 return word;
59398}
59399utils.zero2 = zero2;
59400
59401function toHex(msg) {
59402 var res = '';
59403 for (var i = 0; i < msg.length; i++)
59404 res += zero2(msg[i].toString(16));
59405 return res;
59406}
59407utils.toHex = toHex;
59408
59409utils.encode = function encode(arr, enc) {
59410 if (enc === 'hex')
59411 return toHex(arr);
59412 else
59413 return arr;
59414};
59415
59416},{}],215:[function(require,module,exports){
59417/*
59418object-assign
59419(c) Sindre Sorhus
59420@license MIT
59421*/
59422
59423'use strict';
59424/* eslint-disable no-unused-vars */
59425var getOwnPropertySymbols = Object.getOwnPropertySymbols;
59426var hasOwnProperty = Object.prototype.hasOwnProperty;
59427var propIsEnumerable = Object.prototype.propertyIsEnumerable;
59428
59429function toObject(val) {
59430 if (val === null || val === undefined) {
59431 throw new TypeError('Object.assign cannot be called with null or undefined');
59432 }
59433
59434 return Object(val);
59435}
59436
59437function shouldUseNative() {
59438 try {
59439 if (!Object.assign) {
59440 return false;
59441 }
59442
59443 // Detect buggy property enumeration order in older V8 versions.
59444
59445 // https://bugs.chromium.org/p/v8/issues/detail?id=4118
59446 var test1 = new String('abc'); // eslint-disable-line no-new-wrappers
59447 test1[5] = 'de';
59448 if (Object.getOwnPropertyNames(test1)[0] === '5') {
59449 return false;
59450 }
59451
59452 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
59453 var test2 = {};
59454 for (var i = 0; i < 10; i++) {
59455 test2['_' + String.fromCharCode(i)] = i;
59456 }
59457 var order2 = Object.getOwnPropertyNames(test2).map(function (n) {
59458 return test2[n];
59459 });
59460 if (order2.join('') !== '0123456789') {
59461 return false;
59462 }
59463
59464 // https://bugs.chromium.org/p/v8/issues/detail?id=3056
59465 var test3 = {};
59466 'abcdefghijklmnopqrst'.split('').forEach(function (letter) {
59467 test3[letter] = letter;
59468 });
59469 if (Object.keys(Object.assign({}, test3)).join('') !==
59470 'abcdefghijklmnopqrst') {
59471 return false;
59472 }
59473
59474 return true;
59475 } catch (err) {
59476 // We don't expect any of the above to throw, but better to be safe.
59477 return false;
59478 }
59479}
59480
59481module.exports = shouldUseNative() ? Object.assign : function (target, source) {
59482 var from;
59483 var to = toObject(target);
59484 var symbols;
59485
59486 for (var s = 1; s < arguments.length; s++) {
59487 from = Object(arguments[s]);
59488
59489 for (var key in from) {
59490 if (hasOwnProperty.call(from, key)) {
59491 to[key] = from[key];
59492 }
59493 }
59494
59495 if (getOwnPropertySymbols) {
59496 symbols = getOwnPropertySymbols(from);
59497 for (var i = 0; i < symbols.length; i++) {
59498 if (propIsEnumerable.call(from, symbols[i])) {
59499 to[symbols[i]] = from[symbols[i]];
59500 }
59501 }
59502 }
59503 }
59504
59505 return to;
59506};
59507
59508},{}],216:[function(require,module,exports){
59509module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
59510"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
59511"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
59512"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
59513"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
59514"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
59515"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
59516"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
59517"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
59518"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
59519"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
59520"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
59521}
59522},{}],217:[function(require,module,exports){
59523// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
59524// Fedor, you are amazing.
59525'use strict'
59526
59527var asn1 = require('asn1.js')
59528
59529exports.certificate = require('./certificate')
59530
59531var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
59532 this.seq().obj(
59533 this.key('version').int(),
59534 this.key('modulus').int(),
59535 this.key('publicExponent').int(),
59536 this.key('privateExponent').int(),
59537 this.key('prime1').int(),
59538 this.key('prime2').int(),
59539 this.key('exponent1').int(),
59540 this.key('exponent2').int(),
59541 this.key('coefficient').int()
59542 )
59543})
59544exports.RSAPrivateKey = RSAPrivateKey
59545
59546var RSAPublicKey = asn1.define('RSAPublicKey', function () {
59547 this.seq().obj(
59548 this.key('modulus').int(),
59549 this.key('publicExponent').int()
59550 )
59551})
59552exports.RSAPublicKey = RSAPublicKey
59553
59554var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
59555 this.seq().obj(
59556 this.key('algorithm').use(AlgorithmIdentifier),
59557 this.key('subjectPublicKey').bitstr()
59558 )
59559})
59560exports.PublicKey = PublicKey
59561
59562var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
59563 this.seq().obj(
59564 this.key('algorithm').objid(),
59565 this.key('none').null_().optional(),
59566 this.key('curve').objid().optional(),
59567 this.key('params').seq().obj(
59568 this.key('p').int(),
59569 this.key('q').int(),
59570 this.key('g').int()
59571 ).optional()
59572 )
59573})
59574
59575var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
59576 this.seq().obj(
59577 this.key('version').int(),
59578 this.key('algorithm').use(AlgorithmIdentifier),
59579 this.key('subjectPrivateKey').octstr()
59580 )
59581})
59582exports.PrivateKey = PrivateKeyInfo
59583var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
59584 this.seq().obj(
59585 this.key('algorithm').seq().obj(
59586 this.key('id').objid(),
59587 this.key('decrypt').seq().obj(
59588 this.key('kde').seq().obj(
59589 this.key('id').objid(),
59590 this.key('kdeparams').seq().obj(
59591 this.key('salt').octstr(),
59592 this.key('iters').int()
59593 )
59594 ),
59595 this.key('cipher').seq().obj(
59596 this.key('algo').objid(),
59597 this.key('iv').octstr()
59598 )
59599 )
59600 ),
59601 this.key('subjectPrivateKey').octstr()
59602 )
59603})
59604
59605exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
59606
59607var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
59608 this.seq().obj(
59609 this.key('version').int(),
59610 this.key('p').int(),
59611 this.key('q').int(),
59612 this.key('g').int(),
59613 this.key('pub_key').int(),
59614 this.key('priv_key').int()
59615 )
59616})
59617exports.DSAPrivateKey = DSAPrivateKey
59618
59619exports.DSAparam = asn1.define('DSAparam', function () {
59620 this.int()
59621})
59622
59623var ECPrivateKey = asn1.define('ECPrivateKey', function () {
59624 this.seq().obj(
59625 this.key('version').int(),
59626 this.key('privateKey').octstr(),
59627 this.key('parameters').optional().explicit(0).use(ECParameters),
59628 this.key('publicKey').optional().explicit(1).bitstr()
59629 )
59630})
59631exports.ECPrivateKey = ECPrivateKey
59632
59633var ECParameters = asn1.define('ECParameters', function () {
59634 this.choice({
59635 namedCurve: this.objid()
59636 })
59637})
59638
59639exports.signature = asn1.define('signature', function () {
59640 this.seq().obj(
59641 this.key('r').int(),
59642 this.key('s').int()
59643 )
59644})
59645
59646},{"./certificate":218,"asn1.js":48}],218:[function(require,module,exports){
59647// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
59648// thanks to @Rantanen
59649
59650'use strict'
59651
59652var asn = require('asn1.js')
59653
59654var Time = asn.define('Time', function () {
59655 this.choice({
59656 utcTime: this.utctime(),
59657 generalTime: this.gentime()
59658 })
59659})
59660
59661var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
59662 this.seq().obj(
59663 this.key('type').objid(),
59664 this.key('value').any()
59665 )
59666})
59667
59668var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
59669 this.seq().obj(
59670 this.key('algorithm').objid(),
59671 this.key('parameters').optional(),
59672 this.key('curve').objid().optional()
59673 )
59674})
59675
59676var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
59677 this.seq().obj(
59678 this.key('algorithm').use(AlgorithmIdentifier),
59679 this.key('subjectPublicKey').bitstr()
59680 )
59681})
59682
59683var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
59684 this.setof(AttributeTypeValue)
59685})
59686
59687var RDNSequence = asn.define('RDNSequence', function () {
59688 this.seqof(RelativeDistinguishedName)
59689})
59690
59691var Name = asn.define('Name', function () {
59692 this.choice({
59693 rdnSequence: this.use(RDNSequence)
59694 })
59695})
59696
59697var Validity = asn.define('Validity', function () {
59698 this.seq().obj(
59699 this.key('notBefore').use(Time),
59700 this.key('notAfter').use(Time)
59701 )
59702})
59703
59704var Extension = asn.define('Extension', function () {
59705 this.seq().obj(
59706 this.key('extnID').objid(),
59707 this.key('critical').bool().def(false),
59708 this.key('extnValue').octstr()
59709 )
59710})
59711
59712var TBSCertificate = asn.define('TBSCertificate', function () {
59713 this.seq().obj(
59714 this.key('version').explicit(0).int().optional(),
59715 this.key('serialNumber').int(),
59716 this.key('signature').use(AlgorithmIdentifier),
59717 this.key('issuer').use(Name),
59718 this.key('validity').use(Validity),
59719 this.key('subject').use(Name),
59720 this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
59721 this.key('issuerUniqueID').implicit(1).bitstr().optional(),
59722 this.key('subjectUniqueID').implicit(2).bitstr().optional(),
59723 this.key('extensions').explicit(3).seqof(Extension).optional()
59724 )
59725})
59726
59727var X509Certificate = asn.define('X509Certificate', function () {
59728 this.seq().obj(
59729 this.key('tbsCertificate').use(TBSCertificate),
59730 this.key('signatureAlgorithm').use(AlgorithmIdentifier),
59731 this.key('signatureValue').bitstr()
59732 )
59733})
59734
59735module.exports = X509Certificate
59736
59737},{"asn1.js":48}],219:[function(require,module,exports){
59738// adapted from https://github.com/apatil/pemstrip
59739var findProc = /Proc-Type: 4,ENCRYPTED[\n\r]+DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)[\n\r]+([0-9A-z\n\r+/=]+)[\n\r]+/m
59740var startRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----/m
59741var fullRegex = /^-----BEGIN ((?:.*? KEY)|CERTIFICATE)-----([0-9A-z\n\r+/=]+)-----END \1-----$/m
59742var evp = require('evp_bytestokey')
59743var ciphers = require('browserify-aes')
59744var Buffer = require('safe-buffer').Buffer
59745module.exports = function (okey, password) {
59746 var key = okey.toString()
59747 var match = key.match(findProc)
59748 var decrypted
59749 if (!match) {
59750 var match2 = key.match(fullRegex)
59751 decrypted = Buffer.from(match2[2].replace(/[\r\n]/g, ''), 'base64')
59752 } else {
59753 var suite = 'aes' + match[1]
59754 var iv = Buffer.from(match[2], 'hex')
59755 var cipherText = Buffer.from(match[3].replace(/[\r\n]/g, ''), 'base64')
59756 var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
59757 var out = []
59758 var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
59759 out.push(cipher.update(cipherText))
59760 out.push(cipher.final())
59761 decrypted = Buffer.concat(out)
59762 }
59763 var tag = key.match(startRegex)[1]
59764 return {
59765 tag: tag,
59766 data: decrypted
59767 }
59768}
59769
59770},{"browserify-aes":85,"evp_bytestokey":173,"safe-buffer":256}],220:[function(require,module,exports){
59771var asn1 = require('./asn1')
59772var aesid = require('./aesid.json')
59773var fixProc = require('./fixProc')
59774var ciphers = require('browserify-aes')
59775var compat = require('pbkdf2')
59776var Buffer = require('safe-buffer').Buffer
59777module.exports = parseKeys
59778
59779function parseKeys (buffer) {
59780 var password
59781 if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
59782 password = buffer.passphrase
59783 buffer = buffer.key
59784 }
59785 if (typeof buffer === 'string') {
59786 buffer = Buffer.from(buffer)
59787 }
59788
59789 var stripped = fixProc(buffer, password)
59790
59791 var type = stripped.tag
59792 var data = stripped.data
59793 var subtype, ndata
59794 switch (type) {
59795 case 'CERTIFICATE':
59796 ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
59797 // falls through
59798 case 'PUBLIC KEY':
59799 if (!ndata) {
59800 ndata = asn1.PublicKey.decode(data, 'der')
59801 }
59802 subtype = ndata.algorithm.algorithm.join('.')
59803 switch (subtype) {
59804 case '1.2.840.113549.1.1.1':
59805 return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
59806 case '1.2.840.10045.2.1':
59807 ndata.subjectPrivateKey = ndata.subjectPublicKey
59808 return {
59809 type: 'ec',
59810 data: ndata
59811 }
59812 case '1.2.840.10040.4.1':
59813 ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
59814 return {
59815 type: 'dsa',
59816 data: ndata.algorithm.params
59817 }
59818 default: throw new Error('unknown key id ' + subtype)
59819 }
59820 // throw new Error('unknown key type ' + type)
59821 case 'ENCRYPTED PRIVATE KEY':
59822 data = asn1.EncryptedPrivateKey.decode(data, 'der')
59823 data = decrypt(data, password)
59824 // falls through
59825 case 'PRIVATE KEY':
59826 ndata = asn1.PrivateKey.decode(data, 'der')
59827 subtype = ndata.algorithm.algorithm.join('.')
59828 switch (subtype) {
59829 case '1.2.840.113549.1.1.1':
59830 return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
59831 case '1.2.840.10045.2.1':
59832 return {
59833 curve: ndata.algorithm.curve,
59834 privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
59835 }
59836 case '1.2.840.10040.4.1':
59837 ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
59838 return {
59839 type: 'dsa',
59840 params: ndata.algorithm.params
59841 }
59842 default: throw new Error('unknown key id ' + subtype)
59843 }
59844 // throw new Error('unknown key type ' + type)
59845 case 'RSA PUBLIC KEY':
59846 return asn1.RSAPublicKey.decode(data, 'der')
59847 case 'RSA PRIVATE KEY':
59848 return asn1.RSAPrivateKey.decode(data, 'der')
59849 case 'DSA PRIVATE KEY':
59850 return {
59851 type: 'dsa',
59852 params: asn1.DSAPrivateKey.decode(data, 'der')
59853 }
59854 case 'EC PRIVATE KEY':
59855 data = asn1.ECPrivateKey.decode(data, 'der')
59856 return {
59857 curve: data.parameters.value,
59858 privateKey: data.privateKey
59859 }
59860 default: throw new Error('unknown key type ' + type)
59861 }
59862}
59863parseKeys.signature = asn1.signature
59864function decrypt (data, password) {
59865 var salt = data.algorithm.decrypt.kde.kdeparams.salt
59866 var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
59867 var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
59868 var iv = data.algorithm.decrypt.cipher.iv
59869 var cipherText = data.subjectPrivateKey
59870 var keylen = parseInt(algo.split('-')[1], 10) / 8
59871 var key = compat.pbkdf2Sync(password, salt, iters, keylen, 'sha1')
59872 var cipher = ciphers.createDecipheriv(algo, key, iv)
59873 var out = []
59874 out.push(cipher.update(cipherText))
59875 out.push(cipher.final())
59876 return Buffer.concat(out)
59877}
59878
59879},{"./aesid.json":216,"./asn1":217,"./fixProc":219,"browserify-aes":85,"pbkdf2":221,"safe-buffer":256}],221:[function(require,module,exports){
59880exports.pbkdf2 = require('./lib/async')
59881exports.pbkdf2Sync = require('./lib/sync')
59882
59883},{"./lib/async":222,"./lib/sync":225}],222:[function(require,module,exports){
59884(function (global){(function (){
59885var Buffer = require('safe-buffer').Buffer
59886
59887var checkParameters = require('./precondition')
59888var defaultEncoding = require('./default-encoding')
59889var sync = require('./sync')
59890var toBuffer = require('./to-buffer')
59891
59892var ZERO_BUF
59893var subtle = global.crypto && global.crypto.subtle
59894var toBrowser = {
59895 sha: 'SHA-1',
59896 'sha-1': 'SHA-1',
59897 sha1: 'SHA-1',
59898 sha256: 'SHA-256',
59899 'sha-256': 'SHA-256',
59900 sha384: 'SHA-384',
59901 'sha-384': 'SHA-384',
59902 'sha-512': 'SHA-512',
59903 sha512: 'SHA-512'
59904}
59905var checks = []
59906function checkNative (algo) {
59907 if (global.process && !global.process.browser) {
59908 return Promise.resolve(false)
59909 }
59910 if (!subtle || !subtle.importKey || !subtle.deriveBits) {
59911 return Promise.resolve(false)
59912 }
59913 if (checks[algo] !== undefined) {
59914 return checks[algo]
59915 }
59916 ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
59917 var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
59918 .then(function () {
59919 return true
59920 }).catch(function () {
59921 return false
59922 })
59923 checks[algo] = prom
59924 return prom
59925}
59926var nextTick
59927function getNextTick () {
59928 if (nextTick) {
59929 return nextTick
59930 }
59931 if (global.process && global.process.nextTick) {
59932 nextTick = global.process.nextTick
59933 } else if (global.queueMicrotask) {
59934 nextTick = global.queueMicrotask
59935 } else if (global.setImmediate) {
59936 nextTick = global.setImmediate
59937 } else {
59938 nextTick = global.setTimeout
59939 }
59940 return nextTick
59941}
59942function browserPbkdf2 (password, salt, iterations, length, algo) {
59943 return subtle.importKey(
59944 'raw', password, { name: 'PBKDF2' }, false, ['deriveBits']
59945 ).then(function (key) {
59946 return subtle.deriveBits({
59947 name: 'PBKDF2',
59948 salt: salt,
59949 iterations: iterations,
59950 hash: {
59951 name: algo
59952 }
59953 }, key, length << 3)
59954 }).then(function (res) {
59955 return Buffer.from(res)
59956 })
59957}
59958
59959function resolvePromise (promise, callback) {
59960 promise.then(function (out) {
59961 getNextTick()(function () {
59962 callback(null, out)
59963 })
59964 }, function (e) {
59965 getNextTick()(function () {
59966 callback(e)
59967 })
59968 })
59969}
59970module.exports = function (password, salt, iterations, keylen, digest, callback) {
59971 if (typeof digest === 'function') {
59972 callback = digest
59973 digest = undefined
59974 }
59975
59976 digest = digest || 'sha1'
59977 var algo = toBrowser[digest.toLowerCase()]
59978
59979 if (!algo || typeof global.Promise !== 'function') {
59980 getNextTick()(function () {
59981 var out
59982 try {
59983 out = sync(password, salt, iterations, keylen, digest)
59984 } catch (e) {
59985 return callback(e)
59986 }
59987 callback(null, out)
59988 })
59989 return
59990 }
59991
59992 checkParameters(iterations, keylen)
59993 password = toBuffer(password, defaultEncoding, 'Password')
59994 salt = toBuffer(salt, defaultEncoding, 'Salt')
59995 if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
59996
59997 resolvePromise(checkNative(algo).then(function (resp) {
59998 if (resp) return browserPbkdf2(password, salt, iterations, keylen, algo)
59999
60000 return sync(password, salt, iterations, keylen, digest)
60001 }), callback)
60002}
60003
60004}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
60005},{"./default-encoding":223,"./precondition":224,"./sync":225,"./to-buffer":226,"safe-buffer":256}],223:[function(require,module,exports){
60006(function (process,global){(function (){
60007var defaultEncoding
60008/* istanbul ignore next */
60009if (global.process && global.process.browser) {
60010 defaultEncoding = 'utf-8'
60011} else if (global.process && global.process.version) {
60012 var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
60013
60014 defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
60015} else {
60016 defaultEncoding = 'utf-8'
60017}
60018module.exports = defaultEncoding
60019
60020}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
60021},{"_process":228}],224:[function(require,module,exports){
60022var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
60023
60024module.exports = function (iterations, keylen) {
60025 if (typeof iterations !== 'number') {
60026 throw new TypeError('Iterations not a number')
60027 }
60028
60029 if (iterations < 0) {
60030 throw new TypeError('Bad iterations')
60031 }
60032
60033 if (typeof keylen !== 'number') {
60034 throw new TypeError('Key length not a number')
60035 }
60036
60037 if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
60038 throw new TypeError('Bad key length')
60039 }
60040}
60041
60042},{}],225:[function(require,module,exports){
60043var md5 = require('create-hash/md5')
60044var RIPEMD160 = require('ripemd160')
60045var sha = require('sha.js')
60046var Buffer = require('safe-buffer').Buffer
60047
60048var checkParameters = require('./precondition')
60049var defaultEncoding = require('./default-encoding')
60050var toBuffer = require('./to-buffer')
60051
60052var ZEROS = Buffer.alloc(128)
60053var sizes = {
60054 md5: 16,
60055 sha1: 20,
60056 sha224: 28,
60057 sha256: 32,
60058 sha384: 48,
60059 sha512: 64,
60060 rmd160: 20,
60061 ripemd160: 20
60062}
60063
60064function Hmac (alg, key, saltLen) {
60065 var hash = getDigest(alg)
60066 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
60067
60068 if (key.length > blocksize) {
60069 key = hash(key)
60070 } else if (key.length < blocksize) {
60071 key = Buffer.concat([key, ZEROS], blocksize)
60072 }
60073
60074 var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
60075 var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
60076 for (var i = 0; i < blocksize; i++) {
60077 ipad[i] = key[i] ^ 0x36
60078 opad[i] = key[i] ^ 0x5C
60079 }
60080
60081 var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
60082 ipad.copy(ipad1, 0, 0, blocksize)
60083 this.ipad1 = ipad1
60084 this.ipad2 = ipad
60085 this.opad = opad
60086 this.alg = alg
60087 this.blocksize = blocksize
60088 this.hash = hash
60089 this.size = sizes[alg]
60090}
60091
60092Hmac.prototype.run = function (data, ipad) {
60093 data.copy(ipad, this.blocksize)
60094 var h = this.hash(ipad)
60095 h.copy(this.opad, this.blocksize)
60096 return this.hash(this.opad)
60097}
60098
60099function getDigest (alg) {
60100 function shaFunc (data) {
60101 return sha(alg).update(data).digest()
60102 }
60103 function rmd160Func (data) {
60104 return new RIPEMD160().update(data).digest()
60105 }
60106
60107 if (alg === 'rmd160' || alg === 'ripemd160') return rmd160Func
60108 if (alg === 'md5') return md5
60109 return shaFunc
60110}
60111
60112function pbkdf2 (password, salt, iterations, keylen, digest) {
60113 checkParameters(iterations, keylen)
60114 password = toBuffer(password, defaultEncoding, 'Password')
60115 salt = toBuffer(salt, defaultEncoding, 'Salt')
60116
60117 digest = digest || 'sha1'
60118
60119 var hmac = new Hmac(digest, password, salt.length)
60120
60121 var DK = Buffer.allocUnsafe(keylen)
60122 var block1 = Buffer.allocUnsafe(salt.length + 4)
60123 salt.copy(block1, 0, 0, salt.length)
60124
60125 var destPos = 0
60126 var hLen = sizes[digest]
60127 var l = Math.ceil(keylen / hLen)
60128
60129 for (var i = 1; i <= l; i++) {
60130 block1.writeUInt32BE(i, salt.length)
60131
60132 var T = hmac.run(block1, hmac.ipad1)
60133 var U = T
60134
60135 for (var j = 1; j < iterations; j++) {
60136 U = hmac.run(U, hmac.ipad2)
60137 for (var k = 0; k < hLen; k++) T[k] ^= U[k]
60138 }
60139
60140 T.copy(DK, destPos)
60141 destPos += hLen
60142 }
60143
60144 return DK
60145}
60146
60147module.exports = pbkdf2
60148
60149},{"./default-encoding":223,"./precondition":224,"./to-buffer":226,"create-hash/md5":137,"ripemd160":255,"safe-buffer":256,"sha.js":259}],226:[function(require,module,exports){
60150var Buffer = require('safe-buffer').Buffer
60151
60152module.exports = function (thing, encoding, name) {
60153 if (Buffer.isBuffer(thing)) {
60154 return thing
60155 } else if (typeof thing === 'string') {
60156 return Buffer.from(thing, encoding)
60157 } else if (ArrayBuffer.isView(thing)) {
60158 return Buffer.from(thing.buffer)
60159 } else {
60160 throw new TypeError(name + ' must be a string, a Buffer, a typed array or a DataView')
60161 }
60162}
60163
60164},{"safe-buffer":256}],227:[function(require,module,exports){
60165(function (process){(function (){
60166'use strict';
60167
60168if (typeof process === 'undefined' ||
60169 !process.version ||
60170 process.version.indexOf('v0.') === 0 ||
60171 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
60172 module.exports = { nextTick: nextTick };
60173} else {
60174 module.exports = process
60175}
60176
60177function nextTick(fn, arg1, arg2, arg3) {
60178 if (typeof fn !== 'function') {
60179 throw new TypeError('"callback" argument must be a function');
60180 }
60181 var len = arguments.length;
60182 var args, i;
60183 switch (len) {
60184 case 0:
60185 case 1:
60186 return process.nextTick(fn);
60187 case 2:
60188 return process.nextTick(function afterTickOne() {
60189 fn.call(null, arg1);
60190 });
60191 case 3:
60192 return process.nextTick(function afterTickTwo() {
60193 fn.call(null, arg1, arg2);
60194 });
60195 case 4:
60196 return process.nextTick(function afterTickThree() {
60197 fn.call(null, arg1, arg2, arg3);
60198 });
60199 default:
60200 args = new Array(len - 1);
60201 i = 0;
60202 while (i < args.length) {
60203 args[i++] = arguments[i];
60204 }
60205 return process.nextTick(function afterTick() {
60206 fn.apply(null, args);
60207 });
60208 }
60209}
60210
60211
60212}).call(this)}).call(this,require('_process'))
60213},{"_process":228}],228:[function(require,module,exports){
60214// shim for using process in browser
60215var process = module.exports = {};
60216
60217// cached from whatever global is present so that test runners that stub it
60218// don't break things. But we need to wrap it in a try catch in case it is
60219// wrapped in strict mode code which doesn't define any globals. It's inside a
60220// function because try/catches deoptimize in certain engines.
60221
60222var cachedSetTimeout;
60223var cachedClearTimeout;
60224
60225function defaultSetTimout() {
60226 throw new Error('setTimeout has not been defined');
60227}
60228function defaultClearTimeout () {
60229 throw new Error('clearTimeout has not been defined');
60230}
60231(function () {
60232 try {
60233 if (typeof setTimeout === 'function') {
60234 cachedSetTimeout = setTimeout;
60235 } else {
60236 cachedSetTimeout = defaultSetTimout;
60237 }
60238 } catch (e) {
60239 cachedSetTimeout = defaultSetTimout;
60240 }
60241 try {
60242 if (typeof clearTimeout === 'function') {
60243 cachedClearTimeout = clearTimeout;
60244 } else {
60245 cachedClearTimeout = defaultClearTimeout;
60246 }
60247 } catch (e) {
60248 cachedClearTimeout = defaultClearTimeout;
60249 }
60250} ())
60251function runTimeout(fun) {
60252 if (cachedSetTimeout === setTimeout) {
60253 //normal enviroments in sane situations
60254 return setTimeout(fun, 0);
60255 }
60256 // if setTimeout wasn't available but was latter defined
60257 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
60258 cachedSetTimeout = setTimeout;
60259 return setTimeout(fun, 0);
60260 }
60261 try {
60262 // when when somebody has screwed with setTimeout but no I.E. maddness
60263 return cachedSetTimeout(fun, 0);
60264 } catch(e){
60265 try {
60266 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
60267 return cachedSetTimeout.call(null, fun, 0);
60268 } catch(e){
60269 // 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
60270 return cachedSetTimeout.call(this, fun, 0);
60271 }
60272 }
60273
60274
60275}
60276function runClearTimeout(marker) {
60277 if (cachedClearTimeout === clearTimeout) {
60278 //normal enviroments in sane situations
60279 return clearTimeout(marker);
60280 }
60281 // if clearTimeout wasn't available but was latter defined
60282 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
60283 cachedClearTimeout = clearTimeout;
60284 return clearTimeout(marker);
60285 }
60286 try {
60287 // when when somebody has screwed with setTimeout but no I.E. maddness
60288 return cachedClearTimeout(marker);
60289 } catch (e){
60290 try {
60291 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
60292 return cachedClearTimeout.call(null, marker);
60293 } catch (e){
60294 // 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.
60295 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
60296 return cachedClearTimeout.call(this, marker);
60297 }
60298 }
60299
60300
60301
60302}
60303var queue = [];
60304var draining = false;
60305var currentQueue;
60306var queueIndex = -1;
60307
60308function cleanUpNextTick() {
60309 if (!draining || !currentQueue) {
60310 return;
60311 }
60312 draining = false;
60313 if (currentQueue.length) {
60314 queue = currentQueue.concat(queue);
60315 } else {
60316 queueIndex = -1;
60317 }
60318 if (queue.length) {
60319 drainQueue();
60320 }
60321}
60322
60323function drainQueue() {
60324 if (draining) {
60325 return;
60326 }
60327 var timeout = runTimeout(cleanUpNextTick);
60328 draining = true;
60329
60330 var len = queue.length;
60331 while(len) {
60332 currentQueue = queue;
60333 queue = [];
60334 while (++queueIndex < len) {
60335 if (currentQueue) {
60336 currentQueue[queueIndex].run();
60337 }
60338 }
60339 queueIndex = -1;
60340 len = queue.length;
60341 }
60342 currentQueue = null;
60343 draining = false;
60344 runClearTimeout(timeout);
60345}
60346
60347process.nextTick = function (fun) {
60348 var args = new Array(arguments.length - 1);
60349 if (arguments.length > 1) {
60350 for (var i = 1; i < arguments.length; i++) {
60351 args[i - 1] = arguments[i];
60352 }
60353 }
60354 queue.push(new Item(fun, args));
60355 if (queue.length === 1 && !draining) {
60356 runTimeout(drainQueue);
60357 }
60358};
60359
60360// v8 likes predictible objects
60361function Item(fun, array) {
60362 this.fun = fun;
60363 this.array = array;
60364}
60365Item.prototype.run = function () {
60366 this.fun.apply(null, this.array);
60367};
60368process.title = 'browser';
60369process.browser = true;
60370process.env = {};
60371process.argv = [];
60372process.version = ''; // empty string to avoid regexp issues
60373process.versions = {};
60374
60375function noop() {}
60376
60377process.on = noop;
60378process.addListener = noop;
60379process.once = noop;
60380process.off = noop;
60381process.removeListener = noop;
60382process.removeAllListeners = noop;
60383process.emit = noop;
60384process.prependListener = noop;
60385process.prependOnceListener = noop;
60386
60387process.listeners = function (name) { return [] }
60388
60389process.binding = function (name) {
60390 throw new Error('process.binding is not supported');
60391};
60392
60393process.cwd = function () { return '/' };
60394process.chdir = function (dir) {
60395 throw new Error('process.chdir is not supported');
60396};
60397process.umask = function() { return 0; };
60398
60399},{}],229:[function(require,module,exports){
60400exports.publicEncrypt = require('./publicEncrypt')
60401exports.privateDecrypt = require('./privateDecrypt')
60402
60403exports.privateEncrypt = function privateEncrypt (key, buf) {
60404 return exports.publicEncrypt(key, buf, true)
60405}
60406
60407exports.publicDecrypt = function publicDecrypt (key, buf) {
60408 return exports.privateDecrypt(key, buf, true)
60409}
60410
60411},{"./privateDecrypt":231,"./publicEncrypt":232}],230:[function(require,module,exports){
60412var createHash = require('create-hash')
60413var Buffer = require('safe-buffer').Buffer
60414
60415module.exports = function (seed, len) {
60416 var t = Buffer.alloc(0)
60417 var i = 0
60418 var c
60419 while (t.length < len) {
60420 c = i2ops(i++)
60421 t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()])
60422 }
60423 return t.slice(0, len)
60424}
60425
60426function i2ops (c) {
60427 var out = Buffer.allocUnsafe(4)
60428 out.writeUInt32BE(c, 0)
60429 return out
60430}
60431
60432},{"create-hash":136,"safe-buffer":256}],231:[function(require,module,exports){
60433var parseKeys = require('parse-asn1')
60434var mgf = require('./mgf')
60435var xor = require('./xor')
60436var BN = require('bn.js')
60437var crt = require('browserify-rsa')
60438var createHash = require('create-hash')
60439var withPublic = require('./withPublic')
60440var Buffer = require('safe-buffer').Buffer
60441
60442module.exports = function privateDecrypt (privateKey, enc, reverse) {
60443 var padding
60444 if (privateKey.padding) {
60445 padding = privateKey.padding
60446 } else if (reverse) {
60447 padding = 1
60448 } else {
60449 padding = 4
60450 }
60451
60452 var key = parseKeys(privateKey)
60453 var k = key.modulus.byteLength()
60454 if (enc.length > k || new BN(enc).cmp(key.modulus) >= 0) {
60455 throw new Error('decryption error')
60456 }
60457 var msg
60458 if (reverse) {
60459 msg = withPublic(new BN(enc), key)
60460 } else {
60461 msg = crt(enc, key)
60462 }
60463 var zBuffer = Buffer.alloc(k - msg.length)
60464 msg = Buffer.concat([zBuffer, msg], k)
60465 if (padding === 4) {
60466 return oaep(key, msg)
60467 } else if (padding === 1) {
60468 return pkcs1(key, msg, reverse)
60469 } else if (padding === 3) {
60470 return msg
60471 } else {
60472 throw new Error('unknown padding')
60473 }
60474}
60475
60476function oaep (key, msg) {
60477 var k = key.modulus.byteLength()
60478 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
60479 var hLen = iHash.length
60480 if (msg[0] !== 0) {
60481 throw new Error('decryption error')
60482 }
60483 var maskedSeed = msg.slice(1, hLen + 1)
60484 var maskedDb = msg.slice(hLen + 1)
60485 var seed = xor(maskedSeed, mgf(maskedDb, hLen))
60486 var db = xor(maskedDb, mgf(seed, k - hLen - 1))
60487 if (compare(iHash, db.slice(0, hLen))) {
60488 throw new Error('decryption error')
60489 }
60490 var i = hLen
60491 while (db[i] === 0) {
60492 i++
60493 }
60494 if (db[i++] !== 1) {
60495 throw new Error('decryption error')
60496 }
60497 return db.slice(i)
60498}
60499
60500function pkcs1 (key, msg, reverse) {
60501 var p1 = msg.slice(0, 2)
60502 var i = 2
60503 var status = 0
60504 while (msg[i++] !== 0) {
60505 if (i >= msg.length) {
60506 status++
60507 break
60508 }
60509 }
60510 var ps = msg.slice(2, i - 1)
60511
60512 if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)) {
60513 status++
60514 }
60515 if (ps.length < 8) {
60516 status++
60517 }
60518 if (status) {
60519 throw new Error('decryption error')
60520 }
60521 return msg.slice(i)
60522}
60523function compare (a, b) {
60524 a = Buffer.from(a)
60525 b = Buffer.from(b)
60526 var dif = 0
60527 var len = a.length
60528 if (a.length !== b.length) {
60529 dif++
60530 len = Math.min(a.length, b.length)
60531 }
60532 var i = -1
60533 while (++i < len) {
60534 dif += (a[i] ^ b[i])
60535 }
60536 return dif
60537}
60538
60539},{"./mgf":230,"./withPublic":233,"./xor":234,"bn.js":80,"browserify-rsa":103,"create-hash":136,"parse-asn1":220,"safe-buffer":256}],232:[function(require,module,exports){
60540var parseKeys = require('parse-asn1')
60541var randomBytes = require('randombytes')
60542var createHash = require('create-hash')
60543var mgf = require('./mgf')
60544var xor = require('./xor')
60545var BN = require('bn.js')
60546var withPublic = require('./withPublic')
60547var crt = require('browserify-rsa')
60548var Buffer = require('safe-buffer').Buffer
60549
60550module.exports = function publicEncrypt (publicKey, msg, reverse) {
60551 var padding
60552 if (publicKey.padding) {
60553 padding = publicKey.padding
60554 } else if (reverse) {
60555 padding = 1
60556 } else {
60557 padding = 4
60558 }
60559 var key = parseKeys(publicKey)
60560 var paddedMsg
60561 if (padding === 4) {
60562 paddedMsg = oaep(key, msg)
60563 } else if (padding === 1) {
60564 paddedMsg = pkcs1(key, msg, reverse)
60565 } else if (padding === 3) {
60566 paddedMsg = new BN(msg)
60567 if (paddedMsg.cmp(key.modulus) >= 0) {
60568 throw new Error('data too long for modulus')
60569 }
60570 } else {
60571 throw new Error('unknown padding')
60572 }
60573 if (reverse) {
60574 return crt(paddedMsg, key)
60575 } else {
60576 return withPublic(paddedMsg, key)
60577 }
60578}
60579
60580function oaep (key, msg) {
60581 var k = key.modulus.byteLength()
60582 var mLen = msg.length
60583 var iHash = createHash('sha1').update(Buffer.alloc(0)).digest()
60584 var hLen = iHash.length
60585 var hLen2 = 2 * hLen
60586 if (mLen > k - hLen2 - 2) {
60587 throw new Error('message too long')
60588 }
60589 var ps = Buffer.alloc(k - mLen - hLen2 - 2)
60590 var dblen = k - hLen - 1
60591 var seed = randomBytes(hLen)
60592 var maskedDb = xor(Buffer.concat([iHash, ps, Buffer.alloc(1, 1), msg], dblen), mgf(seed, dblen))
60593 var maskedSeed = xor(seed, mgf(maskedDb, hLen))
60594 return new BN(Buffer.concat([Buffer.alloc(1), maskedSeed, maskedDb], k))
60595}
60596function pkcs1 (key, msg, reverse) {
60597 var mLen = msg.length
60598 var k = key.modulus.byteLength()
60599 if (mLen > k - 11) {
60600 throw new Error('message too long')
60601 }
60602 var ps
60603 if (reverse) {
60604 ps = Buffer.alloc(k - mLen - 3, 0xff)
60605 } else {
60606 ps = nonZero(k - mLen - 3)
60607 }
60608 return new BN(Buffer.concat([Buffer.from([0, reverse ? 1 : 2]), ps, Buffer.alloc(1), msg], k))
60609}
60610function nonZero (len) {
60611 var out = Buffer.allocUnsafe(len)
60612 var i = 0
60613 var cache = randomBytes(len * 2)
60614 var cur = 0
60615 var num
60616 while (i < len) {
60617 if (cur === cache.length) {
60618 cache = randomBytes(len * 2)
60619 cur = 0
60620 }
60621 num = cache[cur++]
60622 if (num) {
60623 out[i++] = num
60624 }
60625 }
60626 return out
60627}
60628
60629},{"./mgf":230,"./withPublic":233,"./xor":234,"bn.js":80,"browserify-rsa":103,"create-hash":136,"parse-asn1":220,"randombytes":238,"safe-buffer":256}],233:[function(require,module,exports){
60630var BN = require('bn.js')
60631var Buffer = require('safe-buffer').Buffer
60632
60633function withPublic (paddedMsg, key) {
60634 return Buffer.from(paddedMsg
60635 .toRed(BN.mont(key.modulus))
60636 .redPow(new BN(key.publicExponent))
60637 .fromRed()
60638 .toArray())
60639}
60640
60641module.exports = withPublic
60642
60643},{"bn.js":80,"safe-buffer":256}],234:[function(require,module,exports){
60644module.exports = function xor (a, b) {
60645 var len = a.length
60646 var i = -1
60647 while (++i < len) {
60648 a[i] ^= b[i]
60649 }
60650 return a
60651}
60652
60653},{}],235:[function(require,module,exports){
60654// Copyright Joyent, Inc. and other Node contributors.
60655//
60656// Permission is hereby granted, free of charge, to any person obtaining a
60657// copy of this software and associated documentation files (the
60658// "Software"), to deal in the Software without restriction, including
60659// without limitation the rights to use, copy, modify, merge, publish,
60660// distribute, sublicense, and/or sell copies of the Software, and to permit
60661// persons to whom the Software is furnished to do so, subject to the
60662// following conditions:
60663//
60664// The above copyright notice and this permission notice shall be included
60665// in all copies or substantial portions of the Software.
60666//
60667// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
60668// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
60669// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
60670// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
60671// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
60672// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
60673// USE OR OTHER DEALINGS IN THE SOFTWARE.
60674
60675'use strict';
60676
60677// If obj.hasOwnProperty has been overridden, then calling
60678// obj.hasOwnProperty(prop) will break.
60679// See: https://github.com/joyent/node/issues/1707
60680function hasOwnProperty(obj, prop) {
60681 return Object.prototype.hasOwnProperty.call(obj, prop);
60682}
60683
60684module.exports = function(qs, sep, eq, options) {
60685 sep = sep || '&';
60686 eq = eq || '=';
60687 var obj = {};
60688
60689 if (typeof qs !== 'string' || qs.length === 0) {
60690 return obj;
60691 }
60692
60693 var regexp = /\+/g;
60694 qs = qs.split(sep);
60695
60696 var maxKeys = 1000;
60697 if (options && typeof options.maxKeys === 'number') {
60698 maxKeys = options.maxKeys;
60699 }
60700
60701 var len = qs.length;
60702 // maxKeys <= 0 means that we should not limit keys count
60703 if (maxKeys > 0 && len > maxKeys) {
60704 len = maxKeys;
60705 }
60706
60707 for (var i = 0; i < len; ++i) {
60708 var x = qs[i].replace(regexp, '%20'),
60709 idx = x.indexOf(eq),
60710 kstr, vstr, k, v;
60711
60712 if (idx >= 0) {
60713 kstr = x.substr(0, idx);
60714 vstr = x.substr(idx + 1);
60715 } else {
60716 kstr = x;
60717 vstr = '';
60718 }
60719
60720 k = decodeURIComponent(kstr);
60721 v = decodeURIComponent(vstr);
60722
60723 if (!hasOwnProperty(obj, k)) {
60724 obj[k] = v;
60725 } else if (isArray(obj[k])) {
60726 obj[k].push(v);
60727 } else {
60728 obj[k] = [obj[k], v];
60729 }
60730 }
60731
60732 return obj;
60733};
60734
60735var isArray = Array.isArray || function (xs) {
60736 return Object.prototype.toString.call(xs) === '[object Array]';
60737};
60738
60739},{}],236:[function(require,module,exports){
60740// Copyright Joyent, Inc. and other Node contributors.
60741//
60742// Permission is hereby granted, free of charge, to any person obtaining a
60743// copy of this software and associated documentation files (the
60744// "Software"), to deal in the Software without restriction, including
60745// without limitation the rights to use, copy, modify, merge, publish,
60746// distribute, sublicense, and/or sell copies of the Software, and to permit
60747// persons to whom the Software is furnished to do so, subject to the
60748// following conditions:
60749//
60750// The above copyright notice and this permission notice shall be included
60751// in all copies or substantial portions of the Software.
60752//
60753// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
60754// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
60755// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
60756// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
60757// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
60758// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
60759// USE OR OTHER DEALINGS IN THE SOFTWARE.
60760
60761'use strict';
60762
60763var stringifyPrimitive = function(v) {
60764 switch (typeof v) {
60765 case 'string':
60766 return v;
60767
60768 case 'boolean':
60769 return v ? 'true' : 'false';
60770
60771 case 'number':
60772 return isFinite(v) ? v : '';
60773
60774 default:
60775 return '';
60776 }
60777};
60778
60779module.exports = function(obj, sep, eq, name) {
60780 sep = sep || '&';
60781 eq = eq || '=';
60782 if (obj === null) {
60783 obj = undefined;
60784 }
60785
60786 if (typeof obj === 'object') {
60787 return map(objectKeys(obj), function(k) {
60788 var ks = encodeURIComponent(stringifyPrimitive(k)) + eq;
60789 if (isArray(obj[k])) {
60790 return map(obj[k], function(v) {
60791 return ks + encodeURIComponent(stringifyPrimitive(v));
60792 }).join(sep);
60793 } else {
60794 return ks + encodeURIComponent(stringifyPrimitive(obj[k]));
60795 }
60796 }).join(sep);
60797
60798 }
60799
60800 if (!name) return '';
60801 return encodeURIComponent(stringifyPrimitive(name)) + eq +
60802 encodeURIComponent(stringifyPrimitive(obj));
60803};
60804
60805var isArray = Array.isArray || function (xs) {
60806 return Object.prototype.toString.call(xs) === '[object Array]';
60807};
60808
60809function map (xs, f) {
60810 if (xs.map) return xs.map(f);
60811 var res = [];
60812 for (var i = 0; i < xs.length; i++) {
60813 res.push(f(xs[i], i));
60814 }
60815 return res;
60816}
60817
60818var objectKeys = Object.keys || function (obj) {
60819 var res = [];
60820 for (var key in obj) {
60821 if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key);
60822 }
60823 return res;
60824};
60825
60826},{}],237:[function(require,module,exports){
60827'use strict';
60828
60829exports.decode = exports.parse = require('./decode');
60830exports.encode = exports.stringify = require('./encode');
60831
60832},{"./decode":235,"./encode":236}],238:[function(require,module,exports){
60833(function (process,global){(function (){
60834'use strict'
60835
60836// limit of Crypto.getRandomValues()
60837// https://developer.mozilla.org/en-US/docs/Web/API/Crypto/getRandomValues
60838var MAX_BYTES = 65536
60839
60840// Node supports requesting up to this number of bytes
60841// https://github.com/nodejs/node/blob/master/lib/internal/crypto/random.js#L48
60842var MAX_UINT32 = 4294967295
60843
60844function oldBrowser () {
60845 throw new Error('Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11')
60846}
60847
60848var Buffer = require('safe-buffer').Buffer
60849var crypto = global.crypto || global.msCrypto
60850
60851if (crypto && crypto.getRandomValues) {
60852 module.exports = randomBytes
60853} else {
60854 module.exports = oldBrowser
60855}
60856
60857function randomBytes (size, cb) {
60858 // phantomjs needs to throw
60859 if (size > MAX_UINT32) throw new RangeError('requested too many random bytes')
60860
60861 var bytes = Buffer.allocUnsafe(size)
60862
60863 if (size > 0) { // getRandomValues fails on IE if size == 0
60864 if (size > MAX_BYTES) { // this is the max bytes crypto.getRandomValues
60865 // can do at once see https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
60866 for (var generated = 0; generated < size; generated += MAX_BYTES) {
60867 // buffer.slice automatically checks if the end is past the end of
60868 // the buffer so we don't have to here
60869 crypto.getRandomValues(bytes.slice(generated, generated + MAX_BYTES))
60870 }
60871 } else {
60872 crypto.getRandomValues(bytes)
60873 }
60874 }
60875
60876 if (typeof cb === 'function') {
60877 return process.nextTick(function () {
60878 cb(null, bytes)
60879 })
60880 }
60881
60882 return bytes
60883}
60884
60885}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
60886},{"_process":228,"safe-buffer":256}],239:[function(require,module,exports){
60887(function (process,global){(function (){
60888'use strict'
60889
60890function oldBrowser () {
60891 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
60892}
60893var safeBuffer = require('safe-buffer')
60894var randombytes = require('randombytes')
60895var Buffer = safeBuffer.Buffer
60896var kBufferMaxLength = safeBuffer.kMaxLength
60897var crypto = global.crypto || global.msCrypto
60898var kMaxUint32 = Math.pow(2, 32) - 1
60899function assertOffset (offset, length) {
60900 if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
60901 throw new TypeError('offset must be a number')
60902 }
60903
60904 if (offset > kMaxUint32 || offset < 0) {
60905 throw new TypeError('offset must be a uint32')
60906 }
60907
60908 if (offset > kBufferMaxLength || offset > length) {
60909 throw new RangeError('offset out of range')
60910 }
60911}
60912
60913function assertSize (size, offset, length) {
60914 if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
60915 throw new TypeError('size must be a number')
60916 }
60917
60918 if (size > kMaxUint32 || size < 0) {
60919 throw new TypeError('size must be a uint32')
60920 }
60921
60922 if (size + offset > length || size > kBufferMaxLength) {
60923 throw new RangeError('buffer too small')
60924 }
60925}
60926if ((crypto && crypto.getRandomValues) || !process.browser) {
60927 exports.randomFill = randomFill
60928 exports.randomFillSync = randomFillSync
60929} else {
60930 exports.randomFill = oldBrowser
60931 exports.randomFillSync = oldBrowser
60932}
60933function randomFill (buf, offset, size, cb) {
60934 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
60935 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
60936 }
60937
60938 if (typeof offset === 'function') {
60939 cb = offset
60940 offset = 0
60941 size = buf.length
60942 } else if (typeof size === 'function') {
60943 cb = size
60944 size = buf.length - offset
60945 } else if (typeof cb !== 'function') {
60946 throw new TypeError('"cb" argument must be a function')
60947 }
60948 assertOffset(offset, buf.length)
60949 assertSize(size, offset, buf.length)
60950 return actualFill(buf, offset, size, cb)
60951}
60952
60953function actualFill (buf, offset, size, cb) {
60954 if (process.browser) {
60955 var ourBuf = buf.buffer
60956 var uint = new Uint8Array(ourBuf, offset, size)
60957 crypto.getRandomValues(uint)
60958 if (cb) {
60959 process.nextTick(function () {
60960 cb(null, buf)
60961 })
60962 return
60963 }
60964 return buf
60965 }
60966 if (cb) {
60967 randombytes(size, function (err, bytes) {
60968 if (err) {
60969 return cb(err)
60970 }
60971 bytes.copy(buf, offset)
60972 cb(null, buf)
60973 })
60974 return
60975 }
60976 var bytes = randombytes(size)
60977 bytes.copy(buf, offset)
60978 return buf
60979}
60980function randomFillSync (buf, offset, size) {
60981 if (typeof offset === 'undefined') {
60982 offset = 0
60983 }
60984 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
60985 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
60986 }
60987
60988 assertOffset(offset, buf.length)
60989
60990 if (size === undefined) size = buf.length - offset
60991
60992 assertSize(size, offset, buf.length)
60993
60994 return actualFill(buf, offset, size)
60995}
60996
60997}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
60998},{"_process":228,"randombytes":238,"safe-buffer":256}],240:[function(require,module,exports){
60999module.exports = require('./lib/_stream_duplex.js');
61000
61001},{"./lib/_stream_duplex.js":241}],241:[function(require,module,exports){
61002// Copyright Joyent, Inc. and other Node contributors.
61003//
61004// Permission is hereby granted, free of charge, to any person obtaining a
61005// copy of this software and associated documentation files (the
61006// "Software"), to deal in the Software without restriction, including
61007// without limitation the rights to use, copy, modify, merge, publish,
61008// distribute, sublicense, and/or sell copies of the Software, and to permit
61009// persons to whom the Software is furnished to do so, subject to the
61010// following conditions:
61011//
61012// The above copyright notice and this permission notice shall be included
61013// in all copies or substantial portions of the Software.
61014//
61015// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
61016// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
61017// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
61018// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
61019// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
61020// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
61021// USE OR OTHER DEALINGS IN THE SOFTWARE.
61022
61023// a duplex stream is just a stream that is both readable and writable.
61024// Since JS doesn't have multiple prototypal inheritance, this class
61025// prototypally inherits from Readable, and then parasitically from
61026// Writable.
61027
61028'use strict';
61029
61030/*<replacement>*/
61031
61032var pna = require('process-nextick-args');
61033/*</replacement>*/
61034
61035/*<replacement>*/
61036var objectKeys = Object.keys || function (obj) {
61037 var keys = [];
61038 for (var key in obj) {
61039 keys.push(key);
61040 }return keys;
61041};
61042/*</replacement>*/
61043
61044module.exports = Duplex;
61045
61046/*<replacement>*/
61047var util = Object.create(require('core-util-is'));
61048util.inherits = require('inherits');
61049/*</replacement>*/
61050
61051var Readable = require('./_stream_readable');
61052var Writable = require('./_stream_writable');
61053
61054util.inherits(Duplex, Readable);
61055
61056{
61057 // avoid scope creep, the keys array can then be collected
61058 var keys = objectKeys(Writable.prototype);
61059 for (var v = 0; v < keys.length; v++) {
61060 var method = keys[v];
61061 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
61062 }
61063}
61064
61065function Duplex(options) {
61066 if (!(this instanceof Duplex)) return new Duplex(options);
61067
61068 Readable.call(this, options);
61069 Writable.call(this, options);
61070
61071 if (options && options.readable === false) this.readable = false;
61072
61073 if (options && options.writable === false) this.writable = false;
61074
61075 this.allowHalfOpen = true;
61076 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
61077
61078 this.once('end', onend);
61079}
61080
61081Object.defineProperty(Duplex.prototype, 'writableHighWaterMark', {
61082 // making it explicit this property is not enumerable
61083 // because otherwise some prototype manipulation in
61084 // userland will fail
61085 enumerable: false,
61086 get: function () {
61087 return this._writableState.highWaterMark;
61088 }
61089});
61090
61091// the no-half-open enforcer
61092function onend() {
61093 // if we allow half-open state, or if the writable side ended,
61094 // then we're ok.
61095 if (this.allowHalfOpen || this._writableState.ended) return;
61096
61097 // no more data can be written.
61098 // But allow more writes to happen in this tick.
61099 pna.nextTick(onEndNT, this);
61100}
61101
61102function onEndNT(self) {
61103 self.end();
61104}
61105
61106Object.defineProperty(Duplex.prototype, 'destroyed', {
61107 get: function () {
61108 if (this._readableState === undefined || this._writableState === undefined) {
61109 return false;
61110 }
61111 return this._readableState.destroyed && this._writableState.destroyed;
61112 },
61113 set: function (value) {
61114 // we ignore the value if the stream
61115 // has not been initialized yet
61116 if (this._readableState === undefined || this._writableState === undefined) {
61117 return;
61118 }
61119
61120 // backward compatibility, the user is explicitly
61121 // managing destroyed
61122 this._readableState.destroyed = value;
61123 this._writableState.destroyed = value;
61124 }
61125});
61126
61127Duplex.prototype._destroy = function (err, cb) {
61128 this.push(null);
61129 this.end();
61130
61131 pna.nextTick(cb, err);
61132};
61133},{"./_stream_readable":243,"./_stream_writable":245,"core-util-is":134,"inherits":249,"process-nextick-args":227}],242:[function(require,module,exports){
61134// Copyright Joyent, Inc. and other Node contributors.
61135//
61136// Permission is hereby granted, free of charge, to any person obtaining a
61137// copy of this software and associated documentation files (the
61138// "Software"), to deal in the Software without restriction, including
61139// without limitation the rights to use, copy, modify, merge, publish,
61140// distribute, sublicense, and/or sell copies of the Software, and to permit
61141// persons to whom the Software is furnished to do so, subject to the
61142// following conditions:
61143//
61144// The above copyright notice and this permission notice shall be included
61145// in all copies or substantial portions of the Software.
61146//
61147// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
61148// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
61149// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
61150// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
61151// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
61152// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
61153// USE OR OTHER DEALINGS IN THE SOFTWARE.
61154
61155// a passthrough stream.
61156// basically just the most minimal sort of Transform stream.
61157// Every written chunk gets output as-is.
61158
61159'use strict';
61160
61161module.exports = PassThrough;
61162
61163var Transform = require('./_stream_transform');
61164
61165/*<replacement>*/
61166var util = Object.create(require('core-util-is'));
61167util.inherits = require('inherits');
61168/*</replacement>*/
61169
61170util.inherits(PassThrough, Transform);
61171
61172function PassThrough(options) {
61173 if (!(this instanceof PassThrough)) return new PassThrough(options);
61174
61175 Transform.call(this, options);
61176}
61177
61178PassThrough.prototype._transform = function (chunk, encoding, cb) {
61179 cb(null, chunk);
61180};
61181},{"./_stream_transform":244,"core-util-is":134,"inherits":249}],243:[function(require,module,exports){
61182(function (process,global){(function (){
61183// Copyright Joyent, Inc. and other Node contributors.
61184//
61185// Permission is hereby granted, free of charge, to any person obtaining a
61186// copy of this software and associated documentation files (the
61187// "Software"), to deal in the Software without restriction, including
61188// without limitation the rights to use, copy, modify, merge, publish,
61189// distribute, sublicense, and/or sell copies of the Software, and to permit
61190// persons to whom the Software is furnished to do so, subject to the
61191// following conditions:
61192//
61193// The above copyright notice and this permission notice shall be included
61194// in all copies or substantial portions of the Software.
61195//
61196// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
61197// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
61198// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
61199// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
61200// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
61201// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
61202// USE OR OTHER DEALINGS IN THE SOFTWARE.
61203
61204'use strict';
61205
61206/*<replacement>*/
61207
61208var pna = require('process-nextick-args');
61209/*</replacement>*/
61210
61211module.exports = Readable;
61212
61213/*<replacement>*/
61214var isArray = require('isarray');
61215/*</replacement>*/
61216
61217/*<replacement>*/
61218var Duplex;
61219/*</replacement>*/
61220
61221Readable.ReadableState = ReadableState;
61222
61223/*<replacement>*/
61224var EE = require('events').EventEmitter;
61225
61226var EElistenerCount = function (emitter, type) {
61227 return emitter.listeners(type).length;
61228};
61229/*</replacement>*/
61230
61231/*<replacement>*/
61232var Stream = require('./internal/streams/stream');
61233/*</replacement>*/
61234
61235/*<replacement>*/
61236
61237var Buffer = require('safe-buffer').Buffer;
61238var OurUint8Array = global.Uint8Array || function () {};
61239function _uint8ArrayToBuffer(chunk) {
61240 return Buffer.from(chunk);
61241}
61242function _isUint8Array(obj) {
61243 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
61244}
61245
61246/*</replacement>*/
61247
61248/*<replacement>*/
61249var util = Object.create(require('core-util-is'));
61250util.inherits = require('inherits');
61251/*</replacement>*/
61252
61253/*<replacement>*/
61254var debugUtil = require('util');
61255var debug = void 0;
61256if (debugUtil && debugUtil.debuglog) {
61257 debug = debugUtil.debuglog('stream');
61258} else {
61259 debug = function () {};
61260}
61261/*</replacement>*/
61262
61263var BufferList = require('./internal/streams/BufferList');
61264var destroyImpl = require('./internal/streams/destroy');
61265var StringDecoder;
61266
61267util.inherits(Readable, Stream);
61268
61269var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
61270
61271function prependListener(emitter, event, fn) {
61272 // Sadly this is not cacheable as some libraries bundle their own
61273 // event emitter implementation with them.
61274 if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn);
61275
61276 // This is a hack to make sure that our error handler is attached before any
61277 // userland ones. NEVER DO THIS. This is here only because this code needs
61278 // to continue to work with older versions of Node.js that do not include
61279 // the prependListener() method. The goal is to eventually remove this hack.
61280 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]];
61281}
61282
61283function ReadableState(options, stream) {
61284 Duplex = Duplex || require('./_stream_duplex');
61285
61286 options = options || {};
61287
61288 // Duplex streams are both readable and writable, but share
61289 // the same options object.
61290 // However, some cases require setting options to different
61291 // values for the readable and the writable sides of the duplex stream.
61292 // These options can be provided separately as readableXXX and writableXXX.
61293 var isDuplex = stream instanceof Duplex;
61294
61295 // object stream flag. Used to make read(n) ignore n and to
61296 // make all the buffer merging and length checks go away
61297 this.objectMode = !!options.objectMode;
61298
61299 if (isDuplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
61300
61301 // the point at which it stops calling _read() to fill the buffer
61302 // Note: 0 is a valid value, means "don't call _read preemptively ever"
61303 var hwm = options.highWaterMark;
61304 var readableHwm = options.readableHighWaterMark;
61305 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
61306
61307 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (readableHwm || readableHwm === 0)) this.highWaterMark = readableHwm;else this.highWaterMark = defaultHwm;
61308
61309 // cast to ints.
61310 this.highWaterMark = Math.floor(this.highWaterMark);
61311
61312 // A linked list is used to store data chunks instead of an array because the
61313 // linked list can remove elements from the beginning faster than
61314 // array.shift()
61315 this.buffer = new BufferList();
61316 this.length = 0;
61317 this.pipes = null;
61318 this.pipesCount = 0;
61319 this.flowing = null;
61320 this.ended = false;
61321 this.endEmitted = false;
61322 this.reading = false;
61323
61324 // a flag to be able to tell if the event 'readable'/'data' is emitted
61325 // immediately, or on a later tick. We set this to true at first, because
61326 // any actions that shouldn't happen until "later" should generally also
61327 // not happen before the first read call.
61328 this.sync = true;
61329
61330 // whenever we return null, then we set a flag to say
61331 // that we're awaiting a 'readable' event emission.
61332 this.needReadable = false;
61333 this.emittedReadable = false;
61334 this.readableListening = false;
61335 this.resumeScheduled = false;
61336
61337 // has it been destroyed
61338 this.destroyed = false;
61339
61340 // Crypto is kind of old and crusty. Historically, its default string
61341 // encoding is 'binary' so we have to make this configurable.
61342 // Everything else in the universe uses 'utf8', though.
61343 this.defaultEncoding = options.defaultEncoding || 'utf8';
61344
61345 // the number of writers that are awaiting a drain event in .pipe()s
61346 this.awaitDrain = 0;
61347
61348 // if true, a maybeReadMore has been scheduled
61349 this.readingMore = false;
61350
61351 this.decoder = null;
61352 this.encoding = null;
61353 if (options.encoding) {
61354 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
61355 this.decoder = new StringDecoder(options.encoding);
61356 this.encoding = options.encoding;
61357 }
61358}
61359
61360function Readable(options) {
61361 Duplex = Duplex || require('./_stream_duplex');
61362
61363 if (!(this instanceof Readable)) return new Readable(options);
61364
61365 this._readableState = new ReadableState(options, this);
61366
61367 // legacy
61368 this.readable = true;
61369
61370 if (options) {
61371 if (typeof options.read === 'function') this._read = options.read;
61372
61373 if (typeof options.destroy === 'function') this._destroy = options.destroy;
61374 }
61375
61376 Stream.call(this);
61377}
61378
61379Object.defineProperty(Readable.prototype, 'destroyed', {
61380 get: function () {
61381 if (this._readableState === undefined) {
61382 return false;
61383 }
61384 return this._readableState.destroyed;
61385 },
61386 set: function (value) {
61387 // we ignore the value if the stream
61388 // has not been initialized yet
61389 if (!this._readableState) {
61390 return;
61391 }
61392
61393 // backward compatibility, the user is explicitly
61394 // managing destroyed
61395 this._readableState.destroyed = value;
61396 }
61397});
61398
61399Readable.prototype.destroy = destroyImpl.destroy;
61400Readable.prototype._undestroy = destroyImpl.undestroy;
61401Readable.prototype._destroy = function (err, cb) {
61402 this.push(null);
61403 cb(err);
61404};
61405
61406// Manually shove something into the read() buffer.
61407// This returns true if the highWaterMark has not been hit yet,
61408// similar to how Writable.write() returns true if you should
61409// write() some more.
61410Readable.prototype.push = function (chunk, encoding) {
61411 var state = this._readableState;
61412 var skipChunkCheck;
61413
61414 if (!state.objectMode) {
61415 if (typeof chunk === 'string') {
61416 encoding = encoding || state.defaultEncoding;
61417 if (encoding !== state.encoding) {
61418 chunk = Buffer.from(chunk, encoding);
61419 encoding = '';
61420 }
61421 skipChunkCheck = true;
61422 }
61423 } else {
61424 skipChunkCheck = true;
61425 }
61426
61427 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
61428};
61429
61430// Unshift should *always* be something directly out of read()
61431Readable.prototype.unshift = function (chunk) {
61432 return readableAddChunk(this, chunk, null, true, false);
61433};
61434
61435function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
61436 var state = stream._readableState;
61437 if (chunk === null) {
61438 state.reading = false;
61439 onEofChunk(stream, state);
61440 } else {
61441 var er;
61442 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
61443 if (er) {
61444 stream.emit('error', er);
61445 } else if (state.objectMode || chunk && chunk.length > 0) {
61446 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
61447 chunk = _uint8ArrayToBuffer(chunk);
61448 }
61449
61450 if (addToFront) {
61451 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
61452 } else if (state.ended) {
61453 stream.emit('error', new Error('stream.push() after EOF'));
61454 } else {
61455 state.reading = false;
61456 if (state.decoder && !encoding) {
61457 chunk = state.decoder.write(chunk);
61458 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
61459 } else {
61460 addChunk(stream, state, chunk, false);
61461 }
61462 }
61463 } else if (!addToFront) {
61464 state.reading = false;
61465 }
61466 }
61467
61468 return needMoreData(state);
61469}
61470
61471function addChunk(stream, state, chunk, addToFront) {
61472 if (state.flowing && state.length === 0 && !state.sync) {
61473 stream.emit('data', chunk);
61474 stream.read(0);
61475 } else {
61476 // update the buffer info.
61477 state.length += state.objectMode ? 1 : chunk.length;
61478 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
61479
61480 if (state.needReadable) emitReadable(stream);
61481 }
61482 maybeReadMore(stream, state);
61483}
61484
61485function chunkInvalid(state, chunk) {
61486 var er;
61487 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
61488 er = new TypeError('Invalid non-string/buffer chunk');
61489 }
61490 return er;
61491}
61492
61493// if it's past the high water mark, we can push in some more.
61494// Also, if we have no data yet, we can stand some
61495// more bytes. This is to work around cases where hwm=0,
61496// such as the repl. Also, if the push() triggered a
61497// readable event, and the user called read(largeNumber) such that
61498// needReadable was set, then we ought to push more, so that another
61499// 'readable' event will be triggered.
61500function needMoreData(state) {
61501 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
61502}
61503
61504Readable.prototype.isPaused = function () {
61505 return this._readableState.flowing === false;
61506};
61507
61508// backwards compatibility.
61509Readable.prototype.setEncoding = function (enc) {
61510 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
61511 this._readableState.decoder = new StringDecoder(enc);
61512 this._readableState.encoding = enc;
61513 return this;
61514};
61515
61516// Don't raise the hwm > 8MB
61517var MAX_HWM = 0x800000;
61518function computeNewHighWaterMark(n) {
61519 if (n >= MAX_HWM) {
61520 n = MAX_HWM;
61521 } else {
61522 // Get the next highest power of 2 to prevent increasing hwm excessively in
61523 // tiny amounts
61524 n--;
61525 n |= n >>> 1;
61526 n |= n >>> 2;
61527 n |= n >>> 4;
61528 n |= n >>> 8;
61529 n |= n >>> 16;
61530 n++;
61531 }
61532 return n;
61533}
61534
61535// This function is designed to be inlinable, so please take care when making
61536// changes to the function body.
61537function howMuchToRead(n, state) {
61538 if (n <= 0 || state.length === 0 && state.ended) return 0;
61539 if (state.objectMode) return 1;
61540 if (n !== n) {
61541 // Only flow one buffer at a time
61542 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
61543 }
61544 // If we're asking for more than the current hwm, then raise the hwm.
61545 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
61546 if (n <= state.length) return n;
61547 // Don't have enough
61548 if (!state.ended) {
61549 state.needReadable = true;
61550 return 0;
61551 }
61552 return state.length;
61553}
61554
61555// you can override either this method, or the async _read(n) below.
61556Readable.prototype.read = function (n) {
61557 debug('read', n);
61558 n = parseInt(n, 10);
61559 var state = this._readableState;
61560 var nOrig = n;
61561
61562 if (n !== 0) state.emittedReadable = false;
61563
61564 // if we're doing read(0) to trigger a readable event, but we
61565 // already have a bunch of data in the buffer, then just trigger
61566 // the 'readable' event and move on.
61567 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
61568 debug('read: emitReadable', state.length, state.ended);
61569 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
61570 return null;
61571 }
61572
61573 n = howMuchToRead(n, state);
61574
61575 // if we've ended, and we're now clear, then finish it up.
61576 if (n === 0 && state.ended) {
61577 if (state.length === 0) endReadable(this);
61578 return null;
61579 }
61580
61581 // All the actual chunk generation logic needs to be
61582 // *below* the call to _read. The reason is that in certain
61583 // synthetic stream cases, such as passthrough streams, _read
61584 // may be a completely synchronous operation which may change
61585 // the state of the read buffer, providing enough data when
61586 // before there was *not* enough.
61587 //
61588 // So, the steps are:
61589 // 1. Figure out what the state of things will be after we do
61590 // a read from the buffer.
61591 //
61592 // 2. If that resulting state will trigger a _read, then call _read.
61593 // Note that this may be asynchronous, or synchronous. Yes, it is
61594 // deeply ugly to write APIs this way, but that still doesn't mean
61595 // that the Readable class should behave improperly, as streams are
61596 // designed to be sync/async agnostic.
61597 // Take note if the _read call is sync or async (ie, if the read call
61598 // has returned yet), so that we know whether or not it's safe to emit
61599 // 'readable' etc.
61600 //
61601 // 3. Actually pull the requested chunks out of the buffer and return.
61602
61603 // if we need a readable event, then we need to do some reading.
61604 var doRead = state.needReadable;
61605 debug('need readable', doRead);
61606
61607 // if we currently have less than the highWaterMark, then also read some
61608 if (state.length === 0 || state.length - n < state.highWaterMark) {
61609 doRead = true;
61610 debug('length less than watermark', doRead);
61611 }
61612
61613 // however, if we've ended, then there's no point, and if we're already
61614 // reading, then it's unnecessary.
61615 if (state.ended || state.reading) {
61616 doRead = false;
61617 debug('reading or ended', doRead);
61618 } else if (doRead) {
61619 debug('do read');
61620 state.reading = true;
61621 state.sync = true;
61622 // if the length is currently zero, then we *need* a readable event.
61623 if (state.length === 0) state.needReadable = true;
61624 // call internal read method
61625 this._read(state.highWaterMark);
61626 state.sync = false;
61627 // If _read pushed data synchronously, then `reading` will be false,
61628 // and we need to re-evaluate how much data we can return to the user.
61629 if (!state.reading) n = howMuchToRead(nOrig, state);
61630 }
61631
61632 var ret;
61633 if (n > 0) ret = fromList(n, state);else ret = null;
61634
61635 if (ret === null) {
61636 state.needReadable = true;
61637 n = 0;
61638 } else {
61639 state.length -= n;
61640 }
61641
61642 if (state.length === 0) {
61643 // If we have nothing in the buffer, then we want to know
61644 // as soon as we *do* get something into the buffer.
61645 if (!state.ended) state.needReadable = true;
61646
61647 // If we tried to read() past the EOF, then emit end on the next tick.
61648 if (nOrig !== n && state.ended) endReadable(this);
61649 }
61650
61651 if (ret !== null) this.emit('data', ret);
61652
61653 return ret;
61654};
61655
61656function onEofChunk(stream, state) {
61657 if (state.ended) return;
61658 if (state.decoder) {
61659 var chunk = state.decoder.end();
61660 if (chunk && chunk.length) {
61661 state.buffer.push(chunk);
61662 state.length += state.objectMode ? 1 : chunk.length;
61663 }
61664 }
61665 state.ended = true;
61666
61667 // emit 'readable' now to make sure it gets picked up.
61668 emitReadable(stream);
61669}
61670
61671// Don't emit readable right away in sync mode, because this can trigger
61672// another read() call => stack overflow. This way, it might trigger
61673// a nextTick recursion warning, but that's not so bad.
61674function emitReadable(stream) {
61675 var state = stream._readableState;
61676 state.needReadable = false;
61677 if (!state.emittedReadable) {
61678 debug('emitReadable', state.flowing);
61679 state.emittedReadable = true;
61680 if (state.sync) pna.nextTick(emitReadable_, stream);else emitReadable_(stream);
61681 }
61682}
61683
61684function emitReadable_(stream) {
61685 debug('emit readable');
61686 stream.emit('readable');
61687 flow(stream);
61688}
61689
61690// at this point, the user has presumably seen the 'readable' event,
61691// and called read() to consume some data. that may have triggered
61692// in turn another _read(n) call, in which case reading = true if
61693// it's in progress.
61694// However, if we're not ended, or reading, and the length < hwm,
61695// then go ahead and try to read some more preemptively.
61696function maybeReadMore(stream, state) {
61697 if (!state.readingMore) {
61698 state.readingMore = true;
61699 pna.nextTick(maybeReadMore_, stream, state);
61700 }
61701}
61702
61703function maybeReadMore_(stream, state) {
61704 var len = state.length;
61705 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
61706 debug('maybeReadMore read 0');
61707 stream.read(0);
61708 if (len === state.length)
61709 // didn't get any data, stop spinning.
61710 break;else len = state.length;
61711 }
61712 state.readingMore = false;
61713}
61714
61715// abstract method. to be overridden in specific implementation classes.
61716// call cb(er, data) where data is <= n in length.
61717// for virtual (non-string, non-buffer) streams, "length" is somewhat
61718// arbitrary, and perhaps not very meaningful.
61719Readable.prototype._read = function (n) {
61720 this.emit('error', new Error('_read() is not implemented'));
61721};
61722
61723Readable.prototype.pipe = function (dest, pipeOpts) {
61724 var src = this;
61725 var state = this._readableState;
61726
61727 switch (state.pipesCount) {
61728 case 0:
61729 state.pipes = dest;
61730 break;
61731 case 1:
61732 state.pipes = [state.pipes, dest];
61733 break;
61734 default:
61735 state.pipes.push(dest);
61736 break;
61737 }
61738 state.pipesCount += 1;
61739 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
61740
61741 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
61742
61743 var endFn = doEnd ? onend : unpipe;
61744 if (state.endEmitted) pna.nextTick(endFn);else src.once('end', endFn);
61745
61746 dest.on('unpipe', onunpipe);
61747 function onunpipe(readable, unpipeInfo) {
61748 debug('onunpipe');
61749 if (readable === src) {
61750 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
61751 unpipeInfo.hasUnpiped = true;
61752 cleanup();
61753 }
61754 }
61755 }
61756
61757 function onend() {
61758 debug('onend');
61759 dest.end();
61760 }
61761
61762 // when the dest drains, it reduces the awaitDrain counter
61763 // on the source. This would be more elegant with a .once()
61764 // handler in flow(), but adding and removing repeatedly is
61765 // too slow.
61766 var ondrain = pipeOnDrain(src);
61767 dest.on('drain', ondrain);
61768
61769 var cleanedUp = false;
61770 function cleanup() {
61771 debug('cleanup');
61772 // cleanup event handlers once the pipe is broken
61773 dest.removeListener('close', onclose);
61774 dest.removeListener('finish', onfinish);
61775 dest.removeListener('drain', ondrain);
61776 dest.removeListener('error', onerror);
61777 dest.removeListener('unpipe', onunpipe);
61778 src.removeListener('end', onend);
61779 src.removeListener('end', unpipe);
61780 src.removeListener('data', ondata);
61781
61782 cleanedUp = true;
61783
61784 // if the reader is waiting for a drain event from this
61785 // specific writer, then it would cause it to never start
61786 // flowing again.
61787 // So, if this is awaiting a drain, then we just call it now.
61788 // If we don't know, then assume that we are waiting for one.
61789 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
61790 }
61791
61792 // If the user pushes more data while we're writing to dest then we'll end up
61793 // in ondata again. However, we only want to increase awaitDrain once because
61794 // dest will only emit one 'drain' event for the multiple writes.
61795 // => Introduce a guard on increasing awaitDrain.
61796 var increasedAwaitDrain = false;
61797 src.on('data', ondata);
61798 function ondata(chunk) {
61799 debug('ondata');
61800 increasedAwaitDrain = false;
61801 var ret = dest.write(chunk);
61802 if (false === ret && !increasedAwaitDrain) {
61803 // If the user unpiped during `dest.write()`, it is possible
61804 // to get stuck in a permanently paused state if that write
61805 // also returned false.
61806 // => Check whether `dest` is still a piping destination.
61807 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
61808 debug('false write response, pause', src._readableState.awaitDrain);
61809 src._readableState.awaitDrain++;
61810 increasedAwaitDrain = true;
61811 }
61812 src.pause();
61813 }
61814 }
61815
61816 // if the dest has an error, then stop piping into it.
61817 // however, don't suppress the throwing behavior for this.
61818 function onerror(er) {
61819 debug('onerror', er);
61820 unpipe();
61821 dest.removeListener('error', onerror);
61822 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
61823 }
61824
61825 // Make sure our error handler is attached before userland ones.
61826 prependListener(dest, 'error', onerror);
61827
61828 // Both close and finish should trigger unpipe, but only once.
61829 function onclose() {
61830 dest.removeListener('finish', onfinish);
61831 unpipe();
61832 }
61833 dest.once('close', onclose);
61834 function onfinish() {
61835 debug('onfinish');
61836 dest.removeListener('close', onclose);
61837 unpipe();
61838 }
61839 dest.once('finish', onfinish);
61840
61841 function unpipe() {
61842 debug('unpipe');
61843 src.unpipe(dest);
61844 }
61845
61846 // tell the dest that it's being piped to
61847 dest.emit('pipe', src);
61848
61849 // start the flow if it hasn't been started already.
61850 if (!state.flowing) {
61851 debug('pipe resume');
61852 src.resume();
61853 }
61854
61855 return dest;
61856};
61857
61858function pipeOnDrain(src) {
61859 return function () {
61860 var state = src._readableState;
61861 debug('pipeOnDrain', state.awaitDrain);
61862 if (state.awaitDrain) state.awaitDrain--;
61863 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
61864 state.flowing = true;
61865 flow(src);
61866 }
61867 };
61868}
61869
61870Readable.prototype.unpipe = function (dest) {
61871 var state = this._readableState;
61872 var unpipeInfo = { hasUnpiped: false };
61873
61874 // if we're not piping anywhere, then do nothing.
61875 if (state.pipesCount === 0) return this;
61876
61877 // just one destination. most common case.
61878 if (state.pipesCount === 1) {
61879 // passed in one, but it's not the right one.
61880 if (dest && dest !== state.pipes) return this;
61881
61882 if (!dest) dest = state.pipes;
61883
61884 // got a match.
61885 state.pipes = null;
61886 state.pipesCount = 0;
61887 state.flowing = false;
61888 if (dest) dest.emit('unpipe', this, unpipeInfo);
61889 return this;
61890 }
61891
61892 // slow case. multiple pipe destinations.
61893
61894 if (!dest) {
61895 // remove all.
61896 var dests = state.pipes;
61897 var len = state.pipesCount;
61898 state.pipes = null;
61899 state.pipesCount = 0;
61900 state.flowing = false;
61901
61902 for (var i = 0; i < len; i++) {
61903 dests[i].emit('unpipe', this, unpipeInfo);
61904 }return this;
61905 }
61906
61907 // try to find the right one.
61908 var index = indexOf(state.pipes, dest);
61909 if (index === -1) return this;
61910
61911 state.pipes.splice(index, 1);
61912 state.pipesCount -= 1;
61913 if (state.pipesCount === 1) state.pipes = state.pipes[0];
61914
61915 dest.emit('unpipe', this, unpipeInfo);
61916
61917 return this;
61918};
61919
61920// set up data events if they are asked for
61921// Ensure readable listeners eventually get something
61922Readable.prototype.on = function (ev, fn) {
61923 var res = Stream.prototype.on.call(this, ev, fn);
61924
61925 if (ev === 'data') {
61926 // Start flowing on next tick if stream isn't explicitly paused
61927 if (this._readableState.flowing !== false) this.resume();
61928 } else if (ev === 'readable') {
61929 var state = this._readableState;
61930 if (!state.endEmitted && !state.readableListening) {
61931 state.readableListening = state.needReadable = true;
61932 state.emittedReadable = false;
61933 if (!state.reading) {
61934 pna.nextTick(nReadingNextTick, this);
61935 } else if (state.length) {
61936 emitReadable(this);
61937 }
61938 }
61939 }
61940
61941 return res;
61942};
61943Readable.prototype.addListener = Readable.prototype.on;
61944
61945function nReadingNextTick(self) {
61946 debug('readable nexttick read 0');
61947 self.read(0);
61948}
61949
61950// pause() and resume() are remnants of the legacy readable stream API
61951// If the user uses them, then switch into old mode.
61952Readable.prototype.resume = function () {
61953 var state = this._readableState;
61954 if (!state.flowing) {
61955 debug('resume');
61956 state.flowing = true;
61957 resume(this, state);
61958 }
61959 return this;
61960};
61961
61962function resume(stream, state) {
61963 if (!state.resumeScheduled) {
61964 state.resumeScheduled = true;
61965 pna.nextTick(resume_, stream, state);
61966 }
61967}
61968
61969function resume_(stream, state) {
61970 if (!state.reading) {
61971 debug('resume read 0');
61972 stream.read(0);
61973 }
61974
61975 state.resumeScheduled = false;
61976 state.awaitDrain = 0;
61977 stream.emit('resume');
61978 flow(stream);
61979 if (state.flowing && !state.reading) stream.read(0);
61980}
61981
61982Readable.prototype.pause = function () {
61983 debug('call pause flowing=%j', this._readableState.flowing);
61984 if (false !== this._readableState.flowing) {
61985 debug('pause');
61986 this._readableState.flowing = false;
61987 this.emit('pause');
61988 }
61989 return this;
61990};
61991
61992function flow(stream) {
61993 var state = stream._readableState;
61994 debug('flow', state.flowing);
61995 while (state.flowing && stream.read() !== null) {}
61996}
61997
61998// wrap an old-style stream as the async data source.
61999// This is *not* part of the readable stream interface.
62000// It is an ugly unfortunate mess of history.
62001Readable.prototype.wrap = function (stream) {
62002 var _this = this;
62003
62004 var state = this._readableState;
62005 var paused = false;
62006
62007 stream.on('end', function () {
62008 debug('wrapped end');
62009 if (state.decoder && !state.ended) {
62010 var chunk = state.decoder.end();
62011 if (chunk && chunk.length) _this.push(chunk);
62012 }
62013
62014 _this.push(null);
62015 });
62016
62017 stream.on('data', function (chunk) {
62018 debug('wrapped data');
62019 if (state.decoder) chunk = state.decoder.write(chunk);
62020
62021 // don't skip over falsy values in objectMode
62022 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
62023
62024 var ret = _this.push(chunk);
62025 if (!ret) {
62026 paused = true;
62027 stream.pause();
62028 }
62029 });
62030
62031 // proxy all the other methods.
62032 // important when wrapping filters and duplexes.
62033 for (var i in stream) {
62034 if (this[i] === undefined && typeof stream[i] === 'function') {
62035 this[i] = function (method) {
62036 return function () {
62037 return stream[method].apply(stream, arguments);
62038 };
62039 }(i);
62040 }
62041 }
62042
62043 // proxy certain important events.
62044 for (var n = 0; n < kProxyEvents.length; n++) {
62045 stream.on(kProxyEvents[n], this.emit.bind(this, kProxyEvents[n]));
62046 }
62047
62048 // when we try to consume some more bytes, simply unpause the
62049 // underlying stream.
62050 this._read = function (n) {
62051 debug('wrapped _read', n);
62052 if (paused) {
62053 paused = false;
62054 stream.resume();
62055 }
62056 };
62057
62058 return this;
62059};
62060
62061Object.defineProperty(Readable.prototype, 'readableHighWaterMark', {
62062 // making it explicit this property is not enumerable
62063 // because otherwise some prototype manipulation in
62064 // userland will fail
62065 enumerable: false,
62066 get: function () {
62067 return this._readableState.highWaterMark;
62068 }
62069});
62070
62071// exposed for testing purposes only.
62072Readable._fromList = fromList;
62073
62074// Pluck off n bytes from an array of buffers.
62075// Length is the combined lengths of all the buffers in the list.
62076// This function is designed to be inlinable, so please take care when making
62077// changes to the function body.
62078function fromList(n, state) {
62079 // nothing buffered
62080 if (state.length === 0) return null;
62081
62082 var ret;
62083 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
62084 // read it all, truncate the list
62085 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);
62086 state.buffer.clear();
62087 } else {
62088 // read part of list
62089 ret = fromListPartial(n, state.buffer, state.decoder);
62090 }
62091
62092 return ret;
62093}
62094
62095// Extracts only enough buffered data to satisfy the amount requested.
62096// This function is designed to be inlinable, so please take care when making
62097// changes to the function body.
62098function fromListPartial(n, list, hasStrings) {
62099 var ret;
62100 if (n < list.head.data.length) {
62101 // slice is the same for buffers and strings
62102 ret = list.head.data.slice(0, n);
62103 list.head.data = list.head.data.slice(n);
62104 } else if (n === list.head.data.length) {
62105 // first chunk is a perfect match
62106 ret = list.shift();
62107 } else {
62108 // result spans more than one buffer
62109 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
62110 }
62111 return ret;
62112}
62113
62114// Copies a specified amount of characters from the list of buffered data
62115// chunks.
62116// This function is designed to be inlinable, so please take care when making
62117// changes to the function body.
62118function copyFromBufferString(n, list) {
62119 var p = list.head;
62120 var c = 1;
62121 var ret = p.data;
62122 n -= ret.length;
62123 while (p = p.next) {
62124 var str = p.data;
62125 var nb = n > str.length ? str.length : n;
62126 if (nb === str.length) ret += str;else ret += str.slice(0, n);
62127 n -= nb;
62128 if (n === 0) {
62129 if (nb === str.length) {
62130 ++c;
62131 if (p.next) list.head = p.next;else list.head = list.tail = null;
62132 } else {
62133 list.head = p;
62134 p.data = str.slice(nb);
62135 }
62136 break;
62137 }
62138 ++c;
62139 }
62140 list.length -= c;
62141 return ret;
62142}
62143
62144// Copies a specified amount of bytes from the list of buffered data chunks.
62145// This function is designed to be inlinable, so please take care when making
62146// changes to the function body.
62147function copyFromBuffer(n, list) {
62148 var ret = Buffer.allocUnsafe(n);
62149 var p = list.head;
62150 var c = 1;
62151 p.data.copy(ret);
62152 n -= p.data.length;
62153 while (p = p.next) {
62154 var buf = p.data;
62155 var nb = n > buf.length ? buf.length : n;
62156 buf.copy(ret, ret.length - n, 0, nb);
62157 n -= nb;
62158 if (n === 0) {
62159 if (nb === buf.length) {
62160 ++c;
62161 if (p.next) list.head = p.next;else list.head = list.tail = null;
62162 } else {
62163 list.head = p;
62164 p.data = buf.slice(nb);
62165 }
62166 break;
62167 }
62168 ++c;
62169 }
62170 list.length -= c;
62171 return ret;
62172}
62173
62174function endReadable(stream) {
62175 var state = stream._readableState;
62176
62177 // If we get here before consuming all the bytes, then that is a
62178 // bug in node. Should never happen.
62179 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
62180
62181 if (!state.endEmitted) {
62182 state.ended = true;
62183 pna.nextTick(endReadableNT, state, stream);
62184 }
62185}
62186
62187function endReadableNT(state, stream) {
62188 // Check that we didn't get one last unshift.
62189 if (!state.endEmitted && state.length === 0) {
62190 state.endEmitted = true;
62191 stream.readable = false;
62192 stream.emit('end');
62193 }
62194}
62195
62196function indexOf(xs, x) {
62197 for (var i = 0, l = xs.length; i < l; i++) {
62198 if (xs[i] === x) return i;
62199 }
62200 return -1;
62201}
62202}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
62203},{"./_stream_duplex":241,"./internal/streams/BufferList":246,"./internal/streams/destroy":247,"./internal/streams/stream":248,"_process":228,"core-util-is":134,"events":172,"inherits":249,"isarray":208,"process-nextick-args":227,"safe-buffer":250,"string_decoder/":267,"util":82}],244:[function(require,module,exports){
62204// Copyright Joyent, Inc. and other Node contributors.
62205//
62206// Permission is hereby granted, free of charge, to any person obtaining a
62207// copy of this software and associated documentation files (the
62208// "Software"), to deal in the Software without restriction, including
62209// without limitation the rights to use, copy, modify, merge, publish,
62210// distribute, sublicense, and/or sell copies of the Software, and to permit
62211// persons to whom the Software is furnished to do so, subject to the
62212// following conditions:
62213//
62214// The above copyright notice and this permission notice shall be included
62215// in all copies or substantial portions of the Software.
62216//
62217// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
62218// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
62219// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
62220// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
62221// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
62222// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
62223// USE OR OTHER DEALINGS IN THE SOFTWARE.
62224
62225// a transform stream is a readable/writable stream where you do
62226// something with the data. Sometimes it's called a "filter",
62227// but that's not a great name for it, since that implies a thing where
62228// some bits pass through, and others are simply ignored. (That would
62229// be a valid example of a transform, of course.)
62230//
62231// While the output is causally related to the input, it's not a
62232// necessarily symmetric or synchronous transformation. For example,
62233// a zlib stream might take multiple plain-text writes(), and then
62234// emit a single compressed chunk some time in the future.
62235//
62236// Here's how this works:
62237//
62238// The Transform stream has all the aspects of the readable and writable
62239// stream classes. When you write(chunk), that calls _write(chunk,cb)
62240// internally, and returns false if there's a lot of pending writes
62241// buffered up. When you call read(), that calls _read(n) until
62242// there's enough pending readable data buffered up.
62243//
62244// In a transform stream, the written data is placed in a buffer. When
62245// _read(n) is called, it transforms the queued up data, calling the
62246// buffered _write cb's as it consumes chunks. If consuming a single
62247// written chunk would result in multiple output chunks, then the first
62248// outputted bit calls the readcb, and subsequent chunks just go into
62249// the read buffer, and will cause it to emit 'readable' if necessary.
62250//
62251// This way, back-pressure is actually determined by the reading side,
62252// since _read has to be called to start processing a new chunk. However,
62253// a pathological inflate type of transform can cause excessive buffering
62254// here. For example, imagine a stream where every byte of input is
62255// interpreted as an integer from 0-255, and then results in that many
62256// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
62257// 1kb of data being output. In this case, you could write a very small
62258// amount of input, and end up with a very large amount of output. In
62259// such a pathological inflating mechanism, there'd be no way to tell
62260// the system to stop doing the transform. A single 4MB write could
62261// cause the system to run out of memory.
62262//
62263// However, even in such a pathological case, only a single written chunk
62264// would be consumed, and then the rest would wait (un-transformed) until
62265// the results of the previous transformed chunk were consumed.
62266
62267'use strict';
62268
62269module.exports = Transform;
62270
62271var Duplex = require('./_stream_duplex');
62272
62273/*<replacement>*/
62274var util = Object.create(require('core-util-is'));
62275util.inherits = require('inherits');
62276/*</replacement>*/
62277
62278util.inherits(Transform, Duplex);
62279
62280function afterTransform(er, data) {
62281 var ts = this._transformState;
62282 ts.transforming = false;
62283
62284 var cb = ts.writecb;
62285
62286 if (!cb) {
62287 return this.emit('error', new Error('write callback called multiple times'));
62288 }
62289
62290 ts.writechunk = null;
62291 ts.writecb = null;
62292
62293 if (data != null) // single equals check for both `null` and `undefined`
62294 this.push(data);
62295
62296 cb(er);
62297
62298 var rs = this._readableState;
62299 rs.reading = false;
62300 if (rs.needReadable || rs.length < rs.highWaterMark) {
62301 this._read(rs.highWaterMark);
62302 }
62303}
62304
62305function Transform(options) {
62306 if (!(this instanceof Transform)) return new Transform(options);
62307
62308 Duplex.call(this, options);
62309
62310 this._transformState = {
62311 afterTransform: afterTransform.bind(this),
62312 needTransform: false,
62313 transforming: false,
62314 writecb: null,
62315 writechunk: null,
62316 writeencoding: null
62317 };
62318
62319 // start out asking for a readable event once data is transformed.
62320 this._readableState.needReadable = true;
62321
62322 // we have implemented the _read method, and done the other things
62323 // that Readable wants before the first _read call, so unset the
62324 // sync guard flag.
62325 this._readableState.sync = false;
62326
62327 if (options) {
62328 if (typeof options.transform === 'function') this._transform = options.transform;
62329
62330 if (typeof options.flush === 'function') this._flush = options.flush;
62331 }
62332
62333 // When the writable side finishes, then flush out anything remaining.
62334 this.on('prefinish', prefinish);
62335}
62336
62337function prefinish() {
62338 var _this = this;
62339
62340 if (typeof this._flush === 'function') {
62341 this._flush(function (er, data) {
62342 done(_this, er, data);
62343 });
62344 } else {
62345 done(this, null, null);
62346 }
62347}
62348
62349Transform.prototype.push = function (chunk, encoding) {
62350 this._transformState.needTransform = false;
62351 return Duplex.prototype.push.call(this, chunk, encoding);
62352};
62353
62354// This is the part where you do stuff!
62355// override this function in implementation classes.
62356// 'chunk' is an input chunk.
62357//
62358// Call `push(newChunk)` to pass along transformed output
62359// to the readable side. You may call 'push' zero or more times.
62360//
62361// Call `cb(err)` when you are done with this chunk. If you pass
62362// an error, then that'll put the hurt on the whole operation. If you
62363// never call cb(), then you'll never get another chunk.
62364Transform.prototype._transform = function (chunk, encoding, cb) {
62365 throw new Error('_transform() is not implemented');
62366};
62367
62368Transform.prototype._write = function (chunk, encoding, cb) {
62369 var ts = this._transformState;
62370 ts.writecb = cb;
62371 ts.writechunk = chunk;
62372 ts.writeencoding = encoding;
62373 if (!ts.transforming) {
62374 var rs = this._readableState;
62375 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
62376 }
62377};
62378
62379// Doesn't matter what the args are here.
62380// _transform does all the work.
62381// That we got here means that the readable side wants more data.
62382Transform.prototype._read = function (n) {
62383 var ts = this._transformState;
62384
62385 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
62386 ts.transforming = true;
62387 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
62388 } else {
62389 // mark that we need a transform, so that any data that comes in
62390 // will get processed, now that we've asked for it.
62391 ts.needTransform = true;
62392 }
62393};
62394
62395Transform.prototype._destroy = function (err, cb) {
62396 var _this2 = this;
62397
62398 Duplex.prototype._destroy.call(this, err, function (err2) {
62399 cb(err2);
62400 _this2.emit('close');
62401 });
62402};
62403
62404function done(stream, er, data) {
62405 if (er) return stream.emit('error', er);
62406
62407 if (data != null) // single equals check for both `null` and `undefined`
62408 stream.push(data);
62409
62410 // if there's nothing in the write buffer, then that means
62411 // that nothing more will ever be provided
62412 if (stream._writableState.length) throw new Error('Calling transform done when ws.length != 0');
62413
62414 if (stream._transformState.transforming) throw new Error('Calling transform done when still transforming');
62415
62416 return stream.push(null);
62417}
62418},{"./_stream_duplex":241,"core-util-is":134,"inherits":249}],245:[function(require,module,exports){
62419(function (process,global,setImmediate){(function (){
62420// Copyright Joyent, Inc. and other Node contributors.
62421//
62422// Permission is hereby granted, free of charge, to any person obtaining a
62423// copy of this software and associated documentation files (the
62424// "Software"), to deal in the Software without restriction, including
62425// without limitation the rights to use, copy, modify, merge, publish,
62426// distribute, sublicense, and/or sell copies of the Software, and to permit
62427// persons to whom the Software is furnished to do so, subject to the
62428// following conditions:
62429//
62430// The above copyright notice and this permission notice shall be included
62431// in all copies or substantial portions of the Software.
62432//
62433// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
62434// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
62435// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
62436// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
62437// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
62438// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
62439// USE OR OTHER DEALINGS IN THE SOFTWARE.
62440
62441// A bit simpler than readable streams.
62442// Implement an async ._write(chunk, encoding, cb), and it'll handle all
62443// the drain event emission and buffering.
62444
62445'use strict';
62446
62447/*<replacement>*/
62448
62449var pna = require('process-nextick-args');
62450/*</replacement>*/
62451
62452module.exports = Writable;
62453
62454/* <replacement> */
62455function WriteReq(chunk, encoding, cb) {
62456 this.chunk = chunk;
62457 this.encoding = encoding;
62458 this.callback = cb;
62459 this.next = null;
62460}
62461
62462// It seems a linked list but it is not
62463// there will be only 2 of these for each stream
62464function CorkedRequest(state) {
62465 var _this = this;
62466
62467 this.next = null;
62468 this.entry = null;
62469 this.finish = function () {
62470 onCorkedFinish(_this, state);
62471 };
62472}
62473/* </replacement> */
62474
62475/*<replacement>*/
62476var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : pna.nextTick;
62477/*</replacement>*/
62478
62479/*<replacement>*/
62480var Duplex;
62481/*</replacement>*/
62482
62483Writable.WritableState = WritableState;
62484
62485/*<replacement>*/
62486var util = Object.create(require('core-util-is'));
62487util.inherits = require('inherits');
62488/*</replacement>*/
62489
62490/*<replacement>*/
62491var internalUtil = {
62492 deprecate: require('util-deprecate')
62493};
62494/*</replacement>*/
62495
62496/*<replacement>*/
62497var Stream = require('./internal/streams/stream');
62498/*</replacement>*/
62499
62500/*<replacement>*/
62501
62502var Buffer = require('safe-buffer').Buffer;
62503var OurUint8Array = global.Uint8Array || function () {};
62504function _uint8ArrayToBuffer(chunk) {
62505 return Buffer.from(chunk);
62506}
62507function _isUint8Array(obj) {
62508 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
62509}
62510
62511/*</replacement>*/
62512
62513var destroyImpl = require('./internal/streams/destroy');
62514
62515util.inherits(Writable, Stream);
62516
62517function nop() {}
62518
62519function WritableState(options, stream) {
62520 Duplex = Duplex || require('./_stream_duplex');
62521
62522 options = options || {};
62523
62524 // Duplex streams are both readable and writable, but share
62525 // the same options object.
62526 // However, some cases require setting options to different
62527 // values for the readable and the writable sides of the duplex stream.
62528 // These options can be provided separately as readableXXX and writableXXX.
62529 var isDuplex = stream instanceof Duplex;
62530
62531 // object stream flag to indicate whether or not this stream
62532 // contains buffers or objects.
62533 this.objectMode = !!options.objectMode;
62534
62535 if (isDuplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
62536
62537 // the point at which write() starts returning false
62538 // Note: 0 is a valid value, means that we always return false if
62539 // the entire buffer is not flushed immediately on write()
62540 var hwm = options.highWaterMark;
62541 var writableHwm = options.writableHighWaterMark;
62542 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
62543
62544 if (hwm || hwm === 0) this.highWaterMark = hwm;else if (isDuplex && (writableHwm || writableHwm === 0)) this.highWaterMark = writableHwm;else this.highWaterMark = defaultHwm;
62545
62546 // cast to ints.
62547 this.highWaterMark = Math.floor(this.highWaterMark);
62548
62549 // if _final has been called
62550 this.finalCalled = false;
62551
62552 // drain event flag.
62553 this.needDrain = false;
62554 // at the start of calling end()
62555 this.ending = false;
62556 // when end() has been called, and returned
62557 this.ended = false;
62558 // when 'finish' is emitted
62559 this.finished = false;
62560
62561 // has it been destroyed
62562 this.destroyed = false;
62563
62564 // should we decode strings into buffers before passing to _write?
62565 // this is here so that some node-core streams can optimize string
62566 // handling at a lower level.
62567 var noDecode = options.decodeStrings === false;
62568 this.decodeStrings = !noDecode;
62569
62570 // Crypto is kind of old and crusty. Historically, its default string
62571 // encoding is 'binary' so we have to make this configurable.
62572 // Everything else in the universe uses 'utf8', though.
62573 this.defaultEncoding = options.defaultEncoding || 'utf8';
62574
62575 // not an actual buffer we keep track of, but a measurement
62576 // of how much we're waiting to get pushed to some underlying
62577 // socket or file.
62578 this.length = 0;
62579
62580 // a flag to see when we're in the middle of a write.
62581 this.writing = false;
62582
62583 // when true all writes will be buffered until .uncork() call
62584 this.corked = 0;
62585
62586 // a flag to be able to tell if the onwrite cb is called immediately,
62587 // or on a later tick. We set this to true at first, because any
62588 // actions that shouldn't happen until "later" should generally also
62589 // not happen before the first write call.
62590 this.sync = true;
62591
62592 // a flag to know if we're processing previously buffered items, which
62593 // may call the _write() callback in the same tick, so that we don't
62594 // end up in an overlapped onwrite situation.
62595 this.bufferProcessing = false;
62596
62597 // the callback that's passed to _write(chunk,cb)
62598 this.onwrite = function (er) {
62599 onwrite(stream, er);
62600 };
62601
62602 // the callback that the user supplies to write(chunk,encoding,cb)
62603 this.writecb = null;
62604
62605 // the amount that is being written when _write is called.
62606 this.writelen = 0;
62607
62608 this.bufferedRequest = null;
62609 this.lastBufferedRequest = null;
62610
62611 // number of pending user-supplied write callbacks
62612 // this must be 0 before 'finish' can be emitted
62613 this.pendingcb = 0;
62614
62615 // emit prefinish if the only thing we're waiting for is _write cbs
62616 // This is relevant for synchronous Transform streams
62617 this.prefinished = false;
62618
62619 // True if the error was already emitted and should not be thrown again
62620 this.errorEmitted = false;
62621
62622 // count buffered requests
62623 this.bufferedRequestCount = 0;
62624
62625 // allocate the first CorkedRequest, there is always
62626 // one allocated and free to use, and we maintain at most two
62627 this.corkedRequestsFree = new CorkedRequest(this);
62628}
62629
62630WritableState.prototype.getBuffer = function getBuffer() {
62631 var current = this.bufferedRequest;
62632 var out = [];
62633 while (current) {
62634 out.push(current);
62635 current = current.next;
62636 }
62637 return out;
62638};
62639
62640(function () {
62641 try {
62642 Object.defineProperty(WritableState.prototype, 'buffer', {
62643 get: internalUtil.deprecate(function () {
62644 return this.getBuffer();
62645 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
62646 });
62647 } catch (_) {}
62648})();
62649
62650// Test _writableState for inheritance to account for Duplex streams,
62651// whose prototype chain only points to Readable.
62652var realHasInstance;
62653if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
62654 realHasInstance = Function.prototype[Symbol.hasInstance];
62655 Object.defineProperty(Writable, Symbol.hasInstance, {
62656 value: function (object) {
62657 if (realHasInstance.call(this, object)) return true;
62658 if (this !== Writable) return false;
62659
62660 return object && object._writableState instanceof WritableState;
62661 }
62662 });
62663} else {
62664 realHasInstance = function (object) {
62665 return object instanceof this;
62666 };
62667}
62668
62669function Writable(options) {
62670 Duplex = Duplex || require('./_stream_duplex');
62671
62672 // Writable ctor is applied to Duplexes, too.
62673 // `realHasInstance` is necessary because using plain `instanceof`
62674 // would return false, as no `_writableState` property is attached.
62675
62676 // Trying to use the custom `instanceof` for Writable here will also break the
62677 // Node.js LazyTransform implementation, which has a non-trivial getter for
62678 // `_writableState` that would lead to infinite recursion.
62679 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
62680 return new Writable(options);
62681 }
62682
62683 this._writableState = new WritableState(options, this);
62684
62685 // legacy.
62686 this.writable = true;
62687
62688 if (options) {
62689 if (typeof options.write === 'function') this._write = options.write;
62690
62691 if (typeof options.writev === 'function') this._writev = options.writev;
62692
62693 if (typeof options.destroy === 'function') this._destroy = options.destroy;
62694
62695 if (typeof options.final === 'function') this._final = options.final;
62696 }
62697
62698 Stream.call(this);
62699}
62700
62701// Otherwise people can pipe Writable streams, which is just wrong.
62702Writable.prototype.pipe = function () {
62703 this.emit('error', new Error('Cannot pipe, not readable'));
62704};
62705
62706function writeAfterEnd(stream, cb) {
62707 var er = new Error('write after end');
62708 // TODO: defer error events consistently everywhere, not just the cb
62709 stream.emit('error', er);
62710 pna.nextTick(cb, er);
62711}
62712
62713// Checks that a user-supplied chunk is valid, especially for the particular
62714// mode the stream is in. Currently this means that `null` is never accepted
62715// and undefined/non-string values are only allowed in object mode.
62716function validChunk(stream, state, chunk, cb) {
62717 var valid = true;
62718 var er = false;
62719
62720 if (chunk === null) {
62721 er = new TypeError('May not write null values to stream');
62722 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
62723 er = new TypeError('Invalid non-string/buffer chunk');
62724 }
62725 if (er) {
62726 stream.emit('error', er);
62727 pna.nextTick(cb, er);
62728 valid = false;
62729 }
62730 return valid;
62731}
62732
62733Writable.prototype.write = function (chunk, encoding, cb) {
62734 var state = this._writableState;
62735 var ret = false;
62736 var isBuf = !state.objectMode && _isUint8Array(chunk);
62737
62738 if (isBuf && !Buffer.isBuffer(chunk)) {
62739 chunk = _uint8ArrayToBuffer(chunk);
62740 }
62741
62742 if (typeof encoding === 'function') {
62743 cb = encoding;
62744 encoding = null;
62745 }
62746
62747 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
62748
62749 if (typeof cb !== 'function') cb = nop;
62750
62751 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
62752 state.pendingcb++;
62753 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
62754 }
62755
62756 return ret;
62757};
62758
62759Writable.prototype.cork = function () {
62760 var state = this._writableState;
62761
62762 state.corked++;
62763};
62764
62765Writable.prototype.uncork = function () {
62766 var state = this._writableState;
62767
62768 if (state.corked) {
62769 state.corked--;
62770
62771 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
62772 }
62773};
62774
62775Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
62776 // node::ParseEncoding() requires lower case.
62777 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
62778 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);
62779 this._writableState.defaultEncoding = encoding;
62780 return this;
62781};
62782
62783function decodeChunk(state, chunk, encoding) {
62784 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
62785 chunk = Buffer.from(chunk, encoding);
62786 }
62787 return chunk;
62788}
62789
62790Object.defineProperty(Writable.prototype, 'writableHighWaterMark', {
62791 // making it explicit this property is not enumerable
62792 // because otherwise some prototype manipulation in
62793 // userland will fail
62794 enumerable: false,
62795 get: function () {
62796 return this._writableState.highWaterMark;
62797 }
62798});
62799
62800// if we're already writing something, then just put this
62801// in the queue, and wait our turn. Otherwise, call _write
62802// If we return false, then we need a drain event, so set that flag.
62803function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
62804 if (!isBuf) {
62805 var newChunk = decodeChunk(state, chunk, encoding);
62806 if (chunk !== newChunk) {
62807 isBuf = true;
62808 encoding = 'buffer';
62809 chunk = newChunk;
62810 }
62811 }
62812 var len = state.objectMode ? 1 : chunk.length;
62813
62814 state.length += len;
62815
62816 var ret = state.length < state.highWaterMark;
62817 // we must ensure that previous needDrain will not be reset to false.
62818 if (!ret) state.needDrain = true;
62819
62820 if (state.writing || state.corked) {
62821 var last = state.lastBufferedRequest;
62822 state.lastBufferedRequest = {
62823 chunk: chunk,
62824 encoding: encoding,
62825 isBuf: isBuf,
62826 callback: cb,
62827 next: null
62828 };
62829 if (last) {
62830 last.next = state.lastBufferedRequest;
62831 } else {
62832 state.bufferedRequest = state.lastBufferedRequest;
62833 }
62834 state.bufferedRequestCount += 1;
62835 } else {
62836 doWrite(stream, state, false, len, chunk, encoding, cb);
62837 }
62838
62839 return ret;
62840}
62841
62842function doWrite(stream, state, writev, len, chunk, encoding, cb) {
62843 state.writelen = len;
62844 state.writecb = cb;
62845 state.writing = true;
62846 state.sync = true;
62847 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
62848 state.sync = false;
62849}
62850
62851function onwriteError(stream, state, sync, er, cb) {
62852 --state.pendingcb;
62853
62854 if (sync) {
62855 // defer the callback if we are being called synchronously
62856 // to avoid piling up things on the stack
62857 pna.nextTick(cb, er);
62858 // this can emit finish, and it will always happen
62859 // after error
62860 pna.nextTick(finishMaybe, stream, state);
62861 stream._writableState.errorEmitted = true;
62862 stream.emit('error', er);
62863 } else {
62864 // the caller expect this to happen before if
62865 // it is async
62866 cb(er);
62867 stream._writableState.errorEmitted = true;
62868 stream.emit('error', er);
62869 // this can emit finish, but finish must
62870 // always follow error
62871 finishMaybe(stream, state);
62872 }
62873}
62874
62875function onwriteStateUpdate(state) {
62876 state.writing = false;
62877 state.writecb = null;
62878 state.length -= state.writelen;
62879 state.writelen = 0;
62880}
62881
62882function onwrite(stream, er) {
62883 var state = stream._writableState;
62884 var sync = state.sync;
62885 var cb = state.writecb;
62886
62887 onwriteStateUpdate(state);
62888
62889 if (er) onwriteError(stream, state, sync, er, cb);else {
62890 // Check if we're actually ready to finish, but don't emit yet
62891 var finished = needFinish(state);
62892
62893 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
62894 clearBuffer(stream, state);
62895 }
62896
62897 if (sync) {
62898 /*<replacement>*/
62899 asyncWrite(afterWrite, stream, state, finished, cb);
62900 /*</replacement>*/
62901 } else {
62902 afterWrite(stream, state, finished, cb);
62903 }
62904 }
62905}
62906
62907function afterWrite(stream, state, finished, cb) {
62908 if (!finished) onwriteDrain(stream, state);
62909 state.pendingcb--;
62910 cb();
62911 finishMaybe(stream, state);
62912}
62913
62914// Must force callback to be called on nextTick, so that we don't
62915// emit 'drain' before the write() consumer gets the 'false' return
62916// value, and has a chance to attach a 'drain' listener.
62917function onwriteDrain(stream, state) {
62918 if (state.length === 0 && state.needDrain) {
62919 state.needDrain = false;
62920 stream.emit('drain');
62921 }
62922}
62923
62924// if there's something in the buffer waiting, then process it
62925function clearBuffer(stream, state) {
62926 state.bufferProcessing = true;
62927 var entry = state.bufferedRequest;
62928
62929 if (stream._writev && entry && entry.next) {
62930 // Fast case, write everything using _writev()
62931 var l = state.bufferedRequestCount;
62932 var buffer = new Array(l);
62933 var holder = state.corkedRequestsFree;
62934 holder.entry = entry;
62935
62936 var count = 0;
62937 var allBuffers = true;
62938 while (entry) {
62939 buffer[count] = entry;
62940 if (!entry.isBuf) allBuffers = false;
62941 entry = entry.next;
62942 count += 1;
62943 }
62944 buffer.allBuffers = allBuffers;
62945
62946 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
62947
62948 // doWrite is almost always async, defer these to save a bit of time
62949 // as the hot path ends with doWrite
62950 state.pendingcb++;
62951 state.lastBufferedRequest = null;
62952 if (holder.next) {
62953 state.corkedRequestsFree = holder.next;
62954 holder.next = null;
62955 } else {
62956 state.corkedRequestsFree = new CorkedRequest(state);
62957 }
62958 state.bufferedRequestCount = 0;
62959 } else {
62960 // Slow case, write chunks one-by-one
62961 while (entry) {
62962 var chunk = entry.chunk;
62963 var encoding = entry.encoding;
62964 var cb = entry.callback;
62965 var len = state.objectMode ? 1 : chunk.length;
62966
62967 doWrite(stream, state, false, len, chunk, encoding, cb);
62968 entry = entry.next;
62969 state.bufferedRequestCount--;
62970 // if we didn't call the onwrite immediately, then
62971 // it means that we need to wait until it does.
62972 // also, that means that the chunk and cb are currently
62973 // being processed, so move the buffer counter past them.
62974 if (state.writing) {
62975 break;
62976 }
62977 }
62978
62979 if (entry === null) state.lastBufferedRequest = null;
62980 }
62981
62982 state.bufferedRequest = entry;
62983 state.bufferProcessing = false;
62984}
62985
62986Writable.prototype._write = function (chunk, encoding, cb) {
62987 cb(new Error('_write() is not implemented'));
62988};
62989
62990Writable.prototype._writev = null;
62991
62992Writable.prototype.end = function (chunk, encoding, cb) {
62993 var state = this._writableState;
62994
62995 if (typeof chunk === 'function') {
62996 cb = chunk;
62997 chunk = null;
62998 encoding = null;
62999 } else if (typeof encoding === 'function') {
63000 cb = encoding;
63001 encoding = null;
63002 }
63003
63004 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
63005
63006 // .end() fully uncorks
63007 if (state.corked) {
63008 state.corked = 1;
63009 this.uncork();
63010 }
63011
63012 // ignore unnecessary end() calls.
63013 if (!state.ending && !state.finished) endWritable(this, state, cb);
63014};
63015
63016function needFinish(state) {
63017 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
63018}
63019function callFinal(stream, state) {
63020 stream._final(function (err) {
63021 state.pendingcb--;
63022 if (err) {
63023 stream.emit('error', err);
63024 }
63025 state.prefinished = true;
63026 stream.emit('prefinish');
63027 finishMaybe(stream, state);
63028 });
63029}
63030function prefinish(stream, state) {
63031 if (!state.prefinished && !state.finalCalled) {
63032 if (typeof stream._final === 'function') {
63033 state.pendingcb++;
63034 state.finalCalled = true;
63035 pna.nextTick(callFinal, stream, state);
63036 } else {
63037 state.prefinished = true;
63038 stream.emit('prefinish');
63039 }
63040 }
63041}
63042
63043function finishMaybe(stream, state) {
63044 var need = needFinish(state);
63045 if (need) {
63046 prefinish(stream, state);
63047 if (state.pendingcb === 0) {
63048 state.finished = true;
63049 stream.emit('finish');
63050 }
63051 }
63052 return need;
63053}
63054
63055function endWritable(stream, state, cb) {
63056 state.ending = true;
63057 finishMaybe(stream, state);
63058 if (cb) {
63059 if (state.finished) pna.nextTick(cb);else stream.once('finish', cb);
63060 }
63061 state.ended = true;
63062 stream.writable = false;
63063}
63064
63065function onCorkedFinish(corkReq, state, err) {
63066 var entry = corkReq.entry;
63067 corkReq.entry = null;
63068 while (entry) {
63069 var cb = entry.callback;
63070 state.pendingcb--;
63071 cb(err);
63072 entry = entry.next;
63073 }
63074 if (state.corkedRequestsFree) {
63075 state.corkedRequestsFree.next = corkReq;
63076 } else {
63077 state.corkedRequestsFree = corkReq;
63078 }
63079}
63080
63081Object.defineProperty(Writable.prototype, 'destroyed', {
63082 get: function () {
63083 if (this._writableState === undefined) {
63084 return false;
63085 }
63086 return this._writableState.destroyed;
63087 },
63088 set: function (value) {
63089 // we ignore the value if the stream
63090 // has not been initialized yet
63091 if (!this._writableState) {
63092 return;
63093 }
63094
63095 // backward compatibility, the user is explicitly
63096 // managing destroyed
63097 this._writableState.destroyed = value;
63098 }
63099});
63100
63101Writable.prototype.destroy = destroyImpl.destroy;
63102Writable.prototype._undestroy = destroyImpl.undestroy;
63103Writable.prototype._destroy = function (err, cb) {
63104 this.end();
63105 cb(err);
63106};
63107}).call(this)}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("timers").setImmediate)
63108},{"./_stream_duplex":241,"./internal/streams/destroy":247,"./internal/streams/stream":248,"_process":228,"core-util-is":134,"inherits":249,"process-nextick-args":227,"safe-buffer":250,"timers":269,"util-deprecate":272}],246:[function(require,module,exports){
63109'use strict';
63110
63111function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
63112
63113var Buffer = require('safe-buffer').Buffer;
63114var util = require('util');
63115
63116function copyBuffer(src, target, offset) {
63117 src.copy(target, offset);
63118}
63119
63120module.exports = function () {
63121 function BufferList() {
63122 _classCallCheck(this, BufferList);
63123
63124 this.head = null;
63125 this.tail = null;
63126 this.length = 0;
63127 }
63128
63129 BufferList.prototype.push = function push(v) {
63130 var entry = { data: v, next: null };
63131 if (this.length > 0) this.tail.next = entry;else this.head = entry;
63132 this.tail = entry;
63133 ++this.length;
63134 };
63135
63136 BufferList.prototype.unshift = function unshift(v) {
63137 var entry = { data: v, next: this.head };
63138 if (this.length === 0) this.tail = entry;
63139 this.head = entry;
63140 ++this.length;
63141 };
63142
63143 BufferList.prototype.shift = function shift() {
63144 if (this.length === 0) return;
63145 var ret = this.head.data;
63146 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
63147 --this.length;
63148 return ret;
63149 };
63150
63151 BufferList.prototype.clear = function clear() {
63152 this.head = this.tail = null;
63153 this.length = 0;
63154 };
63155
63156 BufferList.prototype.join = function join(s) {
63157 if (this.length === 0) return '';
63158 var p = this.head;
63159 var ret = '' + p.data;
63160 while (p = p.next) {
63161 ret += s + p.data;
63162 }return ret;
63163 };
63164
63165 BufferList.prototype.concat = function concat(n) {
63166 if (this.length === 0) return Buffer.alloc(0);
63167 if (this.length === 1) return this.head.data;
63168 var ret = Buffer.allocUnsafe(n >>> 0);
63169 var p = this.head;
63170 var i = 0;
63171 while (p) {
63172 copyBuffer(p.data, ret, i);
63173 i += p.data.length;
63174 p = p.next;
63175 }
63176 return ret;
63177 };
63178
63179 return BufferList;
63180}();
63181
63182if (util && util.inspect && util.inspect.custom) {
63183 module.exports.prototype[util.inspect.custom] = function () {
63184 var obj = util.inspect({ length: this.length });
63185 return this.constructor.name + ' ' + obj;
63186 };
63187}
63188},{"safe-buffer":250,"util":82}],247:[function(require,module,exports){
63189'use strict';
63190
63191/*<replacement>*/
63192
63193var pna = require('process-nextick-args');
63194/*</replacement>*/
63195
63196// undocumented cb() API, needed for core, not for public API
63197function destroy(err, cb) {
63198 var _this = this;
63199
63200 var readableDestroyed = this._readableState && this._readableState.destroyed;
63201 var writableDestroyed = this._writableState && this._writableState.destroyed;
63202
63203 if (readableDestroyed || writableDestroyed) {
63204 if (cb) {
63205 cb(err);
63206 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
63207 pna.nextTick(emitErrorNT, this, err);
63208 }
63209 return this;
63210 }
63211
63212 // we set destroyed to true before firing error callbacks in order
63213 // to make it re-entrance safe in case destroy() is called within callbacks
63214
63215 if (this._readableState) {
63216 this._readableState.destroyed = true;
63217 }
63218
63219 // if this is a duplex stream mark the writable part as destroyed as well
63220 if (this._writableState) {
63221 this._writableState.destroyed = true;
63222 }
63223
63224 this._destroy(err || null, function (err) {
63225 if (!cb && err) {
63226 pna.nextTick(emitErrorNT, _this, err);
63227 if (_this._writableState) {
63228 _this._writableState.errorEmitted = true;
63229 }
63230 } else if (cb) {
63231 cb(err);
63232 }
63233 });
63234
63235 return this;
63236}
63237
63238function undestroy() {
63239 if (this._readableState) {
63240 this._readableState.destroyed = false;
63241 this._readableState.reading = false;
63242 this._readableState.ended = false;
63243 this._readableState.endEmitted = false;
63244 }
63245
63246 if (this._writableState) {
63247 this._writableState.destroyed = false;
63248 this._writableState.ended = false;
63249 this._writableState.ending = false;
63250 this._writableState.finished = false;
63251 this._writableState.errorEmitted = false;
63252 }
63253}
63254
63255function emitErrorNT(self, err) {
63256 self.emit('error', err);
63257}
63258
63259module.exports = {
63260 destroy: destroy,
63261 undestroy: undestroy
63262};
63263},{"process-nextick-args":227}],248:[function(require,module,exports){
63264arguments[4][126][0].apply(exports,arguments)
63265},{"dup":126,"events":172}],249:[function(require,module,exports){
63266arguments[4][112][0].apply(exports,arguments)
63267},{"dup":112}],250:[function(require,module,exports){
63268/* eslint-disable node/no-deprecated-api */
63269var buffer = require('buffer')
63270var Buffer = buffer.Buffer
63271
63272// alternative to using Object.keys for old browsers
63273function copyProps (src, dst) {
63274 for (var key in src) {
63275 dst[key] = src[key]
63276 }
63277}
63278if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
63279 module.exports = buffer
63280} else {
63281 // Copy properties from require('buffer')
63282 copyProps(buffer, exports)
63283 exports.Buffer = SafeBuffer
63284}
63285
63286function SafeBuffer (arg, encodingOrOffset, length) {
63287 return Buffer(arg, encodingOrOffset, length)
63288}
63289
63290// Copy static methods from Buffer
63291copyProps(Buffer, SafeBuffer)
63292
63293SafeBuffer.from = function (arg, encodingOrOffset, length) {
63294 if (typeof arg === 'number') {
63295 throw new TypeError('Argument must not be a number')
63296 }
63297 return Buffer(arg, encodingOrOffset, length)
63298}
63299
63300SafeBuffer.alloc = function (size, fill, encoding) {
63301 if (typeof size !== 'number') {
63302 throw new TypeError('Argument must be a number')
63303 }
63304 var buf = Buffer(size)
63305 if (fill !== undefined) {
63306 if (typeof encoding === 'string') {
63307 buf.fill(fill, encoding)
63308 } else {
63309 buf.fill(fill)
63310 }
63311 } else {
63312 buf.fill(0)
63313 }
63314 return buf
63315}
63316
63317SafeBuffer.allocUnsafe = function (size) {
63318 if (typeof size !== 'number') {
63319 throw new TypeError('Argument must be a number')
63320 }
63321 return Buffer(size)
63322}
63323
63324SafeBuffer.allocUnsafeSlow = function (size) {
63325 if (typeof size !== 'number') {
63326 throw new TypeError('Argument must be a number')
63327 }
63328 return buffer.SlowBuffer(size)
63329}
63330
63331},{"buffer":132}],251:[function(require,module,exports){
63332module.exports = require('./readable').PassThrough
63333
63334},{"./readable":252}],252:[function(require,module,exports){
63335exports = module.exports = require('./lib/_stream_readable.js');
63336exports.Stream = exports;
63337exports.Readable = exports;
63338exports.Writable = require('./lib/_stream_writable.js');
63339exports.Duplex = require('./lib/_stream_duplex.js');
63340exports.Transform = require('./lib/_stream_transform.js');
63341exports.PassThrough = require('./lib/_stream_passthrough.js');
63342
63343},{"./lib/_stream_duplex.js":241,"./lib/_stream_passthrough.js":242,"./lib/_stream_readable.js":243,"./lib/_stream_transform.js":244,"./lib/_stream_writable.js":245}],253:[function(require,module,exports){
63344module.exports = require('./readable').Transform
63345
63346},{"./readable":252}],254:[function(require,module,exports){
63347module.exports = require('./lib/_stream_writable.js');
63348
63349},{"./lib/_stream_writable.js":245}],255:[function(require,module,exports){
63350'use strict'
63351var Buffer = require('buffer').Buffer
63352var inherits = require('inherits')
63353var HashBase = require('hash-base')
63354
63355var ARRAY16 = new Array(16)
63356
63357var zl = [
63358 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
63359 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
63360 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
63361 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
63362 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
63363]
63364
63365var zr = [
63366 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
63367 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
63368 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
63369 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
63370 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
63371]
63372
63373var sl = [
63374 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
63375 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
63376 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
63377 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
63378 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
63379]
63380
63381var sr = [
63382 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
63383 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
63384 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
63385 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
63386 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
63387]
63388
63389var hl = [0x00000000, 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xa953fd4e]
63390var hr = [0x50a28be6, 0x5c4dd124, 0x6d703ef3, 0x7a6d76e9, 0x00000000]
63391
63392function RIPEMD160 () {
63393 HashBase.call(this, 64)
63394
63395 // state
63396 this._a = 0x67452301
63397 this._b = 0xefcdab89
63398 this._c = 0x98badcfe
63399 this._d = 0x10325476
63400 this._e = 0xc3d2e1f0
63401}
63402
63403inherits(RIPEMD160, HashBase)
63404
63405RIPEMD160.prototype._update = function () {
63406 var words = ARRAY16
63407 for (var j = 0; j < 16; ++j) words[j] = this._block.readInt32LE(j * 4)
63408
63409 var al = this._a | 0
63410 var bl = this._b | 0
63411 var cl = this._c | 0
63412 var dl = this._d | 0
63413 var el = this._e | 0
63414
63415 var ar = this._a | 0
63416 var br = this._b | 0
63417 var cr = this._c | 0
63418 var dr = this._d | 0
63419 var er = this._e | 0
63420
63421 // computation
63422 for (var i = 0; i < 80; i += 1) {
63423 var tl
63424 var tr
63425 if (i < 16) {
63426 tl = fn1(al, bl, cl, dl, el, words[zl[i]], hl[0], sl[i])
63427 tr = fn5(ar, br, cr, dr, er, words[zr[i]], hr[0], sr[i])
63428 } else if (i < 32) {
63429 tl = fn2(al, bl, cl, dl, el, words[zl[i]], hl[1], sl[i])
63430 tr = fn4(ar, br, cr, dr, er, words[zr[i]], hr[1], sr[i])
63431 } else if (i < 48) {
63432 tl = fn3(al, bl, cl, dl, el, words[zl[i]], hl[2], sl[i])
63433 tr = fn3(ar, br, cr, dr, er, words[zr[i]], hr[2], sr[i])
63434 } else if (i < 64) {
63435 tl = fn4(al, bl, cl, dl, el, words[zl[i]], hl[3], sl[i])
63436 tr = fn2(ar, br, cr, dr, er, words[zr[i]], hr[3], sr[i])
63437 } else { // if (i<80) {
63438 tl = fn5(al, bl, cl, dl, el, words[zl[i]], hl[4], sl[i])
63439 tr = fn1(ar, br, cr, dr, er, words[zr[i]], hr[4], sr[i])
63440 }
63441
63442 al = el
63443 el = dl
63444 dl = rotl(cl, 10)
63445 cl = bl
63446 bl = tl
63447
63448 ar = er
63449 er = dr
63450 dr = rotl(cr, 10)
63451 cr = br
63452 br = tr
63453 }
63454
63455 // update state
63456 var t = (this._b + cl + dr) | 0
63457 this._b = (this._c + dl + er) | 0
63458 this._c = (this._d + el + ar) | 0
63459 this._d = (this._e + al + br) | 0
63460 this._e = (this._a + bl + cr) | 0
63461 this._a = t
63462}
63463
63464RIPEMD160.prototype._digest = function () {
63465 // create padding and handle blocks
63466 this._block[this._blockOffset++] = 0x80
63467 if (this._blockOffset > 56) {
63468 this._block.fill(0, this._blockOffset, 64)
63469 this._update()
63470 this._blockOffset = 0
63471 }
63472
63473 this._block.fill(0, this._blockOffset, 56)
63474 this._block.writeUInt32LE(this._length[0], 56)
63475 this._block.writeUInt32LE(this._length[1], 60)
63476 this._update()
63477
63478 // produce result
63479 var buffer = Buffer.alloc ? Buffer.alloc(20) : new Buffer(20)
63480 buffer.writeInt32LE(this._a, 0)
63481 buffer.writeInt32LE(this._b, 4)
63482 buffer.writeInt32LE(this._c, 8)
63483 buffer.writeInt32LE(this._d, 12)
63484 buffer.writeInt32LE(this._e, 16)
63485 return buffer
63486}
63487
63488function rotl (x, n) {
63489 return (x << n) | (x >>> (32 - n))
63490}
63491
63492function fn1 (a, b, c, d, e, m, k, s) {
63493 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
63494}
63495
63496function fn2 (a, b, c, d, e, m, k, s) {
63497 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
63498}
63499
63500function fn3 (a, b, c, d, e, m, k, s) {
63501 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
63502}
63503
63504function fn4 (a, b, c, d, e, m, k, s) {
63505 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
63506}
63507
63508function fn5 (a, b, c, d, e, m, k, s) {
63509 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
63510}
63511
63512module.exports = RIPEMD160
63513
63514},{"buffer":132,"hash-base":174,"inherits":206}],256:[function(require,module,exports){
63515/* eslint-disable node/no-deprecated-api */
63516var buffer = require('buffer')
63517var Buffer = buffer.Buffer
63518
63519// alternative to using Object.keys for old browsers
63520function copyProps (src, dst) {
63521 for (var key in src) {
63522 dst[key] = src[key]
63523 }
63524}
63525if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
63526 module.exports = buffer
63527} else {
63528 // Copy properties from require('buffer')
63529 copyProps(buffer, exports)
63530 exports.Buffer = SafeBuffer
63531}
63532
63533function SafeBuffer (arg, encodingOrOffset, length) {
63534 return Buffer(arg, encodingOrOffset, length)
63535}
63536
63537SafeBuffer.prototype = Object.create(Buffer.prototype)
63538
63539// Copy static methods from Buffer
63540copyProps(Buffer, SafeBuffer)
63541
63542SafeBuffer.from = function (arg, encodingOrOffset, length) {
63543 if (typeof arg === 'number') {
63544 throw new TypeError('Argument must not be a number')
63545 }
63546 return Buffer(arg, encodingOrOffset, length)
63547}
63548
63549SafeBuffer.alloc = function (size, fill, encoding) {
63550 if (typeof size !== 'number') {
63551 throw new TypeError('Argument must be a number')
63552 }
63553 var buf = Buffer(size)
63554 if (fill !== undefined) {
63555 if (typeof encoding === 'string') {
63556 buf.fill(fill, encoding)
63557 } else {
63558 buf.fill(fill)
63559 }
63560 } else {
63561 buf.fill(0)
63562 }
63563 return buf
63564}
63565
63566SafeBuffer.allocUnsafe = function (size) {
63567 if (typeof size !== 'number') {
63568 throw new TypeError('Argument must be a number')
63569 }
63570 return Buffer(size)
63571}
63572
63573SafeBuffer.allocUnsafeSlow = function (size) {
63574 if (typeof size !== 'number') {
63575 throw new TypeError('Argument must be a number')
63576 }
63577 return buffer.SlowBuffer(size)
63578}
63579
63580},{"buffer":132}],257:[function(require,module,exports){
63581(function (process){(function (){
63582/* eslint-disable node/no-deprecated-api */
63583
63584'use strict'
63585
63586var buffer = require('buffer')
63587var Buffer = buffer.Buffer
63588
63589var safer = {}
63590
63591var key
63592
63593for (key in buffer) {
63594 if (!buffer.hasOwnProperty(key)) continue
63595 if (key === 'SlowBuffer' || key === 'Buffer') continue
63596 safer[key] = buffer[key]
63597}
63598
63599var Safer = safer.Buffer = {}
63600for (key in Buffer) {
63601 if (!Buffer.hasOwnProperty(key)) continue
63602 if (key === 'allocUnsafe' || key === 'allocUnsafeSlow') continue
63603 Safer[key] = Buffer[key]
63604}
63605
63606safer.Buffer.prototype = Buffer.prototype
63607
63608if (!Safer.from || Safer.from === Uint8Array.from) {
63609 Safer.from = function (value, encodingOrOffset, length) {
63610 if (typeof value === 'number') {
63611 throw new TypeError('The "value" argument must not be of type number. Received type ' + typeof value)
63612 }
63613 if (value && typeof value.length === 'undefined') {
63614 throw new TypeError('The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type ' + typeof value)
63615 }
63616 return Buffer(value, encodingOrOffset, length)
63617 }
63618}
63619
63620if (!Safer.alloc) {
63621 Safer.alloc = function (size, fill, encoding) {
63622 if (typeof size !== 'number') {
63623 throw new TypeError('The "size" argument must be of type number. Received type ' + typeof size)
63624 }
63625 if (size < 0 || size >= 2 * (1 << 30)) {
63626 throw new RangeError('The value "' + size + '" is invalid for option "size"')
63627 }
63628 var buf = Buffer(size)
63629 if (!fill || fill.length === 0) {
63630 buf.fill(0)
63631 } else if (typeof encoding === 'string') {
63632 buf.fill(fill, encoding)
63633 } else {
63634 buf.fill(fill)
63635 }
63636 return buf
63637 }
63638}
63639
63640if (!safer.kStringMaxLength) {
63641 try {
63642 safer.kStringMaxLength = process.binding('buffer').kStringMaxLength
63643 } catch (e) {
63644 // we can't determine kStringMaxLength in environments where process.binding
63645 // is unsupported, so let's not set it
63646 }
63647}
63648
63649if (!safer.constants) {
63650 safer.constants = {
63651 MAX_LENGTH: safer.kMaxLength
63652 }
63653 if (safer.kStringMaxLength) {
63654 safer.constants.MAX_STRING_LENGTH = safer.kStringMaxLength
63655 }
63656}
63657
63658module.exports = safer
63659
63660}).call(this)}).call(this,require('_process'))
63661},{"_process":228,"buffer":132}],258:[function(require,module,exports){
63662var Buffer = require('safe-buffer').Buffer
63663
63664// prototype class for hash functions
63665function Hash (blockSize, finalSize) {
63666 this._block = Buffer.alloc(blockSize)
63667 this._finalSize = finalSize
63668 this._blockSize = blockSize
63669 this._len = 0
63670}
63671
63672Hash.prototype.update = function (data, enc) {
63673 if (typeof data === 'string') {
63674 enc = enc || 'utf8'
63675 data = Buffer.from(data, enc)
63676 }
63677
63678 var block = this._block
63679 var blockSize = this._blockSize
63680 var length = data.length
63681 var accum = this._len
63682
63683 for (var offset = 0; offset < length;) {
63684 var assigned = accum % blockSize
63685 var remainder = Math.min(length - offset, blockSize - assigned)
63686
63687 for (var i = 0; i < remainder; i++) {
63688 block[assigned + i] = data[offset + i]
63689 }
63690
63691 accum += remainder
63692 offset += remainder
63693
63694 if ((accum % blockSize) === 0) {
63695 this._update(block)
63696 }
63697 }
63698
63699 this._len += length
63700 return this
63701}
63702
63703Hash.prototype.digest = function (enc) {
63704 var rem = this._len % this._blockSize
63705
63706 this._block[rem] = 0x80
63707
63708 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
63709 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
63710 this._block.fill(0, rem + 1)
63711
63712 if (rem >= this._finalSize) {
63713 this._update(this._block)
63714 this._block.fill(0)
63715 }
63716
63717 var bits = this._len * 8
63718
63719 // uint32
63720 if (bits <= 0xffffffff) {
63721 this._block.writeUInt32BE(bits, this._blockSize - 4)
63722
63723 // uint64
63724 } else {
63725 var lowBits = (bits & 0xffffffff) >>> 0
63726 var highBits = (bits - lowBits) / 0x100000000
63727
63728 this._block.writeUInt32BE(highBits, this._blockSize - 8)
63729 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
63730 }
63731
63732 this._update(this._block)
63733 var hash = this._hash()
63734
63735 return enc ? hash.toString(enc) : hash
63736}
63737
63738Hash.prototype._update = function () {
63739 throw new Error('_update must be implemented by subclass')
63740}
63741
63742module.exports = Hash
63743
63744},{"safe-buffer":256}],259:[function(require,module,exports){
63745var exports = module.exports = function SHA (algorithm) {
63746 algorithm = algorithm.toLowerCase()
63747
63748 var Algorithm = exports[algorithm]
63749 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
63750
63751 return new Algorithm()
63752}
63753
63754exports.sha = require('./sha')
63755exports.sha1 = require('./sha1')
63756exports.sha224 = require('./sha224')
63757exports.sha256 = require('./sha256')
63758exports.sha384 = require('./sha384')
63759exports.sha512 = require('./sha512')
63760
63761},{"./sha":260,"./sha1":261,"./sha224":262,"./sha256":263,"./sha384":264,"./sha512":265}],260:[function(require,module,exports){
63762/*
63763 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
63764 * in FIPS PUB 180-1
63765 * This source code is derived from sha1.js of the same repository.
63766 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
63767 * operation was added.
63768 */
63769
63770var inherits = require('inherits')
63771var Hash = require('./hash')
63772var Buffer = require('safe-buffer').Buffer
63773
63774var K = [
63775 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
63776]
63777
63778var W = new Array(80)
63779
63780function Sha () {
63781 this.init()
63782 this._w = W
63783
63784 Hash.call(this, 64, 56)
63785}
63786
63787inherits(Sha, Hash)
63788
63789Sha.prototype.init = function () {
63790 this._a = 0x67452301
63791 this._b = 0xefcdab89
63792 this._c = 0x98badcfe
63793 this._d = 0x10325476
63794 this._e = 0xc3d2e1f0
63795
63796 return this
63797}
63798
63799function rotl5 (num) {
63800 return (num << 5) | (num >>> 27)
63801}
63802
63803function rotl30 (num) {
63804 return (num << 30) | (num >>> 2)
63805}
63806
63807function ft (s, b, c, d) {
63808 if (s === 0) return (b & c) | ((~b) & d)
63809 if (s === 2) return (b & c) | (b & d) | (c & d)
63810 return b ^ c ^ d
63811}
63812
63813Sha.prototype._update = function (M) {
63814 var W = this._w
63815
63816 var a = this._a | 0
63817 var b = this._b | 0
63818 var c = this._c | 0
63819 var d = this._d | 0
63820 var e = this._e | 0
63821
63822 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
63823 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
63824
63825 for (var j = 0; j < 80; ++j) {
63826 var s = ~~(j / 20)
63827 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
63828
63829 e = d
63830 d = c
63831 c = rotl30(b)
63832 b = a
63833 a = t
63834 }
63835
63836 this._a = (a + this._a) | 0
63837 this._b = (b + this._b) | 0
63838 this._c = (c + this._c) | 0
63839 this._d = (d + this._d) | 0
63840 this._e = (e + this._e) | 0
63841}
63842
63843Sha.prototype._hash = function () {
63844 var H = Buffer.allocUnsafe(20)
63845
63846 H.writeInt32BE(this._a | 0, 0)
63847 H.writeInt32BE(this._b | 0, 4)
63848 H.writeInt32BE(this._c | 0, 8)
63849 H.writeInt32BE(this._d | 0, 12)
63850 H.writeInt32BE(this._e | 0, 16)
63851
63852 return H
63853}
63854
63855module.exports = Sha
63856
63857},{"./hash":258,"inherits":206,"safe-buffer":256}],261:[function(require,module,exports){
63858/*
63859 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
63860 * in FIPS PUB 180-1
63861 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
63862 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
63863 * Distributed under the BSD License
63864 * See http://pajhome.org.uk/crypt/md5 for details.
63865 */
63866
63867var inherits = require('inherits')
63868var Hash = require('./hash')
63869var Buffer = require('safe-buffer').Buffer
63870
63871var K = [
63872 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
63873]
63874
63875var W = new Array(80)
63876
63877function Sha1 () {
63878 this.init()
63879 this._w = W
63880
63881 Hash.call(this, 64, 56)
63882}
63883
63884inherits(Sha1, Hash)
63885
63886Sha1.prototype.init = function () {
63887 this._a = 0x67452301
63888 this._b = 0xefcdab89
63889 this._c = 0x98badcfe
63890 this._d = 0x10325476
63891 this._e = 0xc3d2e1f0
63892
63893 return this
63894}
63895
63896function rotl1 (num) {
63897 return (num << 1) | (num >>> 31)
63898}
63899
63900function rotl5 (num) {
63901 return (num << 5) | (num >>> 27)
63902}
63903
63904function rotl30 (num) {
63905 return (num << 30) | (num >>> 2)
63906}
63907
63908function ft (s, b, c, d) {
63909 if (s === 0) return (b & c) | ((~b) & d)
63910 if (s === 2) return (b & c) | (b & d) | (c & d)
63911 return b ^ c ^ d
63912}
63913
63914Sha1.prototype._update = function (M) {
63915 var W = this._w
63916
63917 var a = this._a | 0
63918 var b = this._b | 0
63919 var c = this._c | 0
63920 var d = this._d | 0
63921 var e = this._e | 0
63922
63923 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
63924 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
63925
63926 for (var j = 0; j < 80; ++j) {
63927 var s = ~~(j / 20)
63928 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
63929
63930 e = d
63931 d = c
63932 c = rotl30(b)
63933 b = a
63934 a = t
63935 }
63936
63937 this._a = (a + this._a) | 0
63938 this._b = (b + this._b) | 0
63939 this._c = (c + this._c) | 0
63940 this._d = (d + this._d) | 0
63941 this._e = (e + this._e) | 0
63942}
63943
63944Sha1.prototype._hash = function () {
63945 var H = Buffer.allocUnsafe(20)
63946
63947 H.writeInt32BE(this._a | 0, 0)
63948 H.writeInt32BE(this._b | 0, 4)
63949 H.writeInt32BE(this._c | 0, 8)
63950 H.writeInt32BE(this._d | 0, 12)
63951 H.writeInt32BE(this._e | 0, 16)
63952
63953 return H
63954}
63955
63956module.exports = Sha1
63957
63958},{"./hash":258,"inherits":206,"safe-buffer":256}],262:[function(require,module,exports){
63959/**
63960 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
63961 * in FIPS 180-2
63962 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
63963 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
63964 *
63965 */
63966
63967var inherits = require('inherits')
63968var Sha256 = require('./sha256')
63969var Hash = require('./hash')
63970var Buffer = require('safe-buffer').Buffer
63971
63972var W = new Array(64)
63973
63974function Sha224 () {
63975 this.init()
63976
63977 this._w = W // new Array(64)
63978
63979 Hash.call(this, 64, 56)
63980}
63981
63982inherits(Sha224, Sha256)
63983
63984Sha224.prototype.init = function () {
63985 this._a = 0xc1059ed8
63986 this._b = 0x367cd507
63987 this._c = 0x3070dd17
63988 this._d = 0xf70e5939
63989 this._e = 0xffc00b31
63990 this._f = 0x68581511
63991 this._g = 0x64f98fa7
63992 this._h = 0xbefa4fa4
63993
63994 return this
63995}
63996
63997Sha224.prototype._hash = function () {
63998 var H = Buffer.allocUnsafe(28)
63999
64000 H.writeInt32BE(this._a, 0)
64001 H.writeInt32BE(this._b, 4)
64002 H.writeInt32BE(this._c, 8)
64003 H.writeInt32BE(this._d, 12)
64004 H.writeInt32BE(this._e, 16)
64005 H.writeInt32BE(this._f, 20)
64006 H.writeInt32BE(this._g, 24)
64007
64008 return H
64009}
64010
64011module.exports = Sha224
64012
64013},{"./hash":258,"./sha256":263,"inherits":206,"safe-buffer":256}],263:[function(require,module,exports){
64014/**
64015 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
64016 * in FIPS 180-2
64017 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
64018 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
64019 *
64020 */
64021
64022var inherits = require('inherits')
64023var Hash = require('./hash')
64024var Buffer = require('safe-buffer').Buffer
64025
64026var K = [
64027 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
64028 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
64029 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
64030 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
64031 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
64032 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
64033 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
64034 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
64035 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
64036 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
64037 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
64038 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
64039 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
64040 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
64041 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
64042 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
64043]
64044
64045var W = new Array(64)
64046
64047function Sha256 () {
64048 this.init()
64049
64050 this._w = W // new Array(64)
64051
64052 Hash.call(this, 64, 56)
64053}
64054
64055inherits(Sha256, Hash)
64056
64057Sha256.prototype.init = function () {
64058 this._a = 0x6a09e667
64059 this._b = 0xbb67ae85
64060 this._c = 0x3c6ef372
64061 this._d = 0xa54ff53a
64062 this._e = 0x510e527f
64063 this._f = 0x9b05688c
64064 this._g = 0x1f83d9ab
64065 this._h = 0x5be0cd19
64066
64067 return this
64068}
64069
64070function ch (x, y, z) {
64071 return z ^ (x & (y ^ z))
64072}
64073
64074function maj (x, y, z) {
64075 return (x & y) | (z & (x | y))
64076}
64077
64078function sigma0 (x) {
64079 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
64080}
64081
64082function sigma1 (x) {
64083 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
64084}
64085
64086function gamma0 (x) {
64087 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
64088}
64089
64090function gamma1 (x) {
64091 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
64092}
64093
64094Sha256.prototype._update = function (M) {
64095 var W = this._w
64096
64097 var a = this._a | 0
64098 var b = this._b | 0
64099 var c = this._c | 0
64100 var d = this._d | 0
64101 var e = this._e | 0
64102 var f = this._f | 0
64103 var g = this._g | 0
64104 var h = this._h | 0
64105
64106 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
64107 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
64108
64109 for (var j = 0; j < 64; ++j) {
64110 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
64111 var T2 = (sigma0(a) + maj(a, b, c)) | 0
64112
64113 h = g
64114 g = f
64115 f = e
64116 e = (d + T1) | 0
64117 d = c
64118 c = b
64119 b = a
64120 a = (T1 + T2) | 0
64121 }
64122
64123 this._a = (a + this._a) | 0
64124 this._b = (b + this._b) | 0
64125 this._c = (c + this._c) | 0
64126 this._d = (d + this._d) | 0
64127 this._e = (e + this._e) | 0
64128 this._f = (f + this._f) | 0
64129 this._g = (g + this._g) | 0
64130 this._h = (h + this._h) | 0
64131}
64132
64133Sha256.prototype._hash = function () {
64134 var H = Buffer.allocUnsafe(32)
64135
64136 H.writeInt32BE(this._a, 0)
64137 H.writeInt32BE(this._b, 4)
64138 H.writeInt32BE(this._c, 8)
64139 H.writeInt32BE(this._d, 12)
64140 H.writeInt32BE(this._e, 16)
64141 H.writeInt32BE(this._f, 20)
64142 H.writeInt32BE(this._g, 24)
64143 H.writeInt32BE(this._h, 28)
64144
64145 return H
64146}
64147
64148module.exports = Sha256
64149
64150},{"./hash":258,"inherits":206,"safe-buffer":256}],264:[function(require,module,exports){
64151var inherits = require('inherits')
64152var SHA512 = require('./sha512')
64153var Hash = require('./hash')
64154var Buffer = require('safe-buffer').Buffer
64155
64156var W = new Array(160)
64157
64158function Sha384 () {
64159 this.init()
64160 this._w = W
64161
64162 Hash.call(this, 128, 112)
64163}
64164
64165inherits(Sha384, SHA512)
64166
64167Sha384.prototype.init = function () {
64168 this._ah = 0xcbbb9d5d
64169 this._bh = 0x629a292a
64170 this._ch = 0x9159015a
64171 this._dh = 0x152fecd8
64172 this._eh = 0x67332667
64173 this._fh = 0x8eb44a87
64174 this._gh = 0xdb0c2e0d
64175 this._hh = 0x47b5481d
64176
64177 this._al = 0xc1059ed8
64178 this._bl = 0x367cd507
64179 this._cl = 0x3070dd17
64180 this._dl = 0xf70e5939
64181 this._el = 0xffc00b31
64182 this._fl = 0x68581511
64183 this._gl = 0x64f98fa7
64184 this._hl = 0xbefa4fa4
64185
64186 return this
64187}
64188
64189Sha384.prototype._hash = function () {
64190 var H = Buffer.allocUnsafe(48)
64191
64192 function writeInt64BE (h, l, offset) {
64193 H.writeInt32BE(h, offset)
64194 H.writeInt32BE(l, offset + 4)
64195 }
64196
64197 writeInt64BE(this._ah, this._al, 0)
64198 writeInt64BE(this._bh, this._bl, 8)
64199 writeInt64BE(this._ch, this._cl, 16)
64200 writeInt64BE(this._dh, this._dl, 24)
64201 writeInt64BE(this._eh, this._el, 32)
64202 writeInt64BE(this._fh, this._fl, 40)
64203
64204 return H
64205}
64206
64207module.exports = Sha384
64208
64209},{"./hash":258,"./sha512":265,"inherits":206,"safe-buffer":256}],265:[function(require,module,exports){
64210var inherits = require('inherits')
64211var Hash = require('./hash')
64212var Buffer = require('safe-buffer').Buffer
64213
64214var K = [
64215 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
64216 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
64217 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
64218 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
64219 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
64220 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
64221 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
64222 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
64223 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
64224 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
64225 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
64226 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
64227 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
64228 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
64229 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
64230 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
64231 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
64232 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
64233 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
64234 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
64235 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
64236 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
64237 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
64238 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
64239 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
64240 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
64241 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
64242 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
64243 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
64244 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
64245 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
64246 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
64247 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
64248 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
64249 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
64250 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
64251 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
64252 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
64253 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
64254 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
64255]
64256
64257var W = new Array(160)
64258
64259function Sha512 () {
64260 this.init()
64261 this._w = W
64262
64263 Hash.call(this, 128, 112)
64264}
64265
64266inherits(Sha512, Hash)
64267
64268Sha512.prototype.init = function () {
64269 this._ah = 0x6a09e667
64270 this._bh = 0xbb67ae85
64271 this._ch = 0x3c6ef372
64272 this._dh = 0xa54ff53a
64273 this._eh = 0x510e527f
64274 this._fh = 0x9b05688c
64275 this._gh = 0x1f83d9ab
64276 this._hh = 0x5be0cd19
64277
64278 this._al = 0xf3bcc908
64279 this._bl = 0x84caa73b
64280 this._cl = 0xfe94f82b
64281 this._dl = 0x5f1d36f1
64282 this._el = 0xade682d1
64283 this._fl = 0x2b3e6c1f
64284 this._gl = 0xfb41bd6b
64285 this._hl = 0x137e2179
64286
64287 return this
64288}
64289
64290function Ch (x, y, z) {
64291 return z ^ (x & (y ^ z))
64292}
64293
64294function maj (x, y, z) {
64295 return (x & y) | (z & (x | y))
64296}
64297
64298function sigma0 (x, xl) {
64299 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
64300}
64301
64302function sigma1 (x, xl) {
64303 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
64304}
64305
64306function Gamma0 (x, xl) {
64307 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
64308}
64309
64310function Gamma0l (x, xl) {
64311 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
64312}
64313
64314function Gamma1 (x, xl) {
64315 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
64316}
64317
64318function Gamma1l (x, xl) {
64319 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
64320}
64321
64322function getCarry (a, b) {
64323 return (a >>> 0) < (b >>> 0) ? 1 : 0
64324}
64325
64326Sha512.prototype._update = function (M) {
64327 var W = this._w
64328
64329 var ah = this._ah | 0
64330 var bh = this._bh | 0
64331 var ch = this._ch | 0
64332 var dh = this._dh | 0
64333 var eh = this._eh | 0
64334 var fh = this._fh | 0
64335 var gh = this._gh | 0
64336 var hh = this._hh | 0
64337
64338 var al = this._al | 0
64339 var bl = this._bl | 0
64340 var cl = this._cl | 0
64341 var dl = this._dl | 0
64342 var el = this._el | 0
64343 var fl = this._fl | 0
64344 var gl = this._gl | 0
64345 var hl = this._hl | 0
64346
64347 for (var i = 0; i < 32; i += 2) {
64348 W[i] = M.readInt32BE(i * 4)
64349 W[i + 1] = M.readInt32BE(i * 4 + 4)
64350 }
64351 for (; i < 160; i += 2) {
64352 var xh = W[i - 15 * 2]
64353 var xl = W[i - 15 * 2 + 1]
64354 var gamma0 = Gamma0(xh, xl)
64355 var gamma0l = Gamma0l(xl, xh)
64356
64357 xh = W[i - 2 * 2]
64358 xl = W[i - 2 * 2 + 1]
64359 var gamma1 = Gamma1(xh, xl)
64360 var gamma1l = Gamma1l(xl, xh)
64361
64362 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
64363 var Wi7h = W[i - 7 * 2]
64364 var Wi7l = W[i - 7 * 2 + 1]
64365
64366 var Wi16h = W[i - 16 * 2]
64367 var Wi16l = W[i - 16 * 2 + 1]
64368
64369 var Wil = (gamma0l + Wi7l) | 0
64370 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
64371 Wil = (Wil + gamma1l) | 0
64372 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
64373 Wil = (Wil + Wi16l) | 0
64374 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
64375
64376 W[i] = Wih
64377 W[i + 1] = Wil
64378 }
64379
64380 for (var j = 0; j < 160; j += 2) {
64381 Wih = W[j]
64382 Wil = W[j + 1]
64383
64384 var majh = maj(ah, bh, ch)
64385 var majl = maj(al, bl, cl)
64386
64387 var sigma0h = sigma0(ah, al)
64388 var sigma0l = sigma0(al, ah)
64389 var sigma1h = sigma1(eh, el)
64390 var sigma1l = sigma1(el, eh)
64391
64392 // t1 = h + sigma1 + ch + K[j] + W[j]
64393 var Kih = K[j]
64394 var Kil = K[j + 1]
64395
64396 var chh = Ch(eh, fh, gh)
64397 var chl = Ch(el, fl, gl)
64398
64399 var t1l = (hl + sigma1l) | 0
64400 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
64401 t1l = (t1l + chl) | 0
64402 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
64403 t1l = (t1l + Kil) | 0
64404 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
64405 t1l = (t1l + Wil) | 0
64406 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
64407
64408 // t2 = sigma0 + maj
64409 var t2l = (sigma0l + majl) | 0
64410 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
64411
64412 hh = gh
64413 hl = gl
64414 gh = fh
64415 gl = fl
64416 fh = eh
64417 fl = el
64418 el = (dl + t1l) | 0
64419 eh = (dh + t1h + getCarry(el, dl)) | 0
64420 dh = ch
64421 dl = cl
64422 ch = bh
64423 cl = bl
64424 bh = ah
64425 bl = al
64426 al = (t1l + t2l) | 0
64427 ah = (t1h + t2h + getCarry(al, t1l)) | 0
64428 }
64429
64430 this._al = (this._al + al) | 0
64431 this._bl = (this._bl + bl) | 0
64432 this._cl = (this._cl + cl) | 0
64433 this._dl = (this._dl + dl) | 0
64434 this._el = (this._el + el) | 0
64435 this._fl = (this._fl + fl) | 0
64436 this._gl = (this._gl + gl) | 0
64437 this._hl = (this._hl + hl) | 0
64438
64439 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
64440 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
64441 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
64442 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
64443 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
64444 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
64445 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
64446 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
64447}
64448
64449Sha512.prototype._hash = function () {
64450 var H = Buffer.allocUnsafe(64)
64451
64452 function writeInt64BE (h, l, offset) {
64453 H.writeInt32BE(h, offset)
64454 H.writeInt32BE(l, offset + 4)
64455 }
64456
64457 writeInt64BE(this._ah, this._al, 0)
64458 writeInt64BE(this._bh, this._bl, 8)
64459 writeInt64BE(this._ch, this._cl, 16)
64460 writeInt64BE(this._dh, this._dl, 24)
64461 writeInt64BE(this._eh, this._el, 32)
64462 writeInt64BE(this._fh, this._fl, 40)
64463 writeInt64BE(this._gh, this._gl, 48)
64464 writeInt64BE(this._hh, this._hl, 56)
64465
64466 return H
64467}
64468
64469module.exports = Sha512
64470
64471},{"./hash":258,"inherits":206,"safe-buffer":256}],266:[function(require,module,exports){
64472// Copyright Joyent, Inc. and other Node contributors.
64473//
64474// Permission is hereby granted, free of charge, to any person obtaining a
64475// copy of this software and associated documentation files (the
64476// "Software"), to deal in the Software without restriction, including
64477// without limitation the rights to use, copy, modify, merge, publish,
64478// distribute, sublicense, and/or sell copies of the Software, and to permit
64479// persons to whom the Software is furnished to do so, subject to the
64480// following conditions:
64481//
64482// The above copyright notice and this permission notice shall be included
64483// in all copies or substantial portions of the Software.
64484//
64485// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
64486// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
64487// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
64488// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
64489// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
64490// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
64491// USE OR OTHER DEALINGS IN THE SOFTWARE.
64492
64493module.exports = Stream;
64494
64495var EE = require('events').EventEmitter;
64496var inherits = require('inherits');
64497
64498inherits(Stream, EE);
64499Stream.Readable = require('readable-stream/readable.js');
64500Stream.Writable = require('readable-stream/writable.js');
64501Stream.Duplex = require('readable-stream/duplex.js');
64502Stream.Transform = require('readable-stream/transform.js');
64503Stream.PassThrough = require('readable-stream/passthrough.js');
64504
64505// Backwards-compat with node 0.4.x
64506Stream.Stream = Stream;
64507
64508
64509
64510// old-style streams. Note that the pipe method (the only relevant
64511// part of this class) is overridden in the Readable class.
64512
64513function Stream() {
64514 EE.call(this);
64515}
64516
64517Stream.prototype.pipe = function(dest, options) {
64518 var source = this;
64519
64520 function ondata(chunk) {
64521 if (dest.writable) {
64522 if (false === dest.write(chunk) && source.pause) {
64523 source.pause();
64524 }
64525 }
64526 }
64527
64528 source.on('data', ondata);
64529
64530 function ondrain() {
64531 if (source.readable && source.resume) {
64532 source.resume();
64533 }
64534 }
64535
64536 dest.on('drain', ondrain);
64537
64538 // If the 'end' option is not supplied, dest.end() will be called when
64539 // source gets the 'end' or 'close' events. Only dest.end() once.
64540 if (!dest._isStdio && (!options || options.end !== false)) {
64541 source.on('end', onend);
64542 source.on('close', onclose);
64543 }
64544
64545 var didOnEnd = false;
64546 function onend() {
64547 if (didOnEnd) return;
64548 didOnEnd = true;
64549
64550 dest.end();
64551 }
64552
64553
64554 function onclose() {
64555 if (didOnEnd) return;
64556 didOnEnd = true;
64557
64558 if (typeof dest.destroy === 'function') dest.destroy();
64559 }
64560
64561 // don't leave dangling pipes when there are errors.
64562 function onerror(er) {
64563 cleanup();
64564 if (EE.listenerCount(this, 'error') === 0) {
64565 throw er; // Unhandled stream error in pipe.
64566 }
64567 }
64568
64569 source.on('error', onerror);
64570 dest.on('error', onerror);
64571
64572 // remove all the event listeners that were added.
64573 function cleanup() {
64574 source.removeListener('data', ondata);
64575 dest.removeListener('drain', ondrain);
64576
64577 source.removeListener('end', onend);
64578 source.removeListener('close', onclose);
64579
64580 source.removeListener('error', onerror);
64581 dest.removeListener('error', onerror);
64582
64583 source.removeListener('end', cleanup);
64584 source.removeListener('close', cleanup);
64585
64586 dest.removeListener('close', cleanup);
64587 }
64588
64589 source.on('end', cleanup);
64590 source.on('close', cleanup);
64591
64592 dest.on('close', cleanup);
64593
64594 dest.emit('pipe', source);
64595
64596 // Allow for unix-like usage: A.pipe(B).pipe(C)
64597 return dest;
64598};
64599
64600},{"events":172,"inherits":206,"readable-stream/duplex.js":240,"readable-stream/passthrough.js":251,"readable-stream/readable.js":252,"readable-stream/transform.js":253,"readable-stream/writable.js":254}],267:[function(require,module,exports){
64601// Copyright Joyent, Inc. and other Node contributors.
64602//
64603// Permission is hereby granted, free of charge, to any person obtaining a
64604// copy of this software and associated documentation files (the
64605// "Software"), to deal in the Software without restriction, including
64606// without limitation the rights to use, copy, modify, merge, publish,
64607// distribute, sublicense, and/or sell copies of the Software, and to permit
64608// persons to whom the Software is furnished to do so, subject to the
64609// following conditions:
64610//
64611// The above copyright notice and this permission notice shall be included
64612// in all copies or substantial portions of the Software.
64613//
64614// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
64615// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
64616// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
64617// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
64618// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
64619// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
64620// USE OR OTHER DEALINGS IN THE SOFTWARE.
64621
64622'use strict';
64623
64624/*<replacement>*/
64625
64626var Buffer = require('safe-buffer').Buffer;
64627/*</replacement>*/
64628
64629var isEncoding = Buffer.isEncoding || function (encoding) {
64630 encoding = '' + encoding;
64631 switch (encoding && encoding.toLowerCase()) {
64632 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':
64633 return true;
64634 default:
64635 return false;
64636 }
64637};
64638
64639function _normalizeEncoding(enc) {
64640 if (!enc) return 'utf8';
64641 var retried;
64642 while (true) {
64643 switch (enc) {
64644 case 'utf8':
64645 case 'utf-8':
64646 return 'utf8';
64647 case 'ucs2':
64648 case 'ucs-2':
64649 case 'utf16le':
64650 case 'utf-16le':
64651 return 'utf16le';
64652 case 'latin1':
64653 case 'binary':
64654 return 'latin1';
64655 case 'base64':
64656 case 'ascii':
64657 case 'hex':
64658 return enc;
64659 default:
64660 if (retried) return; // undefined
64661 enc = ('' + enc).toLowerCase();
64662 retried = true;
64663 }
64664 }
64665};
64666
64667// Do not cache `Buffer.isEncoding` when checking encoding names as some
64668// modules monkey-patch it to support additional encodings
64669function normalizeEncoding(enc) {
64670 var nenc = _normalizeEncoding(enc);
64671 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
64672 return nenc || enc;
64673}
64674
64675// StringDecoder provides an interface for efficiently splitting a series of
64676// buffers into a series of JS strings without breaking apart multi-byte
64677// characters.
64678exports.StringDecoder = StringDecoder;
64679function StringDecoder(encoding) {
64680 this.encoding = normalizeEncoding(encoding);
64681 var nb;
64682 switch (this.encoding) {
64683 case 'utf16le':
64684 this.text = utf16Text;
64685 this.end = utf16End;
64686 nb = 4;
64687 break;
64688 case 'utf8':
64689 this.fillLast = utf8FillLast;
64690 nb = 4;
64691 break;
64692 case 'base64':
64693 this.text = base64Text;
64694 this.end = base64End;
64695 nb = 3;
64696 break;
64697 default:
64698 this.write = simpleWrite;
64699 this.end = simpleEnd;
64700 return;
64701 }
64702 this.lastNeed = 0;
64703 this.lastTotal = 0;
64704 this.lastChar = Buffer.allocUnsafe(nb);
64705}
64706
64707StringDecoder.prototype.write = function (buf) {
64708 if (buf.length === 0) return '';
64709 var r;
64710 var i;
64711 if (this.lastNeed) {
64712 r = this.fillLast(buf);
64713 if (r === undefined) return '';
64714 i = this.lastNeed;
64715 this.lastNeed = 0;
64716 } else {
64717 i = 0;
64718 }
64719 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
64720 return r || '';
64721};
64722
64723StringDecoder.prototype.end = utf8End;
64724
64725// Returns only complete characters in a Buffer
64726StringDecoder.prototype.text = utf8Text;
64727
64728// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
64729StringDecoder.prototype.fillLast = function (buf) {
64730 if (this.lastNeed <= buf.length) {
64731 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
64732 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
64733 }
64734 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
64735 this.lastNeed -= buf.length;
64736};
64737
64738// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
64739// continuation byte. If an invalid byte is detected, -2 is returned.
64740function utf8CheckByte(byte) {
64741 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;
64742 return byte >> 6 === 0x02 ? -1 : -2;
64743}
64744
64745// Checks at most 3 bytes at the end of a Buffer in order to detect an
64746// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
64747// needed to complete the UTF-8 character (if applicable) are returned.
64748function utf8CheckIncomplete(self, buf, i) {
64749 var j = buf.length - 1;
64750 if (j < i) return 0;
64751 var nb = utf8CheckByte(buf[j]);
64752 if (nb >= 0) {
64753 if (nb > 0) self.lastNeed = nb - 1;
64754 return nb;
64755 }
64756 if (--j < i || nb === -2) return 0;
64757 nb = utf8CheckByte(buf[j]);
64758 if (nb >= 0) {
64759 if (nb > 0) self.lastNeed = nb - 2;
64760 return nb;
64761 }
64762 if (--j < i || nb === -2) return 0;
64763 nb = utf8CheckByte(buf[j]);
64764 if (nb >= 0) {
64765 if (nb > 0) {
64766 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
64767 }
64768 return nb;
64769 }
64770 return 0;
64771}
64772
64773// Validates as many continuation bytes for a multi-byte UTF-8 character as
64774// needed or are available. If we see a non-continuation byte where we expect
64775// one, we "replace" the validated continuation bytes we've seen so far with
64776// a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding
64777// behavior. The continuation byte check is included three times in the case
64778// where all of the continuation bytes for a character exist in the same buffer.
64779// It is also done this way as a slight performance increase instead of using a
64780// loop.
64781function utf8CheckExtraBytes(self, buf, p) {
64782 if ((buf[0] & 0xC0) !== 0x80) {
64783 self.lastNeed = 0;
64784 return '\ufffd';
64785 }
64786 if (self.lastNeed > 1 && buf.length > 1) {
64787 if ((buf[1] & 0xC0) !== 0x80) {
64788 self.lastNeed = 1;
64789 return '\ufffd';
64790 }
64791 if (self.lastNeed > 2 && buf.length > 2) {
64792 if ((buf[2] & 0xC0) !== 0x80) {
64793 self.lastNeed = 2;
64794 return '\ufffd';
64795 }
64796 }
64797 }
64798}
64799
64800// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
64801function utf8FillLast(buf) {
64802 var p = this.lastTotal - this.lastNeed;
64803 var r = utf8CheckExtraBytes(this, buf, p);
64804 if (r !== undefined) return r;
64805 if (this.lastNeed <= buf.length) {
64806 buf.copy(this.lastChar, p, 0, this.lastNeed);
64807 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
64808 }
64809 buf.copy(this.lastChar, p, 0, buf.length);
64810 this.lastNeed -= buf.length;
64811}
64812
64813// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
64814// partial character, the character's bytes are buffered until the required
64815// number of bytes are available.
64816function utf8Text(buf, i) {
64817 var total = utf8CheckIncomplete(this, buf, i);
64818 if (!this.lastNeed) return buf.toString('utf8', i);
64819 this.lastTotal = total;
64820 var end = buf.length - (total - this.lastNeed);
64821 buf.copy(this.lastChar, 0, end);
64822 return buf.toString('utf8', i, end);
64823}
64824
64825// For UTF-8, a replacement character is added when ending on a partial
64826// character.
64827function utf8End(buf) {
64828 var r = buf && buf.length ? this.write(buf) : '';
64829 if (this.lastNeed) return r + '\ufffd';
64830 return r;
64831}
64832
64833// UTF-16LE typically needs two bytes per character, but even if we have an even
64834// number of bytes available, we need to check if we end on a leading/high
64835// surrogate. In that case, we need to wait for the next two bytes in order to
64836// decode the last character properly.
64837function utf16Text(buf, i) {
64838 if ((buf.length - i) % 2 === 0) {
64839 var r = buf.toString('utf16le', i);
64840 if (r) {
64841 var c = r.charCodeAt(r.length - 1);
64842 if (c >= 0xD800 && c <= 0xDBFF) {
64843 this.lastNeed = 2;
64844 this.lastTotal = 4;
64845 this.lastChar[0] = buf[buf.length - 2];
64846 this.lastChar[1] = buf[buf.length - 1];
64847 return r.slice(0, -1);
64848 }
64849 }
64850 return r;
64851 }
64852 this.lastNeed = 1;
64853 this.lastTotal = 2;
64854 this.lastChar[0] = buf[buf.length - 1];
64855 return buf.toString('utf16le', i, buf.length - 1);
64856}
64857
64858// For UTF-16LE we do not explicitly append special replacement characters if we
64859// end on a partial character, we simply let v8 handle that.
64860function utf16End(buf) {
64861 var r = buf && buf.length ? this.write(buf) : '';
64862 if (this.lastNeed) {
64863 var end = this.lastTotal - this.lastNeed;
64864 return r + this.lastChar.toString('utf16le', 0, end);
64865 }
64866 return r;
64867}
64868
64869function base64Text(buf, i) {
64870 var n = (buf.length - i) % 3;
64871 if (n === 0) return buf.toString('base64', i);
64872 this.lastNeed = 3 - n;
64873 this.lastTotal = 3;
64874 if (n === 1) {
64875 this.lastChar[0] = buf[buf.length - 1];
64876 } else {
64877 this.lastChar[0] = buf[buf.length - 2];
64878 this.lastChar[1] = buf[buf.length - 1];
64879 }
64880 return buf.toString('base64', i, buf.length - n);
64881}
64882
64883function base64End(buf) {
64884 var r = buf && buf.length ? this.write(buf) : '';
64885 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
64886 return r;
64887}
64888
64889// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
64890function simpleWrite(buf) {
64891 return buf.toString(this.encoding);
64892}
64893
64894function simpleEnd(buf) {
64895 return buf && buf.length ? this.write(buf) : '';
64896}
64897},{"safe-buffer":268}],268:[function(require,module,exports){
64898arguments[4][250][0].apply(exports,arguments)
64899},{"buffer":132,"dup":250}],269:[function(require,module,exports){
64900(function (setImmediate,clearImmediate){(function (){
64901var nextTick = require('process/browser.js').nextTick;
64902var apply = Function.prototype.apply;
64903var slice = Array.prototype.slice;
64904var immediateIds = {};
64905var nextImmediateId = 0;
64906
64907// DOM APIs, for completeness
64908
64909exports.setTimeout = function() {
64910 return new Timeout(apply.call(setTimeout, window, arguments), clearTimeout);
64911};
64912exports.setInterval = function() {
64913 return new Timeout(apply.call(setInterval, window, arguments), clearInterval);
64914};
64915exports.clearTimeout =
64916exports.clearInterval = function(timeout) { timeout.close(); };
64917
64918function Timeout(id, clearFn) {
64919 this._id = id;
64920 this._clearFn = clearFn;
64921}
64922Timeout.prototype.unref = Timeout.prototype.ref = function() {};
64923Timeout.prototype.close = function() {
64924 this._clearFn.call(window, this._id);
64925};
64926
64927// Does not start the time, just sets up the members needed.
64928exports.enroll = function(item, msecs) {
64929 clearTimeout(item._idleTimeoutId);
64930 item._idleTimeout = msecs;
64931};
64932
64933exports.unenroll = function(item) {
64934 clearTimeout(item._idleTimeoutId);
64935 item._idleTimeout = -1;
64936};
64937
64938exports._unrefActive = exports.active = function(item) {
64939 clearTimeout(item._idleTimeoutId);
64940
64941 var msecs = item._idleTimeout;
64942 if (msecs >= 0) {
64943 item._idleTimeoutId = setTimeout(function onTimeout() {
64944 if (item._onTimeout)
64945 item._onTimeout();
64946 }, msecs);
64947 }
64948};
64949
64950// That's not how node.js implements it but the exposed api is the same.
64951exports.setImmediate = typeof setImmediate === "function" ? setImmediate : function(fn) {
64952 var id = nextImmediateId++;
64953 var args = arguments.length < 2 ? false : slice.call(arguments, 1);
64954
64955 immediateIds[id] = true;
64956
64957 nextTick(function onNextTick() {
64958 if (immediateIds[id]) {
64959 // fn.call() is faster so we optimize for the common use-case
64960 // @see http://jsperf.com/call-apply-segu
64961 if (args) {
64962 fn.apply(null, args);
64963 } else {
64964 fn.call(null);
64965 }
64966 // Prevent ids from leaking
64967 exports.clearImmediate(id);
64968 }
64969 });
64970
64971 return id;
64972};
64973
64974exports.clearImmediate = typeof clearImmediate === "function" ? clearImmediate : function(id) {
64975 delete immediateIds[id];
64976};
64977}).call(this)}).call(this,require("timers").setImmediate,require("timers").clearImmediate)
64978},{"process/browser.js":228,"timers":269}],270:[function(require,module,exports){
64979// Copyright Joyent, Inc. and other Node contributors.
64980//
64981// Permission is hereby granted, free of charge, to any person obtaining a
64982// copy of this software and associated documentation files (the
64983// "Software"), to deal in the Software without restriction, including
64984// without limitation the rights to use, copy, modify, merge, publish,
64985// distribute, sublicense, and/or sell copies of the Software, and to permit
64986// persons to whom the Software is furnished to do so, subject to the
64987// following conditions:
64988//
64989// The above copyright notice and this permission notice shall be included
64990// in all copies or substantial portions of the Software.
64991//
64992// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
64993// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
64994// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
64995// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
64996// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
64997// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
64998// USE OR OTHER DEALINGS IN THE SOFTWARE.
64999
65000'use strict';
65001
65002var punycode = require('punycode');
65003var util = require('./util');
65004
65005exports.parse = urlParse;
65006exports.resolve = urlResolve;
65007exports.resolveObject = urlResolveObject;
65008exports.format = urlFormat;
65009
65010exports.Url = Url;
65011
65012function Url() {
65013 this.protocol = null;
65014 this.slashes = null;
65015 this.auth = null;
65016 this.host = null;
65017 this.port = null;
65018 this.hostname = null;
65019 this.hash = null;
65020 this.search = null;
65021 this.query = null;
65022 this.pathname = null;
65023 this.path = null;
65024 this.href = null;
65025}
65026
65027// Reference: RFC 3986, RFC 1808, RFC 2396
65028
65029// define these here so at least they only have to be
65030// compiled once on the first module load.
65031var protocolPattern = /^([a-z0-9.+-]+:)/i,
65032 portPattern = /:[0-9]*$/,
65033
65034 // Special case for a simple path URL
65035 simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/,
65036
65037 // RFC 2396: characters reserved for delimiting URLs.
65038 // We actually just auto-escape these.
65039 delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'],
65040
65041 // RFC 2396: characters not allowed for various reasons.
65042 unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims),
65043
65044 // Allowed by RFCs, but cause of XSS attacks. Always escape these.
65045 autoEscape = ['\''].concat(unwise),
65046 // Characters that are never ever allowed in a hostname.
65047 // Note that any invalid chars are also handled, but these
65048 // are the ones that are *expected* to be seen, so we fast-path
65049 // them.
65050 nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape),
65051 hostEndingChars = ['/', '?', '#'],
65052 hostnameMaxLen = 255,
65053 hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/,
65054 hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/,
65055 // protocols that can allow "unsafe" and "unwise" chars.
65056 unsafeProtocol = {
65057 'javascript': true,
65058 'javascript:': true
65059 },
65060 // protocols that never have a hostname.
65061 hostlessProtocol = {
65062 'javascript': true,
65063 'javascript:': true
65064 },
65065 // protocols that always contain a // bit.
65066 slashedProtocol = {
65067 'http': true,
65068 'https': true,
65069 'ftp': true,
65070 'gopher': true,
65071 'file': true,
65072 'http:': true,
65073 'https:': true,
65074 'ftp:': true,
65075 'gopher:': true,
65076 'file:': true
65077 },
65078 querystring = require('querystring');
65079
65080function urlParse(url, parseQueryString, slashesDenoteHost) {
65081 if (url && util.isObject(url) && url instanceof Url) return url;
65082
65083 var u = new Url;
65084 u.parse(url, parseQueryString, slashesDenoteHost);
65085 return u;
65086}
65087
65088Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) {
65089 if (!util.isString(url)) {
65090 throw new TypeError("Parameter 'url' must be a string, not " + typeof url);
65091 }
65092
65093 // Copy chrome, IE, opera backslash-handling behavior.
65094 // Back slashes before the query string get converted to forward slashes
65095 // See: https://code.google.com/p/chromium/issues/detail?id=25916
65096 var queryIndex = url.indexOf('?'),
65097 splitter =
65098 (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#',
65099 uSplit = url.split(splitter),
65100 slashRegex = /\\/g;
65101 uSplit[0] = uSplit[0].replace(slashRegex, '/');
65102 url = uSplit.join(splitter);
65103
65104 var rest = url;
65105
65106 // trim before proceeding.
65107 // This is to support parse stuff like " http://foo.com \n"
65108 rest = rest.trim();
65109
65110 if (!slashesDenoteHost && url.split('#').length === 1) {
65111 // Try fast path regexp
65112 var simplePath = simplePathPattern.exec(rest);
65113 if (simplePath) {
65114 this.path = rest;
65115 this.href = rest;
65116 this.pathname = simplePath[1];
65117 if (simplePath[2]) {
65118 this.search = simplePath[2];
65119 if (parseQueryString) {
65120 this.query = querystring.parse(this.search.substr(1));
65121 } else {
65122 this.query = this.search.substr(1);
65123 }
65124 } else if (parseQueryString) {
65125 this.search = '';
65126 this.query = {};
65127 }
65128 return this;
65129 }
65130 }
65131
65132 var proto = protocolPattern.exec(rest);
65133 if (proto) {
65134 proto = proto[0];
65135 var lowerProto = proto.toLowerCase();
65136 this.protocol = lowerProto;
65137 rest = rest.substr(proto.length);
65138 }
65139
65140 // figure out if it's got a host
65141 // user@server is *always* interpreted as a hostname, and url
65142 // resolution will treat //foo/bar as host=foo,path=bar because that's
65143 // how the browser resolves relative URLs.
65144 if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) {
65145 var slashes = rest.substr(0, 2) === '//';
65146 if (slashes && !(proto && hostlessProtocol[proto])) {
65147 rest = rest.substr(2);
65148 this.slashes = true;
65149 }
65150 }
65151
65152 if (!hostlessProtocol[proto] &&
65153 (slashes || (proto && !slashedProtocol[proto]))) {
65154
65155 // there's a hostname.
65156 // the first instance of /, ?, ;, or # ends the host.
65157 //
65158 // If there is an @ in the hostname, then non-host chars *are* allowed
65159 // to the left of the last @ sign, unless some host-ending character
65160 // comes *before* the @-sign.
65161 // URLs are obnoxious.
65162 //
65163 // ex:
65164 // http://a@b@c/ => user:a@b host:c
65165 // http://a@b?@c => user:a host:c path:/?@c
65166
65167 // v0.12 TODO(isaacs): This is not quite how Chrome does things.
65168 // Review our test case against browsers more comprehensively.
65169
65170 // find the first instance of any hostEndingChars
65171 var hostEnd = -1;
65172 for (var i = 0; i < hostEndingChars.length; i++) {
65173 var hec = rest.indexOf(hostEndingChars[i]);
65174 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
65175 hostEnd = hec;
65176 }
65177
65178 // at this point, either we have an explicit point where the
65179 // auth portion cannot go past, or the last @ char is the decider.
65180 var auth, atSign;
65181 if (hostEnd === -1) {
65182 // atSign can be anywhere.
65183 atSign = rest.lastIndexOf('@');
65184 } else {
65185 // atSign must be in auth portion.
65186 // http://a@b/c@d => host:b auth:a path:/c@d
65187 atSign = rest.lastIndexOf('@', hostEnd);
65188 }
65189
65190 // Now we have a portion which is definitely the auth.
65191 // Pull that off.
65192 if (atSign !== -1) {
65193 auth = rest.slice(0, atSign);
65194 rest = rest.slice(atSign + 1);
65195 this.auth = decodeURIComponent(auth);
65196 }
65197
65198 // the host is the remaining to the left of the first non-host char
65199 hostEnd = -1;
65200 for (var i = 0; i < nonHostChars.length; i++) {
65201 var hec = rest.indexOf(nonHostChars[i]);
65202 if (hec !== -1 && (hostEnd === -1 || hec < hostEnd))
65203 hostEnd = hec;
65204 }
65205 // if we still have not hit it, then the entire thing is a host.
65206 if (hostEnd === -1)
65207 hostEnd = rest.length;
65208
65209 this.host = rest.slice(0, hostEnd);
65210 rest = rest.slice(hostEnd);
65211
65212 // pull out port.
65213 this.parseHost();
65214
65215 // we've indicated that there is a hostname,
65216 // so even if it's empty, it has to be present.
65217 this.hostname = this.hostname || '';
65218
65219 // if hostname begins with [ and ends with ]
65220 // assume that it's an IPv6 address.
65221 var ipv6Hostname = this.hostname[0] === '[' &&
65222 this.hostname[this.hostname.length - 1] === ']';
65223
65224 // validate a little.
65225 if (!ipv6Hostname) {
65226 var hostparts = this.hostname.split(/\./);
65227 for (var i = 0, l = hostparts.length; i < l; i++) {
65228 var part = hostparts[i];
65229 if (!part) continue;
65230 if (!part.match(hostnamePartPattern)) {
65231 var newpart = '';
65232 for (var j = 0, k = part.length; j < k; j++) {
65233 if (part.charCodeAt(j) > 127) {
65234 // we replace non-ASCII char with a temporary placeholder
65235 // we need this to make sure size of hostname is not
65236 // broken by replacing non-ASCII by nothing
65237 newpart += 'x';
65238 } else {
65239 newpart += part[j];
65240 }
65241 }
65242 // we test again with ASCII char only
65243 if (!newpart.match(hostnamePartPattern)) {
65244 var validParts = hostparts.slice(0, i);
65245 var notHost = hostparts.slice(i + 1);
65246 var bit = part.match(hostnamePartStart);
65247 if (bit) {
65248 validParts.push(bit[1]);
65249 notHost.unshift(bit[2]);
65250 }
65251 if (notHost.length) {
65252 rest = '/' + notHost.join('.') + rest;
65253 }
65254 this.hostname = validParts.join('.');
65255 break;
65256 }
65257 }
65258 }
65259 }
65260
65261 if (this.hostname.length > hostnameMaxLen) {
65262 this.hostname = '';
65263 } else {
65264 // hostnames are always lower case.
65265 this.hostname = this.hostname.toLowerCase();
65266 }
65267
65268 if (!ipv6Hostname) {
65269 // IDNA Support: Returns a punycoded representation of "domain".
65270 // It only converts parts of the domain name that
65271 // have non-ASCII characters, i.e. it doesn't matter if
65272 // you call it with a domain that already is ASCII-only.
65273 this.hostname = punycode.toASCII(this.hostname);
65274 }
65275
65276 var p = this.port ? ':' + this.port : '';
65277 var h = this.hostname || '';
65278 this.host = h + p;
65279 this.href += this.host;
65280
65281 // strip [ and ] from the hostname
65282 // the host field still retains them, though
65283 if (ipv6Hostname) {
65284 this.hostname = this.hostname.substr(1, this.hostname.length - 2);
65285 if (rest[0] !== '/') {
65286 rest = '/' + rest;
65287 }
65288 }
65289 }
65290
65291 // now rest is set to the post-host stuff.
65292 // chop off any delim chars.
65293 if (!unsafeProtocol[lowerProto]) {
65294
65295 // First, make 100% sure that any "autoEscape" chars get
65296 // escaped, even if encodeURIComponent doesn't think they
65297 // need to be.
65298 for (var i = 0, l = autoEscape.length; i < l; i++) {
65299 var ae = autoEscape[i];
65300 if (rest.indexOf(ae) === -1)
65301 continue;
65302 var esc = encodeURIComponent(ae);
65303 if (esc === ae) {
65304 esc = escape(ae);
65305 }
65306 rest = rest.split(ae).join(esc);
65307 }
65308 }
65309
65310
65311 // chop off from the tail first.
65312 var hash = rest.indexOf('#');
65313 if (hash !== -1) {
65314 // got a fragment string.
65315 this.hash = rest.substr(hash);
65316 rest = rest.slice(0, hash);
65317 }
65318 var qm = rest.indexOf('?');
65319 if (qm !== -1) {
65320 this.search = rest.substr(qm);
65321 this.query = rest.substr(qm + 1);
65322 if (parseQueryString) {
65323 this.query = querystring.parse(this.query);
65324 }
65325 rest = rest.slice(0, qm);
65326 } else if (parseQueryString) {
65327 // no query string, but parseQueryString still requested
65328 this.search = '';
65329 this.query = {};
65330 }
65331 if (rest) this.pathname = rest;
65332 if (slashedProtocol[lowerProto] &&
65333 this.hostname && !this.pathname) {
65334 this.pathname = '/';
65335 }
65336
65337 //to support http.request
65338 if (this.pathname || this.search) {
65339 var p = this.pathname || '';
65340 var s = this.search || '';
65341 this.path = p + s;
65342 }
65343
65344 // finally, reconstruct the href based on what has been validated.
65345 this.href = this.format();
65346 return this;
65347};
65348
65349// format a parsed object into a url string
65350function urlFormat(obj) {
65351 // ensure it's an object, and not a string url.
65352 // If it's an obj, this is a no-op.
65353 // this way, you can call url_format() on strings
65354 // to clean up potentially wonky urls.
65355 if (util.isString(obj)) obj = urlParse(obj);
65356 if (!(obj instanceof Url)) return Url.prototype.format.call(obj);
65357 return obj.format();
65358}
65359
65360Url.prototype.format = function() {
65361 var auth = this.auth || '';
65362 if (auth) {
65363 auth = encodeURIComponent(auth);
65364 auth = auth.replace(/%3A/i, ':');
65365 auth += '@';
65366 }
65367
65368 var protocol = this.protocol || '',
65369 pathname = this.pathname || '',
65370 hash = this.hash || '',
65371 host = false,
65372 query = '';
65373
65374 if (this.host) {
65375 host = auth + this.host;
65376 } else if (this.hostname) {
65377 host = auth + (this.hostname.indexOf(':') === -1 ?
65378 this.hostname :
65379 '[' + this.hostname + ']');
65380 if (this.port) {
65381 host += ':' + this.port;
65382 }
65383 }
65384
65385 if (this.query &&
65386 util.isObject(this.query) &&
65387 Object.keys(this.query).length) {
65388 query = querystring.stringify(this.query);
65389 }
65390
65391 var search = this.search || (query && ('?' + query)) || '';
65392
65393 if (protocol && protocol.substr(-1) !== ':') protocol += ':';
65394
65395 // only the slashedProtocols get the //. Not mailto:, xmpp:, etc.
65396 // unless they had them to begin with.
65397 if (this.slashes ||
65398 (!protocol || slashedProtocol[protocol]) && host !== false) {
65399 host = '//' + (host || '');
65400 if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname;
65401 } else if (!host) {
65402 host = '';
65403 }
65404
65405 if (hash && hash.charAt(0) !== '#') hash = '#' + hash;
65406 if (search && search.charAt(0) !== '?') search = '?' + search;
65407
65408 pathname = pathname.replace(/[?#]/g, function(match) {
65409 return encodeURIComponent(match);
65410 });
65411 search = search.replace('#', '%23');
65412
65413 return protocol + host + pathname + search + hash;
65414};
65415
65416function urlResolve(source, relative) {
65417 return urlParse(source, false, true).resolve(relative);
65418}
65419
65420Url.prototype.resolve = function(relative) {
65421 return this.resolveObject(urlParse(relative, false, true)).format();
65422};
65423
65424function urlResolveObject(source, relative) {
65425 if (!source) return relative;
65426 return urlParse(source, false, true).resolveObject(relative);
65427}
65428
65429Url.prototype.resolveObject = function(relative) {
65430 if (util.isString(relative)) {
65431 var rel = new Url();
65432 rel.parse(relative, false, true);
65433 relative = rel;
65434 }
65435
65436 var result = new Url();
65437 var tkeys = Object.keys(this);
65438 for (var tk = 0; tk < tkeys.length; tk++) {
65439 var tkey = tkeys[tk];
65440 result[tkey] = this[tkey];
65441 }
65442
65443 // hash is always overridden, no matter what.
65444 // even href="" will remove it.
65445 result.hash = relative.hash;
65446
65447 // if the relative url is empty, then there's nothing left to do here.
65448 if (relative.href === '') {
65449 result.href = result.format();
65450 return result;
65451 }
65452
65453 // hrefs like //foo/bar always cut to the protocol.
65454 if (relative.slashes && !relative.protocol) {
65455 // take everything except the protocol from relative
65456 var rkeys = Object.keys(relative);
65457 for (var rk = 0; rk < rkeys.length; rk++) {
65458 var rkey = rkeys[rk];
65459 if (rkey !== 'protocol')
65460 result[rkey] = relative[rkey];
65461 }
65462
65463 //urlParse appends trailing / to urls like http://www.example.com
65464 if (slashedProtocol[result.protocol] &&
65465 result.hostname && !result.pathname) {
65466 result.path = result.pathname = '/';
65467 }
65468
65469 result.href = result.format();
65470 return result;
65471 }
65472
65473 if (relative.protocol && relative.protocol !== result.protocol) {
65474 // if it's a known url protocol, then changing
65475 // the protocol does weird things
65476 // first, if it's not file:, then we MUST have a host,
65477 // and if there was a path
65478 // to begin with, then we MUST have a path.
65479 // if it is file:, then the host is dropped,
65480 // because that's known to be hostless.
65481 // anything else is assumed to be absolute.
65482 if (!slashedProtocol[relative.protocol]) {
65483 var keys = Object.keys(relative);
65484 for (var v = 0; v < keys.length; v++) {
65485 var k = keys[v];
65486 result[k] = relative[k];
65487 }
65488 result.href = result.format();
65489 return result;
65490 }
65491
65492 result.protocol = relative.protocol;
65493 if (!relative.host && !hostlessProtocol[relative.protocol]) {
65494 var relPath = (relative.pathname || '').split('/');
65495 while (relPath.length && !(relative.host = relPath.shift()));
65496 if (!relative.host) relative.host = '';
65497 if (!relative.hostname) relative.hostname = '';
65498 if (relPath[0] !== '') relPath.unshift('');
65499 if (relPath.length < 2) relPath.unshift('');
65500 result.pathname = relPath.join('/');
65501 } else {
65502 result.pathname = relative.pathname;
65503 }
65504 result.search = relative.search;
65505 result.query = relative.query;
65506 result.host = relative.host || '';
65507 result.auth = relative.auth;
65508 result.hostname = relative.hostname || relative.host;
65509 result.port = relative.port;
65510 // to support http.request
65511 if (result.pathname || result.search) {
65512 var p = result.pathname || '';
65513 var s = result.search || '';
65514 result.path = p + s;
65515 }
65516 result.slashes = result.slashes || relative.slashes;
65517 result.href = result.format();
65518 return result;
65519 }
65520
65521 var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'),
65522 isRelAbs = (
65523 relative.host ||
65524 relative.pathname && relative.pathname.charAt(0) === '/'
65525 ),
65526 mustEndAbs = (isRelAbs || isSourceAbs ||
65527 (result.host && relative.pathname)),
65528 removeAllDots = mustEndAbs,
65529 srcPath = result.pathname && result.pathname.split('/') || [],
65530 relPath = relative.pathname && relative.pathname.split('/') || [],
65531 psychotic = result.protocol && !slashedProtocol[result.protocol];
65532
65533 // if the url is a non-slashed url, then relative
65534 // links like ../.. should be able
65535 // to crawl up to the hostname, as well. This is strange.
65536 // result.protocol has already been set by now.
65537 // Later on, put the first path part into the host field.
65538 if (psychotic) {
65539 result.hostname = '';
65540 result.port = null;
65541 if (result.host) {
65542 if (srcPath[0] === '') srcPath[0] = result.host;
65543 else srcPath.unshift(result.host);
65544 }
65545 result.host = '';
65546 if (relative.protocol) {
65547 relative.hostname = null;
65548 relative.port = null;
65549 if (relative.host) {
65550 if (relPath[0] === '') relPath[0] = relative.host;
65551 else relPath.unshift(relative.host);
65552 }
65553 relative.host = null;
65554 }
65555 mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === '');
65556 }
65557
65558 if (isRelAbs) {
65559 // it's absolute.
65560 result.host = (relative.host || relative.host === '') ?
65561 relative.host : result.host;
65562 result.hostname = (relative.hostname || relative.hostname === '') ?
65563 relative.hostname : result.hostname;
65564 result.search = relative.search;
65565 result.query = relative.query;
65566 srcPath = relPath;
65567 // fall through to the dot-handling below.
65568 } else if (relPath.length) {
65569 // it's relative
65570 // throw away the existing file, and take the new path instead.
65571 if (!srcPath) srcPath = [];
65572 srcPath.pop();
65573 srcPath = srcPath.concat(relPath);
65574 result.search = relative.search;
65575 result.query = relative.query;
65576 } else if (!util.isNullOrUndefined(relative.search)) {
65577 // just pull out the search.
65578 // like href='?foo'.
65579 // Put this after the other two cases because it simplifies the booleans
65580 if (psychotic) {
65581 result.hostname = result.host = srcPath.shift();
65582 //occationaly the auth can get stuck only in host
65583 //this especially happens in cases like
65584 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
65585 var authInHost = result.host && result.host.indexOf('@') > 0 ?
65586 result.host.split('@') : false;
65587 if (authInHost) {
65588 result.auth = authInHost.shift();
65589 result.host = result.hostname = authInHost.shift();
65590 }
65591 }
65592 result.search = relative.search;
65593 result.query = relative.query;
65594 //to support http.request
65595 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
65596 result.path = (result.pathname ? result.pathname : '') +
65597 (result.search ? result.search : '');
65598 }
65599 result.href = result.format();
65600 return result;
65601 }
65602
65603 if (!srcPath.length) {
65604 // no path at all. easy.
65605 // we've already handled the other stuff above.
65606 result.pathname = null;
65607 //to support http.request
65608 if (result.search) {
65609 result.path = '/' + result.search;
65610 } else {
65611 result.path = null;
65612 }
65613 result.href = result.format();
65614 return result;
65615 }
65616
65617 // if a url ENDs in . or .., then it must get a trailing slash.
65618 // however, if it ends in anything else non-slashy,
65619 // then it must NOT get a trailing slash.
65620 var last = srcPath.slice(-1)[0];
65621 var hasTrailingSlash = (
65622 (result.host || relative.host || srcPath.length > 1) &&
65623 (last === '.' || last === '..') || last === '');
65624
65625 // strip single dots, resolve double dots to parent dir
65626 // if the path tries to go above the root, `up` ends up > 0
65627 var up = 0;
65628 for (var i = srcPath.length; i >= 0; i--) {
65629 last = srcPath[i];
65630 if (last === '.') {
65631 srcPath.splice(i, 1);
65632 } else if (last === '..') {
65633 srcPath.splice(i, 1);
65634 up++;
65635 } else if (up) {
65636 srcPath.splice(i, 1);
65637 up--;
65638 }
65639 }
65640
65641 // if the path is allowed to go above the root, restore leading ..s
65642 if (!mustEndAbs && !removeAllDots) {
65643 for (; up--; up) {
65644 srcPath.unshift('..');
65645 }
65646 }
65647
65648 if (mustEndAbs && srcPath[0] !== '' &&
65649 (!srcPath[0] || srcPath[0].charAt(0) !== '/')) {
65650 srcPath.unshift('');
65651 }
65652
65653 if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) {
65654 srcPath.push('');
65655 }
65656
65657 var isAbsolute = srcPath[0] === '' ||
65658 (srcPath[0] && srcPath[0].charAt(0) === '/');
65659
65660 // put the host back
65661 if (psychotic) {
65662 result.hostname = result.host = isAbsolute ? '' :
65663 srcPath.length ? srcPath.shift() : '';
65664 //occationaly the auth can get stuck only in host
65665 //this especially happens in cases like
65666 //url.resolveObject('mailto:local1@domain1', 'local2@domain2')
65667 var authInHost = result.host && result.host.indexOf('@') > 0 ?
65668 result.host.split('@') : false;
65669 if (authInHost) {
65670 result.auth = authInHost.shift();
65671 result.host = result.hostname = authInHost.shift();
65672 }
65673 }
65674
65675 mustEndAbs = mustEndAbs || (result.host && srcPath.length);
65676
65677 if (mustEndAbs && !isAbsolute) {
65678 srcPath.unshift('');
65679 }
65680
65681 if (!srcPath.length) {
65682 result.pathname = null;
65683 result.path = null;
65684 } else {
65685 result.pathname = srcPath.join('/');
65686 }
65687
65688 //to support request.http
65689 if (!util.isNull(result.pathname) || !util.isNull(result.search)) {
65690 result.path = (result.pathname ? result.pathname : '') +
65691 (result.search ? result.search : '');
65692 }
65693 result.auth = relative.auth || result.auth;
65694 result.slashes = result.slashes || relative.slashes;
65695 result.href = result.format();
65696 return result;
65697};
65698
65699Url.prototype.parseHost = function() {
65700 var host = this.host;
65701 var port = portPattern.exec(host);
65702 if (port) {
65703 port = port[0];
65704 if (port !== ':') {
65705 this.port = port.substr(1);
65706 }
65707 host = host.substr(0, host.length - port.length);
65708 }
65709 if (host) this.hostname = host;
65710};
65711
65712},{"./util":271,"punycode":128,"querystring":237}],271:[function(require,module,exports){
65713'use strict';
65714
65715module.exports = {
65716 isString: function(arg) {
65717 return typeof(arg) === 'string';
65718 },
65719 isObject: function(arg) {
65720 return typeof(arg) === 'object' && arg !== null;
65721 },
65722 isNull: function(arg) {
65723 return arg === null;
65724 },
65725 isNullOrUndefined: function(arg) {
65726 return arg == null;
65727 }
65728};
65729
65730},{}],272:[function(require,module,exports){
65731(function (global){(function (){
65732
65733/**
65734 * Module exports.
65735 */
65736
65737module.exports = deprecate;
65738
65739/**
65740 * Mark that a method should not be used.
65741 * Returns a modified function which warns once by default.
65742 *
65743 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
65744 *
65745 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
65746 * will throw an Error when invoked.
65747 *
65748 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
65749 * will invoke `console.trace()` instead of `console.error()`.
65750 *
65751 * @param {Function} fn - the function to deprecate
65752 * @param {String} msg - the string to print to the console when `fn` is invoked
65753 * @returns {Function} a new "deprecated" version of `fn`
65754 * @api public
65755 */
65756
65757function deprecate (fn, msg) {
65758 if (config('noDeprecation')) {
65759 return fn;
65760 }
65761
65762 var warned = false;
65763 function deprecated() {
65764 if (!warned) {
65765 if (config('throwDeprecation')) {
65766 throw new Error(msg);
65767 } else if (config('traceDeprecation')) {
65768 console.trace(msg);
65769 } else {
65770 console.warn(msg);
65771 }
65772 warned = true;
65773 }
65774 return fn.apply(this, arguments);
65775 }
65776
65777 return deprecated;
65778}
65779
65780/**
65781 * Checks `localStorage` for boolean values for the given `name`.
65782 *
65783 * @param {String} name
65784 * @returns {Boolean}
65785 * @api private
65786 */
65787
65788function config (name) {
65789 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
65790 try {
65791 if (!global.localStorage) return false;
65792 } catch (_) {
65793 return false;
65794 }
65795 var val = global.localStorage[name];
65796 if (null == val) return false;
65797 return String(val).toLowerCase() === 'true';
65798}
65799
65800}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
65801},{}],273:[function(require,module,exports){
65802module.exports={
65803 "name": "bitcore-lib",
65804 "version": "8.25.10",
65805 "description": "A pure and powerful JavaScript Bitcoin library.",
65806 "author": "BitPay <dev@bitpay.com>",
65807 "main": "index.js",
65808 "scripts": {
65809 "test": "gulp test",
65810 "test:ci": "npm run test",
65811 "coverage": "gulp coverage",
65812 "build": "gulp",
65813 "pub": "npm run build && npm publish"
65814 },
65815 "keywords": [
65816 "bitcoin",
65817 "transaction",
65818 "address",
65819 "p2p",
65820 "ecies",
65821 "cryptocurrency",
65822 "blockchain",
65823 "payment",
65824 "bip21",
65825 "bip32",
65826 "bip37",
65827 "bip69",
65828 "bip70",
65829 "multisig"
65830 ],
65831 "repository": {
65832 "type": "git",
65833 "url": "https://github.com/bitpay/bitcore/tree/master/packages/bitcore-lib"
65834 },
65835 "browser": {
65836 "request": "browser-request"
65837 },
65838 "dependencies": {
65839 "bech32": "=2.0.0",
65840 "bip-schnorr": "=0.6.4",
65841 "bn.js": "=4.11.8",
65842 "bs58": "^4.0.1",
65843 "buffer-compare": "=1.1.1",
65844 "elliptic": "^6.5.3",
65845 "inherits": "=2.0.1",
65846 "lodash": "^4.17.20"
65847 },
65848 "devDependencies": {
65849 "bitcore-build": "^8.25.10",
65850 "brfs": "^2.0.1",
65851 "chai": "^4.2.0",
65852 "gulp": "^4.0.0",
65853 "sinon": "^7.1.1"
65854 },
65855 "license": "MIT",
65856 "gitHead": "012cc0216a9bc6b195035855bd17149bad41acd1"
65857}
65858
65859},{}],"bitcore-lib":[function(require,module,exports){
65860(function (global,Buffer){(function (){
65861'use strict';
65862
65863var bitcore = module.exports;
65864
65865// module information
65866bitcore.version = 'v' + require('./package.json').version;
65867bitcore.versionGuard = function(version) {
65868 if (version !== undefined) {
65869 var message = 'More than one instance of bitcore-lib found. ' +
65870 'Please make sure to require bitcore-lib and check that submodules do' +
65871 ' not also include their own bitcore-lib dependency.';
65872 throw new Error(message);
65873 }
65874};
65875bitcore.versionGuard(global._bitcore);
65876global._bitcore = bitcore.version;
65877
65878// crypto
65879bitcore.crypto = {};
65880bitcore.crypto.BN = require('./lib/crypto/bn');
65881bitcore.crypto.ECDSA = require('./lib/crypto/ecdsa');
65882bitcore.crypto.Hash = require('./lib/crypto/hash');
65883bitcore.crypto.Random = require('./lib/crypto/random');
65884bitcore.crypto.Point = require('./lib/crypto/point');
65885bitcore.crypto.Signature = require('./lib/crypto/signature');
65886
65887// encoding
65888bitcore.encoding = {};
65889bitcore.encoding.Base58 = require('./lib/encoding/base58');
65890bitcore.encoding.Base58Check = require('./lib/encoding/base58check');
65891bitcore.encoding.BufferReader = require('./lib/encoding/bufferreader');
65892bitcore.encoding.BufferWriter = require('./lib/encoding/bufferwriter');
65893bitcore.encoding.Varint = require('./lib/encoding/varint');
65894
65895// utilities
65896bitcore.util = {};
65897bitcore.util.buffer = require('./lib/util/buffer');
65898bitcore.util.js = require('./lib/util/js');
65899bitcore.util.preconditions = require('./lib/util/preconditions');
65900
65901// errors thrown by the library
65902bitcore.errors = require('./lib/errors');
65903
65904// main bitcoin library
65905bitcore.Address = require('./lib/address');
65906bitcore.Block = require('./lib/block');
65907bitcore.MerkleBlock = require('./lib/block/merkleblock');
65908bitcore.BlockHeader = require('./lib/block/blockheader');
65909bitcore.HDPrivateKey = require('./lib/hdprivatekey.js');
65910bitcore.HDPublicKey = require('./lib/hdpublickey.js');
65911bitcore.Message = require('./lib/message');
65912bitcore.Networks = require('./lib/networks');
65913bitcore.Opcode = require('./lib/opcode');
65914bitcore.PrivateKey = require('./lib/privatekey');
65915bitcore.PublicKey = require('./lib/publickey');
65916bitcore.Script = require('./lib/script');
65917bitcore.Transaction = require('./lib/transaction');
65918bitcore.URI = require('./lib/uri');
65919bitcore.Unit = require('./lib/unit');
65920
65921// dependencies, subject to change
65922bitcore.deps = {};
65923bitcore.deps.bnjs = require('bn.js');
65924bitcore.deps.bs58 = require('bs58');
65925bitcore.deps.Buffer = Buffer;
65926bitcore.deps.elliptic = require('elliptic');
65927bitcore.deps._ = require('lodash');
65928
65929// Internal usage, exposed for testing/advanced tweaking
65930bitcore.Transaction.sighash = require('./lib/transaction/sighash');
65931
65932}).call(this)}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},require("buffer").Buffer)
65933},{"./lib/address":1,"./lib/block":4,"./lib/block/blockheader":3,"./lib/block/merkleblock":5,"./lib/crypto/bn":6,"./lib/crypto/ecdsa":7,"./lib/crypto/hash":8,"./lib/crypto/point":9,"./lib/crypto/random":10,"./lib/crypto/signature":11,"./lib/encoding/base58":12,"./lib/encoding/base58check":13,"./lib/encoding/bufferreader":15,"./lib/encoding/bufferwriter":16,"./lib/encoding/varint":17,"./lib/errors":18,"./lib/hdprivatekey.js":20,"./lib/hdpublickey.js":21,"./lib/message":22,"./lib/networks":23,"./lib/opcode":24,"./lib/privatekey":25,"./lib/publickey":26,"./lib/script":27,"./lib/transaction":30,"./lib/transaction/sighash":38,"./lib/unit":43,"./lib/uri":44,"./lib/util/buffer":45,"./lib/util/js":46,"./lib/util/preconditions":47,"./package.json":273,"bn.js":80,"bs58":129,"buffer":132,"elliptic":156,"lodash":210}]},{},[]);