]> git.immae.eu Git - perso/Immae/Projets/Cryptomonnaies/BIP39.git/blame - src/js/nebulas.js
Add Nebulas (nebulas.io)
[perso/Immae/Projets/Cryptomonnaies/BIP39.git] / src / js / nebulas.js
CommitLineData
7a113003 1require=(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(require,module,exports){
2"use strict";
3
4var Buffer = require('safe-buffer').Buffer;
5var Base58 = require('bs58');
6var cryptoUtils = require('./utils/crypto-utils.js');
7var utils = require('./utils/utils.js');
8
9var AddressLength = 26;
10var AddressPrefix = 25;
11var NormalType = 87;
12var ContractType = 88;
13
14var KeyVersion3 = 3;
15var KeyCurrentVersion = 4;
16
17/**
18 * @typedef {Object} KeyOptions
19 * @property {Buffer} salt
20 * @property {Buffer} iv
21 * @property {String} kdf
22 * @property {Number} dklen
23 * @property {Number} c
24 * @property {Number} n
25 * @property {Number} r
26 * @property {Number} p
27 * @property {String} cipher
28 * @property {Buffer} uuid
29 * @global
30 */
31
32/**
33 * Key Object.
34 * @typedef {Object} Key
35 * @property {Number} version
36 * @property {Buffer} id
37 * @property {HexString} address
38 * @property {Object} crypto
39 * @global
40 */
41
42/**
43 * Account constructor.
44 * Class encapsulate main operation with account entity.
45 * @constructor
46 *
47 * @param {Hash} priv Account private key.
48 * @param {String} path
49 *
50 * @example var account = new Account(new Buffer("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6", "hex") );
51 *
52 */
53var Account = function (priv, path) {
54 priv = priv || cryptoUtils.crypto.randomBytes(32);
55 this.setPrivateKey(priv);
56 this.path = path;
57};
58
59/**
60 * Account factory method.
61 * Create random account.
62 * @static
63 *
64 * @return {Account} Instance of Account constructor.
65 *
66 * @example var account = Account.NewAccount();
67 */
68Account.NewAccount = function () {
69 return new Account(cryptoUtils.crypto.randomBytes(32));
70};
71
72/**
73 * Address validation method.
74 *
75 * @static
76 * @param {String/Hash} addr - Account address.
77 * @param {Number} type - NormalType / ContractType
78 *
79 * @return {Boolean} Is address has correct format.
80 *
81 * @example
82 * if ( Account.isValidAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5") ) {
83 * // some code
84 * };
85 */
86Account.isValidAddress = function (addr, type) {
87 /*jshint maxcomplexity:10 */
88
89 if (utils.isString(addr)) {
90 try {
91 addr = Base58.decode(addr);
92 } catch (e) {
93 console.log("invalid address.");
94 // if address can't be base58 decode, return false.
95 return false;
96 }
97 } else if (!Buffer.isBuffer(addr)) {
98 return false;
99 }
100 // address not equal to 26
101 if (addr.length !== AddressLength) {
102 return false;
103 }
104
105 // check if address start with AddressPrefix
106 var buff = Buffer.from(addr);
107 if (buff.readUIntBE(0, 1) !== AddressPrefix) {
108 return false;
109 }
110
111 // check if address type is NormalType or ContractType
112 var t = buff.readUIntBE(1, 1);
113 if (utils.isNumber(type) && (type === NormalType || type === ContractType)) {
114 if (t !== type) {
115 return false;
116 }
117 } else if (t !== NormalType && t !== ContractType) {
118 return false;
119 }
120 var content = addr.slice(0, 22);
121 var checksum = addr.slice(-4);
122 return Buffer.compare(cryptoUtils.sha3(content).slice(0, 4), checksum) === 0;
123};
124
125/**
126 * Restore account from address.
127 * Receive addr or Account instance.
128 * If addr is Account instance return new Account instance with same PrivateKey.
129 *
130 * @static
131 * @param {(Hash|Object)} - Client address or Account instance.
132 *
133 * @return {Account} Instance of Account restored from address.
134 *
135 * @example var account = Account.fromAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5");
136 */
137Account.fromAddress = function (addr) {
138 var acc = new Account();
139 if (addr instanceof Account) {
140 acc.setPrivateKey(addr.getPrivateKey());
141 return acc;
142 }
143 if (utils.isString(addr) && this.isValidAddress(addr)) {
144 acc.address = Base58.decode(addr);
145 return acc;
146 }
147
148 var buf = cryptoUtils.toBuffer(addr);
149 if (this.isValidAddress(buf)) {
150 acc.address = buf;
151 return acc;
152 }
153 throw new Error("invalid address");
154};
155
156/**
157 * Restore account from public key.
158 *
159 * @static
160 * @param {(String/Hash)} - Public key.
161 *
162 * @return {Account} Instance of Account restored from address.
163 *
164 * @example var account = Account.fromPubKey("f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7");
165 */
166Account.fromPubKey = function (publicKey) {
167 var acc = new Account();
168 acc.pubKey = cryptoUtils.toBuffer(publicKey);
169 return acc;
170};
171
172Account.getNormalType = function () {
173 return NormalType;
174};
175
176Account.getContractType = function () {
177 return ContractType;
178};
179
180Account.prototype = {
181 /**
182 * Private Key setter.
183 *
184 * @param {Hash} priv - Account private key.
185 *
186 * @example account.setPrivateKey("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6");
187 */
188 setPrivateKey: function (priv) {
189 if (utils.isString(priv) || Buffer.isBuffer(priv)) {
190 this.privKey = priv.length === 32 ? priv : Buffer(priv, 'hex');
191 this.pubKey = null;
192 this.address = null;
193 }
194 },
195 /**
196 * Private Key getter.
197 *
198 * @return {Buffer} Account private key.
199 *
200 * @example var privKey = account.getPrivateKey();
201 * //<Buffer 5b ed 67 f9 9c b3 31 9e 0c 6f 6a 03 54 8b e3 c8 c5 2a 83 64 46 4f 88 6f> 24
202 */
203 getPrivateKey: function () {
204 return this.privKey;
205 },
206 /**
207 * Get Private Key in hex string format.
208 *
209 * @return {HexString} Account private key in String format.
210 *
211 * @example var privKey = account.getPrivateKeyString();
212 * //"ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6"
213 */
214 getPrivateKeyString: function () {
215 return this.getPrivateKey().toString('hex');
216 },
217 /**
218 * Public Key getter.
219 *
220 * @return {Buffer} Account public key.
221 *
222 * @example var publicKey = account.getPublicKey();
223 * //<Buffer c0 96 aa 4e 66 c7 4a 9a c7 18 31 f1 24 72 2a c1 3e b5 df 7f 97 1b 13 1d 46 a2 8a e6 81 c6 1d 96 f7 07 d0 aa e9 a7 67 436b 68 af a8 f0 96 65 17 24 29 ... >
224 */
225 getPublicKey: function () {
226 if (utils.isNull(this.pubKey)) {
227 this.pubKey = cryptoUtils.privateToPublic(this.privKey);
228 }
229 return this.pubKey;
230 },
231 /**
232 * Get Public Key in hex string format.
233 *
234 * @return {HexString} Account public key in String format.
235 *
236 * @example var publicKey = account.getPublicKey();
237 * //"f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7"
238 */
239 getPublicKeyString: function () {
240 return this.getPublicKey().toString('hex');
241 },
242 /**
243 * Accaunt address getter.
244 *
245 * @return {Buffer} Account address.
246 *
247 * @example var publicKey = account.getAddress();
248 * //<Buffer 7f 87 83 58 46 96 12 7d 1a c0 57 1a 42 87 c6 25 36 08 ff 32 61 36 51 7c>
249 */
250 getAddress: function () {
251 if (utils.isNull(this.address)) {
252
253 var pubKey = this.getPublicKey();
254 if (pubKey.length !== 64) {
255 pubKey = cryptoUtils.secp256k1.publicKeyConvert(pubKey, false).slice(1);
256 }
257
258 // The uncompressed form consists of a 0x04 (in analogy to the DER OCTET STRING tag) plus
259 // the concatenation of the binary representation of the X coordinate plus the binary
260 // representation of the y coordinate of the public point.
261 pubKey = Buffer.concat([cryptoUtils.toBuffer(4), pubKey]);
262
263 // Only take the lower 160bits of the hash
264 var content = cryptoUtils.sha3(pubKey);
265 content = cryptoUtils.ripemd160(content);
266 // content = AddressPrefix + NormalType + content(local address only use normal type)
267 content = Buffer.concat([cryptoUtils.toBuffer(AddressPrefix), cryptoUtils.toBuffer(NormalType), content]);
268 var checksum = cryptoUtils.sha3(content).slice(0, 4);
269 this.address = Buffer.concat([content, checksum]);
270 }
271 return this.address;
272 },
273 /**
274 * Get account address in hex string format.
275 *
276 * @return {HexString} Account address in String format.
277 *
278 * @example var publicKey = account.getAddressString();
279 * //"802d529bf55d6693b3ac72c59b4a7d159da53cae5a7bf99c"
280 */
281 getAddressString: function () {
282 var addr = this.getAddress();
283 return Base58.encode(addr);
284 },
285 /**
286 * Generate key buy passphrase and options.
287 *
288 * @param {Password} password - Provided password.
289 * @param {KeyOptions} opts - Key options.
290 *
291 * @return {Key} Key Object.
292 *
293 * @example var key = account.toKey("passphrase");
294 */
295 toKey: function (password, opts) {
296 /*jshint maxcomplexity:17 */
297
298 opts = opts || {};
299 var salt = opts.salt || cryptoUtils.crypto.randomBytes(32);
300 var iv = opts.iv || cryptoUtils.crypto.randomBytes(16);
301 var derivedKey;
302 var kdf = opts.kdf || 'scrypt';
303 var kdfparams = {
304 dklen: opts.dklen || 32,
305 salt: salt.toString('hex')
306 };
307 if (kdf === 'pbkdf2') {
308 kdfparams.c = opts.c || 262144;
309 kdfparams.prf = 'hmac-sha256';
310 derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256');
311 } else if (kdf === 'scrypt') {
312 kdfparams.n = opts.n || 4096;
313 kdfparams.r = opts.r || 8;
314 kdfparams.p = opts.p || 1;
315 derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
316 } else {
317 throw new Error('Unsupported kdf');
318 }
319 var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv);
320 if (!cipher) {
321 throw new Error('Unsupported cipher');
322 }
323 var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]);
324 // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')])); // KeyVersion3 deprecated
325 var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')]));
326 return {
327 version: KeyCurrentVersion,
328 id: cryptoUtils.uuid.v4({
329 random: opts.uuid || cryptoUtils.crypto.randomBytes(16)
330 }),
331 address: this.getAddressString(),
332 crypto: {
333 ciphertext: ciphertext.toString('hex'),
334 cipherparams: {
335 iv: iv.toString('hex')
336 },
337 cipher: opts.cipher || 'aes-128-ctr',
338 kdf: kdf,
339 kdfparams: kdfparams,
340 mac: mac.toString('hex'),
341 machash: "sha3256"
342 }
343 };
344 },
345 /**
346 * Generate key buy passphrase and options.
347 * Return in JSON format.
348 *
349 * @param {Password} password - Provided password.
350 * @param {KeyOptions} opts - Key options.
351 *
352 * @return {String} JSON stringify Key.
353 *
354 * @example var key = account.toKeyString("passphrase");
355 */
356 toKeyString: function (password, opts) {
357 return JSON.stringify(this.toKey(password, opts));
358 },
359 /**
360 * Restore account from key and passphrase.
361 *
362 * @param {Key} input - Key Object.
363 * @param {Password} password - Provided password.
364 * @param {Boolean} nonStrict - Strict сase sensitivity flag.
365 *
366 * @return {@link Account} - Instance of Account restored from key and passphrase.
367 */
368 fromKey: function (input, password, nonStrict) {
369 /*jshint maxcomplexity:10 */
370
371 var json = typeof input === 'object' ? input : JSON.parse(nonStrict ? input.toLowerCase() : input);
372 if (json.version !== KeyVersion3 && json.version !== KeyCurrentVersion) {
373 throw new Error('Not supported wallet version');
374 }
375 var derivedKey;
376 var kdfparams;
377 if (json.crypto.kdf === 'scrypt') {
378 kdfparams = json.crypto.kdfparams;
379 derivedKey = cryptoUtils.scrypt(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen);
380 } else if (json.crypto.kdf === 'pbkdf2') {
381 kdfparams = json.crypto.kdfparams;
382 if (kdfparams.prf !== 'hmac-sha256') {
383 throw new Error('Unsupported parameters to PBKDF2');
384 }
385 derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256');
386 } else {
387 throw new Error('Unsupported key derivation scheme');
388 }
389 var ciphertext = new Buffer(json.crypto.ciphertext, 'hex');
390 var mac;
391
392 if (json.version === KeyCurrentVersion) {
393 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext, new Buffer(json.crypto.cipherparams.iv, 'hex'), new Buffer(json.crypto.cipher)]));
394 } else {
395 // KeyVersion3
396 mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext]));
397 }
398
399 if (mac.toString('hex') !== json.crypto.mac) {
400 throw new Error('Key derivation failed - possibly wrong passphrase');
401 }
402 var decipher = cryptoUtils.crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex'));
403 var seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]);
404 while (seed.length < 32) {
405 var nullBuff = new Buffer([0x00]);
406 seed = Buffer.concat([nullBuff, seed]);
407 }
408 this.setPrivateKey(seed);
409 return this;
410 }
411
412};
413
414module.exports = Account;
415
416},{"./utils/crypto-utils.js":19,"./utils/utils.js":21,"bs58":105,"safe-buffer":247}],2:[function(require,module,exports){
417
418"use strict";
419
420var utils = require('./utils/utils.js');
421
422/**
423 * Admin API constructor.
424 * Class encapsulate methods for admin APIs commands.
425 * @see [Admin API documentation:]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md}.
426 * @constructor
427 *
428 * @param {Neb} neb - Instance of Neb library.
429 *
430 * @example
431 * var admin = new Admin( new Neb() );
432 * // or just
433 * var admin = new Neb().admin;
434 */
435var Admin = function (neb) {
436 this._setRequest(neb._request);
437};
438
439/**
440 * @private
441 * @param {Request} request - transport wrapper.
442 */
443Admin.prototype._setRequest = function (request) {
444 this._request = request;
445 this._path = '/admin';
446};
447
448/**
449 * Method get info about nodes in Nebulas Network.
450 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#nodeinfo}
451 *
452 * @return [nodeInfoObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#nodeinfo}
453 *
454 * @example
455 * var admin = new Neb().admin;
456 * admin.nodeInfo().then(function(info) {
457 * //code
458 * });
459 */
460Admin.prototype.nodeInfo = function () {
461 return this._sendRequest("get", "/nodeinfo", null);
462};
463
464/**
465 * Method get list of available addresses.
466 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#accounts}
467 *
468 * @return [accountsList]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#accounts}
469 *
470 * @example
471 * var admin = new Neb().admin;
472 * admin.accounts().then(function(accounts) {
473 * //code
474 * });
475 */
476Admin.prototype.accounts = function () {
477 return this._sendRequest("get", "/accounts", null);
478};
479
480/**
481 * Method create a new account in Nebulas network with provided passphrase.
482 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#newaccount}
483 *
484 * @param {Object} options
485 * @param {Password} options.passphrase
486 *
487 * @return [address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#newaccount}
488 *
489 * @example
490 * var admin = new Neb().admin;
491 * admin.newAccount({passphrase: "passphrase"}).then(function(address) {
492 * //code
493 * });
494 */
495Admin.prototype.newAccount = function (options) {
496 options = utils.argumentsToObject(['passphrase'], arguments);
497 var params = { "passphrase": options.passphrase };
498 return this._sendRequest("post", "/account/new", params);
499};
500
501/**
502 * Method unlock account with provided passphrase.
503 * After the default unlock time, the account will be locked.
504 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#unlockaccount}
505 *
506 * @param {Object} options
507 * @param {HexString} options.address
508 * @param {Password} options.passphrase
509 * @param {Number} options.duration
510 *
511 * @return [isUnLocked]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#unlockaccount}
512 *
513 * @example
514 * var admin = new Neb().admin;
515 * admin.unlockAccount({
516 * address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh",
517 * passphrase: "passphrase",
518 * duration: 1000000000
519 * }).then(function(isUnLocked) {
520 * //code
521 * });
522 */
523Admin.prototype.unlockAccount = function (options) {
524 options = utils.argumentsToObject(['address', 'passphrase', 'duration'], arguments);
525 var params = {
526 "address": options.address,
527 "passphrase": options.passphrase,
528 "duration": options.duration
529 };
530 return this._sendRequest("post", "/account/unlock", params);
531};
532
533/**
534 * Method lock account.
535 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#lockaccount}
536 *
537 * @param {Object} options
538 * @param {HexString} options.address
539 *
540 * @return [isLocked]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#lockaccount}
541 *
542 * @example
543 * var admin = new Neb().admin;
544 * admin.lockAccount({address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh"}).then(function(isLocked) {
545 * //code
546 * });
547 */
548Admin.prototype.lockAccount = function (options) {
549 options = utils.argumentsToObject(['address'], arguments);
550 var params = { "address": options.address };
551 return this._sendRequest("post", "/account/lock", params);
552};
553
554/**
555 * Method wrap transaction sending functionality.
556 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransaction}
557 *
558 * @param {TransactionOptions} options
559 *
560 * @return [Transcation hash and contract address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransaction}
561 *
562 * @example
563 * var admin = new Neb().admin;
564 * admin.sendTransaction({
565 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
566 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
567 * value: 10,
568 * nonce: 12,
569 * gasPrice: 1000000,
570 * gasLimit: 2000000
571 * }).then(function(tx) {
572 * //code
573 * });
574 */
575Admin.prototype.sendTransaction = function (options) {
576 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary'], arguments);
577 var params = {
578 "from": options.from,
579 "to": options.to,
580 "value": utils.toString(options.value),
581 "nonce": options.nonce,
582 "gasPrice": utils.toString(options.gasPrice),
583 "gasLimit": utils.toString(options.gasLimit),
584 "contract": options.contract,
585 "binary": options.binary
586 };
587 return this._sendRequest("post", "/transaction", params);
588};
589
590/**
591 * Method sign hash.
592 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signhash}
593 *
594 * @param {Object} options
595 * @param {HexString} options.address
596 * @param {Base64} options.hash of hash bytes with base64 encode.
597 * @param {UInt32} options.alg
598 *
599 * @return [data]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signhash}
600 *
601 * @example
602 * var admin = new Neb().admin;
603 * admin.SignHash({
604 * address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh",
605 * hash: "OGQ5NjllZWY2ZWNhZDNjMjlhM2E2MjkyODBlNjg2Y2YwYzNmNWQ1YTg2YWZmM2NhMTIwMjBjOTIzYWRjNmM5Mg==",
606 * alg: 1
607 * }).then(function(data) {
608 * //code
609 * });
610 */
611Admin.prototype.signHash = function (options) {
612 options = utils.argumentsToObject(['address', 'hash', 'alg'], arguments);
613 var params = {
614 "address": options.address,
615 "hash": options.hash,
616 "alg": options.alg
617 };
618 return this._sendRequest("post", "/sign/hash", params);
619};
620
621/**
622 * Method sign transaction with passphrase.
623 * The transaction's from addrees must be unlock before sign call.
624 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signtransactionwithpassphrase}
625 *
626 * @param {TransactionOptions} options
627 * @param {Password} options.passphrase
628 *
629 * @return [Transcation hash and contract address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signtransactionwithpassphrase}
630 *
631 * @example
632 * var admin = new Neb().admin;
633 * admin.signTransactionWithPassphrase({
634 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
635 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
636 * value: 10,
637 * nonce: 12,
638 * gasPrice: 1000000,
639 * gasLimit: 2000000,
640 * passphrase: "passphrase"
641 * }).then(function(tx) {
642 * //code
643 * });
644 */
645Admin.prototype.signTransactionWithPassphrase = function (options) {
646 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary', 'passphrase'], arguments);
647 var tx = {
648 "from": options.from,
649 "to": options.to,
650 "value": utils.toString(options.value),
651 "nonce": options.nonce,
652 "gasPrice": utils.toString(options.gasPrice),
653 "gasLimit": utils.toString(options.gasLimit),
654 "contract": options.contract,
655 "binary": options.binary
656 };
657 var params = {
658 "transaction": tx,
659 "passphrase": options.passphrase
660 };
661 return this._sendRequest("post", "/sign", params);
662};
663
664/**
665 * Method send transaction with passphrase.
666 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransactionwithpassphrase}
667 *
668 * @param {TransactionOptions} options
669 * @param {Password} options.passphrase
670 *
671 * @return [data]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransactionwithpassphrase}
672 *
673 * @example
674 * var admin = new Neb().admin;
675 * admin.sendTransactionWithPassphrase({
676 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
677 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
678 * value: 10,
679 * nonce: 12,
680 * gasPrice: 1000000,
681 * gasLimit: 2000000,
682 * passphrase: "passphrase"
683 * }).then(function(tx) {
684 * //code
685 * });
686 */
687Admin.prototype.sendTransactionWithPassphrase = function (options) {
688 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary', 'passphrase'], arguments);
689 var tx = {
690 "from": options.from,
691 "to": options.to,
692 "value": utils.toString(options.value),
693 "nonce": options.nonce,
694 "gasPrice": utils.toString(options.gasPrice),
695 "gasLimit": utils.toString(options.gasLimit),
696 "contract": options.contract,
697 "binary": options.binary
698 };
699 var params = {
700 "transaction": tx,
701 "passphrase": options.passphrase
702 };
703 return this._sendRequest("post", "/transactionWithPassphrase", params);
704};
705
706/**
707 * Method start listen provided port.
708 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#startpprof}
709 *
710 * @param {Object} options
711 * @param {String} options.listen - Listen port.
712 *
713 * @return [isListenStrted]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#startpprof}
714 *
715 * @example
716 * var admin = new Neb().admin;
717 * admin.startPprof({listen: '8080'}).then(function(isListenStrted) {
718 * //code
719 * });
720 */
721Admin.prototype.startPprof = function (options) {
722 options = utils.argumentsToObject(['listen'], arguments);
723 var params = { "listen": options.listen };
724 return this._sendRequest("post", "/pprof", params);
725};
726
727/**
728 * Method get config of node in Nebulas Network.
729 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#getConfig}
730 *
731 * @return [config]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#getConfig}
732 *
733 * @example
734 * var admin = new Neb().admin;
735 * admin.getConfig().then(function(info) {
736 * //code
737 * });
738 */
739Admin.prototype.getConfig = function () {
740 return this._sendRequest("get", "/getConfig", null);
741};
742
743Admin.prototype._sendRequest = function (method, api, params, callback) {
744 var action = this._path + api;
745 if (typeof callback === "function") {
746 return this._request.asyncRequest(method, action, params, callback);
747 } else {
748 return this._request.request(method, action, params);
749 }
750};
751
752module.exports = Admin;
753
754},{"./utils/utils.js":21}],3:[function(require,module,exports){
755
756"use strict";
757
758var utils = require('./utils/utils.js');
759
760/**
761 * User API constructor.
762 * Class encapsulate methods for building distributed applications and services.
763 *
764 * @see [API documentation]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md}
765 * @constructor
766 *
767 * @param {Neb} neb - Instance of Neb library.
768 *
769 * @example
770 * var api = new API ( new Neb() );
771 * // or just
772 * var api = new Neb().api;
773 */
774var API = function (neb) {
775 this._setRequest(neb._request);
776};
777
778/**
779 * @private
780 * @param {Request} request - transport wrapper.
781 */
782API.prototype._setRequest = function (request) {
783 this._request = request;
784 this._path = '/user';
785};
786
787/**
788 * Method get state of Nebulas Network.
789 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getnebstate}
790 *
791 * @return [NebStateObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getnebstate}
792 *
793 * @example
794 * var api = new Neb().api;
795 * api.getNebState().then(function(state) {
796 * //code
797 * });
798 */
799API.prototype.getNebState = function () {
800 return this._sendRequest("get", "/nebstate", null);
801};
802
803/**
804 * Method get latest irreversible block of Nebulas Network.
805 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#latestirreversibleblock}
806 *
807 * @return [dataBlockInfo.]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#latestirreversibleblock}
808 *
809 * @example
810 * var api = new Neb().api;
811 * api.latestIrreversibleBlock().then(function(blockData) {
812 * //code
813 * });
814 */
815API.prototype.latestIrreversibleBlock = function () {
816 return this._sendRequest("get", "/lib", null);
817};
818
819/**
820 * Method return the state of the account. Balance and nonce.
821 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getaccountstate}
822 *
823 * @param {Object} options
824 * @param {HexString} options.address
825 * @param {String} options.height
826 *
827 * @return [accaountStateObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getaccountstate}
828 *
829 * @example
830 * var api = new Neb().api;
831 * api.getAccountState({address: "n1QsosVXKxiV3B4iDWNmxfN4VqpHn2TeUcn"}).then(function(state) {
832 * //code
833 * });
834 */
835API.prototype.getAccountState = function (options) {
836 options = utils.argumentsToObject(['address', 'height'], arguments);
837 var params = { "address": options.address, "height": options.height };
838 return this._sendRequest("post", "/accountstate", params);
839};
840
841/**
842 * Method wrap smart contract call functionality.
843 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#call}
844 *
845 * @param {TransactionOptions} options
846 *
847 * @return [Transcation hash]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#call}
848 *
849 * @example
850 * var api = new Neb().api;
851 * api.call({
852 * chainID: 1,
853 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
854 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
855 * value: 10,
856 * nonce: 12,
857 * gasPrice: 1000000,
858 * gasLimit: 2000000,
859 * contract: {
860 * function: "save",
861 * args: "[0]"
862 * }
863 * }).then(function(tx) {
864 * //code
865 * });
866 */
867API.prototype.call = function (options) {
868 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments);
869 var params = {
870 "from": options.from,
871 "to": options.to,
872 "value": utils.toString(options.value),
873 "nonce": options.nonce,
874 "gasPrice": utils.toString(options.gasPrice),
875 "gasLimit": utils.toString(options.gasLimit),
876 "contract": options.contract
877 };
878 return this._sendRequest("post", "/call", params);
879};
880
881/**
882 * Method wrap submit the signed transaction.
883 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction}
884 *
885 * @param {Object} options
886 * @param {String} options.data
887 *
888 * @return [Transcation hash]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction}
889 *
890 * @example
891 * var api = new Neb().api;
892 * var tx = new Transaction({
893 * chainID: 1,
894 * from: acc1,
895 * to: acc2,
896 * value: 10,
897 * nonce: 12,
898 * gasPrice: 1000000,
899 * gasLimit: 2000000
900 * });
901 * tx.signTransaction();
902 * api.sendRawTransaction( {data: tx.toProtoString()} ).then(function(hash) {
903 * //code
904 * });
905 */
906API.prototype.sendRawTransaction = function (options) {
907 options = utils.argumentsToObject(['data'], arguments);
908 var params = { "data": options.data };
909 return this._sendRequest("post", "/rawtransaction", params);
910};
911
912/**
913 * Get block header info by the block hash.
914 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyhash}
915 *
916 * @param {Object} options
917 * @param {HexString} options.hash
918 * @param {Boolean} options.fullTransaction
919 *
920 * @return [Block]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyhash}
921 *
922 * @example
923 * var api = new Neb().api;
924 * api.getBlockByHash({
925 * hash: "00000658397a90df6459b8e7e63ad3f4ce8f0a40b8803ff2f29c611b2e0190b8",
926 * fullTransaction: true
927 * }).then(function(block) {
928 * //code
929 * });
930 */
931API.prototype.getBlockByHash = function (options) {
932 options = utils.argumentsToObject(['hash', 'fullTransaction'], arguments);
933 var params = { "hash": options.hash, "full_fill_transaction": options.fullTransaction };
934 return this._sendRequest("post", "/getBlockByHash", params);
935};
936
937/**
938 * Get block header info by the block height.
939 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyheight}
940 *
941 * @param {Object} options
942 * @param {Number} options.height
943 * @param {Boolean} options.fullTransaction
944 *
945 * @return [Block]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyheight}
946 *
947 * @example
948 * var api = new Neb().api;
949 * api.getBlockByHeight({height:2, fullTransaction:true}).then(function(block) {
950 * //code
951 * });
952 */
953API.prototype.getBlockByHeight = function (options) {
954 options = utils.argumentsToObject(['height', 'fullTransaction'], arguments);
955 var params = { "height": options.height, "full_fill_transaction": options.fullTransaction };
956 return this._sendRequest("post", "/getBlockByHeight", params);
957};
958
959/**
960 * Get transactionReceipt info by tansaction hash.
961 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt}
962 *
963 * @param {Object} options
964 * @param {HexString} options.hash
965 *
966 * @return [TransactionReceipt]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt}
967 *
968 * @example
969 * var api = new Neb().api;
970 * api.getTransactionReceipt({hash: "cc7133643a9ae90ec9fa222871b85349ccb6f04452b835851280285ed72b008c"}).then(function(receipt) {
971 * //code
972 * });
973 */
974API.prototype.getTransactionReceipt = function (options) {
975 options = utils.argumentsToObject(['hash'], arguments);
976 var params = { "hash": options.hash };
977 return this._sendRequest("post", "/getTransactionReceipt", params);
978};
979
980/**
981 * Get transactionReceipt info by contract address.
982 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionbycontract}
983 *
984 * @param {Object} options
985 * @param {HexString} options.address contract address
986 *
987 * @returns the same as [TransactionReceipt]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt}
988 *
989 * @example
990 * var api = new Neb().api;
991 * api.getTransactionByContract({address: "n1sqDHGjYtX6rMqFoq5Tow3s3LqF4ZxBvE3"}).then(function(receipt) {
992 * //code
993 * });
994 */
995API.prototype.getTransactionByContract = function (options) {
996 options = utils.argumentsToObject(['address'], arguments);
997 var params = { "address": options.address };
998 return this._sendRequest("post", "/getTransactionByContract", params);
999};
1000
1001/**
1002 * Return the subscribed events of transaction & block.
1003 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#subscribe}
1004 *
1005 * @param {Object} options
1006 * @param {Array|String} options.topics
1007 * @param {Function} options.onDownloadProgress - On progress callback function. Recive chunk.
1008 *
1009 * @return [eventData]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#subscribe}
1010 *
1011 * @example
1012 * var api = new Neb().api;
1013 * api.subscribe({topics: ["chain.linkBlock", "chain.pendingTransaction"]}).then(function(eventData) {
1014 * //code
1015 * });
1016 */
1017API.prototype.subscribe = function (options) {
1018 options = utils.argumentsToObject(['topics', 'onDownloadProgress'], arguments);
1019 var params = { "topics": options.topics };
1020 var axiosOptions;
1021 if (typeof options.onDownloadProgress === 'function') {
1022 axiosOptions = {
1023 onDownloadProgress: function (e) {
1024 if (typeof e.target._readLength === 'undefined') {
1025 e.target._readLength = 0;
1026 }
1027 var chunk = e.target.responseText.substr(e.target._readLength);
1028 // TODO check and split multi events
1029 if (chunk && chunk.trim().length > 0) {
1030 e.target._readLength += chunk.length;
1031 options.onDownloadProgress(chunk);
1032 }
1033 }
1034 };
1035 }
1036 return this._sendRequest("post", "/subscribe", params, null, axiosOptions);
1037};
1038
1039/**
1040 * Return current gasPrice.
1041 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getgasprice}
1042 *
1043 * @return [Gas Price]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getgasprice}
1044 *
1045 * @example
1046 * var api = new Neb().api;
1047 * api.gasPrice().then(function(gasPrice) {
1048 * //code
1049 * });
1050 */
1051API.prototype.gasPrice = function () {
1052 return this._sendRequest("get", "/getGasPrice", null);
1053};
1054
1055/**
1056 * Return the estimate gas of transaction.
1057 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#estimategas}
1058 *
1059 * @param {TransactionOptions} options
1060 *
1061 * @return [Gas]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#estimategas}
1062 *
1063 * @example
1064 * var api = new Neb().api;
1065 * api.estimateGas({
1066 * chainID: 1,
1067 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
1068 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
1069 * value: 10,
1070 * nonce: 12,
1071 * gasPrice: 1000000,
1072 * gasLimit: 2000000
1073 * }).then(function(gas) {
1074 * //code
1075 * });
1076 */
1077API.prototype.estimateGas = function (options) {
1078 options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary'], arguments);
1079 var params = {
1080 "from": options.from,
1081 "to": options.to,
1082 "value": utils.toString(options.value),
1083 "nonce": options.nonce,
1084 "gasPrice": utils.toString(options.gasPrice),
1085 "gasLimit": utils.toString(options.gasLimit),
1086 "contract": options.contract,
1087 "binary": options.binary
1088 };
1089 return this._sendRequest("post", "/estimateGas", params);
1090};
1091
1092/**
1093 * Return the events list of transaction.
1094 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#geteventsbyhash}
1095 *
1096 * @param {Object} options
1097 * @param {HexString} options.hash
1098 *
1099 * @return [Events]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#geteventsbyhash}
1100 *
1101 * @example
1102 * var api = new Neb().api;
1103 * api.getEventsByHash({hash: "ec239d532249f84f158ef8ec9262e1d3d439709ebf4dd5f7c1036b26c6fe8073"}).then(function(events) {
1104 * //code
1105 * });
1106 */
1107API.prototype.getEventsByHash = function (options) {
1108 options = utils.argumentsToObject(['hash'], arguments);
1109 var params = { "hash": options.hash };
1110 return this._sendRequest("post", "/getEventsByHash", params);
1111};
1112
1113/**
1114 * Method getter for dpos dynasty.
1115 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getdynasty}
1116 *
1117 * @param {Object} options
1118 * @param {Number} options.height
1119 *
1120 * @return [delegatees]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getdynasty}
1121 *
1122 * @example
1123 * var api = new Neb().api;
1124 * api.getDynasty({height: 1}).then(function(delegatees) {
1125 * //code
1126 * });
1127 */
1128API.prototype.getDynasty = function (options) {
1129 options = utils.argumentsToObject(['height'], arguments);
1130 var params = { "height": options.height };
1131 return this._sendRequest("post", "/dynasty", params);
1132};
1133
1134API.prototype._sendRequest = function (method, api, params, callback, axiosOptions) {
1135 var action = this._path + api;
1136 if (typeof callback === "function") {
1137 return this._request.asyncRequest(method, action, params, callback);
1138 } else {
1139 return this._request.request(method, action, params, axiosOptions);
1140 }
1141};
1142
1143module.exports = API;
1144
1145},{"./utils/utils.js":21}],4:[function(require,module,exports){
1146"use strict";
1147
1148var axios = require("axios");
1149
1150var debugLog = false;
1151
1152var HttpRequest = function (host, timeout, apiVersion) {
1153 this.host = host || "http://localhost:8685";
1154 this.timeout = timeout || 0;
1155 this.apiVersion = apiVersion || "v1";
1156};
1157
1158HttpRequest.prototype.setHost = function (host) {
1159 this.host = host;
1160};
1161
1162HttpRequest.prototype.setAPIVersion = function (apiVersion) {
1163 this.apiVersion = apiVersion;
1164};
1165
1166HttpRequest.prototype.createUrl = function (api) {
1167 return this.host + "/" + this.apiVersion + api;
1168};
1169
1170HttpRequest.prototype.request = function (method, api, payload, axiosOptions) {
1171 if (debugLog) {
1172 console.log("[debug] HttpRequest: " + method + " " + this.createUrl(api) + " " + JSON.stringify(payload));
1173 }
1174
1175 var axiosParams = {
1176 method: method,
1177 url: this.createUrl(api),
1178 data: payload
1179 };
1180 if (axiosOptions && typeof axiosOptions.onDownloadProgress === 'function') {
1181 axiosParams.onDownloadProgress = axiosOptions.onDownloadProgress;
1182 }
1183 return axios(axiosParams).then(function (resp) {
1184 if ("text/html; charset=UTF-8" === resp.headers['content-type']) {
1185 throw new Error(resp.status + ' - ' + resp.statusText);
1186 }
1187 if (typeof resp.data === "string") {
1188 try {
1189 resp.data = JSON.parse(resp.data);
1190 } catch (e) {
1191 throw new Error('Response is invalid json');
1192 }
1193 }
1194 return resp.data.result || resp.data;
1195 }).catch(function (e) {
1196 if (typeof e.response !== "undefined") {
1197 if (typeof e.response.data === 'object') {
1198 //400 error
1199 throw new Error(e.response.data.error);
1200 } else {
1201 //500 error
1202 var err = e.response.status + ' - ' + e.response.statusText;
1203 err += "\n" + api + " " + JSON.stringify(payload);
1204 throw new Error(err);
1205 }
1206 } else {
1207 throw new Error(e.message);
1208 }
1209 });
1210};
1211
1212HttpRequest.prototype.asyncRequest = function (method, api, payload, callback) {
1213 return this.request(method, api, payload).then(function (data) {
1214 callback(data);
1215 }).catch(function (err) {
1216 callback(err);
1217 });
1218};
1219
1220module.exports = HttpRequest;
1221
1222},{"axios":46}],5:[function(require,module,exports){
1223
1224"use strict";
1225
1226var API = require("./api.js");
1227var Admin = require("./admin.js");
1228
1229var Unit = require("./utils/unit.js");
1230
1231/**
1232 * Neb API library constructor.
1233 * @constructor
1234 * @param {Request} request - transport wrapper.
1235 */
1236var Neb = function (request) {
1237 if (request) {
1238 this._request = request;
1239 }
1240
1241 this.api = new API(this);
1242 this.admin = new Admin(this);
1243};
1244
1245Neb.prototype.setRequest = function (request) {
1246 this._request = request;
1247 this.api._setRequest(request);
1248 this.admin._setRequest(request);
1249};
1250
1251Neb.prototype.toBasic = Unit.toBasic;
1252Neb.prototype.fromBasic = Unit.fromBasic;
1253Neb.prototype.nasToBasic = Unit.nasToBasic;
1254
1255module.exports = Neb;
1256
1257},{"./admin.js":2,"./api.js":3,"./utils/unit.js":20}],6:[function(require,module,exports){
1258"use strict";
1259
1260var block = {
1261 timestamp: 0,
1262 height: 1,
1263 seed: "s"
1264};
1265
1266var transaction = {
1267 hash: "",
1268 from: "",
1269 to: "",
1270 value: "0",
1271 nonce: 1,
1272 timestamp: 0,
1273 gasPrice: "0",
1274 gasLimit: "0"
1275};
1276
1277var state = function () {};
1278
1279module.exports = {
1280 block: block,
1281 transaction: transaction,
1282 state: state
1283};
1284
1285},{}],7:[function(require,module,exports){
1286// Copyright (C) 2017 go-nebulas authors
1287//
1288// This file is part of the go-nebulas library.
1289//
1290// the go-nebulas library is free software: you can redistribute it and/or modify
1291// it under the terms of the GNU General Public License as published by
1292// the Free Software Foundation, either version 3 of the License, or
1293// (at your option) any later version.
1294//
1295// the go-nebulas library is distributed in the hope that it will be useful,
1296// but WITHOUT ANY WARRANTY; without even the implied warranty of
1297// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1298// GNU General Public License for more details.
1299//
1300// You should have received a copy of the GNU General Public License
1301// along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>.
1302//
1303
1304'use strict';
1305
1306var Blockchain = function () {
1307 Object.defineProperty(this, "nativeBlockchain", {
1308 configurable: false,
1309 enumerable: false,
1310 get: function () {
1311 return _native_blockchain;
1312 }
1313 });
1314};
1315
1316Blockchain.prototype = {
1317 AccountAddress: 0x57,
1318 ContractAddress: 0x58,
1319
1320 blockParse: function (str) {
1321 this.block = JSON.parse(str);
1322 },
1323 transactionParse: function (str) {
1324 var tx = JSON.parse(str);
1325 if (tx != null) {
1326 var value = tx.value === undefined || tx.value.length === 0 ? "0" : tx.value;
1327 tx.value = new BigNumber(value);
1328 var gasPrice = tx.gasPrice === undefined || tx.gasPrice.length === 0 ? "0" : tx.gasPrice;
1329 tx.gasPrice = new BigNumber(gasPrice);
1330 var gasLimit = tx.gasLimit === undefined || tx.gasLimit.length === 0 ? "0" : tx.gasLimit;
1331 tx.gasLimit = new BigNumber(gasLimit);
1332 this.transaction = tx;
1333 }
1334 },
1335 transfer: function (address, value) {
1336 if (!(value instanceof BigNumber)) {
1337 value = new BigNumber(value);
1338 }
1339 var ret = this.nativeBlockchain.transfer(address, value.toString(10));
1340 return ret == 0;
1341 },
1342 verifyAddress: function (address) {
1343 return this.nativeBlockchain.verifyAddress(address);
1344 }
1345};
1346module.exports = new Blockchain();
1347
1348},{}],8:[function(require,module,exports){
1349// Copyright (C) 2017 go-nebulas authors
1350//
1351// This file is part of the go-nebulas library.
1352//
1353// the go-nebulas library is free software: you can redistribute it and/or modify
1354// it under the terms of the GNU General Public License as published by
1355// the Free Software Foundation, either version 3 of the License, or
1356// (at your option) any later version.
1357//
1358// the go-nebulas library is distributed in the hope that it will be useful,
1359// but WITHOUT ANY WARRANTY; without even the implied warranty of
1360// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1361// GNU General Public License for more details.
1362//
1363// You should have received a copy of the GNU General Public License
1364// along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>.
1365//
1366
1367'use strict';
1368
1369function Console() {}
1370
1371function log(...args) {
1372 var level = args.shift();
1373 if (typeof level != 'number') {
1374 throw 'level must be number.';
1375 }
1376
1377 var msg = '';
1378 for (var i = 0; i < args.length - 1; i++) {
1379 msg += format(args[i]) + ' ';
1380 }
1381 msg += format(args[args.length - 1]);
1382
1383 _native_log(level, msg);
1384}
1385
1386function format(obj) {
1387 if (typeof obj == 'object') {
1388 return JSON.stringify(obj);
1389 }
1390 return obj;
1391}
1392
1393[['debug', 1], ['warn', 2], ['info', 3], ['log', 3], ['error', 4]].forEach(function (val) {
1394 Console.prototype[val[0]] = log.bind(null, val[1]);
1395});
1396
1397module.exports = new Console();
1398module.exports.Console = Console;
1399
1400},{}],9:[function(require,module,exports){
1401// Copyright (C) 2017 go-nebulas authors
1402//
1403// This file is part of the go-nebulas library.
1404//
1405// the go-nebulas library is free software: you can redistribute it and/or modify
1406// it under the terms of the GNU General Public License as published by
1407// the Free Software Foundation, either version 3 of the License, or
1408// (at your option) any later version.
1409//
1410// the go-nebulas library is distributed in the hope that it will be useful,
1411// but WITHOUT ANY WARRANTY; without even the implied warranty of
1412// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1413// GNU General Public License for more details.
1414//
1415// You should have received a copy of the GNU General Public License
1416// along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>.
1417//
1418
1419'use strict';
1420
1421exports["Trigger"] = function (topic, data) {
1422 _native_event_trigger(topic, JSON.stringify(data));
1423};
1424
1425},{}],10:[function(require,module,exports){
1426// Copyright (C) 2017 go-nebulas authors
1427//
1428// This file is part of the go-nebulas library.
1429//
1430// the go-nebulas library is free software: you can redistribute it and/or modify
1431// it under the terms of the GNU General Public License as published by
1432// the Free Software Foundation, either version 3 of the License, or
1433// (at your option) any later version.
1434//
1435// the go-nebulas library is distributed in the hope that it will be useful,
1436// but WITHOUT ANY WARRANTY; without even the implied warranty of
1437// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
1438// GNU General Public License for more details.
1439//
1440// You should have received a copy of the GNU General Public License
1441// along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>.
1442//
1443
1444'use strict';
1445
1446var fieldNameRe = /^[a-zA-Z_$][a-zA-Z0-9_]+$/;
1447
1448var combineStorageMapKey = function (fieldName, key) {
1449 return "@" + fieldName + "[" + key + "]";
1450};
1451
1452var applyMapDescriptor = function (obj, descriptor) {
1453 descriptor = Object.assign({
1454 stringify: JSON.stringify,
1455 parse: JSON.parse
1456 }, descriptor || {});
1457
1458 if (typeof descriptor.stringify !== 'function' || typeof descriptor.parse !== 'function') {
1459 throw new Error("descriptor.stringify and descriptor.parse must be function.");
1460 }
1461
1462 Object.defineProperty(obj, "stringify", {
1463 configurable: false,
1464 enumerable: false,
1465 get: function () {
1466 return descriptor.stringify;
1467 }
1468 });
1469
1470 Object.defineProperty(obj, "parse", {
1471 configurable: false,
1472 enumerable: false,
1473 get: function () {
1474 return descriptor.parse;
1475 }
1476 });
1477};
1478
1479var applyFieldDescriptor = function (obj, fieldName, descriptor) {
1480 descriptor = Object.assign({
1481 stringify: JSON.stringify,
1482 parse: JSON.parse
1483 }, descriptor || {});
1484
1485 if (typeof descriptor.stringify !== 'function' || typeof descriptor.parse !== 'function') {
1486 throw new Error("descriptor.stringify and descriptor.parse must be function.");
1487 }
1488
1489 Object.defineProperty(obj, "__stringify__" + fieldName, {
1490 configurable: false,
1491 enumerable: false,
1492 get: function () {
1493 return descriptor.stringify;
1494 }
1495 });
1496
1497 Object.defineProperty(obj, "__parse__" + fieldName, {
1498 configurable: false,
1499 enumerable: false,
1500 get: function () {
1501 return descriptor.parse;
1502 }
1503 });
1504};
1505
1506var ContractStorage = function (handler) {
1507 var ns = new NativeStorage(handler);
1508 Object.defineProperty(this, "nativeStorage", {
1509 configurable: false,
1510 enumerable: false,
1511 get: function () {
1512 return ns;
1513 }
1514 });
1515};
1516
1517var StorageMap = function (contractStorage, fieldName, descriptor) {
1518 if (!contractStorage instanceof ContractStorage) {
1519 throw new Error("StorageMap only accept instance of ContractStorage");
1520 }
1521
1522 if (typeof fieldName !== "string" || fieldNameRe.exec(fieldName) == null) {
1523 throw new Error("StorageMap fieldName must match regex /^[a-zA-Z_$].*$/");
1524 }
1525
1526 Object.defineProperty(this, "contractStorage", {
1527 configurable: false,
1528 enumerable: false,
1529 get: function () {
1530 return contractStorage;
1531 }
1532 });
1533 Object.defineProperty(this, "fieldName", {
1534 configurable: false,
1535 enumerable: false,
1536 get: function () {
1537 return fieldName;
1538 }
1539 });
1540
1541 applyMapDescriptor(this, descriptor);
1542};
1543
1544StorageMap.prototype = {
1545 del: function (key) {
1546 return this.contractStorage.del(combineStorageMapKey(this.fieldName, key));
1547 },
1548 get: function (key) {
1549 var val = this.contractStorage.rawGet(combineStorageMapKey(this.fieldName, key));
1550 if (val != null) {
1551 val = this.parse(val);
1552 }
1553 return val;
1554 },
1555 set: function (key, value) {
1556 var val = this.stringify(value);
1557 return this.contractStorage.rawSet(combineStorageMapKey(this.fieldName, key), val);
1558 }
1559};
1560StorageMap.prototype.put = StorageMap.prototype.set;
1561StorageMap.prototype.delete = StorageMap.prototype.del;
1562
1563ContractStorage.prototype = {
1564 rawGet: function (key) {
1565 return this.nativeStorage.get(key);
1566 },
1567 rawSet: function (key, value) {
1568 var ret = this.nativeStorage.set(key, value);
1569 if (ret != 0) {
1570 throw new Error("set key " + key + " failed.");
1571 }
1572 return ret;
1573 },
1574 del: function (key) {
1575 var ret = this.nativeStorage.del(key);
1576 if (ret != 0) {
1577 throw new Error("del key " + key + " failed.");
1578 }
1579 return ret;
1580 },
1581 get: function (key) {
1582 var val = this.rawGet(key);
1583 if (val != null) {
1584 val = JSON.parse(val);
1585 }
1586 return val;
1587 },
1588 set: function (key, value) {
1589 return this.rawSet(key, JSON.stringify(value));
1590 },
1591 defineProperty: function (obj, fieldName, descriptor) {
1592 if (!obj || !fieldName) {
1593 throw new Error("defineProperty requires at least two parameters.");
1594 }
1595 var $this = this;
1596 Object.defineProperty(obj, fieldName, {
1597 configurable: false,
1598 enumerable: true,
1599 get: function () {
1600 var val = $this.rawGet(fieldName);
1601 if (val != null) {
1602 val = obj["__parse__" + fieldName](val);
1603 }
1604 return val;
1605 },
1606 set: function (val) {
1607 val = obj["__stringify__" + fieldName](val);
1608 return $this.rawSet(fieldName, val);
1609 }
1610 });
1611 applyFieldDescriptor(obj, fieldName, descriptor);
1612 return this;
1613 },
1614 defineProperties: function (obj, props) {
1615 if (!obj || !props) {
1616 throw new Error("defineProperties requires two parameters.");
1617 }
1618
1619 for (const fieldName in props) {
1620 this.defineProperty(obj, fieldName, props[fieldName]);
1621 }
1622 return this;
1623 },
1624 defineMapProperty: function (obj, fieldName, descriptor) {
1625 if (!obj || !fieldName) {
1626 throw new Error("defineMapProperty requires two parameters.");
1627 }
1628
1629 var mapObj = new StorageMap(this, fieldName, descriptor);
1630 Object.defineProperty(obj, fieldName, {
1631 configurable: false,
1632 enumerable: true,
1633 get: function () {
1634 return mapObj;
1635 }
1636 });
1637 return this;
1638 },
1639 defineMapProperties: function (obj, props) {
1640 if (!obj || !props) {
1641 throw new Error("defineMapProperties requires two parameters.");
1642 }
1643
1644 for (const fieldName in props) {
1645 this.defineMapProperty(obj, fieldName, props[fieldName]);
1646 }
1647 return this;
1648 }
1649};
1650
1651ContractStorage.prototype.put = ContractStorage.prototype.set;
1652ContractStorage.prototype.delete = ContractStorage.prototype.del;
1653
1654var lcs = new ContractStorage(_native_storage_handlers.lcs);
1655var gcs = new ContractStorage(_native_storage_handlers.gcs);
1656var obj = { ContractStorage: ContractStorage };
1657Object.defineProperty(obj, "lcs", {
1658 configurable: false,
1659 enumerable: false,
1660 get: function () {
1661 return lcs;
1662 }
1663});
1664
1665Object.defineProperty(obj, "gcs", {
1666 configurable: false,
1667 enumerable: false,
1668 get: function () {
1669 return gcs;
1670 }
1671});
1672
1673module.exports = Object.freeze(obj);
1674
1675},{}],11:[function(require,module,exports){
1676(function (global,__dirname){
1677
1678
1679global;
1680
1681if (typeof window !== "undefined") {
1682 global = window;
1683}
1684
1685if (typeof localStorage === "undefined" || localStorage === null) {
1686 var path = require("path");
1687 var storageFile = path.join(__dirname, "./.storage");
1688 var LocalStorage = require('node-localstorage').LocalStorage;
1689 global.localStorage = new LocalStorage(storageFile);
1690}
1691
1692global.context = require("./context");
1693global._native_blockchain = require("./native/blockchain");
1694global._native_log = require("./native/log");
1695global._native_event_trigger = require("./native/event");
1696global._native_storage_handlers = require("./native/storage").handlers;
1697global.NativeStorage = require("./native/storage").NativeStorage;
1698
1699global.nativeConsole = global.console;
1700global.console = require("./libs/console");
1701global.ContractStorage = require("./libs/storage");
1702global.LocalContractStorage = global.ContractStorage.lcs;
1703// global.GlobalContractStorage = ContractStorage.gcs;
1704global.BigNumber = require("bignumber.js");
1705global.Blockchain = require("./libs/blockchain");
1706global.Event = require("./libs/event");
1707
1708// global.Date = require('./libs/date');
1709// global.Math.random = require('./libs/random');
1710// global.BigNumber.random = global.Math.random;
1711
1712module.exports = {
1713 context: global.context
1714};
1715
1716}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/lib/nvm")
1717},{"./context":6,"./libs/blockchain":7,"./libs/console":8,"./libs/event":9,"./libs/storage":10,"./native/blockchain":12,"./native/event":13,"./native/log":14,"./native/storage":15,"bignumber.js":73,"node-localstorage":"node-localstorage.js","path":183}],12:[function(require,module,exports){
1718"use strict";
1719
1720var Account = require("../../account");
1721
1722var transfer = function (to, value) {
1723 // TODO: mock the transfer func in nebulas
1724 return 0;
1725};
1726
1727var verifyAddress = function (address) {
1728 return Account.isValidAddress(address);
1729};
1730
1731module.exports = {
1732 transfer: transfer,
1733 verifyAddress: verifyAddress
1734};
1735
1736},{"../../account":1}],13:[function(require,module,exports){
1737"use strict";
1738
1739var trigger = function (topic, data) {
1740 var event = {
1741 Topic: topic,
1742 Data: data
1743 };
1744 var key = context.transaction.hash;
1745 var events = localStorage.getItem(key);
1746 if (events === null || typeof events === "undefined") {
1747 events = new Array();
1748 } else {
1749 events = Array.from(events);
1750 }
1751 events.push(event);
1752 localStorage.setItem(key, events);
1753};
1754
1755module.exports = trigger;
1756
1757},{}],14:[function(require,module,exports){
1758"use strict";
1759
1760var log = function (level, msg) {
1761 var levelStr;
1762 switch (level) {
1763 case 1:
1764 levelStr = "debug";
1765 case 2:
1766 levelStr = "warn";
1767 case 3:
1768 levelStr = "info";
1769 case 4:
1770 levelStr = "error";
1771 default:
1772 levelStr = "info";
1773 }
1774 var log = levelStr + ":" + msg;
1775 nativeConsole.log(log);
1776};
1777
1778module.exports = log;
1779
1780},{}],15:[function(require,module,exports){
1781"use strict";
1782
1783var handlers = {
1784 lcs: 1,
1785 gcs: 2
1786};
1787
1788var NativeStorage = function (handler) {
1789 this.handler = handler;
1790};
1791
1792NativeStorage.prototype = {
1793 get: function (key) {
1794 return localStorage.getItem(key);
1795 },
1796 set: function (key, value) {
1797 localStorage.setItem(key, value);
1798 return 0;
1799 },
1800 del: function (key) {
1801 localStorage.removeItem(key);
1802 return 0;
1803 }
1804};
1805
1806module.exports = {
1807 handlers: handlers,
1808 NativeStorage: NativeStorage
1809};
1810
1811},{}],16:[function(require,module,exports){
1812"use strict";
1813
1814var extend = require('extend');
1815var native = require("./native");
1816
1817var funcRegex = new RegExp("^[a-zA-Z$][A-Za-z0-9_$]*$");
1818
1819var NVM = function (block, transaction) {
1820 extend(native.context.block, block);
1821 extend(native.context.transaction, transaction);
1822 // console.log("block:", native.context.block);
1823 // console.log("tx:", native.context.transaction);
1824};
1825
1826NVM.prototype = {
1827 deploy: function (source, args) {
1828 return this.run(source, "init", args);
1829 },
1830 call: function (source, func, args) {
1831 if (funcRegex.test(func)) {
1832 return this.run(source, func, args);
1833 } else {
1834 throw new Error("invalid func");
1835 }
1836 },
1837 run: function (source, func, args) {
1838 Blockchain.blockParse(JSON.stringify(native.context.block));
1839 Blockchain.transactionParse(JSON.stringify(native.context.transaction));
1840 var Contract = eval(source);
1841 // console.log("contract:", Contract);
1842 var contract = new Contract();
1843 if (args === undefined || args.length === 0) {
1844 args = "[]";
1845 }
1846 if (contract[func] != undefined) {
1847 return contract[func].apply(contract, JSON.parse(args));
1848 } else {
1849 throw new Error("function not found");
1850 }
1851 }
1852};
1853
1854module.exports = NVM;
1855
1856},{"./native":11,"extend":145}],17:[function(require,module,exports){
1857module.exports={
1858 "nested": {
1859 "corepb": {
1860 "nested": {
1861 "Data": {
1862 "fields": {
1863 "type": {
1864 "type": "string",
1865 "id": 1
1866 },
1867 "payload": {
1868 "type": "bytes",
1869 "id": 2
1870 }
1871 }
1872 },
1873 "Transaction": {
1874 "fields": {
1875 "hash": {
1876 "type": "bytes",
1877 "id": 1
1878 },
1879 "from": {
1880 "type": "bytes",
1881 "id": 2
1882 },
1883 "to": {
1884 "type": "bytes",
1885 "id": 3
1886 },
1887 "value": {
1888 "type": "bytes",
1889 "id": 4
1890 },
1891 "nonce": {
1892 "type": "uint64",
1893 "id": 5
1894 },
1895 "timestamp": {
1896 "type": "int64",
1897 "id": 6
1898 },
1899 "data": {
1900 "type": "Data",
1901 "id": 7
1902 },
1903 "chainId": {
1904 "type": "uint32",
1905 "id": 8
1906 },
1907 "gasPrice": {
1908 "type": "bytes",
1909 "id": 9
1910 },
1911 "gasLimit": {
1912 "type": "bytes",
1913 "id": 10
1914 },
1915 "alg": {
1916 "type": "uint32",
1917 "id": 11
1918 },
1919 "sign": {
1920 "type": "bytes",
1921 "id": 12
1922 }
1923 }
1924 }
1925 }
1926 }
1927 }
1928}
1929},{}],18:[function(require,module,exports){
1930"use strict";
1931
1932var protobuf = require('protobufjs');
1933var utils = require('./utils/utils.js');
1934var cryptoUtils = require('./utils/crypto-utils.js');
1935var account = require("./account.js");
1936var htmlescape = require('htmlescape');
1937var BigNumber = require('bignumber.js');
1938
1939var SECP256K1 = 1;
1940var root = protobuf.Root.fromJSON(require("./transaction.json"));
1941
1942var TxPayloadBinaryType = "binary";
1943var TxPayloadDeployType = "deploy";
1944var TxPayloadCallType = "call";
1945
1946/**
1947 * @typedef TransactionInit
1948 * @example
1949 * var acc = Account.NewAccount();
1950 *
1951 * var tx = new Transaction({
1952 * chainID: 1,
1953 * from: acc,
1954 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
1955 * value: 10,
1956 * nonce: 12,
1957 * gasPrice: 1000000,
1958 * gasLimit: 2000000
1959 * });
1960 */
1961
1962/**
1963 * Represent of smart contract payload data.
1964 *
1965 * @typedef {Object} Contract
1966 * @property {String} source - Contract source code for deploy contract.
1967 * @property {String} sourceType - Contract source type for deploy contract. Currently support js and ts.
1968 * @property {String} args - The params of contract. The args content is JSON string of parameters array.
1969 * @property {String} function - The contract call function.
1970 * @property {Buffer} binary - Binary contract representation.
1971 *
1972 * @see [Create own smart contract in Nebulas.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md}
1973 * @see [More about transaction parameters.]{@link https://github.com/nebulasio/wiki/blob/c3f5ce8908c80e9104e3b512a7fdfd75f16ac38c/rpc.md#sendtransaction}
1974 *
1975 * @example
1976 * // It's example of possible fields values.
1977 * // For deploy, and execute smart contracts follow this link - https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md
1978 * {
1979 * 'source': '"use strict";var DepositeContent=function(t){if(t){let n=JSON.parse(t);' +
1980 * 'this.balance=new BigNumber(n.balance),this.expiryHeight=new BigNumber(n.expiryHeight)' +
1981 * '}else this.balance=new BigNumber(0),this.expiryHeight=new BigNumber(0)};' +
1982 * 'DepositeContent.prototype={toString:function(){return JSON.stringify(this)}};' +
1983 * 'var BankVaultContract=function(){LocalContractStorage.defineMapProperty(this,"bankVault",' +
1984 * '{parse:function(t){return new DepositeContent(t)},stringify:function(t){return t.toString()}})};' +
1985 * 'BankVaultContract.prototype={init:function(){},save:function(t){var n=Blockchain.transaction.from,' +
1986 * 'e=Blockchain.transaction.value,a=new BigNumber(Blockchain.block.height),r=this.bankVault.get(n);' +
1987 * 'r&&(e=e.plus(r.balance));var i=new DepositeContent;i.balance=e,i.expiryHeight=a.plus(t),' +
1988 * 'this.bankVault.put(n,i)},takeout:function(t){var n=Blockchain.transaction.from,' +
1989 * 'e=new BigNumber(Blockchain.block.height),a=new BigNumber(t),r=this.bankVault.get(n);' +
1990 * 'if(!r)throw new Error("No deposit before.");if(e.lt(r.expiryHeight))throw new Error("Can't takeout before expiryHeight.");' +
1991 * 'if(a.gt(r.balance))throw new Error("Insufficient balance.");if(0!=Blockchain.transfer(n,a))throw new Error("transfer failed.");' +
1992 * 'Event.Trigger("BankVault",{Transfer:{from:Blockchain.transaction.to,to:n,value:a.toString()}}),' +
1993 * 'r.balance=r.balance.sub(a),this.bankVault.put(n,r)},balanceOf:function(){var t=Blockchain.transaction.from;' +
1994 * 'return this.bankVault.get(t)}},module.exports=BankVaultContract;',
1995 * 'sourceType': 'js',
1996 * 'args': '[0]',
1997 * 'function': 'save'
1998 * }
1999 */
2000
2001/**
2002 * Represent Transaction parameters
2003 *
2004 * @typedef {Object} TransactionOptions
2005 * @property {Number} options.chainID - Transaction chain id.
2006 * @property {HexString} options.from - Hex string of the sender account addresss..
2007 * @property {HexString} options.to - Hex string of the receiver account addresss..
2008 * @property {Number} options.value - Value of transaction.
2009 * @property {Number} options.nonce - Transaction nonce.
2010 * @property {Number} options.gasPrice - Gas price. The unit is 10^-18 NAS.
2011 * @property {Number} options.gasLimit - Transaction gas limit.
2012 * @property {Contract} [options.contract]
2013 *
2014 * @example
2015 * {
2016* chainID: 1,
2017* from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
2018* to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2019* value: 10,
2020* nonce: 12,
2021* gasPrice: 1000000,
2022* gasLimit: 2000000
2023* }
2024 */
2025
2026/**
2027 * Transaction constructor.
2028 * Class encapsulate main operation with transactions.
2029 * @see [For more information about parameters, follow this link]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction}
2030 * @constructor
2031 *
2032 * @param {TransactionOptions} options - Transaction options.
2033 *
2034 * @see [Transaction tutorial.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2002%20Transaction.md}
2035 * @see [Create own smart contract in Nebulas.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md}
2036 * @see [More about transaction parameters.]{@link https://github.com/nebulasio/wiki/blob/c3f5ce8908c80e9104e3b512a7fdfd75f16ac38c/rpc.md#sendtransaction}
2037 *
2038 * @example
2039 * var acc = Account.NewAccount();
2040 *
2041 * var tx = new Transaction({
2042 * chainID: 1,
2043 * from: acc,
2044 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2045 * value: 10,
2046 * nonce: 12,
2047 * gasPrice: 1000000,
2048 * gasLimit: 2000000,
2049 * contract: {
2050 * function: "save",
2051 * args: "[0]"
2052 * }
2053 * });
2054 *
2055 */
2056var Transaction = function (options) {
2057 if (arguments.length > 0) {
2058 options = utils.argumentsToObject(['chainID', 'from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments);
2059
2060 this.chainID = options.chainID;
2061 this.from = account.fromAddress(options.from);
2062 this.to = account.fromAddress(options.to);
2063 this.value = utils.toBigNumber(options.value);
2064 if (!this.value.isInteger()) throw new Error("Invalid value! The minimum unit is wei (1^-18nas)");
2065 this.nonce = parseInt(options.nonce); // An error will be thrown is nonce is string. Error: "nonce: integer|Long expected"
2066 this.timestamp = Math.floor(new Date().getTime() / 1000);
2067 this.contract = options.contract;
2068 this.gasPrice = utils.toBigNumber(options.gasPrice);
2069 this.gasLimit = utils.toBigNumber(options.gasLimit);
2070
2071 this.data = parseContract(this.contract);
2072 if (this.gasPrice.lessThanOrEqualTo(0)) {
2073 this.gasPrice = new BigNumber(1000000);
2074 }
2075
2076 if (this.gasLimit.lessThanOrEqualTo(0)) {
2077 this.gasLimit = new BigNumber(20000);
2078 }
2079 }
2080 this.signErrorMessage = "You should sign transaction before this operation.";
2081};
2082
2083var parseContract = function (obj) {
2084 /*jshint maxcomplexity:7 */
2085
2086 var payloadType, payload;
2087 if (obj && utils.isString(obj.source) && obj.source.length > 0) {
2088 payloadType = TxPayloadDeployType;
2089 payload = {
2090 SourceType: obj.sourceType,
2091 Source: obj.source,
2092 Args: obj.args
2093 };
2094 } else if (obj && utils.isString(obj.function) && obj.function.length > 0) {
2095 payloadType = TxPayloadCallType;
2096 payload = {
2097 Function: obj.function,
2098 Args: obj.args
2099 };
2100 } else {
2101 payloadType = TxPayloadBinaryType;
2102 if (obj) {
2103 payload = {
2104 Data: cryptoUtils.toBuffer(obj.binary)
2105 };
2106 }
2107 }
2108 var payloadData = utils.isNull(payload) ? null : cryptoUtils.toBuffer(htmlescape(payload));
2109
2110 return { type: payloadType, payload: payloadData };
2111};
2112
2113/**
2114 * Transaction recover method.
2115 *
2116 * @static
2117 * @param {String/Hash} message - Transaction hash.
2118 * @param {String/Hash} signature - Transaction sign
2119 *
2120 * @return {Hash} Transaction from address public key.
2121 *
2122 * @example
2123 * var pubKey = Transaction.recover("82bc718bfd24392b3872eb5a874927a327ab19b156c5584bd5f93b08fab5b1a2", "003d4064f16cbc72367b0fa3870bdcd1044bdb166019d87cdaac6dcfb8c09ac9471570e5b2e1dc249a8642ba67e585e3f43e6383c3b87532f5eb1fe2e718a5ab00");
2124 */
2125Transaction.recover = function (message, signature) {
2126 message = cryptoUtils.toBuffer(message);
2127 var signBuf = cryptoUtils.toBuffer(signature);
2128 var sign = signBuf.slice(0, 64);
2129 var recovery = signBuf.readUIntBE(64, 1);
2130 if (recovery > 27) {
2131 recovery = recovery - 27;
2132 }
2133 var compressed = false;
2134 var pub = cryptoUtils.recover(message, sign, recovery, compressed);
2135 return pub;
2136};
2137
2138/**
2139 * Transaction fromProto method, parse rawData to transaction object.
2140 *
2141 * @static
2142 * @param {String/Hash} data - Transaction raw data.
2143 *
2144 * @return {Object} Transaction object.
2145 *
2146 * @example
2147 * var tx = Transaction.fromProto("EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA==");
2148 */
2149Transaction.fromProto = function (data) {
2150 var tx = new Transaction();
2151 tx.fromProto(data);
2152 return tx;
2153};
2154
2155Transaction.prototype = {
2156 /**
2157 * Convert transaction to hash by SHA3-256 algorithm.
2158 *
2159 * @return {Hash} hash of Transaction.
2160 *
2161 * @example
2162 * var acc = Account.NewAccount();
2163 *
2164 * var tx = new Transaction({
2165 * chainID: 1,
2166 * from: acc,
2167 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2168 * value: 10,
2169 * nonce: 12,
2170 * gasPrice: 1000000,
2171 * gasLimit: 2000000
2172 * });
2173 * var txHash = tx.hashTransaction();
2174 * //Uint8Array(32) [211, 213, 102, 103, 23, 231, 246, 141, 20, 202, 210, 25, 92, 142, 162, 242, 232, 95, 44, 239, 45, 57, 241, 61, 34, 2, 213, 160, 17, 207, 75, 40]
2175 */
2176 hashTransaction: function () {
2177 var Data = root.lookup("corepb.Data");
2178 var err = Data.verify(this.data);
2179 if (err) {
2180 throw new Error(err);
2181 }
2182 var data = Data.create(this.data);
2183 var dataBuffer = Data.encode(data).finish();
2184 var hash = cryptoUtils.sha3(this.from.getAddress(), this.to.getAddress(), cryptoUtils.padToBigEndian(this.value, 128), cryptoUtils.padToBigEndian(this.nonce, 64), cryptoUtils.padToBigEndian(this.timestamp, 64), dataBuffer, cryptoUtils.padToBigEndian(this.chainID, 32), cryptoUtils.padToBigEndian(this.gasPrice, 128), cryptoUtils.padToBigEndian(this.gasLimit, 128));
2185 return hash;
2186 },
2187 /**
2188 * Sign transaction with the specified algorithm.
2189 *
2190 * @example
2191 * var acc = Account.NewAccount();
2192 *
2193 * var tx = new Transaction({
2194 * chainID: 1,
2195 * from: acc,
2196 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2197 * value: 10,
2198 * nonce: 12,
2199 * gasPrice: 1000000,
2200 * gasLimit: 2000000
2201 * });
2202 * tx.signTransaction();
2203 */
2204 signTransaction: function () {
2205 if (this.from.getPrivateKey() !== null) {
2206 this.hash = this.hashTransaction();
2207 this.alg = SECP256K1;
2208 this.sign = cryptoUtils.sign(this.hash, this.from.getPrivateKey());
2209 } else {
2210 throw new Error("transaction from address's private key is invalid");
2211 }
2212 },
2213 /**
2214 * Conver transaction data to plain JavaScript object.
2215 *
2216 * @return {Object} Plain JavaScript object with Transaction fields.
2217 * @example
2218 * var acc = Account.NewAccount();
2219 * var tx = new Transaction({
2220 * chainID: 1,
2221 * from: acc,
2222 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2223 * value: 10,
2224 * nonce: 12,
2225 * gasPrice: 1000000,
2226 * gasLimit: 2000000
2227 * });
2228 * txData = tx.toPlainObject();
2229 * // {chainID: 1001, from: "n1USdDKeZXQYubA44W2ZVUdW1cjiJuqswxp", to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 1000000000000000000, nonce: 1, …}
2230 */
2231 toPlainObject: function () {
2232 return {
2233 chainID: this.chainID,
2234 from: this.from.getAddressString(),
2235 to: this.to.getAddressString(),
2236 value: utils.isBigNumber(this.value) ? this.value.toNumber() : this.value,
2237 nonce: this.nonce,
2238 gasPrice: utils.isBigNumber(this.gasPrice) ? this.gasPrice.toNumber() : this.gasPrice,
2239 gasLimit: utils.isBigNumber(this.gasLimit) ? this.gasLimit.toNumber() : this.gasLimit,
2240 contract: this.contract
2241 };
2242 },
2243 /**
2244 * Convert transaction to JSON string.
2245 * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting.
2246 *
2247 * @return {String} JSON stringify of transaction data.
2248 * @example
2249 * var acc = Account.NewAccount();
2250 *
2251 * var tx = new Transaction({
2252 * chainID: 1,
2253 * from: acc,
2254 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2255 * value: 10,
2256 * nonce: 12,
2257 * gasPrice: 1000000,
2258 * gasLimit: 2000000
2259 * });
2260 * tx.signTransaction();
2261 * var txHash = tx.toString();
2262 * // "{"chainID":1001,"from":"n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5","to":"n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17","value":"1000000000000000000","nonce":1,"timestamp":1521905294,"data":{"payloadType":"binary","payload":null},"gasPrice":"1000000","gasLimit":"20000","hash":"f52668b853dd476fd309f21b22ade6bb468262f55402965c3460175b10cb2f20","alg":1,"sign":"cf30d5f61e67bbeb73bb9724ba5ba3744dcbc995521c62f9b5f43efabd9b82f10aaadf19a9cdb05f039d8bf074849ef4b508905bcdea76ae57e464e79c958fa900"}"
2263 */
2264 toString: function () {
2265 if (!this.sign) {
2266 throw new Error(this.signErrorMessage);
2267 }
2268 var payload = utils.isNull(this.data.payload) ? null : JSON.parse(this.data.payload.toString());
2269 var tx = {
2270 chainID: this.chainID,
2271 from: this.from.getAddressString(),
2272 to: this.to.getAddressString(),
2273 value: this.value.toString(10),
2274 nonce: this.nonce,
2275 timestamp: this.timestamp,
2276 data: { payloadType: this.data.type, payload: payload },
2277 gasPrice: this.gasPrice.toString(10),
2278 gasLimit: this.gasLimit.toString(10),
2279 hash: this.hash.toString("hex"),
2280 alg: this.alg,
2281 sign: this.sign.toString("hex")
2282
2283 };
2284 return JSON.stringify(tx);
2285 },
2286 /**
2287 * Convert transaction to Protobuf format.
2288 * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting.
2289 *
2290 * @return {Buffer} Transaction data in Protobuf format
2291 *
2292 * @example
2293 * var acc = Account.NewAccount();
2294 *
2295 * var tx = new Transaction({
2296 * chainID: 1,
2297 * from: acc,
2298 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2299 * value: 10,
2300 * nonce: 12,
2301 * gasPrice: 1000000,
2302 * gasLimit: 2000000
2303 * });
2304 * tx.signTransaction();
2305 * var txHash = tx.toProto();
2306 * // Uint8Array(127)
2307 */
2308 toProto: function () {
2309 if (!this.sign) {
2310 throw new Error(this.signErrorMessage);
2311 }
2312 var Data = root.lookup("corepb.Data");
2313 var err = Data.verify(this.data);
2314 if (err) {
2315 throw err;
2316 }
2317 var data = Data.create(this.data);
2318
2319 var TransactionProto = root.lookup("corepb.Transaction");
2320
2321 var txData = {
2322 hash: this.hash,
2323 from: this.from.getAddress(),
2324 to: this.to.getAddress(),
2325 value: cryptoUtils.padToBigEndian(this.value, 128),
2326 nonce: this.nonce,
2327 timestamp: this.timestamp,
2328 data: data,
2329 chainId: this.chainID,
2330 gasPrice: cryptoUtils.padToBigEndian(this.gasPrice, 128),
2331 gasLimit: cryptoUtils.padToBigEndian(this.gasLimit, 128),
2332 alg: this.alg,
2333 sign: this.sign
2334 };
2335
2336 err = TransactionProto.verify(txData);
2337 if (err) {
2338 throw err;
2339 }
2340 var tx = TransactionProto.create(txData);
2341
2342 var txBuffer = TransactionProto.encode(tx).finish();
2343 return txBuffer;
2344 },
2345 /**
2346 * Convert transaction to Protobuf hash string.
2347 * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting.
2348 *
2349 * @return {Base64} Transaction string.
2350 *
2351 * @example
2352 * var acc = Account.NewAccount();
2353 *
2354 * var tx = new Transaction({
2355 * chainID: 1,
2356 * from: acc,
2357 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2358 * value: 10,
2359 * nonce: 12,
2360 * gasPrice: 1000000,
2361 * gasLimit: 2000000
2362 * });
2363 * tx.signTransaction();
2364 * var txHash = tx.toProtoString();
2365 * // "EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA=="
2366 */
2367 toProtoString: function () {
2368 var txBuffer = this.toProto();
2369 return protobuf.util.base64.encode(txBuffer, 0, txBuffer.length);
2370 },
2371 /**
2372 * Restore Transaction from Protobuf format.
2373 * @property {Buffer|String} data - Buffer or stringify Buffer.
2374 *
2375 * @return {Transaction} Restored transaction.
2376 *
2377 * @example
2378 * var acc = Account.NewAccount();
2379 *
2380 * var tx = new Transaction({
2381 * chainID: 1,
2382 * from: acc,
2383 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2384 * value: 10,
2385 * nonce: 12,
2386 * gasPrice: 1000000,
2387 * gasLimit: 2000000
2388 * });
2389 * var tx = tx.fromProto("EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA==");
2390 */
2391 fromProto: function (data) {
2392
2393 var txBuffer;
2394 if (utils.isString(data)) {
2395 txBuffer = new Array(protobuf.util.base64.length(data));
2396 protobuf.util.base64.decode(data, txBuffer, 0);
2397 } else {
2398 txBuffer = data;
2399 }
2400
2401 var TransactionProto = root.lookup("corepb.Transaction");
2402 var txProto = TransactionProto.decode(txBuffer);
2403
2404 this.hash = cryptoUtils.toBuffer(txProto.hash);
2405 this.from = account.fromAddress(txProto.from);
2406 this.to = account.fromAddress(txProto.to);
2407 this.value = utils.toBigNumber("0x" + cryptoUtils.toBuffer(txProto.value).toString("hex"));
2408 // long number is object, should convert to int
2409 this.nonce = parseInt(txProto.nonce.toString());
2410 this.timestamp = parseInt(txProto.timestamp.toString());
2411 this.data = txProto.data;
2412 if (this.data.payload.length === 0) {
2413 this.data.payload = null;
2414 }
2415 this.chainID = txProto.chainId;
2416 this.gasPrice = utils.toBigNumber("0x" + cryptoUtils.toBuffer(txProto.gasPrice).toString("hex"));
2417 this.gasLimit = utils.toBigNumber("0x" + cryptoUtils.toBuffer(txProto.gasLimit).toString("hex"));
2418 this.alg = txProto.alg;
2419 this.sign = cryptoUtils.toBuffer(txProto.sign);
2420
2421 return this;
2422 }
2423};
2424
2425module.exports = Transaction;
2426
2427},{"./account.js":1,"./transaction.json":17,"./utils/crypto-utils.js":19,"./utils/utils.js":21,"bignumber.js":73,"htmlescape":160,"protobufjs":191}],19:[function(require,module,exports){
2428
2429"use strict";
2430
2431var Buffer = require('safe-buffer').Buffer;
2432
2433var jsSHA = require('jssha');
2434var createKeccakHash = require('keccak');
2435var secp256k1 = require('secp256k1');
2436var crypto = require('crypto');
2437var scrypt = require('scryptsy');
2438var RIPEMD160 = require('ripemd160');
2439
2440var uuid = require('uuid');
2441
2442var utils = require('./utils.js');
2443
2444var keccak = function (a, bits) {
2445 a = toBuffer(a);
2446 if (!bits) bits = 256;
2447
2448 return createKeccakHash('keccak' + bits).update(a).digest();
2449};
2450
2451var sha3 = function () {
2452 var shaObj = new jsSHA("SHA3-256", "HEX");
2453 for (var i = 0; i < arguments.length; i++) {
2454 var v = toBuffer(arguments[i]);
2455 shaObj.update(v.toString("hex"));
2456 }
2457 return Buffer.from(shaObj.getHash("HEX"), "hex");
2458};
2459
2460var ripemd160 = function () {
2461 var ripemd160stream = new RIPEMD160();
2462 for (var i = 0; i < arguments.length; i++) {
2463 var v = toBuffer(arguments[i]);
2464 ripemd160stream.update(v);
2465 }
2466 return ripemd160stream.digest();
2467};
2468
2469// check if hex string
2470var isHexPrefixed = function (str) {
2471 if (typeof str !== 'string') {
2472 throw new Error("[is-hex-prefixed] value must be type 'string', is currently type " + typeof str + ", while checking isHexPrefixed.");
2473 }
2474
2475 return str.slice(0, 2) === '0x';
2476};
2477
2478// returns hex string without 0x
2479var stripHexPrefix = function (str) {
2480 if (typeof str !== 'string') {
2481 return str;
2482 }
2483 return isHexPrefixed(str) ? str.slice(2) : str;
2484};
2485
2486function isHexString(value, length) {
2487 if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) {
2488 return false;
2489 }
2490
2491 if (length && value.length !== 2 + 2 * length) {
2492 return false;
2493 }
2494
2495 return true;
2496}
2497
2498// returns hex string from int
2499function intToHex(i) {
2500 var hex = i.toString(16); // eslint-disable-line
2501
2502 return '0x' + padToEven(hex);
2503}
2504
2505// returns buffer from int
2506function intToBuffer(i) {
2507 var hex = intToHex(i);
2508
2509 return new Buffer(hex.slice(2), 'hex');
2510}
2511
2512// returns a buffer filled with 0
2513var zeros = function (bytes) {
2514 return Buffer.allocUnsafe(bytes).fill(0);
2515};
2516
2517var padToEven = function (value) {
2518 var a = value; // eslint-disable-line
2519
2520 if (typeof a !== 'string') {
2521 throw new Error('padToEven only support string');
2522 }
2523
2524 if (a.length % 2) {
2525 a = '0' + a;
2526 }
2527
2528 return a;
2529};
2530
2531// convert value to digit/8 buffer with BigEndian.
2532var padToBigEndian = function (value, digit) {
2533 value = toBuffer(value);
2534 var buff = Buffer.alloc(digit / 8);
2535 for (var i = 0; i < value.length; i++) {
2536 var start = buff.length - value.length + i;
2537 if (start >= 0) {
2538 buff[start] = value[i];
2539 }
2540 }
2541 return buff;
2542};
2543
2544// attempts to turn a value to buffer, the input can be buffer, string,number
2545var toBuffer = function (v) {
2546 /*jshint maxcomplexity:13 */
2547 if (!Buffer.isBuffer(v)) {
2548 if (Array.isArray(v)) {
2549 v = Buffer.from(v);
2550 } else if (typeof v === 'string') {
2551 if (isHexString(v)) {
2552 v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex');
2553 } else {
2554 v = Buffer.from(v);
2555 }
2556 } else if (typeof v === 'number') {
2557 v = intToBuffer(v);
2558 } else if (v === null || v === undefined) {
2559 v = Buffer.allocUnsafe(0);
2560 } else if (utils.isBigNumber(v)) {
2561 // TODO: neb number is a big int, not support if v is decimal, later fix it.
2562 v = Buffer.from(padToEven(v.toString(16)), 'hex');
2563 } else if (v.toArray) {
2564 v = Buffer.from(v.toArray());
2565 } else if (v.subarray) {
2566 v = Buffer.from(v);
2567 } else if (v === null || typeof v === "undefined") {
2568 v = Buffer.allocUnsafe(0);
2569 } else {
2570 throw new Error('invalid type');
2571 }
2572 }
2573 return v;
2574};
2575
2576var bufferToHex = function (buf) {
2577 buf = toBuffer(buf);
2578 return '0x' + buf.toString('hex');
2579};
2580
2581// convert secp256k1 private key to public key
2582var privateToPublic = function (privateKey) {
2583 privateKey = toBuffer(privateKey);
2584 // skip the type flag and use the X, Y points
2585 return secp256k1.publicKeyCreate(privateKey, false).slice(1);
2586};
2587
2588var isValidPublic = function (publicKey, sanitize) {
2589 if (publicKey.length === 64) {
2590 // Convert to SEC1 for secp256k1
2591 return secp256k1.publicKeyVerify(Buffer.concat([Buffer.from([4]), publicKey]));
2592 }
2593
2594 if (!sanitize) {
2595 return false;
2596 }
2597
2598 return secp256k1.publicKeyVerify(publicKey);
2599};
2600
2601// sign transaction hash
2602var sign = function (msgHash, privateKey) {
2603
2604 var sig = secp256k1.sign(toBuffer(msgHash), toBuffer(privateKey));
2605 // var ret = {}
2606 // ret.r = sig.signature.slice(0, 32)
2607 // ret.s = sig.signature.slice(32, 64)
2608 // ret.v = sig.recovery
2609 return Buffer.concat([toBuffer(sig.signature), toBuffer(sig.recovery)]);
2610};
2611
2612var verify = function (message, signature, publicKey) {
2613 signature = signature.slice(0, -1); //remove the sig.recovery byte
2614 publicKey = Buffer.concat([toBuffer([0x04]), toBuffer(publicKey)]); //add 0x04 before publicKey
2615 return secp256k1.verify(toBuffer(message), toBuffer(signature), toBuffer(publicKey));
2616};
2617
2618var recover = function (message, signature, recovery, compressed) {
2619 return secp256k1.recover(toBuffer(message), toBuffer(signature), recovery, compressed);
2620};
2621
2622module.exports = {
2623 secp256k1: secp256k1,
2624 keccak: keccak,
2625 sha3: sha3,
2626 ripemd160: ripemd160,
2627 crypto: crypto,
2628 scrypt: scrypt,
2629 uuid: uuid,
2630
2631 zeros: zeros,
2632 isHexPrefixed: isHexPrefixed,
2633 padToBigEndian: padToBigEndian,
2634 toBuffer: toBuffer,
2635 bufferToHex: bufferToHex,
2636 privateToPublic: privateToPublic,
2637 isValidPublic: isValidPublic,
2638 sign: sign,
2639 verify: verify,
2640 recover: recover
2641};
2642
2643},{"./utils.js":21,"crypto":116,"jssha":166,"keccak":167,"ripemd160":246,"safe-buffer":247,"scryptsy":248,"secp256k1":249,"uuid":266}],20:[function(require,module,exports){
2644
2645"use strict";
2646
2647var BigNumber = require('bignumber.js');
2648var utils = require('./utils.js');
2649
2650var unitMap = {
2651 'none': '0',
2652 'None': '0',
2653 'wei': '1',
2654 'Wei': '1',
2655 'kwei': '1000',
2656 'Kwei': '1000',
2657 'mwei': '1000000',
2658 'Mwei': '1000000',
2659 'gwei': '1000000000',
2660 'Gwei': '1000000000',
2661 'nas': '1000000000000000000',
2662 'NAS': '1000000000000000000'
2663};
2664
2665var unitValue = function (unit) {
2666 unit = unit ? unit.toLowerCase() : 'nas';
2667 var unitValue = unitMap[unit];
2668 if (unitValue === undefined) {
2669 throw new Error('The unit undefined, please use the following units:' + JSON.stringify(unitMap, null, 2));
2670 }
2671 return new BigNumber(unitValue, 10);
2672};
2673
2674var toBasic = function (number, unit) {
2675 return utils.toBigNumber(number).times(unitValue(unit));
2676};
2677
2678var fromBasic = function (number, unit) {
2679 return utils.toBigNumber(number).dividedBy(unitValue(unit));
2680};
2681
2682var nasToBasic = function (number) {
2683 return utils.toBigNumber(number).times(unitValue("nas"));
2684};
2685
2686module.exports = {
2687 toBasic: toBasic,
2688 fromBasic: fromBasic,
2689 nasToBasic: nasToBasic
2690};
2691
2692},{"./utils.js":21,"bignumber.js":73}],21:[function(require,module,exports){
2693
2694"use strict";
2695
2696var BigNumber = require('bignumber.js');
2697
2698var isNull = function (v) {
2699 return v === null || typeof v === "undefined";
2700};
2701
2702var isBrowser = function () {
2703 return typeof window !== "undefined";
2704};
2705
2706var isBigNumber = function (obj) {
2707 return obj instanceof BigNumber || obj && obj.constructor && obj.constructor.name === 'BigNumber';
2708};
2709
2710var isString = function (obj) {
2711 return typeof obj === 'string' && obj.constructor === String;
2712};
2713
2714var isObject = function (obj) {
2715 return obj !== null && typeof obj === 'object';
2716};
2717
2718var isFunction = function (object) {
2719 return typeof object === 'function';
2720};
2721
2722var isNumber = function (object) {
2723 return typeof object === 'number';
2724};
2725
2726var toBigNumber = function (number) {
2727 number = number || 0;
2728 if (isBigNumber(number)) {
2729 return number;
2730 }
2731 if (isString(number) && number.indexOf('0x') === 0) {
2732 return new BigNumber(number.replace('0x', ''), 16);
2733 }
2734 return new BigNumber(number.toString(10), 10);
2735};
2736
2737var toString = function (obj) {
2738 if (isString(obj)) {
2739 return obj;
2740 } else if (isBigNumber(obj)) {
2741 return obj.toString(10);
2742 } else if (isObject(obj)) {
2743 return JSON.stringify(obj);
2744 } else {
2745 return obj + "";
2746 }
2747};
2748
2749// Transform Array-like arguments object to common array.
2750var argumentsToArray = function (args) {
2751 var len = args.length,
2752 resultArray = new Array(len);
2753
2754 for (var i = 0; i < len; i += 1) {
2755 resultArray[i] = args[i];
2756 }
2757 return resultArray;
2758};
2759
2760// Create object based on provided arrays
2761var zipArraysToObject = function (keysArr, valuesArr) {
2762 var resultObject = {};
2763
2764 for (var i = 0; i < keysArr.length; i += 1) {
2765 resultObject[keysArr[i]] = valuesArr[i];
2766 }
2767 return resultObject;
2768};
2769
2770// Function what make overall view for arguments.
2771// If arguments was provided separated by commas like "func(arg1 ,arg2)" we create
2772// ArgumentsObject and write keys from argsNames and value from args.
2773// in case wheare we provide args in object like "func({arg1: value})"
2774// we just return that object
2775var argumentsToObject = function (keys, args) {
2776 var ArgumentsObject = {};
2777
2778 args = argumentsToArray(args);
2779 if (isObject(args[0])) {
2780 ArgumentsObject = args[0];
2781 } else {
2782 ArgumentsObject = zipArraysToObject(keys, args);
2783 }
2784
2785 return ArgumentsObject;
2786};
2787
2788module.exports = {
2789 isNull: isNull,
2790 isBrowser: isBrowser,
2791 isBigNumber: isBigNumber,
2792 isString: isString,
2793 isObject: isObject,
2794 isFunction: isFunction,
2795 isNumber: isNumber,
2796 toBigNumber: toBigNumber,
2797 toString: toString,
2798 argumentsToObject: argumentsToObject,
2799 zipArraysToObject: zipArraysToObject
2800};
2801
2802},{"bignumber.js":73}],22:[function(require,module,exports){
2803"use strict";\r
2804module.exports = asPromise;\r
2805\r
2806/**\r
2807 * Callback as used by {@link util.asPromise}.\r
2808 * @typedef asPromiseCallback\r
2809 * @type {function}\r
2810 * @param {Error|null} error Error, if any\r
2811 * @param {...*} params Additional arguments\r
2812 * @returns {undefined}\r
2813 */\r
2814\r
2815/**\r
2816 * Returns a promise from a node-style callback function.\r
2817 * @memberof util\r
2818 * @param {asPromiseCallback} fn Function to call\r
2819 * @param {*} ctx Function context\r
2820 * @param {...*} params Function arguments\r
2821 * @returns {Promise<*>} Promisified function\r
2822 */\r
2823function asPromise(fn, ctx/*, varargs */) {\r
2824 var params = new Array(arguments.length - 1),\r
2825 offset = 0,\r
2826 index = 2,\r
2827 pending = true;\r
2828 while (index < arguments.length)\r
2829 params[offset++] = arguments[index++];\r
2830 return new Promise(function executor(resolve, reject) {\r
2831 params[offset] = function callback(err/*, varargs */) {\r
2832 if (pending) {\r
2833 pending = false;\r
2834 if (err)\r
2835 reject(err);\r
2836 else {\r
2837 var params = new Array(arguments.length - 1),\r
2838 offset = 0;\r
2839 while (offset < params.length)\r
2840 params[offset++] = arguments[offset];\r
2841 resolve.apply(null, params);\r
2842 }\r
2843 }\r
2844 };\r
2845 try {\r
2846 fn.apply(ctx || null, params);\r
2847 } catch (err) {\r
2848 if (pending) {\r
2849 pending = false;\r
2850 reject(err);\r
2851 }\r
2852 }\r
2853 });\r
2854}\r
2855
2856},{}],23:[function(require,module,exports){
2857"use strict";\r
2858\r
2859/**\r
2860 * A minimal base64 implementation for number arrays.\r
2861 * @memberof util\r
2862 * @namespace\r
2863 */\r
2864var base64 = exports;\r
2865\r
2866/**\r
2867 * Calculates the byte length of a base64 encoded string.\r
2868 * @param {string} string Base64 encoded string\r
2869 * @returns {number} Byte length\r
2870 */\r
2871base64.length = function length(string) {\r
2872 var p = string.length;\r
2873 if (!p)\r
2874 return 0;\r
2875 var n = 0;\r
2876 while (--p % 4 > 1 && string.charAt(p) === "=")\r
2877 ++n;\r
2878 return Math.ceil(string.length * 3) / 4 - n;\r
2879};\r
2880\r
2881// Base64 encoding table\r
2882var b64 = new Array(64);\r
2883\r
2884// Base64 decoding table\r
2885var s64 = new Array(123);\r
2886\r
2887// 65..90, 97..122, 48..57, 43, 47\r
2888for (var i = 0; i < 64;)\r
2889 s64[b64[i] = i < 26 ? i + 65 : i < 52 ? i + 71 : i < 62 ? i - 4 : i - 59 | 43] = i++;\r
2890\r
2891/**\r
2892 * Encodes a buffer to a base64 encoded string.\r
2893 * @param {Uint8Array} buffer Source buffer\r
2894 * @param {number} start Source start\r
2895 * @param {number} end Source end\r
2896 * @returns {string} Base64 encoded string\r
2897 */\r
2898base64.encode = function encode(buffer, start, end) {\r
2899 var parts = null,\r
2900 chunk = [];\r
2901 var i = 0, // output index\r
2902 j = 0, // goto index\r
2903 t; // temporary\r
2904 while (start < end) {\r
2905 var b = buffer[start++];\r
2906 switch (j) {\r
2907 case 0:\r
2908 chunk[i++] = b64[b >> 2];\r
2909 t = (b & 3) << 4;\r
2910 j = 1;\r
2911 break;\r
2912 case 1:\r
2913 chunk[i++] = b64[t | b >> 4];\r
2914 t = (b & 15) << 2;\r
2915 j = 2;\r
2916 break;\r
2917 case 2:\r
2918 chunk[i++] = b64[t | b >> 6];\r
2919 chunk[i++] = b64[b & 63];\r
2920 j = 0;\r
2921 break;\r
2922 }\r
2923 if (i > 8191) {\r
2924 (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r
2925 i = 0;\r
2926 }\r
2927 }\r
2928 if (j) {\r
2929 chunk[i++] = b64[t];\r
2930 chunk[i++] = 61;\r
2931 if (j === 1)\r
2932 chunk[i++] = 61;\r
2933 }\r
2934 if (parts) {\r
2935 if (i)\r
2936 parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r
2937 return parts.join("");\r
2938 }\r
2939 return String.fromCharCode.apply(String, chunk.slice(0, i));\r
2940};\r
2941\r
2942var invalidEncoding = "invalid encoding";\r
2943\r
2944/**\r
2945 * Decodes a base64 encoded string to a buffer.\r
2946 * @param {string} string Source string\r
2947 * @param {Uint8Array} buffer Destination buffer\r
2948 * @param {number} offset Destination offset\r
2949 * @returns {number} Number of bytes written\r
2950 * @throws {Error} If encoding is invalid\r
2951 */\r
2952base64.decode = function decode(string, buffer, offset) {\r
2953 var start = offset;\r
2954 var j = 0, // goto index\r
2955 t; // temporary\r
2956 for (var i = 0; i < string.length;) {\r
2957 var c = string.charCodeAt(i++);\r
2958 if (c === 61 && j > 1)\r
2959 break;\r
2960 if ((c = s64[c]) === undefined)\r
2961 throw Error(invalidEncoding);\r
2962 switch (j) {\r
2963 case 0:\r
2964 t = c;\r
2965 j = 1;\r
2966 break;\r
2967 case 1:\r
2968 buffer[offset++] = t << 2 | (c & 48) >> 4;\r
2969 t = c;\r
2970 j = 2;\r
2971 break;\r
2972 case 2:\r
2973 buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2;\r
2974 t = c;\r
2975 j = 3;\r
2976 break;\r
2977 case 3:\r
2978 buffer[offset++] = (t & 3) << 6 | c;\r
2979 j = 0;\r
2980 break;\r
2981 }\r
2982 }\r
2983 if (j === 1)\r
2984 throw Error(invalidEncoding);\r
2985 return offset - start;\r
2986};\r
2987\r
2988/**\r
2989 * Tests if the specified string appears to be base64 encoded.\r
2990 * @param {string} string String to test\r
2991 * @returns {boolean} `true` if probably base64 encoded, otherwise false\r
2992 */\r
2993base64.test = function test(string) {\r
2994 return /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string);\r
2995};\r
2996
2997},{}],24:[function(require,module,exports){
2998"use strict";\r
2999module.exports = codegen;\r
3000\r
3001/**\r
3002 * Begins generating a function.\r
3003 * @memberof util\r
3004 * @param {string[]} functionParams Function parameter names\r
3005 * @param {string} [functionName] Function name if not anonymous\r
3006 * @returns {Codegen} Appender that appends code to the function's body\r
3007 */\r
3008function codegen(functionParams, functionName) {\r
3009\r
3010 /* istanbul ignore if */\r
3011 if (typeof functionParams === "string") {\r
3012 functionName = functionParams;\r
3013 functionParams = undefined;\r
3014 }\r
3015\r
3016 var body = [];\r
3017\r
3018 /**\r
3019 * Appends code to the function's body or finishes generation.\r
3020 * @typedef Codegen\r
3021 * @type {function}\r
3022 * @param {string|Object.<string,*>} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any\r
3023 * @param {...*} [formatParams] Format parameters\r
3024 * @returns {Codegen|Function} Itself or the generated function if finished\r
3025 * @throws {Error} If format parameter counts do not match\r
3026 */\r
3027\r
3028 function Codegen(formatStringOrScope) {\r
3029 // note that explicit array handling below makes this ~50% faster\r
3030\r
3031 // finish the function\r
3032 if (typeof formatStringOrScope !== "string") {\r
3033 var source = toString();\r
3034 if (codegen.verbose)\r
3035 console.log("codegen: " + source); // eslint-disable-line no-console\r
3036 source = "return " + source;\r
3037 if (formatStringOrScope) {\r
3038 var scopeKeys = Object.keys(formatStringOrScope),\r
3039 scopeParams = new Array(scopeKeys.length + 1),\r
3040 scopeValues = new Array(scopeKeys.length),\r
3041 scopeOffset = 0;\r
3042 while (scopeOffset < scopeKeys.length) {\r
3043 scopeParams[scopeOffset] = scopeKeys[scopeOffset];\r
3044 scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]];\r
3045 }\r
3046 scopeParams[scopeOffset] = source;\r
3047 return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func\r
3048 }\r
3049 return Function(source)(); // eslint-disable-line no-new-func\r
3050 }\r
3051\r
3052 // otherwise append to body\r
3053 var formatParams = new Array(arguments.length - 1),\r
3054 formatOffset = 0;\r
3055 while (formatOffset < formatParams.length)\r
3056 formatParams[formatOffset] = arguments[++formatOffset];\r
3057 formatOffset = 0;\r
3058 formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) {\r
3059 var value = formatParams[formatOffset++];\r
3060 switch ($1) {\r
3061 case "d": case "f": return String(Number(value));\r
3062 case "i": return String(Math.floor(value));\r
3063 case "j": return JSON.stringify(value);\r
3064 case "s": return String(value);\r
3065 }\r
3066 return "%";\r
3067 });\r
3068 if (formatOffset !== formatParams.length)\r
3069 throw Error("parameter count mismatch");\r
3070 body.push(formatStringOrScope);\r
3071 return Codegen;\r
3072 }\r
3073\r
3074 function toString(functionNameOverride) {\r
3075 return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}";\r
3076 }\r
3077\r
3078 Codegen.toString = toString;\r
3079 return Codegen;\r
3080}\r
3081\r
3082/**\r
3083 * Begins generating a function.\r
3084 * @memberof util\r
3085 * @function codegen\r
3086 * @param {string} [functionName] Function name if not anonymous\r
3087 * @returns {Codegen} Appender that appends code to the function's body\r
3088 * @variation 2\r
3089 */\r
3090\r
3091/**\r
3092 * When set to `true`, codegen will log generated code to console. Useful for debugging.\r
3093 * @name util.codegen.verbose\r
3094 * @type {boolean}\r
3095 */\r
3096codegen.verbose = false;\r
3097
3098},{}],25:[function(require,module,exports){
3099"use strict";\r
3100module.exports = EventEmitter;\r
3101\r
3102/**\r
3103 * Constructs a new event emitter instance.\r
3104 * @classdesc A minimal event emitter.\r
3105 * @memberof util\r
3106 * @constructor\r
3107 */\r
3108function EventEmitter() {\r
3109\r
3110 /**\r
3111 * Registered listeners.\r
3112 * @type {Object.<string,*>}\r
3113 * @private\r
3114 */\r
3115 this._listeners = {};\r
3116}\r
3117\r
3118/**\r
3119 * Registers an event listener.\r
3120 * @param {string} evt Event name\r
3121 * @param {function} fn Listener\r
3122 * @param {*} [ctx] Listener context\r
3123 * @returns {util.EventEmitter} `this`\r
3124 */\r
3125EventEmitter.prototype.on = function on(evt, fn, ctx) {\r
3126 (this._listeners[evt] || (this._listeners[evt] = [])).push({\r
3127 fn : fn,\r
3128 ctx : ctx || this\r
3129 });\r
3130 return this;\r
3131};\r
3132\r
3133/**\r
3134 * Removes an event listener or any matching listeners if arguments are omitted.\r
3135 * @param {string} [evt] Event name. Removes all listeners if omitted.\r
3136 * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.\r
3137 * @returns {util.EventEmitter} `this`\r
3138 */\r
3139EventEmitter.prototype.off = function off(evt, fn) {\r
3140 if (evt === undefined)\r
3141 this._listeners = {};\r
3142 else {\r
3143 if (fn === undefined)\r
3144 this._listeners[evt] = [];\r
3145 else {\r
3146 var listeners = this._listeners[evt];\r
3147 for (var i = 0; i < listeners.length;)\r
3148 if (listeners[i].fn === fn)\r
3149 listeners.splice(i, 1);\r
3150 else\r
3151 ++i;\r
3152 }\r
3153 }\r
3154 return this;\r
3155};\r
3156\r
3157/**\r
3158 * Emits an event by calling its listeners with the specified arguments.\r
3159 * @param {string} evt Event name\r
3160 * @param {...*} args Arguments\r
3161 * @returns {util.EventEmitter} `this`\r
3162 */\r
3163EventEmitter.prototype.emit = function emit(evt) {\r
3164 var listeners = this._listeners[evt];\r
3165 if (listeners) {\r
3166 var args = [],\r
3167 i = 1;\r
3168 for (; i < arguments.length;)\r
3169 args.push(arguments[i++]);\r
3170 for (i = 0; i < listeners.length;)\r
3171 listeners[i].fn.apply(listeners[i++].ctx, args);\r
3172 }\r
3173 return this;\r
3174};\r
3175
3176},{}],26:[function(require,module,exports){
3177"use strict";\r
3178module.exports = fetch;\r
3179\r
3180var asPromise = require("@protobufjs/aspromise"),\r
3181 inquire = require("@protobufjs/inquire");\r
3182\r
3183var fs = inquire("fs");\r
3184\r
3185/**\r
3186 * Node-style callback as used by {@link util.fetch}.\r
3187 * @typedef FetchCallback\r
3188 * @type {function}\r
3189 * @param {?Error} error Error, if any, otherwise `null`\r
3190 * @param {string} [contents] File contents, if there hasn't been an error\r
3191 * @returns {undefined}\r
3192 */\r
3193\r
3194/**\r
3195 * Options as used by {@link util.fetch}.\r
3196 * @typedef FetchOptions\r
3197 * @type {Object}\r
3198 * @property {boolean} [binary=false] Whether expecting a binary response\r
3199 * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest\r
3200 */\r
3201\r
3202/**\r
3203 * Fetches the contents of a file.\r
3204 * @memberof util\r
3205 * @param {string} filename File path or url\r
3206 * @param {FetchOptions} options Fetch options\r
3207 * @param {FetchCallback} callback Callback function\r
3208 * @returns {undefined}\r
3209 */\r
3210function fetch(filename, options, callback) {\r
3211 if (typeof options === "function") {\r
3212 callback = options;\r
3213 options = {};\r
3214 } else if (!options)\r
3215 options = {};\r
3216\r
3217 if (!callback)\r
3218 return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this\r
3219\r
3220 // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.\r
3221 if (!options.xhr && fs && fs.readFile)\r
3222 return fs.readFile(filename, function fetchReadFileCallback(err, contents) {\r
3223 return err && typeof XMLHttpRequest !== "undefined"\r
3224 ? fetch.xhr(filename, options, callback)\r
3225 : err\r
3226 ? callback(err)\r
3227 : callback(null, options.binary ? contents : contents.toString("utf8"));\r
3228 });\r
3229\r
3230 // use the XHR version otherwise.\r
3231 return fetch.xhr(filename, options, callback);\r
3232}\r
3233\r
3234/**\r
3235 * Fetches the contents of a file.\r
3236 * @name util.fetch\r
3237 * @function\r
3238 * @param {string} path File path or url\r
3239 * @param {FetchCallback} callback Callback function\r
3240 * @returns {undefined}\r
3241 * @variation 2\r
3242 */\r
3243\r
3244/**\r
3245 * Fetches the contents of a file.\r
3246 * @name util.fetch\r
3247 * @function\r
3248 * @param {string} path File path or url\r
3249 * @param {FetchOptions} [options] Fetch options\r
3250 * @returns {Promise<string|Uint8Array>} Promise\r
3251 * @variation 3\r
3252 */\r
3253\r
3254/**/\r
3255fetch.xhr = function fetch_xhr(filename, options, callback) {\r
3256 var xhr = new XMLHttpRequest();\r
3257 xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() {\r
3258\r
3259 if (xhr.readyState !== 4)\r
3260 return undefined;\r
3261\r
3262 // local cors security errors return status 0 / empty string, too. afaik this cannot be\r
3263 // reliably distinguished from an actually empty file for security reasons. feel free\r
3264 // to send a pull request if you are aware of a solution.\r
3265 if (xhr.status !== 0 && xhr.status !== 200)\r
3266 return callback(Error("status " + xhr.status));\r
3267\r
3268 // if binary data is expected, make sure that some sort of array is returned, even if\r
3269 // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.\r
3270 if (options.binary) {\r
3271 var buffer = xhr.response;\r
3272 if (!buffer) {\r
3273 buffer = [];\r
3274 for (var i = 0; i < xhr.responseText.length; ++i)\r
3275 buffer.push(xhr.responseText.charCodeAt(i) & 255);\r
3276 }\r
3277 return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer);\r
3278 }\r
3279 return callback(null, xhr.responseText);\r
3280 };\r
3281\r
3282 if (options.binary) {\r
3283 // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers\r
3284 if ("overrideMimeType" in xhr)\r
3285 xhr.overrideMimeType("text/plain; charset=x-user-defined");\r
3286 xhr.responseType = "arraybuffer";\r
3287 }\r
3288\r
3289 xhr.open("GET", filename);\r
3290 xhr.send();\r
3291};\r
3292
3293},{"@protobufjs/aspromise":22,"@protobufjs/inquire":28}],27:[function(require,module,exports){
3294"use strict";\r
3295\r
3296module.exports = factory(factory);\r
3297\r
3298/**\r
3299 * Reads / writes floats / doubles from / to buffers.\r
3300 * @name util.float\r
3301 * @namespace\r
3302 */\r
3303\r
3304/**\r
3305 * Writes a 32 bit float to a buffer using little endian byte order.\r
3306 * @name util.float.writeFloatLE\r
3307 * @function\r
3308 * @param {number} val Value to write\r
3309 * @param {Uint8Array} buf Target buffer\r
3310 * @param {number} pos Target buffer offset\r
3311 * @returns {undefined}\r
3312 */\r
3313\r
3314/**\r
3315 * Writes a 32 bit float to a buffer using big endian byte order.\r
3316 * @name util.float.writeFloatBE\r
3317 * @function\r
3318 * @param {number} val Value to write\r
3319 * @param {Uint8Array} buf Target buffer\r
3320 * @param {number} pos Target buffer offset\r
3321 * @returns {undefined}\r
3322 */\r
3323\r
3324/**\r
3325 * Reads a 32 bit float from a buffer using little endian byte order.\r
3326 * @name util.float.readFloatLE\r
3327 * @function\r
3328 * @param {Uint8Array} buf Source buffer\r
3329 * @param {number} pos Source buffer offset\r
3330 * @returns {number} Value read\r
3331 */\r
3332\r
3333/**\r
3334 * Reads a 32 bit float from a buffer using big endian byte order.\r
3335 * @name util.float.readFloatBE\r
3336 * @function\r
3337 * @param {Uint8Array} buf Source buffer\r
3338 * @param {number} pos Source buffer offset\r
3339 * @returns {number} Value read\r
3340 */\r
3341\r
3342/**\r
3343 * Writes a 64 bit double to a buffer using little endian byte order.\r
3344 * @name util.float.writeDoubleLE\r
3345 * @function\r
3346 * @param {number} val Value to write\r
3347 * @param {Uint8Array} buf Target buffer\r
3348 * @param {number} pos Target buffer offset\r
3349 * @returns {undefined}\r
3350 */\r
3351\r
3352/**\r
3353 * Writes a 64 bit double to a buffer using big endian byte order.\r
3354 * @name util.float.writeDoubleBE\r
3355 * @function\r
3356 * @param {number} val Value to write\r
3357 * @param {Uint8Array} buf Target buffer\r
3358 * @param {number} pos Target buffer offset\r
3359 * @returns {undefined}\r
3360 */\r
3361\r
3362/**\r
3363 * Reads a 64 bit double from a buffer using little endian byte order.\r
3364 * @name util.float.readDoubleLE\r
3365 * @function\r
3366 * @param {Uint8Array} buf Source buffer\r
3367 * @param {number} pos Source buffer offset\r
3368 * @returns {number} Value read\r
3369 */\r
3370\r
3371/**\r
3372 * Reads a 64 bit double from a buffer using big endian byte order.\r
3373 * @name util.float.readDoubleBE\r
3374 * @function\r
3375 * @param {Uint8Array} buf Source buffer\r
3376 * @param {number} pos Source buffer offset\r
3377 * @returns {number} Value read\r
3378 */\r
3379\r
3380// Factory function for the purpose of node-based testing in modified global environments\r
3381function factory(exports) {\r
3382\r
3383 // float: typed array\r
3384 if (typeof Float32Array !== "undefined") (function() {\r
3385\r
3386 var f32 = new Float32Array([ -0 ]),\r
3387 f8b = new Uint8Array(f32.buffer),\r
3388 le = f8b[3] === 128;\r
3389\r
3390 function writeFloat_f32_cpy(val, buf, pos) {\r
3391 f32[0] = val;\r
3392 buf[pos ] = f8b[0];\r
3393 buf[pos + 1] = f8b[1];\r
3394 buf[pos + 2] = f8b[2];\r
3395 buf[pos + 3] = f8b[3];\r
3396 }\r
3397\r
3398 function writeFloat_f32_rev(val, buf, pos) {\r
3399 f32[0] = val;\r
3400 buf[pos ] = f8b[3];\r
3401 buf[pos + 1] = f8b[2];\r
3402 buf[pos + 2] = f8b[1];\r
3403 buf[pos + 3] = f8b[0];\r
3404 }\r
3405\r
3406 /* istanbul ignore next */\r
3407 exports.writeFloatLE = le ? writeFloat_f32_cpy : writeFloat_f32_rev;\r
3408 /* istanbul ignore next */\r
3409 exports.writeFloatBE = le ? writeFloat_f32_rev : writeFloat_f32_cpy;\r
3410\r
3411 function readFloat_f32_cpy(buf, pos) {\r
3412 f8b[0] = buf[pos ];\r
3413 f8b[1] = buf[pos + 1];\r
3414 f8b[2] = buf[pos + 2];\r
3415 f8b[3] = buf[pos + 3];\r
3416 return f32[0];\r
3417 }\r
3418\r
3419 function readFloat_f32_rev(buf, pos) {\r
3420 f8b[3] = buf[pos ];\r
3421 f8b[2] = buf[pos + 1];\r
3422 f8b[1] = buf[pos + 2];\r
3423 f8b[0] = buf[pos + 3];\r
3424 return f32[0];\r
3425 }\r
3426\r
3427 /* istanbul ignore next */\r
3428 exports.readFloatLE = le ? readFloat_f32_cpy : readFloat_f32_rev;\r
3429 /* istanbul ignore next */\r
3430 exports.readFloatBE = le ? readFloat_f32_rev : readFloat_f32_cpy;\r
3431\r
3432 // float: ieee754\r
3433 })(); else (function() {\r
3434\r
3435 function writeFloat_ieee754(writeUint, val, buf, pos) {\r
3436 var sign = val < 0 ? 1 : 0;\r
3437 if (sign)\r
3438 val = -val;\r
3439 if (val === 0)\r
3440 writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos);\r
3441 else if (isNaN(val))\r
3442 writeUint(2143289344, buf, pos);\r
3443 else if (val > 3.4028234663852886e+38) // +-Infinity\r
3444 writeUint((sign << 31 | 2139095040) >>> 0, buf, pos);\r
3445 else if (val < 1.1754943508222875e-38) // denormal\r
3446 writeUint((sign << 31 | Math.round(val / 1.401298464324817e-45)) >>> 0, buf, pos);\r
3447 else {\r
3448 var exponent = Math.floor(Math.log(val) / Math.LN2),\r
3449 mantissa = Math.round(val * Math.pow(2, -exponent) * 8388608) & 8388607;\r
3450 writeUint((sign << 31 | exponent + 127 << 23 | mantissa) >>> 0, buf, pos);\r
3451 }\r
3452 }\r
3453\r
3454 exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE);\r
3455 exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE);\r
3456\r
3457 function readFloat_ieee754(readUint, buf, pos) {\r
3458 var uint = readUint(buf, pos),\r
3459 sign = (uint >> 31) * 2 + 1,\r
3460 exponent = uint >>> 23 & 255,\r
3461 mantissa = uint & 8388607;\r
3462 return exponent === 255\r
3463 ? mantissa\r
3464 ? NaN\r
3465 : sign * Infinity\r
3466 : exponent === 0 // denormal\r
3467 ? sign * 1.401298464324817e-45 * mantissa\r
3468 : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608);\r
3469 }\r
3470\r
3471 exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE);\r
3472 exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE);\r
3473\r
3474 })();\r
3475\r
3476 // double: typed array\r
3477 if (typeof Float64Array !== "undefined") (function() {\r
3478\r
3479 var f64 = new Float64Array([-0]),\r
3480 f8b = new Uint8Array(f64.buffer),\r
3481 le = f8b[7] === 128;\r
3482\r
3483 function writeDouble_f64_cpy(val, buf, pos) {\r
3484 f64[0] = val;\r
3485 buf[pos ] = f8b[0];\r
3486 buf[pos + 1] = f8b[1];\r
3487 buf[pos + 2] = f8b[2];\r
3488 buf[pos + 3] = f8b[3];\r
3489 buf[pos + 4] = f8b[4];\r
3490 buf[pos + 5] = f8b[5];\r
3491 buf[pos + 6] = f8b[6];\r
3492 buf[pos + 7] = f8b[7];\r
3493 }\r
3494\r
3495 function writeDouble_f64_rev(val, buf, pos) {\r
3496 f64[0] = val;\r
3497 buf[pos ] = f8b[7];\r
3498 buf[pos + 1] = f8b[6];\r
3499 buf[pos + 2] = f8b[5];\r
3500 buf[pos + 3] = f8b[4];\r
3501 buf[pos + 4] = f8b[3];\r
3502 buf[pos + 5] = f8b[2];\r
3503 buf[pos + 6] = f8b[1];\r
3504 buf[pos + 7] = f8b[0];\r
3505 }\r
3506\r
3507 /* istanbul ignore next */\r
3508 exports.writeDoubleLE = le ? writeDouble_f64_cpy : writeDouble_f64_rev;\r
3509 /* istanbul ignore next */\r
3510 exports.writeDoubleBE = le ? writeDouble_f64_rev : writeDouble_f64_cpy;\r
3511\r
3512 function readDouble_f64_cpy(buf, pos) {\r
3513 f8b[0] = buf[pos ];\r
3514 f8b[1] = buf[pos + 1];\r
3515 f8b[2] = buf[pos + 2];\r
3516 f8b[3] = buf[pos + 3];\r
3517 f8b[4] = buf[pos + 4];\r
3518 f8b[5] = buf[pos + 5];\r
3519 f8b[6] = buf[pos + 6];\r
3520 f8b[7] = buf[pos + 7];\r
3521 return f64[0];\r
3522 }\r
3523\r
3524 function readDouble_f64_rev(buf, pos) {\r
3525 f8b[7] = buf[pos ];\r
3526 f8b[6] = buf[pos + 1];\r
3527 f8b[5] = buf[pos + 2];\r
3528 f8b[4] = buf[pos + 3];\r
3529 f8b[3] = buf[pos + 4];\r
3530 f8b[2] = buf[pos + 5];\r
3531 f8b[1] = buf[pos + 6];\r
3532 f8b[0] = buf[pos + 7];\r
3533 return f64[0];\r
3534 }\r
3535\r
3536 /* istanbul ignore next */\r
3537 exports.readDoubleLE = le ? readDouble_f64_cpy : readDouble_f64_rev;\r
3538 /* istanbul ignore next */\r
3539 exports.readDoubleBE = le ? readDouble_f64_rev : readDouble_f64_cpy;\r
3540\r
3541 // double: ieee754\r
3542 })(); else (function() {\r
3543\r
3544 function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) {\r
3545 var sign = val < 0 ? 1 : 0;\r
3546 if (sign)\r
3547 val = -val;\r
3548 if (val === 0) {\r
3549 writeUint(0, buf, pos + off0);\r
3550 writeUint(1 / val > 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf, pos + off1);\r
3551 } else if (isNaN(val)) {\r
3552 writeUint(0, buf, pos + off0);\r
3553 writeUint(2146959360, buf, pos + off1);\r
3554 } else if (val > 1.7976931348623157e+308) { // +-Infinity\r
3555 writeUint(0, buf, pos + off0);\r
3556 writeUint((sign << 31 | 2146435072) >>> 0, buf, pos + off1);\r
3557 } else {\r
3558 var mantissa;\r
3559 if (val < 2.2250738585072014e-308) { // denormal\r
3560 mantissa = val / 5e-324;\r
3561 writeUint(mantissa >>> 0, buf, pos + off0);\r
3562 writeUint((sign << 31 | mantissa / 4294967296) >>> 0, buf, pos + off1);\r
3563 } else {\r
3564 var exponent = Math.floor(Math.log(val) / Math.LN2);\r
3565 if (exponent === 1024)\r
3566 exponent = 1023;\r
3567 mantissa = val * Math.pow(2, -exponent);\r
3568 writeUint(mantissa * 4503599627370496 >>> 0, buf, pos + off0);\r
3569 writeUint((sign << 31 | exponent + 1023 << 20 | mantissa * 1048576 & 1048575) >>> 0, buf, pos + off1);\r
3570 }\r
3571 }\r
3572 }\r
3573\r
3574 exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4);\r
3575 exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0);\r
3576\r
3577 function readDouble_ieee754(readUint, off0, off1, buf, pos) {\r
3578 var lo = readUint(buf, pos + off0),\r
3579 hi = readUint(buf, pos + off1);\r
3580 var sign = (hi >> 31) * 2 + 1,\r
3581 exponent = hi >>> 20 & 2047,\r
3582 mantissa = 4294967296 * (hi & 1048575) + lo;\r
3583 return exponent === 2047\r
3584 ? mantissa\r
3585 ? NaN\r
3586 : sign * Infinity\r
3587 : exponent === 0 // denormal\r
3588 ? sign * 5e-324 * mantissa\r
3589 : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496);\r
3590 }\r
3591\r
3592 exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4);\r
3593 exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0);\r
3594\r
3595 })();\r
3596\r
3597 return exports;\r
3598}\r
3599\r
3600// uint helpers\r
3601\r
3602function writeUintLE(val, buf, pos) {\r
3603 buf[pos ] = val & 255;\r
3604 buf[pos + 1] = val >>> 8 & 255;\r
3605 buf[pos + 2] = val >>> 16 & 255;\r
3606 buf[pos + 3] = val >>> 24;\r
3607}\r
3608\r
3609function writeUintBE(val, buf, pos) {\r
3610 buf[pos ] = val >>> 24;\r
3611 buf[pos + 1] = val >>> 16 & 255;\r
3612 buf[pos + 2] = val >>> 8 & 255;\r
3613 buf[pos + 3] = val & 255;\r
3614}\r
3615\r
3616function readUintLE(buf, pos) {\r
3617 return (buf[pos ]\r
3618 | buf[pos + 1] << 8\r
3619 | buf[pos + 2] << 16\r
3620 | buf[pos + 3] << 24) >>> 0;\r
3621}\r
3622\r
3623function readUintBE(buf, pos) {\r
3624 return (buf[pos ] << 24\r
3625 | buf[pos + 1] << 16\r
3626 | buf[pos + 2] << 8\r
3627 | buf[pos + 3]) >>> 0;\r
3628}\r
3629
3630},{}],28:[function(require,module,exports){
3631"use strict";\r
3632module.exports = inquire;\r
3633\r
3634/**\r
3635 * Requires a module only if available.\r
3636 * @memberof util\r
3637 * @param {string} moduleName Module to require\r
3638 * @returns {?Object} Required module if available and not empty, otherwise `null`\r
3639 */\r
3640function inquire(moduleName) {\r
3641 try {\r
3642 var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval\r
3643 if (mod && (mod.length || Object.keys(mod).length))\r
3644 return mod;\r
3645 } catch (e) {} // eslint-disable-line no-empty\r
3646 return null;\r
3647}\r
3648
3649},{}],29:[function(require,module,exports){
3650"use strict";\r
3651\r
3652/**\r
3653 * A minimal path module to resolve Unix, Windows and URL paths alike.\r
3654 * @memberof util\r
3655 * @namespace\r
3656 */\r
3657var path = exports;\r
3658\r
3659var isAbsolute =\r
3660/**\r
3661 * Tests if the specified path is absolute.\r
3662 * @param {string} path Path to test\r
3663 * @returns {boolean} `true` if path is absolute\r
3664 */\r
3665path.isAbsolute = function isAbsolute(path) {\r
3666 return /^(?:\/|\w+:)/.test(path);\r
3667};\r
3668\r
3669var normalize =\r
3670/**\r
3671 * Normalizes the specified path.\r
3672 * @param {string} path Path to normalize\r
3673 * @returns {string} Normalized path\r
3674 */\r
3675path.normalize = function normalize(path) {\r
3676 path = path.replace(/\\/g, "/")\r
3677 .replace(/\/{2,}/g, "/");\r
3678 var parts = path.split("/"),\r
3679 absolute = isAbsolute(path),\r
3680 prefix = "";\r
3681 if (absolute)\r
3682 prefix = parts.shift() + "/";\r
3683 for (var i = 0; i < parts.length;) {\r
3684 if (parts[i] === "..") {\r
3685 if (i > 0 && parts[i - 1] !== "..")\r
3686 parts.splice(--i, 2);\r
3687 else if (absolute)\r
3688 parts.splice(i, 1);\r
3689 else\r
3690 ++i;\r
3691 } else if (parts[i] === ".")\r
3692 parts.splice(i, 1);\r
3693 else\r
3694 ++i;\r
3695 }\r
3696 return prefix + parts.join("/");\r
3697};\r
3698\r
3699/**\r
3700 * Resolves the specified include path against the specified origin path.\r
3701 * @param {string} originPath Path to the origin file\r
3702 * @param {string} includePath Include path relative to origin path\r
3703 * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized\r
3704 * @returns {string} Path to the include file\r
3705 */\r
3706path.resolve = function resolve(originPath, includePath, alreadyNormalized) {\r
3707 if (!alreadyNormalized)\r
3708 includePath = normalize(includePath);\r
3709 if (isAbsolute(includePath))\r
3710 return includePath;\r
3711 if (!alreadyNormalized)\r
3712 originPath = normalize(originPath);\r
3713 return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath;\r
3714};\r
3715
3716},{}],30:[function(require,module,exports){
3717"use strict";\r
3718module.exports = pool;\r
3719\r
3720/**\r
3721 * An allocator as used by {@link util.pool}.\r
3722 * @typedef PoolAllocator\r
3723 * @type {function}\r
3724 * @param {number} size Buffer size\r
3725 * @returns {Uint8Array} Buffer\r
3726 */\r
3727\r
3728/**\r
3729 * A slicer as used by {@link util.pool}.\r
3730 * @typedef PoolSlicer\r
3731 * @type {function}\r
3732 * @param {number} start Start offset\r
3733 * @param {number} end End offset\r
3734 * @returns {Uint8Array} Buffer slice\r
3735 * @this {Uint8Array}\r
3736 */\r
3737\r
3738/**\r
3739 * A general purpose buffer pool.\r
3740 * @memberof util\r
3741 * @function\r
3742 * @param {PoolAllocator} alloc Allocator\r
3743 * @param {PoolSlicer} slice Slicer\r
3744 * @param {number} [size=8192] Slab size\r
3745 * @returns {PoolAllocator} Pooled allocator\r
3746 */\r
3747function pool(alloc, slice, size) {\r
3748 var SIZE = size || 8192;\r
3749 var MAX = SIZE >>> 1;\r
3750 var slab = null;\r
3751 var offset = SIZE;\r
3752 return function pool_alloc(size) {\r
3753 if (size < 1 || size > MAX)\r
3754 return alloc(size);\r
3755 if (offset + size > SIZE) {\r
3756 slab = alloc(SIZE);\r
3757 offset = 0;\r
3758 }\r
3759 var buf = slice.call(slab, offset, offset += size);\r
3760 if (offset & 7) // align to 32 bit\r
3761 offset = (offset | 7) + 1;\r
3762 return buf;\r
3763 };\r
3764}\r
3765
3766},{}],31:[function(require,module,exports){
3767"use strict";\r
3768\r
3769/**\r
3770 * A minimal UTF8 implementation for number arrays.\r
3771 * @memberof util\r
3772 * @namespace\r
3773 */\r
3774var utf8 = exports;\r
3775\r
3776/**\r
3777 * Calculates the UTF8 byte length of a string.\r
3778 * @param {string} string String\r
3779 * @returns {number} Byte length\r
3780 */\r
3781utf8.length = function utf8_length(string) {\r
3782 var len = 0,\r
3783 c = 0;\r
3784 for (var i = 0; i < string.length; ++i) {\r
3785 c = string.charCodeAt(i);\r
3786 if (c < 128)\r
3787 len += 1;\r
3788 else if (c < 2048)\r
3789 len += 2;\r
3790 else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) {\r
3791 ++i;\r
3792 len += 4;\r
3793 } else\r
3794 len += 3;\r
3795 }\r
3796 return len;\r
3797};\r
3798\r
3799/**\r
3800 * Reads UTF8 bytes as a string.\r
3801 * @param {Uint8Array} buffer Source buffer\r
3802 * @param {number} start Source start\r
3803 * @param {number} end Source end\r
3804 * @returns {string} String read\r
3805 */\r
3806utf8.read = function utf8_read(buffer, start, end) {\r
3807 var len = end - start;\r
3808 if (len < 1)\r
3809 return "";\r
3810 var parts = null,\r
3811 chunk = [],\r
3812 i = 0, // char offset\r
3813 t; // temporary\r
3814 while (start < end) {\r
3815 t = buffer[start++];\r
3816 if (t < 128)\r
3817 chunk[i++] = t;\r
3818 else if (t > 191 && t < 224)\r
3819 chunk[i++] = (t & 31) << 6 | buffer[start++] & 63;\r
3820 else if (t > 239 && t < 365) {\r
3821 t = ((t & 7) << 18 | (buffer[start++] & 63) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63) - 0x10000;\r
3822 chunk[i++] = 0xD800 + (t >> 10);\r
3823 chunk[i++] = 0xDC00 + (t & 1023);\r
3824 } else\r
3825 chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63;\r
3826 if (i > 8191) {\r
3827 (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk));\r
3828 i = 0;\r
3829 }\r
3830 }\r
3831 if (parts) {\r
3832 if (i)\r
3833 parts.push(String.fromCharCode.apply(String, chunk.slice(0, i)));\r
3834 return parts.join("");\r
3835 }\r
3836 return String.fromCharCode.apply(String, chunk.slice(0, i));\r
3837};\r
3838\r
3839/**\r
3840 * Writes a string as UTF8 bytes.\r
3841 * @param {string} string Source string\r
3842 * @param {Uint8Array} buffer Destination buffer\r
3843 * @param {number} offset Destination offset\r
3844 * @returns {number} Bytes written\r
3845 */\r
3846utf8.write = function utf8_write(string, buffer, offset) {\r
3847 var start = offset,\r
3848 c1, // character 1\r
3849 c2; // character 2\r
3850 for (var i = 0; i < string.length; ++i) {\r
3851 c1 = string.charCodeAt(i);\r
3852 if (c1 < 128) {\r
3853 buffer[offset++] = c1;\r
3854 } else if (c1 < 2048) {\r
3855 buffer[offset++] = c1 >> 6 | 192;\r
3856 buffer[offset++] = c1 & 63 | 128;\r
3857 } else if ((c1 & 0xFC00) === 0xD800 && ((c2 = string.charCodeAt(i + 1)) & 0xFC00) === 0xDC00) {\r
3858 c1 = 0x10000 + ((c1 & 0x03FF) << 10) + (c2 & 0x03FF);\r
3859 ++i;\r
3860 buffer[offset++] = c1 >> 18 | 240;\r
3861 buffer[offset++] = c1 >> 12 & 63 | 128;\r
3862 buffer[offset++] = c1 >> 6 & 63 | 128;\r
3863 buffer[offset++] = c1 & 63 | 128;\r
3864 } else {\r
3865 buffer[offset++] = c1 >> 12 | 224;\r
3866 buffer[offset++] = c1 >> 6 & 63 | 128;\r
3867 buffer[offset++] = c1 & 63 | 128;\r
3868 }\r
3869 }\r
3870 return offset - start;\r
3871};\r
3872
3873},{}],32:[function(require,module,exports){
3874var asn1 = exports;
3875
3876asn1.bignum = require('bn.js');
3877
3878asn1.define = require('./asn1/api').define;
3879asn1.base = require('./asn1/base');
3880asn1.constants = require('./asn1/constants');
3881asn1.decoders = require('./asn1/decoders');
3882asn1.encoders = require('./asn1/encoders');
3883
3884},{"./asn1/api":33,"./asn1/base":35,"./asn1/constants":39,"./asn1/decoders":41,"./asn1/encoders":44,"bn.js":75}],33:[function(require,module,exports){
3885var asn1 = require('../asn1');
3886var inherits = require('inherits');
3887
3888var api = exports;
3889
3890api.define = function define(name, body) {
3891 return new Entity(name, body);
3892};
3893
3894function Entity(name, body) {
3895 this.name = name;
3896 this.body = body;
3897
3898 this.decoders = {};
3899 this.encoders = {};
3900};
3901
3902Entity.prototype._createNamed = function createNamed(base) {
3903 var named;
3904 try {
3905 named = require('vm').runInThisContext(
3906 '(function ' + this.name + '(entity) {\n' +
3907 ' this._initNamed(entity);\n' +
3908 '})'
3909 );
3910 } catch (e) {
3911 named = function (entity) {
3912 this._initNamed(entity);
3913 };
3914 }
3915 inherits(named, base);
3916 named.prototype._initNamed = function initnamed(entity) {
3917 base.call(this, entity);
3918 };
3919
3920 return new named(this);
3921};
3922
3923Entity.prototype._getDecoder = function _getDecoder(enc) {
3924 enc = enc || 'der';
3925 // Lazily create decoder
3926 if (!this.decoders.hasOwnProperty(enc))
3927 this.decoders[enc] = this._createNamed(asn1.decoders[enc]);
3928 return this.decoders[enc];
3929};
3930
3931Entity.prototype.decode = function decode(data, enc, options) {
3932 return this._getDecoder(enc).decode(data, options);
3933};
3934
3935Entity.prototype._getEncoder = function _getEncoder(enc) {
3936 enc = enc || 'der';
3937 // Lazily create encoder
3938 if (!this.encoders.hasOwnProperty(enc))
3939 this.encoders[enc] = this._createNamed(asn1.encoders[enc]);
3940 return this.encoders[enc];
3941};
3942
3943Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
3944 return this._getEncoder(enc).encode(data, reporter);
3945};
3946
3947},{"../asn1":32,"inherits":163,"vm":271}],34:[function(require,module,exports){
3948var inherits = require('inherits');
3949var Reporter = require('../base').Reporter;
3950var Buffer = require('buffer').Buffer;
3951
3952function DecoderBuffer(base, options) {
3953 Reporter.call(this, options);
3954 if (!Buffer.isBuffer(base)) {
3955 this.error('Input not Buffer');
3956 return;
3957 }
3958
3959 this.base = base;
3960 this.offset = 0;
3961 this.length = base.length;
3962}
3963inherits(DecoderBuffer, Reporter);
3964exports.DecoderBuffer = DecoderBuffer;
3965
3966DecoderBuffer.prototype.save = function save() {
3967 return { offset: this.offset, reporter: Reporter.prototype.save.call(this) };
3968};
3969
3970DecoderBuffer.prototype.restore = function restore(save) {
3971 // Return skipped data
3972 var res = new DecoderBuffer(this.base);
3973 res.offset = save.offset;
3974 res.length = this.offset;
3975
3976 this.offset = save.offset;
3977 Reporter.prototype.restore.call(this, save.reporter);
3978
3979 return res;
3980};
3981
3982DecoderBuffer.prototype.isEmpty = function isEmpty() {
3983 return this.offset === this.length;
3984};
3985
3986DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) {
3987 if (this.offset + 1 <= this.length)
3988 return this.base.readUInt8(this.offset++, true);
3989 else
3990 return this.error(fail || 'DecoderBuffer overrun');
3991}
3992
3993DecoderBuffer.prototype.skip = function skip(bytes, fail) {
3994 if (!(this.offset + bytes <= this.length))
3995 return this.error(fail || 'DecoderBuffer overrun');
3996
3997 var res = new DecoderBuffer(this.base);
3998
3999 // Share reporter state
4000 res._reporterState = this._reporterState;
4001
4002 res.offset = this.offset;
4003 res.length = this.offset + bytes;
4004 this.offset += bytes;
4005 return res;
4006}
4007
4008DecoderBuffer.prototype.raw = function raw(save) {
4009 return this.base.slice(save ? save.offset : this.offset, this.length);
4010}
4011
4012function EncoderBuffer(value, reporter) {
4013 if (Array.isArray(value)) {
4014 this.length = 0;
4015 this.value = value.map(function(item) {
4016 if (!(item instanceof EncoderBuffer))
4017 item = new EncoderBuffer(item, reporter);
4018 this.length += item.length;
4019 return item;
4020 }, this);
4021 } else if (typeof value === 'number') {
4022 if (!(0 <= value && value <= 0xff))
4023 return reporter.error('non-byte EncoderBuffer value');
4024 this.value = value;
4025 this.length = 1;
4026 } else if (typeof value === 'string') {
4027 this.value = value;
4028 this.length = Buffer.byteLength(value);
4029 } else if (Buffer.isBuffer(value)) {
4030 this.value = value;
4031 this.length = value.length;
4032 } else {
4033 return reporter.error('Unsupported type: ' + typeof value);
4034 }
4035}
4036exports.EncoderBuffer = EncoderBuffer;
4037
4038EncoderBuffer.prototype.join = function join(out, offset) {
4039 if (!out)
4040 out = new Buffer(this.length);
4041 if (!offset)
4042 offset = 0;
4043
4044 if (this.length === 0)
4045 return out;
4046
4047 if (Array.isArray(this.value)) {
4048 this.value.forEach(function(item) {
4049 item.join(out, offset);
4050 offset += item.length;
4051 });
4052 } else {
4053 if (typeof this.value === 'number')
4054 out[offset] = this.value;
4055 else if (typeof this.value === 'string')
4056 out.write(this.value, offset);
4057 else if (Buffer.isBuffer(this.value))
4058 this.value.copy(out, offset);
4059 offset += this.length;
4060 }
4061
4062 return out;
4063};
4064
4065},{"../base":35,"buffer":107,"inherits":163}],35:[function(require,module,exports){
4066var base = exports;
4067
4068base.Reporter = require('./reporter').Reporter;
4069base.DecoderBuffer = require('./buffer').DecoderBuffer;
4070base.EncoderBuffer = require('./buffer').EncoderBuffer;
4071base.Node = require('./node');
4072
4073},{"./buffer":34,"./node":36,"./reporter":37}],36:[function(require,module,exports){
4074var Reporter = require('../base').Reporter;
4075var EncoderBuffer = require('../base').EncoderBuffer;
4076var DecoderBuffer = require('../base').DecoderBuffer;
4077var assert = require('minimalistic-assert');
4078
4079// Supported tags
4080var tags = [
4081 'seq', 'seqof', 'set', 'setof', 'objid', 'bool',
4082 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc',
4083 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str',
4084 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr'
4085];
4086
4087// Public methods list
4088var methods = [
4089 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
4090 'any', 'contains'
4091].concat(tags);
4092
4093// Overrided methods list
4094var overrided = [
4095 '_peekTag', '_decodeTag', '_use',
4096 '_decodeStr', '_decodeObjid', '_decodeTime',
4097 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
4098
4099 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
4100 '_encodeNull', '_encodeInt', '_encodeBool'
4101];
4102
4103function Node(enc, parent) {
4104 var state = {};
4105 this._baseState = state;
4106
4107 state.enc = enc;
4108
4109 state.parent = parent || null;
4110 state.children = null;
4111
4112 // State
4113 state.tag = null;
4114 state.args = null;
4115 state.reverseArgs = null;
4116 state.choice = null;
4117 state.optional = false;
4118 state.any = false;
4119 state.obj = false;
4120 state.use = null;
4121 state.useDecoder = null;
4122 state.key = null;
4123 state['default'] = null;
4124 state.explicit = null;
4125 state.implicit = null;
4126 state.contains = null;
4127
4128 // Should create new instance on each method
4129 if (!state.parent) {
4130 state.children = [];
4131 this._wrap();
4132 }
4133}
4134module.exports = Node;
4135
4136var stateProps = [
4137 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
4138 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
4139 'implicit', 'contains'
4140];
4141
4142Node.prototype.clone = function clone() {
4143 var state = this._baseState;
4144 var cstate = {};
4145 stateProps.forEach(function(prop) {
4146 cstate[prop] = state[prop];
4147 });
4148 var res = new this.constructor(cstate.parent);
4149 res._baseState = cstate;
4150 return res;
4151};
4152
4153Node.prototype._wrap = function wrap() {
4154 var state = this._baseState;
4155 methods.forEach(function(method) {
4156 this[method] = function _wrappedMethod() {
4157 var clone = new this.constructor(this);
4158 state.children.push(clone);
4159 return clone[method].apply(clone, arguments);
4160 };
4161 }, this);
4162};
4163
4164Node.prototype._init = function init(body) {
4165 var state = this._baseState;
4166
4167 assert(state.parent === null);
4168 body.call(this);
4169
4170 // Filter children
4171 state.children = state.children.filter(function(child) {
4172 return child._baseState.parent === this;
4173 }, this);
4174 assert.equal(state.children.length, 1, 'Root node can have only one child');
4175};
4176
4177Node.prototype._useArgs = function useArgs(args) {
4178 var state = this._baseState;
4179
4180 // Filter children and args
4181 var children = args.filter(function(arg) {
4182 return arg instanceof this.constructor;
4183 }, this);
4184 args = args.filter(function(arg) {
4185 return !(arg instanceof this.constructor);
4186 }, this);
4187
4188 if (children.length !== 0) {
4189 assert(state.children === null);
4190 state.children = children;
4191
4192 // Replace parent to maintain backward link
4193 children.forEach(function(child) {
4194 child._baseState.parent = this;
4195 }, this);
4196 }
4197 if (args.length !== 0) {
4198 assert(state.args === null);
4199 state.args = args;
4200 state.reverseArgs = args.map(function(arg) {
4201 if (typeof arg !== 'object' || arg.constructor !== Object)
4202 return arg;
4203
4204 var res = {};
4205 Object.keys(arg).forEach(function(key) {
4206 if (key == (key | 0))
4207 key |= 0;
4208 var value = arg[key];
4209 res[value] = key;
4210 });
4211 return res;
4212 });
4213 }
4214};
4215
4216//
4217// Overrided methods
4218//
4219
4220overrided.forEach(function(method) {
4221 Node.prototype[method] = function _overrided() {
4222 var state = this._baseState;
4223 throw new Error(method + ' not implemented for encoding: ' + state.enc);
4224 };
4225});
4226
4227//
4228// Public methods
4229//
4230
4231tags.forEach(function(tag) {
4232 Node.prototype[tag] = function _tagMethod() {
4233 var state = this._baseState;
4234 var args = Array.prototype.slice.call(arguments);
4235
4236 assert(state.tag === null);
4237 state.tag = tag;
4238
4239 this._useArgs(args);
4240
4241 return this;
4242 };
4243});
4244
4245Node.prototype.use = function use(item) {
4246 assert(item);
4247 var state = this._baseState;
4248
4249 assert(state.use === null);
4250 state.use = item;
4251
4252 return this;
4253};
4254
4255Node.prototype.optional = function optional() {
4256 var state = this._baseState;
4257
4258 state.optional = true;
4259
4260 return this;
4261};
4262
4263Node.prototype.def = function def(val) {
4264 var state = this._baseState;
4265
4266 assert(state['default'] === null);
4267 state['default'] = val;
4268 state.optional = true;
4269
4270 return this;
4271};
4272
4273Node.prototype.explicit = function explicit(num) {
4274 var state = this._baseState;
4275
4276 assert(state.explicit === null && state.implicit === null);
4277 state.explicit = num;
4278
4279 return this;
4280};
4281
4282Node.prototype.implicit = function implicit(num) {
4283 var state = this._baseState;
4284
4285 assert(state.explicit === null && state.implicit === null);
4286 state.implicit = num;
4287
4288 return this;
4289};
4290
4291Node.prototype.obj = function obj() {
4292 var state = this._baseState;
4293 var args = Array.prototype.slice.call(arguments);
4294
4295 state.obj = true;
4296
4297 if (args.length !== 0)
4298 this._useArgs(args);
4299
4300 return this;
4301};
4302
4303Node.prototype.key = function key(newKey) {
4304 var state = this._baseState;
4305
4306 assert(state.key === null);
4307 state.key = newKey;
4308
4309 return this;
4310};
4311
4312Node.prototype.any = function any() {
4313 var state = this._baseState;
4314
4315 state.any = true;
4316
4317 return this;
4318};
4319
4320Node.prototype.choice = function choice(obj) {
4321 var state = this._baseState;
4322
4323 assert(state.choice === null);
4324 state.choice = obj;
4325 this._useArgs(Object.keys(obj).map(function(key) {
4326 return obj[key];
4327 }));
4328
4329 return this;
4330};
4331
4332Node.prototype.contains = function contains(item) {
4333 var state = this._baseState;
4334
4335 assert(state.use === null);
4336 state.contains = item;
4337
4338 return this;
4339};
4340
4341//
4342// Decoding
4343//
4344
4345Node.prototype._decode = function decode(input, options) {
4346 var state = this._baseState;
4347
4348 // Decode root node
4349 if (state.parent === null)
4350 return input.wrapResult(state.children[0]._decode(input, options));
4351
4352 var result = state['default'];
4353 var present = true;
4354
4355 var prevKey = null;
4356 if (state.key !== null)
4357 prevKey = input.enterKey(state.key);
4358
4359 // Check if tag is there
4360 if (state.optional) {
4361 var tag = null;
4362 if (state.explicit !== null)
4363 tag = state.explicit;
4364 else if (state.implicit !== null)
4365 tag = state.implicit;
4366 else if (state.tag !== null)
4367 tag = state.tag;
4368
4369 if (tag === null && !state.any) {
4370 // Trial and Error
4371 var save = input.save();
4372 try {
4373 if (state.choice === null)
4374 this._decodeGeneric(state.tag, input, options);
4375 else
4376 this._decodeChoice(input, options);
4377 present = true;
4378 } catch (e) {
4379 present = false;
4380 }
4381 input.restore(save);
4382 } else {
4383 present = this._peekTag(input, tag, state.any);
4384
4385 if (input.isError(present))
4386 return present;
4387 }
4388 }
4389
4390 // Push object on stack
4391 var prevObj;
4392 if (state.obj && present)
4393 prevObj = input.enterObject();
4394
4395 if (present) {
4396 // Unwrap explicit values
4397 if (state.explicit !== null) {
4398 var explicit = this._decodeTag(input, state.explicit);
4399 if (input.isError(explicit))
4400 return explicit;
4401 input = explicit;
4402 }
4403
4404 var start = input.offset;
4405
4406 // Unwrap implicit and normal values
4407 if (state.use === null && state.choice === null) {
4408 if (state.any)
4409 var save = input.save();
4410 var body = this._decodeTag(
4411 input,
4412 state.implicit !== null ? state.implicit : state.tag,
4413 state.any
4414 );
4415 if (input.isError(body))
4416 return body;
4417
4418 if (state.any)
4419 result = input.raw(save);
4420 else
4421 input = body;
4422 }
4423
4424 if (options && options.track && state.tag !== null)
4425 options.track(input.path(), start, input.length, 'tagged');
4426
4427 if (options && options.track && state.tag !== null)
4428 options.track(input.path(), input.offset, input.length, 'content');
4429
4430 // Select proper method for tag
4431 if (state.any)
4432 result = result;
4433 else if (state.choice === null)
4434 result = this._decodeGeneric(state.tag, input, options);
4435 else
4436 result = this._decodeChoice(input, options);
4437
4438 if (input.isError(result))
4439 return result;
4440
4441 // Decode children
4442 if (!state.any && state.choice === null && state.children !== null) {
4443 state.children.forEach(function decodeChildren(child) {
4444 // NOTE: We are ignoring errors here, to let parser continue with other
4445 // parts of encoded data
4446 child._decode(input, options);
4447 });
4448 }
4449
4450 // Decode contained/encoded by schema, only in bit or octet strings
4451 if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) {
4452 var data = new DecoderBuffer(result);
4453 result = this._getUse(state.contains, input._reporterState.obj)
4454 ._decode(data, options);
4455 }
4456 }
4457
4458 // Pop object
4459 if (state.obj && present)
4460 result = input.leaveObject(prevObj);
4461
4462 // Set key
4463 if (state.key !== null && (result !== null || present === true))
4464 input.leaveKey(prevKey, state.key, result);
4465 else if (prevKey !== null)
4466 input.exitKey(prevKey);
4467
4468 return result;
4469};
4470
4471Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) {
4472 var state = this._baseState;
4473
4474 if (tag === 'seq' || tag === 'set')
4475 return null;
4476 if (tag === 'seqof' || tag === 'setof')
4477 return this._decodeList(input, tag, state.args[0], options);
4478 else if (/str$/.test(tag))
4479 return this._decodeStr(input, tag, options);
4480 else if (tag === 'objid' && state.args)
4481 return this._decodeObjid(input, state.args[0], state.args[1], options);
4482 else if (tag === 'objid')
4483 return this._decodeObjid(input, null, null, options);
4484 else if (tag === 'gentime' || tag === 'utctime')
4485 return this._decodeTime(input, tag, options);
4486 else if (tag === 'null_')
4487 return this._decodeNull(input, options);
4488 else if (tag === 'bool')
4489 return this._decodeBool(input, options);
4490 else if (tag === 'objDesc')
4491 return this._decodeStr(input, tag, options);
4492 else if (tag === 'int' || tag === 'enum')
4493 return this._decodeInt(input, state.args && state.args[0], options);
4494
4495 if (state.use !== null) {
4496 return this._getUse(state.use, input._reporterState.obj)
4497 ._decode(input, options);
4498 } else {
4499 return input.error('unknown tag: ' + tag);
4500 }
4501};
4502
4503Node.prototype._getUse = function _getUse(entity, obj) {
4504
4505 var state = this._baseState;
4506 // Create altered use decoder if implicit is set
4507 state.useDecoder = this._use(entity, obj);
4508 assert(state.useDecoder._baseState.parent === null);
4509 state.useDecoder = state.useDecoder._baseState.children[0];
4510 if (state.implicit !== state.useDecoder._baseState.implicit) {
4511 state.useDecoder = state.useDecoder.clone();
4512 state.useDecoder._baseState.implicit = state.implicit;
4513 }
4514 return state.useDecoder;
4515};
4516
4517Node.prototype._decodeChoice = function decodeChoice(input, options) {
4518 var state = this._baseState;
4519 var result = null;
4520 var match = false;
4521
4522 Object.keys(state.choice).some(function(key) {
4523 var save = input.save();
4524 var node = state.choice[key];
4525 try {
4526 var value = node._decode(input, options);
4527 if (input.isError(value))
4528 return false;
4529
4530 result = { type: key, value: value };
4531 match = true;
4532 } catch (e) {
4533 input.restore(save);
4534 return false;
4535 }
4536 return true;
4537 }, this);
4538
4539 if (!match)
4540 return input.error('Choice not matched');
4541
4542 return result;
4543};
4544
4545//
4546// Encoding
4547//
4548
4549Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) {
4550 return new EncoderBuffer(data, this.reporter);
4551};
4552
4553Node.prototype._encode = function encode(data, reporter, parent) {
4554 var state = this._baseState;
4555 if (state['default'] !== null && state['default'] === data)
4556 return;
4557
4558 var result = this._encodeValue(data, reporter, parent);
4559 if (result === undefined)
4560 return;
4561
4562 if (this._skipDefault(result, reporter, parent))
4563 return;
4564
4565 return result;
4566};
4567
4568Node.prototype._encodeValue = function encode(data, reporter, parent) {
4569 var state = this._baseState;
4570
4571 // Decode root node
4572 if (state.parent === null)
4573 return state.children[0]._encode(data, reporter || new Reporter());
4574
4575 var result = null;
4576
4577 // Set reporter to share it with a child class
4578 this.reporter = reporter;
4579
4580 // Check if data is there
4581 if (state.optional && data === undefined) {
4582 if (state['default'] !== null)
4583 data = state['default']
4584 else
4585 return;
4586 }
4587
4588 // Encode children first
4589 var content = null;
4590 var primitive = false;
4591 if (state.any) {
4592 // Anything that was given is translated to buffer
4593 result = this._createEncoderBuffer(data);
4594 } else if (state.choice) {
4595 result = this._encodeChoice(data, reporter);
4596 } else if (state.contains) {
4597 content = this._getUse(state.contains, parent)._encode(data, reporter);
4598 primitive = true;
4599 } else if (state.children) {
4600 content = state.children.map(function(child) {
4601 if (child._baseState.tag === 'null_')
4602 return child._encode(null, reporter, data);
4603
4604 if (child._baseState.key === null)
4605 return reporter.error('Child should have a key');
4606 var prevKey = reporter.enterKey(child._baseState.key);
4607
4608 if (typeof data !== 'object')
4609 return reporter.error('Child expected, but input is not object');
4610
4611 var res = child._encode(data[child._baseState.key], reporter, data);
4612 reporter.leaveKey(prevKey);
4613
4614 return res;
4615 }, this).filter(function(child) {
4616 return child;
4617 });
4618 content = this._createEncoderBuffer(content);
4619 } else {
4620 if (state.tag === 'seqof' || state.tag === 'setof') {
4621 // TODO(indutny): this should be thrown on DSL level
4622 if (!(state.args && state.args.length === 1))
4623 return reporter.error('Too many args for : ' + state.tag);
4624
4625 if (!Array.isArray(data))
4626 return reporter.error('seqof/setof, but data is not Array');
4627
4628 var child = this.clone();
4629 child._baseState.implicit = null;
4630 content = this._createEncoderBuffer(data.map(function(item) {
4631 var state = this._baseState;
4632
4633 return this._getUse(state.args[0], data)._encode(item, reporter);
4634 }, child));
4635 } else if (state.use !== null) {
4636 result = this._getUse(state.use, parent)._encode(data, reporter);
4637 } else {
4638 content = this._encodePrimitive(state.tag, data);
4639 primitive = true;
4640 }
4641 }
4642
4643 // Encode data itself
4644 var result;
4645 if (!state.any && state.choice === null) {
4646 var tag = state.implicit !== null ? state.implicit : state.tag;
4647 var cls = state.implicit === null ? 'universal' : 'context';
4648
4649 if (tag === null) {
4650 if (state.use === null)
4651 reporter.error('Tag could be omitted only for .use()');
4652 } else {
4653 if (state.use === null)
4654 result = this._encodeComposite(tag, primitive, cls, content);
4655 }
4656 }
4657
4658 // Wrap in explicit
4659 if (state.explicit !== null)
4660 result = this._encodeComposite(state.explicit, false, 'context', result);
4661
4662 return result;
4663};
4664
4665Node.prototype._encodeChoice = function encodeChoice(data, reporter) {
4666 var state = this._baseState;
4667
4668 var node = state.choice[data.type];
4669 if (!node) {
4670 assert(
4671 false,
4672 data.type + ' not found in ' +
4673 JSON.stringify(Object.keys(state.choice)));
4674 }
4675 return node._encode(data.value, reporter);
4676};
4677
4678Node.prototype._encodePrimitive = function encodePrimitive(tag, data) {
4679 var state = this._baseState;
4680
4681 if (/str$/.test(tag))
4682 return this._encodeStr(data, tag);
4683 else if (tag === 'objid' && state.args)
4684 return this._encodeObjid(data, state.reverseArgs[0], state.args[1]);
4685 else if (tag === 'objid')
4686 return this._encodeObjid(data, null, null);
4687 else if (tag === 'gentime' || tag === 'utctime')
4688 return this._encodeTime(data, tag);
4689 else if (tag === 'null_')
4690 return this._encodeNull();
4691 else if (tag === 'int' || tag === 'enum')
4692 return this._encodeInt(data, state.args && state.reverseArgs[0]);
4693 else if (tag === 'bool')
4694 return this._encodeBool(data);
4695 else if (tag === 'objDesc')
4696 return this._encodeStr(data, tag);
4697 else
4698 throw new Error('Unsupported tag: ' + tag);
4699};
4700
4701Node.prototype._isNumstr = function isNumstr(str) {
4702 return /^[0-9 ]*$/.test(str);
4703};
4704
4705Node.prototype._isPrintstr = function isPrintstr(str) {
4706 return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
4707};
4708
4709},{"../base":35,"minimalistic-assert":176}],37:[function(require,module,exports){
4710var inherits = require('inherits');
4711
4712function Reporter(options) {
4713 this._reporterState = {
4714 obj: null,
4715 path: [],
4716 options: options || {},
4717 errors: []
4718 };
4719}
4720exports.Reporter = Reporter;
4721
4722Reporter.prototype.isError = function isError(obj) {
4723 return obj instanceof ReporterError;
4724};
4725
4726Reporter.prototype.save = function save() {
4727 var state = this._reporterState;
4728
4729 return { obj: state.obj, pathLen: state.path.length };
4730};
4731
4732Reporter.prototype.restore = function restore(data) {
4733 var state = this._reporterState;
4734
4735 state.obj = data.obj;
4736 state.path = state.path.slice(0, data.pathLen);
4737};
4738
4739Reporter.prototype.enterKey = function enterKey(key) {
4740 return this._reporterState.path.push(key);
4741};
4742
4743Reporter.prototype.exitKey = function exitKey(index) {
4744 var state = this._reporterState;
4745
4746 state.path = state.path.slice(0, index - 1);
4747};
4748
4749Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
4750 var state = this._reporterState;
4751
4752 this.exitKey(index);
4753 if (state.obj !== null)
4754 state.obj[key] = value;
4755};
4756
4757Reporter.prototype.path = function path() {
4758 return this._reporterState.path.join('/');
4759};
4760
4761Reporter.prototype.enterObject = function enterObject() {
4762 var state = this._reporterState;
4763
4764 var prev = state.obj;
4765 state.obj = {};
4766 return prev;
4767};
4768
4769Reporter.prototype.leaveObject = function leaveObject(prev) {
4770 var state = this._reporterState;
4771
4772 var now = state.obj;
4773 state.obj = prev;
4774 return now;
4775};
4776
4777Reporter.prototype.error = function error(msg) {
4778 var err;
4779 var state = this._reporterState;
4780
4781 var inherited = msg instanceof ReporterError;
4782 if (inherited) {
4783 err = msg;
4784 } else {
4785 err = new ReporterError(state.path.map(function(elem) {
4786 return '[' + JSON.stringify(elem) + ']';
4787 }).join(''), msg.message || msg, msg.stack);
4788 }
4789
4790 if (!state.options.partial)
4791 throw err;
4792
4793 if (!inherited)
4794 state.errors.push(err);
4795
4796 return err;
4797};
4798
4799Reporter.prototype.wrapResult = function wrapResult(result) {
4800 var state = this._reporterState;
4801 if (!state.options.partial)
4802 return result;
4803
4804 return {
4805 result: this.isError(result) ? null : result,
4806 errors: state.errors
4807 };
4808};
4809
4810function ReporterError(path, msg) {
4811 this.path = path;
4812 this.rethrow(msg);
4813};
4814inherits(ReporterError, Error);
4815
4816ReporterError.prototype.rethrow = function rethrow(msg) {
4817 this.message = msg + ' at: ' + (this.path || '(shallow)');
4818 if (Error.captureStackTrace)
4819 Error.captureStackTrace(this, ReporterError);
4820
4821 if (!this.stack) {
4822 try {
4823 // IE only adds stack when thrown
4824 throw new Error(this.message);
4825 } catch (e) {
4826 this.stack = e.stack;
4827 }
4828 }
4829 return this;
4830};
4831
4832},{"inherits":163}],38:[function(require,module,exports){
4833var constants = require('../constants');
4834
4835exports.tagClass = {
4836 0: 'universal',
4837 1: 'application',
4838 2: 'context',
4839 3: 'private'
4840};
4841exports.tagClassByName = constants._reverse(exports.tagClass);
4842
4843exports.tag = {
4844 0x00: 'end',
4845 0x01: 'bool',
4846 0x02: 'int',
4847 0x03: 'bitstr',
4848 0x04: 'octstr',
4849 0x05: 'null_',
4850 0x06: 'objid',
4851 0x07: 'objDesc',
4852 0x08: 'external',
4853 0x09: 'real',
4854 0x0a: 'enum',
4855 0x0b: 'embed',
4856 0x0c: 'utf8str',
4857 0x0d: 'relativeOid',
4858 0x10: 'seq',
4859 0x11: 'set',
4860 0x12: 'numstr',
4861 0x13: 'printstr',
4862 0x14: 't61str',
4863 0x15: 'videostr',
4864 0x16: 'ia5str',
4865 0x17: 'utctime',
4866 0x18: 'gentime',
4867 0x19: 'graphstr',
4868 0x1a: 'iso646str',
4869 0x1b: 'genstr',
4870 0x1c: 'unistr',
4871 0x1d: 'charstr',
4872 0x1e: 'bmpstr'
4873};
4874exports.tagByName = constants._reverse(exports.tag);
4875
4876},{"../constants":39}],39:[function(require,module,exports){
4877var constants = exports;
4878
4879// Helper
4880constants._reverse = function reverse(map) {
4881 var res = {};
4882
4883 Object.keys(map).forEach(function(key) {
4884 // Convert key to integer if it is stringified
4885 if ((key | 0) == key)
4886 key = key | 0;
4887
4888 var value = map[key];
4889 res[value] = key;
4890 });
4891
4892 return res;
4893};
4894
4895constants.der = require('./der');
4896
4897},{"./der":38}],40:[function(require,module,exports){
4898var inherits = require('inherits');
4899
4900var asn1 = require('../../asn1');
4901var base = asn1.base;
4902var bignum = asn1.bignum;
4903
4904// Import DER constants
4905var der = asn1.constants.der;
4906
4907function DERDecoder(entity) {
4908 this.enc = 'der';
4909 this.name = entity.name;
4910 this.entity = entity;
4911
4912 // Construct base tree
4913 this.tree = new DERNode();
4914 this.tree._init(entity.body);
4915};
4916module.exports = DERDecoder;
4917
4918DERDecoder.prototype.decode = function decode(data, options) {
4919 if (!(data instanceof base.DecoderBuffer))
4920 data = new base.DecoderBuffer(data, options);
4921
4922 return this.tree._decode(data, options);
4923};
4924
4925// Tree methods
4926
4927function DERNode(parent) {
4928 base.Node.call(this, 'der', parent);
4929}
4930inherits(DERNode, base.Node);
4931
4932DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
4933 if (buffer.isEmpty())
4934 return false;
4935
4936 var state = buffer.save();
4937 var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"');
4938 if (buffer.isError(decodedTag))
4939 return decodedTag;
4940
4941 buffer.restore(state);
4942
4943 return decodedTag.tag === tag || decodedTag.tagStr === tag ||
4944 (decodedTag.tagStr + 'of') === tag || any;
4945};
4946
4947DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
4948 var decodedTag = derDecodeTag(buffer,
4949 'Failed to decode tag of "' + tag + '"');
4950 if (buffer.isError(decodedTag))
4951 return decodedTag;
4952
4953 var len = derDecodeLen(buffer,
4954 decodedTag.primitive,
4955 'Failed to get length of "' + tag + '"');
4956
4957 // Failure
4958 if (buffer.isError(len))
4959 return len;
4960
4961 if (!any &&
4962 decodedTag.tag !== tag &&
4963 decodedTag.tagStr !== tag &&
4964 decodedTag.tagStr + 'of' !== tag) {
4965 return buffer.error('Failed to match tag: "' + tag + '"');
4966 }
4967
4968 if (decodedTag.primitive || len !== null)
4969 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
4970
4971 // Indefinite length... find END tag
4972 var state = buffer.save();
4973 var res = this._skipUntilEnd(
4974 buffer,
4975 'Failed to skip indefinite length body: "' + this.tag + '"');
4976 if (buffer.isError(res))
4977 return res;
4978
4979 len = buffer.offset - state.offset;
4980 buffer.restore(state);
4981 return buffer.skip(len, 'Failed to match body of: "' + tag + '"');
4982};
4983
4984DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
4985 while (true) {
4986 var tag = derDecodeTag(buffer, fail);
4987 if (buffer.isError(tag))
4988 return tag;
4989 var len = derDecodeLen(buffer, tag.primitive, fail);
4990 if (buffer.isError(len))
4991 return len;
4992
4993 var res;
4994 if (tag.primitive || len !== null)
4995 res = buffer.skip(len)
4996 else
4997 res = this._skipUntilEnd(buffer, fail);
4998
4999 // Failure
5000 if (buffer.isError(res))
5001 return res;
5002
5003 if (tag.tagStr === 'end')
5004 break;
5005 }
5006};
5007
5008DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
5009 options) {
5010 var result = [];
5011 while (!buffer.isEmpty()) {
5012 var possibleEnd = this._peekTag(buffer, 'end');
5013 if (buffer.isError(possibleEnd))
5014 return possibleEnd;
5015
5016 var res = decoder.decode(buffer, 'der', options);
5017 if (buffer.isError(res) && possibleEnd)
5018 break;
5019 result.push(res);
5020 }
5021 return result;
5022};
5023
5024DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
5025 if (tag === 'bitstr') {
5026 var unused = buffer.readUInt8();
5027 if (buffer.isError(unused))
5028 return unused;
5029 return { unused: unused, data: buffer.raw() };
5030 } else if (tag === 'bmpstr') {
5031 var raw = buffer.raw();
5032 if (raw.length % 2 === 1)
5033 return buffer.error('Decoding of string type: bmpstr length mismatch');
5034
5035 var str = '';
5036 for (var i = 0; i < raw.length / 2; i++) {
5037 str += String.fromCharCode(raw.readUInt16BE(i * 2));
5038 }
5039 return str;
5040 } else if (tag === 'numstr') {
5041 var numstr = buffer.raw().toString('ascii');
5042 if (!this._isNumstr(numstr)) {
5043 return buffer.error('Decoding of string type: ' +
5044 'numstr unsupported characters');
5045 }
5046 return numstr;
5047 } else if (tag === 'octstr') {
5048 return buffer.raw();
5049 } else if (tag === 'objDesc') {
5050 return buffer.raw();
5051 } else if (tag === 'printstr') {
5052 var printstr = buffer.raw().toString('ascii');
5053 if (!this._isPrintstr(printstr)) {
5054 return buffer.error('Decoding of string type: ' +
5055 'printstr unsupported characters');
5056 }
5057 return printstr;
5058 } else if (/str$/.test(tag)) {
5059 return buffer.raw().toString();
5060 } else {
5061 return buffer.error('Decoding of string type: ' + tag + ' unsupported');
5062 }
5063};
5064
5065DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
5066 var result;
5067 var identifiers = [];
5068 var ident = 0;
5069 while (!buffer.isEmpty()) {
5070 var subident = buffer.readUInt8();
5071 ident <<= 7;
5072 ident |= subident & 0x7f;
5073 if ((subident & 0x80) === 0) {
5074 identifiers.push(ident);
5075 ident = 0;
5076 }
5077 }
5078 if (subident & 0x80)
5079 identifiers.push(ident);
5080
5081 var first = (identifiers[0] / 40) | 0;
5082 var second = identifiers[0] % 40;
5083
5084 if (relative)
5085 result = identifiers;
5086 else
5087 result = [first, second].concat(identifiers.slice(1));
5088
5089 if (values) {
5090 var tmp = values[result.join(' ')];
5091 if (tmp === undefined)
5092 tmp = values[result.join('.')];
5093 if (tmp !== undefined)
5094 result = tmp;
5095 }
5096
5097 return result;
5098};
5099
5100DERNode.prototype._decodeTime = function decodeTime(buffer, tag) {
5101 var str = buffer.raw().toString();
5102 if (tag === 'gentime') {
5103 var year = str.slice(0, 4) | 0;
5104 var mon = str.slice(4, 6) | 0;
5105 var day = str.slice(6, 8) | 0;
5106 var hour = str.slice(8, 10) | 0;
5107 var min = str.slice(10, 12) | 0;
5108 var sec = str.slice(12, 14) | 0;
5109 } else if (tag === 'utctime') {
5110 var year = str.slice(0, 2) | 0;
5111 var mon = str.slice(2, 4) | 0;
5112 var day = str.slice(4, 6) | 0;
5113 var hour = str.slice(6, 8) | 0;
5114 var min = str.slice(8, 10) | 0;
5115 var sec = str.slice(10, 12) | 0;
5116 if (year < 70)
5117 year = 2000 + year;
5118 else
5119 year = 1900 + year;
5120 } else {
5121 return buffer.error('Decoding ' + tag + ' time is not supported yet');
5122 }
5123
5124 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
5125};
5126
5127DERNode.prototype._decodeNull = function decodeNull(buffer) {
5128 return null;
5129};
5130
5131DERNode.prototype._decodeBool = function decodeBool(buffer) {
5132 var res = buffer.readUInt8();
5133 if (buffer.isError(res))
5134 return res;
5135 else
5136 return res !== 0;
5137};
5138
5139DERNode.prototype._decodeInt = function decodeInt(buffer, values) {
5140 // Bigint, return as it is (assume big endian)
5141 var raw = buffer.raw();
5142 var res = new bignum(raw);
5143
5144 if (values)
5145 res = values[res.toString(10)] || res;
5146
5147 return res;
5148};
5149
5150DERNode.prototype._use = function use(entity, obj) {
5151 if (typeof entity === 'function')
5152 entity = entity(obj);
5153 return entity._getDecoder('der').tree;
5154};
5155
5156// Utility methods
5157
5158function derDecodeTag(buf, fail) {
5159 var tag = buf.readUInt8(fail);
5160 if (buf.isError(tag))
5161 return tag;
5162
5163 var cls = der.tagClass[tag >> 6];
5164 var primitive = (tag & 0x20) === 0;
5165
5166 // Multi-octet tag - load
5167 if ((tag & 0x1f) === 0x1f) {
5168 var oct = tag;
5169 tag = 0;
5170 while ((oct & 0x80) === 0x80) {
5171 oct = buf.readUInt8(fail);
5172 if (buf.isError(oct))
5173 return oct;
5174
5175 tag <<= 7;
5176 tag |= oct & 0x7f;
5177 }
5178 } else {
5179 tag &= 0x1f;
5180 }
5181 var tagStr = der.tag[tag];
5182
5183 return {
5184 cls: cls,
5185 primitive: primitive,
5186 tag: tag,
5187 tagStr: tagStr
5188 };
5189}
5190
5191function derDecodeLen(buf, primitive, fail) {
5192 var len = buf.readUInt8(fail);
5193 if (buf.isError(len))
5194 return len;
5195
5196 // Indefinite form
5197 if (!primitive && len === 0x80)
5198 return null;
5199
5200 // Definite form
5201 if ((len & 0x80) === 0) {
5202 // Short form
5203 return len;
5204 }
5205
5206 // Long form
5207 var num = len & 0x7f;
5208 if (num > 4)
5209 return buf.error('length octect is too long');
5210
5211 len = 0;
5212 for (var i = 0; i < num; i++) {
5213 len <<= 8;
5214 var j = buf.readUInt8(fail);
5215 if (buf.isError(j))
5216 return j;
5217 len |= j;
5218 }
5219
5220 return len;
5221}
5222
5223},{"../../asn1":32,"inherits":163}],41:[function(require,module,exports){
5224var decoders = exports;
5225
5226decoders.der = require('./der');
5227decoders.pem = require('./pem');
5228
5229},{"./der":40,"./pem":42}],42:[function(require,module,exports){
5230var inherits = require('inherits');
5231var Buffer = require('buffer').Buffer;
5232
5233var DERDecoder = require('./der');
5234
5235function PEMDecoder(entity) {
5236 DERDecoder.call(this, entity);
5237 this.enc = 'pem';
5238};
5239inherits(PEMDecoder, DERDecoder);
5240module.exports = PEMDecoder;
5241
5242PEMDecoder.prototype.decode = function decode(data, options) {
5243 var lines = data.toString().split(/[\r\n]+/g);
5244
5245 var label = options.label.toUpperCase();
5246
5247 var re = /^-----(BEGIN|END) ([^-]+)-----$/;
5248 var start = -1;
5249 var end = -1;
5250 for (var i = 0; i < lines.length; i++) {
5251 var match = lines[i].match(re);
5252 if (match === null)
5253 continue;
5254
5255 if (match[2] !== label)
5256 continue;
5257
5258 if (start === -1) {
5259 if (match[1] !== 'BEGIN')
5260 break;
5261 start = i;
5262 } else {
5263 if (match[1] !== 'END')
5264 break;
5265 end = i;
5266 break;
5267 }
5268 }
5269 if (start === -1 || end === -1)
5270 throw new Error('PEM section not found for: ' + label);
5271
5272 var base64 = lines.slice(start + 1, end).join('');
5273 // Remove excessive symbols
5274 base64.replace(/[^a-z0-9\+\/=]+/gi, '');
5275
5276 var input = new Buffer(base64, 'base64');
5277 return DERDecoder.prototype.decode.call(this, input, options);
5278};
5279
5280},{"./der":40,"buffer":107,"inherits":163}],43:[function(require,module,exports){
5281var inherits = require('inherits');
5282var Buffer = require('buffer').Buffer;
5283
5284var asn1 = require('../../asn1');
5285var base = asn1.base;
5286
5287// Import DER constants
5288var der = asn1.constants.der;
5289
5290function DEREncoder(entity) {
5291 this.enc = 'der';
5292 this.name = entity.name;
5293 this.entity = entity;
5294
5295 // Construct base tree
5296 this.tree = new DERNode();
5297 this.tree._init(entity.body);
5298};
5299module.exports = DEREncoder;
5300
5301DEREncoder.prototype.encode = function encode(data, reporter) {
5302 return this.tree._encode(data, reporter).join();
5303};
5304
5305// Tree methods
5306
5307function DERNode(parent) {
5308 base.Node.call(this, 'der', parent);
5309}
5310inherits(DERNode, base.Node);
5311
5312DERNode.prototype._encodeComposite = function encodeComposite(tag,
5313 primitive,
5314 cls,
5315 content) {
5316 var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
5317
5318 // Short form
5319 if (content.length < 0x80) {
5320 var header = new Buffer(2);
5321 header[0] = encodedTag;
5322 header[1] = content.length;
5323 return this._createEncoderBuffer([ header, content ]);
5324 }
5325
5326 // Long form
5327 // Count octets required to store length
5328 var lenOctets = 1;
5329 for (var i = content.length; i >= 0x100; i >>= 8)
5330 lenOctets++;
5331
5332 var header = new Buffer(1 + 1 + lenOctets);
5333 header[0] = encodedTag;
5334 header[1] = 0x80 | lenOctets;
5335
5336 for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
5337 header[i] = j & 0xff;
5338
5339 return this._createEncoderBuffer([ header, content ]);
5340};
5341
5342DERNode.prototype._encodeStr = function encodeStr(str, tag) {
5343 if (tag === 'bitstr') {
5344 return this._createEncoderBuffer([ str.unused | 0, str.data ]);
5345 } else if (tag === 'bmpstr') {
5346 var buf = new Buffer(str.length * 2);
5347 for (var i = 0; i < str.length; i++) {
5348 buf.writeUInt16BE(str.charCodeAt(i), i * 2);
5349 }
5350 return this._createEncoderBuffer(buf);
5351 } else if (tag === 'numstr') {
5352 if (!this._isNumstr(str)) {
5353 return this.reporter.error('Encoding of string type: numstr supports ' +
5354 'only digits and space');
5355 }
5356 return this._createEncoderBuffer(str);
5357 } else if (tag === 'printstr') {
5358 if (!this._isPrintstr(str)) {
5359 return this.reporter.error('Encoding of string type: printstr supports ' +
5360 'only latin upper and lower case letters, ' +
5361 'digits, space, apostrophe, left and rigth ' +
5362 'parenthesis, plus sign, comma, hyphen, ' +
5363 'dot, slash, colon, equal sign, ' +
5364 'question mark');
5365 }
5366 return this._createEncoderBuffer(str);
5367 } else if (/str$/.test(tag)) {
5368 return this._createEncoderBuffer(str);
5369 } else if (tag === 'objDesc') {
5370 return this._createEncoderBuffer(str);
5371 } else {
5372 return this.reporter.error('Encoding of string type: ' + tag +
5373 ' unsupported');
5374 }
5375};
5376
5377DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
5378 if (typeof id === 'string') {
5379 if (!values)
5380 return this.reporter.error('string objid given, but no values map found');
5381 if (!values.hasOwnProperty(id))
5382 return this.reporter.error('objid not found in values map');
5383 id = values[id].split(/[\s\.]+/g);
5384 for (var i = 0; i < id.length; i++)
5385 id[i] |= 0;
5386 } else if (Array.isArray(id)) {
5387 id = id.slice();
5388 for (var i = 0; i < id.length; i++)
5389 id[i] |= 0;
5390 }
5391
5392 if (!Array.isArray(id)) {
5393 return this.reporter.error('objid() should be either array or string, ' +
5394 'got: ' + JSON.stringify(id));
5395 }
5396
5397 if (!relative) {
5398 if (id[1] >= 40)
5399 return this.reporter.error('Second objid identifier OOB');
5400 id.splice(0, 2, id[0] * 40 + id[1]);
5401 }
5402
5403 // Count number of octets
5404 var size = 0;
5405 for (var i = 0; i < id.length; i++) {
5406 var ident = id[i];
5407 for (size++; ident >= 0x80; ident >>= 7)
5408 size++;
5409 }
5410
5411 var objid = new Buffer(size);
5412 var offset = objid.length - 1;
5413 for (var i = id.length - 1; i >= 0; i--) {
5414 var ident = id[i];
5415 objid[offset--] = ident & 0x7f;
5416 while ((ident >>= 7) > 0)
5417 objid[offset--] = 0x80 | (ident & 0x7f);
5418 }
5419
5420 return this._createEncoderBuffer(objid);
5421};
5422
5423function two(num) {
5424 if (num < 10)
5425 return '0' + num;
5426 else
5427 return num;
5428}
5429
5430DERNode.prototype._encodeTime = function encodeTime(time, tag) {
5431 var str;
5432 var date = new Date(time);
5433
5434 if (tag === 'gentime') {
5435 str = [
5436 two(date.getFullYear()),
5437 two(date.getUTCMonth() + 1),
5438 two(date.getUTCDate()),
5439 two(date.getUTCHours()),
5440 two(date.getUTCMinutes()),
5441 two(date.getUTCSeconds()),
5442 'Z'
5443 ].join('');
5444 } else if (tag === 'utctime') {
5445 str = [
5446 two(date.getFullYear() % 100),
5447 two(date.getUTCMonth() + 1),
5448 two(date.getUTCDate()),
5449 two(date.getUTCHours()),
5450 two(date.getUTCMinutes()),
5451 two(date.getUTCSeconds()),
5452 'Z'
5453 ].join('');
5454 } else {
5455 this.reporter.error('Encoding ' + tag + ' time is not supported yet');
5456 }
5457
5458 return this._encodeStr(str, 'octstr');
5459};
5460
5461DERNode.prototype._encodeNull = function encodeNull() {
5462 return this._createEncoderBuffer('');
5463};
5464
5465DERNode.prototype._encodeInt = function encodeInt(num, values) {
5466 if (typeof num === 'string') {
5467 if (!values)
5468 return this.reporter.error('String int or enum given, but no values map');
5469 if (!values.hasOwnProperty(num)) {
5470 return this.reporter.error('Values map doesn\'t contain: ' +
5471 JSON.stringify(num));
5472 }
5473 num = values[num];
5474 }
5475
5476 // Bignum, assume big endian
5477 if (typeof num !== 'number' && !Buffer.isBuffer(num)) {
5478 var numArray = num.toArray();
5479 if (!num.sign && numArray[0] & 0x80) {
5480 numArray.unshift(0);
5481 }
5482 num = new Buffer(numArray);
5483 }
5484
5485 if (Buffer.isBuffer(num)) {
5486 var size = num.length;
5487 if (num.length === 0)
5488 size++;
5489
5490 var out = new Buffer(size);
5491 num.copy(out);
5492 if (num.length === 0)
5493 out[0] = 0
5494 return this._createEncoderBuffer(out);
5495 }
5496
5497 if (num < 0x80)
5498 return this._createEncoderBuffer(num);
5499
5500 if (num < 0x100)
5501 return this._createEncoderBuffer([0, num]);
5502
5503 var size = 1;
5504 for (var i = num; i >= 0x100; i >>= 8)
5505 size++;
5506
5507 var out = new Array(size);
5508 for (var i = out.length - 1; i >= 0; i--) {
5509 out[i] = num & 0xff;
5510 num >>= 8;
5511 }
5512 if(out[0] & 0x80) {
5513 out.unshift(0);
5514 }
5515
5516 return this._createEncoderBuffer(new Buffer(out));
5517};
5518
5519DERNode.prototype._encodeBool = function encodeBool(value) {
5520 return this._createEncoderBuffer(value ? 0xff : 0);
5521};
5522
5523DERNode.prototype._use = function use(entity, obj) {
5524 if (typeof entity === 'function')
5525 entity = entity(obj);
5526 return entity._getEncoder('der').tree;
5527};
5528
5529DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
5530 var state = this._baseState;
5531 var i;
5532 if (state['default'] === null)
5533 return false;
5534
5535 var data = dataBuffer.join();
5536 if (state.defaultBuffer === undefined)
5537 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
5538
5539 if (data.length !== state.defaultBuffer.length)
5540 return false;
5541
5542 for (i=0; i < data.length; i++)
5543 if (data[i] !== state.defaultBuffer[i])
5544 return false;
5545
5546 return true;
5547};
5548
5549// Utility methods
5550
5551function encodeTag(tag, primitive, cls, reporter) {
5552 var res;
5553
5554 if (tag === 'seqof')
5555 tag = 'seq';
5556 else if (tag === 'setof')
5557 tag = 'set';
5558
5559 if (der.tagByName.hasOwnProperty(tag))
5560 res = der.tagByName[tag];
5561 else if (typeof tag === 'number' && (tag | 0) === tag)
5562 res = tag;
5563 else
5564 return reporter.error('Unknown tag: ' + tag);
5565
5566 if (res >= 0x1f)
5567 return reporter.error('Multi-octet tag encoding unsupported');
5568
5569 if (!primitive)
5570 res |= 0x20;
5571
5572 res |= (der.tagClassByName[cls || 'universal'] << 6);
5573
5574 return res;
5575}
5576
5577},{"../../asn1":32,"buffer":107,"inherits":163}],44:[function(require,module,exports){
5578var encoders = exports;
5579
5580encoders.der = require('./der');
5581encoders.pem = require('./pem');
5582
5583},{"./der":43,"./pem":45}],45:[function(require,module,exports){
5584var inherits = require('inherits');
5585
5586var DEREncoder = require('./der');
5587
5588function PEMEncoder(entity) {
5589 DEREncoder.call(this, entity);
5590 this.enc = 'pem';
5591};
5592inherits(PEMEncoder, DEREncoder);
5593module.exports = PEMEncoder;
5594
5595PEMEncoder.prototype.encode = function encode(data, options) {
5596 var buf = DEREncoder.prototype.encode.call(this, data);
5597
5598 var p = buf.toString('base64');
5599 var out = [ '-----BEGIN ' + options.label + '-----' ];
5600 for (var i = 0; i < p.length; i += 64)
5601 out.push(p.slice(i, i + 64));
5602 out.push('-----END ' + options.label + '-----');
5603 return out.join('\n');
5604};
5605
5606},{"./der":43,"inherits":163}],46:[function(require,module,exports){
5607module.exports = require('./lib/axios');
5608},{"./lib/axios":48}],47:[function(require,module,exports){
5609(function (process){
5610'use strict';
5611
5612var utils = require('./../utils');
5613var settle = require('./../core/settle');
5614var buildURL = require('./../helpers/buildURL');
5615var parseHeaders = require('./../helpers/parseHeaders');
5616var isURLSameOrigin = require('./../helpers/isURLSameOrigin');
5617var createError = require('../core/createError');
5618var btoa = (typeof window !== 'undefined' && window.btoa && window.btoa.bind(window)) || require('./../helpers/btoa');
5619
5620module.exports = function xhrAdapter(config) {
5621 return new Promise(function dispatchXhrRequest(resolve, reject) {
5622 var requestData = config.data;
5623 var requestHeaders = config.headers;
5624
5625 if (utils.isFormData(requestData)) {
5626 delete requestHeaders['Content-Type']; // Let the browser set it
5627 }
5628
5629 var request = new XMLHttpRequest();
5630 var loadEvent = 'onreadystatechange';
5631 var xDomain = false;
5632
5633 // For IE 8/9 CORS support
5634 // Only supports POST and GET calls and doesn't returns the response headers.
5635 // DON'T do this for testing b/c XMLHttpRequest is mocked, not XDomainRequest.
5636 if (process.env.NODE_ENV !== 'test' &&
5637 typeof window !== 'undefined' &&
5638 window.XDomainRequest && !('withCredentials' in request) &&
5639 !isURLSameOrigin(config.url)) {
5640 request = new window.XDomainRequest();
5641 loadEvent = 'onload';
5642 xDomain = true;
5643 request.onprogress = function handleProgress() {};
5644 request.ontimeout = function handleTimeout() {};
5645 }
5646
5647 // HTTP basic authentication
5648 if (config.auth) {
5649 var username = config.auth.username || '';
5650 var password = config.auth.password || '';
5651 requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password);
5652 }
5653
5654 request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true);
5655
5656 // Set the request timeout in MS
5657 request.timeout = config.timeout;
5658
5659 // Listen for ready state
5660 request[loadEvent] = function handleLoad() {
5661 if (!request || (request.readyState !== 4 && !xDomain)) {
5662 return;
5663 }
5664
5665 // The request errored out and we didn't get a response, this will be
5666 // handled by onerror instead
5667 // With one exception: request that using file: protocol, most browsers
5668 // will return status as 0 even though it's a successful request
5669 if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) {
5670 return;
5671 }
5672
5673 // Prepare the response
5674 var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null;
5675 var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response;
5676 var response = {
5677 data: responseData,
5678 // IE sends 1223 instead of 204 (https://github.com/axios/axios/issues/201)
5679 status: request.status === 1223 ? 204 : request.status,
5680 statusText: request.status === 1223 ? 'No Content' : request.statusText,
5681 headers: responseHeaders,
5682 config: config,
5683 request: request
5684 };
5685
5686 settle(resolve, reject, response);
5687
5688 // Clean up request
5689 request = null;
5690 };
5691
5692 // Handle low level network errors
5693 request.onerror = function handleError() {
5694 // Real errors are hidden from us by the browser
5695 // onerror should only fire if it's a network error
5696 reject(createError('Network Error', config, null, request));
5697
5698 // Clean up request
5699 request = null;
5700 };
5701
5702 // Handle timeout
5703 request.ontimeout = function handleTimeout() {
5704 reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED',
5705 request));
5706
5707 // Clean up request
5708 request = null;
5709 };
5710
5711 // Add xsrf header
5712 // This is only done if running in a standard browser environment.
5713 // Specifically not if we're in a web worker, or react-native.
5714 if (utils.isStandardBrowserEnv()) {
5715 var cookies = require('./../helpers/cookies');
5716
5717 // Add xsrf header
5718 var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ?
5719 cookies.read(config.xsrfCookieName) :
5720 undefined;
5721
5722 if (xsrfValue) {
5723 requestHeaders[config.xsrfHeaderName] = xsrfValue;
5724 }
5725 }
5726
5727 // Add headers to the request
5728 if ('setRequestHeader' in request) {
5729 utils.forEach(requestHeaders, function setRequestHeader(val, key) {
5730 if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') {
5731 // Remove Content-Type if data is undefined
5732 delete requestHeaders[key];
5733 } else {
5734 // Otherwise add header to the request
5735 request.setRequestHeader(key, val);
5736 }
5737 });
5738 }
5739
5740 // Add withCredentials to request if needed
5741 if (config.withCredentials) {
5742 request.withCredentials = true;
5743 }
5744
5745 // Add responseType to request if needed
5746 if (config.responseType) {
5747 try {
5748 request.responseType = config.responseType;
5749 } catch (e) {
5750 // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2.
5751 // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function.
5752 if (config.responseType !== 'json') {
5753 throw e;
5754 }
5755 }
5756 }
5757
5758 // Handle progress if needed
5759 if (typeof config.onDownloadProgress === 'function') {
5760 request.addEventListener('progress', config.onDownloadProgress);
5761 }
5762
5763 // Not all browsers support upload events
5764 if (typeof config.onUploadProgress === 'function' && request.upload) {
5765 request.upload.addEventListener('progress', config.onUploadProgress);
5766 }
5767
5768 if (config.cancelToken) {
5769 // Handle cancellation
5770 config.cancelToken.promise.then(function onCanceled(cancel) {
5771 if (!request) {
5772 return;
5773 }
5774
5775 request.abort();
5776 reject(cancel);
5777 // Clean up request
5778 request = null;
5779 });
5780 }
5781
5782 if (requestData === undefined) {
5783 requestData = null;
5784 }
5785
5786 // Send the request
5787 request.send(requestData);
5788 });
5789};
5790
5791}).call(this,require('_process'))
5792},{"../core/createError":54,"./../core/settle":57,"./../helpers/btoa":61,"./../helpers/buildURL":62,"./../helpers/cookies":64,"./../helpers/isURLSameOrigin":66,"./../helpers/parseHeaders":68,"./../utils":70,"_process":190}],48:[function(require,module,exports){
5793'use strict';
5794
5795var utils = require('./utils');
5796var bind = require('./helpers/bind');
5797var Axios = require('./core/Axios');
5798var defaults = require('./defaults');
5799
5800/**
5801 * Create an instance of Axios
5802 *
5803 * @param {Object} defaultConfig The default config for the instance
5804 * @return {Axios} A new instance of Axios
5805 */
5806function createInstance(defaultConfig) {
5807 var context = new Axios(defaultConfig);
5808 var instance = bind(Axios.prototype.request, context);
5809
5810 // Copy axios.prototype to instance
5811 utils.extend(instance, Axios.prototype, context);
5812
5813 // Copy context to instance
5814 utils.extend(instance, context);
5815
5816 return instance;
5817}
5818
5819// Create the default instance to be exported
5820var axios = createInstance(defaults);
5821
5822// Expose Axios class to allow class inheritance
5823axios.Axios = Axios;
5824
5825// Factory for creating new instances
5826axios.create = function create(instanceConfig) {
5827 return createInstance(utils.merge(defaults, instanceConfig));
5828};
5829
5830// Expose Cancel & CancelToken
5831axios.Cancel = require('./cancel/Cancel');
5832axios.CancelToken = require('./cancel/CancelToken');
5833axios.isCancel = require('./cancel/isCancel');
5834
5835// Expose all/spread
5836axios.all = function all(promises) {
5837 return Promise.all(promises);
5838};
5839axios.spread = require('./helpers/spread');
5840
5841module.exports = axios;
5842
5843// Allow use of default import syntax in TypeScript
5844module.exports.default = axios;
5845
5846},{"./cancel/Cancel":49,"./cancel/CancelToken":50,"./cancel/isCancel":51,"./core/Axios":52,"./defaults":59,"./helpers/bind":60,"./helpers/spread":69,"./utils":70}],49:[function(require,module,exports){
5847'use strict';
5848
5849/**
5850 * A `Cancel` is an object that is thrown when an operation is canceled.
5851 *
5852 * @class
5853 * @param {string=} message The message.
5854 */
5855function Cancel(message) {
5856 this.message = message;
5857}
5858
5859Cancel.prototype.toString = function toString() {
5860 return 'Cancel' + (this.message ? ': ' + this.message : '');
5861};
5862
5863Cancel.prototype.__CANCEL__ = true;
5864
5865module.exports = Cancel;
5866
5867},{}],50:[function(require,module,exports){
5868'use strict';
5869
5870var Cancel = require('./Cancel');
5871
5872/**
5873 * A `CancelToken` is an object that can be used to request cancellation of an operation.
5874 *
5875 * @class
5876 * @param {Function} executor The executor function.
5877 */
5878function CancelToken(executor) {
5879 if (typeof executor !== 'function') {
5880 throw new TypeError('executor must be a function.');
5881 }
5882
5883 var resolvePromise;
5884 this.promise = new Promise(function promiseExecutor(resolve) {
5885 resolvePromise = resolve;
5886 });
5887
5888 var token = this;
5889 executor(function cancel(message) {
5890 if (token.reason) {
5891 // Cancellation has already been requested
5892 return;
5893 }
5894
5895 token.reason = new Cancel(message);
5896 resolvePromise(token.reason);
5897 });
5898}
5899
5900/**
5901 * Throws a `Cancel` if cancellation has been requested.
5902 */
5903CancelToken.prototype.throwIfRequested = function throwIfRequested() {
5904 if (this.reason) {
5905 throw this.reason;
5906 }
5907};
5908
5909/**
5910 * Returns an object that contains a new `CancelToken` and a function that, when called,
5911 * cancels the `CancelToken`.
5912 */
5913CancelToken.source = function source() {
5914 var cancel;
5915 var token = new CancelToken(function executor(c) {
5916 cancel = c;
5917 });
5918 return {
5919 token: token,
5920 cancel: cancel
5921 };
5922};
5923
5924module.exports = CancelToken;
5925
5926},{"./Cancel":49}],51:[function(require,module,exports){
5927'use strict';
5928
5929module.exports = function isCancel(value) {
5930 return !!(value && value.__CANCEL__);
5931};
5932
5933},{}],52:[function(require,module,exports){
5934'use strict';
5935
5936var defaults = require('./../defaults');
5937var utils = require('./../utils');
5938var InterceptorManager = require('./InterceptorManager');
5939var dispatchRequest = require('./dispatchRequest');
5940
5941/**
5942 * Create a new instance of Axios
5943 *
5944 * @param {Object} instanceConfig The default config for the instance
5945 */
5946function Axios(instanceConfig) {
5947 this.defaults = instanceConfig;
5948 this.interceptors = {
5949 request: new InterceptorManager(),
5950 response: new InterceptorManager()
5951 };
5952}
5953
5954/**
5955 * Dispatch a request
5956 *
5957 * @param {Object} config The config specific for this request (merged with this.defaults)
5958 */
5959Axios.prototype.request = function request(config) {
5960 /*eslint no-param-reassign:0*/
5961 // Allow for axios('example/url'[, config]) a la fetch API
5962 if (typeof config === 'string') {
5963 config = utils.merge({
5964 url: arguments[0]
5965 }, arguments[1]);
5966 }
5967
5968 config = utils.merge(defaults, {method: 'get'}, this.defaults, config);
5969 config.method = config.method.toLowerCase();
5970
5971 // Hook up interceptors middleware
5972 var chain = [dispatchRequest, undefined];
5973 var promise = Promise.resolve(config);
5974
5975 this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) {
5976 chain.unshift(interceptor.fulfilled, interceptor.rejected);
5977 });
5978
5979 this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) {
5980 chain.push(interceptor.fulfilled, interceptor.rejected);
5981 });
5982
5983 while (chain.length) {
5984 promise = promise.then(chain.shift(), chain.shift());
5985 }
5986
5987 return promise;
5988};
5989
5990// Provide aliases for supported request methods
5991utils.forEach(['delete', 'get', 'head', 'options'], function forEachMethodNoData(method) {
5992 /*eslint func-names:0*/
5993 Axios.prototype[method] = function(url, config) {
5994 return this.request(utils.merge(config || {}, {
5995 method: method,
5996 url: url
5997 }));
5998 };
5999});
6000
6001utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
6002 /*eslint func-names:0*/
6003 Axios.prototype[method] = function(url, data, config) {
6004 return this.request(utils.merge(config || {}, {
6005 method: method,
6006 url: url,
6007 data: data
6008 }));
6009 };
6010});
6011
6012module.exports = Axios;
6013
6014},{"./../defaults":59,"./../utils":70,"./InterceptorManager":53,"./dispatchRequest":55}],53:[function(require,module,exports){
6015'use strict';
6016
6017var utils = require('./../utils');
6018
6019function InterceptorManager() {
6020 this.handlers = [];
6021}
6022
6023/**
6024 * Add a new interceptor to the stack
6025 *
6026 * @param {Function} fulfilled The function to handle `then` for a `Promise`
6027 * @param {Function} rejected The function to handle `reject` for a `Promise`
6028 *
6029 * @return {Number} An ID used to remove interceptor later
6030 */
6031InterceptorManager.prototype.use = function use(fulfilled, rejected) {
6032 this.handlers.push({
6033 fulfilled: fulfilled,
6034 rejected: rejected
6035 });
6036 return this.handlers.length - 1;
6037};
6038
6039/**
6040 * Remove an interceptor from the stack
6041 *
6042 * @param {Number} id The ID that was returned by `use`
6043 */
6044InterceptorManager.prototype.eject = function eject(id) {
6045 if (this.handlers[id]) {
6046 this.handlers[id] = null;
6047 }
6048};
6049
6050/**
6051 * Iterate over all the registered interceptors
6052 *
6053 * This method is particularly useful for skipping over any
6054 * interceptors that may have become `null` calling `eject`.
6055 *
6056 * @param {Function} fn The function to call for each interceptor
6057 */
6058InterceptorManager.prototype.forEach = function forEach(fn) {
6059 utils.forEach(this.handlers, function forEachHandler(h) {
6060 if (h !== null) {
6061 fn(h);
6062 }
6063 });
6064};
6065
6066module.exports = InterceptorManager;
6067
6068},{"./../utils":70}],54:[function(require,module,exports){
6069'use strict';
6070
6071var enhanceError = require('./enhanceError');
6072
6073/**
6074 * Create an Error with the specified message, config, error code, request and response.
6075 *
6076 * @param {string} message The error message.
6077 * @param {Object} config The config.
6078 * @param {string} [code] The error code (for example, 'ECONNABORTED').
6079 * @param {Object} [request] The request.
6080 * @param {Object} [response] The response.
6081 * @returns {Error} The created error.
6082 */
6083module.exports = function createError(message, config, code, request, response) {
6084 var error = new Error(message);
6085 return enhanceError(error, config, code, request, response);
6086};
6087
6088},{"./enhanceError":56}],55:[function(require,module,exports){
6089'use strict';
6090
6091var utils = require('./../utils');
6092var transformData = require('./transformData');
6093var isCancel = require('../cancel/isCancel');
6094var defaults = require('../defaults');
6095var isAbsoluteURL = require('./../helpers/isAbsoluteURL');
6096var combineURLs = require('./../helpers/combineURLs');
6097
6098/**
6099 * Throws a `Cancel` if cancellation has been requested.
6100 */
6101function throwIfCancellationRequested(config) {
6102 if (config.cancelToken) {
6103 config.cancelToken.throwIfRequested();
6104 }
6105}
6106
6107/**
6108 * Dispatch a request to the server using the configured adapter.
6109 *
6110 * @param {object} config The config that is to be used for the request
6111 * @returns {Promise} The Promise to be fulfilled
6112 */
6113module.exports = function dispatchRequest(config) {
6114 throwIfCancellationRequested(config);
6115
6116 // Support baseURL config
6117 if (config.baseURL && !isAbsoluteURL(config.url)) {
6118 config.url = combineURLs(config.baseURL, config.url);
6119 }
6120
6121 // Ensure headers exist
6122 config.headers = config.headers || {};
6123
6124 // Transform request data
6125 config.data = transformData(
6126 config.data,
6127 config.headers,
6128 config.transformRequest
6129 );
6130
6131 // Flatten headers
6132 config.headers = utils.merge(
6133 config.headers.common || {},
6134 config.headers[config.method] || {},
6135 config.headers || {}
6136 );
6137
6138 utils.forEach(
6139 ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
6140 function cleanHeaderConfig(method) {
6141 delete config.headers[method];
6142 }
6143 );
6144
6145 var adapter = config.adapter || defaults.adapter;
6146
6147 return adapter(config).then(function onAdapterResolution(response) {
6148 throwIfCancellationRequested(config);
6149
6150 // Transform response data
6151 response.data = transformData(
6152 response.data,
6153 response.headers,
6154 config.transformResponse
6155 );
6156
6157 return response;
6158 }, function onAdapterRejection(reason) {
6159 if (!isCancel(reason)) {
6160 throwIfCancellationRequested(config);
6161
6162 // Transform response data
6163 if (reason && reason.response) {
6164 reason.response.data = transformData(
6165 reason.response.data,
6166 reason.response.headers,
6167 config.transformResponse
6168 );
6169 }
6170 }
6171
6172 return Promise.reject(reason);
6173 });
6174};
6175
6176},{"../cancel/isCancel":51,"../defaults":59,"./../helpers/combineURLs":63,"./../helpers/isAbsoluteURL":65,"./../utils":70,"./transformData":58}],56:[function(require,module,exports){
6177'use strict';
6178
6179/**
6180 * Update an Error with the specified config, error code, and response.
6181 *
6182 * @param {Error} error The error to update.
6183 * @param {Object} config The config.
6184 * @param {string} [code] The error code (for example, 'ECONNABORTED').
6185 * @param {Object} [request] The request.
6186 * @param {Object} [response] The response.
6187 * @returns {Error} The error.
6188 */
6189module.exports = function enhanceError(error, config, code, request, response) {
6190 error.config = config;
6191 if (code) {
6192 error.code = code;
6193 }
6194 error.request = request;
6195 error.response = response;
6196 return error;
6197};
6198
6199},{}],57:[function(require,module,exports){
6200'use strict';
6201
6202var createError = require('./createError');
6203
6204/**
6205 * Resolve or reject a Promise based on response status.
6206 *
6207 * @param {Function} resolve A function that resolves the promise.
6208 * @param {Function} reject A function that rejects the promise.
6209 * @param {object} response The response.
6210 */
6211module.exports = function settle(resolve, reject, response) {
6212 var validateStatus = response.config.validateStatus;
6213 // Note: status is not exposed by XDomainRequest
6214 if (!response.status || !validateStatus || validateStatus(response.status)) {
6215 resolve(response);
6216 } else {
6217 reject(createError(
6218 'Request failed with status code ' + response.status,
6219 response.config,
6220 null,
6221 response.request,
6222 response
6223 ));
6224 }
6225};
6226
6227},{"./createError":54}],58:[function(require,module,exports){
6228'use strict';
6229
6230var utils = require('./../utils');
6231
6232/**
6233 * Transform the data for a request or a response
6234 *
6235 * @param {Object|String} data The data to be transformed
6236 * @param {Array} headers The headers for the request or response
6237 * @param {Array|Function} fns A single function or Array of functions
6238 * @returns {*} The resulting transformed data
6239 */
6240module.exports = function transformData(data, headers, fns) {
6241 /*eslint no-param-reassign:0*/
6242 utils.forEach(fns, function transform(fn) {
6243 data = fn(data, headers);
6244 });
6245
6246 return data;
6247};
6248
6249},{"./../utils":70}],59:[function(require,module,exports){
6250(function (process){
6251'use strict';
6252
6253var utils = require('./utils');
6254var normalizeHeaderName = require('./helpers/normalizeHeaderName');
6255
6256var DEFAULT_CONTENT_TYPE = {
6257 'Content-Type': 'application/x-www-form-urlencoded'
6258};
6259
6260function setContentTypeIfUnset(headers, value) {
6261 if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) {
6262 headers['Content-Type'] = value;
6263 }
6264}
6265
6266function getDefaultAdapter() {
6267 var adapter;
6268 if (typeof XMLHttpRequest !== 'undefined') {
6269 // For browsers use XHR adapter
6270 adapter = require('./adapters/xhr');
6271 } else if (typeof process !== 'undefined') {
6272 // For node use HTTP adapter
6273 adapter = require('./adapters/http');
6274 }
6275 return adapter;
6276}
6277
6278var defaults = {
6279 adapter: getDefaultAdapter(),
6280
6281 transformRequest: [function transformRequest(data, headers) {
6282 normalizeHeaderName(headers, 'Content-Type');
6283 if (utils.isFormData(data) ||
6284 utils.isArrayBuffer(data) ||
6285 utils.isBuffer(data) ||
6286 utils.isStream(data) ||
6287 utils.isFile(data) ||
6288 utils.isBlob(data)
6289 ) {
6290 return data;
6291 }
6292 if (utils.isArrayBufferView(data)) {
6293 return data.buffer;
6294 }
6295 if (utils.isURLSearchParams(data)) {
6296 setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8');
6297 return data.toString();
6298 }
6299 if (utils.isObject(data)) {
6300 setContentTypeIfUnset(headers, 'application/json;charset=utf-8');
6301 return JSON.stringify(data);
6302 }
6303 return data;
6304 }],
6305
6306 transformResponse: [function transformResponse(data) {
6307 /*eslint no-param-reassign:0*/
6308 if (typeof data === 'string') {
6309 try {
6310 data = JSON.parse(data);
6311 } catch (e) { /* Ignore */ }
6312 }
6313 return data;
6314 }],
6315
6316 /**
6317 * A timeout in milliseconds to abort a request. If set to 0 (default) a
6318 * timeout is not created.
6319 */
6320 timeout: 0,
6321
6322 xsrfCookieName: 'XSRF-TOKEN',
6323 xsrfHeaderName: 'X-XSRF-TOKEN',
6324
6325 maxContentLength: -1,
6326
6327 validateStatus: function validateStatus(status) {
6328 return status >= 200 && status < 300;
6329 }
6330};
6331
6332defaults.headers = {
6333 common: {
6334 'Accept': 'application/json, text/plain, */*'
6335 }
6336};
6337
6338utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) {
6339 defaults.headers[method] = {};
6340});
6341
6342utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) {
6343 defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE);
6344});
6345
6346module.exports = defaults;
6347
6348}).call(this,require('_process'))
6349},{"./adapters/http":47,"./adapters/xhr":47,"./helpers/normalizeHeaderName":67,"./utils":70,"_process":190}],60:[function(require,module,exports){
6350'use strict';
6351
6352module.exports = function bind(fn, thisArg) {
6353 return function wrap() {
6354 var args = new Array(arguments.length);
6355 for (var i = 0; i < args.length; i++) {
6356 args[i] = arguments[i];
6357 }
6358 return fn.apply(thisArg, args);
6359 };
6360};
6361
6362},{}],61:[function(require,module,exports){
6363'use strict';
6364
6365// btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js
6366
6367var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
6368
6369function E() {
6370 this.message = 'String contains an invalid character';
6371}
6372E.prototype = new Error;
6373E.prototype.code = 5;
6374E.prototype.name = 'InvalidCharacterError';
6375
6376function btoa(input) {
6377 var str = String(input);
6378 var output = '';
6379 for (
6380 // initialize result and counter
6381 var block, charCode, idx = 0, map = chars;
6382 // if the next str index does not exist:
6383 // change the mapping table to "="
6384 // check if d has no fractional digits
6385 str.charAt(idx | 0) || (map = '=', idx % 1);
6386 // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8
6387 output += map.charAt(63 & block >> 8 - idx % 1 * 8)
6388 ) {
6389 charCode = str.charCodeAt(idx += 3 / 4);
6390 if (charCode > 0xFF) {
6391 throw new E();
6392 }
6393 block = block << 8 | charCode;
6394 }
6395 return output;
6396}
6397
6398module.exports = btoa;
6399
6400},{}],62:[function(require,module,exports){
6401'use strict';
6402
6403var utils = require('./../utils');
6404
6405function encode(val) {
6406 return encodeURIComponent(val).
6407 replace(/%40/gi, '@').
6408 replace(/%3A/gi, ':').
6409 replace(/%24/g, '$').
6410 replace(/%2C/gi, ',').
6411 replace(/%20/g, '+').
6412 replace(/%5B/gi, '[').
6413 replace(/%5D/gi, ']');
6414}
6415
6416/**
6417 * Build a URL by appending params to the end
6418 *
6419 * @param {string} url The base of the url (e.g., http://www.google.com)
6420 * @param {object} [params] The params to be appended
6421 * @returns {string} The formatted url
6422 */
6423module.exports = function buildURL(url, params, paramsSerializer) {
6424 /*eslint no-param-reassign:0*/
6425 if (!params) {
6426 return url;
6427 }
6428
6429 var serializedParams;
6430 if (paramsSerializer) {
6431 serializedParams = paramsSerializer(params);
6432 } else if (utils.isURLSearchParams(params)) {
6433 serializedParams = params.toString();
6434 } else {
6435 var parts = [];
6436
6437 utils.forEach(params, function serialize(val, key) {
6438 if (val === null || typeof val === 'undefined') {
6439 return;
6440 }
6441
6442 if (utils.isArray(val)) {
6443 key = key + '[]';
6444 } else {
6445 val = [val];
6446 }
6447
6448 utils.forEach(val, function parseValue(v) {
6449 if (utils.isDate(v)) {
6450 v = v.toISOString();
6451 } else if (utils.isObject(v)) {
6452 v = JSON.stringify(v);
6453 }
6454 parts.push(encode(key) + '=' + encode(v));
6455 });
6456 });
6457
6458 serializedParams = parts.join('&');
6459 }
6460
6461 if (serializedParams) {
6462 url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams;
6463 }
6464
6465 return url;
6466};
6467
6468},{"./../utils":70}],63:[function(require,module,exports){
6469'use strict';
6470
6471/**
6472 * Creates a new URL by combining the specified URLs
6473 *
6474 * @param {string} baseURL The base URL
6475 * @param {string} relativeURL The relative URL
6476 * @returns {string} The combined URL
6477 */
6478module.exports = function combineURLs(baseURL, relativeURL) {
6479 return relativeURL
6480 ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '')
6481 : baseURL;
6482};
6483
6484},{}],64:[function(require,module,exports){
6485'use strict';
6486
6487var utils = require('./../utils');
6488
6489module.exports = (
6490 utils.isStandardBrowserEnv() ?
6491
6492 // Standard browser envs support document.cookie
6493 (function standardBrowserEnv() {
6494 return {
6495 write: function write(name, value, expires, path, domain, secure) {
6496 var cookie = [];
6497 cookie.push(name + '=' + encodeURIComponent(value));
6498
6499 if (utils.isNumber(expires)) {
6500 cookie.push('expires=' + new Date(expires).toGMTString());
6501 }
6502
6503 if (utils.isString(path)) {
6504 cookie.push('path=' + path);
6505 }
6506
6507 if (utils.isString(domain)) {
6508 cookie.push('domain=' + domain);
6509 }
6510
6511 if (secure === true) {
6512 cookie.push('secure');
6513 }
6514
6515 document.cookie = cookie.join('; ');
6516 },
6517
6518 read: function read(name) {
6519 var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)'));
6520 return (match ? decodeURIComponent(match[3]) : null);
6521 },
6522
6523 remove: function remove(name) {
6524 this.write(name, '', Date.now() - 86400000);
6525 }
6526 };
6527 })() :
6528
6529 // Non standard browser env (web workers, react-native) lack needed support.
6530 (function nonStandardBrowserEnv() {
6531 return {
6532 write: function write() {},
6533 read: function read() { return null; },
6534 remove: function remove() {}
6535 };
6536 })()
6537);
6538
6539},{"./../utils":70}],65:[function(require,module,exports){
6540'use strict';
6541
6542/**
6543 * Determines whether the specified URL is absolute
6544 *
6545 * @param {string} url The URL to test
6546 * @returns {boolean} True if the specified URL is absolute, otherwise false
6547 */
6548module.exports = function isAbsoluteURL(url) {
6549 // A URL is considered absolute if it begins with "<scheme>://" or "//" (protocol-relative URL).
6550 // RFC 3986 defines scheme name as a sequence of characters beginning with a letter and followed
6551 // by any combination of letters, digits, plus, period, or hyphen.
6552 return /^([a-z][a-z\d\+\-\.]*:)?\/\//i.test(url);
6553};
6554
6555},{}],66:[function(require,module,exports){
6556'use strict';
6557
6558var utils = require('./../utils');
6559
6560module.exports = (
6561 utils.isStandardBrowserEnv() ?
6562
6563 // Standard browser envs have full support of the APIs needed to test
6564 // whether the request URL is of the same origin as current location.
6565 (function standardBrowserEnv() {
6566 var msie = /(msie|trident)/i.test(navigator.userAgent);
6567 var urlParsingNode = document.createElement('a');
6568 var originURL;
6569
6570 /**
6571 * Parse a URL to discover it's components
6572 *
6573 * @param {String} url The URL to be parsed
6574 * @returns {Object}
6575 */
6576 function resolveURL(url) {
6577 var href = url;
6578
6579 if (msie) {
6580 // IE needs attribute set twice to normalize properties
6581 urlParsingNode.setAttribute('href', href);
6582 href = urlParsingNode.href;
6583 }
6584
6585 urlParsingNode.setAttribute('href', href);
6586
6587 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
6588 return {
6589 href: urlParsingNode.href,
6590 protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
6591 host: urlParsingNode.host,
6592 search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
6593 hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
6594 hostname: urlParsingNode.hostname,
6595 port: urlParsingNode.port,
6596 pathname: (urlParsingNode.pathname.charAt(0) === '/') ?
6597 urlParsingNode.pathname :
6598 '/' + urlParsingNode.pathname
6599 };
6600 }
6601
6602 originURL = resolveURL(window.location.href);
6603
6604 /**
6605 * Determine if a URL shares the same origin as the current location
6606 *
6607 * @param {String} requestURL The URL to test
6608 * @returns {boolean} True if URL shares the same origin, otherwise false
6609 */
6610 return function isURLSameOrigin(requestURL) {
6611 var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL;
6612 return (parsed.protocol === originURL.protocol &&
6613 parsed.host === originURL.host);
6614 };
6615 })() :
6616
6617 // Non standard browser envs (web workers, react-native) lack needed support.
6618 (function nonStandardBrowserEnv() {
6619 return function isURLSameOrigin() {
6620 return true;
6621 };
6622 })()
6623);
6624
6625},{"./../utils":70}],67:[function(require,module,exports){
6626'use strict';
6627
6628var utils = require('../utils');
6629
6630module.exports = function normalizeHeaderName(headers, normalizedName) {
6631 utils.forEach(headers, function processHeader(value, name) {
6632 if (name !== normalizedName && name.toUpperCase() === normalizedName.toUpperCase()) {
6633 headers[normalizedName] = value;
6634 delete headers[name];
6635 }
6636 });
6637};
6638
6639},{"../utils":70}],68:[function(require,module,exports){
6640'use strict';
6641
6642var utils = require('./../utils');
6643
6644// Headers whose duplicates are ignored by node
6645// c.f. https://nodejs.org/api/http.html#http_message_headers
6646var ignoreDuplicateOf = [
6647 'age', 'authorization', 'content-length', 'content-type', 'etag',
6648 'expires', 'from', 'host', 'if-modified-since', 'if-unmodified-since',
6649 'last-modified', 'location', 'max-forwards', 'proxy-authorization',
6650 'referer', 'retry-after', 'user-agent'
6651];
6652
6653/**
6654 * Parse headers into an object
6655 *
6656 * ```
6657 * Date: Wed, 27 Aug 2014 08:58:49 GMT
6658 * Content-Type: application/json
6659 * Connection: keep-alive
6660 * Transfer-Encoding: chunked
6661 * ```
6662 *
6663 * @param {String} headers Headers needing to be parsed
6664 * @returns {Object} Headers parsed into an object
6665 */
6666module.exports = function parseHeaders(headers) {
6667 var parsed = {};
6668 var key;
6669 var val;
6670 var i;
6671
6672 if (!headers) { return parsed; }
6673
6674 utils.forEach(headers.split('\n'), function parser(line) {
6675 i = line.indexOf(':');
6676 key = utils.trim(line.substr(0, i)).toLowerCase();
6677 val = utils.trim(line.substr(i + 1));
6678
6679 if (key) {
6680 if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) {
6681 return;
6682 }
6683 if (key === 'set-cookie') {
6684 parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]);
6685 } else {
6686 parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val;
6687 }
6688 }
6689 });
6690
6691 return parsed;
6692};
6693
6694},{"./../utils":70}],69:[function(require,module,exports){
6695'use strict';
6696
6697/**
6698 * Syntactic sugar for invoking a function and expanding an array for arguments.
6699 *
6700 * Common use case would be to use `Function.prototype.apply`.
6701 *
6702 * ```js
6703 * function f(x, y, z) {}
6704 * var args = [1, 2, 3];
6705 * f.apply(null, args);
6706 * ```
6707 *
6708 * With `spread` this example can be re-written.
6709 *
6710 * ```js
6711 * spread(function(x, y, z) {})([1, 2, 3]);
6712 * ```
6713 *
6714 * @param {Function} callback
6715 * @returns {Function}
6716 */
6717module.exports = function spread(callback) {
6718 return function wrap(arr) {
6719 return callback.apply(null, arr);
6720 };
6721};
6722
6723},{}],70:[function(require,module,exports){
6724'use strict';
6725
6726var bind = require('./helpers/bind');
6727var isBuffer = require('is-buffer');
6728
6729/*global toString:true*/
6730
6731// utils is a library of generic helper functions non-specific to axios
6732
6733var toString = Object.prototype.toString;
6734
6735/**
6736 * Determine if a value is an Array
6737 *
6738 * @param {Object} val The value to test
6739 * @returns {boolean} True if value is an Array, otherwise false
6740 */
6741function isArray(val) {
6742 return toString.call(val) === '[object Array]';
6743}
6744
6745/**
6746 * Determine if a value is an ArrayBuffer
6747 *
6748 * @param {Object} val The value to test
6749 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
6750 */
6751function isArrayBuffer(val) {
6752 return toString.call(val) === '[object ArrayBuffer]';
6753}
6754
6755/**
6756 * Determine if a value is a FormData
6757 *
6758 * @param {Object} val The value to test
6759 * @returns {boolean} True if value is an FormData, otherwise false
6760 */
6761function isFormData(val) {
6762 return (typeof FormData !== 'undefined') && (val instanceof FormData);
6763}
6764
6765/**
6766 * Determine if a value is a view on an ArrayBuffer
6767 *
6768 * @param {Object} val The value to test
6769 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
6770 */
6771function isArrayBufferView(val) {
6772 var result;
6773 if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) {
6774 result = ArrayBuffer.isView(val);
6775 } else {
6776 result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer);
6777 }
6778 return result;
6779}
6780
6781/**
6782 * Determine if a value is a String
6783 *
6784 * @param {Object} val The value to test
6785 * @returns {boolean} True if value is a String, otherwise false
6786 */
6787function isString(val) {
6788 return typeof val === 'string';
6789}
6790
6791/**
6792 * Determine if a value is a Number
6793 *
6794 * @param {Object} val The value to test
6795 * @returns {boolean} True if value is a Number, otherwise false
6796 */
6797function isNumber(val) {
6798 return typeof val === 'number';
6799}
6800
6801/**
6802 * Determine if a value is undefined
6803 *
6804 * @param {Object} val The value to test
6805 * @returns {boolean} True if the value is undefined, otherwise false
6806 */
6807function isUndefined(val) {
6808 return typeof val === 'undefined';
6809}
6810
6811/**
6812 * Determine if a value is an Object
6813 *
6814 * @param {Object} val The value to test
6815 * @returns {boolean} True if value is an Object, otherwise false
6816 */
6817function isObject(val) {
6818 return val !== null && typeof val === 'object';
6819}
6820
6821/**
6822 * Determine if a value is a Date
6823 *
6824 * @param {Object} val The value to test
6825 * @returns {boolean} True if value is a Date, otherwise false
6826 */
6827function isDate(val) {
6828 return toString.call(val) === '[object Date]';
6829}
6830
6831/**
6832 * Determine if a value is a File
6833 *
6834 * @param {Object} val The value to test
6835 * @returns {boolean} True if value is a File, otherwise false
6836 */
6837function isFile(val) {
6838 return toString.call(val) === '[object File]';
6839}
6840
6841/**
6842 * Determine if a value is a Blob
6843 *
6844 * @param {Object} val The value to test
6845 * @returns {boolean} True if value is a Blob, otherwise false
6846 */
6847function isBlob(val) {
6848 return toString.call(val) === '[object Blob]';
6849}
6850
6851/**
6852 * Determine if a value is a Function
6853 *
6854 * @param {Object} val The value to test
6855 * @returns {boolean} True if value is a Function, otherwise false
6856 */
6857function isFunction(val) {
6858 return toString.call(val) === '[object Function]';
6859}
6860
6861/**
6862 * Determine if a value is a Stream
6863 *
6864 * @param {Object} val The value to test
6865 * @returns {boolean} True if value is a Stream, otherwise false
6866 */
6867function isStream(val) {
6868 return isObject(val) && isFunction(val.pipe);
6869}
6870
6871/**
6872 * Determine if a value is a URLSearchParams object
6873 *
6874 * @param {Object} val The value to test
6875 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
6876 */
6877function isURLSearchParams(val) {
6878 return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams;
6879}
6880
6881/**
6882 * Trim excess whitespace off the beginning and end of a string
6883 *
6884 * @param {String} str The String to trim
6885 * @returns {String} The String freed of excess whitespace
6886 */
6887function trim(str) {
6888 return str.replace(/^\s*/, '').replace(/\s*$/, '');
6889}
6890
6891/**
6892 * Determine if we're running in a standard browser environment
6893 *
6894 * This allows axios to run in a web worker, and react-native.
6895 * Both environments support XMLHttpRequest, but not fully standard globals.
6896 *
6897 * web workers:
6898 * typeof window -> undefined
6899 * typeof document -> undefined
6900 *
6901 * react-native:
6902 * navigator.product -> 'ReactNative'
6903 */
6904function isStandardBrowserEnv() {
6905 if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') {
6906 return false;
6907 }
6908 return (
6909 typeof window !== 'undefined' &&
6910 typeof document !== 'undefined'
6911 );
6912}
6913
6914/**
6915 * Iterate over an Array or an Object invoking a function for each item.
6916 *
6917 * If `obj` is an Array callback will be called passing
6918 * the value, index, and complete array for each item.
6919 *
6920 * If 'obj' is an Object callback will be called passing
6921 * the value, key, and complete object for each property.
6922 *
6923 * @param {Object|Array} obj The object to iterate
6924 * @param {Function} fn The callback to invoke for each item
6925 */
6926function forEach(obj, fn) {
6927 // Don't bother if no value provided
6928 if (obj === null || typeof obj === 'undefined') {
6929 return;
6930 }
6931
6932 // Force an array if not already something iterable
6933 if (typeof obj !== 'object') {
6934 /*eslint no-param-reassign:0*/
6935 obj = [obj];
6936 }
6937
6938 if (isArray(obj)) {
6939 // Iterate over array values
6940 for (var i = 0, l = obj.length; i < l; i++) {
6941 fn.call(null, obj[i], i, obj);
6942 }
6943 } else {
6944 // Iterate over object keys
6945 for (var key in obj) {
6946 if (Object.prototype.hasOwnProperty.call(obj, key)) {
6947 fn.call(null, obj[key], key, obj);
6948 }
6949 }
6950 }
6951}
6952
6953/**
6954 * Accepts varargs expecting each argument to be an object, then
6955 * immutably merges the properties of each object and returns result.
6956 *
6957 * When multiple objects contain the same key the later object in
6958 * the arguments list will take precedence.
6959 *
6960 * Example:
6961 *
6962 * ```js
6963 * var result = merge({foo: 123}, {foo: 456});
6964 * console.log(result.foo); // outputs 456
6965 * ```
6966 *
6967 * @param {Object} obj1 Object to merge
6968 * @returns {Object} Result of all merge properties
6969 */
6970function merge(/* obj1, obj2, obj3, ... */) {
6971 var result = {};
6972 function assignValue(val, key) {
6973 if (typeof result[key] === 'object' && typeof val === 'object') {
6974 result[key] = merge(result[key], val);
6975 } else {
6976 result[key] = val;
6977 }
6978 }
6979
6980 for (var i = 0, l = arguments.length; i < l; i++) {
6981 forEach(arguments[i], assignValue);
6982 }
6983 return result;
6984}
6985
6986/**
6987 * Extends object a by mutably adding to it the properties of object b.
6988 *
6989 * @param {Object} a The object to be extended
6990 * @param {Object} b The object to copy properties from
6991 * @param {Object} thisArg The object to bind function to
6992 * @return {Object} The resulting value of object a
6993 */
6994function extend(a, b, thisArg) {
6995 forEach(b, function assignValue(val, key) {
6996 if (thisArg && typeof val === 'function') {
6997 a[key] = bind(val, thisArg);
6998 } else {
6999 a[key] = val;
7000 }
7001 });
7002 return a;
7003}
7004
7005module.exports = {
7006 isArray: isArray,
7007 isArrayBuffer: isArrayBuffer,
7008 isBuffer: isBuffer,
7009 isFormData: isFormData,
7010 isArrayBufferView: isArrayBufferView,
7011 isString: isString,
7012 isNumber: isNumber,
7013 isObject: isObject,
7014 isUndefined: isUndefined,
7015 isDate: isDate,
7016 isFile: isFile,
7017 isBlob: isBlob,
7018 isFunction: isFunction,
7019 isStream: isStream,
7020 isURLSearchParams: isURLSearchParams,
7021 isStandardBrowserEnv: isStandardBrowserEnv,
7022 forEach: forEach,
7023 merge: merge,
7024 extend: extend,
7025 trim: trim
7026};
7027
7028},{"./helpers/bind":60,"is-buffer":164}],71:[function(require,module,exports){
7029// base-x encoding
7030// Forked from https://github.com/cryptocoinjs/bs58
7031// Originally written by Mike Hearn for BitcoinJ
7032// Copyright (c) 2011 Google Inc
7033// Ported to JavaScript by Stefan Thomas
7034// Merged Buffer refactorings from base58-native by Stephen Pair
7035// Copyright (c) 2013 BitPay Inc
7036
7037var Buffer = require('safe-buffer').Buffer
7038
7039module.exports = function base (ALPHABET) {
7040 var ALPHABET_MAP = {}
7041 var BASE = ALPHABET.length
7042 var LEADER = ALPHABET.charAt(0)
7043
7044 // pre-compute lookup table
7045 for (var z = 0; z < ALPHABET.length; z++) {
7046 var x = ALPHABET.charAt(z)
7047
7048 if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous')
7049 ALPHABET_MAP[x] = z
7050 }
7051
7052 function encode (source) {
7053 if (source.length === 0) return ''
7054
7055 var digits = [0]
7056 for (var i = 0; i < source.length; ++i) {
7057 for (var j = 0, carry = source[i]; j < digits.length; ++j) {
7058 carry += digits[j] << 8
7059 digits[j] = carry % BASE
7060 carry = (carry / BASE) | 0
7061 }
7062
7063 while (carry > 0) {
7064 digits.push(carry % BASE)
7065 carry = (carry / BASE) | 0
7066 }
7067 }
7068
7069 var string = ''
7070
7071 // deal with leading zeros
7072 for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER
7073 // convert digits to a string
7074 for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]]
7075
7076 return string
7077 }
7078
7079 function decodeUnsafe (string) {
7080 if (typeof string !== 'string') throw new TypeError('Expected String')
7081 if (string.length === 0) return Buffer.allocUnsafe(0)
7082
7083 var bytes = [0]
7084 for (var i = 0; i < string.length; i++) {
7085 var value = ALPHABET_MAP[string[i]]
7086 if (value === undefined) return
7087
7088 for (var j = 0, carry = value; j < bytes.length; ++j) {
7089 carry += bytes[j] * BASE
7090 bytes[j] = carry & 0xff
7091 carry >>= 8
7092 }
7093
7094 while (carry > 0) {
7095 bytes.push(carry & 0xff)
7096 carry >>= 8
7097 }
7098 }
7099
7100 // deal with leading zeros
7101 for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) {
7102 bytes.push(0)
7103 }
7104
7105 return Buffer.from(bytes.reverse())
7106 }
7107
7108 function decode (string) {
7109 var buffer = decodeUnsafe(string)
7110 if (buffer) return buffer
7111
7112 throw new Error('Non-base' + BASE + ' character')
7113 }
7114
7115 return {
7116 encode: encode,
7117 decodeUnsafe: decodeUnsafe,
7118 decode: decode
7119 }
7120}
7121
7122},{"safe-buffer":247}],72:[function(require,module,exports){
7123'use strict'
7124
7125exports.byteLength = byteLength
7126exports.toByteArray = toByteArray
7127exports.fromByteArray = fromByteArray
7128
7129var lookup = []
7130var revLookup = []
7131var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array
7132
7133var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
7134for (var i = 0, len = code.length; i < len; ++i) {
7135 lookup[i] = code[i]
7136 revLookup[code.charCodeAt(i)] = i
7137}
7138
7139revLookup['-'.charCodeAt(0)] = 62
7140revLookup['_'.charCodeAt(0)] = 63
7141
7142function placeHoldersCount (b64) {
7143 var len = b64.length
7144 if (len % 4 > 0) {
7145 throw new Error('Invalid string. Length must be a multiple of 4')
7146 }
7147
7148 // the number of equal signs (place holders)
7149 // if there are two placeholders, than the two characters before it
7150 // represent one byte
7151 // if there is only one, then the three characters before it represent 2 bytes
7152 // this is just a cheap hack to not do indexOf twice
7153 return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0
7154}
7155
7156function byteLength (b64) {
7157 // base64 is 4/3 + up to two characters of the original data
7158 return (b64.length * 3 / 4) - placeHoldersCount(b64)
7159}
7160
7161function toByteArray (b64) {
7162 var i, l, tmp, placeHolders, arr
7163 var len = b64.length
7164 placeHolders = placeHoldersCount(b64)
7165
7166 arr = new Arr((len * 3 / 4) - placeHolders)
7167
7168 // if there are placeholders, only get up to the last complete 4 chars
7169 l = placeHolders > 0 ? len - 4 : len
7170
7171 var L = 0
7172
7173 for (i = 0; i < l; i += 4) {
7174 tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)]
7175 arr[L++] = (tmp >> 16) & 0xFF
7176 arr[L++] = (tmp >> 8) & 0xFF
7177 arr[L++] = tmp & 0xFF
7178 }
7179
7180 if (placeHolders === 2) {
7181 tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4)
7182 arr[L++] = tmp & 0xFF
7183 } else if (placeHolders === 1) {
7184 tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2)
7185 arr[L++] = (tmp >> 8) & 0xFF
7186 arr[L++] = tmp & 0xFF
7187 }
7188
7189 return arr
7190}
7191
7192function tripletToBase64 (num) {
7193 return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F]
7194}
7195
7196function encodeChunk (uint8, start, end) {
7197 var tmp
7198 var output = []
7199 for (var i = start; i < end; i += 3) {
7200 tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2])
7201 output.push(tripletToBase64(tmp))
7202 }
7203 return output.join('')
7204}
7205
7206function fromByteArray (uint8) {
7207 var tmp
7208 var len = uint8.length
7209 var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes
7210 var output = ''
7211 var parts = []
7212 var maxChunkLength = 16383 // must be multiple of 3
7213
7214 // go through the array every three bytes, we'll deal with trailing stuff later
7215 for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) {
7216 parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength)))
7217 }
7218
7219 // pad the end with zeros, but make sure to not forget the extra bytes
7220 if (extraBytes === 1) {
7221 tmp = uint8[len - 1]
7222 output += lookup[tmp >> 2]
7223 output += lookup[(tmp << 4) & 0x3F]
7224 output += '=='
7225 } else if (extraBytes === 2) {
7226 tmp = (uint8[len - 2] << 8) + (uint8[len - 1])
7227 output += lookup[tmp >> 10]
7228 output += lookup[(tmp >> 4) & 0x3F]
7229 output += lookup[(tmp << 2) & 0x3F]
7230 output += '='
7231 }
7232
7233 parts.push(output)
7234
7235 return parts.join('')
7236}
7237
7238},{}],73:[function(require,module,exports){
7239/*! bignumber.js v5.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */\r
7240\r
7241;(function (globalObj) {\r
7242 'use strict';\r
7243\r
7244 /*\r
7245 bignumber.js v5.0.0\r
7246 A JavaScript library for arbitrary-precision arithmetic.\r
7247 https://github.com/MikeMcl/bignumber.js\r
7248 Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>\r
7249 MIT Expat Licence\r
7250 */\r
7251\r
7252\r
7253 var BigNumber,\r
7254 isNumeric = /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,\r
7255 mathceil = Math.ceil,\r
7256 mathfloor = Math.floor,\r
7257 notBool = ' not a boolean or binary digit',\r
7258 roundingMode = 'rounding mode',\r
7259 tooManyDigits = 'number type has more than 15 significant digits',\r
7260 ALPHABET = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',\r
7261 BASE = 1e14,\r
7262 LOG_BASE = 14,\r
7263 MAX_SAFE_INTEGER = 0x1fffffffffffff, // 2^53 - 1\r
7264 // MAX_INT32 = 0x7fffffff, // 2^31 - 1\r
7265 POWS_TEN = [1, 10, 100, 1e3, 1e4, 1e5, 1e6, 1e7, 1e8, 1e9, 1e10, 1e11, 1e12, 1e13],\r
7266 SQRT_BASE = 1e7,\r
7267\r
7268 /*\r
7269 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and\r
7270 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an\r
7271 * exception is thrown (if ERRORS is true).\r
7272 */\r
7273 MAX = 1E9; // 0 to MAX_INT32\r
7274\r
7275\r
7276 /*\r
7277 * Create and return a BigNumber constructor.\r
7278 */\r
7279 function constructorFactory(config) {\r
7280 var div, parseNumeric,\r
7281\r
7282 // id tracks the caller function, so its name can be included in error messages.\r
7283 id = 0,\r
7284 P = BigNumber.prototype,\r
7285 ONE = new BigNumber(1),\r
7286\r
7287\r
7288 /********************************* EDITABLE DEFAULTS **********************************/\r
7289\r
7290\r
7291 /*\r
7292 * The default values below must be integers within the inclusive ranges stated.\r
7293 * The values can also be changed at run-time using BigNumber.config.\r
7294 */\r
7295\r
7296 // The maximum number of decimal places for operations involving division.\r
7297 DECIMAL_PLACES = 20, // 0 to MAX\r
7298\r
7299 /*\r
7300 * The rounding mode used when rounding to the above decimal places, and when using\r
7301 * toExponential, toFixed, toFormat and toPrecision, and round (default value).\r
7302 * UP 0 Away from zero.\r
7303 * DOWN 1 Towards zero.\r
7304 * CEIL 2 Towards +Infinity.\r
7305 * FLOOR 3 Towards -Infinity.\r
7306 * HALF_UP 4 Towards nearest neighbour. If equidistant, up.\r
7307 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.\r
7308 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.\r
7309 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.\r
7310 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.\r
7311 */\r
7312 ROUNDING_MODE = 4, // 0 to 8\r
7313\r
7314 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]\r
7315\r
7316 // The exponent value at and beneath which toString returns exponential notation.\r
7317 // Number type: -7\r
7318 TO_EXP_NEG = -7, // 0 to -MAX\r
7319\r
7320 // The exponent value at and above which toString returns exponential notation.\r
7321 // Number type: 21\r
7322 TO_EXP_POS = 21, // 0 to MAX\r
7323\r
7324 // RANGE : [MIN_EXP, MAX_EXP]\r
7325\r
7326 // The minimum exponent value, beneath which underflow to zero occurs.\r
7327 // Number type: -324 (5e-324)\r
7328 MIN_EXP = -1e7, // -1 to -MAX\r
7329\r
7330 // The maximum exponent value, above which overflow to Infinity occurs.\r
7331 // Number type: 308 (1.7976931348623157e+308)\r
7332 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.\r
7333 MAX_EXP = 1e7, // 1 to MAX\r
7334\r
7335 // Whether BigNumber Errors are ever thrown.\r
7336 ERRORS = true, // true or false\r
7337\r
7338 // Change to intValidatorNoErrors if ERRORS is false.\r
7339 isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors\r
7340\r
7341 // Whether to use cryptographically-secure random number generation, if available.\r
7342 CRYPTO = false, // true or false\r
7343\r
7344 /*\r
7345 * The modulo mode used when calculating the modulus: a mod n.\r
7346 * The quotient (q = a / n) is calculated according to the corresponding rounding mode.\r
7347 * The remainder (r) is calculated as: r = a - n * q.\r
7348 *\r
7349 * UP 0 The remainder is positive if the dividend is negative, else is negative.\r
7350 * DOWN 1 The remainder has the same sign as the dividend.\r
7351 * This modulo mode is commonly known as 'truncated division' and is\r
7352 * equivalent to (a % n) in JavaScript.\r
7353 * FLOOR 3 The remainder has the same sign as the divisor (Python %).\r
7354 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.\r
7355 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).\r
7356 * The remainder is always positive.\r
7357 *\r
7358 * The truncated division, floored division, Euclidian division and IEEE 754 remainder\r
7359 * modes are commonly used for the modulus operation.\r
7360 * Although the other rounding modes can also be used, they may not give useful results.\r
7361 */\r
7362 MODULO_MODE = 1, // 0 to 9\r
7363\r
7364 // The maximum number of significant digits of the result of the toPower operation.\r
7365 // If POW_PRECISION is 0, there will be unlimited significant digits.\r
7366 POW_PRECISION = 0, // 0 to MAX\r
7367\r
7368 // The format specification used by the BigNumber.prototype.toFormat method.\r
7369 FORMAT = {\r
7370 decimalSeparator: '.',\r
7371 groupSeparator: ',',\r
7372 groupSize: 3,\r
7373 secondaryGroupSize: 0,\r
7374 fractionGroupSeparator: '\xA0', // non-breaking space\r
7375 fractionGroupSize: 0\r
7376 };\r
7377\r
7378\r
7379 /******************************************************************************************/\r
7380\r
7381\r
7382 // CONSTRUCTOR\r
7383\r
7384\r
7385 /*\r
7386 * The BigNumber constructor and exported function.\r
7387 * Create and return a new instance of a BigNumber object.\r
7388 *\r
7389 * n {number|string|BigNumber} A numeric value.\r
7390 * [b] {number} The base of n. Integer, 2 to 64 inclusive.\r
7391 */\r
7392 function BigNumber( n, b ) {\r
7393 var c, e, i, num, len, str,\r
7394 x = this;\r
7395\r
7396 // Enable constructor usage without new.\r
7397 if ( !( x instanceof BigNumber ) ) {\r
7398\r
7399 // 'BigNumber() constructor call without new: {n}'\r
7400 // See GitHub issue: #81.\r
7401 //if (ERRORS) raise( 26, 'constructor call without new', n );\r
7402 return new BigNumber( n, b );\r
7403 }\r
7404\r
7405 // 'new BigNumber() base not an integer: {b}'\r
7406 // 'new BigNumber() base out of range: {b}'\r
7407 if ( b == null || !isValidInt( b, 2, 64, id, 'base' ) ) {\r
7408\r
7409 // Duplicate.\r
7410 if ( n instanceof BigNumber ) {\r
7411 x.s = n.s;\r
7412 x.e = n.e;\r
7413 x.c = ( n = n.c ) ? n.slice() : n;\r
7414 id = 0;\r
7415 return;\r
7416 }\r
7417\r
7418 if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) {\r
7419 x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1;\r
7420\r
7421 // Fast path for integers.\r
7422 if ( n === ~~n ) {\r
7423 for ( e = 0, i = n; i >= 10; i /= 10, e++ );\r
7424 x.e = e;\r
7425 x.c = [n];\r
7426 id = 0;\r
7427 return;\r
7428 }\r
7429\r
7430 str = n + '';\r
7431 } else {\r
7432 if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num );\r
7433 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;\r
7434 }\r
7435 } else {\r
7436 b = b | 0;\r
7437 str = n + '';\r
7438\r
7439 // Ensure return value is rounded to DECIMAL_PLACES as with other bases.\r
7440 // Allow exponential notation to be used with base 10 argument.\r
7441 if ( b == 10 ) {\r
7442 x = new BigNumber( n instanceof BigNumber ? n : str );\r
7443 return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE );\r
7444 }\r
7445\r
7446 // Avoid potential interpretation of Infinity and NaN as base 44+ values.\r
7447 // Any number in exponential form will fail due to the [Ee][+-].\r
7448 if ( ( num = typeof n == 'number' ) && n * 0 != 0 ||\r
7449 !( new RegExp( '^-?' + ( c = '[' + ALPHABET.slice( 0, b ) + ']+' ) +\r
7450 '(?:\\.' + c + ')?$',b < 37 ? 'i' : '' ) ).test(str) ) {\r
7451 return parseNumeric( x, str, num, b );\r
7452 }\r
7453\r
7454 if (num) {\r
7455 x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1;\r
7456\r
7457 if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) {\r
7458\r
7459 // 'new BigNumber() number type has more than 15 significant digits: {n}'\r
7460 raise( id, tooManyDigits, n );\r
7461 }\r
7462\r
7463 // Prevent later check for length on converted number.\r
7464 num = false;\r
7465 } else {\r
7466 x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1;\r
7467 }\r
7468\r
7469 str = convertBase( str, 10, b, x.s );\r
7470 }\r
7471\r
7472 // Decimal point?\r
7473 if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' );\r
7474\r
7475 // Exponential form?\r
7476 if ( ( i = str.search( /e/i ) ) > 0 ) {\r
7477\r
7478 // Determine exponent.\r
7479 if ( e < 0 ) e = i;\r
7480 e += +str.slice( i + 1 );\r
7481 str = str.substring( 0, i );\r
7482 } else if ( e < 0 ) {\r
7483\r
7484 // Integer.\r
7485 e = str.length;\r
7486 }\r
7487\r
7488 // Determine leading zeros.\r
7489 for ( i = 0; str.charCodeAt(i) === 48; i++ );\r
7490\r
7491 // Determine trailing zeros.\r
7492 for ( len = str.length; str.charCodeAt(--len) === 48; );\r
7493 str = str.slice( i, len + 1 );\r
7494\r
7495 if (str) {\r
7496 len = str.length;\r
7497\r
7498 // Disallow numbers with over 15 significant digits if number type.\r
7499 // 'new BigNumber() number type has more than 15 significant digits: {n}'\r
7500 if ( num && ERRORS && len > 15 && ( n > MAX_SAFE_INTEGER || n !== mathfloor(n) ) ) {\r
7501 raise( id, tooManyDigits, x.s * n );\r
7502 }\r
7503\r
7504 e = e - i - 1;\r
7505\r
7506 // Overflow?\r
7507 if ( e > MAX_EXP ) {\r
7508\r
7509 // Infinity.\r
7510 x.c = x.e = null;\r
7511\r
7512 // Underflow?\r
7513 } else if ( e < MIN_EXP ) {\r
7514\r
7515 // Zero.\r
7516 x.c = [ x.e = 0 ];\r
7517 } else {\r
7518 x.e = e;\r
7519 x.c = [];\r
7520\r
7521 // Transform base\r
7522\r
7523 // e is the base 10 exponent.\r
7524 // i is where to slice str to get the first element of the coefficient array.\r
7525 i = ( e + 1 ) % LOG_BASE;\r
7526 if ( e < 0 ) i += LOG_BASE;\r
7527\r
7528 if ( i < len ) {\r
7529 if (i) x.c.push( +str.slice( 0, i ) );\r
7530\r
7531 for ( len -= LOG_BASE; i < len; ) {\r
7532 x.c.push( +str.slice( i, i += LOG_BASE ) );\r
7533 }\r
7534\r
7535 str = str.slice(i);\r
7536 i = LOG_BASE - str.length;\r
7537 } else {\r
7538 i -= len;\r
7539 }\r
7540\r
7541 for ( ; i--; str += '0' );\r
7542 x.c.push( +str );\r
7543 }\r
7544 } else {\r
7545\r
7546 // Zero.\r
7547 x.c = [ x.e = 0 ];\r
7548 }\r
7549\r
7550 id = 0;\r
7551 }\r
7552\r
7553\r
7554 // CONSTRUCTOR PROPERTIES\r
7555\r
7556\r
7557 BigNumber.another = constructorFactory;\r
7558\r
7559 BigNumber.ROUND_UP = 0;\r
7560 BigNumber.ROUND_DOWN = 1;\r
7561 BigNumber.ROUND_CEIL = 2;\r
7562 BigNumber.ROUND_FLOOR = 3;\r
7563 BigNumber.ROUND_HALF_UP = 4;\r
7564 BigNumber.ROUND_HALF_DOWN = 5;\r
7565 BigNumber.ROUND_HALF_EVEN = 6;\r
7566 BigNumber.ROUND_HALF_CEIL = 7;\r
7567 BigNumber.ROUND_HALF_FLOOR = 8;\r
7568 BigNumber.EUCLID = 9;\r
7569\r
7570\r
7571 /*\r
7572 * Configure infrequently-changing library-wide settings.\r
7573 *\r
7574 * Accept an object or an argument list, with one or many of the following properties or\r
7575 * parameters respectively:\r
7576 *\r
7577 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive\r
7578 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive\r
7579 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or\r
7580 * [integer -MAX to 0 incl., 0 to MAX incl.]\r
7581 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r
7582 * [integer -MAX to -1 incl., integer 1 to MAX incl.]\r
7583 * ERRORS {boolean|number} true, false, 1 or 0\r
7584 * CRYPTO {boolean|number} true, false, 1 or 0\r
7585 * MODULO_MODE {number} 0 to 9 inclusive\r
7586 * POW_PRECISION {number} 0 to MAX inclusive\r
7587 * FORMAT {object} See BigNumber.prototype.toFormat\r
7588 * decimalSeparator {string}\r
7589 * groupSeparator {string}\r
7590 * groupSize {number}\r
7591 * secondaryGroupSize {number}\r
7592 * fractionGroupSeparator {string}\r
7593 * fractionGroupSize {number}\r
7594 *\r
7595 * (The values assigned to the above FORMAT object properties are not checked for validity.)\r
7596 *\r
7597 * E.g.\r
7598 * BigNumber.config(20, 4) is equivalent to\r
7599 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })\r
7600 *\r
7601 * Ignore properties/parameters set to null or undefined.\r
7602 * Return an object with the properties current values.\r
7603 */\r
7604 BigNumber.config = BigNumber.set = function () {\r
7605 var v, p,\r
7606 i = 0,\r
7607 r = {},\r
7608 a = arguments,\r
7609 o = a[0],\r
7610 has = o && typeof o == 'object'\r
7611 ? function () { if ( o.hasOwnProperty(p) ) return ( v = o[p] ) != null; }\r
7612 : function () { if ( a.length > i ) return ( v = a[i++] ) != null; };\r
7613\r
7614 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.\r
7615 // 'config() DECIMAL_PLACES not an integer: {v}'\r
7616 // 'config() DECIMAL_PLACES out of range: {v}'\r
7617 if ( has( p = 'DECIMAL_PLACES' ) && isValidInt( v, 0, MAX, 2, p ) ) {\r
7618 DECIMAL_PLACES = v | 0;\r
7619 }\r
7620 r[p] = DECIMAL_PLACES;\r
7621\r
7622 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.\r
7623 // 'config() ROUNDING_MODE not an integer: {v}'\r
7624 // 'config() ROUNDING_MODE out of range: {v}'\r
7625 if ( has( p = 'ROUNDING_MODE' ) && isValidInt( v, 0, 8, 2, p ) ) {\r
7626 ROUNDING_MODE = v | 0;\r
7627 }\r
7628 r[p] = ROUNDING_MODE;\r
7629\r
7630 // EXPONENTIAL_AT {number|number[]}\r
7631 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].\r
7632 // 'config() EXPONENTIAL_AT not an integer: {v}'\r
7633 // 'config() EXPONENTIAL_AT out of range: {v}'\r
7634 if ( has( p = 'EXPONENTIAL_AT' ) ) {\r
7635\r
7636 if ( isArray(v) ) {\r
7637 if ( isValidInt( v[0], -MAX, 0, 2, p ) && isValidInt( v[1], 0, MAX, 2, p ) ) {\r
7638 TO_EXP_NEG = v[0] | 0;\r
7639 TO_EXP_POS = v[1] | 0;\r
7640 }\r
7641 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {\r
7642 TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 );\r
7643 }\r
7644 }\r
7645 r[p] = [ TO_EXP_NEG, TO_EXP_POS ];\r
7646\r
7647 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or\r
7648 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].\r
7649 // 'config() RANGE not an integer: {v}'\r
7650 // 'config() RANGE cannot be zero: {v}'\r
7651 // 'config() RANGE out of range: {v}'\r
7652 if ( has( p = 'RANGE' ) ) {\r
7653\r
7654 if ( isArray(v) ) {\r
7655 if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) {\r
7656 MIN_EXP = v[0] | 0;\r
7657 MAX_EXP = v[1] | 0;\r
7658 }\r
7659 } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) {\r
7660 if ( v | 0 ) MIN_EXP = -( MAX_EXP = ( v < 0 ? -v : v ) | 0 );\r
7661 else if (ERRORS) raise( 2, p + ' cannot be zero', v );\r
7662 }\r
7663 }\r
7664 r[p] = [ MIN_EXP, MAX_EXP ];\r
7665\r
7666 // ERRORS {boolean|number} true, false, 1 or 0.\r
7667 // 'config() ERRORS not a boolean or binary digit: {v}'\r
7668 if ( has( p = 'ERRORS' ) ) {\r
7669\r
7670 if ( v === !!v || v === 1 || v === 0 ) {\r
7671 id = 0;\r
7672 isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors;\r
7673 } else if (ERRORS) {\r
7674 raise( 2, p + notBool, v );\r
7675 }\r
7676 }\r
7677 r[p] = ERRORS;\r
7678\r
7679 // CRYPTO {boolean|number} true, false, 1 or 0.\r
7680 // 'config() CRYPTO not a boolean or binary digit: {v}'\r
7681 // 'config() crypto unavailable: {crypto}'\r
7682 if ( has( p = 'CRYPTO' ) ) {\r
7683\r
7684 if ( v === true || v === false || v === 1 || v === 0 ) {\r
7685 if (v) {\r
7686 v = typeof crypto == 'undefined';\r
7687 if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) {\r
7688 CRYPTO = true;\r
7689 } else if (ERRORS) {\r
7690 raise( 2, 'crypto unavailable', v ? void 0 : crypto );\r
7691 } else {\r
7692 CRYPTO = false;\r
7693 }\r
7694 } else {\r
7695 CRYPTO = false;\r
7696 }\r
7697 } else if (ERRORS) {\r
7698 raise( 2, p + notBool, v );\r
7699 }\r
7700 }\r
7701 r[p] = CRYPTO;\r
7702\r
7703 // MODULO_MODE {number} Integer, 0 to 9 inclusive.\r
7704 // 'config() MODULO_MODE not an integer: {v}'\r
7705 // 'config() MODULO_MODE out of range: {v}'\r
7706 if ( has( p = 'MODULO_MODE' ) && isValidInt( v, 0, 9, 2, p ) ) {\r
7707 MODULO_MODE = v | 0;\r
7708 }\r
7709 r[p] = MODULO_MODE;\r
7710\r
7711 // POW_PRECISION {number} Integer, 0 to MAX inclusive.\r
7712 // 'config() POW_PRECISION not an integer: {v}'\r
7713 // 'config() POW_PRECISION out of range: {v}'\r
7714 if ( has( p = 'POW_PRECISION' ) && isValidInt( v, 0, MAX, 2, p ) ) {\r
7715 POW_PRECISION = v | 0;\r
7716 }\r
7717 r[p] = POW_PRECISION;\r
7718\r
7719 // FORMAT {object}\r
7720 // 'config() FORMAT not an object: {v}'\r
7721 if ( has( p = 'FORMAT' ) ) {\r
7722\r
7723 if ( typeof v == 'object' ) {\r
7724 FORMAT = v;\r
7725 } else if (ERRORS) {\r
7726 raise( 2, p + ' not an object', v );\r
7727 }\r
7728 }\r
7729 r[p] = FORMAT;\r
7730\r
7731 return r;\r
7732 };\r
7733\r
7734\r
7735 /*\r
7736 * Return a new BigNumber whose value is the maximum of the arguments.\r
7737 *\r
7738 * arguments {number|string|BigNumber}\r
7739 */\r
7740 BigNumber.max = function () { return maxOrMin( arguments, P.lt ); };\r
7741\r
7742\r
7743 /*\r
7744 * Return a new BigNumber whose value is the minimum of the arguments.\r
7745 *\r
7746 * arguments {number|string|BigNumber}\r
7747 */\r
7748 BigNumber.min = function () { return maxOrMin( arguments, P.gt ); };\r
7749\r
7750\r
7751 /*\r
7752 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,\r
7753 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing\r
7754 * zeros are produced).\r
7755 *\r
7756 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r
7757 *\r
7758 * 'random() decimal places not an integer: {dp}'\r
7759 * 'random() decimal places out of range: {dp}'\r
7760 * 'random() crypto unavailable: {crypto}'\r
7761 */\r
7762 BigNumber.random = (function () {\r
7763 var pow2_53 = 0x20000000000000;\r
7764\r
7765 // Return a 53 bit integer n, where 0 <= n < 9007199254740992.\r
7766 // Check if Math.random() produces more than 32 bits of randomness.\r
7767 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.\r
7768 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.\r
7769 var random53bitInt = (Math.random() * pow2_53) & 0x1fffff\r
7770 ? function () { return mathfloor( Math.random() * pow2_53 ); }\r
7771 : function () { return ((Math.random() * 0x40000000 | 0) * 0x800000) +\r
7772 (Math.random() * 0x800000 | 0); };\r
7773\r
7774 return function (dp) {\r
7775 var a, b, e, k, v,\r
7776 i = 0,\r
7777 c = [],\r
7778 rand = new BigNumber(ONE);\r
7779\r
7780 dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0;\r
7781 k = mathceil( dp / LOG_BASE );\r
7782\r
7783 if (CRYPTO) {\r
7784\r
7785 // Browsers supporting crypto.getRandomValues.\r
7786 if (crypto.getRandomValues) {\r
7787\r
7788 a = crypto.getRandomValues( new Uint32Array( k *= 2 ) );\r
7789\r
7790 for ( ; i < k; ) {\r
7791\r
7792 // 53 bits:\r
7793 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)\r
7794 // 11111 11111111 11111111 11111111 11100000 00000000 00000000\r
7795 // ((Math.pow(2, 32) - 1) >>> 11).toString(2)\r
7796 // 11111 11111111 11111111\r
7797 // 0x20000 is 2^21.\r
7798 v = a[i] * 0x20000 + (a[i + 1] >>> 11);\r
7799\r
7800 // Rejection sampling:\r
7801 // 0 <= v < 9007199254740992\r
7802 // Probability that v >= 9e15, is\r
7803 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251\r
7804 if ( v >= 9e15 ) {\r
7805 b = crypto.getRandomValues( new Uint32Array(2) );\r
7806 a[i] = b[0];\r
7807 a[i + 1] = b[1];\r
7808 } else {\r
7809\r
7810 // 0 <= v <= 8999999999999999\r
7811 // 0 <= (v % 1e14) <= 99999999999999\r
7812 c.push( v % 1e14 );\r
7813 i += 2;\r
7814 }\r
7815 }\r
7816 i = k / 2;\r
7817\r
7818 // Node.js supporting crypto.randomBytes.\r
7819 } else if (crypto.randomBytes) {\r
7820\r
7821 // buffer\r
7822 a = crypto.randomBytes( k *= 7 );\r
7823\r
7824 for ( ; i < k; ) {\r
7825\r
7826 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40\r
7827 // 0x100000000 is 2^32, 0x1000000 is 2^24\r
7828 // 11111 11111111 11111111 11111111 11111111 11111111 11111111\r
7829 // 0 <= v < 9007199254740992\r
7830 v = ( ( a[i] & 31 ) * 0x1000000000000 ) + ( a[i + 1] * 0x10000000000 ) +\r
7831 ( a[i + 2] * 0x100000000 ) + ( a[i + 3] * 0x1000000 ) +\r
7832 ( a[i + 4] << 16 ) + ( a[i + 5] << 8 ) + a[i + 6];\r
7833\r
7834 if ( v >= 9e15 ) {\r
7835 crypto.randomBytes(7).copy( a, i );\r
7836 } else {\r
7837\r
7838 // 0 <= (v % 1e14) <= 99999999999999\r
7839 c.push( v % 1e14 );\r
7840 i += 7;\r
7841 }\r
7842 }\r
7843 i = k / 7;\r
7844 } else {\r
7845 CRYPTO = false;\r
7846 if (ERRORS) raise( 14, 'crypto unavailable', crypto );\r
7847 }\r
7848 }\r
7849\r
7850 // Use Math.random.\r
7851 if (!CRYPTO) {\r
7852\r
7853 for ( ; i < k; ) {\r
7854 v = random53bitInt();\r
7855 if ( v < 9e15 ) c[i++] = v % 1e14;\r
7856 }\r
7857 }\r
7858\r
7859 k = c[--i];\r
7860 dp %= LOG_BASE;\r
7861\r
7862 // Convert trailing digits to zeros according to dp.\r
7863 if ( k && dp ) {\r
7864 v = POWS_TEN[LOG_BASE - dp];\r
7865 c[i] = mathfloor( k / v ) * v;\r
7866 }\r
7867\r
7868 // Remove trailing elements which are zero.\r
7869 for ( ; c[i] === 0; c.pop(), i-- );\r
7870\r
7871 // Zero?\r
7872 if ( i < 0 ) {\r
7873 c = [ e = 0 ];\r
7874 } else {\r
7875\r
7876 // Remove leading elements which are zero and adjust exponent accordingly.\r
7877 for ( e = -1 ; c[0] === 0; c.splice(0, 1), e -= LOG_BASE);\r
7878\r
7879 // Count the digits of the first element of c to determine leading zeros, and...\r
7880 for ( i = 1, v = c[0]; v >= 10; v /= 10, i++);\r
7881\r
7882 // adjust the exponent accordingly.\r
7883 if ( i < LOG_BASE ) e -= LOG_BASE - i;\r
7884 }\r
7885\r
7886 rand.e = e;\r
7887 rand.c = c;\r
7888 return rand;\r
7889 };\r
7890 })();\r
7891\r
7892\r
7893 // PRIVATE FUNCTIONS\r
7894\r
7895\r
7896 // Convert a numeric string of baseIn to a numeric string of baseOut.\r
7897 function convertBase( str, baseOut, baseIn, sign ) {\r
7898 var d, e, k, r, x, xc, y,\r
7899 i = str.indexOf( '.' ),\r
7900 dp = DECIMAL_PLACES,\r
7901 rm = ROUNDING_MODE;\r
7902\r
7903 if ( baseIn < 37 ) str = str.toLowerCase();\r
7904\r
7905 // Non-integer.\r
7906 if ( i >= 0 ) {\r
7907 k = POW_PRECISION;\r
7908\r
7909 // Unlimited precision.\r
7910 POW_PRECISION = 0;\r
7911 str = str.replace( '.', '' );\r
7912 y = new BigNumber(baseIn);\r
7913 x = y.pow( str.length - i );\r
7914 POW_PRECISION = k;\r
7915\r
7916 // Convert str as if an integer, then restore the fraction part by dividing the\r
7917 // result by its base raised to a power.\r
7918 y.c = toBaseOut( toFixedPoint( coeffToString( x.c ), x.e ), 10, baseOut );\r
7919 y.e = y.c.length;\r
7920 }\r
7921\r
7922 // Convert the number as integer.\r
7923 xc = toBaseOut( str, baseIn, baseOut );\r
7924 e = k = xc.length;\r
7925\r
7926 // Remove trailing zeros.\r
7927 for ( ; xc[--k] == 0; xc.pop() );\r
7928 if ( !xc[0] ) return '0';\r
7929\r
7930 if ( i < 0 ) {\r
7931 --e;\r
7932 } else {\r
7933 x.c = xc;\r
7934 x.e = e;\r
7935\r
7936 // sign is needed for correct rounding.\r
7937 x.s = sign;\r
7938 x = div( x, y, dp, rm, baseOut );\r
7939 xc = x.c;\r
7940 r = x.r;\r
7941 e = x.e;\r
7942 }\r
7943\r
7944 d = e + dp + 1;\r
7945\r
7946 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.\r
7947 i = xc[d];\r
7948 k = baseOut / 2;\r
7949 r = r || d < 0 || xc[d + 1] != null;\r
7950\r
7951 r = rm < 4 ? ( i != null || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\r
7952 : i > k || i == k &&( rm == 4 || r || rm == 6 && xc[d - 1] & 1 ||\r
7953 rm == ( x.s < 0 ? 8 : 7 ) );\r
7954\r
7955 if ( d < 1 || !xc[0] ) {\r
7956\r
7957 // 1^-dp or 0.\r
7958 str = r ? toFixedPoint( '1', -dp ) : '0';\r
7959 } else {\r
7960 xc.length = d;\r
7961\r
7962 if (r) {\r
7963\r
7964 // Rounding up may mean the previous digit has to be rounded up and so on.\r
7965 for ( --baseOut; ++xc[--d] > baseOut; ) {\r
7966 xc[d] = 0;\r
7967\r
7968 if ( !d ) {\r
7969 ++e;\r
7970 xc = [1].concat(xc);\r
7971 }\r
7972 }\r
7973 }\r
7974\r
7975 // Determine trailing zeros.\r
7976 for ( k = xc.length; !xc[--k]; );\r
7977\r
7978 // E.g. [4, 11, 15] becomes 4bf.\r
7979 for ( i = 0, str = ''; i <= k; str += ALPHABET.charAt( xc[i++] ) );\r
7980 str = toFixedPoint( str, e );\r
7981 }\r
7982\r
7983 // The caller will add the sign.\r
7984 return str;\r
7985 }\r
7986\r
7987\r
7988 // Perform division in the specified base. Called by div and convertBase.\r
7989 div = (function () {\r
7990\r
7991 // Assume non-zero x and k.\r
7992 function multiply( x, k, base ) {\r
7993 var m, temp, xlo, xhi,\r
7994 carry = 0,\r
7995 i = x.length,\r
7996 klo = k % SQRT_BASE,\r
7997 khi = k / SQRT_BASE | 0;\r
7998\r
7999 for ( x = x.slice(); i--; ) {\r
8000 xlo = x[i] % SQRT_BASE;\r
8001 xhi = x[i] / SQRT_BASE | 0;\r
8002 m = khi * xlo + xhi * klo;\r
8003 temp = klo * xlo + ( ( m % SQRT_BASE ) * SQRT_BASE ) + carry;\r
8004 carry = ( temp / base | 0 ) + ( m / SQRT_BASE | 0 ) + khi * xhi;\r
8005 x[i] = temp % base;\r
8006 }\r
8007\r
8008 if (carry) x = [carry].concat(x);\r
8009\r
8010 return x;\r
8011 }\r
8012\r
8013 function compare( a, b, aL, bL ) {\r
8014 var i, cmp;\r
8015\r
8016 if ( aL != bL ) {\r
8017 cmp = aL > bL ? 1 : -1;\r
8018 } else {\r
8019\r
8020 for ( i = cmp = 0; i < aL; i++ ) {\r
8021\r
8022 if ( a[i] != b[i] ) {\r
8023 cmp = a[i] > b[i] ? 1 : -1;\r
8024 break;\r
8025 }\r
8026 }\r
8027 }\r
8028 return cmp;\r
8029 }\r
8030\r
8031 function subtract( a, b, aL, base ) {\r
8032 var i = 0;\r
8033\r
8034 // Subtract b from a.\r
8035 for ( ; aL--; ) {\r
8036 a[aL] -= i;\r
8037 i = a[aL] < b[aL] ? 1 : 0;\r
8038 a[aL] = i * base + a[aL] - b[aL];\r
8039 }\r
8040\r
8041 // Remove leading zeros.\r
8042 for ( ; !a[0] && a.length > 1; a.splice(0, 1) );\r
8043 }\r
8044\r
8045 // x: dividend, y: divisor.\r
8046 return function ( x, y, dp, rm, base ) {\r
8047 var cmp, e, i, more, n, prod, prodL, q, qc, rem, remL, rem0, xi, xL, yc0,\r
8048 yL, yz,\r
8049 s = x.s == y.s ? 1 : -1,\r
8050 xc = x.c,\r
8051 yc = y.c;\r
8052\r
8053 // Either NaN, Infinity or 0?\r
8054 if ( !xc || !xc[0] || !yc || !yc[0] ) {\r
8055\r
8056 return new BigNumber(\r
8057\r
8058 // Return NaN if either NaN, or both Infinity or 0.\r
8059 !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN :\r
8060\r
8061 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.\r
8062 xc && xc[0] == 0 || !yc ? s * 0 : s / 0\r
8063 );\r
8064 }\r
8065\r
8066 q = new BigNumber(s);\r
8067 qc = q.c = [];\r
8068 e = x.e - y.e;\r
8069 s = dp + e + 1;\r
8070\r
8071 if ( !base ) {\r
8072 base = BASE;\r
8073 e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE );\r
8074 s = s / LOG_BASE | 0;\r
8075 }\r
8076\r
8077 // Result exponent may be one less then the current value of e.\r
8078 // The coefficients of the BigNumbers from convertBase may have trailing zeros.\r
8079 for ( i = 0; yc[i] == ( xc[i] || 0 ); i++ );\r
8080 if ( yc[i] > ( xc[i] || 0 ) ) e--;\r
8081\r
8082 if ( s < 0 ) {\r
8083 qc.push(1);\r
8084 more = true;\r
8085 } else {\r
8086 xL = xc.length;\r
8087 yL = yc.length;\r
8088 i = 0;\r
8089 s += 2;\r
8090\r
8091 // Normalise xc and yc so highest order digit of yc is >= base / 2.\r
8092\r
8093 n = mathfloor( base / ( yc[0] + 1 ) );\r
8094\r
8095 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.\r
8096 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {\r
8097 if ( n > 1 ) {\r
8098 yc = multiply( yc, n, base );\r
8099 xc = multiply( xc, n, base );\r
8100 yL = yc.length;\r
8101 xL = xc.length;\r
8102 }\r
8103\r
8104 xi = yL;\r
8105 rem = xc.slice( 0, yL );\r
8106 remL = rem.length;\r
8107\r
8108 // Add zeros to make remainder as long as divisor.\r
8109 for ( ; remL < yL; rem[remL++] = 0 );\r
8110 yz = yc.slice();\r
8111 yz = [0].concat(yz);\r
8112 yc0 = yc[0];\r
8113 if ( yc[1] >= base / 2 ) yc0++;\r
8114 // Not necessary, but to prevent trial digit n > base, when using base 3.\r
8115 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;\r
8116\r
8117 do {\r
8118 n = 0;\r
8119\r
8120 // Compare divisor and remainder.\r
8121 cmp = compare( yc, rem, yL, remL );\r
8122\r
8123 // If divisor < remainder.\r
8124 if ( cmp < 0 ) {\r
8125\r
8126 // Calculate trial digit, n.\r
8127\r
8128 rem0 = rem[0];\r
8129 if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 );\r
8130\r
8131 // n is how many times the divisor goes into the current remainder.\r
8132 n = mathfloor( rem0 / yc0 );\r
8133\r
8134 // Algorithm:\r
8135 // 1. product = divisor * trial digit (n)\r
8136 // 2. if product > remainder: product -= divisor, n--\r
8137 // 3. remainder -= product\r
8138 // 4. if product was < remainder at 2:\r
8139 // 5. compare new remainder and divisor\r
8140 // 6. If remainder > divisor: remainder -= divisor, n++\r
8141\r
8142 if ( n > 1 ) {\r
8143\r
8144 // n may be > base only when base is 3.\r
8145 if (n >= base) n = base - 1;\r
8146\r
8147 // product = divisor * trial digit.\r
8148 prod = multiply( yc, n, base );\r
8149 prodL = prod.length;\r
8150 remL = rem.length;\r
8151\r
8152 // Compare product and remainder.\r
8153 // If product > remainder.\r
8154 // Trial digit n too high.\r
8155 // n is 1 too high about 5% of the time, and is not known to have\r
8156 // ever been more than 1 too high.\r
8157 while ( compare( prod, rem, prodL, remL ) == 1 ) {\r
8158 n--;\r
8159\r
8160 // Subtract divisor from product.\r
8161 subtract( prod, yL < prodL ? yz : yc, prodL, base );\r
8162 prodL = prod.length;\r
8163 cmp = 1;\r
8164 }\r
8165 } else {\r
8166\r
8167 // n is 0 or 1, cmp is -1.\r
8168 // If n is 0, there is no need to compare yc and rem again below,\r
8169 // so change cmp to 1 to avoid it.\r
8170 // If n is 1, leave cmp as -1, so yc and rem are compared again.\r
8171 if ( n == 0 ) {\r
8172\r
8173 // divisor < remainder, so n must be at least 1.\r
8174 cmp = n = 1;\r
8175 }\r
8176\r
8177 // product = divisor\r
8178 prod = yc.slice();\r
8179 prodL = prod.length;\r
8180 }\r
8181\r
8182 if ( prodL < remL ) prod = [0].concat(prod);\r
8183\r
8184 // Subtract product from remainder.\r
8185 subtract( rem, prod, remL, base );\r
8186 remL = rem.length;\r
8187\r
8188 // If product was < remainder.\r
8189 if ( cmp == -1 ) {\r
8190\r
8191 // Compare divisor and new remainder.\r
8192 // If divisor < new remainder, subtract divisor from remainder.\r
8193 // Trial digit n too low.\r
8194 // n is 1 too low about 5% of the time, and very rarely 2 too low.\r
8195 while ( compare( yc, rem, yL, remL ) < 1 ) {\r
8196 n++;\r
8197\r
8198 // Subtract divisor from remainder.\r
8199 subtract( rem, yL < remL ? yz : yc, remL, base );\r
8200 remL = rem.length;\r
8201 }\r
8202 }\r
8203 } else if ( cmp === 0 ) {\r
8204 n++;\r
8205 rem = [0];\r
8206 } // else cmp === 1 and n will be 0\r
8207\r
8208 // Add the next digit, n, to the result array.\r
8209 qc[i++] = n;\r
8210\r
8211 // Update the remainder.\r
8212 if ( rem[0] ) {\r
8213 rem[remL++] = xc[xi] || 0;\r
8214 } else {\r
8215 rem = [ xc[xi] ];\r
8216 remL = 1;\r
8217 }\r
8218 } while ( ( xi++ < xL || rem[0] != null ) && s-- );\r
8219\r
8220 more = rem[0] != null;\r
8221\r
8222 // Leading zero?\r
8223 if ( !qc[0] ) qc.splice(0, 1);\r
8224 }\r
8225\r
8226 if ( base == BASE ) {\r
8227\r
8228 // To calculate q.e, first get the number of digits of qc[0].\r
8229 for ( i = 1, s = qc[0]; s >= 10; s /= 10, i++ );\r
8230 round( q, dp + ( q.e = i + e * LOG_BASE - 1 ) + 1, rm, more );\r
8231\r
8232 // Caller is convertBase.\r
8233 } else {\r
8234 q.e = e;\r
8235 q.r = +more;\r
8236 }\r
8237\r
8238 return q;\r
8239 };\r
8240 })();\r
8241\r
8242\r
8243 /*\r
8244 * Return a string representing the value of BigNumber n in fixed-point or exponential\r
8245 * notation rounded to the specified decimal places or significant digits.\r
8246 *\r
8247 * n is a BigNumber.\r
8248 * i is the index of the last digit required (i.e. the digit that may be rounded up).\r
8249 * rm is the rounding mode.\r
8250 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.\r
8251 */\r
8252 function format( n, i, rm, caller ) {\r
8253 var c0, e, ne, len, str;\r
8254\r
8255 rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode )\r
8256 ? rm | 0 : ROUNDING_MODE;\r
8257\r
8258 if ( !n.c ) return n.toString();\r
8259 c0 = n.c[0];\r
8260 ne = n.e;\r
8261\r
8262 if ( i == null ) {\r
8263 str = coeffToString( n.c );\r
8264 str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG\r
8265 ? toExponential( str, ne )\r
8266 : toFixedPoint( str, ne );\r
8267 } else {\r
8268 n = round( new BigNumber(n), i, rm );\r
8269\r
8270 // n.e may have changed if the value was rounded up.\r
8271 e = n.e;\r
8272\r
8273 str = coeffToString( n.c );\r
8274 len = str.length;\r
8275\r
8276 // toPrecision returns exponential notation if the number of significant digits\r
8277 // specified is less than the number of digits necessary to represent the integer\r
8278 // part of the value in fixed-point notation.\r
8279\r
8280 // Exponential notation.\r
8281 if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) {\r
8282\r
8283 // Append zeros?\r
8284 for ( ; len < i; str += '0', len++ );\r
8285 str = toExponential( str, e );\r
8286\r
8287 // Fixed-point notation.\r
8288 } else {\r
8289 i -= ne;\r
8290 str = toFixedPoint( str, e );\r
8291\r
8292 // Append zeros?\r
8293 if ( e + 1 > len ) {\r
8294 if ( --i > 0 ) for ( str += '.'; i--; str += '0' );\r
8295 } else {\r
8296 i += e - len;\r
8297 if ( i > 0 ) {\r
8298 if ( e + 1 == len ) str += '.';\r
8299 for ( ; i--; str += '0' );\r
8300 }\r
8301 }\r
8302 }\r
8303 }\r
8304\r
8305 return n.s < 0 && c0 ? '-' + str : str;\r
8306 }\r
8307\r
8308\r
8309 // Handle BigNumber.max and BigNumber.min.\r
8310 function maxOrMin( args, method ) {\r
8311 var m, n,\r
8312 i = 0;\r
8313\r
8314 if ( isArray( args[0] ) ) args = args[0];\r
8315 m = new BigNumber( args[0] );\r
8316\r
8317 for ( ; ++i < args.length; ) {\r
8318 n = new BigNumber( args[i] );\r
8319\r
8320 // If any number is NaN, return NaN.\r
8321 if ( !n.s ) {\r
8322 m = n;\r
8323 break;\r
8324 } else if ( method.call( m, n ) ) {\r
8325 m = n;\r
8326 }\r
8327 }\r
8328\r
8329 return m;\r
8330 }\r
8331\r
8332\r
8333 /*\r
8334 * Return true if n is an integer in range, otherwise throw.\r
8335 * Use for argument validation when ERRORS is true.\r
8336 */\r
8337 function intValidatorWithErrors( n, min, max, caller, name ) {\r
8338 if ( n < min || n > max || n != truncate(n) ) {\r
8339 raise( caller, ( name || 'decimal places' ) +\r
8340 ( n < min || n > max ? ' out of range' : ' not an integer' ), n );\r
8341 }\r
8342\r
8343 return true;\r
8344 }\r
8345\r
8346\r
8347 /*\r
8348 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.\r
8349 * Called by minus, plus and times.\r
8350 */\r
8351 function normalise( n, c, e ) {\r
8352 var i = 1,\r
8353 j = c.length;\r
8354\r
8355 // Remove trailing zeros.\r
8356 for ( ; !c[--j]; c.pop() );\r
8357\r
8358 // Calculate the base 10 exponent. First get the number of digits of c[0].\r
8359 for ( j = c[0]; j >= 10; j /= 10, i++ );\r
8360\r
8361 // Overflow?\r
8362 if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) {\r
8363\r
8364 // Infinity.\r
8365 n.c = n.e = null;\r
8366\r
8367 // Underflow?\r
8368 } else if ( e < MIN_EXP ) {\r
8369\r
8370 // Zero.\r
8371 n.c = [ n.e = 0 ];\r
8372 } else {\r
8373 n.e = e;\r
8374 n.c = c;\r
8375 }\r
8376\r
8377 return n;\r
8378 }\r
8379\r
8380\r
8381 // Handle values that fail the validity test in BigNumber.\r
8382 parseNumeric = (function () {\r
8383 var basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i,\r
8384 dotAfter = /^([^.]+)\.$/,\r
8385 dotBefore = /^\.([^.]+)$/,\r
8386 isInfinityOrNaN = /^-?(Infinity|NaN)$/,\r
8387 whitespaceOrPlus = /^\s*\+(?=[\w.])|^\s+|\s+$/g;\r
8388\r
8389 return function ( x, str, num, b ) {\r
8390 var base,\r
8391 s = num ? str : str.replace( whitespaceOrPlus, '' );\r
8392\r
8393 // No exception on ±Infinity or NaN.\r
8394 if ( isInfinityOrNaN.test(s) ) {\r
8395 x.s = isNaN(s) ? null : s < 0 ? -1 : 1;\r
8396 } else {\r
8397 if ( !num ) {\r
8398\r
8399 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i\r
8400 s = s.replace( basePrefix, function ( m, p1, p2 ) {\r
8401 base = ( p2 = p2.toLowerCase() ) == 'x' ? 16 : p2 == 'b' ? 2 : 8;\r
8402 return !b || b == base ? p1 : m;\r
8403 });\r
8404\r
8405 if (b) {\r
8406 base = b;\r
8407\r
8408 // E.g. '1.' to '1', '.1' to '0.1'\r
8409 s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' );\r
8410 }\r
8411\r
8412 if ( str != s ) return new BigNumber( s, base );\r
8413 }\r
8414\r
8415 // 'new BigNumber() not a number: {n}'\r
8416 // 'new BigNumber() not a base {b} number: {n}'\r
8417 if (ERRORS) raise( id, 'not a' + ( b ? ' base ' + b : '' ) + ' number', str );\r
8418 x.s = null;\r
8419 }\r
8420\r
8421 x.c = x.e = null;\r
8422 id = 0;\r
8423 }\r
8424 })();\r
8425\r
8426\r
8427 // Throw a BigNumber Error.\r
8428 function raise( caller, msg, val ) {\r
8429 var error = new Error( [\r
8430 'new BigNumber', // 0\r
8431 'cmp', // 1\r
8432 'config', // 2\r
8433 'div', // 3\r
8434 'divToInt', // 4\r
8435 'eq', // 5\r
8436 'gt', // 6\r
8437 'gte', // 7\r
8438 'lt', // 8\r
8439 'lte', // 9\r
8440 'minus', // 10\r
8441 'mod', // 11\r
8442 'plus', // 12\r
8443 'precision', // 13\r
8444 'random', // 14\r
8445 'round', // 15\r
8446 'shift', // 16\r
8447 'times', // 17\r
8448 'toDigits', // 18\r
8449 'toExponential', // 19\r
8450 'toFixed', // 20\r
8451 'toFormat', // 21\r
8452 'toFraction', // 22\r
8453 'pow', // 23\r
8454 'toPrecision', // 24\r
8455 'toString', // 25\r
8456 'BigNumber' // 26\r
8457 ][caller] + '() ' + msg + ': ' + val );\r
8458\r
8459 error.name = 'BigNumber Error';\r
8460 id = 0;\r
8461 throw error;\r
8462 }\r
8463\r
8464\r
8465 /*\r
8466 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.\r
8467 * If r is truthy, it is known that there are more digits after the rounding digit.\r
8468 */\r
8469 function round( x, sd, rm, r ) {\r
8470 var d, i, j, k, n, ni, rd,\r
8471 xc = x.c,\r
8472 pows10 = POWS_TEN;\r
8473\r
8474 // if x is not Infinity or NaN...\r
8475 if (xc) {\r
8476\r
8477 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.\r
8478 // n is a base 1e14 number, the value of the element of array x.c containing rd.\r
8479 // ni is the index of n within x.c.\r
8480 // d is the number of digits of n.\r
8481 // i is the index of rd within n including leading zeros.\r
8482 // j is the actual index of rd within n (if < 0, rd is a leading zero).\r
8483 out: {\r
8484\r
8485 // Get the number of digits of the first element of xc.\r
8486 for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ );\r
8487 i = sd - d;\r
8488\r
8489 // If the rounding digit is in the first element of xc...\r
8490 if ( i < 0 ) {\r
8491 i += LOG_BASE;\r
8492 j = sd;\r
8493 n = xc[ ni = 0 ];\r
8494\r
8495 // Get the rounding digit at index j of n.\r
8496 rd = n / pows10[ d - j - 1 ] % 10 | 0;\r
8497 } else {\r
8498 ni = mathceil( ( i + 1 ) / LOG_BASE );\r
8499\r
8500 if ( ni >= xc.length ) {\r
8501\r
8502 if (r) {\r
8503\r
8504 // Needed by sqrt.\r
8505 for ( ; xc.length <= ni; xc.push(0) );\r
8506 n = rd = 0;\r
8507 d = 1;\r
8508 i %= LOG_BASE;\r
8509 j = i - LOG_BASE + 1;\r
8510 } else {\r
8511 break out;\r
8512 }\r
8513 } else {\r
8514 n = k = xc[ni];\r
8515\r
8516 // Get the number of digits of n.\r
8517 for ( d = 1; k >= 10; k /= 10, d++ );\r
8518\r
8519 // Get the index of rd within n.\r
8520 i %= LOG_BASE;\r
8521\r
8522 // Get the index of rd within n, adjusted for leading zeros.\r
8523 // The number of leading zeros of n is given by LOG_BASE - d.\r
8524 j = i - LOG_BASE + d;\r
8525\r
8526 // Get the rounding digit at index j of n.\r
8527 rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0;\r
8528 }\r
8529 }\r
8530\r
8531 r = r || sd < 0 ||\r
8532\r
8533 // Are there any non-zero digits after the rounding digit?\r
8534 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right\r
8535 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.\r
8536 xc[ni + 1] != null || ( j < 0 ? n : n % pows10[ d - j - 1 ] );\r
8537\r
8538 r = rm < 4\r
8539 ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) )\r
8540 : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 &&\r
8541\r
8542 // Check whether the digit to the left of the rounding digit is odd.\r
8543 ( ( i > 0 ? j > 0 ? n / pows10[ d - j ] : 0 : xc[ni - 1] ) % 10 ) & 1 ||\r
8544 rm == ( x.s < 0 ? 8 : 7 ) );\r
8545\r
8546 if ( sd < 1 || !xc[0] ) {\r
8547 xc.length = 0;\r
8548\r
8549 if (r) {\r
8550\r
8551 // Convert sd to decimal places.\r
8552 sd -= x.e + 1;\r
8553\r
8554 // 1, 0.1, 0.01, 0.001, 0.0001 etc.\r
8555 xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ];\r
8556 x.e = -sd || 0;\r
8557 } else {\r
8558\r
8559 // Zero.\r
8560 xc[0] = x.e = 0;\r
8561 }\r
8562\r
8563 return x;\r
8564 }\r
8565\r
8566 // Remove excess digits.\r
8567 if ( i == 0 ) {\r
8568 xc.length = ni;\r
8569 k = 1;\r
8570 ni--;\r
8571 } else {\r
8572 xc.length = ni + 1;\r
8573 k = pows10[ LOG_BASE - i ];\r
8574\r
8575 // E.g. 56700 becomes 56000 if 7 is the rounding digit.\r
8576 // j > 0 means i > number of leading zeros of n.\r
8577 xc[ni] = j > 0 ? mathfloor( n / pows10[ d - j ] % pows10[j] ) * k : 0;\r
8578 }\r
8579\r
8580 // Round up?\r
8581 if (r) {\r
8582\r
8583 for ( ; ; ) {\r
8584\r
8585 // If the digit to be rounded up is in the first element of xc...\r
8586 if ( ni == 0 ) {\r
8587\r
8588 // i will be the length of xc[0] before k is added.\r
8589 for ( i = 1, j = xc[0]; j >= 10; j /= 10, i++ );\r
8590 j = xc[0] += k;\r
8591 for ( k = 1; j >= 10; j /= 10, k++ );\r
8592\r
8593 // if i != k the length has increased.\r
8594 if ( i != k ) {\r
8595 x.e++;\r
8596 if ( xc[0] == BASE ) xc[0] = 1;\r
8597 }\r
8598\r
8599 break;\r
8600 } else {\r
8601 xc[ni] += k;\r
8602 if ( xc[ni] != BASE ) break;\r
8603 xc[ni--] = 0;\r
8604 k = 1;\r
8605 }\r
8606 }\r
8607 }\r
8608\r
8609 // Remove trailing zeros.\r
8610 for ( i = xc.length; xc[--i] === 0; xc.pop() );\r
8611 }\r
8612\r
8613 // Overflow? Infinity.\r
8614 if ( x.e > MAX_EXP ) {\r
8615 x.c = x.e = null;\r
8616\r
8617 // Underflow? Zero.\r
8618 } else if ( x.e < MIN_EXP ) {\r
8619 x.c = [ x.e = 0 ];\r
8620 }\r
8621 }\r
8622\r
8623 return x;\r
8624 }\r
8625\r
8626\r
8627 // PROTOTYPE/INSTANCE METHODS\r
8628\r
8629\r
8630 /*\r
8631 * Return a new BigNumber whose value is the absolute value of this BigNumber.\r
8632 */\r
8633 P.absoluteValue = P.abs = function () {\r
8634 var x = new BigNumber(this);\r
8635 if ( x.s < 0 ) x.s = 1;\r
8636 return x;\r
8637 };\r
8638\r
8639\r
8640 /*\r
8641 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole\r
8642 * number in the direction of Infinity.\r
8643 */\r
8644 P.ceil = function () {\r
8645 return round( new BigNumber(this), this.e + 1, 2 );\r
8646 };\r
8647\r
8648\r
8649 /*\r
8650 * Return\r
8651 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),\r
8652 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),\r
8653 * 0 if they have the same value,\r
8654 * or null if the value of either is NaN.\r
8655 */\r
8656 P.comparedTo = P.cmp = function ( y, b ) {\r
8657 id = 1;\r
8658 return compare( this, new BigNumber( y, b ) );\r
8659 };\r
8660\r
8661\r
8662 /*\r
8663 * Return the number of decimal places of the value of this BigNumber, or null if the value\r
8664 * of this BigNumber is ±Infinity or NaN.\r
8665 */\r
8666 P.decimalPlaces = P.dp = function () {\r
8667 var n, v,\r
8668 c = this.c;\r
8669\r
8670 if ( !c ) return null;\r
8671 n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE;\r
8672\r
8673 // Subtract the number of trailing zeros of the last number.\r
8674 if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- );\r
8675 if ( n < 0 ) n = 0;\r
8676\r
8677 return n;\r
8678 };\r
8679\r
8680\r
8681 /*\r
8682 * n / 0 = I\r
8683 * n / N = N\r
8684 * n / I = 0\r
8685 * 0 / n = 0\r
8686 * 0 / 0 = N\r
8687 * 0 / N = N\r
8688 * 0 / I = 0\r
8689 * N / n = N\r
8690 * N / 0 = N\r
8691 * N / N = N\r
8692 * N / I = N\r
8693 * I / n = I\r
8694 * I / 0 = I\r
8695 * I / N = N\r
8696 * I / I = N\r
8697 *\r
8698 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of\r
8699 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r
8700 */\r
8701 P.dividedBy = P.div = function ( y, b ) {\r
8702 id = 3;\r
8703 return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE );\r
8704 };\r
8705\r
8706\r
8707 /*\r
8708 * Return a new BigNumber whose value is the integer part of dividing the value of this\r
8709 * BigNumber by the value of BigNumber(y, b).\r
8710 */\r
8711 P.dividedToIntegerBy = P.divToInt = function ( y, b ) {\r
8712 id = 4;\r
8713 return div( this, new BigNumber( y, b ), 0, 1 );\r
8714 };\r
8715\r
8716\r
8717 /*\r
8718 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),\r
8719 * otherwise returns false.\r
8720 */\r
8721 P.equals = P.eq = function ( y, b ) {\r
8722 id = 5;\r
8723 return compare( this, new BigNumber( y, b ) ) === 0;\r
8724 };\r
8725\r
8726\r
8727 /*\r
8728 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole\r
8729 * number in the direction of -Infinity.\r
8730 */\r
8731 P.floor = function () {\r
8732 return round( new BigNumber(this), this.e + 1, 3 );\r
8733 };\r
8734\r
8735\r
8736 /*\r
8737 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),\r
8738 * otherwise returns false.\r
8739 */\r
8740 P.greaterThan = P.gt = function ( y, b ) {\r
8741 id = 6;\r
8742 return compare( this, new BigNumber( y, b ) ) > 0;\r
8743 };\r
8744\r
8745\r
8746 /*\r
8747 * Return true if the value of this BigNumber is greater than or equal to the value of\r
8748 * BigNumber(y, b), otherwise returns false.\r
8749 */\r
8750 P.greaterThanOrEqualTo = P.gte = function ( y, b ) {\r
8751 id = 7;\r
8752 return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0;\r
8753\r
8754 };\r
8755\r
8756\r
8757 /*\r
8758 * Return true if the value of this BigNumber is a finite number, otherwise returns false.\r
8759 */\r
8760 P.isFinite = function () {\r
8761 return !!this.c;\r
8762 };\r
8763\r
8764\r
8765 /*\r
8766 * Return true if the value of this BigNumber is an integer, otherwise return false.\r
8767 */\r
8768 P.isInteger = P.isInt = function () {\r
8769 return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2;\r
8770 };\r
8771\r
8772\r
8773 /*\r
8774 * Return true if the value of this BigNumber is NaN, otherwise returns false.\r
8775 */\r
8776 P.isNaN = function () {\r
8777 return !this.s;\r
8778 };\r
8779\r
8780\r
8781 /*\r
8782 * Return true if the value of this BigNumber is negative, otherwise returns false.\r
8783 */\r
8784 P.isNegative = P.isNeg = function () {\r
8785 return this.s < 0;\r
8786 };\r
8787\r
8788\r
8789 /*\r
8790 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.\r
8791 */\r
8792 P.isZero = function () {\r
8793 return !!this.c && this.c[0] == 0;\r
8794 };\r
8795\r
8796\r
8797 /*\r
8798 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),\r
8799 * otherwise returns false.\r
8800 */\r
8801 P.lessThan = P.lt = function ( y, b ) {\r
8802 id = 8;\r
8803 return compare( this, new BigNumber( y, b ) ) < 0;\r
8804 };\r
8805\r
8806\r
8807 /*\r
8808 * Return true if the value of this BigNumber is less than or equal to the value of\r
8809 * BigNumber(y, b), otherwise returns false.\r
8810 */\r
8811 P.lessThanOrEqualTo = P.lte = function ( y, b ) {\r
8812 id = 9;\r
8813 return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0;\r
8814 };\r
8815\r
8816\r
8817 /*\r
8818 * n - 0 = n\r
8819 * n - N = N\r
8820 * n - I = -I\r
8821 * 0 - n = -n\r
8822 * 0 - 0 = 0\r
8823 * 0 - N = N\r
8824 * 0 - I = -I\r
8825 * N - n = N\r
8826 * N - 0 = N\r
8827 * N - N = N\r
8828 * N - I = N\r
8829 * I - n = I\r
8830 * I - 0 = I\r
8831 * I - N = N\r
8832 * I - I = N\r
8833 *\r
8834 * Return a new BigNumber whose value is the value of this BigNumber minus the value of\r
8835 * BigNumber(y, b).\r
8836 */\r
8837 P.minus = P.sub = function ( y, b ) {\r
8838 var i, j, t, xLTy,\r
8839 x = this,\r
8840 a = x.s;\r
8841\r
8842 id = 10;\r
8843 y = new BigNumber( y, b );\r
8844 b = y.s;\r
8845\r
8846 // Either NaN?\r
8847 if ( !a || !b ) return new BigNumber(NaN);\r
8848\r
8849 // Signs differ?\r
8850 if ( a != b ) {\r
8851 y.s = -b;\r
8852 return x.plus(y);\r
8853 }\r
8854\r
8855 var xe = x.e / LOG_BASE,\r
8856 ye = y.e / LOG_BASE,\r
8857 xc = x.c,\r
8858 yc = y.c;\r
8859\r
8860 if ( !xe || !ye ) {\r
8861\r
8862 // Either Infinity?\r
8863 if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN );\r
8864\r
8865 // Either zero?\r
8866 if ( !xc[0] || !yc[0] ) {\r
8867\r
8868 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r
8869 return yc[0] ? ( y.s = -b, y ) : new BigNumber( xc[0] ? x :\r
8870\r
8871 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity\r
8872 ROUNDING_MODE == 3 ? -0 : 0 );\r
8873 }\r
8874 }\r
8875\r
8876 xe = bitFloor(xe);\r
8877 ye = bitFloor(ye);\r
8878 xc = xc.slice();\r
8879\r
8880 // Determine which is the bigger number.\r
8881 if ( a = xe - ye ) {\r
8882\r
8883 if ( xLTy = a < 0 ) {\r
8884 a = -a;\r
8885 t = xc;\r
8886 } else {\r
8887 ye = xe;\r
8888 t = yc;\r
8889 }\r
8890\r
8891 t.reverse();\r
8892\r
8893 // Prepend zeros to equalise exponents.\r
8894 for ( b = a; b--; t.push(0) );\r
8895 t.reverse();\r
8896 } else {\r
8897\r
8898 // Exponents equal. Check digit by digit.\r
8899 j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b;\r
8900\r
8901 for ( a = b = 0; b < j; b++ ) {\r
8902\r
8903 if ( xc[b] != yc[b] ) {\r
8904 xLTy = xc[b] < yc[b];\r
8905 break;\r
8906 }\r
8907 }\r
8908 }\r
8909\r
8910 // x < y? Point xc to the array of the bigger number.\r
8911 if (xLTy) t = xc, xc = yc, yc = t, y.s = -y.s;\r
8912\r
8913 b = ( j = yc.length ) - ( i = xc.length );\r
8914\r
8915 // Append zeros to xc if shorter.\r
8916 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.\r
8917 if ( b > 0 ) for ( ; b--; xc[i++] = 0 );\r
8918 b = BASE - 1;\r
8919\r
8920 // Subtract yc from xc.\r
8921 for ( ; j > a; ) {\r
8922\r
8923 if ( xc[--j] < yc[j] ) {\r
8924 for ( i = j; i && !xc[--i]; xc[i] = b );\r
8925 --xc[i];\r
8926 xc[j] += BASE;\r
8927 }\r
8928\r
8929 xc[j] -= yc[j];\r
8930 }\r
8931\r
8932 // Remove leading zeros and adjust exponent accordingly.\r
8933 for ( ; xc[0] == 0; xc.splice(0, 1), --ye );\r
8934\r
8935 // Zero?\r
8936 if ( !xc[0] ) {\r
8937\r
8938 // Following IEEE 754 (2008) 6.3,\r
8939 // n - n = +0 but n - n = -0 when rounding towards -Infinity.\r
8940 y.s = ROUNDING_MODE == 3 ? -1 : 1;\r
8941 y.c = [ y.e = 0 ];\r
8942 return y;\r
8943 }\r
8944\r
8945 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity\r
8946 // for finite x and y.\r
8947 return normalise( y, xc, ye );\r
8948 };\r
8949\r
8950\r
8951 /*\r
8952 * n % 0 = N\r
8953 * n % N = N\r
8954 * n % I = n\r
8955 * 0 % n = 0\r
8956 * -0 % n = -0\r
8957 * 0 % 0 = N\r
8958 * 0 % N = N\r
8959 * 0 % I = 0\r
8960 * N % n = N\r
8961 * N % 0 = N\r
8962 * N % N = N\r
8963 * N % I = N\r
8964 * I % n = N\r
8965 * I % 0 = N\r
8966 * I % N = N\r
8967 * I % I = N\r
8968 *\r
8969 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of\r
8970 * BigNumber(y, b). The result depends on the value of MODULO_MODE.\r
8971 */\r
8972 P.modulo = P.mod = function ( y, b ) {\r
8973 var q, s,\r
8974 x = this;\r
8975\r
8976 id = 11;\r
8977 y = new BigNumber( y, b );\r
8978\r
8979 // Return NaN if x is Infinity or NaN, or y is NaN or zero.\r
8980 if ( !x.c || !y.s || y.c && !y.c[0] ) {\r
8981 return new BigNumber(NaN);\r
8982\r
8983 // Return x if y is Infinity or x is zero.\r
8984 } else if ( !y.c || x.c && !x.c[0] ) {\r
8985 return new BigNumber(x);\r
8986 }\r
8987\r
8988 if ( MODULO_MODE == 9 ) {\r
8989\r
8990 // Euclidian division: q = sign(y) * floor(x / abs(y))\r
8991 // r = x - qy where 0 <= r < abs(y)\r
8992 s = y.s;\r
8993 y.s = 1;\r
8994 q = div( x, y, 0, 3 );\r
8995 y.s = s;\r
8996 q.s *= s;\r
8997 } else {\r
8998 q = div( x, y, 0, MODULO_MODE );\r
8999 }\r
9000\r
9001 return x.minus( q.times(y) );\r
9002 };\r
9003\r
9004\r
9005 /*\r
9006 * Return a new BigNumber whose value is the value of this BigNumber negated,\r
9007 * i.e. multiplied by -1.\r
9008 */\r
9009 P.negated = P.neg = function () {\r
9010 var x = new BigNumber(this);\r
9011 x.s = -x.s || null;\r
9012 return x;\r
9013 };\r
9014\r
9015\r
9016 /*\r
9017 * n + 0 = n\r
9018 * n + N = N\r
9019 * n + I = I\r
9020 * 0 + n = n\r
9021 * 0 + 0 = 0\r
9022 * 0 + N = N\r
9023 * 0 + I = I\r
9024 * N + n = N\r
9025 * N + 0 = N\r
9026 * N + N = N\r
9027 * N + I = N\r
9028 * I + n = I\r
9029 * I + 0 = I\r
9030 * I + N = N\r
9031 * I + I = I\r
9032 *\r
9033 * Return a new BigNumber whose value is the value of this BigNumber plus the value of\r
9034 * BigNumber(y, b).\r
9035 */\r
9036 P.plus = P.add = function ( y, b ) {\r
9037 var t,\r
9038 x = this,\r
9039 a = x.s;\r
9040\r
9041 id = 12;\r
9042 y = new BigNumber( y, b );\r
9043 b = y.s;\r
9044\r
9045 // Either NaN?\r
9046 if ( !a || !b ) return new BigNumber(NaN);\r
9047\r
9048 // Signs differ?\r
9049 if ( a != b ) {\r
9050 y.s = -b;\r
9051 return x.minus(y);\r
9052 }\r
9053\r
9054 var xe = x.e / LOG_BASE,\r
9055 ye = y.e / LOG_BASE,\r
9056 xc = x.c,\r
9057 yc = y.c;\r
9058\r
9059 if ( !xe || !ye ) {\r
9060\r
9061 // Return ±Infinity if either ±Infinity.\r
9062 if ( !xc || !yc ) return new BigNumber( a / 0 );\r
9063\r
9064 // Either zero?\r
9065 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.\r
9066 if ( !xc[0] || !yc[0] ) return yc[0] ? y : new BigNumber( xc[0] ? x : a * 0 );\r
9067 }\r
9068\r
9069 xe = bitFloor(xe);\r
9070 ye = bitFloor(ye);\r
9071 xc = xc.slice();\r
9072\r
9073 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.\r
9074 if ( a = xe - ye ) {\r
9075 if ( a > 0 ) {\r
9076 ye = xe;\r
9077 t = yc;\r
9078 } else {\r
9079 a = -a;\r
9080 t = xc;\r
9081 }\r
9082\r
9083 t.reverse();\r
9084 for ( ; a--; t.push(0) );\r
9085 t.reverse();\r
9086 }\r
9087\r
9088 a = xc.length;\r
9089 b = yc.length;\r
9090\r
9091 // Point xc to the longer array, and b to the shorter length.\r
9092 if ( a - b < 0 ) t = yc, yc = xc, xc = t, b = a;\r
9093\r
9094 // Only start adding at yc.length - 1 as the further digits of xc can be ignored.\r
9095 for ( a = 0; b; ) {\r
9096 a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0;\r
9097 xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE;\r
9098 }\r
9099\r
9100 if (a) {\r
9101 xc = [a].concat(xc);\r
9102 ++ye;\r
9103 }\r
9104\r
9105 // No need to check for zero, as +x + +y != 0 && -x + -y != 0\r
9106 // ye = MAX_EXP + 1 possible\r
9107 return normalise( y, xc, ye );\r
9108 };\r
9109\r
9110\r
9111 /*\r
9112 * Return the number of significant digits of the value of this BigNumber.\r
9113 *\r
9114 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.\r
9115 */\r
9116 P.precision = P.sd = function (z) {\r
9117 var n, v,\r
9118 x = this,\r
9119 c = x.c;\r
9120\r
9121 // 'precision() argument not a boolean or binary digit: {z}'\r
9122 if ( z != null && z !== !!z && z !== 1 && z !== 0 ) {\r
9123 if (ERRORS) raise( 13, 'argument' + notBool, z );\r
9124 if ( z != !!z ) z = null;\r
9125 }\r
9126\r
9127 if ( !c ) return null;\r
9128 v = c.length - 1;\r
9129 n = v * LOG_BASE + 1;\r
9130\r
9131 if ( v = c[v] ) {\r
9132\r
9133 // Subtract the number of trailing zeros of the last element.\r
9134 for ( ; v % 10 == 0; v /= 10, n-- );\r
9135\r
9136 // Add the number of digits of the first element.\r
9137 for ( v = c[0]; v >= 10; v /= 10, n++ );\r
9138 }\r
9139\r
9140 if ( z && x.e + 1 > n ) n = x.e + 1;\r
9141\r
9142 return n;\r
9143 };\r
9144\r
9145\r
9146 /*\r
9147 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of\r
9148 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if\r
9149 * omitted.\r
9150 *\r
9151 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r
9152 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r
9153 *\r
9154 * 'round() decimal places out of range: {dp}'\r
9155 * 'round() decimal places not an integer: {dp}'\r
9156 * 'round() rounding mode not an integer: {rm}'\r
9157 * 'round() rounding mode out of range: {rm}'\r
9158 */\r
9159 P.round = function ( dp, rm ) {\r
9160 var n = new BigNumber(this);\r
9161\r
9162 if ( dp == null || isValidInt( dp, 0, MAX, 15 ) ) {\r
9163 round( n, ~~dp + this.e + 1, rm == null ||\r
9164 !isValidInt( rm, 0, 8, 15, roundingMode ) ? ROUNDING_MODE : rm | 0 );\r
9165 }\r
9166\r
9167 return n;\r
9168 };\r
9169\r
9170\r
9171 /*\r
9172 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places\r
9173 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.\r
9174 *\r
9175 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r
9176 *\r
9177 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity\r
9178 * otherwise.\r
9179 *\r
9180 * 'shift() argument not an integer: {k}'\r
9181 * 'shift() argument out of range: {k}'\r
9182 */\r
9183 P.shift = function (k) {\r
9184 var n = this;\r
9185 return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' )\r
9186\r
9187 // k < 1e+21, or truncate(k) will produce exponential notation.\r
9188 ? n.times( '1e' + truncate(k) )\r
9189 : new BigNumber( n.c && n.c[0] && ( k < -MAX_SAFE_INTEGER || k > MAX_SAFE_INTEGER )\r
9190 ? n.s * ( k < 0 ? 0 : 1 / 0 )\r
9191 : n );\r
9192 };\r
9193\r
9194\r
9195 /*\r
9196 * sqrt(-n) = N\r
9197 * sqrt( N) = N\r
9198 * sqrt(-I) = N\r
9199 * sqrt( I) = I\r
9200 * sqrt( 0) = 0\r
9201 * sqrt(-0) = -0\r
9202 *\r
9203 * Return a new BigNumber whose value is the square root of the value of this BigNumber,\r
9204 * rounded according to DECIMAL_PLACES and ROUNDING_MODE.\r
9205 */\r
9206 P.squareRoot = P.sqrt = function () {\r
9207 var m, n, r, rep, t,\r
9208 x = this,\r
9209 c = x.c,\r
9210 s = x.s,\r
9211 e = x.e,\r
9212 dp = DECIMAL_PLACES + 4,\r
9213 half = new BigNumber('0.5');\r
9214\r
9215 // Negative/NaN/Infinity/zero?\r
9216 if ( s !== 1 || !c || !c[0] ) {\r
9217 return new BigNumber( !s || s < 0 && ( !c || c[0] ) ? NaN : c ? x : 1 / 0 );\r
9218 }\r
9219\r
9220 // Initial estimate.\r
9221 s = Math.sqrt( +x );\r
9222\r
9223 // Math.sqrt underflow/overflow?\r
9224 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.\r
9225 if ( s == 0 || s == 1 / 0 ) {\r
9226 n = coeffToString(c);\r
9227 if ( ( n.length + e ) % 2 == 0 ) n += '0';\r
9228 s = Math.sqrt(n);\r
9229 e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 );\r
9230\r
9231 if ( s == 1 / 0 ) {\r
9232 n = '1e' + e;\r
9233 } else {\r
9234 n = s.toExponential();\r
9235 n = n.slice( 0, n.indexOf('e') + 1 ) + e;\r
9236 }\r
9237\r
9238 r = new BigNumber(n);\r
9239 } else {\r
9240 r = new BigNumber( s + '' );\r
9241 }\r
9242\r
9243 // Check for zero.\r
9244 // r could be zero if MIN_EXP is changed after the this value was created.\r
9245 // This would cause a division by zero (x/t) and hence Infinity below, which would cause\r
9246 // coeffToString to throw.\r
9247 if ( r.c[0] ) {\r
9248 e = r.e;\r
9249 s = e + dp;\r
9250 if ( s < 3 ) s = 0;\r
9251\r
9252 // Newton-Raphson iteration.\r
9253 for ( ; ; ) {\r
9254 t = r;\r
9255 r = half.times( t.plus( div( x, t, dp, 1 ) ) );\r
9256\r
9257 if ( coeffToString( t.c ).slice( 0, s ) === ( n =\r
9258 coeffToString( r.c ) ).slice( 0, s ) ) {\r
9259\r
9260 // The exponent of r may here be one less than the final result exponent,\r
9261 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits\r
9262 // are indexed correctly.\r
9263 if ( r.e < e ) --s;\r
9264 n = n.slice( s - 3, s + 1 );\r
9265\r
9266 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits\r
9267 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the\r
9268 // iteration.\r
9269 if ( n == '9999' || !rep && n == '4999' ) {\r
9270\r
9271 // On the first iteration only, check to see if rounding up gives the\r
9272 // exact result as the nines may infinitely repeat.\r
9273 if ( !rep ) {\r
9274 round( t, t.e + DECIMAL_PLACES + 2, 0 );\r
9275\r
9276 if ( t.times(t).eq(x) ) {\r
9277 r = t;\r
9278 break;\r
9279 }\r
9280 }\r
9281\r
9282 dp += 4;\r
9283 s += 4;\r
9284 rep = 1;\r
9285 } else {\r
9286\r
9287 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact\r
9288 // result. If not, then there are further digits and m will be truthy.\r
9289 if ( !+n || !+n.slice(1) && n.charAt(0) == '5' ) {\r
9290\r
9291 // Truncate to the first rounding digit.\r
9292 round( r, r.e + DECIMAL_PLACES + 2, 1 );\r
9293 m = !r.times(r).eq(x);\r
9294 }\r
9295\r
9296 break;\r
9297 }\r
9298 }\r
9299 }\r
9300 }\r
9301\r
9302 return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m );\r
9303 };\r
9304\r
9305\r
9306 /*\r
9307 * n * 0 = 0\r
9308 * n * N = N\r
9309 * n * I = I\r
9310 * 0 * n = 0\r
9311 * 0 * 0 = 0\r
9312 * 0 * N = N\r
9313 * 0 * I = N\r
9314 * N * n = N\r
9315 * N * 0 = N\r
9316 * N * N = N\r
9317 * N * I = N\r
9318 * I * n = I\r
9319 * I * 0 = N\r
9320 * I * N = N\r
9321 * I * I = I\r
9322 *\r
9323 * Return a new BigNumber whose value is the value of this BigNumber times the value of\r
9324 * BigNumber(y, b).\r
9325 */\r
9326 P.times = P.mul = function ( y, b ) {\r
9327 var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc,\r
9328 base, sqrtBase,\r
9329 x = this,\r
9330 xc = x.c,\r
9331 yc = ( id = 17, y = new BigNumber( y, b ) ).c;\r
9332\r
9333 // Either NaN, ±Infinity or ±0?\r
9334 if ( !xc || !yc || !xc[0] || !yc[0] ) {\r
9335\r
9336 // Return NaN if either is NaN, or one is 0 and the other is Infinity.\r
9337 if ( !x.s || !y.s || xc && !xc[0] && !yc || yc && !yc[0] && !xc ) {\r
9338 y.c = y.e = y.s = null;\r
9339 } else {\r
9340 y.s *= x.s;\r
9341\r
9342 // Return ±Infinity if either is ±Infinity.\r
9343 if ( !xc || !yc ) {\r
9344 y.c = y.e = null;\r
9345\r
9346 // Return ±0 if either is ±0.\r
9347 } else {\r
9348 y.c = [0];\r
9349 y.e = 0;\r
9350 }\r
9351 }\r
9352\r
9353 return y;\r
9354 }\r
9355\r
9356 e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE );\r
9357 y.s *= x.s;\r
9358 xcL = xc.length;\r
9359 ycL = yc.length;\r
9360\r
9361 // Ensure xc points to longer array and xcL to its length.\r
9362 if ( xcL < ycL ) zc = xc, xc = yc, yc = zc, i = xcL, xcL = ycL, ycL = i;\r
9363\r
9364 // Initialise the result array with zeros.\r
9365 for ( i = xcL + ycL, zc = []; i--; zc.push(0) );\r
9366\r
9367 base = BASE;\r
9368 sqrtBase = SQRT_BASE;\r
9369\r
9370 for ( i = ycL; --i >= 0; ) {\r
9371 c = 0;\r
9372 ylo = yc[i] % sqrtBase;\r
9373 yhi = yc[i] / sqrtBase | 0;\r
9374\r
9375 for ( k = xcL, j = i + k; j > i; ) {\r
9376 xlo = xc[--k] % sqrtBase;\r
9377 xhi = xc[k] / sqrtBase | 0;\r
9378 m = yhi * xlo + xhi * ylo;\r
9379 xlo = ylo * xlo + ( ( m % sqrtBase ) * sqrtBase ) + zc[j] + c;\r
9380 c = ( xlo / base | 0 ) + ( m / sqrtBase | 0 ) + yhi * xhi;\r
9381 zc[j--] = xlo % base;\r
9382 }\r
9383\r
9384 zc[j] = c;\r
9385 }\r
9386\r
9387 if (c) {\r
9388 ++e;\r
9389 } else {\r
9390 zc.splice(0, 1);\r
9391 }\r
9392\r
9393 return normalise( y, zc, e );\r
9394 };\r
9395\r
9396\r
9397 /*\r
9398 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of\r
9399 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r
9400 *\r
9401 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r
9402 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r
9403 *\r
9404 * 'toDigits() precision out of range: {sd}'\r
9405 * 'toDigits() precision not an integer: {sd}'\r
9406 * 'toDigits() rounding mode not an integer: {rm}'\r
9407 * 'toDigits() rounding mode out of range: {rm}'\r
9408 */\r
9409 P.toDigits = function ( sd, rm ) {\r
9410 var n = new BigNumber(this);\r
9411 sd = sd == null || !isValidInt( sd, 1, MAX, 18, 'precision' ) ? null : sd | 0;\r
9412 rm = rm == null || !isValidInt( rm, 0, 8, 18, roundingMode ) ? ROUNDING_MODE : rm | 0;\r
9413 return sd ? round( n, sd, rm ) : n;\r
9414 };\r
9415\r
9416\r
9417 /*\r
9418 * Return a string representing the value of this BigNumber in exponential notation and\r
9419 * rounded using ROUNDING_MODE to dp fixed decimal places.\r
9420 *\r
9421 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r
9422 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r
9423 *\r
9424 * 'toExponential() decimal places not an integer: {dp}'\r
9425 * 'toExponential() decimal places out of range: {dp}'\r
9426 * 'toExponential() rounding mode not an integer: {rm}'\r
9427 * 'toExponential() rounding mode out of range: {rm}'\r
9428 */\r
9429 P.toExponential = function ( dp, rm ) {\r
9430 return format( this,\r
9431 dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 );\r
9432 };\r
9433\r
9434\r
9435 /*\r
9436 * Return a string representing the value of this BigNumber in fixed-point notation rounding\r
9437 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.\r
9438 *\r
9439 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',\r
9440 * but e.g. (-0.00001).toFixed(0) is '-0'.\r
9441 *\r
9442 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r
9443 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r
9444 *\r
9445 * 'toFixed() decimal places not an integer: {dp}'\r
9446 * 'toFixed() decimal places out of range: {dp}'\r
9447 * 'toFixed() rounding mode not an integer: {rm}'\r
9448 * 'toFixed() rounding mode out of range: {rm}'\r
9449 */\r
9450 P.toFixed = function ( dp, rm ) {\r
9451 return format( this, dp != null && isValidInt( dp, 0, MAX, 20 )\r
9452 ? ~~dp + this.e + 1 : null, rm, 20 );\r
9453 };\r
9454\r
9455\r
9456 /*\r
9457 * Return a string representing the value of this BigNumber in fixed-point notation rounded\r
9458 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties\r
9459 * of the FORMAT object (see BigNumber.config).\r
9460 *\r
9461 * FORMAT = {\r
9462 * decimalSeparator : '.',\r
9463 * groupSeparator : ',',\r
9464 * groupSize : 3,\r
9465 * secondaryGroupSize : 0,\r
9466 * fractionGroupSeparator : '\xA0', // non-breaking space\r
9467 * fractionGroupSize : 0\r
9468 * };\r
9469 *\r
9470 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.\r
9471 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r
9472 *\r
9473 * 'toFormat() decimal places not an integer: {dp}'\r
9474 * 'toFormat() decimal places out of range: {dp}'\r
9475 * 'toFormat() rounding mode not an integer: {rm}'\r
9476 * 'toFormat() rounding mode out of range: {rm}'\r
9477 */\r
9478 P.toFormat = function ( dp, rm ) {\r
9479 var str = format( this, dp != null && isValidInt( dp, 0, MAX, 21 )\r
9480 ? ~~dp + this.e + 1 : null, rm, 21 );\r
9481\r
9482 if ( this.c ) {\r
9483 var i,\r
9484 arr = str.split('.'),\r
9485 g1 = +FORMAT.groupSize,\r
9486 g2 = +FORMAT.secondaryGroupSize,\r
9487 groupSeparator = FORMAT.groupSeparator,\r
9488 intPart = arr[0],\r
9489 fractionPart = arr[1],\r
9490 isNeg = this.s < 0,\r
9491 intDigits = isNeg ? intPart.slice(1) : intPart,\r
9492 len = intDigits.length;\r
9493\r
9494 if (g2) i = g1, g1 = g2, g2 = i, len -= i;\r
9495\r
9496 if ( g1 > 0 && len > 0 ) {\r
9497 i = len % g1 || g1;\r
9498 intPart = intDigits.substr( 0, i );\r
9499\r
9500 for ( ; i < len; i += g1 ) {\r
9501 intPart += groupSeparator + intDigits.substr( i, g1 );\r
9502 }\r
9503\r
9504 if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i);\r
9505 if (isNeg) intPart = '-' + intPart;\r
9506 }\r
9507\r
9508 str = fractionPart\r
9509 ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize )\r
9510 ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ),\r
9511 '$&' + FORMAT.fractionGroupSeparator )\r
9512 : fractionPart )\r
9513 : intPart;\r
9514 }\r
9515\r
9516 return str;\r
9517 };\r
9518\r
9519\r
9520 /*\r
9521 * Return a string array representing the value of this BigNumber as a simple fraction with\r
9522 * an integer numerator and an integer denominator. The denominator will be a positive\r
9523 * non-zero value less than or equal to the specified maximum denominator. If a maximum\r
9524 * denominator is not specified, the denominator will be the lowest value necessary to\r
9525 * represent the number exactly.\r
9526 *\r
9527 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.\r
9528 *\r
9529 * 'toFraction() max denominator not an integer: {md}'\r
9530 * 'toFraction() max denominator out of range: {md}'\r
9531 */\r
9532 P.toFraction = function (md) {\r
9533 var arr, d0, d2, e, exp, n, n0, q, s,\r
9534 k = ERRORS,\r
9535 x = this,\r
9536 xc = x.c,\r
9537 d = new BigNumber(ONE),\r
9538 n1 = d0 = new BigNumber(ONE),\r
9539 d1 = n0 = new BigNumber(ONE);\r
9540\r
9541 if ( md != null ) {\r
9542 ERRORS = false;\r
9543 n = new BigNumber(md);\r
9544 ERRORS = k;\r
9545\r
9546 if ( !( k = n.isInt() ) || n.lt(ONE) ) {\r
9547\r
9548 if (ERRORS) {\r
9549 raise( 22,\r
9550 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md );\r
9551 }\r
9552\r
9553 // ERRORS is false:\r
9554 // If md is a finite non-integer >= 1, round it to an integer and use it.\r
9555 md = !k && n.c && round( n, n.e + 1, 1 ).gte(ONE) ? n : null;\r
9556 }\r
9557 }\r
9558\r
9559 if ( !xc ) return x.toString();\r
9560 s = coeffToString(xc);\r
9561\r
9562 // Determine initial denominator.\r
9563 // d is a power of 10 and the minimum max denominator that specifies the value exactly.\r
9564 e = d.e = s.length - x.e - 1;\r
9565 d.c[0] = POWS_TEN[ ( exp = e % LOG_BASE ) < 0 ? LOG_BASE + exp : exp ];\r
9566 md = !md || n.cmp(d) > 0 ? ( e > 0 ? d : n1 ) : n;\r
9567\r
9568 exp = MAX_EXP;\r
9569 MAX_EXP = 1 / 0;\r
9570 n = new BigNumber(s);\r
9571\r
9572 // n0 = d1 = 0\r
9573 n0.c[0] = 0;\r
9574\r
9575 for ( ; ; ) {\r
9576 q = div( n, d, 0, 1 );\r
9577 d2 = d0.plus( q.times(d1) );\r
9578 if ( d2.cmp(md) == 1 ) break;\r
9579 d0 = d1;\r
9580 d1 = d2;\r
9581 n1 = n0.plus( q.times( d2 = n1 ) );\r
9582 n0 = d2;\r
9583 d = n.minus( q.times( d2 = d ) );\r
9584 n = d2;\r
9585 }\r
9586\r
9587 d2 = div( md.minus(d0), d1, 0, 1 );\r
9588 n0 = n0.plus( d2.times(n1) );\r
9589 d0 = d0.plus( d2.times(d1) );\r
9590 n0.s = n1.s = x.s;\r
9591 e *= 2;\r
9592\r
9593 // Determine which fraction is closer to x, n0/d0 or n1/d1\r
9594 arr = div( n1, d1, e, ROUNDING_MODE ).minus(x).abs().cmp(\r
9595 div( n0, d0, e, ROUNDING_MODE ).minus(x).abs() ) < 1\r
9596 ? [ n1.toString(), d1.toString() ]\r
9597 : [ n0.toString(), d0.toString() ];\r
9598\r
9599 MAX_EXP = exp;\r
9600 return arr;\r
9601 };\r
9602\r
9603\r
9604 /*\r
9605 * Return the value of this BigNumber converted to a number primitive.\r
9606 */\r
9607 P.toNumber = function () {\r
9608 return +this;\r
9609 };\r
9610\r
9611\r
9612 /*\r
9613 * Return a BigNumber whose value is the value of this BigNumber raised to the power n.\r
9614 * If m is present, return the result modulo m.\r
9615 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.\r
9616 * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using\r
9617 * ROUNDING_MODE.\r
9618 *\r
9619 * The modular power operation works efficiently when x, n, and m are positive integers,\r
9620 * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).\r
9621 *\r
9622 * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.\r
9623 * [m] {number|string|BigNumber} The modulus.\r
9624 *\r
9625 * 'pow() exponent not an integer: {n}'\r
9626 * 'pow() exponent out of range: {n}'\r
9627 *\r
9628 * Performs 54 loop iterations for n of 9007199254740991.\r
9629 */\r
9630 P.toPower = P.pow = function ( n, m ) {\r
9631 var k, y, z,\r
9632 i = mathfloor( n < 0 ? -n : +n ),\r
9633 x = this;\r
9634\r
9635 if ( m != null ) {\r
9636 id = 23;\r
9637 m = new BigNumber(m);\r
9638 }\r
9639\r
9640 // Pass ±Infinity to Math.pow if exponent is out of range.\r
9641 if ( !isValidInt( n, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 23, 'exponent' ) &&\r
9642 ( !isFinite(n) || i > MAX_SAFE_INTEGER && ( n /= 0 ) ||\r
9643 parseFloat(n) != n && !( n = NaN ) ) || n == 0 ) {\r
9644 k = Math.pow( +x, n );\r
9645 return new BigNumber( m ? k % m : k );\r
9646 }\r
9647\r
9648 if (m) {\r
9649 if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) {\r
9650 x = x.mod(m);\r
9651 } else {\r
9652 z = m;\r
9653\r
9654 // Nullify m so only a single mod operation is performed at the end.\r
9655 m = null;\r
9656 }\r
9657 } else if (POW_PRECISION) {\r
9658\r
9659 // Truncating each coefficient array to a length of k after each multiplication\r
9660 // equates to truncating significant digits to POW_PRECISION + [28, 41],\r
9661 // i.e. there will be a minimum of 28 guard digits retained.\r
9662 // (Using + 1.5 would give [9, 21] guard digits.)\r
9663 k = mathceil( POW_PRECISION / LOG_BASE + 2 );\r
9664 }\r
9665\r
9666 y = new BigNumber(ONE);\r
9667\r
9668 for ( ; ; ) {\r
9669 if ( i % 2 ) {\r
9670 y = y.times(x);\r
9671 if ( !y.c ) break;\r
9672 if (k) {\r
9673 if ( y.c.length > k ) y.c.length = k;\r
9674 } else if (m) {\r
9675 y = y.mod(m);\r
9676 }\r
9677 }\r
9678\r
9679 i = mathfloor( i / 2 );\r
9680 if ( !i ) break;\r
9681 x = x.times(x);\r
9682 if (k) {\r
9683 if ( x.c && x.c.length > k ) x.c.length = k;\r
9684 } else if (m) {\r
9685 x = x.mod(m);\r
9686 }\r
9687 }\r
9688\r
9689 if (m) return y;\r
9690 if ( n < 0 ) y = ONE.div(y);\r
9691\r
9692 return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y;\r
9693 };\r
9694\r
9695\r
9696 /*\r
9697 * Return a string representing the value of this BigNumber rounded to sd significant digits\r
9698 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits\r
9699 * necessary to represent the integer part of the value in fixed-point notation, then use\r
9700 * exponential notation.\r
9701 *\r
9702 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.\r
9703 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.\r
9704 *\r
9705 * 'toPrecision() precision not an integer: {sd}'\r
9706 * 'toPrecision() precision out of range: {sd}'\r
9707 * 'toPrecision() rounding mode not an integer: {rm}'\r
9708 * 'toPrecision() rounding mode out of range: {rm}'\r
9709 */\r
9710 P.toPrecision = function ( sd, rm ) {\r
9711 return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' )\r
9712 ? sd | 0 : null, rm, 24 );\r
9713 };\r
9714\r
9715\r
9716 /*\r
9717 * Return a string representing the value of this BigNumber in base b, or base 10 if b is\r
9718 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and\r
9719 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent\r
9720 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than\r
9721 * TO_EXP_NEG, return exponential notation.\r
9722 *\r
9723 * [b] {number} Integer, 2 to 64 inclusive.\r
9724 *\r
9725 * 'toString() base not an integer: {b}'\r
9726 * 'toString() base out of range: {b}'\r
9727 */\r
9728 P.toString = function (b) {\r
9729 var str,\r
9730 n = this,\r
9731 s = n.s,\r
9732 e = n.e;\r
9733\r
9734 // Infinity or NaN?\r
9735 if ( e === null ) {\r
9736\r
9737 if (s) {\r
9738 str = 'Infinity';\r
9739 if ( s < 0 ) str = '-' + str;\r
9740 } else {\r
9741 str = 'NaN';\r
9742 }\r
9743 } else {\r
9744 str = coeffToString( n.c );\r
9745\r
9746 if ( b == null || !isValidInt( b, 2, 64, 25, 'base' ) ) {\r
9747 str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r
9748 ? toExponential( str, e )\r
9749 : toFixedPoint( str, e );\r
9750 } else {\r
9751 str = convertBase( toFixedPoint( str, e ), b | 0, 10, s );\r
9752 }\r
9753\r
9754 if ( s < 0 && n.c[0] ) str = '-' + str;\r
9755 }\r
9756\r
9757 return str;\r
9758 };\r
9759\r
9760\r
9761 /*\r
9762 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole\r
9763 * number.\r
9764 */\r
9765 P.truncated = P.trunc = function () {\r
9766 return round( new BigNumber(this), this.e + 1, 1 );\r
9767 };\r
9768\r
9769\r
9770 /*\r
9771 * Return as toString, but do not accept a base argument, and include the minus sign for\r
9772 * negative zero.\r
9773 */\r
9774 P.valueOf = P.toJSON = function () {\r
9775 var str,\r
9776 n = this,\r
9777 e = n.e;\r
9778\r
9779 if ( e === null ) return n.toString();\r
9780\r
9781 str = coeffToString( n.c );\r
9782\r
9783 str = e <= TO_EXP_NEG || e >= TO_EXP_POS\r
9784 ? toExponential( str, e )\r
9785 : toFixedPoint( str, e );\r
9786\r
9787 return n.s < 0 ? '-' + str : str;\r
9788 };\r
9789\r
9790\r
9791 P.isBigNumber = true;\r
9792\r
9793 if ( config != null ) BigNumber.config(config);\r
9794\r
9795 return BigNumber;\r
9796 }\r
9797\r
9798\r
9799 // PRIVATE HELPER FUNCTIONS\r
9800\r
9801\r
9802 function bitFloor(n) {\r
9803 var i = n | 0;\r
9804 return n > 0 || n === i ? i : i - 1;\r
9805 }\r
9806\r
9807\r
9808 // Return a coefficient array as a string of base 10 digits.\r
9809 function coeffToString(a) {\r
9810 var s, z,\r
9811 i = 1,\r
9812 j = a.length,\r
9813 r = a[0] + '';\r
9814\r
9815 for ( ; i < j; ) {\r
9816 s = a[i++] + '';\r
9817 z = LOG_BASE - s.length;\r
9818 for ( ; z--; s = '0' + s );\r
9819 r += s;\r
9820 }\r
9821\r
9822 // Determine trailing zeros.\r
9823 for ( j = r.length; r.charCodeAt(--j) === 48; );\r
9824 return r.slice( 0, j + 1 || 1 );\r
9825 }\r
9826\r
9827\r
9828 // Compare the value of BigNumbers x and y.\r
9829 function compare( x, y ) {\r
9830 var a, b,\r
9831 xc = x.c,\r
9832 yc = y.c,\r
9833 i = x.s,\r
9834 j = y.s,\r
9835 k = x.e,\r
9836 l = y.e;\r
9837\r
9838 // Either NaN?\r
9839 if ( !i || !j ) return null;\r
9840\r
9841 a = xc && !xc[0];\r
9842 b = yc && !yc[0];\r
9843\r
9844 // Either zero?\r
9845 if ( a || b ) return a ? b ? 0 : -j : i;\r
9846\r
9847 // Signs differ?\r
9848 if ( i != j ) return i;\r
9849\r
9850 a = i < 0;\r
9851 b = k == l;\r
9852\r
9853 // Either Infinity?\r
9854 if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1;\r
9855\r
9856 // Compare exponents.\r
9857 if ( !b ) return k > l ^ a ? 1 : -1;\r
9858\r
9859 j = ( k = xc.length ) < ( l = yc.length ) ? k : l;\r
9860\r
9861 // Compare digit by digit.\r
9862 for ( i = 0; i < j; i++ ) if ( xc[i] != yc[i] ) return xc[i] > yc[i] ^ a ? 1 : -1;\r
9863\r
9864 // Compare lengths.\r
9865 return k == l ? 0 : k > l ^ a ? 1 : -1;\r
9866 }\r
9867\r
9868\r
9869 /*\r
9870 * Return true if n is a valid number in range, otherwise false.\r
9871 * Use for argument validation when ERRORS is false.\r
9872 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.\r
9873 */\r
9874 function intValidatorNoErrors( n, min, max ) {\r
9875 return ( n = truncate(n) ) >= min && n <= max;\r
9876 }\r
9877\r
9878\r
9879 function isArray(obj) {\r
9880 return Object.prototype.toString.call(obj) == '[object Array]';\r
9881 }\r
9882\r
9883\r
9884 /*\r
9885 * Convert string of baseIn to an array of numbers of baseOut.\r
9886 * Eg. convertBase('255', 10, 16) returns [15, 15].\r
9887 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].\r
9888 */\r
9889 function toBaseOut( str, baseIn, baseOut ) {\r
9890 var j,\r
9891 arr = [0],\r
9892 arrL,\r
9893 i = 0,\r
9894 len = str.length;\r
9895\r
9896 for ( ; i < len; ) {\r
9897 for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn );\r
9898 arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) );\r
9899\r
9900 for ( ; j < arr.length; j++ ) {\r
9901\r
9902 if ( arr[j] > baseOut - 1 ) {\r
9903 if ( arr[j + 1] == null ) arr[j + 1] = 0;\r
9904 arr[j + 1] += arr[j] / baseOut | 0;\r
9905 arr[j] %= baseOut;\r
9906 }\r
9907 }\r
9908 }\r
9909\r
9910 return arr.reverse();\r
9911 }\r
9912\r
9913\r
9914 function toExponential( str, e ) {\r
9915 return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) +\r
9916 ( e < 0 ? 'e' : 'e+' ) + e;\r
9917 }\r
9918\r
9919\r
9920 function toFixedPoint( str, e ) {\r
9921 var len, z;\r
9922\r
9923 // Negative exponent?\r
9924 if ( e < 0 ) {\r
9925\r
9926 // Prepend zeros.\r
9927 for ( z = '0.'; ++e; z += '0' );\r
9928 str = z + str;\r
9929\r
9930 // Positive exponent\r
9931 } else {\r
9932 len = str.length;\r
9933\r
9934 // Append zeros.\r
9935 if ( ++e > len ) {\r
9936 for ( z = '0', e -= len; --e; z += '0' );\r
9937 str += z;\r
9938 } else if ( e < len ) {\r
9939 str = str.slice( 0, e ) + '.' + str.slice(e);\r
9940 }\r
9941 }\r
9942\r
9943 return str;\r
9944 }\r
9945\r
9946\r
9947 function truncate(n) {\r
9948 n = parseFloat(n);\r
9949 return n < 0 ? mathceil(n) : mathfloor(n);\r
9950 }\r
9951\r
9952\r
9953 // EXPORT\r
9954\r
9955\r
9956 BigNumber = constructorFactory();\r
9957 BigNumber['default'] = BigNumber.BigNumber = BigNumber;\r
9958\r
9959\r
9960 // AMD.\r
9961 if ( typeof define == 'function' && define.amd ) {\r
9962 define( function () { return BigNumber; } );\r
9963\r
9964 // Node.js and other environments that support module.exports.\r
9965 } else if ( typeof module != 'undefined' && module.exports ) {\r
9966 module.exports = BigNumber;\r
9967\r
9968 // Browser.\r
9969 } else {\r
9970 if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')();\r
9971 globalObj.BigNumber = BigNumber;\r
9972 }\r
9973})(this);\r
9974
9975},{}],74:[function(require,module,exports){
9976// Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki
9977// Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
9978// NOTE: SIGHASH byte ignored AND restricted, truncate before use
9979
9980var Buffer = require('safe-buffer').Buffer
9981
9982function check (buffer) {
9983 if (buffer.length < 8) return false
9984 if (buffer.length > 72) return false
9985 if (buffer[0] !== 0x30) return false
9986 if (buffer[1] !== buffer.length - 2) return false
9987 if (buffer[2] !== 0x02) return false
9988
9989 var lenR = buffer[3]
9990 if (lenR === 0) return false
9991 if (5 + lenR >= buffer.length) return false
9992 if (buffer[4 + lenR] !== 0x02) return false
9993
9994 var lenS = buffer[5 + lenR]
9995 if (lenS === 0) return false
9996 if ((6 + lenR + lenS) !== buffer.length) return false
9997
9998 if (buffer[4] & 0x80) return false
9999 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false
10000
10001 if (buffer[lenR + 6] & 0x80) return false
10002 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false
10003 return true
10004}
10005
10006function decode (buffer) {
10007 if (buffer.length < 8) throw new Error('DER sequence length is too short')
10008 if (buffer.length > 72) throw new Error('DER sequence length is too long')
10009 if (buffer[0] !== 0x30) throw new Error('Expected DER sequence')
10010 if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid')
10011 if (buffer[2] !== 0x02) throw new Error('Expected DER integer')
10012
10013 var lenR = buffer[3]
10014 if (lenR === 0) throw new Error('R length is zero')
10015 if (5 + lenR >= buffer.length) throw new Error('R length is too long')
10016 if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)')
10017
10018 var lenS = buffer[5 + lenR]
10019 if (lenS === 0) throw new Error('S length is zero')
10020 if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid')
10021
10022 if (buffer[4] & 0x80) throw new Error('R value is negative')
10023 if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded')
10024
10025 if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative')
10026 if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded')
10027
10028 // non-BIP66 - extract R, S values
10029 return {
10030 r: buffer.slice(4, 4 + lenR),
10031 s: buffer.slice(6 + lenR)
10032 }
10033}
10034
10035/*
10036 * Expects r and s to be positive DER integers.
10037 *
10038 * The DER format uses the most significant bit as a sign bit (& 0x80).
10039 * If the significant bit is set AND the integer is positive, a 0x00 is prepended.
10040 *
10041 * Examples:
10042 *
10043 * 0 => 0x00
10044 * 1 => 0x01
10045 * -1 => 0xff
10046 * 127 => 0x7f
10047 * -127 => 0x81
10048 * 128 => 0x0080
10049 * -128 => 0x80
10050 * 255 => 0x00ff
10051 * -255 => 0xff01
10052 * 16300 => 0x3fac
10053 * -16300 => 0xc054
10054 * 62300 => 0x00f35c
10055 * -62300 => 0xff0ca4
10056*/
10057function encode (r, s) {
10058 var lenR = r.length
10059 var lenS = s.length
10060 if (lenR === 0) throw new Error('R length is zero')
10061 if (lenS === 0) throw new Error('S length is zero')
10062 if (lenR > 33) throw new Error('R length is too long')
10063 if (lenS > 33) throw new Error('S length is too long')
10064 if (r[0] & 0x80) throw new Error('R value is negative')
10065 if (s[0] & 0x80) throw new Error('S value is negative')
10066 if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded')
10067 if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded')
10068
10069 var signature = Buffer.allocUnsafe(6 + lenR + lenS)
10070
10071 // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S]
10072 signature[0] = 0x30
10073 signature[1] = signature.length - 2
10074 signature[2] = 0x02
10075 signature[3] = r.length
10076 r.copy(signature, 4)
10077 signature[4 + lenR] = 0x02
10078 signature[5 + lenR] = s.length
10079 s.copy(signature, 6 + lenR)
10080
10081 return signature
10082}
10083
10084module.exports = {
10085 check: check,
10086 decode: decode,
10087 encode: encode
10088}
10089
10090},{"safe-buffer":247}],75:[function(require,module,exports){
10091(function (module, exports) {
10092 'use strict';
10093
10094 // Utils
10095 function assert (val, msg) {
10096 if (!val) throw new Error(msg || 'Assertion failed');
10097 }
10098
10099 // Could use `inherits` module, but don't want to move from single file
10100 // architecture yet.
10101 function inherits (ctor, superCtor) {
10102 ctor.super_ = superCtor;
10103 var TempCtor = function () {};
10104 TempCtor.prototype = superCtor.prototype;
10105 ctor.prototype = new TempCtor();
10106 ctor.prototype.constructor = ctor;
10107 }
10108
10109 // BN
10110
10111 function BN (number, base, endian) {
10112 if (BN.isBN(number)) {
10113 return number;
10114 }
10115
10116 this.negative = 0;
10117 this.words = null;
10118 this.length = 0;
10119
10120 // Reduction context
10121 this.red = null;
10122
10123 if (number !== null) {
10124 if (base === 'le' || base === 'be') {
10125 endian = base;
10126 base = 10;
10127 }
10128
10129 this._init(number || 0, base || 10, endian || 'be');
10130 }
10131 }
10132 if (typeof module === 'object') {
10133 module.exports = BN;
10134 } else {
10135 exports.BN = BN;
10136 }
10137
10138 BN.BN = BN;
10139 BN.wordSize = 26;
10140
10141 var Buffer;
10142 try {
10143 Buffer = require('buffer').Buffer;
10144 } catch (e) {
10145 }
10146
10147 BN.isBN = function isBN (num) {
10148 if (num instanceof BN) {
10149 return true;
10150 }
10151
10152 return num !== null && typeof num === 'object' &&
10153 num.constructor.wordSize === BN.wordSize && Array.isArray(num.words);
10154 };
10155
10156 BN.max = function max (left, right) {
10157 if (left.cmp(right) > 0) return left;
10158 return right;
10159 };
10160
10161 BN.min = function min (left, right) {
10162 if (left.cmp(right) < 0) return left;
10163 return right;
10164 };
10165
10166 BN.prototype._init = function init (number, base, endian) {
10167 if (typeof number === 'number') {
10168 return this._initNumber(number, base, endian);
10169 }
10170
10171 if (typeof number === 'object') {
10172 return this._initArray(number, base, endian);
10173 }
10174
10175 if (base === 'hex') {
10176 base = 16;
10177 }
10178 assert(base === (base | 0) && base >= 2 && base <= 36);
10179
10180 number = number.toString().replace(/\s+/g, '');
10181 var start = 0;
10182 if (number[0] === '-') {
10183 start++;
10184 }
10185
10186 if (base === 16) {
10187 this._parseHex(number, start);
10188 } else {
10189 this._parseBase(number, base, start);
10190 }
10191
10192 if (number[0] === '-') {
10193 this.negative = 1;
10194 }
10195
10196 this.strip();
10197
10198 if (endian !== 'le') return;
10199
10200 this._initArray(this.toArray(), base, endian);
10201 };
10202
10203 BN.prototype._initNumber = function _initNumber (number, base, endian) {
10204 if (number < 0) {
10205 this.negative = 1;
10206 number = -number;
10207 }
10208 if (number < 0x4000000) {
10209 this.words = [ number & 0x3ffffff ];
10210 this.length = 1;
10211 } else if (number < 0x10000000000000) {
10212 this.words = [
10213 number & 0x3ffffff,
10214 (number / 0x4000000) & 0x3ffffff
10215 ];
10216 this.length = 2;
10217 } else {
10218 assert(number < 0x20000000000000); // 2 ^ 53 (unsafe)
10219 this.words = [
10220 number & 0x3ffffff,
10221 (number / 0x4000000) & 0x3ffffff,
10222 1
10223 ];
10224 this.length = 3;
10225 }
10226
10227 if (endian !== 'le') return;
10228
10229 // Reverse the bytes
10230 this._initArray(this.toArray(), base, endian);
10231 };
10232
10233 BN.prototype._initArray = function _initArray (number, base, endian) {
10234 // Perhaps a Uint8Array
10235 assert(typeof number.length === 'number');
10236 if (number.length <= 0) {
10237 this.words = [ 0 ];
10238 this.length = 1;
10239 return this;
10240 }
10241
10242 this.length = Math.ceil(number.length / 3);
10243 this.words = new Array(this.length);
10244 for (var i = 0; i < this.length; i++) {
10245 this.words[i] = 0;
10246 }
10247
10248 var j, w;
10249 var off = 0;
10250 if (endian === 'be') {
10251 for (i = number.length - 1, j = 0; i >= 0; i -= 3) {
10252 w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16);
10253 this.words[j] |= (w << off) & 0x3ffffff;
10254 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
10255 off += 24;
10256 if (off >= 26) {
10257 off -= 26;
10258 j++;
10259 }
10260 }
10261 } else if (endian === 'le') {
10262 for (i = 0, j = 0; i < number.length; i += 3) {
10263 w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16);
10264 this.words[j] |= (w << off) & 0x3ffffff;
10265 this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff;
10266 off += 24;
10267 if (off >= 26) {
10268 off -= 26;
10269 j++;
10270 }
10271 }
10272 }
10273 return this.strip();
10274 };
10275
10276 function parseHex (str, start, end) {
10277 var r = 0;
10278 var len = Math.min(str.length, end);
10279 for (var i = start; i < len; i++) {
10280 var c = str.charCodeAt(i) - 48;
10281
10282 r <<= 4;
10283
10284 // 'a' - 'f'
10285 if (c >= 49 && c <= 54) {
10286 r |= c - 49 + 0xa;
10287
10288 // 'A' - 'F'
10289 } else if (c >= 17 && c <= 22) {
10290 r |= c - 17 + 0xa;
10291
10292 // '0' - '9'
10293 } else {
10294 r |= c & 0xf;
10295 }
10296 }
10297 return r;
10298 }
10299
10300 BN.prototype._parseHex = function _parseHex (number, start) {
10301 // Create possibly bigger array to ensure that it fits the number
10302 this.length = Math.ceil((number.length - start) / 6);
10303 this.words = new Array(this.length);
10304 for (var i = 0; i < this.length; i++) {
10305 this.words[i] = 0;
10306 }
10307
10308 var j, w;
10309 // Scan 24-bit chunks and add them to the number
10310 var off = 0;
10311 for (i = number.length - 6, j = 0; i >= start; i -= 6) {
10312 w = parseHex(number, i, i + 6);
10313 this.words[j] |= (w << off) & 0x3ffffff;
10314 // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb
10315 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
10316 off += 24;
10317 if (off >= 26) {
10318 off -= 26;
10319 j++;
10320 }
10321 }
10322 if (i + 6 !== start) {
10323 w = parseHex(number, start, i + 6);
10324 this.words[j] |= (w << off) & 0x3ffffff;
10325 this.words[j + 1] |= w >>> (26 - off) & 0x3fffff;
10326 }
10327 this.strip();
10328 };
10329
10330 function parseBase (str, start, end, mul) {
10331 var r = 0;
10332 var len = Math.min(str.length, end);
10333 for (var i = start; i < len; i++) {
10334 var c = str.charCodeAt(i) - 48;
10335
10336 r *= mul;
10337
10338 // 'a'
10339 if (c >= 49) {
10340 r += c - 49 + 0xa;
10341
10342 // 'A'
10343 } else if (c >= 17) {
10344 r += c - 17 + 0xa;
10345
10346 // '0' - '9'
10347 } else {
10348 r += c;
10349 }
10350 }
10351 return r;
10352 }
10353
10354 BN.prototype._parseBase = function _parseBase (number, base, start) {
10355 // Initialize as zero
10356 this.words = [ 0 ];
10357 this.length = 1;
10358
10359 // Find length of limb in base
10360 for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) {
10361 limbLen++;
10362 }
10363 limbLen--;
10364 limbPow = (limbPow / base) | 0;
10365
10366 var total = number.length - start;
10367 var mod = total % limbLen;
10368 var end = Math.min(total, total - mod) + start;
10369
10370 var word = 0;
10371 for (var i = start; i < end; i += limbLen) {
10372 word = parseBase(number, i, i + limbLen, base);
10373
10374 this.imuln(limbPow);
10375 if (this.words[0] + word < 0x4000000) {
10376 this.words[0] += word;
10377 } else {
10378 this._iaddn(word);
10379 }
10380 }
10381
10382 if (mod !== 0) {
10383 var pow = 1;
10384 word = parseBase(number, i, number.length, base);
10385
10386 for (i = 0; i < mod; i++) {
10387 pow *= base;
10388 }
10389
10390 this.imuln(pow);
10391 if (this.words[0] + word < 0x4000000) {
10392 this.words[0] += word;
10393 } else {
10394 this._iaddn(word);
10395 }
10396 }
10397 };
10398
10399 BN.prototype.copy = function copy (dest) {
10400 dest.words = new Array(this.length);
10401 for (var i = 0; i < this.length; i++) {
10402 dest.words[i] = this.words[i];
10403 }
10404 dest.length = this.length;
10405 dest.negative = this.negative;
10406 dest.red = this.red;
10407 };
10408
10409 BN.prototype.clone = function clone () {
10410 var r = new BN(null);
10411 this.copy(r);
10412 return r;
10413 };
10414
10415 BN.prototype._expand = function _expand (size) {
10416 while (this.length < size) {
10417 this.words[this.length++] = 0;
10418 }
10419 return this;
10420 };
10421
10422 // Remove leading `0` from `this`
10423 BN.prototype.strip = function strip () {
10424 while (this.length > 1 && this.words[this.length - 1] === 0) {
10425 this.length--;
10426 }
10427 return this._normSign();
10428 };
10429
10430 BN.prototype._normSign = function _normSign () {
10431 // -0 = 0
10432 if (this.length === 1 && this.words[0] === 0) {
10433 this.negative = 0;
10434 }
10435 return this;
10436 };
10437
10438 BN.prototype.inspect = function inspect () {
10439 return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
10440 };
10441
10442 /*
10443
10444 var zeros = [];
10445 var groupSizes = [];
10446 var groupBases = [];
10447
10448 var s = '';
10449 var i = -1;
10450 while (++i < BN.wordSize) {
10451 zeros[i] = s;
10452 s += '0';
10453 }
10454 groupSizes[0] = 0;
10455 groupSizes[1] = 0;
10456 groupBases[0] = 0;
10457 groupBases[1] = 0;
10458 var base = 2 - 1;
10459 while (++base < 36 + 1) {
10460 var groupSize = 0;
10461 var groupBase = 1;
10462 while (groupBase < (1 << BN.wordSize) / base) {
10463 groupBase *= base;
10464 groupSize += 1;
10465 }
10466 groupSizes[base] = groupSize;
10467 groupBases[base] = groupBase;
10468 }
10469
10470 */
10471
10472 var zeros = [
10473 '',
10474 '0',
10475 '00',
10476 '000',
10477 '0000',
10478 '00000',
10479 '000000',
10480 '0000000',
10481 '00000000',
10482 '000000000',
10483 '0000000000',
10484 '00000000000',
10485 '000000000000',
10486 '0000000000000',
10487 '00000000000000',
10488 '000000000000000',
10489 '0000000000000000',
10490 '00000000000000000',
10491 '000000000000000000',
10492 '0000000000000000000',
10493 '00000000000000000000',
10494 '000000000000000000000',
10495 '0000000000000000000000',
10496 '00000000000000000000000',
10497 '000000000000000000000000',
10498 '0000000000000000000000000'
10499 ];
10500
10501 var groupSizes = [
10502 0, 0,
10503 25, 16, 12, 11, 10, 9, 8,
10504 8, 7, 7, 7, 7, 6, 6,
10505 6, 6, 6, 6, 6, 5, 5,
10506 5, 5, 5, 5, 5, 5, 5,
10507 5, 5, 5, 5, 5, 5, 5
10508 ];
10509
10510 var groupBases = [
10511 0, 0,
10512 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216,
10513 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625,
10514 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632,
10515 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149,
10516 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176
10517 ];
10518
10519 BN.prototype.toString = function toString (base, padding) {
10520 base = base || 10;
10521 padding = padding | 0 || 1;
10522
10523 var out;
10524 if (base === 16 || base === 'hex') {
10525 out = '';
10526 var off = 0;
10527 var carry = 0;
10528 for (var i = 0; i < this.length; i++) {
10529 var w = this.words[i];
10530 var word = (((w << off) | carry) & 0xffffff).toString(16);
10531 carry = (w >>> (24 - off)) & 0xffffff;
10532 if (carry !== 0 || i !== this.length - 1) {
10533 out = zeros[6 - word.length] + word + out;
10534 } else {
10535 out = word + out;
10536 }
10537 off += 2;
10538 if (off >= 26) {
10539 off -= 26;
10540 i--;
10541 }
10542 }
10543 if (carry !== 0) {
10544 out = carry.toString(16) + out;
10545 }
10546 while (out.length % padding !== 0) {
10547 out = '0' + out;
10548 }
10549 if (this.negative !== 0) {
10550 out = '-' + out;
10551 }
10552 return out;
10553 }
10554
10555 if (base === (base | 0) && base >= 2 && base <= 36) {
10556 // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base));
10557 var groupSize = groupSizes[base];
10558 // var groupBase = Math.pow(base, groupSize);
10559 var groupBase = groupBases[base];
10560 out = '';
10561 var c = this.clone();
10562 c.negative = 0;
10563 while (!c.isZero()) {
10564 var r = c.modn(groupBase).toString(base);
10565 c = c.idivn(groupBase);
10566
10567 if (!c.isZero()) {
10568 out = zeros[groupSize - r.length] + r + out;
10569 } else {
10570 out = r + out;
10571 }
10572 }
10573 if (this.isZero()) {
10574 out = '0' + out;
10575 }
10576 while (out.length % padding !== 0) {
10577 out = '0' + out;
10578 }
10579 if (this.negative !== 0) {
10580 out = '-' + out;
10581 }
10582 return out;
10583 }
10584
10585 assert(false, 'Base should be between 2 and 36');
10586 };
10587
10588 BN.prototype.toNumber = function toNumber () {
10589 var ret = this.words[0];
10590 if (this.length === 2) {
10591 ret += this.words[1] * 0x4000000;
10592 } else if (this.length === 3 && this.words[2] === 0x01) {
10593 // NOTE: at this stage it is known that the top bit is set
10594 ret += 0x10000000000000 + (this.words[1] * 0x4000000);
10595 } else if (this.length > 2) {
10596 assert(false, 'Number can only safely store up to 53 bits');
10597 }
10598 return (this.negative !== 0) ? -ret : ret;
10599 };
10600
10601 BN.prototype.toJSON = function toJSON () {
10602 return this.toString(16);
10603 };
10604
10605 BN.prototype.toBuffer = function toBuffer (endian, length) {
10606 assert(typeof Buffer !== 'undefined');
10607 return this.toArrayLike(Buffer, endian, length);
10608 };
10609
10610 BN.prototype.toArray = function toArray (endian, length) {
10611 return this.toArrayLike(Array, endian, length);
10612 };
10613
10614 BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) {
10615 var byteLength = this.byteLength();
10616 var reqLength = length || Math.max(1, byteLength);
10617 assert(byteLength <= reqLength, 'byte array longer than desired length');
10618 assert(reqLength > 0, 'Requested array length <= 0');
10619
10620 this.strip();
10621 var littleEndian = endian === 'le';
10622 var res = new ArrayType(reqLength);
10623
10624 var b, i;
10625 var q = this.clone();
10626 if (!littleEndian) {
10627 // Assume big-endian
10628 for (i = 0; i < reqLength - byteLength; i++) {
10629 res[i] = 0;
10630 }
10631
10632 for (i = 0; !q.isZero(); i++) {
10633 b = q.andln(0xff);
10634 q.iushrn(8);
10635
10636 res[reqLength - i - 1] = b;
10637 }
10638 } else {
10639 for (i = 0; !q.isZero(); i++) {
10640 b = q.andln(0xff);
10641 q.iushrn(8);
10642
10643 res[i] = b;
10644 }
10645
10646 for (; i < reqLength; i++) {
10647 res[i] = 0;
10648 }
10649 }
10650
10651 return res;
10652 };
10653
10654 if (Math.clz32) {
10655 BN.prototype._countBits = function _countBits (w) {
10656 return 32 - Math.clz32(w);
10657 };
10658 } else {
10659 BN.prototype._countBits = function _countBits (w) {
10660 var t = w;
10661 var r = 0;
10662 if (t >= 0x1000) {
10663 r += 13;
10664 t >>>= 13;
10665 }
10666 if (t >= 0x40) {
10667 r += 7;
10668 t >>>= 7;
10669 }
10670 if (t >= 0x8) {
10671 r += 4;
10672 t >>>= 4;
10673 }
10674 if (t >= 0x02) {
10675 r += 2;
10676 t >>>= 2;
10677 }
10678 return r + t;
10679 };
10680 }
10681
10682 BN.prototype._zeroBits = function _zeroBits (w) {
10683 // Short-cut
10684 if (w === 0) return 26;
10685
10686 var t = w;
10687 var r = 0;
10688 if ((t & 0x1fff) === 0) {
10689 r += 13;
10690 t >>>= 13;
10691 }
10692 if ((t & 0x7f) === 0) {
10693 r += 7;
10694 t >>>= 7;
10695 }
10696 if ((t & 0xf) === 0) {
10697 r += 4;
10698 t >>>= 4;
10699 }
10700 if ((t & 0x3) === 0) {
10701 r += 2;
10702 t >>>= 2;
10703 }
10704 if ((t & 0x1) === 0) {
10705 r++;
10706 }
10707 return r;
10708 };
10709
10710 // Return number of used bits in a BN
10711 BN.prototype.bitLength = function bitLength () {
10712 var w = this.words[this.length - 1];
10713 var hi = this._countBits(w);
10714 return (this.length - 1) * 26 + hi;
10715 };
10716
10717 function toBitArray (num) {
10718 var w = new Array(num.bitLength());
10719
10720 for (var bit = 0; bit < w.length; bit++) {
10721 var off = (bit / 26) | 0;
10722 var wbit = bit % 26;
10723
10724 w[bit] = (num.words[off] & (1 << wbit)) >>> wbit;
10725 }
10726
10727 return w;
10728 }
10729
10730 // Number of trailing zero bits
10731 BN.prototype.zeroBits = function zeroBits () {
10732 if (this.isZero()) return 0;
10733
10734 var r = 0;
10735 for (var i = 0; i < this.length; i++) {
10736 var b = this._zeroBits(this.words[i]);
10737 r += b;
10738 if (b !== 26) break;
10739 }
10740 return r;
10741 };
10742
10743 BN.prototype.byteLength = function byteLength () {
10744 return Math.ceil(this.bitLength() / 8);
10745 };
10746
10747 BN.prototype.toTwos = function toTwos (width) {
10748 if (this.negative !== 0) {
10749 return this.abs().inotn(width).iaddn(1);
10750 }
10751 return this.clone();
10752 };
10753
10754 BN.prototype.fromTwos = function fromTwos (width) {
10755 if (this.testn(width - 1)) {
10756 return this.notn(width).iaddn(1).ineg();
10757 }
10758 return this.clone();
10759 };
10760
10761 BN.prototype.isNeg = function isNeg () {
10762 return this.negative !== 0;
10763 };
10764
10765 // Return negative clone of `this`
10766 BN.prototype.neg = function neg () {
10767 return this.clone().ineg();
10768 };
10769
10770 BN.prototype.ineg = function ineg () {
10771 if (!this.isZero()) {
10772 this.negative ^= 1;
10773 }
10774
10775 return this;
10776 };
10777
10778 // Or `num` with `this` in-place
10779 BN.prototype.iuor = function iuor (num) {
10780 while (this.length < num.length) {
10781 this.words[this.length++] = 0;
10782 }
10783
10784 for (var i = 0; i < num.length; i++) {
10785 this.words[i] = this.words[i] | num.words[i];
10786 }
10787
10788 return this.strip();
10789 };
10790
10791 BN.prototype.ior = function ior (num) {
10792 assert((this.negative | num.negative) === 0);
10793 return this.iuor(num);
10794 };
10795
10796 // Or `num` with `this`
10797 BN.prototype.or = function or (num) {
10798 if (this.length > num.length) return this.clone().ior(num);
10799 return num.clone().ior(this);
10800 };
10801
10802 BN.prototype.uor = function uor (num) {
10803 if (this.length > num.length) return this.clone().iuor(num);
10804 return num.clone().iuor(this);
10805 };
10806
10807 // And `num` with `this` in-place
10808 BN.prototype.iuand = function iuand (num) {
10809 // b = min-length(num, this)
10810 var b;
10811 if (this.length > num.length) {
10812 b = num;
10813 } else {
10814 b = this;
10815 }
10816
10817 for (var i = 0; i < b.length; i++) {
10818 this.words[i] = this.words[i] & num.words[i];
10819 }
10820
10821 this.length = b.length;
10822
10823 return this.strip();
10824 };
10825
10826 BN.prototype.iand = function iand (num) {
10827 assert((this.negative | num.negative) === 0);
10828 return this.iuand(num);
10829 };
10830
10831 // And `num` with `this`
10832 BN.prototype.and = function and (num) {
10833 if (this.length > num.length) return this.clone().iand(num);
10834 return num.clone().iand(this);
10835 };
10836
10837 BN.prototype.uand = function uand (num) {
10838 if (this.length > num.length) return this.clone().iuand(num);
10839 return num.clone().iuand(this);
10840 };
10841
10842 // Xor `num` with `this` in-place
10843 BN.prototype.iuxor = function iuxor (num) {
10844 // a.length > b.length
10845 var a;
10846 var b;
10847 if (this.length > num.length) {
10848 a = this;
10849 b = num;
10850 } else {
10851 a = num;
10852 b = this;
10853 }
10854
10855 for (var i = 0; i < b.length; i++) {
10856 this.words[i] = a.words[i] ^ b.words[i];
10857 }
10858
10859 if (this !== a) {
10860 for (; i < a.length; i++) {
10861 this.words[i] = a.words[i];
10862 }
10863 }
10864
10865 this.length = a.length;
10866
10867 return this.strip();
10868 };
10869
10870 BN.prototype.ixor = function ixor (num) {
10871 assert((this.negative | num.negative) === 0);
10872 return this.iuxor(num);
10873 };
10874
10875 // Xor `num` with `this`
10876 BN.prototype.xor = function xor (num) {
10877 if (this.length > num.length) return this.clone().ixor(num);
10878 return num.clone().ixor(this);
10879 };
10880
10881 BN.prototype.uxor = function uxor (num) {
10882 if (this.length > num.length) return this.clone().iuxor(num);
10883 return num.clone().iuxor(this);
10884 };
10885
10886 // Not ``this`` with ``width`` bitwidth
10887 BN.prototype.inotn = function inotn (width) {
10888 assert(typeof width === 'number' && width >= 0);
10889
10890 var bytesNeeded = Math.ceil(width / 26) | 0;
10891 var bitsLeft = width % 26;
10892
10893 // Extend the buffer with leading zeroes
10894 this._expand(bytesNeeded);
10895
10896 if (bitsLeft > 0) {
10897 bytesNeeded--;
10898 }
10899
10900 // Handle complete words
10901 for (var i = 0; i < bytesNeeded; i++) {
10902 this.words[i] = ~this.words[i] & 0x3ffffff;
10903 }
10904
10905 // Handle the residue
10906 if (bitsLeft > 0) {
10907 this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft));
10908 }
10909
10910 // And remove leading zeroes
10911 return this.strip();
10912 };
10913
10914 BN.prototype.notn = function notn (width) {
10915 return this.clone().inotn(width);
10916 };
10917
10918 // Set `bit` of `this`
10919 BN.prototype.setn = function setn (bit, val) {
10920 assert(typeof bit === 'number' && bit >= 0);
10921
10922 var off = (bit / 26) | 0;
10923 var wbit = bit % 26;
10924
10925 this._expand(off + 1);
10926
10927 if (val) {
10928 this.words[off] = this.words[off] | (1 << wbit);
10929 } else {
10930 this.words[off] = this.words[off] & ~(1 << wbit);
10931 }
10932
10933 return this.strip();
10934 };
10935
10936 // Add `num` to `this` in-place
10937 BN.prototype.iadd = function iadd (num) {
10938 var r;
10939
10940 // negative + positive
10941 if (this.negative !== 0 && num.negative === 0) {
10942 this.negative = 0;
10943 r = this.isub(num);
10944 this.negative ^= 1;
10945 return this._normSign();
10946
10947 // positive + negative
10948 } else if (this.negative === 0 && num.negative !== 0) {
10949 num.negative = 0;
10950 r = this.isub(num);
10951 num.negative = 1;
10952 return r._normSign();
10953 }
10954
10955 // a.length > b.length
10956 var a, b;
10957 if (this.length > num.length) {
10958 a = this;
10959 b = num;
10960 } else {
10961 a = num;
10962 b = this;
10963 }
10964
10965 var carry = 0;
10966 for (var i = 0; i < b.length; i++) {
10967 r = (a.words[i] | 0) + (b.words[i] | 0) + carry;
10968 this.words[i] = r & 0x3ffffff;
10969 carry = r >>> 26;
10970 }
10971 for (; carry !== 0 && i < a.length; i++) {
10972 r = (a.words[i] | 0) + carry;
10973 this.words[i] = r & 0x3ffffff;
10974 carry = r >>> 26;
10975 }
10976
10977 this.length = a.length;
10978 if (carry !== 0) {
10979 this.words[this.length] = carry;
10980 this.length++;
10981 // Copy the rest of the words
10982 } else if (a !== this) {
10983 for (; i < a.length; i++) {
10984 this.words[i] = a.words[i];
10985 }
10986 }
10987
10988 return this;
10989 };
10990
10991 // Add `num` to `this`
10992 BN.prototype.add = function add (num) {
10993 var res;
10994 if (num.negative !== 0 && this.negative === 0) {
10995 num.negative = 0;
10996 res = this.sub(num);
10997 num.negative ^= 1;
10998 return res;
10999 } else if (num.negative === 0 && this.negative !== 0) {
11000 this.negative = 0;
11001 res = num.sub(this);
11002 this.negative = 1;
11003 return res;
11004 }
11005
11006 if (this.length > num.length) return this.clone().iadd(num);
11007
11008 return num.clone().iadd(this);
11009 };
11010
11011 // Subtract `num` from `this` in-place
11012 BN.prototype.isub = function isub (num) {
11013 // this - (-num) = this + num
11014 if (num.negative !== 0) {
11015 num.negative = 0;
11016 var r = this.iadd(num);
11017 num.negative = 1;
11018 return r._normSign();
11019
11020 // -this - num = -(this + num)
11021 } else if (this.negative !== 0) {
11022 this.negative = 0;
11023 this.iadd(num);
11024 this.negative = 1;
11025 return this._normSign();
11026 }
11027
11028 // At this point both numbers are positive
11029 var cmp = this.cmp(num);
11030
11031 // Optimization - zeroify
11032 if (cmp === 0) {
11033 this.negative = 0;
11034 this.length = 1;
11035 this.words[0] = 0;
11036 return this;
11037 }
11038
11039 // a > b
11040 var a, b;
11041 if (cmp > 0) {
11042 a = this;
11043 b = num;
11044 } else {
11045 a = num;
11046 b = this;
11047 }
11048
11049 var carry = 0;
11050 for (var i = 0; i < b.length; i++) {
11051 r = (a.words[i] | 0) - (b.words[i] | 0) + carry;
11052 carry = r >> 26;
11053 this.words[i] = r & 0x3ffffff;
11054 }
11055 for (; carry !== 0 && i < a.length; i++) {
11056 r = (a.words[i] | 0) + carry;
11057 carry = r >> 26;
11058 this.words[i] = r & 0x3ffffff;
11059 }
11060
11061 // Copy rest of the words
11062 if (carry === 0 && i < a.length && a !== this) {
11063 for (; i < a.length; i++) {
11064 this.words[i] = a.words[i];
11065 }
11066 }
11067
11068 this.length = Math.max(this.length, i);
11069
11070 if (a !== this) {
11071 this.negative = 1;
11072 }
11073
11074 return this.strip();
11075 };
11076
11077 // Subtract `num` from `this`
11078 BN.prototype.sub = function sub (num) {
11079 return this.clone().isub(num);
11080 };
11081
11082 function smallMulTo (self, num, out) {
11083 out.negative = num.negative ^ self.negative;
11084 var len = (self.length + num.length) | 0;
11085 out.length = len;
11086 len = (len - 1) | 0;
11087
11088 // Peel one iteration (compiler can't do it, because of code complexity)
11089 var a = self.words[0] | 0;
11090 var b = num.words[0] | 0;
11091 var r = a * b;
11092
11093 var lo = r & 0x3ffffff;
11094 var carry = (r / 0x4000000) | 0;
11095 out.words[0] = lo;
11096
11097 for (var k = 1; k < len; k++) {
11098 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
11099 // note that ncarry could be >= 0x3ffffff
11100 var ncarry = carry >>> 26;
11101 var rword = carry & 0x3ffffff;
11102 var maxJ = Math.min(k, num.length - 1);
11103 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
11104 var i = (k - j) | 0;
11105 a = self.words[i] | 0;
11106 b = num.words[j] | 0;
11107 r = a * b + rword;
11108 ncarry += (r / 0x4000000) | 0;
11109 rword = r & 0x3ffffff;
11110 }
11111 out.words[k] = rword | 0;
11112 carry = ncarry | 0;
11113 }
11114 if (carry !== 0) {
11115 out.words[k] = carry | 0;
11116 } else {
11117 out.length--;
11118 }
11119
11120 return out.strip();
11121 }
11122
11123 // TODO(indutny): it may be reasonable to omit it for users who don't need
11124 // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit
11125 // multiplication (like elliptic secp256k1).
11126 var comb10MulTo = function comb10MulTo (self, num, out) {
11127 var a = self.words;
11128 var b = num.words;
11129 var o = out.words;
11130 var c = 0;
11131 var lo;
11132 var mid;
11133 var hi;
11134 var a0 = a[0] | 0;
11135 var al0 = a0 & 0x1fff;
11136 var ah0 = a0 >>> 13;
11137 var a1 = a[1] | 0;
11138 var al1 = a1 & 0x1fff;
11139 var ah1 = a1 >>> 13;
11140 var a2 = a[2] | 0;
11141 var al2 = a2 & 0x1fff;
11142 var ah2 = a2 >>> 13;
11143 var a3 = a[3] | 0;
11144 var al3 = a3 & 0x1fff;
11145 var ah3 = a3 >>> 13;
11146 var a4 = a[4] | 0;
11147 var al4 = a4 & 0x1fff;
11148 var ah4 = a4 >>> 13;
11149 var a5 = a[5] | 0;
11150 var al5 = a5 & 0x1fff;
11151 var ah5 = a5 >>> 13;
11152 var a6 = a[6] | 0;
11153 var al6 = a6 & 0x1fff;
11154 var ah6 = a6 >>> 13;
11155 var a7 = a[7] | 0;
11156 var al7 = a7 & 0x1fff;
11157 var ah7 = a7 >>> 13;
11158 var a8 = a[8] | 0;
11159 var al8 = a8 & 0x1fff;
11160 var ah8 = a8 >>> 13;
11161 var a9 = a[9] | 0;
11162 var al9 = a9 & 0x1fff;
11163 var ah9 = a9 >>> 13;
11164 var b0 = b[0] | 0;
11165 var bl0 = b0 & 0x1fff;
11166 var bh0 = b0 >>> 13;
11167 var b1 = b[1] | 0;
11168 var bl1 = b1 & 0x1fff;
11169 var bh1 = b1 >>> 13;
11170 var b2 = b[2] | 0;
11171 var bl2 = b2 & 0x1fff;
11172 var bh2 = b2 >>> 13;
11173 var b3 = b[3] | 0;
11174 var bl3 = b3 & 0x1fff;
11175 var bh3 = b3 >>> 13;
11176 var b4 = b[4] | 0;
11177 var bl4 = b4 & 0x1fff;
11178 var bh4 = b4 >>> 13;
11179 var b5 = b[5] | 0;
11180 var bl5 = b5 & 0x1fff;
11181 var bh5 = b5 >>> 13;
11182 var b6 = b[6] | 0;
11183 var bl6 = b6 & 0x1fff;
11184 var bh6 = b6 >>> 13;
11185 var b7 = b[7] | 0;
11186 var bl7 = b7 & 0x1fff;
11187 var bh7 = b7 >>> 13;
11188 var b8 = b[8] | 0;
11189 var bl8 = b8 & 0x1fff;
11190 var bh8 = b8 >>> 13;
11191 var b9 = b[9] | 0;
11192 var bl9 = b9 & 0x1fff;
11193 var bh9 = b9 >>> 13;
11194
11195 out.negative = self.negative ^ num.negative;
11196 out.length = 19;
11197 /* k = 0 */
11198 lo = Math.imul(al0, bl0);
11199 mid = Math.imul(al0, bh0);
11200 mid = (mid + Math.imul(ah0, bl0)) | 0;
11201 hi = Math.imul(ah0, bh0);
11202 var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11203 c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0;
11204 w0 &= 0x3ffffff;
11205 /* k = 1 */
11206 lo = Math.imul(al1, bl0);
11207 mid = Math.imul(al1, bh0);
11208 mid = (mid + Math.imul(ah1, bl0)) | 0;
11209 hi = Math.imul(ah1, bh0);
11210 lo = (lo + Math.imul(al0, bl1)) | 0;
11211 mid = (mid + Math.imul(al0, bh1)) | 0;
11212 mid = (mid + Math.imul(ah0, bl1)) | 0;
11213 hi = (hi + Math.imul(ah0, bh1)) | 0;
11214 var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11215 c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0;
11216 w1 &= 0x3ffffff;
11217 /* k = 2 */
11218 lo = Math.imul(al2, bl0);
11219 mid = Math.imul(al2, bh0);
11220 mid = (mid + Math.imul(ah2, bl0)) | 0;
11221 hi = Math.imul(ah2, bh0);
11222 lo = (lo + Math.imul(al1, bl1)) | 0;
11223 mid = (mid + Math.imul(al1, bh1)) | 0;
11224 mid = (mid + Math.imul(ah1, bl1)) | 0;
11225 hi = (hi + Math.imul(ah1, bh1)) | 0;
11226 lo = (lo + Math.imul(al0, bl2)) | 0;
11227 mid = (mid + Math.imul(al0, bh2)) | 0;
11228 mid = (mid + Math.imul(ah0, bl2)) | 0;
11229 hi = (hi + Math.imul(ah0, bh2)) | 0;
11230 var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11231 c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0;
11232 w2 &= 0x3ffffff;
11233 /* k = 3 */
11234 lo = Math.imul(al3, bl0);
11235 mid = Math.imul(al3, bh0);
11236 mid = (mid + Math.imul(ah3, bl0)) | 0;
11237 hi = Math.imul(ah3, bh0);
11238 lo = (lo + Math.imul(al2, bl1)) | 0;
11239 mid = (mid + Math.imul(al2, bh1)) | 0;
11240 mid = (mid + Math.imul(ah2, bl1)) | 0;
11241 hi = (hi + Math.imul(ah2, bh1)) | 0;
11242 lo = (lo + Math.imul(al1, bl2)) | 0;
11243 mid = (mid + Math.imul(al1, bh2)) | 0;
11244 mid = (mid + Math.imul(ah1, bl2)) | 0;
11245 hi = (hi + Math.imul(ah1, bh2)) | 0;
11246 lo = (lo + Math.imul(al0, bl3)) | 0;
11247 mid = (mid + Math.imul(al0, bh3)) | 0;
11248 mid = (mid + Math.imul(ah0, bl3)) | 0;
11249 hi = (hi + Math.imul(ah0, bh3)) | 0;
11250 var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11251 c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0;
11252 w3 &= 0x3ffffff;
11253 /* k = 4 */
11254 lo = Math.imul(al4, bl0);
11255 mid = Math.imul(al4, bh0);
11256 mid = (mid + Math.imul(ah4, bl0)) | 0;
11257 hi = Math.imul(ah4, bh0);
11258 lo = (lo + Math.imul(al3, bl1)) | 0;
11259 mid = (mid + Math.imul(al3, bh1)) | 0;
11260 mid = (mid + Math.imul(ah3, bl1)) | 0;
11261 hi = (hi + Math.imul(ah3, bh1)) | 0;
11262 lo = (lo + Math.imul(al2, bl2)) | 0;
11263 mid = (mid + Math.imul(al2, bh2)) | 0;
11264 mid = (mid + Math.imul(ah2, bl2)) | 0;
11265 hi = (hi + Math.imul(ah2, bh2)) | 0;
11266 lo = (lo + Math.imul(al1, bl3)) | 0;
11267 mid = (mid + Math.imul(al1, bh3)) | 0;
11268 mid = (mid + Math.imul(ah1, bl3)) | 0;
11269 hi = (hi + Math.imul(ah1, bh3)) | 0;
11270 lo = (lo + Math.imul(al0, bl4)) | 0;
11271 mid = (mid + Math.imul(al0, bh4)) | 0;
11272 mid = (mid + Math.imul(ah0, bl4)) | 0;
11273 hi = (hi + Math.imul(ah0, bh4)) | 0;
11274 var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11275 c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0;
11276 w4 &= 0x3ffffff;
11277 /* k = 5 */
11278 lo = Math.imul(al5, bl0);
11279 mid = Math.imul(al5, bh0);
11280 mid = (mid + Math.imul(ah5, bl0)) | 0;
11281 hi = Math.imul(ah5, bh0);
11282 lo = (lo + Math.imul(al4, bl1)) | 0;
11283 mid = (mid + Math.imul(al4, bh1)) | 0;
11284 mid = (mid + Math.imul(ah4, bl1)) | 0;
11285 hi = (hi + Math.imul(ah4, bh1)) | 0;
11286 lo = (lo + Math.imul(al3, bl2)) | 0;
11287 mid = (mid + Math.imul(al3, bh2)) | 0;
11288 mid = (mid + Math.imul(ah3, bl2)) | 0;
11289 hi = (hi + Math.imul(ah3, bh2)) | 0;
11290 lo = (lo + Math.imul(al2, bl3)) | 0;
11291 mid = (mid + Math.imul(al2, bh3)) | 0;
11292 mid = (mid + Math.imul(ah2, bl3)) | 0;
11293 hi = (hi + Math.imul(ah2, bh3)) | 0;
11294 lo = (lo + Math.imul(al1, bl4)) | 0;
11295 mid = (mid + Math.imul(al1, bh4)) | 0;
11296 mid = (mid + Math.imul(ah1, bl4)) | 0;
11297 hi = (hi + Math.imul(ah1, bh4)) | 0;
11298 lo = (lo + Math.imul(al0, bl5)) | 0;
11299 mid = (mid + Math.imul(al0, bh5)) | 0;
11300 mid = (mid + Math.imul(ah0, bl5)) | 0;
11301 hi = (hi + Math.imul(ah0, bh5)) | 0;
11302 var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11303 c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0;
11304 w5 &= 0x3ffffff;
11305 /* k = 6 */
11306 lo = Math.imul(al6, bl0);
11307 mid = Math.imul(al6, bh0);
11308 mid = (mid + Math.imul(ah6, bl0)) | 0;
11309 hi = Math.imul(ah6, bh0);
11310 lo = (lo + Math.imul(al5, bl1)) | 0;
11311 mid = (mid + Math.imul(al5, bh1)) | 0;
11312 mid = (mid + Math.imul(ah5, bl1)) | 0;
11313 hi = (hi + Math.imul(ah5, bh1)) | 0;
11314 lo = (lo + Math.imul(al4, bl2)) | 0;
11315 mid = (mid + Math.imul(al4, bh2)) | 0;
11316 mid = (mid + Math.imul(ah4, bl2)) | 0;
11317 hi = (hi + Math.imul(ah4, bh2)) | 0;
11318 lo = (lo + Math.imul(al3, bl3)) | 0;
11319 mid = (mid + Math.imul(al3, bh3)) | 0;
11320 mid = (mid + Math.imul(ah3, bl3)) | 0;
11321 hi = (hi + Math.imul(ah3, bh3)) | 0;
11322 lo = (lo + Math.imul(al2, bl4)) | 0;
11323 mid = (mid + Math.imul(al2, bh4)) | 0;
11324 mid = (mid + Math.imul(ah2, bl4)) | 0;
11325 hi = (hi + Math.imul(ah2, bh4)) | 0;
11326 lo = (lo + Math.imul(al1, bl5)) | 0;
11327 mid = (mid + Math.imul(al1, bh5)) | 0;
11328 mid = (mid + Math.imul(ah1, bl5)) | 0;
11329 hi = (hi + Math.imul(ah1, bh5)) | 0;
11330 lo = (lo + Math.imul(al0, bl6)) | 0;
11331 mid = (mid + Math.imul(al0, bh6)) | 0;
11332 mid = (mid + Math.imul(ah0, bl6)) | 0;
11333 hi = (hi + Math.imul(ah0, bh6)) | 0;
11334 var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11335 c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0;
11336 w6 &= 0x3ffffff;
11337 /* k = 7 */
11338 lo = Math.imul(al7, bl0);
11339 mid = Math.imul(al7, bh0);
11340 mid = (mid + Math.imul(ah7, bl0)) | 0;
11341 hi = Math.imul(ah7, bh0);
11342 lo = (lo + Math.imul(al6, bl1)) | 0;
11343 mid = (mid + Math.imul(al6, bh1)) | 0;
11344 mid = (mid + Math.imul(ah6, bl1)) | 0;
11345 hi = (hi + Math.imul(ah6, bh1)) | 0;
11346 lo = (lo + Math.imul(al5, bl2)) | 0;
11347 mid = (mid + Math.imul(al5, bh2)) | 0;
11348 mid = (mid + Math.imul(ah5, bl2)) | 0;
11349 hi = (hi + Math.imul(ah5, bh2)) | 0;
11350 lo = (lo + Math.imul(al4, bl3)) | 0;
11351 mid = (mid + Math.imul(al4, bh3)) | 0;
11352 mid = (mid + Math.imul(ah4, bl3)) | 0;
11353 hi = (hi + Math.imul(ah4, bh3)) | 0;
11354 lo = (lo + Math.imul(al3, bl4)) | 0;
11355 mid = (mid + Math.imul(al3, bh4)) | 0;
11356 mid = (mid + Math.imul(ah3, bl4)) | 0;
11357 hi = (hi + Math.imul(ah3, bh4)) | 0;
11358 lo = (lo + Math.imul(al2, bl5)) | 0;
11359 mid = (mid + Math.imul(al2, bh5)) | 0;
11360 mid = (mid + Math.imul(ah2, bl5)) | 0;
11361 hi = (hi + Math.imul(ah2, bh5)) | 0;
11362 lo = (lo + Math.imul(al1, bl6)) | 0;
11363 mid = (mid + Math.imul(al1, bh6)) | 0;
11364 mid = (mid + Math.imul(ah1, bl6)) | 0;
11365 hi = (hi + Math.imul(ah1, bh6)) | 0;
11366 lo = (lo + Math.imul(al0, bl7)) | 0;
11367 mid = (mid + Math.imul(al0, bh7)) | 0;
11368 mid = (mid + Math.imul(ah0, bl7)) | 0;
11369 hi = (hi + Math.imul(ah0, bh7)) | 0;
11370 var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11371 c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0;
11372 w7 &= 0x3ffffff;
11373 /* k = 8 */
11374 lo = Math.imul(al8, bl0);
11375 mid = Math.imul(al8, bh0);
11376 mid = (mid + Math.imul(ah8, bl0)) | 0;
11377 hi = Math.imul(ah8, bh0);
11378 lo = (lo + Math.imul(al7, bl1)) | 0;
11379 mid = (mid + Math.imul(al7, bh1)) | 0;
11380 mid = (mid + Math.imul(ah7, bl1)) | 0;
11381 hi = (hi + Math.imul(ah7, bh1)) | 0;
11382 lo = (lo + Math.imul(al6, bl2)) | 0;
11383 mid = (mid + Math.imul(al6, bh2)) | 0;
11384 mid = (mid + Math.imul(ah6, bl2)) | 0;
11385 hi = (hi + Math.imul(ah6, bh2)) | 0;
11386 lo = (lo + Math.imul(al5, bl3)) | 0;
11387 mid = (mid + Math.imul(al5, bh3)) | 0;
11388 mid = (mid + Math.imul(ah5, bl3)) | 0;
11389 hi = (hi + Math.imul(ah5, bh3)) | 0;
11390 lo = (lo + Math.imul(al4, bl4)) | 0;
11391 mid = (mid + Math.imul(al4, bh4)) | 0;
11392 mid = (mid + Math.imul(ah4, bl4)) | 0;
11393 hi = (hi + Math.imul(ah4, bh4)) | 0;
11394 lo = (lo + Math.imul(al3, bl5)) | 0;
11395 mid = (mid + Math.imul(al3, bh5)) | 0;
11396 mid = (mid + Math.imul(ah3, bl5)) | 0;
11397 hi = (hi + Math.imul(ah3, bh5)) | 0;
11398 lo = (lo + Math.imul(al2, bl6)) | 0;
11399 mid = (mid + Math.imul(al2, bh6)) | 0;
11400 mid = (mid + Math.imul(ah2, bl6)) | 0;
11401 hi = (hi + Math.imul(ah2, bh6)) | 0;
11402 lo = (lo + Math.imul(al1, bl7)) | 0;
11403 mid = (mid + Math.imul(al1, bh7)) | 0;
11404 mid = (mid + Math.imul(ah1, bl7)) | 0;
11405 hi = (hi + Math.imul(ah1, bh7)) | 0;
11406 lo = (lo + Math.imul(al0, bl8)) | 0;
11407 mid = (mid + Math.imul(al0, bh8)) | 0;
11408 mid = (mid + Math.imul(ah0, bl8)) | 0;
11409 hi = (hi + Math.imul(ah0, bh8)) | 0;
11410 var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11411 c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0;
11412 w8 &= 0x3ffffff;
11413 /* k = 9 */
11414 lo = Math.imul(al9, bl0);
11415 mid = Math.imul(al9, bh0);
11416 mid = (mid + Math.imul(ah9, bl0)) | 0;
11417 hi = Math.imul(ah9, bh0);
11418 lo = (lo + Math.imul(al8, bl1)) | 0;
11419 mid = (mid + Math.imul(al8, bh1)) | 0;
11420 mid = (mid + Math.imul(ah8, bl1)) | 0;
11421 hi = (hi + Math.imul(ah8, bh1)) | 0;
11422 lo = (lo + Math.imul(al7, bl2)) | 0;
11423 mid = (mid + Math.imul(al7, bh2)) | 0;
11424 mid = (mid + Math.imul(ah7, bl2)) | 0;
11425 hi = (hi + Math.imul(ah7, bh2)) | 0;
11426 lo = (lo + Math.imul(al6, bl3)) | 0;
11427 mid = (mid + Math.imul(al6, bh3)) | 0;
11428 mid = (mid + Math.imul(ah6, bl3)) | 0;
11429 hi = (hi + Math.imul(ah6, bh3)) | 0;
11430 lo = (lo + Math.imul(al5, bl4)) | 0;
11431 mid = (mid + Math.imul(al5, bh4)) | 0;
11432 mid = (mid + Math.imul(ah5, bl4)) | 0;
11433 hi = (hi + Math.imul(ah5, bh4)) | 0;
11434 lo = (lo + Math.imul(al4, bl5)) | 0;
11435 mid = (mid + Math.imul(al4, bh5)) | 0;
11436 mid = (mid + Math.imul(ah4, bl5)) | 0;
11437 hi = (hi + Math.imul(ah4, bh5)) | 0;
11438 lo = (lo + Math.imul(al3, bl6)) | 0;
11439 mid = (mid + Math.imul(al3, bh6)) | 0;
11440 mid = (mid + Math.imul(ah3, bl6)) | 0;
11441 hi = (hi + Math.imul(ah3, bh6)) | 0;
11442 lo = (lo + Math.imul(al2, bl7)) | 0;
11443 mid = (mid + Math.imul(al2, bh7)) | 0;
11444 mid = (mid + Math.imul(ah2, bl7)) | 0;
11445 hi = (hi + Math.imul(ah2, bh7)) | 0;
11446 lo = (lo + Math.imul(al1, bl8)) | 0;
11447 mid = (mid + Math.imul(al1, bh8)) | 0;
11448 mid = (mid + Math.imul(ah1, bl8)) | 0;
11449 hi = (hi + Math.imul(ah1, bh8)) | 0;
11450 lo = (lo + Math.imul(al0, bl9)) | 0;
11451 mid = (mid + Math.imul(al0, bh9)) | 0;
11452 mid = (mid + Math.imul(ah0, bl9)) | 0;
11453 hi = (hi + Math.imul(ah0, bh9)) | 0;
11454 var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11455 c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0;
11456 w9 &= 0x3ffffff;
11457 /* k = 10 */
11458 lo = Math.imul(al9, bl1);
11459 mid = Math.imul(al9, bh1);
11460 mid = (mid + Math.imul(ah9, bl1)) | 0;
11461 hi = Math.imul(ah9, bh1);
11462 lo = (lo + Math.imul(al8, bl2)) | 0;
11463 mid = (mid + Math.imul(al8, bh2)) | 0;
11464 mid = (mid + Math.imul(ah8, bl2)) | 0;
11465 hi = (hi + Math.imul(ah8, bh2)) | 0;
11466 lo = (lo + Math.imul(al7, bl3)) | 0;
11467 mid = (mid + Math.imul(al7, bh3)) | 0;
11468 mid = (mid + Math.imul(ah7, bl3)) | 0;
11469 hi = (hi + Math.imul(ah7, bh3)) | 0;
11470 lo = (lo + Math.imul(al6, bl4)) | 0;
11471 mid = (mid + Math.imul(al6, bh4)) | 0;
11472 mid = (mid + Math.imul(ah6, bl4)) | 0;
11473 hi = (hi + Math.imul(ah6, bh4)) | 0;
11474 lo = (lo + Math.imul(al5, bl5)) | 0;
11475 mid = (mid + Math.imul(al5, bh5)) | 0;
11476 mid = (mid + Math.imul(ah5, bl5)) | 0;
11477 hi = (hi + Math.imul(ah5, bh5)) | 0;
11478 lo = (lo + Math.imul(al4, bl6)) | 0;
11479 mid = (mid + Math.imul(al4, bh6)) | 0;
11480 mid = (mid + Math.imul(ah4, bl6)) | 0;
11481 hi = (hi + Math.imul(ah4, bh6)) | 0;
11482 lo = (lo + Math.imul(al3, bl7)) | 0;
11483 mid = (mid + Math.imul(al3, bh7)) | 0;
11484 mid = (mid + Math.imul(ah3, bl7)) | 0;
11485 hi = (hi + Math.imul(ah3, bh7)) | 0;
11486 lo = (lo + Math.imul(al2, bl8)) | 0;
11487 mid = (mid + Math.imul(al2, bh8)) | 0;
11488 mid = (mid + Math.imul(ah2, bl8)) | 0;
11489 hi = (hi + Math.imul(ah2, bh8)) | 0;
11490 lo = (lo + Math.imul(al1, bl9)) | 0;
11491 mid = (mid + Math.imul(al1, bh9)) | 0;
11492 mid = (mid + Math.imul(ah1, bl9)) | 0;
11493 hi = (hi + Math.imul(ah1, bh9)) | 0;
11494 var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11495 c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0;
11496 w10 &= 0x3ffffff;
11497 /* k = 11 */
11498 lo = Math.imul(al9, bl2);
11499 mid = Math.imul(al9, bh2);
11500 mid = (mid + Math.imul(ah9, bl2)) | 0;
11501 hi = Math.imul(ah9, bh2);
11502 lo = (lo + Math.imul(al8, bl3)) | 0;
11503 mid = (mid + Math.imul(al8, bh3)) | 0;
11504 mid = (mid + Math.imul(ah8, bl3)) | 0;
11505 hi = (hi + Math.imul(ah8, bh3)) | 0;
11506 lo = (lo + Math.imul(al7, bl4)) | 0;
11507 mid = (mid + Math.imul(al7, bh4)) | 0;
11508 mid = (mid + Math.imul(ah7, bl4)) | 0;
11509 hi = (hi + Math.imul(ah7, bh4)) | 0;
11510 lo = (lo + Math.imul(al6, bl5)) | 0;
11511 mid = (mid + Math.imul(al6, bh5)) | 0;
11512 mid = (mid + Math.imul(ah6, bl5)) | 0;
11513 hi = (hi + Math.imul(ah6, bh5)) | 0;
11514 lo = (lo + Math.imul(al5, bl6)) | 0;
11515 mid = (mid + Math.imul(al5, bh6)) | 0;
11516 mid = (mid + Math.imul(ah5, bl6)) | 0;
11517 hi = (hi + Math.imul(ah5, bh6)) | 0;
11518 lo = (lo + Math.imul(al4, bl7)) | 0;
11519 mid = (mid + Math.imul(al4, bh7)) | 0;
11520 mid = (mid + Math.imul(ah4, bl7)) | 0;
11521 hi = (hi + Math.imul(ah4, bh7)) | 0;
11522 lo = (lo + Math.imul(al3, bl8)) | 0;
11523 mid = (mid + Math.imul(al3, bh8)) | 0;
11524 mid = (mid + Math.imul(ah3, bl8)) | 0;
11525 hi = (hi + Math.imul(ah3, bh8)) | 0;
11526 lo = (lo + Math.imul(al2, bl9)) | 0;
11527 mid = (mid + Math.imul(al2, bh9)) | 0;
11528 mid = (mid + Math.imul(ah2, bl9)) | 0;
11529 hi = (hi + Math.imul(ah2, bh9)) | 0;
11530 var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11531 c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0;
11532 w11 &= 0x3ffffff;
11533 /* k = 12 */
11534 lo = Math.imul(al9, bl3);
11535 mid = Math.imul(al9, bh3);
11536 mid = (mid + Math.imul(ah9, bl3)) | 0;
11537 hi = Math.imul(ah9, bh3);
11538 lo = (lo + Math.imul(al8, bl4)) | 0;
11539 mid = (mid + Math.imul(al8, bh4)) | 0;
11540 mid = (mid + Math.imul(ah8, bl4)) | 0;
11541 hi = (hi + Math.imul(ah8, bh4)) | 0;
11542 lo = (lo + Math.imul(al7, bl5)) | 0;
11543 mid = (mid + Math.imul(al7, bh5)) | 0;
11544 mid = (mid + Math.imul(ah7, bl5)) | 0;
11545 hi = (hi + Math.imul(ah7, bh5)) | 0;
11546 lo = (lo + Math.imul(al6, bl6)) | 0;
11547 mid = (mid + Math.imul(al6, bh6)) | 0;
11548 mid = (mid + Math.imul(ah6, bl6)) | 0;
11549 hi = (hi + Math.imul(ah6, bh6)) | 0;
11550 lo = (lo + Math.imul(al5, bl7)) | 0;
11551 mid = (mid + Math.imul(al5, bh7)) | 0;
11552 mid = (mid + Math.imul(ah5, bl7)) | 0;
11553 hi = (hi + Math.imul(ah5, bh7)) | 0;
11554 lo = (lo + Math.imul(al4, bl8)) | 0;
11555 mid = (mid + Math.imul(al4, bh8)) | 0;
11556 mid = (mid + Math.imul(ah4, bl8)) | 0;
11557 hi = (hi + Math.imul(ah4, bh8)) | 0;
11558 lo = (lo + Math.imul(al3, bl9)) | 0;
11559 mid = (mid + Math.imul(al3, bh9)) | 0;
11560 mid = (mid + Math.imul(ah3, bl9)) | 0;
11561 hi = (hi + Math.imul(ah3, bh9)) | 0;
11562 var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11563 c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0;
11564 w12 &= 0x3ffffff;
11565 /* k = 13 */
11566 lo = Math.imul(al9, bl4);
11567 mid = Math.imul(al9, bh4);
11568 mid = (mid + Math.imul(ah9, bl4)) | 0;
11569 hi = Math.imul(ah9, bh4);
11570 lo = (lo + Math.imul(al8, bl5)) | 0;
11571 mid = (mid + Math.imul(al8, bh5)) | 0;
11572 mid = (mid + Math.imul(ah8, bl5)) | 0;
11573 hi = (hi + Math.imul(ah8, bh5)) | 0;
11574 lo = (lo + Math.imul(al7, bl6)) | 0;
11575 mid = (mid + Math.imul(al7, bh6)) | 0;
11576 mid = (mid + Math.imul(ah7, bl6)) | 0;
11577 hi = (hi + Math.imul(ah7, bh6)) | 0;
11578 lo = (lo + Math.imul(al6, bl7)) | 0;
11579 mid = (mid + Math.imul(al6, bh7)) | 0;
11580 mid = (mid + Math.imul(ah6, bl7)) | 0;
11581 hi = (hi + Math.imul(ah6, bh7)) | 0;
11582 lo = (lo + Math.imul(al5, bl8)) | 0;
11583 mid = (mid + Math.imul(al5, bh8)) | 0;
11584 mid = (mid + Math.imul(ah5, bl8)) | 0;
11585 hi = (hi + Math.imul(ah5, bh8)) | 0;
11586 lo = (lo + Math.imul(al4, bl9)) | 0;
11587 mid = (mid + Math.imul(al4, bh9)) | 0;
11588 mid = (mid + Math.imul(ah4, bl9)) | 0;
11589 hi = (hi + Math.imul(ah4, bh9)) | 0;
11590 var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11591 c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0;
11592 w13 &= 0x3ffffff;
11593 /* k = 14 */
11594 lo = Math.imul(al9, bl5);
11595 mid = Math.imul(al9, bh5);
11596 mid = (mid + Math.imul(ah9, bl5)) | 0;
11597 hi = Math.imul(ah9, bh5);
11598 lo = (lo + Math.imul(al8, bl6)) | 0;
11599 mid = (mid + Math.imul(al8, bh6)) | 0;
11600 mid = (mid + Math.imul(ah8, bl6)) | 0;
11601 hi = (hi + Math.imul(ah8, bh6)) | 0;
11602 lo = (lo + Math.imul(al7, bl7)) | 0;
11603 mid = (mid + Math.imul(al7, bh7)) | 0;
11604 mid = (mid + Math.imul(ah7, bl7)) | 0;
11605 hi = (hi + Math.imul(ah7, bh7)) | 0;
11606 lo = (lo + Math.imul(al6, bl8)) | 0;
11607 mid = (mid + Math.imul(al6, bh8)) | 0;
11608 mid = (mid + Math.imul(ah6, bl8)) | 0;
11609 hi = (hi + Math.imul(ah6, bh8)) | 0;
11610 lo = (lo + Math.imul(al5, bl9)) | 0;
11611 mid = (mid + Math.imul(al5, bh9)) | 0;
11612 mid = (mid + Math.imul(ah5, bl9)) | 0;
11613 hi = (hi + Math.imul(ah5, bh9)) | 0;
11614 var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11615 c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0;
11616 w14 &= 0x3ffffff;
11617 /* k = 15 */
11618 lo = Math.imul(al9, bl6);
11619 mid = Math.imul(al9, bh6);
11620 mid = (mid + Math.imul(ah9, bl6)) | 0;
11621 hi = Math.imul(ah9, bh6);
11622 lo = (lo + Math.imul(al8, bl7)) | 0;
11623 mid = (mid + Math.imul(al8, bh7)) | 0;
11624 mid = (mid + Math.imul(ah8, bl7)) | 0;
11625 hi = (hi + Math.imul(ah8, bh7)) | 0;
11626 lo = (lo + Math.imul(al7, bl8)) | 0;
11627 mid = (mid + Math.imul(al7, bh8)) | 0;
11628 mid = (mid + Math.imul(ah7, bl8)) | 0;
11629 hi = (hi + Math.imul(ah7, bh8)) | 0;
11630 lo = (lo + Math.imul(al6, bl9)) | 0;
11631 mid = (mid + Math.imul(al6, bh9)) | 0;
11632 mid = (mid + Math.imul(ah6, bl9)) | 0;
11633 hi = (hi + Math.imul(ah6, bh9)) | 0;
11634 var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11635 c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0;
11636 w15 &= 0x3ffffff;
11637 /* k = 16 */
11638 lo = Math.imul(al9, bl7);
11639 mid = Math.imul(al9, bh7);
11640 mid = (mid + Math.imul(ah9, bl7)) | 0;
11641 hi = Math.imul(ah9, bh7);
11642 lo = (lo + Math.imul(al8, bl8)) | 0;
11643 mid = (mid + Math.imul(al8, bh8)) | 0;
11644 mid = (mid + Math.imul(ah8, bl8)) | 0;
11645 hi = (hi + Math.imul(ah8, bh8)) | 0;
11646 lo = (lo + Math.imul(al7, bl9)) | 0;
11647 mid = (mid + Math.imul(al7, bh9)) | 0;
11648 mid = (mid + Math.imul(ah7, bl9)) | 0;
11649 hi = (hi + Math.imul(ah7, bh9)) | 0;
11650 var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11651 c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0;
11652 w16 &= 0x3ffffff;
11653 /* k = 17 */
11654 lo = Math.imul(al9, bl8);
11655 mid = Math.imul(al9, bh8);
11656 mid = (mid + Math.imul(ah9, bl8)) | 0;
11657 hi = Math.imul(ah9, bh8);
11658 lo = (lo + Math.imul(al8, bl9)) | 0;
11659 mid = (mid + Math.imul(al8, bh9)) | 0;
11660 mid = (mid + Math.imul(ah8, bl9)) | 0;
11661 hi = (hi + Math.imul(ah8, bh9)) | 0;
11662 var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11663 c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0;
11664 w17 &= 0x3ffffff;
11665 /* k = 18 */
11666 lo = Math.imul(al9, bl9);
11667 mid = Math.imul(al9, bh9);
11668 mid = (mid + Math.imul(ah9, bl9)) | 0;
11669 hi = Math.imul(ah9, bh9);
11670 var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0;
11671 c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0;
11672 w18 &= 0x3ffffff;
11673 o[0] = w0;
11674 o[1] = w1;
11675 o[2] = w2;
11676 o[3] = w3;
11677 o[4] = w4;
11678 o[5] = w5;
11679 o[6] = w6;
11680 o[7] = w7;
11681 o[8] = w8;
11682 o[9] = w9;
11683 o[10] = w10;
11684 o[11] = w11;
11685 o[12] = w12;
11686 o[13] = w13;
11687 o[14] = w14;
11688 o[15] = w15;
11689 o[16] = w16;
11690 o[17] = w17;
11691 o[18] = w18;
11692 if (c !== 0) {
11693 o[19] = c;
11694 out.length++;
11695 }
11696 return out;
11697 };
11698
11699 // Polyfill comb
11700 if (!Math.imul) {
11701 comb10MulTo = smallMulTo;
11702 }
11703
11704 function bigMulTo (self, num, out) {
11705 out.negative = num.negative ^ self.negative;
11706 out.length = self.length + num.length;
11707
11708 var carry = 0;
11709 var hncarry = 0;
11710 for (var k = 0; k < out.length - 1; k++) {
11711 // Sum all words with the same `i + j = k` and accumulate `ncarry`,
11712 // note that ncarry could be >= 0x3ffffff
11713 var ncarry = hncarry;
11714 hncarry = 0;
11715 var rword = carry & 0x3ffffff;
11716 var maxJ = Math.min(k, num.length - 1);
11717 for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) {
11718 var i = k - j;
11719 var a = self.words[i] | 0;
11720 var b = num.words[j] | 0;
11721 var r = a * b;
11722
11723 var lo = r & 0x3ffffff;
11724 ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0;
11725 lo = (lo + rword) | 0;
11726 rword = lo & 0x3ffffff;
11727 ncarry = (ncarry + (lo >>> 26)) | 0;
11728
11729 hncarry += ncarry >>> 26;
11730 ncarry &= 0x3ffffff;
11731 }
11732 out.words[k] = rword;
11733 carry = ncarry;
11734 ncarry = hncarry;
11735 }
11736 if (carry !== 0) {
11737 out.words[k] = carry;
11738 } else {
11739 out.length--;
11740 }
11741
11742 return out.strip();
11743 }
11744
11745 function jumboMulTo (self, num, out) {
11746 var fftm = new FFTM();
11747 return fftm.mulp(self, num, out);
11748 }
11749
11750 BN.prototype.mulTo = function mulTo (num, out) {
11751 var res;
11752 var len = this.length + num.length;
11753 if (this.length === 10 && num.length === 10) {
11754 res = comb10MulTo(this, num, out);
11755 } else if (len < 63) {
11756 res = smallMulTo(this, num, out);
11757 } else if (len < 1024) {
11758 res = bigMulTo(this, num, out);
11759 } else {
11760 res = jumboMulTo(this, num, out);
11761 }
11762
11763 return res;
11764 };
11765
11766 // Cooley-Tukey algorithm for FFT
11767 // slightly revisited to rely on looping instead of recursion
11768
11769 function FFTM (x, y) {
11770 this.x = x;
11771 this.y = y;
11772 }
11773
11774 FFTM.prototype.makeRBT = function makeRBT (N) {
11775 var t = new Array(N);
11776 var l = BN.prototype._countBits(N) - 1;
11777 for (var i = 0; i < N; i++) {
11778 t[i] = this.revBin(i, l, N);
11779 }
11780
11781 return t;
11782 };
11783
11784 // Returns binary-reversed representation of `x`
11785 FFTM.prototype.revBin = function revBin (x, l, N) {
11786 if (x === 0 || x === N - 1) return x;
11787
11788 var rb = 0;
11789 for (var i = 0; i < l; i++) {
11790 rb |= (x & 1) << (l - i - 1);
11791 x >>= 1;
11792 }
11793
11794 return rb;
11795 };
11796
11797 // Performs "tweedling" phase, therefore 'emulating'
11798 // behaviour of the recursive algorithm
11799 FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) {
11800 for (var i = 0; i < N; i++) {
11801 rtws[i] = rws[rbt[i]];
11802 itws[i] = iws[rbt[i]];
11803 }
11804 };
11805
11806 FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) {
11807 this.permute(rbt, rws, iws, rtws, itws, N);
11808
11809 for (var s = 1; s < N; s <<= 1) {
11810 var l = s << 1;
11811
11812 var rtwdf = Math.cos(2 * Math.PI / l);
11813 var itwdf = Math.sin(2 * Math.PI / l);
11814
11815 for (var p = 0; p < N; p += l) {
11816 var rtwdf_ = rtwdf;
11817 var itwdf_ = itwdf;
11818
11819 for (var j = 0; j < s; j++) {
11820 var re = rtws[p + j];
11821 var ie = itws[p + j];
11822
11823 var ro = rtws[p + j + s];
11824 var io = itws[p + j + s];
11825
11826 var rx = rtwdf_ * ro - itwdf_ * io;
11827
11828 io = rtwdf_ * io + itwdf_ * ro;
11829 ro = rx;
11830
11831 rtws[p + j] = re + ro;
11832 itws[p + j] = ie + io;
11833
11834 rtws[p + j + s] = re - ro;
11835 itws[p + j + s] = ie - io;
11836
11837 /* jshint maxdepth : false */
11838 if (j !== l) {
11839 rx = rtwdf * rtwdf_ - itwdf * itwdf_;
11840
11841 itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_;
11842 rtwdf_ = rx;
11843 }
11844 }
11845 }
11846 }
11847 };
11848
11849 FFTM.prototype.guessLen13b = function guessLen13b (n, m) {
11850 var N = Math.max(m, n) | 1;
11851 var odd = N & 1;
11852 var i = 0;
11853 for (N = N / 2 | 0; N; N = N >>> 1) {
11854 i++;
11855 }
11856
11857 return 1 << i + 1 + odd;
11858 };
11859
11860 FFTM.prototype.conjugate = function conjugate (rws, iws, N) {
11861 if (N <= 1) return;
11862
11863 for (var i = 0; i < N / 2; i++) {
11864 var t = rws[i];
11865
11866 rws[i] = rws[N - i - 1];
11867 rws[N - i - 1] = t;
11868
11869 t = iws[i];
11870
11871 iws[i] = -iws[N - i - 1];
11872 iws[N - i - 1] = -t;
11873 }
11874 };
11875
11876 FFTM.prototype.normalize13b = function normalize13b (ws, N) {
11877 var carry = 0;
11878 for (var i = 0; i < N / 2; i++) {
11879 var w = Math.round(ws[2 * i + 1] / N) * 0x2000 +
11880 Math.round(ws[2 * i] / N) +
11881 carry;
11882
11883 ws[i] = w & 0x3ffffff;
11884
11885 if (w < 0x4000000) {
11886 carry = 0;
11887 } else {
11888 carry = w / 0x4000000 | 0;
11889 }
11890 }
11891
11892 return ws;
11893 };
11894
11895 FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) {
11896 var carry = 0;
11897 for (var i = 0; i < len; i++) {
11898 carry = carry + (ws[i] | 0);
11899
11900 rws[2 * i] = carry & 0x1fff; carry = carry >>> 13;
11901 rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13;
11902 }
11903
11904 // Pad with zeroes
11905 for (i = 2 * len; i < N; ++i) {
11906 rws[i] = 0;
11907 }
11908
11909 assert(carry === 0);
11910 assert((carry & ~0x1fff) === 0);
11911 };
11912
11913 FFTM.prototype.stub = function stub (N) {
11914 var ph = new Array(N);
11915 for (var i = 0; i < N; i++) {
11916 ph[i] = 0;
11917 }
11918
11919 return ph;
11920 };
11921
11922 FFTM.prototype.mulp = function mulp (x, y, out) {
11923 var N = 2 * this.guessLen13b(x.length, y.length);
11924
11925 var rbt = this.makeRBT(N);
11926
11927 var _ = this.stub(N);
11928
11929 var rws = new Array(N);
11930 var rwst = new Array(N);
11931 var iwst = new Array(N);
11932
11933 var nrws = new Array(N);
11934 var nrwst = new Array(N);
11935 var niwst = new Array(N);
11936
11937 var rmws = out.words;
11938 rmws.length = N;
11939
11940 this.convert13b(x.words, x.length, rws, N);
11941 this.convert13b(y.words, y.length, nrws, N);
11942
11943 this.transform(rws, _, rwst, iwst, N, rbt);
11944 this.transform(nrws, _, nrwst, niwst, N, rbt);
11945
11946 for (var i = 0; i < N; i++) {
11947 var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i];
11948 iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i];
11949 rwst[i] = rx;
11950 }
11951
11952 this.conjugate(rwst, iwst, N);
11953 this.transform(rwst, iwst, rmws, _, N, rbt);
11954 this.conjugate(rmws, _, N);
11955 this.normalize13b(rmws, N);
11956
11957 out.negative = x.negative ^ y.negative;
11958 out.length = x.length + y.length;
11959 return out.strip();
11960 };
11961
11962 // Multiply `this` by `num`
11963 BN.prototype.mul = function mul (num) {
11964 var out = new BN(null);
11965 out.words = new Array(this.length + num.length);
11966 return this.mulTo(num, out);
11967 };
11968
11969 // Multiply employing FFT
11970 BN.prototype.mulf = function mulf (num) {
11971 var out = new BN(null);
11972 out.words = new Array(this.length + num.length);
11973 return jumboMulTo(this, num, out);
11974 };
11975
11976 // In-place Multiplication
11977 BN.prototype.imul = function imul (num) {
11978 return this.clone().mulTo(num, this);
11979 };
11980
11981 BN.prototype.imuln = function imuln (num) {
11982 assert(typeof num === 'number');
11983 assert(num < 0x4000000);
11984
11985 // Carry
11986 var carry = 0;
11987 for (var i = 0; i < this.length; i++) {
11988 var w = (this.words[i] | 0) * num;
11989 var lo = (w & 0x3ffffff) + (carry & 0x3ffffff);
11990 carry >>= 26;
11991 carry += (w / 0x4000000) | 0;
11992 // NOTE: lo is 27bit maximum
11993 carry += lo >>> 26;
11994 this.words[i] = lo & 0x3ffffff;
11995 }
11996
11997 if (carry !== 0) {
11998 this.words[i] = carry;
11999 this.length++;
12000 }
12001
12002 return this;
12003 };
12004
12005 BN.prototype.muln = function muln (num) {
12006 return this.clone().imuln(num);
12007 };
12008
12009 // `this` * `this`
12010 BN.prototype.sqr = function sqr () {
12011 return this.mul(this);
12012 };
12013
12014 // `this` * `this` in-place
12015 BN.prototype.isqr = function isqr () {
12016 return this.imul(this.clone());
12017 };
12018
12019 // Math.pow(`this`, `num`)
12020 BN.prototype.pow = function pow (num) {
12021 var w = toBitArray(num);
12022 if (w.length === 0) return new BN(1);
12023
12024 // Skip leading zeroes
12025 var res = this;
12026 for (var i = 0; i < w.length; i++, res = res.sqr()) {
12027 if (w[i] !== 0) break;
12028 }
12029
12030 if (++i < w.length) {
12031 for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) {
12032 if (w[i] === 0) continue;
12033
12034 res = res.mul(q);
12035 }
12036 }
12037
12038 return res;
12039 };
12040
12041 // Shift-left in-place
12042 BN.prototype.iushln = function iushln (bits) {
12043 assert(typeof bits === 'number' && bits >= 0);
12044 var r = bits % 26;
12045 var s = (bits - r) / 26;
12046 var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r);
12047 var i;
12048
12049 if (r !== 0) {
12050 var carry = 0;
12051
12052 for (i = 0; i < this.length; i++) {
12053 var newCarry = this.words[i] & carryMask;
12054 var c = ((this.words[i] | 0) - newCarry) << r;
12055 this.words[i] = c | carry;
12056 carry = newCarry >>> (26 - r);
12057 }
12058
12059 if (carry) {
12060 this.words[i] = carry;
12061 this.length++;
12062 }
12063 }
12064
12065 if (s !== 0) {
12066 for (i = this.length - 1; i >= 0; i--) {
12067 this.words[i + s] = this.words[i];
12068 }
12069
12070 for (i = 0; i < s; i++) {
12071 this.words[i] = 0;
12072 }
12073
12074 this.length += s;
12075 }
12076
12077 return this.strip();
12078 };
12079
12080 BN.prototype.ishln = function ishln (bits) {
12081 // TODO(indutny): implement me
12082 assert(this.negative === 0);
12083 return this.iushln(bits);
12084 };
12085
12086 // Shift-right in-place
12087 // NOTE: `hint` is a lowest bit before trailing zeroes
12088 // NOTE: if `extended` is present - it will be filled with destroyed bits
12089 BN.prototype.iushrn = function iushrn (bits, hint, extended) {
12090 assert(typeof bits === 'number' && bits >= 0);
12091 var h;
12092 if (hint) {
12093 h = (hint - (hint % 26)) / 26;
12094 } else {
12095 h = 0;
12096 }
12097
12098 var r = bits % 26;
12099 var s = Math.min((bits - r) / 26, this.length);
12100 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
12101 var maskedWords = extended;
12102
12103 h -= s;
12104 h = Math.max(0, h);
12105
12106 // Extended mode, copy masked part
12107 if (maskedWords) {
12108 for (var i = 0; i < s; i++) {
12109 maskedWords.words[i] = this.words[i];
12110 }
12111 maskedWords.length = s;
12112 }
12113
12114 if (s === 0) {
12115 // No-op, we should not move anything at all
12116 } else if (this.length > s) {
12117 this.length -= s;
12118 for (i = 0; i < this.length; i++) {
12119 this.words[i] = this.words[i + s];
12120 }
12121 } else {
12122 this.words[0] = 0;
12123 this.length = 1;
12124 }
12125
12126 var carry = 0;
12127 for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) {
12128 var word = this.words[i] | 0;
12129 this.words[i] = (carry << (26 - r)) | (word >>> r);
12130 carry = word & mask;
12131 }
12132
12133 // Push carried bits as a mask
12134 if (maskedWords && carry !== 0) {
12135 maskedWords.words[maskedWords.length++] = carry;
12136 }
12137
12138 if (this.length === 0) {
12139 this.words[0] = 0;
12140 this.length = 1;
12141 }
12142
12143 return this.strip();
12144 };
12145
12146 BN.prototype.ishrn = function ishrn (bits, hint, extended) {
12147 // TODO(indutny): implement me
12148 assert(this.negative === 0);
12149 return this.iushrn(bits, hint, extended);
12150 };
12151
12152 // Shift-left
12153 BN.prototype.shln = function shln (bits) {
12154 return this.clone().ishln(bits);
12155 };
12156
12157 BN.prototype.ushln = function ushln (bits) {
12158 return this.clone().iushln(bits);
12159 };
12160
12161 // Shift-right
12162 BN.prototype.shrn = function shrn (bits) {
12163 return this.clone().ishrn(bits);
12164 };
12165
12166 BN.prototype.ushrn = function ushrn (bits) {
12167 return this.clone().iushrn(bits);
12168 };
12169
12170 // Test if n bit is set
12171 BN.prototype.testn = function testn (bit) {
12172 assert(typeof bit === 'number' && bit >= 0);
12173 var r = bit % 26;
12174 var s = (bit - r) / 26;
12175 var q = 1 << r;
12176
12177 // Fast case: bit is much higher than all existing words
12178 if (this.length <= s) return false;
12179
12180 // Check bit and return
12181 var w = this.words[s];
12182
12183 return !!(w & q);
12184 };
12185
12186 // Return only lowers bits of number (in-place)
12187 BN.prototype.imaskn = function imaskn (bits) {
12188 assert(typeof bits === 'number' && bits >= 0);
12189 var r = bits % 26;
12190 var s = (bits - r) / 26;
12191
12192 assert(this.negative === 0, 'imaskn works only with positive numbers');
12193
12194 if (this.length <= s) {
12195 return this;
12196 }
12197
12198 if (r !== 0) {
12199 s++;
12200 }
12201 this.length = Math.min(s, this.length);
12202
12203 if (r !== 0) {
12204 var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r);
12205 this.words[this.length - 1] &= mask;
12206 }
12207
12208 return this.strip();
12209 };
12210
12211 // Return only lowers bits of number
12212 BN.prototype.maskn = function maskn (bits) {
12213 return this.clone().imaskn(bits);
12214 };
12215
12216 // Add plain number `num` to `this`
12217 BN.prototype.iaddn = function iaddn (num) {
12218 assert(typeof num === 'number');
12219 assert(num < 0x4000000);
12220 if (num < 0) return this.isubn(-num);
12221
12222 // Possible sign change
12223 if (this.negative !== 0) {
12224 if (this.length === 1 && (this.words[0] | 0) < num) {
12225 this.words[0] = num - (this.words[0] | 0);
12226 this.negative = 0;
12227 return this;
12228 }
12229
12230 this.negative = 0;
12231 this.isubn(num);
12232 this.negative = 1;
12233 return this;
12234 }
12235
12236 // Add without checks
12237 return this._iaddn(num);
12238 };
12239
12240 BN.prototype._iaddn = function _iaddn (num) {
12241 this.words[0] += num;
12242
12243 // Carry
12244 for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) {
12245 this.words[i] -= 0x4000000;
12246 if (i === this.length - 1) {
12247 this.words[i + 1] = 1;
12248 } else {
12249 this.words[i + 1]++;
12250 }
12251 }
12252 this.length = Math.max(this.length, i + 1);
12253
12254 return this;
12255 };
12256
12257 // Subtract plain number `num` from `this`
12258 BN.prototype.isubn = function isubn (num) {
12259 assert(typeof num === 'number');
12260 assert(num < 0x4000000);
12261 if (num < 0) return this.iaddn(-num);
12262
12263 if (this.negative !== 0) {
12264 this.negative = 0;
12265 this.iaddn(num);
12266 this.negative = 1;
12267 return this;
12268 }
12269
12270 this.words[0] -= num;
12271
12272 if (this.length === 1 && this.words[0] < 0) {
12273 this.words[0] = -this.words[0];
12274 this.negative = 1;
12275 } else {
12276 // Carry
12277 for (var i = 0; i < this.length && this.words[i] < 0; i++) {
12278 this.words[i] += 0x4000000;
12279 this.words[i + 1] -= 1;
12280 }
12281 }
12282
12283 return this.strip();
12284 };
12285
12286 BN.prototype.addn = function addn (num) {
12287 return this.clone().iaddn(num);
12288 };
12289
12290 BN.prototype.subn = function subn (num) {
12291 return this.clone().isubn(num);
12292 };
12293
12294 BN.prototype.iabs = function iabs () {
12295 this.negative = 0;
12296
12297 return this;
12298 };
12299
12300 BN.prototype.abs = function abs () {
12301 return this.clone().iabs();
12302 };
12303
12304 BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) {
12305 var len = num.length + shift;
12306 var i;
12307
12308 this._expand(len);
12309
12310 var w;
12311 var carry = 0;
12312 for (i = 0; i < num.length; i++) {
12313 w = (this.words[i + shift] | 0) + carry;
12314 var right = (num.words[i] | 0) * mul;
12315 w -= right & 0x3ffffff;
12316 carry = (w >> 26) - ((right / 0x4000000) | 0);
12317 this.words[i + shift] = w & 0x3ffffff;
12318 }
12319 for (; i < this.length - shift; i++) {
12320 w = (this.words[i + shift] | 0) + carry;
12321 carry = w >> 26;
12322 this.words[i + shift] = w & 0x3ffffff;
12323 }
12324
12325 if (carry === 0) return this.strip();
12326
12327 // Subtraction overflow
12328 assert(carry === -1);
12329 carry = 0;
12330 for (i = 0; i < this.length; i++) {
12331 w = -(this.words[i] | 0) + carry;
12332 carry = w >> 26;
12333 this.words[i] = w & 0x3ffffff;
12334 }
12335 this.negative = 1;
12336
12337 return this.strip();
12338 };
12339
12340 BN.prototype._wordDiv = function _wordDiv (num, mode) {
12341 var shift = this.length - num.length;
12342
12343 var a = this.clone();
12344 var b = num;
12345
12346 // Normalize
12347 var bhi = b.words[b.length - 1] | 0;
12348 var bhiBits = this._countBits(bhi);
12349 shift = 26 - bhiBits;
12350 if (shift !== 0) {
12351 b = b.ushln(shift);
12352 a.iushln(shift);
12353 bhi = b.words[b.length - 1] | 0;
12354 }
12355
12356 // Initialize quotient
12357 var m = a.length - b.length;
12358 var q;
12359
12360 if (mode !== 'mod') {
12361 q = new BN(null);
12362 q.length = m + 1;
12363 q.words = new Array(q.length);
12364 for (var i = 0; i < q.length; i++) {
12365 q.words[i] = 0;
12366 }
12367 }
12368
12369 var diff = a.clone()._ishlnsubmul(b, 1, m);
12370 if (diff.negative === 0) {
12371 a = diff;
12372 if (q) {
12373 q.words[m] = 1;
12374 }
12375 }
12376
12377 for (var j = m - 1; j >= 0; j--) {
12378 var qj = (a.words[b.length + j] | 0) * 0x4000000 +
12379 (a.words[b.length + j - 1] | 0);
12380
12381 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
12382 // (0x7ffffff)
12383 qj = Math.min((qj / bhi) | 0, 0x3ffffff);
12384
12385 a._ishlnsubmul(b, qj, j);
12386 while (a.negative !== 0) {
12387 qj--;
12388 a.negative = 0;
12389 a._ishlnsubmul(b, 1, j);
12390 if (!a.isZero()) {
12391 a.negative ^= 1;
12392 }
12393 }
12394 if (q) {
12395 q.words[j] = qj;
12396 }
12397 }
12398 if (q) {
12399 q.strip();
12400 }
12401 a.strip();
12402
12403 // Denormalize
12404 if (mode !== 'div' && shift !== 0) {
12405 a.iushrn(shift);
12406 }
12407
12408 return {
12409 div: q || null,
12410 mod: a
12411 };
12412 };
12413
12414 // NOTE: 1) `mode` can be set to `mod` to request mod only,
12415 // to `div` to request div only, or be absent to
12416 // request both div & mod
12417 // 2) `positive` is true if unsigned mod is requested
12418 BN.prototype.divmod = function divmod (num, mode, positive) {
12419 assert(!num.isZero());
12420
12421 if (this.isZero()) {
12422 return {
12423 div: new BN(0),
12424 mod: new BN(0)
12425 };
12426 }
12427
12428 var div, mod, res;
12429 if (this.negative !== 0 && num.negative === 0) {
12430 res = this.neg().divmod(num, mode);
12431
12432 if (mode !== 'mod') {
12433 div = res.div.neg();
12434 }
12435
12436 if (mode !== 'div') {
12437 mod = res.mod.neg();
12438 if (positive && mod.negative !== 0) {
12439 mod.iadd(num);
12440 }
12441 }
12442
12443 return {
12444 div: div,
12445 mod: mod
12446 };
12447 }
12448
12449 if (this.negative === 0 && num.negative !== 0) {
12450 res = this.divmod(num.neg(), mode);
12451
12452 if (mode !== 'mod') {
12453 div = res.div.neg();
12454 }
12455
12456 return {
12457 div: div,
12458 mod: res.mod
12459 };
12460 }
12461
12462 if ((this.negative & num.negative) !== 0) {
12463 res = this.neg().divmod(num.neg(), mode);
12464
12465 if (mode !== 'div') {
12466 mod = res.mod.neg();
12467 if (positive && mod.negative !== 0) {
12468 mod.isub(num);
12469 }
12470 }
12471
12472 return {
12473 div: res.div,
12474 mod: mod
12475 };
12476 }
12477
12478 // Both numbers are positive at this point
12479
12480 // Strip both numbers to approximate shift value
12481 if (num.length > this.length || this.cmp(num) < 0) {
12482 return {
12483 div: new BN(0),
12484 mod: this
12485 };
12486 }
12487
12488 // Very short reduction
12489 if (num.length === 1) {
12490 if (mode === 'div') {
12491 return {
12492 div: this.divn(num.words[0]),
12493 mod: null
12494 };
12495 }
12496
12497 if (mode === 'mod') {
12498 return {
12499 div: null,
12500 mod: new BN(this.modn(num.words[0]))
12501 };
12502 }
12503
12504 return {
12505 div: this.divn(num.words[0]),
12506 mod: new BN(this.modn(num.words[0]))
12507 };
12508 }
12509
12510 return this._wordDiv(num, mode);
12511 };
12512
12513 // Find `this` / `num`
12514 BN.prototype.div = function div (num) {
12515 return this.divmod(num, 'div', false).div;
12516 };
12517
12518 // Find `this` % `num`
12519 BN.prototype.mod = function mod (num) {
12520 return this.divmod(num, 'mod', false).mod;
12521 };
12522
12523 BN.prototype.umod = function umod (num) {
12524 return this.divmod(num, 'mod', true).mod;
12525 };
12526
12527 // Find Round(`this` / `num`)
12528 BN.prototype.divRound = function divRound (num) {
12529 var dm = this.divmod(num);
12530
12531 // Fast case - exact division
12532 if (dm.mod.isZero()) return dm.div;
12533
12534 var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod;
12535
12536 var half = num.ushrn(1);
12537 var r2 = num.andln(1);
12538 var cmp = mod.cmp(half);
12539
12540 // Round down
12541 if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div;
12542
12543 // Round up
12544 return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1);
12545 };
12546
12547 BN.prototype.modn = function modn (num) {
12548 assert(num <= 0x3ffffff);
12549 var p = (1 << 26) % num;
12550
12551 var acc = 0;
12552 for (var i = this.length - 1; i >= 0; i--) {
12553 acc = (p * acc + (this.words[i] | 0)) % num;
12554 }
12555
12556 return acc;
12557 };
12558
12559 // In-place division by number
12560 BN.prototype.idivn = function idivn (num) {
12561 assert(num <= 0x3ffffff);
12562
12563 var carry = 0;
12564 for (var i = this.length - 1; i >= 0; i--) {
12565 var w = (this.words[i] | 0) + carry * 0x4000000;
12566 this.words[i] = (w / num) | 0;
12567 carry = w % num;
12568 }
12569
12570 return this.strip();
12571 };
12572
12573 BN.prototype.divn = function divn (num) {
12574 return this.clone().idivn(num);
12575 };
12576
12577 BN.prototype.egcd = function egcd (p) {
12578 assert(p.negative === 0);
12579 assert(!p.isZero());
12580
12581 var x = this;
12582 var y = p.clone();
12583
12584 if (x.negative !== 0) {
12585 x = x.umod(p);
12586 } else {
12587 x = x.clone();
12588 }
12589
12590 // A * x + B * y = x
12591 var A = new BN(1);
12592 var B = new BN(0);
12593
12594 // C * x + D * y = y
12595 var C = new BN(0);
12596 var D = new BN(1);
12597
12598 var g = 0;
12599
12600 while (x.isEven() && y.isEven()) {
12601 x.iushrn(1);
12602 y.iushrn(1);
12603 ++g;
12604 }
12605
12606 var yp = y.clone();
12607 var xp = x.clone();
12608
12609 while (!x.isZero()) {
12610 for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
12611 if (i > 0) {
12612 x.iushrn(i);
12613 while (i-- > 0) {
12614 if (A.isOdd() || B.isOdd()) {
12615 A.iadd(yp);
12616 B.isub(xp);
12617 }
12618
12619 A.iushrn(1);
12620 B.iushrn(1);
12621 }
12622 }
12623
12624 for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
12625 if (j > 0) {
12626 y.iushrn(j);
12627 while (j-- > 0) {
12628 if (C.isOdd() || D.isOdd()) {
12629 C.iadd(yp);
12630 D.isub(xp);
12631 }
12632
12633 C.iushrn(1);
12634 D.iushrn(1);
12635 }
12636 }
12637
12638 if (x.cmp(y) >= 0) {
12639 x.isub(y);
12640 A.isub(C);
12641 B.isub(D);
12642 } else {
12643 y.isub(x);
12644 C.isub(A);
12645 D.isub(B);
12646 }
12647 }
12648
12649 return {
12650 a: C,
12651 b: D,
12652 gcd: y.iushln(g)
12653 };
12654 };
12655
12656 // This is reduced incarnation of the binary EEA
12657 // above, designated to invert members of the
12658 // _prime_ fields F(p) at a maximal speed
12659 BN.prototype._invmp = function _invmp (p) {
12660 assert(p.negative === 0);
12661 assert(!p.isZero());
12662
12663 var a = this;
12664 var b = p.clone();
12665
12666 if (a.negative !== 0) {
12667 a = a.umod(p);
12668 } else {
12669 a = a.clone();
12670 }
12671
12672 var x1 = new BN(1);
12673 var x2 = new BN(0);
12674
12675 var delta = b.clone();
12676
12677 while (a.cmpn(1) > 0 && b.cmpn(1) > 0) {
12678 for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1);
12679 if (i > 0) {
12680 a.iushrn(i);
12681 while (i-- > 0) {
12682 if (x1.isOdd()) {
12683 x1.iadd(delta);
12684 }
12685
12686 x1.iushrn(1);
12687 }
12688 }
12689
12690 for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1);
12691 if (j > 0) {
12692 b.iushrn(j);
12693 while (j-- > 0) {
12694 if (x2.isOdd()) {
12695 x2.iadd(delta);
12696 }
12697
12698 x2.iushrn(1);
12699 }
12700 }
12701
12702 if (a.cmp(b) >= 0) {
12703 a.isub(b);
12704 x1.isub(x2);
12705 } else {
12706 b.isub(a);
12707 x2.isub(x1);
12708 }
12709 }
12710
12711 var res;
12712 if (a.cmpn(1) === 0) {
12713 res = x1;
12714 } else {
12715 res = x2;
12716 }
12717
12718 if (res.cmpn(0) < 0) {
12719 res.iadd(p);
12720 }
12721
12722 return res;
12723 };
12724
12725 BN.prototype.gcd = function gcd (num) {
12726 if (this.isZero()) return num.abs();
12727 if (num.isZero()) return this.abs();
12728
12729 var a = this.clone();
12730 var b = num.clone();
12731 a.negative = 0;
12732 b.negative = 0;
12733
12734 // Remove common factor of two
12735 for (var shift = 0; a.isEven() && b.isEven(); shift++) {
12736 a.iushrn(1);
12737 b.iushrn(1);
12738 }
12739
12740 do {
12741 while (a.isEven()) {
12742 a.iushrn(1);
12743 }
12744 while (b.isEven()) {
12745 b.iushrn(1);
12746 }
12747
12748 var r = a.cmp(b);
12749 if (r < 0) {
12750 // Swap `a` and `b` to make `a` always bigger than `b`
12751 var t = a;
12752 a = b;
12753 b = t;
12754 } else if (r === 0 || b.cmpn(1) === 0) {
12755 break;
12756 }
12757
12758 a.isub(b);
12759 } while (true);
12760
12761 return b.iushln(shift);
12762 };
12763
12764 // Invert number in the field F(num)
12765 BN.prototype.invm = function invm (num) {
12766 return this.egcd(num).a.umod(num);
12767 };
12768
12769 BN.prototype.isEven = function isEven () {
12770 return (this.words[0] & 1) === 0;
12771 };
12772
12773 BN.prototype.isOdd = function isOdd () {
12774 return (this.words[0] & 1) === 1;
12775 };
12776
12777 // And first word and num
12778 BN.prototype.andln = function andln (num) {
12779 return this.words[0] & num;
12780 };
12781
12782 // Increment at the bit position in-line
12783 BN.prototype.bincn = function bincn (bit) {
12784 assert(typeof bit === 'number');
12785 var r = bit % 26;
12786 var s = (bit - r) / 26;
12787 var q = 1 << r;
12788
12789 // Fast case: bit is much higher than all existing words
12790 if (this.length <= s) {
12791 this._expand(s + 1);
12792 this.words[s] |= q;
12793 return this;
12794 }
12795
12796 // Add bit and propagate, if needed
12797 var carry = q;
12798 for (var i = s; carry !== 0 && i < this.length; i++) {
12799 var w = this.words[i] | 0;
12800 w += carry;
12801 carry = w >>> 26;
12802 w &= 0x3ffffff;
12803 this.words[i] = w;
12804 }
12805 if (carry !== 0) {
12806 this.words[i] = carry;
12807 this.length++;
12808 }
12809 return this;
12810 };
12811
12812 BN.prototype.isZero = function isZero () {
12813 return this.length === 1 && this.words[0] === 0;
12814 };
12815
12816 BN.prototype.cmpn = function cmpn (num) {
12817 var negative = num < 0;
12818
12819 if (this.negative !== 0 && !negative) return -1;
12820 if (this.negative === 0 && negative) return 1;
12821
12822 this.strip();
12823
12824 var res;
12825 if (this.length > 1) {
12826 res = 1;
12827 } else {
12828 if (negative) {
12829 num = -num;
12830 }
12831
12832 assert(num <= 0x3ffffff, 'Number is too big');
12833
12834 var w = this.words[0] | 0;
12835 res = w === num ? 0 : w < num ? -1 : 1;
12836 }
12837 if (this.negative !== 0) return -res | 0;
12838 return res;
12839 };
12840
12841 // Compare two numbers and return:
12842 // 1 - if `this` > `num`
12843 // 0 - if `this` == `num`
12844 // -1 - if `this` < `num`
12845 BN.prototype.cmp = function cmp (num) {
12846 if (this.negative !== 0 && num.negative === 0) return -1;
12847 if (this.negative === 0 && num.negative !== 0) return 1;
12848
12849 var res = this.ucmp(num);
12850 if (this.negative !== 0) return -res | 0;
12851 return res;
12852 };
12853
12854 // Unsigned comparison
12855 BN.prototype.ucmp = function ucmp (num) {
12856 // At this point both numbers have the same sign
12857 if (this.length > num.length) return 1;
12858 if (this.length < num.length) return -1;
12859
12860 var res = 0;
12861 for (var i = this.length - 1; i >= 0; i--) {
12862 var a = this.words[i] | 0;
12863 var b = num.words[i] | 0;
12864
12865 if (a === b) continue;
12866 if (a < b) {
12867 res = -1;
12868 } else if (a > b) {
12869 res = 1;
12870 }
12871 break;
12872 }
12873 return res;
12874 };
12875
12876 BN.prototype.gtn = function gtn (num) {
12877 return this.cmpn(num) === 1;
12878 };
12879
12880 BN.prototype.gt = function gt (num) {
12881 return this.cmp(num) === 1;
12882 };
12883
12884 BN.prototype.gten = function gten (num) {
12885 return this.cmpn(num) >= 0;
12886 };
12887
12888 BN.prototype.gte = function gte (num) {
12889 return this.cmp(num) >= 0;
12890 };
12891
12892 BN.prototype.ltn = function ltn (num) {
12893 return this.cmpn(num) === -1;
12894 };
12895
12896 BN.prototype.lt = function lt (num) {
12897 return this.cmp(num) === -1;
12898 };
12899
12900 BN.prototype.lten = function lten (num) {
12901 return this.cmpn(num) <= 0;
12902 };
12903
12904 BN.prototype.lte = function lte (num) {
12905 return this.cmp(num) <= 0;
12906 };
12907
12908 BN.prototype.eqn = function eqn (num) {
12909 return this.cmpn(num) === 0;
12910 };
12911
12912 BN.prototype.eq = function eq (num) {
12913 return this.cmp(num) === 0;
12914 };
12915
12916 //
12917 // A reduce context, could be using montgomery or something better, depending
12918 // on the `m` itself.
12919 //
12920 BN.red = function red (num) {
12921 return new Red(num);
12922 };
12923
12924 BN.prototype.toRed = function toRed (ctx) {
12925 assert(!this.red, 'Already a number in reduction context');
12926 assert(this.negative === 0, 'red works only with positives');
12927 return ctx.convertTo(this)._forceRed(ctx);
12928 };
12929
12930 BN.prototype.fromRed = function fromRed () {
12931 assert(this.red, 'fromRed works only with numbers in reduction context');
12932 return this.red.convertFrom(this);
12933 };
12934
12935 BN.prototype._forceRed = function _forceRed (ctx) {
12936 this.red = ctx;
12937 return this;
12938 };
12939
12940 BN.prototype.forceRed = function forceRed (ctx) {
12941 assert(!this.red, 'Already a number in reduction context');
12942 return this._forceRed(ctx);
12943 };
12944
12945 BN.prototype.redAdd = function redAdd (num) {
12946 assert(this.red, 'redAdd works only with red numbers');
12947 return this.red.add(this, num);
12948 };
12949
12950 BN.prototype.redIAdd = function redIAdd (num) {
12951 assert(this.red, 'redIAdd works only with red numbers');
12952 return this.red.iadd(this, num);
12953 };
12954
12955 BN.prototype.redSub = function redSub (num) {
12956 assert(this.red, 'redSub works only with red numbers');
12957 return this.red.sub(this, num);
12958 };
12959
12960 BN.prototype.redISub = function redISub (num) {
12961 assert(this.red, 'redISub works only with red numbers');
12962 return this.red.isub(this, num);
12963 };
12964
12965 BN.prototype.redShl = function redShl (num) {
12966 assert(this.red, 'redShl works only with red numbers');
12967 return this.red.shl(this, num);
12968 };
12969
12970 BN.prototype.redMul = function redMul (num) {
12971 assert(this.red, 'redMul works only with red numbers');
12972 this.red._verify2(this, num);
12973 return this.red.mul(this, num);
12974 };
12975
12976 BN.prototype.redIMul = function redIMul (num) {
12977 assert(this.red, 'redMul works only with red numbers');
12978 this.red._verify2(this, num);
12979 return this.red.imul(this, num);
12980 };
12981
12982 BN.prototype.redSqr = function redSqr () {
12983 assert(this.red, 'redSqr works only with red numbers');
12984 this.red._verify1(this);
12985 return this.red.sqr(this);
12986 };
12987
12988 BN.prototype.redISqr = function redISqr () {
12989 assert(this.red, 'redISqr works only with red numbers');
12990 this.red._verify1(this);
12991 return this.red.isqr(this);
12992 };
12993
12994 // Square root over p
12995 BN.prototype.redSqrt = function redSqrt () {
12996 assert(this.red, 'redSqrt works only with red numbers');
12997 this.red._verify1(this);
12998 return this.red.sqrt(this);
12999 };
13000
13001 BN.prototype.redInvm = function redInvm () {
13002 assert(this.red, 'redInvm works only with red numbers');
13003 this.red._verify1(this);
13004 return this.red.invm(this);
13005 };
13006
13007 // Return negative clone of `this` % `red modulo`
13008 BN.prototype.redNeg = function redNeg () {
13009 assert(this.red, 'redNeg works only with red numbers');
13010 this.red._verify1(this);
13011 return this.red.neg(this);
13012 };
13013
13014 BN.prototype.redPow = function redPow (num) {
13015 assert(this.red && !num.red, 'redPow(normalNum)');
13016 this.red._verify1(this);
13017 return this.red.pow(this, num);
13018 };
13019
13020 // Prime numbers with efficient reduction
13021 var primes = {
13022 k256: null,
13023 p224: null,
13024 p192: null,
13025 p25519: null
13026 };
13027
13028 // Pseudo-Mersenne prime
13029 function MPrime (name, p) {
13030 // P = 2 ^ N - K
13031 this.name = name;
13032 this.p = new BN(p, 16);
13033 this.n = this.p.bitLength();
13034 this.k = new BN(1).iushln(this.n).isub(this.p);
13035
13036 this.tmp = this._tmp();
13037 }
13038
13039 MPrime.prototype._tmp = function _tmp () {
13040 var tmp = new BN(null);
13041 tmp.words = new Array(Math.ceil(this.n / 13));
13042 return tmp;
13043 };
13044
13045 MPrime.prototype.ireduce = function ireduce (num) {
13046 // Assumes that `num` is less than `P^2`
13047 // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P)
13048 var r = num;
13049 var rlen;
13050
13051 do {
13052 this.split(r, this.tmp);
13053 r = this.imulK(r);
13054 r = r.iadd(this.tmp);
13055 rlen = r.bitLength();
13056 } while (rlen > this.n);
13057
13058 var cmp = rlen < this.n ? -1 : r.ucmp(this.p);
13059 if (cmp === 0) {
13060 r.words[0] = 0;
13061 r.length = 1;
13062 } else if (cmp > 0) {
13063 r.isub(this.p);
13064 } else {
13065 r.strip();
13066 }
13067
13068 return r;
13069 };
13070
13071 MPrime.prototype.split = function split (input, out) {
13072 input.iushrn(this.n, 0, out);
13073 };
13074
13075 MPrime.prototype.imulK = function imulK (num) {
13076 return num.imul(this.k);
13077 };
13078
13079 function K256 () {
13080 MPrime.call(
13081 this,
13082 'k256',
13083 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
13084 }
13085 inherits(K256, MPrime);
13086
13087 K256.prototype.split = function split (input, output) {
13088 // 256 = 9 * 26 + 22
13089 var mask = 0x3fffff;
13090
13091 var outLen = Math.min(input.length, 9);
13092 for (var i = 0; i < outLen; i++) {
13093 output.words[i] = input.words[i];
13094 }
13095 output.length = outLen;
13096
13097 if (input.length <= 9) {
13098 input.words[0] = 0;
13099 input.length = 1;
13100 return;
13101 }
13102
13103 // Shift by 9 limbs
13104 var prev = input.words[9];
13105 output.words[output.length++] = prev & mask;
13106
13107 for (i = 10; i < input.length; i++) {
13108 var next = input.words[i] | 0;
13109 input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22);
13110 prev = next;
13111 }
13112 prev >>>= 22;
13113 input.words[i - 10] = prev;
13114 if (prev === 0 && input.length > 10) {
13115 input.length -= 10;
13116 } else {
13117 input.length -= 9;
13118 }
13119 };
13120
13121 K256.prototype.imulK = function imulK (num) {
13122 // K = 0x1000003d1 = [ 0x40, 0x3d1 ]
13123 num.words[num.length] = 0;
13124 num.words[num.length + 1] = 0;
13125 num.length += 2;
13126
13127 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
13128 var lo = 0;
13129 for (var i = 0; i < num.length; i++) {
13130 var w = num.words[i] | 0;
13131 lo += w * 0x3d1;
13132 num.words[i] = lo & 0x3ffffff;
13133 lo = w * 0x40 + ((lo / 0x4000000) | 0);
13134 }
13135
13136 // Fast length reduction
13137 if (num.words[num.length - 1] === 0) {
13138 num.length--;
13139 if (num.words[num.length - 1] === 0) {
13140 num.length--;
13141 }
13142 }
13143 return num;
13144 };
13145
13146 function P224 () {
13147 MPrime.call(
13148 this,
13149 'p224',
13150 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
13151 }
13152 inherits(P224, MPrime);
13153
13154 function P192 () {
13155 MPrime.call(
13156 this,
13157 'p192',
13158 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
13159 }
13160 inherits(P192, MPrime);
13161
13162 function P25519 () {
13163 // 2 ^ 255 - 19
13164 MPrime.call(
13165 this,
13166 '25519',
13167 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
13168 }
13169 inherits(P25519, MPrime);
13170
13171 P25519.prototype.imulK = function imulK (num) {
13172 // K = 0x13
13173 var carry = 0;
13174 for (var i = 0; i < num.length; i++) {
13175 var hi = (num.words[i] | 0) * 0x13 + carry;
13176 var lo = hi & 0x3ffffff;
13177 hi >>>= 26;
13178
13179 num.words[i] = lo;
13180 carry = hi;
13181 }
13182 if (carry !== 0) {
13183 num.words[num.length++] = carry;
13184 }
13185 return num;
13186 };
13187
13188 // Exported mostly for testing purposes, use plain name instead
13189 BN._prime = function prime (name) {
13190 // Cached version of prime
13191 if (primes[name]) return primes[name];
13192
13193 var prime;
13194 if (name === 'k256') {
13195 prime = new K256();
13196 } else if (name === 'p224') {
13197 prime = new P224();
13198 } else if (name === 'p192') {
13199 prime = new P192();
13200 } else if (name === 'p25519') {
13201 prime = new P25519();
13202 } else {
13203 throw new Error('Unknown prime ' + name);
13204 }
13205 primes[name] = prime;
13206
13207 return prime;
13208 };
13209
13210 //
13211 // Base reduction engine
13212 //
13213 function Red (m) {
13214 if (typeof m === 'string') {
13215 var prime = BN._prime(m);
13216 this.m = prime.p;
13217 this.prime = prime;
13218 } else {
13219 assert(m.gtn(1), 'modulus must be greater than 1');
13220 this.m = m;
13221 this.prime = null;
13222 }
13223 }
13224
13225 Red.prototype._verify1 = function _verify1 (a) {
13226 assert(a.negative === 0, 'red works only with positives');
13227 assert(a.red, 'red works only with red numbers');
13228 };
13229
13230 Red.prototype._verify2 = function _verify2 (a, b) {
13231 assert((a.negative | b.negative) === 0, 'red works only with positives');
13232 assert(a.red && a.red === b.red,
13233 'red works only with red numbers');
13234 };
13235
13236 Red.prototype.imod = function imod (a) {
13237 if (this.prime) return this.prime.ireduce(a)._forceRed(this);
13238 return a.umod(this.m)._forceRed(this);
13239 };
13240
13241 Red.prototype.neg = function neg (a) {
13242 if (a.isZero()) {
13243 return a.clone();
13244 }
13245
13246 return this.m.sub(a)._forceRed(this);
13247 };
13248
13249 Red.prototype.add = function add (a, b) {
13250 this._verify2(a, b);
13251
13252 var res = a.add(b);
13253 if (res.cmp(this.m) >= 0) {
13254 res.isub(this.m);
13255 }
13256 return res._forceRed(this);
13257 };
13258
13259 Red.prototype.iadd = function iadd (a, b) {
13260 this._verify2(a, b);
13261
13262 var res = a.iadd(b);
13263 if (res.cmp(this.m) >= 0) {
13264 res.isub(this.m);
13265 }
13266 return res;
13267 };
13268
13269 Red.prototype.sub = function sub (a, b) {
13270 this._verify2(a, b);
13271
13272 var res = a.sub(b);
13273 if (res.cmpn(0) < 0) {
13274 res.iadd(this.m);
13275 }
13276 return res._forceRed(this);
13277 };
13278
13279 Red.prototype.isub = function isub (a, b) {
13280 this._verify2(a, b);
13281
13282 var res = a.isub(b);
13283 if (res.cmpn(0) < 0) {
13284 res.iadd(this.m);
13285 }
13286 return res;
13287 };
13288
13289 Red.prototype.shl = function shl (a, num) {
13290 this._verify1(a);
13291 return this.imod(a.ushln(num));
13292 };
13293
13294 Red.prototype.imul = function imul (a, b) {
13295 this._verify2(a, b);
13296 return this.imod(a.imul(b));
13297 };
13298
13299 Red.prototype.mul = function mul (a, b) {
13300 this._verify2(a, b);
13301 return this.imod(a.mul(b));
13302 };
13303
13304 Red.prototype.isqr = function isqr (a) {
13305 return this.imul(a, a.clone());
13306 };
13307
13308 Red.prototype.sqr = function sqr (a) {
13309 return this.mul(a, a);
13310 };
13311
13312 Red.prototype.sqrt = function sqrt (a) {
13313 if (a.isZero()) return a.clone();
13314
13315 var mod3 = this.m.andln(3);
13316 assert(mod3 % 2 === 1);
13317
13318 // Fast case
13319 if (mod3 === 3) {
13320 var pow = this.m.add(new BN(1)).iushrn(2);
13321 return this.pow(a, pow);
13322 }
13323
13324 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
13325 //
13326 // Find Q and S, that Q * 2 ^ S = (P - 1)
13327 var q = this.m.subn(1);
13328 var s = 0;
13329 while (!q.isZero() && q.andln(1) === 0) {
13330 s++;
13331 q.iushrn(1);
13332 }
13333 assert(!q.isZero());
13334
13335 var one = new BN(1).toRed(this);
13336 var nOne = one.redNeg();
13337
13338 // Find quadratic non-residue
13339 // NOTE: Max is such because of generalized Riemann hypothesis.
13340 var lpow = this.m.subn(1).iushrn(1);
13341 var z = this.m.bitLength();
13342 z = new BN(2 * z * z).toRed(this);
13343
13344 while (this.pow(z, lpow).cmp(nOne) !== 0) {
13345 z.redIAdd(nOne);
13346 }
13347
13348 var c = this.pow(z, q);
13349 var r = this.pow(a, q.addn(1).iushrn(1));
13350 var t = this.pow(a, q);
13351 var m = s;
13352 while (t.cmp(one) !== 0) {
13353 var tmp = t;
13354 for (var i = 0; tmp.cmp(one) !== 0; i++) {
13355 tmp = tmp.redSqr();
13356 }
13357 assert(i < m);
13358 var b = this.pow(c, new BN(1).iushln(m - i - 1));
13359
13360 r = r.redMul(b);
13361 c = b.redSqr();
13362 t = t.redMul(c);
13363 m = i;
13364 }
13365
13366 return r;
13367 };
13368
13369 Red.prototype.invm = function invm (a) {
13370 var inv = a._invmp(this.m);
13371 if (inv.negative !== 0) {
13372 inv.negative = 0;
13373 return this.imod(inv).redNeg();
13374 } else {
13375 return this.imod(inv);
13376 }
13377 };
13378
13379 Red.prototype.pow = function pow (a, num) {
13380 if (num.isZero()) return new BN(1).toRed(this);
13381 if (num.cmpn(1) === 0) return a.clone();
13382
13383 var windowSize = 4;
13384 var wnd = new Array(1 << windowSize);
13385 wnd[0] = new BN(1).toRed(this);
13386 wnd[1] = a;
13387 for (var i = 2; i < wnd.length; i++) {
13388 wnd[i] = this.mul(wnd[i - 1], a);
13389 }
13390
13391 var res = wnd[0];
13392 var current = 0;
13393 var currentLen = 0;
13394 var start = num.bitLength() % 26;
13395 if (start === 0) {
13396 start = 26;
13397 }
13398
13399 for (i = num.length - 1; i >= 0; i--) {
13400 var word = num.words[i];
13401 for (var j = start - 1; j >= 0; j--) {
13402 var bit = (word >> j) & 1;
13403 if (res !== wnd[0]) {
13404 res = this.sqr(res);
13405 }
13406
13407 if (bit === 0 && current === 0) {
13408 currentLen = 0;
13409 continue;
13410 }
13411
13412 current <<= 1;
13413 current |= bit;
13414 currentLen++;
13415 if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue;
13416
13417 res = this.mul(res, wnd[current]);
13418 currentLen = 0;
13419 current = 0;
13420 }
13421 start = 26;
13422 }
13423
13424 return res;
13425 };
13426
13427 Red.prototype.convertTo = function convertTo (num) {
13428 var r = num.umod(this.m);
13429
13430 return r === num ? r.clone() : r;
13431 };
13432
13433 Red.prototype.convertFrom = function convertFrom (num) {
13434 var res = num.clone();
13435 res.red = null;
13436 return res;
13437 };
13438
13439 //
13440 // Montgomery method engine
13441 //
13442
13443 BN.mont = function mont (num) {
13444 return new Mont(num);
13445 };
13446
13447 function Mont (m) {
13448 Red.call(this, m);
13449
13450 this.shift = this.m.bitLength();
13451 if (this.shift % 26 !== 0) {
13452 this.shift += 26 - (this.shift % 26);
13453 }
13454
13455 this.r = new BN(1).iushln(this.shift);
13456 this.r2 = this.imod(this.r.sqr());
13457 this.rinv = this.r._invmp(this.m);
13458
13459 this.minv = this.rinv.mul(this.r).isubn(1).div(this.m);
13460 this.minv = this.minv.umod(this.r);
13461 this.minv = this.r.sub(this.minv);
13462 }
13463 inherits(Mont, Red);
13464
13465 Mont.prototype.convertTo = function convertTo (num) {
13466 return this.imod(num.ushln(this.shift));
13467 };
13468
13469 Mont.prototype.convertFrom = function convertFrom (num) {
13470 var r = this.imod(num.mul(this.rinv));
13471 r.red = null;
13472 return r;
13473 };
13474
13475 Mont.prototype.imul = function imul (a, b) {
13476 if (a.isZero() || b.isZero()) {
13477 a.words[0] = 0;
13478 a.length = 1;
13479 return a;
13480 }
13481
13482 var t = a.imul(b);
13483 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
13484 var u = t.isub(c).iushrn(this.shift);
13485 var res = u;
13486
13487 if (u.cmp(this.m) >= 0) {
13488 res = u.isub(this.m);
13489 } else if (u.cmpn(0) < 0) {
13490 res = u.iadd(this.m);
13491 }
13492
13493 return res._forceRed(this);
13494 };
13495
13496 Mont.prototype.mul = function mul (a, b) {
13497 if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this);
13498
13499 var t = a.mul(b);
13500 var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m);
13501 var u = t.isub(c).iushrn(this.shift);
13502 var res = u;
13503 if (u.cmp(this.m) >= 0) {
13504 res = u.isub(this.m);
13505 } else if (u.cmpn(0) < 0) {
13506 res = u.iadd(this.m);
13507 }
13508
13509 return res._forceRed(this);
13510 };
13511
13512 Mont.prototype.invm = function invm (a) {
13513 // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R
13514 var res = this.imod(a._invmp(this.m).mul(this.r2));
13515 return res._forceRed(this);
13516 };
13517})(typeof module === 'undefined' || module, this);
13518
13519},{"buffer":77}],76:[function(require,module,exports){
13520var r;
13521
13522module.exports = function rand(len) {
13523 if (!r)
13524 r = new Rand(null);
13525
13526 return r.generate(len);
13527};
13528
13529function Rand(rand) {
13530 this.rand = rand;
13531}
13532module.exports.Rand = Rand;
13533
13534Rand.prototype.generate = function generate(len) {
13535 return this._rand(len);
13536};
13537
13538// Emulate crypto API using randy
13539Rand.prototype._rand = function _rand(n) {
13540 if (this.rand.getBytes)
13541 return this.rand.getBytes(n);
13542
13543 var res = new Uint8Array(n);
13544 for (var i = 0; i < res.length; i++)
13545 res[i] = this.rand.getByte();
13546 return res;
13547};
13548
13549if (typeof self === 'object') {
13550 if (self.crypto && self.crypto.getRandomValues) {
13551 // Modern browsers
13552 Rand.prototype._rand = function _rand(n) {
13553 var arr = new Uint8Array(n);
13554 self.crypto.getRandomValues(arr);
13555 return arr;
13556 };
13557 } else if (self.msCrypto && self.msCrypto.getRandomValues) {
13558 // IE
13559 Rand.prototype._rand = function _rand(n) {
13560 var arr = new Uint8Array(n);
13561 self.msCrypto.getRandomValues(arr);
13562 return arr;
13563 };
13564
13565 // Safari's WebWorkers do not have `crypto`
13566 } else if (typeof window === 'object') {
13567 // Old junk
13568 Rand.prototype._rand = function() {
13569 throw new Error('Not implemented yet');
13570 };
13571 }
13572} else {
13573 // Node.js or Web worker with no crypto support
13574 try {
13575 var crypto = require('crypto');
13576 if (typeof crypto.randomBytes !== 'function')
13577 throw new Error('Not supported');
13578
13579 Rand.prototype._rand = function _rand(n) {
13580 return crypto.randomBytes(n);
13581 };
13582 } catch (e) {
13583 }
13584}
13585
13586},{"crypto":77}],77:[function(require,module,exports){
13587
13588},{}],78:[function(require,module,exports){
13589// based on the aes implimentation in triple sec
13590// https://github.com/keybase/triplesec
13591// which is in turn based on the one from crypto-js
13592// https://code.google.com/p/crypto-js/
13593
13594var Buffer = require('safe-buffer').Buffer
13595
13596function asUInt32Array (buf) {
13597 if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf)
13598
13599 var len = (buf.length / 4) | 0
13600 var out = new Array(len)
13601
13602 for (var i = 0; i < len; i++) {
13603 out[i] = buf.readUInt32BE(i * 4)
13604 }
13605
13606 return out
13607}
13608
13609function scrubVec (v) {
13610 for (var i = 0; i < v.length; v++) {
13611 v[i] = 0
13612 }
13613}
13614
13615function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) {
13616 var SUB_MIX0 = SUB_MIX[0]
13617 var SUB_MIX1 = SUB_MIX[1]
13618 var SUB_MIX2 = SUB_MIX[2]
13619 var SUB_MIX3 = SUB_MIX[3]
13620
13621 var s0 = M[0] ^ keySchedule[0]
13622 var s1 = M[1] ^ keySchedule[1]
13623 var s2 = M[2] ^ keySchedule[2]
13624 var s3 = M[3] ^ keySchedule[3]
13625 var t0, t1, t2, t3
13626 var ksRow = 4
13627
13628 for (var round = 1; round < nRounds; round++) {
13629 t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++]
13630 t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++]
13631 t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++]
13632 t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++]
13633 s0 = t0
13634 s1 = t1
13635 s2 = t2
13636 s3 = t3
13637 }
13638
13639 t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++]
13640 t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++]
13641 t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++]
13642 t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++]
13643 t0 = t0 >>> 0
13644 t1 = t1 >>> 0
13645 t2 = t2 >>> 0
13646 t3 = t3 >>> 0
13647
13648 return [t0, t1, t2, t3]
13649}
13650
13651// AES constants
13652var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
13653var G = (function () {
13654 // Compute double table
13655 var d = new Array(256)
13656 for (var j = 0; j < 256; j++) {
13657 if (j < 128) {
13658 d[j] = j << 1
13659 } else {
13660 d[j] = (j << 1) ^ 0x11b
13661 }
13662 }
13663
13664 var SBOX = []
13665 var INV_SBOX = []
13666 var SUB_MIX = [[], [], [], []]
13667 var INV_SUB_MIX = [[], [], [], []]
13668
13669 // Walk GF(2^8)
13670 var x = 0
13671 var xi = 0
13672 for (var i = 0; i < 256; ++i) {
13673 // Compute sbox
13674 var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4)
13675 sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63
13676 SBOX[x] = sx
13677 INV_SBOX[sx] = x
13678
13679 // Compute multiplication
13680 var x2 = d[x]
13681 var x4 = d[x2]
13682 var x8 = d[x4]
13683
13684 // Compute sub bytes, mix columns tables
13685 var t = (d[sx] * 0x101) ^ (sx * 0x1010100)
13686 SUB_MIX[0][x] = (t << 24) | (t >>> 8)
13687 SUB_MIX[1][x] = (t << 16) | (t >>> 16)
13688 SUB_MIX[2][x] = (t << 8) | (t >>> 24)
13689 SUB_MIX[3][x] = t
13690
13691 // Compute inv sub bytes, inv mix columns tables
13692 t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100)
13693 INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8)
13694 INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16)
13695 INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24)
13696 INV_SUB_MIX[3][sx] = t
13697
13698 if (x === 0) {
13699 x = xi = 1
13700 } else {
13701 x = x2 ^ d[d[d[x8 ^ x2]]]
13702 xi ^= d[d[xi]]
13703 }
13704 }
13705
13706 return {
13707 SBOX: SBOX,
13708 INV_SBOX: INV_SBOX,
13709 SUB_MIX: SUB_MIX,
13710 INV_SUB_MIX: INV_SUB_MIX
13711 }
13712})()
13713
13714function AES (key) {
13715 this._key = asUInt32Array(key)
13716 this._reset()
13717}
13718
13719AES.blockSize = 4 * 4
13720AES.keySize = 256 / 8
13721AES.prototype.blockSize = AES.blockSize
13722AES.prototype.keySize = AES.keySize
13723AES.prototype._reset = function () {
13724 var keyWords = this._key
13725 var keySize = keyWords.length
13726 var nRounds = keySize + 6
13727 var ksRows = (nRounds + 1) * 4
13728
13729 var keySchedule = []
13730 for (var k = 0; k < keySize; k++) {
13731 keySchedule[k] = keyWords[k]
13732 }
13733
13734 for (k = keySize; k < ksRows; k++) {
13735 var t = keySchedule[k - 1]
13736
13737 if (k % keySize === 0) {
13738 t = (t << 8) | (t >>> 24)
13739 t =
13740 (G.SBOX[t >>> 24] << 24) |
13741 (G.SBOX[(t >>> 16) & 0xff] << 16) |
13742 (G.SBOX[(t >>> 8) & 0xff] << 8) |
13743 (G.SBOX[t & 0xff])
13744
13745 t ^= RCON[(k / keySize) | 0] << 24
13746 } else if (keySize > 6 && k % keySize === 4) {
13747 t =
13748 (G.SBOX[t >>> 24] << 24) |
13749 (G.SBOX[(t >>> 16) & 0xff] << 16) |
13750 (G.SBOX[(t >>> 8) & 0xff] << 8) |
13751 (G.SBOX[t & 0xff])
13752 }
13753
13754 keySchedule[k] = keySchedule[k - keySize] ^ t
13755 }
13756
13757 var invKeySchedule = []
13758 for (var ik = 0; ik < ksRows; ik++) {
13759 var ksR = ksRows - ik
13760 var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)]
13761
13762 if (ik < 4 || ksR <= 4) {
13763 invKeySchedule[ik] = tt
13764 } else {
13765 invKeySchedule[ik] =
13766 G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^
13767 G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^
13768 G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^
13769 G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]]
13770 }
13771 }
13772
13773 this._nRounds = nRounds
13774 this._keySchedule = keySchedule
13775 this._invKeySchedule = invKeySchedule
13776}
13777
13778AES.prototype.encryptBlockRaw = function (M) {
13779 M = asUInt32Array(M)
13780 return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds)
13781}
13782
13783AES.prototype.encryptBlock = function (M) {
13784 var out = this.encryptBlockRaw(M)
13785 var buf = Buffer.allocUnsafe(16)
13786 buf.writeUInt32BE(out[0], 0)
13787 buf.writeUInt32BE(out[1], 4)
13788 buf.writeUInt32BE(out[2], 8)
13789 buf.writeUInt32BE(out[3], 12)
13790 return buf
13791}
13792
13793AES.prototype.decryptBlock = function (M) {
13794 M = asUInt32Array(M)
13795
13796 // swap
13797 var m1 = M[1]
13798 M[1] = M[3]
13799 M[3] = m1
13800
13801 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds)
13802 var buf = Buffer.allocUnsafe(16)
13803 buf.writeUInt32BE(out[0], 0)
13804 buf.writeUInt32BE(out[3], 4)
13805 buf.writeUInt32BE(out[2], 8)
13806 buf.writeUInt32BE(out[1], 12)
13807 return buf
13808}
13809
13810AES.prototype.scrub = function () {
13811 scrubVec(this._keySchedule)
13812 scrubVec(this._invKeySchedule)
13813 scrubVec(this._key)
13814}
13815
13816module.exports.AES = AES
13817
13818},{"safe-buffer":247}],79:[function(require,module,exports){
13819var aes = require('./aes')
13820var Buffer = require('safe-buffer').Buffer
13821var Transform = require('cipher-base')
13822var inherits = require('inherits')
13823var GHASH = require('./ghash')
13824var xor = require('buffer-xor')
13825var incr32 = require('./incr32')
13826
13827function xorTest (a, b) {
13828 var out = 0
13829 if (a.length !== b.length) out++
13830
13831 var len = Math.min(a.length, b.length)
13832 for (var i = 0; i < len; ++i) {
13833 out += (a[i] ^ b[i])
13834 }
13835
13836 return out
13837}
13838
13839function calcIv (self, iv, ck) {
13840 if (iv.length === 12) {
13841 self._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])])
13842 return Buffer.concat([iv, Buffer.from([0, 0, 0, 2])])
13843 }
13844 var ghash = new GHASH(ck)
13845 var len = iv.length
13846 var toPad = len % 16
13847 ghash.update(iv)
13848 if (toPad) {
13849 toPad = 16 - toPad
13850 ghash.update(Buffer.alloc(toPad, 0))
13851 }
13852 ghash.update(Buffer.alloc(8, 0))
13853 var ivBits = len * 8
13854 var tail = Buffer.alloc(8)
13855 tail.writeUIntBE(ivBits, 0, 8)
13856 ghash.update(tail)
13857 self._finID = ghash.state
13858 var out = Buffer.from(self._finID)
13859 incr32(out)
13860 return out
13861}
13862function StreamCipher (mode, key, iv, decrypt) {
13863 Transform.call(this)
13864
13865 var h = Buffer.alloc(4, 0)
13866
13867 this._cipher = new aes.AES(key)
13868 var ck = this._cipher.encryptBlock(h)
13869 this._ghash = new GHASH(ck)
13870 iv = calcIv(this, iv, ck)
13871
13872 this._prev = Buffer.from(iv)
13873 this._cache = Buffer.allocUnsafe(0)
13874 this._secCache = Buffer.allocUnsafe(0)
13875 this._decrypt = decrypt
13876 this._alen = 0
13877 this._len = 0
13878 this._mode = mode
13879
13880 this._authTag = null
13881 this._called = false
13882}
13883
13884inherits(StreamCipher, Transform)
13885
13886StreamCipher.prototype._update = function (chunk) {
13887 if (!this._called && this._alen) {
13888 var rump = 16 - (this._alen % 16)
13889 if (rump < 16) {
13890 rump = Buffer.alloc(rump, 0)
13891 this._ghash.update(rump)
13892 }
13893 }
13894
13895 this._called = true
13896 var out = this._mode.encrypt(this, chunk)
13897 if (this._decrypt) {
13898 this._ghash.update(chunk)
13899 } else {
13900 this._ghash.update(out)
13901 }
13902 this._len += chunk.length
13903 return out
13904}
13905
13906StreamCipher.prototype._final = function () {
13907 if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data')
13908
13909 var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID))
13910 if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data')
13911
13912 this._authTag = tag
13913 this._cipher.scrub()
13914}
13915
13916StreamCipher.prototype.getAuthTag = function getAuthTag () {
13917 if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state')
13918
13919 return this._authTag
13920}
13921
13922StreamCipher.prototype.setAuthTag = function setAuthTag (tag) {
13923 if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state')
13924
13925 this._authTag = tag
13926}
13927
13928StreamCipher.prototype.setAAD = function setAAD (buf) {
13929 if (this._called) throw new Error('Attempting to set AAD in unsupported state')
13930
13931 this._ghash.update(buf)
13932 this._alen += buf.length
13933}
13934
13935module.exports = StreamCipher
13936
13937},{"./aes":78,"./ghash":83,"./incr32":84,"buffer-xor":106,"cipher-base":108,"inherits":163,"safe-buffer":247}],80:[function(require,module,exports){
13938var ciphers = require('./encrypter')
13939var deciphers = require('./decrypter')
13940var modes = require('./modes/list.json')
13941
13942function getCiphers () {
13943 return Object.keys(modes)
13944}
13945
13946exports.createCipher = exports.Cipher = ciphers.createCipher
13947exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv
13948exports.createDecipher = exports.Decipher = deciphers.createDecipher
13949exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv
13950exports.listCiphers = exports.getCiphers = getCiphers
13951
13952},{"./decrypter":81,"./encrypter":82,"./modes/list.json":92}],81:[function(require,module,exports){
13953var AuthCipher = require('./authCipher')
13954var Buffer = require('safe-buffer').Buffer
13955var MODES = require('./modes')
13956var StreamCipher = require('./streamCipher')
13957var Transform = require('cipher-base')
13958var aes = require('./aes')
13959var ebtk = require('evp_bytestokey')
13960var inherits = require('inherits')
13961
13962function Decipher (mode, key, iv) {
13963 Transform.call(this)
13964
13965 this._cache = new Splitter()
13966 this._last = void 0
13967 this._cipher = new aes.AES(key)
13968 this._prev = Buffer.from(iv)
13969 this._mode = mode
13970 this._autopadding = true
13971}
13972
13973inherits(Decipher, Transform)
13974
13975Decipher.prototype._update = function (data) {
13976 this._cache.add(data)
13977 var chunk
13978 var thing
13979 var out = []
13980 while ((chunk = this._cache.get(this._autopadding))) {
13981 thing = this._mode.decrypt(this, chunk)
13982 out.push(thing)
13983 }
13984 return Buffer.concat(out)
13985}
13986
13987Decipher.prototype._final = function () {
13988 var chunk = this._cache.flush()
13989 if (this._autopadding) {
13990 return unpad(this._mode.decrypt(this, chunk))
13991 } else if (chunk) {
13992 throw new Error('data not multiple of block length')
13993 }
13994}
13995
13996Decipher.prototype.setAutoPadding = function (setTo) {
13997 this._autopadding = !!setTo
13998 return this
13999}
14000
14001function Splitter () {
14002 this.cache = Buffer.allocUnsafe(0)
14003}
14004
14005Splitter.prototype.add = function (data) {
14006 this.cache = Buffer.concat([this.cache, data])
14007}
14008
14009Splitter.prototype.get = function (autoPadding) {
14010 var out
14011 if (autoPadding) {
14012 if (this.cache.length > 16) {
14013 out = this.cache.slice(0, 16)
14014 this.cache = this.cache.slice(16)
14015 return out
14016 }
14017 } else {
14018 if (this.cache.length >= 16) {
14019 out = this.cache.slice(0, 16)
14020 this.cache = this.cache.slice(16)
14021 return out
14022 }
14023 }
14024
14025 return null
14026}
14027
14028Splitter.prototype.flush = function () {
14029 if (this.cache.length) return this.cache
14030}
14031
14032function unpad (last) {
14033 var padded = last[15]
14034 var i = -1
14035 while (++i < padded) {
14036 if (last[(i + (16 - padded))] !== padded) {
14037 throw new Error('unable to decrypt data')
14038 }
14039 }
14040 if (padded === 16) return
14041
14042 return last.slice(0, 16 - padded)
14043}
14044
14045function createDecipheriv (suite, password, iv) {
14046 var config = MODES[suite.toLowerCase()]
14047 if (!config) throw new TypeError('invalid suite type')
14048
14049 if (typeof iv === 'string') iv = Buffer.from(iv)
14050 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
14051
14052 if (typeof password === 'string') password = Buffer.from(password)
14053 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
14054
14055 if (config.type === 'stream') {
14056 return new StreamCipher(config.module, password, iv, true)
14057 } else if (config.type === 'auth') {
14058 return new AuthCipher(config.module, password, iv, true)
14059 }
14060
14061 return new Decipher(config.module, password, iv)
14062}
14063
14064function createDecipher (suite, password) {
14065 var config = MODES[suite.toLowerCase()]
14066 if (!config) throw new TypeError('invalid suite type')
14067
14068 var keys = ebtk(password, false, config.key, config.iv)
14069 return createDecipheriv(suite, keys.key, keys.iv)
14070}
14071
14072exports.createDecipher = createDecipher
14073exports.createDecipheriv = createDecipheriv
14074
14075},{"./aes":78,"./authCipher":79,"./modes":91,"./streamCipher":94,"cipher-base":108,"evp_bytestokey":144,"inherits":163,"safe-buffer":247}],82:[function(require,module,exports){
14076var MODES = require('./modes')
14077var AuthCipher = require('./authCipher')
14078var Buffer = require('safe-buffer').Buffer
14079var StreamCipher = require('./streamCipher')
14080var Transform = require('cipher-base')
14081var aes = require('./aes')
14082var ebtk = require('evp_bytestokey')
14083var inherits = require('inherits')
14084
14085function Cipher (mode, key, iv) {
14086 Transform.call(this)
14087
14088 this._cache = new Splitter()
14089 this._cipher = new aes.AES(key)
14090 this._prev = Buffer.from(iv)
14091 this._mode = mode
14092 this._autopadding = true
14093}
14094
14095inherits(Cipher, Transform)
14096
14097Cipher.prototype._update = function (data) {
14098 this._cache.add(data)
14099 var chunk
14100 var thing
14101 var out = []
14102
14103 while ((chunk = this._cache.get())) {
14104 thing = this._mode.encrypt(this, chunk)
14105 out.push(thing)
14106 }
14107
14108 return Buffer.concat(out)
14109}
14110
14111var PADDING = Buffer.alloc(16, 0x10)
14112
14113Cipher.prototype._final = function () {
14114 var chunk = this._cache.flush()
14115 if (this._autopadding) {
14116 chunk = this._mode.encrypt(this, chunk)
14117 this._cipher.scrub()
14118 return chunk
14119 }
14120
14121 if (!chunk.equals(PADDING)) {
14122 this._cipher.scrub()
14123 throw new Error('data not multiple of block length')
14124 }
14125}
14126
14127Cipher.prototype.setAutoPadding = function (setTo) {
14128 this._autopadding = !!setTo
14129 return this
14130}
14131
14132function Splitter () {
14133 this.cache = Buffer.allocUnsafe(0)
14134}
14135
14136Splitter.prototype.add = function (data) {
14137 this.cache = Buffer.concat([this.cache, data])
14138}
14139
14140Splitter.prototype.get = function () {
14141 if (this.cache.length > 15) {
14142 var out = this.cache.slice(0, 16)
14143 this.cache = this.cache.slice(16)
14144 return out
14145 }
14146 return null
14147}
14148
14149Splitter.prototype.flush = function () {
14150 var len = 16 - this.cache.length
14151 var padBuff = Buffer.allocUnsafe(len)
14152
14153 var i = -1
14154 while (++i < len) {
14155 padBuff.writeUInt8(len, i)
14156 }
14157
14158 return Buffer.concat([this.cache, padBuff])
14159}
14160
14161function createCipheriv (suite, password, iv) {
14162 var config = MODES[suite.toLowerCase()]
14163 if (!config) throw new TypeError('invalid suite type')
14164
14165 if (typeof password === 'string') password = Buffer.from(password)
14166 if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length)
14167
14168 if (typeof iv === 'string') iv = Buffer.from(iv)
14169 if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length)
14170
14171 if (config.type === 'stream') {
14172 return new StreamCipher(config.module, password, iv)
14173 } else if (config.type === 'auth') {
14174 return new AuthCipher(config.module, password, iv)
14175 }
14176
14177 return new Cipher(config.module, password, iv)
14178}
14179
14180function createCipher (suite, password) {
14181 var config = MODES[suite.toLowerCase()]
14182 if (!config) throw new TypeError('invalid suite type')
14183
14184 var keys = ebtk(password, false, config.key, config.iv)
14185 return createCipheriv(suite, keys.key, keys.iv)
14186}
14187
14188exports.createCipheriv = createCipheriv
14189exports.createCipher = createCipher
14190
14191},{"./aes":78,"./authCipher":79,"./modes":91,"./streamCipher":94,"cipher-base":108,"evp_bytestokey":144,"inherits":163,"safe-buffer":247}],83:[function(require,module,exports){
14192var Buffer = require('safe-buffer').Buffer
14193var ZEROES = Buffer.alloc(16, 0)
14194
14195function toArray (buf) {
14196 return [
14197 buf.readUInt32BE(0),
14198 buf.readUInt32BE(4),
14199 buf.readUInt32BE(8),
14200 buf.readUInt32BE(12)
14201 ]
14202}
14203
14204function fromArray (out) {
14205 var buf = Buffer.allocUnsafe(16)
14206 buf.writeUInt32BE(out[0] >>> 0, 0)
14207 buf.writeUInt32BE(out[1] >>> 0, 4)
14208 buf.writeUInt32BE(out[2] >>> 0, 8)
14209 buf.writeUInt32BE(out[3] >>> 0, 12)
14210 return buf
14211}
14212
14213function GHASH (key) {
14214 this.h = key
14215 this.state = Buffer.alloc(16, 0)
14216 this.cache = Buffer.allocUnsafe(0)
14217}
14218
14219// from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
14220// by Juho Vähä-Herttua
14221GHASH.prototype.ghash = function (block) {
14222 var i = -1
14223 while (++i < block.length) {
14224 this.state[i] ^= block[i]
14225 }
14226 this._multiply()
14227}
14228
14229GHASH.prototype._multiply = function () {
14230 var Vi = toArray(this.h)
14231 var Zi = [0, 0, 0, 0]
14232 var j, xi, lsbVi
14233 var i = -1
14234 while (++i < 128) {
14235 xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0
14236 if (xi) {
14237 // Z_i+1 = Z_i ^ V_i
14238 Zi[0] ^= Vi[0]
14239 Zi[1] ^= Vi[1]
14240 Zi[2] ^= Vi[2]
14241 Zi[3] ^= Vi[3]
14242 }
14243
14244 // Store the value of LSB(V_i)
14245 lsbVi = (Vi[3] & 1) !== 0
14246
14247 // V_i+1 = V_i >> 1
14248 for (j = 3; j > 0; j--) {
14249 Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31)
14250 }
14251 Vi[0] = Vi[0] >>> 1
14252
14253 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
14254 if (lsbVi) {
14255 Vi[0] = Vi[0] ^ (0xe1 << 24)
14256 }
14257 }
14258 this.state = fromArray(Zi)
14259}
14260
14261GHASH.prototype.update = function (buf) {
14262 this.cache = Buffer.concat([this.cache, buf])
14263 var chunk
14264 while (this.cache.length >= 16) {
14265 chunk = this.cache.slice(0, 16)
14266 this.cache = this.cache.slice(16)
14267 this.ghash(chunk)
14268 }
14269}
14270
14271GHASH.prototype.final = function (abl, bl) {
14272 if (this.cache.length) {
14273 this.ghash(Buffer.concat([this.cache, ZEROES], 16))
14274 }
14275
14276 this.ghash(fromArray([0, abl, 0, bl]))
14277 return this.state
14278}
14279
14280module.exports = GHASH
14281
14282},{"safe-buffer":247}],84:[function(require,module,exports){
14283function incr32 (iv) {
14284 var len = iv.length
14285 var item
14286 while (len--) {
14287 item = iv.readUInt8(len)
14288 if (item === 255) {
14289 iv.writeUInt8(0, len)
14290 } else {
14291 item++
14292 iv.writeUInt8(item, len)
14293 break
14294 }
14295 }
14296}
14297module.exports = incr32
14298
14299},{}],85:[function(require,module,exports){
14300var xor = require('buffer-xor')
14301
14302exports.encrypt = function (self, block) {
14303 var data = xor(block, self._prev)
14304
14305 self._prev = self._cipher.encryptBlock(data)
14306 return self._prev
14307}
14308
14309exports.decrypt = function (self, block) {
14310 var pad = self._prev
14311
14312 self._prev = block
14313 var out = self._cipher.decryptBlock(block)
14314
14315 return xor(out, pad)
14316}
14317
14318},{"buffer-xor":106}],86:[function(require,module,exports){
14319var Buffer = require('safe-buffer').Buffer
14320var xor = require('buffer-xor')
14321
14322function encryptStart (self, data, decrypt) {
14323 var len = data.length
14324 var out = xor(data, self._cache)
14325 self._cache = self._cache.slice(len)
14326 self._prev = Buffer.concat([self._prev, decrypt ? data : out])
14327 return out
14328}
14329
14330exports.encrypt = function (self, data, decrypt) {
14331 var out = Buffer.allocUnsafe(0)
14332 var len
14333
14334 while (data.length) {
14335 if (self._cache.length === 0) {
14336 self._cache = self._cipher.encryptBlock(self._prev)
14337 self._prev = Buffer.allocUnsafe(0)
14338 }
14339
14340 if (self._cache.length <= data.length) {
14341 len = self._cache.length
14342 out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)])
14343 data = data.slice(len)
14344 } else {
14345 out = Buffer.concat([out, encryptStart(self, data, decrypt)])
14346 break
14347 }
14348 }
14349
14350 return out
14351}
14352
14353},{"buffer-xor":106,"safe-buffer":247}],87:[function(require,module,exports){
14354var Buffer = require('safe-buffer').Buffer
14355
14356function encryptByte (self, byteParam, decrypt) {
14357 var pad
14358 var i = -1
14359 var len = 8
14360 var out = 0
14361 var bit, value
14362 while (++i < len) {
14363 pad = self._cipher.encryptBlock(self._prev)
14364 bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0
14365 value = pad[0] ^ bit
14366 out += ((value & 0x80) >> (i % 8))
14367 self._prev = shiftIn(self._prev, decrypt ? bit : value)
14368 }
14369 return out
14370}
14371
14372function shiftIn (buffer, value) {
14373 var len = buffer.length
14374 var i = -1
14375 var out = Buffer.allocUnsafe(buffer.length)
14376 buffer = Buffer.concat([buffer, Buffer.from([value])])
14377
14378 while (++i < len) {
14379 out[i] = buffer[i] << 1 | buffer[i + 1] >> (7)
14380 }
14381
14382 return out
14383}
14384
14385exports.encrypt = function (self, chunk, decrypt) {
14386 var len = chunk.length
14387 var out = Buffer.allocUnsafe(len)
14388 var i = -1
14389
14390 while (++i < len) {
14391 out[i] = encryptByte(self, chunk[i], decrypt)
14392 }
14393
14394 return out
14395}
14396
14397},{"safe-buffer":247}],88:[function(require,module,exports){
14398var Buffer = require('safe-buffer').Buffer
14399
14400function encryptByte (self, byteParam, decrypt) {
14401 var pad = self._cipher.encryptBlock(self._prev)
14402 var out = pad[0] ^ byteParam
14403
14404 self._prev = Buffer.concat([
14405 self._prev.slice(1),
14406 Buffer.from([decrypt ? byteParam : out])
14407 ])
14408
14409 return out
14410}
14411
14412exports.encrypt = function (self, chunk, decrypt) {
14413 var len = chunk.length
14414 var out = Buffer.allocUnsafe(len)
14415 var i = -1
14416
14417 while (++i < len) {
14418 out[i] = encryptByte(self, chunk[i], decrypt)
14419 }
14420
14421 return out
14422}
14423
14424},{"safe-buffer":247}],89:[function(require,module,exports){
14425var xor = require('buffer-xor')
14426var Buffer = require('safe-buffer').Buffer
14427var incr32 = require('../incr32')
14428
14429function getBlock (self) {
14430 var out = self._cipher.encryptBlockRaw(self._prev)
14431 incr32(self._prev)
14432 return out
14433}
14434
14435var blockSize = 16
14436exports.encrypt = function (self, chunk) {
14437 var chunkNum = Math.ceil(chunk.length / blockSize)
14438 var start = self._cache.length
14439 self._cache = Buffer.concat([
14440 self._cache,
14441 Buffer.allocUnsafe(chunkNum * blockSize)
14442 ])
14443 for (var i = 0; i < chunkNum; i++) {
14444 var out = getBlock(self)
14445 var offset = start + i * blockSize
14446 self._cache.writeUInt32BE(out[0], offset + 0)
14447 self._cache.writeUInt32BE(out[1], offset + 4)
14448 self._cache.writeUInt32BE(out[2], offset + 8)
14449 self._cache.writeUInt32BE(out[3], offset + 12)
14450 }
14451 var pad = self._cache.slice(0, chunk.length)
14452 self._cache = self._cache.slice(chunk.length)
14453 return xor(chunk, pad)
14454}
14455
14456},{"../incr32":84,"buffer-xor":106,"safe-buffer":247}],90:[function(require,module,exports){
14457exports.encrypt = function (self, block) {
14458 return self._cipher.encryptBlock(block)
14459}
14460
14461exports.decrypt = function (self, block) {
14462 return self._cipher.decryptBlock(block)
14463}
14464
14465},{}],91:[function(require,module,exports){
14466var modeModules = {
14467 ECB: require('./ecb'),
14468 CBC: require('./cbc'),
14469 CFB: require('./cfb'),
14470 CFB8: require('./cfb8'),
14471 CFB1: require('./cfb1'),
14472 OFB: require('./ofb'),
14473 CTR: require('./ctr'),
14474 GCM: require('./ctr')
14475}
14476
14477var modes = require('./list.json')
14478
14479for (var key in modes) {
14480 modes[key].module = modeModules[modes[key].mode]
14481}
14482
14483module.exports = modes
14484
14485},{"./cbc":85,"./cfb":86,"./cfb1":87,"./cfb8":88,"./ctr":89,"./ecb":90,"./list.json":92,"./ofb":93}],92:[function(require,module,exports){
14486module.exports={
14487 "aes-128-ecb": {
14488 "cipher": "AES",
14489 "key": 128,
14490 "iv": 0,
14491 "mode": "ECB",
14492 "type": "block"
14493 },
14494 "aes-192-ecb": {
14495 "cipher": "AES",
14496 "key": 192,
14497 "iv": 0,
14498 "mode": "ECB",
14499 "type": "block"
14500 },
14501 "aes-256-ecb": {
14502 "cipher": "AES",
14503 "key": 256,
14504 "iv": 0,
14505 "mode": "ECB",
14506 "type": "block"
14507 },
14508 "aes-128-cbc": {
14509 "cipher": "AES",
14510 "key": 128,
14511 "iv": 16,
14512 "mode": "CBC",
14513 "type": "block"
14514 },
14515 "aes-192-cbc": {
14516 "cipher": "AES",
14517 "key": 192,
14518 "iv": 16,
14519 "mode": "CBC",
14520 "type": "block"
14521 },
14522 "aes-256-cbc": {
14523 "cipher": "AES",
14524 "key": 256,
14525 "iv": 16,
14526 "mode": "CBC",
14527 "type": "block"
14528 },
14529 "aes128": {
14530 "cipher": "AES",
14531 "key": 128,
14532 "iv": 16,
14533 "mode": "CBC",
14534 "type": "block"
14535 },
14536 "aes192": {
14537 "cipher": "AES",
14538 "key": 192,
14539 "iv": 16,
14540 "mode": "CBC",
14541 "type": "block"
14542 },
14543 "aes256": {
14544 "cipher": "AES",
14545 "key": 256,
14546 "iv": 16,
14547 "mode": "CBC",
14548 "type": "block"
14549 },
14550 "aes-128-cfb": {
14551 "cipher": "AES",
14552 "key": 128,
14553 "iv": 16,
14554 "mode": "CFB",
14555 "type": "stream"
14556 },
14557 "aes-192-cfb": {
14558 "cipher": "AES",
14559 "key": 192,
14560 "iv": 16,
14561 "mode": "CFB",
14562 "type": "stream"
14563 },
14564 "aes-256-cfb": {
14565 "cipher": "AES",
14566 "key": 256,
14567 "iv": 16,
14568 "mode": "CFB",
14569 "type": "stream"
14570 },
14571 "aes-128-cfb8": {
14572 "cipher": "AES",
14573 "key": 128,
14574 "iv": 16,
14575 "mode": "CFB8",
14576 "type": "stream"
14577 },
14578 "aes-192-cfb8": {
14579 "cipher": "AES",
14580 "key": 192,
14581 "iv": 16,
14582 "mode": "CFB8",
14583 "type": "stream"
14584 },
14585 "aes-256-cfb8": {
14586 "cipher": "AES",
14587 "key": 256,
14588 "iv": 16,
14589 "mode": "CFB8",
14590 "type": "stream"
14591 },
14592 "aes-128-cfb1": {
14593 "cipher": "AES",
14594 "key": 128,
14595 "iv": 16,
14596 "mode": "CFB1",
14597 "type": "stream"
14598 },
14599 "aes-192-cfb1": {
14600 "cipher": "AES",
14601 "key": 192,
14602 "iv": 16,
14603 "mode": "CFB1",
14604 "type": "stream"
14605 },
14606 "aes-256-cfb1": {
14607 "cipher": "AES",
14608 "key": 256,
14609 "iv": 16,
14610 "mode": "CFB1",
14611 "type": "stream"
14612 },
14613 "aes-128-ofb": {
14614 "cipher": "AES",
14615 "key": 128,
14616 "iv": 16,
14617 "mode": "OFB",
14618 "type": "stream"
14619 },
14620 "aes-192-ofb": {
14621 "cipher": "AES",
14622 "key": 192,
14623 "iv": 16,
14624 "mode": "OFB",
14625 "type": "stream"
14626 },
14627 "aes-256-ofb": {
14628 "cipher": "AES",
14629 "key": 256,
14630 "iv": 16,
14631 "mode": "OFB",
14632 "type": "stream"
14633 },
14634 "aes-128-ctr": {
14635 "cipher": "AES",
14636 "key": 128,
14637 "iv": 16,
14638 "mode": "CTR",
14639 "type": "stream"
14640 },
14641 "aes-192-ctr": {
14642 "cipher": "AES",
14643 "key": 192,
14644 "iv": 16,
14645 "mode": "CTR",
14646 "type": "stream"
14647 },
14648 "aes-256-ctr": {
14649 "cipher": "AES",
14650 "key": 256,
14651 "iv": 16,
14652 "mode": "CTR",
14653 "type": "stream"
14654 },
14655 "aes-128-gcm": {
14656 "cipher": "AES",
14657 "key": 128,
14658 "iv": 12,
14659 "mode": "GCM",
14660 "type": "auth"
14661 },
14662 "aes-192-gcm": {
14663 "cipher": "AES",
14664 "key": 192,
14665 "iv": 12,
14666 "mode": "GCM",
14667 "type": "auth"
14668 },
14669 "aes-256-gcm": {
14670 "cipher": "AES",
14671 "key": 256,
14672 "iv": 12,
14673 "mode": "GCM",
14674 "type": "auth"
14675 }
14676}
14677
14678},{}],93:[function(require,module,exports){
14679(function (Buffer){
14680var xor = require('buffer-xor')
14681
14682function getBlock (self) {
14683 self._prev = self._cipher.encryptBlock(self._prev)
14684 return self._prev
14685}
14686
14687exports.encrypt = function (self, chunk) {
14688 while (self._cache.length < chunk.length) {
14689 self._cache = Buffer.concat([self._cache, getBlock(self)])
14690 }
14691
14692 var pad = self._cache.slice(0, chunk.length)
14693 self._cache = self._cache.slice(chunk.length)
14694 return xor(chunk, pad)
14695}
14696
14697}).call(this,require("buffer").Buffer)
14698},{"buffer":107,"buffer-xor":106}],94:[function(require,module,exports){
14699var aes = require('./aes')
14700var Buffer = require('safe-buffer').Buffer
14701var Transform = require('cipher-base')
14702var inherits = require('inherits')
14703
14704function StreamCipher (mode, key, iv, decrypt) {
14705 Transform.call(this)
14706
14707 this._cipher = new aes.AES(key)
14708 this._prev = Buffer.from(iv)
14709 this._cache = Buffer.allocUnsafe(0)
14710 this._secCache = Buffer.allocUnsafe(0)
14711 this._decrypt = decrypt
14712 this._mode = mode
14713}
14714
14715inherits(StreamCipher, Transform)
14716
14717StreamCipher.prototype._update = function (chunk) {
14718 return this._mode.encrypt(this, chunk, this._decrypt)
14719}
14720
14721StreamCipher.prototype._final = function () {
14722 this._cipher.scrub()
14723}
14724
14725module.exports = StreamCipher
14726
14727},{"./aes":78,"cipher-base":108,"inherits":163,"safe-buffer":247}],95:[function(require,module,exports){
14728var ebtk = require('evp_bytestokey')
14729var aes = require('browserify-aes/browser')
14730var DES = require('browserify-des')
14731var desModes = require('browserify-des/modes')
14732var aesModes = require('browserify-aes/modes')
14733function createCipher (suite, password) {
14734 var keyLen, ivLen
14735 suite = suite.toLowerCase()
14736 if (aesModes[suite]) {
14737 keyLen = aesModes[suite].key
14738 ivLen = aesModes[suite].iv
14739 } else if (desModes[suite]) {
14740 keyLen = desModes[suite].key * 8
14741 ivLen = desModes[suite].iv
14742 } else {
14743 throw new TypeError('invalid suite type')
14744 }
14745 var keys = ebtk(password, false, keyLen, ivLen)
14746 return createCipheriv(suite, keys.key, keys.iv)
14747}
14748function createDecipher (suite, password) {
14749 var keyLen, ivLen
14750 suite = suite.toLowerCase()
14751 if (aesModes[suite]) {
14752 keyLen = aesModes[suite].key
14753 ivLen = aesModes[suite].iv
14754 } else if (desModes[suite]) {
14755 keyLen = desModes[suite].key * 8
14756 ivLen = desModes[suite].iv
14757 } else {
14758 throw new TypeError('invalid suite type')
14759 }
14760 var keys = ebtk(password, false, keyLen, ivLen)
14761 return createDecipheriv(suite, keys.key, keys.iv)
14762}
14763
14764function createCipheriv (suite, key, iv) {
14765 suite = suite.toLowerCase()
14766 if (aesModes[suite]) {
14767 return aes.createCipheriv(suite, key, iv)
14768 } else if (desModes[suite]) {
14769 return new DES({
14770 key: key,
14771 iv: iv,
14772 mode: suite
14773 })
14774 } else {
14775 throw new TypeError('invalid suite type')
14776 }
14777}
14778function createDecipheriv (suite, key, iv) {
14779 suite = suite.toLowerCase()
14780 if (aesModes[suite]) {
14781 return aes.createDecipheriv(suite, key, iv)
14782 } else if (desModes[suite]) {
14783 return new DES({
14784 key: key,
14785 iv: iv,
14786 mode: suite,
14787 decrypt: true
14788 })
14789 } else {
14790 throw new TypeError('invalid suite type')
14791 }
14792}
14793exports.createCipher = exports.Cipher = createCipher
14794exports.createCipheriv = exports.Cipheriv = createCipheriv
14795exports.createDecipher = exports.Decipher = createDecipher
14796exports.createDecipheriv = exports.Decipheriv = createDecipheriv
14797function getCiphers () {
14798 return Object.keys(desModes).concat(aes.getCiphers())
14799}
14800exports.listCiphers = exports.getCiphers = getCiphers
14801
14802},{"browserify-aes/browser":80,"browserify-aes/modes":91,"browserify-des":96,"browserify-des/modes":97,"evp_bytestokey":144}],96:[function(require,module,exports){
14803(function (Buffer){
14804var CipherBase = require('cipher-base')
14805var des = require('des.js')
14806var inherits = require('inherits')
14807
14808var modes = {
14809 'des-ede3-cbc': des.CBC.instantiate(des.EDE),
14810 'des-ede3': des.EDE,
14811 'des-ede-cbc': des.CBC.instantiate(des.EDE),
14812 'des-ede': des.EDE,
14813 'des-cbc': des.CBC.instantiate(des.DES),
14814 'des-ecb': des.DES
14815}
14816modes.des = modes['des-cbc']
14817modes.des3 = modes['des-ede3-cbc']
14818module.exports = DES
14819inherits(DES, CipherBase)
14820function DES (opts) {
14821 CipherBase.call(this)
14822 var modeName = opts.mode.toLowerCase()
14823 var mode = modes[modeName]
14824 var type
14825 if (opts.decrypt) {
14826 type = 'decrypt'
14827 } else {
14828 type = 'encrypt'
14829 }
14830 var key = opts.key
14831 if (modeName === 'des-ede' || modeName === 'des-ede-cbc') {
14832 key = Buffer.concat([key, key.slice(0, 8)])
14833 }
14834 var iv = opts.iv
14835 this._des = mode.create({
14836 key: key,
14837 iv: iv,
14838 type: type
14839 })
14840}
14841DES.prototype._update = function (data) {
14842 return new Buffer(this._des.update(data))
14843}
14844DES.prototype._final = function () {
14845 return new Buffer(this._des.final())
14846}
14847
14848}).call(this,require("buffer").Buffer)
14849},{"buffer":107,"cipher-base":108,"des.js":117,"inherits":163}],97:[function(require,module,exports){
14850exports['des-ecb'] = {
14851 key: 8,
14852 iv: 0
14853}
14854exports['des-cbc'] = exports.des = {
14855 key: 8,
14856 iv: 8
14857}
14858exports['des-ede3-cbc'] = exports.des3 = {
14859 key: 24,
14860 iv: 8
14861}
14862exports['des-ede3'] = {
14863 key: 24,
14864 iv: 0
14865}
14866exports['des-ede-cbc'] = {
14867 key: 16,
14868 iv: 8
14869}
14870exports['des-ede'] = {
14871 key: 16,
14872 iv: 0
14873}
14874
14875},{}],98:[function(require,module,exports){
14876(function (Buffer){
14877var bn = require('bn.js');
14878var randomBytes = require('randombytes');
14879module.exports = crt;
14880function blind(priv) {
14881 var r = getr(priv);
14882 var blinder = r.toRed(bn.mont(priv.modulus))
14883 .redPow(new bn(priv.publicExponent)).fromRed();
14884 return {
14885 blinder: blinder,
14886 unblinder:r.invm(priv.modulus)
14887 };
14888}
14889function crt(msg, priv) {
14890 var blinds = blind(priv);
14891 var len = priv.modulus.byteLength();
14892 var mod = bn.mont(priv.modulus);
14893 var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus);
14894 var c1 = blinded.toRed(bn.mont(priv.prime1));
14895 var c2 = blinded.toRed(bn.mont(priv.prime2));
14896 var qinv = priv.coefficient;
14897 var p = priv.prime1;
14898 var q = priv.prime2;
14899 var m1 = c1.redPow(priv.exponent1);
14900 var m2 = c2.redPow(priv.exponent2);
14901 m1 = m1.fromRed();
14902 m2 = m2.fromRed();
14903 var h = m1.isub(m2).imul(qinv).umod(p);
14904 h.imul(q);
14905 m2.iadd(h);
14906 return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len));
14907}
14908crt.getr = getr;
14909function getr(priv) {
14910 var len = priv.modulus.byteLength();
14911 var r = new bn(randomBytes(len));
14912 while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) {
14913 r = new bn(randomBytes(len));
14914 }
14915 return r;
14916}
14917
14918}).call(this,require("buffer").Buffer)
14919},{"bn.js":75,"buffer":107,"randombytes":231}],99:[function(require,module,exports){
14920module.exports = require('./browser/algorithms.json')
14921
14922},{"./browser/algorithms.json":100}],100:[function(require,module,exports){
14923module.exports={
14924 "sha224WithRSAEncryption": {
14925 "sign": "rsa",
14926 "hash": "sha224",
14927 "id": "302d300d06096086480165030402040500041c"
14928 },
14929 "RSA-SHA224": {
14930 "sign": "ecdsa/rsa",
14931 "hash": "sha224",
14932 "id": "302d300d06096086480165030402040500041c"
14933 },
14934 "sha256WithRSAEncryption": {
14935 "sign": "rsa",
14936 "hash": "sha256",
14937 "id": "3031300d060960864801650304020105000420"
14938 },
14939 "RSA-SHA256": {
14940 "sign": "ecdsa/rsa",
14941 "hash": "sha256",
14942 "id": "3031300d060960864801650304020105000420"
14943 },
14944 "sha384WithRSAEncryption": {
14945 "sign": "rsa",
14946 "hash": "sha384",
14947 "id": "3041300d060960864801650304020205000430"
14948 },
14949 "RSA-SHA384": {
14950 "sign": "ecdsa/rsa",
14951 "hash": "sha384",
14952 "id": "3041300d060960864801650304020205000430"
14953 },
14954 "sha512WithRSAEncryption": {
14955 "sign": "rsa",
14956 "hash": "sha512",
14957 "id": "3051300d060960864801650304020305000440"
14958 },
14959 "RSA-SHA512": {
14960 "sign": "ecdsa/rsa",
14961 "hash": "sha512",
14962 "id": "3051300d060960864801650304020305000440"
14963 },
14964 "RSA-SHA1": {
14965 "sign": "rsa",
14966 "hash": "sha1",
14967 "id": "3021300906052b0e03021a05000414"
14968 },
14969 "ecdsa-with-SHA1": {
14970 "sign": "ecdsa",
14971 "hash": "sha1",
14972 "id": ""
14973 },
14974 "sha256": {
14975 "sign": "ecdsa",
14976 "hash": "sha256",
14977 "id": ""
14978 },
14979 "sha224": {
14980 "sign": "ecdsa",
14981 "hash": "sha224",
14982 "id": ""
14983 },
14984 "sha384": {
14985 "sign": "ecdsa",
14986 "hash": "sha384",
14987 "id": ""
14988 },
14989 "sha512": {
14990 "sign": "ecdsa",
14991 "hash": "sha512",
14992 "id": ""
14993 },
14994 "DSA-SHA": {
14995 "sign": "dsa",
14996 "hash": "sha1",
14997 "id": ""
14998 },
14999 "DSA-SHA1": {
15000 "sign": "dsa",
15001 "hash": "sha1",
15002 "id": ""
15003 },
15004 "DSA": {
15005 "sign": "dsa",
15006 "hash": "sha1",
15007 "id": ""
15008 },
15009 "DSA-WITH-SHA224": {
15010 "sign": "dsa",
15011 "hash": "sha224",
15012 "id": ""
15013 },
15014 "DSA-SHA224": {
15015 "sign": "dsa",
15016 "hash": "sha224",
15017 "id": ""
15018 },
15019 "DSA-WITH-SHA256": {
15020 "sign": "dsa",
15021 "hash": "sha256",
15022 "id": ""
15023 },
15024 "DSA-SHA256": {
15025 "sign": "dsa",
15026 "hash": "sha256",
15027 "id": ""
15028 },
15029 "DSA-WITH-SHA384": {
15030 "sign": "dsa",
15031 "hash": "sha384",
15032 "id": ""
15033 },
15034 "DSA-SHA384": {
15035 "sign": "dsa",
15036 "hash": "sha384",
15037 "id": ""
15038 },
15039 "DSA-WITH-SHA512": {
15040 "sign": "dsa",
15041 "hash": "sha512",
15042 "id": ""
15043 },
15044 "DSA-SHA512": {
15045 "sign": "dsa",
15046 "hash": "sha512",
15047 "id": ""
15048 },
15049 "DSA-RIPEMD160": {
15050 "sign": "dsa",
15051 "hash": "rmd160",
15052 "id": ""
15053 },
15054 "ripemd160WithRSA": {
15055 "sign": "rsa",
15056 "hash": "rmd160",
15057 "id": "3021300906052b2403020105000414"
15058 },
15059 "RSA-RIPEMD160": {
15060 "sign": "rsa",
15061 "hash": "rmd160",
15062 "id": "3021300906052b2403020105000414"
15063 },
15064 "md5WithRSAEncryption": {
15065 "sign": "rsa",
15066 "hash": "md5",
15067 "id": "3020300c06082a864886f70d020505000410"
15068 },
15069 "RSA-MD5": {
15070 "sign": "rsa",
15071 "hash": "md5",
15072 "id": "3020300c06082a864886f70d020505000410"
15073 }
15074}
15075
15076},{}],101:[function(require,module,exports){
15077module.exports={
15078 "1.3.132.0.10": "secp256k1",
15079 "1.3.132.0.33": "p224",
15080 "1.2.840.10045.3.1.1": "p192",
15081 "1.2.840.10045.3.1.7": "p256",
15082 "1.3.132.0.34": "p384",
15083 "1.3.132.0.35": "p521"
15084}
15085
15086},{}],102:[function(require,module,exports){
15087(function (Buffer){
15088var createHash = require('create-hash')
15089var stream = require('stream')
15090var inherits = require('inherits')
15091var sign = require('./sign')
15092var verify = require('./verify')
15093
15094var algorithms = require('./algorithms.json')
15095Object.keys(algorithms).forEach(function (key) {
15096 algorithms[key].id = new Buffer(algorithms[key].id, 'hex')
15097 algorithms[key.toLowerCase()] = algorithms[key]
15098})
15099
15100function Sign (algorithm) {
15101 stream.Writable.call(this)
15102
15103 var data = algorithms[algorithm]
15104 if (!data) throw new Error('Unknown message digest')
15105
15106 this._hashType = data.hash
15107 this._hash = createHash(data.hash)
15108 this._tag = data.id
15109 this._signType = data.sign
15110}
15111inherits(Sign, stream.Writable)
15112
15113Sign.prototype._write = function _write (data, _, done) {
15114 this._hash.update(data)
15115 done()
15116}
15117
15118Sign.prototype.update = function update (data, enc) {
15119 if (typeof data === 'string') data = new Buffer(data, enc)
15120
15121 this._hash.update(data)
15122 return this
15123}
15124
15125Sign.prototype.sign = function signMethod (key, enc) {
15126 this.end()
15127 var hash = this._hash.digest()
15128 var sig = sign(hash, key, this._hashType, this._signType, this._tag)
15129
15130 return enc ? sig.toString(enc) : sig
15131}
15132
15133function Verify (algorithm) {
15134 stream.Writable.call(this)
15135
15136 var data = algorithms[algorithm]
15137 if (!data) throw new Error('Unknown message digest')
15138
15139 this._hash = createHash(data.hash)
15140 this._tag = data.id
15141 this._signType = data.sign
15142}
15143inherits(Verify, stream.Writable)
15144
15145Verify.prototype._write = function _write (data, _, done) {
15146 this._hash.update(data)
15147 done()
15148}
15149
15150Verify.prototype.update = function update (data, enc) {
15151 if (typeof data === 'string') data = new Buffer(data, enc)
15152
15153 this._hash.update(data)
15154 return this
15155}
15156
15157Verify.prototype.verify = function verifyMethod (key, sig, enc) {
15158 if (typeof sig === 'string') sig = new Buffer(sig, enc)
15159
15160 this.end()
15161 var hash = this._hash.digest()
15162 return verify(sig, hash, key, this._signType, this._tag)
15163}
15164
15165function createSign (algorithm) {
15166 return new Sign(algorithm)
15167}
15168
15169function createVerify (algorithm) {
15170 return new Verify(algorithm)
15171}
15172
15173module.exports = {
15174 Sign: createSign,
15175 Verify: createVerify,
15176 createSign: createSign,
15177 createVerify: createVerify
15178}
15179
15180}).call(this,require("buffer").Buffer)
15181},{"./algorithms.json":100,"./sign":103,"./verify":104,"buffer":107,"create-hash":111,"inherits":163,"stream":263}],103:[function(require,module,exports){
15182(function (Buffer){
15183// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
15184var createHmac = require('create-hmac')
15185var crt = require('browserify-rsa')
15186var EC = require('elliptic').ec
15187var BN = require('bn.js')
15188var parseKeys = require('parse-asn1')
15189var curves = require('./curves.json')
15190
15191function sign (hash, key, hashType, signType, tag) {
15192 var priv = parseKeys(key)
15193 if (priv.curve) {
15194 // rsa keys can be interpreted as ecdsa ones in openssl
15195 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
15196 return ecSign(hash, priv)
15197 } else if (priv.type === 'dsa') {
15198 if (signType !== 'dsa') throw new Error('wrong private key type')
15199 return dsaSign(hash, priv, hashType)
15200 } else {
15201 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type')
15202 }
15203 hash = Buffer.concat([tag, hash])
15204 var len = priv.modulus.byteLength()
15205 var pad = [ 0, 1 ]
15206 while (hash.length + pad.length + 1 < len) pad.push(0xff)
15207 pad.push(0x00)
15208 var i = -1
15209 while (++i < hash.length) pad.push(hash[i])
15210
15211 var out = crt(pad, priv)
15212 return out
15213}
15214
15215function ecSign (hash, priv) {
15216 var curveId = curves[priv.curve.join('.')]
15217 if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.'))
15218
15219 var curve = new EC(curveId)
15220 var key = curve.keyFromPrivate(priv.privateKey)
15221 var out = key.sign(hash)
15222
15223 return new Buffer(out.toDER())
15224}
15225
15226function dsaSign (hash, priv, algo) {
15227 var x = priv.params.priv_key
15228 var p = priv.params.p
15229 var q = priv.params.q
15230 var g = priv.params.g
15231 var r = new BN(0)
15232 var k
15233 var H = bits2int(hash, q).mod(q)
15234 var s = false
15235 var kv = getKey(x, q, hash, algo)
15236 while (s === false) {
15237 k = makeKey(q, kv, algo)
15238 r = makeR(g, k, p, q)
15239 s = k.invm(q).imul(H.add(x.mul(r))).mod(q)
15240 if (s.cmpn(0) === 0) {
15241 s = false
15242 r = new BN(0)
15243 }
15244 }
15245 return toDER(r, s)
15246}
15247
15248function toDER (r, s) {
15249 r = r.toArray()
15250 s = s.toArray()
15251
15252 // Pad values
15253 if (r[0] & 0x80) r = [ 0 ].concat(r)
15254 if (s[0] & 0x80) s = [ 0 ].concat(s)
15255
15256 var total = r.length + s.length + 4
15257 var res = [ 0x30, total, 0x02, r.length ]
15258 res = res.concat(r, [ 0x02, s.length ], s)
15259 return new Buffer(res)
15260}
15261
15262function getKey (x, q, hash, algo) {
15263 x = new Buffer(x.toArray())
15264 if (x.length < q.byteLength()) {
15265 var zeros = new Buffer(q.byteLength() - x.length)
15266 zeros.fill(0)
15267 x = Buffer.concat([ zeros, x ])
15268 }
15269 var hlen = hash.length
15270 var hbits = bits2octets(hash, q)
15271 var v = new Buffer(hlen)
15272 v.fill(1)
15273 var k = new Buffer(hlen)
15274 k.fill(0)
15275 k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest()
15276 v = createHmac(algo, k).update(v).digest()
15277 k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest()
15278 v = createHmac(algo, k).update(v).digest()
15279 return { k: k, v: v }
15280}
15281
15282function bits2int (obits, q) {
15283 var bits = new BN(obits)
15284 var shift = (obits.length << 3) - q.bitLength()
15285 if (shift > 0) bits.ishrn(shift)
15286 return bits
15287}
15288
15289function bits2octets (bits, q) {
15290 bits = bits2int(bits, q)
15291 bits = bits.mod(q)
15292 var out = new Buffer(bits.toArray())
15293 if (out.length < q.byteLength()) {
15294 var zeros = new Buffer(q.byteLength() - out.length)
15295 zeros.fill(0)
15296 out = Buffer.concat([ zeros, out ])
15297 }
15298 return out
15299}
15300
15301function makeKey (q, kv, algo) {
15302 var t
15303 var k
15304
15305 do {
15306 t = new Buffer(0)
15307
15308 while (t.length * 8 < q.bitLength()) {
15309 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
15310 t = Buffer.concat([ t, kv.v ])
15311 }
15312
15313 k = bits2int(t, q)
15314 kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest()
15315 kv.v = createHmac(algo, kv.k).update(kv.v).digest()
15316 } while (k.cmp(q) !== -1)
15317
15318 return k
15319}
15320
15321function makeR (g, k, p, q) {
15322 return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q)
15323}
15324
15325module.exports = sign
15326module.exports.getKey = getKey
15327module.exports.makeKey = makeKey
15328
15329}).call(this,require("buffer").Buffer)
15330},{"./curves.json":101,"bn.js":75,"browserify-rsa":98,"buffer":107,"create-hmac":114,"elliptic":127,"parse-asn1":182}],104:[function(require,module,exports){
15331(function (Buffer){
15332// much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js
15333var BN = require('bn.js')
15334var EC = require('elliptic').ec
15335var parseKeys = require('parse-asn1')
15336var curves = require('./curves.json')
15337
15338function verify (sig, hash, key, signType, tag) {
15339 var pub = parseKeys(key)
15340 if (pub.type === 'ec') {
15341 // rsa keys can be interpreted as ecdsa ones in openssl
15342 if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
15343 return ecVerify(sig, hash, pub)
15344 } else if (pub.type === 'dsa') {
15345 if (signType !== 'dsa') throw new Error('wrong public key type')
15346 return dsaVerify(sig, hash, pub)
15347 } else {
15348 if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type')
15349 }
15350 hash = Buffer.concat([tag, hash])
15351 var len = pub.modulus.byteLength()
15352 var pad = [ 1 ]
15353 var padNum = 0
15354 while (hash.length + pad.length + 2 < len) {
15355 pad.push(0xff)
15356 padNum++
15357 }
15358 pad.push(0x00)
15359 var i = -1
15360 while (++i < hash.length) {
15361 pad.push(hash[i])
15362 }
15363 pad = new Buffer(pad)
15364 var red = BN.mont(pub.modulus)
15365 sig = new BN(sig).toRed(red)
15366
15367 sig = sig.redPow(new BN(pub.publicExponent))
15368 sig = new Buffer(sig.fromRed().toArray())
15369 var out = padNum < 8 ? 1 : 0
15370 len = Math.min(sig.length, pad.length)
15371 if (sig.length !== pad.length) out = 1
15372
15373 i = -1
15374 while (++i < len) out |= sig[i] ^ pad[i]
15375 return out === 0
15376}
15377
15378function ecVerify (sig, hash, pub) {
15379 var curveId = curves[pub.data.algorithm.curve.join('.')]
15380 if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.'))
15381
15382 var curve = new EC(curveId)
15383 var pubkey = pub.data.subjectPrivateKey.data
15384
15385 return curve.verify(hash, sig, pubkey)
15386}
15387
15388function dsaVerify (sig, hash, pub) {
15389 var p = pub.data.p
15390 var q = pub.data.q
15391 var g = pub.data.g
15392 var y = pub.data.pub_key
15393 var unpacked = parseKeys.signature.decode(sig, 'der')
15394 var s = unpacked.s
15395 var r = unpacked.r
15396 checkValue(s, q)
15397 checkValue(r, q)
15398 var montp = BN.mont(p)
15399 var w = s.invm(q)
15400 var v = g.toRed(montp)
15401 .redPow(new BN(hash).mul(w).mod(q))
15402 .fromRed()
15403 .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed())
15404 .mod(p)
15405 .mod(q)
15406 return v.cmp(r) === 0
15407}
15408
15409function checkValue (b, q) {
15410 if (b.cmpn(0) <= 0) throw new Error('invalid sig')
15411 if (b.cmp(q) >= q) throw new Error('invalid sig')
15412}
15413
15414module.exports = verify
15415
15416}).call(this,require("buffer").Buffer)
15417},{"./curves.json":101,"bn.js":75,"buffer":107,"elliptic":127,"parse-asn1":182}],105:[function(require,module,exports){
15418var basex = require('base-x')
15419var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
15420
15421module.exports = basex(ALPHABET)
15422
15423},{"base-x":71}],106:[function(require,module,exports){
15424(function (Buffer){
15425module.exports = function xor (a, b) {
15426 var length = Math.min(a.length, b.length)
15427 var buffer = new Buffer(length)
15428
15429 for (var i = 0; i < length; ++i) {
15430 buffer[i] = a[i] ^ b[i]
15431 }
15432
15433 return buffer
15434}
15435
15436}).call(this,require("buffer").Buffer)
15437},{"buffer":107}],107:[function(require,module,exports){
15438/*!
15439 * The buffer module from node.js, for the browser.
15440 *
15441 * @author Feross Aboukhadijeh <https://feross.org>
15442 * @license MIT
15443 */
15444/* eslint-disable no-proto */
15445
15446'use strict'
15447
15448var base64 = require('base64-js')
15449var ieee754 = require('ieee754')
15450
15451exports.Buffer = Buffer
15452exports.SlowBuffer = SlowBuffer
15453exports.INSPECT_MAX_BYTES = 50
15454
15455var K_MAX_LENGTH = 0x7fffffff
15456exports.kMaxLength = K_MAX_LENGTH
15457
15458/**
15459 * If `Buffer.TYPED_ARRAY_SUPPORT`:
15460 * === true Use Uint8Array implementation (fastest)
15461 * === false Print warning and recommend using `buffer` v4.x which has an Object
15462 * implementation (most compatible, even IE6)
15463 *
15464 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
15465 * Opera 11.6+, iOS 4.2+.
15466 *
15467 * We report that the browser does not support typed arrays if the are not subclassable
15468 * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array`
15469 * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support
15470 * for __proto__ and has a buggy typed array implementation.
15471 */
15472Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport()
15473
15474if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' &&
15475 typeof console.error === 'function') {
15476 console.error(
15477 'This browser lacks typed array (Uint8Array) support which is required by ' +
15478 '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.'
15479 )
15480}
15481
15482function typedArraySupport () {
15483 // Can typed array instances can be augmented?
15484 try {
15485 var arr = new Uint8Array(1)
15486 arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }}
15487 return arr.foo() === 42
15488 } catch (e) {
15489 return false
15490 }
15491}
15492
15493function createBuffer (length) {
15494 if (length > K_MAX_LENGTH) {
15495 throw new RangeError('Invalid typed array length')
15496 }
15497 // Return an augmented `Uint8Array` instance
15498 var buf = new Uint8Array(length)
15499 buf.__proto__ = Buffer.prototype
15500 return buf
15501}
15502
15503/**
15504 * The Buffer constructor returns instances of `Uint8Array` that have their
15505 * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of
15506 * `Uint8Array`, so the returned instances will have all the node `Buffer` methods
15507 * and the `Uint8Array` methods. Square bracket notation works as expected -- it
15508 * returns a single octet.
15509 *
15510 * The `Uint8Array` prototype remains unmodified.
15511 */
15512
15513function Buffer (arg, encodingOrOffset, length) {
15514 // Common case.
15515 if (typeof arg === 'number') {
15516 if (typeof encodingOrOffset === 'string') {
15517 throw new Error(
15518 'If encoding is specified then the first argument must be a string'
15519 )
15520 }
15521 return allocUnsafe(arg)
15522 }
15523 return from(arg, encodingOrOffset, length)
15524}
15525
15526// Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
15527if (typeof Symbol !== 'undefined' && Symbol.species &&
15528 Buffer[Symbol.species] === Buffer) {
15529 Object.defineProperty(Buffer, Symbol.species, {
15530 value: null,
15531 configurable: true,
15532 enumerable: false,
15533 writable: false
15534 })
15535}
15536
15537Buffer.poolSize = 8192 // not used by this implementation
15538
15539function from (value, encodingOrOffset, length) {
15540 if (typeof value === 'number') {
15541 throw new TypeError('"value" argument must not be a number')
15542 }
15543
15544 if (isArrayBuffer(value)) {
15545 return fromArrayBuffer(value, encodingOrOffset, length)
15546 }
15547
15548 if (typeof value === 'string') {
15549 return fromString(value, encodingOrOffset)
15550 }
15551
15552 return fromObject(value)
15553}
15554
15555/**
15556 * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError
15557 * if value is a number.
15558 * Buffer.from(str[, encoding])
15559 * Buffer.from(array)
15560 * Buffer.from(buffer)
15561 * Buffer.from(arrayBuffer[, byteOffset[, length]])
15562 **/
15563Buffer.from = function (value, encodingOrOffset, length) {
15564 return from(value, encodingOrOffset, length)
15565}
15566
15567// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
15568// https://github.com/feross/buffer/pull/148
15569Buffer.prototype.__proto__ = Uint8Array.prototype
15570Buffer.__proto__ = Uint8Array
15571
15572function assertSize (size) {
15573 if (typeof size !== 'number') {
15574 throw new TypeError('"size" argument must be a number')
15575 } else if (size < 0) {
15576 throw new RangeError('"size" argument must not be negative')
15577 }
15578}
15579
15580function alloc (size, fill, encoding) {
15581 assertSize(size)
15582 if (size <= 0) {
15583 return createBuffer(size)
15584 }
15585 if (fill !== undefined) {
15586 // Only pay attention to encoding if it's a string. This
15587 // prevents accidentally sending in a number that would
15588 // be interpretted as a start offset.
15589 return typeof encoding === 'string'
15590 ? createBuffer(size).fill(fill, encoding)
15591 : createBuffer(size).fill(fill)
15592 }
15593 return createBuffer(size)
15594}
15595
15596/**
15597 * Creates a new filled Buffer instance.
15598 * alloc(size[, fill[, encoding]])
15599 **/
15600Buffer.alloc = function (size, fill, encoding) {
15601 return alloc(size, fill, encoding)
15602}
15603
15604function allocUnsafe (size) {
15605 assertSize(size)
15606 return createBuffer(size < 0 ? 0 : checked(size) | 0)
15607}
15608
15609/**
15610 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
15611 * */
15612Buffer.allocUnsafe = function (size) {
15613 return allocUnsafe(size)
15614}
15615/**
15616 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
15617 */
15618Buffer.allocUnsafeSlow = function (size) {
15619 return allocUnsafe(size)
15620}
15621
15622function fromString (string, encoding) {
15623 if (typeof encoding !== 'string' || encoding === '') {
15624 encoding = 'utf8'
15625 }
15626
15627 if (!Buffer.isEncoding(encoding)) {
15628 throw new TypeError('"encoding" must be a valid string encoding')
15629 }
15630
15631 var length = byteLength(string, encoding) | 0
15632 var buf = createBuffer(length)
15633
15634 var actual = buf.write(string, encoding)
15635
15636 if (actual !== length) {
15637 // Writing a hex string, for example, that contains invalid characters will
15638 // cause everything after the first invalid character to be ignored. (e.g.
15639 // 'abxxcd' will be treated as 'ab')
15640 buf = buf.slice(0, actual)
15641 }
15642
15643 return buf
15644}
15645
15646function fromArrayLike (array) {
15647 var length = array.length < 0 ? 0 : checked(array.length) | 0
15648 var buf = createBuffer(length)
15649 for (var i = 0; i < length; i += 1) {
15650 buf[i] = array[i] & 255
15651 }
15652 return buf
15653}
15654
15655function fromArrayBuffer (array, byteOffset, length) {
15656 if (byteOffset < 0 || array.byteLength < byteOffset) {
15657 throw new RangeError('\'offset\' is out of bounds')
15658 }
15659
15660 if (array.byteLength < byteOffset + (length || 0)) {
15661 throw new RangeError('\'length\' is out of bounds')
15662 }
15663
15664 var buf
15665 if (byteOffset === undefined && length === undefined) {
15666 buf = new Uint8Array(array)
15667 } else if (length === undefined) {
15668 buf = new Uint8Array(array, byteOffset)
15669 } else {
15670 buf = new Uint8Array(array, byteOffset, length)
15671 }
15672
15673 // Return an augmented `Uint8Array` instance
15674 buf.__proto__ = Buffer.prototype
15675 return buf
15676}
15677
15678function fromObject (obj) {
15679 if (Buffer.isBuffer(obj)) {
15680 var len = checked(obj.length) | 0
15681 var buf = createBuffer(len)
15682
15683 if (buf.length === 0) {
15684 return buf
15685 }
15686
15687 obj.copy(buf, 0, 0, len)
15688 return buf
15689 }
15690
15691 if (obj) {
15692 if (isArrayBufferView(obj) || 'length' in obj) {
15693 if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) {
15694 return createBuffer(0)
15695 }
15696 return fromArrayLike(obj)
15697 }
15698
15699 if (obj.type === 'Buffer' && Array.isArray(obj.data)) {
15700 return fromArrayLike(obj.data)
15701 }
15702 }
15703
15704 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
15705}
15706
15707function checked (length) {
15708 // Note: cannot use `length < K_MAX_LENGTH` here because that fails when
15709 // length is NaN (which is otherwise coerced to zero.)
15710 if (length >= K_MAX_LENGTH) {
15711 throw new RangeError('Attempt to allocate Buffer larger than maximum ' +
15712 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes')
15713 }
15714 return length | 0
15715}
15716
15717function SlowBuffer (length) {
15718 if (+length != length) { // eslint-disable-line eqeqeq
15719 length = 0
15720 }
15721 return Buffer.alloc(+length)
15722}
15723
15724Buffer.isBuffer = function isBuffer (b) {
15725 return b != null && b._isBuffer === true
15726}
15727
15728Buffer.compare = function compare (a, b) {
15729 if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) {
15730 throw new TypeError('Arguments must be Buffers')
15731 }
15732
15733 if (a === b) return 0
15734
15735 var x = a.length
15736 var y = b.length
15737
15738 for (var i = 0, len = Math.min(x, y); i < len; ++i) {
15739 if (a[i] !== b[i]) {
15740 x = a[i]
15741 y = b[i]
15742 break
15743 }
15744 }
15745
15746 if (x < y) return -1
15747 if (y < x) return 1
15748 return 0
15749}
15750
15751Buffer.isEncoding = function isEncoding (encoding) {
15752 switch (String(encoding).toLowerCase()) {
15753 case 'hex':
15754 case 'utf8':
15755 case 'utf-8':
15756 case 'ascii':
15757 case 'latin1':
15758 case 'binary':
15759 case 'base64':
15760 case 'ucs2':
15761 case 'ucs-2':
15762 case 'utf16le':
15763 case 'utf-16le':
15764 return true
15765 default:
15766 return false
15767 }
15768}
15769
15770Buffer.concat = function concat (list, length) {
15771 if (!Array.isArray(list)) {
15772 throw new TypeError('"list" argument must be an Array of Buffers')
15773 }
15774
15775 if (list.length === 0) {
15776 return Buffer.alloc(0)
15777 }
15778
15779 var i
15780 if (length === undefined) {
15781 length = 0
15782 for (i = 0; i < list.length; ++i) {
15783 length += list[i].length
15784 }
15785 }
15786
15787 var buffer = Buffer.allocUnsafe(length)
15788 var pos = 0
15789 for (i = 0; i < list.length; ++i) {
15790 var buf = list[i]
15791 if (!Buffer.isBuffer(buf)) {
15792 throw new TypeError('"list" argument must be an Array of Buffers')
15793 }
15794 buf.copy(buffer, pos)
15795 pos += buf.length
15796 }
15797 return buffer
15798}
15799
15800function byteLength (string, encoding) {
15801 if (Buffer.isBuffer(string)) {
15802 return string.length
15803 }
15804 if (isArrayBufferView(string) || isArrayBuffer(string)) {
15805 return string.byteLength
15806 }
15807 if (typeof string !== 'string') {
15808 string = '' + string
15809 }
15810
15811 var len = string.length
15812 if (len === 0) return 0
15813
15814 // Use a for loop to avoid recursion
15815 var loweredCase = false
15816 for (;;) {
15817 switch (encoding) {
15818 case 'ascii':
15819 case 'latin1':
15820 case 'binary':
15821 return len
15822 case 'utf8':
15823 case 'utf-8':
15824 case undefined:
15825 return utf8ToBytes(string).length
15826 case 'ucs2':
15827 case 'ucs-2':
15828 case 'utf16le':
15829 case 'utf-16le':
15830 return len * 2
15831 case 'hex':
15832 return len >>> 1
15833 case 'base64':
15834 return base64ToBytes(string).length
15835 default:
15836 if (loweredCase) return utf8ToBytes(string).length // assume utf8
15837 encoding = ('' + encoding).toLowerCase()
15838 loweredCase = true
15839 }
15840 }
15841}
15842Buffer.byteLength = byteLength
15843
15844function slowToString (encoding, start, end) {
15845 var loweredCase = false
15846
15847 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
15848 // property of a typed array.
15849
15850 // This behaves neither like String nor Uint8Array in that we set start/end
15851 // to their upper/lower bounds if the value passed is out of range.
15852 // undefined is handled specially as per ECMA-262 6th Edition,
15853 // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization.
15854 if (start === undefined || start < 0) {
15855 start = 0
15856 }
15857 // Return early if start > this.length. Done here to prevent potential uint32
15858 // coercion fail below.
15859 if (start > this.length) {
15860 return ''
15861 }
15862
15863 if (end === undefined || end > this.length) {
15864 end = this.length
15865 }
15866
15867 if (end <= 0) {
15868 return ''
15869 }
15870
15871 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
15872 end >>>= 0
15873 start >>>= 0
15874
15875 if (end <= start) {
15876 return ''
15877 }
15878
15879 if (!encoding) encoding = 'utf8'
15880
15881 while (true) {
15882 switch (encoding) {
15883 case 'hex':
15884 return hexSlice(this, start, end)
15885
15886 case 'utf8':
15887 case 'utf-8':
15888 return utf8Slice(this, start, end)
15889
15890 case 'ascii':
15891 return asciiSlice(this, start, end)
15892
15893 case 'latin1':
15894 case 'binary':
15895 return latin1Slice(this, start, end)
15896
15897 case 'base64':
15898 return base64Slice(this, start, end)
15899
15900 case 'ucs2':
15901 case 'ucs-2':
15902 case 'utf16le':
15903 case 'utf-16le':
15904 return utf16leSlice(this, start, end)
15905
15906 default:
15907 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
15908 encoding = (encoding + '').toLowerCase()
15909 loweredCase = true
15910 }
15911 }
15912}
15913
15914// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package)
15915// to detect a Buffer instance. It's not possible to use `instanceof Buffer`
15916// reliably in a browserify context because there could be multiple different
15917// copies of the 'buffer' package in use. This method works even for Buffer
15918// instances that were created from another copy of the `buffer` package.
15919// See: https://github.com/feross/buffer/issues/154
15920Buffer.prototype._isBuffer = true
15921
15922function swap (b, n, m) {
15923 var i = b[n]
15924 b[n] = b[m]
15925 b[m] = i
15926}
15927
15928Buffer.prototype.swap16 = function swap16 () {
15929 var len = this.length
15930 if (len % 2 !== 0) {
15931 throw new RangeError('Buffer size must be a multiple of 16-bits')
15932 }
15933 for (var i = 0; i < len; i += 2) {
15934 swap(this, i, i + 1)
15935 }
15936 return this
15937}
15938
15939Buffer.prototype.swap32 = function swap32 () {
15940 var len = this.length
15941 if (len % 4 !== 0) {
15942 throw new RangeError('Buffer size must be a multiple of 32-bits')
15943 }
15944 for (var i = 0; i < len; i += 4) {
15945 swap(this, i, i + 3)
15946 swap(this, i + 1, i + 2)
15947 }
15948 return this
15949}
15950
15951Buffer.prototype.swap64 = function swap64 () {
15952 var len = this.length
15953 if (len % 8 !== 0) {
15954 throw new RangeError('Buffer size must be a multiple of 64-bits')
15955 }
15956 for (var i = 0; i < len; i += 8) {
15957 swap(this, i, i + 7)
15958 swap(this, i + 1, i + 6)
15959 swap(this, i + 2, i + 5)
15960 swap(this, i + 3, i + 4)
15961 }
15962 return this
15963}
15964
15965Buffer.prototype.toString = function toString () {
15966 var length = this.length
15967 if (length === 0) return ''
15968 if (arguments.length === 0) return utf8Slice(this, 0, length)
15969 return slowToString.apply(this, arguments)
15970}
15971
15972Buffer.prototype.equals = function equals (b) {
15973 if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer')
15974 if (this === b) return true
15975 return Buffer.compare(this, b) === 0
15976}
15977
15978Buffer.prototype.inspect = function inspect () {
15979 var str = ''
15980 var max = exports.INSPECT_MAX_BYTES
15981 if (this.length > 0) {
15982 str = this.toString('hex', 0, max).match(/.{2}/g).join(' ')
15983 if (this.length > max) str += ' ... '
15984 }
15985 return '<Buffer ' + str + '>'
15986}
15987
15988Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) {
15989 if (!Buffer.isBuffer(target)) {
15990 throw new TypeError('Argument must be a Buffer')
15991 }
15992
15993 if (start === undefined) {
15994 start = 0
15995 }
15996 if (end === undefined) {
15997 end = target ? target.length : 0
15998 }
15999 if (thisStart === undefined) {
16000 thisStart = 0
16001 }
16002 if (thisEnd === undefined) {
16003 thisEnd = this.length
16004 }
16005
16006 if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) {
16007 throw new RangeError('out of range index')
16008 }
16009
16010 if (thisStart >= thisEnd && start >= end) {
16011 return 0
16012 }
16013 if (thisStart >= thisEnd) {
16014 return -1
16015 }
16016 if (start >= end) {
16017 return 1
16018 }
16019
16020 start >>>= 0
16021 end >>>= 0
16022 thisStart >>>= 0
16023 thisEnd >>>= 0
16024
16025 if (this === target) return 0
16026
16027 var x = thisEnd - thisStart
16028 var y = end - start
16029 var len = Math.min(x, y)
16030
16031 var thisCopy = this.slice(thisStart, thisEnd)
16032 var targetCopy = target.slice(start, end)
16033
16034 for (var i = 0; i < len; ++i) {
16035 if (thisCopy[i] !== targetCopy[i]) {
16036 x = thisCopy[i]
16037 y = targetCopy[i]
16038 break
16039 }
16040 }
16041
16042 if (x < y) return -1
16043 if (y < x) return 1
16044 return 0
16045}
16046
16047// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`,
16048// OR the last index of `val` in `buffer` at offset <= `byteOffset`.
16049//
16050// Arguments:
16051// - buffer - a Buffer to search
16052// - val - a string, Buffer, or number
16053// - byteOffset - an index into `buffer`; will be clamped to an int32
16054// - encoding - an optional encoding, relevant is val is a string
16055// - dir - true for indexOf, false for lastIndexOf
16056function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) {
16057 // Empty buffer means no match
16058 if (buffer.length === 0) return -1
16059
16060 // Normalize byteOffset
16061 if (typeof byteOffset === 'string') {
16062 encoding = byteOffset
16063 byteOffset = 0
16064 } else if (byteOffset > 0x7fffffff) {
16065 byteOffset = 0x7fffffff
16066 } else if (byteOffset < -0x80000000) {
16067 byteOffset = -0x80000000
16068 }
16069 byteOffset = +byteOffset // Coerce to Number.
16070 if (numberIsNaN(byteOffset)) {
16071 // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer
16072 byteOffset = dir ? 0 : (buffer.length - 1)
16073 }
16074
16075 // Normalize byteOffset: negative offsets start from the end of the buffer
16076 if (byteOffset < 0) byteOffset = buffer.length + byteOffset
16077 if (byteOffset >= buffer.length) {
16078 if (dir) return -1
16079 else byteOffset = buffer.length - 1
16080 } else if (byteOffset < 0) {
16081 if (dir) byteOffset = 0
16082 else return -1
16083 }
16084
16085 // Normalize val
16086 if (typeof val === 'string') {
16087 val = Buffer.from(val, encoding)
16088 }
16089
16090 // Finally, search either indexOf (if dir is true) or lastIndexOf
16091 if (Buffer.isBuffer(val)) {
16092 // Special case: looking for empty string/buffer always fails
16093 if (val.length === 0) {
16094 return -1
16095 }
16096 return arrayIndexOf(buffer, val, byteOffset, encoding, dir)
16097 } else if (typeof val === 'number') {
16098 val = val & 0xFF // Search for a byte value [0-255]
16099 if (typeof Uint8Array.prototype.indexOf === 'function') {
16100 if (dir) {
16101 return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset)
16102 } else {
16103 return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset)
16104 }
16105 }
16106 return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir)
16107 }
16108
16109 throw new TypeError('val must be string, number or Buffer')
16110}
16111
16112function arrayIndexOf (arr, val, byteOffset, encoding, dir) {
16113 var indexSize = 1
16114 var arrLength = arr.length
16115 var valLength = val.length
16116
16117 if (encoding !== undefined) {
16118 encoding = String(encoding).toLowerCase()
16119 if (encoding === 'ucs2' || encoding === 'ucs-2' ||
16120 encoding === 'utf16le' || encoding === 'utf-16le') {
16121 if (arr.length < 2 || val.length < 2) {
16122 return -1
16123 }
16124 indexSize = 2
16125 arrLength /= 2
16126 valLength /= 2
16127 byteOffset /= 2
16128 }
16129 }
16130
16131 function read (buf, i) {
16132 if (indexSize === 1) {
16133 return buf[i]
16134 } else {
16135 return buf.readUInt16BE(i * indexSize)
16136 }
16137 }
16138
16139 var i
16140 if (dir) {
16141 var foundIndex = -1
16142 for (i = byteOffset; i < arrLength; i++) {
16143 if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) {
16144 if (foundIndex === -1) foundIndex = i
16145 if (i - foundIndex + 1 === valLength) return foundIndex * indexSize
16146 } else {
16147 if (foundIndex !== -1) i -= i - foundIndex
16148 foundIndex = -1
16149 }
16150 }
16151 } else {
16152 if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength
16153 for (i = byteOffset; i >= 0; i--) {
16154 var found = true
16155 for (var j = 0; j < valLength; j++) {
16156 if (read(arr, i + j) !== read(val, j)) {
16157 found = false
16158 break
16159 }
16160 }
16161 if (found) return i
16162 }
16163 }
16164
16165 return -1
16166}
16167
16168Buffer.prototype.includes = function includes (val, byteOffset, encoding) {
16169 return this.indexOf(val, byteOffset, encoding) !== -1
16170}
16171
16172Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) {
16173 return bidirectionalIndexOf(this, val, byteOffset, encoding, true)
16174}
16175
16176Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) {
16177 return bidirectionalIndexOf(this, val, byteOffset, encoding, false)
16178}
16179
16180function hexWrite (buf, string, offset, length) {
16181 offset = Number(offset) || 0
16182 var remaining = buf.length - offset
16183 if (!length) {
16184 length = remaining
16185 } else {
16186 length = Number(length)
16187 if (length > remaining) {
16188 length = remaining
16189 }
16190 }
16191
16192 // must be an even number of digits
16193 var strLen = string.length
16194 if (strLen % 2 !== 0) throw new TypeError('Invalid hex string')
16195
16196 if (length > strLen / 2) {
16197 length = strLen / 2
16198 }
16199 for (var i = 0; i < length; ++i) {
16200 var parsed = parseInt(string.substr(i * 2, 2), 16)
16201 if (numberIsNaN(parsed)) return i
16202 buf[offset + i] = parsed
16203 }
16204 return i
16205}
16206
16207function utf8Write (buf, string, offset, length) {
16208 return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length)
16209}
16210
16211function asciiWrite (buf, string, offset, length) {
16212 return blitBuffer(asciiToBytes(string), buf, offset, length)
16213}
16214
16215function latin1Write (buf, string, offset, length) {
16216 return asciiWrite(buf, string, offset, length)
16217}
16218
16219function base64Write (buf, string, offset, length) {
16220 return blitBuffer(base64ToBytes(string), buf, offset, length)
16221}
16222
16223function ucs2Write (buf, string, offset, length) {
16224 return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length)
16225}
16226
16227Buffer.prototype.write = function write (string, offset, length, encoding) {
16228 // Buffer#write(string)
16229 if (offset === undefined) {
16230 encoding = 'utf8'
16231 length = this.length
16232 offset = 0
16233 // Buffer#write(string, encoding)
16234 } else if (length === undefined && typeof offset === 'string') {
16235 encoding = offset
16236 length = this.length
16237 offset = 0
16238 // Buffer#write(string, offset[, length][, encoding])
16239 } else if (isFinite(offset)) {
16240 offset = offset >>> 0
16241 if (isFinite(length)) {
16242 length = length >>> 0
16243 if (encoding === undefined) encoding = 'utf8'
16244 } else {
16245 encoding = length
16246 length = undefined
16247 }
16248 } else {
16249 throw new Error(
16250 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
16251 )
16252 }
16253
16254 var remaining = this.length - offset
16255 if (length === undefined || length > remaining) length = remaining
16256
16257 if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) {
16258 throw new RangeError('Attempt to write outside buffer bounds')
16259 }
16260
16261 if (!encoding) encoding = 'utf8'
16262
16263 var loweredCase = false
16264 for (;;) {
16265 switch (encoding) {
16266 case 'hex':
16267 return hexWrite(this, string, offset, length)
16268
16269 case 'utf8':
16270 case 'utf-8':
16271 return utf8Write(this, string, offset, length)
16272
16273 case 'ascii':
16274 return asciiWrite(this, string, offset, length)
16275
16276 case 'latin1':
16277 case 'binary':
16278 return latin1Write(this, string, offset, length)
16279
16280 case 'base64':
16281 // Warning: maxLength not taken into account in base64Write
16282 return base64Write(this, string, offset, length)
16283
16284 case 'ucs2':
16285 case 'ucs-2':
16286 case 'utf16le':
16287 case 'utf-16le':
16288 return ucs2Write(this, string, offset, length)
16289
16290 default:
16291 if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding)
16292 encoding = ('' + encoding).toLowerCase()
16293 loweredCase = true
16294 }
16295 }
16296}
16297
16298Buffer.prototype.toJSON = function toJSON () {
16299 return {
16300 type: 'Buffer',
16301 data: Array.prototype.slice.call(this._arr || this, 0)
16302 }
16303}
16304
16305function base64Slice (buf, start, end) {
16306 if (start === 0 && end === buf.length) {
16307 return base64.fromByteArray(buf)
16308 } else {
16309 return base64.fromByteArray(buf.slice(start, end))
16310 }
16311}
16312
16313function utf8Slice (buf, start, end) {
16314 end = Math.min(buf.length, end)
16315 var res = []
16316
16317 var i = start
16318 while (i < end) {
16319 var firstByte = buf[i]
16320 var codePoint = null
16321 var bytesPerSequence = (firstByte > 0xEF) ? 4
16322 : (firstByte > 0xDF) ? 3
16323 : (firstByte > 0xBF) ? 2
16324 : 1
16325
16326 if (i + bytesPerSequence <= end) {
16327 var secondByte, thirdByte, fourthByte, tempCodePoint
16328
16329 switch (bytesPerSequence) {
16330 case 1:
16331 if (firstByte < 0x80) {
16332 codePoint = firstByte
16333 }
16334 break
16335 case 2:
16336 secondByte = buf[i + 1]
16337 if ((secondByte & 0xC0) === 0x80) {
16338 tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F)
16339 if (tempCodePoint > 0x7F) {
16340 codePoint = tempCodePoint
16341 }
16342 }
16343 break
16344 case 3:
16345 secondByte = buf[i + 1]
16346 thirdByte = buf[i + 2]
16347 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) {
16348 tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F)
16349 if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) {
16350 codePoint = tempCodePoint
16351 }
16352 }
16353 break
16354 case 4:
16355 secondByte = buf[i + 1]
16356 thirdByte = buf[i + 2]
16357 fourthByte = buf[i + 3]
16358 if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) {
16359 tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F)
16360 if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) {
16361 codePoint = tempCodePoint
16362 }
16363 }
16364 }
16365 }
16366
16367 if (codePoint === null) {
16368 // we did not generate a valid codePoint so insert a
16369 // replacement char (U+FFFD) and advance only 1 byte
16370 codePoint = 0xFFFD
16371 bytesPerSequence = 1
16372 } else if (codePoint > 0xFFFF) {
16373 // encode to utf16 (surrogate pair dance)
16374 codePoint -= 0x10000
16375 res.push(codePoint >>> 10 & 0x3FF | 0xD800)
16376 codePoint = 0xDC00 | codePoint & 0x3FF
16377 }
16378
16379 res.push(codePoint)
16380 i += bytesPerSequence
16381 }
16382
16383 return decodeCodePointsArray(res)
16384}
16385
16386// Based on http://stackoverflow.com/a/22747272/680742, the browser with
16387// the lowest limit is Chrome, with 0x10000 args.
16388// We go 1 magnitude less, for safety
16389var MAX_ARGUMENTS_LENGTH = 0x1000
16390
16391function decodeCodePointsArray (codePoints) {
16392 var len = codePoints.length
16393 if (len <= MAX_ARGUMENTS_LENGTH) {
16394 return String.fromCharCode.apply(String, codePoints) // avoid extra slice()
16395 }
16396
16397 // Decode in chunks to avoid "call stack size exceeded".
16398 var res = ''
16399 var i = 0
16400 while (i < len) {
16401 res += String.fromCharCode.apply(
16402 String,
16403 codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH)
16404 )
16405 }
16406 return res
16407}
16408
16409function asciiSlice (buf, start, end) {
16410 var ret = ''
16411 end = Math.min(buf.length, end)
16412
16413 for (var i = start; i < end; ++i) {
16414 ret += String.fromCharCode(buf[i] & 0x7F)
16415 }
16416 return ret
16417}
16418
16419function latin1Slice (buf, start, end) {
16420 var ret = ''
16421 end = Math.min(buf.length, end)
16422
16423 for (var i = start; i < end; ++i) {
16424 ret += String.fromCharCode(buf[i])
16425 }
16426 return ret
16427}
16428
16429function hexSlice (buf, start, end) {
16430 var len = buf.length
16431
16432 if (!start || start < 0) start = 0
16433 if (!end || end < 0 || end > len) end = len
16434
16435 var out = ''
16436 for (var i = start; i < end; ++i) {
16437 out += toHex(buf[i])
16438 }
16439 return out
16440}
16441
16442function utf16leSlice (buf, start, end) {
16443 var bytes = buf.slice(start, end)
16444 var res = ''
16445 for (var i = 0; i < bytes.length; i += 2) {
16446 res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256))
16447 }
16448 return res
16449}
16450
16451Buffer.prototype.slice = function slice (start, end) {
16452 var len = this.length
16453 start = ~~start
16454 end = end === undefined ? len : ~~end
16455
16456 if (start < 0) {
16457 start += len
16458 if (start < 0) start = 0
16459 } else if (start > len) {
16460 start = len
16461 }
16462
16463 if (end < 0) {
16464 end += len
16465 if (end < 0) end = 0
16466 } else if (end > len) {
16467 end = len
16468 }
16469
16470 if (end < start) end = start
16471
16472 var newBuf = this.subarray(start, end)
16473 // Return an augmented `Uint8Array` instance
16474 newBuf.__proto__ = Buffer.prototype
16475 return newBuf
16476}
16477
16478/*
16479 * Need to make sure that buffer isn't trying to write out of bounds.
16480 */
16481function checkOffset (offset, ext, length) {
16482 if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint')
16483 if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length')
16484}
16485
16486Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) {
16487 offset = offset >>> 0
16488 byteLength = byteLength >>> 0
16489 if (!noAssert) checkOffset(offset, byteLength, this.length)
16490
16491 var val = this[offset]
16492 var mul = 1
16493 var i = 0
16494 while (++i < byteLength && (mul *= 0x100)) {
16495 val += this[offset + i] * mul
16496 }
16497
16498 return val
16499}
16500
16501Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) {
16502 offset = offset >>> 0
16503 byteLength = byteLength >>> 0
16504 if (!noAssert) {
16505 checkOffset(offset, byteLength, this.length)
16506 }
16507
16508 var val = this[offset + --byteLength]
16509 var mul = 1
16510 while (byteLength > 0 && (mul *= 0x100)) {
16511 val += this[offset + --byteLength] * mul
16512 }
16513
16514 return val
16515}
16516
16517Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) {
16518 offset = offset >>> 0
16519 if (!noAssert) checkOffset(offset, 1, this.length)
16520 return this[offset]
16521}
16522
16523Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) {
16524 offset = offset >>> 0
16525 if (!noAssert) checkOffset(offset, 2, this.length)
16526 return this[offset] | (this[offset + 1] << 8)
16527}
16528
16529Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) {
16530 offset = offset >>> 0
16531 if (!noAssert) checkOffset(offset, 2, this.length)
16532 return (this[offset] << 8) | this[offset + 1]
16533}
16534
16535Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) {
16536 offset = offset >>> 0
16537 if (!noAssert) checkOffset(offset, 4, this.length)
16538
16539 return ((this[offset]) |
16540 (this[offset + 1] << 8) |
16541 (this[offset + 2] << 16)) +
16542 (this[offset + 3] * 0x1000000)
16543}
16544
16545Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) {
16546 offset = offset >>> 0
16547 if (!noAssert) checkOffset(offset, 4, this.length)
16548
16549 return (this[offset] * 0x1000000) +
16550 ((this[offset + 1] << 16) |
16551 (this[offset + 2] << 8) |
16552 this[offset + 3])
16553}
16554
16555Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) {
16556 offset = offset >>> 0
16557 byteLength = byteLength >>> 0
16558 if (!noAssert) checkOffset(offset, byteLength, this.length)
16559
16560 var val = this[offset]
16561 var mul = 1
16562 var i = 0
16563 while (++i < byteLength && (mul *= 0x100)) {
16564 val += this[offset + i] * mul
16565 }
16566 mul *= 0x80
16567
16568 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
16569
16570 return val
16571}
16572
16573Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) {
16574 offset = offset >>> 0
16575 byteLength = byteLength >>> 0
16576 if (!noAssert) checkOffset(offset, byteLength, this.length)
16577
16578 var i = byteLength
16579 var mul = 1
16580 var val = this[offset + --i]
16581 while (i > 0 && (mul *= 0x100)) {
16582 val += this[offset + --i] * mul
16583 }
16584 mul *= 0x80
16585
16586 if (val >= mul) val -= Math.pow(2, 8 * byteLength)
16587
16588 return val
16589}
16590
16591Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) {
16592 offset = offset >>> 0
16593 if (!noAssert) checkOffset(offset, 1, this.length)
16594 if (!(this[offset] & 0x80)) return (this[offset])
16595 return ((0xff - this[offset] + 1) * -1)
16596}
16597
16598Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) {
16599 offset = offset >>> 0
16600 if (!noAssert) checkOffset(offset, 2, this.length)
16601 var val = this[offset] | (this[offset + 1] << 8)
16602 return (val & 0x8000) ? val | 0xFFFF0000 : val
16603}
16604
16605Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) {
16606 offset = offset >>> 0
16607 if (!noAssert) checkOffset(offset, 2, this.length)
16608 var val = this[offset + 1] | (this[offset] << 8)
16609 return (val & 0x8000) ? val | 0xFFFF0000 : val
16610}
16611
16612Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) {
16613 offset = offset >>> 0
16614 if (!noAssert) checkOffset(offset, 4, this.length)
16615
16616 return (this[offset]) |
16617 (this[offset + 1] << 8) |
16618 (this[offset + 2] << 16) |
16619 (this[offset + 3] << 24)
16620}
16621
16622Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) {
16623 offset = offset >>> 0
16624 if (!noAssert) checkOffset(offset, 4, this.length)
16625
16626 return (this[offset] << 24) |
16627 (this[offset + 1] << 16) |
16628 (this[offset + 2] << 8) |
16629 (this[offset + 3])
16630}
16631
16632Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) {
16633 offset = offset >>> 0
16634 if (!noAssert) checkOffset(offset, 4, this.length)
16635 return ieee754.read(this, offset, true, 23, 4)
16636}
16637
16638Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) {
16639 offset = offset >>> 0
16640 if (!noAssert) checkOffset(offset, 4, this.length)
16641 return ieee754.read(this, offset, false, 23, 4)
16642}
16643
16644Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) {
16645 offset = offset >>> 0
16646 if (!noAssert) checkOffset(offset, 8, this.length)
16647 return ieee754.read(this, offset, true, 52, 8)
16648}
16649
16650Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) {
16651 offset = offset >>> 0
16652 if (!noAssert) checkOffset(offset, 8, this.length)
16653 return ieee754.read(this, offset, false, 52, 8)
16654}
16655
16656function checkInt (buf, value, offset, ext, max, min) {
16657 if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance')
16658 if (value > max || value < min) throw new RangeError('"value" argument is out of bounds')
16659 if (offset + ext > buf.length) throw new RangeError('Index out of range')
16660}
16661
16662Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) {
16663 value = +value
16664 offset = offset >>> 0
16665 byteLength = byteLength >>> 0
16666 if (!noAssert) {
16667 var maxBytes = Math.pow(2, 8 * byteLength) - 1
16668 checkInt(this, value, offset, byteLength, maxBytes, 0)
16669 }
16670
16671 var mul = 1
16672 var i = 0
16673 this[offset] = value & 0xFF
16674 while (++i < byteLength && (mul *= 0x100)) {
16675 this[offset + i] = (value / mul) & 0xFF
16676 }
16677
16678 return offset + byteLength
16679}
16680
16681Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) {
16682 value = +value
16683 offset = offset >>> 0
16684 byteLength = byteLength >>> 0
16685 if (!noAssert) {
16686 var maxBytes = Math.pow(2, 8 * byteLength) - 1
16687 checkInt(this, value, offset, byteLength, maxBytes, 0)
16688 }
16689
16690 var i = byteLength - 1
16691 var mul = 1
16692 this[offset + i] = value & 0xFF
16693 while (--i >= 0 && (mul *= 0x100)) {
16694 this[offset + i] = (value / mul) & 0xFF
16695 }
16696
16697 return offset + byteLength
16698}
16699
16700Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) {
16701 value = +value
16702 offset = offset >>> 0
16703 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0)
16704 this[offset] = (value & 0xff)
16705 return offset + 1
16706}
16707
16708Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) {
16709 value = +value
16710 offset = offset >>> 0
16711 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
16712 this[offset] = (value & 0xff)
16713 this[offset + 1] = (value >>> 8)
16714 return offset + 2
16715}
16716
16717Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) {
16718 value = +value
16719 offset = offset >>> 0
16720 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0)
16721 this[offset] = (value >>> 8)
16722 this[offset + 1] = (value & 0xff)
16723 return offset + 2
16724}
16725
16726Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) {
16727 value = +value
16728 offset = offset >>> 0
16729 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
16730 this[offset + 3] = (value >>> 24)
16731 this[offset + 2] = (value >>> 16)
16732 this[offset + 1] = (value >>> 8)
16733 this[offset] = (value & 0xff)
16734 return offset + 4
16735}
16736
16737Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) {
16738 value = +value
16739 offset = offset >>> 0
16740 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0)
16741 this[offset] = (value >>> 24)
16742 this[offset + 1] = (value >>> 16)
16743 this[offset + 2] = (value >>> 8)
16744 this[offset + 3] = (value & 0xff)
16745 return offset + 4
16746}
16747
16748Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) {
16749 value = +value
16750 offset = offset >>> 0
16751 if (!noAssert) {
16752 var limit = Math.pow(2, (8 * byteLength) - 1)
16753
16754 checkInt(this, value, offset, byteLength, limit - 1, -limit)
16755 }
16756
16757 var i = 0
16758 var mul = 1
16759 var sub = 0
16760 this[offset] = value & 0xFF
16761 while (++i < byteLength && (mul *= 0x100)) {
16762 if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) {
16763 sub = 1
16764 }
16765 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
16766 }
16767
16768 return offset + byteLength
16769}
16770
16771Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) {
16772 value = +value
16773 offset = offset >>> 0
16774 if (!noAssert) {
16775 var limit = Math.pow(2, (8 * byteLength) - 1)
16776
16777 checkInt(this, value, offset, byteLength, limit - 1, -limit)
16778 }
16779
16780 var i = byteLength - 1
16781 var mul = 1
16782 var sub = 0
16783 this[offset + i] = value & 0xFF
16784 while (--i >= 0 && (mul *= 0x100)) {
16785 if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) {
16786 sub = 1
16787 }
16788 this[offset + i] = ((value / mul) >> 0) - sub & 0xFF
16789 }
16790
16791 return offset + byteLength
16792}
16793
16794Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) {
16795 value = +value
16796 offset = offset >>> 0
16797 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80)
16798 if (value < 0) value = 0xff + value + 1
16799 this[offset] = (value & 0xff)
16800 return offset + 1
16801}
16802
16803Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) {
16804 value = +value
16805 offset = offset >>> 0
16806 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
16807 this[offset] = (value & 0xff)
16808 this[offset + 1] = (value >>> 8)
16809 return offset + 2
16810}
16811
16812Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) {
16813 value = +value
16814 offset = offset >>> 0
16815 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000)
16816 this[offset] = (value >>> 8)
16817 this[offset + 1] = (value & 0xff)
16818 return offset + 2
16819}
16820
16821Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) {
16822 value = +value
16823 offset = offset >>> 0
16824 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
16825 this[offset] = (value & 0xff)
16826 this[offset + 1] = (value >>> 8)
16827 this[offset + 2] = (value >>> 16)
16828 this[offset + 3] = (value >>> 24)
16829 return offset + 4
16830}
16831
16832Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) {
16833 value = +value
16834 offset = offset >>> 0
16835 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000)
16836 if (value < 0) value = 0xffffffff + value + 1
16837 this[offset] = (value >>> 24)
16838 this[offset + 1] = (value >>> 16)
16839 this[offset + 2] = (value >>> 8)
16840 this[offset + 3] = (value & 0xff)
16841 return offset + 4
16842}
16843
16844function checkIEEE754 (buf, value, offset, ext, max, min) {
16845 if (offset + ext > buf.length) throw new RangeError('Index out of range')
16846 if (offset < 0) throw new RangeError('Index out of range')
16847}
16848
16849function writeFloat (buf, value, offset, littleEndian, noAssert) {
16850 value = +value
16851 offset = offset >>> 0
16852 if (!noAssert) {
16853 checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
16854 }
16855 ieee754.write(buf, value, offset, littleEndian, 23, 4)
16856 return offset + 4
16857}
16858
16859Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) {
16860 return writeFloat(this, value, offset, true, noAssert)
16861}
16862
16863Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) {
16864 return writeFloat(this, value, offset, false, noAssert)
16865}
16866
16867function writeDouble (buf, value, offset, littleEndian, noAssert) {
16868 value = +value
16869 offset = offset >>> 0
16870 if (!noAssert) {
16871 checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
16872 }
16873 ieee754.write(buf, value, offset, littleEndian, 52, 8)
16874 return offset + 8
16875}
16876
16877Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) {
16878 return writeDouble(this, value, offset, true, noAssert)
16879}
16880
16881Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) {
16882 return writeDouble(this, value, offset, false, noAssert)
16883}
16884
16885// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
16886Buffer.prototype.copy = function copy (target, targetStart, start, end) {
16887 if (!start) start = 0
16888 if (!end && end !== 0) end = this.length
16889 if (targetStart >= target.length) targetStart = target.length
16890 if (!targetStart) targetStart = 0
16891 if (end > 0 && end < start) end = start
16892
16893 // Copy 0 bytes; we're done
16894 if (end === start) return 0
16895 if (target.length === 0 || this.length === 0) return 0
16896
16897 // Fatal error conditions
16898 if (targetStart < 0) {
16899 throw new RangeError('targetStart out of bounds')
16900 }
16901 if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds')
16902 if (end < 0) throw new RangeError('sourceEnd out of bounds')
16903
16904 // Are we oob?
16905 if (end > this.length) end = this.length
16906 if (target.length - targetStart < end - start) {
16907 end = target.length - targetStart + start
16908 }
16909
16910 var len = end - start
16911 var i
16912
16913 if (this === target && start < targetStart && targetStart < end) {
16914 // descending copy from end
16915 for (i = len - 1; i >= 0; --i) {
16916 target[i + targetStart] = this[i + start]
16917 }
16918 } else if (len < 1000) {
16919 // ascending copy from start
16920 for (i = 0; i < len; ++i) {
16921 target[i + targetStart] = this[i + start]
16922 }
16923 } else {
16924 Uint8Array.prototype.set.call(
16925 target,
16926 this.subarray(start, start + len),
16927 targetStart
16928 )
16929 }
16930
16931 return len
16932}
16933
16934// Usage:
16935// buffer.fill(number[, offset[, end]])
16936// buffer.fill(buffer[, offset[, end]])
16937// buffer.fill(string[, offset[, end]][, encoding])
16938Buffer.prototype.fill = function fill (val, start, end, encoding) {
16939 // Handle string cases:
16940 if (typeof val === 'string') {
16941 if (typeof start === 'string') {
16942 encoding = start
16943 start = 0
16944 end = this.length
16945 } else if (typeof end === 'string') {
16946 encoding = end
16947 end = this.length
16948 }
16949 if (val.length === 1) {
16950 var code = val.charCodeAt(0)
16951 if (code < 256) {
16952 val = code
16953 }
16954 }
16955 if (encoding !== undefined && typeof encoding !== 'string') {
16956 throw new TypeError('encoding must be a string')
16957 }
16958 if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) {
16959 throw new TypeError('Unknown encoding: ' + encoding)
16960 }
16961 } else if (typeof val === 'number') {
16962 val = val & 255
16963 }
16964
16965 // Invalid ranges are not set to a default, so can range check early.
16966 if (start < 0 || this.length < start || this.length < end) {
16967 throw new RangeError('Out of range index')
16968 }
16969
16970 if (end <= start) {
16971 return this
16972 }
16973
16974 start = start >>> 0
16975 end = end === undefined ? this.length : end >>> 0
16976
16977 if (!val) val = 0
16978
16979 var i
16980 if (typeof val === 'number') {
16981 for (i = start; i < end; ++i) {
16982 this[i] = val
16983 }
16984 } else {
16985 var bytes = Buffer.isBuffer(val)
16986 ? val
16987 : new Buffer(val, encoding)
16988 var len = bytes.length
16989 for (i = 0; i < end - start; ++i) {
16990 this[i + start] = bytes[i % len]
16991 }
16992 }
16993
16994 return this
16995}
16996
16997// HELPER FUNCTIONS
16998// ================
16999
17000var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g
17001
17002function base64clean (str) {
17003 // Node strips out invalid characters like \n and \t from the string, base64-js does not
17004 str = str.trim().replace(INVALID_BASE64_RE, '')
17005 // Node converts strings with length < 2 to ''
17006 if (str.length < 2) return ''
17007 // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not
17008 while (str.length % 4 !== 0) {
17009 str = str + '='
17010 }
17011 return str
17012}
17013
17014function toHex (n) {
17015 if (n < 16) return '0' + n.toString(16)
17016 return n.toString(16)
17017}
17018
17019function utf8ToBytes (string, units) {
17020 units = units || Infinity
17021 var codePoint
17022 var length = string.length
17023 var leadSurrogate = null
17024 var bytes = []
17025
17026 for (var i = 0; i < length; ++i) {
17027 codePoint = string.charCodeAt(i)
17028
17029 // is surrogate component
17030 if (codePoint > 0xD7FF && codePoint < 0xE000) {
17031 // last char was a lead
17032 if (!leadSurrogate) {
17033 // no lead yet
17034 if (codePoint > 0xDBFF) {
17035 // unexpected trail
17036 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
17037 continue
17038 } else if (i + 1 === length) {
17039 // unpaired lead
17040 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
17041 continue
17042 }
17043
17044 // valid lead
17045 leadSurrogate = codePoint
17046
17047 continue
17048 }
17049
17050 // 2 leads in a row
17051 if (codePoint < 0xDC00) {
17052 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
17053 leadSurrogate = codePoint
17054 continue
17055 }
17056
17057 // valid surrogate pair
17058 codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000
17059 } else if (leadSurrogate) {
17060 // valid bmp char, but last char was a lead
17061 if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD)
17062 }
17063
17064 leadSurrogate = null
17065
17066 // encode utf8
17067 if (codePoint < 0x80) {
17068 if ((units -= 1) < 0) break
17069 bytes.push(codePoint)
17070 } else if (codePoint < 0x800) {
17071 if ((units -= 2) < 0) break
17072 bytes.push(
17073 codePoint >> 0x6 | 0xC0,
17074 codePoint & 0x3F | 0x80
17075 )
17076 } else if (codePoint < 0x10000) {
17077 if ((units -= 3) < 0) break
17078 bytes.push(
17079 codePoint >> 0xC | 0xE0,
17080 codePoint >> 0x6 & 0x3F | 0x80,
17081 codePoint & 0x3F | 0x80
17082 )
17083 } else if (codePoint < 0x110000) {
17084 if ((units -= 4) < 0) break
17085 bytes.push(
17086 codePoint >> 0x12 | 0xF0,
17087 codePoint >> 0xC & 0x3F | 0x80,
17088 codePoint >> 0x6 & 0x3F | 0x80,
17089 codePoint & 0x3F | 0x80
17090 )
17091 } else {
17092 throw new Error('Invalid code point')
17093 }
17094 }
17095
17096 return bytes
17097}
17098
17099function asciiToBytes (str) {
17100 var byteArray = []
17101 for (var i = 0; i < str.length; ++i) {
17102 // Node's code seems to be doing this and not & 0x7F..
17103 byteArray.push(str.charCodeAt(i) & 0xFF)
17104 }
17105 return byteArray
17106}
17107
17108function utf16leToBytes (str, units) {
17109 var c, hi, lo
17110 var byteArray = []
17111 for (var i = 0; i < str.length; ++i) {
17112 if ((units -= 2) < 0) break
17113
17114 c = str.charCodeAt(i)
17115 hi = c >> 8
17116 lo = c % 256
17117 byteArray.push(lo)
17118 byteArray.push(hi)
17119 }
17120
17121 return byteArray
17122}
17123
17124function base64ToBytes (str) {
17125 return base64.toByteArray(base64clean(str))
17126}
17127
17128function blitBuffer (src, dst, offset, length) {
17129 for (var i = 0; i < length; ++i) {
17130 if ((i + offset >= dst.length) || (i >= src.length)) break
17131 dst[i + offset] = src[i]
17132 }
17133 return i
17134}
17135
17136// ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check
17137// but they should be treated as valid. See: https://github.com/feross/buffer/issues/166
17138function isArrayBuffer (obj) {
17139 return obj instanceof ArrayBuffer ||
17140 (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' &&
17141 typeof obj.byteLength === 'number')
17142}
17143
17144// Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
17145function isArrayBufferView (obj) {
17146 return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj)
17147}
17148
17149function numberIsNaN (obj) {
17150 return obj !== obj // eslint-disable-line no-self-compare
17151}
17152
17153},{"base64-js":72,"ieee754":161}],108:[function(require,module,exports){
17154var Buffer = require('safe-buffer').Buffer
17155var Transform = require('stream').Transform
17156var StringDecoder = require('string_decoder').StringDecoder
17157var inherits = require('inherits')
17158
17159function CipherBase (hashMode) {
17160 Transform.call(this)
17161 this.hashMode = typeof hashMode === 'string'
17162 if (this.hashMode) {
17163 this[hashMode] = this._finalOrDigest
17164 } else {
17165 this.final = this._finalOrDigest
17166 }
17167 if (this._final) {
17168 this.__final = this._final
17169 this._final = null
17170 }
17171 this._decoder = null
17172 this._encoding = null
17173}
17174inherits(CipherBase, Transform)
17175
17176CipherBase.prototype.update = function (data, inputEnc, outputEnc) {
17177 if (typeof data === 'string') {
17178 data = Buffer.from(data, inputEnc)
17179 }
17180
17181 var outData = this._update(data)
17182 if (this.hashMode) return this
17183
17184 if (outputEnc) {
17185 outData = this._toString(outData, outputEnc)
17186 }
17187
17188 return outData
17189}
17190
17191CipherBase.prototype.setAutoPadding = function () {}
17192CipherBase.prototype.getAuthTag = function () {
17193 throw new Error('trying to get auth tag in unsupported state')
17194}
17195
17196CipherBase.prototype.setAuthTag = function () {
17197 throw new Error('trying to set auth tag in unsupported state')
17198}
17199
17200CipherBase.prototype.setAAD = function () {
17201 throw new Error('trying to set aad in unsupported state')
17202}
17203
17204CipherBase.prototype._transform = function (data, _, next) {
17205 var err
17206 try {
17207 if (this.hashMode) {
17208 this._update(data)
17209 } else {
17210 this.push(this._update(data))
17211 }
17212 } catch (e) {
17213 err = e
17214 } finally {
17215 next(err)
17216 }
17217}
17218CipherBase.prototype._flush = function (done) {
17219 var err
17220 try {
17221 this.push(this.__final())
17222 } catch (e) {
17223 err = e
17224 }
17225
17226 done(err)
17227}
17228CipherBase.prototype._finalOrDigest = function (outputEnc) {
17229 var outData = this.__final() || Buffer.alloc(0)
17230 if (outputEnc) {
17231 outData = this._toString(outData, outputEnc, true)
17232 }
17233 return outData
17234}
17235
17236CipherBase.prototype._toString = function (value, enc, fin) {
17237 if (!this._decoder) {
17238 this._decoder = new StringDecoder(enc)
17239 this._encoding = enc
17240 }
17241
17242 if (this._encoding !== enc) throw new Error('can\'t switch encodings')
17243
17244 var out = this._decoder.write(value)
17245 if (fin) {
17246 out += this._decoder.end()
17247 }
17248
17249 return out
17250}
17251
17252module.exports = CipherBase
17253
17254},{"inherits":163,"safe-buffer":247,"stream":263,"string_decoder":264}],109:[function(require,module,exports){
17255(function (Buffer){
17256// Copyright Joyent, Inc. and other Node contributors.
17257//
17258// Permission is hereby granted, free of charge, to any person obtaining a
17259// copy of this software and associated documentation files (the
17260// "Software"), to deal in the Software without restriction, including
17261// without limitation the rights to use, copy, modify, merge, publish,
17262// distribute, sublicense, and/or sell copies of the Software, and to permit
17263// persons to whom the Software is furnished to do so, subject to the
17264// following conditions:
17265//
17266// The above copyright notice and this permission notice shall be included
17267// in all copies or substantial portions of the Software.
17268//
17269// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
17270// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
17271// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
17272// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
17273// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
17274// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
17275// USE OR OTHER DEALINGS IN THE SOFTWARE.
17276
17277// NOTE: These type checking functions intentionally don't use `instanceof`
17278// because it is fragile and can be easily faked with `Object.create()`.
17279
17280function isArray(arg) {
17281 if (Array.isArray) {
17282 return Array.isArray(arg);
17283 }
17284 return objectToString(arg) === '[object Array]';
17285}
17286exports.isArray = isArray;
17287
17288function isBoolean(arg) {
17289 return typeof arg === 'boolean';
17290}
17291exports.isBoolean = isBoolean;
17292
17293function isNull(arg) {
17294 return arg === null;
17295}
17296exports.isNull = isNull;
17297
17298function isNullOrUndefined(arg) {
17299 return arg == null;
17300}
17301exports.isNullOrUndefined = isNullOrUndefined;
17302
17303function isNumber(arg) {
17304 return typeof arg === 'number';
17305}
17306exports.isNumber = isNumber;
17307
17308function isString(arg) {
17309 return typeof arg === 'string';
17310}
17311exports.isString = isString;
17312
17313function isSymbol(arg) {
17314 return typeof arg === 'symbol';
17315}
17316exports.isSymbol = isSymbol;
17317
17318function isUndefined(arg) {
17319 return arg === void 0;
17320}
17321exports.isUndefined = isUndefined;
17322
17323function isRegExp(re) {
17324 return objectToString(re) === '[object RegExp]';
17325}
17326exports.isRegExp = isRegExp;
17327
17328function isObject(arg) {
17329 return typeof arg === 'object' && arg !== null;
17330}
17331exports.isObject = isObject;
17332
17333function isDate(d) {
17334 return objectToString(d) === '[object Date]';
17335}
17336exports.isDate = isDate;
17337
17338function isError(e) {
17339 return (objectToString(e) === '[object Error]' || e instanceof Error);
17340}
17341exports.isError = isError;
17342
17343function isFunction(arg) {
17344 return typeof arg === 'function';
17345}
17346exports.isFunction = isFunction;
17347
17348function isPrimitive(arg) {
17349 return arg === null ||
17350 typeof arg === 'boolean' ||
17351 typeof arg === 'number' ||
17352 typeof arg === 'string' ||
17353 typeof arg === 'symbol' || // ES6 symbol
17354 typeof arg === 'undefined';
17355}
17356exports.isPrimitive = isPrimitive;
17357
17358exports.isBuffer = Buffer.isBuffer;
17359
17360function objectToString(o) {
17361 return Object.prototype.toString.call(o);
17362}
17363
17364}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
17365},{"../../is-buffer/index.js":164}],110:[function(require,module,exports){
17366(function (Buffer){
17367var elliptic = require('elliptic');
17368var BN = require('bn.js');
17369
17370module.exports = function createECDH(curve) {
17371 return new ECDH(curve);
17372};
17373
17374var aliases = {
17375 secp256k1: {
17376 name: 'secp256k1',
17377 byteLength: 32
17378 },
17379 secp224r1: {
17380 name: 'p224',
17381 byteLength: 28
17382 },
17383 prime256v1: {
17384 name: 'p256',
17385 byteLength: 32
17386 },
17387 prime192v1: {
17388 name: 'p192',
17389 byteLength: 24
17390 },
17391 ed25519: {
17392 name: 'ed25519',
17393 byteLength: 32
17394 },
17395 secp384r1: {
17396 name: 'p384',
17397 byteLength: 48
17398 },
17399 secp521r1: {
17400 name: 'p521',
17401 byteLength: 66
17402 }
17403};
17404
17405aliases.p224 = aliases.secp224r1;
17406aliases.p256 = aliases.secp256r1 = aliases.prime256v1;
17407aliases.p192 = aliases.secp192r1 = aliases.prime192v1;
17408aliases.p384 = aliases.secp384r1;
17409aliases.p521 = aliases.secp521r1;
17410
17411function ECDH(curve) {
17412 this.curveType = aliases[curve];
17413 if (!this.curveType ) {
17414 this.curveType = {
17415 name: curve
17416 };
17417 }
17418 this.curve = new elliptic.ec(this.curveType.name);
17419 this.keys = void 0;
17420}
17421
17422ECDH.prototype.generateKeys = function (enc, format) {
17423 this.keys = this.curve.genKeyPair();
17424 return this.getPublicKey(enc, format);
17425};
17426
17427ECDH.prototype.computeSecret = function (other, inenc, enc) {
17428 inenc = inenc || 'utf8';
17429 if (!Buffer.isBuffer(other)) {
17430 other = new Buffer(other, inenc);
17431 }
17432 var otherPub = this.curve.keyFromPublic(other).getPublic();
17433 var out = otherPub.mul(this.keys.getPrivate()).getX();
17434 return formatReturnValue(out, enc, this.curveType.byteLength);
17435};
17436
17437ECDH.prototype.getPublicKey = function (enc, format) {
17438 var key = this.keys.getPublic(format === 'compressed', true);
17439 if (format === 'hybrid') {
17440 if (key[key.length - 1] % 2) {
17441 key[0] = 7;
17442 } else {
17443 key [0] = 6;
17444 }
17445 }
17446 return formatReturnValue(key, enc);
17447};
17448
17449ECDH.prototype.getPrivateKey = function (enc) {
17450 return formatReturnValue(this.keys.getPrivate(), enc);
17451};
17452
17453ECDH.prototype.setPublicKey = function (pub, enc) {
17454 enc = enc || 'utf8';
17455 if (!Buffer.isBuffer(pub)) {
17456 pub = new Buffer(pub, enc);
17457 }
17458 this.keys._importPublic(pub);
17459 return this;
17460};
17461
17462ECDH.prototype.setPrivateKey = function (priv, enc) {
17463 enc = enc || 'utf8';
17464 if (!Buffer.isBuffer(priv)) {
17465 priv = new Buffer(priv, enc);
17466 }
17467 var _priv = new BN(priv);
17468 _priv = _priv.toString(16);
17469 this.keys._importPrivate(_priv);
17470 return this;
17471};
17472
17473function formatReturnValue(bn, enc, len) {
17474 if (!Array.isArray(bn)) {
17475 bn = bn.toArray();
17476 }
17477 var buf = new Buffer(bn);
17478 if (len && buf.length < len) {
17479 var zeros = new Buffer(len - buf.length);
17480 zeros.fill(0);
17481 buf = Buffer.concat([zeros, buf]);
17482 }
17483 if (!enc) {
17484 return buf;
17485 } else {
17486 return buf.toString(enc);
17487 }
17488}
17489
17490}).call(this,require("buffer").Buffer)
17491},{"bn.js":75,"buffer":107,"elliptic":127}],111:[function(require,module,exports){
17492(function (Buffer){
17493'use strict'
17494var inherits = require('inherits')
17495var md5 = require('./md5')
17496var RIPEMD160 = require('ripemd160')
17497var sha = require('sha.js')
17498
17499var Base = require('cipher-base')
17500
17501function HashNoConstructor (hash) {
17502 Base.call(this, 'digest')
17503
17504 this._hash = hash
17505 this.buffers = []
17506}
17507
17508inherits(HashNoConstructor, Base)
17509
17510HashNoConstructor.prototype._update = function (data) {
17511 this.buffers.push(data)
17512}
17513
17514HashNoConstructor.prototype._final = function () {
17515 var buf = Buffer.concat(this.buffers)
17516 var r = this._hash(buf)
17517 this.buffers = null
17518
17519 return r
17520}
17521
17522function Hash (hash) {
17523 Base.call(this, 'digest')
17524
17525 this._hash = hash
17526}
17527
17528inherits(Hash, Base)
17529
17530Hash.prototype._update = function (data) {
17531 this._hash.update(data)
17532}
17533
17534Hash.prototype._final = function () {
17535 return this._hash.digest()
17536}
17537
17538module.exports = function createHash (alg) {
17539 alg = alg.toLowerCase()
17540 if (alg === 'md5') return new HashNoConstructor(md5)
17541 if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160())
17542
17543 return new Hash(sha(alg))
17544}
17545
17546}).call(this,require("buffer").Buffer)
17547},{"./md5":113,"buffer":107,"cipher-base":108,"inherits":163,"ripemd160":246,"sha.js":256}],112:[function(require,module,exports){
17548(function (Buffer){
17549'use strict'
17550var intSize = 4
17551var zeroBuffer = new Buffer(intSize)
17552zeroBuffer.fill(0)
17553
17554var charSize = 8
17555var hashSize = 16
17556
17557function toArray (buf) {
17558 if ((buf.length % intSize) !== 0) {
17559 var len = buf.length + (intSize - (buf.length % intSize))
17560 buf = Buffer.concat([buf, zeroBuffer], len)
17561 }
17562
17563 var arr = new Array(buf.length >>> 2)
17564 for (var i = 0, j = 0; i < buf.length; i += intSize, j++) {
17565 arr[j] = buf.readInt32LE(i)
17566 }
17567
17568 return arr
17569}
17570
17571module.exports = function hash (buf, fn) {
17572 var arr = fn(toArray(buf), buf.length * charSize)
17573 buf = new Buffer(hashSize)
17574 for (var i = 0; i < arr.length; i++) {
17575 buf.writeInt32LE(arr[i], i << 2, true)
17576 }
17577 return buf
17578}
17579
17580}).call(this,require("buffer").Buffer)
17581},{"buffer":107}],113:[function(require,module,exports){
17582'use strict'
17583/*
17584 * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
17585 * Digest Algorithm, as defined in RFC 1321.
17586 * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002.
17587 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
17588 * Distributed under the BSD License
17589 * See http://pajhome.org.uk/crypt/md5 for more info.
17590 */
17591
17592var makeHash = require('./make-hash')
17593
17594/*
17595 * Calculate the MD5 of an array of little-endian words, and a bit length
17596 */
17597function core_md5 (x, len) {
17598 /* append padding */
17599 x[len >> 5] |= 0x80 << ((len) % 32)
17600 x[(((len + 64) >>> 9) << 4) + 14] = len
17601
17602 var a = 1732584193
17603 var b = -271733879
17604 var c = -1732584194
17605 var d = 271733878
17606
17607 for (var i = 0; i < x.length; i += 16) {
17608 var olda = a
17609 var oldb = b
17610 var oldc = c
17611 var oldd = d
17612
17613 a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936)
17614 d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586)
17615 c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819)
17616 b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330)
17617 a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897)
17618 d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426)
17619 c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341)
17620 b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983)
17621 a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416)
17622 d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417)
17623 c = md5_ff(c, d, a, b, x[i + 10], 17, -42063)
17624 b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162)
17625 a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682)
17626 d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101)
17627 c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290)
17628 b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329)
17629
17630 a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510)
17631 d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632)
17632 c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713)
17633 b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302)
17634 a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691)
17635 d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083)
17636 c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335)
17637 b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848)
17638 a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438)
17639 d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690)
17640 c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961)
17641 b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501)
17642 a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467)
17643 d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784)
17644 c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473)
17645 b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734)
17646
17647 a = md5_hh(a, b, c, d, x[i + 5], 4, -378558)
17648 d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463)
17649 c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562)
17650 b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556)
17651 a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060)
17652 d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353)
17653 c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632)
17654 b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640)
17655 a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174)
17656 d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222)
17657 c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979)
17658 b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189)
17659 a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487)
17660 d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835)
17661 c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520)
17662 b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651)
17663
17664 a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844)
17665 d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415)
17666 c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905)
17667 b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055)
17668 a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571)
17669 d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606)
17670 c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523)
17671 b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799)
17672 a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359)
17673 d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744)
17674 c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380)
17675 b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649)
17676 a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070)
17677 d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379)
17678 c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259)
17679 b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551)
17680
17681 a = safe_add(a, olda)
17682 b = safe_add(b, oldb)
17683 c = safe_add(c, oldc)
17684 d = safe_add(d, oldd)
17685 }
17686
17687 return [a, b, c, d]
17688}
17689
17690/*
17691 * These functions implement the four basic operations the algorithm uses.
17692 */
17693function md5_cmn (q, a, b, x, s, t) {
17694 return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b)
17695}
17696
17697function md5_ff (a, b, c, d, x, s, t) {
17698 return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t)
17699}
17700
17701function md5_gg (a, b, c, d, x, s, t) {
17702 return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t)
17703}
17704
17705function md5_hh (a, b, c, d, x, s, t) {
17706 return md5_cmn(b ^ c ^ d, a, b, x, s, t)
17707}
17708
17709function md5_ii (a, b, c, d, x, s, t) {
17710 return md5_cmn(c ^ (b | (~d)), a, b, x, s, t)
17711}
17712
17713/*
17714 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
17715 * to work around bugs in some JS interpreters.
17716 */
17717function safe_add (x, y) {
17718 var lsw = (x & 0xFFFF) + (y & 0xFFFF)
17719 var msw = (x >> 16) + (y >> 16) + (lsw >> 16)
17720 return (msw << 16) | (lsw & 0xFFFF)
17721}
17722
17723/*
17724 * Bitwise rotate a 32-bit number to the left.
17725 */
17726function bit_rol (num, cnt) {
17727 return (num << cnt) | (num >>> (32 - cnt))
17728}
17729
17730module.exports = function md5 (buf) {
17731 return makeHash(buf, core_md5)
17732}
17733
17734},{"./make-hash":112}],114:[function(require,module,exports){
17735'use strict'
17736var inherits = require('inherits')
17737var Legacy = require('./legacy')
17738var Base = require('cipher-base')
17739var Buffer = require('safe-buffer').Buffer
17740var md5 = require('create-hash/md5')
17741var RIPEMD160 = require('ripemd160')
17742
17743var sha = require('sha.js')
17744
17745var ZEROS = Buffer.alloc(128)
17746
17747function Hmac (alg, key) {
17748 Base.call(this, 'digest')
17749 if (typeof key === 'string') {
17750 key = Buffer.from(key)
17751 }
17752
17753 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
17754
17755 this._alg = alg
17756 this._key = key
17757 if (key.length > blocksize) {
17758 var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
17759 key = hash.update(key).digest()
17760 } else if (key.length < blocksize) {
17761 key = Buffer.concat([key, ZEROS], blocksize)
17762 }
17763
17764 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
17765 var opad = this._opad = Buffer.allocUnsafe(blocksize)
17766
17767 for (var i = 0; i < blocksize; i++) {
17768 ipad[i] = key[i] ^ 0x36
17769 opad[i] = key[i] ^ 0x5C
17770 }
17771 this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg)
17772 this._hash.update(ipad)
17773}
17774
17775inherits(Hmac, Base)
17776
17777Hmac.prototype._update = function (data) {
17778 this._hash.update(data)
17779}
17780
17781Hmac.prototype._final = function () {
17782 var h = this._hash.digest()
17783 var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg)
17784 return hash.update(this._opad).update(h).digest()
17785}
17786
17787module.exports = function createHmac (alg, key) {
17788 alg = alg.toLowerCase()
17789 if (alg === 'rmd160' || alg === 'ripemd160') {
17790 return new Hmac('rmd160', key)
17791 }
17792 if (alg === 'md5') {
17793 return new Legacy(md5, key)
17794 }
17795 return new Hmac(alg, key)
17796}
17797
17798},{"./legacy":115,"cipher-base":108,"create-hash/md5":113,"inherits":163,"ripemd160":246,"safe-buffer":247,"sha.js":256}],115:[function(require,module,exports){
17799'use strict'
17800var inherits = require('inherits')
17801var Buffer = require('safe-buffer').Buffer
17802
17803var Base = require('cipher-base')
17804
17805var ZEROS = Buffer.alloc(128)
17806var blocksize = 64
17807
17808function Hmac (alg, key) {
17809 Base.call(this, 'digest')
17810 if (typeof key === 'string') {
17811 key = Buffer.from(key)
17812 }
17813
17814 this._alg = alg
17815 this._key = key
17816
17817 if (key.length > blocksize) {
17818 key = alg(key)
17819 } else if (key.length < blocksize) {
17820 key = Buffer.concat([key, ZEROS], blocksize)
17821 }
17822
17823 var ipad = this._ipad = Buffer.allocUnsafe(blocksize)
17824 var opad = this._opad = Buffer.allocUnsafe(blocksize)
17825
17826 for (var i = 0; i < blocksize; i++) {
17827 ipad[i] = key[i] ^ 0x36
17828 opad[i] = key[i] ^ 0x5C
17829 }
17830
17831 this._hash = [ipad]
17832}
17833
17834inherits(Hmac, Base)
17835
17836Hmac.prototype._update = function (data) {
17837 this._hash.push(data)
17838}
17839
17840Hmac.prototype._final = function () {
17841 var h = this._alg(Buffer.concat(this._hash))
17842 return this._alg(Buffer.concat([this._opad, h]))
17843}
17844module.exports = Hmac
17845
17846},{"cipher-base":108,"inherits":163,"safe-buffer":247}],116:[function(require,module,exports){
17847'use strict'
17848
17849exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes')
17850exports.createHash = exports.Hash = require('create-hash')
17851exports.createHmac = exports.Hmac = require('create-hmac')
17852
17853var algos = require('browserify-sign/algos')
17854var algoKeys = Object.keys(algos)
17855var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys)
17856exports.getHashes = function () {
17857 return hashes
17858}
17859
17860var p = require('pbkdf2')
17861exports.pbkdf2 = p.pbkdf2
17862exports.pbkdf2Sync = p.pbkdf2Sync
17863
17864var aes = require('browserify-cipher')
17865
17866exports.Cipher = aes.Cipher
17867exports.createCipher = aes.createCipher
17868exports.Cipheriv = aes.Cipheriv
17869exports.createCipheriv = aes.createCipheriv
17870exports.Decipher = aes.Decipher
17871exports.createDecipher = aes.createDecipher
17872exports.Decipheriv = aes.Decipheriv
17873exports.createDecipheriv = aes.createDecipheriv
17874exports.getCiphers = aes.getCiphers
17875exports.listCiphers = aes.listCiphers
17876
17877var dh = require('diffie-hellman')
17878
17879exports.DiffieHellmanGroup = dh.DiffieHellmanGroup
17880exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup
17881exports.getDiffieHellman = dh.getDiffieHellman
17882exports.createDiffieHellman = dh.createDiffieHellman
17883exports.DiffieHellman = dh.DiffieHellman
17884
17885var sign = require('browserify-sign')
17886
17887exports.createSign = sign.createSign
17888exports.Sign = sign.Sign
17889exports.createVerify = sign.createVerify
17890exports.Verify = sign.Verify
17891
17892exports.createECDH = require('create-ecdh')
17893
17894var publicEncrypt = require('public-encrypt')
17895
17896exports.publicEncrypt = publicEncrypt.publicEncrypt
17897exports.privateEncrypt = publicEncrypt.privateEncrypt
17898exports.publicDecrypt = publicEncrypt.publicDecrypt
17899exports.privateDecrypt = publicEncrypt.privateDecrypt
17900
17901// the least I can do is make error messages for the rest of the node.js/crypto api.
17902// ;[
17903// 'createCredentials'
17904// ].forEach(function (name) {
17905// exports[name] = function () {
17906// throw new Error([
17907// 'sorry, ' + name + ' is not implemented yet',
17908// 'we accept pull requests',
17909// 'https://github.com/crypto-browserify/crypto-browserify'
17910// ].join('\n'))
17911// }
17912// })
17913
17914var rf = require('randomfill')
17915
17916exports.randomFill = rf.randomFill
17917exports.randomFillSync = rf.randomFillSync
17918
17919exports.createCredentials = function () {
17920 throw new Error([
17921 'sorry, createCredentials is not implemented yet',
17922 'we accept pull requests',
17923 'https://github.com/crypto-browserify/crypto-browserify'
17924 ].join('\n'))
17925}
17926
17927exports.constants = {
17928 'DH_CHECK_P_NOT_SAFE_PRIME': 2,
17929 'DH_CHECK_P_NOT_PRIME': 1,
17930 'DH_UNABLE_TO_CHECK_GENERATOR': 4,
17931 'DH_NOT_SUITABLE_GENERATOR': 8,
17932 'NPN_ENABLED': 1,
17933 'ALPN_ENABLED': 1,
17934 'RSA_PKCS1_PADDING': 1,
17935 'RSA_SSLV23_PADDING': 2,
17936 'RSA_NO_PADDING': 3,
17937 'RSA_PKCS1_OAEP_PADDING': 4,
17938 'RSA_X931_PADDING': 5,
17939 'RSA_PKCS1_PSS_PADDING': 6,
17940 'POINT_CONVERSION_COMPRESSED': 2,
17941 'POINT_CONVERSION_UNCOMPRESSED': 4,
17942 'POINT_CONVERSION_HYBRID': 6
17943}
17944
17945},{"browserify-cipher":95,"browserify-sign":102,"browserify-sign/algos":99,"create-ecdh":110,"create-hash":111,"create-hmac":114,"diffie-hellman":123,"pbkdf2":184,"public-encrypt":225,"randombytes":231,"randomfill":232}],117:[function(require,module,exports){
17946'use strict';
17947
17948exports.utils = require('./des/utils');
17949exports.Cipher = require('./des/cipher');
17950exports.DES = require('./des/des');
17951exports.CBC = require('./des/cbc');
17952exports.EDE = require('./des/ede');
17953
17954},{"./des/cbc":118,"./des/cipher":119,"./des/des":120,"./des/ede":121,"./des/utils":122}],118:[function(require,module,exports){
17955'use strict';
17956
17957var assert = require('minimalistic-assert');
17958var inherits = require('inherits');
17959
17960var proto = {};
17961
17962function CBCState(iv) {
17963 assert.equal(iv.length, 8, 'Invalid IV length');
17964
17965 this.iv = new Array(8);
17966 for (var i = 0; i < this.iv.length; i++)
17967 this.iv[i] = iv[i];
17968}
17969
17970function instantiate(Base) {
17971 function CBC(options) {
17972 Base.call(this, options);
17973 this._cbcInit();
17974 }
17975 inherits(CBC, Base);
17976
17977 var keys = Object.keys(proto);
17978 for (var i = 0; i < keys.length; i++) {
17979 var key = keys[i];
17980 CBC.prototype[key] = proto[key];
17981 }
17982
17983 CBC.create = function create(options) {
17984 return new CBC(options);
17985 };
17986
17987 return CBC;
17988}
17989
17990exports.instantiate = instantiate;
17991
17992proto._cbcInit = function _cbcInit() {
17993 var state = new CBCState(this.options.iv);
17994 this._cbcState = state;
17995};
17996
17997proto._update = function _update(inp, inOff, out, outOff) {
17998 var state = this._cbcState;
17999 var superProto = this.constructor.super_.prototype;
18000
18001 var iv = state.iv;
18002 if (this.type === 'encrypt') {
18003 for (var i = 0; i < this.blockSize; i++)
18004 iv[i] ^= inp[inOff + i];
18005
18006 superProto._update.call(this, iv, 0, out, outOff);
18007
18008 for (var i = 0; i < this.blockSize; i++)
18009 iv[i] = out[outOff + i];
18010 } else {
18011 superProto._update.call(this, inp, inOff, out, outOff);
18012
18013 for (var i = 0; i < this.blockSize; i++)
18014 out[outOff + i] ^= iv[i];
18015
18016 for (var i = 0; i < this.blockSize; i++)
18017 iv[i] = inp[inOff + i];
18018 }
18019};
18020
18021},{"inherits":163,"minimalistic-assert":176}],119:[function(require,module,exports){
18022'use strict';
18023
18024var assert = require('minimalistic-assert');
18025
18026function Cipher(options) {
18027 this.options = options;
18028
18029 this.type = this.options.type;
18030 this.blockSize = 8;
18031 this._init();
18032
18033 this.buffer = new Array(this.blockSize);
18034 this.bufferOff = 0;
18035}
18036module.exports = Cipher;
18037
18038Cipher.prototype._init = function _init() {
18039 // Might be overrided
18040};
18041
18042Cipher.prototype.update = function update(data) {
18043 if (data.length === 0)
18044 return [];
18045
18046 if (this.type === 'decrypt')
18047 return this._updateDecrypt(data);
18048 else
18049 return this._updateEncrypt(data);
18050};
18051
18052Cipher.prototype._buffer = function _buffer(data, off) {
18053 // Append data to buffer
18054 var min = Math.min(this.buffer.length - this.bufferOff, data.length - off);
18055 for (var i = 0; i < min; i++)
18056 this.buffer[this.bufferOff + i] = data[off + i];
18057 this.bufferOff += min;
18058
18059 // Shift next
18060 return min;
18061};
18062
18063Cipher.prototype._flushBuffer = function _flushBuffer(out, off) {
18064 this._update(this.buffer, 0, out, off);
18065 this.bufferOff = 0;
18066 return this.blockSize;
18067};
18068
18069Cipher.prototype._updateEncrypt = function _updateEncrypt(data) {
18070 var inputOff = 0;
18071 var outputOff = 0;
18072
18073 var count = ((this.bufferOff + data.length) / this.blockSize) | 0;
18074 var out = new Array(count * this.blockSize);
18075
18076 if (this.bufferOff !== 0) {
18077 inputOff += this._buffer(data, inputOff);
18078
18079 if (this.bufferOff === this.buffer.length)
18080 outputOff += this._flushBuffer(out, outputOff);
18081 }
18082
18083 // Write blocks
18084 var max = data.length - ((data.length - inputOff) % this.blockSize);
18085 for (; inputOff < max; inputOff += this.blockSize) {
18086 this._update(data, inputOff, out, outputOff);
18087 outputOff += this.blockSize;
18088 }
18089
18090 // Queue rest
18091 for (; inputOff < data.length; inputOff++, this.bufferOff++)
18092 this.buffer[this.bufferOff] = data[inputOff];
18093
18094 return out;
18095};
18096
18097Cipher.prototype._updateDecrypt = function _updateDecrypt(data) {
18098 var inputOff = 0;
18099 var outputOff = 0;
18100
18101 var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1;
18102 var out = new Array(count * this.blockSize);
18103
18104 // TODO(indutny): optimize it, this is far from optimal
18105 for (; count > 0; count--) {
18106 inputOff += this._buffer(data, inputOff);
18107 outputOff += this._flushBuffer(out, outputOff);
18108 }
18109
18110 // Buffer rest of the input
18111 inputOff += this._buffer(data, inputOff);
18112
18113 return out;
18114};
18115
18116Cipher.prototype.final = function final(buffer) {
18117 var first;
18118 if (buffer)
18119 first = this.update(buffer);
18120
18121 var last;
18122 if (this.type === 'encrypt')
18123 last = this._finalEncrypt();
18124 else
18125 last = this._finalDecrypt();
18126
18127 if (first)
18128 return first.concat(last);
18129 else
18130 return last;
18131};
18132
18133Cipher.prototype._pad = function _pad(buffer, off) {
18134 if (off === 0)
18135 return false;
18136
18137 while (off < buffer.length)
18138 buffer[off++] = 0;
18139
18140 return true;
18141};
18142
18143Cipher.prototype._finalEncrypt = function _finalEncrypt() {
18144 if (!this._pad(this.buffer, this.bufferOff))
18145 return [];
18146
18147 var out = new Array(this.blockSize);
18148 this._update(this.buffer, 0, out, 0);
18149 return out;
18150};
18151
18152Cipher.prototype._unpad = function _unpad(buffer) {
18153 return buffer;
18154};
18155
18156Cipher.prototype._finalDecrypt = function _finalDecrypt() {
18157 assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt');
18158 var out = new Array(this.blockSize);
18159 this._flushBuffer(out, 0);
18160
18161 return this._unpad(out);
18162};
18163
18164},{"minimalistic-assert":176}],120:[function(require,module,exports){
18165'use strict';
18166
18167var assert = require('minimalistic-assert');
18168var inherits = require('inherits');
18169
18170var des = require('../des');
18171var utils = des.utils;
18172var Cipher = des.Cipher;
18173
18174function DESState() {
18175 this.tmp = new Array(2);
18176 this.keys = null;
18177}
18178
18179function DES(options) {
18180 Cipher.call(this, options);
18181
18182 var state = new DESState();
18183 this._desState = state;
18184
18185 this.deriveKeys(state, options.key);
18186}
18187inherits(DES, Cipher);
18188module.exports = DES;
18189
18190DES.create = function create(options) {
18191 return new DES(options);
18192};
18193
18194var shiftTable = [
18195 1, 1, 2, 2, 2, 2, 2, 2,
18196 1, 2, 2, 2, 2, 2, 2, 1
18197];
18198
18199DES.prototype.deriveKeys = function deriveKeys(state, key) {
18200 state.keys = new Array(16 * 2);
18201
18202 assert.equal(key.length, this.blockSize, 'Invalid key length');
18203
18204 var kL = utils.readUInt32BE(key, 0);
18205 var kR = utils.readUInt32BE(key, 4);
18206
18207 utils.pc1(kL, kR, state.tmp, 0);
18208 kL = state.tmp[0];
18209 kR = state.tmp[1];
18210 for (var i = 0; i < state.keys.length; i += 2) {
18211 var shift = shiftTable[i >>> 1];
18212 kL = utils.r28shl(kL, shift);
18213 kR = utils.r28shl(kR, shift);
18214 utils.pc2(kL, kR, state.keys, i);
18215 }
18216};
18217
18218DES.prototype._update = function _update(inp, inOff, out, outOff) {
18219 var state = this._desState;
18220
18221 var l = utils.readUInt32BE(inp, inOff);
18222 var r = utils.readUInt32BE(inp, inOff + 4);
18223
18224 // Initial Permutation
18225 utils.ip(l, r, state.tmp, 0);
18226 l = state.tmp[0];
18227 r = state.tmp[1];
18228
18229 if (this.type === 'encrypt')
18230 this._encrypt(state, l, r, state.tmp, 0);
18231 else
18232 this._decrypt(state, l, r, state.tmp, 0);
18233
18234 l = state.tmp[0];
18235 r = state.tmp[1];
18236
18237 utils.writeUInt32BE(out, l, outOff);
18238 utils.writeUInt32BE(out, r, outOff + 4);
18239};
18240
18241DES.prototype._pad = function _pad(buffer, off) {
18242 var value = buffer.length - off;
18243 for (var i = off; i < buffer.length; i++)
18244 buffer[i] = value;
18245
18246 return true;
18247};
18248
18249DES.prototype._unpad = function _unpad(buffer) {
18250 var pad = buffer[buffer.length - 1];
18251 for (var i = buffer.length - pad; i < buffer.length; i++)
18252 assert.equal(buffer[i], pad);
18253
18254 return buffer.slice(0, buffer.length - pad);
18255};
18256
18257DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) {
18258 var l = lStart;
18259 var r = rStart;
18260
18261 // Apply f() x16 times
18262 for (var i = 0; i < state.keys.length; i += 2) {
18263 var keyL = state.keys[i];
18264 var keyR = state.keys[i + 1];
18265
18266 // f(r, k)
18267 utils.expand(r, state.tmp, 0);
18268
18269 keyL ^= state.tmp[0];
18270 keyR ^= state.tmp[1];
18271 var s = utils.substitute(keyL, keyR);
18272 var f = utils.permute(s);
18273
18274 var t = r;
18275 r = (l ^ f) >>> 0;
18276 l = t;
18277 }
18278
18279 // Reverse Initial Permutation
18280 utils.rip(r, l, out, off);
18281};
18282
18283DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) {
18284 var l = rStart;
18285 var r = lStart;
18286
18287 // Apply f() x16 times
18288 for (var i = state.keys.length - 2; i >= 0; i -= 2) {
18289 var keyL = state.keys[i];
18290 var keyR = state.keys[i + 1];
18291
18292 // f(r, k)
18293 utils.expand(l, state.tmp, 0);
18294
18295 keyL ^= state.tmp[0];
18296 keyR ^= state.tmp[1];
18297 var s = utils.substitute(keyL, keyR);
18298 var f = utils.permute(s);
18299
18300 var t = l;
18301 l = (r ^ f) >>> 0;
18302 r = t;
18303 }
18304
18305 // Reverse Initial Permutation
18306 utils.rip(l, r, out, off);
18307};
18308
18309},{"../des":117,"inherits":163,"minimalistic-assert":176}],121:[function(require,module,exports){
18310'use strict';
18311
18312var assert = require('minimalistic-assert');
18313var inherits = require('inherits');
18314
18315var des = require('../des');
18316var Cipher = des.Cipher;
18317var DES = des.DES;
18318
18319function EDEState(type, key) {
18320 assert.equal(key.length, 24, 'Invalid key length');
18321
18322 var k1 = key.slice(0, 8);
18323 var k2 = key.slice(8, 16);
18324 var k3 = key.slice(16, 24);
18325
18326 if (type === 'encrypt') {
18327 this.ciphers = [
18328 DES.create({ type: 'encrypt', key: k1 }),
18329 DES.create({ type: 'decrypt', key: k2 }),
18330 DES.create({ type: 'encrypt', key: k3 })
18331 ];
18332 } else {
18333 this.ciphers = [
18334 DES.create({ type: 'decrypt', key: k3 }),
18335 DES.create({ type: 'encrypt', key: k2 }),
18336 DES.create({ type: 'decrypt', key: k1 })
18337 ];
18338 }
18339}
18340
18341function EDE(options) {
18342 Cipher.call(this, options);
18343
18344 var state = new EDEState(this.type, this.options.key);
18345 this._edeState = state;
18346}
18347inherits(EDE, Cipher);
18348
18349module.exports = EDE;
18350
18351EDE.create = function create(options) {
18352 return new EDE(options);
18353};
18354
18355EDE.prototype._update = function _update(inp, inOff, out, outOff) {
18356 var state = this._edeState;
18357
18358 state.ciphers[0]._update(inp, inOff, out, outOff);
18359 state.ciphers[1]._update(out, outOff, out, outOff);
18360 state.ciphers[2]._update(out, outOff, out, outOff);
18361};
18362
18363EDE.prototype._pad = DES.prototype._pad;
18364EDE.prototype._unpad = DES.prototype._unpad;
18365
18366},{"../des":117,"inherits":163,"minimalistic-assert":176}],122:[function(require,module,exports){
18367'use strict';
18368
18369exports.readUInt32BE = function readUInt32BE(bytes, off) {
18370 var res = (bytes[0 + off] << 24) |
18371 (bytes[1 + off] << 16) |
18372 (bytes[2 + off] << 8) |
18373 bytes[3 + off];
18374 return res >>> 0;
18375};
18376
18377exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) {
18378 bytes[0 + off] = value >>> 24;
18379 bytes[1 + off] = (value >>> 16) & 0xff;
18380 bytes[2 + off] = (value >>> 8) & 0xff;
18381 bytes[3 + off] = value & 0xff;
18382};
18383
18384exports.ip = function ip(inL, inR, out, off) {
18385 var outL = 0;
18386 var outR = 0;
18387
18388 for (var i = 6; i >= 0; i -= 2) {
18389 for (var j = 0; j <= 24; j += 8) {
18390 outL <<= 1;
18391 outL |= (inR >>> (j + i)) & 1;
18392 }
18393 for (var j = 0; j <= 24; j += 8) {
18394 outL <<= 1;
18395 outL |= (inL >>> (j + i)) & 1;
18396 }
18397 }
18398
18399 for (var i = 6; i >= 0; i -= 2) {
18400 for (var j = 1; j <= 25; j += 8) {
18401 outR <<= 1;
18402 outR |= (inR >>> (j + i)) & 1;
18403 }
18404 for (var j = 1; j <= 25; j += 8) {
18405 outR <<= 1;
18406 outR |= (inL >>> (j + i)) & 1;
18407 }
18408 }
18409
18410 out[off + 0] = outL >>> 0;
18411 out[off + 1] = outR >>> 0;
18412};
18413
18414exports.rip = function rip(inL, inR, out, off) {
18415 var outL = 0;
18416 var outR = 0;
18417
18418 for (var i = 0; i < 4; i++) {
18419 for (var j = 24; j >= 0; j -= 8) {
18420 outL <<= 1;
18421 outL |= (inR >>> (j + i)) & 1;
18422 outL <<= 1;
18423 outL |= (inL >>> (j + i)) & 1;
18424 }
18425 }
18426 for (var i = 4; i < 8; i++) {
18427 for (var j = 24; j >= 0; j -= 8) {
18428 outR <<= 1;
18429 outR |= (inR >>> (j + i)) & 1;
18430 outR <<= 1;
18431 outR |= (inL >>> (j + i)) & 1;
18432 }
18433 }
18434
18435 out[off + 0] = outL >>> 0;
18436 out[off + 1] = outR >>> 0;
18437};
18438
18439exports.pc1 = function pc1(inL, inR, out, off) {
18440 var outL = 0;
18441 var outR = 0;
18442
18443 // 7, 15, 23, 31, 39, 47, 55, 63
18444 // 6, 14, 22, 30, 39, 47, 55, 63
18445 // 5, 13, 21, 29, 39, 47, 55, 63
18446 // 4, 12, 20, 28
18447 for (var i = 7; i >= 5; i--) {
18448 for (var j = 0; j <= 24; j += 8) {
18449 outL <<= 1;
18450 outL |= (inR >> (j + i)) & 1;
18451 }
18452 for (var j = 0; j <= 24; j += 8) {
18453 outL <<= 1;
18454 outL |= (inL >> (j + i)) & 1;
18455 }
18456 }
18457 for (var j = 0; j <= 24; j += 8) {
18458 outL <<= 1;
18459 outL |= (inR >> (j + i)) & 1;
18460 }
18461
18462 // 1, 9, 17, 25, 33, 41, 49, 57
18463 // 2, 10, 18, 26, 34, 42, 50, 58
18464 // 3, 11, 19, 27, 35, 43, 51, 59
18465 // 36, 44, 52, 60
18466 for (var i = 1; i <= 3; i++) {
18467 for (var j = 0; j <= 24; j += 8) {
18468 outR <<= 1;
18469 outR |= (inR >> (j + i)) & 1;
18470 }
18471 for (var j = 0; j <= 24; j += 8) {
18472 outR <<= 1;
18473 outR |= (inL >> (j + i)) & 1;
18474 }
18475 }
18476 for (var j = 0; j <= 24; j += 8) {
18477 outR <<= 1;
18478 outR |= (inL >> (j + i)) & 1;
18479 }
18480
18481 out[off + 0] = outL >>> 0;
18482 out[off + 1] = outR >>> 0;
18483};
18484
18485exports.r28shl = function r28shl(num, shift) {
18486 return ((num << shift) & 0xfffffff) | (num >>> (28 - shift));
18487};
18488
18489var pc2table = [
18490 // inL => outL
18491 14, 11, 17, 4, 27, 23, 25, 0,
18492 13, 22, 7, 18, 5, 9, 16, 24,
18493 2, 20, 12, 21, 1, 8, 15, 26,
18494
18495 // inR => outR
18496 15, 4, 25, 19, 9, 1, 26, 16,
18497 5, 11, 23, 8, 12, 7, 17, 0,
18498 22, 3, 10, 14, 6, 20, 27, 24
18499];
18500
18501exports.pc2 = function pc2(inL, inR, out, off) {
18502 var outL = 0;
18503 var outR = 0;
18504
18505 var len = pc2table.length >>> 1;
18506 for (var i = 0; i < len; i++) {
18507 outL <<= 1;
18508 outL |= (inL >>> pc2table[i]) & 0x1;
18509 }
18510 for (var i = len; i < pc2table.length; i++) {
18511 outR <<= 1;
18512 outR |= (inR >>> pc2table[i]) & 0x1;
18513 }
18514
18515 out[off + 0] = outL >>> 0;
18516 out[off + 1] = outR >>> 0;
18517};
18518
18519exports.expand = function expand(r, out, off) {
18520 var outL = 0;
18521 var outR = 0;
18522
18523 outL = ((r & 1) << 5) | (r >>> 27);
18524 for (var i = 23; i >= 15; i -= 4) {
18525 outL <<= 6;
18526 outL |= (r >>> i) & 0x3f;
18527 }
18528 for (var i = 11; i >= 3; i -= 4) {
18529 outR |= (r >>> i) & 0x3f;
18530 outR <<= 6;
18531 }
18532 outR |= ((r & 0x1f) << 1) | (r >>> 31);
18533
18534 out[off + 0] = outL >>> 0;
18535 out[off + 1] = outR >>> 0;
18536};
18537
18538var sTable = [
18539 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1,
18540 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8,
18541 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7,
18542 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13,
18543
18544 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14,
18545 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5,
18546 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2,
18547 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9,
18548
18549 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10,
18550 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1,
18551 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7,
18552 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12,
18553
18554 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3,
18555 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9,
18556 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8,
18557 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14,
18558
18559 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1,
18560 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6,
18561 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13,
18562 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3,
18563
18564 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5,
18565 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8,
18566 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10,
18567 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13,
18568
18569 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10,
18570 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6,
18571 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7,
18572 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12,
18573
18574 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4,
18575 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2,
18576 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13,
18577 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11
18578];
18579
18580exports.substitute = function substitute(inL, inR) {
18581 var out = 0;
18582 for (var i = 0; i < 4; i++) {
18583 var b = (inL >>> (18 - i * 6)) & 0x3f;
18584 var sb = sTable[i * 0x40 + b];
18585
18586 out <<= 4;
18587 out |= sb;
18588 }
18589 for (var i = 0; i < 4; i++) {
18590 var b = (inR >>> (18 - i * 6)) & 0x3f;
18591 var sb = sTable[4 * 0x40 + i * 0x40 + b];
18592
18593 out <<= 4;
18594 out |= sb;
18595 }
18596 return out >>> 0;
18597};
18598
18599var permuteTable = [
18600 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22,
18601 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7
18602];
18603
18604exports.permute = function permute(num) {
18605 var out = 0;
18606 for (var i = 0; i < permuteTable.length; i++) {
18607 out <<= 1;
18608 out |= (num >>> permuteTable[i]) & 0x1;
18609 }
18610 return out >>> 0;
18611};
18612
18613exports.padSplit = function padSplit(num, size, group) {
18614 var str = num.toString(2);
18615 while (str.length < size)
18616 str = '0' + str;
18617
18618 var out = [];
18619 for (var i = 0; i < size; i += group)
18620 out.push(str.slice(i, i + group));
18621 return out.join(' ');
18622};
18623
18624},{}],123:[function(require,module,exports){
18625(function (Buffer){
18626var generatePrime = require('./lib/generatePrime')
18627var primes = require('./lib/primes.json')
18628
18629var DH = require('./lib/dh')
18630
18631function getDiffieHellman (mod) {
18632 var prime = new Buffer(primes[mod].prime, 'hex')
18633 var gen = new Buffer(primes[mod].gen, 'hex')
18634
18635 return new DH(prime, gen)
18636}
18637
18638var ENCODINGS = {
18639 'binary': true, 'hex': true, 'base64': true
18640}
18641
18642function createDiffieHellman (prime, enc, generator, genc) {
18643 if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) {
18644 return createDiffieHellman(prime, 'binary', enc, generator)
18645 }
18646
18647 enc = enc || 'binary'
18648 genc = genc || 'binary'
18649 generator = generator || new Buffer([2])
18650
18651 if (!Buffer.isBuffer(generator)) {
18652 generator = new Buffer(generator, genc)
18653 }
18654
18655 if (typeof prime === 'number') {
18656 return new DH(generatePrime(prime, generator), generator, true)
18657 }
18658
18659 if (!Buffer.isBuffer(prime)) {
18660 prime = new Buffer(prime, enc)
18661 }
18662
18663 return new DH(prime, generator, true)
18664}
18665
18666exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman
18667exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman
18668
18669}).call(this,require("buffer").Buffer)
18670},{"./lib/dh":124,"./lib/generatePrime":125,"./lib/primes.json":126,"buffer":107}],124:[function(require,module,exports){
18671(function (Buffer){
18672var BN = require('bn.js');
18673var MillerRabin = require('miller-rabin');
18674var millerRabin = new MillerRabin();
18675var TWENTYFOUR = new BN(24);
18676var ELEVEN = new BN(11);
18677var TEN = new BN(10);
18678var THREE = new BN(3);
18679var SEVEN = new BN(7);
18680var primes = require('./generatePrime');
18681var randomBytes = require('randombytes');
18682module.exports = DH;
18683
18684function setPublicKey(pub, enc) {
18685 enc = enc || 'utf8';
18686 if (!Buffer.isBuffer(pub)) {
18687 pub = new Buffer(pub, enc);
18688 }
18689 this._pub = new BN(pub);
18690 return this;
18691}
18692
18693function setPrivateKey(priv, enc) {
18694 enc = enc || 'utf8';
18695 if (!Buffer.isBuffer(priv)) {
18696 priv = new Buffer(priv, enc);
18697 }
18698 this._priv = new BN(priv);
18699 return this;
18700}
18701
18702var primeCache = {};
18703function checkPrime(prime, generator) {
18704 var gen = generator.toString('hex');
18705 var hex = [gen, prime.toString(16)].join('_');
18706 if (hex in primeCache) {
18707 return primeCache[hex];
18708 }
18709 var error = 0;
18710
18711 if (prime.isEven() ||
18712 !primes.simpleSieve ||
18713 !primes.fermatTest(prime) ||
18714 !millerRabin.test(prime)) {
18715 //not a prime so +1
18716 error += 1;
18717
18718 if (gen === '02' || gen === '05') {
18719 // we'd be able to check the generator
18720 // it would fail so +8
18721 error += 8;
18722 } else {
18723 //we wouldn't be able to test the generator
18724 // so +4
18725 error += 4;
18726 }
18727 primeCache[hex] = error;
18728 return error;
18729 }
18730 if (!millerRabin.test(prime.shrn(1))) {
18731 //not a safe prime
18732 error += 2;
18733 }
18734 var rem;
18735 switch (gen) {
18736 case '02':
18737 if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) {
18738 // unsuidable generator
18739 error += 8;
18740 }
18741 break;
18742 case '05':
18743 rem = prime.mod(TEN);
18744 if (rem.cmp(THREE) && rem.cmp(SEVEN)) {
18745 // prime mod 10 needs to equal 3 or 7
18746 error += 8;
18747 }
18748 break;
18749 default:
18750 error += 4;
18751 }
18752 primeCache[hex] = error;
18753 return error;
18754}
18755
18756function DH(prime, generator, malleable) {
18757 this.setGenerator(generator);
18758 this.__prime = new BN(prime);
18759 this._prime = BN.mont(this.__prime);
18760 this._primeLen = prime.length;
18761 this._pub = undefined;
18762 this._priv = undefined;
18763 this._primeCode = undefined;
18764 if (malleable) {
18765 this.setPublicKey = setPublicKey;
18766 this.setPrivateKey = setPrivateKey;
18767 } else {
18768 this._primeCode = 8;
18769 }
18770}
18771Object.defineProperty(DH.prototype, 'verifyError', {
18772 enumerable: true,
18773 get: function () {
18774 if (typeof this._primeCode !== 'number') {
18775 this._primeCode = checkPrime(this.__prime, this.__gen);
18776 }
18777 return this._primeCode;
18778 }
18779});
18780DH.prototype.generateKeys = function () {
18781 if (!this._priv) {
18782 this._priv = new BN(randomBytes(this._primeLen));
18783 }
18784 this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed();
18785 return this.getPublicKey();
18786};
18787
18788DH.prototype.computeSecret = function (other) {
18789 other = new BN(other);
18790 other = other.toRed(this._prime);
18791 var secret = other.redPow(this._priv).fromRed();
18792 var out = new Buffer(secret.toArray());
18793 var prime = this.getPrime();
18794 if (out.length < prime.length) {
18795 var front = new Buffer(prime.length - out.length);
18796 front.fill(0);
18797 out = Buffer.concat([front, out]);
18798 }
18799 return out;
18800};
18801
18802DH.prototype.getPublicKey = function getPublicKey(enc) {
18803 return formatReturnValue(this._pub, enc);
18804};
18805
18806DH.prototype.getPrivateKey = function getPrivateKey(enc) {
18807 return formatReturnValue(this._priv, enc);
18808};
18809
18810DH.prototype.getPrime = function (enc) {
18811 return formatReturnValue(this.__prime, enc);
18812};
18813
18814DH.prototype.getGenerator = function (enc) {
18815 return formatReturnValue(this._gen, enc);
18816};
18817
18818DH.prototype.setGenerator = function (gen, enc) {
18819 enc = enc || 'utf8';
18820 if (!Buffer.isBuffer(gen)) {
18821 gen = new Buffer(gen, enc);
18822 }
18823 this.__gen = gen;
18824 this._gen = new BN(gen);
18825 return this;
18826};
18827
18828function formatReturnValue(bn, enc) {
18829 var buf = new Buffer(bn.toArray());
18830 if (!enc) {
18831 return buf;
18832 } else {
18833 return buf.toString(enc);
18834 }
18835}
18836
18837}).call(this,require("buffer").Buffer)
18838},{"./generatePrime":125,"bn.js":75,"buffer":107,"miller-rabin":175,"randombytes":231}],125:[function(require,module,exports){
18839var randomBytes = require('randombytes');
18840module.exports = findPrime;
18841findPrime.simpleSieve = simpleSieve;
18842findPrime.fermatTest = fermatTest;
18843var BN = require('bn.js');
18844var TWENTYFOUR = new BN(24);
18845var MillerRabin = require('miller-rabin');
18846var millerRabin = new MillerRabin();
18847var ONE = new BN(1);
18848var TWO = new BN(2);
18849var FIVE = new BN(5);
18850var SIXTEEN = new BN(16);
18851var EIGHT = new BN(8);
18852var TEN = new BN(10);
18853var THREE = new BN(3);
18854var SEVEN = new BN(7);
18855var ELEVEN = new BN(11);
18856var FOUR = new BN(4);
18857var TWELVE = new BN(12);
18858var primes = null;
18859
18860function _getPrimes() {
18861 if (primes !== null)
18862 return primes;
18863
18864 var limit = 0x100000;
18865 var res = [];
18866 res[0] = 2;
18867 for (var i = 1, k = 3; k < limit; k += 2) {
18868 var sqrt = Math.ceil(Math.sqrt(k));
18869 for (var j = 0; j < i && res[j] <= sqrt; j++)
18870 if (k % res[j] === 0)
18871 break;
18872
18873 if (i !== j && res[j] <= sqrt)
18874 continue;
18875
18876 res[i++] = k;
18877 }
18878 primes = res;
18879 return res;
18880}
18881
18882function simpleSieve(p) {
18883 var primes = _getPrimes();
18884
18885 for (var i = 0; i < primes.length; i++)
18886 if (p.modn(primes[i]) === 0) {
18887 if (p.cmpn(primes[i]) === 0) {
18888 return true;
18889 } else {
18890 return false;
18891 }
18892 }
18893
18894 return true;
18895}
18896
18897function fermatTest(p) {
18898 var red = BN.mont(p);
18899 return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0;
18900}
18901
18902function findPrime(bits, gen) {
18903 if (bits < 16) {
18904 // this is what openssl does
18905 if (gen === 2 || gen === 5) {
18906 return new BN([0x8c, 0x7b]);
18907 } else {
18908 return new BN([0x8c, 0x27]);
18909 }
18910 }
18911 gen = new BN(gen);
18912
18913 var num, n2;
18914
18915 while (true) {
18916 num = new BN(randomBytes(Math.ceil(bits / 8)));
18917 while (num.bitLength() > bits) {
18918 num.ishrn(1);
18919 }
18920 if (num.isEven()) {
18921 num.iadd(ONE);
18922 }
18923 if (!num.testn(1)) {
18924 num.iadd(TWO);
18925 }
18926 if (!gen.cmp(TWO)) {
18927 while (num.mod(TWENTYFOUR).cmp(ELEVEN)) {
18928 num.iadd(FOUR);
18929 }
18930 } else if (!gen.cmp(FIVE)) {
18931 while (num.mod(TEN).cmp(THREE)) {
18932 num.iadd(FOUR);
18933 }
18934 }
18935 n2 = num.shrn(1);
18936 if (simpleSieve(n2) && simpleSieve(num) &&
18937 fermatTest(n2) && fermatTest(num) &&
18938 millerRabin.test(n2) && millerRabin.test(num)) {
18939 return num;
18940 }
18941 }
18942
18943}
18944
18945},{"bn.js":75,"miller-rabin":175,"randombytes":231}],126:[function(require,module,exports){
18946module.exports={
18947 "modp1": {
18948 "gen": "02",
18949 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
18950 },
18951 "modp2": {
18952 "gen": "02",
18953 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
18954 },
18955 "modp5": {
18956 "gen": "02",
18957 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
18958 },
18959 "modp14": {
18960 "gen": "02",
18961 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
18962 },
18963 "modp15": {
18964 "gen": "02",
18965 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
18966 },
18967 "modp16": {
18968 "gen": "02",
18969 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
18970 },
18971 "modp17": {
18972 "gen": "02",
18973 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
18974 },
18975 "modp18": {
18976 "gen": "02",
18977 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
18978 }
18979}
18980},{}],127:[function(require,module,exports){
18981'use strict';
18982
18983var elliptic = exports;
18984
18985elliptic.version = require('../package.json').version;
18986elliptic.utils = require('./elliptic/utils');
18987elliptic.rand = require('brorand');
18988elliptic.curve = require('./elliptic/curve');
18989elliptic.curves = require('./elliptic/curves');
18990
18991// Protocols
18992elliptic.ec = require('./elliptic/ec');
18993elliptic.eddsa = require('./elliptic/eddsa');
18994
18995},{"../package.json":142,"./elliptic/curve":130,"./elliptic/curves":133,"./elliptic/ec":134,"./elliptic/eddsa":137,"./elliptic/utils":141,"brorand":76}],128:[function(require,module,exports){
18996'use strict';
18997
18998var BN = require('bn.js');
18999var elliptic = require('../../elliptic');
19000var utils = elliptic.utils;
19001var getNAF = utils.getNAF;
19002var getJSF = utils.getJSF;
19003var assert = utils.assert;
19004
19005function BaseCurve(type, conf) {
19006 this.type = type;
19007 this.p = new BN(conf.p, 16);
19008
19009 // Use Montgomery, when there is no fast reduction for the prime
19010 this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p);
19011
19012 // Useful for many curves
19013 this.zero = new BN(0).toRed(this.red);
19014 this.one = new BN(1).toRed(this.red);
19015 this.two = new BN(2).toRed(this.red);
19016
19017 // Curve configuration, optional
19018 this.n = conf.n && new BN(conf.n, 16);
19019 this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed);
19020
19021 // Temporary arrays
19022 this._wnafT1 = new Array(4);
19023 this._wnafT2 = new Array(4);
19024 this._wnafT3 = new Array(4);
19025 this._wnafT4 = new Array(4);
19026
19027 // Generalized Greg Maxwell's trick
19028 var adjustCount = this.n && this.p.div(this.n);
19029 if (!adjustCount || adjustCount.cmpn(100) > 0) {
19030 this.redN = null;
19031 } else {
19032 this._maxwellTrick = true;
19033 this.redN = this.n.toRed(this.red);
19034 }
19035}
19036module.exports = BaseCurve;
19037
19038BaseCurve.prototype.point = function point() {
19039 throw new Error('Not implemented');
19040};
19041
19042BaseCurve.prototype.validate = function validate() {
19043 throw new Error('Not implemented');
19044};
19045
19046BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) {
19047 assert(p.precomputed);
19048 var doubles = p._getDoubles();
19049
19050 var naf = getNAF(k, 1);
19051 var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1);
19052 I /= 3;
19053
19054 // Translate into more windowed form
19055 var repr = [];
19056 for (var j = 0; j < naf.length; j += doubles.step) {
19057 var nafW = 0;
19058 for (var k = j + doubles.step - 1; k >= j; k--)
19059 nafW = (nafW << 1) + naf[k];
19060 repr.push(nafW);
19061 }
19062
19063 var a = this.jpoint(null, null, null);
19064 var b = this.jpoint(null, null, null);
19065 for (var i = I; i > 0; i--) {
19066 for (var j = 0; j < repr.length; j++) {
19067 var nafW = repr[j];
19068 if (nafW === i)
19069 b = b.mixedAdd(doubles.points[j]);
19070 else if (nafW === -i)
19071 b = b.mixedAdd(doubles.points[j].neg());
19072 }
19073 a = a.add(b);
19074 }
19075 return a.toP();
19076};
19077
19078BaseCurve.prototype._wnafMul = function _wnafMul(p, k) {
19079 var w = 4;
19080
19081 // Precompute window
19082 var nafPoints = p._getNAFPoints(w);
19083 w = nafPoints.wnd;
19084 var wnd = nafPoints.points;
19085
19086 // Get NAF form
19087 var naf = getNAF(k, w);
19088
19089 // Add `this`*(N+1) for every w-NAF index
19090 var acc = this.jpoint(null, null, null);
19091 for (var i = naf.length - 1; i >= 0; i--) {
19092 // Count zeroes
19093 for (var k = 0; i >= 0 && naf[i] === 0; i--)
19094 k++;
19095 if (i >= 0)
19096 k++;
19097 acc = acc.dblp(k);
19098
19099 if (i < 0)
19100 break;
19101 var z = naf[i];
19102 assert(z !== 0);
19103 if (p.type === 'affine') {
19104 // J +- P
19105 if (z > 0)
19106 acc = acc.mixedAdd(wnd[(z - 1) >> 1]);
19107 else
19108 acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg());
19109 } else {
19110 // J +- J
19111 if (z > 0)
19112 acc = acc.add(wnd[(z - 1) >> 1]);
19113 else
19114 acc = acc.add(wnd[(-z - 1) >> 1].neg());
19115 }
19116 }
19117 return p.type === 'affine' ? acc.toP() : acc;
19118};
19119
19120BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW,
19121 points,
19122 coeffs,
19123 len,
19124 jacobianResult) {
19125 var wndWidth = this._wnafT1;
19126 var wnd = this._wnafT2;
19127 var naf = this._wnafT3;
19128
19129 // Fill all arrays
19130 var max = 0;
19131 for (var i = 0; i < len; i++) {
19132 var p = points[i];
19133 var nafPoints = p._getNAFPoints(defW);
19134 wndWidth[i] = nafPoints.wnd;
19135 wnd[i] = nafPoints.points;
19136 }
19137
19138 // Comb small window NAFs
19139 for (var i = len - 1; i >= 1; i -= 2) {
19140 var a = i - 1;
19141 var b = i;
19142 if (wndWidth[a] !== 1 || wndWidth[b] !== 1) {
19143 naf[a] = getNAF(coeffs[a], wndWidth[a]);
19144 naf[b] = getNAF(coeffs[b], wndWidth[b]);
19145 max = Math.max(naf[a].length, max);
19146 max = Math.max(naf[b].length, max);
19147 continue;
19148 }
19149
19150 var comb = [
19151 points[a], /* 1 */
19152 null, /* 3 */
19153 null, /* 5 */
19154 points[b] /* 7 */
19155 ];
19156
19157 // Try to avoid Projective points, if possible
19158 if (points[a].y.cmp(points[b].y) === 0) {
19159 comb[1] = points[a].add(points[b]);
19160 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
19161 } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) {
19162 comb[1] = points[a].toJ().mixedAdd(points[b]);
19163 comb[2] = points[a].add(points[b].neg());
19164 } else {
19165 comb[1] = points[a].toJ().mixedAdd(points[b]);
19166 comb[2] = points[a].toJ().mixedAdd(points[b].neg());
19167 }
19168
19169 var index = [
19170 -3, /* -1 -1 */
19171 -1, /* -1 0 */
19172 -5, /* -1 1 */
19173 -7, /* 0 -1 */
19174 0, /* 0 0 */
19175 7, /* 0 1 */
19176 5, /* 1 -1 */
19177 1, /* 1 0 */
19178 3 /* 1 1 */
19179 ];
19180
19181 var jsf = getJSF(coeffs[a], coeffs[b]);
19182 max = Math.max(jsf[0].length, max);
19183 naf[a] = new Array(max);
19184 naf[b] = new Array(max);
19185 for (var j = 0; j < max; j++) {
19186 var ja = jsf[0][j] | 0;
19187 var jb = jsf[1][j] | 0;
19188
19189 naf[a][j] = index[(ja + 1) * 3 + (jb + 1)];
19190 naf[b][j] = 0;
19191 wnd[a] = comb;
19192 }
19193 }
19194
19195 var acc = this.jpoint(null, null, null);
19196 var tmp = this._wnafT4;
19197 for (var i = max; i >= 0; i--) {
19198 var k = 0;
19199
19200 while (i >= 0) {
19201 var zero = true;
19202 for (var j = 0; j < len; j++) {
19203 tmp[j] = naf[j][i] | 0;
19204 if (tmp[j] !== 0)
19205 zero = false;
19206 }
19207 if (!zero)
19208 break;
19209 k++;
19210 i--;
19211 }
19212 if (i >= 0)
19213 k++;
19214 acc = acc.dblp(k);
19215 if (i < 0)
19216 break;
19217
19218 for (var j = 0; j < len; j++) {
19219 var z = tmp[j];
19220 var p;
19221 if (z === 0)
19222 continue;
19223 else if (z > 0)
19224 p = wnd[j][(z - 1) >> 1];
19225 else if (z < 0)
19226 p = wnd[j][(-z - 1) >> 1].neg();
19227
19228 if (p.type === 'affine')
19229 acc = acc.mixedAdd(p);
19230 else
19231 acc = acc.add(p);
19232 }
19233 }
19234 // Zeroify references
19235 for (var i = 0; i < len; i++)
19236 wnd[i] = null;
19237
19238 if (jacobianResult)
19239 return acc;
19240 else
19241 return acc.toP();
19242};
19243
19244function BasePoint(curve, type) {
19245 this.curve = curve;
19246 this.type = type;
19247 this.precomputed = null;
19248}
19249BaseCurve.BasePoint = BasePoint;
19250
19251BasePoint.prototype.eq = function eq(/*other*/) {
19252 throw new Error('Not implemented');
19253};
19254
19255BasePoint.prototype.validate = function validate() {
19256 return this.curve.validate(this);
19257};
19258
19259BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
19260 bytes = utils.toArray(bytes, enc);
19261
19262 var len = this.p.byteLength();
19263
19264 // uncompressed, hybrid-odd, hybrid-even
19265 if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) &&
19266 bytes.length - 1 === 2 * len) {
19267 if (bytes[0] === 0x06)
19268 assert(bytes[bytes.length - 1] % 2 === 0);
19269 else if (bytes[0] === 0x07)
19270 assert(bytes[bytes.length - 1] % 2 === 1);
19271
19272 var res = this.point(bytes.slice(1, 1 + len),
19273 bytes.slice(1 + len, 1 + 2 * len));
19274
19275 return res;
19276 } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) &&
19277 bytes.length - 1 === len) {
19278 return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03);
19279 }
19280 throw new Error('Unknown point format');
19281};
19282
19283BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) {
19284 return this.encode(enc, true);
19285};
19286
19287BasePoint.prototype._encode = function _encode(compact) {
19288 var len = this.curve.p.byteLength();
19289 var x = this.getX().toArray('be', len);
19290
19291 if (compact)
19292 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x);
19293
19294 return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ;
19295};
19296
19297BasePoint.prototype.encode = function encode(enc, compact) {
19298 return utils.encode(this._encode(compact), enc);
19299};
19300
19301BasePoint.prototype.precompute = function precompute(power) {
19302 if (this.precomputed)
19303 return this;
19304
19305 var precomputed = {
19306 doubles: null,
19307 naf: null,
19308 beta: null
19309 };
19310 precomputed.naf = this._getNAFPoints(8);
19311 precomputed.doubles = this._getDoubles(4, power);
19312 precomputed.beta = this._getBeta();
19313 this.precomputed = precomputed;
19314
19315 return this;
19316};
19317
19318BasePoint.prototype._hasDoubles = function _hasDoubles(k) {
19319 if (!this.precomputed)
19320 return false;
19321
19322 var doubles = this.precomputed.doubles;
19323 if (!doubles)
19324 return false;
19325
19326 return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step);
19327};
19328
19329BasePoint.prototype._getDoubles = function _getDoubles(step, power) {
19330 if (this.precomputed && this.precomputed.doubles)
19331 return this.precomputed.doubles;
19332
19333 var doubles = [ this ];
19334 var acc = this;
19335 for (var i = 0; i < power; i += step) {
19336 for (var j = 0; j < step; j++)
19337 acc = acc.dbl();
19338 doubles.push(acc);
19339 }
19340 return {
19341 step: step,
19342 points: doubles
19343 };
19344};
19345
19346BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) {
19347 if (this.precomputed && this.precomputed.naf)
19348 return this.precomputed.naf;
19349
19350 var res = [ this ];
19351 var max = (1 << wnd) - 1;
19352 var dbl = max === 1 ? null : this.dbl();
19353 for (var i = 1; i < max; i++)
19354 res[i] = res[i - 1].add(dbl);
19355 return {
19356 wnd: wnd,
19357 points: res
19358 };
19359};
19360
19361BasePoint.prototype._getBeta = function _getBeta() {
19362 return null;
19363};
19364
19365BasePoint.prototype.dblp = function dblp(k) {
19366 var r = this;
19367 for (var i = 0; i < k; i++)
19368 r = r.dbl();
19369 return r;
19370};
19371
19372},{"../../elliptic":127,"bn.js":75}],129:[function(require,module,exports){
19373'use strict';
19374
19375var curve = require('../curve');
19376var elliptic = require('../../elliptic');
19377var BN = require('bn.js');
19378var inherits = require('inherits');
19379var Base = curve.base;
19380
19381var assert = elliptic.utils.assert;
19382
19383function EdwardsCurve(conf) {
19384 // NOTE: Important as we are creating point in Base.call()
19385 this.twisted = (conf.a | 0) !== 1;
19386 this.mOneA = this.twisted && (conf.a | 0) === -1;
19387 this.extended = this.mOneA;
19388
19389 Base.call(this, 'edwards', conf);
19390
19391 this.a = new BN(conf.a, 16).umod(this.red.m);
19392 this.a = this.a.toRed(this.red);
19393 this.c = new BN(conf.c, 16).toRed(this.red);
19394 this.c2 = this.c.redSqr();
19395 this.d = new BN(conf.d, 16).toRed(this.red);
19396 this.dd = this.d.redAdd(this.d);
19397
19398 assert(!this.twisted || this.c.fromRed().cmpn(1) === 0);
19399 this.oneC = (conf.c | 0) === 1;
19400}
19401inherits(EdwardsCurve, Base);
19402module.exports = EdwardsCurve;
19403
19404EdwardsCurve.prototype._mulA = function _mulA(num) {
19405 if (this.mOneA)
19406 return num.redNeg();
19407 else
19408 return this.a.redMul(num);
19409};
19410
19411EdwardsCurve.prototype._mulC = function _mulC(num) {
19412 if (this.oneC)
19413 return num;
19414 else
19415 return this.c.redMul(num);
19416};
19417
19418// Just for compatibility with Short curve
19419EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) {
19420 return this.point(x, y, z, t);
19421};
19422
19423EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) {
19424 x = new BN(x, 16);
19425 if (!x.red)
19426 x = x.toRed(this.red);
19427
19428 var x2 = x.redSqr();
19429 var rhs = this.c2.redSub(this.a.redMul(x2));
19430 var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2));
19431
19432 var y2 = rhs.redMul(lhs.redInvm());
19433 var y = y2.redSqrt();
19434 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
19435 throw new Error('invalid point');
19436
19437 var isOdd = y.fromRed().isOdd();
19438 if (odd && !isOdd || !odd && isOdd)
19439 y = y.redNeg();
19440
19441 return this.point(x, y);
19442};
19443
19444EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) {
19445 y = new BN(y, 16);
19446 if (!y.red)
19447 y = y.toRed(this.red);
19448
19449 // x^2 = (y^2 - 1) / (d y^2 + 1)
19450 var y2 = y.redSqr();
19451 var lhs = y2.redSub(this.one);
19452 var rhs = y2.redMul(this.d).redAdd(this.one);
19453 var x2 = lhs.redMul(rhs.redInvm());
19454
19455 if (x2.cmp(this.zero) === 0) {
19456 if (odd)
19457 throw new Error('invalid point');
19458 else
19459 return this.point(this.zero, y);
19460 }
19461
19462 var x = x2.redSqrt();
19463 if (x.redSqr().redSub(x2).cmp(this.zero) !== 0)
19464 throw new Error('invalid point');
19465
19466 if (x.isOdd() !== odd)
19467 x = x.redNeg();
19468
19469 return this.point(x, y);
19470};
19471
19472EdwardsCurve.prototype.validate = function validate(point) {
19473 if (point.isInfinity())
19474 return true;
19475
19476 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
19477 point.normalize();
19478
19479 var x2 = point.x.redSqr();
19480 var y2 = point.y.redSqr();
19481 var lhs = x2.redMul(this.a).redAdd(y2);
19482 var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2)));
19483
19484 return lhs.cmp(rhs) === 0;
19485};
19486
19487function Point(curve, x, y, z, t) {
19488 Base.BasePoint.call(this, curve, 'projective');
19489 if (x === null && y === null && z === null) {
19490 this.x = this.curve.zero;
19491 this.y = this.curve.one;
19492 this.z = this.curve.one;
19493 this.t = this.curve.zero;
19494 this.zOne = true;
19495 } else {
19496 this.x = new BN(x, 16);
19497 this.y = new BN(y, 16);
19498 this.z = z ? new BN(z, 16) : this.curve.one;
19499 this.t = t && new BN(t, 16);
19500 if (!this.x.red)
19501 this.x = this.x.toRed(this.curve.red);
19502 if (!this.y.red)
19503 this.y = this.y.toRed(this.curve.red);
19504 if (!this.z.red)
19505 this.z = this.z.toRed(this.curve.red);
19506 if (this.t && !this.t.red)
19507 this.t = this.t.toRed(this.curve.red);
19508 this.zOne = this.z === this.curve.one;
19509
19510 // Use extended coordinates
19511 if (this.curve.extended && !this.t) {
19512 this.t = this.x.redMul(this.y);
19513 if (!this.zOne)
19514 this.t = this.t.redMul(this.z.redInvm());
19515 }
19516 }
19517}
19518inherits(Point, Base.BasePoint);
19519
19520EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
19521 return Point.fromJSON(this, obj);
19522};
19523
19524EdwardsCurve.prototype.point = function point(x, y, z, t) {
19525 return new Point(this, x, y, z, t);
19526};
19527
19528Point.fromJSON = function fromJSON(curve, obj) {
19529 return new Point(curve, obj[0], obj[1], obj[2]);
19530};
19531
19532Point.prototype.inspect = function inspect() {
19533 if (this.isInfinity())
19534 return '<EC Point Infinity>';
19535 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
19536 ' y: ' + this.y.fromRed().toString(16, 2) +
19537 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
19538};
19539
19540Point.prototype.isInfinity = function isInfinity() {
19541 // XXX This code assumes that zero is always zero in red
19542 return this.x.cmpn(0) === 0 &&
19543 this.y.cmp(this.z) === 0;
19544};
19545
19546Point.prototype._extDbl = function _extDbl() {
19547 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
19548 // #doubling-dbl-2008-hwcd
19549 // 4M + 4S
19550
19551 // A = X1^2
19552 var a = this.x.redSqr();
19553 // B = Y1^2
19554 var b = this.y.redSqr();
19555 // C = 2 * Z1^2
19556 var c = this.z.redSqr();
19557 c = c.redIAdd(c);
19558 // D = a * A
19559 var d = this.curve._mulA(a);
19560 // E = (X1 + Y1)^2 - A - B
19561 var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b);
19562 // G = D + B
19563 var g = d.redAdd(b);
19564 // F = G - C
19565 var f = g.redSub(c);
19566 // H = D - B
19567 var h = d.redSub(b);
19568 // X3 = E * F
19569 var nx = e.redMul(f);
19570 // Y3 = G * H
19571 var ny = g.redMul(h);
19572 // T3 = E * H
19573 var nt = e.redMul(h);
19574 // Z3 = F * G
19575 var nz = f.redMul(g);
19576 return this.curve.point(nx, ny, nz, nt);
19577};
19578
19579Point.prototype._projDbl = function _projDbl() {
19580 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
19581 // #doubling-dbl-2008-bbjlp
19582 // #doubling-dbl-2007-bl
19583 // and others
19584 // Generally 3M + 4S or 2M + 4S
19585
19586 // B = (X1 + Y1)^2
19587 var b = this.x.redAdd(this.y).redSqr();
19588 // C = X1^2
19589 var c = this.x.redSqr();
19590 // D = Y1^2
19591 var d = this.y.redSqr();
19592
19593 var nx;
19594 var ny;
19595 var nz;
19596 if (this.curve.twisted) {
19597 // E = a * C
19598 var e = this.curve._mulA(c);
19599 // F = E + D
19600 var f = e.redAdd(d);
19601 if (this.zOne) {
19602 // X3 = (B - C - D) * (F - 2)
19603 nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two));
19604 // Y3 = F * (E - D)
19605 ny = f.redMul(e.redSub(d));
19606 // Z3 = F^2 - 2 * F
19607 nz = f.redSqr().redSub(f).redSub(f);
19608 } else {
19609 // H = Z1^2
19610 var h = this.z.redSqr();
19611 // J = F - 2 * H
19612 var j = f.redSub(h).redISub(h);
19613 // X3 = (B-C-D)*J
19614 nx = b.redSub(c).redISub(d).redMul(j);
19615 // Y3 = F * (E - D)
19616 ny = f.redMul(e.redSub(d));
19617 // Z3 = F * J
19618 nz = f.redMul(j);
19619 }
19620 } else {
19621 // E = C + D
19622 var e = c.redAdd(d);
19623 // H = (c * Z1)^2
19624 var h = this.curve._mulC(this.c.redMul(this.z)).redSqr();
19625 // J = E - 2 * H
19626 var j = e.redSub(h).redSub(h);
19627 // X3 = c * (B - E) * J
19628 nx = this.curve._mulC(b.redISub(e)).redMul(j);
19629 // Y3 = c * E * (C - D)
19630 ny = this.curve._mulC(e).redMul(c.redISub(d));
19631 // Z3 = E * J
19632 nz = e.redMul(j);
19633 }
19634 return this.curve.point(nx, ny, nz);
19635};
19636
19637Point.prototype.dbl = function dbl() {
19638 if (this.isInfinity())
19639 return this;
19640
19641 // Double in extended coordinates
19642 if (this.curve.extended)
19643 return this._extDbl();
19644 else
19645 return this._projDbl();
19646};
19647
19648Point.prototype._extAdd = function _extAdd(p) {
19649 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
19650 // #addition-add-2008-hwcd-3
19651 // 8M
19652
19653 // A = (Y1 - X1) * (Y2 - X2)
19654 var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x));
19655 // B = (Y1 + X1) * (Y2 + X2)
19656 var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x));
19657 // C = T1 * k * T2
19658 var c = this.t.redMul(this.curve.dd).redMul(p.t);
19659 // D = Z1 * 2 * Z2
19660 var d = this.z.redMul(p.z.redAdd(p.z));
19661 // E = B - A
19662 var e = b.redSub(a);
19663 // F = D - C
19664 var f = d.redSub(c);
19665 // G = D + C
19666 var g = d.redAdd(c);
19667 // H = B + A
19668 var h = b.redAdd(a);
19669 // X3 = E * F
19670 var nx = e.redMul(f);
19671 // Y3 = G * H
19672 var ny = g.redMul(h);
19673 // T3 = E * H
19674 var nt = e.redMul(h);
19675 // Z3 = F * G
19676 var nz = f.redMul(g);
19677 return this.curve.point(nx, ny, nz, nt);
19678};
19679
19680Point.prototype._projAdd = function _projAdd(p) {
19681 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
19682 // #addition-add-2008-bbjlp
19683 // #addition-add-2007-bl
19684 // 10M + 1S
19685
19686 // A = Z1 * Z2
19687 var a = this.z.redMul(p.z);
19688 // B = A^2
19689 var b = a.redSqr();
19690 // C = X1 * X2
19691 var c = this.x.redMul(p.x);
19692 // D = Y1 * Y2
19693 var d = this.y.redMul(p.y);
19694 // E = d * C * D
19695 var e = this.curve.d.redMul(c).redMul(d);
19696 // F = B - E
19697 var f = b.redSub(e);
19698 // G = B + E
19699 var g = b.redAdd(e);
19700 // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D)
19701 var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d);
19702 var nx = a.redMul(f).redMul(tmp);
19703 var ny;
19704 var nz;
19705 if (this.curve.twisted) {
19706 // Y3 = A * G * (D - a * C)
19707 ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c)));
19708 // Z3 = F * G
19709 nz = f.redMul(g);
19710 } else {
19711 // Y3 = A * G * (D - C)
19712 ny = a.redMul(g).redMul(d.redSub(c));
19713 // Z3 = c * F * G
19714 nz = this.curve._mulC(f).redMul(g);
19715 }
19716 return this.curve.point(nx, ny, nz);
19717};
19718
19719Point.prototype.add = function add(p) {
19720 if (this.isInfinity())
19721 return p;
19722 if (p.isInfinity())
19723 return this;
19724
19725 if (this.curve.extended)
19726 return this._extAdd(p);
19727 else
19728 return this._projAdd(p);
19729};
19730
19731Point.prototype.mul = function mul(k) {
19732 if (this._hasDoubles(k))
19733 return this.curve._fixedNafMul(this, k);
19734 else
19735 return this.curve._wnafMul(this, k);
19736};
19737
19738Point.prototype.mulAdd = function mulAdd(k1, p, k2) {
19739 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false);
19740};
19741
19742Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) {
19743 return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true);
19744};
19745
19746Point.prototype.normalize = function normalize() {
19747 if (this.zOne)
19748 return this;
19749
19750 // Normalize coordinates
19751 var zi = this.z.redInvm();
19752 this.x = this.x.redMul(zi);
19753 this.y = this.y.redMul(zi);
19754 if (this.t)
19755 this.t = this.t.redMul(zi);
19756 this.z = this.curve.one;
19757 this.zOne = true;
19758 return this;
19759};
19760
19761Point.prototype.neg = function neg() {
19762 return this.curve.point(this.x.redNeg(),
19763 this.y,
19764 this.z,
19765 this.t && this.t.redNeg());
19766};
19767
19768Point.prototype.getX = function getX() {
19769 this.normalize();
19770 return this.x.fromRed();
19771};
19772
19773Point.prototype.getY = function getY() {
19774 this.normalize();
19775 return this.y.fromRed();
19776};
19777
19778Point.prototype.eq = function eq(other) {
19779 return this === other ||
19780 this.getX().cmp(other.getX()) === 0 &&
19781 this.getY().cmp(other.getY()) === 0;
19782};
19783
19784Point.prototype.eqXToP = function eqXToP(x) {
19785 var rx = x.toRed(this.curve.red).redMul(this.z);
19786 if (this.x.cmp(rx) === 0)
19787 return true;
19788
19789 var xc = x.clone();
19790 var t = this.curve.redN.redMul(this.z);
19791 for (;;) {
19792 xc.iadd(this.curve.n);
19793 if (xc.cmp(this.curve.p) >= 0)
19794 return false;
19795
19796 rx.redIAdd(t);
19797 if (this.x.cmp(rx) === 0)
19798 return true;
19799 }
19800 return false;
19801};
19802
19803// Compatibility with BaseCurve
19804Point.prototype.toP = Point.prototype.normalize;
19805Point.prototype.mixedAdd = Point.prototype.add;
19806
19807},{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],130:[function(require,module,exports){
19808'use strict';
19809
19810var curve = exports;
19811
19812curve.base = require('./base');
19813curve.short = require('./short');
19814curve.mont = require('./mont');
19815curve.edwards = require('./edwards');
19816
19817},{"./base":128,"./edwards":129,"./mont":131,"./short":132}],131:[function(require,module,exports){
19818'use strict';
19819
19820var curve = require('../curve');
19821var BN = require('bn.js');
19822var inherits = require('inherits');
19823var Base = curve.base;
19824
19825var elliptic = require('../../elliptic');
19826var utils = elliptic.utils;
19827
19828function MontCurve(conf) {
19829 Base.call(this, 'mont', conf);
19830
19831 this.a = new BN(conf.a, 16).toRed(this.red);
19832 this.b = new BN(conf.b, 16).toRed(this.red);
19833 this.i4 = new BN(4).toRed(this.red).redInvm();
19834 this.two = new BN(2).toRed(this.red);
19835 this.a24 = this.i4.redMul(this.a.redAdd(this.two));
19836}
19837inherits(MontCurve, Base);
19838module.exports = MontCurve;
19839
19840MontCurve.prototype.validate = function validate(point) {
19841 var x = point.normalize().x;
19842 var x2 = x.redSqr();
19843 var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x);
19844 var y = rhs.redSqrt();
19845
19846 return y.redSqr().cmp(rhs) === 0;
19847};
19848
19849function Point(curve, x, z) {
19850 Base.BasePoint.call(this, curve, 'projective');
19851 if (x === null && z === null) {
19852 this.x = this.curve.one;
19853 this.z = this.curve.zero;
19854 } else {
19855 this.x = new BN(x, 16);
19856 this.z = new BN(z, 16);
19857 if (!this.x.red)
19858 this.x = this.x.toRed(this.curve.red);
19859 if (!this.z.red)
19860 this.z = this.z.toRed(this.curve.red);
19861 }
19862}
19863inherits(Point, Base.BasePoint);
19864
19865MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) {
19866 return this.point(utils.toArray(bytes, enc), 1);
19867};
19868
19869MontCurve.prototype.point = function point(x, z) {
19870 return new Point(this, x, z);
19871};
19872
19873MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) {
19874 return Point.fromJSON(this, obj);
19875};
19876
19877Point.prototype.precompute = function precompute() {
19878 // No-op
19879};
19880
19881Point.prototype._encode = function _encode() {
19882 return this.getX().toArray('be', this.curve.p.byteLength());
19883};
19884
19885Point.fromJSON = function fromJSON(curve, obj) {
19886 return new Point(curve, obj[0], obj[1] || curve.one);
19887};
19888
19889Point.prototype.inspect = function inspect() {
19890 if (this.isInfinity())
19891 return '<EC Point Infinity>';
19892 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
19893 ' z: ' + this.z.fromRed().toString(16, 2) + '>';
19894};
19895
19896Point.prototype.isInfinity = function isInfinity() {
19897 // XXX This code assumes that zero is always zero in red
19898 return this.z.cmpn(0) === 0;
19899};
19900
19901Point.prototype.dbl = function dbl() {
19902 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
19903 // 2M + 2S + 4A
19904
19905 // A = X1 + Z1
19906 var a = this.x.redAdd(this.z);
19907 // AA = A^2
19908 var aa = a.redSqr();
19909 // B = X1 - Z1
19910 var b = this.x.redSub(this.z);
19911 // BB = B^2
19912 var bb = b.redSqr();
19913 // C = AA - BB
19914 var c = aa.redSub(bb);
19915 // X3 = AA * BB
19916 var nx = aa.redMul(bb);
19917 // Z3 = C * (BB + A24 * C)
19918 var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c)));
19919 return this.curve.point(nx, nz);
19920};
19921
19922Point.prototype.add = function add() {
19923 throw new Error('Not supported on Montgomery curve');
19924};
19925
19926Point.prototype.diffAdd = function diffAdd(p, diff) {
19927 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
19928 // 4M + 2S + 6A
19929
19930 // A = X2 + Z2
19931 var a = this.x.redAdd(this.z);
19932 // B = X2 - Z2
19933 var b = this.x.redSub(this.z);
19934 // C = X3 + Z3
19935 var c = p.x.redAdd(p.z);
19936 // D = X3 - Z3
19937 var d = p.x.redSub(p.z);
19938 // DA = D * A
19939 var da = d.redMul(a);
19940 // CB = C * B
19941 var cb = c.redMul(b);
19942 // X5 = Z1 * (DA + CB)^2
19943 var nx = diff.z.redMul(da.redAdd(cb).redSqr());
19944 // Z5 = X1 * (DA - CB)^2
19945 var nz = diff.x.redMul(da.redISub(cb).redSqr());
19946 return this.curve.point(nx, nz);
19947};
19948
19949Point.prototype.mul = function mul(k) {
19950 var t = k.clone();
19951 var a = this; // (N / 2) * Q + Q
19952 var b = this.curve.point(null, null); // (N / 2) * Q
19953 var c = this; // Q
19954
19955 for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1))
19956 bits.push(t.andln(1));
19957
19958 for (var i = bits.length - 1; i >= 0; i--) {
19959 if (bits[i] === 0) {
19960 // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q
19961 a = a.diffAdd(b, c);
19962 // N * Q = 2 * ((N / 2) * Q + Q))
19963 b = b.dbl();
19964 } else {
19965 // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q)
19966 b = a.diffAdd(b, c);
19967 // N * Q + Q = 2 * ((N / 2) * Q + Q)
19968 a = a.dbl();
19969 }
19970 }
19971 return b;
19972};
19973
19974Point.prototype.mulAdd = function mulAdd() {
19975 throw new Error('Not supported on Montgomery curve');
19976};
19977
19978Point.prototype.jumlAdd = function jumlAdd() {
19979 throw new Error('Not supported on Montgomery curve');
19980};
19981
19982Point.prototype.eq = function eq(other) {
19983 return this.getX().cmp(other.getX()) === 0;
19984};
19985
19986Point.prototype.normalize = function normalize() {
19987 this.x = this.x.redMul(this.z.redInvm());
19988 this.z = this.curve.one;
19989 return this;
19990};
19991
19992Point.prototype.getX = function getX() {
19993 // Normalize coordinates
19994 this.normalize();
19995
19996 return this.x.fromRed();
19997};
19998
19999},{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],132:[function(require,module,exports){
20000'use strict';
20001
20002var curve = require('../curve');
20003var elliptic = require('../../elliptic');
20004var BN = require('bn.js');
20005var inherits = require('inherits');
20006var Base = curve.base;
20007
20008var assert = elliptic.utils.assert;
20009
20010function ShortCurve(conf) {
20011 Base.call(this, 'short', conf);
20012
20013 this.a = new BN(conf.a, 16).toRed(this.red);
20014 this.b = new BN(conf.b, 16).toRed(this.red);
20015 this.tinv = this.two.redInvm();
20016
20017 this.zeroA = this.a.fromRed().cmpn(0) === 0;
20018 this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0;
20019
20020 // If the curve is endomorphic, precalculate beta and lambda
20021 this.endo = this._getEndomorphism(conf);
20022 this._endoWnafT1 = new Array(4);
20023 this._endoWnafT2 = new Array(4);
20024}
20025inherits(ShortCurve, Base);
20026module.exports = ShortCurve;
20027
20028ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) {
20029 // No efficient endomorphism
20030 if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1)
20031 return;
20032
20033 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
20034 var beta;
20035 var lambda;
20036 if (conf.beta) {
20037 beta = new BN(conf.beta, 16).toRed(this.red);
20038 } else {
20039 var betas = this._getEndoRoots(this.p);
20040 // Choose the smallest beta
20041 beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1];
20042 beta = beta.toRed(this.red);
20043 }
20044 if (conf.lambda) {
20045 lambda = new BN(conf.lambda, 16);
20046 } else {
20047 // Choose the lambda that is matching selected beta
20048 var lambdas = this._getEndoRoots(this.n);
20049 if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) {
20050 lambda = lambdas[0];
20051 } else {
20052 lambda = lambdas[1];
20053 assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0);
20054 }
20055 }
20056
20057 // Get basis vectors, used for balanced length-two representation
20058 var basis;
20059 if (conf.basis) {
20060 basis = conf.basis.map(function(vec) {
20061 return {
20062 a: new BN(vec.a, 16),
20063 b: new BN(vec.b, 16)
20064 };
20065 });
20066 } else {
20067 basis = this._getEndoBasis(lambda);
20068 }
20069
20070 return {
20071 beta: beta,
20072 lambda: lambda,
20073 basis: basis
20074 };
20075};
20076
20077ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) {
20078 // Find roots of for x^2 + x + 1 in F
20079 // Root = (-1 +- Sqrt(-3)) / 2
20080 //
20081 var red = num === this.p ? this.red : BN.mont(num);
20082 var tinv = new BN(2).toRed(red).redInvm();
20083 var ntinv = tinv.redNeg();
20084
20085 var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv);
20086
20087 var l1 = ntinv.redAdd(s).fromRed();
20088 var l2 = ntinv.redSub(s).fromRed();
20089 return [ l1, l2 ];
20090};
20091
20092ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) {
20093 // aprxSqrt >= sqrt(this.n)
20094 var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2));
20095
20096 // 3.74
20097 // Run EGCD, until r(L + 1) < aprxSqrt
20098 var u = lambda;
20099 var v = this.n.clone();
20100 var x1 = new BN(1);
20101 var y1 = new BN(0);
20102 var x2 = new BN(0);
20103 var y2 = new BN(1);
20104
20105 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
20106 var a0;
20107 var b0;
20108 // First vector
20109 var a1;
20110 var b1;
20111 // Second vector
20112 var a2;
20113 var b2;
20114
20115 var prevR;
20116 var i = 0;
20117 var r;
20118 var x;
20119 while (u.cmpn(0) !== 0) {
20120 var q = v.div(u);
20121 r = v.sub(q.mul(u));
20122 x = x2.sub(q.mul(x1));
20123 var y = y2.sub(q.mul(y1));
20124
20125 if (!a1 && r.cmp(aprxSqrt) < 0) {
20126 a0 = prevR.neg();
20127 b0 = x1;
20128 a1 = r.neg();
20129 b1 = x;
20130 } else if (a1 && ++i === 2) {
20131 break;
20132 }
20133 prevR = r;
20134
20135 v = u;
20136 u = r;
20137 x2 = x1;
20138 x1 = x;
20139 y2 = y1;
20140 y1 = y;
20141 }
20142 a2 = r.neg();
20143 b2 = x;
20144
20145 var len1 = a1.sqr().add(b1.sqr());
20146 var len2 = a2.sqr().add(b2.sqr());
20147 if (len2.cmp(len1) >= 0) {
20148 a2 = a0;
20149 b2 = b0;
20150 }
20151
20152 // Normalize signs
20153 if (a1.negative) {
20154 a1 = a1.neg();
20155 b1 = b1.neg();
20156 }
20157 if (a2.negative) {
20158 a2 = a2.neg();
20159 b2 = b2.neg();
20160 }
20161
20162 return [
20163 { a: a1, b: b1 },
20164 { a: a2, b: b2 }
20165 ];
20166};
20167
20168ShortCurve.prototype._endoSplit = function _endoSplit(k) {
20169 var basis = this.endo.basis;
20170 var v1 = basis[0];
20171 var v2 = basis[1];
20172
20173 var c1 = v2.b.mul(k).divRound(this.n);
20174 var c2 = v1.b.neg().mul(k).divRound(this.n);
20175
20176 var p1 = c1.mul(v1.a);
20177 var p2 = c2.mul(v2.a);
20178 var q1 = c1.mul(v1.b);
20179 var q2 = c2.mul(v2.b);
20180
20181 // Calculate answer
20182 var k1 = k.sub(p1).sub(p2);
20183 var k2 = q1.add(q2).neg();
20184 return { k1: k1, k2: k2 };
20185};
20186
20187ShortCurve.prototype.pointFromX = function pointFromX(x, odd) {
20188 x = new BN(x, 16);
20189 if (!x.red)
20190 x = x.toRed(this.red);
20191
20192 var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b);
20193 var y = y2.redSqrt();
20194 if (y.redSqr().redSub(y2).cmp(this.zero) !== 0)
20195 throw new Error('invalid point');
20196
20197 // XXX Is there any way to tell if the number is odd without converting it
20198 // to non-red form?
20199 var isOdd = y.fromRed().isOdd();
20200 if (odd && !isOdd || !odd && isOdd)
20201 y = y.redNeg();
20202
20203 return this.point(x, y);
20204};
20205
20206ShortCurve.prototype.validate = function validate(point) {
20207 if (point.inf)
20208 return true;
20209
20210 var x = point.x;
20211 var y = point.y;
20212
20213 var ax = this.a.redMul(x);
20214 var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b);
20215 return y.redSqr().redISub(rhs).cmpn(0) === 0;
20216};
20217
20218ShortCurve.prototype._endoWnafMulAdd =
20219 function _endoWnafMulAdd(points, coeffs, jacobianResult) {
20220 var npoints = this._endoWnafT1;
20221 var ncoeffs = this._endoWnafT2;
20222 for (var i = 0; i < points.length; i++) {
20223 var split = this._endoSplit(coeffs[i]);
20224 var p = points[i];
20225 var beta = p._getBeta();
20226
20227 if (split.k1.negative) {
20228 split.k1.ineg();
20229 p = p.neg(true);
20230 }
20231 if (split.k2.negative) {
20232 split.k2.ineg();
20233 beta = beta.neg(true);
20234 }
20235
20236 npoints[i * 2] = p;
20237 npoints[i * 2 + 1] = beta;
20238 ncoeffs[i * 2] = split.k1;
20239 ncoeffs[i * 2 + 1] = split.k2;
20240 }
20241 var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult);
20242
20243 // Clean-up references to points and coefficients
20244 for (var j = 0; j < i * 2; j++) {
20245 npoints[j] = null;
20246 ncoeffs[j] = null;
20247 }
20248 return res;
20249};
20250
20251function Point(curve, x, y, isRed) {
20252 Base.BasePoint.call(this, curve, 'affine');
20253 if (x === null && y === null) {
20254 this.x = null;
20255 this.y = null;
20256 this.inf = true;
20257 } else {
20258 this.x = new BN(x, 16);
20259 this.y = new BN(y, 16);
20260 // Force redgomery representation when loading from JSON
20261 if (isRed) {
20262 this.x.forceRed(this.curve.red);
20263 this.y.forceRed(this.curve.red);
20264 }
20265 if (!this.x.red)
20266 this.x = this.x.toRed(this.curve.red);
20267 if (!this.y.red)
20268 this.y = this.y.toRed(this.curve.red);
20269 this.inf = false;
20270 }
20271}
20272inherits(Point, Base.BasePoint);
20273
20274ShortCurve.prototype.point = function point(x, y, isRed) {
20275 return new Point(this, x, y, isRed);
20276};
20277
20278ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) {
20279 return Point.fromJSON(this, obj, red);
20280};
20281
20282Point.prototype._getBeta = function _getBeta() {
20283 if (!this.curve.endo)
20284 return;
20285
20286 var pre = this.precomputed;
20287 if (pre && pre.beta)
20288 return pre.beta;
20289
20290 var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y);
20291 if (pre) {
20292 var curve = this.curve;
20293 var endoMul = function(p) {
20294 return curve.point(p.x.redMul(curve.endo.beta), p.y);
20295 };
20296 pre.beta = beta;
20297 beta.precomputed = {
20298 beta: null,
20299 naf: pre.naf && {
20300 wnd: pre.naf.wnd,
20301 points: pre.naf.points.map(endoMul)
20302 },
20303 doubles: pre.doubles && {
20304 step: pre.doubles.step,
20305 points: pre.doubles.points.map(endoMul)
20306 }
20307 };
20308 }
20309 return beta;
20310};
20311
20312Point.prototype.toJSON = function toJSON() {
20313 if (!this.precomputed)
20314 return [ this.x, this.y ];
20315
20316 return [ this.x, this.y, this.precomputed && {
20317 doubles: this.precomputed.doubles && {
20318 step: this.precomputed.doubles.step,
20319 points: this.precomputed.doubles.points.slice(1)
20320 },
20321 naf: this.precomputed.naf && {
20322 wnd: this.precomputed.naf.wnd,
20323 points: this.precomputed.naf.points.slice(1)
20324 }
20325 } ];
20326};
20327
20328Point.fromJSON = function fromJSON(curve, obj, red) {
20329 if (typeof obj === 'string')
20330 obj = JSON.parse(obj);
20331 var res = curve.point(obj[0], obj[1], red);
20332 if (!obj[2])
20333 return res;
20334
20335 function obj2point(obj) {
20336 return curve.point(obj[0], obj[1], red);
20337 }
20338
20339 var pre = obj[2];
20340 res.precomputed = {
20341 beta: null,
20342 doubles: pre.doubles && {
20343 step: pre.doubles.step,
20344 points: [ res ].concat(pre.doubles.points.map(obj2point))
20345 },
20346 naf: pre.naf && {
20347 wnd: pre.naf.wnd,
20348 points: [ res ].concat(pre.naf.points.map(obj2point))
20349 }
20350 };
20351 return res;
20352};
20353
20354Point.prototype.inspect = function inspect() {
20355 if (this.isInfinity())
20356 return '<EC Point Infinity>';
20357 return '<EC Point x: ' + this.x.fromRed().toString(16, 2) +
20358 ' y: ' + this.y.fromRed().toString(16, 2) + '>';
20359};
20360
20361Point.prototype.isInfinity = function isInfinity() {
20362 return this.inf;
20363};
20364
20365Point.prototype.add = function add(p) {
20366 // O + P = P
20367 if (this.inf)
20368 return p;
20369
20370 // P + O = P
20371 if (p.inf)
20372 return this;
20373
20374 // P + P = 2P
20375 if (this.eq(p))
20376 return this.dbl();
20377
20378 // P + (-P) = O
20379 if (this.neg().eq(p))
20380 return this.curve.point(null, null);
20381
20382 // P + Q = O
20383 if (this.x.cmp(p.x) === 0)
20384 return this.curve.point(null, null);
20385
20386 var c = this.y.redSub(p.y);
20387 if (c.cmpn(0) !== 0)
20388 c = c.redMul(this.x.redSub(p.x).redInvm());
20389 var nx = c.redSqr().redISub(this.x).redISub(p.x);
20390 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
20391 return this.curve.point(nx, ny);
20392};
20393
20394Point.prototype.dbl = function dbl() {
20395 if (this.inf)
20396 return this;
20397
20398 // 2P = O
20399 var ys1 = this.y.redAdd(this.y);
20400 if (ys1.cmpn(0) === 0)
20401 return this.curve.point(null, null);
20402
20403 var a = this.curve.a;
20404
20405 var x2 = this.x.redSqr();
20406 var dyinv = ys1.redInvm();
20407 var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv);
20408
20409 var nx = c.redSqr().redISub(this.x.redAdd(this.x));
20410 var ny = c.redMul(this.x.redSub(nx)).redISub(this.y);
20411 return this.curve.point(nx, ny);
20412};
20413
20414Point.prototype.getX = function getX() {
20415 return this.x.fromRed();
20416};
20417
20418Point.prototype.getY = function getY() {
20419 return this.y.fromRed();
20420};
20421
20422Point.prototype.mul = function mul(k) {
20423 k = new BN(k, 16);
20424
20425 if (this._hasDoubles(k))
20426 return this.curve._fixedNafMul(this, k);
20427 else if (this.curve.endo)
20428 return this.curve._endoWnafMulAdd([ this ], [ k ]);
20429 else
20430 return this.curve._wnafMul(this, k);
20431};
20432
20433Point.prototype.mulAdd = function mulAdd(k1, p2, k2) {
20434 var points = [ this, p2 ];
20435 var coeffs = [ k1, k2 ];
20436 if (this.curve.endo)
20437 return this.curve._endoWnafMulAdd(points, coeffs);
20438 else
20439 return this.curve._wnafMulAdd(1, points, coeffs, 2);
20440};
20441
20442Point.prototype.jmulAdd = function jmulAdd(k1, p2, k2) {
20443 var points = [ this, p2 ];
20444 var coeffs = [ k1, k2 ];
20445 if (this.curve.endo)
20446 return this.curve._endoWnafMulAdd(points, coeffs, true);
20447 else
20448 return this.curve._wnafMulAdd(1, points, coeffs, 2, true);
20449};
20450
20451Point.prototype.eq = function eq(p) {
20452 return this === p ||
20453 this.inf === p.inf &&
20454 (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0);
20455};
20456
20457Point.prototype.neg = function neg(_precompute) {
20458 if (this.inf)
20459 return this;
20460
20461 var res = this.curve.point(this.x, this.y.redNeg());
20462 if (_precompute && this.precomputed) {
20463 var pre = this.precomputed;
20464 var negate = function(p) {
20465 return p.neg();
20466 };
20467 res.precomputed = {
20468 naf: pre.naf && {
20469 wnd: pre.naf.wnd,
20470 points: pre.naf.points.map(negate)
20471 },
20472 doubles: pre.doubles && {
20473 step: pre.doubles.step,
20474 points: pre.doubles.points.map(negate)
20475 }
20476 };
20477 }
20478 return res;
20479};
20480
20481Point.prototype.toJ = function toJ() {
20482 if (this.inf)
20483 return this.curve.jpoint(null, null, null);
20484
20485 var res = this.curve.jpoint(this.x, this.y, this.curve.one);
20486 return res;
20487};
20488
20489function JPoint(curve, x, y, z) {
20490 Base.BasePoint.call(this, curve, 'jacobian');
20491 if (x === null && y === null && z === null) {
20492 this.x = this.curve.one;
20493 this.y = this.curve.one;
20494 this.z = new BN(0);
20495 } else {
20496 this.x = new BN(x, 16);
20497 this.y = new BN(y, 16);
20498 this.z = new BN(z, 16);
20499 }
20500 if (!this.x.red)
20501 this.x = this.x.toRed(this.curve.red);
20502 if (!this.y.red)
20503 this.y = this.y.toRed(this.curve.red);
20504 if (!this.z.red)
20505 this.z = this.z.toRed(this.curve.red);
20506
20507 this.zOne = this.z === this.curve.one;
20508}
20509inherits(JPoint, Base.BasePoint);
20510
20511ShortCurve.prototype.jpoint = function jpoint(x, y, z) {
20512 return new JPoint(this, x, y, z);
20513};
20514
20515JPoint.prototype.toP = function toP() {
20516 if (this.isInfinity())
20517 return this.curve.point(null, null);
20518
20519 var zinv = this.z.redInvm();
20520 var zinv2 = zinv.redSqr();
20521 var ax = this.x.redMul(zinv2);
20522 var ay = this.y.redMul(zinv2).redMul(zinv);
20523
20524 return this.curve.point(ax, ay);
20525};
20526
20527JPoint.prototype.neg = function neg() {
20528 return this.curve.jpoint(this.x, this.y.redNeg(), this.z);
20529};
20530
20531JPoint.prototype.add = function add(p) {
20532 // O + P = P
20533 if (this.isInfinity())
20534 return p;
20535
20536 // P + O = P
20537 if (p.isInfinity())
20538 return this;
20539
20540 // 12M + 4S + 7A
20541 var pz2 = p.z.redSqr();
20542 var z2 = this.z.redSqr();
20543 var u1 = this.x.redMul(pz2);
20544 var u2 = p.x.redMul(z2);
20545 var s1 = this.y.redMul(pz2.redMul(p.z));
20546 var s2 = p.y.redMul(z2.redMul(this.z));
20547
20548 var h = u1.redSub(u2);
20549 var r = s1.redSub(s2);
20550 if (h.cmpn(0) === 0) {
20551 if (r.cmpn(0) !== 0)
20552 return this.curve.jpoint(null, null, null);
20553 else
20554 return this.dbl();
20555 }
20556
20557 var h2 = h.redSqr();
20558 var h3 = h2.redMul(h);
20559 var v = u1.redMul(h2);
20560
20561 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
20562 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
20563 var nz = this.z.redMul(p.z).redMul(h);
20564
20565 return this.curve.jpoint(nx, ny, nz);
20566};
20567
20568JPoint.prototype.mixedAdd = function mixedAdd(p) {
20569 // O + P = P
20570 if (this.isInfinity())
20571 return p.toJ();
20572
20573 // P + O = P
20574 if (p.isInfinity())
20575 return this;
20576
20577 // 8M + 3S + 7A
20578 var z2 = this.z.redSqr();
20579 var u1 = this.x;
20580 var u2 = p.x.redMul(z2);
20581 var s1 = this.y;
20582 var s2 = p.y.redMul(z2).redMul(this.z);
20583
20584 var h = u1.redSub(u2);
20585 var r = s1.redSub(s2);
20586 if (h.cmpn(0) === 0) {
20587 if (r.cmpn(0) !== 0)
20588 return this.curve.jpoint(null, null, null);
20589 else
20590 return this.dbl();
20591 }
20592
20593 var h2 = h.redSqr();
20594 var h3 = h2.redMul(h);
20595 var v = u1.redMul(h2);
20596
20597 var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v);
20598 var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3));
20599 var nz = this.z.redMul(h);
20600
20601 return this.curve.jpoint(nx, ny, nz);
20602};
20603
20604JPoint.prototype.dblp = function dblp(pow) {
20605 if (pow === 0)
20606 return this;
20607 if (this.isInfinity())
20608 return this;
20609 if (!pow)
20610 return this.dbl();
20611
20612 if (this.curve.zeroA || this.curve.threeA) {
20613 var r = this;
20614 for (var i = 0; i < pow; i++)
20615 r = r.dbl();
20616 return r;
20617 }
20618
20619 // 1M + 2S + 1A + N * (4S + 5M + 8A)
20620 // N = 1 => 6M + 6S + 9A
20621 var a = this.curve.a;
20622 var tinv = this.curve.tinv;
20623
20624 var jx = this.x;
20625 var jy = this.y;
20626 var jz = this.z;
20627 var jz4 = jz.redSqr().redSqr();
20628
20629 // Reuse results
20630 var jyd = jy.redAdd(jy);
20631 for (var i = 0; i < pow; i++) {
20632 var jx2 = jx.redSqr();
20633 var jyd2 = jyd.redSqr();
20634 var jyd4 = jyd2.redSqr();
20635 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
20636
20637 var t1 = jx.redMul(jyd2);
20638 var nx = c.redSqr().redISub(t1.redAdd(t1));
20639 var t2 = t1.redISub(nx);
20640 var dny = c.redMul(t2);
20641 dny = dny.redIAdd(dny).redISub(jyd4);
20642 var nz = jyd.redMul(jz);
20643 if (i + 1 < pow)
20644 jz4 = jz4.redMul(jyd4);
20645
20646 jx = nx;
20647 jz = nz;
20648 jyd = dny;
20649 }
20650
20651 return this.curve.jpoint(jx, jyd.redMul(tinv), jz);
20652};
20653
20654JPoint.prototype.dbl = function dbl() {
20655 if (this.isInfinity())
20656 return this;
20657
20658 if (this.curve.zeroA)
20659 return this._zeroDbl();
20660 else if (this.curve.threeA)
20661 return this._threeDbl();
20662 else
20663 return this._dbl();
20664};
20665
20666JPoint.prototype._zeroDbl = function _zeroDbl() {
20667 var nx;
20668 var ny;
20669 var nz;
20670 // Z = 1
20671 if (this.zOne) {
20672 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
20673 // #doubling-mdbl-2007-bl
20674 // 1M + 5S + 14A
20675
20676 // XX = X1^2
20677 var xx = this.x.redSqr();
20678 // YY = Y1^2
20679 var yy = this.y.redSqr();
20680 // YYYY = YY^2
20681 var yyyy = yy.redSqr();
20682 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
20683 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
20684 s = s.redIAdd(s);
20685 // M = 3 * XX + a; a = 0
20686 var m = xx.redAdd(xx).redIAdd(xx);
20687 // T = M ^ 2 - 2*S
20688 var t = m.redSqr().redISub(s).redISub(s);
20689
20690 // 8 * YYYY
20691 var yyyy8 = yyyy.redIAdd(yyyy);
20692 yyyy8 = yyyy8.redIAdd(yyyy8);
20693 yyyy8 = yyyy8.redIAdd(yyyy8);
20694
20695 // X3 = T
20696 nx = t;
20697 // Y3 = M * (S - T) - 8 * YYYY
20698 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
20699 // Z3 = 2*Y1
20700 nz = this.y.redAdd(this.y);
20701 } else {
20702 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
20703 // #doubling-dbl-2009-l
20704 // 2M + 5S + 13A
20705
20706 // A = X1^2
20707 var a = this.x.redSqr();
20708 // B = Y1^2
20709 var b = this.y.redSqr();
20710 // C = B^2
20711 var c = b.redSqr();
20712 // D = 2 * ((X1 + B)^2 - A - C)
20713 var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c);
20714 d = d.redIAdd(d);
20715 // E = 3 * A
20716 var e = a.redAdd(a).redIAdd(a);
20717 // F = E^2
20718 var f = e.redSqr();
20719
20720 // 8 * C
20721 var c8 = c.redIAdd(c);
20722 c8 = c8.redIAdd(c8);
20723 c8 = c8.redIAdd(c8);
20724
20725 // X3 = F - 2 * D
20726 nx = f.redISub(d).redISub(d);
20727 // Y3 = E * (D - X3) - 8 * C
20728 ny = e.redMul(d.redISub(nx)).redISub(c8);
20729 // Z3 = 2 * Y1 * Z1
20730 nz = this.y.redMul(this.z);
20731 nz = nz.redIAdd(nz);
20732 }
20733
20734 return this.curve.jpoint(nx, ny, nz);
20735};
20736
20737JPoint.prototype._threeDbl = function _threeDbl() {
20738 var nx;
20739 var ny;
20740 var nz;
20741 // Z = 1
20742 if (this.zOne) {
20743 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
20744 // #doubling-mdbl-2007-bl
20745 // 1M + 5S + 15A
20746
20747 // XX = X1^2
20748 var xx = this.x.redSqr();
20749 // YY = Y1^2
20750 var yy = this.y.redSqr();
20751 // YYYY = YY^2
20752 var yyyy = yy.redSqr();
20753 // S = 2 * ((X1 + YY)^2 - XX - YYYY)
20754 var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
20755 s = s.redIAdd(s);
20756 // M = 3 * XX + a
20757 var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a);
20758 // T = M^2 - 2 * S
20759 var t = m.redSqr().redISub(s).redISub(s);
20760 // X3 = T
20761 nx = t;
20762 // Y3 = M * (S - T) - 8 * YYYY
20763 var yyyy8 = yyyy.redIAdd(yyyy);
20764 yyyy8 = yyyy8.redIAdd(yyyy8);
20765 yyyy8 = yyyy8.redIAdd(yyyy8);
20766 ny = m.redMul(s.redISub(t)).redISub(yyyy8);
20767 // Z3 = 2 * Y1
20768 nz = this.y.redAdd(this.y);
20769 } else {
20770 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
20771 // 3M + 5S
20772
20773 // delta = Z1^2
20774 var delta = this.z.redSqr();
20775 // gamma = Y1^2
20776 var gamma = this.y.redSqr();
20777 // beta = X1 * gamma
20778 var beta = this.x.redMul(gamma);
20779 // alpha = 3 * (X1 - delta) * (X1 + delta)
20780 var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta));
20781 alpha = alpha.redAdd(alpha).redIAdd(alpha);
20782 // X3 = alpha^2 - 8 * beta
20783 var beta4 = beta.redIAdd(beta);
20784 beta4 = beta4.redIAdd(beta4);
20785 var beta8 = beta4.redAdd(beta4);
20786 nx = alpha.redSqr().redISub(beta8);
20787 // Z3 = (Y1 + Z1)^2 - gamma - delta
20788 nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta);
20789 // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2
20790 var ggamma8 = gamma.redSqr();
20791 ggamma8 = ggamma8.redIAdd(ggamma8);
20792 ggamma8 = ggamma8.redIAdd(ggamma8);
20793 ggamma8 = ggamma8.redIAdd(ggamma8);
20794 ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8);
20795 }
20796
20797 return this.curve.jpoint(nx, ny, nz);
20798};
20799
20800JPoint.prototype._dbl = function _dbl() {
20801 var a = this.curve.a;
20802
20803 // 4M + 6S + 10A
20804 var jx = this.x;
20805 var jy = this.y;
20806 var jz = this.z;
20807 var jz4 = jz.redSqr().redSqr();
20808
20809 var jx2 = jx.redSqr();
20810 var jy2 = jy.redSqr();
20811
20812 var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4));
20813
20814 var jxd4 = jx.redAdd(jx);
20815 jxd4 = jxd4.redIAdd(jxd4);
20816 var t1 = jxd4.redMul(jy2);
20817 var nx = c.redSqr().redISub(t1.redAdd(t1));
20818 var t2 = t1.redISub(nx);
20819
20820 var jyd8 = jy2.redSqr();
20821 jyd8 = jyd8.redIAdd(jyd8);
20822 jyd8 = jyd8.redIAdd(jyd8);
20823 jyd8 = jyd8.redIAdd(jyd8);
20824 var ny = c.redMul(t2).redISub(jyd8);
20825 var nz = jy.redAdd(jy).redMul(jz);
20826
20827 return this.curve.jpoint(nx, ny, nz);
20828};
20829
20830JPoint.prototype.trpl = function trpl() {
20831 if (!this.curve.zeroA)
20832 return this.dbl().add(this);
20833
20834 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
20835 // 5M + 10S + ...
20836
20837 // XX = X1^2
20838 var xx = this.x.redSqr();
20839 // YY = Y1^2
20840 var yy = this.y.redSqr();
20841 // ZZ = Z1^2
20842 var zz = this.z.redSqr();
20843 // YYYY = YY^2
20844 var yyyy = yy.redSqr();
20845 // M = 3 * XX + a * ZZ2; a = 0
20846 var m = xx.redAdd(xx).redIAdd(xx);
20847 // MM = M^2
20848 var mm = m.redSqr();
20849 // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM
20850 var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy);
20851 e = e.redIAdd(e);
20852 e = e.redAdd(e).redIAdd(e);
20853 e = e.redISub(mm);
20854 // EE = E^2
20855 var ee = e.redSqr();
20856 // T = 16*YYYY
20857 var t = yyyy.redIAdd(yyyy);
20858 t = t.redIAdd(t);
20859 t = t.redIAdd(t);
20860 t = t.redIAdd(t);
20861 // U = (M + E)^2 - MM - EE - T
20862 var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t);
20863 // X3 = 4 * (X1 * EE - 4 * YY * U)
20864 var yyu4 = yy.redMul(u);
20865 yyu4 = yyu4.redIAdd(yyu4);
20866 yyu4 = yyu4.redIAdd(yyu4);
20867 var nx = this.x.redMul(ee).redISub(yyu4);
20868 nx = nx.redIAdd(nx);
20869 nx = nx.redIAdd(nx);
20870 // Y3 = 8 * Y1 * (U * (T - U) - E * EE)
20871 var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee)));
20872 ny = ny.redIAdd(ny);
20873 ny = ny.redIAdd(ny);
20874 ny = ny.redIAdd(ny);
20875 // Z3 = (Z1 + E)^2 - ZZ - EE
20876 var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee);
20877
20878 return this.curve.jpoint(nx, ny, nz);
20879};
20880
20881JPoint.prototype.mul = function mul(k, kbase) {
20882 k = new BN(k, kbase);
20883
20884 return this.curve._wnafMul(this, k);
20885};
20886
20887JPoint.prototype.eq = function eq(p) {
20888 if (p.type === 'affine')
20889 return this.eq(p.toJ());
20890
20891 if (this === p)
20892 return true;
20893
20894 // x1 * z2^2 == x2 * z1^2
20895 var z2 = this.z.redSqr();
20896 var pz2 = p.z.redSqr();
20897 if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0)
20898 return false;
20899
20900 // y1 * z2^3 == y2 * z1^3
20901 var z3 = z2.redMul(this.z);
20902 var pz3 = pz2.redMul(p.z);
20903 return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0;
20904};
20905
20906JPoint.prototype.eqXToP = function eqXToP(x) {
20907 var zs = this.z.redSqr();
20908 var rx = x.toRed(this.curve.red).redMul(zs);
20909 if (this.x.cmp(rx) === 0)
20910 return true;
20911
20912 var xc = x.clone();
20913 var t = this.curve.redN.redMul(zs);
20914 for (;;) {
20915 xc.iadd(this.curve.n);
20916 if (xc.cmp(this.curve.p) >= 0)
20917 return false;
20918
20919 rx.redIAdd(t);
20920 if (this.x.cmp(rx) === 0)
20921 return true;
20922 }
20923 return false;
20924};
20925
20926JPoint.prototype.inspect = function inspect() {
20927 if (this.isInfinity())
20928 return '<EC JPoint Infinity>';
20929 return '<EC JPoint x: ' + this.x.toString(16, 2) +
20930 ' y: ' + this.y.toString(16, 2) +
20931 ' z: ' + this.z.toString(16, 2) + '>';
20932};
20933
20934JPoint.prototype.isInfinity = function isInfinity() {
20935 // XXX This code assumes that zero is always zero in red
20936 return this.z.cmpn(0) === 0;
20937};
20938
20939},{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],133:[function(require,module,exports){
20940'use strict';
20941
20942var curves = exports;
20943
20944var hash = require('hash.js');
20945var elliptic = require('../elliptic');
20946
20947var assert = elliptic.utils.assert;
20948
20949function PresetCurve(options) {
20950 if (options.type === 'short')
20951 this.curve = new elliptic.curve.short(options);
20952 else if (options.type === 'edwards')
20953 this.curve = new elliptic.curve.edwards(options);
20954 else
20955 this.curve = new elliptic.curve.mont(options);
20956 this.g = this.curve.g;
20957 this.n = this.curve.n;
20958 this.hash = options.hash;
20959
20960 assert(this.g.validate(), 'Invalid curve');
20961 assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O');
20962}
20963curves.PresetCurve = PresetCurve;
20964
20965function defineCurve(name, options) {
20966 Object.defineProperty(curves, name, {
20967 configurable: true,
20968 enumerable: true,
20969 get: function() {
20970 var curve = new PresetCurve(options);
20971 Object.defineProperty(curves, name, {
20972 configurable: true,
20973 enumerable: true,
20974 value: curve
20975 });
20976 return curve;
20977 }
20978 });
20979}
20980
20981defineCurve('p192', {
20982 type: 'short',
20983 prime: 'p192',
20984 p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff',
20985 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc',
20986 b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1',
20987 n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831',
20988 hash: hash.sha256,
20989 gRed: false,
20990 g: [
20991 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
20992 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
20993 ]
20994});
20995
20996defineCurve('p224', {
20997 type: 'short',
20998 prime: 'p224',
20999 p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001',
21000 a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe',
21001 b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4',
21002 n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d',
21003 hash: hash.sha256,
21004 gRed: false,
21005 g: [
21006 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
21007 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
21008 ]
21009});
21010
21011defineCurve('p256', {
21012 type: 'short',
21013 prime: null,
21014 p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff',
21015 a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc',
21016 b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b',
21017 n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551',
21018 hash: hash.sha256,
21019 gRed: false,
21020 g: [
21021 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
21022 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
21023 ]
21024});
21025
21026defineCurve('p384', {
21027 type: 'short',
21028 prime: null,
21029 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
21030 'fffffffe ffffffff 00000000 00000000 ffffffff',
21031 a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
21032 'fffffffe ffffffff 00000000 00000000 fffffffc',
21033 b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' +
21034 '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef',
21035 n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' +
21036 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973',
21037 hash: hash.sha384,
21038 gRed: false,
21039 g: [
21040 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' +
21041 '5502f25d bf55296c 3a545e38 72760ab7',
21042 '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' +
21043 '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f'
21044 ]
21045});
21046
21047defineCurve('p521', {
21048 type: 'short',
21049 prime: null,
21050 p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
21051 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
21052 'ffffffff ffffffff ffffffff ffffffff ffffffff',
21053 a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
21054 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
21055 'ffffffff ffffffff ffffffff ffffffff fffffffc',
21056 b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' +
21057 '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' +
21058 '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00',
21059 n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' +
21060 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' +
21061 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409',
21062 hash: hash.sha512,
21063 gRed: false,
21064 g: [
21065 '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' +
21066 '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' +
21067 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66',
21068 '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' +
21069 '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' +
21070 '3fad0761 353c7086 a272c240 88be9476 9fd16650'
21071 ]
21072});
21073
21074defineCurve('curve25519', {
21075 type: 'mont',
21076 prime: 'p25519',
21077 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
21078 a: '76d06',
21079 b: '1',
21080 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
21081 hash: hash.sha256,
21082 gRed: false,
21083 g: [
21084 '9'
21085 ]
21086});
21087
21088defineCurve('ed25519', {
21089 type: 'edwards',
21090 prime: 'p25519',
21091 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
21092 a: '-1',
21093 c: '1',
21094 // -121665 * (121666^(-1)) (mod P)
21095 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
21096 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
21097 hash: hash.sha256,
21098 gRed: false,
21099 g: [
21100 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
21101
21102 // 4/5
21103 '6666666666666666666666666666666666666666666666666666666666666658'
21104 ]
21105});
21106
21107var pre;
21108try {
21109 pre = require('./precomputed/secp256k1');
21110} catch (e) {
21111 pre = undefined;
21112}
21113
21114defineCurve('secp256k1', {
21115 type: 'short',
21116 prime: 'k256',
21117 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
21118 a: '0',
21119 b: '7',
21120 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
21121 h: '1',
21122 hash: hash.sha256,
21123
21124 // Precomputed endomorphism
21125 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
21126 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
21127 basis: [
21128 {
21129 a: '3086d221a7d46bcde86c90e49284eb15',
21130 b: '-e4437ed6010e88286f547fa90abfe4c3'
21131 },
21132 {
21133 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
21134 b: '3086d221a7d46bcde86c90e49284eb15'
21135 }
21136 ],
21137
21138 gRed: false,
21139 g: [
21140 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
21141 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
21142 pre
21143 ]
21144});
21145
21146},{"../elliptic":127,"./precomputed/secp256k1":140,"hash.js":147}],134:[function(require,module,exports){
21147'use strict';
21148
21149var BN = require('bn.js');
21150var HmacDRBG = require('hmac-drbg');
21151var elliptic = require('../../elliptic');
21152var utils = elliptic.utils;
21153var assert = utils.assert;
21154
21155var KeyPair = require('./key');
21156var Signature = require('./signature');
21157
21158function EC(options) {
21159 if (!(this instanceof EC))
21160 return new EC(options);
21161
21162 // Shortcut `elliptic.ec(curve-name)`
21163 if (typeof options === 'string') {
21164 assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options);
21165
21166 options = elliptic.curves[options];
21167 }
21168
21169 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
21170 if (options instanceof elliptic.curves.PresetCurve)
21171 options = { curve: options };
21172
21173 this.curve = options.curve.curve;
21174 this.n = this.curve.n;
21175 this.nh = this.n.ushrn(1);
21176 this.g = this.curve.g;
21177
21178 // Point on curve
21179 this.g = options.curve.g;
21180 this.g.precompute(options.curve.n.bitLength() + 1);
21181
21182 // Hash for function for DRBG
21183 this.hash = options.hash || options.curve.hash;
21184}
21185module.exports = EC;
21186
21187EC.prototype.keyPair = function keyPair(options) {
21188 return new KeyPair(this, options);
21189};
21190
21191EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) {
21192 return KeyPair.fromPrivate(this, priv, enc);
21193};
21194
21195EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) {
21196 return KeyPair.fromPublic(this, pub, enc);
21197};
21198
21199EC.prototype.genKeyPair = function genKeyPair(options) {
21200 if (!options)
21201 options = {};
21202
21203 // Instantiate Hmac_DRBG
21204 var drbg = new HmacDRBG({
21205 hash: this.hash,
21206 pers: options.pers,
21207 persEnc: options.persEnc || 'utf8',
21208 entropy: options.entropy || elliptic.rand(this.hash.hmacStrength),
21209 entropyEnc: options.entropy && options.entropyEnc || 'utf8',
21210 nonce: this.n.toArray()
21211 });
21212
21213 var bytes = this.n.byteLength();
21214 var ns2 = this.n.sub(new BN(2));
21215 do {
21216 var priv = new BN(drbg.generate(bytes));
21217 if (priv.cmp(ns2) > 0)
21218 continue;
21219
21220 priv.iaddn(1);
21221 return this.keyFromPrivate(priv);
21222 } while (true);
21223};
21224
21225EC.prototype._truncateToN = function truncateToN(msg, truncOnly) {
21226 var delta = msg.byteLength() * 8 - this.n.bitLength();
21227 if (delta > 0)
21228 msg = msg.ushrn(delta);
21229 if (!truncOnly && msg.cmp(this.n) >= 0)
21230 return msg.sub(this.n);
21231 else
21232 return msg;
21233};
21234
21235EC.prototype.sign = function sign(msg, key, enc, options) {
21236 if (typeof enc === 'object') {
21237 options = enc;
21238 enc = null;
21239 }
21240 if (!options)
21241 options = {};
21242
21243 key = this.keyFromPrivate(key, enc);
21244 msg = this._truncateToN(new BN(msg, 16));
21245
21246 // Zero-extend key to provide enough entropy
21247 var bytes = this.n.byteLength();
21248 var bkey = key.getPrivate().toArray('be', bytes);
21249
21250 // Zero-extend nonce to have the same byte size as N
21251 var nonce = msg.toArray('be', bytes);
21252
21253 // Instantiate Hmac_DRBG
21254 var drbg = new HmacDRBG({
21255 hash: this.hash,
21256 entropy: bkey,
21257 nonce: nonce,
21258 pers: options.pers,
21259 persEnc: options.persEnc || 'utf8'
21260 });
21261
21262 // Number of bytes to generate
21263 var ns1 = this.n.sub(new BN(1));
21264
21265 for (var iter = 0; true; iter++) {
21266 var k = options.k ?
21267 options.k(iter) :
21268 new BN(drbg.generate(this.n.byteLength()));
21269 k = this._truncateToN(k, true);
21270 if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0)
21271 continue;
21272
21273 var kp = this.g.mul(k);
21274 if (kp.isInfinity())
21275 continue;
21276
21277 var kpX = kp.getX();
21278 var r = kpX.umod(this.n);
21279 if (r.cmpn(0) === 0)
21280 continue;
21281
21282 var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg));
21283 s = s.umod(this.n);
21284 if (s.cmpn(0) === 0)
21285 continue;
21286
21287 var recoveryParam = (kp.getY().isOdd() ? 1 : 0) |
21288 (kpX.cmp(r) !== 0 ? 2 : 0);
21289
21290 // Use complement of `s`, if it is > `n / 2`
21291 if (options.canonical && s.cmp(this.nh) > 0) {
21292 s = this.n.sub(s);
21293 recoveryParam ^= 1;
21294 }
21295
21296 return new Signature({ r: r, s: s, recoveryParam: recoveryParam });
21297 }
21298};
21299
21300EC.prototype.verify = function verify(msg, signature, key, enc) {
21301 msg = this._truncateToN(new BN(msg, 16));
21302 key = this.keyFromPublic(key, enc);
21303 signature = new Signature(signature, 'hex');
21304
21305 // Perform primitive values validation
21306 var r = signature.r;
21307 var s = signature.s;
21308 if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0)
21309 return false;
21310 if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0)
21311 return false;
21312
21313 // Validate signature
21314 var sinv = s.invm(this.n);
21315 var u1 = sinv.mul(msg).umod(this.n);
21316 var u2 = sinv.mul(r).umod(this.n);
21317
21318 if (!this.curve._maxwellTrick) {
21319 var p = this.g.mulAdd(u1, key.getPublic(), u2);
21320 if (p.isInfinity())
21321 return false;
21322
21323 return p.getX().umod(this.n).cmp(r) === 0;
21324 }
21325
21326 // NOTE: Greg Maxwell's trick, inspired by:
21327 // https://git.io/vad3K
21328
21329 var p = this.g.jmulAdd(u1, key.getPublic(), u2);
21330 if (p.isInfinity())
21331 return false;
21332
21333 // Compare `p.x` of Jacobian point with `r`,
21334 // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the
21335 // inverse of `p.z^2`
21336 return p.eqXToP(r);
21337};
21338
21339EC.prototype.recoverPubKey = function(msg, signature, j, enc) {
21340 assert((3 & j) === j, 'The recovery param is more than two bits');
21341 signature = new Signature(signature, enc);
21342
21343 var n = this.n;
21344 var e = new BN(msg);
21345 var r = signature.r;
21346 var s = signature.s;
21347
21348 // A set LSB signifies that the y-coordinate is odd
21349 var isYOdd = j & 1;
21350 var isSecondKey = j >> 1;
21351 if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey)
21352 throw new Error('Unable to find sencond key candinate');
21353
21354 // 1.1. Let x = r + jn.
21355 if (isSecondKey)
21356 r = this.curve.pointFromX(r.add(this.curve.n), isYOdd);
21357 else
21358 r = this.curve.pointFromX(r, isYOdd);
21359
21360 var rInv = signature.r.invm(n);
21361 var s1 = n.sub(e).mul(rInv).umod(n);
21362 var s2 = s.mul(rInv).umod(n);
21363
21364 // 1.6.1 Compute Q = r^-1 (sR - eG)
21365 // Q = r^-1 (sR + -eG)
21366 return this.g.mulAdd(s1, r, s2);
21367};
21368
21369EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) {
21370 signature = new Signature(signature, enc);
21371 if (signature.recoveryParam !== null)
21372 return signature.recoveryParam;
21373
21374 for (var i = 0; i < 4; i++) {
21375 var Qprime;
21376 try {
21377 Qprime = this.recoverPubKey(e, signature, i);
21378 } catch (e) {
21379 continue;
21380 }
21381
21382 if (Qprime.eq(Q))
21383 return i;
21384 }
21385 throw new Error('Unable to find valid recovery factor');
21386};
21387
21388},{"../../elliptic":127,"./key":135,"./signature":136,"bn.js":75,"hmac-drbg":159}],135:[function(require,module,exports){
21389'use strict';
21390
21391var BN = require('bn.js');
21392var elliptic = require('../../elliptic');
21393var utils = elliptic.utils;
21394var assert = utils.assert;
21395
21396function KeyPair(ec, options) {
21397 this.ec = ec;
21398 this.priv = null;
21399 this.pub = null;
21400
21401 // KeyPair(ec, { priv: ..., pub: ... })
21402 if (options.priv)
21403 this._importPrivate(options.priv, options.privEnc);
21404 if (options.pub)
21405 this._importPublic(options.pub, options.pubEnc);
21406}
21407module.exports = KeyPair;
21408
21409KeyPair.fromPublic = function fromPublic(ec, pub, enc) {
21410 if (pub instanceof KeyPair)
21411 return pub;
21412
21413 return new KeyPair(ec, {
21414 pub: pub,
21415 pubEnc: enc
21416 });
21417};
21418
21419KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) {
21420 if (priv instanceof KeyPair)
21421 return priv;
21422
21423 return new KeyPair(ec, {
21424 priv: priv,
21425 privEnc: enc
21426 });
21427};
21428
21429KeyPair.prototype.validate = function validate() {
21430 var pub = this.getPublic();
21431
21432 if (pub.isInfinity())
21433 return { result: false, reason: 'Invalid public key' };
21434 if (!pub.validate())
21435 return { result: false, reason: 'Public key is not a point' };
21436 if (!pub.mul(this.ec.curve.n).isInfinity())
21437 return { result: false, reason: 'Public key * N != O' };
21438
21439 return { result: true, reason: null };
21440};
21441
21442KeyPair.prototype.getPublic = function getPublic(compact, enc) {
21443 // compact is optional argument
21444 if (typeof compact === 'string') {
21445 enc = compact;
21446 compact = null;
21447 }
21448
21449 if (!this.pub)
21450 this.pub = this.ec.g.mul(this.priv);
21451
21452 if (!enc)
21453 return this.pub;
21454
21455 return this.pub.encode(enc, compact);
21456};
21457
21458KeyPair.prototype.getPrivate = function getPrivate(enc) {
21459 if (enc === 'hex')
21460 return this.priv.toString(16, 2);
21461 else
21462 return this.priv;
21463};
21464
21465KeyPair.prototype._importPrivate = function _importPrivate(key, enc) {
21466 this.priv = new BN(key, enc || 16);
21467
21468 // Ensure that the priv won't be bigger than n, otherwise we may fail
21469 // in fixed multiplication method
21470 this.priv = this.priv.umod(this.ec.curve.n);
21471};
21472
21473KeyPair.prototype._importPublic = function _importPublic(key, enc) {
21474 if (key.x || key.y) {
21475 // Montgomery points only have an `x` coordinate.
21476 // Weierstrass/Edwards points on the other hand have both `x` and
21477 // `y` coordinates.
21478 if (this.ec.curve.type === 'mont') {
21479 assert(key.x, 'Need x coordinate');
21480 } else if (this.ec.curve.type === 'short' ||
21481 this.ec.curve.type === 'edwards') {
21482 assert(key.x && key.y, 'Need both x and y coordinate');
21483 }
21484 this.pub = this.ec.curve.point(key.x, key.y);
21485 return;
21486 }
21487 this.pub = this.ec.curve.decodePoint(key, enc);
21488};
21489
21490// ECDH
21491KeyPair.prototype.derive = function derive(pub) {
21492 return pub.mul(this.priv).getX();
21493};
21494
21495// ECDSA
21496KeyPair.prototype.sign = function sign(msg, enc, options) {
21497 return this.ec.sign(msg, this, enc, options);
21498};
21499
21500KeyPair.prototype.verify = function verify(msg, signature) {
21501 return this.ec.verify(msg, signature, this);
21502};
21503
21504KeyPair.prototype.inspect = function inspect() {
21505 return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) +
21506 ' pub: ' + (this.pub && this.pub.inspect()) + ' >';
21507};
21508
21509},{"../../elliptic":127,"bn.js":75}],136:[function(require,module,exports){
21510'use strict';
21511
21512var BN = require('bn.js');
21513
21514var elliptic = require('../../elliptic');
21515var utils = elliptic.utils;
21516var assert = utils.assert;
21517
21518function Signature(options, enc) {
21519 if (options instanceof Signature)
21520 return options;
21521
21522 if (this._importDER(options, enc))
21523 return;
21524
21525 assert(options.r && options.s, 'Signature without r or s');
21526 this.r = new BN(options.r, 16);
21527 this.s = new BN(options.s, 16);
21528 if (options.recoveryParam === undefined)
21529 this.recoveryParam = null;
21530 else
21531 this.recoveryParam = options.recoveryParam;
21532}
21533module.exports = Signature;
21534
21535function Position() {
21536 this.place = 0;
21537}
21538
21539function getLength(buf, p) {
21540 var initial = buf[p.place++];
21541 if (!(initial & 0x80)) {
21542 return initial;
21543 }
21544 var octetLen = initial & 0xf;
21545 var val = 0;
21546 for (var i = 0, off = p.place; i < octetLen; i++, off++) {
21547 val <<= 8;
21548 val |= buf[off];
21549 }
21550 p.place = off;
21551 return val;
21552}
21553
21554function rmPadding(buf) {
21555 var i = 0;
21556 var len = buf.length - 1;
21557 while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) {
21558 i++;
21559 }
21560 if (i === 0) {
21561 return buf;
21562 }
21563 return buf.slice(i);
21564}
21565
21566Signature.prototype._importDER = function _importDER(data, enc) {
21567 data = utils.toArray(data, enc);
21568 var p = new Position();
21569 if (data[p.place++] !== 0x30) {
21570 return false;
21571 }
21572 var len = getLength(data, p);
21573 if ((len + p.place) !== data.length) {
21574 return false;
21575 }
21576 if (data[p.place++] !== 0x02) {
21577 return false;
21578 }
21579 var rlen = getLength(data, p);
21580 var r = data.slice(p.place, rlen + p.place);
21581 p.place += rlen;
21582 if (data[p.place++] !== 0x02) {
21583 return false;
21584 }
21585 var slen = getLength(data, p);
21586 if (data.length !== slen + p.place) {
21587 return false;
21588 }
21589 var s = data.slice(p.place, slen + p.place);
21590 if (r[0] === 0 && (r[1] & 0x80)) {
21591 r = r.slice(1);
21592 }
21593 if (s[0] === 0 && (s[1] & 0x80)) {
21594 s = s.slice(1);
21595 }
21596
21597 this.r = new BN(r);
21598 this.s = new BN(s);
21599 this.recoveryParam = null;
21600
21601 return true;
21602};
21603
21604function constructLength(arr, len) {
21605 if (len < 0x80) {
21606 arr.push(len);
21607 return;
21608 }
21609 var octets = 1 + (Math.log(len) / Math.LN2 >>> 3);
21610 arr.push(octets | 0x80);
21611 while (--octets) {
21612 arr.push((len >>> (octets << 3)) & 0xff);
21613 }
21614 arr.push(len);
21615}
21616
21617Signature.prototype.toDER = function toDER(enc) {
21618 var r = this.r.toArray();
21619 var s = this.s.toArray();
21620
21621 // Pad values
21622 if (r[0] & 0x80)
21623 r = [ 0 ].concat(r);
21624 // Pad values
21625 if (s[0] & 0x80)
21626 s = [ 0 ].concat(s);
21627
21628 r = rmPadding(r);
21629 s = rmPadding(s);
21630
21631 while (!s[0] && !(s[1] & 0x80)) {
21632 s = s.slice(1);
21633 }
21634 var arr = [ 0x02 ];
21635 constructLength(arr, r.length);
21636 arr = arr.concat(r);
21637 arr.push(0x02);
21638 constructLength(arr, s.length);
21639 var backHalf = arr.concat(s);
21640 var res = [ 0x30 ];
21641 constructLength(res, backHalf.length);
21642 res = res.concat(backHalf);
21643 return utils.encode(res, enc);
21644};
21645
21646},{"../../elliptic":127,"bn.js":75}],137:[function(require,module,exports){
21647'use strict';
21648
21649var hash = require('hash.js');
21650var elliptic = require('../../elliptic');
21651var utils = elliptic.utils;
21652var assert = utils.assert;
21653var parseBytes = utils.parseBytes;
21654var KeyPair = require('./key');
21655var Signature = require('./signature');
21656
21657function EDDSA(curve) {
21658 assert(curve === 'ed25519', 'only tested with ed25519 so far');
21659
21660 if (!(this instanceof EDDSA))
21661 return new EDDSA(curve);
21662
21663 var curve = elliptic.curves[curve].curve;
21664 this.curve = curve;
21665 this.g = curve.g;
21666 this.g.precompute(curve.n.bitLength() + 1);
21667
21668 this.pointClass = curve.point().constructor;
21669 this.encodingLength = Math.ceil(curve.n.bitLength() / 8);
21670 this.hash = hash.sha512;
21671}
21672
21673module.exports = EDDSA;
21674
21675/**
21676* @param {Array|String} message - message bytes
21677* @param {Array|String|KeyPair} secret - secret bytes or a keypair
21678* @returns {Signature} - signature
21679*/
21680EDDSA.prototype.sign = function sign(message, secret) {
21681 message = parseBytes(message);
21682 var key = this.keyFromSecret(secret);
21683 var r = this.hashInt(key.messagePrefix(), message);
21684 var R = this.g.mul(r);
21685 var Rencoded = this.encodePoint(R);
21686 var s_ = this.hashInt(Rencoded, key.pubBytes(), message)
21687 .mul(key.priv());
21688 var S = r.add(s_).umod(this.curve.n);
21689 return this.makeSignature({ R: R, S: S, Rencoded: Rencoded });
21690};
21691
21692/**
21693* @param {Array} message - message bytes
21694* @param {Array|String|Signature} sig - sig bytes
21695* @param {Array|String|Point|KeyPair} pub - public key
21696* @returns {Boolean} - true if public key matches sig of message
21697*/
21698EDDSA.prototype.verify = function verify(message, sig, pub) {
21699 message = parseBytes(message);
21700 sig = this.makeSignature(sig);
21701 var key = this.keyFromPublic(pub);
21702 var h = this.hashInt(sig.Rencoded(), key.pubBytes(), message);
21703 var SG = this.g.mul(sig.S());
21704 var RplusAh = sig.R().add(key.pub().mul(h));
21705 return RplusAh.eq(SG);
21706};
21707
21708EDDSA.prototype.hashInt = function hashInt() {
21709 var hash = this.hash();
21710 for (var i = 0; i < arguments.length; i++)
21711 hash.update(arguments[i]);
21712 return utils.intFromLE(hash.digest()).umod(this.curve.n);
21713};
21714
21715EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) {
21716 return KeyPair.fromPublic(this, pub);
21717};
21718
21719EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) {
21720 return KeyPair.fromSecret(this, secret);
21721};
21722
21723EDDSA.prototype.makeSignature = function makeSignature(sig) {
21724 if (sig instanceof Signature)
21725 return sig;
21726 return new Signature(this, sig);
21727};
21728
21729/**
21730* * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
21731*
21732* EDDSA defines methods for encoding and decoding points and integers. These are
21733* helper convenience methods, that pass along to utility functions implied
21734* parameters.
21735*
21736*/
21737EDDSA.prototype.encodePoint = function encodePoint(point) {
21738 var enc = point.getY().toArray('le', this.encodingLength);
21739 enc[this.encodingLength - 1] |= point.getX().isOdd() ? 0x80 : 0;
21740 return enc;
21741};
21742
21743EDDSA.prototype.decodePoint = function decodePoint(bytes) {
21744 bytes = utils.parseBytes(bytes);
21745
21746 var lastIx = bytes.length - 1;
21747 var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80);
21748 var xIsOdd = (bytes[lastIx] & 0x80) !== 0;
21749
21750 var y = utils.intFromLE(normed);
21751 return this.curve.pointFromY(y, xIsOdd);
21752};
21753
21754EDDSA.prototype.encodeInt = function encodeInt(num) {
21755 return num.toArray('le', this.encodingLength);
21756};
21757
21758EDDSA.prototype.decodeInt = function decodeInt(bytes) {
21759 return utils.intFromLE(bytes);
21760};
21761
21762EDDSA.prototype.isPoint = function isPoint(val) {
21763 return val instanceof this.pointClass;
21764};
21765
21766},{"../../elliptic":127,"./key":138,"./signature":139,"hash.js":147}],138:[function(require,module,exports){
21767'use strict';
21768
21769var elliptic = require('../../elliptic');
21770var utils = elliptic.utils;
21771var assert = utils.assert;
21772var parseBytes = utils.parseBytes;
21773var cachedProperty = utils.cachedProperty;
21774
21775/**
21776* @param {EDDSA} eddsa - instance
21777* @param {Object} params - public/private key parameters
21778*
21779* @param {Array<Byte>} [params.secret] - secret seed bytes
21780* @param {Point} [params.pub] - public key point (aka `A` in eddsa terms)
21781* @param {Array<Byte>} [params.pub] - public key point encoded as bytes
21782*
21783*/
21784function KeyPair(eddsa, params) {
21785 this.eddsa = eddsa;
21786 this._secret = parseBytes(params.secret);
21787 if (eddsa.isPoint(params.pub))
21788 this._pub = params.pub;
21789 else
21790 this._pubBytes = parseBytes(params.pub);
21791}
21792
21793KeyPair.fromPublic = function fromPublic(eddsa, pub) {
21794 if (pub instanceof KeyPair)
21795 return pub;
21796 return new KeyPair(eddsa, { pub: pub });
21797};
21798
21799KeyPair.fromSecret = function fromSecret(eddsa, secret) {
21800 if (secret instanceof KeyPair)
21801 return secret;
21802 return new KeyPair(eddsa, { secret: secret });
21803};
21804
21805KeyPair.prototype.secret = function secret() {
21806 return this._secret;
21807};
21808
21809cachedProperty(KeyPair, 'pubBytes', function pubBytes() {
21810 return this.eddsa.encodePoint(this.pub());
21811});
21812
21813cachedProperty(KeyPair, 'pub', function pub() {
21814 if (this._pubBytes)
21815 return this.eddsa.decodePoint(this._pubBytes);
21816 return this.eddsa.g.mul(this.priv());
21817});
21818
21819cachedProperty(KeyPair, 'privBytes', function privBytes() {
21820 var eddsa = this.eddsa;
21821 var hash = this.hash();
21822 var lastIx = eddsa.encodingLength - 1;
21823
21824 var a = hash.slice(0, eddsa.encodingLength);
21825 a[0] &= 248;
21826 a[lastIx] &= 127;
21827 a[lastIx] |= 64;
21828
21829 return a;
21830});
21831
21832cachedProperty(KeyPair, 'priv', function priv() {
21833 return this.eddsa.decodeInt(this.privBytes());
21834});
21835
21836cachedProperty(KeyPair, 'hash', function hash() {
21837 return this.eddsa.hash().update(this.secret()).digest();
21838});
21839
21840cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() {
21841 return this.hash().slice(this.eddsa.encodingLength);
21842});
21843
21844KeyPair.prototype.sign = function sign(message) {
21845 assert(this._secret, 'KeyPair can only verify');
21846 return this.eddsa.sign(message, this);
21847};
21848
21849KeyPair.prototype.verify = function verify(message, sig) {
21850 return this.eddsa.verify(message, sig, this);
21851};
21852
21853KeyPair.prototype.getSecret = function getSecret(enc) {
21854 assert(this._secret, 'KeyPair is public only');
21855 return utils.encode(this.secret(), enc);
21856};
21857
21858KeyPair.prototype.getPublic = function getPublic(enc) {
21859 return utils.encode(this.pubBytes(), enc);
21860};
21861
21862module.exports = KeyPair;
21863
21864},{"../../elliptic":127}],139:[function(require,module,exports){
21865'use strict';
21866
21867var BN = require('bn.js');
21868var elliptic = require('../../elliptic');
21869var utils = elliptic.utils;
21870var assert = utils.assert;
21871var cachedProperty = utils.cachedProperty;
21872var parseBytes = utils.parseBytes;
21873
21874/**
21875* @param {EDDSA} eddsa - eddsa instance
21876* @param {Array<Bytes>|Object} sig -
21877* @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes
21878* @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes
21879* @param {Array<Bytes>} [sig.Rencoded] - R point encoded
21880* @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded
21881*/
21882function Signature(eddsa, sig) {
21883 this.eddsa = eddsa;
21884
21885 if (typeof sig !== 'object')
21886 sig = parseBytes(sig);
21887
21888 if (Array.isArray(sig)) {
21889 sig = {
21890 R: sig.slice(0, eddsa.encodingLength),
21891 S: sig.slice(eddsa.encodingLength)
21892 };
21893 }
21894
21895 assert(sig.R && sig.S, 'Signature without R or S');
21896
21897 if (eddsa.isPoint(sig.R))
21898 this._R = sig.R;
21899 if (sig.S instanceof BN)
21900 this._S = sig.S;
21901
21902 this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded;
21903 this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded;
21904}
21905
21906cachedProperty(Signature, 'S', function S() {
21907 return this.eddsa.decodeInt(this.Sencoded());
21908});
21909
21910cachedProperty(Signature, 'R', function R() {
21911 return this.eddsa.decodePoint(this.Rencoded());
21912});
21913
21914cachedProperty(Signature, 'Rencoded', function Rencoded() {
21915 return this.eddsa.encodePoint(this.R());
21916});
21917
21918cachedProperty(Signature, 'Sencoded', function Sencoded() {
21919 return this.eddsa.encodeInt(this.S());
21920});
21921
21922Signature.prototype.toBytes = function toBytes() {
21923 return this.Rencoded().concat(this.Sencoded());
21924};
21925
21926Signature.prototype.toHex = function toHex() {
21927 return utils.encode(this.toBytes(), 'hex').toUpperCase();
21928};
21929
21930module.exports = Signature;
21931
21932},{"../../elliptic":127,"bn.js":75}],140:[function(require,module,exports){
21933module.exports = {
21934 doubles: {
21935 step: 4,
21936 points: [
21937 [
21938 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
21939 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
21940 ],
21941 [
21942 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
21943 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
21944 ],
21945 [
21946 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
21947 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
21948 ],
21949 [
21950 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
21951 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
21952 ],
21953 [
21954 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
21955 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
21956 ],
21957 [
21958 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
21959 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
21960 ],
21961 [
21962 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
21963 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
21964 ],
21965 [
21966 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
21967 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
21968 ],
21969 [
21970 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
21971 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
21972 ],
21973 [
21974 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
21975 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
21976 ],
21977 [
21978 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
21979 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
21980 ],
21981 [
21982 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
21983 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
21984 ],
21985 [
21986 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
21987 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
21988 ],
21989 [
21990 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
21991 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
21992 ],
21993 [
21994 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
21995 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
21996 ],
21997 [
21998 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
21999 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
22000 ],
22001 [
22002 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
22003 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
22004 ],
22005 [
22006 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
22007 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
22008 ],
22009 [
22010 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
22011 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
22012 ],
22013 [
22014 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
22015 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
22016 ],
22017 [
22018 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
22019 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
22020 ],
22021 [
22022 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
22023 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
22024 ],
22025 [
22026 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
22027 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
22028 ],
22029 [
22030 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
22031 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
22032 ],
22033 [
22034 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
22035 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
22036 ],
22037 [
22038 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
22039 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
22040 ],
22041 [
22042 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
22043 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
22044 ],
22045 [
22046 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
22047 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
22048 ],
22049 [
22050 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
22051 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
22052 ],
22053 [
22054 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
22055 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
22056 ],
22057 [
22058 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
22059 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
22060 ],
22061 [
22062 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
22063 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
22064 ],
22065 [
22066 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
22067 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
22068 ],
22069 [
22070 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
22071 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
22072 ],
22073 [
22074 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
22075 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
22076 ],
22077 [
22078 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
22079 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
22080 ],
22081 [
22082 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
22083 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
22084 ],
22085 [
22086 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
22087 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
22088 ],
22089 [
22090 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
22091 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
22092 ],
22093 [
22094 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
22095 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
22096 ],
22097 [
22098 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
22099 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
22100 ],
22101 [
22102 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
22103 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
22104 ],
22105 [
22106 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
22107 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
22108 ],
22109 [
22110 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
22111 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
22112 ],
22113 [
22114 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
22115 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
22116 ],
22117 [
22118 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
22119 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
22120 ],
22121 [
22122 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
22123 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
22124 ],
22125 [
22126 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
22127 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
22128 ],
22129 [
22130 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
22131 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
22132 ],
22133 [
22134 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
22135 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
22136 ],
22137 [
22138 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
22139 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
22140 ],
22141 [
22142 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
22143 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
22144 ],
22145 [
22146 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
22147 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
22148 ],
22149 [
22150 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
22151 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
22152 ],
22153 [
22154 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
22155 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
22156 ],
22157 [
22158 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
22159 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
22160 ],
22161 [
22162 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
22163 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
22164 ],
22165 [
22166 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
22167 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
22168 ],
22169 [
22170 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
22171 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
22172 ],
22173 [
22174 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
22175 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
22176 ],
22177 [
22178 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
22179 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
22180 ],
22181 [
22182 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
22183 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
22184 ],
22185 [
22186 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
22187 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
22188 ],
22189 [
22190 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
22191 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
22192 ],
22193 [
22194 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
22195 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
22196 ]
22197 ]
22198 },
22199 naf: {
22200 wnd: 7,
22201 points: [
22202 [
22203 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
22204 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
22205 ],
22206 [
22207 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
22208 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
22209 ],
22210 [
22211 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
22212 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
22213 ],
22214 [
22215 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
22216 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
22217 ],
22218 [
22219 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
22220 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
22221 ],
22222 [
22223 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
22224 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
22225 ],
22226 [
22227 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
22228 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
22229 ],
22230 [
22231 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
22232 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
22233 ],
22234 [
22235 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
22236 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
22237 ],
22238 [
22239 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
22240 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
22241 ],
22242 [
22243 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
22244 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
22245 ],
22246 [
22247 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
22248 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
22249 ],
22250 [
22251 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
22252 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
22253 ],
22254 [
22255 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
22256 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
22257 ],
22258 [
22259 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
22260 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
22261 ],
22262 [
22263 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
22264 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
22265 ],
22266 [
22267 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
22268 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
22269 ],
22270 [
22271 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
22272 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
22273 ],
22274 [
22275 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
22276 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
22277 ],
22278 [
22279 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
22280 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
22281 ],
22282 [
22283 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
22284 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
22285 ],
22286 [
22287 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
22288 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
22289 ],
22290 [
22291 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
22292 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
22293 ],
22294 [
22295 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
22296 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
22297 ],
22298 [
22299 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
22300 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
22301 ],
22302 [
22303 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
22304 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
22305 ],
22306 [
22307 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
22308 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
22309 ],
22310 [
22311 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
22312 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
22313 ],
22314 [
22315 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
22316 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
22317 ],
22318 [
22319 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
22320 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
22321 ],
22322 [
22323 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
22324 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
22325 ],
22326 [
22327 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
22328 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
22329 ],
22330 [
22331 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
22332 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
22333 ],
22334 [
22335 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
22336 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
22337 ],
22338 [
22339 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
22340 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
22341 ],
22342 [
22343 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
22344 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
22345 ],
22346 [
22347 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
22348 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
22349 ],
22350 [
22351 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
22352 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
22353 ],
22354 [
22355 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
22356 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
22357 ],
22358 [
22359 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
22360 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
22361 ],
22362 [
22363 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
22364 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
22365 ],
22366 [
22367 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
22368 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
22369 ],
22370 [
22371 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
22372 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
22373 ],
22374 [
22375 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
22376 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
22377 ],
22378 [
22379 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
22380 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
22381 ],
22382 [
22383 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
22384 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
22385 ],
22386 [
22387 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
22388 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
22389 ],
22390 [
22391 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
22392 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
22393 ],
22394 [
22395 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
22396 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
22397 ],
22398 [
22399 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
22400 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
22401 ],
22402 [
22403 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
22404 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
22405 ],
22406 [
22407 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
22408 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
22409 ],
22410 [
22411 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
22412 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
22413 ],
22414 [
22415 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
22416 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
22417 ],
22418 [
22419 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
22420 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
22421 ],
22422 [
22423 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
22424 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
22425 ],
22426 [
22427 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
22428 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
22429 ],
22430 [
22431 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
22432 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
22433 ],
22434 [
22435 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
22436 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
22437 ],
22438 [
22439 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
22440 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
22441 ],
22442 [
22443 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
22444 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
22445 ],
22446 [
22447 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
22448 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
22449 ],
22450 [
22451 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
22452 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
22453 ],
22454 [
22455 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
22456 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
22457 ],
22458 [
22459 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
22460 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
22461 ],
22462 [
22463 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
22464 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
22465 ],
22466 [
22467 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
22468 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
22469 ],
22470 [
22471 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
22472 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
22473 ],
22474 [
22475 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
22476 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
22477 ],
22478 [
22479 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
22480 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
22481 ],
22482 [
22483 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
22484 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
22485 ],
22486 [
22487 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
22488 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
22489 ],
22490 [
22491 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
22492 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
22493 ],
22494 [
22495 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
22496 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
22497 ],
22498 [
22499 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
22500 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
22501 ],
22502 [
22503 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
22504 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
22505 ],
22506 [
22507 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
22508 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
22509 ],
22510 [
22511 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
22512 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
22513 ],
22514 [
22515 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
22516 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
22517 ],
22518 [
22519 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
22520 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
22521 ],
22522 [
22523 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
22524 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
22525 ],
22526 [
22527 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
22528 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
22529 ],
22530 [
22531 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
22532 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
22533 ],
22534 [
22535 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
22536 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
22537 ],
22538 [
22539 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
22540 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
22541 ],
22542 [
22543 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
22544 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
22545 ],
22546 [
22547 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
22548 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
22549 ],
22550 [
22551 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
22552 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
22553 ],
22554 [
22555 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
22556 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
22557 ],
22558 [
22559 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
22560 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
22561 ],
22562 [
22563 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
22564 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
22565 ],
22566 [
22567 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
22568 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
22569 ],
22570 [
22571 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
22572 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
22573 ],
22574 [
22575 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
22576 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
22577 ],
22578 [
22579 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
22580 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
22581 ],
22582 [
22583 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
22584 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
22585 ],
22586 [
22587 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
22588 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
22589 ],
22590 [
22591 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
22592 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
22593 ],
22594 [
22595 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
22596 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
22597 ],
22598 [
22599 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
22600 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
22601 ],
22602 [
22603 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
22604 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
22605 ],
22606 [
22607 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
22608 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
22609 ],
22610 [
22611 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
22612 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
22613 ],
22614 [
22615 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
22616 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
22617 ],
22618 [
22619 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
22620 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
22621 ],
22622 [
22623 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
22624 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
22625 ],
22626 [
22627 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
22628 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
22629 ],
22630 [
22631 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
22632 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
22633 ],
22634 [
22635 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
22636 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
22637 ],
22638 [
22639 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
22640 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
22641 ],
22642 [
22643 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
22644 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
22645 ],
22646 [
22647 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
22648 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
22649 ],
22650 [
22651 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
22652 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
22653 ],
22654 [
22655 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
22656 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
22657 ],
22658 [
22659 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
22660 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
22661 ],
22662 [
22663 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
22664 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
22665 ],
22666 [
22667 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
22668 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
22669 ],
22670 [
22671 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
22672 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
22673 ],
22674 [
22675 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
22676 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
22677 ],
22678 [
22679 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
22680 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
22681 ],
22682 [
22683 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
22684 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
22685 ],
22686 [
22687 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
22688 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
22689 ],
22690 [
22691 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
22692 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
22693 ],
22694 [
22695 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
22696 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
22697 ],
22698 [
22699 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
22700 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
22701 ],
22702 [
22703 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
22704 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
22705 ],
22706 [
22707 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
22708 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
22709 ]
22710 ]
22711 }
22712};
22713
22714},{}],141:[function(require,module,exports){
22715'use strict';
22716
22717var utils = exports;
22718var BN = require('bn.js');
22719var minAssert = require('minimalistic-assert');
22720var minUtils = require('minimalistic-crypto-utils');
22721
22722utils.assert = minAssert;
22723utils.toArray = minUtils.toArray;
22724utils.zero2 = minUtils.zero2;
22725utils.toHex = minUtils.toHex;
22726utils.encode = minUtils.encode;
22727
22728// Represent num in a w-NAF form
22729function getNAF(num, w) {
22730 var naf = [];
22731 var ws = 1 << (w + 1);
22732 var k = num.clone();
22733 while (k.cmpn(1) >= 0) {
22734 var z;
22735 if (k.isOdd()) {
22736 var mod = k.andln(ws - 1);
22737 if (mod > (ws >> 1) - 1)
22738 z = (ws >> 1) - mod;
22739 else
22740 z = mod;
22741 k.isubn(z);
22742 } else {
22743 z = 0;
22744 }
22745 naf.push(z);
22746
22747 // Optimization, shift by word if possible
22748 var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1;
22749 for (var i = 1; i < shift; i++)
22750 naf.push(0);
22751 k.iushrn(shift);
22752 }
22753
22754 return naf;
22755}
22756utils.getNAF = getNAF;
22757
22758// Represent k1, k2 in a Joint Sparse Form
22759function getJSF(k1, k2) {
22760 var jsf = [
22761 [],
22762 []
22763 ];
22764
22765 k1 = k1.clone();
22766 k2 = k2.clone();
22767 var d1 = 0;
22768 var d2 = 0;
22769 while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) {
22770
22771 // First phase
22772 var m14 = (k1.andln(3) + d1) & 3;
22773 var m24 = (k2.andln(3) + d2) & 3;
22774 if (m14 === 3)
22775 m14 = -1;
22776 if (m24 === 3)
22777 m24 = -1;
22778 var u1;
22779 if ((m14 & 1) === 0) {
22780 u1 = 0;
22781 } else {
22782 var m8 = (k1.andln(7) + d1) & 7;
22783 if ((m8 === 3 || m8 === 5) && m24 === 2)
22784 u1 = -m14;
22785 else
22786 u1 = m14;
22787 }
22788 jsf[0].push(u1);
22789
22790 var u2;
22791 if ((m24 & 1) === 0) {
22792 u2 = 0;
22793 } else {
22794 var m8 = (k2.andln(7) + d2) & 7;
22795 if ((m8 === 3 || m8 === 5) && m14 === 2)
22796 u2 = -m24;
22797 else
22798 u2 = m24;
22799 }
22800 jsf[1].push(u2);
22801
22802 // Second phase
22803 if (2 * d1 === u1 + 1)
22804 d1 = 1 - d1;
22805 if (2 * d2 === u2 + 1)
22806 d2 = 1 - d2;
22807 k1.iushrn(1);
22808 k2.iushrn(1);
22809 }
22810
22811 return jsf;
22812}
22813utils.getJSF = getJSF;
22814
22815function cachedProperty(obj, name, computer) {
22816 var key = '_' + name;
22817 obj.prototype[name] = function cachedProperty() {
22818 return this[key] !== undefined ? this[key] :
22819 this[key] = computer.call(this);
22820 };
22821}
22822utils.cachedProperty = cachedProperty;
22823
22824function parseBytes(bytes) {
22825 return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') :
22826 bytes;
22827}
22828utils.parseBytes = parseBytes;
22829
22830function intFromLE(bytes) {
22831 return new BN(bytes, 'hex', 'le');
22832}
22833utils.intFromLE = intFromLE;
22834
22835
22836},{"bn.js":75,"minimalistic-assert":176,"minimalistic-crypto-utils":177}],142:[function(require,module,exports){
22837module.exports={
22838 "_from": "elliptic@^6.0.0",
22839 "_id": "elliptic@6.4.0",
22840 "_inBundle": false,
22841 "_integrity": "sha1-ysmvh2LIWDYYcAPI3+GT5eLq5d8=",
22842 "_location": "/elliptic",
22843 "_phantomChildren": {},
22844 "_requested": {
22845 "type": "range",
22846 "registry": true,
22847 "raw": "elliptic@^6.0.0",
22848 "name": "elliptic",
22849 "escapedName": "elliptic",
22850 "rawSpec": "^6.0.0",
22851 "saveSpec": null,
22852 "fetchSpec": "^6.0.0"
22853 },
22854 "_requiredBy": [
22855 "/browserify-sign",
22856 "/create-ecdh"
22857 ],
22858 "_resolved": "http://registry.npm.taobao.org/elliptic/download/elliptic-6.4.0.tgz",
22859 "_shasum": "cac9af8762c85836187003c8dfe193e5e2eae5df",
22860 "_spec": "elliptic@^6.0.0",
22861 "_where": "/Users/qywang/workspace/go/src/github.com/nebulasio/go-nebulas/cmd/console/neb.js/node_modules/browserify-sign",
22862 "author": {
22863 "name": "Fedor Indutny",
22864 "email": "fedor@indutny.com"
22865 },
22866 "bugs": {
22867 "url": "https://github.com/indutny/elliptic/issues"
22868 },
22869 "bundleDependencies": false,
22870 "dependencies": {
22871 "bn.js": "^4.4.0",
22872 "brorand": "^1.0.1",
22873 "hash.js": "^1.0.0",
22874 "hmac-drbg": "^1.0.0",
22875 "inherits": "^2.0.1",
22876 "minimalistic-assert": "^1.0.0",
22877 "minimalistic-crypto-utils": "^1.0.0"
22878 },
22879 "deprecated": false,
22880 "description": "EC cryptography",
22881 "devDependencies": {
22882 "brfs": "^1.4.3",
22883 "coveralls": "^2.11.3",
22884 "grunt": "^0.4.5",
22885 "grunt-browserify": "^5.0.0",
22886 "grunt-cli": "^1.2.0",
22887 "grunt-contrib-connect": "^1.0.0",
22888 "grunt-contrib-copy": "^1.0.0",
22889 "grunt-contrib-uglify": "^1.0.1",
22890 "grunt-mocha-istanbul": "^3.0.1",
22891 "grunt-saucelabs": "^8.6.2",
22892 "istanbul": "^0.4.2",
22893 "jscs": "^2.9.0",
22894 "jshint": "^2.6.0",
22895 "mocha": "^2.1.0"
22896 },
22897 "files": [
22898 "lib"
22899 ],
22900 "homepage": "https://github.com/indutny/elliptic",
22901 "keywords": [
22902 "EC",
22903 "Elliptic",
22904 "curve",
22905 "Cryptography"
22906 ],
22907 "license": "MIT",
22908 "main": "lib/elliptic.js",
22909 "name": "elliptic",
22910 "repository": {
22911 "type": "git",
22912 "url": "git+ssh://git@github.com/indutny/elliptic.git"
22913 },
22914 "scripts": {
22915 "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
22916 "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js",
22917 "lint": "npm run jscs && npm run jshint",
22918 "test": "npm run lint && npm run unit",
22919 "unit": "istanbul test _mocha --reporter=spec test/index.js",
22920 "version": "grunt dist && git add dist/"
22921 },
22922 "version": "6.4.0"
22923}
22924
22925},{}],143:[function(require,module,exports){
22926// Copyright Joyent, Inc. and other Node contributors.
22927//
22928// Permission is hereby granted, free of charge, to any person obtaining a
22929// copy of this software and associated documentation files (the
22930// "Software"), to deal in the Software without restriction, including
22931// without limitation the rights to use, copy, modify, merge, publish,
22932// distribute, sublicense, and/or sell copies of the Software, and to permit
22933// persons to whom the Software is furnished to do so, subject to the
22934// following conditions:
22935//
22936// The above copyright notice and this permission notice shall be included
22937// in all copies or substantial portions of the Software.
22938//
22939// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
22940// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
22941// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
22942// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
22943// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
22944// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
22945// USE OR OTHER DEALINGS IN THE SOFTWARE.
22946
22947function EventEmitter() {
22948 this._events = this._events || {};
22949 this._maxListeners = this._maxListeners || undefined;
22950}
22951module.exports = EventEmitter;
22952
22953// Backwards-compat with node 0.10.x
22954EventEmitter.EventEmitter = EventEmitter;
22955
22956EventEmitter.prototype._events = undefined;
22957EventEmitter.prototype._maxListeners = undefined;
22958
22959// By default EventEmitters will print a warning if more than 10 listeners are
22960// added to it. This is a useful default which helps finding memory leaks.
22961EventEmitter.defaultMaxListeners = 10;
22962
22963// Obviously not all Emitters should be limited to 10. This function allows
22964// that to be increased. Set to zero for unlimited.
22965EventEmitter.prototype.setMaxListeners = function(n) {
22966 if (!isNumber(n) || n < 0 || isNaN(n))
22967 throw TypeError('n must be a positive number');
22968 this._maxListeners = n;
22969 return this;
22970};
22971
22972EventEmitter.prototype.emit = function(type) {
22973 var er, handler, len, args, i, listeners;
22974
22975 if (!this._events)
22976 this._events = {};
22977
22978 // If there is no 'error' event listener then throw.
22979 if (type === 'error') {
22980 if (!this._events.error ||
22981 (isObject(this._events.error) && !this._events.error.length)) {
22982 er = arguments[1];
22983 if (er instanceof Error) {
22984 throw er; // Unhandled 'error' event
22985 } else {
22986 // At least give some kind of context to the user
22987 var err = new Error('Uncaught, unspecified "error" event. (' + er + ')');
22988 err.context = er;
22989 throw err;
22990 }
22991 }
22992 }
22993
22994 handler = this._events[type];
22995
22996 if (isUndefined(handler))
22997 return false;
22998
22999 if (isFunction(handler)) {
23000 switch (arguments.length) {
23001 // fast cases
23002 case 1:
23003 handler.call(this);
23004 break;
23005 case 2:
23006 handler.call(this, arguments[1]);
23007 break;
23008 case 3:
23009 handler.call(this, arguments[1], arguments[2]);
23010 break;
23011 // slower
23012 default:
23013 args = Array.prototype.slice.call(arguments, 1);
23014 handler.apply(this, args);
23015 }
23016 } else if (isObject(handler)) {
23017 args = Array.prototype.slice.call(arguments, 1);
23018 listeners = handler.slice();
23019 len = listeners.length;
23020 for (i = 0; i < len; i++)
23021 listeners[i].apply(this, args);
23022 }
23023
23024 return true;
23025};
23026
23027EventEmitter.prototype.addListener = function(type, listener) {
23028 var m;
23029
23030 if (!isFunction(listener))
23031 throw TypeError('listener must be a function');
23032
23033 if (!this._events)
23034 this._events = {};
23035
23036 // To avoid recursion in the case that type === "newListener"! Before
23037 // adding it to the listeners, first emit "newListener".
23038 if (this._events.newListener)
23039 this.emit('newListener', type,
23040 isFunction(listener.listener) ?
23041 listener.listener : listener);
23042
23043 if (!this._events[type])
23044 // Optimize the case of one listener. Don't need the extra array object.
23045 this._events[type] = listener;
23046 else if (isObject(this._events[type]))
23047 // If we've already got an array, just append.
23048 this._events[type].push(listener);
23049 else
23050 // Adding the second element, need to change to array.
23051 this._events[type] = [this._events[type], listener];
23052
23053 // Check for listener leak
23054 if (isObject(this._events[type]) && !this._events[type].warned) {
23055 if (!isUndefined(this._maxListeners)) {
23056 m = this._maxListeners;
23057 } else {
23058 m = EventEmitter.defaultMaxListeners;
23059 }
23060
23061 if (m && m > 0 && this._events[type].length > m) {
23062 this._events[type].warned = true;
23063 console.error('(node) warning: possible EventEmitter memory ' +
23064 'leak detected. %d listeners added. ' +
23065 'Use emitter.setMaxListeners() to increase limit.',
23066 this._events[type].length);
23067 if (typeof console.trace === 'function') {
23068 // not supported in IE 10
23069 console.trace();
23070 }
23071 }
23072 }
23073
23074 return this;
23075};
23076
23077EventEmitter.prototype.on = EventEmitter.prototype.addListener;
23078
23079EventEmitter.prototype.once = function(type, listener) {
23080 if (!isFunction(listener))
23081 throw TypeError('listener must be a function');
23082
23083 var fired = false;
23084
23085 function g() {
23086 this.removeListener(type, g);
23087
23088 if (!fired) {
23089 fired = true;
23090 listener.apply(this, arguments);
23091 }
23092 }
23093
23094 g.listener = listener;
23095 this.on(type, g);
23096
23097 return this;
23098};
23099
23100// emits a 'removeListener' event iff the listener was removed
23101EventEmitter.prototype.removeListener = function(type, listener) {
23102 var list, position, length, i;
23103
23104 if (!isFunction(listener))
23105 throw TypeError('listener must be a function');
23106
23107 if (!this._events || !this._events[type])
23108 return this;
23109
23110 list = this._events[type];
23111 length = list.length;
23112 position = -1;
23113
23114 if (list === listener ||
23115 (isFunction(list.listener) && list.listener === listener)) {
23116 delete this._events[type];
23117 if (this._events.removeListener)
23118 this.emit('removeListener', type, listener);
23119
23120 } else if (isObject(list)) {
23121 for (i = length; i-- > 0;) {
23122 if (list[i] === listener ||
23123 (list[i].listener && list[i].listener === listener)) {
23124 position = i;
23125 break;
23126 }
23127 }
23128
23129 if (position < 0)
23130 return this;
23131
23132 if (list.length === 1) {
23133 list.length = 0;
23134 delete this._events[type];
23135 } else {
23136 list.splice(position, 1);
23137 }
23138
23139 if (this._events.removeListener)
23140 this.emit('removeListener', type, listener);
23141 }
23142
23143 return this;
23144};
23145
23146EventEmitter.prototype.removeAllListeners = function(type) {
23147 var key, listeners;
23148
23149 if (!this._events)
23150 return this;
23151
23152 // not listening for removeListener, no need to emit
23153 if (!this._events.removeListener) {
23154 if (arguments.length === 0)
23155 this._events = {};
23156 else if (this._events[type])
23157 delete this._events[type];
23158 return this;
23159 }
23160
23161 // emit removeListener for all listeners on all events
23162 if (arguments.length === 0) {
23163 for (key in this._events) {
23164 if (key === 'removeListener') continue;
23165 this.removeAllListeners(key);
23166 }
23167 this.removeAllListeners('removeListener');
23168 this._events = {};
23169 return this;
23170 }
23171
23172 listeners = this._events[type];
23173
23174 if (isFunction(listeners)) {
23175 this.removeListener(type, listeners);
23176 } else if (listeners) {
23177 // LIFO order
23178 while (listeners.length)
23179 this.removeListener(type, listeners[listeners.length - 1]);
23180 }
23181 delete this._events[type];
23182
23183 return this;
23184};
23185
23186EventEmitter.prototype.listeners = function(type) {
23187 var ret;
23188 if (!this._events || !this._events[type])
23189 ret = [];
23190 else if (isFunction(this._events[type]))
23191 ret = [this._events[type]];
23192 else
23193 ret = this._events[type].slice();
23194 return ret;
23195};
23196
23197EventEmitter.prototype.listenerCount = function(type) {
23198 if (this._events) {
23199 var evlistener = this._events[type];
23200
23201 if (isFunction(evlistener))
23202 return 1;
23203 else if (evlistener)
23204 return evlistener.length;
23205 }
23206 return 0;
23207};
23208
23209EventEmitter.listenerCount = function(emitter, type) {
23210 return emitter.listenerCount(type);
23211};
23212
23213function isFunction(arg) {
23214 return typeof arg === 'function';
23215}
23216
23217function isNumber(arg) {
23218 return typeof arg === 'number';
23219}
23220
23221function isObject(arg) {
23222 return typeof arg === 'object' && arg !== null;
23223}
23224
23225function isUndefined(arg) {
23226 return arg === void 0;
23227}
23228
23229},{}],144:[function(require,module,exports){
23230var Buffer = require('safe-buffer').Buffer
23231var MD5 = require('md5.js')
23232
23233/* eslint-disable camelcase */
23234function EVP_BytesToKey (password, salt, keyBits, ivLen) {
23235 if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary')
23236 if (salt) {
23237 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary')
23238 if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length')
23239 }
23240
23241 var keyLen = keyBits / 8
23242 var key = Buffer.alloc(keyLen)
23243 var iv = Buffer.alloc(ivLen || 0)
23244 var tmp = Buffer.alloc(0)
23245
23246 while (keyLen > 0 || ivLen > 0) {
23247 var hash = new MD5()
23248 hash.update(tmp)
23249 hash.update(password)
23250 if (salt) hash.update(salt)
23251 tmp = hash.digest()
23252
23253 var used = 0
23254
23255 if (keyLen > 0) {
23256 var keyStart = key.length - keyLen
23257 used = Math.min(keyLen, tmp.length)
23258 tmp.copy(key, keyStart, 0, used)
23259 keyLen -= used
23260 }
23261
23262 if (used < tmp.length && ivLen > 0) {
23263 var ivStart = iv.length - ivLen
23264 var length = Math.min(ivLen, tmp.length - used)
23265 tmp.copy(iv, ivStart, used, used + length)
23266 ivLen -= length
23267 }
23268 }
23269
23270 tmp.fill(0)
23271 return { key: key, iv: iv }
23272}
23273
23274module.exports = EVP_BytesToKey
23275
23276},{"md5.js":173,"safe-buffer":247}],145:[function(require,module,exports){
23277'use strict';
23278
23279var hasOwn = Object.prototype.hasOwnProperty;
23280var toStr = Object.prototype.toString;
23281
23282var isArray = function isArray(arr) {
23283 if (typeof Array.isArray === 'function') {
23284 return Array.isArray(arr);
23285 }
23286
23287 return toStr.call(arr) === '[object Array]';
23288};
23289
23290var isPlainObject = function isPlainObject(obj) {
23291 if (!obj || toStr.call(obj) !== '[object Object]') {
23292 return false;
23293 }
23294
23295 var hasOwnConstructor = hasOwn.call(obj, 'constructor');
23296 var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf');
23297 // Not own constructor property must be Object
23298 if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) {
23299 return false;
23300 }
23301
23302 // Own properties are enumerated firstly, so to speed up,
23303 // if last one is own, then all properties are own.
23304 var key;
23305 for (key in obj) { /**/ }
23306
23307 return typeof key === 'undefined' || hasOwn.call(obj, key);
23308};
23309
23310module.exports = function extend() {
23311 var options, name, src, copy, copyIsArray, clone;
23312 var target = arguments[0];
23313 var i = 1;
23314 var length = arguments.length;
23315 var deep = false;
23316
23317 // Handle a deep copy situation
23318 if (typeof target === 'boolean') {
23319 deep = target;
23320 target = arguments[1] || {};
23321 // skip the boolean and the target
23322 i = 2;
23323 }
23324 if (target == null || (typeof target !== 'object' && typeof target !== 'function')) {
23325 target = {};
23326 }
23327
23328 for (; i < length; ++i) {
23329 options = arguments[i];
23330 // Only deal with non-null/undefined values
23331 if (options != null) {
23332 // Extend the base object
23333 for (name in options) {
23334 src = target[name];
23335 copy = options[name];
23336
23337 // Prevent never-ending loop
23338 if (target !== copy) {
23339 // Recurse if we're merging plain objects or arrays
23340 if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) {
23341 if (copyIsArray) {
23342 copyIsArray = false;
23343 clone = src && isArray(src) ? src : [];
23344 } else {
23345 clone = src && isPlainObject(src) ? src : {};
23346 }
23347
23348 // Never move original objects, clone them
23349 target[name] = extend(deep, clone, copy);
23350
23351 // Don't bring in undefined values
23352 } else if (typeof copy !== 'undefined') {
23353 target[name] = copy;
23354 }
23355 }
23356 }
23357 }
23358 }
23359
23360 // Return the modified object
23361 return target;
23362};
23363
23364},{}],146:[function(require,module,exports){
23365(function (Buffer){
23366'use strict'
23367var Transform = require('stream').Transform
23368var inherits = require('inherits')
23369
23370function HashBase (blockSize) {
23371 Transform.call(this)
23372
23373 this._block = new Buffer(blockSize)
23374 this._blockSize = blockSize
23375 this._blockOffset = 0
23376 this._length = [0, 0, 0, 0]
23377
23378 this._finalized = false
23379}
23380
23381inherits(HashBase, Transform)
23382
23383HashBase.prototype._transform = function (chunk, encoding, callback) {
23384 var error = null
23385 try {
23386 if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding)
23387 this.update(chunk)
23388 } catch (err) {
23389 error = err
23390 }
23391
23392 callback(error)
23393}
23394
23395HashBase.prototype._flush = function (callback) {
23396 var error = null
23397 try {
23398 this.push(this._digest())
23399 } catch (err) {
23400 error = err
23401 }
23402
23403 callback(error)
23404}
23405
23406HashBase.prototype.update = function (data, encoding) {
23407 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
23408 if (this._finalized) throw new Error('Digest already called')
23409 if (!Buffer.isBuffer(data)) data = new Buffer(data, encoding || 'binary')
23410
23411 // consume data
23412 var block = this._block
23413 var offset = 0
23414 while (this._blockOffset + data.length - offset >= this._blockSize) {
23415 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
23416 this._update()
23417 this._blockOffset = 0
23418 }
23419 while (offset < data.length) block[this._blockOffset++] = data[offset++]
23420
23421 // update length
23422 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
23423 this._length[j] += carry
23424 carry = (this._length[j] / 0x0100000000) | 0
23425 if (carry > 0) this._length[j] -= 0x0100000000 * carry
23426 }
23427
23428 return this
23429}
23430
23431HashBase.prototype._update = function (data) {
23432 throw new Error('_update is not implemented')
23433}
23434
23435HashBase.prototype.digest = function (encoding) {
23436 if (this._finalized) throw new Error('Digest already called')
23437 this._finalized = true
23438
23439 var digest = this._digest()
23440 if (encoding !== undefined) digest = digest.toString(encoding)
23441 return digest
23442}
23443
23444HashBase.prototype._digest = function () {
23445 throw new Error('_digest is not implemented')
23446}
23447
23448module.exports = HashBase
23449
23450}).call(this,require("buffer").Buffer)
23451},{"buffer":107,"inherits":163,"stream":263}],147:[function(require,module,exports){
23452var hash = exports;
23453
23454hash.utils = require('./hash/utils');
23455hash.common = require('./hash/common');
23456hash.sha = require('./hash/sha');
23457hash.ripemd = require('./hash/ripemd');
23458hash.hmac = require('./hash/hmac');
23459
23460// Proxy hash functions to the main object
23461hash.sha1 = hash.sha.sha1;
23462hash.sha256 = hash.sha.sha256;
23463hash.sha224 = hash.sha.sha224;
23464hash.sha384 = hash.sha.sha384;
23465hash.sha512 = hash.sha.sha512;
23466hash.ripemd160 = hash.ripemd.ripemd160;
23467
23468},{"./hash/common":148,"./hash/hmac":149,"./hash/ripemd":150,"./hash/sha":151,"./hash/utils":158}],148:[function(require,module,exports){
23469'use strict';
23470
23471var utils = require('./utils');
23472var assert = require('minimalistic-assert');
23473
23474function BlockHash() {
23475 this.pending = null;
23476 this.pendingTotal = 0;
23477 this.blockSize = this.constructor.blockSize;
23478 this.outSize = this.constructor.outSize;
23479 this.hmacStrength = this.constructor.hmacStrength;
23480 this.padLength = this.constructor.padLength / 8;
23481 this.endian = 'big';
23482
23483 this._delta8 = this.blockSize / 8;
23484 this._delta32 = this.blockSize / 32;
23485}
23486exports.BlockHash = BlockHash;
23487
23488BlockHash.prototype.update = function update(msg, enc) {
23489 // Convert message to array, pad it, and join into 32bit blocks
23490 msg = utils.toArray(msg, enc);
23491 if (!this.pending)
23492 this.pending = msg;
23493 else
23494 this.pending = this.pending.concat(msg);
23495 this.pendingTotal += msg.length;
23496
23497 // Enough data, try updating
23498 if (this.pending.length >= this._delta8) {
23499 msg = this.pending;
23500
23501 // Process pending data in blocks
23502 var r = msg.length % this._delta8;
23503 this.pending = msg.slice(msg.length - r, msg.length);
23504 if (this.pending.length === 0)
23505 this.pending = null;
23506
23507 msg = utils.join32(msg, 0, msg.length - r, this.endian);
23508 for (var i = 0; i < msg.length; i += this._delta32)
23509 this._update(msg, i, i + this._delta32);
23510 }
23511
23512 return this;
23513};
23514
23515BlockHash.prototype.digest = function digest(enc) {
23516 this.update(this._pad());
23517 assert(this.pending === null);
23518
23519 return this._digest(enc);
23520};
23521
23522BlockHash.prototype._pad = function pad() {
23523 var len = this.pendingTotal;
23524 var bytes = this._delta8;
23525 var k = bytes - ((len + this.padLength) % bytes);
23526 var res = new Array(k + this.padLength);
23527 res[0] = 0x80;
23528 for (var i = 1; i < k; i++)
23529 res[i] = 0;
23530
23531 // Append length
23532 len <<= 3;
23533 if (this.endian === 'big') {
23534 for (var t = 8; t < this.padLength; t++)
23535 res[i++] = 0;
23536
23537 res[i++] = 0;
23538 res[i++] = 0;
23539 res[i++] = 0;
23540 res[i++] = 0;
23541 res[i++] = (len >>> 24) & 0xff;
23542 res[i++] = (len >>> 16) & 0xff;
23543 res[i++] = (len >>> 8) & 0xff;
23544 res[i++] = len & 0xff;
23545 } else {
23546 res[i++] = len & 0xff;
23547 res[i++] = (len >>> 8) & 0xff;
23548 res[i++] = (len >>> 16) & 0xff;
23549 res[i++] = (len >>> 24) & 0xff;
23550 res[i++] = 0;
23551 res[i++] = 0;
23552 res[i++] = 0;
23553 res[i++] = 0;
23554
23555 for (t = 8; t < this.padLength; t++)
23556 res[i++] = 0;
23557 }
23558
23559 return res;
23560};
23561
23562},{"./utils":158,"minimalistic-assert":176}],149:[function(require,module,exports){
23563'use strict';
23564
23565var utils = require('./utils');
23566var assert = require('minimalistic-assert');
23567
23568function Hmac(hash, key, enc) {
23569 if (!(this instanceof Hmac))
23570 return new Hmac(hash, key, enc);
23571 this.Hash = hash;
23572 this.blockSize = hash.blockSize / 8;
23573 this.outSize = hash.outSize / 8;
23574 this.inner = null;
23575 this.outer = null;
23576
23577 this._init(utils.toArray(key, enc));
23578}
23579module.exports = Hmac;
23580
23581Hmac.prototype._init = function init(key) {
23582 // Shorten key, if needed
23583 if (key.length > this.blockSize)
23584 key = new this.Hash().update(key).digest();
23585 assert(key.length <= this.blockSize);
23586
23587 // Add padding to key
23588 for (var i = key.length; i < this.blockSize; i++)
23589 key.push(0);
23590
23591 for (i = 0; i < key.length; i++)
23592 key[i] ^= 0x36;
23593 this.inner = new this.Hash().update(key);
23594
23595 // 0x36 ^ 0x5c = 0x6a
23596 for (i = 0; i < key.length; i++)
23597 key[i] ^= 0x6a;
23598 this.outer = new this.Hash().update(key);
23599};
23600
23601Hmac.prototype.update = function update(msg, enc) {
23602 this.inner.update(msg, enc);
23603 return this;
23604};
23605
23606Hmac.prototype.digest = function digest(enc) {
23607 this.outer.update(this.inner.digest());
23608 return this.outer.digest(enc);
23609};
23610
23611},{"./utils":158,"minimalistic-assert":176}],150:[function(require,module,exports){
23612'use strict';
23613
23614var utils = require('./utils');
23615var common = require('./common');
23616
23617var rotl32 = utils.rotl32;
23618var sum32 = utils.sum32;
23619var sum32_3 = utils.sum32_3;
23620var sum32_4 = utils.sum32_4;
23621var BlockHash = common.BlockHash;
23622
23623function RIPEMD160() {
23624 if (!(this instanceof RIPEMD160))
23625 return new RIPEMD160();
23626
23627 BlockHash.call(this);
23628
23629 this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
23630 this.endian = 'little';
23631}
23632utils.inherits(RIPEMD160, BlockHash);
23633exports.ripemd160 = RIPEMD160;
23634
23635RIPEMD160.blockSize = 512;
23636RIPEMD160.outSize = 160;
23637RIPEMD160.hmacStrength = 192;
23638RIPEMD160.padLength = 64;
23639
23640RIPEMD160.prototype._update = function update(msg, start) {
23641 var A = this.h[0];
23642 var B = this.h[1];
23643 var C = this.h[2];
23644 var D = this.h[3];
23645 var E = this.h[4];
23646 var Ah = A;
23647 var Bh = B;
23648 var Ch = C;
23649 var Dh = D;
23650 var Eh = E;
23651 for (var j = 0; j < 80; j++) {
23652 var T = sum32(
23653 rotl32(
23654 sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)),
23655 s[j]),
23656 E);
23657 A = E;
23658 E = D;
23659 D = rotl32(C, 10);
23660 C = B;
23661 B = T;
23662 T = sum32(
23663 rotl32(
23664 sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)),
23665 sh[j]),
23666 Eh);
23667 Ah = Eh;
23668 Eh = Dh;
23669 Dh = rotl32(Ch, 10);
23670 Ch = Bh;
23671 Bh = T;
23672 }
23673 T = sum32_3(this.h[1], C, Dh);
23674 this.h[1] = sum32_3(this.h[2], D, Eh);
23675 this.h[2] = sum32_3(this.h[3], E, Ah);
23676 this.h[3] = sum32_3(this.h[4], A, Bh);
23677 this.h[4] = sum32_3(this.h[0], B, Ch);
23678 this.h[0] = T;
23679};
23680
23681RIPEMD160.prototype._digest = function digest(enc) {
23682 if (enc === 'hex')
23683 return utils.toHex32(this.h, 'little');
23684 else
23685 return utils.split32(this.h, 'little');
23686};
23687
23688function f(j, x, y, z) {
23689 if (j <= 15)
23690 return x ^ y ^ z;
23691 else if (j <= 31)
23692 return (x & y) | ((~x) & z);
23693 else if (j <= 47)
23694 return (x | (~y)) ^ z;
23695 else if (j <= 63)
23696 return (x & z) | (y & (~z));
23697 else
23698 return x ^ (y | (~z));
23699}
23700
23701function K(j) {
23702 if (j <= 15)
23703 return 0x00000000;
23704 else if (j <= 31)
23705 return 0x5a827999;
23706 else if (j <= 47)
23707 return 0x6ed9eba1;
23708 else if (j <= 63)
23709 return 0x8f1bbcdc;
23710 else
23711 return 0xa953fd4e;
23712}
23713
23714function Kh(j) {
23715 if (j <= 15)
23716 return 0x50a28be6;
23717 else if (j <= 31)
23718 return 0x5c4dd124;
23719 else if (j <= 47)
23720 return 0x6d703ef3;
23721 else if (j <= 63)
23722 return 0x7a6d76e9;
23723 else
23724 return 0x00000000;
23725}
23726
23727var r = [
23728 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15,
23729 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8,
23730 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12,
23731 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2,
23732 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
23733];
23734
23735var rh = [
23736 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12,
23737 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2,
23738 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13,
23739 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14,
23740 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
23741];
23742
23743var s = [
23744 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8,
23745 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12,
23746 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5,
23747 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12,
23748 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
23749];
23750
23751var sh = [
23752 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6,
23753 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11,
23754 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5,
23755 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8,
23756 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
23757];
23758
23759},{"./common":148,"./utils":158}],151:[function(require,module,exports){
23760'use strict';
23761
23762exports.sha1 = require('./sha/1');
23763exports.sha224 = require('./sha/224');
23764exports.sha256 = require('./sha/256');
23765exports.sha384 = require('./sha/384');
23766exports.sha512 = require('./sha/512');
23767
23768},{"./sha/1":152,"./sha/224":153,"./sha/256":154,"./sha/384":155,"./sha/512":156}],152:[function(require,module,exports){
23769'use strict';
23770
23771var utils = require('../utils');
23772var common = require('../common');
23773var shaCommon = require('./common');
23774
23775var rotl32 = utils.rotl32;
23776var sum32 = utils.sum32;
23777var sum32_5 = utils.sum32_5;
23778var ft_1 = shaCommon.ft_1;
23779var BlockHash = common.BlockHash;
23780
23781var sha1_K = [
23782 0x5A827999, 0x6ED9EBA1,
23783 0x8F1BBCDC, 0xCA62C1D6
23784];
23785
23786function SHA1() {
23787 if (!(this instanceof SHA1))
23788 return new SHA1();
23789
23790 BlockHash.call(this);
23791 this.h = [
23792 0x67452301, 0xefcdab89, 0x98badcfe,
23793 0x10325476, 0xc3d2e1f0 ];
23794 this.W = new Array(80);
23795}
23796
23797utils.inherits(SHA1, BlockHash);
23798module.exports = SHA1;
23799
23800SHA1.blockSize = 512;
23801SHA1.outSize = 160;
23802SHA1.hmacStrength = 80;
23803SHA1.padLength = 64;
23804
23805SHA1.prototype._update = function _update(msg, start) {
23806 var W = this.W;
23807
23808 for (var i = 0; i < 16; i++)
23809 W[i] = msg[start + i];
23810
23811 for(; i < W.length; i++)
23812 W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1);
23813
23814 var a = this.h[0];
23815 var b = this.h[1];
23816 var c = this.h[2];
23817 var d = this.h[3];
23818 var e = this.h[4];
23819
23820 for (i = 0; i < W.length; i++) {
23821 var s = ~~(i / 20);
23822 var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]);
23823 e = d;
23824 d = c;
23825 c = rotl32(b, 30);
23826 b = a;
23827 a = t;
23828 }
23829
23830 this.h[0] = sum32(this.h[0], a);
23831 this.h[1] = sum32(this.h[1], b);
23832 this.h[2] = sum32(this.h[2], c);
23833 this.h[3] = sum32(this.h[3], d);
23834 this.h[4] = sum32(this.h[4], e);
23835};
23836
23837SHA1.prototype._digest = function digest(enc) {
23838 if (enc === 'hex')
23839 return utils.toHex32(this.h, 'big');
23840 else
23841 return utils.split32(this.h, 'big');
23842};
23843
23844},{"../common":148,"../utils":158,"./common":157}],153:[function(require,module,exports){
23845'use strict';
23846
23847var utils = require('../utils');
23848var SHA256 = require('./256');
23849
23850function SHA224() {
23851 if (!(this instanceof SHA224))
23852 return new SHA224();
23853
23854 SHA256.call(this);
23855 this.h = [
23856 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
23857 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
23858}
23859utils.inherits(SHA224, SHA256);
23860module.exports = SHA224;
23861
23862SHA224.blockSize = 512;
23863SHA224.outSize = 224;
23864SHA224.hmacStrength = 192;
23865SHA224.padLength = 64;
23866
23867SHA224.prototype._digest = function digest(enc) {
23868 // Just truncate output
23869 if (enc === 'hex')
23870 return utils.toHex32(this.h.slice(0, 7), 'big');
23871 else
23872 return utils.split32(this.h.slice(0, 7), 'big');
23873};
23874
23875
23876},{"../utils":158,"./256":154}],154:[function(require,module,exports){
23877'use strict';
23878
23879var utils = require('../utils');
23880var common = require('../common');
23881var shaCommon = require('./common');
23882var assert = require('minimalistic-assert');
23883
23884var sum32 = utils.sum32;
23885var sum32_4 = utils.sum32_4;
23886var sum32_5 = utils.sum32_5;
23887var ch32 = shaCommon.ch32;
23888var maj32 = shaCommon.maj32;
23889var s0_256 = shaCommon.s0_256;
23890var s1_256 = shaCommon.s1_256;
23891var g0_256 = shaCommon.g0_256;
23892var g1_256 = shaCommon.g1_256;
23893
23894var BlockHash = common.BlockHash;
23895
23896var sha256_K = [
23897 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5,
23898 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5,
23899 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3,
23900 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174,
23901 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc,
23902 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da,
23903 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7,
23904 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967,
23905 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13,
23906 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85,
23907 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3,
23908 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070,
23909 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5,
23910 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3,
23911 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208,
23912 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2
23913];
23914
23915function SHA256() {
23916 if (!(this instanceof SHA256))
23917 return new SHA256();
23918
23919 BlockHash.call(this);
23920 this.h = [
23921 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
23922 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
23923 ];
23924 this.k = sha256_K;
23925 this.W = new Array(64);
23926}
23927utils.inherits(SHA256, BlockHash);
23928module.exports = SHA256;
23929
23930SHA256.blockSize = 512;
23931SHA256.outSize = 256;
23932SHA256.hmacStrength = 192;
23933SHA256.padLength = 64;
23934
23935SHA256.prototype._update = function _update(msg, start) {
23936 var W = this.W;
23937
23938 for (var i = 0; i < 16; i++)
23939 W[i] = msg[start + i];
23940 for (; i < W.length; i++)
23941 W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]);
23942
23943 var a = this.h[0];
23944 var b = this.h[1];
23945 var c = this.h[2];
23946 var d = this.h[3];
23947 var e = this.h[4];
23948 var f = this.h[5];
23949 var g = this.h[6];
23950 var h = this.h[7];
23951
23952 assert(this.k.length === W.length);
23953 for (i = 0; i < W.length; i++) {
23954 var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]);
23955 var T2 = sum32(s0_256(a), maj32(a, b, c));
23956 h = g;
23957 g = f;
23958 f = e;
23959 e = sum32(d, T1);
23960 d = c;
23961 c = b;
23962 b = a;
23963 a = sum32(T1, T2);
23964 }
23965
23966 this.h[0] = sum32(this.h[0], a);
23967 this.h[1] = sum32(this.h[1], b);
23968 this.h[2] = sum32(this.h[2], c);
23969 this.h[3] = sum32(this.h[3], d);
23970 this.h[4] = sum32(this.h[4], e);
23971 this.h[5] = sum32(this.h[5], f);
23972 this.h[6] = sum32(this.h[6], g);
23973 this.h[7] = sum32(this.h[7], h);
23974};
23975
23976SHA256.prototype._digest = function digest(enc) {
23977 if (enc === 'hex')
23978 return utils.toHex32(this.h, 'big');
23979 else
23980 return utils.split32(this.h, 'big');
23981};
23982
23983},{"../common":148,"../utils":158,"./common":157,"minimalistic-assert":176}],155:[function(require,module,exports){
23984'use strict';
23985
23986var utils = require('../utils');
23987
23988var SHA512 = require('./512');
23989
23990function SHA384() {
23991 if (!(this instanceof SHA384))
23992 return new SHA384();
23993
23994 SHA512.call(this);
23995 this.h = [
23996 0xcbbb9d5d, 0xc1059ed8,
23997 0x629a292a, 0x367cd507,
23998 0x9159015a, 0x3070dd17,
23999 0x152fecd8, 0xf70e5939,
24000 0x67332667, 0xffc00b31,
24001 0x8eb44a87, 0x68581511,
24002 0xdb0c2e0d, 0x64f98fa7,
24003 0x47b5481d, 0xbefa4fa4 ];
24004}
24005utils.inherits(SHA384, SHA512);
24006module.exports = SHA384;
24007
24008SHA384.blockSize = 1024;
24009SHA384.outSize = 384;
24010SHA384.hmacStrength = 192;
24011SHA384.padLength = 128;
24012
24013SHA384.prototype._digest = function digest(enc) {
24014 if (enc === 'hex')
24015 return utils.toHex32(this.h.slice(0, 12), 'big');
24016 else
24017 return utils.split32(this.h.slice(0, 12), 'big');
24018};
24019
24020},{"../utils":158,"./512":156}],156:[function(require,module,exports){
24021'use strict';
24022
24023var utils = require('../utils');
24024var common = require('../common');
24025var assert = require('minimalistic-assert');
24026
24027var rotr64_hi = utils.rotr64_hi;
24028var rotr64_lo = utils.rotr64_lo;
24029var shr64_hi = utils.shr64_hi;
24030var shr64_lo = utils.shr64_lo;
24031var sum64 = utils.sum64;
24032var sum64_hi = utils.sum64_hi;
24033var sum64_lo = utils.sum64_lo;
24034var sum64_4_hi = utils.sum64_4_hi;
24035var sum64_4_lo = utils.sum64_4_lo;
24036var sum64_5_hi = utils.sum64_5_hi;
24037var sum64_5_lo = utils.sum64_5_lo;
24038
24039var BlockHash = common.BlockHash;
24040
24041var sha512_K = [
24042 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
24043 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
24044 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
24045 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
24046 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
24047 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
24048 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
24049 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
24050 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
24051 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
24052 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
24053 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
24054 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
24055 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
24056 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
24057 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
24058 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
24059 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
24060 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
24061 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
24062 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
24063 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
24064 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
24065 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
24066 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
24067 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
24068 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
24069 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
24070 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
24071 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
24072 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
24073 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
24074 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
24075 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
24076 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
24077 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
24078 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
24079 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
24080 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
24081 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
24082];
24083
24084function SHA512() {
24085 if (!(this instanceof SHA512))
24086 return new SHA512();
24087
24088 BlockHash.call(this);
24089 this.h = [
24090 0x6a09e667, 0xf3bcc908,
24091 0xbb67ae85, 0x84caa73b,
24092 0x3c6ef372, 0xfe94f82b,
24093 0xa54ff53a, 0x5f1d36f1,
24094 0x510e527f, 0xade682d1,
24095 0x9b05688c, 0x2b3e6c1f,
24096 0x1f83d9ab, 0xfb41bd6b,
24097 0x5be0cd19, 0x137e2179 ];
24098 this.k = sha512_K;
24099 this.W = new Array(160);
24100}
24101utils.inherits(SHA512, BlockHash);
24102module.exports = SHA512;
24103
24104SHA512.blockSize = 1024;
24105SHA512.outSize = 512;
24106SHA512.hmacStrength = 192;
24107SHA512.padLength = 128;
24108
24109SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) {
24110 var W = this.W;
24111
24112 // 32 x 32bit words
24113 for (var i = 0; i < 32; i++)
24114 W[i] = msg[start + i];
24115 for (; i < W.length; i += 2) {
24116 var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2
24117 var c0_lo = g1_512_lo(W[i - 4], W[i - 3]);
24118 var c1_hi = W[i - 14]; // i - 7
24119 var c1_lo = W[i - 13];
24120 var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15
24121 var c2_lo = g0_512_lo(W[i - 30], W[i - 29]);
24122 var c3_hi = W[i - 32]; // i - 16
24123 var c3_lo = W[i - 31];
24124
24125 W[i] = sum64_4_hi(
24126 c0_hi, c0_lo,
24127 c1_hi, c1_lo,
24128 c2_hi, c2_lo,
24129 c3_hi, c3_lo);
24130 W[i + 1] = sum64_4_lo(
24131 c0_hi, c0_lo,
24132 c1_hi, c1_lo,
24133 c2_hi, c2_lo,
24134 c3_hi, c3_lo);
24135 }
24136};
24137
24138SHA512.prototype._update = function _update(msg, start) {
24139 this._prepareBlock(msg, start);
24140
24141 var W = this.W;
24142
24143 var ah = this.h[0];
24144 var al = this.h[1];
24145 var bh = this.h[2];
24146 var bl = this.h[3];
24147 var ch = this.h[4];
24148 var cl = this.h[5];
24149 var dh = this.h[6];
24150 var dl = this.h[7];
24151 var eh = this.h[8];
24152 var el = this.h[9];
24153 var fh = this.h[10];
24154 var fl = this.h[11];
24155 var gh = this.h[12];
24156 var gl = this.h[13];
24157 var hh = this.h[14];
24158 var hl = this.h[15];
24159
24160 assert(this.k.length === W.length);
24161 for (var i = 0; i < W.length; i += 2) {
24162 var c0_hi = hh;
24163 var c0_lo = hl;
24164 var c1_hi = s1_512_hi(eh, el);
24165 var c1_lo = s1_512_lo(eh, el);
24166 var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl);
24167 var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl);
24168 var c3_hi = this.k[i];
24169 var c3_lo = this.k[i + 1];
24170 var c4_hi = W[i];
24171 var c4_lo = W[i + 1];
24172
24173 var T1_hi = sum64_5_hi(
24174 c0_hi, c0_lo,
24175 c1_hi, c1_lo,
24176 c2_hi, c2_lo,
24177 c3_hi, c3_lo,
24178 c4_hi, c4_lo);
24179 var T1_lo = sum64_5_lo(
24180 c0_hi, c0_lo,
24181 c1_hi, c1_lo,
24182 c2_hi, c2_lo,
24183 c3_hi, c3_lo,
24184 c4_hi, c4_lo);
24185
24186 c0_hi = s0_512_hi(ah, al);
24187 c0_lo = s0_512_lo(ah, al);
24188 c1_hi = maj64_hi(ah, al, bh, bl, ch, cl);
24189 c1_lo = maj64_lo(ah, al, bh, bl, ch, cl);
24190
24191 var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo);
24192 var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo);
24193
24194 hh = gh;
24195 hl = gl;
24196
24197 gh = fh;
24198 gl = fl;
24199
24200 fh = eh;
24201 fl = el;
24202
24203 eh = sum64_hi(dh, dl, T1_hi, T1_lo);
24204 el = sum64_lo(dl, dl, T1_hi, T1_lo);
24205
24206 dh = ch;
24207 dl = cl;
24208
24209 ch = bh;
24210 cl = bl;
24211
24212 bh = ah;
24213 bl = al;
24214
24215 ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo);
24216 al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo);
24217 }
24218
24219 sum64(this.h, 0, ah, al);
24220 sum64(this.h, 2, bh, bl);
24221 sum64(this.h, 4, ch, cl);
24222 sum64(this.h, 6, dh, dl);
24223 sum64(this.h, 8, eh, el);
24224 sum64(this.h, 10, fh, fl);
24225 sum64(this.h, 12, gh, gl);
24226 sum64(this.h, 14, hh, hl);
24227};
24228
24229SHA512.prototype._digest = function digest(enc) {
24230 if (enc === 'hex')
24231 return utils.toHex32(this.h, 'big');
24232 else
24233 return utils.split32(this.h, 'big');
24234};
24235
24236function ch64_hi(xh, xl, yh, yl, zh) {
24237 var r = (xh & yh) ^ ((~xh) & zh);
24238 if (r < 0)
24239 r += 0x100000000;
24240 return r;
24241}
24242
24243function ch64_lo(xh, xl, yh, yl, zh, zl) {
24244 var r = (xl & yl) ^ ((~xl) & zl);
24245 if (r < 0)
24246 r += 0x100000000;
24247 return r;
24248}
24249
24250function maj64_hi(xh, xl, yh, yl, zh) {
24251 var r = (xh & yh) ^ (xh & zh) ^ (yh & zh);
24252 if (r < 0)
24253 r += 0x100000000;
24254 return r;
24255}
24256
24257function maj64_lo(xh, xl, yh, yl, zh, zl) {
24258 var r = (xl & yl) ^ (xl & zl) ^ (yl & zl);
24259 if (r < 0)
24260 r += 0x100000000;
24261 return r;
24262}
24263
24264function s0_512_hi(xh, xl) {
24265 var c0_hi = rotr64_hi(xh, xl, 28);
24266 var c1_hi = rotr64_hi(xl, xh, 2); // 34
24267 var c2_hi = rotr64_hi(xl, xh, 7); // 39
24268
24269 var r = c0_hi ^ c1_hi ^ c2_hi;
24270 if (r < 0)
24271 r += 0x100000000;
24272 return r;
24273}
24274
24275function s0_512_lo(xh, xl) {
24276 var c0_lo = rotr64_lo(xh, xl, 28);
24277 var c1_lo = rotr64_lo(xl, xh, 2); // 34
24278 var c2_lo = rotr64_lo(xl, xh, 7); // 39
24279
24280 var r = c0_lo ^ c1_lo ^ c2_lo;
24281 if (r < 0)
24282 r += 0x100000000;
24283 return r;
24284}
24285
24286function s1_512_hi(xh, xl) {
24287 var c0_hi = rotr64_hi(xh, xl, 14);
24288 var c1_hi = rotr64_hi(xh, xl, 18);
24289 var c2_hi = rotr64_hi(xl, xh, 9); // 41
24290
24291 var r = c0_hi ^ c1_hi ^ c2_hi;
24292 if (r < 0)
24293 r += 0x100000000;
24294 return r;
24295}
24296
24297function s1_512_lo(xh, xl) {
24298 var c0_lo = rotr64_lo(xh, xl, 14);
24299 var c1_lo = rotr64_lo(xh, xl, 18);
24300 var c2_lo = rotr64_lo(xl, xh, 9); // 41
24301
24302 var r = c0_lo ^ c1_lo ^ c2_lo;
24303 if (r < 0)
24304 r += 0x100000000;
24305 return r;
24306}
24307
24308function g0_512_hi(xh, xl) {
24309 var c0_hi = rotr64_hi(xh, xl, 1);
24310 var c1_hi = rotr64_hi(xh, xl, 8);
24311 var c2_hi = shr64_hi(xh, xl, 7);
24312
24313 var r = c0_hi ^ c1_hi ^ c2_hi;
24314 if (r < 0)
24315 r += 0x100000000;
24316 return r;
24317}
24318
24319function g0_512_lo(xh, xl) {
24320 var c0_lo = rotr64_lo(xh, xl, 1);
24321 var c1_lo = rotr64_lo(xh, xl, 8);
24322 var c2_lo = shr64_lo(xh, xl, 7);
24323
24324 var r = c0_lo ^ c1_lo ^ c2_lo;
24325 if (r < 0)
24326 r += 0x100000000;
24327 return r;
24328}
24329
24330function g1_512_hi(xh, xl) {
24331 var c0_hi = rotr64_hi(xh, xl, 19);
24332 var c1_hi = rotr64_hi(xl, xh, 29); // 61
24333 var c2_hi = shr64_hi(xh, xl, 6);
24334
24335 var r = c0_hi ^ c1_hi ^ c2_hi;
24336 if (r < 0)
24337 r += 0x100000000;
24338 return r;
24339}
24340
24341function g1_512_lo(xh, xl) {
24342 var c0_lo = rotr64_lo(xh, xl, 19);
24343 var c1_lo = rotr64_lo(xl, xh, 29); // 61
24344 var c2_lo = shr64_lo(xh, xl, 6);
24345
24346 var r = c0_lo ^ c1_lo ^ c2_lo;
24347 if (r < 0)
24348 r += 0x100000000;
24349 return r;
24350}
24351
24352},{"../common":148,"../utils":158,"minimalistic-assert":176}],157:[function(require,module,exports){
24353'use strict';
24354
24355var utils = require('../utils');
24356var rotr32 = utils.rotr32;
24357
24358function ft_1(s, x, y, z) {
24359 if (s === 0)
24360 return ch32(x, y, z);
24361 if (s === 1 || s === 3)
24362 return p32(x, y, z);
24363 if (s === 2)
24364 return maj32(x, y, z);
24365}
24366exports.ft_1 = ft_1;
24367
24368function ch32(x, y, z) {
24369 return (x & y) ^ ((~x) & z);
24370}
24371exports.ch32 = ch32;
24372
24373function maj32(x, y, z) {
24374 return (x & y) ^ (x & z) ^ (y & z);
24375}
24376exports.maj32 = maj32;
24377
24378function p32(x, y, z) {
24379 return x ^ y ^ z;
24380}
24381exports.p32 = p32;
24382
24383function s0_256(x) {
24384 return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22);
24385}
24386exports.s0_256 = s0_256;
24387
24388function s1_256(x) {
24389 return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25);
24390}
24391exports.s1_256 = s1_256;
24392
24393function g0_256(x) {
24394 return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3);
24395}
24396exports.g0_256 = g0_256;
24397
24398function g1_256(x) {
24399 return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10);
24400}
24401exports.g1_256 = g1_256;
24402
24403},{"../utils":158}],158:[function(require,module,exports){
24404'use strict';
24405
24406var assert = require('minimalistic-assert');
24407var inherits = require('inherits');
24408
24409exports.inherits = inherits;
24410
24411function toArray(msg, enc) {
24412 if (Array.isArray(msg))
24413 return msg.slice();
24414 if (!msg)
24415 return [];
24416 var res = [];
24417 if (typeof msg === 'string') {
24418 if (!enc) {
24419 for (var i = 0; i < msg.length; i++) {
24420 var c = msg.charCodeAt(i);
24421 var hi = c >> 8;
24422 var lo = c & 0xff;
24423 if (hi)
24424 res.push(hi, lo);
24425 else
24426 res.push(lo);
24427 }
24428 } else if (enc === 'hex') {
24429 msg = msg.replace(/[^a-z0-9]+/ig, '');
24430 if (msg.length % 2 !== 0)
24431 msg = '0' + msg;
24432 for (i = 0; i < msg.length; i += 2)
24433 res.push(parseInt(msg[i] + msg[i + 1], 16));
24434 }
24435 } else {
24436 for (i = 0; i < msg.length; i++)
24437 res[i] = msg[i] | 0;
24438 }
24439 return res;
24440}
24441exports.toArray = toArray;
24442
24443function toHex(msg) {
24444 var res = '';
24445 for (var i = 0; i < msg.length; i++)
24446 res += zero2(msg[i].toString(16));
24447 return res;
24448}
24449exports.toHex = toHex;
24450
24451function htonl(w) {
24452 var res = (w >>> 24) |
24453 ((w >>> 8) & 0xff00) |
24454 ((w << 8) & 0xff0000) |
24455 ((w & 0xff) << 24);
24456 return res >>> 0;
24457}
24458exports.htonl = htonl;
24459
24460function toHex32(msg, endian) {
24461 var res = '';
24462 for (var i = 0; i < msg.length; i++) {
24463 var w = msg[i];
24464 if (endian === 'little')
24465 w = htonl(w);
24466 res += zero8(w.toString(16));
24467 }
24468 return res;
24469}
24470exports.toHex32 = toHex32;
24471
24472function zero2(word) {
24473 if (word.length === 1)
24474 return '0' + word;
24475 else
24476 return word;
24477}
24478exports.zero2 = zero2;
24479
24480function zero8(word) {
24481 if (word.length === 7)
24482 return '0' + word;
24483 else if (word.length === 6)
24484 return '00' + word;
24485 else if (word.length === 5)
24486 return '000' + word;
24487 else if (word.length === 4)
24488 return '0000' + word;
24489 else if (word.length === 3)
24490 return '00000' + word;
24491 else if (word.length === 2)
24492 return '000000' + word;
24493 else if (word.length === 1)
24494 return '0000000' + word;
24495 else
24496 return word;
24497}
24498exports.zero8 = zero8;
24499
24500function join32(msg, start, end, endian) {
24501 var len = end - start;
24502 assert(len % 4 === 0);
24503 var res = new Array(len / 4);
24504 for (var i = 0, k = start; i < res.length; i++, k += 4) {
24505 var w;
24506 if (endian === 'big')
24507 w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3];
24508 else
24509 w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k];
24510 res[i] = w >>> 0;
24511 }
24512 return res;
24513}
24514exports.join32 = join32;
24515
24516function split32(msg, endian) {
24517 var res = new Array(msg.length * 4);
24518 for (var i = 0, k = 0; i < msg.length; i++, k += 4) {
24519 var m = msg[i];
24520 if (endian === 'big') {
24521 res[k] = m >>> 24;
24522 res[k + 1] = (m >>> 16) & 0xff;
24523 res[k + 2] = (m >>> 8) & 0xff;
24524 res[k + 3] = m & 0xff;
24525 } else {
24526 res[k + 3] = m >>> 24;
24527 res[k + 2] = (m >>> 16) & 0xff;
24528 res[k + 1] = (m >>> 8) & 0xff;
24529 res[k] = m & 0xff;
24530 }
24531 }
24532 return res;
24533}
24534exports.split32 = split32;
24535
24536function rotr32(w, b) {
24537 return (w >>> b) | (w << (32 - b));
24538}
24539exports.rotr32 = rotr32;
24540
24541function rotl32(w, b) {
24542 return (w << b) | (w >>> (32 - b));
24543}
24544exports.rotl32 = rotl32;
24545
24546function sum32(a, b) {
24547 return (a + b) >>> 0;
24548}
24549exports.sum32 = sum32;
24550
24551function sum32_3(a, b, c) {
24552 return (a + b + c) >>> 0;
24553}
24554exports.sum32_3 = sum32_3;
24555
24556function sum32_4(a, b, c, d) {
24557 return (a + b + c + d) >>> 0;
24558}
24559exports.sum32_4 = sum32_4;
24560
24561function sum32_5(a, b, c, d, e) {
24562 return (a + b + c + d + e) >>> 0;
24563}
24564exports.sum32_5 = sum32_5;
24565
24566function sum64(buf, pos, ah, al) {
24567 var bh = buf[pos];
24568 var bl = buf[pos + 1];
24569
24570 var lo = (al + bl) >>> 0;
24571 var hi = (lo < al ? 1 : 0) + ah + bh;
24572 buf[pos] = hi >>> 0;
24573 buf[pos + 1] = lo;
24574}
24575exports.sum64 = sum64;
24576
24577function sum64_hi(ah, al, bh, bl) {
24578 var lo = (al + bl) >>> 0;
24579 var hi = (lo < al ? 1 : 0) + ah + bh;
24580 return hi >>> 0;
24581}
24582exports.sum64_hi = sum64_hi;
24583
24584function sum64_lo(ah, al, bh, bl) {
24585 var lo = al + bl;
24586 return lo >>> 0;
24587}
24588exports.sum64_lo = sum64_lo;
24589
24590function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) {
24591 var carry = 0;
24592 var lo = al;
24593 lo = (lo + bl) >>> 0;
24594 carry += lo < al ? 1 : 0;
24595 lo = (lo + cl) >>> 0;
24596 carry += lo < cl ? 1 : 0;
24597 lo = (lo + dl) >>> 0;
24598 carry += lo < dl ? 1 : 0;
24599
24600 var hi = ah + bh + ch + dh + carry;
24601 return hi >>> 0;
24602}
24603exports.sum64_4_hi = sum64_4_hi;
24604
24605function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) {
24606 var lo = al + bl + cl + dl;
24607 return lo >>> 0;
24608}
24609exports.sum64_4_lo = sum64_4_lo;
24610
24611function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
24612 var carry = 0;
24613 var lo = al;
24614 lo = (lo + bl) >>> 0;
24615 carry += lo < al ? 1 : 0;
24616 lo = (lo + cl) >>> 0;
24617 carry += lo < cl ? 1 : 0;
24618 lo = (lo + dl) >>> 0;
24619 carry += lo < dl ? 1 : 0;
24620 lo = (lo + el) >>> 0;
24621 carry += lo < el ? 1 : 0;
24622
24623 var hi = ah + bh + ch + dh + eh + carry;
24624 return hi >>> 0;
24625}
24626exports.sum64_5_hi = sum64_5_hi;
24627
24628function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) {
24629 var lo = al + bl + cl + dl + el;
24630
24631 return lo >>> 0;
24632}
24633exports.sum64_5_lo = sum64_5_lo;
24634
24635function rotr64_hi(ah, al, num) {
24636 var r = (al << (32 - num)) | (ah >>> num);
24637 return r >>> 0;
24638}
24639exports.rotr64_hi = rotr64_hi;
24640
24641function rotr64_lo(ah, al, num) {
24642 var r = (ah << (32 - num)) | (al >>> num);
24643 return r >>> 0;
24644}
24645exports.rotr64_lo = rotr64_lo;
24646
24647function shr64_hi(ah, al, num) {
24648 return ah >>> num;
24649}
24650exports.shr64_hi = shr64_hi;
24651
24652function shr64_lo(ah, al, num) {
24653 var r = (ah << (32 - num)) | (al >>> num);
24654 return r >>> 0;
24655}
24656exports.shr64_lo = shr64_lo;
24657
24658},{"inherits":163,"minimalistic-assert":176}],159:[function(require,module,exports){
24659'use strict';
24660
24661var hash = require('hash.js');
24662var utils = require('minimalistic-crypto-utils');
24663var assert = require('minimalistic-assert');
24664
24665function HmacDRBG(options) {
24666 if (!(this instanceof HmacDRBG))
24667 return new HmacDRBG(options);
24668 this.hash = options.hash;
24669 this.predResist = !!options.predResist;
24670
24671 this.outLen = this.hash.outSize;
24672 this.minEntropy = options.minEntropy || this.hash.hmacStrength;
24673
24674 this._reseed = null;
24675 this.reseedInterval = null;
24676 this.K = null;
24677 this.V = null;
24678
24679 var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex');
24680 var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex');
24681 var pers = utils.toArray(options.pers, options.persEnc || 'hex');
24682 assert(entropy.length >= (this.minEntropy / 8),
24683 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
24684 this._init(entropy, nonce, pers);
24685}
24686module.exports = HmacDRBG;
24687
24688HmacDRBG.prototype._init = function init(entropy, nonce, pers) {
24689 var seed = entropy.concat(nonce).concat(pers);
24690
24691 this.K = new Array(this.outLen / 8);
24692 this.V = new Array(this.outLen / 8);
24693 for (var i = 0; i < this.V.length; i++) {
24694 this.K[i] = 0x00;
24695 this.V[i] = 0x01;
24696 }
24697
24698 this._update(seed);
24699 this._reseed = 1;
24700 this.reseedInterval = 0x1000000000000; // 2^48
24701};
24702
24703HmacDRBG.prototype._hmac = function hmac() {
24704 return new hash.hmac(this.hash, this.K);
24705};
24706
24707HmacDRBG.prototype._update = function update(seed) {
24708 var kmac = this._hmac()
24709 .update(this.V)
24710 .update([ 0x00 ]);
24711 if (seed)
24712 kmac = kmac.update(seed);
24713 this.K = kmac.digest();
24714 this.V = this._hmac().update(this.V).digest();
24715 if (!seed)
24716 return;
24717
24718 this.K = this._hmac()
24719 .update(this.V)
24720 .update([ 0x01 ])
24721 .update(seed)
24722 .digest();
24723 this.V = this._hmac().update(this.V).digest();
24724};
24725
24726HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) {
24727 // Optional entropy enc
24728 if (typeof entropyEnc !== 'string') {
24729 addEnc = add;
24730 add = entropyEnc;
24731 entropyEnc = null;
24732 }
24733
24734 entropy = utils.toArray(entropy, entropyEnc);
24735 add = utils.toArray(add, addEnc);
24736
24737 assert(entropy.length >= (this.minEntropy / 8),
24738 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits');
24739
24740 this._update(entropy.concat(add || []));
24741 this._reseed = 1;
24742};
24743
24744HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) {
24745 if (this._reseed > this.reseedInterval)
24746 throw new Error('Reseed is required');
24747
24748 // Optional encoding
24749 if (typeof enc !== 'string') {
24750 addEnc = add;
24751 add = enc;
24752 enc = null;
24753 }
24754
24755 // Optional additional data
24756 if (add) {
24757 add = utils.toArray(add, addEnc || 'hex');
24758 this._update(add);
24759 }
24760
24761 var temp = [];
24762 while (temp.length < len) {
24763 this.V = this._hmac().update(this.V).digest();
24764 temp = temp.concat(this.V);
24765 }
24766
24767 var res = temp.slice(0, len);
24768 this._update(add);
24769 this._reseed++;
24770 return utils.encode(res, enc);
24771};
24772
24773},{"hash.js":147,"minimalistic-assert":176,"minimalistic-crypto-utils":177}],160:[function(require,module,exports){
24774/**
24775 * Properly escape JSON for usage as an object literal inside of a `<script>` tag.
24776 * JS implementation of http://golang.org/pkg/encoding/json/#HTMLEscape
24777 * More info: http://timelessrepo.com/json-isnt-a-javascript-subset
24778 */
24779
24780'use strict';
24781
24782var ESCAPE_LOOKUP = {
24783 '&': '\\u0026',
24784 '>': '\\u003e',
24785 '<': '\\u003c',
24786 '\u2028': '\\u2028',
24787 '\u2029': '\\u2029'
24788};
24789
24790var ESCAPE_REGEX = /[&><\u2028\u2029]/g;
24791
24792function escaper(match) {
24793 return ESCAPE_LOOKUP[match];
24794}
24795
24796module.exports = function(obj) {
24797 return JSON.stringify(obj).replace(ESCAPE_REGEX, escaper);
24798};
24799
24800/***/
24801
24802var TERMINATORS_LOOKUP = {
24803 '\u2028': '\\u2028',
24804 '\u2029': '\\u2029'
24805};
24806
24807var TERMINATORS_REGEX = /[\u2028\u2029]/g;
24808
24809function sanitizer(match) {
24810 return TERMINATORS_LOOKUP[match];
24811}
24812
24813module.exports.sanitize = function(str) {
24814 return str.replace(TERMINATORS_REGEX, sanitizer);
24815};
24816
24817},{}],161:[function(require,module,exports){
24818exports.read = function (buffer, offset, isLE, mLen, nBytes) {
24819 var e, m
24820 var eLen = nBytes * 8 - mLen - 1
24821 var eMax = (1 << eLen) - 1
24822 var eBias = eMax >> 1
24823 var nBits = -7
24824 var i = isLE ? (nBytes - 1) : 0
24825 var d = isLE ? -1 : 1
24826 var s = buffer[offset + i]
24827
24828 i += d
24829
24830 e = s & ((1 << (-nBits)) - 1)
24831 s >>= (-nBits)
24832 nBits += eLen
24833 for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {}
24834
24835 m = e & ((1 << (-nBits)) - 1)
24836 e >>= (-nBits)
24837 nBits += mLen
24838 for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {}
24839
24840 if (e === 0) {
24841 e = 1 - eBias
24842 } else if (e === eMax) {
24843 return m ? NaN : ((s ? -1 : 1) * Infinity)
24844 } else {
24845 m = m + Math.pow(2, mLen)
24846 e = e - eBias
24847 }
24848 return (s ? -1 : 1) * m * Math.pow(2, e - mLen)
24849}
24850
24851exports.write = function (buffer, value, offset, isLE, mLen, nBytes) {
24852 var e, m, c
24853 var eLen = nBytes * 8 - mLen - 1
24854 var eMax = (1 << eLen) - 1
24855 var eBias = eMax >> 1
24856 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0)
24857 var i = isLE ? 0 : (nBytes - 1)
24858 var d = isLE ? 1 : -1
24859 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0
24860
24861 value = Math.abs(value)
24862
24863 if (isNaN(value) || value === Infinity) {
24864 m = isNaN(value) ? 1 : 0
24865 e = eMax
24866 } else {
24867 e = Math.floor(Math.log(value) / Math.LN2)
24868 if (value * (c = Math.pow(2, -e)) < 1) {
24869 e--
24870 c *= 2
24871 }
24872 if (e + eBias >= 1) {
24873 value += rt / c
24874 } else {
24875 value += rt * Math.pow(2, 1 - eBias)
24876 }
24877 if (value * c >= 2) {
24878 e++
24879 c /= 2
24880 }
24881
24882 if (e + eBias >= eMax) {
24883 m = 0
24884 e = eMax
24885 } else if (e + eBias >= 1) {
24886 m = (value * c - 1) * Math.pow(2, mLen)
24887 e = e + eBias
24888 } else {
24889 m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen)
24890 e = 0
24891 }
24892 }
24893
24894 for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {}
24895
24896 e = (e << mLen) | m
24897 eLen += mLen
24898 for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {}
24899
24900 buffer[offset + i - d] |= s * 128
24901}
24902
24903},{}],162:[function(require,module,exports){
24904
24905var indexOf = [].indexOf;
24906
24907module.exports = function(arr, obj){
24908 if (indexOf) return arr.indexOf(obj);
24909 for (var i = 0; i < arr.length; ++i) {
24910 if (arr[i] === obj) return i;
24911 }
24912 return -1;
24913};
24914},{}],163:[function(require,module,exports){
24915if (typeof Object.create === 'function') {
24916 // implementation from standard node.js 'util' module
24917 module.exports = function inherits(ctor, superCtor) {
24918 ctor.super_ = superCtor
24919 ctor.prototype = Object.create(superCtor.prototype, {
24920 constructor: {
24921 value: ctor,
24922 enumerable: false,
24923 writable: true,
24924 configurable: true
24925 }
24926 });
24927 };
24928} else {
24929 // old school shim for old browsers
24930 module.exports = function inherits(ctor, superCtor) {
24931 ctor.super_ = superCtor
24932 var TempCtor = function () {}
24933 TempCtor.prototype = superCtor.prototype
24934 ctor.prototype = new TempCtor()
24935 ctor.prototype.constructor = ctor
24936 }
24937}
24938
24939},{}],164:[function(require,module,exports){
24940/*!
24941 * Determine if an object is a Buffer
24942 *
24943 * @author Feross Aboukhadijeh <https://feross.org>
24944 * @license MIT
24945 */
24946
24947// The _isBuffer check is for Safari 5-7 support, because it's missing
24948// Object.prototype.constructor. Remove this eventually
24949module.exports = function (obj) {
24950 return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer)
24951}
24952
24953function isBuffer (obj) {
24954 return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj)
24955}
24956
24957// For Node v0.10 support. Remove this eventually.
24958function isSlowBuffer (obj) {
24959 return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0))
24960}
24961
24962},{}],165:[function(require,module,exports){
24963var toString = {}.toString;
24964
24965module.exports = Array.isArray || function (arr) {
24966 return toString.call(arr) == '[object Array]';
24967};
24968
24969},{}],166:[function(require,module,exports){
24970/*
24971 A JavaScript implementation of the SHA family of hashes, as
24972 defined in FIPS PUB 180-4 and FIPS PUB 202, as well as the corresponding
24973 HMAC implementation as defined in FIPS PUB 198a
24974
24975 Copyright Brian Turek 2008-2017
24976 Distributed under the BSD License
24977 See http://caligatio.github.com/jsSHA/ for more information
24978
24979 Several functions taken from Paul Johnston
24980*/
24981'use strict';(function(Y){function C(c,a,b){var e=0,h=[],n=0,g,l,d,f,m,q,u,r,I=!1,v=[],w=[],t,y=!1,z=!1,x=-1;b=b||{};g=b.encoding||"UTF8";t=b.numRounds||1;if(t!==parseInt(t,10)||1>t)throw Error("numRounds must a integer >= 1");if("SHA-1"===c)m=512,q=K,u=Z,f=160,r=function(a){return a.slice()};else if(0===c.lastIndexOf("SHA-",0))if(q=function(a,b){return L(a,b,c)},u=function(a,b,h,e){var k,f;if("SHA-224"===c||"SHA-256"===c)k=(b+65>>>9<<4)+15,f=16;else if("SHA-384"===c||"SHA-512"===c)k=(b+129>>>10<<
249825)+31,f=32;else throw Error("Unexpected error in SHA-2 implementation");for(;a.length<=k;)a.push(0);a[b>>>5]|=128<<24-b%32;b=b+h;a[k]=b&4294967295;a[k-1]=b/4294967296|0;h=a.length;for(b=0;b<h;b+=f)e=L(a.slice(b,b+f),e,c);if("SHA-224"===c)a=[e[0],e[1],e[2],e[3],e[4],e[5],e[6]];else if("SHA-256"===c)a=e;else if("SHA-384"===c)a=[e[0].a,e[0].b,e[1].a,e[1].b,e[2].a,e[2].b,e[3].a,e[3].b,e[4].a,e[4].b,e[5].a,e[5].b];else if("SHA-512"===c)a=[e[0].a,e[0].b,e[1].a,e[1].b,e[2].a,e[2].b,e[3].a,e[3].b,e[4].a,
24983e[4].b,e[5].a,e[5].b,e[6].a,e[6].b,e[7].a,e[7].b];else throw Error("Unexpected error in SHA-2 implementation");return a},r=function(a){return a.slice()},"SHA-224"===c)m=512,f=224;else if("SHA-256"===c)m=512,f=256;else if("SHA-384"===c)m=1024,f=384;else if("SHA-512"===c)m=1024,f=512;else throw Error("Chosen SHA variant is not supported");else if(0===c.lastIndexOf("SHA3-",0)||0===c.lastIndexOf("SHAKE",0)){var F=6;q=D;r=function(a){var c=[],e;for(e=0;5>e;e+=1)c[e]=a[e].slice();return c};x=1;if("SHA3-224"===
24984c)m=1152,f=224;else if("SHA3-256"===c)m=1088,f=256;else if("SHA3-384"===c)m=832,f=384;else if("SHA3-512"===c)m=576,f=512;else if("SHAKE128"===c)m=1344,f=-1,F=31,z=!0;else if("SHAKE256"===c)m=1088,f=-1,F=31,z=!0;else throw Error("Chosen SHA variant is not supported");u=function(a,c,e,b,h){e=m;var k=F,f,g=[],n=e>>>5,l=0,d=c>>>5;for(f=0;f<d&&c>=e;f+=n)b=D(a.slice(f,f+n),b),c-=e;a=a.slice(f);for(c%=e;a.length<n;)a.push(0);f=c>>>3;a[f>>2]^=k<<f%4*8;a[n-1]^=2147483648;for(b=D(a,b);32*g.length<h;){a=b[l%
249855][l/5|0];g.push(a.b);if(32*g.length>=h)break;g.push(a.a);l+=1;0===64*l%e&&D(null,b)}return g}}else throw Error("Chosen SHA variant is not supported");d=M(a,g,x);l=A(c);this.setHMACKey=function(a,b,h){var k;if(!0===I)throw Error("HMAC key already set");if(!0===y)throw Error("Cannot set HMAC key after calling update");if(!0===z)throw Error("SHAKE is not supported for HMAC");g=(h||{}).encoding||"UTF8";b=M(b,g,x)(a);a=b.binLen;b=b.value;k=m>>>3;h=k/4-1;if(k<a/8){for(b=u(b,a,0,A(c),f);b.length<=h;)b.push(0);
24986b[h]&=4294967040}else if(k>a/8){for(;b.length<=h;)b.push(0);b[h]&=4294967040}for(a=0;a<=h;a+=1)v[a]=b[a]^909522486,w[a]=b[a]^1549556828;l=q(v,l);e=m;I=!0};this.update=function(a){var c,b,k,f=0,g=m>>>5;c=d(a,h,n);a=c.binLen;b=c.value;c=a>>>5;for(k=0;k<c;k+=g)f+m<=a&&(l=q(b.slice(k,k+g),l),f+=m);e+=f;h=b.slice(f>>>5);n=a%m;y=!0};this.getHash=function(a,b){var k,g,d,m;if(!0===I)throw Error("Cannot call getHash after setting HMAC key");d=N(b);if(!0===z){if(-1===d.shakeLen)throw Error("shakeLen must be specified in options");
24987f=d.shakeLen}switch(a){case "HEX":k=function(a){return O(a,f,x,d)};break;case "B64":k=function(a){return P(a,f,x,d)};break;case "BYTES":k=function(a){return Q(a,f,x)};break;case "ARRAYBUFFER":try{g=new ArrayBuffer(0)}catch(p){throw Error("ARRAYBUFFER not supported by this environment");}k=function(a){return R(a,f,x)};break;default:throw Error("format must be HEX, B64, BYTES, or ARRAYBUFFER");}m=u(h.slice(),n,e,r(l),f);for(g=1;g<t;g+=1)!0===z&&0!==f%32&&(m[m.length-1]&=16777215>>>24-f%32),m=u(m,f,
249880,A(c),f);return k(m)};this.getHMAC=function(a,b){var k,g,d,p;if(!1===I)throw Error("Cannot call getHMAC without first setting HMAC key");d=N(b);switch(a){case "HEX":k=function(a){return O(a,f,x,d)};break;case "B64":k=function(a){return P(a,f,x,d)};break;case "BYTES":k=function(a){return Q(a,f,x)};break;case "ARRAYBUFFER":try{k=new ArrayBuffer(0)}catch(v){throw Error("ARRAYBUFFER not supported by this environment");}k=function(a){return R(a,f,x)};break;default:throw Error("outputFormat must be HEX, B64, BYTES, or ARRAYBUFFER");
24989}g=u(h.slice(),n,e,r(l),f);p=q(w,A(c));p=u(g,f,m,p,f);return k(p)}}function b(c,a){this.a=c;this.b=a}function O(c,a,b,e){var h="";a/=8;var n,g,d;d=-1===b?3:0;for(n=0;n<a;n+=1)g=c[n>>>2]>>>8*(d+n%4*b),h+="0123456789abcdef".charAt(g>>>4&15)+"0123456789abcdef".charAt(g&15);return e.outputUpper?h.toUpperCase():h}function P(c,a,b,e){var h="",n=a/8,g,d,p,f;f=-1===b?3:0;for(g=0;g<n;g+=3)for(d=g+1<n?c[g+1>>>2]:0,p=g+2<n?c[g+2>>>2]:0,p=(c[g>>>2]>>>8*(f+g%4*b)&255)<<16|(d>>>8*(f+(g+1)%4*b)&255)<<8|p>>>8*(f+
24990(g+2)%4*b)&255,d=0;4>d;d+=1)8*g+6*d<=a?h+="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".charAt(p>>>6*(3-d)&63):h+=e.b64Pad;return h}function Q(c,a,b){var e="";a/=8;var h,d,g;g=-1===b?3:0;for(h=0;h<a;h+=1)d=c[h>>>2]>>>8*(g+h%4*b)&255,e+=String.fromCharCode(d);return e}function R(c,a,b){a/=8;var e,h=new ArrayBuffer(a),d,g;g=new Uint8Array(h);d=-1===b?3:0;for(e=0;e<a;e+=1)g[e]=c[e>>>2]>>>8*(d+e%4*b)&255;return h}function N(c){var a={outputUpper:!1,b64Pad:"=",shakeLen:-1};c=c||{};
24991a.outputUpper=c.outputUpper||!1;!0===c.hasOwnProperty("b64Pad")&&(a.b64Pad=c.b64Pad);if(!0===c.hasOwnProperty("shakeLen")){if(0!==c.shakeLen%8)throw Error("shakeLen must be a multiple of 8");a.shakeLen=c.shakeLen}if("boolean"!==typeof a.outputUpper)throw Error("Invalid outputUpper formatting option");if("string"!==typeof a.b64Pad)throw Error("Invalid b64Pad formatting option");return a}function M(c,a,b){switch(a){case "UTF8":case "UTF16BE":case "UTF16LE":break;default:throw Error("encoding must be UTF8, UTF16BE, or UTF16LE");
24992}switch(c){case "HEX":c=function(a,c,d){var g=a.length,l,p,f,m,q,u;if(0!==g%2)throw Error("String of HEX type must be in byte increments");c=c||[0];d=d||0;q=d>>>3;u=-1===b?3:0;for(l=0;l<g;l+=2){p=parseInt(a.substr(l,2),16);if(isNaN(p))throw Error("String of HEX type contains invalid characters");m=(l>>>1)+q;for(f=m>>>2;c.length<=f;)c.push(0);c[f]|=p<<8*(u+m%4*b)}return{value:c,binLen:4*g+d}};break;case "TEXT":c=function(c,h,d){var g,l,p=0,f,m,q,u,r,t;h=h||[0];d=d||0;q=d>>>3;if("UTF8"===a)for(t=-1===
24993b?3:0,f=0;f<c.length;f+=1)for(g=c.charCodeAt(f),l=[],128>g?l.push(g):2048>g?(l.push(192|g>>>6),l.push(128|g&63)):55296>g||57344<=g?l.push(224|g>>>12,128|g>>>6&63,128|g&63):(f+=1,g=65536+((g&1023)<<10|c.charCodeAt(f)&1023),l.push(240|g>>>18,128|g>>>12&63,128|g>>>6&63,128|g&63)),m=0;m<l.length;m+=1){r=p+q;for(u=r>>>2;h.length<=u;)h.push(0);h[u]|=l[m]<<8*(t+r%4*b);p+=1}else if("UTF16BE"===a||"UTF16LE"===a)for(t=-1===b?2:0,l="UTF16LE"===a&&1!==b||"UTF16LE"!==a&&1===b,f=0;f<c.length;f+=1){g=c.charCodeAt(f);
24994!0===l&&(m=g&255,g=m<<8|g>>>8);r=p+q;for(u=r>>>2;h.length<=u;)h.push(0);h[u]|=g<<8*(t+r%4*b);p+=2}return{value:h,binLen:8*p+d}};break;case "B64":c=function(a,c,d){var g=0,l,p,f,m,q,u,r,t;if(-1===a.search(/^[a-zA-Z0-9=+\/]+$/))throw Error("Invalid character in base-64 string");p=a.indexOf("=");a=a.replace(/\=/g,"");if(-1!==p&&p<a.length)throw Error("Invalid '=' found in base-64 string");c=c||[0];d=d||0;u=d>>>3;t=-1===b?3:0;for(p=0;p<a.length;p+=4){q=a.substr(p,4);for(f=m=0;f<q.length;f+=1)l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".indexOf(q[f]),
24995m|=l<<18-6*f;for(f=0;f<q.length-1;f+=1){r=g+u;for(l=r>>>2;c.length<=l;)c.push(0);c[l]|=(m>>>16-8*f&255)<<8*(t+r%4*b);g+=1}}return{value:c,binLen:8*g+d}};break;case "BYTES":c=function(a,c,d){var g,l,p,f,m,q;c=c||[0];d=d||0;p=d>>>3;q=-1===b?3:0;for(l=0;l<a.length;l+=1)g=a.charCodeAt(l),m=l+p,f=m>>>2,c.length<=f&&c.push(0),c[f]|=g<<8*(q+m%4*b);return{value:c,binLen:8*a.length+d}};break;case "ARRAYBUFFER":try{c=new ArrayBuffer(0)}catch(e){throw Error("ARRAYBUFFER not supported by this environment");}c=
24996function(a,c,d){var g,l,p,f,m,q;c=c||[0];d=d||0;l=d>>>3;m=-1===b?3:0;q=new Uint8Array(a);for(g=0;g<a.byteLength;g+=1)f=g+l,p=f>>>2,c.length<=p&&c.push(0),c[p]|=q[g]<<8*(m+f%4*b);return{value:c,binLen:8*a.byteLength+d}};break;default:throw Error("format must be HEX, TEXT, B64, BYTES, or ARRAYBUFFER");}return c}function y(c,a){return c<<a|c>>>32-a}function S(c,a){return 32<a?(a-=32,new b(c.b<<a|c.a>>>32-a,c.a<<a|c.b>>>32-a)):0!==a?new b(c.a<<a|c.b>>>32-a,c.b<<a|c.a>>>32-a):c}function w(c,a){return c>>>
24997a|c<<32-a}function t(c,a){var k=null,k=new b(c.a,c.b);return k=32>=a?new b(k.a>>>a|k.b<<32-a&4294967295,k.b>>>a|k.a<<32-a&4294967295):new b(k.b>>>a-32|k.a<<64-a&4294967295,k.a>>>a-32|k.b<<64-a&4294967295)}function T(c,a){var k=null;return k=32>=a?new b(c.a>>>a,c.b>>>a|c.a<<32-a&4294967295):new b(0,c.a>>>a-32)}function aa(c,a,b){return c&a^~c&b}function ba(c,a,k){return new b(c.a&a.a^~c.a&k.a,c.b&a.b^~c.b&k.b)}function U(c,a,b){return c&a^c&b^a&b}function ca(c,a,k){return new b(c.a&a.a^c.a&k.a^a.a&
24998k.a,c.b&a.b^c.b&k.b^a.b&k.b)}function da(c){return w(c,2)^w(c,13)^w(c,22)}function ea(c){var a=t(c,28),k=t(c,34);c=t(c,39);return new b(a.a^k.a^c.a,a.b^k.b^c.b)}function fa(c){return w(c,6)^w(c,11)^w(c,25)}function ga(c){var a=t(c,14),k=t(c,18);c=t(c,41);return new b(a.a^k.a^c.a,a.b^k.b^c.b)}function ha(c){return w(c,7)^w(c,18)^c>>>3}function ia(c){var a=t(c,1),k=t(c,8);c=T(c,7);return new b(a.a^k.a^c.a,a.b^k.b^c.b)}function ja(c){return w(c,17)^w(c,19)^c>>>10}function ka(c){var a=t(c,19),k=t(c,61);
24999c=T(c,6);return new b(a.a^k.a^c.a,a.b^k.b^c.b)}function G(c,a){var b=(c&65535)+(a&65535);return((c>>>16)+(a>>>16)+(b>>>16)&65535)<<16|b&65535}function la(c,a,b,e){var h=(c&65535)+(a&65535)+(b&65535)+(e&65535);return((c>>>16)+(a>>>16)+(b>>>16)+(e>>>16)+(h>>>16)&65535)<<16|h&65535}function H(c,a,b,e,h){var d=(c&65535)+(a&65535)+(b&65535)+(e&65535)+(h&65535);return((c>>>16)+(a>>>16)+(b>>>16)+(e>>>16)+(h>>>16)+(d>>>16)&65535)<<16|d&65535}function ma(c,a){var d,e,h;d=(c.b&65535)+(a.b&65535);e=(c.b>>>16)+
25000(a.b>>>16)+(d>>>16);h=(e&65535)<<16|d&65535;d=(c.a&65535)+(a.a&65535)+(e>>>16);e=(c.a>>>16)+(a.a>>>16)+(d>>>16);return new b((e&65535)<<16|d&65535,h)}function na(c,a,d,e){var h,n,g;h=(c.b&65535)+(a.b&65535)+(d.b&65535)+(e.b&65535);n=(c.b>>>16)+(a.b>>>16)+(d.b>>>16)+(e.b>>>16)+(h>>>16);g=(n&65535)<<16|h&65535;h=(c.a&65535)+(a.a&65535)+(d.a&65535)+(e.a&65535)+(n>>>16);n=(c.a>>>16)+(a.a>>>16)+(d.a>>>16)+(e.a>>>16)+(h>>>16);return new b((n&65535)<<16|h&65535,g)}function oa(c,a,d,e,h){var n,g,l;n=(c.b&
2500165535)+(a.b&65535)+(d.b&65535)+(e.b&65535)+(h.b&65535);g=(c.b>>>16)+(a.b>>>16)+(d.b>>>16)+(e.b>>>16)+(h.b>>>16)+(n>>>16);l=(g&65535)<<16|n&65535;n=(c.a&65535)+(a.a&65535)+(d.a&65535)+(e.a&65535)+(h.a&65535)+(g>>>16);g=(c.a>>>16)+(a.a>>>16)+(d.a>>>16)+(e.a>>>16)+(h.a>>>16)+(n>>>16);return new b((g&65535)<<16|n&65535,l)}function B(c,a){return new b(c.a^a.a,c.b^a.b)}function A(c){var a=[],d;if("SHA-1"===c)a=[1732584193,4023233417,2562383102,271733878,3285377520];else if(0===c.lastIndexOf("SHA-",0))switch(a=
25002[3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428],d=[1779033703,3144134277,1013904242,2773480762,1359893119,2600822924,528734635,1541459225],c){case "SHA-224":break;case "SHA-256":a=d;break;case "SHA-384":a=[new b(3418070365,a[0]),new b(1654270250,a[1]),new b(2438529370,a[2]),new b(355462360,a[3]),new b(1731405415,a[4]),new b(41048885895,a[5]),new b(3675008525,a[6]),new b(1203062813,a[7])];break;case "SHA-512":a=[new b(d[0],4089235720),new b(d[1],2227873595),
25003new b(d[2],4271175723),new b(d[3],1595750129),new b(d[4],2917565137),new b(d[5],725511199),new b(d[6],4215389547),new b(d[7],327033209)];break;default:throw Error("Unknown SHA variant");}else if(0===c.lastIndexOf("SHA3-",0)||0===c.lastIndexOf("SHAKE",0))for(c=0;5>c;c+=1)a[c]=[new b(0,0),new b(0,0),new b(0,0),new b(0,0),new b(0,0)];else throw Error("No SHA variants supported");return a}function K(c,a){var b=[],e,d,n,g,l,p,f;e=a[0];d=a[1];n=a[2];g=a[3];l=a[4];for(f=0;80>f;f+=1)b[f]=16>f?c[f]:y(b[f-
250043]^b[f-8]^b[f-14]^b[f-16],1),p=20>f?H(y(e,5),d&n^~d&g,l,1518500249,b[f]):40>f?H(y(e,5),d^n^g,l,1859775393,b[f]):60>f?H(y(e,5),U(d,n,g),l,2400959708,b[f]):H(y(e,5),d^n^g,l,3395469782,b[f]),l=g,g=n,n=y(d,30),d=e,e=p;a[0]=G(e,a[0]);a[1]=G(d,a[1]);a[2]=G(n,a[2]);a[3]=G(g,a[3]);a[4]=G(l,a[4]);return a}function Z(c,a,b,e){var d;for(d=(a+65>>>9<<4)+15;c.length<=d;)c.push(0);c[a>>>5]|=128<<24-a%32;a+=b;c[d]=a&4294967295;c[d-1]=a/4294967296|0;a=c.length;for(d=0;d<a;d+=16)e=K(c.slice(d,d+16),e);return e}function L(c,
25005a,k){var e,h,n,g,l,p,f,m,q,u,r,t,v,w,y,A,z,x,F,B,C,D,E=[],J;if("SHA-224"===k||"SHA-256"===k)u=64,t=1,D=Number,v=G,w=la,y=H,A=ha,z=ja,x=da,F=fa,C=U,B=aa,J=d;else if("SHA-384"===k||"SHA-512"===k)u=80,t=2,D=b,v=ma,w=na,y=oa,A=ia,z=ka,x=ea,F=ga,C=ca,B=ba,J=V;else throw Error("Unexpected error in SHA-2 implementation");k=a[0];e=a[1];h=a[2];n=a[3];g=a[4];l=a[5];p=a[6];f=a[7];for(r=0;r<u;r+=1)16>r?(q=r*t,m=c.length<=q?0:c[q],q=c.length<=q+1?0:c[q+1],E[r]=new D(m,q)):E[r]=w(z(E[r-2]),E[r-7],A(E[r-15]),E[r-
2500616]),m=y(f,F(g),B(g,l,p),J[r],E[r]),q=v(x(k),C(k,e,h)),f=p,p=l,l=g,g=v(n,m),n=h,h=e,e=k,k=v(m,q);a[0]=v(k,a[0]);a[1]=v(e,a[1]);a[2]=v(h,a[2]);a[3]=v(n,a[3]);a[4]=v(g,a[4]);a[5]=v(l,a[5]);a[6]=v(p,a[6]);a[7]=v(f,a[7]);return a}function D(c,a){var d,e,h,n,g=[],l=[];if(null!==c)for(e=0;e<c.length;e+=2)a[(e>>>1)%5][(e>>>1)/5|0]=B(a[(e>>>1)%5][(e>>>1)/5|0],new b(c[e+1],c[e]));for(d=0;24>d;d+=1){n=A("SHA3-");for(e=0;5>e;e+=1){h=a[e][0];var p=a[e][1],f=a[e][2],m=a[e][3],q=a[e][4];g[e]=new b(h.a^p.a^f.a^
25007m.a^q.a,h.b^p.b^f.b^m.b^q.b)}for(e=0;5>e;e+=1)l[e]=B(g[(e+4)%5],S(g[(e+1)%5],1));for(e=0;5>e;e+=1)for(h=0;5>h;h+=1)a[e][h]=B(a[e][h],l[e]);for(e=0;5>e;e+=1)for(h=0;5>h;h+=1)n[h][(2*e+3*h)%5]=S(a[e][h],W[e][h]);for(e=0;5>e;e+=1)for(h=0;5>h;h+=1)a[e][h]=B(n[e][h],new b(~n[(e+1)%5][h].a&n[(e+2)%5][h].a,~n[(e+1)%5][h].b&n[(e+2)%5][h].b));a[0][0]=B(a[0][0],X[d])}return a}var d,V,W,X;d=[1116352408,1899447441,3049323471,3921009573,961987163,1508970993,2453635748,2870763221,3624381080,310598401,607225278,
250081426881987,1925078388,2162078206,2614888103,3248222580,3835390401,4022224774,264347078,604807628,770255983,1249150122,1555081692,1996064986,2554220882,2821834349,2952996808,3210313671,3336571891,3584528711,113926993,338241895,666307205,773529912,1294757372,1396182291,1695183700,1986661051,2177026350,2456956037,2730485921,2820302411,3259730800,3345764771,3516065817,3600352804,4094571909,275423344,430227734,506948616,659060556,883997877,958139571,1322822218,1537002063,1747873779,1955562222,2024104815,
250092227730452,2361852424,2428436474,2756734187,3204031479,3329325298];V=[new b(d[0],3609767458),new b(d[1],602891725),new b(d[2],3964484399),new b(d[3],2173295548),new b(d[4],4081628472),new b(d[5],3053834265),new b(d[6],2937671579),new b(d[7],3664609560),new b(d[8],2734883394),new b(d[9],1164996542),new b(d[10],1323610764),new b(d[11],3590304994),new b(d[12],4068182383),new b(d[13],991336113),new b(d[14],633803317),new b(d[15],3479774868),new b(d[16],2666613458),new b(d[17],944711139),new b(d[18],2341262773),
25010new b(d[19],2007800933),new b(d[20],1495990901),new b(d[21],1856431235),new b(d[22],3175218132),new b(d[23],2198950837),new b(d[24],3999719339),new b(d[25],766784016),new b(d[26],2566594879),new b(d[27],3203337956),new b(d[28],1034457026),new b(d[29],2466948901),new b(d[30],3758326383),new b(d[31],168717936),new b(d[32],1188179964),new b(d[33],1546045734),new b(d[34],1522805485),new b(d[35],2643833823),new b(d[36],2343527390),new b(d[37],1014477480),new b(d[38],1206759142),new b(d[39],344077627),
25011new b(d[40],1290863460),new b(d[41],3158454273),new b(d[42],3505952657),new b(d[43],106217008),new b(d[44],3606008344),new b(d[45],1432725776),new b(d[46],1467031594),new b(d[47],851169720),new b(d[48],3100823752),new b(d[49],1363258195),new b(d[50],3750685593),new b(d[51],3785050280),new b(d[52],3318307427),new b(d[53],3812723403),new b(d[54],2003034995),new b(d[55],3602036899),new b(d[56],1575990012),new b(d[57],1125592928),new b(d[58],2716904306),new b(d[59],442776044),new b(d[60],593698344),new b(d[61],
250123733110249),new b(d[62],2999351573),new b(d[63],3815920427),new b(3391569614,3928383900),new b(3515267271,566280711),new b(3940187606,3454069534),new b(4118630271,4000239992),new b(116418474,1914138554),new b(174292421,2731055270),new b(289380356,3203993006),new b(460393269,320620315),new b(685471733,587496836),new b(852142971,1086792851),new b(1017036298,365543100),new b(1126000580,2618297676),new b(1288033470,3409855158),new b(1501505948,4234509866),new b(1607167915,987167468),new b(1816402316,
250131246189591)];X=[new b(0,1),new b(0,32898),new b(2147483648,32906),new b(2147483648,2147516416),new b(0,32907),new b(0,2147483649),new b(2147483648,2147516545),new b(2147483648,32777),new b(0,138),new b(0,136),new b(0,2147516425),new b(0,2147483658),new b(0,2147516555),new b(2147483648,139),new b(2147483648,32905),new b(2147483648,32771),new b(2147483648,32770),new b(2147483648,128),new b(0,32778),new b(2147483648,2147483658),new b(2147483648,2147516545),new b(2147483648,32896),new b(0,2147483649),
25014new b(2147483648,2147516424)];W=[[0,36,3,41,18],[1,44,10,45,2],[62,6,43,15,61],[28,55,25,21,56],[27,20,39,8,14]];"function"===typeof define&&define.amd?define(function(){return C}):"undefined"!==typeof exports?("undefined"!==typeof module&&module.exports&&(module.exports=C),exports=C):Y.jsSHA=C})(this);
25015
25016},{}],167:[function(require,module,exports){
25017'use strict'
25018module.exports = require('./lib/api')(require('./lib/keccak'))
25019
25020},{"./lib/api":168,"./lib/keccak":172}],168:[function(require,module,exports){
25021'use strict'
25022var createKeccak = require('./keccak')
25023var createShake = require('./shake')
25024
25025module.exports = function (KeccakState) {
25026 var Keccak = createKeccak(KeccakState)
25027 var Shake = createShake(KeccakState)
25028
25029 return function (algorithm, options) {
25030 var hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm
25031 switch (hash) {
25032 case 'keccak224': return new Keccak(1152, 448, null, 224, options)
25033 case 'keccak256': return new Keccak(1088, 512, null, 256, options)
25034 case 'keccak384': return new Keccak(832, 768, null, 384, options)
25035 case 'keccak512': return new Keccak(576, 1024, null, 512, options)
25036
25037 case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options)
25038 case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options)
25039 case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options)
25040 case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options)
25041
25042 case 'shake128': return new Shake(1344, 256, 0x1f, options)
25043 case 'shake256': return new Shake(1088, 512, 0x1f, options)
25044
25045 default: throw new Error('Invald algorithm: ' + algorithm)
25046 }
25047 }
25048}
25049
25050},{"./keccak":169,"./shake":170}],169:[function(require,module,exports){
25051'use strict'
25052var Buffer = require('safe-buffer').Buffer
25053var Transform = require('stream').Transform
25054var inherits = require('inherits')
25055
25056module.exports = function (KeccakState) {
25057 function Keccak (rate, capacity, delimitedSuffix, hashBitLength, options) {
25058 Transform.call(this, options)
25059
25060 this._rate = rate
25061 this._capacity = capacity
25062 this._delimitedSuffix = delimitedSuffix
25063 this._hashBitLength = hashBitLength
25064 this._options = options
25065
25066 this._state = new KeccakState()
25067 this._state.initialize(rate, capacity)
25068 this._finalized = false
25069 }
25070
25071 inherits(Keccak, Transform)
25072
25073 Keccak.prototype._transform = function (chunk, encoding, callback) {
25074 var error = null
25075 try {
25076 this.update(chunk, encoding)
25077 } catch (err) {
25078 error = err
25079 }
25080
25081 callback(error)
25082 }
25083
25084 Keccak.prototype._flush = function (callback) {
25085 var error = null
25086 try {
25087 this.push(this.digest())
25088 } catch (err) {
25089 error = err
25090 }
25091
25092 callback(error)
25093 }
25094
25095 Keccak.prototype.update = function (data, encoding) {
25096 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
25097 if (this._finalized) throw new Error('Digest already called')
25098 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
25099
25100 this._state.absorb(data)
25101
25102 return this
25103 }
25104
25105 Keccak.prototype.digest = function (encoding) {
25106 if (this._finalized) throw new Error('Digest already called')
25107 this._finalized = true
25108
25109 if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix)
25110 var digest = this._state.squeeze(this._hashBitLength / 8)
25111 if (encoding !== undefined) digest = digest.toString(encoding)
25112
25113 this._resetState()
25114
25115 return digest
25116 }
25117
25118 // remove result from memory
25119 Keccak.prototype._resetState = function () {
25120 this._state.initialize(this._rate, this._capacity)
25121 return this
25122 }
25123
25124 // because sometimes we need hash right now and little later
25125 Keccak.prototype._clone = function () {
25126 var clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options)
25127 this._state.copy(clone._state)
25128 clone._finalized = this._finalized
25129
25130 return clone
25131 }
25132
25133 return Keccak
25134}
25135
25136},{"inherits":163,"safe-buffer":247,"stream":263}],170:[function(require,module,exports){
25137'use strict'
25138var Buffer = require('safe-buffer').Buffer
25139var Transform = require('stream').Transform
25140var inherits = require('inherits')
25141
25142module.exports = function (KeccakState) {
25143 function Shake (rate, capacity, delimitedSuffix, options) {
25144 Transform.call(this, options)
25145
25146 this._rate = rate
25147 this._capacity = capacity
25148 this._delimitedSuffix = delimitedSuffix
25149 this._options = options
25150
25151 this._state = new KeccakState()
25152 this._state.initialize(rate, capacity)
25153 this._finalized = false
25154 }
25155
25156 inherits(Shake, Transform)
25157
25158 Shake.prototype._transform = function (chunk, encoding, callback) {
25159 var error = null
25160 try {
25161 this.update(chunk, encoding)
25162 } catch (err) {
25163 error = err
25164 }
25165
25166 callback(error)
25167 }
25168
25169 Shake.prototype._flush = function () {}
25170
25171 Shake.prototype._read = function (size) {
25172 this.push(this.squeeze(size))
25173 }
25174
25175 Shake.prototype.update = function (data, encoding) {
25176 if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer')
25177 if (this._finalized) throw new Error('Squeeze already called')
25178 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
25179
25180 this._state.absorb(data)
25181
25182 return this
25183 }
25184
25185 Shake.prototype.squeeze = function (dataByteLength, encoding) {
25186 if (!this._finalized) {
25187 this._finalized = true
25188 this._state.absorbLastFewBits(this._delimitedSuffix)
25189 }
25190
25191 var data = this._state.squeeze(dataByteLength)
25192 if (encoding !== undefined) data = data.toString(encoding)
25193
25194 return data
25195 }
25196
25197 Shake.prototype._resetState = function () {
25198 this._state.initialize(this._rate, this._capacity)
25199 return this
25200 }
25201
25202 Shake.prototype._clone = function () {
25203 var clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options)
25204 this._state.copy(clone._state)
25205 clone._finalized = this._finalized
25206
25207 return clone
25208 }
25209
25210 return Shake
25211}
25212
25213},{"inherits":163,"safe-buffer":247,"stream":263}],171:[function(require,module,exports){
25214'use strict'
25215var P1600_ROUND_CONSTANTS = [1, 0, 32898, 0, 32906, 2147483648, 2147516416, 2147483648, 32907, 0, 2147483649, 0, 2147516545, 2147483648, 32777, 2147483648, 138, 0, 136, 0, 2147516425, 0, 2147483658, 0, 2147516555, 0, 139, 2147483648, 32905, 2147483648, 32771, 2147483648, 32770, 2147483648, 128, 2147483648, 32778, 0, 2147483658, 2147483648, 2147516545, 2147483648, 32896, 2147483648, 2147483649, 0, 2147516424, 2147483648]
25216
25217exports.p1600 = function (s) {
25218 for (var round = 0; round < 24; ++round) {
25219 // theta
25220 var lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40]
25221 var hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41]
25222 var lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42]
25223 var hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43]
25224 var lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44]
25225 var hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45]
25226 var lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46]
25227 var hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47]
25228 var lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48]
25229 var hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49]
25230
25231 var lo = lo4 ^ (lo1 << 1 | hi1 >>> 31)
25232 var hi = hi4 ^ (hi1 << 1 | lo1 >>> 31)
25233 var t1slo0 = s[0] ^ lo
25234 var t1shi0 = s[1] ^ hi
25235 var t1slo5 = s[10] ^ lo
25236 var t1shi5 = s[11] ^ hi
25237 var t1slo10 = s[20] ^ lo
25238 var t1shi10 = s[21] ^ hi
25239 var t1slo15 = s[30] ^ lo
25240 var t1shi15 = s[31] ^ hi
25241 var t1slo20 = s[40] ^ lo
25242 var t1shi20 = s[41] ^ hi
25243 lo = lo0 ^ (lo2 << 1 | hi2 >>> 31)
25244 hi = hi0 ^ (hi2 << 1 | lo2 >>> 31)
25245 var t1slo1 = s[2] ^ lo
25246 var t1shi1 = s[3] ^ hi
25247 var t1slo6 = s[12] ^ lo
25248 var t1shi6 = s[13] ^ hi
25249 var t1slo11 = s[22] ^ lo
25250 var t1shi11 = s[23] ^ hi
25251 var t1slo16 = s[32] ^ lo
25252 var t1shi16 = s[33] ^ hi
25253 var t1slo21 = s[42] ^ lo
25254 var t1shi21 = s[43] ^ hi
25255 lo = lo1 ^ (lo3 << 1 | hi3 >>> 31)
25256 hi = hi1 ^ (hi3 << 1 | lo3 >>> 31)
25257 var t1slo2 = s[4] ^ lo
25258 var t1shi2 = s[5] ^ hi
25259 var t1slo7 = s[14] ^ lo
25260 var t1shi7 = s[15] ^ hi
25261 var t1slo12 = s[24] ^ lo
25262 var t1shi12 = s[25] ^ hi
25263 var t1slo17 = s[34] ^ lo
25264 var t1shi17 = s[35] ^ hi
25265 var t1slo22 = s[44] ^ lo
25266 var t1shi22 = s[45] ^ hi
25267 lo = lo2 ^ (lo4 << 1 | hi4 >>> 31)
25268 hi = hi2 ^ (hi4 << 1 | lo4 >>> 31)
25269 var t1slo3 = s[6] ^ lo
25270 var t1shi3 = s[7] ^ hi
25271 var t1slo8 = s[16] ^ lo
25272 var t1shi8 = s[17] ^ hi
25273 var t1slo13 = s[26] ^ lo
25274 var t1shi13 = s[27] ^ hi
25275 var t1slo18 = s[36] ^ lo
25276 var t1shi18 = s[37] ^ hi
25277 var t1slo23 = s[46] ^ lo
25278 var t1shi23 = s[47] ^ hi
25279 lo = lo3 ^ (lo0 << 1 | hi0 >>> 31)
25280 hi = hi3 ^ (hi0 << 1 | lo0 >>> 31)
25281 var t1slo4 = s[8] ^ lo
25282 var t1shi4 = s[9] ^ hi
25283 var t1slo9 = s[18] ^ lo
25284 var t1shi9 = s[19] ^ hi
25285 var t1slo14 = s[28] ^ lo
25286 var t1shi14 = s[29] ^ hi
25287 var t1slo19 = s[38] ^ lo
25288 var t1shi19 = s[39] ^ hi
25289 var t1slo24 = s[48] ^ lo
25290 var t1shi24 = s[49] ^ hi
25291
25292 // rho & pi
25293 var t2slo0 = t1slo0
25294 var t2shi0 = t1shi0
25295 var t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28)
25296 var t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28)
25297 var t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29)
25298 var t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29)
25299 var t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23)
25300 var t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23)
25301 var t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14)
25302 var t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14)
25303 var t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31)
25304 var t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31)
25305 var t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20)
25306 var t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20)
25307 var t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22)
25308 var t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22)
25309 var t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19)
25310 var t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19)
25311 var t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30)
25312 var t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30)
25313 var t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2)
25314 var t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2)
25315 var t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26)
25316 var t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26)
25317 var t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21)
25318 var t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21)
25319 var t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17)
25320 var t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17)
25321 var t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3)
25322 var t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3)
25323 var t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4)
25324 var t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4)
25325 var t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9)
25326 var t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9)
25327 var t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7)
25328 var t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7)
25329 var t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11)
25330 var t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11)
25331 var t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8)
25332 var t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8)
25333 var t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5)
25334 var t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5)
25335 var t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12)
25336 var t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12)
25337 var t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25)
25338 var t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25)
25339 var t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24)
25340 var t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24)
25341 var t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18)
25342 var t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18)
25343
25344 // chi
25345 s[0] = t2slo0 ^ (~t2slo1 & t2slo2)
25346 s[1] = t2shi0 ^ (~t2shi1 & t2shi2)
25347 s[10] = t2slo5 ^ (~t2slo6 & t2slo7)
25348 s[11] = t2shi5 ^ (~t2shi6 & t2shi7)
25349 s[20] = t2slo10 ^ (~t2slo11 & t2slo12)
25350 s[21] = t2shi10 ^ (~t2shi11 & t2shi12)
25351 s[30] = t2slo15 ^ (~t2slo16 & t2slo17)
25352 s[31] = t2shi15 ^ (~t2shi16 & t2shi17)
25353 s[40] = t2slo20 ^ (~t2slo21 & t2slo22)
25354 s[41] = t2shi20 ^ (~t2shi21 & t2shi22)
25355 s[2] = t2slo1 ^ (~t2slo2 & t2slo3)
25356 s[3] = t2shi1 ^ (~t2shi2 & t2shi3)
25357 s[12] = t2slo6 ^ (~t2slo7 & t2slo8)
25358 s[13] = t2shi6 ^ (~t2shi7 & t2shi8)
25359 s[22] = t2slo11 ^ (~t2slo12 & t2slo13)
25360 s[23] = t2shi11 ^ (~t2shi12 & t2shi13)
25361 s[32] = t2slo16 ^ (~t2slo17 & t2slo18)
25362 s[33] = t2shi16 ^ (~t2shi17 & t2shi18)
25363 s[42] = t2slo21 ^ (~t2slo22 & t2slo23)
25364 s[43] = t2shi21 ^ (~t2shi22 & t2shi23)
25365 s[4] = t2slo2 ^ (~t2slo3 & t2slo4)
25366 s[5] = t2shi2 ^ (~t2shi3 & t2shi4)
25367 s[14] = t2slo7 ^ (~t2slo8 & t2slo9)
25368 s[15] = t2shi7 ^ (~t2shi8 & t2shi9)
25369 s[24] = t2slo12 ^ (~t2slo13 & t2slo14)
25370 s[25] = t2shi12 ^ (~t2shi13 & t2shi14)
25371 s[34] = t2slo17 ^ (~t2slo18 & t2slo19)
25372 s[35] = t2shi17 ^ (~t2shi18 & t2shi19)
25373 s[44] = t2slo22 ^ (~t2slo23 & t2slo24)
25374 s[45] = t2shi22 ^ (~t2shi23 & t2shi24)
25375 s[6] = t2slo3 ^ (~t2slo4 & t2slo0)
25376 s[7] = t2shi3 ^ (~t2shi4 & t2shi0)
25377 s[16] = t2slo8 ^ (~t2slo9 & t2slo5)
25378 s[17] = t2shi8 ^ (~t2shi9 & t2shi5)
25379 s[26] = t2slo13 ^ (~t2slo14 & t2slo10)
25380 s[27] = t2shi13 ^ (~t2shi14 & t2shi10)
25381 s[36] = t2slo18 ^ (~t2slo19 & t2slo15)
25382 s[37] = t2shi18 ^ (~t2shi19 & t2shi15)
25383 s[46] = t2slo23 ^ (~t2slo24 & t2slo20)
25384 s[47] = t2shi23 ^ (~t2shi24 & t2shi20)
25385 s[8] = t2slo4 ^ (~t2slo0 & t2slo1)
25386 s[9] = t2shi4 ^ (~t2shi0 & t2shi1)
25387 s[18] = t2slo9 ^ (~t2slo5 & t2slo6)
25388 s[19] = t2shi9 ^ (~t2shi5 & t2shi6)
25389 s[28] = t2slo14 ^ (~t2slo10 & t2slo11)
25390 s[29] = t2shi14 ^ (~t2shi10 & t2shi11)
25391 s[38] = t2slo19 ^ (~t2slo15 & t2slo16)
25392 s[39] = t2shi19 ^ (~t2shi15 & t2shi16)
25393 s[48] = t2slo24 ^ (~t2slo20 & t2slo21)
25394 s[49] = t2shi24 ^ (~t2shi20 & t2shi21)
25395
25396 // iota
25397 s[0] ^= P1600_ROUND_CONSTANTS[round * 2]
25398 s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1]
25399 }
25400}
25401
25402},{}],172:[function(require,module,exports){
25403'use strict'
25404var Buffer = require('safe-buffer').Buffer
25405var keccakState = require('./keccak-state-unroll')
25406
25407function Keccak () {
25408 // much faster than `new Array(50)`
25409 this.state = [
25410 0, 0, 0, 0, 0,
25411 0, 0, 0, 0, 0,
25412 0, 0, 0, 0, 0,
25413 0, 0, 0, 0, 0,
25414 0, 0, 0, 0, 0
25415 ]
25416
25417 this.blockSize = null
25418 this.count = 0
25419 this.squeezing = false
25420}
25421
25422Keccak.prototype.initialize = function (rate, capacity) {
25423 for (var i = 0; i < 50; ++i) this.state[i] = 0
25424 this.blockSize = rate / 8
25425 this.count = 0
25426 this.squeezing = false
25427}
25428
25429Keccak.prototype.absorb = function (data) {
25430 for (var i = 0; i < data.length; ++i) {
25431 this.state[~~(this.count / 4)] ^= data[i] << (8 * (this.count % 4))
25432 this.count += 1
25433 if (this.count === this.blockSize) {
25434 keccakState.p1600(this.state)
25435 this.count = 0
25436 }
25437 }
25438}
25439
25440Keccak.prototype.absorbLastFewBits = function (bits) {
25441 this.state[~~(this.count / 4)] ^= bits << (8 * (this.count % 4))
25442 if ((bits & 0x80) !== 0 && this.count === (this.blockSize - 1)) keccakState.p1600(this.state)
25443 this.state[~~((this.blockSize - 1) / 4)] ^= 0x80 << (8 * ((this.blockSize - 1) % 4))
25444 keccakState.p1600(this.state)
25445 this.count = 0
25446 this.squeezing = true
25447}
25448
25449Keccak.prototype.squeeze = function (length) {
25450 if (!this.squeezing) this.absorbLastFewBits(0x01)
25451
25452 var output = Buffer.alloc(length)
25453 for (var i = 0; i < length; ++i) {
25454 output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff
25455 this.count += 1
25456 if (this.count === this.blockSize) {
25457 keccakState.p1600(this.state)
25458 this.count = 0
25459 }
25460 }
25461
25462 return output
25463}
25464
25465Keccak.prototype.copy = function (dest) {
25466 for (var i = 0; i < 50; ++i) dest.state[i] = this.state[i]
25467 dest.blockSize = this.blockSize
25468 dest.count = this.count
25469 dest.squeezing = this.squeezing
25470}
25471
25472module.exports = Keccak
25473
25474},{"./keccak-state-unroll":171,"safe-buffer":247}],173:[function(require,module,exports){
25475(function (Buffer){
25476'use strict'
25477var inherits = require('inherits')
25478var HashBase = require('hash-base')
25479
25480var ARRAY16 = new Array(16)
25481
25482function MD5 () {
25483 HashBase.call(this, 64)
25484
25485 // state
25486 this._a = 0x67452301
25487 this._b = 0xefcdab89
25488 this._c = 0x98badcfe
25489 this._d = 0x10325476
25490}
25491
25492inherits(MD5, HashBase)
25493
25494MD5.prototype._update = function () {
25495 var M = ARRAY16
25496 for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4)
25497
25498 var a = this._a
25499 var b = this._b
25500 var c = this._c
25501 var d = this._d
25502
25503 a = fnF(a, b, c, d, M[0], 0xd76aa478, 7)
25504 d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12)
25505 c = fnF(c, d, a, b, M[2], 0x242070db, 17)
25506 b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22)
25507 a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7)
25508 d = fnF(d, a, b, c, M[5], 0x4787c62a, 12)
25509 c = fnF(c, d, a, b, M[6], 0xa8304613, 17)
25510 b = fnF(b, c, d, a, M[7], 0xfd469501, 22)
25511 a = fnF(a, b, c, d, M[8], 0x698098d8, 7)
25512 d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12)
25513 c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17)
25514 b = fnF(b, c, d, a, M[11], 0x895cd7be, 22)
25515 a = fnF(a, b, c, d, M[12], 0x6b901122, 7)
25516 d = fnF(d, a, b, c, M[13], 0xfd987193, 12)
25517 c = fnF(c, d, a, b, M[14], 0xa679438e, 17)
25518 b = fnF(b, c, d, a, M[15], 0x49b40821, 22)
25519
25520 a = fnG(a, b, c, d, M[1], 0xf61e2562, 5)
25521 d = fnG(d, a, b, c, M[6], 0xc040b340, 9)
25522 c = fnG(c, d, a, b, M[11], 0x265e5a51, 14)
25523 b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20)
25524 a = fnG(a, b, c, d, M[5], 0xd62f105d, 5)
25525 d = fnG(d, a, b, c, M[10], 0x02441453, 9)
25526 c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14)
25527 b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20)
25528 a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5)
25529 d = fnG(d, a, b, c, M[14], 0xc33707d6, 9)
25530 c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14)
25531 b = fnG(b, c, d, a, M[8], 0x455a14ed, 20)
25532 a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5)
25533 d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9)
25534 c = fnG(c, d, a, b, M[7], 0x676f02d9, 14)
25535 b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20)
25536
25537 a = fnH(a, b, c, d, M[5], 0xfffa3942, 4)
25538 d = fnH(d, a, b, c, M[8], 0x8771f681, 11)
25539 c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16)
25540 b = fnH(b, c, d, a, M[14], 0xfde5380c, 23)
25541 a = fnH(a, b, c, d, M[1], 0xa4beea44, 4)
25542 d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11)
25543 c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16)
25544 b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23)
25545 a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4)
25546 d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11)
25547 c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16)
25548 b = fnH(b, c, d, a, M[6], 0x04881d05, 23)
25549 a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4)
25550 d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11)
25551 c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16)
25552 b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23)
25553
25554 a = fnI(a, b, c, d, M[0], 0xf4292244, 6)
25555 d = fnI(d, a, b, c, M[7], 0x432aff97, 10)
25556 c = fnI(c, d, a, b, M[14], 0xab9423a7, 15)
25557 b = fnI(b, c, d, a, M[5], 0xfc93a039, 21)
25558 a = fnI(a, b, c, d, M[12], 0x655b59c3, 6)
25559 d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10)
25560 c = fnI(c, d, a, b, M[10], 0xffeff47d, 15)
25561 b = fnI(b, c, d, a, M[1], 0x85845dd1, 21)
25562 a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6)
25563 d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10)
25564 c = fnI(c, d, a, b, M[6], 0xa3014314, 15)
25565 b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21)
25566 a = fnI(a, b, c, d, M[4], 0xf7537e82, 6)
25567 d = fnI(d, a, b, c, M[11], 0xbd3af235, 10)
25568 c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15)
25569 b = fnI(b, c, d, a, M[9], 0xeb86d391, 21)
25570
25571 this._a = (this._a + a) | 0
25572 this._b = (this._b + b) | 0
25573 this._c = (this._c + c) | 0
25574 this._d = (this._d + d) | 0
25575}
25576
25577MD5.prototype._digest = function () {
25578 // create padding and handle blocks
25579 this._block[this._blockOffset++] = 0x80
25580 if (this._blockOffset > 56) {
25581 this._block.fill(0, this._blockOffset, 64)
25582 this._update()
25583 this._blockOffset = 0
25584 }
25585
25586 this._block.fill(0, this._blockOffset, 56)
25587 this._block.writeUInt32LE(this._length[0], 56)
25588 this._block.writeUInt32LE(this._length[1], 60)
25589 this._update()
25590
25591 // produce result
25592 var buffer = new Buffer(16)
25593 buffer.writeInt32LE(this._a, 0)
25594 buffer.writeInt32LE(this._b, 4)
25595 buffer.writeInt32LE(this._c, 8)
25596 buffer.writeInt32LE(this._d, 12)
25597 return buffer
25598}
25599
25600function rotl (x, n) {
25601 return (x << n) | (x >>> (32 - n))
25602}
25603
25604function fnF (a, b, c, d, m, k, s) {
25605 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0
25606}
25607
25608function fnG (a, b, c, d, m, k, s) {
25609 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0
25610}
25611
25612function fnH (a, b, c, d, m, k, s) {
25613 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0
25614}
25615
25616function fnI (a, b, c, d, m, k, s) {
25617 return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0
25618}
25619
25620module.exports = MD5
25621
25622}).call(this,require("buffer").Buffer)
25623},{"buffer":107,"hash-base":174,"inherits":163}],174:[function(require,module,exports){
25624'use strict'
25625var Buffer = require('safe-buffer').Buffer
25626var Transform = require('stream').Transform
25627var inherits = require('inherits')
25628
25629function throwIfNotStringOrBuffer (val, prefix) {
25630 if (!Buffer.isBuffer(val) && typeof val !== 'string') {
25631 throw new TypeError(prefix + ' must be a string or a buffer')
25632 }
25633}
25634
25635function HashBase (blockSize) {
25636 Transform.call(this)
25637
25638 this._block = Buffer.allocUnsafe(blockSize)
25639 this._blockSize = blockSize
25640 this._blockOffset = 0
25641 this._length = [0, 0, 0, 0]
25642
25643 this._finalized = false
25644}
25645
25646inherits(HashBase, Transform)
25647
25648HashBase.prototype._transform = function (chunk, encoding, callback) {
25649 var error = null
25650 try {
25651 this.update(chunk, encoding)
25652 } catch (err) {
25653 error = err
25654 }
25655
25656 callback(error)
25657}
25658
25659HashBase.prototype._flush = function (callback) {
25660 var error = null
25661 try {
25662 this.push(this.digest())
25663 } catch (err) {
25664 error = err
25665 }
25666
25667 callback(error)
25668}
25669
25670HashBase.prototype.update = function (data, encoding) {
25671 throwIfNotStringOrBuffer(data, 'Data')
25672 if (this._finalized) throw new Error('Digest already called')
25673 if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding)
25674
25675 // consume data
25676 var block = this._block
25677 var offset = 0
25678 while (this._blockOffset + data.length - offset >= this._blockSize) {
25679 for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++]
25680 this._update()
25681 this._blockOffset = 0
25682 }
25683 while (offset < data.length) block[this._blockOffset++] = data[offset++]
25684
25685 // update length
25686 for (var j = 0, carry = data.length * 8; carry > 0; ++j) {
25687 this._length[j] += carry
25688 carry = (this._length[j] / 0x0100000000) | 0
25689 if (carry > 0) this._length[j] -= 0x0100000000 * carry
25690 }
25691
25692 return this
25693}
25694
25695HashBase.prototype._update = function () {
25696 throw new Error('_update is not implemented')
25697}
25698
25699HashBase.prototype.digest = function (encoding) {
25700 if (this._finalized) throw new Error('Digest already called')
25701 this._finalized = true
25702
25703 var digest = this._digest()
25704 if (encoding !== undefined) digest = digest.toString(encoding)
25705
25706 // reset state
25707 this._block.fill(0)
25708 this._blockOffset = 0
25709 for (var i = 0; i < 4; ++i) this._length[i] = 0
25710
25711 return digest
25712}
25713
25714HashBase.prototype._digest = function () {
25715 throw new Error('_digest is not implemented')
25716}
25717
25718module.exports = HashBase
25719
25720},{"inherits":163,"safe-buffer":247,"stream":263}],175:[function(require,module,exports){
25721var bn = require('bn.js');
25722var brorand = require('brorand');
25723
25724function MillerRabin(rand) {
25725 this.rand = rand || new brorand.Rand();
25726}
25727module.exports = MillerRabin;
25728
25729MillerRabin.create = function create(rand) {
25730 return new MillerRabin(rand);
25731};
25732
25733MillerRabin.prototype._randbelow = function _randbelow(n) {
25734 var len = n.bitLength();
25735 var min_bytes = Math.ceil(len / 8);
25736
25737 // Generage random bytes until a number less than n is found.
25738 // This ensures that 0..n-1 have an equal probability of being selected.
25739 do
25740 var a = new bn(this.rand.generate(min_bytes));
25741 while (a.cmp(n) >= 0);
25742
25743 return a;
25744};
25745
25746MillerRabin.prototype._randrange = function _randrange(start, stop) {
25747 // Generate a random number greater than or equal to start and less than stop.
25748 var size = stop.sub(start);
25749 return start.add(this._randbelow(size));
25750};
25751
25752MillerRabin.prototype.test = function test(n, k, cb) {
25753 var len = n.bitLength();
25754 var red = bn.mont(n);
25755 var rone = new bn(1).toRed(red);
25756
25757 if (!k)
25758 k = Math.max(1, (len / 48) | 0);
25759
25760 // Find d and s, (n - 1) = (2 ^ s) * d;
25761 var n1 = n.subn(1);
25762 for (var s = 0; !n1.testn(s); s++) {}
25763 var d = n.shrn(s);
25764
25765 var rn1 = n1.toRed(red);
25766
25767 var prime = true;
25768 for (; k > 0; k--) {
25769 var a = this._randrange(new bn(2), n1);
25770 if (cb)
25771 cb(a);
25772
25773 var x = a.toRed(red).redPow(d);
25774 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
25775 continue;
25776
25777 for (var i = 1; i < s; i++) {
25778 x = x.redSqr();
25779
25780 if (x.cmp(rone) === 0)
25781 return false;
25782 if (x.cmp(rn1) === 0)
25783 break;
25784 }
25785
25786 if (i === s)
25787 return false;
25788 }
25789
25790 return prime;
25791};
25792
25793MillerRabin.prototype.getDivisor = function getDivisor(n, k) {
25794 var len = n.bitLength();
25795 var red = bn.mont(n);
25796 var rone = new bn(1).toRed(red);
25797
25798 if (!k)
25799 k = Math.max(1, (len / 48) | 0);
25800
25801 // Find d and s, (n - 1) = (2 ^ s) * d;
25802 var n1 = n.subn(1);
25803 for (var s = 0; !n1.testn(s); s++) {}
25804 var d = n.shrn(s);
25805
25806 var rn1 = n1.toRed(red);
25807
25808 for (; k > 0; k--) {
25809 var a = this._randrange(new bn(2), n1);
25810
25811 var g = n.gcd(a);
25812 if (g.cmpn(1) !== 0)
25813 return g;
25814
25815 var x = a.toRed(red).redPow(d);
25816 if (x.cmp(rone) === 0 || x.cmp(rn1) === 0)
25817 continue;
25818
25819 for (var i = 1; i < s; i++) {
25820 x = x.redSqr();
25821
25822 if (x.cmp(rone) === 0)
25823 return x.fromRed().subn(1).gcd(n);
25824 if (x.cmp(rn1) === 0)
25825 break;
25826 }
25827
25828 if (i === s) {
25829 x = x.redSqr();
25830 return x.fromRed().subn(1).gcd(n);
25831 }
25832 }
25833
25834 return false;
25835};
25836
25837},{"bn.js":75,"brorand":76}],176:[function(require,module,exports){
25838module.exports = assert;
25839
25840function assert(val, msg) {
25841 if (!val)
25842 throw new Error(msg || 'Assertion failed');
25843}
25844
25845assert.equal = function assertEqual(l, r, msg) {
25846 if (l != r)
25847 throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r));
25848};
25849
25850},{}],177:[function(require,module,exports){
25851'use strict';
25852
25853var utils = exports;
25854
25855function toArray(msg, enc) {
25856 if (Array.isArray(msg))
25857 return msg.slice();
25858 if (!msg)
25859 return [];
25860 var res = [];
25861 if (typeof msg !== 'string') {
25862 for (var i = 0; i < msg.length; i++)
25863 res[i] = msg[i] | 0;
25864 return res;
25865 }
25866 if (enc === 'hex') {
25867 msg = msg.replace(/[^a-z0-9]+/ig, '');
25868 if (msg.length % 2 !== 0)
25869 msg = '0' + msg;
25870 for (var i = 0; i < msg.length; i += 2)
25871 res.push(parseInt(msg[i] + msg[i + 1], 16));
25872 } else {
25873 for (var i = 0; i < msg.length; i++) {
25874 var c = msg.charCodeAt(i);
25875 var hi = c >> 8;
25876 var lo = c & 0xff;
25877 if (hi)
25878 res.push(hi, lo);
25879 else
25880 res.push(lo);
25881 }
25882 }
25883 return res;
25884}
25885utils.toArray = toArray;
25886
25887function zero2(word) {
25888 if (word.length === 1)
25889 return '0' + word;
25890 else
25891 return word;
25892}
25893utils.zero2 = zero2;
25894
25895function toHex(msg) {
25896 var res = '';
25897 for (var i = 0; i < msg.length; i++)
25898 res += zero2(msg[i].toString(16));
25899 return res;
25900}
25901utils.toHex = toHex;
25902
25903utils.encode = function encode(arr, enc) {
25904 if (enc === 'hex')
25905 return toHex(arr);
25906 else
25907 return arr;
25908};
25909
25910},{}],178:[function(require,module,exports){
25911module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb",
25912"2.16.840.1.101.3.4.1.2": "aes-128-cbc",
25913"2.16.840.1.101.3.4.1.3": "aes-128-ofb",
25914"2.16.840.1.101.3.4.1.4": "aes-128-cfb",
25915"2.16.840.1.101.3.4.1.21": "aes-192-ecb",
25916"2.16.840.1.101.3.4.1.22": "aes-192-cbc",
25917"2.16.840.1.101.3.4.1.23": "aes-192-ofb",
25918"2.16.840.1.101.3.4.1.24": "aes-192-cfb",
25919"2.16.840.1.101.3.4.1.41": "aes-256-ecb",
25920"2.16.840.1.101.3.4.1.42": "aes-256-cbc",
25921"2.16.840.1.101.3.4.1.43": "aes-256-ofb",
25922"2.16.840.1.101.3.4.1.44": "aes-256-cfb"
25923}
25924},{}],179:[function(require,module,exports){
25925// from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js
25926// Fedor, you are amazing.
25927'use strict'
25928
25929var asn1 = require('asn1.js')
25930
25931exports.certificate = require('./certificate')
25932
25933var RSAPrivateKey = asn1.define('RSAPrivateKey', function () {
25934 this.seq().obj(
25935 this.key('version').int(),
25936 this.key('modulus').int(),
25937 this.key('publicExponent').int(),
25938 this.key('privateExponent').int(),
25939 this.key('prime1').int(),
25940 this.key('prime2').int(),
25941 this.key('exponent1').int(),
25942 this.key('exponent2').int(),
25943 this.key('coefficient').int()
25944 )
25945})
25946exports.RSAPrivateKey = RSAPrivateKey
25947
25948var RSAPublicKey = asn1.define('RSAPublicKey', function () {
25949 this.seq().obj(
25950 this.key('modulus').int(),
25951 this.key('publicExponent').int()
25952 )
25953})
25954exports.RSAPublicKey = RSAPublicKey
25955
25956var PublicKey = asn1.define('SubjectPublicKeyInfo', function () {
25957 this.seq().obj(
25958 this.key('algorithm').use(AlgorithmIdentifier),
25959 this.key('subjectPublicKey').bitstr()
25960 )
25961})
25962exports.PublicKey = PublicKey
25963
25964var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () {
25965 this.seq().obj(
25966 this.key('algorithm').objid(),
25967 this.key('none').null_().optional(),
25968 this.key('curve').objid().optional(),
25969 this.key('params').seq().obj(
25970 this.key('p').int(),
25971 this.key('q').int(),
25972 this.key('g').int()
25973 ).optional()
25974 )
25975})
25976
25977var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () {
25978 this.seq().obj(
25979 this.key('version').int(),
25980 this.key('algorithm').use(AlgorithmIdentifier),
25981 this.key('subjectPrivateKey').octstr()
25982 )
25983})
25984exports.PrivateKey = PrivateKeyInfo
25985var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () {
25986 this.seq().obj(
25987 this.key('algorithm').seq().obj(
25988 this.key('id').objid(),
25989 this.key('decrypt').seq().obj(
25990 this.key('kde').seq().obj(
25991 this.key('id').objid(),
25992 this.key('kdeparams').seq().obj(
25993 this.key('salt').octstr(),
25994 this.key('iters').int()
25995 )
25996 ),
25997 this.key('cipher').seq().obj(
25998 this.key('algo').objid(),
25999 this.key('iv').octstr()
26000 )
26001 )
26002 ),
26003 this.key('subjectPrivateKey').octstr()
26004 )
26005})
26006
26007exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo
26008
26009var DSAPrivateKey = asn1.define('DSAPrivateKey', function () {
26010 this.seq().obj(
26011 this.key('version').int(),
26012 this.key('p').int(),
26013 this.key('q').int(),
26014 this.key('g').int(),
26015 this.key('pub_key').int(),
26016 this.key('priv_key').int()
26017 )
26018})
26019exports.DSAPrivateKey = DSAPrivateKey
26020
26021exports.DSAparam = asn1.define('DSAparam', function () {
26022 this.int()
26023})
26024
26025var ECPrivateKey = asn1.define('ECPrivateKey', function () {
26026 this.seq().obj(
26027 this.key('version').int(),
26028 this.key('privateKey').octstr(),
26029 this.key('parameters').optional().explicit(0).use(ECParameters),
26030 this.key('publicKey').optional().explicit(1).bitstr()
26031 )
26032})
26033exports.ECPrivateKey = ECPrivateKey
26034
26035var ECParameters = asn1.define('ECParameters', function () {
26036 this.choice({
26037 namedCurve: this.objid()
26038 })
26039})
26040
26041exports.signature = asn1.define('signature', function () {
26042 this.seq().obj(
26043 this.key('r').int(),
26044 this.key('s').int()
26045 )
26046})
26047
26048},{"./certificate":180,"asn1.js":32}],180:[function(require,module,exports){
26049// from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js
26050// thanks to @Rantanen
26051
26052'use strict'
26053
26054var asn = require('asn1.js')
26055
26056var Time = asn.define('Time', function () {
26057 this.choice({
26058 utcTime: this.utctime(),
26059 generalTime: this.gentime()
26060 })
26061})
26062
26063var AttributeTypeValue = asn.define('AttributeTypeValue', function () {
26064 this.seq().obj(
26065 this.key('type').objid(),
26066 this.key('value').any()
26067 )
26068})
26069
26070var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () {
26071 this.seq().obj(
26072 this.key('algorithm').objid(),
26073 this.key('parameters').optional()
26074 )
26075})
26076
26077var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () {
26078 this.seq().obj(
26079 this.key('algorithm').use(AlgorithmIdentifier),
26080 this.key('subjectPublicKey').bitstr()
26081 )
26082})
26083
26084var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () {
26085 this.setof(AttributeTypeValue)
26086})
26087
26088var RDNSequence = asn.define('RDNSequence', function () {
26089 this.seqof(RelativeDistinguishedName)
26090})
26091
26092var Name = asn.define('Name', function () {
26093 this.choice({
26094 rdnSequence: this.use(RDNSequence)
26095 })
26096})
26097
26098var Validity = asn.define('Validity', function () {
26099 this.seq().obj(
26100 this.key('notBefore').use(Time),
26101 this.key('notAfter').use(Time)
26102 )
26103})
26104
26105var Extension = asn.define('Extension', function () {
26106 this.seq().obj(
26107 this.key('extnID').objid(),
26108 this.key('critical').bool().def(false),
26109 this.key('extnValue').octstr()
26110 )
26111})
26112
26113var TBSCertificate = asn.define('TBSCertificate', function () {
26114 this.seq().obj(
26115 this.key('version').explicit(0).int(),
26116 this.key('serialNumber').int(),
26117 this.key('signature').use(AlgorithmIdentifier),
26118 this.key('issuer').use(Name),
26119 this.key('validity').use(Validity),
26120 this.key('subject').use(Name),
26121 this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo),
26122 this.key('issuerUniqueID').implicit(1).bitstr().optional(),
26123 this.key('subjectUniqueID').implicit(2).bitstr().optional(),
26124 this.key('extensions').explicit(3).seqof(Extension).optional()
26125 )
26126})
26127
26128var X509Certificate = asn.define('X509Certificate', function () {
26129 this.seq().obj(
26130 this.key('tbsCertificate').use(TBSCertificate),
26131 this.key('signatureAlgorithm').use(AlgorithmIdentifier),
26132 this.key('signatureValue').bitstr()
26133 )
26134})
26135
26136module.exports = X509Certificate
26137
26138},{"asn1.js":32}],181:[function(require,module,exports){
26139(function (Buffer){
26140// adapted from https://github.com/apatil/pemstrip
26141var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m
26142var startRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m
26143var fullRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m
26144var evp = require('evp_bytestokey')
26145var ciphers = require('browserify-aes')
26146module.exports = function (okey, password) {
26147 var key = okey.toString()
26148 var match = key.match(findProc)
26149 var decrypted
26150 if (!match) {
26151 var match2 = key.match(fullRegex)
26152 decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64')
26153 } else {
26154 var suite = 'aes' + match[1]
26155 var iv = new Buffer(match[2], 'hex')
26156 var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64')
26157 var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key
26158 var out = []
26159 var cipher = ciphers.createDecipheriv(suite, cipherKey, iv)
26160 out.push(cipher.update(cipherText))
26161 out.push(cipher.final())
26162 decrypted = Buffer.concat(out)
26163 }
26164 var tag = key.match(startRegex)[1]
26165 return {
26166 tag: tag,
26167 data: decrypted
26168 }
26169}
26170
26171}).call(this,require("buffer").Buffer)
26172},{"browserify-aes":80,"buffer":107,"evp_bytestokey":144}],182:[function(require,module,exports){
26173(function (Buffer){
26174var asn1 = require('./asn1')
26175var aesid = require('./aesid.json')
26176var fixProc = require('./fixProc')
26177var ciphers = require('browserify-aes')
26178var compat = require('pbkdf2')
26179module.exports = parseKeys
26180
26181function parseKeys (buffer) {
26182 var password
26183 if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) {
26184 password = buffer.passphrase
26185 buffer = buffer.key
26186 }
26187 if (typeof buffer === 'string') {
26188 buffer = new Buffer(buffer)
26189 }
26190
26191 var stripped = fixProc(buffer, password)
26192
26193 var type = stripped.tag
26194 var data = stripped.data
26195 var subtype, ndata
26196 switch (type) {
26197 case 'CERTIFICATE':
26198 ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo
26199 // falls through
26200 case 'PUBLIC KEY':
26201 if (!ndata) {
26202 ndata = asn1.PublicKey.decode(data, 'der')
26203 }
26204 subtype = ndata.algorithm.algorithm.join('.')
26205 switch (subtype) {
26206 case '1.2.840.113549.1.1.1':
26207 return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der')
26208 case '1.2.840.10045.2.1':
26209 ndata.subjectPrivateKey = ndata.subjectPublicKey
26210 return {
26211 type: 'ec',
26212 data: ndata
26213 }
26214 case '1.2.840.10040.4.1':
26215 ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der')
26216 return {
26217 type: 'dsa',
26218 data: ndata.algorithm.params
26219 }
26220 default: throw new Error('unknown key id ' + subtype)
26221 }
26222 throw new Error('unknown key type ' + type)
26223 case 'ENCRYPTED PRIVATE KEY':
26224 data = asn1.EncryptedPrivateKey.decode(data, 'der')
26225 data = decrypt(data, password)
26226 // falls through
26227 case 'PRIVATE KEY':
26228 ndata = asn1.PrivateKey.decode(data, 'der')
26229 subtype = ndata.algorithm.algorithm.join('.')
26230 switch (subtype) {
26231 case '1.2.840.113549.1.1.1':
26232 return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der')
26233 case '1.2.840.10045.2.1':
26234 return {
26235 curve: ndata.algorithm.curve,
26236 privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey
26237 }
26238 case '1.2.840.10040.4.1':
26239 ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der')
26240 return {
26241 type: 'dsa',
26242 params: ndata.algorithm.params
26243 }
26244 default: throw new Error('unknown key id ' + subtype)
26245 }
26246 throw new Error('unknown key type ' + type)
26247 case 'RSA PUBLIC KEY':
26248 return asn1.RSAPublicKey.decode(data, 'der')
26249 case 'RSA PRIVATE KEY':
26250 return asn1.RSAPrivateKey.decode(data, 'der')
26251 case 'DSA PRIVATE KEY':
26252 return {
26253 type: 'dsa',
26254 params: asn1.DSAPrivateKey.decode(data, 'der')
26255 }
26256 case 'EC PRIVATE KEY':
26257 data = asn1.ECPrivateKey.decode(data, 'der')
26258 return {
26259 curve: data.parameters.value,
26260 privateKey: data.privateKey
26261 }
26262 default: throw new Error('unknown key type ' + type)
26263 }
26264}
26265parseKeys.signature = asn1.signature
26266function decrypt (data, password) {
26267 var salt = data.algorithm.decrypt.kde.kdeparams.salt
26268 var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10)
26269 var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')]
26270 var iv = data.algorithm.decrypt.cipher.iv
26271 var cipherText = data.subjectPrivateKey
26272 var keylen = parseInt(algo.split('-')[1], 10) / 8
26273 var key = compat.pbkdf2Sync(password, salt, iters, keylen)
26274 var cipher = ciphers.createDecipheriv(algo, key, iv)
26275 var out = []
26276 out.push(cipher.update(cipherText))
26277 out.push(cipher.final())
26278 return Buffer.concat(out)
26279}
26280
26281}).call(this,require("buffer").Buffer)
26282},{"./aesid.json":178,"./asn1":179,"./fixProc":181,"browserify-aes":80,"buffer":107,"pbkdf2":184}],183:[function(require,module,exports){
26283(function (process){
26284// Copyright Joyent, Inc. and other Node contributors.
26285//
26286// Permission is hereby granted, free of charge, to any person obtaining a
26287// copy of this software and associated documentation files (the
26288// "Software"), to deal in the Software without restriction, including
26289// without limitation the rights to use, copy, modify, merge, publish,
26290// distribute, sublicense, and/or sell copies of the Software, and to permit
26291// persons to whom the Software is furnished to do so, subject to the
26292// following conditions:
26293//
26294// The above copyright notice and this permission notice shall be included
26295// in all copies or substantial portions of the Software.
26296//
26297// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
26298// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26299// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
26300// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
26301// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
26302// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
26303// USE OR OTHER DEALINGS IN THE SOFTWARE.
26304
26305// resolves . and .. elements in a path array with directory names there
26306// must be no slashes, empty elements, or device names (c:\) in the array
26307// (so also no leading and trailing slashes - it does not distinguish
26308// relative and absolute paths)
26309function normalizeArray(parts, allowAboveRoot) {
26310 // if the path tries to go above the root, `up` ends up > 0
26311 var up = 0;
26312 for (var i = parts.length - 1; i >= 0; i--) {
26313 var last = parts[i];
26314 if (last === '.') {
26315 parts.splice(i, 1);
26316 } else if (last === '..') {
26317 parts.splice(i, 1);
26318 up++;
26319 } else if (up) {
26320 parts.splice(i, 1);
26321 up--;
26322 }
26323 }
26324
26325 // if the path is allowed to go above the root, restore leading ..s
26326 if (allowAboveRoot) {
26327 for (; up--; up) {
26328 parts.unshift('..');
26329 }
26330 }
26331
26332 return parts;
26333}
26334
26335// Split a filename into [root, dir, basename, ext], unix version
26336// 'root' is just a slash, or nothing.
26337var splitPathRe =
26338 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
26339var splitPath = function(filename) {
26340 return splitPathRe.exec(filename).slice(1);
26341};
26342
26343// path.resolve([from ...], to)
26344// posix version
26345exports.resolve = function() {
26346 var resolvedPath = '',
26347 resolvedAbsolute = false;
26348
26349 for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) {
26350 var path = (i >= 0) ? arguments[i] : process.cwd();
26351
26352 // Skip empty and invalid entries
26353 if (typeof path !== 'string') {
26354 throw new TypeError('Arguments to path.resolve must be strings');
26355 } else if (!path) {
26356 continue;
26357 }
26358
26359 resolvedPath = path + '/' + resolvedPath;
26360 resolvedAbsolute = path.charAt(0) === '/';
26361 }
26362
26363 // At this point the path should be resolved to a full absolute path, but
26364 // handle relative paths to be safe (might happen when process.cwd() fails)
26365
26366 // Normalize the path
26367 resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) {
26368 return !!p;
26369 }), !resolvedAbsolute).join('/');
26370
26371 return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.';
26372};
26373
26374// path.normalize(path)
26375// posix version
26376exports.normalize = function(path) {
26377 var isAbsolute = exports.isAbsolute(path),
26378 trailingSlash = substr(path, -1) === '/';
26379
26380 // Normalize the path
26381 path = normalizeArray(filter(path.split('/'), function(p) {
26382 return !!p;
26383 }), !isAbsolute).join('/');
26384
26385 if (!path && !isAbsolute) {
26386 path = '.';
26387 }
26388 if (path && trailingSlash) {
26389 path += '/';
26390 }
26391
26392 return (isAbsolute ? '/' : '') + path;
26393};
26394
26395// posix version
26396exports.isAbsolute = function(path) {
26397 return path.charAt(0) === '/';
26398};
26399
26400// posix version
26401exports.join = function() {
26402 var paths = Array.prototype.slice.call(arguments, 0);
26403 return exports.normalize(filter(paths, function(p, index) {
26404 if (typeof p !== 'string') {
26405 throw new TypeError('Arguments to path.join must be strings');
26406 }
26407 return p;
26408 }).join('/'));
26409};
26410
26411
26412// path.relative(from, to)
26413// posix version
26414exports.relative = function(from, to) {
26415 from = exports.resolve(from).substr(1);
26416 to = exports.resolve(to).substr(1);
26417
26418 function trim(arr) {
26419 var start = 0;
26420 for (; start < arr.length; start++) {
26421 if (arr[start] !== '') break;
26422 }
26423
26424 var end = arr.length - 1;
26425 for (; end >= 0; end--) {
26426 if (arr[end] !== '') break;
26427 }
26428
26429 if (start > end) return [];
26430 return arr.slice(start, end - start + 1);
26431 }
26432
26433 var fromParts = trim(from.split('/'));
26434 var toParts = trim(to.split('/'));
26435
26436 var length = Math.min(fromParts.length, toParts.length);
26437 var samePartsLength = length;
26438 for (var i = 0; i < length; i++) {
26439 if (fromParts[i] !== toParts[i]) {
26440 samePartsLength = i;
26441 break;
26442 }
26443 }
26444
26445 var outputParts = [];
26446 for (var i = samePartsLength; i < fromParts.length; i++) {
26447 outputParts.push('..');
26448 }
26449
26450 outputParts = outputParts.concat(toParts.slice(samePartsLength));
26451
26452 return outputParts.join('/');
26453};
26454
26455exports.sep = '/';
26456exports.delimiter = ':';
26457
26458exports.dirname = function(path) {
26459 var result = splitPath(path),
26460 root = result[0],
26461 dir = result[1];
26462
26463 if (!root && !dir) {
26464 // No dirname whatsoever
26465 return '.';
26466 }
26467
26468 if (dir) {
26469 // It has a dirname, strip trailing slash
26470 dir = dir.substr(0, dir.length - 1);
26471 }
26472
26473 return root + dir;
26474};
26475
26476
26477exports.basename = function(path, ext) {
26478 var f = splitPath(path)[2];
26479 // TODO: make this comparison case-insensitive on windows?
26480 if (ext && f.substr(-1 * ext.length) === ext) {
26481 f = f.substr(0, f.length - ext.length);
26482 }
26483 return f;
26484};
26485
26486
26487exports.extname = function(path) {
26488 return splitPath(path)[3];
26489};
26490
26491function filter (xs, f) {
26492 if (xs.filter) return xs.filter(f);
26493 var res = [];
26494 for (var i = 0; i < xs.length; i++) {
26495 if (f(xs[i], i, xs)) res.push(xs[i]);
26496 }
26497 return res;
26498}
26499
26500// String.prototype.substr - negative index don't work in IE8
26501var substr = 'ab'.substr(-1) === 'b'
26502 ? function (str, start, len) { return str.substr(start, len) }
26503 : function (str, start, len) {
26504 if (start < 0) start = str.length + start;
26505 return str.substr(start, len);
26506 }
26507;
26508
26509}).call(this,require('_process'))
26510},{"_process":190}],184:[function(require,module,exports){
26511
26512exports.pbkdf2 = require('./lib/async')
26513
26514exports.pbkdf2Sync = require('./lib/sync')
26515
26516},{"./lib/async":185,"./lib/sync":188}],185:[function(require,module,exports){
26517(function (process,global){
26518var checkParameters = require('./precondition')
26519var defaultEncoding = require('./default-encoding')
26520var sync = require('./sync')
26521var Buffer = require('safe-buffer').Buffer
26522
26523var ZERO_BUF
26524var subtle = global.crypto && global.crypto.subtle
26525var toBrowser = {
26526 'sha': 'SHA-1',
26527 'sha-1': 'SHA-1',
26528 'sha1': 'SHA-1',
26529 'sha256': 'SHA-256',
26530 'sha-256': 'SHA-256',
26531 'sha384': 'SHA-384',
26532 'sha-384': 'SHA-384',
26533 'sha-512': 'SHA-512',
26534 'sha512': 'SHA-512'
26535}
26536var checks = []
26537function checkNative (algo) {
26538 if (global.process && !global.process.browser) {
26539 return Promise.resolve(false)
26540 }
26541 if (!subtle || !subtle.importKey || !subtle.deriveBits) {
26542 return Promise.resolve(false)
26543 }
26544 if (checks[algo] !== undefined) {
26545 return checks[algo]
26546 }
26547 ZERO_BUF = ZERO_BUF || Buffer.alloc(8)
26548 var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo)
26549 .then(function () {
26550 return true
26551 }).catch(function () {
26552 return false
26553 })
26554 checks[algo] = prom
26555 return prom
26556}
26557function browserPbkdf2 (password, salt, iterations, length, algo) {
26558 return subtle.importKey(
26559 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits']
26560 ).then(function (key) {
26561 return subtle.deriveBits({
26562 name: 'PBKDF2',
26563 salt: salt,
26564 iterations: iterations,
26565 hash: {
26566 name: algo
26567 }
26568 }, key, length << 3)
26569 }).then(function (res) {
26570 return Buffer.from(res)
26571 })
26572}
26573function resolvePromise (promise, callback) {
26574 promise.then(function (out) {
26575 process.nextTick(function () {
26576 callback(null, out)
26577 })
26578 }, function (e) {
26579 process.nextTick(function () {
26580 callback(e)
26581 })
26582 })
26583}
26584module.exports = function (password, salt, iterations, keylen, digest, callback) {
26585 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
26586 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
26587
26588 checkParameters(iterations, keylen)
26589 if (typeof digest === 'function') {
26590 callback = digest
26591 digest = undefined
26592 }
26593 if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2')
26594
26595 digest = digest || 'sha1'
26596 var algo = toBrowser[digest.toLowerCase()]
26597 if (!algo || typeof global.Promise !== 'function') {
26598 return process.nextTick(function () {
26599 var out
26600 try {
26601 out = sync(password, salt, iterations, keylen, digest)
26602 } catch (e) {
26603 return callback(e)
26604 }
26605 callback(null, out)
26606 })
26607 }
26608 resolvePromise(checkNative(algo).then(function (resp) {
26609 if (resp) {
26610 return browserPbkdf2(password, salt, iterations, keylen, algo)
26611 } else {
26612 return sync(password, salt, iterations, keylen, digest)
26613 }
26614 }), callback)
26615}
26616
26617}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
26618},{"./default-encoding":186,"./precondition":187,"./sync":188,"_process":190,"safe-buffer":247}],186:[function(require,module,exports){
26619(function (process){
26620var defaultEncoding
26621/* istanbul ignore next */
26622if (process.browser) {
26623 defaultEncoding = 'utf-8'
26624} else {
26625 var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10)
26626
26627 defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary'
26628}
26629module.exports = defaultEncoding
26630
26631}).call(this,require('_process'))
26632},{"_process":190}],187:[function(require,module,exports){
26633var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs
26634module.exports = function (iterations, keylen) {
26635 if (typeof iterations !== 'number') {
26636 throw new TypeError('Iterations not a number')
26637 }
26638
26639 if (iterations < 0) {
26640 throw new TypeError('Bad iterations')
26641 }
26642
26643 if (typeof keylen !== 'number') {
26644 throw new TypeError('Key length not a number')
26645 }
26646
26647 if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */
26648 throw new TypeError('Bad key length')
26649 }
26650}
26651
26652},{}],188:[function(require,module,exports){
26653var md5 = require('create-hash/md5')
26654var rmd160 = require('ripemd160')
26655var sha = require('sha.js')
26656
26657var checkParameters = require('./precondition')
26658var defaultEncoding = require('./default-encoding')
26659var Buffer = require('safe-buffer').Buffer
26660var ZEROS = Buffer.alloc(128)
26661var sizes = {
26662 md5: 16,
26663 sha1: 20,
26664 sha224: 28,
26665 sha256: 32,
26666 sha384: 48,
26667 sha512: 64,
26668 rmd160: 20,
26669 ripemd160: 20
26670}
26671
26672function Hmac (alg, key, saltLen) {
26673 var hash = getDigest(alg)
26674 var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64
26675
26676 if (key.length > blocksize) {
26677 key = hash(key)
26678 } else if (key.length < blocksize) {
26679 key = Buffer.concat([key, ZEROS], blocksize)
26680 }
26681
26682 var ipad = Buffer.allocUnsafe(blocksize + sizes[alg])
26683 var opad = Buffer.allocUnsafe(blocksize + sizes[alg])
26684 for (var i = 0; i < blocksize; i++) {
26685 ipad[i] = key[i] ^ 0x36
26686 opad[i] = key[i] ^ 0x5C
26687 }
26688
26689 var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4)
26690 ipad.copy(ipad1, 0, 0, blocksize)
26691 this.ipad1 = ipad1
26692 this.ipad2 = ipad
26693 this.opad = opad
26694 this.alg = alg
26695 this.blocksize = blocksize
26696 this.hash = hash
26697 this.size = sizes[alg]
26698}
26699
26700Hmac.prototype.run = function (data, ipad) {
26701 data.copy(ipad, this.blocksize)
26702 var h = this.hash(ipad)
26703 h.copy(this.opad, this.blocksize)
26704 return this.hash(this.opad)
26705}
26706
26707function getDigest (alg) {
26708 function shaFunc (data) {
26709 return sha(alg).update(data).digest()
26710 }
26711
26712 if (alg === 'rmd160' || alg === 'ripemd160') return rmd160
26713 if (alg === 'md5') return md5
26714 return shaFunc
26715}
26716
26717function pbkdf2 (password, salt, iterations, keylen, digest) {
26718 if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding)
26719 if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding)
26720
26721 checkParameters(iterations, keylen)
26722
26723 digest = digest || 'sha1'
26724
26725 var hmac = new Hmac(digest, password, salt.length)
26726
26727 var DK = Buffer.allocUnsafe(keylen)
26728 var block1 = Buffer.allocUnsafe(salt.length + 4)
26729 salt.copy(block1, 0, 0, salt.length)
26730
26731 var destPos = 0
26732 var hLen = sizes[digest]
26733 var l = Math.ceil(keylen / hLen)
26734
26735 for (var i = 1; i <= l; i++) {
26736 block1.writeUInt32BE(i, salt.length)
26737
26738 var T = hmac.run(block1, hmac.ipad1)
26739 var U = T
26740
26741 for (var j = 1; j < iterations; j++) {
26742 U = hmac.run(U, hmac.ipad2)
26743 for (var k = 0; k < hLen; k++) T[k] ^= U[k]
26744 }
26745
26746 T.copy(DK, destPos)
26747 destPos += hLen
26748 }
26749
26750 return DK
26751}
26752
26753module.exports = pbkdf2
26754
26755},{"./default-encoding":186,"./precondition":187,"create-hash/md5":113,"ripemd160":246,"safe-buffer":247,"sha.js":256}],189:[function(require,module,exports){
26756(function (process){
26757'use strict';
26758
26759if (!process.version ||
26760 process.version.indexOf('v0.') === 0 ||
26761 process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) {
26762 module.exports = nextTick;
26763} else {
26764 module.exports = process.nextTick;
26765}
26766
26767function nextTick(fn, arg1, arg2, arg3) {
26768 if (typeof fn !== 'function') {
26769 throw new TypeError('"callback" argument must be a function');
26770 }
26771 var len = arguments.length;
26772 var args, i;
26773 switch (len) {
26774 case 0:
26775 case 1:
26776 return process.nextTick(fn);
26777 case 2:
26778 return process.nextTick(function afterTickOne() {
26779 fn.call(null, arg1);
26780 });
26781 case 3:
26782 return process.nextTick(function afterTickTwo() {
26783 fn.call(null, arg1, arg2);
26784 });
26785 case 4:
26786 return process.nextTick(function afterTickThree() {
26787 fn.call(null, arg1, arg2, arg3);
26788 });
26789 default:
26790 args = new Array(len - 1);
26791 i = 0;
26792 while (i < args.length) {
26793 args[i++] = arguments[i];
26794 }
26795 return process.nextTick(function afterTick() {
26796 fn.apply(null, args);
26797 });
26798 }
26799}
26800
26801}).call(this,require('_process'))
26802},{"_process":190}],190:[function(require,module,exports){
26803// shim for using process in browser
26804var process = module.exports = {};
26805
26806// cached from whatever global is present so that test runners that stub it
26807// don't break things. But we need to wrap it in a try catch in case it is
26808// wrapped in strict mode code which doesn't define any globals. It's inside a
26809// function because try/catches deoptimize in certain engines.
26810
26811var cachedSetTimeout;
26812var cachedClearTimeout;
26813
26814function defaultSetTimout() {
26815 throw new Error('setTimeout has not been defined');
26816}
26817function defaultClearTimeout () {
26818 throw new Error('clearTimeout has not been defined');
26819}
26820(function () {
26821 try {
26822 if (typeof setTimeout === 'function') {
26823 cachedSetTimeout = setTimeout;
26824 } else {
26825 cachedSetTimeout = defaultSetTimout;
26826 }
26827 } catch (e) {
26828 cachedSetTimeout = defaultSetTimout;
26829 }
26830 try {
26831 if (typeof clearTimeout === 'function') {
26832 cachedClearTimeout = clearTimeout;
26833 } else {
26834 cachedClearTimeout = defaultClearTimeout;
26835 }
26836 } catch (e) {
26837 cachedClearTimeout = defaultClearTimeout;
26838 }
26839} ())
26840function runTimeout(fun) {
26841 if (cachedSetTimeout === setTimeout) {
26842 //normal enviroments in sane situations
26843 return setTimeout(fun, 0);
26844 }
26845 // if setTimeout wasn't available but was latter defined
26846 if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) {
26847 cachedSetTimeout = setTimeout;
26848 return setTimeout(fun, 0);
26849 }
26850 try {
26851 // when when somebody has screwed with setTimeout but no I.E. maddness
26852 return cachedSetTimeout(fun, 0);
26853 } catch(e){
26854 try {
26855 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
26856 return cachedSetTimeout.call(null, fun, 0);
26857 } catch(e){
26858 // 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
26859 return cachedSetTimeout.call(this, fun, 0);
26860 }
26861 }
26862
26863
26864}
26865function runClearTimeout(marker) {
26866 if (cachedClearTimeout === clearTimeout) {
26867 //normal enviroments in sane situations
26868 return clearTimeout(marker);
26869 }
26870 // if clearTimeout wasn't available but was latter defined
26871 if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) {
26872 cachedClearTimeout = clearTimeout;
26873 return clearTimeout(marker);
26874 }
26875 try {
26876 // when when somebody has screwed with setTimeout but no I.E. maddness
26877 return cachedClearTimeout(marker);
26878 } catch (e){
26879 try {
26880 // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally
26881 return cachedClearTimeout.call(null, marker);
26882 } catch (e){
26883 // 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.
26884 // Some versions of I.E. have different rules for clearTimeout vs setTimeout
26885 return cachedClearTimeout.call(this, marker);
26886 }
26887 }
26888
26889
26890
26891}
26892var queue = [];
26893var draining = false;
26894var currentQueue;
26895var queueIndex = -1;
26896
26897function cleanUpNextTick() {
26898 if (!draining || !currentQueue) {
26899 return;
26900 }
26901 draining = false;
26902 if (currentQueue.length) {
26903 queue = currentQueue.concat(queue);
26904 } else {
26905 queueIndex = -1;
26906 }
26907 if (queue.length) {
26908 drainQueue();
26909 }
26910}
26911
26912function drainQueue() {
26913 if (draining) {
26914 return;
26915 }
26916 var timeout = runTimeout(cleanUpNextTick);
26917 draining = true;
26918
26919 var len = queue.length;
26920 while(len) {
26921 currentQueue = queue;
26922 queue = [];
26923 while (++queueIndex < len) {
26924 if (currentQueue) {
26925 currentQueue[queueIndex].run();
26926 }
26927 }
26928 queueIndex = -1;
26929 len = queue.length;
26930 }
26931 currentQueue = null;
26932 draining = false;
26933 runClearTimeout(timeout);
26934}
26935
26936process.nextTick = function (fun) {
26937 var args = new Array(arguments.length - 1);
26938 if (arguments.length > 1) {
26939 for (var i = 1; i < arguments.length; i++) {
26940 args[i - 1] = arguments[i];
26941 }
26942 }
26943 queue.push(new Item(fun, args));
26944 if (queue.length === 1 && !draining) {
26945 runTimeout(drainQueue);
26946 }
26947};
26948
26949// v8 likes predictible objects
26950function Item(fun, array) {
26951 this.fun = fun;
26952 this.array = array;
26953}
26954Item.prototype.run = function () {
26955 this.fun.apply(null, this.array);
26956};
26957process.title = 'browser';
26958process.browser = true;
26959process.env = {};
26960process.argv = [];
26961process.version = ''; // empty string to avoid regexp issues
26962process.versions = {};
26963
26964function noop() {}
26965
26966process.on = noop;
26967process.addListener = noop;
26968process.once = noop;
26969process.off = noop;
26970process.removeListener = noop;
26971process.removeAllListeners = noop;
26972process.emit = noop;
26973process.prependListener = noop;
26974process.prependOnceListener = noop;
26975
26976process.listeners = function (name) { return [] }
26977
26978process.binding = function (name) {
26979 throw new Error('process.binding is not supported');
26980};
26981
26982process.cwd = function () { return '/' };
26983process.chdir = function (dir) {
26984 throw new Error('process.chdir is not supported');
26985};
26986process.umask = function() { return 0; };
26987
26988},{}],191:[function(require,module,exports){
26989// full library entry point.\r
26990\r
26991"use strict";\r
26992module.exports = require("./src/index");\r
26993
26994},{"./src/index":200}],192:[function(require,module,exports){
26995"use strict";\r
26996module.exports = common;\r
26997\r
26998var commonRe = /\/|\./;\r
26999\r
27000/**\r
27001 * Provides common type definitions.\r
27002 * Can also be used to provide additional google types or your own custom types.\r
27003 * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name\r
27004 * @param {Object.<string,*>} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition\r
27005 * @returns {undefined}\r
27006 * @property {INamespace} google/protobuf/any.proto Any\r
27007 * @property {INamespace} google/protobuf/duration.proto Duration\r
27008 * @property {INamespace} google/protobuf/empty.proto Empty\r
27009 * @property {INamespace} google/protobuf/field_mask.proto FieldMask\r
27010 * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue\r
27011 * @property {INamespace} google/protobuf/timestamp.proto Timestamp\r
27012 * @property {INamespace} google/protobuf/wrappers.proto Wrappers\r
27013 * @example\r
27014 * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)\r
27015 * protobuf.common("descriptor", descriptorJson);\r
27016 *\r
27017 * // manually provides a custom definition (uses my.foo namespace)\r
27018 * protobuf.common("my/foo/bar.proto", myFooBarJson);\r
27019 */\r
27020function common(name, json) {\r
27021 if (!commonRe.test(name)) {\r
27022 name = "google/protobuf/" + name + ".proto";\r
27023 json = { nested: { google: { nested: { protobuf: { nested: json } } } } };\r
27024 }\r
27025 common[name] = json;\r
27026}\r
27027\r
27028// Not provided because of limited use (feel free to discuss or to provide yourself):\r
27029//\r
27030// google/protobuf/descriptor.proto\r
27031// google/protobuf/source_context.proto\r
27032// google/protobuf/type.proto\r
27033//\r
27034// Stripped and pre-parsed versions of these non-bundled files are instead available as part of\r
27035// the repository or package within the google/protobuf directory.\r
27036\r
27037common("any", {\r
27038\r
27039 /**\r
27040 * Properties of a google.protobuf.Any message.\r
27041 * @interface IAny\r
27042 * @type {Object}\r
27043 * @property {string} [typeUrl]\r
27044 * @property {Uint8Array} [bytes]\r
27045 * @memberof common\r
27046 */\r
27047 Any: {\r
27048 fields: {\r
27049 type_url: {\r
27050 type: "string",\r
27051 id: 1\r
27052 },\r
27053 value: {\r
27054 type: "bytes",\r
27055 id: 2\r
27056 }\r
27057 }\r
27058 }\r
27059});\r
27060\r
27061var timeType;\r
27062\r
27063common("duration", {\r
27064\r
27065 /**\r
27066 * Properties of a google.protobuf.Duration message.\r
27067 * @interface IDuration\r
27068 * @type {Object}\r
27069 * @property {number|Long} [seconds]\r
27070 * @property {number} [nanos]\r
27071 * @memberof common\r
27072 */\r
27073 Duration: timeType = {\r
27074 fields: {\r
27075 seconds: {\r
27076 type: "int64",\r
27077 id: 1\r
27078 },\r
27079 nanos: {\r
27080 type: "int32",\r
27081 id: 2\r
27082 }\r
27083 }\r
27084 }\r
27085});\r
27086\r
27087common("timestamp", {\r
27088\r
27089 /**\r
27090 * Properties of a google.protobuf.Timestamp message.\r
27091 * @interface ITimestamp\r
27092 * @type {Object}\r
27093 * @property {number|Long} [seconds]\r
27094 * @property {number} [nanos]\r
27095 * @memberof common\r
27096 */\r
27097 Timestamp: timeType\r
27098});\r
27099\r
27100common("empty", {\r
27101\r
27102 /**\r
27103 * Properties of a google.protobuf.Empty message.\r
27104 * @interface IEmpty\r
27105 * @memberof common\r
27106 */\r
27107 Empty: {\r
27108 fields: {}\r
27109 }\r
27110});\r
27111\r
27112common("struct", {\r
27113\r
27114 /**\r
27115 * Properties of a google.protobuf.Struct message.\r
27116 * @interface IStruct\r
27117 * @type {Object}\r
27118 * @property {Object.<string,IValue>} [fields]\r
27119 * @memberof common\r
27120 */\r
27121 Struct: {\r
27122 fields: {\r
27123 fields: {\r
27124 keyType: "string",\r
27125 type: "Value",\r
27126 id: 1\r
27127 }\r
27128 }\r
27129 },\r
27130\r
27131 /**\r
27132 * Properties of a google.protobuf.Value message.\r
27133 * @interface IValue\r
27134 * @type {Object}\r
27135 * @property {string} [kind]\r
27136 * @property {0} [nullValue]\r
27137 * @property {number} [numberValue]\r
27138 * @property {string} [stringValue]\r
27139 * @property {boolean} [boolValue]\r
27140 * @property {IStruct} [structValue]\r
27141 * @property {IListValue} [listValue]\r
27142 * @memberof common\r
27143 */\r
27144 Value: {\r
27145 oneofs: {\r
27146 kind: {\r
27147 oneof: [\r
27148 "nullValue",\r
27149 "numberValue",\r
27150 "stringValue",\r
27151 "boolValue",\r
27152 "structValue",\r
27153 "listValue"\r
27154 ]\r
27155 }\r
27156 },\r
27157 fields: {\r
27158 nullValue: {\r
27159 type: "NullValue",\r
27160 id: 1\r
27161 },\r
27162 numberValue: {\r
27163 type: "double",\r
27164 id: 2\r
27165 },\r
27166 stringValue: {\r
27167 type: "string",\r
27168 id: 3\r
27169 },\r
27170 boolValue: {\r
27171 type: "bool",\r
27172 id: 4\r
27173 },\r
27174 structValue: {\r
27175 type: "Struct",\r
27176 id: 5\r
27177 },\r
27178 listValue: {\r
27179 type: "ListValue",\r
27180 id: 6\r
27181 }\r
27182 }\r
27183 },\r
27184\r
27185 NullValue: {\r
27186 values: {\r
27187 NULL_VALUE: 0\r
27188 }\r
27189 },\r
27190\r
27191 /**\r
27192 * Properties of a google.protobuf.ListValue message.\r
27193 * @interface IListValue\r
27194 * @type {Object}\r
27195 * @property {Array.<IValue>} [values]\r
27196 * @memberof common\r
27197 */\r
27198 ListValue: {\r
27199 fields: {\r
27200 values: {\r
27201 rule: "repeated",\r
27202 type: "Value",\r
27203 id: 1\r
27204 }\r
27205 }\r
27206 }\r
27207});\r
27208\r
27209common("wrappers", {\r
27210\r
27211 /**\r
27212 * Properties of a google.protobuf.DoubleValue message.\r
27213 * @interface IDoubleValue\r
27214 * @type {Object}\r
27215 * @property {number} [value]\r
27216 * @memberof common\r
27217 */\r
27218 DoubleValue: {\r
27219 fields: {\r
27220 value: {\r
27221 type: "double",\r
27222 id: 1\r
27223 }\r
27224 }\r
27225 },\r
27226\r
27227 /**\r
27228 * Properties of a google.protobuf.FloatValue message.\r
27229 * @interface IFloatValue\r
27230 * @type {Object}\r
27231 * @property {number} [value]\r
27232 * @memberof common\r
27233 */\r
27234 FloatValue: {\r
27235 fields: {\r
27236 value: {\r
27237 type: "float",\r
27238 id: 1\r
27239 }\r
27240 }\r
27241 },\r
27242\r
27243 /**\r
27244 * Properties of a google.protobuf.Int64Value message.\r
27245 * @interface IInt64Value\r
27246 * @type {Object}\r
27247 * @property {number|Long} [value]\r
27248 * @memberof common\r
27249 */\r
27250 Int64Value: {\r
27251 fields: {\r
27252 value: {\r
27253 type: "int64",\r
27254 id: 1\r
27255 }\r
27256 }\r
27257 },\r
27258\r
27259 /**\r
27260 * Properties of a google.protobuf.UInt64Value message.\r
27261 * @interface IUInt64Value\r
27262 * @type {Object}\r
27263 * @property {number|Long} [value]\r
27264 * @memberof common\r
27265 */\r
27266 UInt64Value: {\r
27267 fields: {\r
27268 value: {\r
27269 type: "uint64",\r
27270 id: 1\r
27271 }\r
27272 }\r
27273 },\r
27274\r
27275 /**\r
27276 * Properties of a google.protobuf.Int32Value message.\r
27277 * @interface IInt32Value\r
27278 * @type {Object}\r
27279 * @property {number} [value]\r
27280 * @memberof common\r
27281 */\r
27282 Int32Value: {\r
27283 fields: {\r
27284 value: {\r
27285 type: "int32",\r
27286 id: 1\r
27287 }\r
27288 }\r
27289 },\r
27290\r
27291 /**\r
27292 * Properties of a google.protobuf.UInt32Value message.\r
27293 * @interface IUInt32Value\r
27294 * @type {Object}\r
27295 * @property {number} [value]\r
27296 * @memberof common\r
27297 */\r
27298 UInt32Value: {\r
27299 fields: {\r
27300 value: {\r
27301 type: "uint32",\r
27302 id: 1\r
27303 }\r
27304 }\r
27305 },\r
27306\r
27307 /**\r
27308 * Properties of a google.protobuf.BoolValue message.\r
27309 * @interface IBoolValue\r
27310 * @type {Object}\r
27311 * @property {boolean} [value]\r
27312 * @memberof common\r
27313 */\r
27314 BoolValue: {\r
27315 fields: {\r
27316 value: {\r
27317 type: "bool",\r
27318 id: 1\r
27319 }\r
27320 }\r
27321 },\r
27322\r
27323 /**\r
27324 * Properties of a google.protobuf.StringValue message.\r
27325 * @interface IStringValue\r
27326 * @type {Object}\r
27327 * @property {string} [value]\r
27328 * @memberof common\r
27329 */\r
27330 StringValue: {\r
27331 fields: {\r
27332 value: {\r
27333 type: "string",\r
27334 id: 1\r
27335 }\r
27336 }\r
27337 },\r
27338\r
27339 /**\r
27340 * Properties of a google.protobuf.BytesValue message.\r
27341 * @interface IBytesValue\r
27342 * @type {Object}\r
27343 * @property {Uint8Array} [value]\r
27344 * @memberof common\r
27345 */\r
27346 BytesValue: {\r
27347 fields: {\r
27348 value: {\r
27349 type: "bytes",\r
27350 id: 1\r
27351 }\r
27352 }\r
27353 }\r
27354});\r
27355\r
27356common("field_mask", {\r
27357\r
27358 /**\r
27359 * Properties of a google.protobuf.FieldMask message.\r
27360 * @interface IDoubleValue\r
27361 * @type {Object}\r
27362 * @property {number} [value]\r
27363 * @memberof common\r
27364 */\r
27365 FieldMask: {\r
27366 fields: {\r
27367 paths: {\r
27368 rule: "repeated",\r
27369 type: "string",\r
27370 id: 1\r
27371 }\r
27372 }\r
27373 }\r
27374});\r
27375\r
27376/**\r
27377 * Gets the root definition of the specified common proto file.\r
27378 *\r
27379 * Bundled definitions are:\r
27380 * - google/protobuf/any.proto\r
27381 * - google/protobuf/duration.proto\r
27382 * - google/protobuf/empty.proto\r
27383 * - google/protobuf/field_mask.proto\r
27384 * - google/protobuf/struct.proto\r
27385 * - google/protobuf/timestamp.proto\r
27386 * - google/protobuf/wrappers.proto\r
27387 *\r
27388 * @param {string} file Proto file name\r
27389 * @returns {INamespace|null} Root definition or `null` if not defined\r
27390 */\r
27391common.get = function get(file) {\r
27392 return common[file] || null;\r
27393};\r
27394
27395},{}],193:[function(require,module,exports){
27396"use strict";\r
27397/**\r
27398 * Runtime message from/to plain object converters.\r
27399 * @namespace\r
27400 */\r
27401var converter = exports;\r
27402\r
27403var Enum = require("./enum"),\r
27404 util = require("./util");\r
27405\r
27406/**\r
27407 * Generates a partial value fromObject conveter.\r
27408 * @param {Codegen} gen Codegen instance\r
27409 * @param {Field} field Reflected field\r
27410 * @param {number} fieldIndex Field index\r
27411 * @param {string} prop Property reference\r
27412 * @returns {Codegen} Codegen instance\r
27413 * @ignore\r
27414 */\r
27415function genValuePartial_fromObject(gen, field, fieldIndex, prop) {\r
27416 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27417 if (field.resolvedType) {\r
27418 if (field.resolvedType instanceof Enum) { gen\r
27419 ("switch(d%s){", prop);\r
27420 for (var values = field.resolvedType.values, keys = Object.keys(values), i = 0; i < keys.length; ++i) {\r
27421 if (field.repeated && values[keys[i]] === field.typeDefault) gen\r
27422 ("default:");\r
27423 gen\r
27424 ("case%j:", keys[i])\r
27425 ("case %i:", values[keys[i]])\r
27426 ("m%s=%j", prop, values[keys[i]])\r
27427 ("break");\r
27428 } gen\r
27429 ("}");\r
27430 } else gen\r
27431 ("if(typeof d%s!==\"object\")", prop)\r
27432 ("throw TypeError(%j)", field.fullName + ": object expected")\r
27433 ("m%s=types[%i].fromObject(d%s)", prop, fieldIndex, prop);\r
27434 } else {\r
27435 var isUnsigned = false;\r
27436 switch (field.type) {\r
27437 case "double":\r
27438 case "float": gen\r
27439 ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity"\r
27440 break;\r
27441 case "uint32":\r
27442 case "fixed32": gen\r
27443 ("m%s=d%s>>>0", prop, prop);\r
27444 break;\r
27445 case "int32":\r
27446 case "sint32":\r
27447 case "sfixed32": gen\r
27448 ("m%s=d%s|0", prop, prop);\r
27449 break;\r
27450 case "uint64":\r
27451 isUnsigned = true;\r
27452 // eslint-disable-line no-fallthrough\r
27453 case "int64":\r
27454 case "sint64":\r
27455 case "fixed64":\r
27456 case "sfixed64": gen\r
27457 ("if(util.Long)")\r
27458 ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop, prop, isUnsigned)\r
27459 ("else if(typeof d%s===\"string\")", prop)\r
27460 ("m%s=parseInt(d%s,10)", prop, prop)\r
27461 ("else if(typeof d%s===\"number\")", prop)\r
27462 ("m%s=d%s", prop, prop)\r
27463 ("else if(typeof d%s===\"object\")", prop)\r
27464 ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop, prop, prop, isUnsigned ? "true" : "");\r
27465 break;\r
27466 case "bytes": gen\r
27467 ("if(typeof d%s===\"string\")", prop)\r
27468 ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop, prop, prop)\r
27469 ("else if(d%s.length)", prop)\r
27470 ("m%s=d%s", prop, prop);\r
27471 break;\r
27472 case "string": gen\r
27473 ("m%s=String(d%s)", prop, prop);\r
27474 break;\r
27475 case "bool": gen\r
27476 ("m%s=Boolean(d%s)", prop, prop);\r
27477 break;\r
27478 /* default: gen\r
27479 ("m%s=d%s", prop, prop);\r
27480 break; */\r
27481 }\r
27482 }\r
27483 return gen;\r
27484 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27485}\r
27486\r
27487/**\r
27488 * Generates a plain object to runtime message converter specific to the specified message type.\r
27489 * @param {Type} mtype Message type\r
27490 * @returns {Codegen} Codegen instance\r
27491 */\r
27492converter.fromObject = function fromObject(mtype) {\r
27493 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27494 var fields = mtype.fieldsArray;\r
27495 var gen = util.codegen(["d"], mtype.name + "$fromObject")\r
27496 ("if(d instanceof this.ctor)")\r
27497 ("return d");\r
27498 if (!fields.length) return gen\r
27499 ("return new this.ctor");\r
27500 gen\r
27501 ("var m=new this.ctor");\r
27502 for (var i = 0; i < fields.length; ++i) {\r
27503 var field = fields[i].resolve(),\r
27504 prop = util.safeProp(field.name);\r
27505\r
27506 // Map fields\r
27507 if (field.map) { gen\r
27508 ("if(d%s){", prop)\r
27509 ("if(typeof d%s!==\"object\")", prop)\r
27510 ("throw TypeError(%j)", field.fullName + ": object expected")\r
27511 ("m%s={}", prop)\r
27512 ("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop);\r
27513 genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[ks[i]]")\r
27514 ("}")\r
27515 ("}");\r
27516\r
27517 // Repeated fields\r
27518 } else if (field.repeated) { gen\r
27519 ("if(d%s){", prop)\r
27520 ("if(!Array.isArray(d%s))", prop)\r
27521 ("throw TypeError(%j)", field.fullName + ": array expected")\r
27522 ("m%s=[]", prop)\r
27523 ("for(var i=0;i<d%s.length;++i){", prop);\r
27524 genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[i]")\r
27525 ("}")\r
27526 ("}");\r
27527\r
27528 // Non-repeated fields\r
27529 } else {\r
27530 if (!(field.resolvedType instanceof Enum)) gen // no need to test for null/undefined if an enum (uses switch)\r
27531 ("if(d%s!=null){", prop); // !== undefined && !== null\r
27532 genValuePartial_fromObject(gen, field, /* not sorted */ i, prop);\r
27533 if (!(field.resolvedType instanceof Enum)) gen\r
27534 ("}");\r
27535 }\r
27536 } return gen\r
27537 ("return m");\r
27538 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27539};\r
27540\r
27541/**\r
27542 * Generates a partial value toObject converter.\r
27543 * @param {Codegen} gen Codegen instance\r
27544 * @param {Field} field Reflected field\r
27545 * @param {number} fieldIndex Field index\r
27546 * @param {string} prop Property reference\r
27547 * @returns {Codegen} Codegen instance\r
27548 * @ignore\r
27549 */\r
27550function genValuePartial_toObject(gen, field, fieldIndex, prop) {\r
27551 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27552 if (field.resolvedType) {\r
27553 if (field.resolvedType instanceof Enum) gen\r
27554 ("d%s=o.enums===String?types[%i].values[m%s]:m%s", prop, fieldIndex, prop, prop);\r
27555 else gen\r
27556 ("d%s=types[%i].toObject(m%s,o)", prop, fieldIndex, prop);\r
27557 } else {\r
27558 var isUnsigned = false;\r
27559 switch (field.type) {\r
27560 case "double":\r
27561 case "float": gen\r
27562 ("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", prop, prop, prop, prop);\r
27563 break;\r
27564 case "uint64":\r
27565 isUnsigned = true;\r
27566 // eslint-disable-line no-fallthrough\r
27567 case "int64":\r
27568 case "sint64":\r
27569 case "fixed64":\r
27570 case "sfixed64": gen\r
27571 ("if(typeof m%s===\"number\")", prop)\r
27572 ("d%s=o.longs===String?String(m%s):m%s", prop, prop, prop)\r
27573 ("else") // Long-like\r
27574 ("d%s=o.longs===String?util.Long.prototype.toString.call(m%s):o.longs===Number?new util.LongBits(m%s.low>>>0,m%s.high>>>0).toNumber(%s):m%s", prop, prop, prop, prop, isUnsigned ? "true": "", prop);\r
27575 break;\r
27576 case "bytes": gen\r
27577 ("d%s=o.bytes===String?util.base64.encode(m%s,0,m%s.length):o.bytes===Array?Array.prototype.slice.call(m%s):m%s", prop, prop, prop, prop, prop);\r
27578 break;\r
27579 default: gen\r
27580 ("d%s=m%s", prop, prop);\r
27581 break;\r
27582 }\r
27583 }\r
27584 return gen;\r
27585 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27586}\r
27587\r
27588/**\r
27589 * Generates a runtime message to plain object converter specific to the specified message type.\r
27590 * @param {Type} mtype Message type\r
27591 * @returns {Codegen} Codegen instance\r
27592 */\r
27593converter.toObject = function toObject(mtype) {\r
27594 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27595 var fields = mtype.fieldsArray.slice().sort(util.compareFieldsById);\r
27596 if (!fields.length)\r
27597 return util.codegen()("return {}");\r
27598 var gen = util.codegen(["m", "o"], mtype.name + "$toObject")\r
27599 ("if(!o)")\r
27600 ("o={}")\r
27601 ("var d={}");\r
27602\r
27603 var repeatedFields = [],\r
27604 mapFields = [],\r
27605 normalFields = [],\r
27606 i = 0;\r
27607 for (; i < fields.length; ++i)\r
27608 if (!fields[i].partOf)\r
27609 ( fields[i].resolve().repeated ? repeatedFields\r
27610 : fields[i].map ? mapFields\r
27611 : normalFields).push(fields[i]);\r
27612\r
27613 if (repeatedFields.length) { gen\r
27614 ("if(o.arrays||o.defaults){");\r
27615 for (i = 0; i < repeatedFields.length; ++i) gen\r
27616 ("d%s=[]", util.safeProp(repeatedFields[i].name));\r
27617 gen\r
27618 ("}");\r
27619 }\r
27620\r
27621 if (mapFields.length) { gen\r
27622 ("if(o.objects||o.defaults){");\r
27623 for (i = 0; i < mapFields.length; ++i) gen\r
27624 ("d%s={}", util.safeProp(mapFields[i].name));\r
27625 gen\r
27626 ("}");\r
27627 }\r
27628\r
27629 if (normalFields.length) { gen\r
27630 ("if(o.defaults){");\r
27631 for (i = 0; i < normalFields.length; ++i) {\r
27632 var field = normalFields[i],\r
27633 prop = util.safeProp(field.name);\r
27634 if (field.resolvedType instanceof Enum) gen\r
27635 ("d%s=o.enums===String?%j:%j", prop, field.resolvedType.valuesById[field.typeDefault], field.typeDefault);\r
27636 else if (field.long) gen\r
27637 ("if(util.Long){")\r
27638 ("var n=new util.Long(%i,%i,%j)", field.typeDefault.low, field.typeDefault.high, field.typeDefault.unsigned)\r
27639 ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop)\r
27640 ("}else")\r
27641 ("d%s=o.longs===String?%j:%i", prop, field.typeDefault.toString(), field.typeDefault.toNumber());\r
27642 else if (field.bytes) gen\r
27643 ("d%s=o.bytes===String?%j:%s", prop, String.fromCharCode.apply(String, field.typeDefault), "[" + Array.prototype.slice.call(field.typeDefault).join(",") + "]");\r
27644 else gen\r
27645 ("d%s=%j", prop, field.typeDefault); // also messages (=null)\r
27646 } gen\r
27647 ("}");\r
27648 }\r
27649 var hasKs2 = false;\r
27650 for (i = 0; i < fields.length; ++i) {\r
27651 var field = fields[i],\r
27652 index = mtype._fieldsArray.indexOf(field),\r
27653 prop = util.safeProp(field.name);\r
27654 if (field.map) {\r
27655 if (!hasKs2) { hasKs2 = true; gen\r
27656 ("var ks2");\r
27657 } gen\r
27658 ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop)\r
27659 ("d%s={}", prop)\r
27660 ("for(var j=0;j<ks2.length;++j){");\r
27661 genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[ks2[j]]")\r
27662 ("}");\r
27663 } else if (field.repeated) { gen\r
27664 ("if(m%s&&m%s.length){", prop, prop)\r
27665 ("d%s=[]", prop)\r
27666 ("for(var j=0;j<m%s.length;++j){", prop);\r
27667 genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[j]")\r
27668 ("}");\r
27669 } else { gen\r
27670 ("if(m%s!=null&&m.hasOwnProperty(%j)){", prop, field.name); // !== undefined && !== null\r
27671 genValuePartial_toObject(gen, field, /* sorted */ index, prop);\r
27672 if (field.partOf) gen\r
27673 ("if(o.oneofs)")\r
27674 ("d%s=%j", util.safeProp(field.partOf.name), field.name);\r
27675 }\r
27676 gen\r
27677 ("}");\r
27678 }\r
27679 return gen\r
27680 ("return d");\r
27681 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27682};\r
27683
27684},{"./enum":196,"./util":218}],194:[function(require,module,exports){
27685"use strict";\r
27686module.exports = decoder;\r
27687\r
27688var Enum = require("./enum"),\r
27689 types = require("./types"),\r
27690 util = require("./util");\r
27691\r
27692function missing(field) {\r
27693 return "missing required '" + field.name + "'";\r
27694}\r
27695\r
27696/**\r
27697 * Generates a decoder specific to the specified message type.\r
27698 * @param {Type} mtype Message type\r
27699 * @returns {Codegen} Codegen instance\r
27700 */\r
27701function decoder(mtype) {\r
27702 /* eslint-disable no-unexpected-multiline */\r
27703 var gen = util.codegen(["r", "l"], mtype.name + "$decode")\r
27704 ("if(!(r instanceof Reader))")\r
27705 ("r=Reader.create(r)")\r
27706 ("var c=l===undefined?r.len:r.pos+l,m=new this.ctor" + (mtype.fieldsArray.filter(function(field) { return field.map; }).length ? ",k" : ""))\r
27707 ("while(r.pos<c){")\r
27708 ("var t=r.uint32()");\r
27709 if (mtype.group) gen\r
27710 ("if((t&7)===4)")\r
27711 ("break");\r
27712 gen\r
27713 ("switch(t>>>3){");\r
27714\r
27715 var i = 0;\r
27716 for (; i < /* initializes */ mtype.fieldsArray.length; ++i) {\r
27717 var field = mtype._fieldsArray[i].resolve(),\r
27718 type = field.resolvedType instanceof Enum ? "int32" : field.type,\r
27719 ref = "m" + util.safeProp(field.name); gen\r
27720 ("case %i:", field.id);\r
27721\r
27722 // Map fields\r
27723 if (field.map) { gen\r
27724 ("r.skip().pos++") // assumes id 1 + key wireType\r
27725 ("if(%s===util.emptyObject)", ref)\r
27726 ("%s={}", ref)\r
27727 ("k=r.%s()", field.keyType)\r
27728 ("r.pos++"); // assumes id 2 + value wireType\r
27729 if (types.long[field.keyType] !== undefined) {\r
27730 if (types.basic[type] === undefined) gen\r
27731 ("%s[typeof k===\"object\"?util.longToHash(k):k]=types[%i].decode(r,r.uint32())", ref, i); // can't be groups\r
27732 else gen\r
27733 ("%s[typeof k===\"object\"?util.longToHash(k):k]=r.%s()", ref, type);\r
27734 } else {\r
27735 if (types.basic[type] === undefined) gen\r
27736 ("%s[k]=types[%i].decode(r,r.uint32())", ref, i); // can't be groups\r
27737 else gen\r
27738 ("%s[k]=r.%s()", ref, type);\r
27739 }\r
27740\r
27741 // Repeated fields\r
27742 } else if (field.repeated) { gen\r
27743\r
27744 ("if(!(%s&&%s.length))", ref, ref)\r
27745 ("%s=[]", ref);\r
27746\r
27747 // Packable (always check for forward and backward compatiblity)\r
27748 if (types.packed[type] !== undefined) gen\r
27749 ("if((t&7)===2){")\r
27750 ("var c2=r.uint32()+r.pos")\r
27751 ("while(r.pos<c2)")\r
27752 ("%s.push(r.%s())", ref, type)\r
27753 ("}else");\r
27754\r
27755 // Non-packed\r
27756 if (types.basic[type] === undefined) gen(field.resolvedType.group\r
27757 ? "%s.push(types[%i].decode(r))"\r
27758 : "%s.push(types[%i].decode(r,r.uint32()))", ref, i);\r
27759 else gen\r
27760 ("%s.push(r.%s())", ref, type);\r
27761\r
27762 // Non-repeated\r
27763 } else if (types.basic[type] === undefined) gen(field.resolvedType.group\r
27764 ? "%s=types[%i].decode(r)"\r
27765 : "%s=types[%i].decode(r,r.uint32())", ref, i);\r
27766 else gen\r
27767 ("%s=r.%s()", ref, type);\r
27768 gen\r
27769 ("break");\r
27770 // Unknown fields\r
27771 } gen\r
27772 ("default:")\r
27773 ("r.skipType(t&7)")\r
27774 ("break")\r
27775\r
27776 ("}")\r
27777 ("}");\r
27778\r
27779 // Field presence\r
27780 for (i = 0; i < mtype._fieldsArray.length; ++i) {\r
27781 var rfield = mtype._fieldsArray[i];\r
27782 if (rfield.required) gen\r
27783 ("if(!m.hasOwnProperty(%j))", rfield.name)\r
27784 ("throw util.ProtocolError(%j,{instance:m})", missing(rfield));\r
27785 }\r
27786\r
27787 return gen\r
27788 ("return m");\r
27789 /* eslint-enable no-unexpected-multiline */\r
27790}\r
27791
27792},{"./enum":196,"./types":217,"./util":218}],195:[function(require,module,exports){
27793"use strict";\r
27794module.exports = encoder;\r
27795\r
27796var Enum = require("./enum"),\r
27797 types = require("./types"),\r
27798 util = require("./util");\r
27799\r
27800/**\r
27801 * Generates a partial message type encoder.\r
27802 * @param {Codegen} gen Codegen instance\r
27803 * @param {Field} field Reflected field\r
27804 * @param {number} fieldIndex Field index\r
27805 * @param {string} ref Variable reference\r
27806 * @returns {Codegen} Codegen instance\r
27807 * @ignore\r
27808 */\r
27809function genTypePartial(gen, field, fieldIndex, ref) {\r
27810 return field.resolvedType.group\r
27811 ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex, ref, (field.id << 3 | 3) >>> 0, (field.id << 3 | 4) >>> 0)\r
27812 : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex, ref, (field.id << 3 | 2) >>> 0);\r
27813}\r
27814\r
27815/**\r
27816 * Generates an encoder specific to the specified message type.\r
27817 * @param {Type} mtype Message type\r
27818 * @returns {Codegen} Codegen instance\r
27819 */\r
27820function encoder(mtype) {\r
27821 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27822 var gen = util.codegen(["m", "w"], mtype.name + "$encode")\r
27823 ("if(!w)")\r
27824 ("w=Writer.create()");\r
27825\r
27826 var i, ref;\r
27827\r
27828 // "when a message is serialized its known fields should be written sequentially by field number"\r
27829 var fields = /* initializes */ mtype.fieldsArray.slice().sort(util.compareFieldsById);\r
27830\r
27831 for (var i = 0; i < fields.length; ++i) {\r
27832 var field = fields[i].resolve(),\r
27833 index = mtype._fieldsArray.indexOf(field),\r
27834 type = field.resolvedType instanceof Enum ? "int32" : field.type,\r
27835 wireType = types.basic[type];\r
27836 ref = "m" + util.safeProp(field.name);\r
27837\r
27838 // Map fields\r
27839 if (field.map) {\r
27840 gen\r
27841 ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name) // !== undefined && !== null\r
27842 ("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref)\r
27843 ("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field.id << 3 | 2) >>> 0, 8 | types.mapKey[field.keyType], field.keyType);\r
27844 if (wireType === undefined) gen\r
27845 ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index, ref); // can't be groups\r
27846 else gen\r
27847 (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref);\r
27848 gen\r
27849 ("}")\r
27850 ("}");\r
27851\r
27852 // Repeated fields\r
27853 } else if (field.repeated) { gen\r
27854 ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null\r
27855\r
27856 // Packed repeated\r
27857 if (field.packed && types.packed[type] !== undefined) { gen\r
27858\r
27859 ("w.uint32(%i).fork()", (field.id << 3 | 2) >>> 0)\r
27860 ("for(var i=0;i<%s.length;++i)", ref)\r
27861 ("w.%s(%s[i])", type, ref)\r
27862 ("w.ldelim()");\r
27863\r
27864 // Non-packed\r
27865 } else { gen\r
27866\r
27867 ("for(var i=0;i<%s.length;++i)", ref);\r
27868 if (wireType === undefined)\r
27869 genTypePartial(gen, field, index, ref + "[i]");\r
27870 else gen\r
27871 ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref);\r
27872\r
27873 } gen\r
27874 ("}");\r
27875\r
27876 // Non-repeated\r
27877 } else {\r
27878 if (field.optional) gen\r
27879 ("if(%s!=null&&m.hasOwnProperty(%j))", ref, field.name); // !== undefined && !== null\r
27880\r
27881 if (wireType === undefined)\r
27882 genTypePartial(gen, field, index, ref);\r
27883 else gen\r
27884 ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref);\r
27885\r
27886 }\r
27887 }\r
27888\r
27889 return gen\r
27890 ("return w");\r
27891 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */\r
27892}
27893},{"./enum":196,"./types":217,"./util":218}],196:[function(require,module,exports){
27894"use strict";\r
27895module.exports = Enum;\r
27896\r
27897// extends ReflectionObject\r
27898var ReflectionObject = require("./object");\r
27899((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum";\r
27900\r
27901var Namespace = require("./namespace"),\r
27902 util = require("./util");\r
27903\r
27904/**\r
27905 * Constructs a new enum instance.\r
27906 * @classdesc Reflected enum.\r
27907 * @extends ReflectionObject\r
27908 * @constructor\r
27909 * @param {string} name Unique name within its namespace\r
27910 * @param {Object.<string,number>} [values] Enum values as an object, by name\r
27911 * @param {Object.<string,*>} [options] Declared options\r
27912 * @param {string} [comment] The comment for this enum\r
27913 * @param {Object.<string,string>} [comments] The value comments for this enum\r
27914 */\r
27915function Enum(name, values, options, comment, comments) {\r
27916 ReflectionObject.call(this, name, options);\r
27917\r
27918 if (values && typeof values !== "object")\r
27919 throw TypeError("values must be an object");\r
27920\r
27921 /**\r
27922 * Enum values by id.\r
27923 * @type {Object.<number,string>}\r
27924 */\r
27925 this.valuesById = {};\r
27926\r
27927 /**\r
27928 * Enum values by name.\r
27929 * @type {Object.<string,number>}\r
27930 */\r
27931 this.values = Object.create(this.valuesById); // toJSON, marker\r
27932\r
27933 /**\r
27934 * Enum comment text.\r
27935 * @type {string|null}\r
27936 */\r
27937 this.comment = comment;\r
27938\r
27939 /**\r
27940 * Value comment texts, if any.\r
27941 * @type {Object.<string,string>}\r
27942 */\r
27943 this.comments = comments || {};\r
27944\r
27945 /**\r
27946 * Reserved ranges, if any.\r
27947 * @type {Array.<number[]|string>}\r
27948 */\r
27949 this.reserved = undefined; // toJSON\r
27950\r
27951 // Note that values inherit valuesById on their prototype which makes them a TypeScript-\r
27952 // compatible enum. This is used by pbts to write actual enum definitions that work for\r
27953 // static and reflection code alike instead of emitting generic object definitions.\r
27954\r
27955 if (values)\r
27956 for (var keys = Object.keys(values), i = 0; i < keys.length; ++i)\r
27957 if (typeof values[keys[i]] === "number") // use forward entries only\r
27958 this.valuesById[ this.values[keys[i]] = values[keys[i]] ] = keys[i];\r
27959}\r
27960\r
27961/**\r
27962 * Enum descriptor.\r
27963 * @interface IEnum\r
27964 * @property {Object.<string,number>} values Enum values\r
27965 * @property {Object.<string,*>} [options] Enum options\r
27966 */\r
27967\r
27968/**\r
27969 * Constructs an enum from an enum descriptor.\r
27970 * @param {string} name Enum name\r
27971 * @param {IEnum} json Enum descriptor\r
27972 * @returns {Enum} Created enum\r
27973 * @throws {TypeError} If arguments are invalid\r
27974 */\r
27975Enum.fromJSON = function fromJSON(name, json) {\r
27976 var enm = new Enum(name, json.values, json.options, json.comment, json.comments);\r
27977 enm.reserved = json.reserved;\r
27978 return enm;\r
27979};\r
27980\r
27981/**\r
27982 * Converts this enum to an enum descriptor.\r
27983 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r
27984 * @returns {IEnum} Enum descriptor\r
27985 */\r
27986Enum.prototype.toJSON = function toJSON(toJSONOptions) {\r
27987 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r
27988 return util.toObject([\r
27989 "options" , this.options,\r
27990 "values" , this.values,\r
27991 "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,\r
27992 "comment" , keepComments ? this.comment : undefined,\r
27993 "comments" , keepComments ? this.comments : undefined\r
27994 ]);\r
27995};\r
27996\r
27997/**\r
27998 * Adds a value to this enum.\r
27999 * @param {string} name Value name\r
28000 * @param {number} id Value id\r
28001 * @param {string} [comment] Comment, if any\r
28002 * @returns {Enum} `this`\r
28003 * @throws {TypeError} If arguments are invalid\r
28004 * @throws {Error} If there is already a value with this name or id\r
28005 */\r
28006Enum.prototype.add = function add(name, id, comment) {\r
28007 // utilized by the parser but not by .fromJSON\r
28008\r
28009 if (!util.isString(name))\r
28010 throw TypeError("name must be a string");\r
28011\r
28012 if (!util.isInteger(id))\r
28013 throw TypeError("id must be an integer");\r
28014\r
28015 if (this.values[name] !== undefined)\r
28016 throw Error("duplicate name '" + name + "' in " + this);\r
28017\r
28018 if (this.isReservedId(id))\r
28019 throw Error("id " + id + " is reserved in " + this);\r
28020\r
28021 if (this.isReservedName(name))\r
28022 throw Error("name '" + name + "' is reserved in " + this);\r
28023\r
28024 if (this.valuesById[id] !== undefined) {\r
28025 if (!(this.options && this.options.allow_alias))\r
28026 throw Error("duplicate id " + id + " in " + this);\r
28027 this.values[name] = id;\r
28028 } else\r
28029 this.valuesById[this.values[name] = id] = name;\r
28030\r
28031 this.comments[name] = comment || null;\r
28032 return this;\r
28033};\r
28034\r
28035/**\r
28036 * Removes a value from this enum\r
28037 * @param {string} name Value name\r
28038 * @returns {Enum} `this`\r
28039 * @throws {TypeError} If arguments are invalid\r
28040 * @throws {Error} If `name` is not a name of this enum\r
28041 */\r
28042Enum.prototype.remove = function remove(name) {\r
28043\r
28044 if (!util.isString(name))\r
28045 throw TypeError("name must be a string");\r
28046\r
28047 var val = this.values[name];\r
28048 if (val == null)\r
28049 throw Error("name '" + name + "' does not exist in " + this);\r
28050\r
28051 delete this.valuesById[val];\r
28052 delete this.values[name];\r
28053 delete this.comments[name];\r
28054\r
28055 return this;\r
28056};\r
28057\r
28058/**\r
28059 * Tests if the specified id is reserved.\r
28060 * @param {number} id Id to test\r
28061 * @returns {boolean} `true` if reserved, otherwise `false`\r
28062 */\r
28063Enum.prototype.isReservedId = function isReservedId(id) {\r
28064 return Namespace.isReservedId(this.reserved, id);\r
28065};\r
28066\r
28067/**\r
28068 * Tests if the specified name is reserved.\r
28069 * @param {string} name Name to test\r
28070 * @returns {boolean} `true` if reserved, otherwise `false`\r
28071 */\r
28072Enum.prototype.isReservedName = function isReservedName(name) {\r
28073 return Namespace.isReservedName(this.reserved, name);\r
28074};\r
28075
28076},{"./namespace":204,"./object":205,"./util":218}],197:[function(require,module,exports){
28077"use strict";\r
28078module.exports = Field;\r
28079\r
28080// extends ReflectionObject\r
28081var ReflectionObject = require("./object");\r
28082((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field";\r
28083\r
28084var Enum = require("./enum"),\r
28085 types = require("./types"),\r
28086 util = require("./util");\r
28087\r
28088var Type; // cyclic\r
28089\r
28090var ruleRe = /^required|optional|repeated$/;\r
28091\r
28092/**\r
28093 * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.\r
28094 * @name Field\r
28095 * @classdesc Reflected message field.\r
28096 * @extends FieldBase\r
28097 * @constructor\r
28098 * @param {string} name Unique name within its namespace\r
28099 * @param {number} id Unique id within its namespace\r
28100 * @param {string} type Value type\r
28101 * @param {string|Object.<string,*>} [rule="optional"] Field rule\r
28102 * @param {string|Object.<string,*>} [extend] Extended type if different from parent\r
28103 * @param {Object.<string,*>} [options] Declared options\r
28104 */\r
28105\r
28106/**\r
28107 * Constructs a field from a field descriptor.\r
28108 * @param {string} name Field name\r
28109 * @param {IField} json Field descriptor\r
28110 * @returns {Field} Created field\r
28111 * @throws {TypeError} If arguments are invalid\r
28112 */\r
28113Field.fromJSON = function fromJSON(name, json) {\r
28114 return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment);\r
28115};\r
28116\r
28117/**\r
28118 * Not an actual constructor. Use {@link Field} instead.\r
28119 * @classdesc Base class of all reflected message fields. This is not an actual class but here for the sake of having consistent type definitions.\r
28120 * @exports FieldBase\r
28121 * @extends ReflectionObject\r
28122 * @constructor\r
28123 * @param {string} name Unique name within its namespace\r
28124 * @param {number} id Unique id within its namespace\r
28125 * @param {string} type Value type\r
28126 * @param {string|Object.<string,*>} [rule="optional"] Field rule\r
28127 * @param {string|Object.<string,*>} [extend] Extended type if different from parent\r
28128 * @param {Object.<string,*>} [options] Declared options\r
28129 * @param {string} [comment] Comment associated with this field\r
28130 */\r
28131function Field(name, id, type, rule, extend, options, comment) {\r
28132\r
28133 if (util.isObject(rule)) {\r
28134 comment = extend;\r
28135 options = rule;\r
28136 rule = extend = undefined;\r
28137 } else if (util.isObject(extend)) {\r
28138 comment = options;\r
28139 options = extend;\r
28140 extend = undefined;\r
28141 }\r
28142\r
28143 ReflectionObject.call(this, name, options);\r
28144\r
28145 if (!util.isInteger(id) || id < 0)\r
28146 throw TypeError("id must be a non-negative integer");\r
28147\r
28148 if (!util.isString(type))\r
28149 throw TypeError("type must be a string");\r
28150\r
28151 if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase()))\r
28152 throw TypeError("rule must be a string rule");\r
28153\r
28154 if (extend !== undefined && !util.isString(extend))\r
28155 throw TypeError("extend must be a string");\r
28156\r
28157 /**\r
28158 * Field rule, if any.\r
28159 * @type {string|undefined}\r
28160 */\r
28161 this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON\r
28162\r
28163 /**\r
28164 * Field type.\r
28165 * @type {string}\r
28166 */\r
28167 this.type = type; // toJSON\r
28168\r
28169 /**\r
28170 * Unique field id.\r
28171 * @type {number}\r
28172 */\r
28173 this.id = id; // toJSON, marker\r
28174\r
28175 /**\r
28176 * Extended type if different from parent.\r
28177 * @type {string|undefined}\r
28178 */\r
28179 this.extend = extend || undefined; // toJSON\r
28180\r
28181 /**\r
28182 * Whether this field is required.\r
28183 * @type {boolean}\r
28184 */\r
28185 this.required = rule === "required";\r
28186\r
28187 /**\r
28188 * Whether this field is optional.\r
28189 * @type {boolean}\r
28190 */\r
28191 this.optional = !this.required;\r
28192\r
28193 /**\r
28194 * Whether this field is repeated.\r
28195 * @type {boolean}\r
28196 */\r
28197 this.repeated = rule === "repeated";\r
28198\r
28199 /**\r
28200 * Whether this field is a map or not.\r
28201 * @type {boolean}\r
28202 */\r
28203 this.map = false;\r
28204\r
28205 /**\r
28206 * Message this field belongs to.\r
28207 * @type {Type|null}\r
28208 */\r
28209 this.message = null;\r
28210\r
28211 /**\r
28212 * OneOf this field belongs to, if any,\r
28213 * @type {OneOf|null}\r
28214 */\r
28215 this.partOf = null;\r
28216\r
28217 /**\r
28218 * The field type's default value.\r
28219 * @type {*}\r
28220 */\r
28221 this.typeDefault = null;\r
28222\r
28223 /**\r
28224 * The field's default value on prototypes.\r
28225 * @type {*}\r
28226 */\r
28227 this.defaultValue = null;\r
28228\r
28229 /**\r
28230 * Whether this field's value should be treated as a long.\r
28231 * @type {boolean}\r
28232 */\r
28233 this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false;\r
28234\r
28235 /**\r
28236 * Whether this field's value is a buffer.\r
28237 * @type {boolean}\r
28238 */\r
28239 this.bytes = type === "bytes";\r
28240\r
28241 /**\r
28242 * Resolved type if not a basic type.\r
28243 * @type {Type|Enum|null}\r
28244 */\r
28245 this.resolvedType = null;\r
28246\r
28247 /**\r
28248 * Sister-field within the extended type if a declaring extension field.\r
28249 * @type {Field|null}\r
28250 */\r
28251 this.extensionField = null;\r
28252\r
28253 /**\r
28254 * Sister-field within the declaring namespace if an extended field.\r
28255 * @type {Field|null}\r
28256 */\r
28257 this.declaringField = null;\r
28258\r
28259 /**\r
28260 * Internally remembers whether this field is packed.\r
28261 * @type {boolean|null}\r
28262 * @private\r
28263 */\r
28264 this._packed = null;\r
28265\r
28266 /**\r
28267 * Comment for this field.\r
28268 * @type {string|null}\r
28269 */\r
28270 this.comment = comment;\r
28271}\r
28272\r
28273/**\r
28274 * Determines whether this field is packed. Only relevant when repeated and working with proto2.\r
28275 * @name Field#packed\r
28276 * @type {boolean}\r
28277 * @readonly\r
28278 */\r
28279Object.defineProperty(Field.prototype, "packed", {\r
28280 get: function() {\r
28281 // defaults to packed=true if not explicity set to false\r
28282 if (this._packed === null)\r
28283 this._packed = this.getOption("packed") !== false;\r
28284 return this._packed;\r
28285 }\r
28286});\r
28287\r
28288/**\r
28289 * @override\r
28290 */\r
28291Field.prototype.setOption = function setOption(name, value, ifNotSet) {\r
28292 if (name === "packed") // clear cached before setting\r
28293 this._packed = null;\r
28294 return ReflectionObject.prototype.setOption.call(this, name, value, ifNotSet);\r
28295};\r
28296\r
28297/**\r
28298 * Field descriptor.\r
28299 * @interface IField\r
28300 * @property {string} [rule="optional"] Field rule\r
28301 * @property {string} type Field type\r
28302 * @property {number} id Field id\r
28303 * @property {Object.<string,*>} [options] Field options\r
28304 */\r
28305\r
28306/**\r
28307 * Extension field descriptor.\r
28308 * @interface IExtensionField\r
28309 * @extends IField\r
28310 * @property {string} extend Extended type\r
28311 */\r
28312\r
28313/**\r
28314 * Converts this field to a field descriptor.\r
28315 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r
28316 * @returns {IField} Field descriptor\r
28317 */\r
28318Field.prototype.toJSON = function toJSON(toJSONOptions) {\r
28319 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r
28320 return util.toObject([\r
28321 "rule" , this.rule !== "optional" && this.rule || undefined,\r
28322 "type" , this.type,\r
28323 "id" , this.id,\r
28324 "extend" , this.extend,\r
28325 "options" , this.options,\r
28326 "comment" , keepComments ? this.comment : undefined\r
28327 ]);\r
28328};\r
28329\r
28330/**\r
28331 * Resolves this field's type references.\r
28332 * @returns {Field} `this`\r
28333 * @throws {Error} If any reference cannot be resolved\r
28334 */\r
28335Field.prototype.resolve = function resolve() {\r
28336\r
28337 if (this.resolved)\r
28338 return this;\r
28339\r
28340 if ((this.typeDefault = types.defaults[this.type]) === undefined) { // if not a basic type, resolve it\r
28341 this.resolvedType = (this.declaringField ? this.declaringField.parent : this.parent).lookupTypeOrEnum(this.type);\r
28342 if (this.resolvedType instanceof Type)\r
28343 this.typeDefault = null;\r
28344 else // instanceof Enum\r
28345 this.typeDefault = this.resolvedType.values[Object.keys(this.resolvedType.values)[0]]; // first defined\r
28346 }\r
28347\r
28348 // use explicitly set default value if present\r
28349 if (this.options && this.options["default"] != null) {\r
28350 this.typeDefault = this.options["default"];\r
28351 if (this.resolvedType instanceof Enum && typeof this.typeDefault === "string")\r
28352 this.typeDefault = this.resolvedType.values[this.typeDefault];\r
28353 }\r
28354\r
28355 // remove unnecessary options\r
28356 if (this.options) {\r
28357 if (this.options.packed === true || this.options.packed !== undefined && this.resolvedType && !(this.resolvedType instanceof Enum))\r
28358 delete this.options.packed;\r
28359 if (!Object.keys(this.options).length)\r
28360 this.options = undefined;\r
28361 }\r
28362\r
28363 // convert to internal data type if necesssary\r
28364 if (this.long) {\r
28365 this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u");\r
28366\r
28367 /* istanbul ignore else */\r
28368 if (Object.freeze)\r
28369 Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)\r
28370\r
28371 } else if (this.bytes && typeof this.typeDefault === "string") {\r
28372 var buf;\r
28373 if (util.base64.test(this.typeDefault))\r
28374 util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0);\r
28375 else\r
28376 util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0);\r
28377 this.typeDefault = buf;\r
28378 }\r
28379\r
28380 // take special care of maps and repeated fields\r
28381 if (this.map)\r
28382 this.defaultValue = util.emptyObject;\r
28383 else if (this.repeated)\r
28384 this.defaultValue = util.emptyArray;\r
28385 else\r
28386 this.defaultValue = this.typeDefault;\r
28387\r
28388 // ensure proper value on prototype\r
28389 if (this.parent instanceof Type)\r
28390 this.parent.ctor.prototype[this.name] = this.defaultValue;\r
28391\r
28392 return ReflectionObject.prototype.resolve.call(this);\r
28393};\r
28394\r
28395/**\r
28396 * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).\r
28397 * @typedef FieldDecorator\r
28398 * @type {function}\r
28399 * @param {Object} prototype Target prototype\r
28400 * @param {string} fieldName Field name\r
28401 * @returns {undefined}\r
28402 */\r
28403\r
28404/**\r
28405 * Field decorator (TypeScript).\r
28406 * @name Field.d\r
28407 * @function\r
28408 * @param {number} fieldId Field id\r
28409 * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type\r
28410 * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule\r
28411 * @param {T} [defaultValue] Default value\r
28412 * @returns {FieldDecorator} Decorator function\r
28413 * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]\r
28414 */\r
28415Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) {\r
28416\r
28417 // submessage: decorate the submessage and use its name as the type\r
28418 if (typeof fieldType === "function")\r
28419 fieldType = util.decorateType(fieldType).name;\r
28420\r
28421 // enum reference: create a reflected copy of the enum and keep reuseing it\r
28422 else if (fieldType && typeof fieldType === "object")\r
28423 fieldType = util.decorateEnum(fieldType).name;\r
28424\r
28425 return function fieldDecorator(prototype, fieldName) {\r
28426 util.decorateType(prototype.constructor)\r
28427 .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue }));\r
28428 };\r
28429};\r
28430\r
28431/**\r
28432 * Field decorator (TypeScript).\r
28433 * @name Field.d\r
28434 * @function\r
28435 * @param {number} fieldId Field id\r
28436 * @param {Constructor<T>|string} fieldType Field type\r
28437 * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule\r
28438 * @returns {FieldDecorator} Decorator function\r
28439 * @template T extends Message<T>\r
28440 * @variation 2\r
28441 */\r
28442// like Field.d but without a default value\r
28443\r
28444Field._configure = function configure(Type_) {\r
28445 Type = Type_;\r
28446};\r
28447
28448},{"./enum":196,"./object":205,"./types":217,"./util":218}],198:[function(require,module,exports){
28449"use strict";\r
28450var protobuf = module.exports = require("./index-minimal");\r
28451\r
28452protobuf.build = "light";\r
28453\r
28454/**\r
28455 * A node-style callback as used by {@link load} and {@link Root#load}.\r
28456 * @typedef LoadCallback\r
28457 * @type {function}\r
28458 * @param {Error|null} error Error, if any, otherwise `null`\r
28459 * @param {Root} [root] Root, if there hasn't been an error\r
28460 * @returns {undefined}\r
28461 */\r
28462\r
28463/**\r
28464 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\r
28465 * @param {string|string[]} filename One or multiple files to load\r
28466 * @param {Root} root Root namespace, defaults to create a new one if omitted.\r
28467 * @param {LoadCallback} callback Callback function\r
28468 * @returns {undefined}\r
28469 * @see {@link Root#load}\r
28470 */\r
28471function load(filename, root, callback) {\r
28472 if (typeof root === "function") {\r
28473 callback = root;\r
28474 root = new protobuf.Root();\r
28475 } else if (!root)\r
28476 root = new protobuf.Root();\r
28477 return root.load(filename, callback);\r
28478}\r
28479\r
28480/**\r
28481 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.\r
28482 * @name load\r
28483 * @function\r
28484 * @param {string|string[]} filename One or multiple files to load\r
28485 * @param {LoadCallback} callback Callback function\r
28486 * @returns {undefined}\r
28487 * @see {@link Root#load}\r
28488 * @variation 2\r
28489 */\r
28490// function load(filename:string, callback:LoadCallback):undefined\r
28491\r
28492/**\r
28493 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.\r
28494 * @name load\r
28495 * @function\r
28496 * @param {string|string[]} filename One or multiple files to load\r
28497 * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\r
28498 * @returns {Promise<Root>} Promise\r
28499 * @see {@link Root#load}\r
28500 * @variation 3\r
28501 */\r
28502// function load(filename:string, [root:Root]):Promise<Root>\r
28503\r
28504protobuf.load = load;\r
28505\r
28506/**\r
28507 * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).\r
28508 * @param {string|string[]} filename One or multiple files to load\r
28509 * @param {Root} [root] Root namespace, defaults to create a new one if omitted.\r
28510 * @returns {Root} Root namespace\r
28511 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\r
28512 * @see {@link Root#loadSync}\r
28513 */\r
28514function loadSync(filename, root) {\r
28515 if (!root)\r
28516 root = new protobuf.Root();\r
28517 return root.loadSync(filename);\r
28518}\r
28519\r
28520protobuf.loadSync = loadSync;\r
28521\r
28522// Serialization\r
28523protobuf.encoder = require("./encoder");\r
28524protobuf.decoder = require("./decoder");\r
28525protobuf.verifier = require("./verifier");\r
28526protobuf.converter = require("./converter");\r
28527\r
28528// Reflection\r
28529protobuf.ReflectionObject = require("./object");\r
28530protobuf.Namespace = require("./namespace");\r
28531protobuf.Root = require("./root");\r
28532protobuf.Enum = require("./enum");\r
28533protobuf.Type = require("./type");\r
28534protobuf.Field = require("./field");\r
28535protobuf.OneOf = require("./oneof");\r
28536protobuf.MapField = require("./mapfield");\r
28537protobuf.Service = require("./service");\r
28538protobuf.Method = require("./method");\r
28539\r
28540// Runtime\r
28541protobuf.Message = require("./message");\r
28542protobuf.wrappers = require("./wrappers");\r
28543\r
28544// Utility\r
28545protobuf.types = require("./types");\r
28546protobuf.util = require("./util");\r
28547\r
28548// Configure reflection\r
28549protobuf.ReflectionObject._configure(protobuf.Root);\r
28550protobuf.Namespace._configure(protobuf.Type, protobuf.Service);\r
28551protobuf.Root._configure(protobuf.Type);\r
28552protobuf.Field._configure(protobuf.Type);\r
28553
28554},{"./converter":193,"./decoder":194,"./encoder":195,"./enum":196,"./field":197,"./index-minimal":199,"./mapfield":201,"./message":202,"./method":203,"./namespace":204,"./object":205,"./oneof":206,"./root":210,"./service":214,"./type":216,"./types":217,"./util":218,"./verifier":221,"./wrappers":222}],199:[function(require,module,exports){
28555"use strict";\r
28556var protobuf = exports;\r
28557\r
28558/**\r
28559 * Build type, one of `"full"`, `"light"` or `"minimal"`.\r
28560 * @name build\r
28561 * @type {string}\r
28562 * @const\r
28563 */\r
28564protobuf.build = "minimal";\r
28565\r
28566// Serialization\r
28567protobuf.Writer = require("./writer");\r
28568protobuf.BufferWriter = require("./writer_buffer");\r
28569protobuf.Reader = require("./reader");\r
28570protobuf.BufferReader = require("./reader_buffer");\r
28571\r
28572// Utility\r
28573protobuf.util = require("./util/minimal");\r
28574protobuf.rpc = require("./rpc");\r
28575protobuf.roots = require("./roots");\r
28576protobuf.configure = configure;\r
28577\r
28578/* istanbul ignore next */\r
28579/**\r
28580 * Reconfigures the library according to the environment.\r
28581 * @returns {undefined}\r
28582 */\r
28583function configure() {\r
28584 protobuf.Reader._configure(protobuf.BufferReader);\r
28585 protobuf.util._configure();\r
28586}\r
28587\r
28588// Configure serialization\r
28589protobuf.Writer._configure(protobuf.BufferWriter);\r
28590configure();\r
28591
28592},{"./reader":208,"./reader_buffer":209,"./roots":211,"./rpc":212,"./util/minimal":220,"./writer":223,"./writer_buffer":224}],200:[function(require,module,exports){
28593"use strict";\r
28594var protobuf = module.exports = require("./index-light");\r
28595\r
28596protobuf.build = "full";\r
28597\r
28598// Parser\r
28599protobuf.tokenize = require("./tokenize");\r
28600protobuf.parse = require("./parse");\r
28601protobuf.common = require("./common");\r
28602\r
28603// Configure parser\r
28604protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common);\r
28605
28606},{"./common":192,"./index-light":198,"./parse":207,"./tokenize":215}],201:[function(require,module,exports){
28607"use strict";\r
28608module.exports = MapField;\r
28609\r
28610// extends Field\r
28611var Field = require("./field");\r
28612((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField";\r
28613\r
28614var types = require("./types"),\r
28615 util = require("./util");\r
28616\r
28617/**\r
28618 * Constructs a new map field instance.\r
28619 * @classdesc Reflected map field.\r
28620 * @extends FieldBase\r
28621 * @constructor\r
28622 * @param {string} name Unique name within its namespace\r
28623 * @param {number} id Unique id within its namespace\r
28624 * @param {string} keyType Key type\r
28625 * @param {string} type Value type\r
28626 * @param {Object.<string,*>} [options] Declared options\r
28627 * @param {string} [comment] Comment associated with this field\r
28628 */\r
28629function MapField(name, id, keyType, type, options, comment) {\r
28630 Field.call(this, name, id, type, undefined, undefined, options, comment);\r
28631\r
28632 /* istanbul ignore if */\r
28633 if (!util.isString(keyType))\r
28634 throw TypeError("keyType must be a string");\r
28635\r
28636 /**\r
28637 * Key type.\r
28638 * @type {string}\r
28639 */\r
28640 this.keyType = keyType; // toJSON, marker\r
28641\r
28642 /**\r
28643 * Resolved key type if not a basic type.\r
28644 * @type {ReflectionObject|null}\r
28645 */\r
28646 this.resolvedKeyType = null;\r
28647\r
28648 // Overrides Field#map\r
28649 this.map = true;\r
28650}\r
28651\r
28652/**\r
28653 * Map field descriptor.\r
28654 * @interface IMapField\r
28655 * @extends {IField}\r
28656 * @property {string} keyType Key type\r
28657 */\r
28658\r
28659/**\r
28660 * Extension map field descriptor.\r
28661 * @interface IExtensionMapField\r
28662 * @extends IMapField\r
28663 * @property {string} extend Extended type\r
28664 */\r
28665\r
28666/**\r
28667 * Constructs a map field from a map field descriptor.\r
28668 * @param {string} name Field name\r
28669 * @param {IMapField} json Map field descriptor\r
28670 * @returns {MapField} Created map field\r
28671 * @throws {TypeError} If arguments are invalid\r
28672 */\r
28673MapField.fromJSON = function fromJSON(name, json) {\r
28674 return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment);\r
28675};\r
28676\r
28677/**\r
28678 * Converts this map field to a map field descriptor.\r
28679 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r
28680 * @returns {IMapField} Map field descriptor\r
28681 */\r
28682MapField.prototype.toJSON = function toJSON(toJSONOptions) {\r
28683 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r
28684 return util.toObject([\r
28685 "keyType" , this.keyType,\r
28686 "type" , this.type,\r
28687 "id" , this.id,\r
28688 "extend" , this.extend,\r
28689 "options" , this.options,\r
28690 "comment" , keepComments ? this.comment : undefined\r
28691 ]);\r
28692};\r
28693\r
28694/**\r
28695 * @override\r
28696 */\r
28697MapField.prototype.resolve = function resolve() {\r
28698 if (this.resolved)\r
28699 return this;\r
28700\r
28701 // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes"\r
28702 if (types.mapKey[this.keyType] === undefined)\r
28703 throw Error("invalid key type: " + this.keyType);\r
28704\r
28705 return Field.prototype.resolve.call(this);\r
28706};\r
28707\r
28708/**\r
28709 * Map field decorator (TypeScript).\r
28710 * @name MapField.d\r
28711 * @function\r
28712 * @param {number} fieldId Field id\r
28713 * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type\r
28714 * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type\r
28715 * @returns {FieldDecorator} Decorator function\r
28716 * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }\r
28717 */\r
28718MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) {\r
28719\r
28720 // submessage value: decorate the submessage and use its name as the type\r
28721 if (typeof fieldValueType === "function")\r
28722 fieldValueType = util.decorateType(fieldValueType).name;\r
28723\r
28724 // enum reference value: create a reflected copy of the enum and keep reuseing it\r
28725 else if (fieldValueType && typeof fieldValueType === "object")\r
28726 fieldValueType = util.decorateEnum(fieldValueType).name;\r
28727\r
28728 return function mapFieldDecorator(prototype, fieldName) {\r
28729 util.decorateType(prototype.constructor)\r
28730 .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType));\r
28731 };\r
28732};\r
28733
28734},{"./field":197,"./types":217,"./util":218}],202:[function(require,module,exports){
28735"use strict";\r
28736module.exports = Message;\r
28737\r
28738var util = require("./util/minimal");\r
28739\r
28740/**\r
28741 * Constructs a new message instance.\r
28742 * @classdesc Abstract runtime message.\r
28743 * @constructor\r
28744 * @param {Properties<T>} [properties] Properties to set\r
28745 * @template T extends object\r
28746 */\r
28747function Message(properties) {\r
28748 // not used internally\r
28749 if (properties)\r
28750 for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i)\r
28751 this[keys[i]] = properties[keys[i]];\r
28752}\r
28753\r
28754/**\r
28755 * Reference to the reflected type.\r
28756 * @name Message.$type\r
28757 * @type {Type}\r
28758 * @readonly\r
28759 */\r
28760\r
28761/**\r
28762 * Reference to the reflected type.\r
28763 * @name Message#$type\r
28764 * @type {Type}\r
28765 * @readonly\r
28766 */\r
28767\r
28768/*eslint-disable valid-jsdoc*/\r
28769\r
28770/**\r
28771 * Creates a new message of this type using the specified properties.\r
28772 * @param {Object.<string,*>} [properties] Properties to set\r
28773 * @returns {Message<T>} Message instance\r
28774 * @template T extends Message<T>\r
28775 * @this Constructor<T>\r
28776 */\r
28777Message.create = function create(properties) {\r
28778 return this.$type.create(properties);\r
28779};\r
28780\r
28781/**\r
28782 * Encodes a message of this type.\r
28783 * @param {T|Object.<string,*>} message Message to encode\r
28784 * @param {Writer} [writer] Writer to use\r
28785 * @returns {Writer} Writer\r
28786 * @template T extends Message<T>\r
28787 * @this Constructor<T>\r
28788 */\r
28789Message.encode = function encode(message, writer) {\r
28790 return this.$type.encode(message, writer);\r
28791};\r
28792\r
28793/**\r
28794 * Encodes a message of this type preceeded by its length as a varint.\r
28795 * @param {T|Object.<string,*>} message Message to encode\r
28796 * @param {Writer} [writer] Writer to use\r
28797 * @returns {Writer} Writer\r
28798 * @template T extends Message<T>\r
28799 * @this Constructor<T>\r
28800 */\r
28801Message.encodeDelimited = function encodeDelimited(message, writer) {\r
28802 return this.$type.encodeDelimited(message, writer);\r
28803};\r
28804\r
28805/**\r
28806 * Decodes a message of this type.\r
28807 * @name Message.decode\r
28808 * @function\r
28809 * @param {Reader|Uint8Array} reader Reader or buffer to decode\r
28810 * @returns {T} Decoded message\r
28811 * @template T extends Message<T>\r
28812 * @this Constructor<T>\r
28813 */\r
28814Message.decode = function decode(reader) {\r
28815 return this.$type.decode(reader);\r
28816};\r
28817\r
28818/**\r
28819 * Decodes a message of this type preceeded by its length as a varint.\r
28820 * @name Message.decodeDelimited\r
28821 * @function\r
28822 * @param {Reader|Uint8Array} reader Reader or buffer to decode\r
28823 * @returns {T} Decoded message\r
28824 * @template T extends Message<T>\r
28825 * @this Constructor<T>\r
28826 */\r
28827Message.decodeDelimited = function decodeDelimited(reader) {\r
28828 return this.$type.decodeDelimited(reader);\r
28829};\r
28830\r
28831/**\r
28832 * Verifies a message of this type.\r
28833 * @name Message.verify\r
28834 * @function\r
28835 * @param {Object.<string,*>} message Plain object to verify\r
28836 * @returns {string|null} `null` if valid, otherwise the reason why it is not\r
28837 */\r
28838Message.verify = function verify(message) {\r
28839 return this.$type.verify(message);\r
28840};\r
28841\r
28842/**\r
28843 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\r
28844 * @param {Object.<string,*>} object Plain object\r
28845 * @returns {T} Message instance\r
28846 * @template T extends Message<T>\r
28847 * @this Constructor<T>\r
28848 */\r
28849Message.fromObject = function fromObject(object) {\r
28850 return this.$type.fromObject(object);\r
28851};\r
28852\r
28853/**\r
28854 * Creates a plain object from a message of this type. Also converts values to other types if specified.\r
28855 * @param {T} message Message instance\r
28856 * @param {IConversionOptions} [options] Conversion options\r
28857 * @returns {Object.<string,*>} Plain object\r
28858 * @template T extends Message<T>\r
28859 * @this Constructor<T>\r
28860 */\r
28861Message.toObject = function toObject(message, options) {\r
28862 return this.$type.toObject(message, options);\r
28863};\r
28864\r
28865/**\r
28866 * Converts this message to JSON.\r
28867 * @returns {Object.<string,*>} JSON object\r
28868 */\r
28869Message.prototype.toJSON = function toJSON() {\r
28870 return this.$type.toObject(this, util.toJSONOptions);\r
28871};\r
28872\r
28873/*eslint-enable valid-jsdoc*/
28874},{"./util/minimal":220}],203:[function(require,module,exports){
28875"use strict";\r
28876module.exports = Method;\r
28877\r
28878// extends ReflectionObject\r
28879var ReflectionObject = require("./object");\r
28880((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method";\r
28881\r
28882var util = require("./util");\r
28883\r
28884/**\r
28885 * Constructs a new service method instance.\r
28886 * @classdesc Reflected service method.\r
28887 * @extends ReflectionObject\r
28888 * @constructor\r
28889 * @param {string} name Method name\r
28890 * @param {string|undefined} type Method type, usually `"rpc"`\r
28891 * @param {string} requestType Request message type\r
28892 * @param {string} responseType Response message type\r
28893 * @param {boolean|Object.<string,*>} [requestStream] Whether the request is streamed\r
28894 * @param {boolean|Object.<string,*>} [responseStream] Whether the response is streamed\r
28895 * @param {Object.<string,*>} [options] Declared options\r
28896 * @param {string} [comment] The comment for this method\r
28897 */\r
28898function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment) {\r
28899\r
28900 /* istanbul ignore next */\r
28901 if (util.isObject(requestStream)) {\r
28902 options = requestStream;\r
28903 requestStream = responseStream = undefined;\r
28904 } else if (util.isObject(responseStream)) {\r
28905 options = responseStream;\r
28906 responseStream = undefined;\r
28907 }\r
28908\r
28909 /* istanbul ignore if */\r
28910 if (!(type === undefined || util.isString(type)))\r
28911 throw TypeError("type must be a string");\r
28912\r
28913 /* istanbul ignore if */\r
28914 if (!util.isString(requestType))\r
28915 throw TypeError("requestType must be a string");\r
28916\r
28917 /* istanbul ignore if */\r
28918 if (!util.isString(responseType))\r
28919 throw TypeError("responseType must be a string");\r
28920\r
28921 ReflectionObject.call(this, name, options);\r
28922\r
28923 /**\r
28924 * Method type.\r
28925 * @type {string}\r
28926 */\r
28927 this.type = type || "rpc"; // toJSON\r
28928\r
28929 /**\r
28930 * Request type.\r
28931 * @type {string}\r
28932 */\r
28933 this.requestType = requestType; // toJSON, marker\r
28934\r
28935 /**\r
28936 * Whether requests are streamed or not.\r
28937 * @type {boolean|undefined}\r
28938 */\r
28939 this.requestStream = requestStream ? true : undefined; // toJSON\r
28940\r
28941 /**\r
28942 * Response type.\r
28943 * @type {string}\r
28944 */\r
28945 this.responseType = responseType; // toJSON\r
28946\r
28947 /**\r
28948 * Whether responses are streamed or not.\r
28949 * @type {boolean|undefined}\r
28950 */\r
28951 this.responseStream = responseStream ? true : undefined; // toJSON\r
28952\r
28953 /**\r
28954 * Resolved request type.\r
28955 * @type {Type|null}\r
28956 */\r
28957 this.resolvedRequestType = null;\r
28958\r
28959 /**\r
28960 * Resolved response type.\r
28961 * @type {Type|null}\r
28962 */\r
28963 this.resolvedResponseType = null;\r
28964\r
28965 /**\r
28966 * Comment for this method\r
28967 * @type {string|null}\r
28968 */\r
28969 this.comment = comment;\r
28970}\r
28971\r
28972/**\r
28973 * Method descriptor.\r
28974 * @interface IMethod\r
28975 * @property {string} [type="rpc"] Method type\r
28976 * @property {string} requestType Request type\r
28977 * @property {string} responseType Response type\r
28978 * @property {boolean} [requestStream=false] Whether requests are streamed\r
28979 * @property {boolean} [responseStream=false] Whether responses are streamed\r
28980 * @property {Object.<string,*>} [options] Method options\r
28981 */\r
28982\r
28983/**\r
28984 * Constructs a method from a method descriptor.\r
28985 * @param {string} name Method name\r
28986 * @param {IMethod} json Method descriptor\r
28987 * @returns {Method} Created method\r
28988 * @throws {TypeError} If arguments are invalid\r
28989 */\r
28990Method.fromJSON = function fromJSON(name, json) {\r
28991 return new Method(name, json.type, json.requestType, json.responseType, json.requestStream, json.responseStream, json.options, json.comment);\r
28992};\r
28993\r
28994/**\r
28995 * Converts this method to a method descriptor.\r
28996 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r
28997 * @returns {IMethod} Method descriptor\r
28998 */\r
28999Method.prototype.toJSON = function toJSON(toJSONOptions) {\r
29000 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r
29001 return util.toObject([\r
29002 "type" , this.type !== "rpc" && /* istanbul ignore next */ this.type || undefined,\r
29003 "requestType" , this.requestType,\r
29004 "requestStream" , this.requestStream,\r
29005 "responseType" , this.responseType,\r
29006 "responseStream" , this.responseStream,\r
29007 "options" , this.options,\r
29008 "comment" , keepComments ? this.comment : undefined\r
29009 ]);\r
29010};\r
29011\r
29012/**\r
29013 * @override\r
29014 */\r
29015Method.prototype.resolve = function resolve() {\r
29016\r
29017 /* istanbul ignore if */\r
29018 if (this.resolved)\r
29019 return this;\r
29020\r
29021 this.resolvedRequestType = this.parent.lookupType(this.requestType);\r
29022 this.resolvedResponseType = this.parent.lookupType(this.responseType);\r
29023\r
29024 return ReflectionObject.prototype.resolve.call(this);\r
29025};\r
29026
29027},{"./object":205,"./util":218}],204:[function(require,module,exports){
29028"use strict";\r
29029module.exports = Namespace;\r
29030\r
29031// extends ReflectionObject\r
29032var ReflectionObject = require("./object");\r
29033((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace";\r
29034\r
29035var Enum = require("./enum"),\r
29036 Field = require("./field"),\r
29037 util = require("./util");\r
29038\r
29039var Type, // cyclic\r
29040 Service; // "\r
29041\r
29042/**\r
29043 * Constructs a new namespace instance.\r
29044 * @name Namespace\r
29045 * @classdesc Reflected namespace.\r
29046 * @extends NamespaceBase\r
29047 * @constructor\r
29048 * @param {string} name Namespace name\r
29049 * @param {Object.<string,*>} [options] Declared options\r
29050 */\r
29051\r
29052/**\r
29053 * Constructs a namespace from JSON.\r
29054 * @memberof Namespace\r
29055 * @function\r
29056 * @param {string} name Namespace name\r
29057 * @param {Object.<string,*>} json JSON object\r
29058 * @returns {Namespace} Created namespace\r
29059 * @throws {TypeError} If arguments are invalid\r
29060 */\r
29061Namespace.fromJSON = function fromJSON(name, json) {\r
29062 return new Namespace(name, json.options).addJSON(json.nested);\r
29063};\r
29064\r
29065/**\r
29066 * Converts an array of reflection objects to JSON.\r
29067 * @memberof Namespace\r
29068 * @param {ReflectionObject[]} array Object array\r
29069 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r
29070 * @returns {Object.<string,*>|undefined} JSON object or `undefined` when array is empty\r
29071 */\r
29072function arrayToJSON(array, toJSONOptions) {\r
29073 if (!(array && array.length))\r
29074 return undefined;\r
29075 var obj = {};\r
29076 for (var i = 0; i < array.length; ++i)\r
29077 obj[array[i].name] = array[i].toJSON(toJSONOptions);\r
29078 return obj;\r
29079}\r
29080\r
29081Namespace.arrayToJSON = arrayToJSON;\r
29082\r
29083/**\r
29084 * Tests if the specified id is reserved.\r
29085 * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names\r
29086 * @param {number} id Id to test\r
29087 * @returns {boolean} `true` if reserved, otherwise `false`\r
29088 */\r
29089Namespace.isReservedId = function isReservedId(reserved, id) {\r
29090 if (reserved)\r
29091 for (var i = 0; i < reserved.length; ++i)\r
29092 if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] >= id)\r
29093 return true;\r
29094 return false;\r
29095};\r
29096\r
29097/**\r
29098 * Tests if the specified name is reserved.\r
29099 * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names\r
29100 * @param {string} name Name to test\r
29101 * @returns {boolean} `true` if reserved, otherwise `false`\r
29102 */\r
29103Namespace.isReservedName = function isReservedName(reserved, name) {\r
29104 if (reserved)\r
29105 for (var i = 0; i < reserved.length; ++i)\r
29106 if (reserved[i] === name)\r
29107 return true;\r
29108 return false;\r
29109};\r
29110\r
29111/**\r
29112 * Not an actual constructor. Use {@link Namespace} instead.\r
29113 * @classdesc Base class of all reflection objects containing nested objects. This is not an actual class but here for the sake of having consistent type definitions.\r
29114 * @exports NamespaceBase\r
29115 * @extends ReflectionObject\r
29116 * @abstract\r
29117 * @constructor\r
29118 * @param {string} name Namespace name\r
29119 * @param {Object.<string,*>} [options] Declared options\r
29120 * @see {@link Namespace}\r
29121 */\r
29122function Namespace(name, options) {\r
29123 ReflectionObject.call(this, name, options);\r
29124\r
29125 /**\r
29126 * Nested objects by name.\r
29127 * @type {Object.<string,ReflectionObject>|undefined}\r
29128 */\r
29129 this.nested = undefined; // toJSON\r
29130\r
29131 /**\r
29132 * Cached nested objects as an array.\r
29133 * @type {ReflectionObject[]|null}\r
29134 * @private\r
29135 */\r
29136 this._nestedArray = null;\r
29137}\r
29138\r
29139function clearCache(namespace) {\r
29140 namespace._nestedArray = null;\r
29141 return namespace;\r
29142}\r
29143\r
29144/**\r
29145 * Nested objects of this namespace as an array for iteration.\r
29146 * @name NamespaceBase#nestedArray\r
29147 * @type {ReflectionObject[]}\r
29148 * @readonly\r
29149 */\r
29150Object.defineProperty(Namespace.prototype, "nestedArray", {\r
29151 get: function() {\r
29152 return this._nestedArray || (this._nestedArray = util.toArray(this.nested));\r
29153 }\r
29154});\r
29155\r
29156/**\r
29157 * Namespace descriptor.\r
29158 * @interface INamespace\r
29159 * @property {Object.<string,*>} [options] Namespace options\r
29160 * @property {Object.<string,AnyNestedObject>} [nested] Nested object descriptors\r
29161 */\r
29162\r
29163/**\r
29164 * Any extension field descriptor.\r
29165 * @typedef AnyExtensionField\r
29166 * @type {IExtensionField|IExtensionMapField}\r
29167 */\r
29168\r
29169/**\r
29170 * Any nested object descriptor.\r
29171 * @typedef AnyNestedObject\r
29172 * @type {IEnum|IType|IService|AnyExtensionField|INamespace}\r
29173 */\r
29174// ^ BEWARE: VSCode hangs forever when using more than 5 types (that's why AnyExtensionField exists in the first place)\r
29175\r
29176/**\r
29177 * Converts this namespace to a namespace descriptor.\r
29178 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r
29179 * @returns {INamespace} Namespace descriptor\r
29180 */\r
29181Namespace.prototype.toJSON = function toJSON(toJSONOptions) {\r
29182 return util.toObject([\r
29183 "options" , this.options,\r
29184 "nested" , arrayToJSON(this.nestedArray, toJSONOptions)\r
29185 ]);\r
29186};\r
29187\r
29188/**\r
29189 * Adds nested objects to this namespace from nested object descriptors.\r
29190 * @param {Object.<string,AnyNestedObject>} nestedJson Any nested object descriptors\r
29191 * @returns {Namespace} `this`\r
29192 */\r
29193Namespace.prototype.addJSON = function addJSON(nestedJson) {\r
29194 var ns = this;\r
29195 /* istanbul ignore else */\r
29196 if (nestedJson) {\r
29197 for (var names = Object.keys(nestedJson), i = 0, nested; i < names.length; ++i) {\r
29198 nested = nestedJson[names[i]];\r
29199 ns.add( // most to least likely\r
29200 ( nested.fields !== undefined\r
29201 ? Type.fromJSON\r
29202 : nested.values !== undefined\r
29203 ? Enum.fromJSON\r
29204 : nested.methods !== undefined\r
29205 ? Service.fromJSON\r
29206 : nested.id !== undefined\r
29207 ? Field.fromJSON\r
29208 : Namespace.fromJSON )(names[i], nested)\r
29209 );\r
29210 }\r
29211 }\r
29212 return this;\r
29213};\r
29214\r
29215/**\r
29216 * Gets the nested object of the specified name.\r
29217 * @param {string} name Nested object name\r
29218 * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist\r
29219 */\r
29220Namespace.prototype.get = function get(name) {\r
29221 return this.nested && this.nested[name]\r
29222 || null;\r
29223};\r
29224\r
29225/**\r
29226 * Gets the values of the nested {@link Enum|enum} of the specified name.\r
29227 * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.\r
29228 * @param {string} name Nested enum name\r
29229 * @returns {Object.<string,number>} Enum values\r
29230 * @throws {Error} If there is no such enum\r
29231 */\r
29232Namespace.prototype.getEnum = function getEnum(name) {\r
29233 if (this.nested && this.nested[name] instanceof Enum)\r
29234 return this.nested[name].values;\r
29235 throw Error("no such enum: " + name);\r
29236};\r
29237\r
29238/**\r
29239 * Adds a nested object to this namespace.\r
29240 * @param {ReflectionObject} object Nested object to add\r
29241 * @returns {Namespace} `this`\r
29242 * @throws {TypeError} If arguments are invalid\r
29243 * @throws {Error} If there is already a nested object with this name\r
29244 */\r
29245Namespace.prototype.add = function add(object) {\r
29246\r
29247 if (!(object instanceof Field && object.extend !== undefined || object instanceof Type || object instanceof Enum || object instanceof Service || object instanceof Namespace))\r
29248 throw TypeError("object must be a valid nested object");\r
29249\r
29250 if (!this.nested)\r
29251 this.nested = {};\r
29252 else {\r
29253 var prev = this.get(object.name);\r
29254 if (prev) {\r
29255 if (prev instanceof Namespace && object instanceof Namespace && !(prev instanceof Type || prev instanceof Service)) {\r
29256 // replace plain namespace but keep existing nested elements and options\r
29257 var nested = prev.nestedArray;\r
29258 for (var i = 0; i < nested.length; ++i)\r
29259 object.add(nested[i]);\r
29260 this.remove(prev);\r
29261 if (!this.nested)\r
29262 this.nested = {};\r
29263 object.setOptions(prev.options, true);\r
29264\r
29265 } else\r
29266 throw Error("duplicate name '" + object.name + "' in " + this);\r
29267 }\r
29268 }\r
29269 this.nested[object.name] = object;\r
29270 object.onAdd(this);\r
29271 return clearCache(this);\r
29272};\r
29273\r
29274/**\r
29275 * Removes a nested object from this namespace.\r
29276 * @param {ReflectionObject} object Nested object to remove\r
29277 * @returns {Namespace} `this`\r
29278 * @throws {TypeError} If arguments are invalid\r
29279 * @throws {Error} If `object` is not a member of this namespace\r
29280 */\r
29281Namespace.prototype.remove = function remove(object) {\r
29282\r
29283 if (!(object instanceof ReflectionObject))\r
29284 throw TypeError("object must be a ReflectionObject");\r
29285 if (object.parent !== this)\r
29286 throw Error(object + " is not a member of " + this);\r
29287\r
29288 delete this.nested[object.name];\r
29289 if (!Object.keys(this.nested).length)\r
29290 this.nested = undefined;\r
29291\r
29292 object.onRemove(this);\r
29293 return clearCache(this);\r
29294};\r
29295\r
29296/**\r
29297 * Defines additial namespaces within this one if not yet existing.\r
29298 * @param {string|string[]} path Path to create\r
29299 * @param {*} [json] Nested types to create from JSON\r
29300 * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty\r
29301 */\r
29302Namespace.prototype.define = function define(path, json) {\r
29303\r
29304 if (util.isString(path))\r
29305 path = path.split(".");\r
29306 else if (!Array.isArray(path))\r
29307 throw TypeError("illegal path");\r
29308 if (path && path.length && path[0] === "")\r
29309 throw Error("path must be relative");\r
29310\r
29311 var ptr = this;\r
29312 while (path.length > 0) {\r
29313 var part = path.shift();\r
29314 if (ptr.nested && ptr.nested[part]) {\r
29315 ptr = ptr.nested[part];\r
29316 if (!(ptr instanceof Namespace))\r
29317 throw Error("path conflicts with non-namespace objects");\r
29318 } else\r
29319 ptr.add(ptr = new Namespace(part));\r
29320 }\r
29321 if (json)\r
29322 ptr.addJSON(json);\r
29323 return ptr;\r
29324};\r
29325\r
29326/**\r
29327 * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.\r
29328 * @returns {Namespace} `this`\r
29329 */\r
29330Namespace.prototype.resolveAll = function resolveAll() {\r
29331 var nested = this.nestedArray, i = 0;\r
29332 while (i < nested.length)\r
29333 if (nested[i] instanceof Namespace)\r
29334 nested[i++].resolveAll();\r
29335 else\r
29336 nested[i++].resolve();\r
29337 return this.resolve();\r
29338};\r
29339\r
29340/**\r
29341 * Recursively looks up the reflection object matching the specified path in the scope of this namespace.\r
29342 * @param {string|string[]} path Path to look up\r
29343 * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.\r
29344 * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked\r
29345 * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\r
29346 */\r
29347Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) {\r
29348\r
29349 /* istanbul ignore next */\r
29350 if (typeof filterTypes === "boolean") {\r
29351 parentAlreadyChecked = filterTypes;\r
29352 filterTypes = undefined;\r
29353 } else if (filterTypes && !Array.isArray(filterTypes))\r
29354 filterTypes = [ filterTypes ];\r
29355\r
29356 if (util.isString(path) && path.length) {\r
29357 if (path === ".")\r
29358 return this.root;\r
29359 path = path.split(".");\r
29360 } else if (!path.length)\r
29361 return this;\r
29362\r
29363 // Start at root if path is absolute\r
29364 if (path[0] === "")\r
29365 return this.root.lookup(path.slice(1), filterTypes);\r
29366\r
29367 // Test if the first part matches any nested object, and if so, traverse if path contains more\r
29368 var found = this.get(path[0]);\r
29369 if (found) {\r
29370 if (path.length === 1) {\r
29371 if (!filterTypes || filterTypes.indexOf(found.constructor) > -1)\r
29372 return found;\r
29373 } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true)))\r
29374 return found;\r
29375\r
29376 // Otherwise try each nested namespace\r
29377 } else\r
29378 for (var i = 0; i < this.nestedArray.length; ++i)\r
29379 if (this._nestedArray[i] instanceof Namespace && (found = this._nestedArray[i].lookup(path, filterTypes, true)))\r
29380 return found;\r
29381\r
29382 // If there hasn't been a match, try again at the parent\r
29383 if (this.parent === null || parentAlreadyChecked)\r
29384 return null;\r
29385 return this.parent.lookup(path, filterTypes);\r
29386};\r
29387\r
29388/**\r
29389 * Looks up the reflection object at the specified path, relative to this namespace.\r
29390 * @name NamespaceBase#lookup\r
29391 * @function\r
29392 * @param {string|string[]} path Path to look up\r
29393 * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked\r
29394 * @returns {ReflectionObject|null} Looked up object or `null` if none could be found\r
29395 * @variation 2\r
29396 */\r
29397// lookup(path: string, [parentAlreadyChecked: boolean])\r
29398\r
29399/**\r
29400 * Looks up the {@link Type|type} at the specified path, relative to this namespace.\r
29401 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\r
29402 * @param {string|string[]} path Path to look up\r
29403 * @returns {Type} Looked up type\r
29404 * @throws {Error} If `path` does not point to a type\r
29405 */\r
29406Namespace.prototype.lookupType = function lookupType(path) {\r
29407 var found = this.lookup(path, [ Type ]);\r
29408 if (!found)\r
29409 throw Error("no such type: " + path);\r
29410 return found;\r
29411};\r
29412\r
29413/**\r
29414 * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.\r
29415 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\r
29416 * @param {string|string[]} path Path to look up\r
29417 * @returns {Enum} Looked up enum\r
29418 * @throws {Error} If `path` does not point to an enum\r
29419 */\r
29420Namespace.prototype.lookupEnum = function lookupEnum(path) {\r
29421 var found = this.lookup(path, [ Enum ]);\r
29422 if (!found)\r
29423 throw Error("no such Enum '" + path + "' in " + this);\r
29424 return found;\r
29425};\r
29426\r
29427/**\r
29428 * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.\r
29429 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\r
29430 * @param {string|string[]} path Path to look up\r
29431 * @returns {Type} Looked up type or enum\r
29432 * @throws {Error} If `path` does not point to a type or enum\r
29433 */\r
29434Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) {\r
29435 var found = this.lookup(path, [ Type, Enum ]);\r
29436 if (!found)\r
29437 throw Error("no such Type or Enum '" + path + "' in " + this);\r
29438 return found;\r
29439};\r
29440\r
29441/**\r
29442 * Looks up the {@link Service|service} at the specified path, relative to this namespace.\r
29443 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.\r
29444 * @param {string|string[]} path Path to look up\r
29445 * @returns {Service} Looked up service\r
29446 * @throws {Error} If `path` does not point to a service\r
29447 */\r
29448Namespace.prototype.lookupService = function lookupService(path) {\r
29449 var found = this.lookup(path, [ Service ]);\r
29450 if (!found)\r
29451 throw Error("no such Service '" + path + "' in " + this);\r
29452 return found;\r
29453};\r
29454\r
29455Namespace._configure = function(Type_, Service_) {\r
29456 Type = Type_;\r
29457 Service = Service_;\r
29458};\r
29459
29460},{"./enum":196,"./field":197,"./object":205,"./util":218}],205:[function(require,module,exports){
29461"use strict";\r
29462module.exports = ReflectionObject;\r
29463\r
29464ReflectionObject.className = "ReflectionObject";\r
29465\r
29466var util = require("./util");\r
29467\r
29468var Root; // cyclic\r
29469\r
29470/**\r
29471 * Constructs a new reflection object instance.\r
29472 * @classdesc Base class of all reflection objects.\r
29473 * @constructor\r
29474 * @param {string} name Object name\r
29475 * @param {Object.<string,*>} [options] Declared options\r
29476 * @abstract\r
29477 */\r
29478function ReflectionObject(name, options) {\r
29479\r
29480 if (!util.isString(name))\r
29481 throw TypeError("name must be a string");\r
29482\r
29483 if (options && !util.isObject(options))\r
29484 throw TypeError("options must be an object");\r
29485\r
29486 /**\r
29487 * Options.\r
29488 * @type {Object.<string,*>|undefined}\r
29489 */\r
29490 this.options = options; // toJSON\r
29491\r
29492 /**\r
29493 * Unique name within its namespace.\r
29494 * @type {string}\r
29495 */\r
29496 this.name = name;\r
29497\r
29498 /**\r
29499 * Parent namespace.\r
29500 * @type {Namespace|null}\r
29501 */\r
29502 this.parent = null;\r
29503\r
29504 /**\r
29505 * Whether already resolved or not.\r
29506 * @type {boolean}\r
29507 */\r
29508 this.resolved = false;\r
29509\r
29510 /**\r
29511 * Comment text, if any.\r
29512 * @type {string|null}\r
29513 */\r
29514 this.comment = null;\r
29515\r
29516 /**\r
29517 * Defining file name.\r
29518 * @type {string|null}\r
29519 */\r
29520 this.filename = null;\r
29521}\r
29522\r
29523Object.defineProperties(ReflectionObject.prototype, {\r
29524\r
29525 /**\r
29526 * Reference to the root namespace.\r
29527 * @name ReflectionObject#root\r
29528 * @type {Root}\r
29529 * @readonly\r
29530 */\r
29531 root: {\r
29532 get: function() {\r
29533 var ptr = this;\r
29534 while (ptr.parent !== null)\r
29535 ptr = ptr.parent;\r
29536 return ptr;\r
29537 }\r
29538 },\r
29539\r
29540 /**\r
29541 * Full name including leading dot.\r
29542 * @name ReflectionObject#fullName\r
29543 * @type {string}\r
29544 * @readonly\r
29545 */\r
29546 fullName: {\r
29547 get: function() {\r
29548 var path = [ this.name ],\r
29549 ptr = this.parent;\r
29550 while (ptr) {\r
29551 path.unshift(ptr.name);\r
29552 ptr = ptr.parent;\r
29553 }\r
29554 return path.join(".");\r
29555 }\r
29556 }\r
29557});\r
29558\r
29559/**\r
29560 * Converts this reflection object to its descriptor representation.\r
29561 * @returns {Object.<string,*>} Descriptor\r
29562 * @abstract\r
29563 */\r
29564ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() {\r
29565 throw Error(); // not implemented, shouldn't happen\r
29566};\r
29567\r
29568/**\r
29569 * Called when this object is added to a parent.\r
29570 * @param {ReflectionObject} parent Parent added to\r
29571 * @returns {undefined}\r
29572 */\r
29573ReflectionObject.prototype.onAdd = function onAdd(parent) {\r
29574 if (this.parent && this.parent !== parent)\r
29575 this.parent.remove(this);\r
29576 this.parent = parent;\r
29577 this.resolved = false;\r
29578 var root = parent.root;\r
29579 if (root instanceof Root)\r
29580 root._handleAdd(this);\r
29581};\r
29582\r
29583/**\r
29584 * Called when this object is removed from a parent.\r
29585 * @param {ReflectionObject} parent Parent removed from\r
29586 * @returns {undefined}\r
29587 */\r
29588ReflectionObject.prototype.onRemove = function onRemove(parent) {\r
29589 var root = parent.root;\r
29590 if (root instanceof Root)\r
29591 root._handleRemove(this);\r
29592 this.parent = null;\r
29593 this.resolved = false;\r
29594};\r
29595\r
29596/**\r
29597 * Resolves this objects type references.\r
29598 * @returns {ReflectionObject} `this`\r
29599 */\r
29600ReflectionObject.prototype.resolve = function resolve() {\r
29601 if (this.resolved)\r
29602 return this;\r
29603 if (this.root instanceof Root)\r
29604 this.resolved = true; // only if part of a root\r
29605 return this;\r
29606};\r
29607\r
29608/**\r
29609 * Gets an option value.\r
29610 * @param {string} name Option name\r
29611 * @returns {*} Option value or `undefined` if not set\r
29612 */\r
29613ReflectionObject.prototype.getOption = function getOption(name) {\r
29614 if (this.options)\r
29615 return this.options[name];\r
29616 return undefined;\r
29617};\r
29618\r
29619/**\r
29620 * Sets an option.\r
29621 * @param {string} name Option name\r
29622 * @param {*} value Option value\r
29623 * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set\r
29624 * @returns {ReflectionObject} `this`\r
29625 */\r
29626ReflectionObject.prototype.setOption = function setOption(name, value, ifNotSet) {\r
29627 if (!ifNotSet || !this.options || this.options[name] === undefined)\r
29628 (this.options || (this.options = {}))[name] = value;\r
29629 return this;\r
29630};\r
29631\r
29632/**\r
29633 * Sets multiple options.\r
29634 * @param {Object.<string,*>} options Options to set\r
29635 * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set\r
29636 * @returns {ReflectionObject} `this`\r
29637 */\r
29638ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) {\r
29639 if (options)\r
29640 for (var keys = Object.keys(options), i = 0; i < keys.length; ++i)\r
29641 this.setOption(keys[i], options[keys[i]], ifNotSet);\r
29642 return this;\r
29643};\r
29644\r
29645/**\r
29646 * Converts this instance to its string representation.\r
29647 * @returns {string} Class name[, space, full name]\r
29648 */\r
29649ReflectionObject.prototype.toString = function toString() {\r
29650 var className = this.constructor.className,\r
29651 fullName = this.fullName;\r
29652 if (fullName.length)\r
29653 return className + " " + fullName;\r
29654 return className;\r
29655};\r
29656\r
29657ReflectionObject._configure = function(Root_) {\r
29658 Root = Root_;\r
29659};\r
29660
29661},{"./util":218}],206:[function(require,module,exports){
29662"use strict";\r
29663module.exports = OneOf;\r
29664\r
29665// extends ReflectionObject\r
29666var ReflectionObject = require("./object");\r
29667((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf";\r
29668\r
29669var Field = require("./field"),\r
29670 util = require("./util");\r
29671\r
29672/**\r
29673 * Constructs a new oneof instance.\r
29674 * @classdesc Reflected oneof.\r
29675 * @extends ReflectionObject\r
29676 * @constructor\r
29677 * @param {string} name Oneof name\r
29678 * @param {string[]|Object.<string,*>} [fieldNames] Field names\r
29679 * @param {Object.<string,*>} [options] Declared options\r
29680 * @param {string} [comment] Comment associated with this field\r
29681 */\r
29682function OneOf(name, fieldNames, options, comment) {\r
29683 if (!Array.isArray(fieldNames)) {\r
29684 options = fieldNames;\r
29685 fieldNames = undefined;\r
29686 }\r
29687 ReflectionObject.call(this, name, options);\r
29688\r
29689 /* istanbul ignore if */\r
29690 if (!(fieldNames === undefined || Array.isArray(fieldNames)))\r
29691 throw TypeError("fieldNames must be an Array");\r
29692\r
29693 /**\r
29694 * Field names that belong to this oneof.\r
29695 * @type {string[]}\r
29696 */\r
29697 this.oneof = fieldNames || []; // toJSON, marker\r
29698\r
29699 /**\r
29700 * Fields that belong to this oneof as an array for iteration.\r
29701 * @type {Field[]}\r
29702 * @readonly\r
29703 */\r
29704 this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent\r
29705\r
29706 /**\r
29707 * Comment for this field.\r
29708 * @type {string|null}\r
29709 */\r
29710 this.comment = comment;\r
29711}\r
29712\r
29713/**\r
29714 * Oneof descriptor.\r
29715 * @interface IOneOf\r
29716 * @property {Array.<string>} oneof Oneof field names\r
29717 * @property {Object.<string,*>} [options] Oneof options\r
29718 */\r
29719\r
29720/**\r
29721 * Constructs a oneof from a oneof descriptor.\r
29722 * @param {string} name Oneof name\r
29723 * @param {IOneOf} json Oneof descriptor\r
29724 * @returns {OneOf} Created oneof\r
29725 * @throws {TypeError} If arguments are invalid\r
29726 */\r
29727OneOf.fromJSON = function fromJSON(name, json) {\r
29728 return new OneOf(name, json.oneof, json.options, json.comment);\r
29729};\r
29730\r
29731/**\r
29732 * Converts this oneof to a oneof descriptor.\r
29733 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r
29734 * @returns {IOneOf} Oneof descriptor\r
29735 */\r
29736OneOf.prototype.toJSON = function toJSON(toJSONOptions) {\r
29737 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r
29738 return util.toObject([\r
29739 "options" , this.options,\r
29740 "oneof" , this.oneof,\r
29741 "comment" , keepComments ? this.comment : undefined\r
29742 ]);\r
29743};\r
29744\r
29745/**\r
29746 * Adds the fields of the specified oneof to the parent if not already done so.\r
29747 * @param {OneOf} oneof The oneof\r
29748 * @returns {undefined}\r
29749 * @inner\r
29750 * @ignore\r
29751 */\r
29752function addFieldsToParent(oneof) {\r
29753 if (oneof.parent)\r
29754 for (var i = 0; i < oneof.fieldsArray.length; ++i)\r
29755 if (!oneof.fieldsArray[i].parent)\r
29756 oneof.parent.add(oneof.fieldsArray[i]);\r
29757}\r
29758\r
29759/**\r
29760 * Adds a field to this oneof and removes it from its current parent, if any.\r
29761 * @param {Field} field Field to add\r
29762 * @returns {OneOf} `this`\r
29763 */\r
29764OneOf.prototype.add = function add(field) {\r
29765\r
29766 /* istanbul ignore if */\r
29767 if (!(field instanceof Field))\r
29768 throw TypeError("field must be a Field");\r
29769\r
29770 if (field.parent && field.parent !== this.parent)\r
29771 field.parent.remove(field);\r
29772 this.oneof.push(field.name);\r
29773 this.fieldsArray.push(field);\r
29774 field.partOf = this; // field.parent remains null\r
29775 addFieldsToParent(this);\r
29776 return this;\r
29777};\r
29778\r
29779/**\r
29780 * Removes a field from this oneof and puts it back to the oneof's parent.\r
29781 * @param {Field} field Field to remove\r
29782 * @returns {OneOf} `this`\r
29783 */\r
29784OneOf.prototype.remove = function remove(field) {\r
29785\r
29786 /* istanbul ignore if */\r
29787 if (!(field instanceof Field))\r
29788 throw TypeError("field must be a Field");\r
29789\r
29790 var index = this.fieldsArray.indexOf(field);\r
29791\r
29792 /* istanbul ignore if */\r
29793 if (index < 0)\r
29794 throw Error(field + " is not a member of " + this);\r
29795\r
29796 this.fieldsArray.splice(index, 1);\r
29797 index = this.oneof.indexOf(field.name);\r
29798\r
29799 /* istanbul ignore else */\r
29800 if (index > -1) // theoretical\r
29801 this.oneof.splice(index, 1);\r
29802\r
29803 field.partOf = null;\r
29804 return this;\r
29805};\r
29806\r
29807/**\r
29808 * @override\r
29809 */\r
29810OneOf.prototype.onAdd = function onAdd(parent) {\r
29811 ReflectionObject.prototype.onAdd.call(this, parent);\r
29812 var self = this;\r
29813 // Collect present fields\r
29814 for (var i = 0; i < this.oneof.length; ++i) {\r
29815 var field = parent.get(this.oneof[i]);\r
29816 if (field && !field.partOf) {\r
29817 field.partOf = self;\r
29818 self.fieldsArray.push(field);\r
29819 }\r
29820 }\r
29821 // Add not yet present fields\r
29822 addFieldsToParent(this);\r
29823};\r
29824\r
29825/**\r
29826 * @override\r
29827 */\r
29828OneOf.prototype.onRemove = function onRemove(parent) {\r
29829 for (var i = 0, field; i < this.fieldsArray.length; ++i)\r
29830 if ((field = this.fieldsArray[i]).parent)\r
29831 field.parent.remove(field);\r
29832 ReflectionObject.prototype.onRemove.call(this, parent);\r
29833};\r
29834\r
29835/**\r
29836 * Decorator function as returned by {@link OneOf.d} (TypeScript).\r
29837 * @typedef OneOfDecorator\r
29838 * @type {function}\r
29839 * @param {Object} prototype Target prototype\r
29840 * @param {string} oneofName OneOf name\r
29841 * @returns {undefined}\r
29842 */\r
29843\r
29844/**\r
29845 * OneOf decorator (TypeScript).\r
29846 * @function\r
29847 * @param {...string} fieldNames Field names\r
29848 * @returns {OneOfDecorator} Decorator function\r
29849 * @template T extends string\r
29850 */\r
29851OneOf.d = function decorateOneOf() {\r
29852 var fieldNames = new Array(arguments.length),\r
29853 index = 0;\r
29854 while (index < arguments.length)\r
29855 fieldNames[index] = arguments[index++];\r
29856 return function oneOfDecorator(prototype, oneofName) {\r
29857 util.decorateType(prototype.constructor)\r
29858 .add(new OneOf(oneofName, fieldNames));\r
29859 Object.defineProperty(prototype, oneofName, {\r
29860 get: util.oneOfGetter(fieldNames),\r
29861 set: util.oneOfSetter(fieldNames)\r
29862 });\r
29863 };\r
29864};\r
29865
29866},{"./field":197,"./object":205,"./util":218}],207:[function(require,module,exports){
29867"use strict";\r
29868module.exports = parse;\r
29869\r
29870parse.filename = null;\r
29871parse.defaults = { keepCase: false };\r
29872\r
29873var tokenize = require("./tokenize"),\r
29874 Root = require("./root"),\r
29875 Type = require("./type"),\r
29876 Field = require("./field"),\r
29877 MapField = require("./mapfield"),\r
29878 OneOf = require("./oneof"),\r
29879 Enum = require("./enum"),\r
29880 Service = require("./service"),\r
29881 Method = require("./method"),\r
29882 types = require("./types"),\r
29883 util = require("./util");\r
29884\r
29885var base10Re = /^[1-9][0-9]*$/,\r
29886 base10NegRe = /^-?[1-9][0-9]*$/,\r
29887 base16Re = /^0[x][0-9a-fA-F]+$/,\r
29888 base16NegRe = /^-?0[x][0-9a-fA-F]+$/,\r
29889 base8Re = /^0[0-7]+$/,\r
29890 base8NegRe = /^-?0[0-7]+$/,\r
29891 numberRe = /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,\r
29892 nameRe = /^[a-zA-Z_][a-zA-Z_0-9]*$/,\r
29893 typeRefRe = /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,\r
29894 fqTypeRefRe = /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;\r
29895\r
29896/**\r
29897 * Result object returned from {@link parse}.\r
29898 * @interface IParserResult\r
29899 * @property {string|undefined} package Package name, if declared\r
29900 * @property {string[]|undefined} imports Imports, if any\r
29901 * @property {string[]|undefined} weakImports Weak imports, if any\r
29902 * @property {string|undefined} syntax Syntax, if specified (either `"proto2"` or `"proto3"`)\r
29903 * @property {Root} root Populated root instance\r
29904 */\r
29905\r
29906/**\r
29907 * Options modifying the behavior of {@link parse}.\r
29908 * @interface IParseOptions\r
29909 * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case\r
29910 * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.\r
29911 */\r
29912\r
29913/**\r
29914 * Options modifying the behavior of JSON serialization.\r
29915 * @interface IToJSONOptions\r
29916 * @property {boolean} [keepComments=false] Serializes comments.\r
29917 */\r
29918\r
29919/**\r
29920 * Parses the given .proto source and returns an object with the parsed contents.\r
29921 * @param {string} source Source contents\r
29922 * @param {Root} root Root to populate\r
29923 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\r
29924 * @returns {IParserResult} Parser result\r
29925 * @property {string} filename=null Currently processing file name for error reporting, if known\r
29926 * @property {IParseOptions} defaults Default {@link IParseOptions}\r
29927 */\r
29928function parse(source, root, options) {\r
29929 /* eslint-disable callback-return */\r
29930 if (!(root instanceof Root)) {\r
29931 options = root;\r
29932 root = new Root();\r
29933 }\r
29934 if (!options)\r
29935 options = parse.defaults;\r
29936\r
29937 var tn = tokenize(source, options.alternateCommentMode || false),\r
29938 next = tn.next,\r
29939 push = tn.push,\r
29940 peek = tn.peek,\r
29941 skip = tn.skip,\r
29942 cmnt = tn.cmnt;\r
29943\r
29944 var head = true,\r
29945 pkg,\r
29946 imports,\r
29947 weakImports,\r
29948 syntax,\r
29949 isProto3 = false;\r
29950\r
29951 var ptr = root;\r
29952\r
29953 var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase;\r
29954\r
29955 /* istanbul ignore next */\r
29956 function illegal(token, name, insideTryCatch) {\r
29957 var filename = parse.filename;\r
29958 if (!insideTryCatch)\r
29959 parse.filename = null;\r
29960 return Error("illegal " + (name || "token") + " '" + token + "' (" + (filename ? filename + ", " : "") + "line " + tn.line + ")");\r
29961 }\r
29962\r
29963 function readString() {\r
29964 var values = [],\r
29965 token;\r
29966 do {\r
29967 /* istanbul ignore if */\r
29968 if ((token = next()) !== "\"" && token !== "'")\r
29969 throw illegal(token);\r
29970\r
29971 values.push(next());\r
29972 skip(token);\r
29973 token = peek();\r
29974 } while (token === "\"" || token === "'");\r
29975 return values.join("");\r
29976 }\r
29977\r
29978 function readValue(acceptTypeRef) {\r
29979 var token = next();\r
29980 switch (token) {\r
29981 case "'":\r
29982 case "\"":\r
29983 push(token);\r
29984 return readString();\r
29985 case "true": case "TRUE":\r
29986 return true;\r
29987 case "false": case "FALSE":\r
29988 return false;\r
29989 }\r
29990 try {\r
29991 return parseNumber(token, /* insideTryCatch */ true);\r
29992 } catch (e) {\r
29993\r
29994 /* istanbul ignore else */\r
29995 if (acceptTypeRef && typeRefRe.test(token))\r
29996 return token;\r
29997\r
29998 /* istanbul ignore next */\r
29999 throw illegal(token, "value");\r
30000 }\r
30001 }\r
30002\r
30003 function readRanges(target, acceptStrings) {\r
30004 var token, start;\r
30005 do {\r
30006 if (acceptStrings && ((token = peek()) === "\"" || token === "'"))\r
30007 target.push(readString());\r
30008 else\r
30009 target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]);\r
30010 } while (skip(",", true));\r
30011 skip(";");\r
30012 }\r
30013\r
30014 function parseNumber(token, insideTryCatch) {\r
30015 var sign = 1;\r
30016 if (token.charAt(0) === "-") {\r
30017 sign = -1;\r
30018 token = token.substring(1);\r
30019 }\r
30020 switch (token) {\r
30021 case "inf": case "INF": case "Inf":\r
30022 return sign * Infinity;\r
30023 case "nan": case "NAN": case "Nan": case "NaN":\r
30024 return NaN;\r
30025 case "0":\r
30026 return 0;\r
30027 }\r
30028 if (base10Re.test(token))\r
30029 return sign * parseInt(token, 10);\r
30030 if (base16Re.test(token))\r
30031 return sign * parseInt(token, 16);\r
30032 if (base8Re.test(token))\r
30033 return sign * parseInt(token, 8);\r
30034\r
30035 /* istanbul ignore else */\r
30036 if (numberRe.test(token))\r
30037 return sign * parseFloat(token);\r
30038\r
30039 /* istanbul ignore next */\r
30040 throw illegal(token, "number", insideTryCatch);\r
30041 }\r
30042\r
30043 function parseId(token, acceptNegative) {\r
30044 switch (token) {\r
30045 case "max": case "MAX": case "Max":\r
30046 return 536870911;\r
30047 case "0":\r
30048 return 0;\r
30049 }\r
30050\r
30051 /* istanbul ignore if */\r
30052 if (!acceptNegative && token.charAt(0) === "-")\r
30053 throw illegal(token, "id");\r
30054\r
30055 if (base10NegRe.test(token))\r
30056 return parseInt(token, 10);\r
30057 if (base16NegRe.test(token))\r
30058 return parseInt(token, 16);\r
30059\r
30060 /* istanbul ignore else */\r
30061 if (base8NegRe.test(token))\r
30062 return parseInt(token, 8);\r
30063\r
30064 /* istanbul ignore next */\r
30065 throw illegal(token, "id");\r
30066 }\r
30067\r
30068 function parsePackage() {\r
30069\r
30070 /* istanbul ignore if */\r
30071 if (pkg !== undefined)\r
30072 throw illegal("package");\r
30073\r
30074 pkg = next();\r
30075\r
30076 /* istanbul ignore if */\r
30077 if (!typeRefRe.test(pkg))\r
30078 throw illegal(pkg, "name");\r
30079\r
30080 ptr = ptr.define(pkg);\r
30081 skip(";");\r
30082 }\r
30083\r
30084 function parseImport() {\r
30085 var token = peek();\r
30086 var whichImports;\r
30087 switch (token) {\r
30088 case "weak":\r
30089 whichImports = weakImports || (weakImports = []);\r
30090 next();\r
30091 break;\r
30092 case "public":\r
30093 next();\r
30094 // eslint-disable-line no-fallthrough\r
30095 default:\r
30096 whichImports = imports || (imports = []);\r
30097 break;\r
30098 }\r
30099 token = readString();\r
30100 skip(";");\r
30101 whichImports.push(token);\r
30102 }\r
30103\r
30104 function parseSyntax() {\r
30105 skip("=");\r
30106 syntax = readString();\r
30107 isProto3 = syntax === "proto3";\r
30108\r
30109 /* istanbul ignore if */\r
30110 if (!isProto3 && syntax !== "proto2")\r
30111 throw illegal(syntax, "syntax");\r
30112\r
30113 skip(";");\r
30114 }\r
30115\r
30116 function parseCommon(parent, token) {\r
30117 switch (token) {\r
30118\r
30119 case "option":\r
30120 parseOption(parent, token);\r
30121 skip(";");\r
30122 return true;\r
30123\r
30124 case "message":\r
30125 parseType(parent, token);\r
30126 return true;\r
30127\r
30128 case "enum":\r
30129 parseEnum(parent, token);\r
30130 return true;\r
30131\r
30132 case "service":\r
30133 parseService(parent, token);\r
30134 return true;\r
30135\r
30136 case "extend":\r
30137 parseExtension(parent, token);\r
30138 return true;\r
30139 }\r
30140 return false;\r
30141 }\r
30142\r
30143 function ifBlock(obj, fnIf, fnElse) {\r
30144 var trailingLine = tn.line;\r
30145 if (obj) {\r
30146 obj.comment = cmnt(); // try block-type comment\r
30147 obj.filename = parse.filename;\r
30148 }\r
30149 if (skip("{", true)) {\r
30150 var token;\r
30151 while ((token = next()) !== "}")\r
30152 fnIf(token);\r
30153 skip(";", true);\r
30154 } else {\r
30155 if (fnElse)\r
30156 fnElse();\r
30157 skip(";");\r
30158 if (obj && typeof obj.comment !== "string")\r
30159 obj.comment = cmnt(trailingLine); // try line-type comment if no block\r
30160 }\r
30161 }\r
30162\r
30163 function parseType(parent, token) {\r
30164\r
30165 /* istanbul ignore if */\r
30166 if (!nameRe.test(token = next()))\r
30167 throw illegal(token, "type name");\r
30168\r
30169 var type = new Type(token);\r
30170 ifBlock(type, function parseType_block(token) {\r
30171 if (parseCommon(type, token))\r
30172 return;\r
30173\r
30174 switch (token) {\r
30175\r
30176 case "map":\r
30177 parseMapField(type, token);\r
30178 break;\r
30179\r
30180 case "required":\r
30181 case "optional":\r
30182 case "repeated":\r
30183 parseField(type, token);\r
30184 break;\r
30185\r
30186 case "oneof":\r
30187 parseOneOf(type, token);\r
30188 break;\r
30189\r
30190 case "extensions":\r
30191 readRanges(type.extensions || (type.extensions = []));\r
30192 break;\r
30193\r
30194 case "reserved":\r
30195 readRanges(type.reserved || (type.reserved = []), true);\r
30196 break;\r
30197\r
30198 default:\r
30199 /* istanbul ignore if */\r
30200 if (!isProto3 || !typeRefRe.test(token))\r
30201 throw illegal(token);\r
30202\r
30203 push(token);\r
30204 parseField(type, "optional");\r
30205 break;\r
30206 }\r
30207 });\r
30208 parent.add(type);\r
30209 }\r
30210\r
30211 function parseField(parent, rule, extend) {\r
30212 var type = next();\r
30213 if (type === "group") {\r
30214 parseGroup(parent, rule);\r
30215 return;\r
30216 }\r
30217\r
30218 /* istanbul ignore if */\r
30219 if (!typeRefRe.test(type))\r
30220 throw illegal(type, "type");\r
30221\r
30222 var name = next();\r
30223\r
30224 /* istanbul ignore if */\r
30225 if (!nameRe.test(name))\r
30226 throw illegal(name, "name");\r
30227\r
30228 name = applyCase(name);\r
30229 skip("=");\r
30230\r
30231 var field = new Field(name, parseId(next()), type, rule, extend);\r
30232 ifBlock(field, function parseField_block(token) {\r
30233\r
30234 /* istanbul ignore else */\r
30235 if (token === "option") {\r
30236 parseOption(field, token);\r
30237 skip(";");\r
30238 } else\r
30239 throw illegal(token);\r
30240\r
30241 }, function parseField_line() {\r
30242 parseInlineOptions(field);\r
30243 });\r
30244 parent.add(field);\r
30245\r
30246 // JSON defaults to packed=true if not set so we have to set packed=false explicity when\r
30247 // parsing proto2 descriptors without the option, where applicable. This must be done for\r
30248 // all known packable types and anything that could be an enum (= is not a basic type).\r
30249 if (!isProto3 && field.repeated && (types.packed[type] !== undefined || types.basic[type] === undefined))\r
30250 field.setOption("packed", false, /* ifNotSet */ true);\r
30251 }\r
30252\r
30253 function parseGroup(parent, rule) {\r
30254 var name = next();\r
30255\r
30256 /* istanbul ignore if */\r
30257 if (!nameRe.test(name))\r
30258 throw illegal(name, "name");\r
30259\r
30260 var fieldName = util.lcFirst(name);\r
30261 if (name === fieldName)\r
30262 name = util.ucFirst(name);\r
30263 skip("=");\r
30264 var id = parseId(next());\r
30265 var type = new Type(name);\r
30266 type.group = true;\r
30267 var field = new Field(fieldName, id, name, rule);\r
30268 field.filename = parse.filename;\r
30269 ifBlock(type, function parseGroup_block(token) {\r
30270 switch (token) {\r
30271\r
30272 case "option":\r
30273 parseOption(type, token);\r
30274 skip(";");\r
30275 break;\r
30276\r
30277 case "required":\r
30278 case "optional":\r
30279 case "repeated":\r
30280 parseField(type, token);\r
30281 break;\r
30282\r
30283 /* istanbul ignore next */\r
30284 default:\r
30285 throw illegal(token); // there are no groups with proto3 semantics\r
30286 }\r
30287 });\r
30288 parent.add(type)\r
30289 .add(field);\r
30290 }\r
30291\r
30292 function parseMapField(parent) {\r
30293 skip("<");\r
30294 var keyType = next();\r
30295\r
30296 /* istanbul ignore if */\r
30297 if (types.mapKey[keyType] === undefined)\r
30298 throw illegal(keyType, "type");\r
30299\r
30300 skip(",");\r
30301 var valueType = next();\r
30302\r
30303 /* istanbul ignore if */\r
30304 if (!typeRefRe.test(valueType))\r
30305 throw illegal(valueType, "type");\r
30306\r
30307 skip(">");\r
30308 var name = next();\r
30309\r
30310 /* istanbul ignore if */\r
30311 if (!nameRe.test(name))\r
30312 throw illegal(name, "name");\r
30313\r
30314 skip("=");\r
30315 var field = new MapField(applyCase(name), parseId(next()), keyType, valueType);\r
30316 ifBlock(field, function parseMapField_block(token) {\r
30317\r
30318 /* istanbul ignore else */\r
30319 if (token === "option") {\r
30320 parseOption(field, token);\r
30321 skip(";");\r
30322 } else\r
30323 throw illegal(token);\r
30324\r
30325 }, function parseMapField_line() {\r
30326 parseInlineOptions(field);\r
30327 });\r
30328 parent.add(field);\r
30329 }\r
30330\r
30331 function parseOneOf(parent, token) {\r
30332\r
30333 /* istanbul ignore if */\r
30334 if (!nameRe.test(token = next()))\r
30335 throw illegal(token, "name");\r
30336\r
30337 var oneof = new OneOf(applyCase(token));\r
30338 ifBlock(oneof, function parseOneOf_block(token) {\r
30339 if (token === "option") {\r
30340 parseOption(oneof, token);\r
30341 skip(";");\r
30342 } else {\r
30343 push(token);\r
30344 parseField(oneof, "optional");\r
30345 }\r
30346 });\r
30347 parent.add(oneof);\r
30348 }\r
30349\r
30350 function parseEnum(parent, token) {\r
30351\r
30352 /* istanbul ignore if */\r
30353 if (!nameRe.test(token = next()))\r
30354 throw illegal(token, "name");\r
30355\r
30356 var enm = new Enum(token);\r
30357 ifBlock(enm, function parseEnum_block(token) {\r
30358 switch(token) {\r
30359 case "option":\r
30360 parseOption(enm, token);\r
30361 skip(";");\r
30362 break;\r
30363\r
30364 case "reserved":\r
30365 readRanges(enm.reserved || (enm.reserved = []), true);\r
30366 break;\r
30367\r
30368 default:\r
30369 parseEnumValue(enm, token);\r
30370 }\r
30371 });\r
30372 parent.add(enm);\r
30373 }\r
30374\r
30375 function parseEnumValue(parent, token) {\r
30376\r
30377 /* istanbul ignore if */\r
30378 if (!nameRe.test(token))\r
30379 throw illegal(token, "name");\r
30380\r
30381 skip("=");\r
30382 var value = parseId(next(), true),\r
30383 dummy = {};\r
30384 ifBlock(dummy, function parseEnumValue_block(token) {\r
30385\r
30386 /* istanbul ignore else */\r
30387 if (token === "option") {\r
30388 parseOption(dummy, token); // skip\r
30389 skip(";");\r
30390 } else\r
30391 throw illegal(token);\r
30392\r
30393 }, function parseEnumValue_line() {\r
30394 parseInlineOptions(dummy); // skip\r
30395 });\r
30396 parent.add(token, value, dummy.comment);\r
30397 }\r
30398\r
30399 function parseOption(parent, token) {\r
30400 var isCustom = skip("(", true);\r
30401\r
30402 /* istanbul ignore if */\r
30403 if (!typeRefRe.test(token = next()))\r
30404 throw illegal(token, "name");\r
30405\r
30406 var name = token;\r
30407 if (isCustom) {\r
30408 skip(")");\r
30409 name = "(" + name + ")";\r
30410 token = peek();\r
30411 if (fqTypeRefRe.test(token)) {\r
30412 name += token;\r
30413 next();\r
30414 }\r
30415 }\r
30416 skip("=");\r
30417 parseOptionValue(parent, name);\r
30418 }\r
30419\r
30420 function parseOptionValue(parent, name) {\r
30421 if (skip("{", true)) { // { a: "foo" b { c: "bar" } }\r
30422 do {\r
30423 /* istanbul ignore if */\r
30424 if (!nameRe.test(token = next()))\r
30425 throw illegal(token, "name");\r
30426\r
30427 if (peek() === "{")\r
30428 parseOptionValue(parent, name + "." + token);\r
30429 else {\r
30430 skip(":");\r
30431 if (peek() === "{")\r
30432 parseOptionValue(parent, name + "." + token);\r
30433 else\r
30434 setOption(parent, name + "." + token, readValue(true));\r
30435 }\r
30436 } while (!skip("}", true));\r
30437 } else\r
30438 setOption(parent, name, readValue(true));\r
30439 // Does not enforce a delimiter to be universal\r
30440 }\r
30441\r
30442 function setOption(parent, name, value) {\r
30443 if (parent.setOption)\r
30444 parent.setOption(name, value);\r
30445 }\r
30446\r
30447 function parseInlineOptions(parent) {\r
30448 if (skip("[", true)) {\r
30449 do {\r
30450 parseOption(parent, "option");\r
30451 } while (skip(",", true));\r
30452 skip("]");\r
30453 }\r
30454 return parent;\r
30455 }\r
30456\r
30457 function parseService(parent, token) {\r
30458\r
30459 /* istanbul ignore if */\r
30460 if (!nameRe.test(token = next()))\r
30461 throw illegal(token, "service name");\r
30462\r
30463 var service = new Service(token);\r
30464 ifBlock(service, function parseService_block(token) {\r
30465 if (parseCommon(service, token))\r
30466 return;\r
30467\r
30468 /* istanbul ignore else */\r
30469 if (token === "rpc")\r
30470 parseMethod(service, token);\r
30471 else\r
30472 throw illegal(token);\r
30473 });\r
30474 parent.add(service);\r
30475 }\r
30476\r
30477 function parseMethod(parent, token) {\r
30478 var type = token;\r
30479\r
30480 /* istanbul ignore if */\r
30481 if (!nameRe.test(token = next()))\r
30482 throw illegal(token, "name");\r
30483\r
30484 var name = token,\r
30485 requestType, requestStream,\r
30486 responseType, responseStream;\r
30487\r
30488 skip("(");\r
30489 if (skip("stream", true))\r
30490 requestStream = true;\r
30491\r
30492 /* istanbul ignore if */\r
30493 if (!typeRefRe.test(token = next()))\r
30494 throw illegal(token);\r
30495\r
30496 requestType = token;\r
30497 skip(")"); skip("returns"); skip("(");\r
30498 if (skip("stream", true))\r
30499 responseStream = true;\r
30500\r
30501 /* istanbul ignore if */\r
30502 if (!typeRefRe.test(token = next()))\r
30503 throw illegal(token);\r
30504\r
30505 responseType = token;\r
30506 skip(")");\r
30507\r
30508 var method = new Method(name, type, requestType, responseType, requestStream, responseStream);\r
30509 ifBlock(method, function parseMethod_block(token) {\r
30510\r
30511 /* istanbul ignore else */\r
30512 if (token === "option") {\r
30513 parseOption(method, token);\r
30514 skip(";");\r
30515 } else\r
30516 throw illegal(token);\r
30517\r
30518 });\r
30519 parent.add(method);\r
30520 }\r
30521\r
30522 function parseExtension(parent, token) {\r
30523\r
30524 /* istanbul ignore if */\r
30525 if (!typeRefRe.test(token = next()))\r
30526 throw illegal(token, "reference");\r
30527\r
30528 var reference = token;\r
30529 ifBlock(null, function parseExtension_block(token) {\r
30530 switch (token) {\r
30531\r
30532 case "required":\r
30533 case "repeated":\r
30534 case "optional":\r
30535 parseField(parent, token, reference);\r
30536 break;\r
30537\r
30538 default:\r
30539 /* istanbul ignore if */\r
30540 if (!isProto3 || !typeRefRe.test(token))\r
30541 throw illegal(token);\r
30542 push(token);\r
30543 parseField(parent, "optional", reference);\r
30544 break;\r
30545 }\r
30546 });\r
30547 }\r
30548\r
30549 var token;\r
30550 while ((token = next()) !== null) {\r
30551 switch (token) {\r
30552\r
30553 case "package":\r
30554\r
30555 /* istanbul ignore if */\r
30556 if (!head)\r
30557 throw illegal(token);\r
30558\r
30559 parsePackage();\r
30560 break;\r
30561\r
30562 case "import":\r
30563\r
30564 /* istanbul ignore if */\r
30565 if (!head)\r
30566 throw illegal(token);\r
30567\r
30568 parseImport();\r
30569 break;\r
30570\r
30571 case "syntax":\r
30572\r
30573 /* istanbul ignore if */\r
30574 if (!head)\r
30575 throw illegal(token);\r
30576\r
30577 parseSyntax();\r
30578 break;\r
30579\r
30580 case "option":\r
30581\r
30582 /* istanbul ignore if */\r
30583 if (!head)\r
30584 throw illegal(token);\r
30585\r
30586 parseOption(ptr, token);\r
30587 skip(";");\r
30588 break;\r
30589\r
30590 default:\r
30591\r
30592 /* istanbul ignore else */\r
30593 if (parseCommon(ptr, token)) {\r
30594 head = false;\r
30595 continue;\r
30596 }\r
30597\r
30598 /* istanbul ignore next */\r
30599 throw illegal(token);\r
30600 }\r
30601 }\r
30602\r
30603 parse.filename = null;\r
30604 return {\r
30605 "package" : pkg,\r
30606 "imports" : imports,\r
30607 weakImports : weakImports,\r
30608 syntax : syntax,\r
30609 root : root\r
30610 };\r
30611}\r
30612\r
30613/**\r
30614 * Parses the given .proto source and returns an object with the parsed contents.\r
30615 * @name parse\r
30616 * @function\r
30617 * @param {string} source Source contents\r
30618 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\r
30619 * @returns {IParserResult} Parser result\r
30620 * @property {string} filename=null Currently processing file name for error reporting, if known\r
30621 * @property {IParseOptions} defaults Default {@link IParseOptions}\r
30622 * @variation 2\r
30623 */\r
30624
30625},{"./enum":196,"./field":197,"./mapfield":201,"./method":203,"./oneof":206,"./root":210,"./service":214,"./tokenize":215,"./type":216,"./types":217,"./util":218}],208:[function(require,module,exports){
30626"use strict";\r
30627module.exports = Reader;\r
30628\r
30629var util = require("./util/minimal");\r
30630\r
30631var BufferReader; // cyclic\r
30632\r
30633var LongBits = util.LongBits,\r
30634 utf8 = util.utf8;\r
30635\r
30636/* istanbul ignore next */\r
30637function indexOutOfRange(reader, writeLength) {\r
30638 return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len);\r
30639}\r
30640\r
30641/**\r
30642 * Constructs a new reader instance using the specified buffer.\r
30643 * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.\r
30644 * @constructor\r
30645 * @param {Uint8Array} buffer Buffer to read from\r
30646 */\r
30647function Reader(buffer) {\r
30648\r
30649 /**\r
30650 * Read buffer.\r
30651 * @type {Uint8Array}\r
30652 */\r
30653 this.buf = buffer;\r
30654\r
30655 /**\r
30656 * Read buffer position.\r
30657 * @type {number}\r
30658 */\r
30659 this.pos = 0;\r
30660\r
30661 /**\r
30662 * Read buffer length.\r
30663 * @type {number}\r
30664 */\r
30665 this.len = buffer.length;\r
30666}\r
30667\r
30668var create_array = typeof Uint8Array !== "undefined"\r
30669 ? function create_typed_array(buffer) {\r
30670 if (buffer instanceof Uint8Array || Array.isArray(buffer))\r
30671 return new Reader(buffer);\r
30672 throw Error("illegal buffer");\r
30673 }\r
30674 /* istanbul ignore next */\r
30675 : function create_array(buffer) {\r
30676 if (Array.isArray(buffer))\r
30677 return new Reader(buffer);\r
30678 throw Error("illegal buffer");\r
30679 };\r
30680\r
30681/**\r
30682 * Creates a new reader using the specified buffer.\r
30683 * @function\r
30684 * @param {Uint8Array|Buffer} buffer Buffer to read from\r
30685 * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}\r
30686 * @throws {Error} If `buffer` is not a valid buffer\r
30687 */\r
30688Reader.create = util.Buffer\r
30689 ? function create_buffer_setup(buffer) {\r
30690 return (Reader.create = function create_buffer(buffer) {\r
30691 return util.Buffer.isBuffer(buffer)\r
30692 ? new BufferReader(buffer)\r
30693 /* istanbul ignore next */\r
30694 : create_array(buffer);\r
30695 })(buffer);\r
30696 }\r
30697 /* istanbul ignore next */\r
30698 : create_array;\r
30699\r
30700Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice;\r
30701\r
30702/**\r
30703 * Reads a varint as an unsigned 32 bit value.\r
30704 * @function\r
30705 * @returns {number} Value read\r
30706 */\r
30707Reader.prototype.uint32 = (function read_uint32_setup() {\r
30708 var value = 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)\r
30709 return function read_uint32() {\r
30710 value = ( this.buf[this.pos] & 127 ) >>> 0; if (this.buf[this.pos++] < 128) return value;\r
30711 value = (value | (this.buf[this.pos] & 127) << 7) >>> 0; if (this.buf[this.pos++] < 128) return value;\r
30712 value = (value | (this.buf[this.pos] & 127) << 14) >>> 0; if (this.buf[this.pos++] < 128) return value;\r
30713 value = (value | (this.buf[this.pos] & 127) << 21) >>> 0; if (this.buf[this.pos++] < 128) return value;\r
30714 value = (value | (this.buf[this.pos] & 15) << 28) >>> 0; if (this.buf[this.pos++] < 128) return value;\r
30715\r
30716 /* istanbul ignore if */\r
30717 if ((this.pos += 5) > this.len) {\r
30718 this.pos = this.len;\r
30719 throw indexOutOfRange(this, 10);\r
30720 }\r
30721 return value;\r
30722 };\r
30723})();\r
30724\r
30725/**\r
30726 * Reads a varint as a signed 32 bit value.\r
30727 * @returns {number} Value read\r
30728 */\r
30729Reader.prototype.int32 = function read_int32() {\r
30730 return this.uint32() | 0;\r
30731};\r
30732\r
30733/**\r
30734 * Reads a zig-zag encoded varint as a signed 32 bit value.\r
30735 * @returns {number} Value read\r
30736 */\r
30737Reader.prototype.sint32 = function read_sint32() {\r
30738 var value = this.uint32();\r
30739 return value >>> 1 ^ -(value & 1) | 0;\r
30740};\r
30741\r
30742/* eslint-disable no-invalid-this */\r
30743\r
30744function readLongVarint() {\r
30745 // tends to deopt with local vars for octet etc.\r
30746 var bits = new LongBits(0, 0);\r
30747 var i = 0;\r
30748 if (this.len - this.pos > 4) { // fast route (lo)\r
30749 for (; i < 4; ++i) {\r
30750 // 1st..4th\r
30751 bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\r
30752 if (this.buf[this.pos++] < 128)\r
30753 return bits;\r
30754 }\r
30755 // 5th\r
30756 bits.lo = (bits.lo | (this.buf[this.pos] & 127) << 28) >>> 0;\r
30757 bits.hi = (bits.hi | (this.buf[this.pos] & 127) >> 4) >>> 0;\r
30758 if (this.buf[this.pos++] < 128)\r
30759 return bits;\r
30760 i = 0;\r
30761 } else {\r
30762 for (; i < 3; ++i) {\r
30763 /* istanbul ignore if */\r
30764 if (this.pos >= this.len)\r
30765 throw indexOutOfRange(this);\r
30766 // 1st..3th\r
30767 bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0;\r
30768 if (this.buf[this.pos++] < 128)\r
30769 return bits;\r
30770 }\r
30771 // 4th\r
30772 bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0;\r
30773 return bits;\r
30774 }\r
30775 if (this.len - this.pos > 4) { // fast route (hi)\r
30776 for (; i < 5; ++i) {\r
30777 // 6th..10th\r
30778 bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\r
30779 if (this.buf[this.pos++] < 128)\r
30780 return bits;\r
30781 }\r
30782 } else {\r
30783 for (; i < 5; ++i) {\r
30784 /* istanbul ignore if */\r
30785 if (this.pos >= this.len)\r
30786 throw indexOutOfRange(this);\r
30787 // 6th..10th\r
30788 bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0;\r
30789 if (this.buf[this.pos++] < 128)\r
30790 return bits;\r
30791 }\r
30792 }\r
30793 /* istanbul ignore next */\r
30794 throw Error("invalid varint encoding");\r
30795}\r
30796\r
30797/* eslint-enable no-invalid-this */\r
30798\r
30799/**\r
30800 * Reads a varint as a signed 64 bit value.\r
30801 * @name Reader#int64\r
30802 * @function\r
30803 * @returns {Long} Value read\r
30804 */\r
30805\r
30806/**\r
30807 * Reads a varint as an unsigned 64 bit value.\r
30808 * @name Reader#uint64\r
30809 * @function\r
30810 * @returns {Long} Value read\r
30811 */\r
30812\r
30813/**\r
30814 * Reads a zig-zag encoded varint as a signed 64 bit value.\r
30815 * @name Reader#sint64\r
30816 * @function\r
30817 * @returns {Long} Value read\r
30818 */\r
30819\r
30820/**\r
30821 * Reads a varint as a boolean.\r
30822 * @returns {boolean} Value read\r
30823 */\r
30824Reader.prototype.bool = function read_bool() {\r
30825 return this.uint32() !== 0;\r
30826};\r
30827\r
30828function readFixed32_end(buf, end) { // note that this uses `end`, not `pos`\r
30829 return (buf[end - 4]\r
30830 | buf[end - 3] << 8\r
30831 | buf[end - 2] << 16\r
30832 | buf[end - 1] << 24) >>> 0;\r
30833}\r
30834\r
30835/**\r
30836 * Reads fixed 32 bits as an unsigned 32 bit integer.\r
30837 * @returns {number} Value read\r
30838 */\r
30839Reader.prototype.fixed32 = function read_fixed32() {\r
30840\r
30841 /* istanbul ignore if */\r
30842 if (this.pos + 4 > this.len)\r
30843 throw indexOutOfRange(this, 4);\r
30844\r
30845 return readFixed32_end(this.buf, this.pos += 4);\r
30846};\r
30847\r
30848/**\r
30849 * Reads fixed 32 bits as a signed 32 bit integer.\r
30850 * @returns {number} Value read\r
30851 */\r
30852Reader.prototype.sfixed32 = function read_sfixed32() {\r
30853\r
30854 /* istanbul ignore if */\r
30855 if (this.pos + 4 > this.len)\r
30856 throw indexOutOfRange(this, 4);\r
30857\r
30858 return readFixed32_end(this.buf, this.pos += 4) | 0;\r
30859};\r
30860\r
30861/* eslint-disable no-invalid-this */\r
30862\r
30863function readFixed64(/* this: Reader */) {\r
30864\r
30865 /* istanbul ignore if */\r
30866 if (this.pos + 8 > this.len)\r
30867 throw indexOutOfRange(this, 8);\r
30868\r
30869 return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4));\r
30870}\r
30871\r
30872/* eslint-enable no-invalid-this */\r
30873\r
30874/**\r
30875 * Reads fixed 64 bits.\r
30876 * @name Reader#fixed64\r
30877 * @function\r
30878 * @returns {Long} Value read\r
30879 */\r
30880\r
30881/**\r
30882 * Reads zig-zag encoded fixed 64 bits.\r
30883 * @name Reader#sfixed64\r
30884 * @function\r
30885 * @returns {Long} Value read\r
30886 */\r
30887\r
30888/**\r
30889 * Reads a float (32 bit) as a number.\r
30890 * @function\r
30891 * @returns {number} Value read\r
30892 */\r
30893Reader.prototype.float = function read_float() {\r
30894\r
30895 /* istanbul ignore if */\r
30896 if (this.pos + 4 > this.len)\r
30897 throw indexOutOfRange(this, 4);\r
30898\r
30899 var value = util.float.readFloatLE(this.buf, this.pos);\r
30900 this.pos += 4;\r
30901 return value;\r
30902};\r
30903\r
30904/**\r
30905 * Reads a double (64 bit float) as a number.\r
30906 * @function\r
30907 * @returns {number} Value read\r
30908 */\r
30909Reader.prototype.double = function read_double() {\r
30910\r
30911 /* istanbul ignore if */\r
30912 if (this.pos + 8 > this.len)\r
30913 throw indexOutOfRange(this, 4);\r
30914\r
30915 var value = util.float.readDoubleLE(this.buf, this.pos);\r
30916 this.pos += 8;\r
30917 return value;\r
30918};\r
30919\r
30920/**\r
30921 * Reads a sequence of bytes preceeded by its length as a varint.\r
30922 * @returns {Uint8Array} Value read\r
30923 */\r
30924Reader.prototype.bytes = function read_bytes() {\r
30925 var length = this.uint32(),\r
30926 start = this.pos,\r
30927 end = this.pos + length;\r
30928\r
30929 /* istanbul ignore if */\r
30930 if (end > this.len)\r
30931 throw indexOutOfRange(this, length);\r
30932\r
30933 this.pos += length;\r
30934 if (Array.isArray(this.buf)) // plain array\r
30935 return this.buf.slice(start, end);\r
30936 return start === end // fix for IE 10/Win8 and others' subarray returning array of size 1\r
30937 ? new this.buf.constructor(0)\r
30938 : this._slice.call(this.buf, start, end);\r
30939};\r
30940\r
30941/**\r
30942 * Reads a string preceeded by its byte length as a varint.\r
30943 * @returns {string} Value read\r
30944 */\r
30945Reader.prototype.string = function read_string() {\r
30946 var bytes = this.bytes();\r
30947 return utf8.read(bytes, 0, bytes.length);\r
30948};\r
30949\r
30950/**\r
30951 * Skips the specified number of bytes if specified, otherwise skips a varint.\r
30952 * @param {number} [length] Length if known, otherwise a varint is assumed\r
30953 * @returns {Reader} `this`\r
30954 */\r
30955Reader.prototype.skip = function skip(length) {\r
30956 if (typeof length === "number") {\r
30957 /* istanbul ignore if */\r
30958 if (this.pos + length > this.len)\r
30959 throw indexOutOfRange(this, length);\r
30960 this.pos += length;\r
30961 } else {\r
30962 do {\r
30963 /* istanbul ignore if */\r
30964 if (this.pos >= this.len)\r
30965 throw indexOutOfRange(this);\r
30966 } while (this.buf[this.pos++] & 128);\r
30967 }\r
30968 return this;\r
30969};\r
30970\r
30971/**\r
30972 * Skips the next element of the specified wire type.\r
30973 * @param {number} wireType Wire type received\r
30974 * @returns {Reader} `this`\r
30975 */\r
30976Reader.prototype.skipType = function(wireType) {\r
30977 switch (wireType) {\r
30978 case 0:\r
30979 this.skip();\r
30980 break;\r
30981 case 1:\r
30982 this.skip(8);\r
30983 break;\r
30984 case 2:\r
30985 this.skip(this.uint32());\r
30986 break;\r
30987 case 3:\r
30988 do { // eslint-disable-line no-constant-condition\r
30989 if ((wireType = this.uint32() & 7) === 4)\r
30990 break;\r
30991 this.skipType(wireType);\r
30992 } while (true);\r
30993 break;\r
30994 case 5:\r
30995 this.skip(4);\r
30996 break;\r
30997\r
30998 /* istanbul ignore next */\r
30999 default:\r
31000 throw Error("invalid wire type " + wireType + " at offset " + this.pos);\r
31001 }\r
31002 return this;\r
31003};\r
31004\r
31005Reader._configure = function(BufferReader_) {\r
31006 BufferReader = BufferReader_;\r
31007\r
31008 var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber";\r
31009 util.merge(Reader.prototype, {\r
31010\r
31011 int64: function read_int64() {\r
31012 return readLongVarint.call(this)[fn](false);\r
31013 },\r
31014\r
31015 uint64: function read_uint64() {\r
31016 return readLongVarint.call(this)[fn](true);\r
31017 },\r
31018\r
31019 sint64: function read_sint64() {\r
31020 return readLongVarint.call(this).zzDecode()[fn](false);\r
31021 },\r
31022\r
31023 fixed64: function read_fixed64() {\r
31024 return readFixed64.call(this)[fn](true);\r
31025 },\r
31026\r
31027 sfixed64: function read_sfixed64() {\r
31028 return readFixed64.call(this)[fn](false);\r
31029 }\r
31030\r
31031 });\r
31032};\r
31033
31034},{"./util/minimal":220}],209:[function(require,module,exports){
31035"use strict";\r
31036module.exports = BufferReader;\r
31037\r
31038// extends Reader\r
31039var Reader = require("./reader");\r
31040(BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader;\r
31041\r
31042var util = require("./util/minimal");\r
31043\r
31044/**\r
31045 * Constructs a new buffer reader instance.\r
31046 * @classdesc Wire format reader using node buffers.\r
31047 * @extends Reader\r
31048 * @constructor\r
31049 * @param {Buffer} buffer Buffer to read from\r
31050 */\r
31051function BufferReader(buffer) {\r
31052 Reader.call(this, buffer);\r
31053\r
31054 /**\r
31055 * Read buffer.\r
31056 * @name BufferReader#buf\r
31057 * @type {Buffer}\r
31058 */\r
31059}\r
31060\r
31061/* istanbul ignore else */\r
31062if (util.Buffer)\r
31063 BufferReader.prototype._slice = util.Buffer.prototype.slice;\r
31064\r
31065/**\r
31066 * @override\r
31067 */\r
31068BufferReader.prototype.string = function read_string_buffer() {\r
31069 var len = this.uint32(); // modifies pos\r
31070 return this.buf.utf8Slice(this.pos, this.pos = Math.min(this.pos + len, this.len));\r
31071};\r
31072\r
31073/**\r
31074 * Reads a sequence of bytes preceeded by its length as a varint.\r
31075 * @name BufferReader#bytes\r
31076 * @function\r
31077 * @returns {Buffer} Value read\r
31078 */\r
31079
31080},{"./reader":208,"./util/minimal":220}],210:[function(require,module,exports){
31081"use strict";\r
31082module.exports = Root;\r
31083\r
31084// extends Namespace\r
31085var Namespace = require("./namespace");\r
31086((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root";\r
31087\r
31088var Field = require("./field"),\r
31089 Enum = require("./enum"),\r
31090 OneOf = require("./oneof"),\r
31091 util = require("./util");\r
31092\r
31093var Type, // cyclic\r
31094 parse, // might be excluded\r
31095 common; // "\r
31096\r
31097/**\r
31098 * Constructs a new root namespace instance.\r
31099 * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.\r
31100 * @extends NamespaceBase\r
31101 * @constructor\r
31102 * @param {Object.<string,*>} [options] Top level options\r
31103 */\r
31104function Root(options) {\r
31105 Namespace.call(this, "", options);\r
31106\r
31107 /**\r
31108 * Deferred extension fields.\r
31109 * @type {Field[]}\r
31110 */\r
31111 this.deferred = [];\r
31112\r
31113 /**\r
31114 * Resolved file names of loaded files.\r
31115 * @type {string[]}\r
31116 */\r
31117 this.files = [];\r
31118}\r
31119\r
31120/**\r
31121 * Loads a namespace descriptor into a root namespace.\r
31122 * @param {INamespace} json Nameespace descriptor\r
31123 * @param {Root} [root] Root namespace, defaults to create a new one if omitted\r
31124 * @returns {Root} Root namespace\r
31125 */\r
31126Root.fromJSON = function fromJSON(json, root) {\r
31127 if (!root)\r
31128 root = new Root();\r
31129 if (json.options)\r
31130 root.setOptions(json.options);\r
31131 return root.addJSON(json.nested);\r
31132};\r
31133\r
31134/**\r
31135 * Resolves the path of an imported file, relative to the importing origin.\r
31136 * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.\r
31137 * @function\r
31138 * @param {string} origin The file name of the importing file\r
31139 * @param {string} target The file name being imported\r
31140 * @returns {string|null} Resolved path to `target` or `null` to skip the file\r
31141 */\r
31142Root.prototype.resolvePath = util.path.resolve;\r
31143\r
31144// A symbol-like function to safely signal synchronous loading\r
31145/* istanbul ignore next */\r
31146function SYNC() {} // eslint-disable-line no-empty-function\r
31147\r
31148/**\r
31149 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\r
31150 * @param {string|string[]} filename Names of one or multiple files to load\r
31151 * @param {IParseOptions} options Parse options\r
31152 * @param {LoadCallback} callback Callback function\r
31153 * @returns {undefined}\r
31154 */\r
31155Root.prototype.load = function load(filename, options, callback) {\r
31156 if (typeof options === "function") {\r
31157 callback = options;\r
31158 options = undefined;\r
31159 }\r
31160 var self = this;\r
31161 if (!callback)\r
31162 return util.asPromise(load, self, filename, options);\r
31163\r
31164 var sync = callback === SYNC; // undocumented\r
31165\r
31166 // Finishes loading by calling the callback (exactly once)\r
31167 function finish(err, root) {\r
31168 /* istanbul ignore if */\r
31169 if (!callback)\r
31170 return;\r
31171 var cb = callback;\r
31172 callback = null;\r
31173 if (sync)\r
31174 throw err;\r
31175 cb(err, root);\r
31176 }\r
31177\r
31178 // Processes a single file\r
31179 function process(filename, source) {\r
31180 try {\r
31181 if (util.isString(source) && source.charAt(0) === "{")\r
31182 source = JSON.parse(source);\r
31183 if (!util.isString(source))\r
31184 self.setOptions(source.options).addJSON(source.nested);\r
31185 else {\r
31186 parse.filename = filename;\r
31187 var parsed = parse(source, self, options),\r
31188 resolved,\r
31189 i = 0;\r
31190 if (parsed.imports)\r
31191 for (; i < parsed.imports.length; ++i)\r
31192 if (resolved = self.resolvePath(filename, parsed.imports[i]))\r
31193 fetch(resolved);\r
31194 if (parsed.weakImports)\r
31195 for (i = 0; i < parsed.weakImports.length; ++i)\r
31196 if (resolved = self.resolvePath(filename, parsed.weakImports[i]))\r
31197 fetch(resolved, true);\r
31198 }\r
31199 } catch (err) {\r
31200 finish(err);\r
31201 }\r
31202 if (!sync && !queued)\r
31203 finish(null, self); // only once anyway\r
31204 }\r
31205\r
31206 // Fetches a single file\r
31207 function fetch(filename, weak) {\r
31208\r
31209 // Strip path if this file references a bundled definition\r
31210 var idx = filename.lastIndexOf("google/protobuf/");\r
31211 if (idx > -1) {\r
31212 var altname = filename.substring(idx);\r
31213 if (altname in common)\r
31214 filename = altname;\r
31215 }\r
31216\r
31217 // Skip if already loaded / attempted\r
31218 if (self.files.indexOf(filename) > -1)\r
31219 return;\r
31220 self.files.push(filename);\r
31221\r
31222 // Shortcut bundled definitions\r
31223 if (filename in common) {\r
31224 if (sync)\r
31225 process(filename, common[filename]);\r
31226 else {\r
31227 ++queued;\r
31228 setTimeout(function() {\r
31229 --queued;\r
31230 process(filename, common[filename]);\r
31231 });\r
31232 }\r
31233 return;\r
31234 }\r
31235\r
31236 // Otherwise fetch from disk or network\r
31237 if (sync) {\r
31238 var source;\r
31239 try {\r
31240 source = util.fs.readFileSync(filename).toString("utf8");\r
31241 } catch (err) {\r
31242 if (!weak)\r
31243 finish(err);\r
31244 return;\r
31245 }\r
31246 process(filename, source);\r
31247 } else {\r
31248 ++queued;\r
31249 util.fetch(filename, function(err, source) {\r
31250 --queued;\r
31251 /* istanbul ignore if */\r
31252 if (!callback)\r
31253 return; // terminated meanwhile\r
31254 if (err) {\r
31255 /* istanbul ignore else */\r
31256 if (!weak)\r
31257 finish(err);\r
31258 else if (!queued) // can't be covered reliably\r
31259 finish(null, self);\r
31260 return;\r
31261 }\r
31262 process(filename, source);\r
31263 });\r
31264 }\r
31265 }\r
31266 var queued = 0;\r
31267\r
31268 // Assembling the root namespace doesn't require working type\r
31269 // references anymore, so we can load everything in parallel\r
31270 if (util.isString(filename))\r
31271 filename = [ filename ];\r
31272 for (var i = 0, resolved; i < filename.length; ++i)\r
31273 if (resolved = self.resolvePath("", filename[i]))\r
31274 fetch(resolved);\r
31275\r
31276 if (sync)\r
31277 return self;\r
31278 if (!queued)\r
31279 finish(null, self);\r
31280 return undefined;\r
31281};\r
31282// function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined\r
31283\r
31284/**\r
31285 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.\r
31286 * @function Root#load\r
31287 * @param {string|string[]} filename Names of one or multiple files to load\r
31288 * @param {LoadCallback} callback Callback function\r
31289 * @returns {undefined}\r
31290 * @variation 2\r
31291 */\r
31292// function load(filename:string, callback:LoadCallback):undefined\r
31293\r
31294/**\r
31295 * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.\r
31296 * @function Root#load\r
31297 * @param {string|string[]} filename Names of one or multiple files to load\r
31298 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\r
31299 * @returns {Promise<Root>} Promise\r
31300 * @variation 3\r
31301 */\r
31302// function load(filename:string, [options:IParseOptions]):Promise<Root>\r
31303\r
31304/**\r
31305 * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).\r
31306 * @function Root#loadSync\r
31307 * @param {string|string[]} filename Names of one or multiple files to load\r
31308 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.\r
31309 * @returns {Root} Root namespace\r
31310 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid\r
31311 */\r
31312Root.prototype.loadSync = function loadSync(filename, options) {\r
31313 if (!util.isNode)\r
31314 throw Error("not supported");\r
31315 return this.load(filename, options, SYNC);\r
31316};\r
31317\r
31318/**\r
31319 * @override\r
31320 */\r
31321Root.prototype.resolveAll = function resolveAll() {\r
31322 if (this.deferred.length)\r
31323 throw Error("unresolvable extensions: " + this.deferred.map(function(field) {\r
31324 return "'extend " + field.extend + "' in " + field.parent.fullName;\r
31325 }).join(", "));\r
31326 return Namespace.prototype.resolveAll.call(this);\r
31327};\r
31328\r
31329// only uppercased (and thus conflict-free) children are exposed, see below\r
31330var exposeRe = /^[A-Z]/;\r
31331\r
31332/**\r
31333 * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.\r
31334 * @param {Root} root Root instance\r
31335 * @param {Field} field Declaring extension field witin the declaring type\r
31336 * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise\r
31337 * @inner\r
31338 * @ignore\r
31339 */\r
31340function tryHandleExtension(root, field) {\r
31341 var extendedType = field.parent.lookup(field.extend);\r
31342 if (extendedType) {\r
31343 var sisterField = new Field(field.fullName, field.id, field.type, field.rule, undefined, field.options);\r
31344 sisterField.declaringField = field;\r
31345 field.extensionField = sisterField;\r
31346 extendedType.add(sisterField);\r
31347 return true;\r
31348 }\r
31349 return false;\r
31350}\r
31351\r
31352/**\r
31353 * Called when any object is added to this root or its sub-namespaces.\r
31354 * @param {ReflectionObject} object Object added\r
31355 * @returns {undefined}\r
31356 * @private\r
31357 */\r
31358Root.prototype._handleAdd = function _handleAdd(object) {\r
31359 if (object instanceof Field) {\r
31360\r
31361 if (/* an extension field (implies not part of a oneof) */ object.extend !== undefined && /* not already handled */ !object.extensionField)\r
31362 if (!tryHandleExtension(this, object))\r
31363 this.deferred.push(object);\r
31364\r
31365 } else if (object instanceof Enum) {\r
31366\r
31367 if (exposeRe.test(object.name))\r
31368 object.parent[object.name] = object.values; // expose enum values as property of its parent\r
31369\r
31370 } else if (!(object instanceof OneOf)) /* everything else is a namespace */ {\r
31371\r
31372 if (object instanceof Type) // Try to handle any deferred extensions\r
31373 for (var i = 0; i < this.deferred.length;)\r
31374 if (tryHandleExtension(this, this.deferred[i]))\r
31375 this.deferred.splice(i, 1);\r
31376 else\r
31377 ++i;\r
31378 for (var j = 0; j < /* initializes */ object.nestedArray.length; ++j) // recurse into the namespace\r
31379 this._handleAdd(object._nestedArray[j]);\r
31380 if (exposeRe.test(object.name))\r
31381 object.parent[object.name] = object; // expose namespace as property of its parent\r
31382 }\r
31383\r
31384 // The above also adds uppercased (and thus conflict-free) nested types, services and enums as\r
31385 // properties of namespaces just like static code does. This allows using a .d.ts generated for\r
31386 // a static module with reflection-based solutions where the condition is met.\r
31387};\r
31388\r
31389/**\r
31390 * Called when any object is removed from this root or its sub-namespaces.\r
31391 * @param {ReflectionObject} object Object removed\r
31392 * @returns {undefined}\r
31393 * @private\r
31394 */\r
31395Root.prototype._handleRemove = function _handleRemove(object) {\r
31396 if (object instanceof Field) {\r
31397\r
31398 if (/* an extension field */ object.extend !== undefined) {\r
31399 if (/* already handled */ object.extensionField) { // remove its sister field\r
31400 object.extensionField.parent.remove(object.extensionField);\r
31401 object.extensionField = null;\r
31402 } else { // cancel the extension\r
31403 var index = this.deferred.indexOf(object);\r
31404 /* istanbul ignore else */\r
31405 if (index > -1)\r
31406 this.deferred.splice(index, 1);\r
31407 }\r
31408 }\r
31409\r
31410 } else if (object instanceof Enum) {\r
31411\r
31412 if (exposeRe.test(object.name))\r
31413 delete object.parent[object.name]; // unexpose enum values\r
31414\r
31415 } else if (object instanceof Namespace) {\r
31416\r
31417 for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace\r
31418 this._handleRemove(object._nestedArray[i]);\r
31419\r
31420 if (exposeRe.test(object.name))\r
31421 delete object.parent[object.name]; // unexpose namespaces\r
31422\r
31423 }\r
31424};\r
31425\r
31426Root._configure = function(Type_, parse_, common_) {\r
31427 Type = Type_;\r
31428 parse = parse_;\r
31429 common = common_;\r
31430};\r
31431
31432},{"./enum":196,"./field":197,"./namespace":204,"./oneof":206,"./util":218}],211:[function(require,module,exports){
31433"use strict";\r
31434module.exports = {};\r
31435\r
31436/**\r
31437 * Named roots.\r
31438 * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).\r
31439 * Can also be used manually to make roots available accross modules.\r
31440 * @name roots\r
31441 * @type {Object.<string,Root>}\r
31442 * @example\r
31443 * // pbjs -r myroot -o compiled.js ...\r
31444 *\r
31445 * // in another module:\r
31446 * require("./compiled.js");\r
31447 *\r
31448 * // in any subsequent module:\r
31449 * var root = protobuf.roots["myroot"];\r
31450 */\r
31451
31452},{}],212:[function(require,module,exports){
31453"use strict";\r
31454\r
31455/**\r
31456 * Streaming RPC helpers.\r
31457 * @namespace\r
31458 */\r
31459var rpc = exports;\r
31460\r
31461/**\r
31462 * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.\r
31463 * @typedef RPCImpl\r
31464 * @type {function}\r
31465 * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called\r
31466 * @param {Uint8Array} requestData Request data\r
31467 * @param {RPCImplCallback} callback Callback function\r
31468 * @returns {undefined}\r
31469 * @example\r
31470 * function rpcImpl(method, requestData, callback) {\r
31471 * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code\r
31472 * throw Error("no such method");\r
31473 * asynchronouslyObtainAResponse(requestData, function(err, responseData) {\r
31474 * callback(err, responseData);\r
31475 * });\r
31476 * }\r
31477 */\r
31478\r
31479/**\r
31480 * Node-style callback as used by {@link RPCImpl}.\r
31481 * @typedef RPCImplCallback\r
31482 * @type {function}\r
31483 * @param {Error|null} error Error, if any, otherwise `null`\r
31484 * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error\r
31485 * @returns {undefined}\r
31486 */\r
31487\r
31488rpc.Service = require("./rpc/service");\r
31489
31490},{"./rpc/service":213}],213:[function(require,module,exports){
31491"use strict";\r
31492module.exports = Service;\r
31493\r
31494var util = require("../util/minimal");\r
31495\r
31496// Extends EventEmitter\r
31497(Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service;\r
31498\r
31499/**\r
31500 * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.\r
31501 *\r
31502 * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.\r
31503 * @typedef rpc.ServiceMethodCallback\r
31504 * @template TRes extends Message<TRes>\r
31505 * @type {function}\r
31506 * @param {Error|null} error Error, if any\r
31507 * @param {TRes} [response] Response message\r
31508 * @returns {undefined}\r
31509 */\r
31510\r
31511/**\r
31512 * A service method part of a {@link rpc.Service} as created by {@link Service.create}.\r
31513 * @typedef rpc.ServiceMethod\r
31514 * @template TReq extends Message<TReq>\r
31515 * @template TRes extends Message<TRes>\r
31516 * @type {function}\r
31517 * @param {TReq|Properties<TReq>} request Request message or plain object\r
31518 * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message\r
31519 * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`\r
31520 */\r
31521\r
31522/**\r
31523 * Constructs a new RPC service instance.\r
31524 * @classdesc An RPC service as returned by {@link Service#create}.\r
31525 * @exports rpc.Service\r
31526 * @extends util.EventEmitter\r
31527 * @constructor\r
31528 * @param {RPCImpl} rpcImpl RPC implementation\r
31529 * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\r
31530 * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\r
31531 */\r
31532function Service(rpcImpl, requestDelimited, responseDelimited) {\r
31533\r
31534 if (typeof rpcImpl !== "function")\r
31535 throw TypeError("rpcImpl must be a function");\r
31536\r
31537 util.EventEmitter.call(this);\r
31538\r
31539 /**\r
31540 * RPC implementation. Becomes `null` once the service is ended.\r
31541 * @type {RPCImpl|null}\r
31542 */\r
31543 this.rpcImpl = rpcImpl;\r
31544\r
31545 /**\r
31546 * Whether requests are length-delimited.\r
31547 * @type {boolean}\r
31548 */\r
31549 this.requestDelimited = Boolean(requestDelimited);\r
31550\r
31551 /**\r
31552 * Whether responses are length-delimited.\r
31553 * @type {boolean}\r
31554 */\r
31555 this.responseDelimited = Boolean(responseDelimited);\r
31556}\r
31557\r
31558/**\r
31559 * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.\r
31560 * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method\r
31561 * @param {Constructor<TReq>} requestCtor Request constructor\r
31562 * @param {Constructor<TRes>} responseCtor Response constructor\r
31563 * @param {TReq|Properties<TReq>} request Request message or plain object\r
31564 * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback\r
31565 * @returns {undefined}\r
31566 * @template TReq extends Message<TReq>\r
31567 * @template TRes extends Message<TRes>\r
31568 */\r
31569Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) {\r
31570\r
31571 if (!request)\r
31572 throw TypeError("request must be specified");\r
31573\r
31574 var self = this;\r
31575 if (!callback)\r
31576 return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request);\r
31577\r
31578 if (!self.rpcImpl) {\r
31579 setTimeout(function() { callback(Error("already ended")); }, 0);\r
31580 return undefined;\r
31581 }\r
31582\r
31583 try {\r
31584 return self.rpcImpl(\r
31585 method,\r
31586 requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(),\r
31587 function rpcCallback(err, response) {\r
31588\r
31589 if (err) {\r
31590 self.emit("error", err, method);\r
31591 return callback(err);\r
31592 }\r
31593\r
31594 if (response === null) {\r
31595 self.end(/* endedByRPC */ true);\r
31596 return undefined;\r
31597 }\r
31598\r
31599 if (!(response instanceof responseCtor)) {\r
31600 try {\r
31601 response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response);\r
31602 } catch (err) {\r
31603 self.emit("error", err, method);\r
31604 return callback(err);\r
31605 }\r
31606 }\r
31607\r
31608 self.emit("data", response, method);\r
31609 return callback(null, response);\r
31610 }\r
31611 );\r
31612 } catch (err) {\r
31613 self.emit("error", err, method);\r
31614 setTimeout(function() { callback(err); }, 0);\r
31615 return undefined;\r
31616 }\r
31617};\r
31618\r
31619/**\r
31620 * Ends this service and emits the `end` event.\r
31621 * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.\r
31622 * @returns {rpc.Service} `this`\r
31623 */\r
31624Service.prototype.end = function end(endedByRPC) {\r
31625 if (this.rpcImpl) {\r
31626 if (!endedByRPC) // signal end to rpcImpl\r
31627 this.rpcImpl(null, null, null);\r
31628 this.rpcImpl = null;\r
31629 this.emit("end").off();\r
31630 }\r
31631 return this;\r
31632};\r
31633
31634},{"../util/minimal":220}],214:[function(require,module,exports){
31635"use strict";\r
31636module.exports = Service;\r
31637\r
31638// extends Namespace\r
31639var Namespace = require("./namespace");\r
31640((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service";\r
31641\r
31642var Method = require("./method"),\r
31643 util = require("./util"),\r
31644 rpc = require("./rpc");\r
31645\r
31646/**\r
31647 * Constructs a new service instance.\r
31648 * @classdesc Reflected service.\r
31649 * @extends NamespaceBase\r
31650 * @constructor\r
31651 * @param {string} name Service name\r
31652 * @param {Object.<string,*>} [options] Service options\r
31653 * @throws {TypeError} If arguments are invalid\r
31654 */\r
31655function Service(name, options) {\r
31656 Namespace.call(this, name, options);\r
31657\r
31658 /**\r
31659 * Service methods.\r
31660 * @type {Object.<string,Method>}\r
31661 */\r
31662 this.methods = {}; // toJSON, marker\r
31663\r
31664 /**\r
31665 * Cached methods as an array.\r
31666 * @type {Method[]|null}\r
31667 * @private\r
31668 */\r
31669 this._methodsArray = null;\r
31670}\r
31671\r
31672/**\r
31673 * Service descriptor.\r
31674 * @interface IService\r
31675 * @extends INamespace\r
31676 * @property {Object.<string,IMethod>} methods Method descriptors\r
31677 */\r
31678\r
31679/**\r
31680 * Constructs a service from a service descriptor.\r
31681 * @param {string} name Service name\r
31682 * @param {IService} json Service descriptor\r
31683 * @returns {Service} Created service\r
31684 * @throws {TypeError} If arguments are invalid\r
31685 */\r
31686Service.fromJSON = function fromJSON(name, json) {\r
31687 var service = new Service(name, json.options);\r
31688 /* istanbul ignore else */\r
31689 if (json.methods)\r
31690 for (var names = Object.keys(json.methods), i = 0; i < names.length; ++i)\r
31691 service.add(Method.fromJSON(names[i], json.methods[names[i]]));\r
31692 if (json.nested)\r
31693 service.addJSON(json.nested);\r
31694 service.comment = json.comment;\r
31695 return service;\r
31696};\r
31697\r
31698/**\r
31699 * Converts this service to a service descriptor.\r
31700 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r
31701 * @returns {IService} Service descriptor\r
31702 */\r
31703Service.prototype.toJSON = function toJSON(toJSONOptions) {\r
31704 var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\r
31705 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r
31706 return util.toObject([\r
31707 "options" , inherited && inherited.options || undefined,\r
31708 "methods" , Namespace.arrayToJSON(this.methodsArray, toJSONOptions) || /* istanbul ignore next */ {},\r
31709 "nested" , inherited && inherited.nested || undefined,\r
31710 "comment" , keepComments ? this.comment : undefined\r
31711 ]);\r
31712};\r
31713\r
31714/**\r
31715 * Methods of this service as an array for iteration.\r
31716 * @name Service#methodsArray\r
31717 * @type {Method[]}\r
31718 * @readonly\r
31719 */\r
31720Object.defineProperty(Service.prototype, "methodsArray", {\r
31721 get: function() {\r
31722 return this._methodsArray || (this._methodsArray = util.toArray(this.methods));\r
31723 }\r
31724});\r
31725\r
31726function clearCache(service) {\r
31727 service._methodsArray = null;\r
31728 return service;\r
31729}\r
31730\r
31731/**\r
31732 * @override\r
31733 */\r
31734Service.prototype.get = function get(name) {\r
31735 return this.methods[name]\r
31736 || Namespace.prototype.get.call(this, name);\r
31737};\r
31738\r
31739/**\r
31740 * @override\r
31741 */\r
31742Service.prototype.resolveAll = function resolveAll() {\r
31743 var methods = this.methodsArray;\r
31744 for (var i = 0; i < methods.length; ++i)\r
31745 methods[i].resolve();\r
31746 return Namespace.prototype.resolve.call(this);\r
31747};\r
31748\r
31749/**\r
31750 * @override\r
31751 */\r
31752Service.prototype.add = function add(object) {\r
31753\r
31754 /* istanbul ignore if */\r
31755 if (this.get(object.name))\r
31756 throw Error("duplicate name '" + object.name + "' in " + this);\r
31757\r
31758 if (object instanceof Method) {\r
31759 this.methods[object.name] = object;\r
31760 object.parent = this;\r
31761 return clearCache(this);\r
31762 }\r
31763 return Namespace.prototype.add.call(this, object);\r
31764};\r
31765\r
31766/**\r
31767 * @override\r
31768 */\r
31769Service.prototype.remove = function remove(object) {\r
31770 if (object instanceof Method) {\r
31771\r
31772 /* istanbul ignore if */\r
31773 if (this.methods[object.name] !== object)\r
31774 throw Error(object + " is not a member of " + this);\r
31775\r
31776 delete this.methods[object.name];\r
31777 object.parent = null;\r
31778 return clearCache(this);\r
31779 }\r
31780 return Namespace.prototype.remove.call(this, object);\r
31781};\r
31782\r
31783/**\r
31784 * Creates a runtime service using the specified rpc implementation.\r
31785 * @param {RPCImpl} rpcImpl RPC implementation\r
31786 * @param {boolean} [requestDelimited=false] Whether requests are length-delimited\r
31787 * @param {boolean} [responseDelimited=false] Whether responses are length-delimited\r
31788 * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.\r
31789 */\r
31790Service.prototype.create = function create(rpcImpl, requestDelimited, responseDelimited) {\r
31791 var rpcService = new rpc.Service(rpcImpl, requestDelimited, responseDelimited);\r
31792 for (var i = 0, method; i < /* initializes */ this.methodsArray.length; ++i) {\r
31793 var methodName = util.lcFirst((method = this._methodsArray[i]).resolve().name).replace(/[^$\w_]/g, "");\r
31794 rpcService[methodName] = util.codegen(["r","c"], util.isReserved(methodName) ? methodName + "_" : methodName)("return this.rpcCall(m,q,s,r,c)")({\r
31795 m: method,\r
31796 q: method.resolvedRequestType.ctor,\r
31797 s: method.resolvedResponseType.ctor\r
31798 });\r
31799 }\r
31800 return rpcService;\r
31801};\r
31802
31803},{"./method":203,"./namespace":204,"./rpc":212,"./util":218}],215:[function(require,module,exports){
31804"use strict";\r
31805module.exports = tokenize;\r
31806\r
31807var delimRe = /[\s{}=;:[\],'"()<>]/g,\r
31808 stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,\r
31809 stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;\r
31810\r
31811var setCommentRe = /^ *[*/]+ */,\r
31812 setCommentAltRe = /^\s*\*?\/*/,\r
31813 setCommentSplitRe = /\n/g,\r
31814 whitespaceRe = /\s/,\r
31815 unescapeRe = /\\(.?)/g;\r
31816\r
31817var unescapeMap = {\r
31818 "0": "\0",\r
31819 "r": "\r",\r
31820 "n": "\n",\r
31821 "t": "\t"\r
31822};\r
31823\r
31824/**\r
31825 * Unescapes a string.\r
31826 * @param {string} str String to unescape\r
31827 * @returns {string} Unescaped string\r
31828 * @property {Object.<string,string>} map Special characters map\r
31829 * @memberof tokenize\r
31830 */\r
31831function unescape(str) {\r
31832 return str.replace(unescapeRe, function($0, $1) {\r
31833 switch ($1) {\r
31834 case "\\":\r
31835 case "":\r
31836 return $1;\r
31837 default:\r
31838 return unescapeMap[$1] || "";\r
31839 }\r
31840 });\r
31841}\r
31842\r
31843tokenize.unescape = unescape;\r
31844\r
31845/**\r
31846 * Gets the next token and advances.\r
31847 * @typedef TokenizerHandleNext\r
31848 * @type {function}\r
31849 * @returns {string|null} Next token or `null` on eof\r
31850 */\r
31851\r
31852/**\r
31853 * Peeks for the next token.\r
31854 * @typedef TokenizerHandlePeek\r
31855 * @type {function}\r
31856 * @returns {string|null} Next token or `null` on eof\r
31857 */\r
31858\r
31859/**\r
31860 * Pushes a token back to the stack.\r
31861 * @typedef TokenizerHandlePush\r
31862 * @type {function}\r
31863 * @param {string} token Token\r
31864 * @returns {undefined}\r
31865 */\r
31866\r
31867/**\r
31868 * Skips the next token.\r
31869 * @typedef TokenizerHandleSkip\r
31870 * @type {function}\r
31871 * @param {string} expected Expected token\r
31872 * @param {boolean} [optional=false] If optional\r
31873 * @returns {boolean} Whether the token matched\r
31874 * @throws {Error} If the token didn't match and is not optional\r
31875 */\r
31876\r
31877/**\r
31878 * Gets the comment on the previous line or, alternatively, the line comment on the specified line.\r
31879 * @typedef TokenizerHandleCmnt\r
31880 * @type {function}\r
31881 * @param {number} [line] Line number\r
31882 * @returns {string|null} Comment text or `null` if none\r
31883 */\r
31884\r
31885/**\r
31886 * Handle object returned from {@link tokenize}.\r
31887 * @interface ITokenizerHandle\r
31888 * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)\r
31889 * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)\r
31890 * @property {TokenizerHandlePush} push Pushes a token back to the stack\r
31891 * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws\r
31892 * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any\r
31893 * @property {number} line Current line number\r
31894 */\r
31895\r
31896/**\r
31897 * Tokenizes the given .proto source and returns an object with useful utility functions.\r
31898 * @param {string} source Source contents\r
31899 * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.\r
31900 * @returns {ITokenizerHandle} Tokenizer handle\r
31901 */\r
31902function tokenize(source, alternateCommentMode) {\r
31903 /* eslint-disable callback-return */\r
31904 source = source.toString();\r
31905\r
31906 var offset = 0,\r
31907 length = source.length,\r
31908 line = 1,\r
31909 commentType = null,\r
31910 commentText = null,\r
31911 commentLine = 0,\r
31912 commentLineEmpty = false;\r
31913\r
31914 var stack = [];\r
31915\r
31916 var stringDelim = null;\r
31917\r
31918 /* istanbul ignore next */\r
31919 /**\r
31920 * Creates an error for illegal syntax.\r
31921 * @param {string} subject Subject\r
31922 * @returns {Error} Error created\r
31923 * @inner\r
31924 */\r
31925 function illegal(subject) {\r
31926 return Error("illegal " + subject + " (line " + line + ")");\r
31927 }\r
31928\r
31929 /**\r
31930 * Reads a string till its end.\r
31931 * @returns {string} String read\r
31932 * @inner\r
31933 */\r
31934 function readString() {\r
31935 var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe;\r
31936 re.lastIndex = offset - 1;\r
31937 var match = re.exec(source);\r
31938 if (!match)\r
31939 throw illegal("string");\r
31940 offset = re.lastIndex;\r
31941 push(stringDelim);\r
31942 stringDelim = null;\r
31943 return unescape(match[1]);\r
31944 }\r
31945\r
31946 /**\r
31947 * Gets the character at `pos` within the source.\r
31948 * @param {number} pos Position\r
31949 * @returns {string} Character\r
31950 * @inner\r
31951 */\r
31952 function charAt(pos) {\r
31953 return source.charAt(pos);\r
31954 }\r
31955\r
31956 /**\r
31957 * Sets the current comment text.\r
31958 * @param {number} start Start offset\r
31959 * @param {number} end End offset\r
31960 * @returns {undefined}\r
31961 * @inner\r
31962 */\r
31963 function setComment(start, end) {\r
31964 commentType = source.charAt(start++);\r
31965 commentLine = line;\r
31966 commentLineEmpty = false;\r
31967 var lookback;\r
31968 if (alternateCommentMode) {\r
31969 lookback = 2; // alternate comment parsing: "//" or "/*"\r
31970 } else {\r
31971 lookback = 3; // "///" or "/**"\r
31972 }\r
31973 var commentOffset = start - lookback,\r
31974 c;\r
31975 do {\r
31976 if (--commentOffset < 0 ||\r
31977 (c = source.charAt(commentOffset)) === "\n") {\r
31978 commentLineEmpty = true;\r
31979 break;\r
31980 }\r
31981 } while (c === " " || c === "\t");\r
31982 var lines = source\r
31983 .substring(start, end)\r
31984 .split(setCommentSplitRe);\r
31985 for (var i = 0; i < lines.length; ++i)\r
31986 lines[i] = lines[i]\r
31987 .replace(alternateCommentMode ? setCommentAltRe : setCommentRe, "")\r
31988 .trim();\r
31989 commentText = lines\r
31990 .join("\n")\r
31991 .trim();\r
31992 }\r
31993\r
31994 function isDoubleSlashCommentLine(startOffset) {\r
31995 var endOffset = findEndOfLine(startOffset);\r
31996\r
31997 // see if remaining line matches comment pattern\r
31998 var lineText = source.substring(startOffset, endOffset);\r
31999 // look for 1 or 2 slashes since startOffset would already point past\r
32000 // the first slash that started the comment.\r
32001 var isComment = /^\s*\/{1,2}/.test(lineText);\r
32002 return isComment;\r
32003 }\r
32004\r
32005 function findEndOfLine(cursor) {\r
32006 // find end of cursor's line\r
32007 var endOffset = cursor;\r
32008 while (endOffset < length && charAt(endOffset) !== "\n") {\r
32009 endOffset++;\r
32010 }\r
32011 return endOffset;\r
32012 }\r
32013\r
32014 /**\r
32015 * Obtains the next token.\r
32016 * @returns {string|null} Next token or `null` on eof\r
32017 * @inner\r
32018 */\r
32019 function next() {\r
32020 if (stack.length > 0)\r
32021 return stack.shift();\r
32022 if (stringDelim)\r
32023 return readString();\r
32024 var repeat,\r
32025 prev,\r
32026 curr,\r
32027 start,\r
32028 isDoc;\r
32029 do {\r
32030 if (offset === length)\r
32031 return null;\r
32032 repeat = false;\r
32033 while (whitespaceRe.test(curr = charAt(offset))) {\r
32034 if (curr === "\n")\r
32035 ++line;\r
32036 if (++offset === length)\r
32037 return null;\r
32038 }\r
32039\r
32040 if (charAt(offset) === "/") {\r
32041 if (++offset === length) {\r
32042 throw illegal("comment");\r
32043 }\r
32044 if (charAt(offset) === "/") { // Line\r
32045 if (!alternateCommentMode) {\r
32046 // check for triple-slash comment\r
32047 isDoc = charAt(start = offset + 1) === "/";\r
32048\r
32049 while (charAt(++offset) !== "\n") {\r
32050 if (offset === length) {\r
32051 return null;\r
32052 }\r
32053 }\r
32054 ++offset;\r
32055 if (isDoc) {\r
32056 setComment(start, offset - 1);\r
32057 }\r
32058 ++line;\r
32059 repeat = true;\r
32060 } else {\r
32061 // check for double-slash comments, consolidating consecutive lines\r
32062 start = offset;\r
32063 isDoc = false;\r
32064 if (isDoubleSlashCommentLine(offset)) {\r
32065 isDoc = true;\r
32066 do {\r
32067 offset = findEndOfLine(offset);\r
32068 if (offset === length) {\r
32069 break;\r
32070 }\r
32071 offset++;\r
32072 } while (isDoubleSlashCommentLine(offset));\r
32073 } else {\r
32074 offset = Math.min(length, findEndOfLine(offset) + 1);\r
32075 }\r
32076 if (isDoc) {\r
32077 setComment(start, offset);\r
32078 }\r
32079 line++;\r
32080 repeat = true;\r
32081 }\r
32082 } else if ((curr = charAt(offset)) === "*") { /* Block */\r
32083 // check for /** (regular comment mode) or /* (alternate comment mode)\r
32084 start = offset + 1;\r
32085 isDoc = alternateCommentMode || charAt(start) === "*";\r
32086 do {\r
32087 if (curr === "\n") {\r
32088 ++line;\r
32089 }\r
32090 if (++offset === length) {\r
32091 throw illegal("comment");\r
32092 }\r
32093 prev = curr;\r
32094 curr = charAt(offset);\r
32095 } while (prev !== "*" || curr !== "/");\r
32096 ++offset;\r
32097 if (isDoc) {\r
32098 setComment(start, offset - 2);\r
32099 }\r
32100 repeat = true;\r
32101 } else {\r
32102 return "/";\r
32103 }\r
32104 }\r
32105 } while (repeat);\r
32106\r
32107 // offset !== length if we got here\r
32108\r
32109 var end = offset;\r
32110 delimRe.lastIndex = 0;\r
32111 var delim = delimRe.test(charAt(end++));\r
32112 if (!delim)\r
32113 while (end < length && !delimRe.test(charAt(end)))\r
32114 ++end;\r
32115 var token = source.substring(offset, offset = end);\r
32116 if (token === "\"" || token === "'")\r
32117 stringDelim = token;\r
32118 return token;\r
32119 }\r
32120\r
32121 /**\r
32122 * Pushes a token back to the stack.\r
32123 * @param {string} token Token\r
32124 * @returns {undefined}\r
32125 * @inner\r
32126 */\r
32127 function push(token) {\r
32128 stack.push(token);\r
32129 }\r
32130\r
32131 /**\r
32132 * Peeks for the next token.\r
32133 * @returns {string|null} Token or `null` on eof\r
32134 * @inner\r
32135 */\r
32136 function peek() {\r
32137 if (!stack.length) {\r
32138 var token = next();\r
32139 if (token === null)\r
32140 return null;\r
32141 push(token);\r
32142 }\r
32143 return stack[0];\r
32144 }\r
32145\r
32146 /**\r
32147 * Skips a token.\r
32148 * @param {string} expected Expected token\r
32149 * @param {boolean} [optional=false] Whether the token is optional\r
32150 * @returns {boolean} `true` when skipped, `false` if not\r
32151 * @throws {Error} When a required token is not present\r
32152 * @inner\r
32153 */\r
32154 function skip(expected, optional) {\r
32155 var actual = peek(),\r
32156 equals = actual === expected;\r
32157 if (equals) {\r
32158 next();\r
32159 return true;\r
32160 }\r
32161 if (!optional)\r
32162 throw illegal("token '" + actual + "', '" + expected + "' expected");\r
32163 return false;\r
32164 }\r
32165\r
32166 /**\r
32167 * Gets a comment.\r
32168 * @param {number} [trailingLine] Line number if looking for a trailing comment\r
32169 * @returns {string|null} Comment text\r
32170 * @inner\r
32171 */\r
32172 function cmnt(trailingLine) {\r
32173 var ret = null;\r
32174 if (trailingLine === undefined) {\r
32175 if (commentLine === line - 1 && (alternateCommentMode || commentType === "*" || commentLineEmpty)) {\r
32176 ret = commentText;\r
32177 }\r
32178 } else {\r
32179 /* istanbul ignore else */\r
32180 if (commentLine < trailingLine) {\r
32181 peek();\r
32182 }\r
32183 if (commentLine === trailingLine && !commentLineEmpty && (alternateCommentMode || commentType === "/")) {\r
32184 ret = commentText;\r
32185 }\r
32186 }\r
32187 return ret;\r
32188 }\r
32189\r
32190 return Object.defineProperty({\r
32191 next: next,\r
32192 peek: peek,\r
32193 push: push,\r
32194 skip: skip,\r
32195 cmnt: cmnt\r
32196 }, "line", {\r
32197 get: function() { return line; }\r
32198 });\r
32199 /* eslint-enable callback-return */\r
32200}\r
32201
32202},{}],216:[function(require,module,exports){
32203"use strict";\r
32204module.exports = Type;\r
32205\r
32206// extends Namespace\r
32207var Namespace = require("./namespace");\r
32208((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type";\r
32209\r
32210var Enum = require("./enum"),\r
32211 OneOf = require("./oneof"),\r
32212 Field = require("./field"),\r
32213 MapField = require("./mapfield"),\r
32214 Service = require("./service"),\r
32215 Message = require("./message"),\r
32216 Reader = require("./reader"),\r
32217 Writer = require("./writer"),\r
32218 util = require("./util"),\r
32219 encoder = require("./encoder"),\r
32220 decoder = require("./decoder"),\r
32221 verifier = require("./verifier"),\r
32222 converter = require("./converter"),\r
32223 wrappers = require("./wrappers");\r
32224\r
32225/**\r
32226 * Constructs a new reflected message type instance.\r
32227 * @classdesc Reflected message type.\r
32228 * @extends NamespaceBase\r
32229 * @constructor\r
32230 * @param {string} name Message name\r
32231 * @param {Object.<string,*>} [options] Declared options\r
32232 */\r
32233function Type(name, options) {\r
32234 Namespace.call(this, name, options);\r
32235\r
32236 /**\r
32237 * Message fields.\r
32238 * @type {Object.<string,Field>}\r
32239 */\r
32240 this.fields = {}; // toJSON, marker\r
32241\r
32242 /**\r
32243 * Oneofs declared within this namespace, if any.\r
32244 * @type {Object.<string,OneOf>}\r
32245 */\r
32246 this.oneofs = undefined; // toJSON\r
32247\r
32248 /**\r
32249 * Extension ranges, if any.\r
32250 * @type {number[][]}\r
32251 */\r
32252 this.extensions = undefined; // toJSON\r
32253\r
32254 /**\r
32255 * Reserved ranges, if any.\r
32256 * @type {Array.<number[]|string>}\r
32257 */\r
32258 this.reserved = undefined; // toJSON\r
32259\r
32260 /*?\r
32261 * Whether this type is a legacy group.\r
32262 * @type {boolean|undefined}\r
32263 */\r
32264 this.group = undefined; // toJSON\r
32265\r
32266 /**\r
32267 * Cached fields by id.\r
32268 * @type {Object.<number,Field>|null}\r
32269 * @private\r
32270 */\r
32271 this._fieldsById = null;\r
32272\r
32273 /**\r
32274 * Cached fields as an array.\r
32275 * @type {Field[]|null}\r
32276 * @private\r
32277 */\r
32278 this._fieldsArray = null;\r
32279\r
32280 /**\r
32281 * Cached oneofs as an array.\r
32282 * @type {OneOf[]|null}\r
32283 * @private\r
32284 */\r
32285 this._oneofsArray = null;\r
32286\r
32287 /**\r
32288 * Cached constructor.\r
32289 * @type {Constructor<{}>}\r
32290 * @private\r
32291 */\r
32292 this._ctor = null;\r
32293}\r
32294\r
32295Object.defineProperties(Type.prototype, {\r
32296\r
32297 /**\r
32298 * Message fields by id.\r
32299 * @name Type#fieldsById\r
32300 * @type {Object.<number,Field>}\r
32301 * @readonly\r
32302 */\r
32303 fieldsById: {\r
32304 get: function() {\r
32305\r
32306 /* istanbul ignore if */\r
32307 if (this._fieldsById)\r
32308 return this._fieldsById;\r
32309\r
32310 this._fieldsById = {};\r
32311 for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) {\r
32312 var field = this.fields[names[i]],\r
32313 id = field.id;\r
32314\r
32315 /* istanbul ignore if */\r
32316 if (this._fieldsById[id])\r
32317 throw Error("duplicate id " + id + " in " + this);\r
32318\r
32319 this._fieldsById[id] = field;\r
32320 }\r
32321 return this._fieldsById;\r
32322 }\r
32323 },\r
32324\r
32325 /**\r
32326 * Fields of this message as an array for iteration.\r
32327 * @name Type#fieldsArray\r
32328 * @type {Field[]}\r
32329 * @readonly\r
32330 */\r
32331 fieldsArray: {\r
32332 get: function() {\r
32333 return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields));\r
32334 }\r
32335 },\r
32336\r
32337 /**\r
32338 * Oneofs of this message as an array for iteration.\r
32339 * @name Type#oneofsArray\r
32340 * @type {OneOf[]}\r
32341 * @readonly\r
32342 */\r
32343 oneofsArray: {\r
32344 get: function() {\r
32345 return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs));\r
32346 }\r
32347 },\r
32348\r
32349 /**\r
32350 * The registered constructor, if any registered, otherwise a generic constructor.\r
32351 * Assigning a function replaces the internal constructor. If the function does not extend {@link Message} yet, its prototype will be setup accordingly and static methods will be populated. If it already extends {@link Message}, it will just replace the internal constructor.\r
32352 * @name Type#ctor\r
32353 * @type {Constructor<{}>}\r
32354 */\r
32355 ctor: {\r
32356 get: function() {\r
32357 return this._ctor || (this.ctor = Type.generateConstructor(this)());\r
32358 },\r
32359 set: function(ctor) {\r
32360\r
32361 // Ensure proper prototype\r
32362 var prototype = ctor.prototype;\r
32363 if (!(prototype instanceof Message)) {\r
32364 (ctor.prototype = new Message()).constructor = ctor;\r
32365 util.merge(ctor.prototype, prototype);\r
32366 }\r
32367\r
32368 // Classes and messages reference their reflected type\r
32369 ctor.$type = ctor.prototype.$type = this;\r
32370\r
32371 // Mix in static methods\r
32372 util.merge(ctor, Message, true);\r
32373\r
32374 this._ctor = ctor;\r
32375\r
32376 // Messages have non-enumerable default values on their prototype\r
32377 var i = 0;\r
32378 for (; i < /* initializes */ this.fieldsArray.length; ++i)\r
32379 this._fieldsArray[i].resolve(); // ensures a proper value\r
32380\r
32381 // Messages have non-enumerable getters and setters for each virtual oneof field\r
32382 var ctorProperties = {};\r
32383 for (i = 0; i < /* initializes */ this.oneofsArray.length; ++i)\r
32384 ctorProperties[this._oneofsArray[i].resolve().name] = {\r
32385 get: util.oneOfGetter(this._oneofsArray[i].oneof),\r
32386 set: util.oneOfSetter(this._oneofsArray[i].oneof)\r
32387 };\r
32388 if (i)\r
32389 Object.defineProperties(ctor.prototype, ctorProperties);\r
32390 }\r
32391 }\r
32392});\r
32393\r
32394/**\r
32395 * Generates a constructor function for the specified type.\r
32396 * @param {Type} mtype Message type\r
32397 * @returns {Codegen} Codegen instance\r
32398 */\r
32399Type.generateConstructor = function generateConstructor(mtype) {\r
32400 /* eslint-disable no-unexpected-multiline */\r
32401 var gen = util.codegen(["p"], mtype.name);\r
32402 // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype\r
32403 for (var i = 0, field; i < mtype.fieldsArray.length; ++i)\r
32404 if ((field = mtype._fieldsArray[i]).map) gen\r
32405 ("this%s={}", util.safeProp(field.name));\r
32406 else if (field.repeated) gen\r
32407 ("this%s=[]", util.safeProp(field.name));\r
32408 return gen\r
32409 ("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)") // omit undefined or null\r
32410 ("this[ks[i]]=p[ks[i]]");\r
32411 /* eslint-enable no-unexpected-multiline */\r
32412};\r
32413\r
32414function clearCache(type) {\r
32415 type._fieldsById = type._fieldsArray = type._oneofsArray = null;\r
32416 delete type.encode;\r
32417 delete type.decode;\r
32418 delete type.verify;\r
32419 return type;\r
32420}\r
32421\r
32422/**\r
32423 * Message type descriptor.\r
32424 * @interface IType\r
32425 * @extends INamespace\r
32426 * @property {Object.<string,IOneOf>} [oneofs] Oneof descriptors\r
32427 * @property {Object.<string,IField>} fields Field descriptors\r
32428 * @property {number[][]} [extensions] Extension ranges\r
32429 * @property {number[][]} [reserved] Reserved ranges\r
32430 * @property {boolean} [group=false] Whether a legacy group or not\r
32431 */\r
32432\r
32433/**\r
32434 * Creates a message type from a message type descriptor.\r
32435 * @param {string} name Message name\r
32436 * @param {IType} json Message type descriptor\r
32437 * @returns {Type} Created message type\r
32438 */\r
32439Type.fromJSON = function fromJSON(name, json) {\r
32440 var type = new Type(name, json.options);\r
32441 type.extensions = json.extensions;\r
32442 type.reserved = json.reserved;\r
32443 var names = Object.keys(json.fields),\r
32444 i = 0;\r
32445 for (; i < names.length; ++i)\r
32446 type.add(\r
32447 ( typeof json.fields[names[i]].keyType !== "undefined"\r
32448 ? MapField.fromJSON\r
32449 : Field.fromJSON )(names[i], json.fields[names[i]])\r
32450 );\r
32451 if (json.oneofs)\r
32452 for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i)\r
32453 type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]]));\r
32454 if (json.nested)\r
32455 for (names = Object.keys(json.nested), i = 0; i < names.length; ++i) {\r
32456 var nested = json.nested[names[i]];\r
32457 type.add( // most to least likely\r
32458 ( nested.id !== undefined\r
32459 ? Field.fromJSON\r
32460 : nested.fields !== undefined\r
32461 ? Type.fromJSON\r
32462 : nested.values !== undefined\r
32463 ? Enum.fromJSON\r
32464 : nested.methods !== undefined\r
32465 ? Service.fromJSON\r
32466 : Namespace.fromJSON )(names[i], nested)\r
32467 );\r
32468 }\r
32469 if (json.extensions && json.extensions.length)\r
32470 type.extensions = json.extensions;\r
32471 if (json.reserved && json.reserved.length)\r
32472 type.reserved = json.reserved;\r
32473 if (json.group)\r
32474 type.group = true;\r
32475 if (json.comment)\r
32476 type.comment = json.comment;\r
32477 return type;\r
32478};\r
32479\r
32480/**\r
32481 * Converts this message type to a message type descriptor.\r
32482 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options\r
32483 * @returns {IType} Message type descriptor\r
32484 */\r
32485Type.prototype.toJSON = function toJSON(toJSONOptions) {\r
32486 var inherited = Namespace.prototype.toJSON.call(this, toJSONOptions);\r
32487 var keepComments = toJSONOptions ? Boolean(toJSONOptions.keepComments) : false;\r
32488 return util.toObject([\r
32489 "options" , inherited && inherited.options || undefined,\r
32490 "oneofs" , Namespace.arrayToJSON(this.oneofsArray, toJSONOptions),\r
32491 "fields" , Namespace.arrayToJSON(this.fieldsArray.filter(function(obj) { return !obj.declaringField; }), toJSONOptions) || {},\r
32492 "extensions" , this.extensions && this.extensions.length ? this.extensions : undefined,\r
32493 "reserved" , this.reserved && this.reserved.length ? this.reserved : undefined,\r
32494 "group" , this.group || undefined,\r
32495 "nested" , inherited && inherited.nested || undefined,\r
32496 "comment" , keepComments ? this.comment : undefined\r
32497 ]);\r
32498};\r
32499\r
32500/**\r
32501 * @override\r
32502 */\r
32503Type.prototype.resolveAll = function resolveAll() {\r
32504 var fields = this.fieldsArray, i = 0;\r
32505 while (i < fields.length)\r
32506 fields[i++].resolve();\r
32507 var oneofs = this.oneofsArray; i = 0;\r
32508 while (i < oneofs.length)\r
32509 oneofs[i++].resolve();\r
32510 return Namespace.prototype.resolveAll.call(this);\r
32511};\r
32512\r
32513/**\r
32514 * @override\r
32515 */\r
32516Type.prototype.get = function get(name) {\r
32517 return this.fields[name]\r
32518 || this.oneofs && this.oneofs[name]\r
32519 || this.nested && this.nested[name]\r
32520 || null;\r
32521};\r
32522\r
32523/**\r
32524 * Adds a nested object to this type.\r
32525 * @param {ReflectionObject} object Nested object to add\r
32526 * @returns {Type} `this`\r
32527 * @throws {TypeError} If arguments are invalid\r
32528 * @throws {Error} If there is already a nested object with this name or, if a field, when there is already a field with this id\r
32529 */\r
32530Type.prototype.add = function add(object) {\r
32531\r
32532 if (this.get(object.name))\r
32533 throw Error("duplicate name '" + object.name + "' in " + this);\r
32534\r
32535 if (object instanceof Field && object.extend === undefined) {\r
32536 // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.\r
32537 // The root object takes care of adding distinct sister-fields to the respective extended\r
32538 // type instead.\r
32539\r
32540 // avoids calling the getter if not absolutely necessary because it's called quite frequently\r
32541 if (this._fieldsById ? /* istanbul ignore next */ this._fieldsById[object.id] : this.fieldsById[object.id])\r
32542 throw Error("duplicate id " + object.id + " in " + this);\r
32543 if (this.isReservedId(object.id))\r
32544 throw Error("id " + object.id + " is reserved in " + this);\r
32545 if (this.isReservedName(object.name))\r
32546 throw Error("name '" + object.name + "' is reserved in " + this);\r
32547\r
32548 if (object.parent)\r
32549 object.parent.remove(object);\r
32550 this.fields[object.name] = object;\r
32551 object.message = this;\r
32552 object.onAdd(this);\r
32553 return clearCache(this);\r
32554 }\r
32555 if (object instanceof OneOf) {\r
32556 if (!this.oneofs)\r
32557 this.oneofs = {};\r
32558 this.oneofs[object.name] = object;\r
32559 object.onAdd(this);\r
32560 return clearCache(this);\r
32561 }\r
32562 return Namespace.prototype.add.call(this, object);\r
32563};\r
32564\r
32565/**\r
32566 * Removes a nested object from this type.\r
32567 * @param {ReflectionObject} object Nested object to remove\r
32568 * @returns {Type} `this`\r
32569 * @throws {TypeError} If arguments are invalid\r
32570 * @throws {Error} If `object` is not a member of this type\r
32571 */\r
32572Type.prototype.remove = function remove(object) {\r
32573 if (object instanceof Field && object.extend === undefined) {\r
32574 // See Type#add for the reason why extension fields are excluded here.\r
32575\r
32576 /* istanbul ignore if */\r
32577 if (!this.fields || this.fields[object.name] !== object)\r
32578 throw Error(object + " is not a member of " + this);\r
32579\r
32580 delete this.fields[object.name];\r
32581 object.parent = null;\r
32582 object.onRemove(this);\r
32583 return clearCache(this);\r
32584 }\r
32585 if (object instanceof OneOf) {\r
32586\r
32587 /* istanbul ignore if */\r
32588 if (!this.oneofs || this.oneofs[object.name] !== object)\r
32589 throw Error(object + " is not a member of " + this);\r
32590\r
32591 delete this.oneofs[object.name];\r
32592 object.parent = null;\r
32593 object.onRemove(this);\r
32594 return clearCache(this);\r
32595 }\r
32596 return Namespace.prototype.remove.call(this, object);\r
32597};\r
32598\r
32599/**\r
32600 * Tests if the specified id is reserved.\r
32601 * @param {number} id Id to test\r
32602 * @returns {boolean} `true` if reserved, otherwise `false`\r
32603 */\r
32604Type.prototype.isReservedId = function isReservedId(id) {\r
32605 return Namespace.isReservedId(this.reserved, id);\r
32606};\r
32607\r
32608/**\r
32609 * Tests if the specified name is reserved.\r
32610 * @param {string} name Name to test\r
32611 * @returns {boolean} `true` if reserved, otherwise `false`\r
32612 */\r
32613Type.prototype.isReservedName = function isReservedName(name) {\r
32614 return Namespace.isReservedName(this.reserved, name);\r
32615};\r
32616\r
32617/**\r
32618 * Creates a new message of this type using the specified properties.\r
32619 * @param {Object.<string,*>} [properties] Properties to set\r
32620 * @returns {Message<{}>} Message instance\r
32621 */\r
32622Type.prototype.create = function create(properties) {\r
32623 return new this.ctor(properties);\r
32624};\r
32625\r
32626/**\r
32627 * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.\r
32628 * @returns {Type} `this`\r
32629 */\r
32630Type.prototype.setup = function setup() {\r
32631 // Sets up everything at once so that the prototype chain does not have to be re-evaluated\r
32632 // multiple times (V8, soft-deopt prototype-check).\r
32633\r
32634 var fullName = this.fullName,\r
32635 types = [];\r
32636 for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i)\r
32637 types.push(this._fieldsArray[i].resolve().resolvedType);\r
32638\r
32639 // Replace setup methods with type-specific generated functions\r
32640 this.encode = encoder(this)({\r
32641 Writer : Writer,\r
32642 types : types,\r
32643 util : util\r
32644 });\r
32645 this.decode = decoder(this)({\r
32646 Reader : Reader,\r
32647 types : types,\r
32648 util : util\r
32649 });\r
32650 this.verify = verifier(this)({\r
32651 types : types,\r
32652 util : util\r
32653 });\r
32654 this.fromObject = converter.fromObject(this)({\r
32655 types : types,\r
32656 util : util\r
32657 });\r
32658 this.toObject = converter.toObject(this)({\r
32659 types : types,\r
32660 util : util\r
32661 });\r
32662\r
32663 // Inject custom wrappers for common types\r
32664 var wrapper = wrappers[fullName];\r
32665 if (wrapper) {\r
32666 var originalThis = Object.create(this);\r
32667 // if (wrapper.fromObject) {\r
32668 originalThis.fromObject = this.fromObject;\r
32669 this.fromObject = wrapper.fromObject.bind(originalThis);\r
32670 // }\r
32671 // if (wrapper.toObject) {\r
32672 originalThis.toObject = this.toObject;\r
32673 this.toObject = wrapper.toObject.bind(originalThis);\r
32674 // }\r
32675 }\r
32676\r
32677 return this;\r
32678};\r
32679\r
32680/**\r
32681 * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.\r
32682 * @param {Message<{}>|Object.<string,*>} message Message instance or plain object\r
32683 * @param {Writer} [writer] Writer to encode to\r
32684 * @returns {Writer} writer\r
32685 */\r
32686Type.prototype.encode = function encode_setup(message, writer) {\r
32687 return this.setup().encode(message, writer); // overrides this method\r
32688};\r
32689\r
32690/**\r
32691 * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.\r
32692 * @param {Message<{}>|Object.<string,*>} message Message instance or plain object\r
32693 * @param {Writer} [writer] Writer to encode to\r
32694 * @returns {Writer} writer\r
32695 */\r
32696Type.prototype.encodeDelimited = function encodeDelimited(message, writer) {\r
32697 return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim();\r
32698};\r
32699\r
32700/**\r
32701 * Decodes a message of this type.\r
32702 * @param {Reader|Uint8Array} reader Reader or buffer to decode from\r
32703 * @param {number} [length] Length of the message, if known beforehand\r
32704 * @returns {Message<{}>} Decoded message\r
32705 * @throws {Error} If the payload is not a reader or valid buffer\r
32706 * @throws {util.ProtocolError<{}>} If required fields are missing\r
32707 */\r
32708Type.prototype.decode = function decode_setup(reader, length) {\r
32709 return this.setup().decode(reader, length); // overrides this method\r
32710};\r
32711\r
32712/**\r
32713 * Decodes a message of this type preceeded by its byte length as a varint.\r
32714 * @param {Reader|Uint8Array} reader Reader or buffer to decode from\r
32715 * @returns {Message<{}>} Decoded message\r
32716 * @throws {Error} If the payload is not a reader or valid buffer\r
32717 * @throws {util.ProtocolError} If required fields are missing\r
32718 */\r
32719Type.prototype.decodeDelimited = function decodeDelimited(reader) {\r
32720 if (!(reader instanceof Reader))\r
32721 reader = Reader.create(reader);\r
32722 return this.decode(reader, reader.uint32());\r
32723};\r
32724\r
32725/**\r
32726 * Verifies that field values are valid and that required fields are present.\r
32727 * @param {Object.<string,*>} message Plain object to verify\r
32728 * @returns {null|string} `null` if valid, otherwise the reason why it is not\r
32729 */\r
32730Type.prototype.verify = function verify_setup(message) {\r
32731 return this.setup().verify(message); // overrides this method\r
32732};\r
32733\r
32734/**\r
32735 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.\r
32736 * @param {Object.<string,*>} object Plain object to convert\r
32737 * @returns {Message<{}>} Message instance\r
32738 */\r
32739Type.prototype.fromObject = function fromObject(object) {\r
32740 return this.setup().fromObject(object);\r
32741};\r
32742\r
32743/**\r
32744 * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.\r
32745 * @interface IConversionOptions\r
32746 * @property {Function} [longs] Long conversion type.\r
32747 * Valid values are `String` and `Number` (the global types).\r
32748 * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.\r
32749 * @property {Function} [enums] Enum value conversion type.\r
32750 * Only valid value is `String` (the global type).\r
32751 * Defaults to copy the present value, which is the numeric id.\r
32752 * @property {Function} [bytes] Bytes value conversion type.\r
32753 * Valid values are `Array` and (a base64 encoded) `String` (the global types).\r
32754 * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.\r
32755 * @property {boolean} [defaults=false] Also sets default values on the resulting object\r
32756 * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`\r
32757 * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`\r
32758 * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any\r
32759 * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings\r
32760 */\r
32761\r
32762/**\r
32763 * Creates a plain object from a message of this type. Also converts values to other types if specified.\r
32764 * @param {Message<{}>} message Message instance\r
32765 * @param {IConversionOptions} [options] Conversion options\r
32766 * @returns {Object.<string,*>} Plain object\r
32767 */\r
32768Type.prototype.toObject = function toObject(message, options) {\r
32769 return this.setup().toObject(message, options);\r
32770};\r
32771\r
32772/**\r
32773 * Decorator function as returned by {@link Type.d} (TypeScript).\r
32774 * @typedef TypeDecorator\r
32775 * @type {function}\r
32776 * @param {Constructor<T>} target Target constructor\r
32777 * @returns {undefined}\r
32778 * @template T extends Message<T>\r
32779 */\r
32780\r
32781/**\r
32782 * Type decorator (TypeScript).\r
32783 * @param {string} [typeName] Type name, defaults to the constructor's name\r
32784 * @returns {TypeDecorator<T>} Decorator function\r
32785 * @template T extends Message<T>\r
32786 */\r
32787Type.d = function decorateType(typeName) {\r
32788 return function typeDecorator(target) {\r
32789 util.decorateType(target, typeName);\r
32790 };\r
32791};\r
32792
32793},{"./converter":193,"./decoder":194,"./encoder":195,"./enum":196,"./field":197,"./mapfield":201,"./message":202,"./namespace":204,"./oneof":206,"./reader":208,"./service":214,"./util":218,"./verifier":221,"./wrappers":222,"./writer":223}],217:[function(require,module,exports){
32794"use strict";\r
32795\r
32796/**\r
32797 * Common type constants.\r
32798 * @namespace\r
32799 */\r
32800var types = exports;\r
32801\r
32802var util = require("./util");\r
32803\r
32804var s = [\r
32805 "double", // 0\r
32806 "float", // 1\r
32807 "int32", // 2\r
32808 "uint32", // 3\r
32809 "sint32", // 4\r
32810 "fixed32", // 5\r
32811 "sfixed32", // 6\r
32812 "int64", // 7\r
32813 "uint64", // 8\r
32814 "sint64", // 9\r
32815 "fixed64", // 10\r
32816 "sfixed64", // 11\r
32817 "bool", // 12\r
32818 "string", // 13\r
32819 "bytes" // 14\r
32820];\r
32821\r
32822function bake(values, offset) {\r
32823 var i = 0, o = {};\r
32824 offset |= 0;\r
32825 while (i < values.length) o[s[i + offset]] = values[i++];\r
32826 return o;\r
32827}\r
32828\r
32829/**\r
32830 * Basic type wire types.\r
32831 * @type {Object.<string,number>}\r
32832 * @const\r
32833 * @property {number} double=1 Fixed64 wire type\r
32834 * @property {number} float=5 Fixed32 wire type\r
32835 * @property {number} int32=0 Varint wire type\r
32836 * @property {number} uint32=0 Varint wire type\r
32837 * @property {number} sint32=0 Varint wire type\r
32838 * @property {number} fixed32=5 Fixed32 wire type\r
32839 * @property {number} sfixed32=5 Fixed32 wire type\r
32840 * @property {number} int64=0 Varint wire type\r
32841 * @property {number} uint64=0 Varint wire type\r
32842 * @property {number} sint64=0 Varint wire type\r
32843 * @property {number} fixed64=1 Fixed64 wire type\r
32844 * @property {number} sfixed64=1 Fixed64 wire type\r
32845 * @property {number} bool=0 Varint wire type\r
32846 * @property {number} string=2 Ldelim wire type\r
32847 * @property {number} bytes=2 Ldelim wire type\r
32848 */\r
32849types.basic = bake([\r
32850 /* double */ 1,\r
32851 /* float */ 5,\r
32852 /* int32 */ 0,\r
32853 /* uint32 */ 0,\r
32854 /* sint32 */ 0,\r
32855 /* fixed32 */ 5,\r
32856 /* sfixed32 */ 5,\r
32857 /* int64 */ 0,\r
32858 /* uint64 */ 0,\r
32859 /* sint64 */ 0,\r
32860 /* fixed64 */ 1,\r
32861 /* sfixed64 */ 1,\r
32862 /* bool */ 0,\r
32863 /* string */ 2,\r
32864 /* bytes */ 2\r
32865]);\r
32866\r
32867/**\r
32868 * Basic type defaults.\r
32869 * @type {Object.<string,*>}\r
32870 * @const\r
32871 * @property {number} double=0 Double default\r
32872 * @property {number} float=0 Float default\r
32873 * @property {number} int32=0 Int32 default\r
32874 * @property {number} uint32=0 Uint32 default\r
32875 * @property {number} sint32=0 Sint32 default\r
32876 * @property {number} fixed32=0 Fixed32 default\r
32877 * @property {number} sfixed32=0 Sfixed32 default\r
32878 * @property {number} int64=0 Int64 default\r
32879 * @property {number} uint64=0 Uint64 default\r
32880 * @property {number} sint64=0 Sint32 default\r
32881 * @property {number} fixed64=0 Fixed64 default\r
32882 * @property {number} sfixed64=0 Sfixed64 default\r
32883 * @property {boolean} bool=false Bool default\r
32884 * @property {string} string="" String default\r
32885 * @property {Array.<number>} bytes=Array(0) Bytes default\r
32886 * @property {null} message=null Message default\r
32887 */\r
32888types.defaults = bake([\r
32889 /* double */ 0,\r
32890 /* float */ 0,\r
32891 /* int32 */ 0,\r
32892 /* uint32 */ 0,\r
32893 /* sint32 */ 0,\r
32894 /* fixed32 */ 0,\r
32895 /* sfixed32 */ 0,\r
32896 /* int64 */ 0,\r
32897 /* uint64 */ 0,\r
32898 /* sint64 */ 0,\r
32899 /* fixed64 */ 0,\r
32900 /* sfixed64 */ 0,\r
32901 /* bool */ false,\r
32902 /* string */ "",\r
32903 /* bytes */ util.emptyArray,\r
32904 /* message */ null\r
32905]);\r
32906\r
32907/**\r
32908 * Basic long type wire types.\r
32909 * @type {Object.<string,number>}\r
32910 * @const\r
32911 * @property {number} int64=0 Varint wire type\r
32912 * @property {number} uint64=0 Varint wire type\r
32913 * @property {number} sint64=0 Varint wire type\r
32914 * @property {number} fixed64=1 Fixed64 wire type\r
32915 * @property {number} sfixed64=1 Fixed64 wire type\r
32916 */\r
32917types.long = bake([\r
32918 /* int64 */ 0,\r
32919 /* uint64 */ 0,\r
32920 /* sint64 */ 0,\r
32921 /* fixed64 */ 1,\r
32922 /* sfixed64 */ 1\r
32923], 7);\r
32924\r
32925/**\r
32926 * Allowed types for map keys with their associated wire type.\r
32927 * @type {Object.<string,number>}\r
32928 * @const\r
32929 * @property {number} int32=0 Varint wire type\r
32930 * @property {number} uint32=0 Varint wire type\r
32931 * @property {number} sint32=0 Varint wire type\r
32932 * @property {number} fixed32=5 Fixed32 wire type\r
32933 * @property {number} sfixed32=5 Fixed32 wire type\r
32934 * @property {number} int64=0 Varint wire type\r
32935 * @property {number} uint64=0 Varint wire type\r
32936 * @property {number} sint64=0 Varint wire type\r
32937 * @property {number} fixed64=1 Fixed64 wire type\r
32938 * @property {number} sfixed64=1 Fixed64 wire type\r
32939 * @property {number} bool=0 Varint wire type\r
32940 * @property {number} string=2 Ldelim wire type\r
32941 */\r
32942types.mapKey = bake([\r
32943 /* int32 */ 0,\r
32944 /* uint32 */ 0,\r
32945 /* sint32 */ 0,\r
32946 /* fixed32 */ 5,\r
32947 /* sfixed32 */ 5,\r
32948 /* int64 */ 0,\r
32949 /* uint64 */ 0,\r
32950 /* sint64 */ 0,\r
32951 /* fixed64 */ 1,\r
32952 /* sfixed64 */ 1,\r
32953 /* bool */ 0,\r
32954 /* string */ 2\r
32955], 2);\r
32956\r
32957/**\r
32958 * Allowed types for packed repeated fields with their associated wire type.\r
32959 * @type {Object.<string,number>}\r
32960 * @const\r
32961 * @property {number} double=1 Fixed64 wire type\r
32962 * @property {number} float=5 Fixed32 wire type\r
32963 * @property {number} int32=0 Varint wire type\r
32964 * @property {number} uint32=0 Varint wire type\r
32965 * @property {number} sint32=0 Varint wire type\r
32966 * @property {number} fixed32=5 Fixed32 wire type\r
32967 * @property {number} sfixed32=5 Fixed32 wire type\r
32968 * @property {number} int64=0 Varint wire type\r
32969 * @property {number} uint64=0 Varint wire type\r
32970 * @property {number} sint64=0 Varint wire type\r
32971 * @property {number} fixed64=1 Fixed64 wire type\r
32972 * @property {number} sfixed64=1 Fixed64 wire type\r
32973 * @property {number} bool=0 Varint wire type\r
32974 */\r
32975types.packed = bake([\r
32976 /* double */ 1,\r
32977 /* float */ 5,\r
32978 /* int32 */ 0,\r
32979 /* uint32 */ 0,\r
32980 /* sint32 */ 0,\r
32981 /* fixed32 */ 5,\r
32982 /* sfixed32 */ 5,\r
32983 /* int64 */ 0,\r
32984 /* uint64 */ 0,\r
32985 /* sint64 */ 0,\r
32986 /* fixed64 */ 1,\r
32987 /* sfixed64 */ 1,\r
32988 /* bool */ 0\r
32989]);\r
32990
32991},{"./util":218}],218:[function(require,module,exports){
32992"use strict";\r
32993\r
32994/**\r
32995 * Various utility functions.\r
32996 * @namespace\r
32997 */\r
32998var util = module.exports = require("./util/minimal");\r
32999\r
33000var roots = require("./roots");\r
33001\r
33002var Type, // cyclic\r
33003 Enum;\r
33004\r
33005util.codegen = require("@protobufjs/codegen");\r
33006util.fetch = require("@protobufjs/fetch");\r
33007util.path = require("@protobufjs/path");\r
33008\r
33009/**\r
33010 * Node's fs module if available.\r
33011 * @type {Object.<string,*>}\r
33012 */\r
33013util.fs = util.inquire("fs");\r
33014\r
33015/**\r
33016 * Converts an object's values to an array.\r
33017 * @param {Object.<string,*>} object Object to convert\r
33018 * @returns {Array.<*>} Converted array\r
33019 */\r
33020util.toArray = function toArray(object) {\r
33021 if (object) {\r
33022 var keys = Object.keys(object),\r
33023 array = new Array(keys.length),\r
33024 index = 0;\r
33025 while (index < keys.length)\r
33026 array[index] = object[keys[index++]];\r
33027 return array;\r
33028 }\r
33029 return [];\r
33030};\r
33031\r
33032/**\r
33033 * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.\r
33034 * @param {Array.<*>} array Array to convert\r
33035 * @returns {Object.<string,*>} Converted object\r
33036 */\r
33037util.toObject = function toObject(array) {\r
33038 var object = {},\r
33039 index = 0;\r
33040 while (index < array.length) {\r
33041 var key = array[index++],\r
33042 val = array[index++];\r
33043 if (val !== undefined)\r
33044 object[key] = val;\r
33045 }\r
33046 return object;\r
33047};\r
33048\r
33049var safePropBackslashRe = /\\/g,\r
33050 safePropQuoteRe = /"/g;\r
33051\r
33052/**\r
33053 * Tests whether the specified name is a reserved word in JS.\r
33054 * @param {string} name Name to test\r
33055 * @returns {boolean} `true` if reserved, otherwise `false`\r
33056 */\r
33057util.isReserved = function isReserved(name) {\r
33058 return /^(?:do|if|in|for|let|new|try|var|case|else|enum|eval|false|null|this|true|void|with|break|catch|class|const|super|throw|while|yield|delete|export|import|public|return|static|switch|typeof|default|extends|finally|package|private|continue|debugger|function|arguments|interface|protected|implements|instanceof)$/.test(name);\r
33059};\r
33060\r
33061/**\r
33062 * Returns a safe property accessor for the specified property name.\r
33063 * @param {string} prop Property name\r
33064 * @returns {string} Safe accessor\r
33065 */\r
33066util.safeProp = function safeProp(prop) {\r
33067 if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop))\r
33068 return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]";\r
33069 return "." + prop;\r
33070};\r
33071\r
33072/**\r
33073 * Converts the first character of a string to upper case.\r
33074 * @param {string} str String to convert\r
33075 * @returns {string} Converted string\r
33076 */\r
33077util.ucFirst = function ucFirst(str) {\r
33078 return str.charAt(0).toUpperCase() + str.substring(1);\r
33079};\r
33080\r
33081var camelCaseRe = /_([a-z])/g;\r
33082\r
33083/**\r
33084 * Converts a string to camel case.\r
33085 * @param {string} str String to convert\r
33086 * @returns {string} Converted string\r
33087 */\r
33088util.camelCase = function camelCase(str) {\r
33089 return str.substring(0, 1)\r
33090 + str.substring(1)\r
33091 .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });\r
33092};\r
33093\r
33094/**\r
33095 * Compares reflected fields by id.\r
33096 * @param {Field} a First field\r
33097 * @param {Field} b Second field\r
33098 * @returns {number} Comparison value\r
33099 */\r
33100util.compareFieldsById = function compareFieldsById(a, b) {\r
33101 return a.id - b.id;\r
33102};\r
33103\r
33104/**\r
33105 * Decorator helper for types (TypeScript).\r
33106 * @param {Constructor<T>} ctor Constructor function\r
33107 * @param {string} [typeName] Type name, defaults to the constructor's name\r
33108 * @returns {Type} Reflected type\r
33109 * @template T extends Message<T>\r
33110 * @property {Root} root Decorators root\r
33111 */\r
33112util.decorateType = function decorateType(ctor, typeName) {\r
33113\r
33114 /* istanbul ignore if */\r
33115 if (ctor.$type) {\r
33116 if (typeName && ctor.$type.name !== typeName) {\r
33117 util.decorateRoot.remove(ctor.$type);\r
33118 ctor.$type.name = typeName;\r
33119 util.decorateRoot.add(ctor.$type);\r
33120 }\r
33121 return ctor.$type;\r
33122 }\r
33123\r
33124 /* istanbul ignore next */\r
33125 if (!Type)\r
33126 Type = require("./type");\r
33127\r
33128 var type = new Type(typeName || ctor.name);\r
33129 util.decorateRoot.add(type);\r
33130 type.ctor = ctor; // sets up .encode, .decode etc.\r
33131 Object.defineProperty(ctor, "$type", { value: type, enumerable: false });\r
33132 Object.defineProperty(ctor.prototype, "$type", { value: type, enumerable: false });\r
33133 return type;\r
33134};\r
33135\r
33136var decorateEnumIndex = 0;\r
33137\r
33138/**\r
33139 * Decorator helper for enums (TypeScript).\r
33140 * @param {Object} object Enum object\r
33141 * @returns {Enum} Reflected enum\r
33142 */\r
33143util.decorateEnum = function decorateEnum(object) {\r
33144\r
33145 /* istanbul ignore if */\r
33146 if (object.$type)\r
33147 return object.$type;\r
33148\r
33149 /* istanbul ignore next */\r
33150 if (!Enum)\r
33151 Enum = require("./enum");\r
33152\r
33153 var enm = new Enum("Enum" + decorateEnumIndex++, object);\r
33154 util.decorateRoot.add(enm);\r
33155 Object.defineProperty(object, "$type", { value: enm, enumerable: false });\r
33156 return enm;\r
33157};\r
33158\r
33159/**\r
33160 * Decorator root (TypeScript).\r
33161 * @name util.decorateRoot\r
33162 * @type {Root}\r
33163 * @readonly\r
33164 */\r
33165Object.defineProperty(util, "decorateRoot", {\r
33166 get: function() {\r
33167 return roots["decorated"] || (roots["decorated"] = new (require("./root"))());\r
33168 }\r
33169});\r
33170
33171},{"./enum":196,"./root":210,"./roots":211,"./type":216,"./util/minimal":220,"@protobufjs/codegen":24,"@protobufjs/fetch":26,"@protobufjs/path":29}],219:[function(require,module,exports){
33172"use strict";\r
33173module.exports = LongBits;\r
33174\r
33175var util = require("../util/minimal");\r
33176\r
33177/**\r
33178 * Constructs new long bits.\r
33179 * @classdesc Helper class for working with the low and high bits of a 64 bit value.\r
33180 * @memberof util\r
33181 * @constructor\r
33182 * @param {number} lo Low 32 bits, unsigned\r
33183 * @param {number} hi High 32 bits, unsigned\r
33184 */\r
33185function LongBits(lo, hi) {\r
33186\r
33187 // note that the casts below are theoretically unnecessary as of today, but older statically\r
33188 // generated converter code might still call the ctor with signed 32bits. kept for compat.\r
33189\r
33190 /**\r
33191 * Low bits.\r
33192 * @type {number}\r
33193 */\r
33194 this.lo = lo >>> 0;\r
33195\r
33196 /**\r
33197 * High bits.\r
33198 * @type {number}\r
33199 */\r
33200 this.hi = hi >>> 0;\r
33201}\r
33202\r
33203/**\r
33204 * Zero bits.\r
33205 * @memberof util.LongBits\r
33206 * @type {util.LongBits}\r
33207 */\r
33208var zero = LongBits.zero = new LongBits(0, 0);\r
33209\r
33210zero.toNumber = function() { return 0; };\r
33211zero.zzEncode = zero.zzDecode = function() { return this; };\r
33212zero.length = function() { return 1; };\r
33213\r
33214/**\r
33215 * Zero hash.\r
33216 * @memberof util.LongBits\r
33217 * @type {string}\r
33218 */\r
33219var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";\r
33220\r
33221/**\r
33222 * Constructs new long bits from the specified number.\r
33223 * @param {number} value Value\r
33224 * @returns {util.LongBits} Instance\r
33225 */\r
33226LongBits.fromNumber = function fromNumber(value) {\r
33227 if (value === 0)\r
33228 return zero;\r
33229 var sign = value < 0;\r
33230 if (sign)\r
33231 value = -value;\r
33232 var lo = value >>> 0,\r
33233 hi = (value - lo) / 4294967296 >>> 0;\r
33234 if (sign) {\r
33235 hi = ~hi >>> 0;\r
33236 lo = ~lo >>> 0;\r
33237 if (++lo > 4294967295) {\r
33238 lo = 0;\r
33239 if (++hi > 4294967295)\r
33240 hi = 0;\r
33241 }\r
33242 }\r
33243 return new LongBits(lo, hi);\r
33244};\r
33245\r
33246/**\r
33247 * Constructs new long bits from a number, long or string.\r
33248 * @param {Long|number|string} value Value\r
33249 * @returns {util.LongBits} Instance\r
33250 */\r
33251LongBits.from = function from(value) {\r
33252 if (typeof value === "number")\r
33253 return LongBits.fromNumber(value);\r
33254 if (util.isString(value)) {\r
33255 /* istanbul ignore else */\r
33256 if (util.Long)\r
33257 value = util.Long.fromString(value);\r
33258 else\r
33259 return LongBits.fromNumber(parseInt(value, 10));\r
33260 }\r
33261 return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;\r
33262};\r
33263\r
33264/**\r
33265 * Converts this long bits to a possibly unsafe JavaScript number.\r
33266 * @param {boolean} [unsigned=false] Whether unsigned or not\r
33267 * @returns {number} Possibly unsafe number\r
33268 */\r
33269LongBits.prototype.toNumber = function toNumber(unsigned) {\r
33270 if (!unsigned && this.hi >>> 31) {\r
33271 var lo = ~this.lo + 1 >>> 0,\r
33272 hi = ~this.hi >>> 0;\r
33273 if (!lo)\r
33274 hi = hi + 1 >>> 0;\r
33275 return -(lo + hi * 4294967296);\r
33276 }\r
33277 return this.lo + this.hi * 4294967296;\r
33278};\r
33279\r
33280/**\r
33281 * Converts this long bits to a long.\r
33282 * @param {boolean} [unsigned=false] Whether unsigned or not\r
33283 * @returns {Long} Long\r
33284 */\r
33285LongBits.prototype.toLong = function toLong(unsigned) {\r
33286 return util.Long\r
33287 ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))\r
33288 /* istanbul ignore next */\r
33289 : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };\r
33290};\r
33291\r
33292var charCodeAt = String.prototype.charCodeAt;\r
33293\r
33294/**\r
33295 * Constructs new long bits from the specified 8 characters long hash.\r
33296 * @param {string} hash Hash\r
33297 * @returns {util.LongBits} Bits\r
33298 */\r
33299LongBits.fromHash = function fromHash(hash) {\r
33300 if (hash === zeroHash)\r
33301 return zero;\r
33302 return new LongBits(\r
33303 ( charCodeAt.call(hash, 0)\r
33304 | charCodeAt.call(hash, 1) << 8\r
33305 | charCodeAt.call(hash, 2) << 16\r
33306 | charCodeAt.call(hash, 3) << 24) >>> 0\r
33307 ,\r
33308 ( charCodeAt.call(hash, 4)\r
33309 | charCodeAt.call(hash, 5) << 8\r
33310 | charCodeAt.call(hash, 6) << 16\r
33311 | charCodeAt.call(hash, 7) << 24) >>> 0\r
33312 );\r
33313};\r
33314\r
33315/**\r
33316 * Converts this long bits to a 8 characters long hash.\r
33317 * @returns {string} Hash\r
33318 */\r
33319LongBits.prototype.toHash = function toHash() {\r
33320 return String.fromCharCode(\r
33321 this.lo & 255,\r
33322 this.lo >>> 8 & 255,\r
33323 this.lo >>> 16 & 255,\r
33324 this.lo >>> 24 ,\r
33325 this.hi & 255,\r
33326 this.hi >>> 8 & 255,\r
33327 this.hi >>> 16 & 255,\r
33328 this.hi >>> 24\r
33329 );\r
33330};\r
33331\r
33332/**\r
33333 * Zig-zag encodes this long bits.\r
33334 * @returns {util.LongBits} `this`\r
33335 */\r
33336LongBits.prototype.zzEncode = function zzEncode() {\r
33337 var mask = this.hi >> 31;\r
33338 this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;\r
33339 this.lo = ( this.lo << 1 ^ mask) >>> 0;\r
33340 return this;\r
33341};\r
33342\r
33343/**\r
33344 * Zig-zag decodes this long bits.\r
33345 * @returns {util.LongBits} `this`\r
33346 */\r
33347LongBits.prototype.zzDecode = function zzDecode() {\r
33348 var mask = -(this.lo & 1);\r
33349 this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;\r
33350 this.hi = ( this.hi >>> 1 ^ mask) >>> 0;\r
33351 return this;\r
33352};\r
33353\r
33354/**\r
33355 * Calculates the length of this longbits when encoded as a varint.\r
33356 * @returns {number} Length\r
33357 */\r
33358LongBits.prototype.length = function length() {\r
33359 var part0 = this.lo,\r
33360 part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,\r
33361 part2 = this.hi >>> 24;\r
33362 return part2 === 0\r
33363 ? part1 === 0\r
33364 ? part0 < 16384\r
33365 ? part0 < 128 ? 1 : 2\r
33366 : part0 < 2097152 ? 3 : 4\r
33367 : part1 < 16384\r
33368 ? part1 < 128 ? 5 : 6\r
33369 : part1 < 2097152 ? 7 : 8\r
33370 : part2 < 128 ? 9 : 10;\r
33371};\r
33372
33373},{"../util/minimal":220}],220:[function(require,module,exports){
33374(function (global){
33375"use strict";\r
33376var util = exports;\r
33377\r
33378// used to return a Promise where callback is omitted\r
33379util.asPromise = require("@protobufjs/aspromise");\r
33380\r
33381// converts to / from base64 encoded strings\r
33382util.base64 = require("@protobufjs/base64");\r
33383\r
33384// base class of rpc.Service\r
33385util.EventEmitter = require("@protobufjs/eventemitter");\r
33386\r
33387// float handling accross browsers\r
33388util.float = require("@protobufjs/float");\r
33389\r
33390// requires modules optionally and hides the call from bundlers\r
33391util.inquire = require("@protobufjs/inquire");\r
33392\r
33393// converts to / from utf8 encoded strings\r
33394util.utf8 = require("@protobufjs/utf8");\r
33395\r
33396// provides a node-like buffer pool in the browser\r
33397util.pool = require("@protobufjs/pool");\r
33398\r
33399// utility to work with the low and high bits of a 64 bit value\r
33400util.LongBits = require("./longbits");\r
33401\r
33402/**\r
33403 * An immuable empty array.\r
33404 * @memberof util\r
33405 * @type {Array.<*>}\r
33406 * @const\r
33407 */\r
33408util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes\r
33409\r
33410/**\r
33411 * An immutable empty object.\r
33412 * @type {Object}\r
33413 * @const\r
33414 */\r
33415util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes\r
33416\r
33417/**\r
33418 * Whether running within node or not.\r
33419 * @memberof util\r
33420 * @type {boolean}\r
33421 * @const\r
33422 */\r
33423util.isNode = Boolean(global.process && global.process.versions && global.process.versions.node);\r
33424\r
33425/**\r
33426 * Tests if the specified value is an integer.\r
33427 * @function\r
33428 * @param {*} value Value to test\r
33429 * @returns {boolean} `true` if the value is an integer\r
33430 */\r
33431util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {\r
33432 return typeof value === "number" && isFinite(value) && Math.floor(value) === value;\r
33433};\r
33434\r
33435/**\r
33436 * Tests if the specified value is a string.\r
33437 * @param {*} value Value to test\r
33438 * @returns {boolean} `true` if the value is a string\r
33439 */\r
33440util.isString = function isString(value) {\r
33441 return typeof value === "string" || value instanceof String;\r
33442};\r
33443\r
33444/**\r
33445 * Tests if the specified value is a non-null object.\r
33446 * @param {*} value Value to test\r
33447 * @returns {boolean} `true` if the value is a non-null object\r
33448 */\r
33449util.isObject = function isObject(value) {\r
33450 return value && typeof value === "object";\r
33451};\r
33452\r
33453/**\r
33454 * Checks if a property on a message is considered to be present.\r
33455 * This is an alias of {@link util.isSet}.\r
33456 * @function\r
33457 * @param {Object} obj Plain object or message instance\r
33458 * @param {string} prop Property name\r
33459 * @returns {boolean} `true` if considered to be present, otherwise `false`\r
33460 */\r
33461util.isset =\r
33462\r
33463/**\r
33464 * Checks if a property on a message is considered to be present.\r
33465 * @param {Object} obj Plain object or message instance\r
33466 * @param {string} prop Property name\r
33467 * @returns {boolean} `true` if considered to be present, otherwise `false`\r
33468 */\r
33469util.isSet = function isSet(obj, prop) {\r
33470 var value = obj[prop];\r
33471 if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins\r
33472 return typeof value !== "object" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;\r
33473 return false;\r
33474};\r
33475\r
33476/**\r
33477 * Any compatible Buffer instance.\r
33478 * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.\r
33479 * @interface Buffer\r
33480 * @extends Uint8Array\r
33481 */\r
33482\r
33483/**\r
33484 * Node's Buffer class if available.\r
33485 * @type {Constructor<Buffer>}\r
33486 */\r
33487util.Buffer = (function() {\r
33488 try {\r
33489 var Buffer = util.inquire("buffer").Buffer;\r
33490 // refuse to use non-node buffers if not explicitly assigned (perf reasons):\r
33491 return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;\r
33492 } catch (e) {\r
33493 /* istanbul ignore next */\r
33494 return null;\r
33495 }\r
33496})();\r
33497\r
33498// Internal alias of or polyfull for Buffer.from.\r
33499util._Buffer_from = null;\r
33500\r
33501// Internal alias of or polyfill for Buffer.allocUnsafe.\r
33502util._Buffer_allocUnsafe = null;\r
33503\r
33504/**\r
33505 * Creates a new buffer of whatever type supported by the environment.\r
33506 * @param {number|number[]} [sizeOrArray=0] Buffer size or number array\r
33507 * @returns {Uint8Array|Buffer} Buffer\r
33508 */\r
33509util.newBuffer = function newBuffer(sizeOrArray) {\r
33510 /* istanbul ignore next */\r
33511 return typeof sizeOrArray === "number"\r
33512 ? util.Buffer\r
33513 ? util._Buffer_allocUnsafe(sizeOrArray)\r
33514 : new util.Array(sizeOrArray)\r
33515 : util.Buffer\r
33516 ? util._Buffer_from(sizeOrArray)\r
33517 : typeof Uint8Array === "undefined"\r
33518 ? sizeOrArray\r
33519 : new Uint8Array(sizeOrArray);\r
33520};\r
33521\r
33522/**\r
33523 * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.\r
33524 * @type {Constructor<Uint8Array>}\r
33525 */\r
33526util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;\r
33527\r
33528/**\r
33529 * Any compatible Long instance.\r
33530 * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.\r
33531 * @interface Long\r
33532 * @property {number} low Low bits\r
33533 * @property {number} high High bits\r
33534 * @property {boolean} unsigned Whether unsigned or not\r
33535 */\r
33536\r
33537/**\r
33538 * Long.js's Long class if available.\r
33539 * @type {Constructor<Long>}\r
33540 */\r
33541util.Long = /* istanbul ignore next */ global.dcodeIO && /* istanbul ignore next */ global.dcodeIO.Long || util.inquire("long");\r
33542\r
33543/**\r
33544 * Regular expression used to verify 2 bit (`bool`) map keys.\r
33545 * @type {RegExp}\r
33546 * @const\r
33547 */\r
33548util.key2Re = /^true|false|0|1$/;\r
33549\r
33550/**\r
33551 * Regular expression used to verify 32 bit (`int32` etc.) map keys.\r
33552 * @type {RegExp}\r
33553 * @const\r
33554 */\r
33555util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;\r
33556\r
33557/**\r
33558 * Regular expression used to verify 64 bit (`int64` etc.) map keys.\r
33559 * @type {RegExp}\r
33560 * @const\r
33561 */\r
33562util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;\r
33563\r
33564/**\r
33565 * Converts a number or long to an 8 characters long hash string.\r
33566 * @param {Long|number} value Value to convert\r
33567 * @returns {string} Hash\r
33568 */\r
33569util.longToHash = function longToHash(value) {\r
33570 return value\r
33571 ? util.LongBits.from(value).toHash()\r
33572 : util.LongBits.zeroHash;\r
33573};\r
33574\r
33575/**\r
33576 * Converts an 8 characters long hash string to a long or number.\r
33577 * @param {string} hash Hash\r
33578 * @param {boolean} [unsigned=false] Whether unsigned or not\r
33579 * @returns {Long|number} Original value\r
33580 */\r
33581util.longFromHash = function longFromHash(hash, unsigned) {\r
33582 var bits = util.LongBits.fromHash(hash);\r
33583 if (util.Long)\r
33584 return util.Long.fromBits(bits.lo, bits.hi, unsigned);\r
33585 return bits.toNumber(Boolean(unsigned));\r
33586};\r
33587\r
33588/**\r
33589 * Merges the properties of the source object into the destination object.\r
33590 * @memberof util\r
33591 * @param {Object.<string,*>} dst Destination object\r
33592 * @param {Object.<string,*>} src Source object\r
33593 * @param {boolean} [ifNotSet=false] Merges only if the key is not already set\r
33594 * @returns {Object.<string,*>} Destination object\r
33595 */\r
33596function merge(dst, src, ifNotSet) { // used by converters\r
33597 for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)\r
33598 if (dst[keys[i]] === undefined || !ifNotSet)\r
33599 dst[keys[i]] = src[keys[i]];\r
33600 return dst;\r
33601}\r
33602\r
33603util.merge = merge;\r
33604\r
33605/**\r
33606 * Converts the first character of a string to lower case.\r
33607 * @param {string} str String to convert\r
33608 * @returns {string} Converted string\r
33609 */\r
33610util.lcFirst = function lcFirst(str) {\r
33611 return str.charAt(0).toLowerCase() + str.substring(1);\r
33612};\r
33613\r
33614/**\r
33615 * Creates a custom error constructor.\r
33616 * @memberof util\r
33617 * @param {string} name Error name\r
33618 * @returns {Constructor<Error>} Custom error constructor\r
33619 */\r
33620function newError(name) {\r
33621\r
33622 function CustomError(message, properties) {\r
33623\r
33624 if (!(this instanceof CustomError))\r
33625 return new CustomError(message, properties);\r
33626\r
33627 // Error.call(this, message);\r
33628 // ^ just returns a new error instance because the ctor can be called as a function\r
33629\r
33630 Object.defineProperty(this, "message", { get: function() { return message; } });\r
33631\r
33632 /* istanbul ignore next */\r
33633 if (Error.captureStackTrace) // node\r
33634 Error.captureStackTrace(this, CustomError);\r
33635 else\r
33636 Object.defineProperty(this, "stack", { value: (new Error()).stack || "" });\r
33637\r
33638 if (properties)\r
33639 merge(this, properties);\r
33640 }\r
33641\r
33642 (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;\r
33643\r
33644 Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } });\r
33645\r
33646 CustomError.prototype.toString = function toString() {\r
33647 return this.name + ": " + this.message;\r
33648 };\r
33649\r
33650 return CustomError;\r
33651}\r
33652\r
33653util.newError = newError;\r
33654\r
33655/**\r
33656 * Constructs a new protocol error.\r
33657 * @classdesc Error subclass indicating a protocol specifc error.\r
33658 * @memberof util\r
33659 * @extends Error\r
33660 * @template T extends Message<T>\r
33661 * @constructor\r
33662 * @param {string} message Error message\r
33663 * @param {Object.<string,*>} [properties] Additional properties\r
33664 * @example\r
33665 * try {\r
33666 * MyMessage.decode(someBuffer); // throws if required fields are missing\r
33667 * } catch (e) {\r
33668 * if (e instanceof ProtocolError && e.instance)\r
33669 * console.log("decoded so far: " + JSON.stringify(e.instance));\r
33670 * }\r
33671 */\r
33672util.ProtocolError = newError("ProtocolError");\r
33673\r
33674/**\r
33675 * So far decoded message instance.\r
33676 * @name util.ProtocolError#instance\r
33677 * @type {Message<T>}\r
33678 */\r
33679\r
33680/**\r
33681 * A OneOf getter as returned by {@link util.oneOfGetter}.\r
33682 * @typedef OneOfGetter\r
33683 * @type {function}\r
33684 * @returns {string|undefined} Set field name, if any\r
33685 */\r
33686\r
33687/**\r
33688 * Builds a getter for a oneof's present field name.\r
33689 * @param {string[]} fieldNames Field names\r
33690 * @returns {OneOfGetter} Unbound getter\r
33691 */\r
33692util.oneOfGetter = function getOneOf(fieldNames) {\r
33693 var fieldMap = {};\r
33694 for (var i = 0; i < fieldNames.length; ++i)\r
33695 fieldMap[fieldNames[i]] = 1;\r
33696\r
33697 /**\r
33698 * @returns {string|undefined} Set field name, if any\r
33699 * @this Object\r
33700 * @ignore\r
33701 */\r
33702 return function() { // eslint-disable-line consistent-return\r
33703 for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)\r
33704 if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)\r
33705 return keys[i];\r
33706 };\r
33707};\r
33708\r
33709/**\r
33710 * A OneOf setter as returned by {@link util.oneOfSetter}.\r
33711 * @typedef OneOfSetter\r
33712 * @type {function}\r
33713 * @param {string|undefined} value Field name\r
33714 * @returns {undefined}\r
33715 */\r
33716\r
33717/**\r
33718 * Builds a setter for a oneof's present field name.\r
33719 * @param {string[]} fieldNames Field names\r
33720 * @returns {OneOfSetter} Unbound setter\r
33721 */\r
33722util.oneOfSetter = function setOneOf(fieldNames) {\r
33723\r
33724 /**\r
33725 * @param {string} name Field name\r
33726 * @returns {undefined}\r
33727 * @this Object\r
33728 * @ignore\r
33729 */\r
33730 return function(name) {\r
33731 for (var i = 0; i < fieldNames.length; ++i)\r
33732 if (fieldNames[i] !== name)\r
33733 delete this[fieldNames[i]];\r
33734 };\r
33735};\r
33736\r
33737/**\r
33738 * Default conversion options used for {@link Message#toJSON} implementations.\r
33739 *\r
33740 * These options are close to proto3's JSON mapping with the exception that internal types like Any are handled just like messages. More precisely:\r
33741 *\r
33742 * - Longs become strings\r
33743 * - Enums become string keys\r
33744 * - Bytes become base64 encoded strings\r
33745 * - (Sub-)Messages become plain objects\r
33746 * - Maps become plain objects with all string keys\r
33747 * - Repeated fields become arrays\r
33748 * - NaN and Infinity for float and double fields become strings\r
33749 *\r
33750 * @type {IConversionOptions}\r
33751 * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json\r
33752 */\r
33753util.toJSONOptions = {\r
33754 longs: String,\r
33755 enums: String,\r
33756 bytes: String,\r
33757 json: true\r
33758};\r
33759\r
33760util._configure = function() {\r
33761 var Buffer = util.Buffer;\r
33762 /* istanbul ignore if */\r
33763 if (!Buffer) {\r
33764 util._Buffer_from = util._Buffer_allocUnsafe = null;\r
33765 return;\r
33766 }\r
33767 // because node 4.x buffers are incompatible & immutable\r
33768 // see: https://github.com/dcodeIO/protobuf.js/pull/665\r
33769 util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||\r
33770 /* istanbul ignore next */\r
33771 function Buffer_from(value, encoding) {\r
33772 return new Buffer(value, encoding);\r
33773 };\r
33774 util._Buffer_allocUnsafe = Buffer.allocUnsafe ||\r
33775 /* istanbul ignore next */\r
33776 function Buffer_allocUnsafe(size) {\r
33777 return new Buffer(size);\r
33778 };\r
33779};\r
33780
33781}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
33782},{"./longbits":219,"@protobufjs/aspromise":22,"@protobufjs/base64":23,"@protobufjs/eventemitter":25,"@protobufjs/float":27,"@protobufjs/inquire":28,"@protobufjs/pool":30,"@protobufjs/utf8":31}],221:[function(require,module,exports){
33783"use strict";\r
33784module.exports = verifier;\r
33785\r
33786var Enum = require("./enum"),\r
33787 util = require("./util");\r
33788\r
33789function invalid(field, expected) {\r
33790 return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected";\r
33791}\r
33792\r
33793/**\r
33794 * Generates a partial value verifier.\r
33795 * @param {Codegen} gen Codegen instance\r
33796 * @param {Field} field Reflected field\r
33797 * @param {number} fieldIndex Field index\r
33798 * @param {string} ref Variable reference\r
33799 * @returns {Codegen} Codegen instance\r
33800 * @ignore\r
33801 */\r
33802function genVerifyValue(gen, field, fieldIndex, ref) {\r
33803 /* eslint-disable no-unexpected-multiline */\r
33804 if (field.resolvedType) {\r
33805 if (field.resolvedType instanceof Enum) { gen\r
33806 ("switch(%s){", ref)\r
33807 ("default:")\r
33808 ("return%j", invalid(field, "enum value"));\r
33809 for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen\r
33810 ("case %i:", field.resolvedType.values[keys[j]]);\r
33811 gen\r
33812 ("break")\r
33813 ("}");\r
33814 } else {\r
33815 gen\r
33816 ("{")\r
33817 ("var e=types[%i].verify(%s);", fieldIndex, ref)\r
33818 ("if(e)")\r
33819 ("return%j+e", field.name + ".")\r
33820 ("}");\r
33821 }\r
33822 } else {\r
33823 switch (field.type) {\r
33824 case "int32":\r
33825 case "uint32":\r
33826 case "sint32":\r
33827 case "fixed32":\r
33828 case "sfixed32": gen\r
33829 ("if(!util.isInteger(%s))", ref)\r
33830 ("return%j", invalid(field, "integer"));\r
33831 break;\r
33832 case "int64":\r
33833 case "uint64":\r
33834 case "sint64":\r
33835 case "fixed64":\r
33836 case "sfixed64": gen\r
33837 ("if(!util.isInteger(%s)&&!(%s&&util.isInteger(%s.low)&&util.isInteger(%s.high)))", ref, ref, ref, ref)\r
33838 ("return%j", invalid(field, "integer|Long"));\r
33839 break;\r
33840 case "float":\r
33841 case "double": gen\r
33842 ("if(typeof %s!==\"number\")", ref)\r
33843 ("return%j", invalid(field, "number"));\r
33844 break;\r
33845 case "bool": gen\r
33846 ("if(typeof %s!==\"boolean\")", ref)\r
33847 ("return%j", invalid(field, "boolean"));\r
33848 break;\r
33849 case "string": gen\r
33850 ("if(!util.isString(%s))", ref)\r
33851 ("return%j", invalid(field, "string"));\r
33852 break;\r
33853 case "bytes": gen\r
33854 ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref)\r
33855 ("return%j", invalid(field, "buffer"));\r
33856 break;\r
33857 }\r
33858 }\r
33859 return gen;\r
33860 /* eslint-enable no-unexpected-multiline */\r
33861}\r
33862\r
33863/**\r
33864 * Generates a partial key verifier.\r
33865 * @param {Codegen} gen Codegen instance\r
33866 * @param {Field} field Reflected field\r
33867 * @param {string} ref Variable reference\r
33868 * @returns {Codegen} Codegen instance\r
33869 * @ignore\r
33870 */\r
33871function genVerifyKey(gen, field, ref) {\r
33872 /* eslint-disable no-unexpected-multiline */\r
33873 switch (field.keyType) {\r
33874 case "int32":\r
33875 case "uint32":\r
33876 case "sint32":\r
33877 case "fixed32":\r
33878 case "sfixed32": gen\r
33879 ("if(!util.key32Re.test(%s))", ref)\r
33880 ("return%j", invalid(field, "integer key"));\r
33881 break;\r
33882 case "int64":\r
33883 case "uint64":\r
33884 case "sint64":\r
33885 case "fixed64":\r
33886 case "sfixed64": gen\r
33887 ("if(!util.key64Re.test(%s))", ref) // see comment above: x is ok, d is not\r
33888 ("return%j", invalid(field, "integer|Long key"));\r
33889 break;\r
33890 case "bool": gen\r
33891 ("if(!util.key2Re.test(%s))", ref)\r
33892 ("return%j", invalid(field, "boolean key"));\r
33893 break;\r
33894 }\r
33895 return gen;\r
33896 /* eslint-enable no-unexpected-multiline */\r
33897}\r
33898\r
33899/**\r
33900 * Generates a verifier specific to the specified message type.\r
33901 * @param {Type} mtype Message type\r
33902 * @returns {Codegen} Codegen instance\r
33903 */\r
33904function verifier(mtype) {\r
33905 /* eslint-disable no-unexpected-multiline */\r
33906\r
33907 var gen = util.codegen(["m"], mtype.name + "$verify")\r
33908 ("if(typeof m!==\"object\"||m===null)")\r
33909 ("return%j", "object expected");\r
33910 var oneofs = mtype.oneofsArray,\r
33911 seenFirstField = {};\r
33912 if (oneofs.length) gen\r
33913 ("var p={}");\r
33914\r
33915 for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {\r
33916 var field = mtype._fieldsArray[i].resolve(),\r
33917 ref = "m" + util.safeProp(field.name);\r
33918\r
33919 if (field.optional) gen\r
33920 ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null\r
33921\r
33922 // map fields\r
33923 if (field.map) { gen\r
33924 ("if(!util.isObject(%s))", ref)\r
33925 ("return%j", invalid(field, "object"))\r
33926 ("var k=Object.keys(%s)", ref)\r
33927 ("for(var i=0;i<k.length;++i){");\r
33928 genVerifyKey(gen, field, "k[i]");\r
33929 genVerifyValue(gen, field, i, ref + "[k[i]]")\r
33930 ("}");\r
33931\r
33932 // repeated fields\r
33933 } else if (field.repeated) { gen\r
33934 ("if(!Array.isArray(%s))", ref)\r
33935 ("return%j", invalid(field, "array"))\r
33936 ("for(var i=0;i<%s.length;++i){", ref);\r
33937 genVerifyValue(gen, field, i, ref + "[i]")\r
33938 ("}");\r
33939\r
33940 // required or present fields\r
33941 } else {\r
33942 if (field.partOf) {\r
33943 var oneofProp = util.safeProp(field.partOf.name);\r
33944 if (seenFirstField[field.partOf.name] === 1) gen\r
33945 ("if(p%s===1)", oneofProp)\r
33946 ("return%j", field.partOf.name + ": multiple values");\r
33947 seenFirstField[field.partOf.name] = 1;\r
33948 gen\r
33949 ("p%s=1", oneofProp);\r
33950 }\r
33951 genVerifyValue(gen, field, i, ref);\r
33952 }\r
33953 if (field.optional) gen\r
33954 ("}");\r
33955 }\r
33956 return gen\r
33957 ("return null");\r
33958 /* eslint-enable no-unexpected-multiline */\r
33959}
33960},{"./enum":196,"./util":218}],222:[function(require,module,exports){
33961"use strict";\r
33962\r
33963/**\r
33964 * Wrappers for common types.\r
33965 * @type {Object.<string,IWrapper>}\r
33966 * @const\r
33967 */\r
33968var wrappers = exports;\r
33969\r
33970var Message = require("./message");\r
33971\r
33972/**\r
33973 * From object converter part of an {@link IWrapper}.\r
33974 * @typedef WrapperFromObjectConverter\r
33975 * @type {function}\r
33976 * @param {Object.<string,*>} object Plain object\r
33977 * @returns {Message<{}>} Message instance\r
33978 * @this Type\r
33979 */\r
33980\r
33981/**\r
33982 * To object converter part of an {@link IWrapper}.\r
33983 * @typedef WrapperToObjectConverter\r
33984 * @type {function}\r
33985 * @param {Message<{}>} message Message instance\r
33986 * @param {IConversionOptions} [options] Conversion options\r
33987 * @returns {Object.<string,*>} Plain object\r
33988 * @this Type\r
33989 */\r
33990\r
33991/**\r
33992 * Common type wrapper part of {@link wrappers}.\r
33993 * @interface IWrapper\r
33994 * @property {WrapperFromObjectConverter} [fromObject] From object converter\r
33995 * @property {WrapperToObjectConverter} [toObject] To object converter\r
33996 */\r
33997\r
33998// Custom wrapper for Any\r
33999wrappers[".google.protobuf.Any"] = {\r
34000\r
34001 fromObject: function(object) {\r
34002\r
34003 // unwrap value type if mapped\r
34004 if (object && object["@type"]) {\r
34005 var type = this.lookup(object["@type"]);\r
34006 /* istanbul ignore else */\r
34007 if (type) {\r
34008 // type_url does not accept leading "."\r
34009 var type_url = object["@type"].charAt(0) === "." ?\r
34010 object["@type"].substr(1) : object["@type"];\r
34011 // type_url prefix is optional, but path seperator is required\r
34012 return this.create({\r
34013 type_url: "/" + type_url,\r
34014 value: type.encode(type.fromObject(object)).finish()\r
34015 });\r
34016 }\r
34017 }\r
34018\r
34019 return this.fromObject(object);\r
34020 },\r
34021\r
34022 toObject: function(message, options) {\r
34023\r
34024 // decode value if requested and unmapped\r
34025 if (options && options.json && message.type_url && message.value) {\r
34026 // Only use fully qualified type name after the last '/'\r
34027 var name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);\r
34028 var type = this.lookup(name);\r
34029 /* istanbul ignore else */\r
34030 if (type)\r
34031 message = type.decode(message.value);\r
34032 }\r
34033\r
34034 // wrap value if unmapped\r
34035 if (!(message instanceof this.ctor) && message instanceof Message) {\r
34036 var object = message.$type.toObject(message, options);\r
34037 object["@type"] = message.$type.fullName;\r
34038 return object;\r
34039 }\r
34040\r
34041 return this.toObject(message, options);\r
34042 }\r
34043};\r
34044
34045},{"./message":202}],223:[function(require,module,exports){
34046"use strict";\r
34047module.exports = Writer;\r
34048\r
34049var util = require("./util/minimal");\r
34050\r
34051var BufferWriter; // cyclic\r
34052\r
34053var LongBits = util.LongBits,\r
34054 base64 = util.base64,\r
34055 utf8 = util.utf8;\r
34056\r
34057/**\r
34058 * Constructs a new writer operation instance.\r
34059 * @classdesc Scheduled writer operation.\r
34060 * @constructor\r
34061 * @param {function(*, Uint8Array, number)} fn Function to call\r
34062 * @param {number} len Value byte length\r
34063 * @param {*} val Value to write\r
34064 * @ignore\r
34065 */\r
34066function Op(fn, len, val) {\r
34067\r
34068 /**\r
34069 * Function to call.\r
34070 * @type {function(Uint8Array, number, *)}\r
34071 */\r
34072 this.fn = fn;\r
34073\r
34074 /**\r
34075 * Value byte length.\r
34076 * @type {number}\r
34077 */\r
34078 this.len = len;\r
34079\r
34080 /**\r
34081 * Next operation.\r
34082 * @type {Writer.Op|undefined}\r
34083 */\r
34084 this.next = undefined;\r
34085\r
34086 /**\r
34087 * Value to write.\r
34088 * @type {*}\r
34089 */\r
34090 this.val = val; // type varies\r
34091}\r
34092\r
34093/* istanbul ignore next */\r
34094function noop() {} // eslint-disable-line no-empty-function\r
34095\r
34096/**\r
34097 * Constructs a new writer state instance.\r
34098 * @classdesc Copied writer state.\r
34099 * @memberof Writer\r
34100 * @constructor\r
34101 * @param {Writer} writer Writer to copy state from\r
34102 * @ignore\r
34103 */\r
34104function State(writer) {\r
34105\r
34106 /**\r
34107 * Current head.\r
34108 * @type {Writer.Op}\r
34109 */\r
34110 this.head = writer.head;\r
34111\r
34112 /**\r
34113 * Current tail.\r
34114 * @type {Writer.Op}\r
34115 */\r
34116 this.tail = writer.tail;\r
34117\r
34118 /**\r
34119 * Current buffer length.\r
34120 * @type {number}\r
34121 */\r
34122 this.len = writer.len;\r
34123\r
34124 /**\r
34125 * Next state.\r
34126 * @type {State|null}\r
34127 */\r
34128 this.next = writer.states;\r
34129}\r
34130\r
34131/**\r
34132 * Constructs a new writer instance.\r
34133 * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.\r
34134 * @constructor\r
34135 */\r
34136function Writer() {\r
34137\r
34138 /**\r
34139 * Current length.\r
34140 * @type {number}\r
34141 */\r
34142 this.len = 0;\r
34143\r
34144 /**\r
34145 * Operations head.\r
34146 * @type {Object}\r
34147 */\r
34148 this.head = new Op(noop, 0, 0);\r
34149\r
34150 /**\r
34151 * Operations tail\r
34152 * @type {Object}\r
34153 */\r
34154 this.tail = this.head;\r
34155\r
34156 /**\r
34157 * Linked forked states.\r
34158 * @type {Object|null}\r
34159 */\r
34160 this.states = null;\r
34161\r
34162 // When a value is written, the writer calculates its byte length and puts it into a linked\r
34163 // list of operations to perform when finish() is called. This both allows us to allocate\r
34164 // buffers of the exact required size and reduces the amount of work we have to do compared\r
34165 // to first calculating over objects and then encoding over objects. In our case, the encoding\r
34166 // part is just a linked list walk calling operations with already prepared values.\r
34167}\r
34168\r
34169/**\r
34170 * Creates a new writer.\r
34171 * @function\r
34172 * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}\r
34173 */\r
34174Writer.create = util.Buffer\r
34175 ? function create_buffer_setup() {\r
34176 return (Writer.create = function create_buffer() {\r
34177 return new BufferWriter();\r
34178 })();\r
34179 }\r
34180 /* istanbul ignore next */\r
34181 : function create_array() {\r
34182 return new Writer();\r
34183 };\r
34184\r
34185/**\r
34186 * Allocates a buffer of the specified size.\r
34187 * @param {number} size Buffer size\r
34188 * @returns {Uint8Array} Buffer\r
34189 */\r
34190Writer.alloc = function alloc(size) {\r
34191 return new util.Array(size);\r
34192};\r
34193\r
34194// Use Uint8Array buffer pool in the browser, just like node does with buffers\r
34195/* istanbul ignore else */\r
34196if (util.Array !== Array)\r
34197 Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);\r
34198\r
34199/**\r
34200 * Pushes a new operation to the queue.\r
34201 * @param {function(Uint8Array, number, *)} fn Function to call\r
34202 * @param {number} len Value byte length\r
34203 * @param {number} val Value to write\r
34204 * @returns {Writer} `this`\r
34205 * @private\r
34206 */\r
34207Writer.prototype._push = function push(fn, len, val) {\r
34208 this.tail = this.tail.next = new Op(fn, len, val);\r
34209 this.len += len;\r
34210 return this;\r
34211};\r
34212\r
34213function writeByte(val, buf, pos) {\r
34214 buf[pos] = val & 255;\r
34215}\r
34216\r
34217function writeVarint32(val, buf, pos) {\r
34218 while (val > 127) {\r
34219 buf[pos++] = val & 127 | 128;\r
34220 val >>>= 7;\r
34221 }\r
34222 buf[pos] = val;\r
34223}\r
34224\r
34225/**\r
34226 * Constructs a new varint writer operation instance.\r
34227 * @classdesc Scheduled varint writer operation.\r
34228 * @extends Op\r
34229 * @constructor\r
34230 * @param {number} len Value byte length\r
34231 * @param {number} val Value to write\r
34232 * @ignore\r
34233 */\r
34234function VarintOp(len, val) {\r
34235 this.len = len;\r
34236 this.next = undefined;\r
34237 this.val = val;\r
34238}\r
34239\r
34240VarintOp.prototype = Object.create(Op.prototype);\r
34241VarintOp.prototype.fn = writeVarint32;\r
34242\r
34243/**\r
34244 * Writes an unsigned 32 bit value as a varint.\r
34245 * @param {number} value Value to write\r
34246 * @returns {Writer} `this`\r
34247 */\r
34248Writer.prototype.uint32 = function write_uint32(value) {\r
34249 // here, the call to this.push has been inlined and a varint specific Op subclass is used.\r
34250 // uint32 is by far the most frequently used operation and benefits significantly from this.\r
34251 this.len += (this.tail = this.tail.next = new VarintOp(\r
34252 (value = value >>> 0)\r
34253 < 128 ? 1\r
34254 : value < 16384 ? 2\r
34255 : value < 2097152 ? 3\r
34256 : value < 268435456 ? 4\r
34257 : 5,\r
34258 value)).len;\r
34259 return this;\r
34260};\r
34261\r
34262/**\r
34263 * Writes a signed 32 bit value as a varint.\r
34264 * @function\r
34265 * @param {number} value Value to write\r
34266 * @returns {Writer} `this`\r
34267 */\r
34268Writer.prototype.int32 = function write_int32(value) {\r
34269 return value < 0\r
34270 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec\r
34271 : this.uint32(value);\r
34272};\r
34273\r
34274/**\r
34275 * Writes a 32 bit value as a varint, zig-zag encoded.\r
34276 * @param {number} value Value to write\r
34277 * @returns {Writer} `this`\r
34278 */\r
34279Writer.prototype.sint32 = function write_sint32(value) {\r
34280 return this.uint32((value << 1 ^ value >> 31) >>> 0);\r
34281};\r
34282\r
34283function writeVarint64(val, buf, pos) {\r
34284 while (val.hi) {\r
34285 buf[pos++] = val.lo & 127 | 128;\r
34286 val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;\r
34287 val.hi >>>= 7;\r
34288 }\r
34289 while (val.lo > 127) {\r
34290 buf[pos++] = val.lo & 127 | 128;\r
34291 val.lo = val.lo >>> 7;\r
34292 }\r
34293 buf[pos++] = val.lo;\r
34294}\r
34295\r
34296/**\r
34297 * Writes an unsigned 64 bit value as a varint.\r
34298 * @param {Long|number|string} value Value to write\r
34299 * @returns {Writer} `this`\r
34300 * @throws {TypeError} If `value` is a string and no long library is present.\r
34301 */\r
34302Writer.prototype.uint64 = function write_uint64(value) {\r
34303 var bits = LongBits.from(value);\r
34304 return this._push(writeVarint64, bits.length(), bits);\r
34305};\r
34306\r
34307/**\r
34308 * Writes a signed 64 bit value as a varint.\r
34309 * @function\r
34310 * @param {Long|number|string} value Value to write\r
34311 * @returns {Writer} `this`\r
34312 * @throws {TypeError} If `value` is a string and no long library is present.\r
34313 */\r
34314Writer.prototype.int64 = Writer.prototype.uint64;\r
34315\r
34316/**\r
34317 * Writes a signed 64 bit value as a varint, zig-zag encoded.\r
34318 * @param {Long|number|string} value Value to write\r
34319 * @returns {Writer} `this`\r
34320 * @throws {TypeError} If `value` is a string and no long library is present.\r
34321 */\r
34322Writer.prototype.sint64 = function write_sint64(value) {\r
34323 var bits = LongBits.from(value).zzEncode();\r
34324 return this._push(writeVarint64, bits.length(), bits);\r
34325};\r
34326\r
34327/**\r
34328 * Writes a boolish value as a varint.\r
34329 * @param {boolean} value Value to write\r
34330 * @returns {Writer} `this`\r
34331 */\r
34332Writer.prototype.bool = function write_bool(value) {\r
34333 return this._push(writeByte, 1, value ? 1 : 0);\r
34334};\r
34335\r
34336function writeFixed32(val, buf, pos) {\r
34337 buf[pos ] = val & 255;\r
34338 buf[pos + 1] = val >>> 8 & 255;\r
34339 buf[pos + 2] = val >>> 16 & 255;\r
34340 buf[pos + 3] = val >>> 24;\r
34341}\r
34342\r
34343/**\r
34344 * Writes an unsigned 32 bit value as fixed 32 bits.\r
34345 * @param {number} value Value to write\r
34346 * @returns {Writer} `this`\r
34347 */\r
34348Writer.prototype.fixed32 = function write_fixed32(value) {\r
34349 return this._push(writeFixed32, 4, value >>> 0);\r
34350};\r
34351\r
34352/**\r
34353 * Writes a signed 32 bit value as fixed 32 bits.\r
34354 * @function\r
34355 * @param {number} value Value to write\r
34356 * @returns {Writer} `this`\r
34357 */\r
34358Writer.prototype.sfixed32 = Writer.prototype.fixed32;\r
34359\r
34360/**\r
34361 * Writes an unsigned 64 bit value as fixed 64 bits.\r
34362 * @param {Long|number|string} value Value to write\r
34363 * @returns {Writer} `this`\r
34364 * @throws {TypeError} If `value` is a string and no long library is present.\r
34365 */\r
34366Writer.prototype.fixed64 = function write_fixed64(value) {\r
34367 var bits = LongBits.from(value);\r
34368 return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);\r
34369};\r
34370\r
34371/**\r
34372 * Writes a signed 64 bit value as fixed 64 bits.\r
34373 * @function\r
34374 * @param {Long|number|string} value Value to write\r
34375 * @returns {Writer} `this`\r
34376 * @throws {TypeError} If `value` is a string and no long library is present.\r
34377 */\r
34378Writer.prototype.sfixed64 = Writer.prototype.fixed64;\r
34379\r
34380/**\r
34381 * Writes a float (32 bit).\r
34382 * @function\r
34383 * @param {number} value Value to write\r
34384 * @returns {Writer} `this`\r
34385 */\r
34386Writer.prototype.float = function write_float(value) {\r
34387 return this._push(util.float.writeFloatLE, 4, value);\r
34388};\r
34389\r
34390/**\r
34391 * Writes a double (64 bit float).\r
34392 * @function\r
34393 * @param {number} value Value to write\r
34394 * @returns {Writer} `this`\r
34395 */\r
34396Writer.prototype.double = function write_double(value) {\r
34397 return this._push(util.float.writeDoubleLE, 8, value);\r
34398};\r
34399\r
34400var writeBytes = util.Array.prototype.set\r
34401 ? function writeBytes_set(val, buf, pos) {\r
34402 buf.set(val, pos); // also works for plain array values\r
34403 }\r
34404 /* istanbul ignore next */\r
34405 : function writeBytes_for(val, buf, pos) {\r
34406 for (var i = 0; i < val.length; ++i)\r
34407 buf[pos + i] = val[i];\r
34408 };\r
34409\r
34410/**\r
34411 * Writes a sequence of bytes.\r
34412 * @param {Uint8Array|string} value Buffer or base64 encoded string to write\r
34413 * @returns {Writer} `this`\r
34414 */\r
34415Writer.prototype.bytes = function write_bytes(value) {\r
34416 var len = value.length >>> 0;\r
34417 if (!len)\r
34418 return this._push(writeByte, 1, 0);\r
34419 if (util.isString(value)) {\r
34420 var buf = Writer.alloc(len = base64.length(value));\r
34421 base64.decode(value, buf, 0);\r
34422 value = buf;\r
34423 }\r
34424 return this.uint32(len)._push(writeBytes, len, value);\r
34425};\r
34426\r
34427/**\r
34428 * Writes a string.\r
34429 * @param {string} value Value to write\r
34430 * @returns {Writer} `this`\r
34431 */\r
34432Writer.prototype.string = function write_string(value) {\r
34433 var len = utf8.length(value);\r
34434 return len\r
34435 ? this.uint32(len)._push(utf8.write, len, value)\r
34436 : this._push(writeByte, 1, 0);\r
34437};\r
34438\r
34439/**\r
34440 * Forks this writer's state by pushing it to a stack.\r
34441 * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.\r
34442 * @returns {Writer} `this`\r
34443 */\r
34444Writer.prototype.fork = function fork() {\r
34445 this.states = new State(this);\r
34446 this.head = this.tail = new Op(noop, 0, 0);\r
34447 this.len = 0;\r
34448 return this;\r
34449};\r
34450\r
34451/**\r
34452 * Resets this instance to the last state.\r
34453 * @returns {Writer} `this`\r
34454 */\r
34455Writer.prototype.reset = function reset() {\r
34456 if (this.states) {\r
34457 this.head = this.states.head;\r
34458 this.tail = this.states.tail;\r
34459 this.len = this.states.len;\r
34460 this.states = this.states.next;\r
34461 } else {\r
34462 this.head = this.tail = new Op(noop, 0, 0);\r
34463 this.len = 0;\r
34464 }\r
34465 return this;\r
34466};\r
34467\r
34468/**\r
34469 * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.\r
34470 * @returns {Writer} `this`\r
34471 */\r
34472Writer.prototype.ldelim = function ldelim() {\r
34473 var head = this.head,\r
34474 tail = this.tail,\r
34475 len = this.len;\r
34476 this.reset().uint32(len);\r
34477 if (len) {\r
34478 this.tail.next = head.next; // skip noop\r
34479 this.tail = tail;\r
34480 this.len += len;\r
34481 }\r
34482 return this;\r
34483};\r
34484\r
34485/**\r
34486 * Finishes the write operation.\r
34487 * @returns {Uint8Array} Finished buffer\r
34488 */\r
34489Writer.prototype.finish = function finish() {\r
34490 var head = this.head.next, // skip noop\r
34491 buf = this.constructor.alloc(this.len),\r
34492 pos = 0;\r
34493 while (head) {\r
34494 head.fn(head.val, buf, pos);\r
34495 pos += head.len;\r
34496 head = head.next;\r
34497 }\r
34498 // this.head = this.tail = null;\r
34499 return buf;\r
34500};\r
34501\r
34502Writer._configure = function(BufferWriter_) {\r
34503 BufferWriter = BufferWriter_;\r
34504};\r
34505
34506},{"./util/minimal":220}],224:[function(require,module,exports){
34507"use strict";\r
34508module.exports = BufferWriter;\r
34509\r
34510// extends Writer\r
34511var Writer = require("./writer");\r
34512(BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;\r
34513\r
34514var util = require("./util/minimal");\r
34515\r
34516var Buffer = util.Buffer;\r
34517\r
34518/**\r
34519 * Constructs a new buffer writer instance.\r
34520 * @classdesc Wire format writer using node buffers.\r
34521 * @extends Writer\r
34522 * @constructor\r
34523 */\r
34524function BufferWriter() {\r
34525 Writer.call(this);\r
34526}\r
34527\r
34528/**\r
34529 * Allocates a buffer of the specified size.\r
34530 * @param {number} size Buffer size\r
34531 * @returns {Buffer} Buffer\r
34532 */\r
34533BufferWriter.alloc = function alloc_buffer(size) {\r
34534 return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size);\r
34535};\r
34536\r
34537var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set"\r
34538 ? function writeBytesBuffer_set(val, buf, pos) {\r
34539 buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)\r
34540 // also works for plain array values\r
34541 }\r
34542 /* istanbul ignore next */\r
34543 : function writeBytesBuffer_copy(val, buf, pos) {\r
34544 if (val.copy) // Buffer values\r
34545 val.copy(buf, pos, 0, val.length);\r
34546 else for (var i = 0; i < val.length;) // plain array values\r
34547 buf[pos++] = val[i++];\r
34548 };\r
34549\r
34550/**\r
34551 * @override\r
34552 */\r
34553BufferWriter.prototype.bytes = function write_bytes_buffer(value) {\r
34554 if (util.isString(value))\r
34555 value = util._Buffer_from(value, "base64");\r
34556 var len = value.length >>> 0;\r
34557 this.uint32(len);\r
34558 if (len)\r
34559 this._push(writeBytesBuffer, len, value);\r
34560 return this;\r
34561};\r
34562\r
34563function writeStringBuffer(val, buf, pos) {\r
34564 if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)\r
34565 util.utf8.write(val, buf, pos);\r
34566 else\r
34567 buf.utf8Write(val, pos);\r
34568}\r
34569\r
34570/**\r
34571 * @override\r
34572 */\r
34573BufferWriter.prototype.string = function write_string_buffer(value) {\r
34574 var len = Buffer.byteLength(value);\r
34575 this.uint32(len);\r
34576 if (len)\r
34577 this._push(writeStringBuffer, len, value);\r
34578 return this;\r
34579};\r
34580\r
34581\r
34582/**\r
34583 * Finishes the write operation.\r
34584 * @name BufferWriter#finish\r
34585 * @function\r
34586 * @returns {Buffer} Finished buffer\r
34587 */\r
34588
34589},{"./util/minimal":220,"./writer":223}],225:[function(require,module,exports){
34590exports.publicEncrypt = require('./publicEncrypt');
34591exports.privateDecrypt = require('./privateDecrypt');
34592
34593exports.privateEncrypt = function privateEncrypt(key, buf) {
34594 return exports.publicEncrypt(key, buf, true);
34595};
34596
34597exports.publicDecrypt = function publicDecrypt(key, buf) {
34598 return exports.privateDecrypt(key, buf, true);
34599};
34600},{"./privateDecrypt":227,"./publicEncrypt":228}],226:[function(require,module,exports){
34601(function (Buffer){
34602var createHash = require('create-hash');
34603module.exports = function (seed, len) {
34604 var t = new Buffer('');
34605 var i = 0, c;
34606 while (t.length < len) {
34607 c = i2ops(i++);
34608 t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]);
34609 }
34610 return t.slice(0, len);
34611};
34612
34613function i2ops(c) {
34614 var out = new Buffer(4);
34615 out.writeUInt32BE(c,0);
34616 return out;
34617}
34618}).call(this,require("buffer").Buffer)
34619},{"buffer":107,"create-hash":111}],227:[function(require,module,exports){
34620(function (Buffer){
34621var parseKeys = require('parse-asn1');
34622var mgf = require('./mgf');
34623var xor = require('./xor');
34624var bn = require('bn.js');
34625var crt = require('browserify-rsa');
34626var createHash = require('create-hash');
34627var withPublic = require('./withPublic');
34628module.exports = function privateDecrypt(private_key, enc, reverse) {
34629 var padding;
34630 if (private_key.padding) {
34631 padding = private_key.padding;
34632 } else if (reverse) {
34633 padding = 1;
34634 } else {
34635 padding = 4;
34636 }
34637
34638 var key = parseKeys(private_key);
34639 var k = key.modulus.byteLength();
34640 if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) {
34641 throw new Error('decryption error');
34642 }
34643 var msg;
34644 if (reverse) {
34645 msg = withPublic(new bn(enc), key);
34646 } else {
34647 msg = crt(enc, key);
34648 }
34649 var zBuffer = new Buffer(k - msg.length);
34650 zBuffer.fill(0);
34651 msg = Buffer.concat([zBuffer, msg], k);
34652 if (padding === 4) {
34653 return oaep(key, msg);
34654 } else if (padding === 1) {
34655 return pkcs1(key, msg, reverse);
34656 } else if (padding === 3) {
34657 return msg;
34658 } else {
34659 throw new Error('unknown padding');
34660 }
34661};
34662
34663function oaep(key, msg){
34664 var n = key.modulus;
34665 var k = key.modulus.byteLength();
34666 var mLen = msg.length;
34667 var iHash = createHash('sha1').update(new Buffer('')).digest();
34668 var hLen = iHash.length;
34669 var hLen2 = 2 * hLen;
34670 if (msg[0] !== 0) {
34671 throw new Error('decryption error');
34672 }
34673 var maskedSeed = msg.slice(1, hLen + 1);
34674 var maskedDb = msg.slice(hLen + 1);
34675 var seed = xor(maskedSeed, mgf(maskedDb, hLen));
34676 var db = xor(maskedDb, mgf(seed, k - hLen - 1));
34677 if (compare(iHash, db.slice(0, hLen))) {
34678 throw new Error('decryption error');
34679 }
34680 var i = hLen;
34681 while (db[i] === 0) {
34682 i++;
34683 }
34684 if (db[i++] !== 1) {
34685 throw new Error('decryption error');
34686 }
34687 return db.slice(i);
34688}
34689
34690function pkcs1(key, msg, reverse){
34691 var p1 = msg.slice(0, 2);
34692 var i = 2;
34693 var status = 0;
34694 while (msg[i++] !== 0) {
34695 if (i >= msg.length) {
34696 status++;
34697 break;
34698 }
34699 }
34700 var ps = msg.slice(2, i - 1);
34701 var p2 = msg.slice(i - 1, i);
34702
34703 if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){
34704 status++;
34705 }
34706 if (ps.length < 8) {
34707 status++;
34708 }
34709 if (status) {
34710 throw new Error('decryption error');
34711 }
34712 return msg.slice(i);
34713}
34714function compare(a, b){
34715 a = new Buffer(a);
34716 b = new Buffer(b);
34717 var dif = 0;
34718 var len = a.length;
34719 if (a.length !== b.length) {
34720 dif++;
34721 len = Math.min(a.length, b.length);
34722 }
34723 var i = -1;
34724 while (++i < len) {
34725 dif += (a[i] ^ b[i]);
34726 }
34727 return dif;
34728}
34729}).call(this,require("buffer").Buffer)
34730},{"./mgf":226,"./withPublic":229,"./xor":230,"bn.js":75,"browserify-rsa":98,"buffer":107,"create-hash":111,"parse-asn1":182}],228:[function(require,module,exports){
34731(function (Buffer){
34732var parseKeys = require('parse-asn1');
34733var randomBytes = require('randombytes');
34734var createHash = require('create-hash');
34735var mgf = require('./mgf');
34736var xor = require('./xor');
34737var bn = require('bn.js');
34738var withPublic = require('./withPublic');
34739var crt = require('browserify-rsa');
34740
34741var constants = {
34742 RSA_PKCS1_OAEP_PADDING: 4,
34743 RSA_PKCS1_PADDIN: 1,
34744 RSA_NO_PADDING: 3
34745};
34746
34747module.exports = function publicEncrypt(public_key, msg, reverse) {
34748 var padding;
34749 if (public_key.padding) {
34750 padding = public_key.padding;
34751 } else if (reverse) {
34752 padding = 1;
34753 } else {
34754 padding = 4;
34755 }
34756 var key = parseKeys(public_key);
34757 var paddedMsg;
34758 if (padding === 4) {
34759 paddedMsg = oaep(key, msg);
34760 } else if (padding === 1) {
34761 paddedMsg = pkcs1(key, msg, reverse);
34762 } else if (padding === 3) {
34763 paddedMsg = new bn(msg);
34764 if (paddedMsg.cmp(key.modulus) >= 0) {
34765 throw new Error('data too long for modulus');
34766 }
34767 } else {
34768 throw new Error('unknown padding');
34769 }
34770 if (reverse) {
34771 return crt(paddedMsg, key);
34772 } else {
34773 return withPublic(paddedMsg, key);
34774 }
34775};
34776
34777function oaep(key, msg){
34778 var k = key.modulus.byteLength();
34779 var mLen = msg.length;
34780 var iHash = createHash('sha1').update(new Buffer('')).digest();
34781 var hLen = iHash.length;
34782 var hLen2 = 2 * hLen;
34783 if (mLen > k - hLen2 - 2) {
34784 throw new Error('message too long');
34785 }
34786 var ps = new Buffer(k - mLen - hLen2 - 2);
34787 ps.fill(0);
34788 var dblen = k - hLen - 1;
34789 var seed = randomBytes(hLen);
34790 var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen));
34791 var maskedSeed = xor(seed, mgf(maskedDb, hLen));
34792 return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k));
34793}
34794function pkcs1(key, msg, reverse){
34795 var mLen = msg.length;
34796 var k = key.modulus.byteLength();
34797 if (mLen > k - 11) {
34798 throw new Error('message too long');
34799 }
34800 var ps;
34801 if (reverse) {
34802 ps = new Buffer(k - mLen - 3);
34803 ps.fill(0xff);
34804 } else {
34805 ps = nonZero(k - mLen - 3);
34806 }
34807 return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k));
34808}
34809function nonZero(len, crypto) {
34810 var out = new Buffer(len);
34811 var i = 0;
34812 var cache = randomBytes(len*2);
34813 var cur = 0;
34814 var num;
34815 while (i < len) {
34816 if (cur === cache.length) {
34817 cache = randomBytes(len*2);
34818 cur = 0;
34819 }
34820 num = cache[cur++];
34821 if (num) {
34822 out[i++] = num;
34823 }
34824 }
34825 return out;
34826}
34827}).call(this,require("buffer").Buffer)
34828},{"./mgf":226,"./withPublic":229,"./xor":230,"bn.js":75,"browserify-rsa":98,"buffer":107,"create-hash":111,"parse-asn1":182,"randombytes":231}],229:[function(require,module,exports){
34829(function (Buffer){
34830var bn = require('bn.js');
34831function withPublic(paddedMsg, key) {
34832 return new Buffer(paddedMsg
34833 .toRed(bn.mont(key.modulus))
34834 .redPow(new bn(key.publicExponent))
34835 .fromRed()
34836 .toArray());
34837}
34838
34839module.exports = withPublic;
34840}).call(this,require("buffer").Buffer)
34841},{"bn.js":75,"buffer":107}],230:[function(require,module,exports){
34842module.exports = function xor(a, b) {
34843 var len = a.length;
34844 var i = -1;
34845 while (++i < len) {
34846 a[i] ^= b[i];
34847 }
34848 return a
34849};
34850},{}],231:[function(require,module,exports){
34851(function (process,global){
34852'use strict'
34853
34854function oldBrowser () {
34855 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
34856}
34857
34858var Buffer = require('safe-buffer').Buffer
34859var crypto = global.crypto || global.msCrypto
34860
34861if (crypto && crypto.getRandomValues) {
34862 module.exports = randomBytes
34863} else {
34864 module.exports = oldBrowser
34865}
34866
34867function randomBytes (size, cb) {
34868 // phantomjs needs to throw
34869 if (size > 65536) throw new Error('requested too many random bytes')
34870 // in case browserify isn't using the Uint8Array version
34871 var rawBytes = new global.Uint8Array(size)
34872
34873 // This will not work in older browsers.
34874 // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues
34875 if (size > 0) { // getRandomValues fails on IE if size == 0
34876 crypto.getRandomValues(rawBytes)
34877 }
34878
34879 // XXX: phantomjs doesn't like a buffer being passed here
34880 var bytes = Buffer.from(rawBytes.buffer)
34881
34882 if (typeof cb === 'function') {
34883 return process.nextTick(function () {
34884 cb(null, bytes)
34885 })
34886 }
34887
34888 return bytes
34889}
34890
34891}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
34892},{"_process":190,"safe-buffer":247}],232:[function(require,module,exports){
34893(function (process,global){
34894'use strict'
34895
34896function oldBrowser () {
34897 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
34898}
34899var safeBuffer = require('safe-buffer')
34900var randombytes = require('randombytes')
34901var Buffer = safeBuffer.Buffer
34902var kBufferMaxLength = safeBuffer.kMaxLength
34903var crypto = global.crypto || global.msCrypto
34904var kMaxUint32 = Math.pow(2, 32) - 1
34905function assertOffset (offset, length) {
34906 if (typeof offset !== 'number' || offset !== offset) { // eslint-disable-line no-self-compare
34907 throw new TypeError('offset must be a number')
34908 }
34909
34910 if (offset > kMaxUint32 || offset < 0) {
34911 throw new TypeError('offset must be a uint32')
34912 }
34913
34914 if (offset > kBufferMaxLength || offset > length) {
34915 throw new RangeError('offset out of range')
34916 }
34917}
34918
34919function assertSize (size, offset, length) {
34920 if (typeof size !== 'number' || size !== size) { // eslint-disable-line no-self-compare
34921 throw new TypeError('size must be a number')
34922 }
34923
34924 if (size > kMaxUint32 || size < 0) {
34925 throw new TypeError('size must be a uint32')
34926 }
34927
34928 if (size + offset > length || size > kBufferMaxLength) {
34929 throw new RangeError('buffer too small')
34930 }
34931}
34932if ((crypto && crypto.getRandomValues) || !process.browser) {
34933 exports.randomFill = randomFill
34934 exports.randomFillSync = randomFillSync
34935} else {
34936 exports.randomFill = oldBrowser
34937 exports.randomFillSync = oldBrowser
34938}
34939function randomFill (buf, offset, size, cb) {
34940 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
34941 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
34942 }
34943
34944 if (typeof offset === 'function') {
34945 cb = offset
34946 offset = 0
34947 size = buf.length
34948 } else if (typeof size === 'function') {
34949 cb = size
34950 size = buf.length - offset
34951 } else if (typeof cb !== 'function') {
34952 throw new TypeError('"cb" argument must be a function')
34953 }
34954 assertOffset(offset, buf.length)
34955 assertSize(size, offset, buf.length)
34956 return actualFill(buf, offset, size, cb)
34957}
34958
34959function actualFill (buf, offset, size, cb) {
34960 if (process.browser) {
34961 var ourBuf = buf.buffer
34962 var uint = new Uint8Array(ourBuf, offset, size)
34963 crypto.getRandomValues(uint)
34964 if (cb) {
34965 process.nextTick(function () {
34966 cb(null, buf)
34967 })
34968 return
34969 }
34970 return buf
34971 }
34972 if (cb) {
34973 randombytes(size, function (err, bytes) {
34974 if (err) {
34975 return cb(err)
34976 }
34977 bytes.copy(buf, offset)
34978 cb(null, buf)
34979 })
34980 return
34981 }
34982 var bytes = randombytes(size)
34983 bytes.copy(buf, offset)
34984 return buf
34985}
34986function randomFillSync (buf, offset, size) {
34987 if (typeof offset === 'undefined') {
34988 offset = 0
34989 }
34990 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
34991 throw new TypeError('"buf" argument must be a Buffer or Uint8Array')
34992 }
34993
34994 assertOffset(offset, buf.length)
34995
34996 if (size === undefined) size = buf.length - offset
34997
34998 assertSize(size, offset, buf.length)
34999
35000 return actualFill(buf, offset, size)
35001}
35002
35003}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
35004},{"_process":190,"randombytes":231,"safe-buffer":247}],233:[function(require,module,exports){
35005module.exports = require('./lib/_stream_duplex.js');
35006
35007},{"./lib/_stream_duplex.js":234}],234:[function(require,module,exports){
35008// Copyright Joyent, Inc. and other Node contributors.
35009//
35010// Permission is hereby granted, free of charge, to any person obtaining a
35011// copy of this software and associated documentation files (the
35012// "Software"), to deal in the Software without restriction, including
35013// without limitation the rights to use, copy, modify, merge, publish,
35014// distribute, sublicense, and/or sell copies of the Software, and to permit
35015// persons to whom the Software is furnished to do so, subject to the
35016// following conditions:
35017//
35018// The above copyright notice and this permission notice shall be included
35019// in all copies or substantial portions of the Software.
35020//
35021// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
35022// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
35023// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
35024// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
35025// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
35026// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
35027// USE OR OTHER DEALINGS IN THE SOFTWARE.
35028
35029// a duplex stream is just a stream that is both readable and writable.
35030// Since JS doesn't have multiple prototypal inheritance, this class
35031// prototypally inherits from Readable, and then parasitically from
35032// Writable.
35033
35034'use strict';
35035
35036/*<replacement>*/
35037
35038var processNextTick = require('process-nextick-args');
35039/*</replacement>*/
35040
35041/*<replacement>*/
35042var objectKeys = Object.keys || function (obj) {
35043 var keys = [];
35044 for (var key in obj) {
35045 keys.push(key);
35046 }return keys;
35047};
35048/*</replacement>*/
35049
35050module.exports = Duplex;
35051
35052/*<replacement>*/
35053var util = require('core-util-is');
35054util.inherits = require('inherits');
35055/*</replacement>*/
35056
35057var Readable = require('./_stream_readable');
35058var Writable = require('./_stream_writable');
35059
35060util.inherits(Duplex, Readable);
35061
35062var keys = objectKeys(Writable.prototype);
35063for (var v = 0; v < keys.length; v++) {
35064 var method = keys[v];
35065 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
35066}
35067
35068function Duplex(options) {
35069 if (!(this instanceof Duplex)) return new Duplex(options);
35070
35071 Readable.call(this, options);
35072 Writable.call(this, options);
35073
35074 if (options && options.readable === false) this.readable = false;
35075
35076 if (options && options.writable === false) this.writable = false;
35077
35078 this.allowHalfOpen = true;
35079 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
35080
35081 this.once('end', onend);
35082}
35083
35084// the no-half-open enforcer
35085function onend() {
35086 // if we allow half-open state, or if the writable side ended,
35087 // then we're ok.
35088 if (this.allowHalfOpen || this._writableState.ended) return;
35089
35090 // no more data can be written.
35091 // But allow more writes to happen in this tick.
35092 processNextTick(onEndNT, this);
35093}
35094
35095function onEndNT(self) {
35096 self.end();
35097}
35098
35099Object.defineProperty(Duplex.prototype, 'destroyed', {
35100 get: function () {
35101 if (this._readableState === undefined || this._writableState === undefined) {
35102 return false;
35103 }
35104 return this._readableState.destroyed && this._writableState.destroyed;
35105 },
35106 set: function (value) {
35107 // we ignore the value if the stream
35108 // has not been initialized yet
35109 if (this._readableState === undefined || this._writableState === undefined) {
35110 return;
35111 }
35112
35113 // backward compatibility, the user is explicitly
35114 // managing destroyed
35115 this._readableState.destroyed = value;
35116 this._writableState.destroyed = value;
35117 }
35118});
35119
35120Duplex.prototype._destroy = function (err, cb) {
35121 this.push(null);
35122 this.end();
35123
35124 processNextTick(cb, err);
35125};
35126
35127function forEach(xs, f) {
35128 for (var i = 0, l = xs.length; i < l; i++) {
35129 f(xs[i], i);
35130 }
35131}
35132},{"./_stream_readable":236,"./_stream_writable":238,"core-util-is":109,"inherits":163,"process-nextick-args":189}],235:[function(require,module,exports){
35133// Copyright Joyent, Inc. and other Node contributors.
35134//
35135// Permission is hereby granted, free of charge, to any person obtaining a
35136// copy of this software and associated documentation files (the
35137// "Software"), to deal in the Software without restriction, including
35138// without limitation the rights to use, copy, modify, merge, publish,
35139// distribute, sublicense, and/or sell copies of the Software, and to permit
35140// persons to whom the Software is furnished to do so, subject to the
35141// following conditions:
35142//
35143// The above copyright notice and this permission notice shall be included
35144// in all copies or substantial portions of the Software.
35145//
35146// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
35147// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
35148// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
35149// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
35150// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
35151// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
35152// USE OR OTHER DEALINGS IN THE SOFTWARE.
35153
35154// a passthrough stream.
35155// basically just the most minimal sort of Transform stream.
35156// Every written chunk gets output as-is.
35157
35158'use strict';
35159
35160module.exports = PassThrough;
35161
35162var Transform = require('./_stream_transform');
35163
35164/*<replacement>*/
35165var util = require('core-util-is');
35166util.inherits = require('inherits');
35167/*</replacement>*/
35168
35169util.inherits(PassThrough, Transform);
35170
35171function PassThrough(options) {
35172 if (!(this instanceof PassThrough)) return new PassThrough(options);
35173
35174 Transform.call(this, options);
35175}
35176
35177PassThrough.prototype._transform = function (chunk, encoding, cb) {
35178 cb(null, chunk);
35179};
35180},{"./_stream_transform":237,"core-util-is":109,"inherits":163}],236:[function(require,module,exports){
35181(function (process,global){
35182// Copyright Joyent, Inc. and other Node contributors.
35183//
35184// Permission is hereby granted, free of charge, to any person obtaining a
35185// copy of this software and associated documentation files (the
35186// "Software"), to deal in the Software without restriction, including
35187// without limitation the rights to use, copy, modify, merge, publish,
35188// distribute, sublicense, and/or sell copies of the Software, and to permit
35189// persons to whom the Software is furnished to do so, subject to the
35190// following conditions:
35191//
35192// The above copyright notice and this permission notice shall be included
35193// in all copies or substantial portions of the Software.
35194//
35195// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
35196// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
35197// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
35198// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
35199// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
35200// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
35201// USE OR OTHER DEALINGS IN THE SOFTWARE.
35202
35203'use strict';
35204
35205/*<replacement>*/
35206
35207var processNextTick = require('process-nextick-args');
35208/*</replacement>*/
35209
35210module.exports = Readable;
35211
35212/*<replacement>*/
35213var isArray = require('isarray');
35214/*</replacement>*/
35215
35216/*<replacement>*/
35217var Duplex;
35218/*</replacement>*/
35219
35220Readable.ReadableState = ReadableState;
35221
35222/*<replacement>*/
35223var EE = require('events').EventEmitter;
35224
35225var EElistenerCount = function (emitter, type) {
35226 return emitter.listeners(type).length;
35227};
35228/*</replacement>*/
35229
35230/*<replacement>*/
35231var Stream = require('./internal/streams/stream');
35232/*</replacement>*/
35233
35234// TODO(bmeurer): Change this back to const once hole checks are
35235// properly optimized away early in Ignition+TurboFan.
35236/*<replacement>*/
35237var Buffer = require('safe-buffer').Buffer;
35238var OurUint8Array = global.Uint8Array || function () {};
35239function _uint8ArrayToBuffer(chunk) {
35240 return Buffer.from(chunk);
35241}
35242function _isUint8Array(obj) {
35243 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
35244}
35245/*</replacement>*/
35246
35247/*<replacement>*/
35248var util = require('core-util-is');
35249util.inherits = require('inherits');
35250/*</replacement>*/
35251
35252/*<replacement>*/
35253var debugUtil = require('util');
35254var debug = void 0;
35255if (debugUtil && debugUtil.debuglog) {
35256 debug = debugUtil.debuglog('stream');
35257} else {
35258 debug = function () {};
35259}
35260/*</replacement>*/
35261
35262var BufferList = require('./internal/streams/BufferList');
35263var destroyImpl = require('./internal/streams/destroy');
35264var StringDecoder;
35265
35266util.inherits(Readable, Stream);
35267
35268var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
35269
35270function prependListener(emitter, event, fn) {
35271 // Sadly this is not cacheable as some libraries bundle their own
35272 // event emitter implementation with them.
35273 if (typeof emitter.prependListener === 'function') {
35274 return emitter.prependListener(event, fn);
35275 } else {
35276 // This is a hack to make sure that our error handler is attached before any
35277 // userland ones. NEVER DO THIS. This is here only because this code needs
35278 // to continue to work with older versions of Node.js that do not include
35279 // the prependListener() method. The goal is to eventually remove this hack.
35280 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]];
35281 }
35282}
35283
35284function ReadableState(options, stream) {
35285 Duplex = Duplex || require('./_stream_duplex');
35286
35287 options = options || {};
35288
35289 // object stream flag. Used to make read(n) ignore n and to
35290 // make all the buffer merging and length checks go away
35291 this.objectMode = !!options.objectMode;
35292
35293 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
35294
35295 // the point at which it stops calling _read() to fill the buffer
35296 // Note: 0 is a valid value, means "don't call _read preemptively ever"
35297 var hwm = options.highWaterMark;
35298 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
35299 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
35300
35301 // cast to ints.
35302 this.highWaterMark = Math.floor(this.highWaterMark);
35303
35304 // A linked list is used to store data chunks instead of an array because the
35305 // linked list can remove elements from the beginning faster than
35306 // array.shift()
35307 this.buffer = new BufferList();
35308 this.length = 0;
35309 this.pipes = null;
35310 this.pipesCount = 0;
35311 this.flowing = null;
35312 this.ended = false;
35313 this.endEmitted = false;
35314 this.reading = false;
35315
35316 // a flag to be able to tell if the event 'readable'/'data' is emitted
35317 // immediately, or on a later tick. We set this to true at first, because
35318 // any actions that shouldn't happen until "later" should generally also
35319 // not happen before the first read call.
35320 this.sync = true;
35321
35322 // whenever we return null, then we set a flag to say
35323 // that we're awaiting a 'readable' event emission.
35324 this.needReadable = false;
35325 this.emittedReadable = false;
35326 this.readableListening = false;
35327 this.resumeScheduled = false;
35328
35329 // has it been destroyed
35330 this.destroyed = false;
35331
35332 // Crypto is kind of old and crusty. Historically, its default string
35333 // encoding is 'binary' so we have to make this configurable.
35334 // Everything else in the universe uses 'utf8', though.
35335 this.defaultEncoding = options.defaultEncoding || 'utf8';
35336
35337 // the number of writers that are awaiting a drain event in .pipe()s
35338 this.awaitDrain = 0;
35339
35340 // if true, a maybeReadMore has been scheduled
35341 this.readingMore = false;
35342
35343 this.decoder = null;
35344 this.encoding = null;
35345 if (options.encoding) {
35346 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
35347 this.decoder = new StringDecoder(options.encoding);
35348 this.encoding = options.encoding;
35349 }
35350}
35351
35352function Readable(options) {
35353 Duplex = Duplex || require('./_stream_duplex');
35354
35355 if (!(this instanceof Readable)) return new Readable(options);
35356
35357 this._readableState = new ReadableState(options, this);
35358
35359 // legacy
35360 this.readable = true;
35361
35362 if (options) {
35363 if (typeof options.read === 'function') this._read = options.read;
35364
35365 if (typeof options.destroy === 'function') this._destroy = options.destroy;
35366 }
35367
35368 Stream.call(this);
35369}
35370
35371Object.defineProperty(Readable.prototype, 'destroyed', {
35372 get: function () {
35373 if (this._readableState === undefined) {
35374 return false;
35375 }
35376 return this._readableState.destroyed;
35377 },
35378 set: function (value) {
35379 // we ignore the value if the stream
35380 // has not been initialized yet
35381 if (!this._readableState) {
35382 return;
35383 }
35384
35385 // backward compatibility, the user is explicitly
35386 // managing destroyed
35387 this._readableState.destroyed = value;
35388 }
35389});
35390
35391Readable.prototype.destroy = destroyImpl.destroy;
35392Readable.prototype._undestroy = destroyImpl.undestroy;
35393Readable.prototype._destroy = function (err, cb) {
35394 this.push(null);
35395 cb(err);
35396};
35397
35398// Manually shove something into the read() buffer.
35399// This returns true if the highWaterMark has not been hit yet,
35400// similar to how Writable.write() returns true if you should
35401// write() some more.
35402Readable.prototype.push = function (chunk, encoding) {
35403 var state = this._readableState;
35404 var skipChunkCheck;
35405
35406 if (!state.objectMode) {
35407 if (typeof chunk === 'string') {
35408 encoding = encoding || state.defaultEncoding;
35409 if (encoding !== state.encoding) {
35410 chunk = Buffer.from(chunk, encoding);
35411 encoding = '';
35412 }
35413 skipChunkCheck = true;
35414 }
35415 } else {
35416 skipChunkCheck = true;
35417 }
35418
35419 return readableAddChunk(this, chunk, encoding, false, skipChunkCheck);
35420};
35421
35422// Unshift should *always* be something directly out of read()
35423Readable.prototype.unshift = function (chunk) {
35424 return readableAddChunk(this, chunk, null, true, false);
35425};
35426
35427function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) {
35428 var state = stream._readableState;
35429 if (chunk === null) {
35430 state.reading = false;
35431 onEofChunk(stream, state);
35432 } else {
35433 var er;
35434 if (!skipChunkCheck) er = chunkInvalid(state, chunk);
35435 if (er) {
35436 stream.emit('error', er);
35437 } else if (state.objectMode || chunk && chunk.length > 0) {
35438 if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) {
35439 chunk = _uint8ArrayToBuffer(chunk);
35440 }
35441
35442 if (addToFront) {
35443 if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true);
35444 } else if (state.ended) {
35445 stream.emit('error', new Error('stream.push() after EOF'));
35446 } else {
35447 state.reading = false;
35448 if (state.decoder && !encoding) {
35449 chunk = state.decoder.write(chunk);
35450 if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state);
35451 } else {
35452 addChunk(stream, state, chunk, false);
35453 }
35454 }
35455 } else if (!addToFront) {
35456 state.reading = false;
35457 }
35458 }
35459
35460 return needMoreData(state);
35461}
35462
35463function addChunk(stream, state, chunk, addToFront) {
35464 if (state.flowing && state.length === 0 && !state.sync) {
35465 stream.emit('data', chunk);
35466 stream.read(0);
35467 } else {
35468 // update the buffer info.
35469 state.length += state.objectMode ? 1 : chunk.length;
35470 if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk);
35471
35472 if (state.needReadable) emitReadable(stream);
35473 }
35474 maybeReadMore(stream, state);
35475}
35476
35477function chunkInvalid(state, chunk) {
35478 var er;
35479 if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
35480 er = new TypeError('Invalid non-string/buffer chunk');
35481 }
35482 return er;
35483}
35484
35485// if it's past the high water mark, we can push in some more.
35486// Also, if we have no data yet, we can stand some
35487// more bytes. This is to work around cases where hwm=0,
35488// such as the repl. Also, if the push() triggered a
35489// readable event, and the user called read(largeNumber) such that
35490// needReadable was set, then we ought to push more, so that another
35491// 'readable' event will be triggered.
35492function needMoreData(state) {
35493 return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0);
35494}
35495
35496Readable.prototype.isPaused = function () {
35497 return this._readableState.flowing === false;
35498};
35499
35500// backwards compatibility.
35501Readable.prototype.setEncoding = function (enc) {
35502 if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder;
35503 this._readableState.decoder = new StringDecoder(enc);
35504 this._readableState.encoding = enc;
35505 return this;
35506};
35507
35508// Don't raise the hwm > 8MB
35509var MAX_HWM = 0x800000;
35510function computeNewHighWaterMark(n) {
35511 if (n >= MAX_HWM) {
35512 n = MAX_HWM;
35513 } else {
35514 // Get the next highest power of 2 to prevent increasing hwm excessively in
35515 // tiny amounts
35516 n--;
35517 n |= n >>> 1;
35518 n |= n >>> 2;
35519 n |= n >>> 4;
35520 n |= n >>> 8;
35521 n |= n >>> 16;
35522 n++;
35523 }
35524 return n;
35525}
35526
35527// This function is designed to be inlinable, so please take care when making
35528// changes to the function body.
35529function howMuchToRead(n, state) {
35530 if (n <= 0 || state.length === 0 && state.ended) return 0;
35531 if (state.objectMode) return 1;
35532 if (n !== n) {
35533 // Only flow one buffer at a time
35534 if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length;
35535 }
35536 // If we're asking for more than the current hwm, then raise the hwm.
35537 if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n);
35538 if (n <= state.length) return n;
35539 // Don't have enough
35540 if (!state.ended) {
35541 state.needReadable = true;
35542 return 0;
35543 }
35544 return state.length;
35545}
35546
35547// you can override either this method, or the async _read(n) below.
35548Readable.prototype.read = function (n) {
35549 debug('read', n);
35550 n = parseInt(n, 10);
35551 var state = this._readableState;
35552 var nOrig = n;
35553
35554 if (n !== 0) state.emittedReadable = false;
35555
35556 // if we're doing read(0) to trigger a readable event, but we
35557 // already have a bunch of data in the buffer, then just trigger
35558 // the 'readable' event and move on.
35559 if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) {
35560 debug('read: emitReadable', state.length, state.ended);
35561 if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this);
35562 return null;
35563 }
35564
35565 n = howMuchToRead(n, state);
35566
35567 // if we've ended, and we're now clear, then finish it up.
35568 if (n === 0 && state.ended) {
35569 if (state.length === 0) endReadable(this);
35570 return null;
35571 }
35572
35573 // All the actual chunk generation logic needs to be
35574 // *below* the call to _read. The reason is that in certain
35575 // synthetic stream cases, such as passthrough streams, _read
35576 // may be a completely synchronous operation which may change
35577 // the state of the read buffer, providing enough data when
35578 // before there was *not* enough.
35579 //
35580 // So, the steps are:
35581 // 1. Figure out what the state of things will be after we do
35582 // a read from the buffer.
35583 //
35584 // 2. If that resulting state will trigger a _read, then call _read.
35585 // Note that this may be asynchronous, or synchronous. Yes, it is
35586 // deeply ugly to write APIs this way, but that still doesn't mean
35587 // that the Readable class should behave improperly, as streams are
35588 // designed to be sync/async agnostic.
35589 // Take note if the _read call is sync or async (ie, if the read call
35590 // has returned yet), so that we know whether or not it's safe to emit
35591 // 'readable' etc.
35592 //
35593 // 3. Actually pull the requested chunks out of the buffer and return.
35594
35595 // if we need a readable event, then we need to do some reading.
35596 var doRead = state.needReadable;
35597 debug('need readable', doRead);
35598
35599 // if we currently have less than the highWaterMark, then also read some
35600 if (state.length === 0 || state.length - n < state.highWaterMark) {
35601 doRead = true;
35602 debug('length less than watermark', doRead);
35603 }
35604
35605 // however, if we've ended, then there's no point, and if we're already
35606 // reading, then it's unnecessary.
35607 if (state.ended || state.reading) {
35608 doRead = false;
35609 debug('reading or ended', doRead);
35610 } else if (doRead) {
35611 debug('do read');
35612 state.reading = true;
35613 state.sync = true;
35614 // if the length is currently zero, then we *need* a readable event.
35615 if (state.length === 0) state.needReadable = true;
35616 // call internal read method
35617 this._read(state.highWaterMark);
35618 state.sync = false;
35619 // If _read pushed data synchronously, then `reading` will be false,
35620 // and we need to re-evaluate how much data we can return to the user.
35621 if (!state.reading) n = howMuchToRead(nOrig, state);
35622 }
35623
35624 var ret;
35625 if (n > 0) ret = fromList(n, state);else ret = null;
35626
35627 if (ret === null) {
35628 state.needReadable = true;
35629 n = 0;
35630 } else {
35631 state.length -= n;
35632 }
35633
35634 if (state.length === 0) {
35635 // If we have nothing in the buffer, then we want to know
35636 // as soon as we *do* get something into the buffer.
35637 if (!state.ended) state.needReadable = true;
35638
35639 // If we tried to read() past the EOF, then emit end on the next tick.
35640 if (nOrig !== n && state.ended) endReadable(this);
35641 }
35642
35643 if (ret !== null) this.emit('data', ret);
35644
35645 return ret;
35646};
35647
35648function onEofChunk(stream, state) {
35649 if (state.ended) return;
35650 if (state.decoder) {
35651 var chunk = state.decoder.end();
35652 if (chunk && chunk.length) {
35653 state.buffer.push(chunk);
35654 state.length += state.objectMode ? 1 : chunk.length;
35655 }
35656 }
35657 state.ended = true;
35658
35659 // emit 'readable' now to make sure it gets picked up.
35660 emitReadable(stream);
35661}
35662
35663// Don't emit readable right away in sync mode, because this can trigger
35664// another read() call => stack overflow. This way, it might trigger
35665// a nextTick recursion warning, but that's not so bad.
35666function emitReadable(stream) {
35667 var state = stream._readableState;
35668 state.needReadable = false;
35669 if (!state.emittedReadable) {
35670 debug('emitReadable', state.flowing);
35671 state.emittedReadable = true;
35672 if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream);
35673 }
35674}
35675
35676function emitReadable_(stream) {
35677 debug('emit readable');
35678 stream.emit('readable');
35679 flow(stream);
35680}
35681
35682// at this point, the user has presumably seen the 'readable' event,
35683// and called read() to consume some data. that may have triggered
35684// in turn another _read(n) call, in which case reading = true if
35685// it's in progress.
35686// However, if we're not ended, or reading, and the length < hwm,
35687// then go ahead and try to read some more preemptively.
35688function maybeReadMore(stream, state) {
35689 if (!state.readingMore) {
35690 state.readingMore = true;
35691 processNextTick(maybeReadMore_, stream, state);
35692 }
35693}
35694
35695function maybeReadMore_(stream, state) {
35696 var len = state.length;
35697 while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) {
35698 debug('maybeReadMore read 0');
35699 stream.read(0);
35700 if (len === state.length)
35701 // didn't get any data, stop spinning.
35702 break;else len = state.length;
35703 }
35704 state.readingMore = false;
35705}
35706
35707// abstract method. to be overridden in specific implementation classes.
35708// call cb(er, data) where data is <= n in length.
35709// for virtual (non-string, non-buffer) streams, "length" is somewhat
35710// arbitrary, and perhaps not very meaningful.
35711Readable.prototype._read = function (n) {
35712 this.emit('error', new Error('_read() is not implemented'));
35713};
35714
35715Readable.prototype.pipe = function (dest, pipeOpts) {
35716 var src = this;
35717 var state = this._readableState;
35718
35719 switch (state.pipesCount) {
35720 case 0:
35721 state.pipes = dest;
35722 break;
35723 case 1:
35724 state.pipes = [state.pipes, dest];
35725 break;
35726 default:
35727 state.pipes.push(dest);
35728 break;
35729 }
35730 state.pipesCount += 1;
35731 debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts);
35732
35733 var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr;
35734
35735 var endFn = doEnd ? onend : unpipe;
35736 if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn);
35737
35738 dest.on('unpipe', onunpipe);
35739 function onunpipe(readable, unpipeInfo) {
35740 debug('onunpipe');
35741 if (readable === src) {
35742 if (unpipeInfo && unpipeInfo.hasUnpiped === false) {
35743 unpipeInfo.hasUnpiped = true;
35744 cleanup();
35745 }
35746 }
35747 }
35748
35749 function onend() {
35750 debug('onend');
35751 dest.end();
35752 }
35753
35754 // when the dest drains, it reduces the awaitDrain counter
35755 // on the source. This would be more elegant with a .once()
35756 // handler in flow(), but adding and removing repeatedly is
35757 // too slow.
35758 var ondrain = pipeOnDrain(src);
35759 dest.on('drain', ondrain);
35760
35761 var cleanedUp = false;
35762 function cleanup() {
35763 debug('cleanup');
35764 // cleanup event handlers once the pipe is broken
35765 dest.removeListener('close', onclose);
35766 dest.removeListener('finish', onfinish);
35767 dest.removeListener('drain', ondrain);
35768 dest.removeListener('error', onerror);
35769 dest.removeListener('unpipe', onunpipe);
35770 src.removeListener('end', onend);
35771 src.removeListener('end', unpipe);
35772 src.removeListener('data', ondata);
35773
35774 cleanedUp = true;
35775
35776 // if the reader is waiting for a drain event from this
35777 // specific writer, then it would cause it to never start
35778 // flowing again.
35779 // So, if this is awaiting a drain, then we just call it now.
35780 // If we don't know, then assume that we are waiting for one.
35781 if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain();
35782 }
35783
35784 // If the user pushes more data while we're writing to dest then we'll end up
35785 // in ondata again. However, we only want to increase awaitDrain once because
35786 // dest will only emit one 'drain' event for the multiple writes.
35787 // => Introduce a guard on increasing awaitDrain.
35788 var increasedAwaitDrain = false;
35789 src.on('data', ondata);
35790 function ondata(chunk) {
35791 debug('ondata');
35792 increasedAwaitDrain = false;
35793 var ret = dest.write(chunk);
35794 if (false === ret && !increasedAwaitDrain) {
35795 // If the user unpiped during `dest.write()`, it is possible
35796 // to get stuck in a permanently paused state if that write
35797 // also returned false.
35798 // => Check whether `dest` is still a piping destination.
35799 if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) {
35800 debug('false write response, pause', src._readableState.awaitDrain);
35801 src._readableState.awaitDrain++;
35802 increasedAwaitDrain = true;
35803 }
35804 src.pause();
35805 }
35806 }
35807
35808 // if the dest has an error, then stop piping into it.
35809 // however, don't suppress the throwing behavior for this.
35810 function onerror(er) {
35811 debug('onerror', er);
35812 unpipe();
35813 dest.removeListener('error', onerror);
35814 if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er);
35815 }
35816
35817 // Make sure our error handler is attached before userland ones.
35818 prependListener(dest, 'error', onerror);
35819
35820 // Both close and finish should trigger unpipe, but only once.
35821 function onclose() {
35822 dest.removeListener('finish', onfinish);
35823 unpipe();
35824 }
35825 dest.once('close', onclose);
35826 function onfinish() {
35827 debug('onfinish');
35828 dest.removeListener('close', onclose);
35829 unpipe();
35830 }
35831 dest.once('finish', onfinish);
35832
35833 function unpipe() {
35834 debug('unpipe');
35835 src.unpipe(dest);
35836 }
35837
35838 // tell the dest that it's being piped to
35839 dest.emit('pipe', src);
35840
35841 // start the flow if it hasn't been started already.
35842 if (!state.flowing) {
35843 debug('pipe resume');
35844 src.resume();
35845 }
35846
35847 return dest;
35848};
35849
35850function pipeOnDrain(src) {
35851 return function () {
35852 var state = src._readableState;
35853 debug('pipeOnDrain', state.awaitDrain);
35854 if (state.awaitDrain) state.awaitDrain--;
35855 if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) {
35856 state.flowing = true;
35857 flow(src);
35858 }
35859 };
35860}
35861
35862Readable.prototype.unpipe = function (dest) {
35863 var state = this._readableState;
35864 var unpipeInfo = { hasUnpiped: false };
35865
35866 // if we're not piping anywhere, then do nothing.
35867 if (state.pipesCount === 0) return this;
35868
35869 // just one destination. most common case.
35870 if (state.pipesCount === 1) {
35871 // passed in one, but it's not the right one.
35872 if (dest && dest !== state.pipes) return this;
35873
35874 if (!dest) dest = state.pipes;
35875
35876 // got a match.
35877 state.pipes = null;
35878 state.pipesCount = 0;
35879 state.flowing = false;
35880 if (dest) dest.emit('unpipe', this, unpipeInfo);
35881 return this;
35882 }
35883
35884 // slow case. multiple pipe destinations.
35885
35886 if (!dest) {
35887 // remove all.
35888 var dests = state.pipes;
35889 var len = state.pipesCount;
35890 state.pipes = null;
35891 state.pipesCount = 0;
35892 state.flowing = false;
35893
35894 for (var i = 0; i < len; i++) {
35895 dests[i].emit('unpipe', this, unpipeInfo);
35896 }return this;
35897 }
35898
35899 // try to find the right one.
35900 var index = indexOf(state.pipes, dest);
35901 if (index === -1) return this;
35902
35903 state.pipes.splice(index, 1);
35904 state.pipesCount -= 1;
35905 if (state.pipesCount === 1) state.pipes = state.pipes[0];
35906
35907 dest.emit('unpipe', this, unpipeInfo);
35908
35909 return this;
35910};
35911
35912// set up data events if they are asked for
35913// Ensure readable listeners eventually get something
35914Readable.prototype.on = function (ev, fn) {
35915 var res = Stream.prototype.on.call(this, ev, fn);
35916
35917 if (ev === 'data') {
35918 // Start flowing on next tick if stream isn't explicitly paused
35919 if (this._readableState.flowing !== false) this.resume();
35920 } else if (ev === 'readable') {
35921 var state = this._readableState;
35922 if (!state.endEmitted && !state.readableListening) {
35923 state.readableListening = state.needReadable = true;
35924 state.emittedReadable = false;
35925 if (!state.reading) {
35926 processNextTick(nReadingNextTick, this);
35927 } else if (state.length) {
35928 emitReadable(this);
35929 }
35930 }
35931 }
35932
35933 return res;
35934};
35935Readable.prototype.addListener = Readable.prototype.on;
35936
35937function nReadingNextTick(self) {
35938 debug('readable nexttick read 0');
35939 self.read(0);
35940}
35941
35942// pause() and resume() are remnants of the legacy readable stream API
35943// If the user uses them, then switch into old mode.
35944Readable.prototype.resume = function () {
35945 var state = this._readableState;
35946 if (!state.flowing) {
35947 debug('resume');
35948 state.flowing = true;
35949 resume(this, state);
35950 }
35951 return this;
35952};
35953
35954function resume(stream, state) {
35955 if (!state.resumeScheduled) {
35956 state.resumeScheduled = true;
35957 processNextTick(resume_, stream, state);
35958 }
35959}
35960
35961function resume_(stream, state) {
35962 if (!state.reading) {
35963 debug('resume read 0');
35964 stream.read(0);
35965 }
35966
35967 state.resumeScheduled = false;
35968 state.awaitDrain = 0;
35969 stream.emit('resume');
35970 flow(stream);
35971 if (state.flowing && !state.reading) stream.read(0);
35972}
35973
35974Readable.prototype.pause = function () {
35975 debug('call pause flowing=%j', this._readableState.flowing);
35976 if (false !== this._readableState.flowing) {
35977 debug('pause');
35978 this._readableState.flowing = false;
35979 this.emit('pause');
35980 }
35981 return this;
35982};
35983
35984function flow(stream) {
35985 var state = stream._readableState;
35986 debug('flow', state.flowing);
35987 while (state.flowing && stream.read() !== null) {}
35988}
35989
35990// wrap an old-style stream as the async data source.
35991// This is *not* part of the readable stream interface.
35992// It is an ugly unfortunate mess of history.
35993Readable.prototype.wrap = function (stream) {
35994 var state = this._readableState;
35995 var paused = false;
35996
35997 var self = this;
35998 stream.on('end', function () {
35999 debug('wrapped end');
36000 if (state.decoder && !state.ended) {
36001 var chunk = state.decoder.end();
36002 if (chunk && chunk.length) self.push(chunk);
36003 }
36004
36005 self.push(null);
36006 });
36007
36008 stream.on('data', function (chunk) {
36009 debug('wrapped data');
36010 if (state.decoder) chunk = state.decoder.write(chunk);
36011
36012 // don't skip over falsy values in objectMode
36013 if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return;
36014
36015 var ret = self.push(chunk);
36016 if (!ret) {
36017 paused = true;
36018 stream.pause();
36019 }
36020 });
36021
36022 // proxy all the other methods.
36023 // important when wrapping filters and duplexes.
36024 for (var i in stream) {
36025 if (this[i] === undefined && typeof stream[i] === 'function') {
36026 this[i] = function (method) {
36027 return function () {
36028 return stream[method].apply(stream, arguments);
36029 };
36030 }(i);
36031 }
36032 }
36033
36034 // proxy certain important events.
36035 for (var n = 0; n < kProxyEvents.length; n++) {
36036 stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n]));
36037 }
36038
36039 // when we try to consume some more bytes, simply unpause the
36040 // underlying stream.
36041 self._read = function (n) {
36042 debug('wrapped _read', n);
36043 if (paused) {
36044 paused = false;
36045 stream.resume();
36046 }
36047 };
36048
36049 return self;
36050};
36051
36052// exposed for testing purposes only.
36053Readable._fromList = fromList;
36054
36055// Pluck off n bytes from an array of buffers.
36056// Length is the combined lengths of all the buffers in the list.
36057// This function is designed to be inlinable, so please take care when making
36058// changes to the function body.
36059function fromList(n, state) {
36060 // nothing buffered
36061 if (state.length === 0) return null;
36062
36063 var ret;
36064 if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) {
36065 // read it all, truncate the list
36066 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);
36067 state.buffer.clear();
36068 } else {
36069 // read part of list
36070 ret = fromListPartial(n, state.buffer, state.decoder);
36071 }
36072
36073 return ret;
36074}
36075
36076// Extracts only enough buffered data to satisfy the amount requested.
36077// This function is designed to be inlinable, so please take care when making
36078// changes to the function body.
36079function fromListPartial(n, list, hasStrings) {
36080 var ret;
36081 if (n < list.head.data.length) {
36082 // slice is the same for buffers and strings
36083 ret = list.head.data.slice(0, n);
36084 list.head.data = list.head.data.slice(n);
36085 } else if (n === list.head.data.length) {
36086 // first chunk is a perfect match
36087 ret = list.shift();
36088 } else {
36089 // result spans more than one buffer
36090 ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list);
36091 }
36092 return ret;
36093}
36094
36095// Copies a specified amount of characters from the list of buffered data
36096// chunks.
36097// This function is designed to be inlinable, so please take care when making
36098// changes to the function body.
36099function copyFromBufferString(n, list) {
36100 var p = list.head;
36101 var c = 1;
36102 var ret = p.data;
36103 n -= ret.length;
36104 while (p = p.next) {
36105 var str = p.data;
36106 var nb = n > str.length ? str.length : n;
36107 if (nb === str.length) ret += str;else ret += str.slice(0, n);
36108 n -= nb;
36109 if (n === 0) {
36110 if (nb === str.length) {
36111 ++c;
36112 if (p.next) list.head = p.next;else list.head = list.tail = null;
36113 } else {
36114 list.head = p;
36115 p.data = str.slice(nb);
36116 }
36117 break;
36118 }
36119 ++c;
36120 }
36121 list.length -= c;
36122 return ret;
36123}
36124
36125// Copies a specified amount of bytes from the list of buffered data chunks.
36126// This function is designed to be inlinable, so please take care when making
36127// changes to the function body.
36128function copyFromBuffer(n, list) {
36129 var ret = Buffer.allocUnsafe(n);
36130 var p = list.head;
36131 var c = 1;
36132 p.data.copy(ret);
36133 n -= p.data.length;
36134 while (p = p.next) {
36135 var buf = p.data;
36136 var nb = n > buf.length ? buf.length : n;
36137 buf.copy(ret, ret.length - n, 0, nb);
36138 n -= nb;
36139 if (n === 0) {
36140 if (nb === buf.length) {
36141 ++c;
36142 if (p.next) list.head = p.next;else list.head = list.tail = null;
36143 } else {
36144 list.head = p;
36145 p.data = buf.slice(nb);
36146 }
36147 break;
36148 }
36149 ++c;
36150 }
36151 list.length -= c;
36152 return ret;
36153}
36154
36155function endReadable(stream) {
36156 var state = stream._readableState;
36157
36158 // If we get here before consuming all the bytes, then that is a
36159 // bug in node. Should never happen.
36160 if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream');
36161
36162 if (!state.endEmitted) {
36163 state.ended = true;
36164 processNextTick(endReadableNT, state, stream);
36165 }
36166}
36167
36168function endReadableNT(state, stream) {
36169 // Check that we didn't get one last unshift.
36170 if (!state.endEmitted && state.length === 0) {
36171 state.endEmitted = true;
36172 stream.readable = false;
36173 stream.emit('end');
36174 }
36175}
36176
36177function forEach(xs, f) {
36178 for (var i = 0, l = xs.length; i < l; i++) {
36179 f(xs[i], i);
36180 }
36181}
36182
36183function indexOf(xs, x) {
36184 for (var i = 0, l = xs.length; i < l; i++) {
36185 if (xs[i] === x) return i;
36186 }
36187 return -1;
36188}
36189}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
36190},{"./_stream_duplex":234,"./internal/streams/BufferList":239,"./internal/streams/destroy":240,"./internal/streams/stream":241,"_process":190,"core-util-is":109,"events":143,"inherits":163,"isarray":165,"process-nextick-args":189,"safe-buffer":247,"string_decoder/":264,"util":77}],237:[function(require,module,exports){
36191// Copyright Joyent, Inc. and other Node contributors.
36192//
36193// Permission is hereby granted, free of charge, to any person obtaining a
36194// copy of this software and associated documentation files (the
36195// "Software"), to deal in the Software without restriction, including
36196// without limitation the rights to use, copy, modify, merge, publish,
36197// distribute, sublicense, and/or sell copies of the Software, and to permit
36198// persons to whom the Software is furnished to do so, subject to the
36199// following conditions:
36200//
36201// The above copyright notice and this permission notice shall be included
36202// in all copies or substantial portions of the Software.
36203//
36204// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
36205// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
36206// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
36207// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
36208// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
36209// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
36210// USE OR OTHER DEALINGS IN THE SOFTWARE.
36211
36212// a transform stream is a readable/writable stream where you do
36213// something with the data. Sometimes it's called a "filter",
36214// but that's not a great name for it, since that implies a thing where
36215// some bits pass through, and others are simply ignored. (That would
36216// be a valid example of a transform, of course.)
36217//
36218// While the output is causally related to the input, it's not a
36219// necessarily symmetric or synchronous transformation. For example,
36220// a zlib stream might take multiple plain-text writes(), and then
36221// emit a single compressed chunk some time in the future.
36222//
36223// Here's how this works:
36224//
36225// The Transform stream has all the aspects of the readable and writable
36226// stream classes. When you write(chunk), that calls _write(chunk,cb)
36227// internally, and returns false if there's a lot of pending writes
36228// buffered up. When you call read(), that calls _read(n) until
36229// there's enough pending readable data buffered up.
36230//
36231// In a transform stream, the written data is placed in a buffer. When
36232// _read(n) is called, it transforms the queued up data, calling the
36233// buffered _write cb's as it consumes chunks. If consuming a single
36234// written chunk would result in multiple output chunks, then the first
36235// outputted bit calls the readcb, and subsequent chunks just go into
36236// the read buffer, and will cause it to emit 'readable' if necessary.
36237//
36238// This way, back-pressure is actually determined by the reading side,
36239// since _read has to be called to start processing a new chunk. However,
36240// a pathological inflate type of transform can cause excessive buffering
36241// here. For example, imagine a stream where every byte of input is
36242// interpreted as an integer from 0-255, and then results in that many
36243// bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in
36244// 1kb of data being output. In this case, you could write a very small
36245// amount of input, and end up with a very large amount of output. In
36246// such a pathological inflating mechanism, there'd be no way to tell
36247// the system to stop doing the transform. A single 4MB write could
36248// cause the system to run out of memory.
36249//
36250// However, even in such a pathological case, only a single written chunk
36251// would be consumed, and then the rest would wait (un-transformed) until
36252// the results of the previous transformed chunk were consumed.
36253
36254'use strict';
36255
36256module.exports = Transform;
36257
36258var Duplex = require('./_stream_duplex');
36259
36260/*<replacement>*/
36261var util = require('core-util-is');
36262util.inherits = require('inherits');
36263/*</replacement>*/
36264
36265util.inherits(Transform, Duplex);
36266
36267function TransformState(stream) {
36268 this.afterTransform = function (er, data) {
36269 return afterTransform(stream, er, data);
36270 };
36271
36272 this.needTransform = false;
36273 this.transforming = false;
36274 this.writecb = null;
36275 this.writechunk = null;
36276 this.writeencoding = null;
36277}
36278
36279function afterTransform(stream, er, data) {
36280 var ts = stream._transformState;
36281 ts.transforming = false;
36282
36283 var cb = ts.writecb;
36284
36285 if (!cb) {
36286 return stream.emit('error', new Error('write callback called multiple times'));
36287 }
36288
36289 ts.writechunk = null;
36290 ts.writecb = null;
36291
36292 if (data !== null && data !== undefined) stream.push(data);
36293
36294 cb(er);
36295
36296 var rs = stream._readableState;
36297 rs.reading = false;
36298 if (rs.needReadable || rs.length < rs.highWaterMark) {
36299 stream._read(rs.highWaterMark);
36300 }
36301}
36302
36303function Transform(options) {
36304 if (!(this instanceof Transform)) return new Transform(options);
36305
36306 Duplex.call(this, options);
36307
36308 this._transformState = new TransformState(this);
36309
36310 var stream = this;
36311
36312 // start out asking for a readable event once data is transformed.
36313 this._readableState.needReadable = true;
36314
36315 // we have implemented the _read method, and done the other things
36316 // that Readable wants before the first _read call, so unset the
36317 // sync guard flag.
36318 this._readableState.sync = false;
36319
36320 if (options) {
36321 if (typeof options.transform === 'function') this._transform = options.transform;
36322
36323 if (typeof options.flush === 'function') this._flush = options.flush;
36324 }
36325
36326 // When the writable side finishes, then flush out anything remaining.
36327 this.once('prefinish', function () {
36328 if (typeof this._flush === 'function') this._flush(function (er, data) {
36329 done(stream, er, data);
36330 });else done(stream);
36331 });
36332}
36333
36334Transform.prototype.push = function (chunk, encoding) {
36335 this._transformState.needTransform = false;
36336 return Duplex.prototype.push.call(this, chunk, encoding);
36337};
36338
36339// This is the part where you do stuff!
36340// override this function in implementation classes.
36341// 'chunk' is an input chunk.
36342//
36343// Call `push(newChunk)` to pass along transformed output
36344// to the readable side. You may call 'push' zero or more times.
36345//
36346// Call `cb(err)` when you are done with this chunk. If you pass
36347// an error, then that'll put the hurt on the whole operation. If you
36348// never call cb(), then you'll never get another chunk.
36349Transform.prototype._transform = function (chunk, encoding, cb) {
36350 throw new Error('_transform() is not implemented');
36351};
36352
36353Transform.prototype._write = function (chunk, encoding, cb) {
36354 var ts = this._transformState;
36355 ts.writecb = cb;
36356 ts.writechunk = chunk;
36357 ts.writeencoding = encoding;
36358 if (!ts.transforming) {
36359 var rs = this._readableState;
36360 if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark);
36361 }
36362};
36363
36364// Doesn't matter what the args are here.
36365// _transform does all the work.
36366// That we got here means that the readable side wants more data.
36367Transform.prototype._read = function (n) {
36368 var ts = this._transformState;
36369
36370 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
36371 ts.transforming = true;
36372 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
36373 } else {
36374 // mark that we need a transform, so that any data that comes in
36375 // will get processed, now that we've asked for it.
36376 ts.needTransform = true;
36377 }
36378};
36379
36380Transform.prototype._destroy = function (err, cb) {
36381 var _this = this;
36382
36383 Duplex.prototype._destroy.call(this, err, function (err2) {
36384 cb(err2);
36385 _this.emit('close');
36386 });
36387};
36388
36389function done(stream, er, data) {
36390 if (er) return stream.emit('error', er);
36391
36392 if (data !== null && data !== undefined) stream.push(data);
36393
36394 // if there's nothing in the write buffer, then that means
36395 // that nothing more will ever be provided
36396 var ws = stream._writableState;
36397 var ts = stream._transformState;
36398
36399 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
36400
36401 if (ts.transforming) throw new Error('Calling transform done when still transforming');
36402
36403 return stream.push(null);
36404}
36405},{"./_stream_duplex":234,"core-util-is":109,"inherits":163}],238:[function(require,module,exports){
36406(function (process,global){
36407// Copyright Joyent, Inc. and other Node contributors.
36408//
36409// Permission is hereby granted, free of charge, to any person obtaining a
36410// copy of this software and associated documentation files (the
36411// "Software"), to deal in the Software without restriction, including
36412// without limitation the rights to use, copy, modify, merge, publish,
36413// distribute, sublicense, and/or sell copies of the Software, and to permit
36414// persons to whom the Software is furnished to do so, subject to the
36415// following conditions:
36416//
36417// The above copyright notice and this permission notice shall be included
36418// in all copies or substantial portions of the Software.
36419//
36420// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
36421// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
36422// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
36423// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
36424// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
36425// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
36426// USE OR OTHER DEALINGS IN THE SOFTWARE.
36427
36428// A bit simpler than readable streams.
36429// Implement an async ._write(chunk, encoding, cb), and it'll handle all
36430// the drain event emission and buffering.
36431
36432'use strict';
36433
36434/*<replacement>*/
36435
36436var processNextTick = require('process-nextick-args');
36437/*</replacement>*/
36438
36439module.exports = Writable;
36440
36441/* <replacement> */
36442function WriteReq(chunk, encoding, cb) {
36443 this.chunk = chunk;
36444 this.encoding = encoding;
36445 this.callback = cb;
36446 this.next = null;
36447}
36448
36449// It seems a linked list but it is not
36450// there will be only 2 of these for each stream
36451function CorkedRequest(state) {
36452 var _this = this;
36453
36454 this.next = null;
36455 this.entry = null;
36456 this.finish = function () {
36457 onCorkedFinish(_this, state);
36458 };
36459}
36460/* </replacement> */
36461
36462/*<replacement>*/
36463var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick;
36464/*</replacement>*/
36465
36466/*<replacement>*/
36467var Duplex;
36468/*</replacement>*/
36469
36470Writable.WritableState = WritableState;
36471
36472/*<replacement>*/
36473var util = require('core-util-is');
36474util.inherits = require('inherits');
36475/*</replacement>*/
36476
36477/*<replacement>*/
36478var internalUtil = {
36479 deprecate: require('util-deprecate')
36480};
36481/*</replacement>*/
36482
36483/*<replacement>*/
36484var Stream = require('./internal/streams/stream');
36485/*</replacement>*/
36486
36487/*<replacement>*/
36488var Buffer = require('safe-buffer').Buffer;
36489var OurUint8Array = global.Uint8Array || function () {};
36490function _uint8ArrayToBuffer(chunk) {
36491 return Buffer.from(chunk);
36492}
36493function _isUint8Array(obj) {
36494 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
36495}
36496/*</replacement>*/
36497
36498var destroyImpl = require('./internal/streams/destroy');
36499
36500util.inherits(Writable, Stream);
36501
36502function nop() {}
36503
36504function WritableState(options, stream) {
36505 Duplex = Duplex || require('./_stream_duplex');
36506
36507 options = options || {};
36508
36509 // object stream flag to indicate whether or not this stream
36510 // contains buffers or objects.
36511 this.objectMode = !!options.objectMode;
36512
36513 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
36514
36515 // the point at which write() starts returning false
36516 // Note: 0 is a valid value, means that we always return false if
36517 // the entire buffer is not flushed immediately on write()
36518 var hwm = options.highWaterMark;
36519 var defaultHwm = this.objectMode ? 16 : 16 * 1024;
36520 this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm;
36521
36522 // cast to ints.
36523 this.highWaterMark = Math.floor(this.highWaterMark);
36524
36525 // if _final has been called
36526 this.finalCalled = false;
36527
36528 // drain event flag.
36529 this.needDrain = false;
36530 // at the start of calling end()
36531 this.ending = false;
36532 // when end() has been called, and returned
36533 this.ended = false;
36534 // when 'finish' is emitted
36535 this.finished = false;
36536
36537 // has it been destroyed
36538 this.destroyed = false;
36539
36540 // should we decode strings into buffers before passing to _write?
36541 // this is here so that some node-core streams can optimize string
36542 // handling at a lower level.
36543 var noDecode = options.decodeStrings === false;
36544 this.decodeStrings = !noDecode;
36545
36546 // Crypto is kind of old and crusty. Historically, its default string
36547 // encoding is 'binary' so we have to make this configurable.
36548 // Everything else in the universe uses 'utf8', though.
36549 this.defaultEncoding = options.defaultEncoding || 'utf8';
36550
36551 // not an actual buffer we keep track of, but a measurement
36552 // of how much we're waiting to get pushed to some underlying
36553 // socket or file.
36554 this.length = 0;
36555
36556 // a flag to see when we're in the middle of a write.
36557 this.writing = false;
36558
36559 // when true all writes will be buffered until .uncork() call
36560 this.corked = 0;
36561
36562 // a flag to be able to tell if the onwrite cb is called immediately,
36563 // or on a later tick. We set this to true at first, because any
36564 // actions that shouldn't happen until "later" should generally also
36565 // not happen before the first write call.
36566 this.sync = true;
36567
36568 // a flag to know if we're processing previously buffered items, which
36569 // may call the _write() callback in the same tick, so that we don't
36570 // end up in an overlapped onwrite situation.
36571 this.bufferProcessing = false;
36572
36573 // the callback that's passed to _write(chunk,cb)
36574 this.onwrite = function (er) {
36575 onwrite(stream, er);
36576 };
36577
36578 // the callback that the user supplies to write(chunk,encoding,cb)
36579 this.writecb = null;
36580
36581 // the amount that is being written when _write is called.
36582 this.writelen = 0;
36583
36584 this.bufferedRequest = null;
36585 this.lastBufferedRequest = null;
36586
36587 // number of pending user-supplied write callbacks
36588 // this must be 0 before 'finish' can be emitted
36589 this.pendingcb = 0;
36590
36591 // emit prefinish if the only thing we're waiting for is _write cbs
36592 // This is relevant for synchronous Transform streams
36593 this.prefinished = false;
36594
36595 // True if the error was already emitted and should not be thrown again
36596 this.errorEmitted = false;
36597
36598 // count buffered requests
36599 this.bufferedRequestCount = 0;
36600
36601 // allocate the first CorkedRequest, there is always
36602 // one allocated and free to use, and we maintain at most two
36603 this.corkedRequestsFree = new CorkedRequest(this);
36604}
36605
36606WritableState.prototype.getBuffer = function getBuffer() {
36607 var current = this.bufferedRequest;
36608 var out = [];
36609 while (current) {
36610 out.push(current);
36611 current = current.next;
36612 }
36613 return out;
36614};
36615
36616(function () {
36617 try {
36618 Object.defineProperty(WritableState.prototype, 'buffer', {
36619 get: internalUtil.deprecate(function () {
36620 return this.getBuffer();
36621 }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003')
36622 });
36623 } catch (_) {}
36624})();
36625
36626// Test _writableState for inheritance to account for Duplex streams,
36627// whose prototype chain only points to Readable.
36628var realHasInstance;
36629if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') {
36630 realHasInstance = Function.prototype[Symbol.hasInstance];
36631 Object.defineProperty(Writable, Symbol.hasInstance, {
36632 value: function (object) {
36633 if (realHasInstance.call(this, object)) return true;
36634
36635 return object && object._writableState instanceof WritableState;
36636 }
36637 });
36638} else {
36639 realHasInstance = function (object) {
36640 return object instanceof this;
36641 };
36642}
36643
36644function Writable(options) {
36645 Duplex = Duplex || require('./_stream_duplex');
36646
36647 // Writable ctor is applied to Duplexes, too.
36648 // `realHasInstance` is necessary because using plain `instanceof`
36649 // would return false, as no `_writableState` property is attached.
36650
36651 // Trying to use the custom `instanceof` for Writable here will also break the
36652 // Node.js LazyTransform implementation, which has a non-trivial getter for
36653 // `_writableState` that would lead to infinite recursion.
36654 if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) {
36655 return new Writable(options);
36656 }
36657
36658 this._writableState = new WritableState(options, this);
36659
36660 // legacy.
36661 this.writable = true;
36662
36663 if (options) {
36664 if (typeof options.write === 'function') this._write = options.write;
36665
36666 if (typeof options.writev === 'function') this._writev = options.writev;
36667
36668 if (typeof options.destroy === 'function') this._destroy = options.destroy;
36669
36670 if (typeof options.final === 'function') this._final = options.final;
36671 }
36672
36673 Stream.call(this);
36674}
36675
36676// Otherwise people can pipe Writable streams, which is just wrong.
36677Writable.prototype.pipe = function () {
36678 this.emit('error', new Error('Cannot pipe, not readable'));
36679};
36680
36681function writeAfterEnd(stream, cb) {
36682 var er = new Error('write after end');
36683 // TODO: defer error events consistently everywhere, not just the cb
36684 stream.emit('error', er);
36685 processNextTick(cb, er);
36686}
36687
36688// Checks that a user-supplied chunk is valid, especially for the particular
36689// mode the stream is in. Currently this means that `null` is never accepted
36690// and undefined/non-string values are only allowed in object mode.
36691function validChunk(stream, state, chunk, cb) {
36692 var valid = true;
36693 var er = false;
36694
36695 if (chunk === null) {
36696 er = new TypeError('May not write null values to stream');
36697 } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) {
36698 er = new TypeError('Invalid non-string/buffer chunk');
36699 }
36700 if (er) {
36701 stream.emit('error', er);
36702 processNextTick(cb, er);
36703 valid = false;
36704 }
36705 return valid;
36706}
36707
36708Writable.prototype.write = function (chunk, encoding, cb) {
36709 var state = this._writableState;
36710 var ret = false;
36711 var isBuf = _isUint8Array(chunk) && !state.objectMode;
36712
36713 if (isBuf && !Buffer.isBuffer(chunk)) {
36714 chunk = _uint8ArrayToBuffer(chunk);
36715 }
36716
36717 if (typeof encoding === 'function') {
36718 cb = encoding;
36719 encoding = null;
36720 }
36721
36722 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
36723
36724 if (typeof cb !== 'function') cb = nop;
36725
36726 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
36727 state.pendingcb++;
36728 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
36729 }
36730
36731 return ret;
36732};
36733
36734Writable.prototype.cork = function () {
36735 var state = this._writableState;
36736
36737 state.corked++;
36738};
36739
36740Writable.prototype.uncork = function () {
36741 var state = this._writableState;
36742
36743 if (state.corked) {
36744 state.corked--;
36745
36746 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
36747 }
36748};
36749
36750Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) {
36751 // node::ParseEncoding() requires lower case.
36752 if (typeof encoding === 'string') encoding = encoding.toLowerCase();
36753 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);
36754 this._writableState.defaultEncoding = encoding;
36755 return this;
36756};
36757
36758function decodeChunk(state, chunk, encoding) {
36759 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
36760 chunk = Buffer.from(chunk, encoding);
36761 }
36762 return chunk;
36763}
36764
36765// if we're already writing something, then just put this
36766// in the queue, and wait our turn. Otherwise, call _write
36767// If we return false, then we need a drain event, so set that flag.
36768function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
36769 if (!isBuf) {
36770 var newChunk = decodeChunk(state, chunk, encoding);
36771 if (chunk !== newChunk) {
36772 isBuf = true;
36773 encoding = 'buffer';
36774 chunk = newChunk;
36775 }
36776 }
36777 var len = state.objectMode ? 1 : chunk.length;
36778
36779 state.length += len;
36780
36781 var ret = state.length < state.highWaterMark;
36782 // we must ensure that previous needDrain will not be reset to false.
36783 if (!ret) state.needDrain = true;
36784
36785 if (state.writing || state.corked) {
36786 var last = state.lastBufferedRequest;
36787 state.lastBufferedRequest = {
36788 chunk: chunk,
36789 encoding: encoding,
36790 isBuf: isBuf,
36791 callback: cb,
36792 next: null
36793 };
36794 if (last) {
36795 last.next = state.lastBufferedRequest;
36796 } else {
36797 state.bufferedRequest = state.lastBufferedRequest;
36798 }
36799 state.bufferedRequestCount += 1;
36800 } else {
36801 doWrite(stream, state, false, len, chunk, encoding, cb);
36802 }
36803
36804 return ret;
36805}
36806
36807function doWrite(stream, state, writev, len, chunk, encoding, cb) {
36808 state.writelen = len;
36809 state.writecb = cb;
36810 state.writing = true;
36811 state.sync = true;
36812 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
36813 state.sync = false;
36814}
36815
36816function onwriteError(stream, state, sync, er, cb) {
36817 --state.pendingcb;
36818
36819 if (sync) {
36820 // defer the callback if we are being called synchronously
36821 // to avoid piling up things on the stack
36822 processNextTick(cb, er);
36823 // this can emit finish, and it will always happen
36824 // after error
36825 processNextTick(finishMaybe, stream, state);
36826 stream._writableState.errorEmitted = true;
36827 stream.emit('error', er);
36828 } else {
36829 // the caller expect this to happen before if
36830 // it is async
36831 cb(er);
36832 stream._writableState.errorEmitted = true;
36833 stream.emit('error', er);
36834 // this can emit finish, but finish must
36835 // always follow error
36836 finishMaybe(stream, state);
36837 }
36838}
36839
36840function onwriteStateUpdate(state) {
36841 state.writing = false;
36842 state.writecb = null;
36843 state.length -= state.writelen;
36844 state.writelen = 0;
36845}
36846
36847function onwrite(stream, er) {
36848 var state = stream._writableState;
36849 var sync = state.sync;
36850 var cb = state.writecb;
36851
36852 onwriteStateUpdate(state);
36853
36854 if (er) onwriteError(stream, state, sync, er, cb);else {
36855 // Check if we're actually ready to finish, but don't emit yet
36856 var finished = needFinish(state);
36857
36858 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
36859 clearBuffer(stream, state);
36860 }
36861
36862 if (sync) {
36863 /*<replacement>*/
36864 asyncWrite(afterWrite, stream, state, finished, cb);
36865 /*</replacement>*/
36866 } else {
36867 afterWrite(stream, state, finished, cb);
36868 }
36869 }
36870}
36871
36872function afterWrite(stream, state, finished, cb) {
36873 if (!finished) onwriteDrain(stream, state);
36874 state.pendingcb--;
36875 cb();
36876 finishMaybe(stream, state);
36877}
36878
36879// Must force callback to be called on nextTick, so that we don't
36880// emit 'drain' before the write() consumer gets the 'false' return
36881// value, and has a chance to attach a 'drain' listener.
36882function onwriteDrain(stream, state) {
36883 if (state.length === 0 && state.needDrain) {
36884 state.needDrain = false;
36885 stream.emit('drain');
36886 }
36887}
36888
36889// if there's something in the buffer waiting, then process it
36890function clearBuffer(stream, state) {
36891 state.bufferProcessing = true;
36892 var entry = state.bufferedRequest;
36893
36894 if (stream._writev && entry && entry.next) {
36895 // Fast case, write everything using _writev()
36896 var l = state.bufferedRequestCount;
36897 var buffer = new Array(l);
36898 var holder = state.corkedRequestsFree;
36899 holder.entry = entry;
36900
36901 var count = 0;
36902 var allBuffers = true;
36903 while (entry) {
36904 buffer[count] = entry;
36905 if (!entry.isBuf) allBuffers = false;
36906 entry = entry.next;
36907 count += 1;
36908 }
36909 buffer.allBuffers = allBuffers;
36910
36911 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
36912
36913 // doWrite is almost always async, defer these to save a bit of time
36914 // as the hot path ends with doWrite
36915 state.pendingcb++;
36916 state.lastBufferedRequest = null;
36917 if (holder.next) {
36918 state.corkedRequestsFree = holder.next;
36919 holder.next = null;
36920 } else {
36921 state.corkedRequestsFree = new CorkedRequest(state);
36922 }
36923 } else {
36924 // Slow case, write chunks one-by-one
36925 while (entry) {
36926 var chunk = entry.chunk;
36927 var encoding = entry.encoding;
36928 var cb = entry.callback;
36929 var len = state.objectMode ? 1 : chunk.length;
36930
36931 doWrite(stream, state, false, len, chunk, encoding, cb);
36932 entry = entry.next;
36933 // if we didn't call the onwrite immediately, then
36934 // it means that we need to wait until it does.
36935 // also, that means that the chunk and cb are currently
36936 // being processed, so move the buffer counter past them.
36937 if (state.writing) {
36938 break;
36939 }
36940 }
36941
36942 if (entry === null) state.lastBufferedRequest = null;
36943 }
36944
36945 state.bufferedRequestCount = 0;
36946 state.bufferedRequest = entry;
36947 state.bufferProcessing = false;
36948}
36949
36950Writable.prototype._write = function (chunk, encoding, cb) {
36951 cb(new Error('_write() is not implemented'));
36952};
36953
36954Writable.prototype._writev = null;
36955
36956Writable.prototype.end = function (chunk, encoding, cb) {
36957 var state = this._writableState;
36958
36959 if (typeof chunk === 'function') {
36960 cb = chunk;
36961 chunk = null;
36962 encoding = null;
36963 } else if (typeof encoding === 'function') {
36964 cb = encoding;
36965 encoding = null;
36966 }
36967
36968 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
36969
36970 // .end() fully uncorks
36971 if (state.corked) {
36972 state.corked = 1;
36973 this.uncork();
36974 }
36975
36976 // ignore unnecessary end() calls.
36977 if (!state.ending && !state.finished) endWritable(this, state, cb);
36978};
36979
36980function needFinish(state) {
36981 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
36982}
36983function callFinal(stream, state) {
36984 stream._final(function (err) {
36985 state.pendingcb--;
36986 if (err) {
36987 stream.emit('error', err);
36988 }
36989 state.prefinished = true;
36990 stream.emit('prefinish');
36991 finishMaybe(stream, state);
36992 });
36993}
36994function prefinish(stream, state) {
36995 if (!state.prefinished && !state.finalCalled) {
36996 if (typeof stream._final === 'function') {
36997 state.pendingcb++;
36998 state.finalCalled = true;
36999 processNextTick(callFinal, stream, state);
37000 } else {
37001 state.prefinished = true;
37002 stream.emit('prefinish');
37003 }
37004 }
37005}
37006
37007function finishMaybe(stream, state) {
37008 var need = needFinish(state);
37009 if (need) {
37010 prefinish(stream, state);
37011 if (state.pendingcb === 0) {
37012 state.finished = true;
37013 stream.emit('finish');
37014 }
37015 }
37016 return need;
37017}
37018
37019function endWritable(stream, state, cb) {
37020 state.ending = true;
37021 finishMaybe(stream, state);
37022 if (cb) {
37023 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
37024 }
37025 state.ended = true;
37026 stream.writable = false;
37027}
37028
37029function onCorkedFinish(corkReq, state, err) {
37030 var entry = corkReq.entry;
37031 corkReq.entry = null;
37032 while (entry) {
37033 var cb = entry.callback;
37034 state.pendingcb--;
37035 cb(err);
37036 entry = entry.next;
37037 }
37038 if (state.corkedRequestsFree) {
37039 state.corkedRequestsFree.next = corkReq;
37040 } else {
37041 state.corkedRequestsFree = corkReq;
37042 }
37043}
37044
37045Object.defineProperty(Writable.prototype, 'destroyed', {
37046 get: function () {
37047 if (this._writableState === undefined) {
37048 return false;
37049 }
37050 return this._writableState.destroyed;
37051 },
37052 set: function (value) {
37053 // we ignore the value if the stream
37054 // has not been initialized yet
37055 if (!this._writableState) {
37056 return;
37057 }
37058
37059 // backward compatibility, the user is explicitly
37060 // managing destroyed
37061 this._writableState.destroyed = value;
37062 }
37063});
37064
37065Writable.prototype.destroy = destroyImpl.destroy;
37066Writable.prototype._undestroy = destroyImpl.undestroy;
37067Writable.prototype._destroy = function (err, cb) {
37068 this.end();
37069 cb(err);
37070};
37071}).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
37072},{"./_stream_duplex":234,"./internal/streams/destroy":240,"./internal/streams/stream":241,"_process":190,"core-util-is":109,"inherits":163,"process-nextick-args":189,"safe-buffer":247,"util-deprecate":265}],239:[function(require,module,exports){
37073'use strict';
37074
37075/*<replacement>*/
37076
37077function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
37078
37079var Buffer = require('safe-buffer').Buffer;
37080/*</replacement>*/
37081
37082function copyBuffer(src, target, offset) {
37083 src.copy(target, offset);
37084}
37085
37086module.exports = function () {
37087 function BufferList() {
37088 _classCallCheck(this, BufferList);
37089
37090 this.head = null;
37091 this.tail = null;
37092 this.length = 0;
37093 }
37094
37095 BufferList.prototype.push = function push(v) {
37096 var entry = { data: v, next: null };
37097 if (this.length > 0) this.tail.next = entry;else this.head = entry;
37098 this.tail = entry;
37099 ++this.length;
37100 };
37101
37102 BufferList.prototype.unshift = function unshift(v) {
37103 var entry = { data: v, next: this.head };
37104 if (this.length === 0) this.tail = entry;
37105 this.head = entry;
37106 ++this.length;
37107 };
37108
37109 BufferList.prototype.shift = function shift() {
37110 if (this.length === 0) return;
37111 var ret = this.head.data;
37112 if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next;
37113 --this.length;
37114 return ret;
37115 };
37116
37117 BufferList.prototype.clear = function clear() {
37118 this.head = this.tail = null;
37119 this.length = 0;
37120 };
37121
37122 BufferList.prototype.join = function join(s) {
37123 if (this.length === 0) return '';
37124 var p = this.head;
37125 var ret = '' + p.data;
37126 while (p = p.next) {
37127 ret += s + p.data;
37128 }return ret;
37129 };
37130
37131 BufferList.prototype.concat = function concat(n) {
37132 if (this.length === 0) return Buffer.alloc(0);
37133 if (this.length === 1) return this.head.data;
37134 var ret = Buffer.allocUnsafe(n >>> 0);
37135 var p = this.head;
37136 var i = 0;
37137 while (p) {
37138 copyBuffer(p.data, ret, i);
37139 i += p.data.length;
37140 p = p.next;
37141 }
37142 return ret;
37143 };
37144
37145 return BufferList;
37146}();
37147},{"safe-buffer":247}],240:[function(require,module,exports){
37148'use strict';
37149
37150/*<replacement>*/
37151
37152var processNextTick = require('process-nextick-args');
37153/*</replacement>*/
37154
37155// undocumented cb() API, needed for core, not for public API
37156function destroy(err, cb) {
37157 var _this = this;
37158
37159 var readableDestroyed = this._readableState && this._readableState.destroyed;
37160 var writableDestroyed = this._writableState && this._writableState.destroyed;
37161
37162 if (readableDestroyed || writableDestroyed) {
37163 if (cb) {
37164 cb(err);
37165 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
37166 processNextTick(emitErrorNT, this, err);
37167 }
37168 return;
37169 }
37170
37171 // we set destroyed to true before firing error callbacks in order
37172 // to make it re-entrance safe in case destroy() is called within callbacks
37173
37174 if (this._readableState) {
37175 this._readableState.destroyed = true;
37176 }
37177
37178 // if this is a duplex stream mark the writable part as destroyed as well
37179 if (this._writableState) {
37180 this._writableState.destroyed = true;
37181 }
37182
37183 this._destroy(err || null, function (err) {
37184 if (!cb && err) {
37185 processNextTick(emitErrorNT, _this, err);
37186 if (_this._writableState) {
37187 _this._writableState.errorEmitted = true;
37188 }
37189 } else if (cb) {
37190 cb(err);
37191 }
37192 });
37193}
37194
37195function undestroy() {
37196 if (this._readableState) {
37197 this._readableState.destroyed = false;
37198 this._readableState.reading = false;
37199 this._readableState.ended = false;
37200 this._readableState.endEmitted = false;
37201 }
37202
37203 if (this._writableState) {
37204 this._writableState.destroyed = false;
37205 this._writableState.ended = false;
37206 this._writableState.ending = false;
37207 this._writableState.finished = false;
37208 this._writableState.errorEmitted = false;
37209 }
37210}
37211
37212function emitErrorNT(self, err) {
37213 self.emit('error', err);
37214}
37215
37216module.exports = {
37217 destroy: destroy,
37218 undestroy: undestroy
37219};
37220},{"process-nextick-args":189}],241:[function(require,module,exports){
37221module.exports = require('events').EventEmitter;
37222
37223},{"events":143}],242:[function(require,module,exports){
37224module.exports = require('./readable').PassThrough
37225
37226},{"./readable":243}],243:[function(require,module,exports){
37227exports = module.exports = require('./lib/_stream_readable.js');
37228exports.Stream = exports;
37229exports.Readable = exports;
37230exports.Writable = require('./lib/_stream_writable.js');
37231exports.Duplex = require('./lib/_stream_duplex.js');
37232exports.Transform = require('./lib/_stream_transform.js');
37233exports.PassThrough = require('./lib/_stream_passthrough.js');
37234
37235},{"./lib/_stream_duplex.js":234,"./lib/_stream_passthrough.js":235,"./lib/_stream_readable.js":236,"./lib/_stream_transform.js":237,"./lib/_stream_writable.js":238}],244:[function(require,module,exports){
37236module.exports = require('./readable').Transform
37237
37238},{"./readable":243}],245:[function(require,module,exports){
37239module.exports = require('./lib/_stream_writable.js');
37240
37241},{"./lib/_stream_writable.js":238}],246:[function(require,module,exports){
37242(function (Buffer){
37243'use strict'
37244var inherits = require('inherits')
37245var HashBase = require('hash-base')
37246
37247function RIPEMD160 () {
37248 HashBase.call(this, 64)
37249
37250 // state
37251 this._a = 0x67452301
37252 this._b = 0xefcdab89
37253 this._c = 0x98badcfe
37254 this._d = 0x10325476
37255 this._e = 0xc3d2e1f0
37256}
37257
37258inherits(RIPEMD160, HashBase)
37259
37260RIPEMD160.prototype._update = function () {
37261 var m = new Array(16)
37262 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
37263
37264 var al = this._a
37265 var bl = this._b
37266 var cl = this._c
37267 var dl = this._d
37268 var el = this._e
37269
37270 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
37271 // K = 0x00000000
37272 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8
37273 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10)
37274 el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10)
37275 dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10)
37276 cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10)
37277 bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10)
37278 al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10)
37279 el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10)
37280 dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10)
37281 cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10)
37282 bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10)
37283 al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10)
37284 el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10)
37285 dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10)
37286 cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10)
37287 bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10)
37288 al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10)
37289
37290 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
37291 // K = 0x5a827999
37292 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12
37293 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10)
37294 dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10)
37295 cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10)
37296 bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10)
37297 al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10)
37298 el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10)
37299 dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10)
37300 cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10)
37301 bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10)
37302 al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10)
37303 el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10)
37304 dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10)
37305 cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10)
37306 bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10)
37307 al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10)
37308 el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10)
37309
37310 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
37311 // K = 0x6ed9eba1
37312 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5
37313 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10)
37314 cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10)
37315 bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10)
37316 al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10)
37317 el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10)
37318 dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10)
37319 cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10)
37320 bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10)
37321 al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10)
37322 el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10)
37323 dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10)
37324 cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10)
37325 bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10)
37326 al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10)
37327 el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10)
37328 dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10)
37329
37330 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
37331 // K = 0x8f1bbcdc
37332 // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12
37333 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10)
37334 bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10)
37335 al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10)
37336 el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10)
37337 dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10)
37338 cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10)
37339 bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10)
37340 al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
37341 el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10)
37342 dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10)
37343 cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10)
37344 bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10)
37345 al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10)
37346 el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10)
37347 dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10)
37348 cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10)
37349
37350 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
37351 // K = 0xa953fd4e
37352 // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6
37353 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10)
37354 al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10)
37355 el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10)
37356 dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10)
37357 cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10)
37358 bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10)
37359 al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10)
37360 el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10)
37361 dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10)
37362 cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10)
37363 bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10)
37364 al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10)
37365 el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10)
37366 dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10)
37367 cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10)
37368 bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10)
37369
37370 var ar = this._a
37371 var br = this._b
37372 var cr = this._c
37373 var dr = this._d
37374 var er = this._e
37375
37376 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
37377 // K' = 0x50a28be6
37378 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6
37379 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10)
37380 er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10)
37381 dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10)
37382 cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10)
37383 br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10)
37384 ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10)
37385 er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10)
37386 dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10)
37387 cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10)
37388 br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10)
37389 ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10)
37390 er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10)
37391 dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10)
37392 cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10)
37393 br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10)
37394 ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10)
37395
37396 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
37397 // K' = 0x5c4dd124
37398 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11
37399 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10)
37400 dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10)
37401 cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10)
37402 br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10)
37403 ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10)
37404 er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10)
37405 dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10)
37406 cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10)
37407 br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10)
37408 ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10)
37409 er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10)
37410 dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10)
37411 cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10)
37412 br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10)
37413 ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10)
37414 er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10)
37415
37416 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
37417 // K' = 0x6d703ef3
37418 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5
37419 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10)
37420 cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10)
37421 br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10)
37422 ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10)
37423 er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10)
37424 dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10)
37425 cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10)
37426 br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10)
37427 ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10)
37428 er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10)
37429 dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10)
37430 cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10)
37431 br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10)
37432 ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10)
37433 er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10)
37434 dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10)
37435
37436 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
37437 // K' = 0x7a6d76e9
37438 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8
37439 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10)
37440 br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10)
37441 ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10)
37442 er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10)
37443 dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10)
37444 cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10)
37445 br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10)
37446 ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10)
37447 er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10)
37448 dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10)
37449 cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10)
37450 br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10)
37451 ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10)
37452 er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10)
37453 dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10)
37454 cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10)
37455
37456 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
37457 // K' = 0x00000000
37458 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11
37459 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10)
37460 ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10)
37461 er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10)
37462 dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10)
37463 cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10)
37464 br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10)
37465 ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10)
37466 er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10)
37467 dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10)
37468 cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10)
37469 br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10)
37470 ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10)
37471 er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10)
37472 dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10)
37473 cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10)
37474 br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10)
37475
37476 // change state
37477 var t = (this._b + cl + dr) | 0
37478 this._b = (this._c + dl + er) | 0
37479 this._c = (this._d + el + ar) | 0
37480 this._d = (this._e + al + br) | 0
37481 this._e = (this._a + bl + cr) | 0
37482 this._a = t
37483}
37484
37485RIPEMD160.prototype._digest = function () {
37486 // create padding and handle blocks
37487 this._block[this._blockOffset++] = 0x80
37488 if (this._blockOffset > 56) {
37489 this._block.fill(0, this._blockOffset, 64)
37490 this._update()
37491 this._blockOffset = 0
37492 }
37493
37494 this._block.fill(0, this._blockOffset, 56)
37495 this._block.writeUInt32LE(this._length[0], 56)
37496 this._block.writeUInt32LE(this._length[1], 60)
37497 this._update()
37498
37499 // produce result
37500 var buffer = new Buffer(20)
37501 buffer.writeInt32LE(this._a, 0)
37502 buffer.writeInt32LE(this._b, 4)
37503 buffer.writeInt32LE(this._c, 8)
37504 buffer.writeInt32LE(this._d, 12)
37505 buffer.writeInt32LE(this._e, 16)
37506 return buffer
37507}
37508
37509function rotl (x, n) {
37510 return (x << n) | (x >>> (32 - n))
37511}
37512
37513function fn1 (a, b, c, d, e, m, k, s) {
37514 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
37515}
37516
37517function fn2 (a, b, c, d, e, m, k, s) {
37518 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
37519}
37520
37521function fn3 (a, b, c, d, e, m, k, s) {
37522 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
37523}
37524
37525function fn4 (a, b, c, d, e, m, k, s) {
37526 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
37527}
37528
37529function fn5 (a, b, c, d, e, m, k, s) {
37530 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
37531}
37532
37533module.exports = RIPEMD160
37534
37535}).call(this,require("buffer").Buffer)
37536},{"buffer":107,"hash-base":146,"inherits":163}],247:[function(require,module,exports){
37537/* eslint-disable node/no-deprecated-api */
37538var buffer = require('buffer')
37539var Buffer = buffer.Buffer
37540
37541// alternative to using Object.keys for old browsers
37542function copyProps (src, dst) {
37543 for (var key in src) {
37544 dst[key] = src[key]
37545 }
37546}
37547if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) {
37548 module.exports = buffer
37549} else {
37550 // Copy properties from require('buffer')
37551 copyProps(buffer, exports)
37552 exports.Buffer = SafeBuffer
37553}
37554
37555function SafeBuffer (arg, encodingOrOffset, length) {
37556 return Buffer(arg, encodingOrOffset, length)
37557}
37558
37559// Copy static methods from Buffer
37560copyProps(Buffer, SafeBuffer)
37561
37562SafeBuffer.from = function (arg, encodingOrOffset, length) {
37563 if (typeof arg === 'number') {
37564 throw new TypeError('Argument must not be a number')
37565 }
37566 return Buffer(arg, encodingOrOffset, length)
37567}
37568
37569SafeBuffer.alloc = function (size, fill, encoding) {
37570 if (typeof size !== 'number') {
37571 throw new TypeError('Argument must be a number')
37572 }
37573 var buf = Buffer(size)
37574 if (fill !== undefined) {
37575 if (typeof encoding === 'string') {
37576 buf.fill(fill, encoding)
37577 } else {
37578 buf.fill(fill)
37579 }
37580 } else {
37581 buf.fill(0)
37582 }
37583 return buf
37584}
37585
37586SafeBuffer.allocUnsafe = function (size) {
37587 if (typeof size !== 'number') {
37588 throw new TypeError('Argument must be a number')
37589 }
37590 return Buffer(size)
37591}
37592
37593SafeBuffer.allocUnsafeSlow = function (size) {
37594 if (typeof size !== 'number') {
37595 throw new TypeError('Argument must be a number')
37596 }
37597 return buffer.SlowBuffer(size)
37598}
37599
37600},{"buffer":107}],248:[function(require,module,exports){
37601(function (Buffer){
37602var crypto = require('crypto')
37603/* eslint-disable camelcase */
37604
37605var MAX_VALUE = 0x7fffffff
37606
37607// N = Cpu cost, r = Memory cost, p = parallelization cost
37608function scrypt (key, salt, N, r, p, dkLen, progressCallback) {
37609 if (N === 0 || (N & (N - 1)) !== 0) throw Error('N must be > 0 and a power of 2')
37610
37611 if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large')
37612 if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large')
37613
37614 var XY = new Buffer(256 * r)
37615 var V = new Buffer(128 * r * N)
37616
37617 // pseudo global
37618 var B32 = new Int32Array(16) // salsa20_8
37619 var x = new Int32Array(16) // salsa20_8
37620 var _X = new Buffer(64) // blockmix_salsa8
37621
37622 // pseudo global
37623 var B = crypto.pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256')
37624
37625 var tickCallback
37626 if (progressCallback) {
37627 var totalOps = p * N * 2
37628 var currentOp = 0
37629
37630 tickCallback = function () {
37631 ++currentOp
37632
37633 // send progress notifications once every 1,000 ops
37634 if (currentOp % 1000 === 0) {
37635 progressCallback({
37636 current: currentOp,
37637 total: totalOps,
37638 percent: (currentOp / totalOps) * 100.0
37639 })
37640 }
37641 }
37642 }
37643
37644 for (var i = 0; i < p; i++) {
37645 smix(B, i * 128 * r, r, N, V, XY)
37646 }
37647
37648 return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256')
37649
37650 // all of these functions are actually moved to the top
37651 // due to function hoisting
37652
37653 function smix (B, Bi, r, N, V, XY) {
37654 var Xi = 0
37655 var Yi = 128 * r
37656 var i
37657
37658 B.copy(XY, Xi, Bi, Bi + Yi)
37659
37660 for (i = 0; i < N; i++) {
37661 XY.copy(V, i * Yi, Xi, Xi + Yi)
37662 blockmix_salsa8(XY, Xi, Yi, r)
37663
37664 if (tickCallback) tickCallback()
37665 }
37666
37667 for (i = 0; i < N; i++) {
37668 var offset = Xi + (2 * r - 1) * 64
37669 var j = XY.readUInt32LE(offset) & (N - 1)
37670 blockxor(V, j * Yi, XY, Xi, Yi)
37671 blockmix_salsa8(XY, Xi, Yi, r)
37672
37673 if (tickCallback) tickCallback()
37674 }
37675
37676 XY.copy(B, Bi, Xi, Xi + Yi)
37677 }
37678
37679 function blockmix_salsa8 (BY, Bi, Yi, r) {
37680 var i
37681
37682 arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64)
37683
37684 for (i = 0; i < 2 * r; i++) {
37685 blockxor(BY, i * 64, _X, 0, 64)
37686 salsa20_8(_X)
37687 arraycopy(_X, 0, BY, Yi + (i * 64), 64)
37688 }
37689
37690 for (i = 0; i < r; i++) {
37691 arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64)
37692 }
37693
37694 for (i = 0; i < r; i++) {
37695 arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64)
37696 }
37697 }
37698
37699 function R (a, b) {
37700 return (a << b) | (a >>> (32 - b))
37701 }
37702
37703 function salsa20_8 (B) {
37704 var i
37705
37706 for (i = 0; i < 16; i++) {
37707 B32[i] = (B[i * 4 + 0] & 0xff) << 0
37708 B32[i] |= (B[i * 4 + 1] & 0xff) << 8
37709 B32[i] |= (B[i * 4 + 2] & 0xff) << 16
37710 B32[i] |= (B[i * 4 + 3] & 0xff) << 24
37711 // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js
37712 }
37713
37714 arraycopy(B32, 0, x, 0, 16)
37715
37716 for (i = 8; i > 0; i -= 2) {
37717 x[4] ^= R(x[0] + x[12], 7)
37718 x[8] ^= R(x[4] + x[0], 9)
37719 x[12] ^= R(x[8] + x[4], 13)
37720 x[0] ^= R(x[12] + x[8], 18)
37721 x[9] ^= R(x[5] + x[1], 7)
37722 x[13] ^= R(x[9] + x[5], 9)
37723 x[1] ^= R(x[13] + x[9], 13)
37724 x[5] ^= R(x[1] + x[13], 18)
37725 x[14] ^= R(x[10] + x[6], 7)
37726 x[2] ^= R(x[14] + x[10], 9)
37727 x[6] ^= R(x[2] + x[14], 13)
37728 x[10] ^= R(x[6] + x[2], 18)
37729 x[3] ^= R(x[15] + x[11], 7)
37730 x[7] ^= R(x[3] + x[15], 9)
37731 x[11] ^= R(x[7] + x[3], 13)
37732 x[15] ^= R(x[11] + x[7], 18)
37733 x[1] ^= R(x[0] + x[3], 7)
37734 x[2] ^= R(x[1] + x[0], 9)
37735 x[3] ^= R(x[2] + x[1], 13)
37736 x[0] ^= R(x[3] + x[2], 18)
37737 x[6] ^= R(x[5] + x[4], 7)
37738 x[7] ^= R(x[6] + x[5], 9)
37739 x[4] ^= R(x[7] + x[6], 13)
37740 x[5] ^= R(x[4] + x[7], 18)
37741 x[11] ^= R(x[10] + x[9], 7)
37742 x[8] ^= R(x[11] + x[10], 9)
37743 x[9] ^= R(x[8] + x[11], 13)
37744 x[10] ^= R(x[9] + x[8], 18)
37745 x[12] ^= R(x[15] + x[14], 7)
37746 x[13] ^= R(x[12] + x[15], 9)
37747 x[14] ^= R(x[13] + x[12], 13)
37748 x[15] ^= R(x[14] + x[13], 18)
37749 }
37750
37751 for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i]
37752
37753 for (i = 0; i < 16; i++) {
37754 var bi = i * 4
37755 B[bi + 0] = (B32[i] >> 0 & 0xff)
37756 B[bi + 1] = (B32[i] >> 8 & 0xff)
37757 B[bi + 2] = (B32[i] >> 16 & 0xff)
37758 B[bi + 3] = (B32[i] >> 24 & 0xff)
37759 // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js
37760 }
37761 }
37762
37763 // naive approach... going back to loop unrolling may yield additional performance
37764 function blockxor (S, Si, D, Di, len) {
37765 for (var i = 0; i < len; i++) {
37766 D[Di + i] ^= S[Si + i]
37767 }
37768 }
37769}
37770
37771function arraycopy (src, srcPos, dest, destPos, length) {
37772 if (Buffer.isBuffer(src) && Buffer.isBuffer(dest)) {
37773 src.copy(dest, destPos, srcPos, srcPos + length)
37774 } else {
37775 while (length--) {
37776 dest[destPos++] = src[srcPos++]
37777 }
37778 }
37779}
37780
37781module.exports = scrypt
37782
37783}).call(this,require("buffer").Buffer)
37784},{"buffer":107,"crypto":116}],249:[function(require,module,exports){
37785'use strict'
37786module.exports = require('./lib')(require('./lib/elliptic'))
37787
37788},{"./lib":253,"./lib/elliptic":252}],250:[function(require,module,exports){
37789(function (Buffer){
37790'use strict'
37791var toString = Object.prototype.toString
37792
37793// TypeError
37794exports.isArray = function (value, message) {
37795 if (!Array.isArray(value)) throw TypeError(message)
37796}
37797
37798exports.isBoolean = function (value, message) {
37799 if (toString.call(value) !== '[object Boolean]') throw TypeError(message)
37800}
37801
37802exports.isBuffer = function (value, message) {
37803 if (!Buffer.isBuffer(value)) throw TypeError(message)
37804}
37805
37806exports.isFunction = function (value, message) {
37807 if (toString.call(value) !== '[object Function]') throw TypeError(message)
37808}
37809
37810exports.isNumber = function (value, message) {
37811 if (toString.call(value) !== '[object Number]') throw TypeError(message)
37812}
37813
37814exports.isObject = function (value, message) {
37815 if (toString.call(value) !== '[object Object]') throw TypeError(message)
37816}
37817
37818// RangeError
37819exports.isBufferLength = function (buffer, length, message) {
37820 if (buffer.length !== length) throw RangeError(message)
37821}
37822
37823exports.isBufferLength2 = function (buffer, length1, length2, message) {
37824 if (buffer.length !== length1 && buffer.length !== length2) throw RangeError(message)
37825}
37826
37827exports.isLengthGTZero = function (value, message) {
37828 if (value.length === 0) throw RangeError(message)
37829}
37830
37831exports.isNumberInInterval = function (number, x, y, message) {
37832 if (number <= x || number >= y) throw RangeError(message)
37833}
37834
37835}).call(this,{"isBuffer":require("../../is-buffer/index.js")})
37836},{"../../is-buffer/index.js":164}],251:[function(require,module,exports){
37837'use strict'
37838var Buffer = require('safe-buffer').Buffer
37839var bip66 = require('bip66')
37840
37841var EC_PRIVKEY_EXPORT_DER_COMPRESSED = Buffer.from([
37842 // begin
37843 0x30, 0x81, 0xd3, 0x02, 0x01, 0x01, 0x04, 0x20,
37844 // private key
37845 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37846 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37847 // middle
37848 0xa0, 0x81, 0x85, 0x30, 0x81, 0x82, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48,
37849 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
37850 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
37851 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04,
37852 0x21, 0x02, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87,
37853 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8,
37854 0x17, 0x98, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
37855 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E,
37856 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x24, 0x03, 0x22, 0x00,
37857 // public key
37858 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37859 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37860 0x00
37861])
37862
37863var EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED = Buffer.from([
37864 // begin
37865 0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20,
37866 // private key
37867 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37868 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37869 // middle
37870 0xa0, 0x81, 0xa5, 0x30, 0x81, 0xa2, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48,
37871 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
37872 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
37873 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04,
37874 0x41, 0x04, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87,
37875 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8,
37876 0x17, 0x98, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0E, 0x11,
37877 0x08, 0xa8, 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10,
37878 0xd4, 0xb8, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
37879 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E,
37880 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x44, 0x03, 0x42, 0x00,
37881 // public key
37882 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37883 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37884 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37885 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00,
37886 0x00
37887])
37888
37889exports.privateKeyExport = function (privateKey, publicKey, compressed) {
37890 var result = Buffer.from(compressed ? EC_PRIVKEY_EXPORT_DER_COMPRESSED : EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED)
37891 privateKey.copy(result, compressed ? 8 : 9)
37892 publicKey.copy(result, compressed ? 181 : 214)
37893 return result
37894}
37895
37896exports.privateKeyImport = function (privateKey) {
37897 var length = privateKey.length
37898
37899 // sequence header
37900 var index = 0
37901 if (length < index + 1 || privateKey[index] !== 0x30) return
37902 index += 1
37903
37904 // sequence length constructor
37905 if (length < index + 1 || !(privateKey[index] & 0x80)) return
37906
37907 var lenb = privateKey[index] & 0x7f
37908 index += 1
37909 if (lenb < 1 || lenb > 2) return
37910 if (length < index + lenb) return
37911
37912 // sequence length
37913 var len = privateKey[index + lenb - 1] | (lenb > 1 ? privateKey[index + lenb - 2] << 8 : 0)
37914 index += lenb
37915 if (length < index + len) return
37916
37917 // sequence element 0: version number (=1)
37918 if (length < index + 3 ||
37919 privateKey[index] !== 0x02 ||
37920 privateKey[index + 1] !== 0x01 ||
37921 privateKey[index + 2] !== 0x01) {
37922 return
37923 }
37924 index += 3
37925
37926 // sequence element 1: octet string, up to 32 bytes
37927 if (length < index + 2 ||
37928 privateKey[index] !== 0x04 ||
37929 privateKey[index + 1] > 0x20 ||
37930 length < index + 2 + privateKey[index + 1]) {
37931 return
37932 }
37933
37934 return privateKey.slice(index + 2, index + 2 + privateKey[index + 1])
37935}
37936
37937exports.signatureExport = function (sigObj) {
37938 var r = Buffer.concat([Buffer.from([0]), sigObj.r])
37939 for (var lenR = 33, posR = 0; lenR > 1 && r[posR] === 0x00 && !(r[posR + 1] & 0x80); --lenR, ++posR);
37940
37941 var s = Buffer.concat([Buffer.from([0]), sigObj.s])
37942 for (var lenS = 33, posS = 0; lenS > 1 && s[posS] === 0x00 && !(s[posS + 1] & 0x80); --lenS, ++posS);
37943
37944 return bip66.encode(r.slice(posR), s.slice(posS))
37945}
37946
37947exports.signatureImport = function (sig) {
37948 var r = Buffer.alloc(32, 0)
37949 var s = Buffer.alloc(32, 0)
37950
37951 try {
37952 var sigObj = bip66.decode(sig)
37953 if (sigObj.r.length === 33 && sigObj.r[0] === 0x00) sigObj.r = sigObj.r.slice(1)
37954 if (sigObj.r.length > 32) throw new Error('R length is too long')
37955 if (sigObj.s.length === 33 && sigObj.s[0] === 0x00) sigObj.s = sigObj.s.slice(1)
37956 if (sigObj.s.length > 32) throw new Error('S length is too long')
37957 } catch (err) {
37958 return
37959 }
37960
37961 sigObj.r.copy(r, 32 - sigObj.r.length)
37962 sigObj.s.copy(s, 32 - sigObj.s.length)
37963
37964 return { r: r, s: s }
37965}
37966
37967exports.signatureImportLax = function (sig) {
37968 var r = Buffer.alloc(32, 0)
37969 var s = Buffer.alloc(32, 0)
37970
37971 var length = sig.length
37972 var index = 0
37973
37974 // sequence tag byte
37975 if (sig[index++] !== 0x30) return
37976
37977 // sequence length byte
37978 var lenbyte = sig[index++]
37979 if (lenbyte & 0x80) {
37980 index += lenbyte - 0x80
37981 if (index > length) return
37982 }
37983
37984 // sequence tag byte for r
37985 if (sig[index++] !== 0x02) return
37986
37987 // length for r
37988 var rlen = sig[index++]
37989 if (rlen & 0x80) {
37990 lenbyte = rlen - 0x80
37991 if (index + lenbyte > length) return
37992 for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1);
37993 for (rlen = 0; lenbyte > 0; index += 1, lenbyte -= 1) rlen = (rlen << 8) + sig[index]
37994 }
37995 if (rlen > length - index) return
37996 var rindex = index
37997 index += rlen
37998
37999 // sequence tag byte for s
38000 if (sig[index++] !== 0x02) return
38001
38002 // length for s
38003 var slen = sig[index++]
38004 if (slen & 0x80) {
38005 lenbyte = slen - 0x80
38006 if (index + lenbyte > length) return
38007 for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1);
38008 for (slen = 0; lenbyte > 0; index += 1, lenbyte -= 1) slen = (slen << 8) + sig[index]
38009 }
38010 if (slen > length - index) return
38011 var sindex = index
38012 index += slen
38013
38014 // ignore leading zeros in r
38015 for (; rlen > 0 && sig[rindex] === 0x00; rlen -= 1, rindex += 1);
38016 // copy r value
38017 if (rlen > 32) return
38018 var rvalue = sig.slice(rindex, rindex + rlen)
38019 rvalue.copy(r, 32 - rvalue.length)
38020
38021 // ignore leading zeros in s
38022 for (; slen > 0 && sig[sindex] === 0x00; slen -= 1, sindex += 1);
38023 // copy s value
38024 if (slen > 32) return
38025 var svalue = sig.slice(sindex, sindex + slen)
38026 svalue.copy(s, 32 - svalue.length)
38027
38028 return { r: r, s: s }
38029}
38030
38031},{"bip66":74,"safe-buffer":247}],252:[function(require,module,exports){
38032'use strict'
38033var Buffer = require('safe-buffer').Buffer
38034var createHash = require('create-hash')
38035var BN = require('bn.js')
38036var EC = require('elliptic').ec
38037
38038var messages = require('../messages.json')
38039
38040var ec = new EC('secp256k1')
38041var ecparams = ec.curve
38042
38043function loadCompressedPublicKey (first, xBuffer) {
38044 var x = new BN(xBuffer)
38045
38046 // overflow
38047 if (x.cmp(ecparams.p) >= 0) return null
38048 x = x.toRed(ecparams.red)
38049
38050 // compute corresponding Y
38051 var y = x.redSqr().redIMul(x).redIAdd(ecparams.b).redSqrt()
38052 if ((first === 0x03) !== y.isOdd()) y = y.redNeg()
38053
38054 return ec.keyPair({ pub: { x: x, y: y } })
38055}
38056
38057function loadUncompressedPublicKey (first, xBuffer, yBuffer) {
38058 var x = new BN(xBuffer)
38059 var y = new BN(yBuffer)
38060
38061 // overflow
38062 if (x.cmp(ecparams.p) >= 0 || y.cmp(ecparams.p) >= 0) return null
38063
38064 x = x.toRed(ecparams.red)
38065 y = y.toRed(ecparams.red)
38066
38067 // is odd flag
38068 if ((first === 0x06 || first === 0x07) && y.isOdd() !== (first === 0x07)) return null
38069
38070 // x*x*x + b = y*y
38071 var x3 = x.redSqr().redIMul(x)
38072 if (!y.redSqr().redISub(x3.redIAdd(ecparams.b)).isZero()) return null
38073
38074 return ec.keyPair({ pub: { x: x, y: y } })
38075}
38076
38077function loadPublicKey (publicKey) {
38078 var first = publicKey[0]
38079 switch (first) {
38080 case 0x02:
38081 case 0x03:
38082 if (publicKey.length !== 33) return null
38083 return loadCompressedPublicKey(first, publicKey.slice(1, 33))
38084 case 0x04:
38085 case 0x06:
38086 case 0x07:
38087 if (publicKey.length !== 65) return null
38088 return loadUncompressedPublicKey(first, publicKey.slice(1, 33), publicKey.slice(33, 65))
38089 default:
38090 return null
38091 }
38092}
38093
38094exports.privateKeyVerify = function (privateKey) {
38095 var bn = new BN(privateKey)
38096 return bn.cmp(ecparams.n) < 0 && !bn.isZero()
38097}
38098
38099exports.privateKeyExport = function (privateKey, compressed) {
38100 var d = new BN(privateKey)
38101 if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PRIVATE_KEY_EXPORT_DER_FAIL)
38102
38103 return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true))
38104}
38105
38106exports.privateKeyNegate = function (privateKey) {
38107 var bn = new BN(privateKey)
38108 return bn.isZero() ? Buffer.alloc(32) : ecparams.n.sub(bn).umod(ecparams.n).toArrayLike(Buffer, 'be', 32)
38109}
38110
38111exports.privateKeyModInverse = function (privateKey) {
38112 var bn = new BN(privateKey)
38113 if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_RANGE_INVALID)
38114
38115 return bn.invm(ecparams.n).toArrayLike(Buffer, 'be', 32)
38116}
38117
38118exports.privateKeyTweakAdd = function (privateKey, tweak) {
38119 var bn = new BN(tweak)
38120 if (bn.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL)
38121
38122 bn.iadd(new BN(privateKey))
38123 if (bn.cmp(ecparams.n) >= 0) bn.isub(ecparams.n)
38124 if (bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL)
38125
38126 return bn.toArrayLike(Buffer, 'be', 32)
38127}
38128
38129exports.privateKeyTweakMul = function (privateKey, tweak) {
38130 var bn = new BN(tweak)
38131 if (bn.cmp(ecparams.n) >= 0 || bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_MUL_FAIL)
38132
38133 bn.imul(new BN(privateKey))
38134 if (bn.cmp(ecparams.n)) bn = bn.umod(ecparams.n)
38135
38136 return bn.toArrayLike(Buffer, 'be', 32)
38137}
38138
38139exports.publicKeyCreate = function (privateKey, compressed) {
38140 var d = new BN(privateKey)
38141 if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.EC_PUBLIC_KEY_CREATE_FAIL)
38142
38143 return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true))
38144}
38145
38146exports.publicKeyConvert = function (publicKey, compressed) {
38147 var pair = loadPublicKey(publicKey)
38148 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
38149
38150 return Buffer.from(pair.getPublic(compressed, true))
38151}
38152
38153exports.publicKeyVerify = function (publicKey) {
38154 return loadPublicKey(publicKey) !== null
38155}
38156
38157exports.publicKeyTweakAdd = function (publicKey, tweak, compressed) {
38158 var pair = loadPublicKey(publicKey)
38159 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
38160
38161 tweak = new BN(tweak)
38162 if (tweak.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL)
38163
38164 return Buffer.from(ecparams.g.mul(tweak).add(pair.pub).encode(true, compressed))
38165}
38166
38167exports.publicKeyTweakMul = function (publicKey, tweak, compressed) {
38168 var pair = loadPublicKey(publicKey)
38169 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
38170
38171 tweak = new BN(tweak)
38172 if (tweak.cmp(ecparams.n) >= 0 || tweak.isZero()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_MUL_FAIL)
38173
38174 return Buffer.from(pair.pub.mul(tweak).encode(true, compressed))
38175}
38176
38177exports.publicKeyCombine = function (publicKeys, compressed) {
38178 var pairs = new Array(publicKeys.length)
38179 for (var i = 0; i < publicKeys.length; ++i) {
38180 pairs[i] = loadPublicKey(publicKeys[i])
38181 if (pairs[i] === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
38182 }
38183
38184 var point = pairs[0].pub
38185 for (var j = 1; j < pairs.length; ++j) point = point.add(pairs[j].pub)
38186 if (point.isInfinity()) throw new Error(messages.EC_PUBLIC_KEY_COMBINE_FAIL)
38187
38188 return Buffer.from(point.encode(true, compressed))
38189}
38190
38191exports.signatureNormalize = function (signature) {
38192 var r = new BN(signature.slice(0, 32))
38193 var s = new BN(signature.slice(32, 64))
38194 if (r.cmp(ecparams.n) >= 0 || s.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL)
38195
38196 var result = Buffer.from(signature)
38197 if (s.cmp(ec.nh) === 1) ecparams.n.sub(s).toArrayLike(Buffer, 'be', 32).copy(result, 32)
38198
38199 return result
38200}
38201
38202exports.signatureExport = function (signature) {
38203 var r = signature.slice(0, 32)
38204 var s = signature.slice(32, 64)
38205 if (new BN(r).cmp(ecparams.n) >= 0 || new BN(s).cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL)
38206
38207 return { r: r, s: s }
38208}
38209
38210exports.signatureImport = function (sigObj) {
38211 var r = new BN(sigObj.r)
38212 if (r.cmp(ecparams.n) >= 0) r = new BN(0)
38213
38214 var s = new BN(sigObj.s)
38215 if (s.cmp(ecparams.n) >= 0) s = new BN(0)
38216
38217 return Buffer.concat([
38218 r.toArrayLike(Buffer, 'be', 32),
38219 s.toArrayLike(Buffer, 'be', 32)
38220 ])
38221}
38222
38223exports.sign = function (message, privateKey, noncefn, data) {
38224 if (typeof noncefn === 'function') {
38225 var getNonce = noncefn
38226 noncefn = function (counter) {
38227 var nonce = getNonce(message, privateKey, null, data, counter)
38228 if (!Buffer.isBuffer(nonce) || nonce.length !== 32) throw new Error(messages.ECDSA_SIGN_FAIL)
38229
38230 return new BN(nonce)
38231 }
38232 }
38233
38234 var d = new BN(privateKey)
38235 if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.ECDSA_SIGN_FAIL)
38236
38237 var result = ec.sign(message, privateKey, { canonical: true, k: noncefn, pers: data })
38238 return {
38239 signature: Buffer.concat([
38240 result.r.toArrayLike(Buffer, 'be', 32),
38241 result.s.toArrayLike(Buffer, 'be', 32)
38242 ]),
38243 recovery: result.recoveryParam
38244 }
38245}
38246
38247exports.verify = function (message, signature, publicKey) {
38248 var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)}
38249
38250 var sigr = new BN(sigObj.r)
38251 var sigs = new BN(sigObj.s)
38252 if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL)
38253 if (sigs.cmp(ec.nh) === 1 || sigr.isZero() || sigs.isZero()) return false
38254
38255 var pair = loadPublicKey(publicKey)
38256 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
38257
38258 return ec.verify(message, sigObj, {x: pair.pub.x, y: pair.pub.y})
38259}
38260
38261exports.recover = function (message, signature, recovery, compressed) {
38262 var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)}
38263
38264 var sigr = new BN(sigObj.r)
38265 var sigs = new BN(sigObj.s)
38266 if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL)
38267
38268 try {
38269 if (sigr.isZero() || sigs.isZero()) throw new Error()
38270
38271 var point = ec.recoverPubKey(message, sigObj, recovery)
38272 return Buffer.from(point.encode(true, compressed))
38273 } catch (err) {
38274 throw new Error(messages.ECDSA_RECOVER_FAIL)
38275 }
38276}
38277
38278exports.ecdh = function (publicKey, privateKey) {
38279 var shared = exports.ecdhUnsafe(publicKey, privateKey, true)
38280 return createHash('sha256').update(shared).digest()
38281}
38282
38283exports.ecdhUnsafe = function (publicKey, privateKey, compressed) {
38284 var pair = loadPublicKey(publicKey)
38285 if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL)
38286
38287 var scalar = new BN(privateKey)
38288 if (scalar.cmp(ecparams.n) >= 0 || scalar.isZero()) throw new Error(messages.ECDH_FAIL)
38289
38290 return Buffer.from(pair.pub.mul(scalar).encode(true, compressed))
38291}
38292
38293},{"../messages.json":254,"bn.js":75,"create-hash":111,"elliptic":127,"safe-buffer":247}],253:[function(require,module,exports){
38294'use strict'
38295var assert = require('./assert')
38296var der = require('./der')
38297var messages = require('./messages.json')
38298
38299function initCompressedValue (value, defaultValue) {
38300 if (value === undefined) return defaultValue
38301
38302 assert.isBoolean(value, messages.COMPRESSED_TYPE_INVALID)
38303 return value
38304}
38305
38306module.exports = function (secp256k1) {
38307 return {
38308 privateKeyVerify: function (privateKey) {
38309 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38310 return privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey)
38311 },
38312
38313 privateKeyExport: function (privateKey, compressed) {
38314 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38315 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
38316
38317 compressed = initCompressedValue(compressed, true)
38318 var publicKey = secp256k1.privateKeyExport(privateKey, compressed)
38319
38320 return der.privateKeyExport(privateKey, publicKey, compressed)
38321 },
38322
38323 privateKeyImport: function (privateKey) {
38324 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38325
38326 privateKey = der.privateKeyImport(privateKey)
38327 if (privateKey && privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey)) return privateKey
38328
38329 throw new Error(messages.EC_PRIVATE_KEY_IMPORT_DER_FAIL)
38330 },
38331
38332 privateKeyNegate: function (privateKey) {
38333 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38334 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
38335
38336 return secp256k1.privateKeyNegate(privateKey)
38337 },
38338
38339 privateKeyModInverse: function (privateKey) {
38340 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38341 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
38342
38343 return secp256k1.privateKeyModInverse(privateKey)
38344 },
38345
38346 privateKeyTweakAdd: function (privateKey, tweak) {
38347 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38348 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
38349
38350 assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID)
38351 assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID)
38352
38353 return secp256k1.privateKeyTweakAdd(privateKey, tweak)
38354 },
38355
38356 privateKeyTweakMul: function (privateKey, tweak) {
38357 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38358 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
38359
38360 assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID)
38361 assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID)
38362
38363 return secp256k1.privateKeyTweakMul(privateKey, tweak)
38364 },
38365
38366 publicKeyCreate: function (privateKey, compressed) {
38367 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38368 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
38369
38370 compressed = initCompressedValue(compressed, true)
38371
38372 return secp256k1.publicKeyCreate(privateKey, compressed)
38373 },
38374
38375 publicKeyConvert: function (publicKey, compressed) {
38376 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
38377 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
38378
38379 compressed = initCompressedValue(compressed, true)
38380
38381 return secp256k1.publicKeyConvert(publicKey, compressed)
38382 },
38383
38384 publicKeyVerify: function (publicKey) {
38385 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
38386 return secp256k1.publicKeyVerify(publicKey)
38387 },
38388
38389 publicKeyTweakAdd: function (publicKey, tweak, compressed) {
38390 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
38391 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
38392
38393 assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID)
38394 assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID)
38395
38396 compressed = initCompressedValue(compressed, true)
38397
38398 return secp256k1.publicKeyTweakAdd(publicKey, tweak, compressed)
38399 },
38400
38401 publicKeyTweakMul: function (publicKey, tweak, compressed) {
38402 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
38403 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
38404
38405 assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID)
38406 assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID)
38407
38408 compressed = initCompressedValue(compressed, true)
38409
38410 return secp256k1.publicKeyTweakMul(publicKey, tweak, compressed)
38411 },
38412
38413 publicKeyCombine: function (publicKeys, compressed) {
38414 assert.isArray(publicKeys, messages.EC_PUBLIC_KEYS_TYPE_INVALID)
38415 assert.isLengthGTZero(publicKeys, messages.EC_PUBLIC_KEYS_LENGTH_INVALID)
38416 for (var i = 0; i < publicKeys.length; ++i) {
38417 assert.isBuffer(publicKeys[i], messages.EC_PUBLIC_KEY_TYPE_INVALID)
38418 assert.isBufferLength2(publicKeys[i], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
38419 }
38420
38421 compressed = initCompressedValue(compressed, true)
38422
38423 return secp256k1.publicKeyCombine(publicKeys, compressed)
38424 },
38425
38426 signatureNormalize: function (signature) {
38427 assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID)
38428 assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
38429
38430 return secp256k1.signatureNormalize(signature)
38431 },
38432
38433 signatureExport: function (signature) {
38434 assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID)
38435 assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
38436
38437 var sigObj = secp256k1.signatureExport(signature)
38438 return der.signatureExport(sigObj)
38439 },
38440
38441 signatureImport: function (sig) {
38442 assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID)
38443 assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
38444
38445 var sigObj = der.signatureImport(sig)
38446 if (sigObj) return secp256k1.signatureImport(sigObj)
38447
38448 throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL)
38449 },
38450
38451 signatureImportLax: function (sig) {
38452 assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID)
38453 assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
38454
38455 var sigObj = der.signatureImportLax(sig)
38456 if (sigObj) return secp256k1.signatureImport(sigObj)
38457
38458 throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL)
38459 },
38460
38461 sign: function (message, privateKey, options) {
38462 assert.isBuffer(message, messages.MSG32_TYPE_INVALID)
38463 assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID)
38464
38465 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38466 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
38467
38468 var data = null
38469 var noncefn = null
38470 if (options !== undefined) {
38471 assert.isObject(options, messages.OPTIONS_TYPE_INVALID)
38472
38473 if (options.data !== undefined) {
38474 assert.isBuffer(options.data, messages.OPTIONS_DATA_TYPE_INVALID)
38475 assert.isBufferLength(options.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID)
38476 data = options.data
38477 }
38478
38479 if (options.noncefn !== undefined) {
38480 assert.isFunction(options.noncefn, messages.OPTIONS_NONCEFN_TYPE_INVALID)
38481 noncefn = options.noncefn
38482 }
38483 }
38484
38485 return secp256k1.sign(message, privateKey, noncefn, data)
38486 },
38487
38488 verify: function (message, signature, publicKey) {
38489 assert.isBuffer(message, messages.MSG32_TYPE_INVALID)
38490 assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID)
38491
38492 assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID)
38493 assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
38494
38495 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
38496 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
38497
38498 return secp256k1.verify(message, signature, publicKey)
38499 },
38500
38501 recover: function (message, signature, recovery, compressed) {
38502 assert.isBuffer(message, messages.MSG32_TYPE_INVALID)
38503 assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID)
38504
38505 assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID)
38506 assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID)
38507
38508 assert.isNumber(recovery, messages.RECOVERY_ID_TYPE_INVALID)
38509 assert.isNumberInInterval(recovery, -1, 4, messages.RECOVERY_ID_VALUE_INVALID)
38510
38511 compressed = initCompressedValue(compressed, true)
38512
38513 return secp256k1.recover(message, signature, recovery, compressed)
38514 },
38515
38516 ecdh: function (publicKey, privateKey) {
38517 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
38518 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
38519
38520 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38521 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
38522
38523 return secp256k1.ecdh(publicKey, privateKey)
38524 },
38525
38526 ecdhUnsafe: function (publicKey, privateKey, compressed) {
38527 assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID)
38528 assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID)
38529
38530 assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID)
38531 assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID)
38532
38533 compressed = initCompressedValue(compressed, true)
38534
38535 return secp256k1.ecdhUnsafe(publicKey, privateKey, compressed)
38536 }
38537 }
38538}
38539
38540},{"./assert":250,"./der":251,"./messages.json":254}],254:[function(require,module,exports){
38541module.exports={
38542 "COMPRESSED_TYPE_INVALID": "compressed should be a boolean",
38543 "EC_PRIVATE_KEY_TYPE_INVALID": "private key should be a Buffer",
38544 "EC_PRIVATE_KEY_LENGTH_INVALID": "private key length is invalid",
38545 "EC_PRIVATE_KEY_RANGE_INVALID": "private key range is invalid",
38546 "EC_PRIVATE_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting private key is invalid",
38547 "EC_PRIVATE_KEY_TWEAK_MUL_FAIL": "tweak out of range",
38548 "EC_PRIVATE_KEY_EXPORT_DER_FAIL": "couldn't export to DER format",
38549 "EC_PRIVATE_KEY_IMPORT_DER_FAIL": "couldn't import from DER format",
38550 "EC_PUBLIC_KEYS_TYPE_INVALID": "public keys should be an Array",
38551 "EC_PUBLIC_KEYS_LENGTH_INVALID": "public keys Array should have at least 1 element",
38552 "EC_PUBLIC_KEY_TYPE_INVALID": "public key should be a Buffer",
38553 "EC_PUBLIC_KEY_LENGTH_INVALID": "public key length is invalid",
38554 "EC_PUBLIC_KEY_PARSE_FAIL": "the public key could not be parsed or is invalid",
38555 "EC_PUBLIC_KEY_CREATE_FAIL": "private was invalid, try again",
38556 "EC_PUBLIC_KEY_TWEAK_ADD_FAIL": "tweak out of range or resulting public key is invalid",
38557 "EC_PUBLIC_KEY_TWEAK_MUL_FAIL": "tweak out of range",
38558 "EC_PUBLIC_KEY_COMBINE_FAIL": "the sum of the public keys is not valid",
38559 "ECDH_FAIL": "scalar was invalid (zero or overflow)",
38560 "ECDSA_SIGNATURE_TYPE_INVALID": "signature should be a Buffer",
38561 "ECDSA_SIGNATURE_LENGTH_INVALID": "signature length is invalid",
38562 "ECDSA_SIGNATURE_PARSE_FAIL": "couldn't parse signature",
38563 "ECDSA_SIGNATURE_PARSE_DER_FAIL": "couldn't parse DER signature",
38564 "ECDSA_SIGNATURE_SERIALIZE_DER_FAIL": "couldn't serialize signature to DER format",
38565 "ECDSA_SIGN_FAIL": "nonce generation function failed or private key is invalid",
38566 "ECDSA_RECOVER_FAIL": "couldn't recover public key from signature",
38567 "MSG32_TYPE_INVALID": "message should be a Buffer",
38568 "MSG32_LENGTH_INVALID": "message length is invalid",
38569 "OPTIONS_TYPE_INVALID": "options should be an Object",
38570 "OPTIONS_DATA_TYPE_INVALID": "options.data should be a Buffer",
38571 "OPTIONS_DATA_LENGTH_INVALID": "options.data length is invalid",
38572 "OPTIONS_NONCEFN_TYPE_INVALID": "options.noncefn should be a Function",
38573 "RECOVERY_ID_TYPE_INVALID": "recovery should be a Number",
38574 "RECOVERY_ID_VALUE_INVALID": "recovery should have value between -1 and 4",
38575 "TWEAK_TYPE_INVALID": "tweak should be a Buffer",
38576 "TWEAK_LENGTH_INVALID": "tweak length is invalid"
38577}
38578
38579},{}],255:[function(require,module,exports){
38580var Buffer = require('safe-buffer').Buffer
38581
38582// prototype class for hash functions
38583function Hash (blockSize, finalSize) {
38584 this._block = Buffer.alloc(blockSize)
38585 this._finalSize = finalSize
38586 this._blockSize = blockSize
38587 this._len = 0
38588}
38589
38590Hash.prototype.update = function (data, enc) {
38591 if (typeof data === 'string') {
38592 enc = enc || 'utf8'
38593 data = Buffer.from(data, enc)
38594 }
38595
38596 var block = this._block
38597 var blockSize = this._blockSize
38598 var length = data.length
38599 var accum = this._len
38600
38601 for (var offset = 0; offset < length;) {
38602 var assigned = accum % blockSize
38603 var remainder = Math.min(length - offset, blockSize - assigned)
38604
38605 for (var i = 0; i < remainder; i++) {
38606 block[assigned + i] = data[offset + i]
38607 }
38608
38609 accum += remainder
38610 offset += remainder
38611
38612 if ((accum % blockSize) === 0) {
38613 this._update(block)
38614 }
38615 }
38616
38617 this._len += length
38618 return this
38619}
38620
38621Hash.prototype.digest = function (enc) {
38622 var rem = this._len % this._blockSize
38623
38624 this._block[rem] = 0x80
38625
38626 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest
38627 // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize
38628 this._block.fill(0, rem + 1)
38629
38630 if (rem >= this._finalSize) {
38631 this._update(this._block)
38632 this._block.fill(0)
38633 }
38634
38635 var bits = this._len * 8
38636
38637 // uint32
38638 if (bits <= 0xffffffff) {
38639 this._block.writeUInt32BE(bits, this._blockSize - 4)
38640
38641 // uint64
38642 } else {
38643 var lowBits = bits & 0xffffffff
38644 var highBits = (bits - lowBits) / 0x100000000
38645
38646 this._block.writeUInt32BE(highBits, this._blockSize - 8)
38647 this._block.writeUInt32BE(lowBits, this._blockSize - 4)
38648 }
38649
38650 this._update(this._block)
38651 var hash = this._hash()
38652
38653 return enc ? hash.toString(enc) : hash
38654}
38655
38656Hash.prototype._update = function () {
38657 throw new Error('_update must be implemented by subclass')
38658}
38659
38660module.exports = Hash
38661
38662},{"safe-buffer":247}],256:[function(require,module,exports){
38663var exports = module.exports = function SHA (algorithm) {
38664 algorithm = algorithm.toLowerCase()
38665
38666 var Algorithm = exports[algorithm]
38667 if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)')
38668
38669 return new Algorithm()
38670}
38671
38672exports.sha = require('./sha')
38673exports.sha1 = require('./sha1')
38674exports.sha224 = require('./sha224')
38675exports.sha256 = require('./sha256')
38676exports.sha384 = require('./sha384')
38677exports.sha512 = require('./sha512')
38678
38679},{"./sha":257,"./sha1":258,"./sha224":259,"./sha256":260,"./sha384":261,"./sha512":262}],257:[function(require,module,exports){
38680/*
38681 * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined
38682 * in FIPS PUB 180-1
38683 * This source code is derived from sha1.js of the same repository.
38684 * The difference between SHA-0 and SHA-1 is just a bitwise rotate left
38685 * operation was added.
38686 */
38687
38688var inherits = require('inherits')
38689var Hash = require('./hash')
38690var Buffer = require('safe-buffer').Buffer
38691
38692var K = [
38693 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
38694]
38695
38696var W = new Array(80)
38697
38698function Sha () {
38699 this.init()
38700 this._w = W
38701
38702 Hash.call(this, 64, 56)
38703}
38704
38705inherits(Sha, Hash)
38706
38707Sha.prototype.init = function () {
38708 this._a = 0x67452301
38709 this._b = 0xefcdab89
38710 this._c = 0x98badcfe
38711 this._d = 0x10325476
38712 this._e = 0xc3d2e1f0
38713
38714 return this
38715}
38716
38717function rotl5 (num) {
38718 return (num << 5) | (num >>> 27)
38719}
38720
38721function rotl30 (num) {
38722 return (num << 30) | (num >>> 2)
38723}
38724
38725function ft (s, b, c, d) {
38726 if (s === 0) return (b & c) | ((~b) & d)
38727 if (s === 2) return (b & c) | (b & d) | (c & d)
38728 return b ^ c ^ d
38729}
38730
38731Sha.prototype._update = function (M) {
38732 var W = this._w
38733
38734 var a = this._a | 0
38735 var b = this._b | 0
38736 var c = this._c | 0
38737 var d = this._d | 0
38738 var e = this._e | 0
38739
38740 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
38741 for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]
38742
38743 for (var j = 0; j < 80; ++j) {
38744 var s = ~~(j / 20)
38745 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
38746
38747 e = d
38748 d = c
38749 c = rotl30(b)
38750 b = a
38751 a = t
38752 }
38753
38754 this._a = (a + this._a) | 0
38755 this._b = (b + this._b) | 0
38756 this._c = (c + this._c) | 0
38757 this._d = (d + this._d) | 0
38758 this._e = (e + this._e) | 0
38759}
38760
38761Sha.prototype._hash = function () {
38762 var H = Buffer.allocUnsafe(20)
38763
38764 H.writeInt32BE(this._a | 0, 0)
38765 H.writeInt32BE(this._b | 0, 4)
38766 H.writeInt32BE(this._c | 0, 8)
38767 H.writeInt32BE(this._d | 0, 12)
38768 H.writeInt32BE(this._e | 0, 16)
38769
38770 return H
38771}
38772
38773module.exports = Sha
38774
38775},{"./hash":255,"inherits":163,"safe-buffer":247}],258:[function(require,module,exports){
38776/*
38777 * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined
38778 * in FIPS PUB 180-1
38779 * Version 2.1a Copyright Paul Johnston 2000 - 2002.
38780 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
38781 * Distributed under the BSD License
38782 * See http://pajhome.org.uk/crypt/md5 for details.
38783 */
38784
38785var inherits = require('inherits')
38786var Hash = require('./hash')
38787var Buffer = require('safe-buffer').Buffer
38788
38789var K = [
38790 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
38791]
38792
38793var W = new Array(80)
38794
38795function Sha1 () {
38796 this.init()
38797 this._w = W
38798
38799 Hash.call(this, 64, 56)
38800}
38801
38802inherits(Sha1, Hash)
38803
38804Sha1.prototype.init = function () {
38805 this._a = 0x67452301
38806 this._b = 0xefcdab89
38807 this._c = 0x98badcfe
38808 this._d = 0x10325476
38809 this._e = 0xc3d2e1f0
38810
38811 return this
38812}
38813
38814function rotl1 (num) {
38815 return (num << 1) | (num >>> 31)
38816}
38817
38818function rotl5 (num) {
38819 return (num << 5) | (num >>> 27)
38820}
38821
38822function rotl30 (num) {
38823 return (num << 30) | (num >>> 2)
38824}
38825
38826function ft (s, b, c, d) {
38827 if (s === 0) return (b & c) | ((~b) & d)
38828 if (s === 2) return (b & c) | (b & d) | (c & d)
38829 return b ^ c ^ d
38830}
38831
38832Sha1.prototype._update = function (M) {
38833 var W = this._w
38834
38835 var a = this._a | 0
38836 var b = this._b | 0
38837 var c = this._c | 0
38838 var d = this._d | 0
38839 var e = this._e | 0
38840
38841 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
38842 for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16])
38843
38844 for (var j = 0; j < 80; ++j) {
38845 var s = ~~(j / 20)
38846 var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0
38847
38848 e = d
38849 d = c
38850 c = rotl30(b)
38851 b = a
38852 a = t
38853 }
38854
38855 this._a = (a + this._a) | 0
38856 this._b = (b + this._b) | 0
38857 this._c = (c + this._c) | 0
38858 this._d = (d + this._d) | 0
38859 this._e = (e + this._e) | 0
38860}
38861
38862Sha1.prototype._hash = function () {
38863 var H = Buffer.allocUnsafe(20)
38864
38865 H.writeInt32BE(this._a | 0, 0)
38866 H.writeInt32BE(this._b | 0, 4)
38867 H.writeInt32BE(this._c | 0, 8)
38868 H.writeInt32BE(this._d | 0, 12)
38869 H.writeInt32BE(this._e | 0, 16)
38870
38871 return H
38872}
38873
38874module.exports = Sha1
38875
38876},{"./hash":255,"inherits":163,"safe-buffer":247}],259:[function(require,module,exports){
38877/**
38878 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
38879 * in FIPS 180-2
38880 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
38881 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
38882 *
38883 */
38884
38885var inherits = require('inherits')
38886var Sha256 = require('./sha256')
38887var Hash = require('./hash')
38888var Buffer = require('safe-buffer').Buffer
38889
38890var W = new Array(64)
38891
38892function Sha224 () {
38893 this.init()
38894
38895 this._w = W // new Array(64)
38896
38897 Hash.call(this, 64, 56)
38898}
38899
38900inherits(Sha224, Sha256)
38901
38902Sha224.prototype.init = function () {
38903 this._a = 0xc1059ed8
38904 this._b = 0x367cd507
38905 this._c = 0x3070dd17
38906 this._d = 0xf70e5939
38907 this._e = 0xffc00b31
38908 this._f = 0x68581511
38909 this._g = 0x64f98fa7
38910 this._h = 0xbefa4fa4
38911
38912 return this
38913}
38914
38915Sha224.prototype._hash = function () {
38916 var H = Buffer.allocUnsafe(28)
38917
38918 H.writeInt32BE(this._a, 0)
38919 H.writeInt32BE(this._b, 4)
38920 H.writeInt32BE(this._c, 8)
38921 H.writeInt32BE(this._d, 12)
38922 H.writeInt32BE(this._e, 16)
38923 H.writeInt32BE(this._f, 20)
38924 H.writeInt32BE(this._g, 24)
38925
38926 return H
38927}
38928
38929module.exports = Sha224
38930
38931},{"./hash":255,"./sha256":260,"inherits":163,"safe-buffer":247}],260:[function(require,module,exports){
38932/**
38933 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
38934 * in FIPS 180-2
38935 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
38936 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
38937 *
38938 */
38939
38940var inherits = require('inherits')
38941var Hash = require('./hash')
38942var Buffer = require('safe-buffer').Buffer
38943
38944var K = [
38945 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5,
38946 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5,
38947 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3,
38948 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174,
38949 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC,
38950 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA,
38951 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7,
38952 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967,
38953 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13,
38954 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85,
38955 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3,
38956 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070,
38957 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5,
38958 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3,
38959 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208,
38960 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2
38961]
38962
38963var W = new Array(64)
38964
38965function Sha256 () {
38966 this.init()
38967
38968 this._w = W // new Array(64)
38969
38970 Hash.call(this, 64, 56)
38971}
38972
38973inherits(Sha256, Hash)
38974
38975Sha256.prototype.init = function () {
38976 this._a = 0x6a09e667
38977 this._b = 0xbb67ae85
38978 this._c = 0x3c6ef372
38979 this._d = 0xa54ff53a
38980 this._e = 0x510e527f
38981 this._f = 0x9b05688c
38982 this._g = 0x1f83d9ab
38983 this._h = 0x5be0cd19
38984
38985 return this
38986}
38987
38988function ch (x, y, z) {
38989 return z ^ (x & (y ^ z))
38990}
38991
38992function maj (x, y, z) {
38993 return (x & y) | (z & (x | y))
38994}
38995
38996function sigma0 (x) {
38997 return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10)
38998}
38999
39000function sigma1 (x) {
39001 return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7)
39002}
39003
39004function gamma0 (x) {
39005 return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3)
39006}
39007
39008function gamma1 (x) {
39009 return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10)
39010}
39011
39012Sha256.prototype._update = function (M) {
39013 var W = this._w
39014
39015 var a = this._a | 0
39016 var b = this._b | 0
39017 var c = this._c | 0
39018 var d = this._d | 0
39019 var e = this._e | 0
39020 var f = this._f | 0
39021 var g = this._g | 0
39022 var h = this._h | 0
39023
39024 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4)
39025 for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0
39026
39027 for (var j = 0; j < 64; ++j) {
39028 var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0
39029 var T2 = (sigma0(a) + maj(a, b, c)) | 0
39030
39031 h = g
39032 g = f
39033 f = e
39034 e = (d + T1) | 0
39035 d = c
39036 c = b
39037 b = a
39038 a = (T1 + T2) | 0
39039 }
39040
39041 this._a = (a + this._a) | 0
39042 this._b = (b + this._b) | 0
39043 this._c = (c + this._c) | 0
39044 this._d = (d + this._d) | 0
39045 this._e = (e + this._e) | 0
39046 this._f = (f + this._f) | 0
39047 this._g = (g + this._g) | 0
39048 this._h = (h + this._h) | 0
39049}
39050
39051Sha256.prototype._hash = function () {
39052 var H = Buffer.allocUnsafe(32)
39053
39054 H.writeInt32BE(this._a, 0)
39055 H.writeInt32BE(this._b, 4)
39056 H.writeInt32BE(this._c, 8)
39057 H.writeInt32BE(this._d, 12)
39058 H.writeInt32BE(this._e, 16)
39059 H.writeInt32BE(this._f, 20)
39060 H.writeInt32BE(this._g, 24)
39061 H.writeInt32BE(this._h, 28)
39062
39063 return H
39064}
39065
39066module.exports = Sha256
39067
39068},{"./hash":255,"inherits":163,"safe-buffer":247}],261:[function(require,module,exports){
39069var inherits = require('inherits')
39070var SHA512 = require('./sha512')
39071var Hash = require('./hash')
39072var Buffer = require('safe-buffer').Buffer
39073
39074var W = new Array(160)
39075
39076function Sha384 () {
39077 this.init()
39078 this._w = W
39079
39080 Hash.call(this, 128, 112)
39081}
39082
39083inherits(Sha384, SHA512)
39084
39085Sha384.prototype.init = function () {
39086 this._ah = 0xcbbb9d5d
39087 this._bh = 0x629a292a
39088 this._ch = 0x9159015a
39089 this._dh = 0x152fecd8
39090 this._eh = 0x67332667
39091 this._fh = 0x8eb44a87
39092 this._gh = 0xdb0c2e0d
39093 this._hh = 0x47b5481d
39094
39095 this._al = 0xc1059ed8
39096 this._bl = 0x367cd507
39097 this._cl = 0x3070dd17
39098 this._dl = 0xf70e5939
39099 this._el = 0xffc00b31
39100 this._fl = 0x68581511
39101 this._gl = 0x64f98fa7
39102 this._hl = 0xbefa4fa4
39103
39104 return this
39105}
39106
39107Sha384.prototype._hash = function () {
39108 var H = Buffer.allocUnsafe(48)
39109
39110 function writeInt64BE (h, l, offset) {
39111 H.writeInt32BE(h, offset)
39112 H.writeInt32BE(l, offset + 4)
39113 }
39114
39115 writeInt64BE(this._ah, this._al, 0)
39116 writeInt64BE(this._bh, this._bl, 8)
39117 writeInt64BE(this._ch, this._cl, 16)
39118 writeInt64BE(this._dh, this._dl, 24)
39119 writeInt64BE(this._eh, this._el, 32)
39120 writeInt64BE(this._fh, this._fl, 40)
39121
39122 return H
39123}
39124
39125module.exports = Sha384
39126
39127},{"./hash":255,"./sha512":262,"inherits":163,"safe-buffer":247}],262:[function(require,module,exports){
39128var inherits = require('inherits')
39129var Hash = require('./hash')
39130var Buffer = require('safe-buffer').Buffer
39131
39132var K = [
39133 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd,
39134 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc,
39135 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019,
39136 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118,
39137 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe,
39138 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2,
39139 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1,
39140 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694,
39141 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3,
39142 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65,
39143 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483,
39144 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5,
39145 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210,
39146 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4,
39147 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725,
39148 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70,
39149 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926,
39150 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df,
39151 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8,
39152 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b,
39153 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001,
39154 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30,
39155 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910,
39156 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8,
39157 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53,
39158 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8,
39159 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb,
39160 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3,
39161 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60,
39162 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec,
39163 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9,
39164 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b,
39165 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207,
39166 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178,
39167 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6,
39168 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b,
39169 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493,
39170 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c,
39171 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a,
39172 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817
39173]
39174
39175var W = new Array(160)
39176
39177function Sha512 () {
39178 this.init()
39179 this._w = W
39180
39181 Hash.call(this, 128, 112)
39182}
39183
39184inherits(Sha512, Hash)
39185
39186Sha512.prototype.init = function () {
39187 this._ah = 0x6a09e667
39188 this._bh = 0xbb67ae85
39189 this._ch = 0x3c6ef372
39190 this._dh = 0xa54ff53a
39191 this._eh = 0x510e527f
39192 this._fh = 0x9b05688c
39193 this._gh = 0x1f83d9ab
39194 this._hh = 0x5be0cd19
39195
39196 this._al = 0xf3bcc908
39197 this._bl = 0x84caa73b
39198 this._cl = 0xfe94f82b
39199 this._dl = 0x5f1d36f1
39200 this._el = 0xade682d1
39201 this._fl = 0x2b3e6c1f
39202 this._gl = 0xfb41bd6b
39203 this._hl = 0x137e2179
39204
39205 return this
39206}
39207
39208function Ch (x, y, z) {
39209 return z ^ (x & (y ^ z))
39210}
39211
39212function maj (x, y, z) {
39213 return (x & y) | (z & (x | y))
39214}
39215
39216function sigma0 (x, xl) {
39217 return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25)
39218}
39219
39220function sigma1 (x, xl) {
39221 return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23)
39222}
39223
39224function Gamma0 (x, xl) {
39225 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7)
39226}
39227
39228function Gamma0l (x, xl) {
39229 return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25)
39230}
39231
39232function Gamma1 (x, xl) {
39233 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6)
39234}
39235
39236function Gamma1l (x, xl) {
39237 return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26)
39238}
39239
39240function getCarry (a, b) {
39241 return (a >>> 0) < (b >>> 0) ? 1 : 0
39242}
39243
39244Sha512.prototype._update = function (M) {
39245 var W = this._w
39246
39247 var ah = this._ah | 0
39248 var bh = this._bh | 0
39249 var ch = this._ch | 0
39250 var dh = this._dh | 0
39251 var eh = this._eh | 0
39252 var fh = this._fh | 0
39253 var gh = this._gh | 0
39254 var hh = this._hh | 0
39255
39256 var al = this._al | 0
39257 var bl = this._bl | 0
39258 var cl = this._cl | 0
39259 var dl = this._dl | 0
39260 var el = this._el | 0
39261 var fl = this._fl | 0
39262 var gl = this._gl | 0
39263 var hl = this._hl | 0
39264
39265 for (var i = 0; i < 32; i += 2) {
39266 W[i] = M.readInt32BE(i * 4)
39267 W[i + 1] = M.readInt32BE(i * 4 + 4)
39268 }
39269 for (; i < 160; i += 2) {
39270 var xh = W[i - 15 * 2]
39271 var xl = W[i - 15 * 2 + 1]
39272 var gamma0 = Gamma0(xh, xl)
39273 var gamma0l = Gamma0l(xl, xh)
39274
39275 xh = W[i - 2 * 2]
39276 xl = W[i - 2 * 2 + 1]
39277 var gamma1 = Gamma1(xh, xl)
39278 var gamma1l = Gamma1l(xl, xh)
39279
39280 // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
39281 var Wi7h = W[i - 7 * 2]
39282 var Wi7l = W[i - 7 * 2 + 1]
39283
39284 var Wi16h = W[i - 16 * 2]
39285 var Wi16l = W[i - 16 * 2 + 1]
39286
39287 var Wil = (gamma0l + Wi7l) | 0
39288 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0
39289 Wil = (Wil + gamma1l) | 0
39290 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0
39291 Wil = (Wil + Wi16l) | 0
39292 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0
39293
39294 W[i] = Wih
39295 W[i + 1] = Wil
39296 }
39297
39298 for (var j = 0; j < 160; j += 2) {
39299 Wih = W[j]
39300 Wil = W[j + 1]
39301
39302 var majh = maj(ah, bh, ch)
39303 var majl = maj(al, bl, cl)
39304
39305 var sigma0h = sigma0(ah, al)
39306 var sigma0l = sigma0(al, ah)
39307 var sigma1h = sigma1(eh, el)
39308 var sigma1l = sigma1(el, eh)
39309
39310 // t1 = h + sigma1 + ch + K[j] + W[j]
39311 var Kih = K[j]
39312 var Kil = K[j + 1]
39313
39314 var chh = Ch(eh, fh, gh)
39315 var chl = Ch(el, fl, gl)
39316
39317 var t1l = (hl + sigma1l) | 0
39318 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0
39319 t1l = (t1l + chl) | 0
39320 t1h = (t1h + chh + getCarry(t1l, chl)) | 0
39321 t1l = (t1l + Kil) | 0
39322 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0
39323 t1l = (t1l + Wil) | 0
39324 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0
39325
39326 // t2 = sigma0 + maj
39327 var t2l = (sigma0l + majl) | 0
39328 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0
39329
39330 hh = gh
39331 hl = gl
39332 gh = fh
39333 gl = fl
39334 fh = eh
39335 fl = el
39336 el = (dl + t1l) | 0
39337 eh = (dh + t1h + getCarry(el, dl)) | 0
39338 dh = ch
39339 dl = cl
39340 ch = bh
39341 cl = bl
39342 bh = ah
39343 bl = al
39344 al = (t1l + t2l) | 0
39345 ah = (t1h + t2h + getCarry(al, t1l)) | 0
39346 }
39347
39348 this._al = (this._al + al) | 0
39349 this._bl = (this._bl + bl) | 0
39350 this._cl = (this._cl + cl) | 0
39351 this._dl = (this._dl + dl) | 0
39352 this._el = (this._el + el) | 0
39353 this._fl = (this._fl + fl) | 0
39354 this._gl = (this._gl + gl) | 0
39355 this._hl = (this._hl + hl) | 0
39356
39357 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0
39358 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0
39359 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0
39360 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0
39361 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0
39362 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0
39363 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0
39364 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0
39365}
39366
39367Sha512.prototype._hash = function () {
39368 var H = Buffer.allocUnsafe(64)
39369
39370 function writeInt64BE (h, l, offset) {
39371 H.writeInt32BE(h, offset)
39372 H.writeInt32BE(l, offset + 4)
39373 }
39374
39375 writeInt64BE(this._ah, this._al, 0)
39376 writeInt64BE(this._bh, this._bl, 8)
39377 writeInt64BE(this._ch, this._cl, 16)
39378 writeInt64BE(this._dh, this._dl, 24)
39379 writeInt64BE(this._eh, this._el, 32)
39380 writeInt64BE(this._fh, this._fl, 40)
39381 writeInt64BE(this._gh, this._gl, 48)
39382 writeInt64BE(this._hh, this._hl, 56)
39383
39384 return H
39385}
39386
39387module.exports = Sha512
39388
39389},{"./hash":255,"inherits":163,"safe-buffer":247}],263:[function(require,module,exports){
39390// Copyright Joyent, Inc. and other Node contributors.
39391//
39392// Permission is hereby granted, free of charge, to any person obtaining a
39393// copy of this software and associated documentation files (the
39394// "Software"), to deal in the Software without restriction, including
39395// without limitation the rights to use, copy, modify, merge, publish,
39396// distribute, sublicense, and/or sell copies of the Software, and to permit
39397// persons to whom the Software is furnished to do so, subject to the
39398// following conditions:
39399//
39400// The above copyright notice and this permission notice shall be included
39401// in all copies or substantial portions of the Software.
39402//
39403// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
39404// OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
39405// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN
39406// NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
39407// DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
39408// OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
39409// USE OR OTHER DEALINGS IN THE SOFTWARE.
39410
39411module.exports = Stream;
39412
39413var EE = require('events').EventEmitter;
39414var inherits = require('inherits');
39415
39416inherits(Stream, EE);
39417Stream.Readable = require('readable-stream/readable.js');
39418Stream.Writable = require('readable-stream/writable.js');
39419Stream.Duplex = require('readable-stream/duplex.js');
39420Stream.Transform = require('readable-stream/transform.js');
39421Stream.PassThrough = require('readable-stream/passthrough.js');
39422
39423// Backwards-compat with node 0.4.x
39424Stream.Stream = Stream;
39425
39426
39427
39428// old-style streams. Note that the pipe method (the only relevant
39429// part of this class) is overridden in the Readable class.
39430
39431function Stream() {
39432 EE.call(this);
39433}
39434
39435Stream.prototype.pipe = function(dest, options) {
39436 var source = this;
39437
39438 function ondata(chunk) {
39439 if (dest.writable) {
39440 if (false === dest.write(chunk) && source.pause) {
39441 source.pause();
39442 }
39443 }
39444 }
39445
39446 source.on('data', ondata);
39447
39448 function ondrain() {
39449 if (source.readable && source.resume) {
39450 source.resume();
39451 }
39452 }
39453
39454 dest.on('drain', ondrain);
39455
39456 // If the 'end' option is not supplied, dest.end() will be called when
39457 // source gets the 'end' or 'close' events. Only dest.end() once.
39458 if (!dest._isStdio && (!options || options.end !== false)) {
39459 source.on('end', onend);
39460 source.on('close', onclose);
39461 }
39462
39463 var didOnEnd = false;
39464 function onend() {
39465 if (didOnEnd) return;
39466 didOnEnd = true;
39467
39468 dest.end();
39469 }
39470
39471
39472 function onclose() {
39473 if (didOnEnd) return;
39474 didOnEnd = true;
39475
39476 if (typeof dest.destroy === 'function') dest.destroy();
39477 }
39478
39479 // don't leave dangling pipes when there are errors.
39480 function onerror(er) {
39481 cleanup();
39482 if (EE.listenerCount(this, 'error') === 0) {
39483 throw er; // Unhandled stream error in pipe.
39484 }
39485 }
39486
39487 source.on('error', onerror);
39488 dest.on('error', onerror);
39489
39490 // remove all the event listeners that were added.
39491 function cleanup() {
39492 source.removeListener('data', ondata);
39493 dest.removeListener('drain', ondrain);
39494
39495 source.removeListener('end', onend);
39496 source.removeListener('close', onclose);
39497
39498 source.removeListener('error', onerror);
39499 dest.removeListener('error', onerror);
39500
39501 source.removeListener('end', cleanup);
39502 source.removeListener('close', cleanup);
39503
39504 dest.removeListener('close', cleanup);
39505 }
39506
39507 source.on('end', cleanup);
39508 source.on('close', cleanup);
39509
39510 dest.on('close', cleanup);
39511
39512 dest.emit('pipe', source);
39513
39514 // Allow for unix-like usage: A.pipe(B).pipe(C)
39515 return dest;
39516};
39517
39518},{"events":143,"inherits":163,"readable-stream/duplex.js":233,"readable-stream/passthrough.js":242,"readable-stream/readable.js":243,"readable-stream/transform.js":244,"readable-stream/writable.js":245}],264:[function(require,module,exports){
39519'use strict';
39520
39521var Buffer = require('safe-buffer').Buffer;
39522
39523var isEncoding = Buffer.isEncoding || function (encoding) {
39524 encoding = '' + encoding;
39525 switch (encoding && encoding.toLowerCase()) {
39526 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':
39527 return true;
39528 default:
39529 return false;
39530 }
39531};
39532
39533function _normalizeEncoding(enc) {
39534 if (!enc) return 'utf8';
39535 var retried;
39536 while (true) {
39537 switch (enc) {
39538 case 'utf8':
39539 case 'utf-8':
39540 return 'utf8';
39541 case 'ucs2':
39542 case 'ucs-2':
39543 case 'utf16le':
39544 case 'utf-16le':
39545 return 'utf16le';
39546 case 'latin1':
39547 case 'binary':
39548 return 'latin1';
39549 case 'base64':
39550 case 'ascii':
39551 case 'hex':
39552 return enc;
39553 default:
39554 if (retried) return; // undefined
39555 enc = ('' + enc).toLowerCase();
39556 retried = true;
39557 }
39558 }
39559};
39560
39561// Do not cache `Buffer.isEncoding` when checking encoding names as some
39562// modules monkey-patch it to support additional encodings
39563function normalizeEncoding(enc) {
39564 var nenc = _normalizeEncoding(enc);
39565 if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc);
39566 return nenc || enc;
39567}
39568
39569// StringDecoder provides an interface for efficiently splitting a series of
39570// buffers into a series of JS strings without breaking apart multi-byte
39571// characters.
39572exports.StringDecoder = StringDecoder;
39573function StringDecoder(encoding) {
39574 this.encoding = normalizeEncoding(encoding);
39575 var nb;
39576 switch (this.encoding) {
39577 case 'utf16le':
39578 this.text = utf16Text;
39579 this.end = utf16End;
39580 nb = 4;
39581 break;
39582 case 'utf8':
39583 this.fillLast = utf8FillLast;
39584 nb = 4;
39585 break;
39586 case 'base64':
39587 this.text = base64Text;
39588 this.end = base64End;
39589 nb = 3;
39590 break;
39591 default:
39592 this.write = simpleWrite;
39593 this.end = simpleEnd;
39594 return;
39595 }
39596 this.lastNeed = 0;
39597 this.lastTotal = 0;
39598 this.lastChar = Buffer.allocUnsafe(nb);
39599}
39600
39601StringDecoder.prototype.write = function (buf) {
39602 if (buf.length === 0) return '';
39603 var r;
39604 var i;
39605 if (this.lastNeed) {
39606 r = this.fillLast(buf);
39607 if (r === undefined) return '';
39608 i = this.lastNeed;
39609 this.lastNeed = 0;
39610 } else {
39611 i = 0;
39612 }
39613 if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i);
39614 return r || '';
39615};
39616
39617StringDecoder.prototype.end = utf8End;
39618
39619// Returns only complete characters in a Buffer
39620StringDecoder.prototype.text = utf8Text;
39621
39622// Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
39623StringDecoder.prototype.fillLast = function (buf) {
39624 if (this.lastNeed <= buf.length) {
39625 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed);
39626 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
39627 }
39628 buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length);
39629 this.lastNeed -= buf.length;
39630};
39631
39632// Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
39633// continuation byte.
39634function utf8CheckByte(byte) {
39635 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;
39636 return -1;
39637}
39638
39639// Checks at most 3 bytes at the end of a Buffer in order to detect an
39640// incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4)
39641// needed to complete the UTF-8 character (if applicable) are returned.
39642function utf8CheckIncomplete(self, buf, i) {
39643 var j = buf.length - 1;
39644 if (j < i) return 0;
39645 var nb = utf8CheckByte(buf[j]);
39646 if (nb >= 0) {
39647 if (nb > 0) self.lastNeed = nb - 1;
39648 return nb;
39649 }
39650 if (--j < i) return 0;
39651 nb = utf8CheckByte(buf[j]);
39652 if (nb >= 0) {
39653 if (nb > 0) self.lastNeed = nb - 2;
39654 return nb;
39655 }
39656 if (--j < i) return 0;
39657 nb = utf8CheckByte(buf[j]);
39658 if (nb >= 0) {
39659 if (nb > 0) {
39660 if (nb === 2) nb = 0;else self.lastNeed = nb - 3;
39661 }
39662 return nb;
39663 }
39664 return 0;
39665}
39666
39667// Validates as many continuation bytes for a multi-byte UTF-8 character as
39668// needed or are available. If we see a non-continuation byte where we expect
39669// one, we "replace" the validated continuation bytes we've seen so far with
39670// UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding
39671// behavior. The continuation byte check is included three times in the case
39672// where all of the continuation bytes for a character exist in the same buffer.
39673// It is also done this way as a slight performance increase instead of using a
39674// loop.
39675function utf8CheckExtraBytes(self, buf, p) {
39676 if ((buf[0] & 0xC0) !== 0x80) {
39677 self.lastNeed = 0;
39678 return '\ufffd'.repeat(p);
39679 }
39680 if (self.lastNeed > 1 && buf.length > 1) {
39681 if ((buf[1] & 0xC0) !== 0x80) {
39682 self.lastNeed = 1;
39683 return '\ufffd'.repeat(p + 1);
39684 }
39685 if (self.lastNeed > 2 && buf.length > 2) {
39686 if ((buf[2] & 0xC0) !== 0x80) {
39687 self.lastNeed = 2;
39688 return '\ufffd'.repeat(p + 2);
39689 }
39690 }
39691 }
39692}
39693
39694// Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
39695function utf8FillLast(buf) {
39696 var p = this.lastTotal - this.lastNeed;
39697 var r = utf8CheckExtraBytes(this, buf, p);
39698 if (r !== undefined) return r;
39699 if (this.lastNeed <= buf.length) {
39700 buf.copy(this.lastChar, p, 0, this.lastNeed);
39701 return this.lastChar.toString(this.encoding, 0, this.lastTotal);
39702 }
39703 buf.copy(this.lastChar, p, 0, buf.length);
39704 this.lastNeed -= buf.length;
39705}
39706
39707// Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a
39708// partial character, the character's bytes are buffered until the required
39709// number of bytes are available.
39710function utf8Text(buf, i) {
39711 var total = utf8CheckIncomplete(this, buf, i);
39712 if (!this.lastNeed) return buf.toString('utf8', i);
39713 this.lastTotal = total;
39714 var end = buf.length - (total - this.lastNeed);
39715 buf.copy(this.lastChar, 0, end);
39716 return buf.toString('utf8', i, end);
39717}
39718
39719// For UTF-8, a replacement character for each buffered byte of a (partial)
39720// character needs to be added to the output.
39721function utf8End(buf) {
39722 var r = buf && buf.length ? this.write(buf) : '';
39723 if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed);
39724 return r;
39725}
39726
39727// UTF-16LE typically needs two bytes per character, but even if we have an even
39728// number of bytes available, we need to check if we end on a leading/high
39729// surrogate. In that case, we need to wait for the next two bytes in order to
39730// decode the last character properly.
39731function utf16Text(buf, i) {
39732 if ((buf.length - i) % 2 === 0) {
39733 var r = buf.toString('utf16le', i);
39734 if (r) {
39735 var c = r.charCodeAt(r.length - 1);
39736 if (c >= 0xD800 && c <= 0xDBFF) {
39737 this.lastNeed = 2;
39738 this.lastTotal = 4;
39739 this.lastChar[0] = buf[buf.length - 2];
39740 this.lastChar[1] = buf[buf.length - 1];
39741 return r.slice(0, -1);
39742 }
39743 }
39744 return r;
39745 }
39746 this.lastNeed = 1;
39747 this.lastTotal = 2;
39748 this.lastChar[0] = buf[buf.length - 1];
39749 return buf.toString('utf16le', i, buf.length - 1);
39750}
39751
39752// For UTF-16LE we do not explicitly append special replacement characters if we
39753// end on a partial character, we simply let v8 handle that.
39754function utf16End(buf) {
39755 var r = buf && buf.length ? this.write(buf) : '';
39756 if (this.lastNeed) {
39757 var end = this.lastTotal - this.lastNeed;
39758 return r + this.lastChar.toString('utf16le', 0, end);
39759 }
39760 return r;
39761}
39762
39763function base64Text(buf, i) {
39764 var n = (buf.length - i) % 3;
39765 if (n === 0) return buf.toString('base64', i);
39766 this.lastNeed = 3 - n;
39767 this.lastTotal = 3;
39768 if (n === 1) {
39769 this.lastChar[0] = buf[buf.length - 1];
39770 } else {
39771 this.lastChar[0] = buf[buf.length - 2];
39772 this.lastChar[1] = buf[buf.length - 1];
39773 }
39774 return buf.toString('base64', i, buf.length - n);
39775}
39776
39777function base64End(buf) {
39778 var r = buf && buf.length ? this.write(buf) : '';
39779 if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed);
39780 return r;
39781}
39782
39783// Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
39784function simpleWrite(buf) {
39785 return buf.toString(this.encoding);
39786}
39787
39788function simpleEnd(buf) {
39789 return buf && buf.length ? this.write(buf) : '';
39790}
39791},{"safe-buffer":247}],265:[function(require,module,exports){
39792(function (global){
39793
39794/**
39795 * Module exports.
39796 */
39797
39798module.exports = deprecate;
39799
39800/**
39801 * Mark that a method should not be used.
39802 * Returns a modified function which warns once by default.
39803 *
39804 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
39805 *
39806 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
39807 * will throw an Error when invoked.
39808 *
39809 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
39810 * will invoke `console.trace()` instead of `console.error()`.
39811 *
39812 * @param {Function} fn - the function to deprecate
39813 * @param {String} msg - the string to print to the console when `fn` is invoked
39814 * @returns {Function} a new "deprecated" version of `fn`
39815 * @api public
39816 */
39817
39818function deprecate (fn, msg) {
39819 if (config('noDeprecation')) {
39820 return fn;
39821 }
39822
39823 var warned = false;
39824 function deprecated() {
39825 if (!warned) {
39826 if (config('throwDeprecation')) {
39827 throw new Error(msg);
39828 } else if (config('traceDeprecation')) {
39829 console.trace(msg);
39830 } else {
39831 console.warn(msg);
39832 }
39833 warned = true;
39834 }
39835 return fn.apply(this, arguments);
39836 }
39837
39838 return deprecated;
39839}
39840
39841/**
39842 * Checks `localStorage` for boolean values for the given `name`.
39843 *
39844 * @param {String} name
39845 * @returns {Boolean}
39846 * @api private
39847 */
39848
39849function config (name) {
39850 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
39851 try {
39852 if (!global.localStorage) return false;
39853 } catch (_) {
39854 return false;
39855 }
39856 var val = global.localStorage[name];
39857 if (null == val) return false;
39858 return String(val).toLowerCase() === 'true';
39859}
39860
39861}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
39862},{}],266:[function(require,module,exports){
39863var v1 = require('./v1');
39864var v4 = require('./v4');
39865
39866var uuid = v4;
39867uuid.v1 = v1;
39868uuid.v4 = v4;
39869
39870module.exports = uuid;
39871
39872},{"./v1":269,"./v4":270}],267:[function(require,module,exports){
39873/**
39874 * Convert array of 16 byte values to UUID string format of the form:
39875 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
39876 */
39877var byteToHex = [];
39878for (var i = 0; i < 256; ++i) {
39879 byteToHex[i] = (i + 0x100).toString(16).substr(1);
39880}
39881
39882function bytesToUuid(buf, offset) {
39883 var i = offset || 0;
39884 var bth = byteToHex;
39885 return bth[buf[i++]] + bth[buf[i++]] +
39886 bth[buf[i++]] + bth[buf[i++]] + '-' +
39887 bth[buf[i++]] + bth[buf[i++]] + '-' +
39888 bth[buf[i++]] + bth[buf[i++]] + '-' +
39889 bth[buf[i++]] + bth[buf[i++]] + '-' +
39890 bth[buf[i++]] + bth[buf[i++]] +
39891 bth[buf[i++]] + bth[buf[i++]] +
39892 bth[buf[i++]] + bth[buf[i++]];
39893}
39894
39895module.exports = bytesToUuid;
39896
39897},{}],268:[function(require,module,exports){
39898(function (global){
39899// Unique ID creation requires a high quality random # generator. In the
39900// browser this is a little complicated due to unknown quality of Math.random()
39901// and inconsistent support for the `crypto` API. We do the best we can via
39902// feature-detection
39903var rng;
39904
39905var crypto = global.crypto || global.msCrypto; // for IE 11
39906if (crypto && crypto.getRandomValues) {
39907 // WHATWG crypto RNG - http://wiki.whatwg.org/wiki/Crypto
39908 var rnds8 = new Uint8Array(16); // eslint-disable-line no-undef
39909 rng = function whatwgRNG() {
39910 crypto.getRandomValues(rnds8);
39911 return rnds8;
39912 };
39913}
39914
39915if (!rng) {
39916 // Math.random()-based (RNG)
39917 //
39918 // If all else fails, use Math.random(). It's fast, but is of unspecified
39919 // quality.
39920 var rnds = new Array(16);
39921 rng = function() {
39922 for (var i = 0, r; i < 16; i++) {
39923 if ((i & 0x03) === 0) r = Math.random() * 0x100000000;
39924 rnds[i] = r >>> ((i & 0x03) << 3) & 0xff;
39925 }
39926
39927 return rnds;
39928 };
39929}
39930
39931module.exports = rng;
39932
39933}).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
39934},{}],269:[function(require,module,exports){
39935var rng = require('./lib/rng');
39936var bytesToUuid = require('./lib/bytesToUuid');
39937
39938// **`v1()` - Generate time-based UUID**
39939//
39940// Inspired by https://github.com/LiosK/UUID.js
39941// and http://docs.python.org/library/uuid.html
39942
39943// random #'s we need to init node and clockseq
39944var _seedBytes = rng();
39945
39946// Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
39947var _nodeId = [
39948 _seedBytes[0] | 0x01,
39949 _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5]
39950];
39951
39952// Per 4.2.2, randomize (14 bit) clockseq
39953var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff;
39954
39955// Previous uuid creation time
39956var _lastMSecs = 0, _lastNSecs = 0;
39957
39958// See https://github.com/broofa/node-uuid for API details
39959function v1(options, buf, offset) {
39960 var i = buf && offset || 0;
39961 var b = buf || [];
39962
39963 options = options || {};
39964
39965 var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq;
39966
39967 // UUID timestamps are 100 nano-second units since the Gregorian epoch,
39968 // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so
39969 // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs'
39970 // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00.
39971 var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime();
39972
39973 // Per 4.2.1.2, use count of uuid's generated during the current clock
39974 // cycle to simulate higher resolution clock
39975 var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1;
39976
39977 // Time since last uuid creation (in msecs)
39978 var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000;
39979
39980 // Per 4.2.1.2, Bump clockseq on clock regression
39981 if (dt < 0 && options.clockseq === undefined) {
39982 clockseq = clockseq + 1 & 0x3fff;
39983 }
39984
39985 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
39986 // time interval
39987 if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) {
39988 nsecs = 0;
39989 }
39990
39991 // Per 4.2.1.2 Throw error if too many uuids are requested
39992 if (nsecs >= 10000) {
39993 throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec');
39994 }
39995
39996 _lastMSecs = msecs;
39997 _lastNSecs = nsecs;
39998 _clockseq = clockseq;
39999
40000 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
40001 msecs += 12219292800000;
40002
40003 // `time_low`
40004 var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000;
40005 b[i++] = tl >>> 24 & 0xff;
40006 b[i++] = tl >>> 16 & 0xff;
40007 b[i++] = tl >>> 8 & 0xff;
40008 b[i++] = tl & 0xff;
40009
40010 // `time_mid`
40011 var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff;
40012 b[i++] = tmh >>> 8 & 0xff;
40013 b[i++] = tmh & 0xff;
40014
40015 // `time_high_and_version`
40016 b[i++] = tmh >>> 24 & 0xf | 0x10; // include version
40017 b[i++] = tmh >>> 16 & 0xff;
40018
40019 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
40020 b[i++] = clockseq >>> 8 | 0x80;
40021
40022 // `clock_seq_low`
40023 b[i++] = clockseq & 0xff;
40024
40025 // `node`
40026 var node = options.node || _nodeId;
40027 for (var n = 0; n < 6; ++n) {
40028 b[i + n] = node[n];
40029 }
40030
40031 return buf ? buf : bytesToUuid(b);
40032}
40033
40034module.exports = v1;
40035
40036},{"./lib/bytesToUuid":267,"./lib/rng":268}],270:[function(require,module,exports){
40037var rng = require('./lib/rng');
40038var bytesToUuid = require('./lib/bytesToUuid');
40039
40040function v4(options, buf, offset) {
40041 var i = buf && offset || 0;
40042
40043 if (typeof(options) == 'string') {
40044 buf = options == 'binary' ? new Array(16) : null;
40045 options = null;
40046 }
40047 options = options || {};
40048
40049 var rnds = options.random || (options.rng || rng)();
40050
40051 // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
40052 rnds[6] = (rnds[6] & 0x0f) | 0x40;
40053 rnds[8] = (rnds[8] & 0x3f) | 0x80;
40054
40055 // Copy bytes to buffer, if provided
40056 if (buf) {
40057 for (var ii = 0; ii < 16; ++ii) {
40058 buf[i + ii] = rnds[ii];
40059 }
40060 }
40061
40062 return buf || bytesToUuid(rnds);
40063}
40064
40065module.exports = v4;
40066
40067},{"./lib/bytesToUuid":267,"./lib/rng":268}],271:[function(require,module,exports){
40068var indexOf = require('indexof');
40069
40070var Object_keys = function (obj) {
40071 if (Object.keys) return Object.keys(obj)
40072 else {
40073 var res = [];
40074 for (var key in obj) res.push(key)
40075 return res;
40076 }
40077};
40078
40079var forEach = function (xs, fn) {
40080 if (xs.forEach) return xs.forEach(fn)
40081 else for (var i = 0; i < xs.length; i++) {
40082 fn(xs[i], i, xs);
40083 }
40084};
40085
40086var defineProp = (function() {
40087 try {
40088 Object.defineProperty({}, '_', {});
40089 return function(obj, name, value) {
40090 Object.defineProperty(obj, name, {
40091 writable: true,
40092 enumerable: false,
40093 configurable: true,
40094 value: value
40095 })
40096 };
40097 } catch(e) {
40098 return function(obj, name, value) {
40099 obj[name] = value;
40100 };
40101 }
40102}());
40103
40104var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function',
40105'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError',
40106'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError',
40107'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape',
40108'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape'];
40109
40110function Context() {}
40111Context.prototype = {};
40112
40113var Script = exports.Script = function NodeScript (code) {
40114 if (!(this instanceof Script)) return new Script(code);
40115 this.code = code;
40116};
40117
40118Script.prototype.runInContext = function (context) {
40119 if (!(context instanceof Context)) {
40120 throw new TypeError("needs a 'context' argument.");
40121 }
40122
40123 var iframe = document.createElement('iframe');
40124 if (!iframe.style) iframe.style = {};
40125 iframe.style.display = 'none';
40126
40127 document.body.appendChild(iframe);
40128
40129 var win = iframe.contentWindow;
40130 var wEval = win.eval, wExecScript = win.execScript;
40131
40132 if (!wEval && wExecScript) {
40133 // win.eval() magically appears when this is called in IE:
40134 wExecScript.call(win, 'null');
40135 wEval = win.eval;
40136 }
40137
40138 forEach(Object_keys(context), function (key) {
40139 win[key] = context[key];
40140 });
40141 forEach(globals, function (key) {
40142 if (context[key]) {
40143 win[key] = context[key];
40144 }
40145 });
40146
40147 var winKeys = Object_keys(win);
40148
40149 var res = wEval.call(win, this.code);
40150
40151 forEach(Object_keys(win), function (key) {
40152 // Avoid copying circular objects like `top` and `window` by only
40153 // updating existing context properties or new properties in the `win`
40154 // that was only introduced after the eval.
40155 if (key in context || indexOf(winKeys, key) === -1) {
40156 context[key] = win[key];
40157 }
40158 });
40159
40160 forEach(globals, function (key) {
40161 if (!(key in context)) {
40162 defineProp(context, key, win[key]);
40163 }
40164 });
40165
40166 document.body.removeChild(iframe);
40167
40168 return res;
40169};
40170
40171Script.prototype.runInThisContext = function () {
40172 return eval(this.code); // maybe...
40173};
40174
40175Script.prototype.runInNewContext = function (context) {
40176 var ctx = Script.createContext(context);
40177 var res = this.runInContext(ctx);
40178
40179 forEach(Object_keys(ctx), function (key) {
40180 context[key] = ctx[key];
40181 });
40182
40183 return res;
40184};
40185
40186forEach(Object_keys(Script.prototype), function (name) {
40187 exports[name] = Script[name] = function (code) {
40188 var s = Script(code);
40189 return s[name].apply(s, [].slice.call(arguments, 1));
40190 };
40191});
40192
40193exports.createScript = function (code) {
40194 return exports.Script(code);
40195};
40196
40197exports.createContext = Script.createContext = function (context) {
40198 var copy = new Context();
40199 if(typeof context === 'object') {
40200 forEach(Object_keys(context), function (key) {
40201 copy[key] = context[key];
40202 });
40203 }
40204 return copy;
40205};
40206
40207},{"indexof":162}],"nebulas":[function(require,module,exports){
40208var HttpRequest = require("./lib/httprequest");
40209var Neb = require('./lib/neb');
40210var Account = require('./lib/account');
40211var Transaction = require('./lib/transaction');
40212var Utils = require('./lib/utils/utils');
40213var CryptoUtils = require('./lib/utils/crypto-utils');
40214var Unit = require('./lib/utils/unit');
40215var NVM = require('./lib/nvm/nvm');
40216
40217// dont override global variable
40218if (typeof window !== 'undefined' && typeof window.Neb === 'undefined') {
40219 window.Neb = Neb;
40220}
40221
40222module.exports = {
40223 HttpRequest: HttpRequest,
40224 Neb: Neb,
40225 Account: Account,
40226 Transaction: Transaction,
40227 Utils: Utils,
40228 CryptoUtils: CryptoUtils,
40229 Unit: Unit,
40230 NVM: NVM
40231};
40232
40233},{"./lib/account":1,"./lib/httprequest":4,"./lib/neb":5,"./lib/nvm/nvm":16,"./lib/transaction":18,"./lib/utils/crypto-utils":19,"./lib/utils/unit":20,"./lib/utils/utils":21}],"node-localstorage.js":[function(require,module,exports){
40234'use strict';
40235
40236// go env doesn't have and need localStorage
40237
40238if (typeof localStorage === 'undefined') {
40239 exports.localStorage = {};
40240} else {
40241 exports.localStorage = localStorage; // jshint ignore:line
40242}
40243
40244},{}]},{},[]);