1 require
=(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
){
4 var Buffer
= require('safe-buffer').Buffer
;
5 var Base58
= require('bs58');
6 var cryptoUtils
= require('./utils/crypto-utils.js');
7 var utils
= require('./utils/utils.js');
9 var AddressLength
= 26;
10 var AddressPrefix
= 25;
12 var ContractType
= 88;
15 var KeyCurrentVersion
= 4;
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
34 * @typedef {Object} Key
35 * @property {Number} version
36 * @property {Buffer} id
37 * @property {HexString} address
38 * @property {Object} crypto
43 * Account constructor.
44 * Class encapsulate main operation with account entity.
47 * @param {Hash} priv Account private key.
48 * @param {String} path
50 * @example var account = new Account(new Buffer("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6", "hex") );
53 var Account = function (priv
, path
) {
54 priv
= priv
|| cryptoUtils
.crypto
.randomBytes(32);
55 this.setPrivateKey(priv
);
60 * Account factory method.
61 * Create random account.
64 * @return {Account} Instance of Account constructor.
66 * @example var account = Account.NewAccount();
68 Account
.NewAccount = function () {
69 return new Account(cryptoUtils
.crypto
.randomBytes(32));
73 * Address validation method.
76 * @param {String/Hash} addr - Account address.
77 * @param {Number} type - NormalType / ContractType
79 * @return {Boolean} Is address has correct format.
82 * if ( Account.isValidAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5") ) {
86 Account
.isValidAddress = function (addr
, type
) {
87 /*jshint maxcomplexity:10 */
89 if (utils
.isString(addr
)) {
91 addr
= Base58
.decode(addr
);
93 console
.log("invalid address.");
94 // if address can't be base58 decode, return false.
97 } else if (!Buffer
.isBuffer(addr
)) {
100 // address not equal to 26
101 if (addr
.length
!== AddressLength
) {
105 // check if address start with AddressPrefix
106 var buff
= Buffer
.from(addr
);
107 if (buff
.readUIntBE(0, 1) !== AddressPrefix
) {
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
)) {
117 } else if (t
!== NormalType
&& t
!== ContractType
) {
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;
126 * Restore account from address.
127 * Receive addr or Account instance.
128 * If addr is Account instance return new Account instance with same PrivateKey.
131 * @param {(Hash|Object)} - Client address or Account instance.
133 * @return {Account} Instance of Account restored from address.
135 * @example var account = Account.fromAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5");
137 Account
.fromAddress = function (addr
) {
138 var acc
= new Account();
139 if (addr
instanceof Account
) {
140 acc
.setPrivateKey(addr
.getPrivateKey());
143 if (utils
.isString(addr
) && this.isValidAddress(addr
)) {
144 acc
.address
= Base58
.decode(addr
);
148 var buf
= cryptoUtils
.toBuffer(addr
);
149 if (this.isValidAddress(buf
)) {
153 throw new Error("invalid address");
157 * Restore account from public key.
160 * @param {(String/Hash)} - Public key.
162 * @return {Account} Instance of Account restored from address.
164 * @example var account = Account.fromPubKey("f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7");
166 Account
.fromPubKey = function (publicKey
) {
167 var acc
= new Account();
168 acc
.pubKey
= cryptoUtils
.toBuffer(publicKey
);
172 Account
.getNormalType = function () {
176 Account
.getContractType = function () {
180 Account
.prototype = {
182 * Private Key setter.
184 * @param {Hash} priv - Account private key.
186 * @example account.setPrivateKey("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6");
188 setPrivateKey: function (priv
) {
189 if (utils
.isString(priv
) || Buffer
.isBuffer(priv
)) {
190 this.privKey
= priv
.length
=== 32 ? priv : Buffer(priv
, 'hex');
196 * Private Key getter.
198 * @return {Buffer} Account private key.
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
203 getPrivateKey: function () {
207 * Get Private Key in hex string format.
209 * @return {HexString} Account private key in String format.
211 * @example var privKey = account.getPrivateKeyString();
212 * //"ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6"
214 getPrivateKeyString: function () {
215 return this.getPrivateKey().toString('hex');
220 * @return {Buffer} Account public key.
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 ... >
225 getPublicKey: function () {
226 if (utils
.isNull(this.pubKey
)) {
227 this.pubKey
= cryptoUtils
.privateToPublic(this.privKey
);
232 * Get Public Key in hex string format.
234 * @return {HexString} Account public key in String format.
236 * @example var publicKey = account.getPublicKey();
237 * //"f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7"
239 getPublicKeyString: function () {
240 return this.getPublicKey().toString('hex');
243 * Accaunt address getter.
245 * @return {Buffer} Account address.
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>
250 getAddress: function () {
251 if (utils
.isNull(this.address
)) {
253 var pubKey
= this.getPublicKey();
254 if (pubKey
.length
!== 64) {
255 pubKey
= cryptoUtils
.secp256k1
.publicKeyConvert(pubKey
, false).slice(1);
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
]);
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
]);
274 * Get account address in hex string format.
276 * @return {HexString} Account address in String format.
278 * @example var publicKey = account.getAddressString();
279 * //"802d529bf55d6693b3ac72c59b4a7d159da53cae5a7bf99c"
281 getAddressString: function () {
282 var addr
= this.getAddress();
283 return Base58
.encode(addr
);
286 * Generate key buy passphrase and options.
288 * @param {Password} password - Provided password.
289 * @param {KeyOptions} opts - Key options.
291 * @return {Key} Key Object.
293 * @example var key = account.toKey("passphrase");
295 toKey: function (password
, opts
) {
296 /*jshint maxcomplexity:17 */
299 var salt
= opts
.salt
|| cryptoUtils
.crypto
.randomBytes(32);
300 var iv
= opts
.iv
|| cryptoUtils
.crypto
.randomBytes(16);
302 var kdf
= opts
.kdf
|| 'scrypt';
304 dklen: opts
.dklen
|| 32,
305 salt: salt
.toString('hex')
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
);
317 throw new Error('Unsupported kdf');
319 var cipher
= cryptoUtils
.crypto
.createCipheriv(opts
.cipher
|| 'aes-128-ctr', derivedKey
.slice(0, 16), iv
);
321 throw new Error('Unsupported cipher');
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')]));
327 version: KeyCurrentVersion
,
328 id: cryptoUtils
.uuid
.v4({
329 random: opts
.uuid
|| cryptoUtils
.crypto
.randomBytes(16)
331 address: this.getAddressString(),
333 ciphertext: ciphertext
.toString('hex'),
335 iv: iv
.toString('hex')
337 cipher: opts
.cipher
|| 'aes-128-ctr',
339 kdfparams: kdfparams
,
340 mac: mac
.toString('hex'),
346 * Generate key buy passphrase and options.
347 * Return in JSON format.
349 * @param {Password} password - Provided password.
350 * @param {KeyOptions} opts - Key options.
352 * @return {String} JSON stringify Key.
354 * @example var key = account.toKeyString("passphrase");
356 toKeyString: function (password
, opts
) {
357 return JSON
.stringify(this.toKey(password
, opts
));
360 * Restore account from key and passphrase.
362 * @param {Key} input - Key Object.
363 * @param {Password} password - Provided password.
364 * @param {Boolean} nonStrict - Strict сase sensitivity flag.
366 * @return {@link Account} - Instance of Account restored from key and passphrase.
368 fromKey: function (input
, password
, nonStrict
) {
369 /*jshint maxcomplexity:10 */
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');
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');
385 derivedKey
= cryptoUtils
.crypto
.pbkdf2Sync(new Buffer(password
), new Buffer(kdfparams
.salt
, 'hex'), kdfparams
.c
, kdfparams
.dklen
, 'sha256');
387 throw new Error('Unsupported key derivation scheme');
389 var ciphertext
= new Buffer(json
.crypto
.ciphertext
, 'hex');
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
)]));
396 mac
= cryptoUtils
.sha3(Buffer
.concat([derivedKey
.slice(16, 32), ciphertext
]));
399 if (mac
.toString('hex') !== json
.crypto
.mac
) {
400 throw new Error('Key derivation failed - possibly wrong passphrase');
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
]);
408 this.setPrivateKey(seed
);
414 module
.exports
= Account
;
416 },{"./utils/crypto-utils.js":19,"./utils/utils.js":21,"bs58":105,"safe-buffer":247}],2:[function(require
,module
,exports
){
420 var utils
= require('./utils/utils.js');
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}.
428 * @param {Neb} neb - Instance of Neb library.
431 * var admin = new Admin( new Neb() );
433 * var admin = new Neb().admin;
435 var Admin = function (neb
) {
436 this._setRequest(neb
._request
);
441 * @param {Request} request - transport wrapper.
443 Admin
.prototype._setRequest = function (request
) {
444 this._request
= request
;
445 this._path
= '/admin';
449 * Method get info about nodes in Nebulas Network.
450 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#nodeinfo}
452 * @return [nodeInfoObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#nodeinfo}
455 * var admin = new Neb().admin;
456 * admin.nodeInfo().then(function(info) {
460 Admin
.prototype.nodeInfo = function () {
461 return this._sendRequest("get", "/nodeinfo", null);
465 * Method get list of available addresses.
466 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#accounts}
468 * @return [accountsList]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#accounts}
471 * var admin = new Neb().admin;
472 * admin.accounts().then(function(accounts) {
476 Admin
.prototype.accounts = function () {
477 return this._sendRequest("get", "/accounts", null);
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}
484 * @param {Object} options
485 * @param {Password} options.passphrase
487 * @return [address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#newaccount}
490 * var admin = new Neb().admin;
491 * admin.newAccount({passphrase: "passphrase"}).then(function(address) {
495 Admin
.prototype.newAccount = function (options
) {
496 options
= utils
.argumentsToObject(['passphrase'], arguments
);
497 var params
= { "passphrase": options
.passphrase
};
498 return this._sendRequest("post", "/account/new", params
);
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}
506 * @param {Object} options
507 * @param {HexString} options.address
508 * @param {Password} options.passphrase
509 * @param {Number} options.duration
511 * @return [isUnLocked]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#unlockaccount}
514 * var admin = new Neb().admin;
515 * admin.unlockAccount({
516 * address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh",
517 * passphrase: "passphrase",
518 * duration: 1000000000
519 * }).then(function(isUnLocked) {
523 Admin
.prototype.unlockAccount = function (options
) {
524 options
= utils
.argumentsToObject(['address', 'passphrase', 'duration'], arguments
);
526 "address": options
.address
,
527 "passphrase": options
.passphrase
,
528 "duration": options
.duration
530 return this._sendRequest("post", "/account/unlock", params
);
534 * Method lock account.
535 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#lockaccount}
537 * @param {Object} options
538 * @param {HexString} options.address
540 * @return [isLocked]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#lockaccount}
543 * var admin = new Neb().admin;
544 * admin.lockAccount({address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh"}).then(function(isLocked) {
548 Admin
.prototype.lockAccount = function (options
) {
549 options
= utils
.argumentsToObject(['address'], arguments
);
550 var params
= { "address": options
.address
};
551 return this._sendRequest("post", "/account/lock", params
);
555 * Method wrap transaction sending functionality.
556 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransaction}
558 * @param {TransactionOptions} options
560 * @return [Transcation hash and contract address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransaction}
563 * var admin = new Neb().admin;
564 * admin.sendTransaction({
565 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
566 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
571 * }).then(function(tx) {
575 Admin
.prototype.sendTransaction = function (options
) {
576 options
= utils
.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary'], arguments
);
578 "from": options
.from,
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
587 return this._sendRequest("post", "/transaction", params
);
592 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signhash}
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
599 * @return [data]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signhash}
602 * var admin = new Neb().admin;
604 * address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh",
605 * hash: "OGQ5NjllZWY2ZWNhZDNjMjlhM2E2MjkyODBlNjg2Y2YwYzNmNWQ1YTg2YWZmM2NhMTIwMjBjOTIzYWRjNmM5Mg==",
607 * }).then(function(data) {
611 Admin
.prototype.signHash = function (options
) {
612 options
= utils
.argumentsToObject(['address', 'hash', 'alg'], arguments
);
614 "address": options
.address
,
615 "hash": options
.hash
,
618 return this._sendRequest("post", "/sign/hash", params
);
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}
626 * @param {TransactionOptions} options
627 * @param {Password} options.passphrase
629 * @return [Transcation hash and contract address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signtransactionwithpassphrase}
632 * var admin = new Neb().admin;
633 * admin.signTransactionWithPassphrase({
634 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
635 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
640 * passphrase: "passphrase"
641 * }).then(function(tx) {
645 Admin
.prototype.signTransactionWithPassphrase = function (options
) {
646 options
= utils
.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary', 'passphrase'], arguments
);
648 "from": options
.from,
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
659 "passphrase": options
.passphrase
661 return this._sendRequest("post", "/sign", params
);
665 * Method send transaction with passphrase.
666 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransactionwithpassphrase}
668 * @param {TransactionOptions} options
669 * @param {Password} options.passphrase
671 * @return [data]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransactionwithpassphrase}
674 * var admin = new Neb().admin;
675 * admin.sendTransactionWithPassphrase({
676 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
677 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
682 * passphrase: "passphrase"
683 * }).then(function(tx) {
687 Admin
.prototype.sendTransactionWithPassphrase = function (options
) {
688 options
= utils
.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary', 'passphrase'], arguments
);
690 "from": options
.from,
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
701 "passphrase": options
.passphrase
703 return this._sendRequest("post", "/transactionWithPassphrase", params
);
707 * Method start listen provided port.
708 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#startpprof}
710 * @param {Object} options
711 * @param {String} options.listen - Listen port.
713 * @return [isListenStrted]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#startpprof}
716 * var admin = new Neb().admin;
717 * admin.startPprof({listen: '8080'}).then(function(isListenStrted) {
721 Admin
.prototype.startPprof = function (options
) {
722 options
= utils
.argumentsToObject(['listen'], arguments
);
723 var params
= { "listen": options
.listen
};
724 return this._sendRequest("post", "/pprof", params
);
728 * Method get config of node in Nebulas Network.
729 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#getConfig}
731 * @return [config]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#getConfig}
734 * var admin = new Neb().admin;
735 * admin.getConfig().then(function(info) {
739 Admin
.prototype.getConfig = function () {
740 return this._sendRequest("get", "/getConfig", null);
743 Admin
.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
);
748 return this._request
.request(method
, action
, params
);
752 module
.exports
= Admin
;
754 },{"./utils/utils.js":21}],3:[function(require
,module
,exports
){
758 var utils
= require('./utils/utils.js');
761 * User API constructor.
762 * Class encapsulate methods for building distributed applications and services.
764 * @see [API documentation]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md}
767 * @param {Neb} neb - Instance of Neb library.
770 * var api = new API ( new Neb() );
772 * var api = new Neb().api;
774 var API = function (neb
) {
775 this._setRequest(neb
._request
);
780 * @param {Request} request - transport wrapper.
782 API
.prototype._setRequest = function (request
) {
783 this._request
= request
;
784 this._path
= '/user';
788 * Method get state of Nebulas Network.
789 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getnebstate}
791 * @return [NebStateObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getnebstate}
794 * var api = new Neb().api;
795 * api.getNebState().then(function(state) {
799 API
.prototype.getNebState = function () {
800 return this._sendRequest("get", "/nebstate", null);
804 * Method get latest irreversible block of Nebulas Network.
805 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#latestirreversibleblock}
807 * @return [dataBlockInfo.]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#latestirreversibleblock}
810 * var api = new Neb().api;
811 * api.latestIrreversibleBlock().then(function(blockData) {
815 API
.prototype.latestIrreversibleBlock = function () {
816 return this._sendRequest("get", "/lib", null);
820 * Method return the state of the account. Balance and nonce.
821 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getaccountstate}
823 * @param {Object} options
824 * @param {HexString} options.address
825 * @param {String} options.height
827 * @return [accaountStateObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getaccountstate}
830 * var api = new Neb().api;
831 * api.getAccountState({address: "n1QsosVXKxiV3B4iDWNmxfN4VqpHn2TeUcn"}).then(function(state) {
835 API
.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
);
842 * Method wrap smart contract call functionality.
843 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#call}
845 * @param {TransactionOptions} options
847 * @return [Transcation hash]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#call}
850 * var api = new Neb().api;
853 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
854 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
863 * }).then(function(tx) {
867 API
.prototype.call = function (options
) {
868 options
= utils
.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments
);
870 "from": options
.from,
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
878 return this._sendRequest("post", "/call", params
);
882 * Method wrap submit the signed transaction.
883 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction}
885 * @param {Object} options
886 * @param {String} options.data
888 * @return [Transcation hash]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction}
891 * var api = new Neb().api;
892 * var tx = new Transaction({
901 * tx.signTransaction();
902 * api.sendRawTransaction( {data: tx.toProtoString()} ).then(function(hash) {
906 API
.prototype.sendRawTransaction = function (options
) {
907 options
= utils
.argumentsToObject(['data'], arguments
);
908 var params
= { "data": options
.data
};
909 return this._sendRequest("post", "/rawtransaction", params
);
913 * Get block header info by the block hash.
914 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyhash}
916 * @param {Object} options
917 * @param {HexString} options.hash
918 * @param {Boolean} options.fullTransaction
920 * @return [Block]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyhash}
923 * var api = new Neb().api;
924 * api.getBlockByHash({
925 * hash: "00000658397a90df6459b8e7e63ad3f4ce8f0a40b8803ff2f29c611b2e0190b8",
926 * fullTransaction: true
927 * }).then(function(block) {
931 API
.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
);
938 * Get block header info by the block height.
939 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyheight}
941 * @param {Object} options
942 * @param {Number} options.height
943 * @param {Boolean} options.fullTransaction
945 * @return [Block]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyheight}
948 * var api = new Neb().api;
949 * api.getBlockByHeight({height:2, fullTransaction:true}).then(function(block) {
953 API
.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
);
960 * Get transactionReceipt info by tansaction hash.
961 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt}
963 * @param {Object} options
964 * @param {HexString} options.hash
966 * @return [TransactionReceipt]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt}
969 * var api = new Neb().api;
970 * api.getTransactionReceipt({hash: "cc7133643a9ae90ec9fa222871b85349ccb6f04452b835851280285ed72b008c"}).then(function(receipt) {
974 API
.prototype.getTransactionReceipt = function (options
) {
975 options
= utils
.argumentsToObject(['hash'], arguments
);
976 var params
= { "hash": options
.hash
};
977 return this._sendRequest("post", "/getTransactionReceipt", params
);
981 * Get transactionReceipt info by contract address.
982 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionbycontract}
984 * @param {Object} options
985 * @param {HexString} options.address contract address
987 * @returns the same as [TransactionReceipt]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt}
990 * var api = new Neb().api;
991 * api.getTransactionByContract({address: "n1sqDHGjYtX6rMqFoq5Tow3s3LqF4ZxBvE3"}).then(function(receipt) {
995 API
.prototype.getTransactionByContract = function (options
) {
996 options
= utils
.argumentsToObject(['address'], arguments
);
997 var params
= { "address": options
.address
};
998 return this._sendRequest("post", "/getTransactionByContract", params
);
1002 * Return the subscribed events of transaction & block.
1003 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#subscribe}
1005 * @param {Object} options
1006 * @param {Array|String} options.topics
1007 * @param {Function} options.onDownloadProgress - On progress callback function. Recive chunk.
1009 * @return [eventData]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#subscribe}
1012 * var api = new Neb().api;
1013 * api.subscribe({topics: ["chain.linkBlock", "chain.pendingTransaction"]}).then(function(eventData) {
1017 API
.prototype.subscribe = function (options
) {
1018 options
= utils
.argumentsToObject(['topics', 'onDownloadProgress'], arguments
);
1019 var params
= { "topics": options
.topics
};
1021 if (typeof options
.onDownloadProgress
=== 'function') {
1023 onDownloadProgress: function (e
) {
1024 if (typeof e
.target
._readLength
=== 'undefined') {
1025 e
.target
._readLength
= 0;
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
);
1036 return this._sendRequest("post", "/subscribe", params
, null, axiosOptions
);
1040 * Return current gasPrice.
1041 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getgasprice}
1043 * @return [Gas Price]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getgasprice}
1046 * var api = new Neb().api;
1047 * api.gasPrice().then(function(gasPrice) {
1051 API
.prototype.gasPrice = function () {
1052 return this._sendRequest("get", "/getGasPrice", null);
1056 * Return the estimate gas of transaction.
1057 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#estimategas}
1059 * @param {TransactionOptions} options
1061 * @return [Gas]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#estimategas}
1064 * var api = new Neb().api;
1067 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
1068 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
1071 * gasPrice: 1000000,
1073 * }).then(function(gas) {
1077 API
.prototype.estimateGas = function (options
) {
1078 options
= utils
.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary'], arguments
);
1080 "from": options
.from,
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
1089 return this._sendRequest("post", "/estimateGas", params
);
1093 * Return the events list of transaction.
1094 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#geteventsbyhash}
1096 * @param {Object} options
1097 * @param {HexString} options.hash
1099 * @return [Events]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#geteventsbyhash}
1102 * var api = new Neb().api;
1103 * api.getEventsByHash({hash: "ec239d532249f84f158ef8ec9262e1d3d439709ebf4dd5f7c1036b26c6fe8073"}).then(function(events) {
1107 API
.prototype.getEventsByHash = function (options
) {
1108 options
= utils
.argumentsToObject(['hash'], arguments
);
1109 var params
= { "hash": options
.hash
};
1110 return this._sendRequest("post", "/getEventsByHash", params
);
1114 * Method getter for dpos dynasty.
1115 * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getdynasty}
1117 * @param {Object} options
1118 * @param {Number} options.height
1120 * @return [delegatees]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getdynasty}
1123 * var api = new Neb().api;
1124 * api.getDynasty({height: 1}).then(function(delegatees) {
1128 API
.prototype.getDynasty = function (options
) {
1129 options
= utils
.argumentsToObject(['height'], arguments
);
1130 var params
= { "height": options
.height
};
1131 return this._sendRequest("post", "/dynasty", params
);
1134 API
.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
);
1139 return this._request
.request(method
, action
, params
, axiosOptions
);
1143 module
.exports
= API
;
1145 },{"./utils/utils.js":21}],4:[function(require
,module
,exports
){
1148 var axios
= require("axios");
1150 var debugLog
= false;
1152 var HttpRequest = function (host
, timeout
, apiVersion
) {
1153 this.host
= host
|| "http://localhost:8685";
1154 this.timeout
= timeout
|| 0;
1155 this.apiVersion
= apiVersion
|| "v1";
1158 HttpRequest
.prototype.setHost = function (host
) {
1162 HttpRequest
.prototype.setAPIVersion = function (apiVersion
) {
1163 this.apiVersion
= apiVersion
;
1166 HttpRequest
.prototype.createUrl = function (api
) {
1167 return this.host
+ "/" + this.apiVersion
+ api
;
1170 HttpRequest
.prototype.request = function (method
, api
, payload
, axiosOptions
) {
1172 console
.log("[debug] HttpRequest: " + method
+ " " + this.createUrl(api
) + " " + JSON
.stringify(payload
));
1177 url: this.createUrl(api
),
1180 if (axiosOptions
&& typeof axiosOptions
.onDownloadProgress
=== 'function') {
1181 axiosParams
.onDownloadProgress
= axiosOptions
.onDownloadProgress
;
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
);
1187 if (typeof resp
.data
=== "string") {
1189 resp
.data
= JSON
.parse(resp
.data
);
1191 throw new Error('Response is invalid json');
1194 return resp
.data
.result
|| resp
.data
;
1195 }).catch(function (e
) {
1196 if (typeof e
.response
!== "undefined") {
1197 if (typeof e
.response
.data
=== 'object') {
1199 throw new Error(e
.response
.data
.error
);
1202 var err
= e
.response
.status
+ ' - ' + e
.response
.statusText
;
1203 err
+= "\n" + api
+ " " + JSON
.stringify(payload
);
1204 throw new Error(err
);
1207 throw new Error(e
.message
);
1212 HttpRequest
.prototype.asyncRequest = function (method
, api
, payload
, callback
) {
1213 return this.request(method
, api
, payload
).then(function (data
) {
1215 }).catch(function (err
) {
1220 module
.exports
= HttpRequest
;
1222 },{"axios":46}],5:[function(require
,module
,exports
){
1226 var API
= require("./api.js");
1227 var Admin
= require("./admin.js");
1229 var Unit
= require("./utils/unit.js");
1232 * Neb API library constructor.
1234 * @param {Request} request - transport wrapper.
1236 var Neb = function (request
) {
1238 this._request
= request
;
1241 this.api
= new API(this);
1242 this.admin
= new Admin(this);
1245 Neb
.prototype.setRequest = function (request
) {
1246 this._request
= request
;
1247 this.api
._setRequest(request
);
1248 this.admin
._setRequest(request
);
1251 Neb
.prototype.toBasic
= Unit
.toBasic
;
1252 Neb
.prototype.fromBasic
= Unit
.fromBasic
;
1253 Neb
.prototype.nasToBasic
= Unit
.nasToBasic
;
1255 module
.exports
= Neb
;
1257 },{"./admin.js":2,"./api.js":3,"./utils/unit.js":20}],6:[function(require
,module
,exports
){
1277 var state = function () {};
1281 transaction: transaction
,
1285 },{}],7:[function(require
,module
,exports
){
1286 // Copyright (C) 2017 go-nebulas authors
1288 // This file is part of the go-nebulas library.
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.
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.
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/>.
1306 var Blockchain = function () {
1307 Object
.defineProperty(this, "nativeBlockchain", {
1308 configurable: false,
1311 return _native_blockchain
;
1316 Blockchain
.prototype = {
1317 AccountAddress: 0x57,
1318 ContractAddress: 0x58,
1320 blockParse: function (str
) {
1321 this.block
= JSON
.parse(str
);
1323 transactionParse: function (str
) {
1324 var tx
= JSON
.parse(str
);
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
;
1335 transfer: function (address
, value
) {
1336 if (!(value
instanceof BigNumber
)) {
1337 value
= new BigNumber(value
);
1339 var ret
= this.nativeBlockchain
.transfer(address
, value
.toString(10));
1342 verifyAddress: function (address
) {
1343 return this.nativeBlockchain
.verifyAddress(address
);
1346 module
.exports
= new Blockchain();
1348 },{}],8:[function(require
,module
,exports
){
1349 // Copyright (C) 2017 go-nebulas authors
1351 // This file is part of the go-nebulas library.
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.
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.
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/>.
1369 function Console() {}
1371 function log(...args
) {
1372 var level
= args
.shift();
1373 if (typeof level
!= 'number') {
1374 throw 'level must be number.';
1378 for (var i
= 0; i
< args
.length
- 1; i
++) {
1379 msg
+= format(args
[i
]) + ' ';
1381 msg
+= format(args
[args
.length
- 1]);
1383 _native_log(level
, msg
);
1386 function format(obj
) {
1387 if (typeof obj
== 'object') {
1388 return JSON
.stringify(obj
);
1393 [['debug', 1], ['warn', 2], ['info', 3], ['log', 3], ['error', 4]].forEach(function (val
) {
1394 Console
.prototype[val
[0]] = log
.bind(null, val
[1]);
1397 module
.exports
= new Console();
1398 module
.exports
.Console
= Console
;
1400 },{}],9:[function(require
,module
,exports
){
1401 // Copyright (C) 2017 go-nebulas authors
1403 // This file is part of the go-nebulas library.
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.
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.
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/>.
1421 exports
["Trigger"] = function (topic
, data
) {
1422 _native_event_trigger(topic
, JSON
.stringify(data
));
1425 },{}],10:[function(require
,module
,exports
){
1426 // Copyright (C) 2017 go-nebulas authors
1428 // This file is part of the go-nebulas library.
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.
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.
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/>.
1446 var fieldNameRe
= /^[a-zA-Z_$][a-zA-Z0-9_]+$/;
1448 var combineStorageMapKey = function (fieldName
, key
) {
1449 return "@" + fieldName
+ "[" + key
+ "]";
1452 var applyMapDescriptor = function (obj
, descriptor
) {
1453 descriptor
= Object
.assign({
1454 stringify: JSON
.stringify
,
1456 }, descriptor
|| {});
1458 if (typeof descriptor
.stringify
!== 'function' || typeof descriptor
.parse
!== 'function') {
1459 throw new Error("descriptor.stringify and descriptor.parse must be function.");
1462 Object
.defineProperty(obj
, "stringify", {
1463 configurable: false,
1466 return descriptor
.stringify
;
1470 Object
.defineProperty(obj
, "parse", {
1471 configurable: false,
1474 return descriptor
.parse
;
1479 var applyFieldDescriptor = function (obj
, fieldName
, descriptor
) {
1480 descriptor
= Object
.assign({
1481 stringify: JSON
.stringify
,
1483 }, descriptor
|| {});
1485 if (typeof descriptor
.stringify
!== 'function' || typeof descriptor
.parse
!== 'function') {
1486 throw new Error("descriptor.stringify and descriptor.parse must be function.");
1489 Object
.defineProperty(obj
, "__stringify__" + fieldName
, {
1490 configurable: false,
1493 return descriptor
.stringify
;
1497 Object
.defineProperty(obj
, "__parse__" + fieldName
, {
1498 configurable: false,
1501 return descriptor
.parse
;
1506 var ContractStorage = function (handler
) {
1507 var ns
= new NativeStorage(handler
);
1508 Object
.defineProperty(this, "nativeStorage", {
1509 configurable: false,
1517 var StorageMap = function (contractStorage
, fieldName
, descriptor
) {
1518 if (!contractStorage
instanceof ContractStorage
) {
1519 throw new Error("StorageMap only accept instance of ContractStorage");
1522 if (typeof fieldName
!== "string" || fieldNameRe
.exec(fieldName
) == null) {
1523 throw new Error("StorageMap fieldName must match regex /^[a-zA-Z_$].*$/");
1526 Object
.defineProperty(this, "contractStorage", {
1527 configurable: false,
1530 return contractStorage
;
1533 Object
.defineProperty(this, "fieldName", {
1534 configurable: false,
1541 applyMapDescriptor(this, descriptor
);
1544 StorageMap
.prototype = {
1545 del: function (key
) {
1546 return this.contractStorage
.del(combineStorageMapKey(this.fieldName
, key
));
1548 get: function (key
) {
1549 var val
= this.contractStorage
.rawGet(combineStorageMapKey(this.fieldName
, key
));
1551 val
= this.parse(val
);
1555 set: function (key
, value
) {
1556 var val
= this.stringify(value
);
1557 return this.contractStorage
.rawSet(combineStorageMapKey(this.fieldName
, key
), val
);
1560 StorageMap
.prototype.put
= StorageMap
.prototype.set;
1561 StorageMap
.prototype.delete = StorageMap
.prototype.del
;
1563 ContractStorage
.prototype = {
1564 rawGet: function (key
) {
1565 return this.nativeStorage
.get(key
);
1567 rawSet: function (key
, value
) {
1568 var ret
= this.nativeStorage
.set(key
, value
);
1570 throw new Error("set key " + key
+ " failed.");
1574 del: function (key
) {
1575 var ret
= this.nativeStorage
.del(key
);
1577 throw new Error("del key " + key
+ " failed.");
1581 get: function (key
) {
1582 var val
= this.rawGet(key
);
1584 val
= JSON
.parse(val
);
1588 set: function (key
, value
) {
1589 return this.rawSet(key
, JSON
.stringify(value
));
1591 defineProperty: function (obj
, fieldName
, descriptor
) {
1592 if (!obj
|| !fieldName
) {
1593 throw new Error("defineProperty requires at least two parameters.");
1596 Object
.defineProperty(obj
, fieldName
, {
1597 configurable: false,
1600 var val
= $this.rawGet(fieldName
);
1602 val
= obj
["__parse__" + fieldName
](val
);
1606 set: function (val
) {
1607 val
= obj
["__stringify__" + fieldName
](val
);
1608 return $this.rawSet(fieldName
, val
);
1611 applyFieldDescriptor(obj
, fieldName
, descriptor
);
1614 defineProperties: function (obj
, props
) {
1615 if (!obj
|| !props
) {
1616 throw new Error("defineProperties requires two parameters.");
1619 for (const fieldName
in props
) {
1620 this.defineProperty(obj
, fieldName
, props
[fieldName
]);
1624 defineMapProperty: function (obj
, fieldName
, descriptor
) {
1625 if (!obj
|| !fieldName
) {
1626 throw new Error("defineMapProperty requires two parameters.");
1629 var mapObj
= new StorageMap(this, fieldName
, descriptor
);
1630 Object
.defineProperty(obj
, fieldName
, {
1631 configurable: false,
1639 defineMapProperties: function (obj
, props
) {
1640 if (!obj
|| !props
) {
1641 throw new Error("defineMapProperties requires two parameters.");
1644 for (const fieldName
in props
) {
1645 this.defineMapProperty(obj
, fieldName
, props
[fieldName
]);
1651 ContractStorage
.prototype.put
= ContractStorage
.prototype.set;
1652 ContractStorage
.prototype.delete = ContractStorage
.prototype.del
;
1654 var lcs
= new ContractStorage(_native_storage_handlers
.lcs
);
1655 var gcs
= new ContractStorage(_native_storage_handlers
.gcs
);
1656 var obj
= { ContractStorage: ContractStorage
};
1657 Object
.defineProperty(obj
, "lcs", {
1658 configurable: false,
1665 Object
.defineProperty(obj
, "gcs", {
1666 configurable: false,
1673 module
.exports
= Object
.freeze(obj
);
1675 },{}],11:[function(require
,module
,exports
){
1676 (function (global
,__dirname
){
1681 if (typeof window
!== "undefined") {
1685 if (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
);
1692 global
.context
= require("./context");
1693 global
._native_blockchain
= require("./native/blockchain");
1694 global
._native_log
= require("./native/log");
1695 global
._native_event_trigger
= require("./native/event");
1696 global
._native_storage_handlers
= require("./native/storage").handlers
;
1697 global
.NativeStorage
= require("./native/storage").NativeStorage
;
1699 global
.nativeConsole
= global
.console
;
1700 global
.console
= require("./libs/console");
1701 global
.ContractStorage
= require("./libs/storage");
1702 global
.LocalContractStorage
= global
.ContractStorage
.lcs
;
1703 // global.GlobalContractStorage = ContractStorage.gcs;
1704 global
.BigNumber
= require("bignumber.js");
1705 global
.Blockchain
= require("./libs/blockchain");
1706 global
.Event
= require("./libs/event");
1708 // global.Date = require('./libs/date');
1709 // global.Math.random = require('./libs/random');
1710 // global.BigNumber.random = global.Math.random;
1713 context: global
.context
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
){
1720 var Account
= require("../../account");
1722 var transfer = function (to
, value
) {
1723 // TODO: mock the transfer func in nebulas
1727 var verifyAddress = function (address
) {
1728 return Account
.isValidAddress(address
);
1733 verifyAddress: verifyAddress
1736 },{"../../account":1}],13:[function(require
,module
,exports
){
1739 var trigger = function (topic
, data
) {
1744 var key
= context
.transaction
.hash
;
1745 var events
= localStorage
.getItem(key
);
1746 if (events
=== null || typeof events
=== "undefined") {
1747 events
= new Array();
1749 events
= Array
.from(events
);
1752 localStorage
.setItem(key
, events
);
1755 module
.exports
= trigger
;
1757 },{}],14:[function(require
,module
,exports
){
1760 var log = function (level
, msg
) {
1774 var log
= levelStr
+ ":" + msg
;
1775 nativeConsole
.log(log
);
1778 module
.exports
= log
;
1780 },{}],15:[function(require
,module
,exports
){
1788 var NativeStorage = function (handler
) {
1789 this.handler
= handler
;
1792 NativeStorage
.prototype = {
1793 get: function (key
) {
1794 return localStorage
.getItem(key
);
1796 set: function (key
, value
) {
1797 localStorage
.setItem(key
, value
);
1800 del: function (key
) {
1801 localStorage
.removeItem(key
);
1808 NativeStorage: NativeStorage
1811 },{}],16:[function(require
,module
,exports
){
1814 var extend
= require('extend');
1815 var native = require("./native");
1817 var funcRegex
= new RegExp("^[a-zA-Z$][A-Za-z0-9_$]*$");
1819 var 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);
1827 deploy: function (source
, args
) {
1828 return this.run(source
, "init", args
);
1830 call: function (source
, func
, args
) {
1831 if (funcRegex
.test(func
)) {
1832 return this.run(source
, func
, args
);
1834 throw new Error("invalid func");
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) {
1846 if (contract
[func
] != undefined) {
1847 return contract
[func
].apply(contract
, JSON
.parse(args
));
1849 throw new Error("function not found");
1854 module
.exports
= NVM
;
1856 },{"./native":11,"extend":145}],17:[function(require
,module
,exports
){
1929 },{}],18:[function(require
,module
,exports
){
1932 var protobuf
= require('protobufjs');
1933 var utils
= require('./utils/utils.js');
1934 var cryptoUtils
= require('./utils/crypto-utils.js');
1935 var account
= require("./account.js");
1936 var htmlescape
= require('htmlescape');
1937 var BigNumber
= require('bignumber.js');
1940 var root
= protobuf
.Root
.fromJSON(require("./transaction.json"));
1942 var TxPayloadBinaryType
= "binary";
1943 var TxPayloadDeployType
= "deploy";
1944 var TxPayloadCallType
= "call";
1947 * @typedef TransactionInit
1949 * var acc = Account.NewAccount();
1951 * var tx = new Transaction({
1954 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
1957 * gasPrice: 1000000,
1963 * Represent of smart contract payload data.
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.
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}
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
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',
1997 * 'function': 'save'
2002 * Represent Transaction parameters
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]
2017 * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5",
2018 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2021 * gasPrice: 1000000,
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}
2032 * @param {TransactionOptions} options - Transaction options.
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}
2039 * var acc = Account.NewAccount();
2041 * var tx = new Transaction({
2044 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2047 * gasPrice: 1000000,
2048 * gasLimit: 2000000,
2056 var Transaction = function (options
) {
2057 if (arguments
.length
> 0) {
2058 options
= utils
.argumentsToObject(['chainID', 'from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments
);
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
);
2071 this.data
= parseContract(this.contract
);
2072 if (this.gasPrice
.lessThanOrEqualTo(0)) {
2073 this.gasPrice
= new BigNumber(1000000);
2076 if (this.gasLimit
.lessThanOrEqualTo(0)) {
2077 this.gasLimit
= new BigNumber(20000);
2080 this.signErrorMessage
= "You should sign transaction before this operation.";
2083 var parseContract = function (obj
) {
2084 /*jshint maxcomplexity:7 */
2086 var payloadType
, payload
;
2087 if (obj
&& utils
.isString(obj
.source
) && obj
.source
.length
> 0) {
2088 payloadType
= TxPayloadDeployType
;
2090 SourceType: obj
.sourceType
,
2094 } else if (obj
&& utils
.isString(obj
.function) && obj
.function.length
> 0) {
2095 payloadType
= TxPayloadCallType
;
2097 Function: obj
.function,
2101 payloadType
= TxPayloadBinaryType
;
2104 Data: cryptoUtils
.toBuffer(obj
.binary
)
2108 var payloadData
= utils
.isNull(payload
) ? null : cryptoUtils
.toBuffer(htmlescape(payload
));
2110 return { type: payloadType
, payload: payloadData
};
2114 * Transaction recover method.
2117 * @param {String/Hash} message - Transaction hash.
2118 * @param {String/Hash} signature - Transaction sign
2120 * @return {Hash} Transaction from address public key.
2123 * var pubKey = Transaction.recover("82bc718bfd24392b3872eb5a874927a327ab19b156c5584bd5f93b08fab5b1a2", "003d4064f16cbc72367b0fa3870bdcd1044bdb166019d87cdaac6dcfb8c09ac9471570e5b2e1dc249a8642ba67e585e3f43e6383c3b87532f5eb1fe2e718a5ab00");
2125 Transaction
.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;
2133 var compressed
= false;
2134 var pub
= cryptoUtils
.recover(message
, sign
, recovery
, compressed
);
2139 * Transaction fromProto method, parse rawData to transaction object.
2142 * @param {String/Hash} data - Transaction raw data.
2144 * @return {Object} Transaction object.
2147 * var tx = Transaction.fromProto("EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA==");
2149 Transaction
.fromProto = function (data
) {
2150 var tx
= new Transaction();
2155 Transaction
.prototype = {
2157 * Convert transaction to hash by SHA3-256 algorithm.
2159 * @return {Hash} hash of Transaction.
2162 * var acc = Account.NewAccount();
2164 * var tx = new Transaction({
2167 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2170 * gasPrice: 1000000,
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]
2176 hashTransaction: function () {
2177 var Data
= root
.lookup("corepb.Data");
2178 var err
= Data
.verify(this.data
);
2180 throw new Error(err
);
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));
2188 * Sign transaction with the specified algorithm.
2191 * var acc = Account.NewAccount();
2193 * var tx = new Transaction({
2196 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2199 * gasPrice: 1000000,
2202 * tx.signTransaction();
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());
2210 throw new Error("transaction from address's private key is invalid");
2214 * Conver transaction data to plain JavaScript object.
2216 * @return {Object} Plain JavaScript object with Transaction fields.
2218 * var acc = Account.NewAccount();
2219 * var tx = new Transaction({
2222 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2225 * gasPrice: 1000000,
2228 * txData = tx.toPlainObject();
2229 * // {chainID: 1001, from: "n1USdDKeZXQYubA44W2ZVUdW1cjiJuqswxp", to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 1000000000000000000, nonce: 1, …}
2231 toPlainObject: function () {
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
,
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
2244 * Convert transaction to JSON string.
2245 * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting.
2247 * @return {String} JSON stringify of transaction data.
2249 * var acc = Account.NewAccount();
2251 * var tx = new Transaction({
2254 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2257 * gasPrice: 1000000,
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"}"
2264 toString: function () {
2266 throw new Error(this.signErrorMessage
);
2268 var payload
= utils
.isNull(this.data
.payload
) ? null : JSON
.parse(this.data
.payload
.toString());
2270 chainID: this.chainID
,
2271 from: this.from.getAddressString(),
2272 to: this.to
.getAddressString(),
2273 value: this.value
.toString(10),
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"),
2281 sign: this.sign
.toString("hex")
2284 return JSON
.stringify(tx
);
2287 * Convert transaction to Protobuf format.
2288 * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting.
2290 * @return {Buffer} Transaction data in Protobuf format
2293 * var acc = Account.NewAccount();
2295 * var tx = new Transaction({
2298 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2301 * gasPrice: 1000000,
2304 * tx.signTransaction();
2305 * var txHash = tx.toProto();
2306 * // Uint8Array(127)
2308 toProto: function () {
2310 throw new Error(this.signErrorMessage
);
2312 var Data
= root
.lookup("corepb.Data");
2313 var err
= Data
.verify(this.data
);
2317 var data
= Data
.create(this.data
);
2319 var TransactionProto
= root
.lookup("corepb.Transaction");
2323 from: this.from.getAddress(),
2324 to: this.to
.getAddress(),
2325 value: cryptoUtils
.padToBigEndian(this.value
, 128),
2327 timestamp: this.timestamp
,
2329 chainId: this.chainID
,
2330 gasPrice: cryptoUtils
.padToBigEndian(this.gasPrice
, 128),
2331 gasLimit: cryptoUtils
.padToBigEndian(this.gasLimit
, 128),
2336 err
= TransactionProto
.verify(txData
);
2340 var tx
= TransactionProto
.create(txData
);
2342 var txBuffer
= TransactionProto
.encode(tx
).finish();
2346 * Convert transaction to Protobuf hash string.
2347 * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting.
2349 * @return {Base64} Transaction string.
2352 * var acc = Account.NewAccount();
2354 * var tx = new Transaction({
2357 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2360 * gasPrice: 1000000,
2363 * tx.signTransaction();
2364 * var txHash = tx.toProtoString();
2365 * // "EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA=="
2367 toProtoString: function () {
2368 var txBuffer
= this.toProto();
2369 return protobuf
.util
.base64
.encode(txBuffer
, 0, txBuffer
.length
);
2372 * Restore Transaction from Protobuf format.
2373 * @property {Buffer|String} data - Buffer or stringify Buffer.
2375 * @return {Transaction} Restored transaction.
2378 * var acc = Account.NewAccount();
2380 * var tx = new Transaction({
2383 * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17",
2386 * gasPrice: 1000000,
2389 * var tx = tx.fromProto("EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA==");
2391 fromProto: function (data
) {
2394 if (utils
.isString(data
)) {
2395 txBuffer
= new Array(protobuf
.util
.base64
.length(data
));
2396 protobuf
.util
.base64
.decode(data
, txBuffer
, 0);
2401 var TransactionProto
= root
.lookup("corepb.Transaction");
2402 var txProto
= TransactionProto
.decode(txBuffer
);
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;
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
);
2425 module
.exports
= Transaction
;
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
){
2431 var Buffer
= require('safe-buffer').Buffer
;
2433 var jsSHA
= require('jssha');
2434 var createKeccakHash
= require('keccak');
2435 var secp256k1
= require('secp256k1');
2436 var crypto
= require('crypto');
2437 var scrypt
= require('scryptsy');
2438 var RIPEMD160
= require('ripemd160');
2440 var uuid
= require('uuid');
2442 var utils
= require('./utils.js');
2444 var keccak = function (a
, bits
) {
2446 if (!bits
) bits
= 256;
2448 return createKeccakHash('keccak' + bits
).update(a
).digest();
2451 var 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"));
2457 return Buffer
.from(shaObj
.getHash("HEX"), "hex");
2460 var 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
);
2466 return ripemd160stream
.digest();
2469 // check if hex string
2470 var 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.");
2475 return str
.slice(0, 2) === '0x';
2478 // returns hex string without 0x
2479 var stripHexPrefix = function (str
) {
2480 if (typeof str
!== 'string') {
2483 return isHexPrefixed(str
) ? str
.slice(2) : str
;
2486 function isHexString(value
, length
) {
2487 if (typeof value
!== 'string' || !value
.match(/^0x[0-9A-Fa-f]*$/)) {
2491 if (length
&& value
.length
!== 2 + 2 * length
) {
2498 // returns hex string from int
2499 function intToHex(i
) {
2500 var hex
= i
.toString(16); // eslint-disable-line
2502 return '0x' + padToEven(hex
);
2505 // returns buffer from int
2506 function intToBuffer(i
) {
2507 var hex
= intToHex(i
);
2509 return new Buffer(hex
.slice(2), 'hex');
2512 // returns a buffer filled with 0
2513 var zeros = function (bytes
) {
2514 return Buffer
.allocUnsafe(bytes
).fill(0);
2517 var padToEven = function (value
) {
2518 var a
= value
; // eslint-disable-line
2520 if (typeof a
!== 'string') {
2521 throw new Error('padToEven only support string');
2531 // convert value to digit/8 buffer with BigEndian.
2532 var 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
;
2538 buff
[start
] = value
[i
];
2544 // attempts to turn a value to buffer, the input can be buffer, string,number
2545 var toBuffer = function (v
) {
2546 /*jshint maxcomplexity:13 */
2547 if (!Buffer
.isBuffer(v
)) {
2548 if (Array
.isArray(v
)) {
2550 } else if (typeof v
=== 'string') {
2551 if (isHexString(v
)) {
2552 v
= Buffer
.from(padToEven(stripHexPrefix(v
)), 'hex');
2556 } else if (typeof v
=== 'number') {
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
) {
2567 } else if (v
=== null || typeof v
=== "undefined") {
2568 v
= Buffer
.allocUnsafe(0);
2570 throw new Error('invalid type');
2576 var bufferToHex = function (buf
) {
2577 buf
= toBuffer(buf
);
2578 return '0x' + buf
.toString('hex');
2581 // convert secp256k1 private key to public key
2582 var 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);
2588 var 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
]));
2598 return secp256k1
.publicKeyVerify(publicKey
);
2601 // sign transaction hash
2602 var sign = function (msgHash
, privateKey
) {
2604 var sig
= secp256k1
.sign(toBuffer(msgHash
), toBuffer(privateKey
));
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
)]);
2612 var 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
));
2618 var recover = function (message
, signature
, recovery
, compressed
) {
2619 return secp256k1
.recover(toBuffer(message
), toBuffer(signature
), recovery
, compressed
);
2623 secp256k1: secp256k1
,
2626 ripemd160: ripemd160
,
2632 isHexPrefixed: isHexPrefixed
,
2633 padToBigEndian: padToBigEndian
,
2635 bufferToHex: bufferToHex
,
2636 privateToPublic: privateToPublic
,
2637 isValidPublic: isValidPublic
,
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
){
2647 var BigNumber
= require('bignumber.js');
2648 var utils
= require('./utils.js');
2659 'gwei': '1000000000',
2660 'Gwei': '1000000000',
2661 'nas': '1000000000000000000',
2662 'NAS': '1000000000000000000'
2665 var 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));
2671 return new BigNumber(unitValue
, 10);
2674 var toBasic = function (number
, unit
) {
2675 return utils
.toBigNumber(number
).times(unitValue(unit
));
2678 var fromBasic = function (number
, unit
) {
2679 return utils
.toBigNumber(number
).dividedBy(unitValue(unit
));
2682 var nasToBasic = function (number
) {
2683 return utils
.toBigNumber(number
).times(unitValue("nas"));
2688 fromBasic: fromBasic
,
2689 nasToBasic: nasToBasic
2692 },{"./utils.js":21,"bignumber.js":73}],21:[function(require
,module
,exports
){
2696 var BigNumber
= require('bignumber.js');
2698 var isNull = function (v
) {
2699 return v
=== null || typeof v
=== "undefined";
2702 var isBrowser = function () {
2703 return typeof window
!== "undefined";
2706 var isBigNumber = function (obj
) {
2707 return obj
instanceof BigNumber
|| obj
&& obj
.constructor && obj
.constructor.name
=== 'BigNumber';
2710 var isString = function (obj
) {
2711 return typeof obj
=== 'string' && obj
.constructor === String
;
2714 var isObject = function (obj
) {
2715 return obj
!== null && typeof obj
=== 'object';
2718 var isFunction = function (object
) {
2719 return typeof object
=== 'function';
2722 var isNumber = function (object
) {
2723 return typeof object
=== 'number';
2726 var toBigNumber = function (number
) {
2727 number
= number
|| 0;
2728 if (isBigNumber(number
)) {
2731 if (isString(number
) && number
.indexOf('0x') === 0) {
2732 return new BigNumber(number
.replace('0x', ''), 16);
2734 return new BigNumber(number
.toString(10), 10);
2737 var toString = function (obj
) {
2738 if (isString(obj
)) {
2740 } else if (isBigNumber(obj
)) {
2741 return obj
.toString(10);
2742 } else if (isObject(obj
)) {
2743 return JSON
.stringify(obj
);
2749 // Transform Array-like arguments object to common array.
2750 var argumentsToArray = function (args
) {
2751 var len
= args
.length
,
2752 resultArray
= new Array(len
);
2754 for (var i
= 0; i
< len
; i
+= 1) {
2755 resultArray
[i
] = args
[i
];
2760 // Create object based on provided arrays
2761 var zipArraysToObject = function (keysArr
, valuesArr
) {
2762 var resultObject
= {};
2764 for (var i
= 0; i
< keysArr
.length
; i
+= 1) {
2765 resultObject
[keysArr
[i
]] = valuesArr
[i
];
2767 return resultObject
;
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
2775 var argumentsToObject = function (keys
, args
) {
2776 var ArgumentsObject
= {};
2778 args
= argumentsToArray(args
);
2779 if (isObject(args
[0])) {
2780 ArgumentsObject
= args
[0];
2782 ArgumentsObject
= zipArraysToObject(keys
, args
);
2785 return ArgumentsObject
;
2790 isBrowser: isBrowser
,
2791 isBigNumber: isBigNumber
,
2794 isFunction: isFunction
,
2796 toBigNumber: toBigNumber
,
2798 argumentsToObject: argumentsToObject
,
2799 zipArraysToObject: zipArraysToObject
2802 },{"bignumber.js":73}],22:[function(require
,module
,exports
){
2804 module
.exports
= asPromise
;
2807 * Callback as used by {@link util.asPromise}.
2808 * @typedef asPromiseCallback
2810 * @param {Error|null} error Error, if any
2811 * @param {...*} params Additional arguments
2812 * @returns {undefined}
2816 * Returns a promise from a node-style callback function.
2818 * @param {asPromiseCallback} fn Function to call
2819 * @param {*} ctx Function context
2820 * @param {...*} params Function arguments
2821 * @returns {Promise<*>} Promisified function
2823 function asPromise(fn
, ctx
/*, varargs */) {
2824 var params
= new Array(arguments
.length
- 1),
2828 while (index
< arguments
.length
)
2829 params
[offset
++] = arguments
[index
++];
2830 return new Promise(function executor(resolve
, reject
) {
2831 params
[offset
] = function callback(err
/*, varargs */) {
2837 var params
= new Array(arguments
.length
- 1),
2839 while (offset
< params
.length
)
2840 params
[offset
++] = arguments
[offset
];
2841 resolve
.apply(null, params
);
2846 fn
.apply(ctx
|| null, params
);
2856 },{}],23:[function(require
,module
,exports
){
2860 * A minimal base64 implementation for number arrays.
2864 var base64
= exports
;
2867 * Calculates the byte length of a base64 encoded string.
2868 * @param {string} string Base64 encoded string
2869 * @returns {number} Byte length
2871 base64
.length
= function length(string
) {
2872 var p
= string
.length
;
2876 while (--p
% 4 > 1 && string
.charAt(p
) === "=")
2878 return Math
.ceil(string
.length
* 3) / 4 - n
;
2881 // Base64 encoding table
2882 var b64
= new Array(64);
2884 // Base64 decoding table
2885 var s64
= new Array(123);
2887 // 65..90, 97..122, 48..57, 43, 47
2888 for (var i
= 0; i
< 64;)
2889 s64
[b64
[i
] = i
< 26 ? i
+ 65 : i
< 52 ? i
+ 71 : i
< 62 ? i
- 4 : i
- 59 | 43] = i
++;
2892 * Encodes a buffer to a base64 encoded string.
2893 * @param {Uint8Array} buffer Source buffer
2894 * @param {number} start Source start
2895 * @param {number} end Source end
2896 * @returns {string} Base64 encoded string
2898 base64
.encode
= function encode(buffer
, start
, end
) {
2901 var i
= 0, // output index
2902 j
= 0, // goto index
2904 while (start
< end
) {
2905 var b
= buffer
[start
++];
2908 chunk
[i
++] = b64
[b
>> 2];
2913 chunk
[i
++] = b64
[t
| b
>> 4];
2918 chunk
[i
++] = b64
[t
| b
>> 6];
2919 chunk
[i
++] = b64
[b
& 63];
2924 (parts
|| (parts
= [])).push(String
.fromCharCode
.apply(String
, chunk
));
2929 chunk
[i
++] = b64
[t
];
2936 parts
.push(String
.fromCharCode
.apply(String
, chunk
.slice(0, i
)));
2937 return parts
.join("");
2939 return String
.fromCharCode
.apply(String
, chunk
.slice(0, i
));
2942 var invalidEncoding
= "invalid encoding";
2945 * Decodes a base64 encoded string to a buffer.
2946 * @param {string} string Source string
2947 * @param {Uint8Array} buffer Destination buffer
2948 * @param {number} offset Destination offset
2949 * @returns {number} Number of bytes written
2950 * @throws {Error} If encoding is invalid
2952 base64
.decode
= function decode(string
, buffer
, offset
) {
2954 var j
= 0, // goto index
2956 for (var i
= 0; i
< string
.length
;) {
2957 var c
= string
.charCodeAt(i
++);
2958 if (c
=== 61 && j
> 1)
2960 if ((c
= s64
[c
]) === undefined)
2961 throw Error(invalidEncoding
);
2968 buffer
[offset
++] = t
<< 2 | (c
& 48) >> 4;
2973 buffer
[offset
++] = (t
& 15) << 4 | (c
& 60) >> 2;
2978 buffer
[offset
++] = (t
& 3) << 6 | c
;
2984 throw Error(invalidEncoding
);
2985 return offset
- start
;
2989 * Tests if the specified string appears to be base64 encoded.
2990 * @param {string} string String to test
2991 * @returns {boolean} `true` if probably base64 encoded, otherwise false
2993 base64
.test
= function test(string
) {
2994 return /^(?:[A-Za-z0-9+/]{4})*(?:[A
-Za
-z0
-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/.test(string
);
2997 },{}],24:[function(require
,module
,exports
){
2999 module
.exports
= codegen
;
3002 * Begins generating a function.
3004 * @param {string[]} functionParams Function parameter names
3005 * @param {string} [functionName] Function name if not anonymous
3006 * @returns {Codegen} Appender that appends code to the function's body
3008 function codegen(functionParams
, functionName
) {
3010 /* istanbul ignore if */
3011 if (typeof functionParams
=== "string") {
3012 functionName
= functionParams
;
3013 functionParams
= undefined;
3019 * Appends code to the function's body or finishes generation.
3022 * @param {string|Object.<string,*>} [formatStringOrScope] Format string or, to finish the function, an object of additional scope variables, if any
3023 * @param {...*} [formatParams] Format parameters
3024 * @returns {Codegen|Function} Itself or the generated function if finished
3025 * @throws {Error} If format parameter counts do not match
3028 function Codegen(formatStringOrScope
) {
3029 // note that explicit array handling below makes this ~50% faster
3031 // finish the function
3032 if (typeof formatStringOrScope
!== "string") {
3033 var source
= toString();
3034 if (codegen
.verbose
)
3035 console
.log("codegen: " + source
); // eslint-disable-line no-console
3036 source
= "return " + source
;
3037 if (formatStringOrScope
) {
3038 var scopeKeys
= Object
.keys(formatStringOrScope
),
3039 scopeParams
= new Array(scopeKeys
.length
+ 1),
3040 scopeValues
= new Array(scopeKeys
.length
),
3042 while (scopeOffset
< scopeKeys
.length
) {
3043 scopeParams
[scopeOffset
] = scopeKeys
[scopeOffset
];
3044 scopeValues
[scopeOffset
] = formatStringOrScope
[scopeKeys
[scopeOffset
++]];
3046 scopeParams
[scopeOffset
] = source
;
3047 return Function
.apply(null, scopeParams
).apply(null, scopeValues
); // eslint-disable-line no-new-func
3049 return Function(source
)(); // eslint-disable-line no-new-func
3052 // otherwise append to body
3053 var formatParams
= new Array(arguments
.length
- 1),
3055 while (formatOffset
< formatParams
.length
)
3056 formatParams
[formatOffset
] = arguments
[++formatOffset
];
3058 formatStringOrScope
= formatStringOrScope
.replace(/%([%dfijs])/g, function replace($0, $1) {
3059 var value
= formatParams
[formatOffset
++];
3061 case "d": case "f": return String(Number(value
));
3062 case "i": return String(Math
.floor(value
));
3063 case "j": return JSON
.stringify(value
);
3064 case "s": return String(value
);
3068 if (formatOffset
!== formatParams
.length
)
3069 throw Error("parameter count mismatch");
3070 body
.push(formatStringOrScope
);
3074 function toString(functionNameOverride
) {
3075 return "function " + (functionNameOverride
|| functionName
|| "") + "(" + (functionParams
&& functionParams
.join(",") || "") + "){\n " + body
.join("\n ") + "\n}";
3078 Codegen
.toString
= toString
;
3083 * Begins generating a function.
3086 * @param {string} [functionName] Function name if not anonymous
3087 * @returns {Codegen} Appender that appends code to the function's body
3092 * When set to `true`, codegen will log generated code to console. Useful for debugging.
3093 * @name util.codegen.verbose
3096 codegen
.verbose
= false;
3098 },{}],25:[function(require
,module
,exports
){
3100 module
.exports
= EventEmitter
;
3103 * Constructs a new event emitter instance.
3104 * @classdesc A minimal event emitter.
3108 function EventEmitter() {
3111 * Registered listeners.
3112 * @type {Object.<string,*>}
3115 this._listeners
= {};
3119 * Registers an event listener.
3120 * @param {string} evt Event name
3121 * @param {function} fn Listener
3122 * @param {*} [ctx] Listener context
3123 * @returns {util.EventEmitter} `this`
3125 EventEmitter
.prototype.on
= function on(evt
, fn
, ctx
) {
3126 (this._listeners
[evt
] || (this._listeners
[evt
] = [])).push({
3134 * Removes an event listener or any matching listeners if arguments are omitted.
3135 * @param {string} [evt] Event name. Removes all listeners if omitted.
3136 * @param {function} [fn] Listener to remove. Removes all listeners of `evt` if omitted.
3137 * @returns {util.EventEmitter} `this`
3139 EventEmitter
.prototype.off
= function off(evt
, fn
) {
3140 if (evt
=== undefined)
3141 this._listeners
= {};
3143 if (fn
=== undefined)
3144 this._listeners
[evt
] = [];
3146 var listeners
= this._listeners
[evt
];
3147 for (var i
= 0; i
< listeners
.length
;)
3148 if (listeners
[i
].fn
=== fn
)
3149 listeners
.splice(i
, 1);
3158 * Emits an event by calling its listeners with the specified arguments.
3159 * @param {string} evt Event name
3160 * @param {...*} args Arguments
3161 * @returns {util.EventEmitter} `this`
3163 EventEmitter
.prototype.emit
= function emit(evt
) {
3164 var listeners
= this._listeners
[evt
];
3168 for (; i
< arguments
.length
;)
3169 args
.push(arguments
[i
++]);
3170 for (i
= 0; i
< listeners
.length
;)
3171 listeners
[i
].fn
.apply(listeners
[i
++].ctx
, args
);
3176 },{}],26:[function(require
,module
,exports
){
3178 module
.exports
= fetch
;
3180 var asPromise
= require("@protobufjs/aspromise"),
3181 inquire
= require("@protobufjs/inquire");
3183 var fs
= inquire("fs");
3186 * Node-style callback as used by {@link util.fetch}.
3187 * @typedef FetchCallback
3189 * @param {?Error} error Error, if any, otherwise `null`
3190 * @param {string} [contents] File contents, if there hasn't been an error
3191 * @returns {undefined}
3195 * Options as used by {@link util.fetch}.
3196 * @typedef FetchOptions
3198 * @property {boolean} [binary=false] Whether expecting a binary response
3199 * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest
3203 * Fetches the contents of a file.
3205 * @param {string} filename File path or url
3206 * @param {FetchOptions} options Fetch options
3207 * @param {FetchCallback} callback Callback function
3208 * @returns {undefined}
3210 function fetch(filename
, options
, callback
) {
3211 if (typeof options
=== "function") {
3214 } else if (!options
)
3218 return asPromise(fetch
, this, filename
, options
); // eslint-disable-line no-invalid-this
3220 // if a node-like filesystem is present, try it first but fall back to XHR if nothing is found.
3221 if (!options
.xhr
&& fs
&& fs
.readFile
)
3222 return fs
.readFile(filename
, function fetchReadFileCallback(err
, contents
) {
3223 return err
&& typeof XMLHttpRequest
!== "undefined"
3224 ? fetch
.xhr(filename
, options
, callback
)
3227 : callback(null, options
.binary
? contents : contents
.toString("utf8"));
3230 // use the XHR version otherwise.
3231 return fetch
.xhr(filename
, options
, callback
);
3235 * Fetches the contents of a file.
3238 * @param {string} path File path or url
3239 * @param {FetchCallback} callback Callback function
3240 * @returns {undefined}
3245 * Fetches the contents of a file.
3248 * @param {string} path File path or url
3249 * @param {FetchOptions} [options] Fetch options
3250 * @returns {Promise<string|Uint8Array>} Promise
3255 fetch
.xhr
= function fetch_xhr(filename
, options
, callback
) {
3256 var xhr
= new XMLHttpRequest();
3257 xhr
.onreadystatechange
/* works everywhere */ = function fetchOnReadyStateChange() {
3259 if (xhr
.readyState
!== 4)
3262 // local cors security errors return status 0 / empty string, too. afaik this cannot be
3263 // reliably distinguished from an actually empty file for security reasons. feel free
3264 // to send a pull request if you are aware of a solution.
3265 if (xhr
.status
!== 0 && xhr
.status
!== 200)
3266 return callback(Error("status " + xhr
.status
));
3268 // if binary data is expected, make sure that some sort of array is returned, even if
3269 // ArrayBuffers are not supported. the binary string fallback, however, is unsafe.
3270 if (options
.binary
) {
3271 var buffer
= xhr
.response
;
3274 for (var i
= 0; i
< xhr
.responseText
.length
; ++i
)
3275 buffer
.push(xhr
.responseText
.charCodeAt(i
) & 255);
3277 return callback(null, typeof Uint8Array
!== "undefined" ? new Uint8Array(buffer
) : buffer
);
3279 return callback(null, xhr
.responseText
);
3282 if (options
.binary
) {
3283 // ref: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Sending_and_Receiving_Binary_Data#Receiving_binary_data_in_older_browsers
3284 if ("overrideMimeType" in xhr
)
3285 xhr
.overrideMimeType("text/plain; charset=x-user-defined");
3286 xhr
.responseType
= "arraybuffer";
3289 xhr
.open("GET", filename
);
3293 },{"@protobufjs/aspromise":22,"@protobufjs/inquire":28}],27:[function(require
,module
,exports
){
3296 module
.exports
= factory(factory
);
3299 * Reads / writes floats / doubles from / to buffers.
3305 * Writes a 32 bit float to a buffer using little endian byte order.
3306 * @name util.float.writeFloatLE
3308 * @param {number} val Value to write
3309 * @param {Uint8Array} buf Target buffer
3310 * @param {number} pos Target buffer offset
3311 * @returns {undefined}
3315 * Writes a 32 bit float to a buffer using big endian byte order.
3316 * @name util.float.writeFloatBE
3318 * @param {number} val Value to write
3319 * @param {Uint8Array} buf Target buffer
3320 * @param {number} pos Target buffer offset
3321 * @returns {undefined}
3325 * Reads a 32 bit float from a buffer using little endian byte order.
3326 * @name util.float.readFloatLE
3328 * @param {Uint8Array} buf Source buffer
3329 * @param {number} pos Source buffer offset
3330 * @returns {number} Value read
3334 * Reads a 32 bit float from a buffer using big endian byte order.
3335 * @name util.float.readFloatBE
3337 * @param {Uint8Array} buf Source buffer
3338 * @param {number} pos Source buffer offset
3339 * @returns {number} Value read
3343 * Writes a 64 bit double to a buffer using little endian byte order.
3344 * @name util.float.writeDoubleLE
3346 * @param {number} val Value to write
3347 * @param {Uint8Array} buf Target buffer
3348 * @param {number} pos Target buffer offset
3349 * @returns {undefined}
3353 * Writes a 64 bit double to a buffer using big endian byte order.
3354 * @name util.float.writeDoubleBE
3356 * @param {number} val Value to write
3357 * @param {Uint8Array} buf Target buffer
3358 * @param {number} pos Target buffer offset
3359 * @returns {undefined}
3363 * Reads a 64 bit double from a buffer using little endian byte order.
3364 * @name util.float.readDoubleLE
3366 * @param {Uint8Array} buf Source buffer
3367 * @param {number} pos Source buffer offset
3368 * @returns {number} Value read
3372 * Reads a 64 bit double from a buffer using big endian byte order.
3373 * @name util.float.readDoubleBE
3375 * @param {Uint8Array} buf Source buffer
3376 * @param {number} pos Source buffer offset
3377 * @returns {number} Value read
3380 // Factory function for the purpose of node-based testing in modified global environments
3381 function factory(exports
) {
3383 // float: typed array
3384 if (typeof Float32Array
!== "undefined") (function() {
3386 var f32
= new Float32Array([ -0 ]),
3387 f8b
= new Uint8Array(f32
.buffer
),
3388 le
= f8b
[3] === 128;
3390 function writeFloat_f32_cpy(val
, buf
, pos
) {
3393 buf
[pos
+ 1] = f8b
[1];
3394 buf
[pos
+ 2] = f8b
[2];
3395 buf
[pos
+ 3] = f8b
[3];
3398 function writeFloat_f32_rev(val
, buf
, pos
) {
3401 buf
[pos
+ 1] = f8b
[2];
3402 buf
[pos
+ 2] = f8b
[1];
3403 buf
[pos
+ 3] = f8b
[0];
3406 /* istanbul ignore next */
3407 exports
.writeFloatLE
= le
? writeFloat_f32_cpy : writeFloat_f32_rev
;
3408 /* istanbul ignore next */
3409 exports
.writeFloatBE
= le
? writeFloat_f32_rev : writeFloat_f32_cpy
;
3411 function readFloat_f32_cpy(buf
, pos
) {
3413 f8b
[1] = buf
[pos
+ 1];
3414 f8b
[2] = buf
[pos
+ 2];
3415 f8b
[3] = buf
[pos
+ 3];
3419 function readFloat_f32_rev(buf
, pos
) {
3421 f8b
[2] = buf
[pos
+ 1];
3422 f8b
[1] = buf
[pos
+ 2];
3423 f8b
[0] = buf
[pos
+ 3];
3427 /* istanbul ignore next */
3428 exports
.readFloatLE
= le
? readFloat_f32_cpy : readFloat_f32_rev
;
3429 /* istanbul ignore next */
3430 exports
.readFloatBE
= le
? readFloat_f32_rev : readFloat_f32_cpy
;
3433 })(); else (function() {
3435 function writeFloat_ieee754(writeUint
, val
, buf
, pos
) {
3436 var sign
= val
< 0 ? 1 : 0;
3440 writeUint(1 / val
> 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf
, pos
);
3441 else if (isNaN(val
))
3442 writeUint(2143289344, buf
, pos
);
3443 else if (val
> 3.4028234663852886e+38) // +-Infinity
3444 writeUint((sign
<< 31 | 2139095040) >>> 0, buf
, pos
);
3445 else if (val
< 1.1754943508222875e-38) // denormal
3446 writeUint((sign
<< 31 | Math
.round(val
/ 1.401298464324817e-45)) >>> 0, buf
, pos
);
3448 var exponent
= Math
.floor(Math
.log(val
) / Math
.LN2
),
3449 mantissa
= Math
.round(val
* Math
.pow(2, -exponent
) * 8388608) & 8388607;
3450 writeUint((sign
<< 31 | exponent
+ 127 << 23 | mantissa
) >>> 0, buf
, pos
);
3454 exports
.writeFloatLE
= writeFloat_ieee754
.bind(null, writeUintLE
);
3455 exports
.writeFloatBE
= writeFloat_ieee754
.bind(null, writeUintBE
);
3457 function readFloat_ieee754(readUint
, buf
, pos
) {
3458 var uint = readUint(buf
, pos
),
3459 sign
= (uint >> 31) * 2 + 1,
3460 exponent
= uint >>> 23 & 255,
3461 mantissa
= uint & 8388607;
3462 return exponent
=== 255
3466 : exponent
=== 0 // denormal
3467 ? sign
* 1.401298464324817e-45 * mantissa
3468 : sign
* Math
.pow(2, exponent
- 150) * (mantissa
+ 8388608);
3471 exports
.readFloatLE
= readFloat_ieee754
.bind(null, readUintLE
);
3472 exports
.readFloatBE
= readFloat_ieee754
.bind(null, readUintBE
);
3476 // double: typed array
3477 if (typeof Float64Array
!== "undefined") (function() {
3479 var f64
= new Float64Array([-0]),
3480 f8b
= new Uint8Array(f64
.buffer
),
3481 le
= f8b
[7] === 128;
3483 function writeDouble_f64_cpy(val
, buf
, pos
) {
3486 buf
[pos
+ 1] = f8b
[1];
3487 buf
[pos
+ 2] = f8b
[2];
3488 buf
[pos
+ 3] = f8b
[3];
3489 buf
[pos
+ 4] = f8b
[4];
3490 buf
[pos
+ 5] = f8b
[5];
3491 buf
[pos
+ 6] = f8b
[6];
3492 buf
[pos
+ 7] = f8b
[7];
3495 function writeDouble_f64_rev(val
, buf
, pos
) {
3498 buf
[pos
+ 1] = f8b
[6];
3499 buf
[pos
+ 2] = f8b
[5];
3500 buf
[pos
+ 3] = f8b
[4];
3501 buf
[pos
+ 4] = f8b
[3];
3502 buf
[pos
+ 5] = f8b
[2];
3503 buf
[pos
+ 6] = f8b
[1];
3504 buf
[pos
+ 7] = f8b
[0];
3507 /* istanbul ignore next */
3508 exports
.writeDoubleLE
= le
? writeDouble_f64_cpy : writeDouble_f64_rev
;
3509 /* istanbul ignore next */
3510 exports
.writeDoubleBE
= le
? writeDouble_f64_rev : writeDouble_f64_cpy
;
3512 function readDouble_f64_cpy(buf
, pos
) {
3514 f8b
[1] = buf
[pos
+ 1];
3515 f8b
[2] = buf
[pos
+ 2];
3516 f8b
[3] = buf
[pos
+ 3];
3517 f8b
[4] = buf
[pos
+ 4];
3518 f8b
[5] = buf
[pos
+ 5];
3519 f8b
[6] = buf
[pos
+ 6];
3520 f8b
[7] = buf
[pos
+ 7];
3524 function readDouble_f64_rev(buf
, pos
) {
3526 f8b
[6] = buf
[pos
+ 1];
3527 f8b
[5] = buf
[pos
+ 2];
3528 f8b
[4] = buf
[pos
+ 3];
3529 f8b
[3] = buf
[pos
+ 4];
3530 f8b
[2] = buf
[pos
+ 5];
3531 f8b
[1] = buf
[pos
+ 6];
3532 f8b
[0] = buf
[pos
+ 7];
3536 /* istanbul ignore next */
3537 exports
.readDoubleLE
= le
? readDouble_f64_cpy : readDouble_f64_rev
;
3538 /* istanbul ignore next */
3539 exports
.readDoubleBE
= le
? readDouble_f64_rev : readDouble_f64_cpy
;
3542 })(); else (function() {
3544 function writeDouble_ieee754(writeUint
, off0
, off1
, val
, buf
, pos
) {
3545 var sign
= val
< 0 ? 1 : 0;
3549 writeUint(0, buf
, pos
+ off0
);
3550 writeUint(1 / val
> 0 ? /* positive */ 0 : /* negative 0 */ 2147483648, buf
, pos
+ off1
);
3551 } else if (isNaN(val
)) {
3552 writeUint(0, buf
, pos
+ off0
);
3553 writeUint(2146959360, buf
, pos
+ off1
);
3554 } else if (val
> 1.7976931348623157e+308) { // +-Infinity
3555 writeUint(0, buf
, pos
+ off0
);
3556 writeUint((sign
<< 31 | 2146435072) >>> 0, buf
, pos
+ off1
);
3559 if (val
< 2.2250738585072014e-308) { // denormal
3560 mantissa
= val
/ 5e-324;
3561 writeUint(mantissa
>>> 0, buf
, pos
+ off0
);
3562 writeUint((sign
<< 31 | mantissa
/ 4294967296) >>> 0, buf
, pos
+ off1
);
3564 var exponent
= Math
.floor(Math
.log(val
) / Math
.LN2
);
3565 if (exponent
=== 1024)
3567 mantissa
= val
* Math
.pow(2, -exponent
);
3568 writeUint(mantissa
* 4503599627370496 >>> 0, buf
, pos
+ off0
);
3569 writeUint((sign
<< 31 | exponent
+ 1023 << 20 | mantissa
* 1048576 & 1048575) >>> 0, buf
, pos
+ off1
);
3574 exports
.writeDoubleLE
= writeDouble_ieee754
.bind(null, writeUintLE
, 0, 4);
3575 exports
.writeDoubleBE
= writeDouble_ieee754
.bind(null, writeUintBE
, 4, 0);
3577 function readDouble_ieee754(readUint
, off0
, off1
, buf
, pos
) {
3578 var lo
= readUint(buf
, pos
+ off0
),
3579 hi
= readUint(buf
, pos
+ off1
);
3580 var sign
= (hi
>> 31) * 2 + 1,
3581 exponent
= hi
>>> 20 & 2047,
3582 mantissa
= 4294967296 * (hi
& 1048575) + lo
;
3583 return exponent
=== 2047
3587 : exponent
=== 0 // denormal
3588 ? sign
* 5e-324 * mantissa
3589 : sign
* Math
.pow(2, exponent
- 1075) * (mantissa
+ 4503599627370496);
3592 exports
.readDoubleLE
= readDouble_ieee754
.bind(null, readUintLE
, 0, 4);
3593 exports
.readDoubleBE
= readDouble_ieee754
.bind(null, readUintBE
, 4, 0);
3602 function writeUintLE(val
, buf
, pos
) {
3603 buf
[pos
] = val
& 255;
3604 buf
[pos
+ 1] = val
>>> 8 & 255;
3605 buf
[pos
+ 2] = val
>>> 16 & 255;
3606 buf
[pos
+ 3] = val
>>> 24;
3609 function writeUintBE(val
, buf
, pos
) {
3610 buf
[pos
] = val
>>> 24;
3611 buf
[pos
+ 1] = val
>>> 16 & 255;
3612 buf
[pos
+ 2] = val
>>> 8 & 255;
3613 buf
[pos
+ 3] = val
& 255;
3616 function readUintLE(buf
, pos
) {
3619 | buf
[pos
+ 2] << 16
3620 | buf
[pos
+ 3] << 24) >>> 0;
3623 function readUintBE(buf
, pos
) {
3624 return (buf
[pos
] << 24
3625 | buf
[pos
+ 1] << 16
3627 | buf
[pos
+ 3]) >>> 0;
3630 },{}],28:[function(require
,module
,exports
){
3632 module
.exports
= inquire
;
3635 * Requires a module only if available.
3637 * @param {string} moduleName Module to require
3638 * @returns {?Object} Required module if available and not empty, otherwise `null`
3640 function inquire(moduleName
) {
3642 var mod
= eval("quire".replace(/^/,"re"))(moduleName); // eslint
-disable
-line no
-eval
3643 if (mod
&& (mod
.length
|| Object
.keys(mod
).length
))
3645 } catch (e
) {} // eslint-disable-line no-empty
3649 },{}],29:[function(require
,module
,exports
){
3653 * A minimal path module to resolve Unix, Windows and URL paths alike.
3661 * Tests if the specified path is absolute.
3662 * @param {string} path Path to test
3663 * @returns {boolean} `true` if path is absolute
3665 path
.isAbsolute
= function isAbsolute(path
) {
3666 return /^(?:\/|\w+:)/.test(path
);
3671 * Normalizes the specified path.
3672 * @param {string} path Path to normalize
3673 * @returns {string} Normalized path
3675 path
.normalize
= function normalize(path
) {
3676 path
= path
.replace(/\\/g
, "/")
3677 .replace(/\/{2,}/g, "/");
3678 var parts
= path
.split("/"),
3679 absolute
= isAbsolute(path
),
3682 prefix
= parts
.shift() + "/";
3683 for (var i
= 0; i
< parts
.length
;) {
3684 if (parts
[i
] === "..") {
3685 if (i
> 0 && parts
[i
- 1] !== "..")
3686 parts
.splice(--i
, 2);
3691 } else if (parts
[i
] === ".")
3696 return prefix
+ parts
.join("/");
3700 * Resolves the specified include path against the specified origin path.
3701 * @param {string} originPath Path to the origin file
3702 * @param {string} includePath Include path relative to origin path
3703 * @param {boolean} [alreadyNormalized=false] `true` if both paths are already known to be normalized
3704 * @returns {string} Path to the include file
3706 path
.resolve
= function resolve(originPath
, includePath
, alreadyNormalized
) {
3707 if (!alreadyNormalized
)
3708 includePath
= normalize(includePath
);
3709 if (isAbsolute(includePath
))
3711 if (!alreadyNormalized
)
3712 originPath
= normalize(originPath
);
3713 return (originPath
= originPath
.replace(/(?:\/|^)[^/]+$/, "")).length
? normalize(originPath
+ "/" + includePath
) : includePath
;
3716 },{}],30:[function(require
,module
,exports
){
3718 module
.exports
= pool
;
3721 * An allocator as used by {@link util.pool}.
3722 * @typedef PoolAllocator
3724 * @param {number} size Buffer size
3725 * @returns {Uint8Array} Buffer
3729 * A slicer as used by {@link util.pool}.
3730 * @typedef PoolSlicer
3732 * @param {number} start Start offset
3733 * @param {number} end End offset
3734 * @returns {Uint8Array} Buffer slice
3735 * @this {Uint8Array}
3739 * A general purpose buffer pool.
3742 * @param {PoolAllocator} alloc Allocator
3743 * @param {PoolSlicer} slice Slicer
3744 * @param {number} [size=8192] Slab size
3745 * @returns {PoolAllocator} Pooled allocator
3747 function pool(alloc
, slice
, size
) {
3748 var SIZE
= size
|| 8192;
3749 var MAX
= SIZE
>>> 1;
3752 return function pool_alloc(size
) {
3753 if (size
< 1 || size
> MAX
)
3755 if (offset
+ size
> SIZE
) {
3759 var buf
= slice
.call(slab
, offset
, offset
+= size
);
3760 if (offset
& 7) // align to 32 bit
3761 offset
= (offset
| 7) + 1;
3766 },{}],31:[function(require
,module
,exports
){
3770 * A minimal UTF8 implementation for number arrays.
3777 * Calculates the UTF8 byte length of a string.
3778 * @param {string} string String
3779 * @returns {number} Byte length
3781 utf8
.length
= function utf8_length(string
) {
3784 for (var i
= 0; i
< string
.length
; ++i
) {
3785 c
= string
.charCodeAt(i
);
3790 else if ((c
& 0xFC00) === 0xD800 && (string
.charCodeAt(i
+ 1) & 0xFC00) === 0xDC00) {
3800 * Reads UTF8 bytes as a string.
3801 * @param {Uint8Array} buffer Source buffer
3802 * @param {number} start Source start
3803 * @param {number} end Source end
3804 * @returns {string} String read
3806 utf8
.read
= function utf8_read(buffer
, start
, end
) {
3807 var len
= end
- start
;
3812 i
= 0, // char offset
3814 while (start
< end
) {
3815 t
= buffer
[start
++];
3818 else if (t
> 191 && t
< 224)
3819 chunk
[i
++] = (t
& 31) << 6 | buffer
[start
++] & 63;
3820 else if (t
> 239 && t
< 365) {
3821 t
= ((t
& 7) << 18 | (buffer
[start
++] & 63) << 12 | (buffer
[start
++] & 63) << 6 | buffer
[start
++] & 63) - 0x10000;
3822 chunk
[i
++] = 0xD800 + (t
>> 10);
3823 chunk
[i
++] = 0xDC00 + (t
& 1023);
3825 chunk
[i
++] = (t
& 15) << 12 | (buffer
[start
++] & 63) << 6 | buffer
[start
++] & 63;
3827 (parts
|| (parts
= [])).push(String
.fromCharCode
.apply(String
, chunk
));
3833 parts
.push(String
.fromCharCode
.apply(String
, chunk
.slice(0, i
)));
3834 return parts
.join("");
3836 return String
.fromCharCode
.apply(String
, chunk
.slice(0, i
));
3840 * Writes a string as UTF8 bytes.
3841 * @param {string} string Source string
3842 * @param {Uint8Array} buffer Destination buffer
3843 * @param {number} offset Destination offset
3844 * @returns {number} Bytes written
3846 utf8
.write
= function utf8_write(string
, buffer
, offset
) {
3850 for (var i
= 0; i
< string
.length
; ++i
) {
3851 c1
= string
.charCodeAt(i
);
3853 buffer
[offset
++] = c1
;
3854 } else if (c1
< 2048) {
3855 buffer
[offset
++] = c1
>> 6 | 192;
3856 buffer
[offset
++] = c1
& 63 | 128;
3857 } else if ((c1
& 0xFC00) === 0xD800 && ((c2
= string
.charCodeAt(i
+ 1)) & 0xFC00) === 0xDC00) {
3858 c1
= 0x10000 + ((c1
& 0x03FF) << 10) + (c2
& 0x03FF);
3860 buffer
[offset
++] = c1
>> 18 | 240;
3861 buffer
[offset
++] = c1
>> 12 & 63 | 128;
3862 buffer
[offset
++] = c1
>> 6 & 63 | 128;
3863 buffer
[offset
++] = c1
& 63 | 128;
3865 buffer
[offset
++] = c1
>> 12 | 224;
3866 buffer
[offset
++] = c1
>> 6 & 63 | 128;
3867 buffer
[offset
++] = c1
& 63 | 128;
3870 return offset
- start
;
3873 },{}],32:[function(require
,module
,exports
){
3876 asn1
.bignum
= require('bn.js');
3878 asn1
.define
= require('./asn1/api').define
;
3879 asn1
.base
= require('./asn1/base');
3880 asn1
.constants
= require('./asn1/constants');
3881 asn1
.decoders
= require('./asn1/decoders');
3882 asn1
.encoders
= require('./asn1/encoders');
3884 },{"./asn1/api":33,"./asn1/base":35,"./asn1/constants":39,"./asn1/decoders":41,"./asn1/encoders":44,"bn.js":75}],33:[function(require
,module
,exports
){
3885 var asn1
= require('../asn1');
3886 var inherits
= require('inherits');
3890 api
.define
= function define(name
, body
) {
3891 return new Entity(name
, body
);
3894 function Entity(name
, body
) {
3902 Entity
.prototype._createNamed
= function createNamed(base
) {
3905 named
= require('vm').runInThisContext(
3906 '(function ' + this.name
+ '(entity) {\n' +
3907 ' this._initNamed(entity);\n' +
3911 named = function (entity
) {
3912 this._initNamed(entity
);
3915 inherits(named
, base
);
3916 named
.prototype._initNamed
= function initnamed(entity
) {
3917 base
.call(this, entity
);
3920 return new named(this);
3923 Entity
.prototype._getDecoder
= function _getDecoder(enc
) {
3925 // Lazily create decoder
3926 if (!this.decoders
.hasOwnProperty(enc
))
3927 this.decoders
[enc
] = this._createNamed(asn1
.decoders
[enc
]);
3928 return this.decoders
[enc
];
3931 Entity
.prototype.decode
= function decode(data
, enc
, options
) {
3932 return this._getDecoder(enc
).decode(data
, options
);
3935 Entity
.prototype._getEncoder
= function _getEncoder(enc
) {
3937 // Lazily create encoder
3938 if (!this.encoders
.hasOwnProperty(enc
))
3939 this.encoders
[enc
] = this._createNamed(asn1
.encoders
[enc
]);
3940 return this.encoders
[enc
];
3943 Entity
.prototype.encode
= function encode(data
, enc
, /* internal */ reporter
) {
3944 return this._getEncoder(enc
).encode(data
, reporter
);
3947 },{"../asn1":32,"inherits":163,"vm":271}],34:[function(require
,module
,exports
){
3948 var inherits
= require('inherits');
3949 var Reporter
= require('../base').Reporter
;
3950 var Buffer
= require('buffer').Buffer
;
3952 function DecoderBuffer(base
, options
) {
3953 Reporter
.call(this, options
);
3954 if (!Buffer
.isBuffer(base
)) {
3955 this.error('Input not Buffer');
3961 this.length
= base
.length
;
3963 inherits(DecoderBuffer
, Reporter
);
3964 exports
.DecoderBuffer
= DecoderBuffer
;
3966 DecoderBuffer
.prototype.save
= function save() {
3967 return { offset: this.offset
, reporter: Reporter
.prototype.save
.call(this) };
3970 DecoderBuffer
.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
;
3976 this.offset
= save
.offset
;
3977 Reporter
.prototype.restore
.call(this, save
.reporter
);
3982 DecoderBuffer
.prototype.isEmpty
= function isEmpty() {
3983 return this.offset
=== this.length
;
3986 DecoderBuffer
.prototype.readUInt8
= function readUInt8(fail
) {
3987 if (this.offset
+ 1 <= this.length
)
3988 return this.base
.readUInt8(this.offset
++, true);
3990 return this.error(fail
|| 'DecoderBuffer overrun');
3993 DecoderBuffer
.prototype.skip
= function skip(bytes
, fail
) {
3994 if (!(this.offset
+ bytes
<= this.length
))
3995 return this.error(fail
|| 'DecoderBuffer overrun');
3997 var res
= new DecoderBuffer(this.base
);
3999 // Share reporter state
4000 res
._reporterState
= this._reporterState
;
4002 res
.offset
= this.offset
;
4003 res
.length
= this.offset
+ bytes
;
4004 this.offset
+= bytes
;
4008 DecoderBuffer
.prototype.raw
= function raw(save
) {
4009 return this.base
.slice(save
? save
.offset : this.offset
, this.length
);
4012 function EncoderBuffer(value
, reporter
) {
4013 if (Array
.isArray(value
)) {
4015 this.value
= value
.map(function(item
) {
4016 if (!(item
instanceof EncoderBuffer
))
4017 item
= new EncoderBuffer(item
, reporter
);
4018 this.length
+= item
.length
;
4021 } else if (typeof value
=== 'number') {
4022 if (!(0 <= value
&& value
<= 0xff))
4023 return reporter
.error('non-byte EncoderBuffer value');
4026 } else if (typeof value
=== 'string') {
4028 this.length
= Buffer
.byteLength(value
);
4029 } else if (Buffer
.isBuffer(value
)) {
4031 this.length
= value
.length
;
4033 return reporter
.error('Unsupported type: ' + typeof value
);
4036 exports
.EncoderBuffer
= EncoderBuffer
;
4038 EncoderBuffer
.prototype.join
= function join(out
, offset
) {
4040 out
= new Buffer(this.length
);
4044 if (this.length
=== 0)
4047 if (Array
.isArray(this.value
)) {
4048 this.value
.forEach(function(item
) {
4049 item
.join(out
, offset
);
4050 offset
+= item
.length
;
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
;
4065 },{"../base":35,"buffer":107,"inherits":163}],35:[function(require
,module
,exports
){
4068 base
.Reporter
= require('./reporter').Reporter
;
4069 base
.DecoderBuffer
= require('./buffer').DecoderBuffer
;
4070 base
.EncoderBuffer
= require('./buffer').EncoderBuffer
;
4071 base
.Node
= require('./node');
4073 },{"./buffer":34,"./node":36,"./reporter":37}],36:[function(require
,module
,exports
){
4074 var Reporter
= require('../base').Reporter
;
4075 var EncoderBuffer
= require('../base').EncoderBuffer
;
4076 var DecoderBuffer
= require('../base').DecoderBuffer
;
4077 var assert
= require('minimalistic-assert');
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'
4087 // Public methods list
4089 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice',
4093 // Overrided methods list
4095 '_peekTag', '_decodeTag', '_use',
4096 '_decodeStr', '_decodeObjid', '_decodeTime',
4097 '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList',
4099 '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime',
4100 '_encodeNull', '_encodeInt', '_encodeBool'
4103 function Node(enc
, parent
) {
4105 this._baseState
= state
;
4109 state
.parent
= parent
|| null;
4110 state
.children
= null;
4115 state
.reverseArgs
= null;
4116 state
.choice
= null;
4117 state
.optional
= false;
4121 state
.useDecoder
= null;
4123 state
['default'] = null;
4124 state
.explicit
= null;
4125 state
.implicit
= null;
4126 state
.contains
= null;
4128 // Should create new instance on each method
4129 if (!state
.parent
) {
4130 state
.children
= [];
4134 module
.exports
= Node
;
4137 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice',
4138 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit',
4139 'implicit', 'contains'
4142 Node
.prototype.clone
= function clone() {
4143 var state
= this._baseState
;
4145 stateProps
.forEach(function(prop
) {
4146 cstate
[prop
] = state
[prop
];
4148 var res
= new this.constructor(cstate
.parent
);
4149 res
._baseState
= cstate
;
4153 Node
.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
);
4164 Node
.prototype._init
= function init(body
) {
4165 var state
= this._baseState
;
4167 assert(state
.parent
=== null);
4171 state
.children
= state
.children
.filter(function(child
) {
4172 return child
._baseState
.parent
=== this;
4174 assert
.equal(state
.children
.length
, 1, 'Root node can have only one child');
4177 Node
.prototype._useArgs
= function useArgs(args
) {
4178 var state
= this._baseState
;
4180 // Filter children and args
4181 var children
= args
.filter(function(arg
) {
4182 return arg
instanceof this.constructor;
4184 args
= args
.filter(function(arg
) {
4185 return !(arg
instanceof this.constructor);
4188 if (children
.length
!== 0) {
4189 assert(state
.children
=== null);
4190 state
.children
= children
;
4192 // Replace parent to maintain backward link
4193 children
.forEach(function(child
) {
4194 child
._baseState
.parent
= this;
4197 if (args
.length
!== 0) {
4198 assert(state
.args
=== null);
4200 state
.reverseArgs
= args
.map(function(arg
) {
4201 if (typeof arg
!== 'object' || arg
.constructor !== Object
)
4205 Object
.keys(arg
).forEach(function(key
) {
4206 if (key
== (key
| 0))
4208 var value
= arg
[key
];
4217 // Overrided methods
4220 overrided
.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
);
4231 tags
.forEach(function(tag
) {
4232 Node
.prototype[tag
] = function _tagMethod() {
4233 var state
= this._baseState
;
4234 var args
= Array
.prototype.slice
.call(arguments
);
4236 assert(state
.tag
=== null);
4239 this._useArgs(args
);
4245 Node
.prototype.use = function use(item
) {
4247 var state
= this._baseState
;
4249 assert(state
.use === null);
4255 Node
.prototype.optional
= function optional() {
4256 var state
= this._baseState
;
4258 state
.optional
= true;
4263 Node
.prototype.def
= function def(val
) {
4264 var state
= this._baseState
;
4266 assert(state
['default'] === null);
4267 state
['default'] = val
;
4268 state
.optional
= true;
4273 Node
.prototype.explicit
= function explicit(num
) {
4274 var state
= this._baseState
;
4276 assert(state
.explicit
=== null && state
.implicit
=== null);
4277 state
.explicit
= num
;
4282 Node
.prototype.implicit
= function implicit(num
) {
4283 var state
= this._baseState
;
4285 assert(state
.explicit
=== null && state
.implicit
=== null);
4286 state
.implicit
= num
;
4291 Node
.prototype.obj
= function obj() {
4292 var state
= this._baseState
;
4293 var args
= Array
.prototype.slice
.call(arguments
);
4297 if (args
.length
!== 0)
4298 this._useArgs(args
);
4303 Node
.prototype.key
= function key(newKey
) {
4304 var state
= this._baseState
;
4306 assert(state
.key
=== null);
4312 Node
.prototype.any
= function any() {
4313 var state
= this._baseState
;
4320 Node
.prototype.choice
= function choice(obj
) {
4321 var state
= this._baseState
;
4323 assert(state
.choice
=== null);
4325 this._useArgs(Object
.keys(obj
).map(function(key
) {
4332 Node
.prototype.contains
= function contains(item
) {
4333 var state
= this._baseState
;
4335 assert(state
.use === null);
4336 state
.contains
= item
;
4345 Node
.prototype._decode
= function decode(input
, options
) {
4346 var state
= this._baseState
;
4349 if (state
.parent
=== null)
4350 return input
.wrapResult(state
.children
[0]._decode(input
, options
));
4352 var result
= state
['default'];
4356 if (state
.key
!== null)
4357 prevKey
= input
.enterKey(state
.key
);
4359 // Check if tag is there
4360 if (state
.optional
) {
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)
4369 if (tag
=== null && !state
.any
) {
4371 var save
= input
.save();
4373 if (state
.choice
=== null)
4374 this._decodeGeneric(state
.tag
, input
, options
);
4376 this._decodeChoice(input
, options
);
4381 input
.restore(save
);
4383 present
= this._peekTag(input
, tag
, state
.any
);
4385 if (input
.isError(present
))
4390 // Push object on stack
4392 if (state
.obj
&& present
)
4393 prevObj
= input
.enterObject();
4396 // Unwrap explicit values
4397 if (state
.explicit
!== null) {
4398 var explicit
= this._decodeTag(input
, state
.explicit
);
4399 if (input
.isError(explicit
))
4404 var start
= input
.offset
;
4406 // Unwrap implicit and normal values
4407 if (state
.use === null && state
.choice
=== null) {
4409 var save
= input
.save();
4410 var body
= this._decodeTag(
4412 state
.implicit
!== null ? state
.implicit : state
.tag
,
4415 if (input
.isError(body
))
4419 result
= input
.raw(save
);
4424 if (options
&& options
.track
&& state
.tag
!== null)
4425 options
.track(input
.path(), start
, input
.length
, 'tagged');
4427 if (options
&& options
.track
&& state
.tag
!== null)
4428 options
.track(input
.path(), input
.offset
, input
.length
, 'content');
4430 // Select proper method for tag
4433 else if (state
.choice
=== null)
4434 result
= this._decodeGeneric(state
.tag
, input
, options
);
4436 result
= this._decodeChoice(input
, options
);
4438 if (input
.isError(result
))
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
);
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
);
4459 if (state
.obj
&& present
)
4460 result
= input
.leaveObject(prevObj
);
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
);
4471 Node
.prototype._decodeGeneric
= function decodeGeneric(tag
, input
, options
) {
4472 var state
= this._baseState
;
4474 if (tag
=== 'seq' || tag
=== 'set')
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
);
4495 if (state
.use !== null) {
4496 return this._getUse(state
.use, input
._reporterState
.obj
)
4497 ._decode(input
, options
);
4499 return input
.error('unknown tag: ' + tag
);
4503 Node
.prototype._getUse
= function _getUse(entity
, obj
) {
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
;
4514 return state
.useDecoder
;
4517 Node
.prototype._decodeChoice
= function decodeChoice(input
, options
) {
4518 var state
= this._baseState
;
4522 Object
.keys(state
.choice
).some(function(key
) {
4523 var save
= input
.save();
4524 var node
= state
.choice
[key
];
4526 var value
= node
._decode(input
, options
);
4527 if (input
.isError(value
))
4530 result
= { type: key
, value: value
};
4533 input
.restore(save
);
4540 return input
.error('Choice not matched');
4549 Node
.prototype._createEncoderBuffer
= function createEncoderBuffer(data
) {
4550 return new EncoderBuffer(data
, this.reporter
);
4553 Node
.prototype._encode
= function encode(data
, reporter
, parent
) {
4554 var state
= this._baseState
;
4555 if (state
['default'] !== null && state
['default'] === data
)
4558 var result
= this._encodeValue(data
, reporter
, parent
);
4559 if (result
=== undefined)
4562 if (this._skipDefault(result
, reporter
, parent
))
4568 Node
.prototype._encodeValue
= function encode(data
, reporter
, parent
) {
4569 var state
= this._baseState
;
4572 if (state
.parent
=== null)
4573 return state
.children
[0]._encode(data
, reporter
|| new Reporter());
4577 // Set reporter to share it with a child class
4578 this.reporter
= reporter
;
4580 // Check if data is there
4581 if (state
.optional
&& data
=== undefined) {
4582 if (state
['default'] !== null)
4583 data
= state
['default']
4588 // Encode children first
4590 var primitive
= false;
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
);
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
);
4604 if (child
._baseState
.key
=== null)
4605 return reporter
.error('Child should have a key');
4606 var prevKey
= reporter
.enterKey(child
._baseState
.key
);
4608 if (typeof data
!== 'object')
4609 return reporter
.error('Child expected, but input is not object');
4611 var res
= child
._encode(data
[child
._baseState
.key
], reporter
, data
);
4612 reporter
.leaveKey(prevKey
);
4615 }, this).filter(function(child
) {
4618 content
= this._createEncoderBuffer(content
);
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
);
4625 if (!Array
.isArray(data
))
4626 return reporter
.error('seqof/setof, but data is not Array');
4628 var child
= this.clone();
4629 child
._baseState
.implicit
= null;
4630 content
= this._createEncoderBuffer(data
.map(function(item
) {
4631 var state
= this._baseState
;
4633 return this._getUse(state
.args
[0], data
)._encode(item
, reporter
);
4635 } else if (state
.use !== null) {
4636 result
= this._getUse(state
.use, parent
)._encode(data
, reporter
);
4638 content
= this._encodePrimitive(state
.tag
, data
);
4643 // Encode data itself
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';
4650 if (state
.use === null)
4651 reporter
.error('Tag could be omitted only for .use()');
4653 if (state
.use === null)
4654 result
= this._encodeComposite(tag
, primitive
, cls
, content
);
4659 if (state
.explicit
!== null)
4660 result
= this._encodeComposite(state
.explicit
, false, 'context', result
);
4665 Node
.prototype._encodeChoice
= function encodeChoice(data
, reporter
) {
4666 var state
= this._baseState
;
4668 var node
= state
.choice
[data
.type
];
4672 data
.type
+ ' not found in ' +
4673 JSON
.stringify(Object
.keys(state
.choice
)));
4675 return node
._encode(data
.value
, reporter
);
4678 Node
.prototype._encodePrimitive
= function encodePrimitive(tag
, data
) {
4679 var state
= this._baseState
;
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
);
4698 throw new Error('Unsupported tag: ' + tag
);
4701 Node
.prototype._isNumstr
= function isNumstr(str
) {
4702 return /^[0-9 ]*$/.test(str
);
4705 Node
.prototype._isPrintstr
= function isPrintstr(str
) {
4706 return /^[A
-Za
-z0
-9 '\(\)\+,\-\.\/:=\?]*$/.test(str);
4709 },{"../base":35,"minimalistic-assert":176}],37:[function(require,module,exports){
4710 var inherits = require('inherits
');
4712 function Reporter(options) {
4713 this._reporterState = {
4716 options: options || {},
4720 exports.Reporter = Reporter;
4722 Reporter.prototype.isError = function isError(obj) {
4723 return obj instanceof ReporterError;
4726 Reporter.prototype.save = function save() {
4727 var state = this._reporterState;
4729 return { obj: state.obj, pathLen: state.path.length };
4732 Reporter.prototype.restore = function restore(data) {
4733 var state = this._reporterState;
4735 state.obj = data.obj;
4736 state.path = state.path.slice(0, data.pathLen);
4739 Reporter.prototype.enterKey = function enterKey(key) {
4740 return this._reporterState.path.push(key);
4743 Reporter.prototype.exitKey = function exitKey(index) {
4744 var state = this._reporterState;
4746 state.path = state.path.slice(0, index - 1);
4749 Reporter.prototype.leaveKey = function leaveKey(index, key, value) {
4750 var state = this._reporterState;
4752 this.exitKey(index);
4753 if (state.obj !== null)
4754 state.obj[key] = value;
4757 Reporter.prototype.path = function path() {
4758 return this._reporterState.path.join('/');
4761 Reporter.prototype.enterObject = function enterObject() {
4762 var state = this._reporterState;
4764 var prev = state.obj;
4769 Reporter.prototype.leaveObject = function leaveObject(prev) {
4770 var state = this._reporterState;
4772 var now = state.obj;
4777 Reporter.prototype.error = function error(msg) {
4779 var state = this._reporterState;
4781 var inherited = msg instanceof ReporterError;
4785 err = new ReporterError(state.path.map(function(elem) {
4786 return '[' + JSON.stringify(elem) + ']';
4787 }).join(''), msg.message || msg, msg.stack);
4790 if (!state.options.partial)
4794 state.errors.push(err);
4799 Reporter.prototype.wrapResult = function wrapResult(result) {
4800 var state = this._reporterState;
4801 if (!state.options.partial)
4805 result: this.isError(result) ? null : result,
4806 errors: state.errors
4810 function ReporterError(path, msg) {
4814 inherits(ReporterError, Error);
4816 ReporterError.prototype.rethrow = function rethrow(msg) {
4817 this.message = msg + ' at: ' + (this.path || '(shallow
)');
4818 if (Error.captureStackTrace)
4819 Error.captureStackTrace(this, ReporterError);
4823 // IE only adds stack when thrown
4824 throw new Error(this.message);
4826 this.stack = e.stack;
4832 },{"inherits":163}],38:[function(require,module,exports){
4833 var constants = require('../constants
');
4835 exports.tagClass = {
4841 exports.tagClassByName = constants._reverse(exports.tagClass);
4857 0x0d: 'relativeOid
',
4874 exports.tagByName = constants._reverse(exports.tag);
4876 },{"../constants":39}],39:[function(require,module,exports){
4877 var constants = exports;
4880 constants._reverse = function reverse(map) {
4883 Object.keys(map).forEach(function(key) {
4884 // Convert key to integer if it is stringified
4885 if ((key | 0) == key)
4888 var value = map[key];
4895 constants.der = require('./der
');
4897 },{"./der":38}],40:[function(require,module,exports){
4898 var inherits = require('inherits
');
4900 var asn1 = require('../../asn1');
4901 var base = asn1.base;
4902 var bignum = asn1.bignum;
4904 // Import DER constants
4905 var der = asn1.constants.der;
4907 function DERDecoder(entity) {
4909 this.name = entity.name;
4910 this.entity = entity;
4912 // Construct base tree
4913 this.tree = new DERNode();
4914 this.tree._init(entity.body);
4916 module.exports = DERDecoder;
4918 DERDecoder.prototype.decode = function decode(data, options) {
4919 if (!(data instanceof base.DecoderBuffer))
4920 data = new base.DecoderBuffer(data, options);
4922 return this.tree._decode(data, options);
4927 function DERNode(parent) {
4928 base.Node.call(this, 'der
', parent);
4930 inherits(DERNode, base.Node);
4932 DERNode.prototype._peekTag = function peekTag(buffer, tag, any) {
4933 if (buffer.isEmpty())
4936 var state = buffer.save();
4937 var decodedTag = derDecodeTag(buffer, 'Failed to peek
tag: "' + tag + '"');
4938 if (buffer.isError(decodedTag))
4941 buffer.restore(state);
4943 return decodedTag.tag === tag || decodedTag.tagStr === tag ||
4944 (decodedTag.tagStr + 'of') === tag || any;
4947 DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) {
4948 var decodedTag = derDecodeTag(buffer,
4949 'Failed to decode tag
of "' + tag + '"');
4950 if (buffer.isError(decodedTag))
4953 var len = derDecodeLen(buffer,
4954 decodedTag.primitive,
4955 'Failed to
get length
of "' + tag + '"');
4958 if (buffer.isError(len))
4962 decodedTag.tag !== tag &&
4963 decodedTag.tagStr !== tag &&
4964 decodedTag.tagStr + 'of' !== tag) {
4965 return buffer.error('Failed to match
tag: "' + tag + '"');
4968 if (decodedTag.primitive || len !== null)
4969 return buffer.skip(len, 'Failed to match body
of: "' + tag + '"');
4971 // Indefinite length... find END tag
4972 var state = buffer.save();
4973 var res = this._skipUntilEnd(
4975 'Failed to skip indefinite length
body: "' + this.tag + '"');
4976 if (buffer.isError(res))
4979 len = buffer.offset - state.offset;
4980 buffer.restore(state);
4981 return buffer.skip(len, 'Failed to match body
of: "' + tag + '"');
4984 DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) {
4986 var tag = derDecodeTag(buffer, fail);
4987 if (buffer.isError(tag))
4989 var len = derDecodeLen(buffer, tag.primitive, fail);
4990 if (buffer.isError(len))
4994 if (tag.primitive || len !== null)
4995 res = buffer.skip(len)
4997 res = this._skipUntilEnd(buffer, fail);
5000 if (buffer.isError(res))
5003 if (tag.tagStr === 'end
')
5008 DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder,
5011 while (!buffer.isEmpty()) {
5012 var possibleEnd = this._peekTag(buffer, 'end
');
5013 if (buffer.isError(possibleEnd))
5016 var res = decoder.decode(buffer, 'der
', options);
5017 if (buffer.isError(res) && possibleEnd)
5024 DERNode.prototype._decodeStr = function decodeStr(buffer, tag) {
5025 if (tag === 'bitstr
') {
5026 var unused = buffer.readUInt8();
5027 if (buffer.isError(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
');
5036 for (var i = 0; i < raw.length / 2; i++) {
5037 str += String.fromCharCode(raw.readUInt16BE(i * 2));
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
');
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
');
5058 } else if (/str$/.test(tag)) {
5059 return buffer.raw().toString();
5061 return buffer.error('Decoding
of string
type: ' + tag + ' unsupported
');
5065 DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) {
5067 var identifiers = [];
5069 while (!buffer.isEmpty()) {
5070 var subident = buffer.readUInt8();
5072 ident |= subident & 0x7f;
5073 if ((subident & 0x80) === 0) {
5074 identifiers.push(ident);
5078 if (subident & 0x80)
5079 identifiers.push(ident);
5081 var first = (identifiers[0] / 40) | 0;
5082 var second = identifiers[0] % 40;
5085 result = identifiers;
5087 result = [first, second].concat(identifiers.slice(1));
5090 var tmp = values[result.join(' ')];
5091 if (tmp === undefined)
5092 tmp = values[result.join('.')];
5093 if (tmp !== undefined)
5100 DERNode.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;
5121 return buffer.error('Decoding
' + tag + ' time is not supported yet
');
5124 return Date.UTC(year, mon - 1, day, hour, min, sec, 0);
5127 DERNode.prototype._decodeNull = function decodeNull(buffer) {
5131 DERNode.prototype._decodeBool = function decodeBool(buffer) {
5132 var res = buffer.readUInt8();
5133 if (buffer.isError(res))
5139 DERNode.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);
5145 res = values[res.toString(10)] || res;
5150 DERNode.prototype._use = function use(entity, obj) {
5151 if (typeof entity === 'function')
5152 entity = entity(obj);
5153 return entity._getDecoder('der
').tree;
5158 function derDecodeTag(buf, fail) {
5159 var tag = buf.readUInt8(fail);
5160 if (buf.isError(tag))
5163 var cls = der.tagClass[tag >> 6];
5164 var primitive = (tag & 0x20) === 0;
5166 // Multi-octet tag - load
5167 if ((tag & 0x1f) === 0x1f) {
5170 while ((oct & 0x80) === 0x80) {
5171 oct = buf.readUInt8(fail);
5172 if (buf.isError(oct))
5181 var tagStr = der.tag[tag];
5185 primitive: primitive,
5191 function derDecodeLen(buf, primitive, fail) {
5192 var len = buf.readUInt8(fail);
5193 if (buf.isError(len))
5197 if (!primitive && len === 0x80)
5201 if ((len & 0x80) === 0) {
5207 var num = len & 0x7f;
5209 return buf.error('length octect is too
long');
5212 for (var i = 0; i < num; i++) {
5214 var j = buf.readUInt8(fail);
5223 },{"../../asn1":32,"inherits":163}],41:[function(require,module,exports){
5224 var decoders = exports;
5226 decoders.der = require('./der
');
5227 decoders.pem = require('./pem
');
5229 },{"./der":40,"./pem":42}],42:[function(require,module,exports){
5230 var inherits = require('inherits
');
5231 var Buffer = require('buffer
').Buffer;
5233 var DERDecoder = require('./der
');
5235 function PEMDecoder(entity) {
5236 DERDecoder.call(this, entity);
5239 inherits(PEMDecoder, DERDecoder);
5240 module.exports = PEMDecoder;
5242 PEMDecoder.prototype.decode = function decode(data, options) {
5243 var lines = data.toString().split(/[\r\n]+/g);
5245 var label = options.label.toUpperCase();
5247 var re = /^-----(BEGIN|END) ([^-]+)-----$/;
5250 for (var i = 0; i < lines.length; i++) {
5251 var match = lines[i].match(re);
5255 if (match[2] !== label)
5259 if (match[1] !== 'BEGIN
')
5263 if (match[1] !== 'END
')
5269 if (start === -1 || end === -1)
5270 throw new Error('PEM section not found
for: ' + label);
5272 var base64 = lines.slice(start + 1, end).join('');
5273 // Remove excessive symbols
5274 base64.replace(/[^a-z0-9\+\/=]+/gi, '');
5276 var input = new Buffer(base64, 'base64
');
5277 return DERDecoder.prototype.decode.call(this, input, options);
5280 },{"./der":40,"buffer":107,"inherits":163}],43:[function(require,module,exports){
5281 var inherits = require('inherits
');
5282 var Buffer = require('buffer
').Buffer;
5284 var asn1 = require('../../asn1');
5285 var base = asn1.base;
5287 // Import DER constants
5288 var der = asn1.constants.der;
5290 function DEREncoder(entity) {
5292 this.name = entity.name;
5293 this.entity = entity;
5295 // Construct base tree
5296 this.tree = new DERNode();
5297 this.tree._init(entity.body);
5299 module.exports = DEREncoder;
5301 DEREncoder.prototype.encode = function encode(data, reporter) {
5302 return this.tree._encode(data, reporter).join();
5307 function DERNode(parent) {
5308 base.Node.call(this, 'der
', parent);
5310 inherits(DERNode, base.Node);
5312 DERNode.prototype._encodeComposite = function encodeComposite(tag,
5316 var encodedTag = encodeTag(tag, primitive, cls, this.reporter);
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 ]);
5327 // Count octets required to store length
5329 for (var i = content.length; i >= 0x100; i >>= 8)
5332 var header = new Buffer(1 + 1 + lenOctets);
5333 header[0] = encodedTag;
5334 header[1] = 0x80 | lenOctets;
5336 for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8)
5337 header[i] = j & 0xff;
5339 return this._createEncoderBuffer([ header, content ]);
5342 DERNode.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);
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
');
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
, ' +
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);
5372 return this.reporter.error('Encoding
of string
type: ' + tag +
5377 DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) {
5378 if (typeof id === 'string
') {
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++)
5386 } else if (Array.isArray(id)) {
5388 for (var i = 0; i < id.length; i++)
5392 if (!Array.isArray(id)) {
5393 return this.reporter.error('objid() should be either array or string
, ' +
5394 'got: ' + JSON.stringify(id));
5399 return this.reporter.error('Second objid identifier OOB
');
5400 id.splice(0, 2, id[0] * 40 + id[1]);
5403 // Count number of octets
5405 for (var i = 0; i < id.length; i++) {
5407 for (size++; ident >= 0x80; ident >>= 7)
5411 var objid = new Buffer(size);
5412 var offset = objid.length - 1;
5413 for (var i = id.length - 1; i >= 0; i--) {
5415 objid[offset--] = ident & 0x7f;
5416 while ((ident >>= 7) > 0)
5417 objid[offset--] = 0x80 | (ident & 0x7f);
5420 return this._createEncoderBuffer(objid);
5430 DERNode.prototype._encodeTime = function encodeTime(time, tag) {
5432 var date = new Date(time);
5434 if (tag === 'gentime
') {
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()),
5444 } else if (tag === 'utctime
') {
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()),
5455 this.reporter.error('Encoding
' + tag + ' time is not supported yet
');
5458 return this._encodeStr(str, 'octstr
');
5461 DERNode.prototype._encodeNull = function encodeNull() {
5462 return this._createEncoderBuffer('');
5465 DERNode.prototype._encodeInt = function encodeInt(num, values) {
5466 if (typeof num === 'string
') {
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));
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);
5482 num = new Buffer(numArray);
5485 if (Buffer.isBuffer(num)) {
5486 var size = num.length;
5487 if (num.length === 0)
5490 var out = new Buffer(size);
5492 if (num.length === 0)
5494 return this._createEncoderBuffer(out);
5498 return this._createEncoderBuffer(num);
5501 return this._createEncoderBuffer([0, num]);
5504 for (var i = num; i >= 0x100; i >>= 8)
5507 var out = new Array(size);
5508 for (var i = out.length - 1; i >= 0; i--) {
5509 out[i] = num & 0xff;
5516 return this._createEncoderBuffer(new Buffer(out));
5519 DERNode.prototype._encodeBool = function encodeBool(value) {
5520 return this._createEncoderBuffer(value ? 0xff : 0);
5523 DERNode.prototype._use = function use(entity, obj) {
5524 if (typeof entity === 'function')
5525 entity = entity(obj);
5526 return entity._getEncoder('der
').tree;
5529 DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) {
5530 var state = this._baseState;
5532 if (state['default'] === null)
5535 var data = dataBuffer.join();
5536 if (state.defaultBuffer === undefined)
5537 state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join();
5539 if (data.length !== state.defaultBuffer.length)
5542 for (i=0; i < data.length; i++)
5543 if (data[i] !== state.defaultBuffer[i])
5551 function encodeTag(tag, primitive, cls, reporter) {
5554 if (tag === 'seqof
')
5556 else if (tag === 'setof
')
5559 if (der.tagByName.hasOwnProperty(tag))
5560 res = der.tagByName[tag];
5561 else if (typeof tag === 'number
' && (tag | 0) === tag)
5564 return reporter.error('Unknown
tag: ' + tag);
5567 return reporter.error('Multi
-octet tag encoding unsupported
');
5572 res |= (der.tagClassByName[cls || 'universal
'] << 6);
5577 },{"../../asn1":32,"buffer":107,"inherits":163}],44:[function(require,module,exports){
5578 var encoders = exports;
5580 encoders.der = require('./der
');
5581 encoders.pem = require('./pem
');
5583 },{"./der":43,"./pem":45}],45:[function(require,module,exports){
5584 var inherits = require('inherits
');
5586 var DEREncoder = require('./der
');
5588 function PEMEncoder(entity) {
5589 DEREncoder.call(this, entity);
5592 inherits(PEMEncoder, DEREncoder);
5593 module.exports = PEMEncoder;
5595 PEMEncoder.prototype.encode = function encode(data, options) {
5596 var buf = DEREncoder.prototype.encode.call(this, data);
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');
5606 },{"./der":43,"inherits":163}],46:[function(require,module,exports){
5607 module.exports = require('./lib/axios');
5608 },{"./lib/axios":48}],47:[function(require,module,exports){
5609 (function (process){
5612 var utils = require('./../utils');
5613 var settle = require('./../core/settle
');
5614 var buildURL = require('./../helpers
/buildURL
');
5615 var parseHeaders = require('./../helpers
/parseHeaders
');
5616 var isURLSameOrigin = require('./../helpers
/isURLSameOrigin
');
5617 var createError = require('../core/createError');
5618 var btoa = (typeof window !== 'undefined' && window.btoa && window.btoa.bind(window)) || require('./../helpers
/btoa
');
5620 module.exports = function xhrAdapter(config) {
5621 return new Promise(function dispatchXhrRequest(resolve, reject) {
5622 var requestData = config.data;
5623 var requestHeaders = config.headers;
5625 if (utils.isFormData(requestData)) {
5626 delete requestHeaders['Content
-Type
']; // Let the browser set it
5629 var request = new XMLHttpRequest();
5630 var loadEvent = 'onreadystatechange
';
5631 var xDomain = false;
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';
5643 request
.onprogress
= function handleProgress() {};
5644 request
.ontimeout
= function handleTimeout() {};
5647 // HTTP basic authentication
5649 var username
= config
.auth
.username
|| '';
5650 var password
= config
.auth
.password
|| '';
5651 requestHeaders
.Authorization
= 'Basic ' + btoa(username
+ ':' + password
);
5654 request
.open(config
.method
.toUpperCase(), buildURL(config
.url
, config
.params
, config
.paramsSerializer
), true);
5656 // Set the request timeout in MS
5657 request
.timeout
= config
.timeout
;
5659 // Listen for ready state
5660 request
[loadEvent
] = function handleLoad() {
5661 if (!request
|| (request
.readyState
!== 4 && !xDomain
)) {
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)) {
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
;
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
,
5686 settle(resolve
, reject
, response
);
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
));
5703 request
.ontimeout
= function handleTimeout() {
5704 reject(createError('timeout of ' + config
.timeout
+ 'ms exceeded', config
, 'ECONNABORTED',
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');
5718 var xsrfValue
= (config
.withCredentials
|| isURLSameOrigin(config
.url
)) && config
.xsrfCookieName
?
5719 cookies
.read(config
.xsrfCookieName
) :
5723 requestHeaders
[config
.xsrfHeaderName
] = xsrfValue
;
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
];
5734 // Otherwise add header to the request
5735 request
.setRequestHeader(key
, val
);
5740 // Add withCredentials to request if needed
5741 if (config
.withCredentials
) {
5742 request
.withCredentials
= true;
5745 // Add responseType to request if needed
5746 if (config
.responseType
) {
5748 request
.responseType
= config
.responseType
;
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') {
5758 // Handle progress if needed
5759 if (typeof config
.onDownloadProgress
=== 'function') {
5760 request
.addEventListener('progress', config
.onDownloadProgress
);
5763 // Not all browsers support upload events
5764 if (typeof config
.onUploadProgress
=== 'function' && request
.upload
) {
5765 request
.upload
.addEventListener('progress', config
.onUploadProgress
);
5768 if (config
.cancelToken
) {
5769 // Handle cancellation
5770 config
.cancelToken
.promise
.then(function onCanceled(cancel
) {
5782 if (requestData
=== undefined) {
5787 request
.send(requestData
);
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
){
5795 var utils
= require('./utils');
5796 var bind
= require('./helpers/bind');
5797 var Axios
= require('./core/Axios');
5798 var defaults
= require('./defaults');
5801 * Create an instance of Axios
5803 * @param {Object} defaultConfig The default config for the instance
5804 * @return {Axios} A new instance of Axios
5806 function createInstance(defaultConfig
) {
5807 var context
= new Axios(defaultConfig
);
5808 var instance
= bind(Axios
.prototype.request
, context
);
5810 // Copy axios.prototype to instance
5811 utils
.extend(instance
, Axios
.prototype, context
);
5813 // Copy context to instance
5814 utils
.extend(instance
, context
);
5819 // Create the default instance to be exported
5820 var axios
= createInstance(defaults
);
5822 // Expose Axios class to allow class inheritance
5823 axios
.Axios
= Axios
;
5825 // Factory for creating new instances
5826 axios
.create
= function create(instanceConfig
) {
5827 return createInstance(utils
.merge(defaults
, instanceConfig
));
5830 // Expose Cancel & CancelToken
5831 axios
.Cancel
= require('./cancel/Cancel');
5832 axios
.CancelToken
= require('./cancel/CancelToken');
5833 axios
.isCancel
= require('./cancel/isCancel');
5835 // Expose all/spread
5836 axios
.all
= function all(promises
) {
5837 return Promise
.all(promises
);
5839 axios
.spread
= require('./helpers/spread');
5841 module
.exports
= axios
;
5843 // Allow use of default import syntax in TypeScript
5844 module
.exports
.default = axios
;
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
){
5850 * A `Cancel` is an object that is thrown when an operation is canceled.
5853 * @param {string=} message The message.
5855 function Cancel(message
) {
5856 this.message
= message
;
5859 Cancel
.prototype.toString
= function toString() {
5860 return 'Cancel' + (this.message
? ': ' + this.message : '');
5863 Cancel
.prototype.__CANCEL__
= true;
5865 module
.exports
= Cancel
;
5867 },{}],50:[function(require
,module
,exports
){
5870 var Cancel
= require('./Cancel');
5873 * A `CancelToken` is an object that can be used to request cancellation of an operation.
5876 * @param {Function} executor The executor function.
5878 function CancelToken(executor
) {
5879 if (typeof executor
!== 'function') {
5880 throw new TypeError('executor must be a function.');
5884 this.promise
= new Promise(function promiseExecutor(resolve
) {
5885 resolvePromise
= resolve
;
5889 executor(function cancel(message
) {
5891 // Cancellation has already been requested
5895 token
.reason
= new Cancel(message
);
5896 resolvePromise(token
.reason
);
5901 * Throws a `Cancel` if cancellation has been requested.
5903 CancelToken
.prototype.throwIfRequested
= function throwIfRequested() {
5910 * Returns an object that contains a new `CancelToken` and a function that, when called,
5911 * cancels the `CancelToken`.
5913 CancelToken
.source
= function source() {
5915 var token
= new CancelToken(function executor(c
) {
5924 module
.exports
= CancelToken
;
5926 },{"./Cancel":49}],51:[function(require
,module
,exports
){
5929 module
.exports
= function isCancel(value
) {
5930 return !!(value
&& value
.__CANCEL__
);
5933 },{}],52:[function(require
,module
,exports
){
5936 var defaults
= require('./../defaults');
5937 var utils
= require('./../utils');
5938 var InterceptorManager
= require('./InterceptorManager');
5939 var dispatchRequest
= require('./dispatchRequest');
5942 * Create a new instance of Axios
5944 * @param {Object} instanceConfig The default config for the instance
5946 function Axios(instanceConfig
) {
5947 this.defaults
= instanceConfig
;
5948 this.interceptors
= {
5949 request: new InterceptorManager(),
5950 response: new InterceptorManager()
5955 * Dispatch a request
5957 * @param {Object} config The config specific for this request (merged with this.defaults)
5959 Axios
.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({
5968 config
= utils
.merge(defaults
, {method: 'get'}, this.defaults
, config
);
5969 config
.method
= config
.method
.toLowerCase();
5971 // Hook up interceptors middleware
5972 var chain
= [dispatchRequest
, undefined];
5973 var promise
= Promise
.resolve(config
);
5975 this.interceptors
.request
.forEach(function unshiftRequestInterceptors(interceptor
) {
5976 chain
.unshift(interceptor
.fulfilled
, interceptor
.rejected
);
5979 this.interceptors
.response
.forEach(function pushResponseInterceptors(interceptor
) {
5980 chain
.push(interceptor
.fulfilled
, interceptor
.rejected
);
5983 while (chain
.length
) {
5984 promise
= promise
.then(chain
.shift(), chain
.shift());
5990 // Provide aliases for supported request methods
5991 utils
.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
|| {}, {
6001 utils
.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
|| {}, {
6012 module
.exports
= Axios
;
6014 },{"./../defaults":59,"./../utils":70,"./InterceptorManager":53,"./dispatchRequest":55}],53:[function(require
,module
,exports
){
6017 var utils
= require('./../utils');
6019 function InterceptorManager() {
6024 * Add a new interceptor to the stack
6026 * @param {Function} fulfilled The function to handle `then` for a `Promise`
6027 * @param {Function} rejected The function to handle `reject` for a `Promise`
6029 * @return {Number} An ID used to remove interceptor later
6031 InterceptorManager
.prototype.use = function use(fulfilled
, rejected
) {
6032 this.handlers
.push({
6033 fulfilled: fulfilled
,
6036 return this.handlers
.length
- 1;
6040 * Remove an interceptor from the stack
6042 * @param {Number} id The ID that was returned by `use`
6044 InterceptorManager
.prototype.eject
= function eject(id
) {
6045 if (this.handlers
[id
]) {
6046 this.handlers
[id
] = null;
6051 * Iterate over all the registered interceptors
6053 * This method is particularly useful for skipping over any
6054 * interceptors that may have become `null` calling `eject`.
6056 * @param {Function} fn The function to call for each interceptor
6058 InterceptorManager
.prototype.forEach
= function forEach(fn
) {
6059 utils
.forEach(this.handlers
, function forEachHandler(h
) {
6066 module
.exports
= InterceptorManager
;
6068 },{"./../utils":70}],54:[function(require
,module
,exports
){
6071 var enhanceError
= require('./enhanceError');
6074 * Create an Error with the specified message, config, error code, request and response.
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.
6083 module
.exports
= function createError(message
, config
, code
, request
, response
) {
6084 var error
= new Error(message
);
6085 return enhanceError(error
, config
, code
, request
, response
);
6088 },{"./enhanceError":56}],55:[function(require
,module
,exports
){
6091 var utils
= require('./../utils');
6092 var transformData
= require('./transformData');
6093 var isCancel
= require('../cancel/isCancel');
6094 var defaults
= require('../defaults');
6095 var isAbsoluteURL
= require('./../helpers/isAbsoluteURL');
6096 var combineURLs
= require('./../helpers/combineURLs');
6099 * Throws a `Cancel` if cancellation has been requested.
6101 function throwIfCancellationRequested(config
) {
6102 if (config
.cancelToken
) {
6103 config
.cancelToken
.throwIfRequested();
6108 * Dispatch a request to the server using the configured adapter.
6110 * @param {object} config The config that is to be used for the request
6111 * @returns {Promise} The Promise to be fulfilled
6113 module
.exports
= function dispatchRequest(config
) {
6114 throwIfCancellationRequested(config
);
6116 // Support baseURL config
6117 if (config
.baseURL
&& !isAbsoluteURL(config
.url
)) {
6118 config
.url
= combineURLs(config
.baseURL
, config
.url
);
6121 // Ensure headers exist
6122 config
.headers
= config
.headers
|| {};
6124 // Transform request data
6125 config
.data
= transformData(
6128 config
.transformRequest
6132 config
.headers
= utils
.merge(
6133 config
.headers
.common
|| {},
6134 config
.headers
[config
.method
] || {},
6135 config
.headers
|| {}
6139 ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'],
6140 function cleanHeaderConfig(method
) {
6141 delete config
.headers
[method
];
6145 var adapter
= config
.adapter
|| defaults
.adapter
;
6147 return adapter(config
).then(function onAdapterResolution(response
) {
6148 throwIfCancellationRequested(config
);
6150 // Transform response data
6151 response
.data
= transformData(
6154 config
.transformResponse
6158 }, function onAdapterRejection(reason
) {
6159 if (!isCancel(reason
)) {
6160 throwIfCancellationRequested(config
);
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
6172 return Promise
.reject(reason
);
6176 },{"../cancel/isCancel":51,"../defaults":59,"./../helpers/combineURLs":63,"./../helpers/isAbsoluteURL":65,"./../utils":70,"./transformData":58}],56:[function(require
,module
,exports
){
6180 * Update an Error with the specified config, error code, and response.
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.
6189 module
.exports
= function enhanceError(error
, config
, code
, request
, response
) {
6190 error
.config
= config
;
6194 error
.request
= request
;
6195 error
.response
= response
;
6199 },{}],57:[function(require
,module
,exports
){
6202 var createError
= require('./createError');
6205 * Resolve or reject a Promise based on response status.
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.
6211 module
.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
)) {
6218 'Request failed with status code ' + response
.status
,
6227 },{"./createError":54}],58:[function(require
,module
,exports
){
6230 var utils
= require('./../utils');
6233 * Transform the data for a request or a response
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
6240 module
.exports
= function transformData(data
, headers
, fns
) {
6241 /*eslint no-param-reassign:0*/
6242 utils
.forEach(fns
, function transform(fn
) {
6243 data
= fn(data
, headers
);
6249 },{"./../utils":70}],59:[function(require
,module
,exports
){
6250 (function (process
){
6253 var utils
= require('./utils');
6254 var normalizeHeaderName
= require('./helpers/normalizeHeaderName');
6256 var DEFAULT_CONTENT_TYPE
= {
6257 'Content-Type': 'application/x-www-form-urlencoded'
6260 function setContentTypeIfUnset(headers
, value
) {
6261 if (!utils
.isUndefined(headers
) && utils
.isUndefined(headers
['Content-Type'])) {
6262 headers
['Content-Type'] = value
;
6266 function getDefaultAdapter() {
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');
6279 adapter: getDefaultAdapter(),
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
) ||
6292 if (utils
.isArrayBufferView(data
)) {
6295 if (utils
.isURLSearchParams(data
)) {
6296 setContentTypeIfUnset(headers
, 'application/x-www-form-urlencoded;charset=utf-8');
6297 return data
.toString();
6299 if (utils
.isObject(data
)) {
6300 setContentTypeIfUnset(headers
, 'application/json;charset=utf-8');
6301 return JSON
.stringify(data
);
6306 transformResponse: [function transformResponse(data
) {
6307 /*eslint no-param-reassign:0*/
6308 if (typeof data
=== 'string') {
6310 data
= JSON
.parse(data
);
6311 } catch (e
) { /* Ignore */ }
6317 * A timeout in milliseconds to abort a request. If set to 0 (default) a
6318 * timeout is not created.
6322 xsrfCookieName: 'XSRF-TOKEN',
6323 xsrfHeaderName: 'X-XSRF-TOKEN',
6325 maxContentLength: -1,
6327 validateStatus: function validateStatus(status
) {
6328 return status
>= 200 && status
< 300;
6332 defaults
.headers
= {
6334 'Accept': 'application/json, text/plain, */*'
6338 utils
.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method
) {
6339 defaults
.headers
[method
] = {};
6342 utils
.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method
) {
6343 defaults
.headers
[method
] = utils
.merge(DEFAULT_CONTENT_TYPE
);
6346 module
.exports
= defaults
;
6348 }).call(this,require('_process'))
6349 },{"./adapters/http":47,"./adapters/xhr":47,"./helpers/normalizeHeaderName":67,"./utils":70,"_process":190}],60:[function(require
,module
,exports
){
6352 module
.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
];
6358 return fn
.apply(thisArg
, args
);
6362 },{}],61:[function(require
,module
,exports
){
6365 // btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js
6367 var chars
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=';
6370 this.message
= 'String contains an invalid character';
6372 E
.prototype = new Error
;
6373 E
.prototype.code
= 5;
6374 E
.prototype.name
= 'InvalidCharacterError';
6376 function btoa(input
) {
6377 var str
= String(input
);
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)
6389 charCode
= str
.charCodeAt(idx
+= 3 / 4);
6390 if (charCode
> 0xFF) {
6393 block
= block
<< 8 | charCode
;
6398 module
.exports
= btoa
;
6400 },{}],62:[function(require
,module
,exports
){
6403 var utils
= require('./../utils');
6405 function 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, ']');
6417 * Build a URL by appending params to the end
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
6423 module
.exports
= function buildURL(url
, params
, paramsSerializer
) {
6424 /*eslint no-param-reassign:0*/
6429 var serializedParams
;
6430 if (paramsSerializer
) {
6431 serializedParams
= paramsSerializer(params
);
6432 } else if (utils
.isURLSearchParams(params
)) {
6433 serializedParams
= params
.toString();
6437 utils
.forEach(params
, function serialize(val
, key
) {
6438 if (val
=== null || typeof val
=== 'undefined') {
6442 if (utils
.isArray(val
)) {
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
);
6454 parts
.push(encode(key
) + '=' + encode(v
));
6458 serializedParams
= parts
.join('&');
6461 if (serializedParams
) {
6462 url
+= (url
.indexOf('?') === -1 ? '?' : '&') + serializedParams
;
6468 },{"./../utils":70}],63:[function(require
,module
,exports
){
6472 * Creates a new URL by combining the specified URLs
6474 * @param {string} baseURL The base URL
6475 * @param {string} relativeURL The relative URL
6476 * @returns {string} The combined URL
6478 module
.exports
= function combineURLs(baseURL
, relativeURL
) {
6480 ? baseURL
.replace(/\/+$/, '') + '/' + relativeURL
.replace(/^\/+/, '')
6484 },{}],64:[function(require
,module
,exports
){
6487 var utils
= require('./../utils');
6490 utils
.isStandardBrowserEnv() ?
6492 // Standard browser envs support document.cookie
6493 (function standardBrowserEnv() {
6495 write: function write(name
, value
, expires
, path
, domain
, secure
) {
6497 cookie
.push(name
+ '=' + encodeURIComponent(value
));
6499 if (utils
.isNumber(expires
)) {
6500 cookie
.push('expires=' + new Date(expires
).toGMTString());
6503 if (utils
.isString(path
)) {
6504 cookie
.push('path=' + path
);
6507 if (utils
.isString(domain
)) {
6508 cookie
.push('domain=' + domain
);
6511 if (secure
=== true) {
6512 cookie
.push('secure');
6515 document
.cookie
= cookie
.join('; ');
6518 read: function read(name
) {
6519 var match
= document
.cookie
.match(new RegExp('(^|;\\s*)(' + name
+ ')=([^;]*)'));
6520 return (match
? decodeURIComponent(match
[3]) : null);
6523 remove: function remove(name
) {
6524 this.write(name
, '', Date
.now() - 86400000);
6529 // Non standard browser env (web workers, react-native) lack needed support.
6530 (function nonStandardBrowserEnv() {
6532 write: function write() {},
6533 read: function read() { return null; },
6534 remove: function remove() {}
6539 },{"./../utils":70}],65:[function(require
,module
,exports
){
6543 * Determines whether the specified URL is absolute
6545 * @param {string} url The URL to test
6546 * @returns {boolean} True if the specified URL is absolute, otherwise false
6548 module
.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
);
6555 },{}],66:[function(require
,module
,exports
){
6558 var utils
= require('./../utils');
6561 utils
.isStandardBrowserEnv() ?
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');
6571 * Parse a URL to discover it's components
6573 * @param {String} url The URL to be parsed
6576 function resolveURL(url
) {
6580 // IE needs attribute set twice to normalize properties
6581 urlParsingNode
.setAttribute('href', href
);
6582 href
= urlParsingNode
.href
;
6585 urlParsingNode
.setAttribute('href', href
);
6587 // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
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
6602 originURL
= resolveURL(window
.location
.href
);
6605 * Determine if a URL shares the same origin as the current location
6607 * @param {String} requestURL The URL to test
6608 * @returns {boolean} True if URL shares the same origin, otherwise false
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
);
6617 // Non standard browser envs (web workers, react-native) lack needed support.
6618 (function nonStandardBrowserEnv() {
6619 return function isURLSameOrigin() {
6625 },{"./../utils":70}],67:[function(require
,module
,exports
){
6628 var utils
= require('../utils');
6630 module
.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
];
6639 },{"../utils":70}],68:[function(require
,module
,exports
){
6642 var utils
= require('./../utils');
6644 // Headers whose duplicates are ignored by node
6645 // c.f. https://nodejs.org/api/http.html#http_message_headers
6646 var 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'
6654 * Parse headers into an object
6657 * Date: Wed, 27 Aug 2014 08:58:49 GMT
6658 * Content-Type: application/json
6659 * Connection: keep-alive
6660 * Transfer-Encoding: chunked
6663 * @param {String} headers Headers needing to be parsed
6664 * @returns {Object} Headers parsed into an object
6666 module
.exports
= function parseHeaders(headers
) {
6672 if (!headers
) { return parsed
; }
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));
6680 if (parsed
[key
] && ignoreDuplicateOf
.indexOf(key
) >= 0) {
6683 if (key
=== 'set-cookie') {
6684 parsed
[key
] = (parsed
[key
] ? parsed
[key
] : []).concat([val
]);
6686 parsed
[key
] = parsed
[key
] ? parsed
[key
] + ', ' + val : val
;
6694 },{"./../utils":70}],69:[function(require
,module
,exports
){
6698 * Syntactic sugar for invoking a function and expanding an array for arguments.
6700 * Common use case would be to use `Function.prototype.apply`.
6703 * function f(x, y, z) {}
6704 * var args = [1, 2, 3];
6705 * f.apply(null, args);
6708 * With `spread` this example can be re-written.
6711 * spread(function(x, y, z) {})([1, 2, 3]);
6714 * @param {Function} callback
6715 * @returns {Function}
6717 module
.exports
= function spread(callback
) {
6718 return function wrap(arr
) {
6719 return callback
.apply(null, arr
);
6723 },{}],70:[function(require
,module
,exports
){
6726 var bind
= require('./helpers/bind');
6727 var isBuffer
= require('is-buffer');
6729 /*global toString:true*/
6731 // utils is a library of generic helper functions non-specific to axios
6733 var toString
= Object
.prototype.toString
;
6736 * Determine if a value is an Array
6738 * @param {Object} val The value to test
6739 * @returns {boolean} True if value is an Array, otherwise false
6741 function isArray(val
) {
6742 return toString
.call(val
) === '[object Array]';
6746 * Determine if a value is an ArrayBuffer
6748 * @param {Object} val The value to test
6749 * @returns {boolean} True if value is an ArrayBuffer, otherwise false
6751 function isArrayBuffer(val
) {
6752 return toString
.call(val
) === '[object ArrayBuffer]';
6756 * Determine if a value is a FormData
6758 * @param {Object} val The value to test
6759 * @returns {boolean} True if value is an FormData, otherwise false
6761 function isFormData(val
) {
6762 return (typeof FormData
!== 'undefined') && (val
instanceof FormData
);
6766 * Determine if a value is a view on an ArrayBuffer
6768 * @param {Object} val The value to test
6769 * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false
6771 function isArrayBufferView(val
) {
6773 if ((typeof ArrayBuffer
!== 'undefined') && (ArrayBuffer
.isView
)) {
6774 result
= ArrayBuffer
.isView(val
);
6776 result
= (val
) && (val
.buffer
) && (val
.buffer
instanceof ArrayBuffer
);
6782 * Determine if a value is a String
6784 * @param {Object} val The value to test
6785 * @returns {boolean} True if value is a String, otherwise false
6787 function isString(val
) {
6788 return typeof val
=== 'string';
6792 * Determine if a value is a Number
6794 * @param {Object} val The value to test
6795 * @returns {boolean} True if value is a Number, otherwise false
6797 function isNumber(val
) {
6798 return typeof val
=== 'number';
6802 * Determine if a value is undefined
6804 * @param {Object} val The value to test
6805 * @returns {boolean} True if the value is undefined, otherwise false
6807 function isUndefined(val
) {
6808 return typeof val
=== 'undefined';
6812 * Determine if a value is an Object
6814 * @param {Object} val The value to test
6815 * @returns {boolean} True if value is an Object, otherwise false
6817 function isObject(val
) {
6818 return val
!== null && typeof val
=== 'object';
6822 * Determine if a value is a Date
6824 * @param {Object} val The value to test
6825 * @returns {boolean} True if value is a Date, otherwise false
6827 function isDate(val
) {
6828 return toString
.call(val
) === '[object Date]';
6832 * Determine if a value is a File
6834 * @param {Object} val The value to test
6835 * @returns {boolean} True if value is a File, otherwise false
6837 function isFile(val
) {
6838 return toString
.call(val
) === '[object File]';
6842 * Determine if a value is a Blob
6844 * @param {Object} val The value to test
6845 * @returns {boolean} True if value is a Blob, otherwise false
6847 function isBlob(val
) {
6848 return toString
.call(val
) === '[object Blob]';
6852 * Determine if a value is a Function
6854 * @param {Object} val The value to test
6855 * @returns {boolean} True if value is a Function, otherwise false
6857 function isFunction(val
) {
6858 return toString
.call(val
) === '[object Function]';
6862 * Determine if a value is a Stream
6864 * @param {Object} val The value to test
6865 * @returns {boolean} True if value is a Stream, otherwise false
6867 function isStream(val
) {
6868 return isObject(val
) && isFunction(val
.pipe
);
6872 * Determine if a value is a URLSearchParams object
6874 * @param {Object} val The value to test
6875 * @returns {boolean} True if value is a URLSearchParams object, otherwise false
6877 function isURLSearchParams(val
) {
6878 return typeof URLSearchParams
!== 'undefined' && val
instanceof URLSearchParams
;
6882 * Trim excess whitespace off the beginning and end of a string
6884 * @param {String} str The String to trim
6885 * @returns {String} The String freed of excess whitespace
6887 function trim(str
) {
6888 return str
.replace(/^\s*/, '').replace(/\s*$/, '');
6892 * Determine if we're running in a standard browser environment
6894 * This allows axios to run in a web worker, and react-native.
6895 * Both environments support XMLHttpRequest, but not fully standard globals.
6898 * typeof window -> undefined
6899 * typeof document -> undefined
6902 * navigator.product -> 'ReactNative'
6904 function isStandardBrowserEnv() {
6905 if (typeof navigator
!== 'undefined' && navigator
.product
=== 'ReactNative') {
6909 typeof window
!== 'undefined' &&
6910 typeof document
!== 'undefined'
6915 * Iterate over an Array or an Object invoking a function for each item.
6917 * If `obj` is an Array callback will be called passing
6918 * the value, index, and complete array for each item.
6920 * If 'obj' is an Object callback will be called passing
6921 * the value, key, and complete object for each property.
6923 * @param {Object|Array} obj The object to iterate
6924 * @param {Function} fn The callback to invoke for each item
6926 function forEach(obj
, fn
) {
6927 // Don't bother if no value provided
6928 if (obj
=== null || typeof obj
=== 'undefined') {
6932 // Force an array if not already something iterable
6933 if (typeof obj
!== 'object') {
6934 /*eslint no-param-reassign:0*/
6939 // Iterate over array values
6940 for (var i
= 0, l
= obj
.length
; i
< l
; i
++) {
6941 fn
.call(null, obj
[i
], i
, obj
);
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
);
6954 * Accepts varargs expecting each argument to be an object, then
6955 * immutably merges the properties of each object and returns result.
6957 * When multiple objects contain the same key the later object in
6958 * the arguments list will take precedence.
6963 * var result = merge({foo: 123}, {foo: 456});
6964 * console.log(result.foo); // outputs 456
6967 * @param {Object} obj1 Object to merge
6968 * @returns {Object} Result of all merge properties
6970 function merge(/* obj1, obj2, obj3, ... */) {
6972 function assignValue(val
, key
) {
6973 if (typeof result
[key
] === 'object' && typeof val
=== 'object') {
6974 result
[key
] = merge(result
[key
], val
);
6980 for (var i
= 0, l
= arguments
.length
; i
< l
; i
++) {
6981 forEach(arguments
[i
], assignValue
);
6987 * Extends object a by mutably adding to it the properties of object b.
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
6994 function extend(a
, b
, thisArg
) {
6995 forEach(b
, function assignValue(val
, key
) {
6996 if (thisArg
&& typeof val
=== 'function') {
6997 a
[key
] = bind(val
, thisArg
);
7007 isArrayBuffer: isArrayBuffer
,
7009 isFormData: isFormData
,
7010 isArrayBufferView: isArrayBufferView
,
7014 isUndefined: isUndefined
,
7018 isFunction: isFunction
,
7020 isURLSearchParams: isURLSearchParams
,
7021 isStandardBrowserEnv: isStandardBrowserEnv
,
7028 },{"./helpers/bind":60,"is-buffer":164}],71:[function(require
,module
,exports
){
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
7037 var Buffer
= require('safe-buffer').Buffer
7039 module
.exports
= function base (ALPHABET
) {
7040 var ALPHABET_MAP
= {}
7041 var BASE
= ALPHABET
.length
7042 var LEADER
= ALPHABET
.charAt(0)
7044 // pre-compute lookup table
7045 for (var z
= 0; z
< ALPHABET
.length
; z
++) {
7046 var x
= ALPHABET
.charAt(z
)
7048 if (ALPHABET_MAP
[x
] !== undefined) throw new TypeError(x
+ ' is ambiguous')
7052 function encode (source
) {
7053 if (source
.length
=== 0) return ''
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
7064 digits
.push(carry
% BASE
)
7065 carry
= (carry
/ BASE
) | 0
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
]]
7079 function decodeUnsafe (string
) {
7080 if (typeof string
!== 'string') throw new TypeError('Expected String')
7081 if (string
.length
=== 0) return Buffer
.allocUnsafe(0)
7084 for (var i
= 0; i
< string
.length
; i
++) {
7085 var value
= ALPHABET_MAP
[string
[i
]]
7086 if (value
=== undefined) return
7088 for (var j
= 0, carry
= value
; j
< bytes
.length
; ++j
) {
7089 carry
+= bytes
[j
] * BASE
7090 bytes
[j
] = carry
& 0xff
7095 bytes
.push(carry
& 0xff)
7100 // deal with leading zeros
7101 for (var k
= 0; string
[k
] === LEADER
&& k
< string
.length
- 1; ++k
) {
7105 return Buffer
.from(bytes
.reverse())
7108 function decode (string
) {
7109 var buffer
= decodeUnsafe(string
)
7110 if (buffer
) return buffer
7112 throw new Error('Non-base' + BASE
+ ' character')
7117 decodeUnsafe: decodeUnsafe
,
7122 },{"safe-buffer":247}],72:[function(require
,module
,exports
){
7125 exports
.byteLength
= byteLength
7126 exports
.toByteArray
= toByteArray
7127 exports
.fromByteArray
= fromByteArray
7131 var Arr
= typeof Uint8Array
!== 'undefined' ? Uint8Array : Array
7133 var code
= 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'
7134 for (var i
= 0, len
= code
.length
; i
< len
; ++i
) {
7136 revLookup
[code
.charCodeAt(i
)] = i
7139 revLookup
['-'.charCodeAt(0)] = 62
7140 revLookup
['_'.charCodeAt(0)] = 63
7142 function placeHoldersCount (b64
) {
7143 var len
= b64
.length
7145 throw new Error('Invalid string. Length must be a multiple of 4')
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
7156 function byteLength (b64
) {
7157 // base64 is 4/3 + up to two characters of the original data
7158 return (b64
.length
* 3 / 4) - placeHoldersCount(b64
)
7161 function toByteArray (b64
) {
7162 var i
, l
, tmp
, placeHolders
, arr
7163 var len
= b64
.length
7164 placeHolders
= placeHoldersCount(b64
)
7166 arr
= new Arr((len
* 3 / 4) - placeHolders
)
7168 // if there are placeholders, only get up to the last complete 4 chars
7169 l
= placeHolders
> 0 ? len
- 4 : len
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
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
7192 function tripletToBase64 (num
) {
7193 return lookup
[num
>> 18 & 0x3F] + lookup
[num
>> 12 & 0x3F] + lookup
[num
>> 6 & 0x3F] + lookup
[num
& 0x3F]
7196 function encodeChunk (uint8
, start
, end
) {
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
))
7203 return output
.join('')
7206 function fromByteArray (uint8
) {
7208 var len
= uint8
.length
7209 var extraBytes
= len
% 3 // if we have 1 byte left, pad 2 bytes
7212 var maxChunkLength
= 16383 // must be multiple of 3
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
)))
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]
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]
7235 return parts
.join('')
7238 },{}],73:[function(require
,module
,exports
){
7239 /*! bignumber.js v5.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */
7241 ;(function (globalObj
) {
7246 A JavaScript library for arbitrary-precision arithmetic.
7247 https://github.com/MikeMcl/bignumber.js
7248 Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com>
7254 isNumeric
= /^-?(\d+(\.\d*)?|\.\d+)(e[+-]?\d+)?$/i,
7255 mathceil
= Math
.ceil
,
7256 mathfloor
= Math
.floor
,
7257 notBool
= ' not a boolean or binary digit',
7258 roundingMode
= 'rounding mode',
7259 tooManyDigits
= 'number type has more than 15 significant digits',
7260 ALPHABET
= '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_',
7263 MAX_SAFE_INTEGER
= 0x1fffffffffffff, // 2^53 - 1
7264 // MAX_INT32 = 0x7fffffff, // 2^31 - 1
7265 POWS_TEN
= [1, 10, 100, 1e3
, 1e4
, 1e5
, 1e6
, 1e7
, 1e8
, 1e9
, 1e10
, 1e11
, 1e12
, 1e13
],
7269 * The limit on the value of DECIMAL_PLACES, TO_EXP_NEG, TO_EXP_POS, MIN_EXP, MAX_EXP, and
7270 * the arguments to toExponential, toFixed, toFormat, and toPrecision, beyond which an
7271 * exception is thrown (if ERRORS is true).
7273 MAX
= 1E9
; // 0 to MAX_INT32
7277 * Create and return a BigNumber constructor.
7279 function constructorFactory(config
) {
7280 var div
, parseNumeric
,
7282 // id tracks the caller function, so its name can be included in error messages.
7284 P
= BigNumber
.prototype,
7285 ONE
= new BigNumber(1),
7288 /********************************* EDITABLE DEFAULTS **********************************/
7292 * The default values below must be integers within the inclusive ranges stated.
7293 * The values can also be changed at run-time using BigNumber.config.
7296 // The maximum number of decimal places for operations involving division.
7297 DECIMAL_PLACES
= 20, // 0 to MAX
7300 * The rounding mode used when rounding to the above decimal places, and when using
7301 * toExponential, toFixed, toFormat and toPrecision, and round (default value).
7302 * UP 0 Away from zero.
7303 * DOWN 1 Towards zero.
7304 * CEIL 2 Towards +Infinity.
7305 * FLOOR 3 Towards -Infinity.
7306 * HALF_UP 4 Towards nearest neighbour. If equidistant, up.
7307 * HALF_DOWN 5 Towards nearest neighbour. If equidistant, down.
7308 * HALF_EVEN 6 Towards nearest neighbour. If equidistant, towards even neighbour.
7309 * HALF_CEIL 7 Towards nearest neighbour. If equidistant, towards +Infinity.
7310 * HALF_FLOOR 8 Towards nearest neighbour. If equidistant, towards -Infinity.
7312 ROUNDING_MODE
= 4, // 0 to 8
7314 // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS]
7316 // The exponent value at and beneath which toString returns exponential notation.
7318 TO_EXP_NEG
= -7, // 0 to -MAX
7320 // The exponent value at and above which toString returns exponential notation.
7322 TO_EXP_POS
= 21, // 0 to MAX
7324 // RANGE : [MIN_EXP, MAX_EXP]
7326 // The minimum exponent value, beneath which underflow to zero occurs.
7327 // Number type: -324 (5e-324)
7328 MIN_EXP
= -1e7
, // -1 to -MAX
7330 // The maximum exponent value, above which overflow to Infinity occurs.
7331 // Number type: 308 (1.7976931348623157e+308)
7332 // For MAX_EXP > 1e7, e.g. new BigNumber('1e100000000').plus(1) may be slow.
7333 MAX_EXP
= 1e7
, // 1 to MAX
7335 // Whether BigNumber Errors are ever thrown.
7336 ERRORS
= true, // true or false
7338 // Change to intValidatorNoErrors if ERRORS is false.
7339 isValidInt
= intValidatorWithErrors
, // intValidatorWithErrors/intValidatorNoErrors
7341 // Whether to use cryptographically-secure random number generation, if available.
7342 CRYPTO
= false, // true or false
7345 * The modulo mode used when calculating the modulus: a mod n.
7346 * The quotient (q = a / n) is calculated according to the corresponding rounding mode.
7347 * The remainder (r) is calculated as: r = a - n * q.
7349 * UP 0 The remainder is positive if the dividend is negative, else is negative.
7350 * DOWN 1 The remainder has the same sign as the dividend.
7351 * This modulo mode is commonly known as 'truncated division' and is
7352 * equivalent to (a % n) in JavaScript.
7353 * FLOOR 3 The remainder has the same sign as the divisor (Python %).
7354 * HALF_EVEN 6 This modulo mode implements the IEEE 754 remainder function.
7355 * EUCLID 9 Euclidian division. q = sign(n) * floor(a / abs(n)).
7356 * The remainder is always positive.
7358 * The truncated division, floored division, Euclidian division and IEEE 754 remainder
7359 * modes are commonly used for the modulus operation.
7360 * Although the other rounding modes can also be used, they may not give useful results.
7362 MODULO_MODE
= 1, // 0 to 9
7364 // The maximum number of significant digits of the result of the toPower operation.
7365 // If POW_PRECISION is 0, there will be unlimited significant digits.
7366 POW_PRECISION
= 0, // 0 to MAX
7368 // The format specification used by the BigNumber.prototype.toFormat method.
7370 decimalSeparator: '.',
7371 groupSeparator: ',',
7373 secondaryGroupSize: 0,
7374 fractionGroupSeparator: '\xA0', // non-breaking space
7375 fractionGroupSize: 0
7379 /******************************************************************************************/
7386 * The BigNumber constructor and exported function.
7387 * Create and return a new instance of a BigNumber object.
7389 * n {number|string|BigNumber} A numeric value.
7390 * [b] {number} The base of n. Integer, 2 to 64 inclusive.
7392 function BigNumber( n
, b
) {
7393 var c
, e
, i
, num
, len
, str
,
7396 // Enable constructor usage without new.
7397 if ( !( x
instanceof BigNumber
) ) {
7399 // 'BigNumber() constructor call without new: {n}'
7400 // See GitHub issue: #81.
7401 //if (ERRORS) raise( 26, 'constructor call without new', n );
7402 return new BigNumber( n
, b
);
7405 // 'new BigNumber() base not an integer: {b}'
7406 // 'new BigNumber() base out of range: {b}'
7407 if ( b
== null || !isValidInt( b
, 2, 64, id
, 'base' ) ) {
7410 if ( n
instanceof BigNumber
) {
7413 x
.c
= ( n
= n
.c
) ? n
.slice() : n
;
7418 if ( ( num
= typeof n
== 'number' ) && n
* 0 == 0 ) {
7419 x
.s
= 1 / n
< 0 ? ( n
= -n
, -1 ) : 1;
7421 // Fast path for integers.
7423 for ( e
= 0, i
= n
; i
>= 10; i
/= 10, e
++ );
7432 if ( !isNumeric
.test( str
= n
+ '' ) ) return parseNumeric( x
, str
, num
);
7433 x
.s
= str
.charCodeAt(0) === 45 ? ( str
= str
.slice(1), -1 ) : 1;
7439 // Ensure return value is rounded to DECIMAL_PLACES as with other bases.
7440 // Allow exponential notation to be used with base 10 argument.
7442 x
= new BigNumber( n
instanceof BigNumber
? n : str
);
7443 return round( x
, DECIMAL_PLACES
+ x
.e
+ 1, ROUNDING_MODE
);
7446 // Avoid potential interpretation of Infinity and NaN as base 44+ values.
7447 // Any number in exponential form will fail due to the [Ee][+-].
7448 if ( ( num
= typeof n
== 'number' ) && n
* 0 != 0 ||
7449 !( new RegExp( '^-?' + ( c
= '[' + ALPHABET
.slice( 0, b
) + ']+' ) +
7450 '(?:\\.' + c
+ ')?$',b
< 37 ? 'i' : '' ) ).test(str
) ) {
7451 return parseNumeric( x
, str
, num
, b
);
7455 x
.s
= 1 / n
< 0 ? ( str
= str
.slice(1), -1 ) : 1;
7457 if ( ERRORS
&& str
.replace( /^0\.0*|\./, '' ).length
> 15 ) {
7459 // 'new BigNumber() number type has more than 15 significant digits: {n}'
7460 raise( id
, tooManyDigits
, n
);
7463 // Prevent later check for length on converted number.
7466 x
.s
= str
.charCodeAt(0) === 45 ? ( str
= str
.slice(1), -1 ) : 1;
7469 str
= convertBase( str
, 10, b
, x
.s
);
7473 if ( ( e
= str
.indexOf('.') ) > -1 ) str
= str
.replace( '.', '' );
7475 // Exponential form?
7476 if ( ( i
= str
.search( /e
/i
) ) > 0 ) {
7478 // Determine exponent.
7480 e
+= +str
.slice( i
+ 1 );
7481 str
= str
.substring( 0, i
);
7482 } else if ( e
< 0 ) {
7488 // Determine leading zeros.
7489 for ( i
= 0; str
.charCodeAt(i
) === 48; i
++ );
7491 // Determine trailing zeros.
7492 for ( len
= str
.length
; str
.charCodeAt(--len
) === 48; );
7493 str
= str
.slice( i
, len
+ 1 );
7498 // Disallow numbers with over 15 significant digits if number type.
7499 // 'new BigNumber() number type has more than 15 significant digits: {n}'
7500 if ( num
&& ERRORS
&& len
> 15 && ( n
> MAX_SAFE_INTEGER
|| n
!== mathfloor(n
) ) ) {
7501 raise( id
, tooManyDigits
, x
.s
* n
);
7507 if ( e
> MAX_EXP
) {
7513 } else if ( e
< MIN_EXP
) {
7523 // e is the base 10 exponent.
7524 // i is where to slice str to get the first element of the coefficient array.
7525 i
= ( e
+ 1 ) % LOG_BASE
;
7526 if ( e
< 0 ) i
+= LOG_BASE
;
7529 if (i
) x
.c
.push( +str
.slice( 0, i
) );
7531 for ( len
-= LOG_BASE
; i
< len
; ) {
7532 x
.c
.push( +str
.slice( i
, i
+= LOG_BASE
) );
7536 i
= LOG_BASE
- str
.length
;
7541 for ( ; i
--; str
+= '0' );
7554 // CONSTRUCTOR PROPERTIES
7557 BigNumber
.another
= constructorFactory
;
7559 BigNumber
.ROUND_UP
= 0;
7560 BigNumber
.ROUND_DOWN
= 1;
7561 BigNumber
.ROUND_CEIL
= 2;
7562 BigNumber
.ROUND_FLOOR
= 3;
7563 BigNumber
.ROUND_HALF_UP
= 4;
7564 BigNumber
.ROUND_HALF_DOWN
= 5;
7565 BigNumber
.ROUND_HALF_EVEN
= 6;
7566 BigNumber
.ROUND_HALF_CEIL
= 7;
7567 BigNumber
.ROUND_HALF_FLOOR
= 8;
7568 BigNumber
.EUCLID
= 9;
7572 * Configure infrequently-changing library-wide settings.
7574 * Accept an object or an argument list, with one or many of the following properties or
7575 * parameters respectively:
7577 * DECIMAL_PLACES {number} Integer, 0 to MAX inclusive
7578 * ROUNDING_MODE {number} Integer, 0 to 8 inclusive
7579 * EXPONENTIAL_AT {number|number[]} Integer, -MAX to MAX inclusive or
7580 * [integer -MAX to 0 incl., 0 to MAX incl.]
7581 * RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
7582 * [integer -MAX to -1 incl., integer 1 to MAX incl.]
7583 * ERRORS {boolean|number} true, false, 1 or 0
7584 * CRYPTO {boolean|number} true, false, 1 or 0
7585 * MODULO_MODE {number} 0 to 9 inclusive
7586 * POW_PRECISION {number} 0 to MAX inclusive
7587 * FORMAT {object} See BigNumber.prototype.toFormat
7588 * decimalSeparator {string}
7589 * groupSeparator {string}
7590 * groupSize {number}
7591 * secondaryGroupSize {number}
7592 * fractionGroupSeparator {string}
7593 * fractionGroupSize {number}
7595 * (The values assigned to the above FORMAT object properties are not checked for validity.)
7598 * BigNumber.config(20, 4) is equivalent to
7599 * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 })
7601 * Ignore properties/parameters set to null or undefined.
7602 * Return an object with the properties current values.
7604 BigNumber
.config
= BigNumber
.set = function () {
7610 has
= o
&& typeof o
== 'object'
7611 ? function () { if ( o
.hasOwnProperty(p
) ) return ( v
= o
[p
] ) != null; }
7612 : function () { if ( a
.length
> i
) return ( v
= a
[i
++] ) != null; };
7614 // DECIMAL_PLACES {number} Integer, 0 to MAX inclusive.
7615 // 'config() DECIMAL_PLACES not an integer: {v}'
7616 // 'config() DECIMAL_PLACES out of range: {v}'
7617 if ( has( p
= 'DECIMAL_PLACES' ) && isValidInt( v
, 0, MAX
, 2, p
) ) {
7618 DECIMAL_PLACES
= v
| 0;
7620 r
[p
] = DECIMAL_PLACES
;
7622 // ROUNDING_MODE {number} Integer, 0 to 8 inclusive.
7623 // 'config() ROUNDING_MODE not an integer: {v}'
7624 // 'config() ROUNDING_MODE out of range: {v}'
7625 if ( has( p
= 'ROUNDING_MODE' ) && isValidInt( v
, 0, 8, 2, p
) ) {
7626 ROUNDING_MODE
= v
| 0;
7628 r
[p
] = ROUNDING_MODE
;
7630 // EXPONENTIAL_AT {number|number[]}
7631 // Integer, -MAX to MAX inclusive or [integer -MAX to 0 inclusive, 0 to MAX inclusive].
7632 // 'config() EXPONENTIAL_AT not an integer: {v}'
7633 // 'config() EXPONENTIAL_AT out of range: {v}'
7634 if ( has( p
= 'EXPONENTIAL_AT' ) ) {
7637 if ( isValidInt( v
[0], -MAX
, 0, 2, p
) && isValidInt( v
[1], 0, MAX
, 2, p
) ) {
7638 TO_EXP_NEG
= v
[0] | 0;
7639 TO_EXP_POS
= v
[1] | 0;
7641 } else if ( isValidInt( v
, -MAX
, MAX
, 2, p
) ) {
7642 TO_EXP_NEG
= -( TO_EXP_POS
= ( v
< 0 ? -v : v
) | 0 );
7645 r
[p
] = [ TO_EXP_NEG
, TO_EXP_POS
];
7647 // RANGE {number|number[]} Non-zero integer, -MAX to MAX inclusive or
7648 // [integer -MAX to -1 inclusive, integer 1 to MAX inclusive].
7649 // 'config() RANGE not an integer: {v}'
7650 // 'config() RANGE cannot be zero: {v}'
7651 // 'config() RANGE out of range: {v}'
7652 if ( has( p
= 'RANGE' ) ) {
7655 if ( isValidInt( v
[0], -MAX
, -1, 2, p
) && isValidInt( v
[1], 1, MAX
, 2, p
) ) {
7659 } else if ( isValidInt( v
, -MAX
, MAX
, 2, p
) ) {
7660 if ( v
| 0 ) MIN_EXP
= -( MAX_EXP
= ( v
< 0 ? -v : v
) | 0 );
7661 else if (ERRORS
) raise( 2, p
+ ' cannot be zero', v
);
7664 r
[p
] = [ MIN_EXP
, MAX_EXP
];
7666 // ERRORS {boolean|number} true, false, 1 or 0.
7667 // 'config() ERRORS not a boolean or binary digit: {v}'
7668 if ( has( p
= 'ERRORS' ) ) {
7670 if ( v
=== !!v
|| v
=== 1 || v
=== 0 ) {
7672 isValidInt
= ( ERRORS
= !!v
) ? intValidatorWithErrors : intValidatorNoErrors
;
7673 } else if (ERRORS
) {
7674 raise( 2, p
+ notBool
, v
);
7679 // CRYPTO {boolean|number} true, false, 1 or 0.
7680 // 'config() CRYPTO not a boolean or binary digit: {v}'
7681 // 'config() crypto unavailable: {crypto}'
7682 if ( has( p
= 'CRYPTO' ) ) {
7684 if ( v
=== true || v
=== false || v
=== 1 || v
=== 0 ) {
7686 v
= typeof crypto
== 'undefined';
7687 if ( !v
&& crypto
&& (crypto
.getRandomValues
|| crypto
.randomBytes
)) {
7689 } else if (ERRORS
) {
7690 raise( 2, 'crypto unavailable', v
? void 0 : crypto
);
7697 } else if (ERRORS
) {
7698 raise( 2, p
+ notBool
, v
);
7703 // MODULO_MODE {number} Integer, 0 to 9 inclusive.
7704 // 'config() MODULO_MODE not an integer: {v}'
7705 // 'config() MODULO_MODE out of range: {v}'
7706 if ( has( p
= 'MODULO_MODE' ) && isValidInt( v
, 0, 9, 2, p
) ) {
7707 MODULO_MODE
= v
| 0;
7711 // POW_PRECISION {number} Integer, 0 to MAX inclusive.
7712 // 'config() POW_PRECISION not an integer: {v}'
7713 // 'config() POW_PRECISION out of range: {v}'
7714 if ( has( p
= 'POW_PRECISION' ) && isValidInt( v
, 0, MAX
, 2, p
) ) {
7715 POW_PRECISION
= v
| 0;
7717 r
[p
] = POW_PRECISION
;
7720 // 'config() FORMAT not an object: {v}'
7721 if ( has( p
= 'FORMAT' ) ) {
7723 if ( typeof v
== 'object' ) {
7725 } else if (ERRORS
) {
7726 raise( 2, p
+ ' not an object', v
);
7736 * Return a new BigNumber whose value is the maximum of the arguments.
7738 * arguments {number|string|BigNumber}
7740 BigNumber
.max = function () { return maxOrMin( arguments
, P
.lt
); };
7744 * Return a new BigNumber whose value is the minimum of the arguments.
7746 * arguments {number|string|BigNumber}
7748 BigNumber
.min = function () { return maxOrMin( arguments
, P
.gt
); };
7752 * Return a new BigNumber with a random value equal to or greater than 0 and less than 1,
7753 * and with dp, or DECIMAL_PLACES if dp is omitted, decimal places (or less if trailing
7754 * zeros are produced).
7756 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
7758 * 'random() decimal places not an integer: {dp}'
7759 * 'random() decimal places out of range: {dp}'
7760 * 'random() crypto unavailable: {crypto}'
7762 BigNumber
.random
= (function () {
7763 var pow2_53
= 0x20000000000000;
7765 // Return a 53 bit integer n, where 0 <= n < 9007199254740992.
7766 // Check if Math.random() produces more than 32 bits of randomness.
7767 // If it does, assume at least 53 bits are produced, otherwise assume at least 30 bits.
7768 // 0x40000000 is 2^30, 0x800000 is 2^23, 0x1fffff is 2^21 - 1.
7769 var random53bitInt
= (Math
.random() * pow2_53
) & 0x1fffff
7770 ? function () { return mathfloor( Math
.random() * pow2_53
); }
7771 : function () { return ((Math
.random() * 0x40000000 | 0) * 0x800000) +
7772 (Math
.random() * 0x800000 | 0); };
7774 return function (dp
) {
7778 rand
= new BigNumber(ONE
);
7780 dp
= dp
== null || !isValidInt( dp
, 0, MAX
, 14 ) ? DECIMAL_PLACES : dp
| 0;
7781 k
= mathceil( dp
/ LOG_BASE
);
7785 // Browsers supporting crypto.getRandomValues.
7786 if (crypto
.getRandomValues
) {
7788 a
= crypto
.getRandomValues( new Uint32Array( k
*= 2 ) );
7793 // ((Math.pow(2, 32) - 1) * Math.pow(2, 21)).toString(2)
7794 // 11111 11111111 11111111 11111111 11100000 00000000 00000000
7795 // ((Math.pow(2, 32) - 1) >>> 11).toString(2)
7796 // 11111 11111111 11111111
7798 v
= a
[i
] * 0x20000 + (a
[i
+ 1] >>> 11);
7800 // Rejection sampling:
7801 // 0 <= v < 9007199254740992
7802 // Probability that v >= 9e15, is
7803 // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251
7805 b
= crypto
.getRandomValues( new Uint32Array(2) );
7810 // 0 <= v <= 8999999999999999
7811 // 0 <= (v % 1e14) <= 99999999999999
7818 // Node.js supporting crypto.randomBytes.
7819 } else if (crypto
.randomBytes
) {
7822 a
= crypto
.randomBytes( k
*= 7 );
7826 // 0x1000000000000 is 2^48, 0x10000000000 is 2^40
7827 // 0x100000000 is 2^32, 0x1000000 is 2^24
7828 // 11111 11111111 11111111 11111111 11111111 11111111 11111111
7829 // 0 <= v < 9007199254740992
7830 v
= ( ( a
[i
] & 31 ) * 0x1000000000000 ) + ( a
[i
+ 1] * 0x10000000000 ) +
7831 ( a
[i
+ 2] * 0x100000000 ) + ( a
[i
+ 3] * 0x1000000 ) +
7832 ( a
[i
+ 4] << 16 ) + ( a
[i
+ 5] << 8 ) + a
[i
+ 6];
7835 crypto
.randomBytes(7).copy( a
, i
);
7838 // 0 <= (v % 1e14) <= 99999999999999
7846 if (ERRORS
) raise( 14, 'crypto unavailable', crypto
);
7854 v
= random53bitInt();
7855 if ( v
< 9e15
) c
[i
++] = v
% 1e14
;
7862 // Convert trailing digits to zeros according to dp.
7864 v
= POWS_TEN
[LOG_BASE
- dp
];
7865 c
[i
] = mathfloor( k
/ v
) * v
;
7868 // Remove trailing elements which are zero.
7869 for ( ; c
[i
] === 0; c
.pop(), i
-- );
7876 // Remove leading elements which are zero and adjust exponent accordingly.
7877 for ( e
= -1 ; c
[0] === 0; c
.splice(0, 1), e
-= LOG_BASE
);
7879 // Count the digits of the first element of c to determine leading zeros, and...
7880 for ( i
= 1, v
= c
[0]; v
>= 10; v
/= 10, i
++);
7882 // adjust the exponent accordingly.
7883 if ( i
< LOG_BASE
) e
-= LOG_BASE
- i
;
7893 // PRIVATE FUNCTIONS
7896 // Convert a numeric string of baseIn to a numeric string of baseOut.
7897 function convertBase( str
, baseOut
, baseIn
, sign
) {
7898 var d
, e
, k
, r
, x
, xc
, y
,
7899 i
= str
.indexOf( '.' ),
7900 dp
= DECIMAL_PLACES
,
7903 if ( baseIn
< 37 ) str
= str
.toLowerCase();
7909 // Unlimited precision.
7911 str
= str
.replace( '.', '' );
7912 y
= new BigNumber(baseIn
);
7913 x
= y
.pow( str
.length
- i
);
7916 // Convert str as if an integer, then restore the fraction part by dividing the
7917 // result by its base raised to a power.
7918 y
.c
= toBaseOut( toFixedPoint( coeffToString( x
.c
), x
.e
), 10, baseOut
);
7922 // Convert the number as integer.
7923 xc
= toBaseOut( str
, baseIn
, baseOut
);
7926 // Remove trailing zeros.
7927 for ( ; xc
[--k
] == 0; xc
.pop() );
7928 if ( !xc
[0] ) return '0';
7936 // sign is needed for correct rounding.
7938 x
= div( x
, y
, dp
, rm
, baseOut
);
7946 // The rounding digit, i.e. the digit to the right of the digit that may be rounded up.
7949 r
= r
|| d
< 0 || xc
[d
+ 1] != null;
7951 r
= rm
< 4 ? ( i
!= null || r
) && ( rm
== 0 || rm
== ( x
.s
< 0 ? 3 : 2 ) )
7952 : i
> k
|| i
== k
&&( rm
== 4 || r
|| rm
== 6 && xc
[d
- 1] & 1 ||
7953 rm
== ( x
.s
< 0 ? 8 : 7 ) );
7955 if ( d
< 1 || !xc
[0] ) {
7958 str
= r
? toFixedPoint( '1', -dp
) : '0';
7964 // Rounding up may mean the previous digit has to be rounded up and so on.
7965 for ( --baseOut
; ++xc
[--d
] > baseOut
; ) {
7970 xc
= [1].concat(xc
);
7975 // Determine trailing zeros.
7976 for ( k
= xc
.length
; !xc
[--k
]; );
7978 // E.g. [4, 11, 15] becomes 4bf.
7979 for ( i
= 0, str
= ''; i
<= k
; str
+= ALPHABET
.charAt( xc
[i
++] ) );
7980 str
= toFixedPoint( str
, e
);
7983 // The caller will add the sign.
7988 // Perform division in the specified base. Called by div and convertBase.
7989 div
= (function () {
7991 // Assume non-zero x and k.
7992 function multiply( x
, k
, base
) {
7993 var m
, temp
, xlo
, xhi
,
7996 klo
= k
% SQRT_BASE
,
7997 khi
= k
/ SQRT_BASE
| 0;
7999 for ( x
= x
.slice(); i
--; ) {
8000 xlo
= x
[i
] % SQRT_BASE
;
8001 xhi
= x
[i
] / SQRT_BASE
| 0;
8002 m
= khi
* xlo
+ xhi
* klo
;
8003 temp
= klo
* xlo
+ ( ( m
% SQRT_BASE
) * SQRT_BASE
) + carry
;
8004 carry
= ( temp
/ base
| 0 ) + ( m
/ SQRT_BASE
| 0 ) + khi
* xhi
;
8008 if (carry
) x
= [carry
].concat(x
);
8013 function compare( a
, b
, aL
, bL
) {
8017 cmp
= aL
> bL
? 1 : -1;
8020 for ( i
= cmp
= 0; i
< aL
; i
++ ) {
8022 if ( a
[i
] != b
[i
] ) {
8023 cmp
= a
[i
] > b
[i
] ? 1 : -1;
8031 function subtract( a
, b
, aL
, base
) {
8034 // Subtract b from a.
8037 i
= a
[aL
] < b
[aL
] ? 1 : 0;
8038 a
[aL
] = i
* base
+ a
[aL
] - b
[aL
];
8041 // Remove leading zeros.
8042 for ( ; !a
[0] && a
.length
> 1; a
.splice(0, 1) );
8045 // x: dividend, y: divisor.
8046 return function ( x
, y
, dp
, rm
, base
) {
8047 var cmp
, e
, i
, more
, n
, prod
, prodL
, q
, qc
, rem
, remL
, rem0
, xi
, xL
, yc0
,
8049 s
= x
.s
== y
.s
? 1 : -1,
8053 // Either NaN, Infinity or 0?
8054 if ( !xc
|| !xc
[0] || !yc
|| !yc
[0] ) {
8056 return new BigNumber(
8058 // Return NaN if either NaN, or both Infinity or 0.
8059 !x
.s
|| !y
.s
|| ( xc
? yc
&& xc
[0] == yc
[0] : !yc
) ? NaN :
8061 // Return ±0 if x is ±0 or y is ±Infinity, or return ±Infinity as y is ±0.
8062 xc
&& xc
[0] == 0 || !yc
? s
* 0 : s
/ 0
8066 q
= new BigNumber(s
);
8073 e
= bitFloor( x
.e
/ LOG_BASE
) - bitFloor( y
.e
/ LOG_BASE
);
8074 s
= s
/ LOG_BASE
| 0;
8077 // Result exponent may be one less then the current value of e.
8078 // The coefficients of the BigNumbers from convertBase may have trailing zeros.
8079 for ( i
= 0; yc
[i
] == ( xc
[i
] || 0 ); i
++ );
8080 if ( yc
[i
] > ( xc
[i
] || 0 ) ) e
--;
8091 // Normalise xc and yc so highest order digit of yc is >= base / 2.
8093 n
= mathfloor( base
/ ( yc
[0] + 1 ) );
8095 // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1.
8096 // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) {
8098 yc
= multiply( yc
, n
, base
);
8099 xc
= multiply( xc
, n
, base
);
8105 rem
= xc
.slice( 0, yL
);
8108 // Add zeros to make remainder as long as divisor.
8109 for ( ; remL
< yL
; rem
[remL
++] = 0 );
8111 yz
= [0].concat(yz
);
8113 if ( yc
[1] >= base
/ 2 ) yc0
++;
8114 // Not necessary, but to prevent trial digit n > base, when using base 3.
8115 // else if ( base == 3 && yc0 == 1 ) yc0 = 1 + 1e-15;
8120 // Compare divisor and remainder.
8121 cmp
= compare( yc
, rem
, yL
, remL
);
8123 // If divisor < remainder.
8126 // Calculate trial digit, n.
8129 if ( yL
!= remL
) rem0
= rem0
* base
+ ( rem
[1] || 0 );
8131 // n is how many times the divisor goes into the current remainder.
8132 n
= mathfloor( rem0
/ yc0
);
8135 // 1. product = divisor * trial digit (n)
8136 // 2. if product > remainder: product -= divisor, n--
8137 // 3. remainder -= product
8138 // 4. if product was < remainder at 2:
8139 // 5. compare new remainder and divisor
8140 // 6. If remainder > divisor: remainder -= divisor, n++
8144 // n may be > base only when base is 3.
8145 if (n
>= base
) n
= base
- 1;
8147 // product = divisor * trial digit.
8148 prod
= multiply( yc
, n
, base
);
8149 prodL
= prod
.length
;
8152 // Compare product and remainder.
8153 // If product > remainder.
8154 // Trial digit n too high.
8155 // n is 1 too high about 5% of the time, and is not known to have
8156 // ever been more than 1 too high.
8157 while ( compare( prod
, rem
, prodL
, remL
) == 1 ) {
8160 // Subtract divisor from product.
8161 subtract( prod
, yL
< prodL
? yz : yc
, prodL
, base
);
8162 prodL
= prod
.length
;
8167 // n is 0 or 1, cmp is -1.
8168 // If n is 0, there is no need to compare yc and rem again below,
8169 // so change cmp to 1 to avoid it.
8170 // If n is 1, leave cmp as -1, so yc and rem are compared again.
8173 // divisor < remainder, so n must be at least 1.
8177 // product = divisor
8179 prodL
= prod
.length
;
8182 if ( prodL
< remL
) prod
= [0].concat(prod
);
8184 // Subtract product from remainder.
8185 subtract( rem
, prod
, remL
, base
);
8188 // If product was < remainder.
8191 // Compare divisor and new remainder.
8192 // If divisor < new remainder, subtract divisor from remainder.
8193 // Trial digit n too low.
8194 // n is 1 too low about 5% of the time, and very rarely 2 too low.
8195 while ( compare( yc
, rem
, yL
, remL
) < 1 ) {
8198 // Subtract divisor from remainder.
8199 subtract( rem
, yL
< remL
? yz : yc
, remL
, base
);
8203 } else if ( cmp
=== 0 ) {
8206 } // else cmp === 1 and n will be 0
8208 // Add the next digit, n, to the result array.
8211 // Update the remainder.
8213 rem
[remL
++] = xc
[xi
] || 0;
8218 } while ( ( xi
++ < xL
|| rem
[0] != null ) && s
-- );
8220 more
= rem
[0] != null;
8223 if ( !qc
[0] ) qc
.splice(0, 1);
8226 if ( base
== BASE
) {
8228 // To calculate q.e, first get the number of digits of qc[0].
8229 for ( i
= 1, s
= qc
[0]; s
>= 10; s
/= 10, i
++ );
8230 round( q
, dp
+ ( q
.e
= i
+ e
* LOG_BASE
- 1 ) + 1, rm
, more
);
8232 // Caller is convertBase.
8244 * Return a string representing the value of BigNumber n in fixed-point or exponential
8245 * notation rounded to the specified decimal places or significant digits.
8248 * i is the index of the last digit required (i.e. the digit that may be rounded up).
8249 * rm is the rounding mode.
8250 * caller is caller id: toExponential 19, toFixed 20, toFormat 21, toPrecision 24.
8252 function format( n
, i
, rm
, caller
) {
8253 var c0
, e
, ne
, len
, str
;
8255 rm
= rm
!= null && isValidInt( rm
, 0, 8, caller
, roundingMode
)
8256 ? rm
| 0 : ROUNDING_MODE
;
8258 if ( !n
.c
) return n
.toString();
8263 str
= coeffToString( n
.c
);
8264 str
= caller
== 19 || caller
== 24 && ne
<= TO_EXP_NEG
8265 ? toExponential( str
, ne
)
8266 : toFixedPoint( str
, ne
);
8268 n
= round( new BigNumber(n
), i
, rm
);
8270 // n.e may have changed if the value was rounded up.
8273 str
= coeffToString( n
.c
);
8276 // toPrecision returns exponential notation if the number of significant digits
8277 // specified is less than the number of digits necessary to represent the integer
8278 // part of the value in fixed-point notation.
8280 // Exponential notation.
8281 if ( caller
== 19 || caller
== 24 && ( i
<= e
|| e
<= TO_EXP_NEG
) ) {
8284 for ( ; len
< i
; str
+= '0', len
++ );
8285 str
= toExponential( str
, e
);
8287 // Fixed-point notation.
8290 str
= toFixedPoint( str
, e
);
8293 if ( e
+ 1 > len
) {
8294 if ( --i
> 0 ) for ( str
+= '.'; i
--; str
+= '0' );
8298 if ( e
+ 1 == len
) str
+= '.';
8299 for ( ; i
--; str
+= '0' );
8305 return n
.s
< 0 && c0
? '-' + str : str
;
8309 // Handle BigNumber.max and BigNumber.min.
8310 function maxOrMin( args
, method
) {
8314 if ( isArray( args
[0] ) ) args
= args
[0];
8315 m
= new BigNumber( args
[0] );
8317 for ( ; ++i
< args
.length
; ) {
8318 n
= new BigNumber( args
[i
] );
8320 // If any number is NaN, return NaN.
8324 } else if ( method
.call( m
, n
) ) {
8334 * Return true if n is an integer in range, otherwise throw.
8335 * Use for argument validation when ERRORS is true.
8337 function intValidatorWithErrors( n
, min
, max
, caller
, name
) {
8338 if ( n
< min
|| n
> max
|| n
!= truncate(n
) ) {
8339 raise( caller
, ( name
|| 'decimal places' ) +
8340 ( n
< min
|| n
> max
? ' out of range' : ' not an integer' ), n
);
8348 * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP.
8349 * Called by minus, plus and times.
8351 function normalise( n
, c
, e
) {
8355 // Remove trailing zeros.
8356 for ( ; !c
[--j
]; c
.pop() );
8358 // Calculate the base 10 exponent. First get the number of digits of c[0].
8359 for ( j
= c
[0]; j
>= 10; j
/= 10, i
++ );
8362 if ( ( e
= i
+ e
* LOG_BASE
- 1 ) > MAX_EXP
) {
8368 } else if ( e
< MIN_EXP
) {
8381 // Handle values that fail the validity test in BigNumber.
8382 parseNumeric
= (function () {
8383 var basePrefix
= /^(-?)0([xbo])(?=\w[\w.]*$)/i,
8384 dotAfter
= /^([^.]+)\.$/,
8385 dotBefore
= /^\.([^.]+)$/,
8386 isInfinityOrNaN
= /^-?(Infinity|NaN)$/,
8387 whitespaceOrPlus
= /^\s*\+(?=[\w.])|^\s+|\s+$/g;
8389 return function ( x
, str
, num
, b
) {
8391 s
= num
? str : str
.replace( whitespaceOrPlus
, '' );
8393 // No exception on ±Infinity or NaN.
8394 if ( isInfinityOrNaN
.test(s
) ) {
8395 x
.s
= isNaN(s
) ? null : s
< 0 ? -1 : 1;
8399 // basePrefix = /^(-?)0([xbo])(?=\w[\w.]*$)/i
8400 s
= s
.replace( basePrefix
, function ( m
, p1
, p2
) {
8401 base
= ( p2
= p2
.toLowerCase() ) == 'x' ? 16 : p2
== 'b' ? 2 : 8;
8402 return !b
|| b
== base
? p1 : m
;
8408 // E.g. '1.' to '1', '.1' to '0.1'
8409 s
= s
.replace( dotAfter
, '$1' ).replace( dotBefore
, '0.$1' );
8412 if ( str
!= s
) return new BigNumber( s
, base
);
8415 // 'new BigNumber() not a number: {n}'
8416 // 'new BigNumber() not a base {b} number: {n}'
8417 if (ERRORS
) raise( id
, 'not a' + ( b
? ' base ' + b : '' ) + ' number', str
);
8427 // Throw a BigNumber Error.
8428 function raise( caller
, msg
, val
) {
8429 var error
= new Error( [
8430 'new BigNumber', // 0
8449 'toExponential', // 19
8454 'toPrecision', // 24
8457 ][caller
] + '() ' + msg
+ ': ' + val
);
8459 error
.name
= 'BigNumber Error';
8466 * Round x to sd significant digits using rounding mode rm. Check for over/under-flow.
8467 * If r is truthy, it is known that there are more digits after the rounding digit.
8469 function round( x
, sd
, rm
, r
) {
8470 var d
, i
, j
, k
, n
, ni
, rd
,
8474 // if x is not Infinity or NaN...
8477 // rd is the rounding digit, i.e. the digit after the digit that may be rounded up.
8478 // n is a base 1e14 number, the value of the element of array x.c containing rd.
8479 // ni is the index of n within x.c.
8480 // d is the number of digits of n.
8481 // i is the index of rd within n including leading zeros.
8482 // j is the actual index of rd within n (if < 0, rd is a leading zero).
8485 // Get the number of digits of the first element of xc.
8486 for ( d
= 1, k
= xc
[0]; k
>= 10; k
/= 10, d
++ );
8489 // If the rounding digit is in the first element of xc...
8495 // Get the rounding digit at index j of n.
8496 rd
= n
/ pows10
[ d
- j
- 1 ] % 10 | 0;
8498 ni
= mathceil( ( i
+ 1 ) / LOG_BASE
);
8500 if ( ni
>= xc
.length
) {
8505 for ( ; xc
.length
<= ni
; xc
.push(0) );
8509 j
= i
- LOG_BASE
+ 1;
8516 // Get the number of digits of n.
8517 for ( d
= 1; k
>= 10; k
/= 10, d
++ );
8519 // Get the index of rd within n.
8522 // Get the index of rd within n, adjusted for leading zeros.
8523 // The number of leading zeros of n is given by LOG_BASE - d.
8524 j
= i
- LOG_BASE
+ d
;
8526 // Get the rounding digit at index j of n.
8527 rd
= j
< 0 ? 0 : n
/ pows10
[ d
- j
- 1 ] % 10 | 0;
8533 // Are there any non-zero digits after the rounding digit?
8534 // The expression n % pows10[ d - j - 1 ] returns all digits of n to the right
8535 // of the digit at j, e.g. if n is 908714 and j is 2, the expression gives 714.
8536 xc
[ni
+ 1] != null || ( j
< 0 ? n : n
% pows10
[ d
- j
- 1 ] );
8539 ? ( rd
|| r
) && ( rm
== 0 || rm
== ( x
.s
< 0 ? 3 : 2 ) )
8540 : rd
> 5 || rd
== 5 && ( rm
== 4 || r
|| rm
== 6 &&
8542 // Check whether the digit to the left of the rounding digit is odd.
8543 ( ( i
> 0 ? j
> 0 ? n
/ pows10
[ d
- j
] : 0 : xc
[ni
- 1] ) % 10 ) & 1 ||
8544 rm
== ( x
.s
< 0 ? 8 : 7 ) );
8546 if ( sd
< 1 || !xc
[0] ) {
8551 // Convert sd to decimal places.
8554 // 1, 0.1, 0.01, 0.001, 0.0001 etc.
8555 xc
[0] = pows10
[ ( LOG_BASE
- sd
% LOG_BASE
) % LOG_BASE
];
8566 // Remove excess digits.
8573 k
= pows10
[ LOG_BASE
- i
];
8575 // E.g. 56700 becomes 56000 if 7 is the rounding digit.
8576 // j > 0 means i > number of leading zeros of n.
8577 xc
[ni
] = j
> 0 ? mathfloor( n
/ pows10
[ d
- j
] % pows10
[j
] ) * k : 0;
8585 // If the digit to be rounded up is in the first element of xc...
8588 // i will be the length of xc[0] before k is added.
8589 for ( i
= 1, j
= xc
[0]; j
>= 10; j
/= 10, i
++ );
8591 for ( k
= 1; j
>= 10; j
/= 10, k
++ );
8593 // if i != k the length has increased.
8596 if ( xc
[0] == BASE
) xc
[0] = 1;
8602 if ( xc
[ni
] != BASE
) break;
8609 // Remove trailing zeros.
8610 for ( i
= xc
.length
; xc
[--i
] === 0; xc
.pop() );
8613 // Overflow? Infinity.
8614 if ( x
.e
> MAX_EXP
) {
8618 } else if ( x
.e
< MIN_EXP
) {
8627 // PROTOTYPE/INSTANCE METHODS
8631 * Return a new BigNumber whose value is the absolute value of this BigNumber.
8633 P
.absoluteValue
= P
.abs = function () {
8634 var x
= new BigNumber(this);
8635 if ( x
.s
< 0 ) x
.s
= 1;
8641 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
8642 * number in the direction of Infinity.
8644 P
.ceil = function () {
8645 return round( new BigNumber(this), this.e
+ 1, 2 );
8651 * 1 if the value of this BigNumber is greater than the value of BigNumber(y, b),
8652 * -1 if the value of this BigNumber is less than the value of BigNumber(y, b),
8653 * 0 if they have the same value,
8654 * or null if the value of either is NaN.
8656 P
.comparedTo
= P
.cmp = function ( y
, b
) {
8658 return compare( this, new BigNumber( y
, b
) );
8663 * Return the number of decimal places of the value of this BigNumber, or null if the value
8664 * of this BigNumber is ±Infinity or NaN.
8666 P
.decimalPlaces
= P
.dp = function () {
8670 if ( !c
) return null;
8671 n
= ( ( v
= c
.length
- 1 ) - bitFloor( this.e
/ LOG_BASE
) ) * LOG_BASE
;
8673 // Subtract the number of trailing zeros of the last number.
8674 if ( v
= c
[v
] ) for ( ; v
% 10 == 0; v
/= 10, n
-- );
8698 * Return a new BigNumber whose value is the value of this BigNumber divided by the value of
8699 * BigNumber(y, b), rounded according to DECIMAL_PLACES and ROUNDING_MODE.
8701 P
.dividedBy
= P
.div = function ( y
, b
) {
8703 return div( this, new BigNumber( y
, b
), DECIMAL_PLACES
, ROUNDING_MODE
);
8708 * Return a new BigNumber whose value is the integer part of dividing the value of this
8709 * BigNumber by the value of BigNumber(y, b).
8711 P
.dividedToIntegerBy
= P
.divToInt = function ( y
, b
) {
8713 return div( this, new BigNumber( y
, b
), 0, 1 );
8718 * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b),
8719 * otherwise returns false.
8721 P
.equals
= P
.eq = function ( y
, b
) {
8723 return compare( this, new BigNumber( y
, b
) ) === 0;
8728 * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole
8729 * number in the direction of -Infinity.
8731 P
.floor = function () {
8732 return round( new BigNumber(this), this.e
+ 1, 3 );
8737 * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b),
8738 * otherwise returns false.
8740 P
.greaterThan
= P
.gt = function ( y
, b
) {
8742 return compare( this, new BigNumber( y
, b
) ) > 0;
8747 * Return true if the value of this BigNumber is greater than or equal to the value of
8748 * BigNumber(y, b), otherwise returns false.
8750 P
.greaterThanOrEqualTo
= P
.gte = function ( y
, b
) {
8752 return ( b
= compare( this, new BigNumber( y
, b
) ) ) === 1 || b
=== 0;
8758 * Return true if the value of this BigNumber is a finite number, otherwise returns false.
8760 P
.isFinite = function () {
8766 * Return true if the value of this BigNumber is an integer, otherwise return false.
8768 P
.isInteger
= P
.isInt = function () {
8769 return !!this.c
&& bitFloor( this.e
/ LOG_BASE
) > this.c
.length
- 2;
8774 * Return true if the value of this BigNumber is NaN, otherwise returns false.
8776 P
.isNaN = function () {
8782 * Return true if the value of this BigNumber is negative, otherwise returns false.
8784 P
.isNegative
= P
.isNeg = function () {
8790 * Return true if the value of this BigNumber is 0 or -0, otherwise returns false.
8792 P
.isZero = function () {
8793 return !!this.c
&& this.c
[0] == 0;
8798 * Return true if the value of this BigNumber is less than the value of BigNumber(y, b),
8799 * otherwise returns false.
8801 P
.lessThan
= P
.lt = function ( y
, b
) {
8803 return compare( this, new BigNumber( y
, b
) ) < 0;
8808 * Return true if the value of this BigNumber is less than or equal to the value of
8809 * BigNumber(y, b), otherwise returns false.
8811 P
.lessThanOrEqualTo
= P
.lte = function ( y
, b
) {
8813 return ( b
= compare( this, new BigNumber( y
, b
) ) ) === -1 || b
=== 0;
8834 * Return a new BigNumber whose value is the value of this BigNumber minus the value of
8837 P
.minus
= P
.sub = function ( y
, b
) {
8843 y
= new BigNumber( y
, b
);
8847 if ( !a
|| !b
) return new BigNumber(NaN
);
8855 var xe
= x
.e
/ LOG_BASE
,
8856 ye
= y
.e
/ LOG_BASE
,
8863 if ( !xc
|| !yc
) return xc
? ( y
.s
= -b
, y
) : new BigNumber( yc
? x : NaN
);
8866 if ( !xc
[0] || !yc
[0] ) {
8868 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
8869 return yc
[0] ? ( y
.s
= -b
, y
) : new BigNumber( xc
[0] ? x :
8871 // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity
8872 ROUNDING_MODE
== 3 ? -0 : 0 );
8880 // Determine which is the bigger number.
8881 if ( a
= xe
- ye
) {
8883 if ( xLTy
= a
< 0 ) {
8893 // Prepend zeros to equalise exponents.
8894 for ( b
= a
; b
--; t
.push(0) );
8898 // Exponents equal. Check digit by digit.
8899 j
= ( xLTy
= ( a
= xc
.length
) < ( b
= yc
.length
) ) ? a : b
;
8901 for ( a
= b
= 0; b
< j
; b
++ ) {
8903 if ( xc
[b
] != yc
[b
] ) {
8904 xLTy
= xc
[b
] < yc
[b
];
8910 // x < y? Point xc to the array of the bigger number.
8911 if (xLTy
) t
= xc
, xc
= yc
, yc
= t
, y
.s
= -y
.s
;
8913 b
= ( j
= yc
.length
) - ( i
= xc
.length
);
8915 // Append zeros to xc if shorter.
8916 // No need to add zeros to yc if shorter as subtract only needs to start at yc.length.
8917 if ( b
> 0 ) for ( ; b
--; xc
[i
++] = 0 );
8920 // Subtract yc from xc.
8923 if ( xc
[--j
] < yc
[j
] ) {
8924 for ( i
= j
; i
&& !xc
[--i
]; xc
[i
] = b
);
8932 // Remove leading zeros and adjust exponent accordingly.
8933 for ( ; xc
[0] == 0; xc
.splice(0, 1), --ye
);
8938 // Following IEEE 754 (2008) 6.3,
8939 // n - n = +0 but n - n = -0 when rounding towards -Infinity.
8940 y
.s
= ROUNDING_MODE
== 3 ? -1 : 1;
8945 // No need to check for Infinity as +x - +y != Infinity && -x - -y != Infinity
8946 // for finite x and y.
8947 return normalise( y
, xc
, ye
);
8969 * Return a new BigNumber whose value is the value of this BigNumber modulo the value of
8970 * BigNumber(y, b). The result depends on the value of MODULO_MODE.
8972 P
.modulo
= P
.mod = function ( y
, b
) {
8977 y
= new BigNumber( y
, b
);
8979 // Return NaN if x is Infinity or NaN, or y is NaN or zero.
8980 if ( !x
.c
|| !y
.s
|| y
.c
&& !y
.c
[0] ) {
8981 return new BigNumber(NaN
);
8983 // Return x if y is Infinity or x is zero.
8984 } else if ( !y
.c
|| x
.c
&& !x
.c
[0] ) {
8985 return new BigNumber(x
);
8988 if ( MODULO_MODE
== 9 ) {
8990 // Euclidian division: q = sign(y) * floor(x / abs(y))
8991 // r = x - qy where 0 <= r < abs(y)
8994 q
= div( x
, y
, 0, 3 );
8998 q
= div( x
, y
, 0, MODULO_MODE
);
9001 return x
.minus( q
.times(y
) );
9006 * Return a new BigNumber whose value is the value of this BigNumber negated,
9007 * i.e. multiplied by -1.
9009 P
.negated
= P
.neg = function () {
9010 var x
= new BigNumber(this);
9033 * Return a new BigNumber whose value is the value of this BigNumber plus the value of
9036 P
.plus
= P
.add = function ( y
, b
) {
9042 y
= new BigNumber( y
, b
);
9046 if ( !a
|| !b
) return new BigNumber(NaN
);
9054 var xe
= x
.e
/ LOG_BASE
,
9055 ye
= y
.e
/ LOG_BASE
,
9061 // Return ±Infinity if either ±Infinity.
9062 if ( !xc
|| !yc
) return new BigNumber( a
/ 0 );
9065 // Return y if y is non-zero, x if x is non-zero, or zero if both are zero.
9066 if ( !xc
[0] || !yc
[0] ) return yc
[0] ? y : new BigNumber( xc
[0] ? x : a
* 0 );
9073 // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts.
9074 if ( a
= xe
- ye
) {
9084 for ( ; a
--; t
.push(0) );
9091 // Point xc to the longer array, and b to the shorter length.
9092 if ( a
- b
< 0 ) t
= yc
, yc
= xc
, xc
= t
, b
= a
;
9094 // Only start adding at yc.length - 1 as the further digits of xc can be ignored.
9096 a
= ( xc
[--b
] = xc
[b
] + yc
[b
] + a
) / BASE
| 0;
9097 xc
[b
] = BASE
=== xc
[b
] ? 0 : xc
[b
] % BASE
;
9101 xc
= [a
].concat(xc
);
9105 // No need to check for zero, as +x + +y != 0 && -x + -y != 0
9106 // ye = MAX_EXP + 1 possible
9107 return normalise( y
, xc
, ye
);
9112 * Return the number of significant digits of the value of this BigNumber.
9114 * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0.
9116 P
.precision
= P
.sd = function (z
) {
9121 // 'precision() argument not a boolean or binary digit: {z}'
9122 if ( z
!= null && z
!== !!z
&& z
!== 1 && z
!== 0 ) {
9123 if (ERRORS
) raise( 13, 'argument' + notBool
, z
);
9124 if ( z
!= !!z
) z
= null;
9127 if ( !c
) return null;
9129 n
= v
* LOG_BASE
+ 1;
9133 // Subtract the number of trailing zeros of the last element.
9134 for ( ; v
% 10 == 0; v
/= 10, n
-- );
9136 // Add the number of digits of the first element.
9137 for ( v
= c
[0]; v
>= 10; v
/= 10, n
++ );
9140 if ( z
&& x
.e
+ 1 > n
) n
= x
.e
+ 1;
9147 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
9148 * dp decimal places using rounding mode rm, or to 0 and ROUNDING_MODE respectively if
9151 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
9152 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9154 * 'round() decimal places out of range: {dp}'
9155 * 'round() decimal places not an integer: {dp}'
9156 * 'round() rounding mode not an integer: {rm}'
9157 * 'round() rounding mode out of range: {rm}'
9159 P
.round = function ( dp
, rm
) {
9160 var n
= new BigNumber(this);
9162 if ( dp
== null || isValidInt( dp
, 0, MAX
, 15 ) ) {
9163 round( n
, ~~dp
+ this.e
+ 1, rm
== null ||
9164 !isValidInt( rm
, 0, 8, 15, roundingMode
) ? ROUNDING_MODE : rm
| 0 );
9172 * Return a new BigNumber whose value is the value of this BigNumber shifted by k places
9173 * (powers of 10). Shift to the right if n > 0, and to the left if n < 0.
9175 * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
9177 * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity
9180 * 'shift() argument not an integer: {k}'
9181 * 'shift() argument out of range: {k}'
9183 P
.shift = function (k
) {
9185 return isValidInt( k
, -MAX_SAFE_INTEGER
, MAX_SAFE_INTEGER
, 16, 'argument' )
9187 // k < 1e+21, or truncate(k) will produce exponential notation.
9188 ? n
.times( '1e' + truncate(k
) )
9189 : new BigNumber( n
.c
&& n
.c
[0] && ( k
< -MAX_SAFE_INTEGER
|| k
> MAX_SAFE_INTEGER
)
9190 ? n
.s
* ( k
< 0 ? 0 : 1 / 0 )
9203 * Return a new BigNumber whose value is the square root of the value of this BigNumber,
9204 * rounded according to DECIMAL_PLACES and ROUNDING_MODE.
9206 P
.squareRoot
= P
.sqrt = function () {
9207 var m
, n
, r
, rep
, t
,
9212 dp
= DECIMAL_PLACES
+ 4,
9213 half
= new BigNumber('0.5');
9215 // Negative/NaN/Infinity/zero?
9216 if ( s
!== 1 || !c
|| !c
[0] ) {
9217 return new BigNumber( !s
|| s
< 0 && ( !c
|| c
[0] ) ? NaN : c
? x : 1 / 0 );
9220 // Initial estimate.
9221 s
= Math
.sqrt( +x
);
9223 // Math.sqrt underflow/overflow?
9224 // Pass x to Math.sqrt as integer, then adjust the exponent of the result.
9225 if ( s
== 0 || s
== 1 / 0 ) {
9226 n
= coeffToString(c
);
9227 if ( ( n
.length
+ e
) % 2 == 0 ) n
+= '0';
9229 e
= bitFloor( ( e
+ 1 ) / 2 ) - ( e
< 0 || e
% 2 );
9234 n
= s
.toExponential();
9235 n
= n
.slice( 0, n
.indexOf('e') + 1 ) + e
;
9238 r
= new BigNumber(n
);
9240 r
= new BigNumber( s
+ '' );
9244 // r could be zero if MIN_EXP is changed after the this value was created.
9245 // This would cause a division by zero (x/t) and hence Infinity below, which would cause
9246 // coeffToString to throw.
9252 // Newton-Raphson iteration.
9255 r
= half
.times( t
.plus( div( x
, t
, dp
, 1 ) ) );
9257 if ( coeffToString( t
.c
).slice( 0, s
) === ( n
=
9258 coeffToString( r
.c
) ).slice( 0, s
) ) {
9260 // The exponent of r may here be one less than the final result exponent,
9261 // e.g 0.0009999 (e-4) --> 0.001 (e-3), so adjust s so the rounding digits
9262 // are indexed correctly.
9264 n
= n
.slice( s
- 3, s
+ 1 );
9266 // The 4th rounding digit may be in error by -1 so if the 4 rounding digits
9267 // are 9999 or 4999 (i.e. approaching a rounding boundary) continue the
9269 if ( n
== '9999' || !rep
&& n
== '4999' ) {
9271 // On the first iteration only, check to see if rounding up gives the
9272 // exact result as the nines may infinitely repeat.
9274 round( t
, t
.e
+ DECIMAL_PLACES
+ 2, 0 );
9276 if ( t
.times(t
).eq(x
) ) {
9287 // If rounding digits are null, 0{0,4} or 50{0,3}, check for exact
9288 // result. If not, then there are further digits and m will be truthy.
9289 if ( !+n
|| !+n
.slice(1) && n
.charAt(0) == '5' ) {
9291 // Truncate to the first rounding digit.
9292 round( r
, r
.e
+ DECIMAL_PLACES
+ 2, 1 );
9293 m
= !r
.times(r
).eq(x
);
9302 return round( r
, r
.e
+ DECIMAL_PLACES
+ 1, ROUNDING_MODE
, m
);
9323 * Return a new BigNumber whose value is the value of this BigNumber times the value of
9326 P
.times
= P
.mul = function ( y
, b
) {
9327 var c
, e
, i
, j
, k
, m
, xcL
, xlo
, xhi
, ycL
, ylo
, yhi
, zc
,
9331 yc
= ( id
= 17, y
= new BigNumber( y
, b
) ).c
;
9333 // Either NaN, ±Infinity or ±0?
9334 if ( !xc
|| !yc
|| !xc
[0] || !yc
[0] ) {
9336 // Return NaN if either is NaN, or one is 0 and the other is Infinity.
9337 if ( !x
.s
|| !y
.s
|| xc
&& !xc
[0] && !yc
|| yc
&& !yc
[0] && !xc
) {
9338 y
.c
= y
.e
= y
.s
= null;
9342 // Return ±Infinity if either is ±Infinity.
9346 // Return ±0 if either is ±0.
9356 e
= bitFloor( x
.e
/ LOG_BASE
) + bitFloor( y
.e
/ LOG_BASE
);
9361 // Ensure xc points to longer array and xcL to its length.
9362 if ( xcL
< ycL
) zc
= xc
, xc
= yc
, yc
= zc
, i
= xcL
, xcL
= ycL
, ycL
= i
;
9364 // Initialise the result array with zeros.
9365 for ( i
= xcL
+ ycL
, zc
= []; i
--; zc
.push(0) );
9368 sqrtBase
= SQRT_BASE
;
9370 for ( i
= ycL
; --i
>= 0; ) {
9372 ylo
= yc
[i
] % sqrtBase
;
9373 yhi
= yc
[i
] / sqrtBase
| 0;
9375 for ( k
= xcL
, j
= i
+ k
; j
> i
; ) {
9376 xlo
= xc
[--k
] % sqrtBase
;
9377 xhi
= xc
[k
] / sqrtBase
| 0;
9378 m
= yhi
* xlo
+ xhi
* ylo
;
9379 xlo
= ylo
* xlo
+ ( ( m
% sqrtBase
) * sqrtBase
) + zc
[j
] + c
;
9380 c
= ( xlo
/ base
| 0 ) + ( m
/ sqrtBase
| 0 ) + yhi
* xhi
;
9381 zc
[j
--] = xlo
% base
;
9393 return normalise( y
, zc
, e
);
9398 * Return a new BigNumber whose value is the value of this BigNumber rounded to a maximum of
9399 * sd significant digits using rounding mode rm, or ROUNDING_MODE if rm is omitted.
9401 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
9402 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9404 * 'toDigits() precision out of range: {sd}'
9405 * 'toDigits() precision not an integer: {sd}'
9406 * 'toDigits() rounding mode not an integer: {rm}'
9407 * 'toDigits() rounding mode out of range: {rm}'
9409 P
.toDigits = function ( sd
, rm
) {
9410 var n
= new BigNumber(this);
9411 sd
= sd
== null || !isValidInt( sd
, 1, MAX
, 18, 'precision' ) ? null : sd
| 0;
9412 rm
= rm
== null || !isValidInt( rm
, 0, 8, 18, roundingMode
) ? ROUNDING_MODE : rm
| 0;
9413 return sd
? round( n
, sd
, rm
) : n
;
9418 * Return a string representing the value of this BigNumber in exponential notation and
9419 * rounded using ROUNDING_MODE to dp fixed decimal places.
9421 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
9422 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9424 * 'toExponential() decimal places not an integer: {dp}'
9425 * 'toExponential() decimal places out of range: {dp}'
9426 * 'toExponential() rounding mode not an integer: {rm}'
9427 * 'toExponential() rounding mode out of range: {rm}'
9429 P
.toExponential = function ( dp
, rm
) {
9430 return format( this,
9431 dp
!= null && isValidInt( dp
, 0, MAX
, 19 ) ? ~~dp
+ 1 : null, rm
, 19 );
9436 * Return a string representing the value of this BigNumber in fixed-point notation rounding
9437 * to dp fixed decimal places using rounding mode rm, or ROUNDING_MODE if rm is omitted.
9439 * Note: as with JavaScript's number type, (-0).toFixed(0) is '0',
9440 * but e.g. (-0.00001).toFixed(0) is '-0'.
9442 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
9443 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9445 * 'toFixed() decimal places not an integer: {dp}'
9446 * 'toFixed() decimal places out of range: {dp}'
9447 * 'toFixed() rounding mode not an integer: {rm}'
9448 * 'toFixed() rounding mode out of range: {rm}'
9450 P
.toFixed = function ( dp
, rm
) {
9451 return format( this, dp
!= null && isValidInt( dp
, 0, MAX
, 20 )
9452 ? ~~dp
+ this.e
+ 1 : null, rm
, 20 );
9457 * Return a string representing the value of this BigNumber in fixed-point notation rounded
9458 * using rm or ROUNDING_MODE to dp decimal places, and formatted according to the properties
9459 * of the FORMAT object (see BigNumber.config).
9462 * decimalSeparator : '.',
9463 * groupSeparator : ',',
9465 * secondaryGroupSize : 0,
9466 * fractionGroupSeparator : '\xA0', // non-breaking space
9467 * fractionGroupSize : 0
9470 * [dp] {number} Decimal places. Integer, 0 to MAX inclusive.
9471 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9473 * 'toFormat() decimal places not an integer: {dp}'
9474 * 'toFormat() decimal places out of range: {dp}'
9475 * 'toFormat() rounding mode not an integer: {rm}'
9476 * 'toFormat() rounding mode out of range: {rm}'
9478 P
.toFormat = function ( dp
, rm
) {
9479 var str
= format( this, dp
!= null && isValidInt( dp
, 0, MAX
, 21 )
9480 ? ~~dp
+ this.e
+ 1 : null, rm
, 21 );
9484 arr
= str
.split('.'),
9485 g1
= +FORMAT
.groupSize
,
9486 g2
= +FORMAT
.secondaryGroupSize
,
9487 groupSeparator
= FORMAT
.groupSeparator
,
9489 fractionPart
= arr
[1],
9491 intDigits
= isNeg
? intPart
.slice(1) : intPart
,
9492 len
= intDigits
.length
;
9494 if (g2
) i
= g1
, g1
= g2
, g2
= i
, len
-= i
;
9496 if ( g1
> 0 && len
> 0 ) {
9498 intPart
= intDigits
.substr( 0, i
);
9500 for ( ; i
< len
; i
+= g1
) {
9501 intPart
+= groupSeparator
+ intDigits
.substr( i
, g1
);
9504 if ( g2
> 0 ) intPart
+= groupSeparator
+ intDigits
.slice(i
);
9505 if (isNeg
) intPart
= '-' + intPart
;
9509 ? intPart
+ FORMAT
.decimalSeparator
+ ( ( g2
= +FORMAT
.fractionGroupSize
)
9510 ? fractionPart
.replace( new RegExp( '\\d{' + g2
+ '}\\B', 'g' ),
9511 '$&' + FORMAT
.fractionGroupSeparator
)
9521 * Return a string array representing the value of this BigNumber as a simple fraction with
9522 * an integer numerator and an integer denominator. The denominator will be a positive
9523 * non-zero value less than or equal to the specified maximum denominator. If a maximum
9524 * denominator is not specified, the denominator will be the lowest value necessary to
9525 * represent the number exactly.
9527 * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator.
9529 * 'toFraction() max denominator not an integer: {md}'
9530 * 'toFraction() max denominator out of range: {md}'
9532 P
.toFraction = function (md
) {
9533 var arr
, d0
, d2
, e
, exp
, n
, n0
, q
, s
,
9537 d
= new BigNumber(ONE
),
9538 n1
= d0
= new BigNumber(ONE
),
9539 d1
= n0
= new BigNumber(ONE
);
9543 n
= new BigNumber(md
);
9546 if ( !( k
= n
.isInt() ) || n
.lt(ONE
) ) {
9550 'max denominator ' + ( k
? 'out of range' : 'not an integer' ), md
);
9554 // If md is a finite non-integer >= 1, round it to an integer and use it.
9555 md
= !k
&& n
.c
&& round( n
, n
.e
+ 1, 1 ).gte(ONE
) ? n : null;
9559 if ( !xc
) return x
.toString();
9560 s
= coeffToString(xc
);
9562 // Determine initial denominator.
9563 // d is a power of 10 and the minimum max denominator that specifies the value exactly.
9564 e
= d
.e
= s
.length
- x
.e
- 1;
9565 d
.c
[0] = POWS_TEN
[ ( exp
= e
% LOG_BASE
) < 0 ? LOG_BASE
+ exp : exp
];
9566 md
= !md
|| n
.cmp(d
) > 0 ? ( e
> 0 ? d : n1
) : n
;
9570 n
= new BigNumber(s
);
9576 q
= div( n
, d
, 0, 1 );
9577 d2
= d0
.plus( q
.times(d1
) );
9578 if ( d2
.cmp(md
) == 1 ) break;
9581 n1
= n0
.plus( q
.times( d2
= n1
) );
9583 d
= n
.minus( q
.times( d2
= d
) );
9587 d2
= div( md
.minus(d0
), d1
, 0, 1 );
9588 n0
= n0
.plus( d2
.times(n1
) );
9589 d0
= d0
.plus( d2
.times(d1
) );
9593 // Determine which fraction is closer to x, n0/d0 or n1/d1
9594 arr
= div( n1
, d1
, e
, ROUNDING_MODE
).minus(x
).abs().cmp(
9595 div( n0
, d0
, e
, ROUNDING_MODE
).minus(x
).abs() ) < 1
9596 ? [ n1
.toString(), d1
.toString() ]
9597 : [ n0
.toString(), d0
.toString() ];
9605 * Return the value of this BigNumber converted to a number primitive.
9607 P
.toNumber = function () {
9613 * Return a BigNumber whose value is the value of this BigNumber raised to the power n.
9614 * If m is present, return the result modulo m.
9615 * If n is negative round according to DECIMAL_PLACES and ROUNDING_MODE.
9616 * If POW_PRECISION is non-zero and m is not present, round to POW_PRECISION using
9619 * The modular power operation works efficiently when x, n, and m are positive integers,
9620 * otherwise it is equivalent to calculating x.toPower(n).modulo(m) (with POW_PRECISION 0).
9622 * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive.
9623 * [m] {number|string|BigNumber} The modulus.
9625 * 'pow() exponent not an integer: {n}'
9626 * 'pow() exponent out of range: {n}'
9628 * Performs 54 loop iterations for n of 9007199254740991.
9630 P
.toPower
= P
.pow = function ( n
, m
) {
9632 i
= mathfloor( n
< 0 ? -n : +n
),
9637 m
= new BigNumber(m
);
9640 // Pass ±Infinity to Math.pow if exponent is out of range.
9641 if ( !isValidInt( n
, -MAX_SAFE_INTEGER
, MAX_SAFE_INTEGER
, 23, 'exponent' ) &&
9642 ( !isFinite(n
) || i
> MAX_SAFE_INTEGER
&& ( n
/= 0 ) ||
9643 parseFloat(n
) != n
&& !( n
= NaN
) ) || n
== 0 ) {
9644 k
= Math
.pow( +x
, n
);
9645 return new BigNumber( m
? k
% m : k
);
9649 if ( n
> 1 && x
.gt(ONE
) && x
.isInt() && m
.gt(ONE
) && m
.isInt() ) {
9654 // Nullify m so only a single mod operation is performed at the end.
9657 } else if (POW_PRECISION
) {
9659 // Truncating each coefficient array to a length of k after each multiplication
9660 // equates to truncating significant digits to POW_PRECISION + [28, 41],
9661 // i.e. there will be a minimum of 28 guard digits retained.
9662 // (Using + 1.5 would give [9, 21] guard digits.)
9663 k
= mathceil( POW_PRECISION
/ LOG_BASE
+ 2 );
9666 y
= new BigNumber(ONE
);
9673 if ( y
.c
.length
> k
) y
.c
.length
= k
;
9679 i
= mathfloor( i
/ 2 );
9683 if ( x
.c
&& x
.c
.length
> k
) x
.c
.length
= k
;
9690 if ( n
< 0 ) y
= ONE
.div(y
);
9692 return z
? y
.mod(z
) : k
? round( y
, POW_PRECISION
, ROUNDING_MODE
) : y
;
9697 * Return a string representing the value of this BigNumber rounded to sd significant digits
9698 * using rounding mode rm or ROUNDING_MODE. If sd is less than the number of digits
9699 * necessary to represent the integer part of the value in fixed-point notation, then use
9700 * exponential notation.
9702 * [sd] {number} Significant digits. Integer, 1 to MAX inclusive.
9703 * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive.
9705 * 'toPrecision() precision not an integer: {sd}'
9706 * 'toPrecision() precision out of range: {sd}'
9707 * 'toPrecision() rounding mode not an integer: {rm}'
9708 * 'toPrecision() rounding mode out of range: {rm}'
9710 P
.toPrecision = function ( sd
, rm
) {
9711 return format( this, sd
!= null && isValidInt( sd
, 1, MAX
, 24, 'precision' )
9712 ? sd
| 0 : null, rm
, 24 );
9717 * Return a string representing the value of this BigNumber in base b, or base 10 if b is
9718 * omitted. If a base is specified, including base 10, round according to DECIMAL_PLACES and
9719 * ROUNDING_MODE. If a base is not specified, and this BigNumber has a positive exponent
9720 * that is equal to or greater than TO_EXP_POS, or a negative exponent equal to or less than
9721 * TO_EXP_NEG, return exponential notation.
9723 * [b] {number} Integer, 2 to 64 inclusive.
9725 * 'toString() base not an integer: {b}'
9726 * 'toString() base out of range: {b}'
9728 P
.toString = function (b
) {
9739 if ( s
< 0 ) str
= '-' + str
;
9744 str
= coeffToString( n
.c
);
9746 if ( b
== null || !isValidInt( b
, 2, 64, 25, 'base' ) ) {
9747 str
= e
<= TO_EXP_NEG
|| e
>= TO_EXP_POS
9748 ? toExponential( str
, e
)
9749 : toFixedPoint( str
, e
);
9751 str
= convertBase( toFixedPoint( str
, e
), b
| 0, 10, s
);
9754 if ( s
< 0 && n
.c
[0] ) str
= '-' + str
;
9762 * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole
9765 P
.truncated
= P
.trunc = function () {
9766 return round( new BigNumber(this), this.e
+ 1, 1 );
9771 * Return as toString, but do not accept a base argument, and include the minus sign for
9774 P
.valueOf
= P
.toJSON = function () {
9779 if ( e
=== null ) return n
.toString();
9781 str
= coeffToString( n
.c
);
9783 str
= e
<= TO_EXP_NEG
|| e
>= TO_EXP_POS
9784 ? toExponential( str
, e
)
9785 : toFixedPoint( str
, e
);
9787 return n
.s
< 0 ? '-' + str : str
;
9791 P
.isBigNumber
= true;
9793 if ( config
!= null ) BigNumber
.config(config
);
9799 // PRIVATE HELPER FUNCTIONS
9802 function bitFloor(n
) {
9804 return n
> 0 || n
=== i
? i : i
- 1;
9808 // Return a coefficient array as a string of base 10 digits.
9809 function coeffToString(a
) {
9817 z
= LOG_BASE
- s
.length
;
9818 for ( ; z
--; s
= '0' + s
);
9822 // Determine trailing zeros.
9823 for ( j
= r
.length
; r
.charCodeAt(--j
) === 48; );
9824 return r
.slice( 0, j
+ 1 || 1 );
9828 // Compare the value of BigNumbers x and y.
9829 function compare( x
, y
) {
9839 if ( !i
|| !j
) return null;
9845 if ( a
|| b
) return a
? b
? 0 : -j : i
;
9848 if ( i
!= j
) return i
;
9854 if ( !xc
|| !yc
) return b
? 0 : !xc
^ a
? 1 : -1;
9856 // Compare exponents.
9857 if ( !b
) return k
> l
^ a
? 1 : -1;
9859 j
= ( k
= xc
.length
) < ( l
= yc
.length
) ? k : l
;
9861 // Compare digit by digit.
9862 for ( i
= 0; i
< j
; i
++ ) if ( xc
[i
] != yc
[i
] ) return xc
[i
] > yc
[i
] ^ a
? 1 : -1;
9865 return k
== l
? 0 : k
> l
^ a
? 1 : -1;
9870 * Return true if n is a valid number in range, otherwise false.
9871 * Use for argument validation when ERRORS is false.
9872 * Note: parseInt('1e+1') == 1 but parseFloat('1e+1') == 10.
9874 function intValidatorNoErrors( n
, min
, max
) {
9875 return ( n
= truncate(n
) ) >= min
&& n
<= max
;
9879 function isArray(obj
) {
9880 return Object
.prototype.toString
.call(obj
) == '[object Array]';
9885 * Convert string of baseIn to an array of numbers of baseOut.
9886 * Eg. convertBase('255', 10, 16) returns [15, 15].
9887 * Eg. convertBase('ff', 16, 10) returns [2, 5, 5].
9889 function toBaseOut( str
, baseIn
, baseOut
) {
9896 for ( ; i
< len
; ) {
9897 for ( arrL
= arr
.length
; arrL
--; arr
[arrL
] *= baseIn
);
9898 arr
[ j
= 0 ] += ALPHABET
.indexOf( str
.charAt( i
++ ) );
9900 for ( ; j
< arr
.length
; j
++ ) {
9902 if ( arr
[j
] > baseOut
- 1 ) {
9903 if ( arr
[j
+ 1] == null ) arr
[j
+ 1] = 0;
9904 arr
[j
+ 1] += arr
[j
] / baseOut
| 0;
9910 return arr
.reverse();
9914 function toExponential( str
, e
) {
9915 return ( str
.length
> 1 ? str
.charAt(0) + '.' + str
.slice(1) : str
) +
9916 ( e
< 0 ? 'e' : 'e+' ) + e
;
9920 function toFixedPoint( str
, e
) {
9923 // Negative exponent?
9927 for ( z
= '0.'; ++e
; z
+= '0' );
9930 // Positive exponent
9936 for ( z
= '0', e
-= len
; --e
; z
+= '0' );
9938 } else if ( e
< len
) {
9939 str
= str
.slice( 0, e
) + '.' + str
.slice(e
);
9947 function truncate(n
) {
9949 return n
< 0 ? mathceil(n
) : mathfloor(n
);
9956 BigNumber
= constructorFactory();
9957 BigNumber
['default'] = BigNumber
.BigNumber
= BigNumber
;
9961 if ( typeof define
== 'function' && define
.amd
) {
9962 define( function () { return BigNumber
; } );
9964 // Node.js and other environments that support module.exports.
9965 } else if ( typeof module
!= 'undefined' && module
.exports
) {
9966 module
.exports
= BigNumber
;
9970 if ( !globalObj
) globalObj
= typeof self
!= 'undefined' ? self : Function('return this')();
9971 globalObj
.BigNumber
= BigNumber
;
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
9980 var Buffer
= require('safe-buffer').Buffer
9982 function 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
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
9994 var lenS
= buffer
[5 + lenR
]
9995 if (lenS
=== 0) return false
9996 if ((6 + lenR
+ lenS
) !== buffer
.length
) return false
9998 if (buffer
[4] & 0x80) return false
9999 if (lenR
> 1 && (buffer
[4] === 0x00) && !(buffer
[5] & 0x80)) return false
10001 if (buffer
[lenR
+ 6] & 0x80) return false
10002 if (lenS
> 1 && (buffer
[lenR
+ 6] === 0x00) && !(buffer
[lenR
+ 7] & 0x80)) return false
10006 function 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')
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)')
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')
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')
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')
10028 // non-BIP66 - extract R, S values
10030 r: buffer
.slice(4, 4 + lenR
),
10031 s: buffer
.slice(6 + lenR
)
10036 * Expects r and s to be positive DER integers.
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.
10054 * 62300 => 0x00f35c
10055 * -62300 => 0xff0ca4
10057 function 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')
10069 var signature
= Buffer
.allocUnsafe(6 + lenR
+ lenS
)
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
)
10090 },{"safe-buffer":247}],75:[function(require
,module
,exports
){
10091 (function (module
, exports
) {
10095 function assert (val
, msg
) {
10096 if (!val
) throw new Error(msg
|| 'Assertion failed');
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
;
10111 function BN (number
, base
, endian
) {
10112 if (BN
.isBN(number
)) {
10120 // Reduction context
10123 if (number
!== null) {
10124 if (base
=== 'le' || base
=== 'be') {
10129 this._init(number
|| 0, base
|| 10, endian
|| 'be');
10132 if (typeof module
=== 'object') {
10133 module
.exports
= BN
;
10143 Buffer
= require('buffer').Buffer
;
10147 BN
.isBN
= function isBN (num
) {
10148 if (num
instanceof BN
) {
10152 return num
!== null && typeof num
=== 'object' &&
10153 num
.constructor.wordSize
=== BN
.wordSize
&& Array
.isArray(num
.words
);
10156 BN
.max
= function max (left
, right
) {
10157 if (left
.cmp(right
) > 0) return left
;
10161 BN
.min
= function min (left
, right
) {
10162 if (left
.cmp(right
) < 0) return left
;
10166 BN
.prototype._init
= function init (number
, base
, endian
) {
10167 if (typeof number
=== 'number') {
10168 return this._initNumber(number
, base
, endian
);
10171 if (typeof number
=== 'object') {
10172 return this._initArray(number
, base
, endian
);
10175 if (base
=== 'hex') {
10178 assert(base
=== (base
| 0) && base
>= 2 && base
<= 36);
10180 number
= number
.toString().replace(/\s+/g, '');
10182 if (number
[0] === '-') {
10187 this._parseHex(number
, start
);
10189 this._parseBase(number
, base
, start
);
10192 if (number
[0] === '-') {
10198 if (endian
!== 'le') return;
10200 this._initArray(this.toArray(), base
, endian
);
10203 BN
.prototype._initNumber
= function _initNumber (number
, base
, endian
) {
10208 if (number
< 0x4000000) {
10209 this.words
= [ number
& 0x3ffffff ];
10211 } else if (number
< 0x10000000000000) {
10213 number
& 0x3ffffff,
10214 (number
/ 0x4000000) & 0x3ffffff
10218 assert(number
< 0x20000000000000); // 2 ^ 53 (unsafe)
10220 number
& 0x3ffffff,
10221 (number
/ 0x4000000) & 0x3ffffff,
10227 if (endian
!== 'le') return;
10229 // Reverse the bytes
10230 this._initArray(this.toArray(), base
, endian
);
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 ];
10242 this.length
= Math
.ceil(number
.length
/ 3);
10243 this.words
= new Array(this.length
);
10244 for (var i
= 0; i
< this.length
; i
++) {
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;
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;
10273 return this.strip();
10276 function parseHex (str
, start
, end
) {
10278 var len
= Math
.min(str
.length
, end
);
10279 for (var i
= start
; i
< len
; i
++) {
10280 var c
= str
.charCodeAt(i
) - 48;
10285 if (c
>= 49 && c
<= 54) {
10289 } else if (c
>= 17 && c
<= 22) {
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
++) {
10309 // Scan 24-bit chunks and add them to the number
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;
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;
10330 function parseBase (str
, start
, end
, mul
) {
10332 var len
= Math
.min(str
.length
, end
);
10333 for (var i
= start
; i
< len
; i
++) {
10334 var c
= str
.charCodeAt(i
) - 48;
10343 } else if (c
>= 17) {
10354 BN
.prototype._parseBase
= function _parseBase (number
, base
, start
) {
10355 // Initialize as zero
10356 this.words
= [ 0 ];
10359 // Find length of limb in base
10360 for (var limbLen
= 0, limbPow
= 1; limbPow
<= 0x3ffffff; limbPow
*= base
) {
10364 limbPow
= (limbPow
/ base
) | 0;
10366 var total
= number
.length
- start
;
10367 var mod
= total
% limbLen
;
10368 var end
= Math
.min(total
, total
- mod
) + start
;
10371 for (var i
= start
; i
< end
; i
+= limbLen
) {
10372 word
= parseBase(number
, i
, i
+ limbLen
, base
);
10374 this.imuln(limbPow
);
10375 if (this.words
[0] + word
< 0x4000000) {
10376 this.words
[0] += word
;
10384 word
= parseBase(number
, i
, number
.length
, base
);
10386 for (i
= 0; i
< mod
; i
++) {
10391 if (this.words
[0] + word
< 0x4000000) {
10392 this.words
[0] += word
;
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
];
10404 dest
.length
= this.length
;
10405 dest
.negative
= this.negative
;
10406 dest
.red
= this.red
;
10409 BN
.prototype.clone
= function clone () {
10410 var r
= new BN(null);
10415 BN
.prototype._expand
= function _expand (size
) {
10416 while (this.length
< size
) {
10417 this.words
[this.length
++] = 0;
10422 // Remove leading `0` from `this`
10423 BN
.prototype.strip
= function strip () {
10424 while (this.length
> 1 && this.words
[this.length
- 1] === 0) {
10427 return this._normSign();
10430 BN
.prototype._normSign
= function _normSign () {
10432 if (this.length
=== 1 && this.words
[0] === 0) {
10438 BN
.prototype.inspect
= function inspect () {
10439 return (this.red
? '<BN-R: ' : '<BN: ') + this.toString(16) + '>';
10445 var groupSizes = [];
10446 var groupBases = [];
10450 while (++i < BN.wordSize) {
10459 while (++base < 36 + 1) {
10462 while (groupBase < (1 << BN.wordSize) / base) {
10466 groupSizes[base] = groupSize;
10467 groupBases[base] = groupBase;
10489 '0000000000000000',
10490 '00000000000000000',
10491 '000000000000000000',
10492 '0000000000000000000',
10493 '00000000000000000000',
10494 '000000000000000000000',
10495 '0000000000000000000000',
10496 '00000000000000000000000',
10497 '000000000000000000000000',
10498 '0000000000000000000000000'
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
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
10519 BN
.prototype.toString
= function toString (base
, padding
) {
10521 padding
= padding
| 0 || 1;
10524 if (base
=== 16 || base
=== 'hex') {
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
;
10544 out
= carry
.toString(16) + out
;
10546 while (out
.length
% padding
!== 0) {
10549 if (this.negative
!== 0) {
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
];
10561 var c
= this.clone();
10563 while (!c
.isZero()) {
10564 var r
= c
.modn(groupBase
).toString(base
);
10565 c
= c
.idivn(groupBase
);
10568 out
= zeros
[groupSize
- r
.length
] + r
+ out
;
10573 if (this.isZero()) {
10576 while (out
.length
% padding
!== 0) {
10579 if (this.negative
!== 0) {
10585 assert(false, 'Base should be between 2 and 36');
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');
10598 return (this.negative
!== 0) ? -ret : ret
;
10601 BN
.prototype.toJSON
= function toJSON () {
10602 return this.toString(16);
10605 BN
.prototype.toBuffer
= function toBuffer (endian
, length
) {
10606 assert(typeof Buffer
!== 'undefined');
10607 return this.toArrayLike(Buffer
, endian
, length
);
10610 BN
.prototype.toArray
= function toArray (endian
, length
) {
10611 return this.toArrayLike(Array
, endian
, length
);
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');
10621 var littleEndian
= endian
=== 'le';
10622 var res
= new ArrayType(reqLength
);
10625 var q
= this.clone();
10626 if (!littleEndian
) {
10627 // Assume big-endian
10628 for (i
= 0; i
< reqLength
- byteLength
; i
++) {
10632 for (i
= 0; !q
.isZero(); i
++) {
10636 res
[reqLength
- i
- 1] = b
;
10639 for (i
= 0; !q
.isZero(); i
++) {
10646 for (; i
< reqLength
; i
++) {
10655 BN
.prototype._countBits
= function _countBits (w
) {
10656 return 32 - Math
.clz32(w
);
10659 BN
.prototype._countBits
= function _countBits (w
) {
10682 BN
.prototype._zeroBits
= function _zeroBits (w
) {
10684 if (w
=== 0) return 26;
10688 if ((t
& 0x1fff) === 0) {
10692 if ((t
& 0x7f) === 0) {
10696 if ((t
& 0xf) === 0) {
10700 if ((t
& 0x3) === 0) {
10704 if ((t
& 0x1) === 0) {
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
;
10717 function toBitArray (num
) {
10718 var w
= new Array(num
.bitLength());
10720 for (var bit
= 0; bit
< w
.length
; bit
++) {
10721 var off
= (bit
/ 26) | 0;
10722 var wbit
= bit
% 26;
10724 w
[bit
] = (num
.words
[off
] & (1 << wbit
)) >>> wbit
;
10730 // Number of trailing zero bits
10731 BN
.prototype.zeroBits
= function zeroBits () {
10732 if (this.isZero()) return 0;
10735 for (var i
= 0; i
< this.length
; i
++) {
10736 var b
= this._zeroBits(this.words
[i
]);
10738 if (b
!== 26) break;
10743 BN
.prototype.byteLength
= function byteLength () {
10744 return Math
.ceil(this.bitLength() / 8);
10747 BN
.prototype.toTwos
= function toTwos (width
) {
10748 if (this.negative
!== 0) {
10749 return this.abs().inotn(width
).iaddn(1);
10751 return this.clone();
10754 BN
.prototype.fromTwos
= function fromTwos (width
) {
10755 if (this.testn(width
- 1)) {
10756 return this.notn(width
).iaddn(1).ineg();
10758 return this.clone();
10761 BN
.prototype.isNeg
= function isNeg () {
10762 return this.negative
!== 0;
10765 // Return negative clone of `this`
10766 BN
.prototype.neg
= function neg () {
10767 return this.clone().ineg();
10770 BN
.prototype.ineg
= function ineg () {
10771 if (!this.isZero()) {
10772 this.negative
^= 1;
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;
10784 for (var i
= 0; i
< num
.length
; i
++) {
10785 this.words
[i
] = this.words
[i
] | num
.words
[i
];
10788 return this.strip();
10791 BN
.prototype.ior
= function ior (num
) {
10792 assert((this.negative
| num
.negative
) === 0);
10793 return this.iuor(num
);
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);
10802 BN
.prototype.uor
= function uor (num
) {
10803 if (this.length
> num
.length
) return this.clone().iuor(num
);
10804 return num
.clone().iuor(this);
10807 // And `num` with `this` in-place
10808 BN
.prototype.iuand
= function iuand (num
) {
10809 // b = min-length(num, this)
10811 if (this.length
> num
.length
) {
10817 for (var i
= 0; i
< b
.length
; i
++) {
10818 this.words
[i
] = this.words
[i
] & num
.words
[i
];
10821 this.length
= b
.length
;
10823 return this.strip();
10826 BN
.prototype.iand
= function iand (num
) {
10827 assert((this.negative
| num
.negative
) === 0);
10828 return this.iuand(num
);
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);
10837 BN
.prototype.uand
= function uand (num
) {
10838 if (this.length
> num
.length
) return this.clone().iuand(num
);
10839 return num
.clone().iuand(this);
10842 // Xor `num` with `this` in-place
10843 BN
.prototype.iuxor
= function iuxor (num
) {
10844 // a.length > b.length
10847 if (this.length
> num
.length
) {
10855 for (var i
= 0; i
< b
.length
; i
++) {
10856 this.words
[i
] = a
.words
[i
] ^ b
.words
[i
];
10860 for (; i
< a
.length
; i
++) {
10861 this.words
[i
] = a
.words
[i
];
10865 this.length
= a
.length
;
10867 return this.strip();
10870 BN
.prototype.ixor
= function ixor (num
) {
10871 assert((this.negative
| num
.negative
) === 0);
10872 return this.iuxor(num
);
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);
10881 BN
.prototype.uxor
= function uxor (num
) {
10882 if (this.length
> num
.length
) return this.clone().iuxor(num
);
10883 return num
.clone().iuxor(this);
10886 // Not ``this`` with ``width`` bitwidth
10887 BN
.prototype.inotn
= function inotn (width
) {
10888 assert(typeof width
=== 'number' && width
>= 0);
10890 var bytesNeeded
= Math
.ceil(width
/ 26) | 0;
10891 var bitsLeft
= width
% 26;
10893 // Extend the buffer with leading zeroes
10894 this._expand(bytesNeeded
);
10896 if (bitsLeft
> 0) {
10900 // Handle complete words
10901 for (var i
= 0; i
< bytesNeeded
; i
++) {
10902 this.words
[i
] = ~this.words
[i
] & 0x3ffffff;
10905 // Handle the residue
10906 if (bitsLeft
> 0) {
10907 this.words
[i
] = ~this.words
[i
] & (0x3ffffff >> (26 - bitsLeft
));
10910 // And remove leading zeroes
10911 return this.strip();
10914 BN
.prototype.notn
= function notn (width
) {
10915 return this.clone().inotn(width
);
10918 // Set `bit` of `this`
10919 BN
.prototype.setn
= function setn (bit
, val
) {
10920 assert(typeof bit
=== 'number' && bit
>= 0);
10922 var off
= (bit
/ 26) | 0;
10923 var wbit
= bit
% 26;
10925 this._expand(off
+ 1);
10928 this.words
[off
] = this.words
[off
] | (1 << wbit
);
10930 this.words
[off
] = this.words
[off
] & ~(1 << wbit
);
10933 return this.strip();
10936 // Add `num` to `this` in-place
10937 BN
.prototype.iadd
= function iadd (num
) {
10940 // negative + positive
10941 if (this.negative
!== 0 && num
.negative
=== 0) {
10943 r
= this.isub(num
);
10944 this.negative
^= 1;
10945 return this._normSign();
10947 // positive + negative
10948 } else if (this.negative
=== 0 && num
.negative
!== 0) {
10950 r
= this.isub(num
);
10952 return r
._normSign();
10955 // a.length > b.length
10957 if (this.length
> num
.length
) {
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;
10971 for (; carry
!== 0 && i
< a
.length
; i
++) {
10972 r
= (a
.words
[i
] | 0) + carry
;
10973 this.words
[i
] = r
& 0x3ffffff;
10977 this.length
= a
.length
;
10979 this.words
[this.length
] = carry
;
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
];
10991 // Add `num` to `this`
10992 BN
.prototype.add
= function add (num
) {
10994 if (num
.negative
!== 0 && this.negative
=== 0) {
10996 res
= this.sub(num
);
10999 } else if (num
.negative
=== 0 && this.negative
!== 0) {
11001 res
= num
.sub(this);
11006 if (this.length
> num
.length
) return this.clone().iadd(num
);
11008 return num
.clone().iadd(this);
11011 // Subtract `num` from `this` in-place
11012 BN
.prototype.isub
= function isub (num
) {
11013 // this - (-num) = this + num
11014 if (num
.negative
!== 0) {
11016 var r
= this.iadd(num
);
11018 return r
._normSign();
11020 // -this - num = -(this + num)
11021 } else if (this.negative
!== 0) {
11025 return this._normSign();
11028 // At this point both numbers are positive
11029 var cmp
= this.cmp(num
);
11031 // Optimization - zeroify
11050 for (var i
= 0; i
< b
.length
; i
++) {
11051 r
= (a
.words
[i
] | 0) - (b
.words
[i
] | 0) + carry
;
11053 this.words
[i
] = r
& 0x3ffffff;
11055 for (; carry
!== 0 && i
< a
.length
; i
++) {
11056 r
= (a
.words
[i
] | 0) + carry
;
11058 this.words
[i
] = r
& 0x3ffffff;
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
];
11068 this.length
= Math
.max(this.length
, i
);
11074 return this.strip();
11077 // Subtract `num` from `this`
11078 BN
.prototype.sub
= function sub (num
) {
11079 return this.clone().isub(num
);
11082 function smallMulTo (self
, num
, out
) {
11083 out
.negative
= num
.negative
^ self
.negative
;
11084 var len
= (self
.length
+ num
.length
) | 0;
11086 len
= (len
- 1) | 0;
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;
11093 var lo
= r
& 0x3ffffff;
11094 var carry
= (r
/ 0x4000000) | 0;
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;
11108 ncarry
+= (r
/ 0x4000000) | 0;
11109 rword
= r
& 0x3ffffff;
11111 out
.words
[k
] = rword
| 0;
11112 carry
= ncarry
| 0;
11115 out
.words
[k
] = carry
| 0;
11120 return out
.strip();
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
;
11135 var al0
= a0
& 0x1fff;
11136 var ah0
= a0
>>> 13;
11138 var al1
= a1
& 0x1fff;
11139 var ah1
= a1
>>> 13;
11141 var al2
= a2
& 0x1fff;
11142 var ah2
= a2
>>> 13;
11144 var al3
= a3
& 0x1fff;
11145 var ah3
= a3
>>> 13;
11147 var al4
= a4
& 0x1fff;
11148 var ah4
= a4
>>> 13;
11150 var al5
= a5
& 0x1fff;
11151 var ah5
= a5
>>> 13;
11153 var al6
= a6
& 0x1fff;
11154 var ah6
= a6
>>> 13;
11156 var al7
= a7
& 0x1fff;
11157 var ah7
= a7
>>> 13;
11159 var al8
= a8
& 0x1fff;
11160 var ah8
= a8
>>> 13;
11162 var al9
= a9
& 0x1fff;
11163 var ah9
= a9
>>> 13;
11165 var bl0
= b0
& 0x1fff;
11166 var bh0
= b0
>>> 13;
11168 var bl1
= b1
& 0x1fff;
11169 var bh1
= b1
>>> 13;
11171 var bl2
= b2
& 0x1fff;
11172 var bh2
= b2
>>> 13;
11174 var bl3
= b3
& 0x1fff;
11175 var bh3
= b3
>>> 13;
11177 var bl4
= b4
& 0x1fff;
11178 var bh4
= b4
>>> 13;
11180 var bl5
= b5
& 0x1fff;
11181 var bh5
= b5
>>> 13;
11183 var bl6
= b6
& 0x1fff;
11184 var bh6
= b6
>>> 13;
11186 var bl7
= b7
& 0x1fff;
11187 var bh7
= b7
>>> 13;
11189 var bl8
= b8
& 0x1fff;
11190 var bh8
= b8
>>> 13;
11192 var bl9
= b9
& 0x1fff;
11193 var bh9
= b9
>>> 13;
11195 out
.negative
= self
.negative
^ num
.negative
;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
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;
11701 comb10MulTo
= smallMulTo
;
11704 function bigMulTo (self
, num
, out
) {
11705 out
.negative
= num
.negative
^ self
.negative
;
11706 out
.length
= self
.length
+ num
.length
;
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
;
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
++) {
11719 var a
= self
.words
[i
] | 0;
11720 var b
= num
.words
[j
] | 0;
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;
11729 hncarry
+= ncarry
>>> 26;
11730 ncarry
&= 0x3ffffff;
11732 out
.words
[k
] = rword
;
11737 out
.words
[k
] = carry
;
11742 return out
.strip();
11745 function jumboMulTo (self
, num
, out
) {
11746 var fftm
= new FFTM();
11747 return fftm
.mulp(self
, num
, out
);
11750 BN
.prototype.mulTo
= function mulTo (num
, out
) {
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
);
11760 res
= jumboMulTo(this, num
, out
);
11766 // Cooley-Tukey algorithm for FFT
11767 // slightly revisited to rely on looping instead of recursion
11769 function FFTM (x
, y
) {
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
);
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
;
11789 for (var i
= 0; i
< l
; i
++) {
11790 rb
|= (x
& 1) << (l
- i
- 1);
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
]];
11806 FFTM
.prototype.transform
= function transform (rws
, iws
, rtws
, itws
, N
, rbt
) {
11807 this.permute(rbt
, rws
, iws
, rtws
, itws
, N
);
11809 for (var s
= 1; s
< N
; s
<<= 1) {
11812 var rtwdf
= Math
.cos(2 * Math
.PI
/ l
);
11813 var itwdf
= Math
.sin(2 * Math
.PI
/ l
);
11815 for (var p
= 0; p
< N
; p
+= l
) {
11816 var rtwdf_
= rtwdf
;
11817 var itwdf_
= itwdf
;
11819 for (var j
= 0; j
< s
; j
++) {
11820 var re
= rtws
[p
+ j
];
11821 var ie
= itws
[p
+ j
];
11823 var ro
= rtws
[p
+ j
+ s
];
11824 var io
= itws
[p
+ j
+ s
];
11826 var rx
= rtwdf_
* ro
- itwdf_
* io
;
11828 io
= rtwdf_
* io
+ itwdf_
* ro
;
11831 rtws
[p
+ j
] = re
+ ro
;
11832 itws
[p
+ j
] = ie
+ io
;
11834 rtws
[p
+ j
+ s
] = re
- ro
;
11835 itws
[p
+ j
+ s
] = ie
- io
;
11837 /* jshint maxdepth : false */
11839 rx
= rtwdf
* rtwdf_
- itwdf
* itwdf_
;
11841 itwdf_
= rtwdf
* itwdf_
+ itwdf
* rtwdf_
;
11849 FFTM
.prototype.guessLen13b
= function guessLen13b (n
, m
) {
11850 var N
= Math
.max(m
, n
) | 1;
11853 for (N
= N
/ 2 | 0; N
; N
= N
>>> 1) {
11857 return 1 << i
+ 1 + odd
;
11860 FFTM
.prototype.conjugate
= function conjugate (rws
, iws
, N
) {
11861 if (N
<= 1) return;
11863 for (var i
= 0; i
< N
/ 2; i
++) {
11866 rws
[i
] = rws
[N
- i
- 1];
11867 rws
[N
- i
- 1] = t
;
11871 iws
[i
] = -iws
[N
- i
- 1];
11872 iws
[N
- i
- 1] = -t
;
11876 FFTM
.prototype.normalize13b
= function normalize13b (ws
, N
) {
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
) +
11883 ws
[i
] = w
& 0x3ffffff;
11885 if (w
< 0x4000000) {
11888 carry
= w
/ 0x4000000 | 0;
11895 FFTM
.prototype.convert13b
= function convert13b (ws
, len
, rws
, N
) {
11897 for (var i
= 0; i
< len
; i
++) {
11898 carry
= carry
+ (ws
[i
] | 0);
11900 rws
[2 * i
] = carry
& 0x1fff; carry
= carry
>>> 13;
11901 rws
[2 * i
+ 1] = carry
& 0x1fff; carry
= carry
>>> 13;
11905 for (i
= 2 * len
; i
< N
; ++i
) {
11909 assert(carry
=== 0);
11910 assert((carry
& ~0x1fff) === 0);
11913 FFTM
.prototype.stub
= function stub (N
) {
11914 var ph
= new Array(N
);
11915 for (var i
= 0; i
< N
; i
++) {
11922 FFTM
.prototype.mulp
= function mulp (x
, y
, out
) {
11923 var N
= 2 * this.guessLen13b(x
.length
, y
.length
);
11925 var rbt
= this.makeRBT(N
);
11927 var _
= this.stub(N
);
11929 var rws
= new Array(N
);
11930 var rwst
= new Array(N
);
11931 var iwst
= new Array(N
);
11933 var nrws
= new Array(N
);
11934 var nrwst
= new Array(N
);
11935 var niwst
= new Array(N
);
11937 var rmws
= out
.words
;
11940 this.convert13b(x
.words
, x
.length
, rws
, N
);
11941 this.convert13b(y
.words
, y
.length
, nrws
, N
);
11943 this.transform(rws
, _
, rwst
, iwst
, N
, rbt
);
11944 this.transform(nrws
, _
, nrwst
, niwst
, N
, rbt
);
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
];
11952 this.conjugate(rwst
, iwst
, N
);
11953 this.transform(rwst
, iwst
, rmws
, _
, N
, rbt
);
11954 this.conjugate(rmws
, _
, N
);
11955 this.normalize13b(rmws
, N
);
11957 out
.negative
= x
.negative
^ y
.negative
;
11958 out
.length
= x
.length
+ y
.length
;
11959 return out
.strip();
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
);
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
);
11976 // In-place Multiplication
11977 BN
.prototype.imul
= function imul (num
) {
11978 return this.clone().mulTo(num
, this);
11981 BN
.prototype.imuln
= function imuln (num
) {
11982 assert(typeof num
=== 'number');
11983 assert(num
< 0x4000000);
11987 for (var i
= 0; i
< this.length
; i
++) {
11988 var w
= (this.words
[i
] | 0) * num
;
11989 var lo
= (w
& 0x3ffffff) + (carry
& 0x3ffffff);
11991 carry
+= (w
/ 0x4000000) | 0;
11992 // NOTE: lo is 27bit maximum
11993 carry
+= lo
>>> 26;
11994 this.words
[i
] = lo
& 0x3ffffff;
11998 this.words
[i
] = carry
;
12005 BN
.prototype.muln
= function muln (num
) {
12006 return this.clone().imuln(num
);
12010 BN
.prototype.sqr
= function sqr () {
12011 return this.mul(this);
12014 // `this` * `this` in-place
12015 BN
.prototype.isqr
= function isqr () {
12016 return this.imul(this.clone());
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);
12024 // Skip leading zeroes
12026 for (var i
= 0; i
< w
.length
; i
++, res
= res
.sqr()) {
12027 if (w
[i
] !== 0) break;
12030 if (++i
< w
.length
) {
12031 for (var q
= res
.sqr(); i
< w
.length
; i
++, q
= q
.sqr()) {
12032 if (w
[i
] === 0) continue;
12041 // Shift-left in-place
12042 BN
.prototype.iushln
= function iushln (bits
) {
12043 assert(typeof bits
=== 'number' && bits
>= 0);
12045 var s
= (bits
- r
) / 26;
12046 var carryMask
= (0x3ffffff >>> (26 - r
)) << (26 - r
);
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
);
12060 this.words
[i
] = carry
;
12066 for (i
= this.length
- 1; i
>= 0; i
--) {
12067 this.words
[i
+ s
] = this.words
[i
];
12070 for (i
= 0; i
< s
; i
++) {
12077 return this.strip();
12080 BN
.prototype.ishln
= function ishln (bits
) {
12081 // TODO(indutny): implement me
12082 assert(this.negative
=== 0);
12083 return this.iushln(bits
);
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);
12093 h
= (hint
- (hint
% 26)) / 26;
12099 var s
= Math
.min((bits
- r
) / 26, this.length
);
12100 var mask
= 0x3ffffff ^ ((0x3ffffff >>> r
) << r
);
12101 var maskedWords
= extended
;
12104 h
= Math
.max(0, h
);
12106 // Extended mode, copy masked part
12108 for (var i
= 0; i
< s
; i
++) {
12109 maskedWords
.words
[i
] = this.words
[i
];
12111 maskedWords
.length
= s
;
12115 // No-op, we should not move anything at all
12116 } else if (this.length
> s
) {
12118 for (i
= 0; i
< this.length
; i
++) {
12119 this.words
[i
] = this.words
[i
+ s
];
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
;
12133 // Push carried bits as a mask
12134 if (maskedWords
&& carry
!== 0) {
12135 maskedWords
.words
[maskedWords
.length
++] = carry
;
12138 if (this.length
=== 0) {
12143 return this.strip();
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
);
12153 BN
.prototype.shln
= function shln (bits
) {
12154 return this.clone().ishln(bits
);
12157 BN
.prototype.ushln
= function ushln (bits
) {
12158 return this.clone().iushln(bits
);
12162 BN
.prototype.shrn
= function shrn (bits
) {
12163 return this.clone().ishrn(bits
);
12166 BN
.prototype.ushrn
= function ushrn (bits
) {
12167 return this.clone().iushrn(bits
);
12170 // Test if n bit is set
12171 BN
.prototype.testn
= function testn (bit
) {
12172 assert(typeof bit
=== 'number' && bit
>= 0);
12174 var s
= (bit
- r
) / 26;
12177 // Fast case: bit is much higher than all existing words
12178 if (this.length
<= s
) return false;
12180 // Check bit and return
12181 var w
= this.words
[s
];
12186 // Return only lowers bits of number (in-place)
12187 BN
.prototype.imaskn
= function imaskn (bits
) {
12188 assert(typeof bits
=== 'number' && bits
>= 0);
12190 var s
= (bits
- r
) / 26;
12192 assert(this.negative
=== 0, 'imaskn works only with positive numbers');
12194 if (this.length
<= s
) {
12201 this.length
= Math
.min(s
, this.length
);
12204 var mask
= 0x3ffffff ^ ((0x3ffffff >>> r
) << r
);
12205 this.words
[this.length
- 1] &= mask
;
12208 return this.strip();
12211 // Return only lowers bits of number
12212 BN
.prototype.maskn
= function maskn (bits
) {
12213 return this.clone().imaskn(bits
);
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
);
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);
12236 // Add without checks
12237 return this._iaddn(num
);
12240 BN
.prototype._iaddn
= function _iaddn (num
) {
12241 this.words
[0] += num
;
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;
12249 this.words
[i
+ 1]++;
12252 this.length
= Math
.max(this.length
, i
+ 1);
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
);
12263 if (this.negative
!== 0) {
12270 this.words
[0] -= num
;
12272 if (this.length
=== 1 && this.words
[0] < 0) {
12273 this.words
[0] = -this.words
[0];
12277 for (var i
= 0; i
< this.length
&& this.words
[i
] < 0; i
++) {
12278 this.words
[i
] += 0x4000000;
12279 this.words
[i
+ 1] -= 1;
12283 return this.strip();
12286 BN
.prototype.addn
= function addn (num
) {
12287 return this.clone().iaddn(num
);
12290 BN
.prototype.subn
= function subn (num
) {
12291 return this.clone().isubn(num
);
12294 BN
.prototype.iabs
= function iabs () {
12300 BN
.prototype.abs
= function abs () {
12301 return this.clone().iabs();
12304 BN
.prototype._ishlnsubmul
= function _ishlnsubmul (num
, mul
, shift
) {
12305 var len
= num
.length
+ shift
;
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;
12319 for (; i
< this.length
- shift
; i
++) {
12320 w
= (this.words
[i
+ shift
] | 0) + carry
;
12322 this.words
[i
+ shift
] = w
& 0x3ffffff;
12325 if (carry
=== 0) return this.strip();
12327 // Subtraction overflow
12328 assert(carry
=== -1);
12330 for (i
= 0; i
< this.length
; i
++) {
12331 w
= -(this.words
[i
] | 0) + carry
;
12333 this.words
[i
] = w
& 0x3ffffff;
12337 return this.strip();
12340 BN
.prototype._wordDiv
= function _wordDiv (num
, mode
) {
12341 var shift
= this.length
- num
.length
;
12343 var a
= this.clone();
12347 var bhi
= b
.words
[b
.length
- 1] | 0;
12348 var bhiBits
= this._countBits(bhi
);
12349 shift
= 26 - bhiBits
;
12351 b
= b
.ushln(shift
);
12353 bhi
= b
.words
[b
.length
- 1] | 0;
12356 // Initialize quotient
12357 var m
= a
.length
- b
.length
;
12360 if (mode
!== 'mod') {
12363 q
.words
= new Array(q
.length
);
12364 for (var i
= 0; i
< q
.length
; i
++) {
12369 var diff
= a
.clone()._ishlnsubmul(b
, 1, m
);
12370 if (diff
.negative
=== 0) {
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);
12381 // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max
12383 qj
= Math
.min((qj
/ bhi
) | 0, 0x3ffffff);
12385 a
._ishlnsubmul(b
, qj
, j
);
12386 while (a
.negative
!== 0) {
12389 a
._ishlnsubmul(b
, 1, j
);
12404 if (mode
!== 'div' && shift
!== 0) {
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());
12421 if (this.isZero()) {
12429 if (this.negative
!== 0 && num
.negative
=== 0) {
12430 res
= this.neg().divmod(num
, mode
);
12432 if (mode
!== 'mod') {
12433 div
= res
.div
.neg();
12436 if (mode
!== 'div') {
12437 mod
= res
.mod
.neg();
12438 if (positive
&& mod
.negative
!== 0) {
12449 if (this.negative
=== 0 && num
.negative
!== 0) {
12450 res
= this.divmod(num
.neg(), mode
);
12452 if (mode
!== 'mod') {
12453 div
= res
.div
.neg();
12462 if ((this.negative
& num
.negative
) !== 0) {
12463 res
= this.neg().divmod(num
.neg(), mode
);
12465 if (mode
!== 'div') {
12466 mod
= res
.mod
.neg();
12467 if (positive
&& mod
.negative
!== 0) {
12478 // Both numbers are positive at this point
12480 // Strip both numbers to approximate shift value
12481 if (num
.length
> this.length
|| this.cmp(num
) < 0) {
12488 // Very short reduction
12489 if (num
.length
=== 1) {
12490 if (mode
=== 'div') {
12492 div: this.divn(num
.words
[0]),
12497 if (mode
=== 'mod') {
12500 mod: new BN(this.modn(num
.words
[0]))
12505 div: this.divn(num
.words
[0]),
12506 mod: new BN(this.modn(num
.words
[0]))
12510 return this._wordDiv(num
, mode
);
12513 // Find `this` / `num`
12514 BN
.prototype.div
= function div (num
) {
12515 return this.divmod(num
, 'div', false).div
;
12518 // Find `this` % `num`
12519 BN
.prototype.mod
= function mod (num
) {
12520 return this.divmod(num
, 'mod', false).mod
;
12523 BN
.prototype.umod
= function umod (num
) {
12524 return this.divmod(num
, 'mod', true).mod
;
12527 // Find Round(`this` / `num`)
12528 BN
.prototype.divRound
= function divRound (num
) {
12529 var dm
= this.divmod(num
);
12531 // Fast case - exact division
12532 if (dm
.mod
.isZero()) return dm
.div
;
12534 var mod
= dm
.div
.negative
!== 0 ? dm
.mod
.isub(num
) : dm
.mod
;
12536 var half
= num
.ushrn(1);
12537 var r2
= num
.andln(1);
12538 var cmp
= mod
.cmp(half
);
12541 if (cmp
< 0 || r2
=== 1 && cmp
=== 0) return dm
.div
;
12544 return dm
.div
.negative
!== 0 ? dm
.div
.isubn(1) : dm
.div
.iaddn(1);
12547 BN
.prototype.modn
= function modn (num
) {
12548 assert(num
<= 0x3ffffff);
12549 var p
= (1 << 26) % num
;
12552 for (var i
= this.length
- 1; i
>= 0; i
--) {
12553 acc
= (p
* acc
+ (this.words
[i
] | 0)) % num
;
12559 // In-place division by number
12560 BN
.prototype.idivn
= function idivn (num
) {
12561 assert(num
<= 0x3ffffff);
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;
12570 return this.strip();
12573 BN
.prototype.divn
= function divn (num
) {
12574 return this.clone().idivn(num
);
12577 BN
.prototype.egcd
= function egcd (p
) {
12578 assert(p
.negative
=== 0);
12579 assert(!p
.isZero());
12584 if (x
.negative
!== 0) {
12590 // A * x + B * y = x
12594 // C * x + D * y = y
12600 while (x
.isEven() && y
.isEven()) {
12606 var yp
= y
.clone();
12607 var xp
= x
.clone();
12609 while (!x
.isZero()) {
12610 for (var i
= 0, im
= 1; (x
.words
[0] & im
) === 0 && i
< 26; ++i
, im
<<= 1);
12614 if (A
.isOdd() || B
.isOdd()) {
12624 for (var j
= 0, jm
= 1; (y
.words
[0] & jm
) === 0 && j
< 26; ++j
, jm
<<= 1);
12628 if (C
.isOdd() || D
.isOdd()) {
12638 if (x
.cmp(y
) >= 0) {
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());
12666 if (a
.negative
!== 0) {
12672 var x1
= new BN(1);
12673 var x2
= new BN(0);
12675 var delta
= b
.clone();
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);
12690 for (var j
= 0, jm
= 1; (b
.words
[0] & jm
) === 0 && j
< 26; ++j
, jm
<<= 1);
12702 if (a
.cmp(b
) >= 0) {
12712 if (a
.cmpn(1) === 0) {
12718 if (res
.cmpn(0) < 0) {
12725 BN
.prototype.gcd
= function gcd (num
) {
12726 if (this.isZero()) return num
.abs();
12727 if (num
.isZero()) return this.abs();
12729 var a
= this.clone();
12730 var b
= num
.clone();
12734 // Remove common factor of two
12735 for (var shift
= 0; a
.isEven() && b
.isEven(); shift
++) {
12741 while (a
.isEven()) {
12744 while (b
.isEven()) {
12750 // Swap `a` and `b` to make `a` always bigger than `b`
12754 } else if (r
=== 0 || b
.cmpn(1) === 0) {
12761 return b
.iushln(shift
);
12764 // Invert number in the field F(num)
12765 BN
.prototype.invm
= function invm (num
) {
12766 return this.egcd(num
).a
.umod(num
);
12769 BN
.prototype.isEven
= function isEven () {
12770 return (this.words
[0] & 1) === 0;
12773 BN
.prototype.isOdd
= function isOdd () {
12774 return (this.words
[0] & 1) === 1;
12777 // And first word and num
12778 BN
.prototype.andln
= function andln (num
) {
12779 return this.words
[0] & num
;
12782 // Increment at the bit position in-line
12783 BN
.prototype.bincn
= function bincn (bit
) {
12784 assert(typeof bit
=== 'number');
12786 var s
= (bit
- r
) / 26;
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
;
12796 // Add bit and propagate, if needed
12798 for (var i
= s
; carry
!== 0 && i
< this.length
; i
++) {
12799 var w
= this.words
[i
] | 0;
12806 this.words
[i
] = carry
;
12812 BN
.prototype.isZero
= function isZero () {
12813 return this.length
=== 1 && this.words
[0] === 0;
12816 BN
.prototype.cmpn
= function cmpn (num
) {
12817 var negative
= num
< 0;
12819 if (this.negative
!== 0 && !negative
) return -1;
12820 if (this.negative
=== 0 && negative
) return 1;
12825 if (this.length
> 1) {
12832 assert(num
<= 0x3ffffff, 'Number is too big');
12834 var w
= this.words
[0] | 0;
12835 res
= w
=== num
? 0 : w
< num
? -1 : 1;
12837 if (this.negative
!== 0) return -res
| 0;
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;
12849 var res
= this.ucmp(num
);
12850 if (this.negative
!== 0) return -res
| 0;
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;
12861 for (var i
= this.length
- 1; i
>= 0; i
--) {
12862 var a
= this.words
[i
] | 0;
12863 var b
= num
.words
[i
] | 0;
12865 if (a
=== b
) continue;
12868 } else if (a
> b
) {
12876 BN
.prototype.gtn
= function gtn (num
) {
12877 return this.cmpn(num
) === 1;
12880 BN
.prototype.gt
= function gt (num
) {
12881 return this.cmp(num
) === 1;
12884 BN
.prototype.gten
= function gten (num
) {
12885 return this.cmpn(num
) >= 0;
12888 BN
.prototype.gte
= function gte (num
) {
12889 return this.cmp(num
) >= 0;
12892 BN
.prototype.ltn
= function ltn (num
) {
12893 return this.cmpn(num
) === -1;
12896 BN
.prototype.lt
= function lt (num
) {
12897 return this.cmp(num
) === -1;
12900 BN
.prototype.lten
= function lten (num
) {
12901 return this.cmpn(num
) <= 0;
12904 BN
.prototype.lte
= function lte (num
) {
12905 return this.cmp(num
) <= 0;
12908 BN
.prototype.eqn
= function eqn (num
) {
12909 return this.cmpn(num
) === 0;
12912 BN
.prototype.eq
= function eq (num
) {
12913 return this.cmp(num
) === 0;
12917 // A reduce context, could be using montgomery or something better, depending
12918 // on the `m` itself.
12920 BN
.red
= function red (num
) {
12921 return new Red(num
);
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
);
12930 BN
.prototype.fromRed
= function fromRed () {
12931 assert(this.red
, 'fromRed works only with numbers in reduction context');
12932 return this.red
.convertFrom(this);
12935 BN
.prototype._forceRed
= function _forceRed (ctx
) {
12940 BN
.prototype.forceRed
= function forceRed (ctx
) {
12941 assert(!this.red
, 'Already a number in reduction context');
12942 return this._forceRed(ctx
);
12945 BN
.prototype.redAdd
= function redAdd (num
) {
12946 assert(this.red
, 'redAdd works only with red numbers');
12947 return this.red
.add(this, num
);
12950 BN
.prototype.redIAdd
= function redIAdd (num
) {
12951 assert(this.red
, 'redIAdd works only with red numbers');
12952 return this.red
.iadd(this, num
);
12955 BN
.prototype.redSub
= function redSub (num
) {
12956 assert(this.red
, 'redSub works only with red numbers');
12957 return this.red
.sub(this, num
);
12960 BN
.prototype.redISub
= function redISub (num
) {
12961 assert(this.red
, 'redISub works only with red numbers');
12962 return this.red
.isub(this, num
);
12965 BN
.prototype.redShl
= function redShl (num
) {
12966 assert(this.red
, 'redShl works only with red numbers');
12967 return this.red
.shl(this, num
);
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
);
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
);
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);
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);
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);
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);
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);
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
);
13020 // Prime numbers with efficient reduction
13028 // Pseudo-Mersenne prime
13029 function MPrime (name
, p
) {
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
);
13036 this.tmp
= this._tmp();
13039 MPrime
.prototype._tmp
= function _tmp () {
13040 var tmp
= new BN(null);
13041 tmp
.words
= new Array(Math
.ceil(this.n
/ 13));
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)
13052 this.split(r
, this.tmp
);
13054 r
= r
.iadd(this.tmp
);
13055 rlen
= r
.bitLength();
13056 } while (rlen
> this.n
);
13058 var cmp
= rlen
< this.n
? -1 : r
.ucmp(this.p
);
13062 } else if (cmp
> 0) {
13071 MPrime
.prototype.split
= function split (input
, out
) {
13072 input
.iushrn(this.n
, 0, out
);
13075 MPrime
.prototype.imulK
= function imulK (num
) {
13076 return num
.imul(this.k
);
13083 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f');
13085 inherits(K256
, MPrime
);
13087 K256
.prototype.split
= function split (input
, output
) {
13088 // 256 = 9 * 26 + 22
13089 var mask
= 0x3fffff;
13091 var outLen
= Math
.min(input
.length
, 9);
13092 for (var i
= 0; i
< outLen
; i
++) {
13093 output
.words
[i
] = input
.words
[i
];
13095 output
.length
= outLen
;
13097 if (input
.length
<= 9) {
13098 input
.words
[0] = 0;
13103 // Shift by 9 limbs
13104 var prev
= input
.words
[9];
13105 output
.words
[output
.length
++] = prev
& mask
;
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);
13113 input
.words
[i
- 10] = prev
;
13114 if (prev
=== 0 && input
.length
> 10) {
13115 input
.length
-= 10;
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;
13127 // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390
13129 for (var i
= 0; i
< num
.length
; i
++) {
13130 var w
= num
.words
[i
] | 0;
13132 num
.words
[i
] = lo
& 0x3ffffff;
13133 lo
= w
* 0x40 + ((lo
/ 0x4000000) | 0);
13136 // Fast length reduction
13137 if (num
.words
[num
.length
- 1] === 0) {
13139 if (num
.words
[num
.length
- 1] === 0) {
13150 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001');
13152 inherits(P224
, MPrime
);
13158 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff');
13160 inherits(P192
, MPrime
);
13162 function P25519 () {
13167 '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed');
13169 inherits(P25519
, MPrime
);
13171 P25519
.prototype.imulK
= function imulK (num
) {
13174 for (var i
= 0; i
< num
.length
; i
++) {
13175 var hi
= (num
.words
[i
] | 0) * 0x13 + carry
;
13176 var lo
= hi
& 0x3ffffff;
13183 num
.words
[num
.length
++] = carry
;
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
];
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();
13203 throw new Error('Unknown prime ' + name
);
13205 primes
[name
] = prime
;
13211 // Base reduction engine
13214 if (typeof m
=== 'string') {
13215 var prime
= BN
._prime(m
);
13217 this.prime
= prime
;
13219 assert(m
.gtn(1), 'modulus must be greater than 1');
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');
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');
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);
13241 Red
.prototype.neg
= function neg (a
) {
13246 return this.m
.sub(a
)._forceRed(this);
13249 Red
.prototype.add
= function add (a
, b
) {
13250 this._verify2(a
, b
);
13252 var res
= a
.add(b
);
13253 if (res
.cmp(this.m
) >= 0) {
13256 return res
._forceRed(this);
13259 Red
.prototype.iadd
= function iadd (a
, b
) {
13260 this._verify2(a
, b
);
13262 var res
= a
.iadd(b
);
13263 if (res
.cmp(this.m
) >= 0) {
13269 Red
.prototype.sub
= function sub (a
, b
) {
13270 this._verify2(a
, b
);
13272 var res
= a
.sub(b
);
13273 if (res
.cmpn(0) < 0) {
13276 return res
._forceRed(this);
13279 Red
.prototype.isub
= function isub (a
, b
) {
13280 this._verify2(a
, b
);
13282 var res
= a
.isub(b
);
13283 if (res
.cmpn(0) < 0) {
13289 Red
.prototype.shl
= function shl (a
, num
) {
13291 return this.imod(a
.ushln(num
));
13294 Red
.prototype.imul
= function imul (a
, b
) {
13295 this._verify2(a
, b
);
13296 return this.imod(a
.imul(b
));
13299 Red
.prototype.mul
= function mul (a
, b
) {
13300 this._verify2(a
, b
);
13301 return this.imod(a
.mul(b
));
13304 Red
.prototype.isqr
= function isqr (a
) {
13305 return this.imul(a
, a
.clone());
13308 Red
.prototype.sqr
= function sqr (a
) {
13309 return this.mul(a
, a
);
13312 Red
.prototype.sqrt
= function sqrt (a
) {
13313 if (a
.isZero()) return a
.clone();
13315 var mod3
= this.m
.andln(3);
13316 assert(mod3
% 2 === 1);
13320 var pow
= this.m
.add(new BN(1)).iushrn(2);
13321 return this.pow(a
, pow
);
13324 // Tonelli-Shanks algorithm (Totally unoptimized and slow)
13326 // Find Q and S, that Q * 2 ^ S = (P - 1)
13327 var q
= this.m
.subn(1);
13329 while (!q
.isZero() && q
.andln(1) === 0) {
13333 assert(!q
.isZero());
13335 var one
= new BN(1).toRed(this);
13336 var nOne
= one
.redNeg();
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);
13344 while (this.pow(z
, lpow
).cmp(nOne
) !== 0) {
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
);
13352 while (t
.cmp(one
) !== 0) {
13354 for (var i
= 0; tmp
.cmp(one
) !== 0; i
++) {
13355 tmp
= tmp
.redSqr();
13358 var b
= this.pow(c
, new BN(1).iushln(m
- i
- 1));
13369 Red
.prototype.invm
= function invm (a
) {
13370 var inv
= a
._invmp(this.m
);
13371 if (inv
.negative
!== 0) {
13373 return this.imod(inv
).redNeg();
13375 return this.imod(inv
);
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();
13383 var windowSize
= 4;
13384 var wnd
= new Array(1 << windowSize
);
13385 wnd
[0] = new BN(1).toRed(this);
13387 for (var i
= 2; i
< wnd
.length
; i
++) {
13388 wnd
[i
] = this.mul(wnd
[i
- 1], a
);
13393 var currentLen
= 0;
13394 var start
= num
.bitLength() % 26;
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
);
13407 if (bit
=== 0 && current
=== 0) {
13415 if (currentLen
!== windowSize
&& (i
!== 0 || j
!== 0)) continue;
13417 res
= this.mul(res
, wnd
[current
]);
13427 Red
.prototype.convertTo
= function convertTo (num
) {
13428 var r
= num
.umod(this.m
);
13430 return r
=== num
? r
.clone() : r
;
13433 Red
.prototype.convertFrom
= function convertFrom (num
) {
13434 var res
= num
.clone();
13440 // Montgomery method engine
13443 BN
.mont
= function mont (num
) {
13444 return new Mont(num
);
13447 function Mont (m
) {
13450 this.shift
= this.m
.bitLength();
13451 if (this.shift
% 26 !== 0) {
13452 this.shift
+= 26 - (this.shift
% 26);
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
);
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
);
13463 inherits(Mont
, Red
);
13465 Mont
.prototype.convertTo
= function convertTo (num
) {
13466 return this.imod(num
.ushln(this.shift
));
13469 Mont
.prototype.convertFrom
= function convertFrom (num
) {
13470 var r
= this.imod(num
.mul(this.rinv
));
13475 Mont
.prototype.imul
= function imul (a
, b
) {
13476 if (a
.isZero() || b
.isZero()) {
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
);
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
);
13493 return res
._forceRed(this);
13496 Mont
.prototype.mul
= function mul (a
, b
) {
13497 if (a
.isZero() || b
.isZero()) return new BN(0)._forceRed(this);
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
);
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
);
13509 return res
._forceRed(this);
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);
13517 })(typeof module
=== 'undefined' || module
, this);
13519 },{"buffer":77}],76:[function(require
,module
,exports
){
13522 module
.exports
= function rand(len
) {
13524 r
= new Rand(null);
13526 return r
.generate(len
);
13529 function Rand(rand
) {
13532 module
.exports
.Rand
= Rand
;
13534 Rand
.prototype.generate
= function generate(len
) {
13535 return this._rand(len
);
13538 // Emulate crypto API using randy
13539 Rand
.prototype._rand
= function _rand(n
) {
13540 if (this.rand
.getBytes
)
13541 return this.rand
.getBytes(n
);
13543 var res
= new Uint8Array(n
);
13544 for (var i
= 0; i
< res
.length
; i
++)
13545 res
[i
] = this.rand
.getByte();
13549 if (typeof self
=== 'object') {
13550 if (self
.crypto
&& self
.crypto
.getRandomValues
) {
13552 Rand
.prototype._rand
= function _rand(n
) {
13553 var arr
= new Uint8Array(n
);
13554 self
.crypto
.getRandomValues(arr
);
13557 } else if (self
.msCrypto
&& self
.msCrypto
.getRandomValues
) {
13559 Rand
.prototype._rand
= function _rand(n
) {
13560 var arr
= new Uint8Array(n
);
13561 self
.msCrypto
.getRandomValues(arr
);
13565 // Safari's WebWorkers do not have `crypto`
13566 } else if (typeof window
=== 'object') {
13568 Rand
.prototype._rand = function() {
13569 throw new Error('Not implemented yet');
13573 // Node.js or Web worker with no crypto support
13575 var crypto
= require('crypto');
13576 if (typeof crypto
.randomBytes
!== 'function')
13577 throw new Error('Not supported');
13579 Rand
.prototype._rand
= function _rand(n
) {
13580 return crypto
.randomBytes(n
);
13586 },{"crypto":77}],77:[function(require
,module
,exports
){
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/
13594 var Buffer
= require('safe-buffer').Buffer
13596 function asUInt32Array (buf
) {
13597 if (!Buffer
.isBuffer(buf
)) buf
= Buffer
.from(buf
)
13599 var len
= (buf
.length
/ 4) | 0
13600 var out
= new Array(len
)
13602 for (var i
= 0; i
< len
; i
++) {
13603 out
[i
] = buf
.readUInt32BE(i
* 4)
13609 function scrubVec (v
) {
13610 for (var i
= 0; i
< v
.length
; v
++) {
13615 function 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]
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]
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
++]
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
++]
13648 return [t0
, t1
, t2
, t3
]
13652 var RCON
= [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36]
13653 var G
= (function () {
13654 // Compute double table
13655 var d
= new Array(256)
13656 for (var j
= 0; j
< 256; j
++) {
13660 d
[j
] = (j
<< 1) ^ 0x11b
13666 var SUB_MIX
= [[], [], [], []]
13667 var INV_SUB_MIX
= [[], [], [], []]
13672 for (var i
= 0; i
< 256; ++i
) {
13674 var sx
= xi
^ (xi
<< 1) ^ (xi
<< 2) ^ (xi
<< 3) ^ (xi
<< 4)
13675 sx
= (sx
>>> 8) ^ (sx
& 0xff) ^ 0x63
13679 // Compute multiplication
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)
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
13701 x
= x2
^ d
[d
[d
[x8
^ x2
]]]
13708 INV_SBOX: INV_SBOX
,
13710 INV_SUB_MIX: INV_SUB_MIX
13714 function AES (key
) {
13715 this._key
= asUInt32Array(key
)
13719 AES
.blockSize
= 4 * 4
13720 AES
.keySize
= 256 / 8
13721 AES
.prototype.blockSize
= AES
.blockSize
13722 AES
.prototype.keySize
= AES
.keySize
13723 AES
.prototype._reset = function () {
13724 var keyWords
= this._key
13725 var keySize
= keyWords
.length
13726 var nRounds
= keySize
+ 6
13727 var ksRows
= (nRounds
+ 1) * 4
13729 var keySchedule
= []
13730 for (var k
= 0; k
< keySize
; k
++) {
13731 keySchedule
[k
] = keyWords
[k
]
13734 for (k
= keySize
; k
< ksRows
; k
++) {
13735 var t
= keySchedule
[k
- 1]
13737 if (k
% keySize
=== 0) {
13738 t
= (t
<< 8) | (t
>>> 24)
13740 (G
.SBOX
[t
>>> 24] << 24) |
13741 (G
.SBOX
[(t
>>> 16) & 0xff] << 16) |
13742 (G
.SBOX
[(t
>>> 8) & 0xff] << 8) |
13745 t
^= RCON
[(k
/ keySize
) | 0] << 24
13746 } else if (keySize
> 6 && k
% keySize
=== 4) {
13748 (G
.SBOX
[t
>>> 24] << 24) |
13749 (G
.SBOX
[(t
>>> 16) & 0xff] << 16) |
13750 (G
.SBOX
[(t
>>> 8) & 0xff] << 8) |
13754 keySchedule
[k
] = keySchedule
[k
- keySize
] ^ t
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)]
13762 if (ik
< 4 || ksR
<= 4) {
13763 invKeySchedule
[ik
] = tt
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]]
13773 this._nRounds
= nRounds
13774 this._keySchedule
= keySchedule
13775 this._invKeySchedule
= invKeySchedule
13778 AES
.prototype.encryptBlockRaw = function (M
) {
13779 M
= asUInt32Array(M
)
13780 return cryptBlock(M
, this._keySchedule
, G
.SUB_MIX
, G
.SBOX
, this._nRounds
)
13783 AES
.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)
13793 AES
.prototype.decryptBlock = function (M
) {
13794 M
= asUInt32Array(M
)
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)
13810 AES
.prototype.scrub = function () {
13811 scrubVec(this._keySchedule
)
13812 scrubVec(this._invKeySchedule
)
13813 scrubVec(this._key
)
13816 module
.exports
.AES
= AES
13818 },{"safe-buffer":247}],79:[function(require
,module
,exports
){
13819 var aes
= require('./aes')
13820 var Buffer
= require('safe-buffer').Buffer
13821 var Transform
= require('cipher-base')
13822 var inherits
= require('inherits')
13823 var GHASH
= require('./ghash')
13824 var xor
= require('buffer-xor')
13825 var incr32
= require('./incr32')
13827 function xorTest (a
, b
) {
13829 if (a
.length
!== b
.length
) out
++
13831 var len
= Math
.min(a
.length
, b
.length
)
13832 for (var i
= 0; i
< len
; ++i
) {
13833 out
+= (a
[i
] ^ b
[i
])
13839 function 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])])
13844 var ghash
= new GHASH(ck
)
13845 var len
= iv
.length
13846 var toPad
= len
% 16
13850 ghash
.update(Buffer
.alloc(toPad
, 0))
13852 ghash
.update(Buffer
.alloc(8, 0))
13853 var ivBits
= len
* 8
13854 var tail
= Buffer
.alloc(8)
13855 tail
.writeUIntBE(ivBits
, 0, 8)
13857 self
._finID
= ghash
.state
13858 var out
= Buffer
.from(self
._finID
)
13862 function StreamCipher (mode
, key
, iv
, decrypt
) {
13863 Transform
.call(this)
13865 var h
= Buffer
.alloc(4, 0)
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
)
13872 this._prev
= Buffer
.from(iv
)
13873 this._cache
= Buffer
.allocUnsafe(0)
13874 this._secCache
= Buffer
.allocUnsafe(0)
13875 this._decrypt
= decrypt
13880 this._authTag
= null
13881 this._called
= false
13884 inherits(StreamCipher
, Transform
)
13886 StreamCipher
.prototype._update = function (chunk
) {
13887 if (!this._called
&& this._alen
) {
13888 var rump
= 16 - (this._alen
% 16)
13890 rump
= Buffer
.alloc(rump
, 0)
13891 this._ghash
.update(rump
)
13895 this._called
= true
13896 var out
= this._mode
.encrypt(this, chunk
)
13897 if (this._decrypt
) {
13898 this._ghash
.update(chunk
)
13900 this._ghash
.update(out
)
13902 this._len
+= chunk
.length
13906 StreamCipher
.prototype._final = function () {
13907 if (this._decrypt
&& !this._authTag
) throw new Error('Unsupported state or unable to authenticate data')
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')
13912 this._authTag
= tag
13913 this._cipher
.scrub()
13916 StreamCipher
.prototype.getAuthTag
= function getAuthTag () {
13917 if (this._decrypt
|| !Buffer
.isBuffer(this._authTag
)) throw new Error('Attempting to get auth tag in unsupported state')
13919 return this._authTag
13922 StreamCipher
.prototype.setAuthTag
= function setAuthTag (tag
) {
13923 if (!this._decrypt
) throw new Error('Attempting to set auth tag in unsupported state')
13925 this._authTag
= tag
13928 StreamCipher
.prototype.setAAD
= function setAAD (buf
) {
13929 if (this._called
) throw new Error('Attempting to set AAD in unsupported state')
13931 this._ghash
.update(buf
)
13932 this._alen
+= buf
.length
13935 module
.exports
= StreamCipher
13937 },{"./aes":78,"./ghash":83,"./incr32":84,"buffer-xor":106,"cipher-base":108,"inherits":163,"safe-buffer":247}],80:[function(require
,module
,exports
){
13938 var ciphers
= require('./encrypter')
13939 var deciphers
= require('./decrypter')
13940 var modes
= require('./modes/list.json')
13942 function getCiphers () {
13943 return Object
.keys(modes
)
13946 exports
.createCipher
= exports
.Cipher
= ciphers
.createCipher
13947 exports
.createCipheriv
= exports
.Cipheriv
= ciphers
.createCipheriv
13948 exports
.createDecipher
= exports
.Decipher
= deciphers
.createDecipher
13949 exports
.createDecipheriv
= exports
.Decipheriv
= deciphers
.createDecipheriv
13950 exports
.listCiphers
= exports
.getCiphers
= getCiphers
13952 },{"./decrypter":81,"./encrypter":82,"./modes/list.json":92}],81:[function(require
,module
,exports
){
13953 var AuthCipher
= require('./authCipher')
13954 var Buffer
= require('safe-buffer').Buffer
13955 var MODES
= require('./modes')
13956 var StreamCipher
= require('./streamCipher')
13957 var Transform
= require('cipher-base')
13958 var aes
= require('./aes')
13959 var ebtk
= require('evp_bytestokey')
13960 var inherits
= require('inherits')
13962 function Decipher (mode
, key
, iv
) {
13963 Transform
.call(this)
13965 this._cache
= new Splitter()
13966 this._last
= void 0
13967 this._cipher
= new aes
.AES(key
)
13968 this._prev
= Buffer
.from(iv
)
13970 this._autopadding
= true
13973 inherits(Decipher
, Transform
)
13975 Decipher
.prototype._update = function (data
) {
13976 this._cache
.add(data
)
13980 while ((chunk
= this._cache
.get(this._autopadding
))) {
13981 thing
= this._mode
.decrypt(this, chunk
)
13984 return Buffer
.concat(out
)
13987 Decipher
.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')
13996 Decipher
.prototype.setAutoPadding = function (setTo
) {
13997 this._autopadding
= !!setTo
14001 function Splitter () {
14002 this.cache
= Buffer
.allocUnsafe(0)
14005 Splitter
.prototype.add = function (data
) {
14006 this.cache
= Buffer
.concat([this.cache
, data
])
14009 Splitter
.prototype.get = function (autoPadding
) {
14012 if (this.cache
.length
> 16) {
14013 out
= this.cache
.slice(0, 16)
14014 this.cache
= this.cache
.slice(16)
14018 if (this.cache
.length
>= 16) {
14019 out
= this.cache
.slice(0, 16)
14020 this.cache
= this.cache
.slice(16)
14028 Splitter
.prototype.flush = function () {
14029 if (this.cache
.length
) return this.cache
14032 function unpad (last
) {
14033 var padded
= last
[15]
14035 while (++i
< padded
) {
14036 if (last
[(i
+ (16 - padded
))] !== padded
) {
14037 throw new Error('unable to decrypt data')
14040 if (padded
=== 16) return
14042 return last
.slice(0, 16 - padded
)
14045 function createDecipheriv (suite
, password
, iv
) {
14046 var config
= MODES
[suite
.toLowerCase()]
14047 if (!config
) throw new TypeError('invalid suite type')
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
)
14052 if (typeof password
=== 'string') password
= Buffer
.from(password
)
14053 if (password
.length
!== config
.key
/ 8) throw new TypeError('invalid key length ' + password
.length
)
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)
14061 return new Decipher(config
.module
, password
, iv
)
14064 function createDecipher (suite
, password
) {
14065 var config
= MODES
[suite
.toLowerCase()]
14066 if (!config
) throw new TypeError('invalid suite type')
14068 var keys
= ebtk(password
, false, config
.key
, config
.iv
)
14069 return createDecipheriv(suite
, keys
.key
, keys
.iv
)
14072 exports
.createDecipher
= createDecipher
14073 exports
.createDecipheriv
= createDecipheriv
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
){
14076 var MODES
= require('./modes')
14077 var AuthCipher
= require('./authCipher')
14078 var Buffer
= require('safe-buffer').Buffer
14079 var StreamCipher
= require('./streamCipher')
14080 var Transform
= require('cipher-base')
14081 var aes
= require('./aes')
14082 var ebtk
= require('evp_bytestokey')
14083 var inherits
= require('inherits')
14085 function Cipher (mode
, key
, iv
) {
14086 Transform
.call(this)
14088 this._cache
= new Splitter()
14089 this._cipher
= new aes
.AES(key
)
14090 this._prev
= Buffer
.from(iv
)
14092 this._autopadding
= true
14095 inherits(Cipher
, Transform
)
14097 Cipher
.prototype._update = function (data
) {
14098 this._cache
.add(data
)
14103 while ((chunk
= this._cache
.get())) {
14104 thing
= this._mode
.encrypt(this, chunk
)
14108 return Buffer
.concat(out
)
14111 var PADDING
= Buffer
.alloc(16, 0x10)
14113 Cipher
.prototype._final = function () {
14114 var chunk
= this._cache
.flush()
14115 if (this._autopadding
) {
14116 chunk
= this._mode
.encrypt(this, chunk
)
14117 this._cipher
.scrub()
14121 if (!chunk
.equals(PADDING
)) {
14122 this._cipher
.scrub()
14123 throw new Error('data not multiple of block length')
14127 Cipher
.prototype.setAutoPadding = function (setTo
) {
14128 this._autopadding
= !!setTo
14132 function Splitter () {
14133 this.cache
= Buffer
.allocUnsafe(0)
14136 Splitter
.prototype.add = function (data
) {
14137 this.cache
= Buffer
.concat([this.cache
, data
])
14140 Splitter
.prototype.get = function () {
14141 if (this.cache
.length
> 15) {
14142 var out
= this.cache
.slice(0, 16)
14143 this.cache
= this.cache
.slice(16)
14149 Splitter
.prototype.flush = function () {
14150 var len
= 16 - this.cache
.length
14151 var padBuff
= Buffer
.allocUnsafe(len
)
14154 while (++i
< len
) {
14155 padBuff
.writeUInt8(len
, i
)
14158 return Buffer
.concat([this.cache
, padBuff
])
14161 function createCipheriv (suite
, password
, iv
) {
14162 var config
= MODES
[suite
.toLowerCase()]
14163 if (!config
) throw new TypeError('invalid suite type')
14165 if (typeof password
=== 'string') password
= Buffer
.from(password
)
14166 if (password
.length
!== config
.key
/ 8) throw new TypeError('invalid key length ' + password
.length
)
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
)
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
)
14177 return new Cipher(config
.module
, password
, iv
)
14180 function createCipher (suite
, password
) {
14181 var config
= MODES
[suite
.toLowerCase()]
14182 if (!config
) throw new TypeError('invalid suite type')
14184 var keys
= ebtk(password
, false, config
.key
, config
.iv
)
14185 return createCipheriv(suite
, keys
.key
, keys
.iv
)
14188 exports
.createCipheriv
= createCipheriv
14189 exports
.createCipher
= createCipher
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
){
14192 var Buffer
= require('safe-buffer').Buffer
14193 var ZEROES
= Buffer
.alloc(16, 0)
14195 function toArray (buf
) {
14197 buf
.readUInt32BE(0),
14198 buf
.readUInt32BE(4),
14199 buf
.readUInt32BE(8),
14200 buf
.readUInt32BE(12)
14204 function 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)
14213 function GHASH (key
) {
14215 this.state
= Buffer
.alloc(16, 0)
14216 this.cache
= Buffer
.allocUnsafe(0)
14219 // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html
14220 // by Juho Vähä-Herttua
14221 GHASH
.prototype.ghash = function (block
) {
14223 while (++i
< block
.length
) {
14224 this.state
[i
] ^= block
[i
]
14229 GHASH
.prototype._multiply = function () {
14230 var Vi
= toArray(this.h
)
14231 var Zi
= [0, 0, 0, 0]
14234 while (++i
< 128) {
14235 xi
= (this.state
[~~(i
/ 8)] & (1 << (7 - (i
% 8)))) !== 0
14237 // Z_i+1 = Z_i ^ V_i
14244 // Store the value of LSB(V_i)
14245 lsbVi
= (Vi
[3] & 1) !== 0
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)
14251 Vi
[0] = Vi
[0] >>> 1
14253 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R
14255 Vi
[0] = Vi
[0] ^ (0xe1 << 24)
14258 this.state
= fromArray(Zi
)
14261 GHASH
.prototype.update = function (buf
) {
14262 this.cache
= Buffer
.concat([this.cache
, buf
])
14264 while (this.cache
.length
>= 16) {
14265 chunk
= this.cache
.slice(0, 16)
14266 this.cache
= this.cache
.slice(16)
14271 GHASH
.prototype.final = function (abl
, bl
) {
14272 if (this.cache
.length
) {
14273 this.ghash(Buffer
.concat([this.cache
, ZEROES
], 16))
14276 this.ghash(fromArray([0, abl
, 0, bl
]))
14280 module
.exports
= GHASH
14282 },{"safe-buffer":247}],84:[function(require
,module
,exports
){
14283 function incr32 (iv
) {
14284 var len
= iv
.length
14287 item
= iv
.readUInt8(len
)
14288 if (item
=== 255) {
14289 iv
.writeUInt8(0, len
)
14292 iv
.writeUInt8(item
, len
)
14297 module
.exports
= incr32
14299 },{}],85:[function(require
,module
,exports
){
14300 var xor
= require('buffer-xor')
14302 exports
.encrypt = function (self
, block
) {
14303 var data
= xor(block
, self
._prev
)
14305 self
._prev
= self
._cipher
.encryptBlock(data
)
14309 exports
.decrypt = function (self
, block
) {
14310 var pad
= self
._prev
14313 var out
= self
._cipher
.decryptBlock(block
)
14315 return xor(out
, pad
)
14318 },{"buffer-xor":106}],86:[function(require
,module
,exports
){
14319 var Buffer
= require('safe-buffer').Buffer
14320 var xor
= require('buffer-xor')
14322 function 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
])
14330 exports
.encrypt = function (self
, data
, decrypt
) {
14331 var out
= Buffer
.allocUnsafe(0)
14334 while (data
.length
) {
14335 if (self
._cache
.length
=== 0) {
14336 self
._cache
= self
._cipher
.encryptBlock(self
._prev
)
14337 self
._prev
= Buffer
.allocUnsafe(0)
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
)
14345 out
= Buffer
.concat([out
, encryptStart(self
, data
, decrypt
)])
14353 },{"buffer-xor":106,"safe-buffer":247}],87:[function(require
,module
,exports
){
14354 var Buffer
= require('safe-buffer').Buffer
14356 function encryptByte (self
, byteParam
, decrypt
) {
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
)
14372 function shiftIn (buffer
, value
) {
14373 var len
= buffer
.length
14375 var out
= Buffer
.allocUnsafe(buffer
.length
)
14376 buffer
= Buffer
.concat([buffer
, Buffer
.from([value
])])
14378 while (++i
< len
) {
14379 out
[i
] = buffer
[i
] << 1 | buffer
[i
+ 1] >> (7)
14385 exports
.encrypt = function (self
, chunk
, decrypt
) {
14386 var len
= chunk
.length
14387 var out
= Buffer
.allocUnsafe(len
)
14390 while (++i
< len
) {
14391 out
[i
] = encryptByte(self
, chunk
[i
], decrypt
)
14397 },{"safe-buffer":247}],88:[function(require
,module
,exports
){
14398 var Buffer
= require('safe-buffer').Buffer
14400 function encryptByte (self
, byteParam
, decrypt
) {
14401 var pad
= self
._cipher
.encryptBlock(self
._prev
)
14402 var out
= pad
[0] ^ byteParam
14404 self
._prev
= Buffer
.concat([
14405 self
._prev
.slice(1),
14406 Buffer
.from([decrypt
? byteParam : out
])
14412 exports
.encrypt = function (self
, chunk
, decrypt
) {
14413 var len
= chunk
.length
14414 var out
= Buffer
.allocUnsafe(len
)
14417 while (++i
< len
) {
14418 out
[i
] = encryptByte(self
, chunk
[i
], decrypt
)
14424 },{"safe-buffer":247}],89:[function(require
,module
,exports
){
14425 var xor
= require('buffer-xor')
14426 var Buffer
= require('safe-buffer').Buffer
14427 var incr32
= require('../incr32')
14429 function getBlock (self
) {
14430 var out
= self
._cipher
.encryptBlockRaw(self
._prev
)
14436 exports
.encrypt = function (self
, chunk
) {
14437 var chunkNum
= Math
.ceil(chunk
.length
/ blockSize
)
14438 var start
= self
._cache
.length
14439 self
._cache
= Buffer
.concat([
14441 Buffer
.allocUnsafe(chunkNum
* blockSize
)
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)
14451 var pad
= self
._cache
.slice(0, chunk
.length
)
14452 self
._cache
= self
._cache
.slice(chunk
.length
)
14453 return xor(chunk
, pad
)
14456 },{"../incr32":84,"buffer-xor":106,"safe-buffer":247}],90:[function(require
,module
,exports
){
14457 exports
.encrypt = function (self
, block
) {
14458 return self
._cipher
.encryptBlock(block
)
14461 exports
.decrypt = function (self
, block
) {
14462 return self
._cipher
.decryptBlock(block
)
14465 },{}],91:[function(require
,module
,exports
){
14466 var 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')
14477 var modes
= require('./list.json')
14479 for (var key
in modes
) {
14480 modes
[key
].module
= modeModules
[modes
[key
].mode
]
14483 module
.exports
= modes
14485 },{"./cbc":85,"./cfb":86,"./cfb1":87,"./cfb8":88,"./ctr":89,"./ecb":90,"./list.json":92,"./ofb":93}],92:[function(require
,module
,exports
){
14678 },{}],93:[function(require
,module
,exports
){
14679 (function (Buffer
){
14680 var xor
= require('buffer-xor')
14682 function getBlock (self
) {
14683 self
._prev
= self
._cipher
.encryptBlock(self
._prev
)
14687 exports
.encrypt = function (self
, chunk
) {
14688 while (self
._cache
.length
< chunk
.length
) {
14689 self
._cache
= Buffer
.concat([self
._cache
, getBlock(self
)])
14692 var pad
= self
._cache
.slice(0, chunk
.length
)
14693 self
._cache
= self
._cache
.slice(chunk
.length
)
14694 return xor(chunk
, pad
)
14697 }).call(this,require("buffer").Buffer
)
14698 },{"buffer":107,"buffer-xor":106}],94:[function(require
,module
,exports
){
14699 var aes
= require('./aes')
14700 var Buffer
= require('safe-buffer').Buffer
14701 var Transform
= require('cipher-base')
14702 var inherits
= require('inherits')
14704 function StreamCipher (mode
, key
, iv
, decrypt
) {
14705 Transform
.call(this)
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
14715 inherits(StreamCipher
, Transform
)
14717 StreamCipher
.prototype._update = function (chunk
) {
14718 return this._mode
.encrypt(this, chunk
, this._decrypt
)
14721 StreamCipher
.prototype._final = function () {
14722 this._cipher
.scrub()
14725 module
.exports
= StreamCipher
14727 },{"./aes":78,"cipher-base":108,"inherits":163,"safe-buffer":247}],95:[function(require
,module
,exports
){
14728 var ebtk
= require('evp_bytestokey')
14729 var aes
= require('browserify-aes/browser')
14730 var DES
= require('browserify-des')
14731 var desModes
= require('browserify-des/modes')
14732 var aesModes
= require('browserify-aes/modes')
14733 function createCipher (suite
, password
) {
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
14743 throw new TypeError('invalid suite type')
14745 var keys
= ebtk(password
, false, keyLen
, ivLen
)
14746 return createCipheriv(suite
, keys
.key
, keys
.iv
)
14748 function createDecipher (suite
, password
) {
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
14758 throw new TypeError('invalid suite type')
14760 var keys
= ebtk(password
, false, keyLen
, ivLen
)
14761 return createDecipheriv(suite
, keys
.key
, keys
.iv
)
14764 function createCipheriv (suite
, key
, iv
) {
14765 suite
= suite
.toLowerCase()
14766 if (aesModes
[suite
]) {
14767 return aes
.createCipheriv(suite
, key
, iv
)
14768 } else if (desModes
[suite
]) {
14775 throw new TypeError('invalid suite type')
14778 function createDecipheriv (suite
, key
, iv
) {
14779 suite
= suite
.toLowerCase()
14780 if (aesModes
[suite
]) {
14781 return aes
.createDecipheriv(suite
, key
, iv
)
14782 } else if (desModes
[suite
]) {
14790 throw new TypeError('invalid suite type')
14793 exports
.createCipher
= exports
.Cipher
= createCipher
14794 exports
.createCipheriv
= exports
.Cipheriv
= createCipheriv
14795 exports
.createDecipher
= exports
.Decipher
= createDecipher
14796 exports
.createDecipheriv
= exports
.Decipheriv
= createDecipheriv
14797 function getCiphers () {
14798 return Object
.keys(desModes
).concat(aes
.getCiphers())
14800 exports
.listCiphers
= exports
.getCiphers
= getCiphers
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
){
14804 var CipherBase
= require('cipher-base')
14805 var des
= require('des.js')
14806 var inherits
= require('inherits')
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
),
14816 modes
.des
= modes
['des-cbc']
14817 modes
.des3
= modes
['des-ede3-cbc']
14818 module
.exports
= DES
14819 inherits(DES
, CipherBase
)
14820 function DES (opts
) {
14821 CipherBase
.call(this)
14822 var modeName
= opts
.mode
.toLowerCase()
14823 var mode
= modes
[modeName
]
14825 if (opts
.decrypt
) {
14831 if (modeName
=== 'des-ede' || modeName
=== 'des-ede-cbc') {
14832 key
= Buffer
.concat([key
, key
.slice(0, 8)])
14835 this._des
= mode
.create({
14841 DES
.prototype._update = function (data
) {
14842 return new Buffer(this._des
.update(data
))
14844 DES
.prototype._final = function () {
14845 return new Buffer(this._des
.final())
14848 }).call(this,require("buffer").Buffer
)
14849 },{"buffer":107,"cipher-base":108,"des.js":117,"inherits":163}],97:[function(require
,module
,exports
){
14850 exports
['des-ecb'] = {
14854 exports
['des-cbc'] = exports
.des
= {
14858 exports
['des-ede3-cbc'] = exports
.des3
= {
14862 exports
['des-ede3'] = {
14866 exports
['des-ede-cbc'] = {
14870 exports
['des-ede'] = {
14875 },{}],98:[function(require
,module
,exports
){
14876 (function (Buffer
){
14877 var bn
= require('bn.js');
14878 var randomBytes
= require('randombytes');
14879 module
.exports
= crt
;
14880 function blind(priv
) {
14881 var r
= getr(priv
);
14882 var blinder
= r
.toRed(bn
.mont(priv
.modulus
))
14883 .redPow(new bn(priv
.publicExponent
)).fromRed();
14886 unblinder:r
.invm(priv
.modulus
)
14889 function 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
);
14903 var h
= m1
.isub(m2
).imul(qinv
).umod(p
);
14906 return new Buffer(m2
.imul(blinds
.unblinder
).umod(priv
.modulus
).toArray(false, len
));
14909 function 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
));
14918 }).call(this,require("buffer").Buffer
)
14919 },{"bn.js":75,"buffer":107,"randombytes":231}],99:[function(require
,module
,exports
){
14920 module
.exports
= require('./browser/algorithms.json')
14922 },{"./browser/algorithms.json":100}],100:[function(require
,module
,exports
){
14924 "sha224WithRSAEncryption": {
14927 "id": "302d300d06096086480165030402040500041c"
14930 "sign": "ecdsa/rsa",
14932 "id": "302d300d06096086480165030402040500041c"
14934 "sha256WithRSAEncryption": {
14937 "id": "3031300d060960864801650304020105000420"
14940 "sign": "ecdsa/rsa",
14942 "id": "3031300d060960864801650304020105000420"
14944 "sha384WithRSAEncryption": {
14947 "id": "3041300d060960864801650304020205000430"
14950 "sign": "ecdsa/rsa",
14952 "id": "3041300d060960864801650304020205000430"
14954 "sha512WithRSAEncryption": {
14957 "id": "3051300d060960864801650304020305000440"
14960 "sign": "ecdsa/rsa",
14962 "id": "3051300d060960864801650304020305000440"
14967 "id": "3021300906052b0e03021a05000414"
14969 "ecdsa-with-SHA1": {
15009 "DSA-WITH-SHA224": {
15019 "DSA-WITH-SHA256": {
15029 "DSA-WITH-SHA384": {
15039 "DSA-WITH-SHA512": {
15054 "ripemd160WithRSA": {
15057 "id": "3021300906052b2403020105000414"
15062 "id": "3021300906052b2403020105000414"
15064 "md5WithRSAEncryption": {
15067 "id": "3020300c06082a864886f70d020505000410"
15072 "id": "3020300c06082a864886f70d020505000410"
15076 },{}],101:[function(require
,module
,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"
15086 },{}],102:[function(require
,module
,exports
){
15087 (function (Buffer
){
15088 var createHash
= require('create-hash')
15089 var stream
= require('stream')
15090 var inherits
= require('inherits')
15091 var sign
= require('./sign')
15092 var verify
= require('./verify')
15094 var algorithms
= require('./algorithms.json')
15095 Object
.keys(algorithms
).forEach(function (key
) {
15096 algorithms
[key
].id
= new Buffer(algorithms
[key
].id
, 'hex')
15097 algorithms
[key
.toLowerCase()] = algorithms
[key
]
15100 function Sign (algorithm
) {
15101 stream
.Writable
.call(this)
15103 var data
= algorithms
[algorithm
]
15104 if (!data
) throw new Error('Unknown message digest')
15106 this._hashType
= data
.hash
15107 this._hash
= createHash(data
.hash
)
15108 this._tag
= data
.id
15109 this._signType
= data
.sign
15111 inherits(Sign
, stream
.Writable
)
15113 Sign
.prototype._write
= function _write (data
, _
, done
) {
15114 this._hash
.update(data
)
15118 Sign
.prototype.update
= function update (data
, enc
) {
15119 if (typeof data
=== 'string') data
= new Buffer(data
, enc
)
15121 this._hash
.update(data
)
15125 Sign
.prototype.sign
= function signMethod (key
, enc
) {
15127 var hash
= this._hash
.digest()
15128 var sig
= sign(hash
, key
, this._hashType
, this._signType
, this._tag
)
15130 return enc
? sig
.toString(enc
) : sig
15133 function Verify (algorithm
) {
15134 stream
.Writable
.call(this)
15136 var data
= algorithms
[algorithm
]
15137 if (!data
) throw new Error('Unknown message digest')
15139 this._hash
= createHash(data
.hash
)
15140 this._tag
= data
.id
15141 this._signType
= data
.sign
15143 inherits(Verify
, stream
.Writable
)
15145 Verify
.prototype._write
= function _write (data
, _
, done
) {
15146 this._hash
.update(data
)
15150 Verify
.prototype.update
= function update (data
, enc
) {
15151 if (typeof data
=== 'string') data
= new Buffer(data
, enc
)
15153 this._hash
.update(data
)
15157 Verify
.prototype.verify
= function verifyMethod (key
, sig
, enc
) {
15158 if (typeof sig
=== 'string') sig
= new Buffer(sig
, enc
)
15161 var hash
= this._hash
.digest()
15162 return verify(sig
, hash
, key
, this._signType
, this._tag
)
15165 function createSign (algorithm
) {
15166 return new Sign(algorithm
)
15169 function createVerify (algorithm
) {
15170 return new Verify(algorithm
)
15175 Verify: createVerify
,
15176 createSign: createSign
,
15177 createVerify: createVerify
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
15184 var createHmac
= require('create-hmac')
15185 var crt
= require('browserify-rsa')
15186 var EC
= require('elliptic').ec
15187 var BN
= require('bn.js')
15188 var parseKeys
= require('parse-asn1')
15189 var curves
= require('./curves.json')
15191 function sign (hash
, key
, hashType
, signType
, tag
) {
15192 var priv
= parseKeys(key
)
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
)
15201 if (signType
!== 'rsa' && signType
!== 'ecdsa/rsa') throw new Error('wrong private key type')
15203 hash
= Buffer
.concat([tag
, hash
])
15204 var len
= priv
.modulus
.byteLength()
15206 while (hash
.length
+ pad
.length
+ 1 < len
) pad
.push(0xff)
15209 while (++i
< hash
.length
) pad
.push(hash
[i
])
15211 var out
= crt(pad
, priv
)
15215 function ecSign (hash
, priv
) {
15216 var curveId
= curves
[priv
.curve
.join('.')]
15217 if (!curveId
) throw new Error('unknown curve ' + priv
.curve
.join('.'))
15219 var curve
= new EC(curveId
)
15220 var key
= curve
.keyFromPrivate(priv
.privateKey
)
15221 var out
= key
.sign(hash
)
15223 return new Buffer(out
.toDER())
15226 function 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
15233 var H
= bits2int(hash
, q
).mod(q
)
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) {
15248 function toDER (r
, s
) {
15253 if (r
[0] & 0x80) r
= [ 0 ].concat(r
)
15254 if (s
[0] & 0x80) s
= [ 0 ].concat(s
)
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
)
15262 function 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
)
15267 x
= Buffer
.concat([ zeros
, x
])
15269 var hlen
= hash
.length
15270 var hbits
= bits2octets(hash
, q
)
15271 var v
= new Buffer(hlen
)
15273 var k
= new Buffer(hlen
)
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
}
15282 function bits2int (obits
, q
) {
15283 var bits
= new BN(obits
)
15284 var shift
= (obits
.length
<< 3) - q
.bitLength()
15285 if (shift
> 0) bits
.ishrn(shift
)
15289 function bits2octets (bits
, q
) {
15290 bits
= bits2int(bits
, q
)
15292 var out
= new Buffer(bits
.toArray())
15293 if (out
.length
< q
.byteLength()) {
15294 var zeros
= new Buffer(q
.byteLength() - out
.length
)
15296 out
= Buffer
.concat([ zeros
, out
])
15301 function makeKey (q
, kv
, algo
) {
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
])
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)
15321 function makeR (g
, k
, p
, q
) {
15322 return g
.toRed(BN
.mont(p
)).redPow(k
).fromRed().mod(q
)
15325 module
.exports
= sign
15326 module
.exports
.getKey
= getKey
15327 module
.exports
.makeKey
= makeKey
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
15333 var BN
= require('bn.js')
15334 var EC
= require('elliptic').ec
15335 var parseKeys
= require('parse-asn1')
15336 var curves
= require('./curves.json')
15338 function 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
)
15348 if (signType
!== 'rsa' && signType
!== 'ecdsa/rsa') throw new Error('wrong public key type')
15350 hash
= Buffer
.concat([tag
, hash
])
15351 var len
= pub
.modulus
.byteLength()
15354 while (hash
.length
+ pad
.length
+ 2 < len
) {
15360 while (++i
< hash
.length
) {
15363 pad
= new Buffer(pad
)
15364 var red
= BN
.mont(pub
.modulus
)
15365 sig
= new BN(sig
).toRed(red
)
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
15374 while (++i
< len
) out
|= sig
[i
] ^ pad
[i
]
15378 function 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('.'))
15382 var curve
= new EC(curveId
)
15383 var pubkey
= pub
.data
.subjectPrivateKey
.data
15385 return curve
.verify(hash
, sig
, pubkey
)
15388 function dsaVerify (sig
, hash
, pub
) {
15392 var y
= pub
.data
.pub_key
15393 var unpacked
= parseKeys
.signature
.decode(sig
, 'der')
15398 var montp
= BN
.mont(p
)
15400 var v
= g
.toRed(montp
)
15401 .redPow(new BN(hash
).mul(w
).mod(q
))
15403 .mul(y
.toRed(montp
).redPow(r
.mul(w
).mod(q
)).fromRed())
15406 return v
.cmp(r
) === 0
15409 function 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')
15414 module
.exports
= verify
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
){
15418 var basex
= require('base-x')
15419 var ALPHABET
= '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'
15421 module
.exports
= basex(ALPHABET
)
15423 },{"base-x":71}],106:[function(require
,module
,exports
){
15424 (function (Buffer
){
15425 module
.exports
= function xor (a
, b
) {
15426 var length
= Math
.min(a
.length
, b
.length
)
15427 var buffer
= new Buffer(length
)
15429 for (var i
= 0; i
< length
; ++i
) {
15430 buffer
[i
] = a
[i
] ^ b
[i
]
15436 }).call(this,require("buffer").Buffer
)
15437 },{"buffer":107}],107:[function(require
,module
,exports
){
15439 * The buffer module from node.js, for the browser.
15441 * @author Feross Aboukhadijeh <https://feross.org>
15444 /* eslint-disable no-proto */
15448 var base64
= require('base64-js')
15449 var ieee754
= require('ieee754')
15451 exports
.Buffer
= Buffer
15452 exports
.SlowBuffer
= SlowBuffer
15453 exports
.INSPECT_MAX_BYTES
= 50
15455 var K_MAX_LENGTH
= 0x7fffffff
15456 exports
.kMaxLength
= K_MAX_LENGTH
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)
15464 * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+,
15465 * Opera 11.6+, iOS 4.2+.
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.
15472 Buffer
.TYPED_ARRAY_SUPPORT
= typedArraySupport()
15474 if (!Buffer
.TYPED_ARRAY_SUPPORT
&& typeof console
!== 'undefined' &&
15475 typeof console
.error
=== 'function') {
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.'
15482 function typedArraySupport () {
15483 // Can typed array instances can be augmented?
15485 var arr
= new Uint8Array(1)
15486 arr
.__proto__
= {__proto__: Uint8Array
.prototype, foo: function () { return 42 }}
15487 return arr
.foo() === 42
15493 function createBuffer (length
) {
15494 if (length
> K_MAX_LENGTH
) {
15495 throw new RangeError('Invalid typed array length')
15497 // Return an augmented `Uint8Array` instance
15498 var buf
= new Uint8Array(length
)
15499 buf
.__proto__
= Buffer
.prototype
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.
15510 * The `Uint8Array` prototype remains unmodified.
15513 function Buffer (arg
, encodingOrOffset
, length
) {
15515 if (typeof arg
=== 'number') {
15516 if (typeof encodingOrOffset
=== 'string') {
15518 'If encoding is specified then the first argument must be a string'
15521 return allocUnsafe(arg
)
15523 return from(arg
, encodingOrOffset
, length
)
15526 // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97
15527 if (typeof Symbol
!== 'undefined' && Symbol
.species
&&
15528 Buffer
[Symbol
.species
] === Buffer
) {
15529 Object
.defineProperty(Buffer
, Symbol
.species
, {
15531 configurable: true,
15537 Buffer
.poolSize
= 8192 // not used by this implementation
15539 function from (value
, encodingOrOffset
, length
) {
15540 if (typeof value
=== 'number') {
15541 throw new TypeError('"value" argument must not be a number')
15544 if (isArrayBuffer(value
)) {
15545 return fromArrayBuffer(value
, encodingOrOffset
, length
)
15548 if (typeof value
=== 'string') {
15549 return fromString(value
, encodingOrOffset
)
15552 return fromObject(value
)
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]])
15563 Buffer
.from = function (value
, encodingOrOffset
, length
) {
15564 return from(value
, encodingOrOffset
, length
)
15567 // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug:
15568 // https://github.com/feross/buffer/pull/148
15569 Buffer
.prototype.__proto__
= Uint8Array
.prototype
15570 Buffer
.__proto__
= Uint8Array
15572 function 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')
15580 function alloc (size
, fill
, encoding
) {
15583 return createBuffer(size
)
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
)
15593 return createBuffer(size
)
15597 * Creates a new filled Buffer instance.
15598 * alloc(size[, fill[, encoding]])
15600 Buffer
.alloc = function (size
, fill
, encoding
) {
15601 return alloc(size
, fill
, encoding
)
15604 function allocUnsafe (size
) {
15606 return createBuffer(size
< 0 ? 0 : checked(size
) | 0)
15610 * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance.
15612 Buffer
.allocUnsafe = function (size
) {
15613 return allocUnsafe(size
)
15616 * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance.
15618 Buffer
.allocUnsafeSlow = function (size
) {
15619 return allocUnsafe(size
)
15622 function fromString (string
, encoding
) {
15623 if (typeof encoding
!== 'string' || encoding
=== '') {
15627 if (!Buffer
.isEncoding(encoding
)) {
15628 throw new TypeError('"encoding" must be a valid string encoding')
15631 var length
= byteLength(string
, encoding
) | 0
15632 var buf
= createBuffer(length
)
15634 var actual
= buf
.write(string
, encoding
)
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
)
15646 function 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
15655 function fromArrayBuffer (array
, byteOffset
, length
) {
15656 if (byteOffset
< 0 || array
.byteLength
< byteOffset
) {
15657 throw new RangeError('\'offset\' is out of bounds')
15660 if (array
.byteLength
< byteOffset
+ (length
|| 0)) {
15661 throw new RangeError('\'length\' is out of bounds')
15665 if (byteOffset
=== undefined && length
=== undefined) {
15666 buf
= new Uint8Array(array
)
15667 } else if (length
=== undefined) {
15668 buf
= new Uint8Array(array
, byteOffset
)
15670 buf
= new Uint8Array(array
, byteOffset
, length
)
15673 // Return an augmented `Uint8Array` instance
15674 buf
.__proto__
= Buffer
.prototype
15678 function fromObject (obj
) {
15679 if (Buffer
.isBuffer(obj
)) {
15680 var len
= checked(obj
.length
) | 0
15681 var buf
= createBuffer(len
)
15683 if (buf
.length
=== 0) {
15687 obj
.copy(buf
, 0, 0, len
)
15692 if (isArrayBufferView(obj
) || 'length' in obj
) {
15693 if (typeof obj
.length
!== 'number' || numberIsNaN(obj
.length
)) {
15694 return createBuffer(0)
15696 return fromArrayLike(obj
)
15699 if (obj
.type
=== 'Buffer' && Array
.isArray(obj
.data
)) {
15700 return fromArrayLike(obj
.data
)
15704 throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.')
15707 function 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')
15717 function SlowBuffer (length
) {
15718 if (+length
!= length
) { // eslint-disable-line eqeqeq
15721 return Buffer
.alloc(+length
)
15724 Buffer
.isBuffer
= function isBuffer (b
) {
15725 return b
!= null && b
._isBuffer
=== true
15728 Buffer
.compare
= function compare (a
, b
) {
15729 if (!Buffer
.isBuffer(a
) || !Buffer
.isBuffer(b
)) {
15730 throw new TypeError('Arguments must be Buffers')
15733 if (a
=== b
) return 0
15738 for (var i
= 0, len
= Math
.min(x
, y
); i
< len
; ++i
) {
15739 if (a
[i
] !== b
[i
]) {
15746 if (x
< y
) return -1
15747 if (y
< x
) return 1
15751 Buffer
.isEncoding
= function isEncoding (encoding
) {
15752 switch (String(encoding
).toLowerCase()) {
15770 Buffer
.concat
= function concat (list
, length
) {
15771 if (!Array
.isArray(list
)) {
15772 throw new TypeError('"list" argument must be an Array of Buffers')
15775 if (list
.length
=== 0) {
15776 return Buffer
.alloc(0)
15780 if (length
=== undefined) {
15782 for (i
= 0; i
< list
.length
; ++i
) {
15783 length
+= list
[i
].length
15787 var buffer
= Buffer
.allocUnsafe(length
)
15789 for (i
= 0; i
< list
.length
; ++i
) {
15791 if (!Buffer
.isBuffer(buf
)) {
15792 throw new TypeError('"list" argument must be an Array of Buffers')
15794 buf
.copy(buffer
, pos
)
15800 function byteLength (string
, encoding
) {
15801 if (Buffer
.isBuffer(string
)) {
15802 return string
.length
15804 if (isArrayBufferView(string
) || isArrayBuffer(string
)) {
15805 return string
.byteLength
15807 if (typeof string
!== 'string') {
15808 string
= '' + string
15811 var len
= string
.length
15812 if (len
=== 0) return 0
15814 // Use a for loop to avoid recursion
15815 var loweredCase
= false
15817 switch (encoding
) {
15825 return utf8ToBytes(string
).length
15834 return base64ToBytes(string
).length
15836 if (loweredCase
) return utf8ToBytes(string
).length
// assume utf8
15837 encoding
= ('' + encoding
).toLowerCase()
15842 Buffer
.byteLength
= byteLength
15844 function slowToString (encoding
, start
, end
) {
15845 var loweredCase
= false
15847 // No need to verify that "this.length <= MAX_UINT32" since it's a read-only
15848 // property of a typed array.
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) {
15857 // Return early if start > this.length. Done here to prevent potential uint32
15858 // coercion fail below.
15859 if (start
> this.length
) {
15863 if (end
=== undefined || end
> this.length
) {
15871 // Force coersion to uint32. This will also coerce falsey/NaN values to 0.
15875 if (end
<= start
) {
15879 if (!encoding
) encoding
= 'utf8'
15882 switch (encoding
) {
15884 return hexSlice(this, start
, end
)
15888 return utf8Slice(this, start
, end
)
15891 return asciiSlice(this, start
, end
)
15895 return latin1Slice(this, start
, end
)
15898 return base64Slice(this, start
, end
)
15904 return utf16leSlice(this, start
, end
)
15907 if (loweredCase
) throw new TypeError('Unknown encoding: ' + encoding
)
15908 encoding
= (encoding
+ '').toLowerCase()
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
15920 Buffer
.prototype._isBuffer
= true
15922 function swap (b
, n
, m
) {
15928 Buffer
.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')
15933 for (var i
= 0; i
< len
; i
+= 2) {
15934 swap(this, i
, i
+ 1)
15939 Buffer
.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')
15944 for (var i
= 0; i
< len
; i
+= 4) {
15945 swap(this, i
, i
+ 3)
15946 swap(this, i
+ 1, i
+ 2)
15951 Buffer
.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')
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)
15965 Buffer
.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
)
15972 Buffer
.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
15978 Buffer
.prototype.inspect
= function inspect () {
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
+= ' ... '
15985 return '<Buffer ' + str
+ '>'
15988 Buffer
.prototype.compare
= function compare (target
, start
, end
, thisStart
, thisEnd
) {
15989 if (!Buffer
.isBuffer(target
)) {
15990 throw new TypeError('Argument must be a Buffer')
15993 if (start
=== undefined) {
15996 if (end
=== undefined) {
15997 end
= target
? target
.length : 0
15999 if (thisStart
=== undefined) {
16002 if (thisEnd
=== undefined) {
16003 thisEnd
= this.length
16006 if (start
< 0 || end
> target
.length
|| thisStart
< 0 || thisEnd
> this.length
) {
16007 throw new RangeError('out of range index')
16010 if (thisStart
>= thisEnd
&& start
>= end
) {
16013 if (thisStart
>= thisEnd
) {
16016 if (start
>= end
) {
16025 if (this === target
) return 0
16027 var x
= thisEnd
- thisStart
16028 var y
= end
- start
16029 var len
= Math
.min(x
, y
)
16031 var thisCopy
= this.slice(thisStart
, thisEnd
)
16032 var targetCopy
= target
.slice(start
, end
)
16034 for (var i
= 0; i
< len
; ++i
) {
16035 if (thisCopy
[i
] !== targetCopy
[i
]) {
16042 if (x
< y
) return -1
16043 if (y
< x
) return 1
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`.
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
16056 function bidirectionalIndexOf (buffer
, val
, byteOffset
, encoding
, dir
) {
16057 // Empty buffer means no match
16058 if (buffer
.length
=== 0) return -1
16060 // Normalize byteOffset
16061 if (typeof byteOffset
=== 'string') {
16062 encoding
= byteOffset
16064 } else if (byteOffset
> 0x7fffffff) {
16065 byteOffset
= 0x7fffffff
16066 } else if (byteOffset
< -0x80000000) {
16067 byteOffset
= -0x80000000
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)
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
) {
16079 else byteOffset
= buffer
.length
- 1
16080 } else if (byteOffset
< 0) {
16081 if (dir
) byteOffset
= 0
16086 if (typeof val
=== 'string') {
16087 val
= Buffer
.from(val
, encoding
)
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) {
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') {
16101 return Uint8Array
.prototype.indexOf
.call(buffer
, val
, byteOffset
)
16103 return Uint8Array
.prototype.lastIndexOf
.call(buffer
, val
, byteOffset
)
16106 return arrayIndexOf(buffer
, [ val
], byteOffset
, encoding
, dir
)
16109 throw new TypeError('val must be string, number or Buffer')
16112 function arrayIndexOf (arr
, val
, byteOffset
, encoding
, dir
) {
16114 var arrLength
= arr
.length
16115 var valLength
= val
.length
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) {
16131 function read (buf
, i
) {
16132 if (indexSize
=== 1) {
16135 return buf
.readUInt16BE(i
* indexSize
)
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
16147 if (foundIndex
!== -1) i
-= i
- foundIndex
16152 if (byteOffset
+ valLength
> arrLength
) byteOffset
= arrLength
- valLength
16153 for (i
= byteOffset
; i
>= 0; i
--) {
16155 for (var j
= 0; j
< valLength
; j
++) {
16156 if (read(arr
, i
+ j
) !== read(val
, j
)) {
16161 if (found
) return i
16168 Buffer
.prototype.includes
= function includes (val
, byteOffset
, encoding
) {
16169 return this.indexOf(val
, byteOffset
, encoding
) !== -1
16172 Buffer
.prototype.indexOf
= function indexOf (val
, byteOffset
, encoding
) {
16173 return bidirectionalIndexOf(this, val
, byteOffset
, encoding
, true)
16176 Buffer
.prototype.lastIndexOf
= function lastIndexOf (val
, byteOffset
, encoding
) {
16177 return bidirectionalIndexOf(this, val
, byteOffset
, encoding
, false)
16180 function hexWrite (buf
, string
, offset
, length
) {
16181 offset
= Number(offset
) || 0
16182 var remaining
= buf
.length
- offset
16186 length
= Number(length
)
16187 if (length
> remaining
) {
16192 // must be an even number of digits
16193 var strLen
= string
.length
16194 if (strLen
% 2 !== 0) throw new TypeError('Invalid hex string')
16196 if (length
> strLen
/ 2) {
16197 length
= strLen
/ 2
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
16207 function utf8Write (buf
, string
, offset
, length
) {
16208 return blitBuffer(utf8ToBytes(string
, buf
.length
- offset
), buf
, offset
, length
)
16211 function asciiWrite (buf
, string
, offset
, length
) {
16212 return blitBuffer(asciiToBytes(string
), buf
, offset
, length
)
16215 function latin1Write (buf
, string
, offset
, length
) {
16216 return asciiWrite(buf
, string
, offset
, length
)
16219 function base64Write (buf
, string
, offset
, length
) {
16220 return blitBuffer(base64ToBytes(string
), buf
, offset
, length
)
16223 function ucs2Write (buf
, string
, offset
, length
) {
16224 return blitBuffer(utf16leToBytes(string
, buf
.length
- offset
), buf
, offset
, length
)
16227 Buffer
.prototype.write
= function write (string
, offset
, length
, encoding
) {
16228 // Buffer#write(string)
16229 if (offset
=== undefined) {
16231 length
= this.length
16233 // Buffer#write(string, encoding)
16234 } else if (length
=== undefined && typeof offset
=== 'string') {
16236 length
= this.length
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'
16250 'Buffer.write(string, encoding, offset[, length]) is no longer supported'
16254 var remaining
= this.length
- offset
16255 if (length
=== undefined || length
> remaining
) length
= remaining
16257 if ((string
.length
> 0 && (length
< 0 || offset
< 0)) || offset
> this.length
) {
16258 throw new RangeError('Attempt to write outside buffer bounds')
16261 if (!encoding
) encoding
= 'utf8'
16263 var loweredCase
= false
16265 switch (encoding
) {
16267 return hexWrite(this, string
, offset
, length
)
16271 return utf8Write(this, string
, offset
, length
)
16274 return asciiWrite(this, string
, offset
, length
)
16278 return latin1Write(this, string
, offset
, length
)
16281 // Warning: maxLength not taken into account in base64Write
16282 return base64Write(this, string
, offset
, length
)
16288 return ucs2Write(this, string
, offset
, length
)
16291 if (loweredCase
) throw new TypeError('Unknown encoding: ' + encoding
)
16292 encoding
= ('' + encoding
).toLowerCase()
16298 Buffer
.prototype.toJSON
= function toJSON () {
16301 data: Array
.prototype.slice
.call(this._arr
|| this, 0)
16305 function base64Slice (buf
, start
, end
) {
16306 if (start
=== 0 && end
=== buf
.length
) {
16307 return base64
.fromByteArray(buf
)
16309 return base64
.fromByteArray(buf
.slice(start
, end
))
16313 function utf8Slice (buf
, start
, end
) {
16314 end
= Math
.min(buf
.length
, end
)
16319 var firstByte
= buf
[i
]
16320 var codePoint
= null
16321 var bytesPerSequence
= (firstByte
> 0xEF) ? 4
16322 : (firstByte
> 0xDF) ? 3
16323 : (firstByte
> 0xBF) ? 2
16326 if (i
+ bytesPerSequence
<= end
) {
16327 var secondByte
, thirdByte
, fourthByte
, tempCodePoint
16329 switch (bytesPerSequence
) {
16331 if (firstByte
< 0x80) {
16332 codePoint
= firstByte
16336 secondByte
= buf
[i
+ 1]
16337 if ((secondByte
& 0xC0) === 0x80) {
16338 tempCodePoint
= (firstByte
& 0x1F) << 0x6 | (secondByte
& 0x3F)
16339 if (tempCodePoint
> 0x7F) {
16340 codePoint
= tempCodePoint
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
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
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
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
16379 res
.push(codePoint
)
16380 i
+= bytesPerSequence
16383 return decodeCodePointsArray(res
)
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
16389 var MAX_ARGUMENTS_LENGTH
= 0x1000
16391 function decodeCodePointsArray (codePoints
) {
16392 var len
= codePoints
.length
16393 if (len
<= MAX_ARGUMENTS_LENGTH
) {
16394 return String
.fromCharCode
.apply(String
, codePoints
) // avoid extra slice()
16397 // Decode in chunks to avoid "call stack size exceeded".
16401 res
+= String
.fromCharCode
.apply(
16403 codePoints
.slice(i
, i
+= MAX_ARGUMENTS_LENGTH
)
16409 function asciiSlice (buf
, start
, end
) {
16411 end
= Math
.min(buf
.length
, end
)
16413 for (var i
= start
; i
< end
; ++i
) {
16414 ret
+= String
.fromCharCode(buf
[i
] & 0x7F)
16419 function latin1Slice (buf
, start
, end
) {
16421 end
= Math
.min(buf
.length
, end
)
16423 for (var i
= start
; i
< end
; ++i
) {
16424 ret
+= String
.fromCharCode(buf
[i
])
16429 function hexSlice (buf
, start
, end
) {
16430 var len
= buf
.length
16432 if (!start
|| start
< 0) start
= 0
16433 if (!end
|| end
< 0 || end
> len
) end
= len
16436 for (var i
= start
; i
< end
; ++i
) {
16437 out
+= toHex(buf
[i
])
16442 function utf16leSlice (buf
, start
, end
) {
16443 var bytes
= buf
.slice(start
, end
)
16445 for (var i
= 0; i
< bytes
.length
; i
+= 2) {
16446 res
+= String
.fromCharCode(bytes
[i
] + (bytes
[i
+ 1] * 256))
16451 Buffer
.prototype.slice
= function slice (start
, end
) {
16452 var len
= this.length
16454 end
= end
=== undefined ? len : ~~end
16458 if (start
< 0) start
= 0
16459 } else if (start
> len
) {
16465 if (end
< 0) end
= 0
16466 } else if (end
> len
) {
16470 if (end
< start
) end
= start
16472 var newBuf
= this.subarray(start
, end
)
16473 // Return an augmented `Uint8Array` instance
16474 newBuf
.__proto__
= Buffer
.prototype
16479 * Need to make sure that buffer isn't trying to write out of bounds.
16481 function 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')
16486 Buffer
.prototype.readUIntLE
= function readUIntLE (offset
, byteLength
, noAssert
) {
16487 offset
= offset
>>> 0
16488 byteLength
= byteLength
>>> 0
16489 if (!noAssert
) checkOffset(offset
, byteLength
, this.length
)
16491 var val
= this[offset
]
16494 while (++i
< byteLength
&& (mul
*= 0x100)) {
16495 val
+= this[offset
+ i
] * mul
16501 Buffer
.prototype.readUIntBE
= function readUIntBE (offset
, byteLength
, noAssert
) {
16502 offset
= offset
>>> 0
16503 byteLength
= byteLength
>>> 0
16505 checkOffset(offset
, byteLength
, this.length
)
16508 var val
= this[offset
+ --byteLength
]
16510 while (byteLength
> 0 && (mul
*= 0x100)) {
16511 val
+= this[offset
+ --byteLength
] * mul
16517 Buffer
.prototype.readUInt8
= function readUInt8 (offset
, noAssert
) {
16518 offset
= offset
>>> 0
16519 if (!noAssert
) checkOffset(offset
, 1, this.length
)
16520 return this[offset
]
16523 Buffer
.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)
16529 Buffer
.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]
16535 Buffer
.prototype.readUInt32LE
= function readUInt32LE (offset
, noAssert
) {
16536 offset
= offset
>>> 0
16537 if (!noAssert
) checkOffset(offset
, 4, this.length
)
16539 return ((this[offset
]) |
16540 (this[offset
+ 1] << 8) |
16541 (this[offset
+ 2] << 16)) +
16542 (this[offset
+ 3] * 0x1000000)
16545 Buffer
.prototype.readUInt32BE
= function readUInt32BE (offset
, noAssert
) {
16546 offset
= offset
>>> 0
16547 if (!noAssert
) checkOffset(offset
, 4, this.length
)
16549 return (this[offset
] * 0x1000000) +
16550 ((this[offset
+ 1] << 16) |
16551 (this[offset
+ 2] << 8) |
16555 Buffer
.prototype.readIntLE
= function readIntLE (offset
, byteLength
, noAssert
) {
16556 offset
= offset
>>> 0
16557 byteLength
= byteLength
>>> 0
16558 if (!noAssert
) checkOffset(offset
, byteLength
, this.length
)
16560 var val
= this[offset
]
16563 while (++i
< byteLength
&& (mul
*= 0x100)) {
16564 val
+= this[offset
+ i
] * mul
16568 if (val
>= mul
) val
-= Math
.pow(2, 8 * byteLength
)
16573 Buffer
.prototype.readIntBE
= function readIntBE (offset
, byteLength
, noAssert
) {
16574 offset
= offset
>>> 0
16575 byteLength
= byteLength
>>> 0
16576 if (!noAssert
) checkOffset(offset
, byteLength
, this.length
)
16580 var val
= this[offset
+ --i
]
16581 while (i
> 0 && (mul
*= 0x100)) {
16582 val
+= this[offset
+ --i
] * mul
16586 if (val
>= mul
) val
-= Math
.pow(2, 8 * byteLength
)
16591 Buffer
.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)
16598 Buffer
.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
16605 Buffer
.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
16612 Buffer
.prototype.readInt32LE
= function readInt32LE (offset
, noAssert
) {
16613 offset
= offset
>>> 0
16614 if (!noAssert
) checkOffset(offset
, 4, this.length
)
16616 return (this[offset
]) |
16617 (this[offset
+ 1] << 8) |
16618 (this[offset
+ 2] << 16) |
16619 (this[offset
+ 3] << 24)
16622 Buffer
.prototype.readInt32BE
= function readInt32BE (offset
, noAssert
) {
16623 offset
= offset
>>> 0
16624 if (!noAssert
) checkOffset(offset
, 4, this.length
)
16626 return (this[offset
] << 24) |
16627 (this[offset
+ 1] << 16) |
16628 (this[offset
+ 2] << 8) |
16632 Buffer
.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)
16638 Buffer
.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)
16644 Buffer
.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)
16650 Buffer
.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)
16656 function 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')
16662 Buffer
.prototype.writeUIntLE
= function writeUIntLE (value
, offset
, byteLength
, noAssert
) {
16664 offset
= offset
>>> 0
16665 byteLength
= byteLength
>>> 0
16667 var maxBytes
= Math
.pow(2, 8 * byteLength
) - 1
16668 checkInt(this, value
, offset
, byteLength
, maxBytes
, 0)
16673 this[offset
] = value
& 0xFF
16674 while (++i
< byteLength
&& (mul
*= 0x100)) {
16675 this[offset
+ i
] = (value
/ mul
) & 0xFF
16678 return offset
+ byteLength
16681 Buffer
.prototype.writeUIntBE
= function writeUIntBE (value
, offset
, byteLength
, noAssert
) {
16683 offset
= offset
>>> 0
16684 byteLength
= byteLength
>>> 0
16686 var maxBytes
= Math
.pow(2, 8 * byteLength
) - 1
16687 checkInt(this, value
, offset
, byteLength
, maxBytes
, 0)
16690 var i
= byteLength
- 1
16692 this[offset
+ i
] = value
& 0xFF
16693 while (--i
>= 0 && (mul
*= 0x100)) {
16694 this[offset
+ i
] = (value
/ mul
) & 0xFF
16697 return offset
+ byteLength
16700 Buffer
.prototype.writeUInt8
= function writeUInt8 (value
, offset
, noAssert
) {
16702 offset
= offset
>>> 0
16703 if (!noAssert
) checkInt(this, value
, offset
, 1, 0xff, 0)
16704 this[offset
] = (value
& 0xff)
16708 Buffer
.prototype.writeUInt16LE
= function writeUInt16LE (value
, offset
, noAssert
) {
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)
16717 Buffer
.prototype.writeUInt16BE
= function writeUInt16BE (value
, offset
, noAssert
) {
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)
16726 Buffer
.prototype.writeUInt32LE
= function writeUInt32LE (value
, offset
, noAssert
) {
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)
16737 Buffer
.prototype.writeUInt32BE
= function writeUInt32BE (value
, offset
, noAssert
) {
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)
16748 Buffer
.prototype.writeIntLE
= function writeIntLE (value
, offset
, byteLength
, noAssert
) {
16750 offset
= offset
>>> 0
16752 var limit
= Math
.pow(2, (8 * byteLength
) - 1)
16754 checkInt(this, value
, offset
, byteLength
, limit
- 1, -limit
)
16760 this[offset
] = value
& 0xFF
16761 while (++i
< byteLength
&& (mul
*= 0x100)) {
16762 if (value
< 0 && sub
=== 0 && this[offset
+ i
- 1] !== 0) {
16765 this[offset
+ i
] = ((value
/ mul
) >> 0) - sub
& 0xFF
16768 return offset
+ byteLength
16771 Buffer
.prototype.writeIntBE
= function writeIntBE (value
, offset
, byteLength
, noAssert
) {
16773 offset
= offset
>>> 0
16775 var limit
= Math
.pow(2, (8 * byteLength
) - 1)
16777 checkInt(this, value
, offset
, byteLength
, limit
- 1, -limit
)
16780 var i
= byteLength
- 1
16783 this[offset
+ i
] = value
& 0xFF
16784 while (--i
>= 0 && (mul
*= 0x100)) {
16785 if (value
< 0 && sub
=== 0 && this[offset
+ i
+ 1] !== 0) {
16788 this[offset
+ i
] = ((value
/ mul
) >> 0) - sub
& 0xFF
16791 return offset
+ byteLength
16794 Buffer
.prototype.writeInt8
= function writeInt8 (value
, offset
, noAssert
) {
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)
16803 Buffer
.prototype.writeInt16LE
= function writeInt16LE (value
, offset
, noAssert
) {
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)
16812 Buffer
.prototype.writeInt16BE
= function writeInt16BE (value
, offset
, noAssert
) {
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)
16821 Buffer
.prototype.writeInt32LE
= function writeInt32LE (value
, offset
, noAssert
) {
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)
16832 Buffer
.prototype.writeInt32BE
= function writeInt32BE (value
, offset
, noAssert
) {
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)
16844 function 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')
16849 function writeFloat (buf
, value
, offset
, littleEndian
, noAssert
) {
16851 offset
= offset
>>> 0
16853 checkIEEE754(buf
, value
, offset
, 4, 3.4028234663852886e+38, -3.4028234663852886e+38)
16855 ieee754
.write(buf
, value
, offset
, littleEndian
, 23, 4)
16859 Buffer
.prototype.writeFloatLE
= function writeFloatLE (value
, offset
, noAssert
) {
16860 return writeFloat(this, value
, offset
, true, noAssert
)
16863 Buffer
.prototype.writeFloatBE
= function writeFloatBE (value
, offset
, noAssert
) {
16864 return writeFloat(this, value
, offset
, false, noAssert
)
16867 function writeDouble (buf
, value
, offset
, littleEndian
, noAssert
) {
16869 offset
= offset
>>> 0
16871 checkIEEE754(buf
, value
, offset
, 8, 1.7976931348623157E+308, -1.7976931348623157E+308)
16873 ieee754
.write(buf
, value
, offset
, littleEndian
, 52, 8)
16877 Buffer
.prototype.writeDoubleLE
= function writeDoubleLE (value
, offset
, noAssert
) {
16878 return writeDouble(this, value
, offset
, true, noAssert
)
16881 Buffer
.prototype.writeDoubleBE
= function writeDoubleBE (value
, offset
, noAssert
) {
16882 return writeDouble(this, value
, offset
, false, noAssert
)
16885 // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
16886 Buffer
.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
16893 // Copy 0 bytes; we're done
16894 if (end
=== start
) return 0
16895 if (target
.length
=== 0 || this.length
=== 0) return 0
16897 // Fatal error conditions
16898 if (targetStart
< 0) {
16899 throw new RangeError('targetStart out of bounds')
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')
16905 if (end
> this.length
) end
= this.length
16906 if (target
.length
- targetStart
< end
- start
) {
16907 end
= target
.length
- targetStart
+ start
16910 var len
= end
- start
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
]
16918 } else if (len
< 1000) {
16919 // ascending copy from start
16920 for (i
= 0; i
< len
; ++i
) {
16921 target
[i
+ targetStart
] = this[i
+ start
]
16924 Uint8Array
.prototype.set.call(
16926 this.subarray(start
, start
+ len
),
16935 // buffer.fill(number[, offset[, end]])
16936 // buffer.fill(buffer[, offset[, end]])
16937 // buffer.fill(string[, offset[, end]][, encoding])
16938 Buffer
.prototype.fill
= function fill (val
, start
, end
, encoding
) {
16939 // Handle string cases:
16940 if (typeof val
=== 'string') {
16941 if (typeof start
=== 'string') {
16945 } else if (typeof end
=== 'string') {
16949 if (val
.length
=== 1) {
16950 var code
= val
.charCodeAt(0)
16955 if (encoding
!== undefined && typeof encoding
!== 'string') {
16956 throw new TypeError('encoding must be a string')
16958 if (typeof encoding
=== 'string' && !Buffer
.isEncoding(encoding
)) {
16959 throw new TypeError('Unknown encoding: ' + encoding
)
16961 } else if (typeof val
=== 'number') {
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')
16970 if (end
<= start
) {
16974 start
= start
>>> 0
16975 end
= end
=== undefined ? this.length : end
>>> 0
16980 if (typeof val
=== 'number') {
16981 for (i
= start
; i
< end
; ++i
) {
16985 var bytes
= Buffer
.isBuffer(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
]
16997 // HELPER FUNCTIONS
16998 // ================
17000 var INVALID_BASE64_RE
= /[^+/0-9A
-Za
-z
-_
]/g
17002 function 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) {
17014 function toHex (n
) {
17015 if (n
< 16) return '0' + n
.toString(16)
17016 return n
.toString(16)
17019 function utf8ToBytes (string
, units
) {
17020 units
= units
|| Infinity
17022 var length
= string
.length
17023 var leadSurrogate
= null
17026 for (var i
= 0; i
< length
; ++i
) {
17027 codePoint
= string
.charCodeAt(i
)
17029 // is surrogate component
17030 if (codePoint
> 0xD7FF && codePoint
< 0xE000) {
17031 // last char was a lead
17032 if (!leadSurrogate
) {
17034 if (codePoint
> 0xDBFF) {
17035 // unexpected trail
17036 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
17038 } else if (i
+ 1 === length
) {
17040 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
17045 leadSurrogate
= codePoint
17050 // 2 leads in a row
17051 if (codePoint
< 0xDC00) {
17052 if ((units
-= 3) > -1) bytes
.push(0xEF, 0xBF, 0xBD)
17053 leadSurrogate
= codePoint
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)
17064 leadSurrogate
= null
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
17073 codePoint
>> 0x6 | 0xC0,
17074 codePoint
& 0x3F | 0x80
17076 } else if (codePoint
< 0x10000) {
17077 if ((units
-= 3) < 0) break
17079 codePoint
>> 0xC | 0xE0,
17080 codePoint
>> 0x6 & 0x3F | 0x80,
17081 codePoint
& 0x3F | 0x80
17083 } else if (codePoint
< 0x110000) {
17084 if ((units
-= 4) < 0) break
17086 codePoint
>> 0x12 | 0xF0,
17087 codePoint
>> 0xC & 0x3F | 0x80,
17088 codePoint
>> 0x6 & 0x3F | 0x80,
17089 codePoint
& 0x3F | 0x80
17092 throw new Error('Invalid code point')
17099 function asciiToBytes (str
) {
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)
17108 function utf16leToBytes (str
, units
) {
17111 for (var i
= 0; i
< str
.length
; ++i
) {
17112 if ((units
-= 2) < 0) break
17114 c
= str
.charCodeAt(i
)
17124 function base64ToBytes (str
) {
17125 return base64
.toByteArray(base64clean(str
))
17128 function 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
]
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
17138 function isArrayBuffer (obj
) {
17139 return obj
instanceof ArrayBuffer
||
17140 (obj
!= null && obj
.constructor != null && obj
.constructor.name
=== 'ArrayBuffer' &&
17141 typeof obj
.byteLength
=== 'number')
17144 // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView`
17145 function isArrayBufferView (obj
) {
17146 return (typeof ArrayBuffer
.isView
=== 'function') && ArrayBuffer
.isView(obj
)
17149 function numberIsNaN (obj
) {
17150 return obj
!== obj
// eslint-disable-line no-self-compare
17153 },{"base64-js":72,"ieee754":161}],108:[function(require
,module
,exports
){
17154 var Buffer
= require('safe-buffer').Buffer
17155 var Transform
= require('stream').Transform
17156 var StringDecoder
= require('string_decoder').StringDecoder
17157 var inherits
= require('inherits')
17159 function CipherBase (hashMode
) {
17160 Transform
.call(this)
17161 this.hashMode
= typeof hashMode
=== 'string'
17162 if (this.hashMode
) {
17163 this[hashMode
] = this._finalOrDigest
17165 this.final
= this._finalOrDigest
17168 this.__final
= this._final
17171 this._decoder
= null
17172 this._encoding
= null
17174 inherits(CipherBase
, Transform
)
17176 CipherBase
.prototype.update = function (data
, inputEnc
, outputEnc
) {
17177 if (typeof data
=== 'string') {
17178 data
= Buffer
.from(data
, inputEnc
)
17181 var outData
= this._update(data
)
17182 if (this.hashMode
) return this
17185 outData
= this._toString(outData
, outputEnc
)
17191 CipherBase
.prototype.setAutoPadding = function () {}
17192 CipherBase
.prototype.getAuthTag = function () {
17193 throw new Error('trying to get auth tag in unsupported state')
17196 CipherBase
.prototype.setAuthTag = function () {
17197 throw new Error('trying to set auth tag in unsupported state')
17200 CipherBase
.prototype.setAAD = function () {
17201 throw new Error('trying to set aad in unsupported state')
17204 CipherBase
.prototype._transform = function (data
, _
, next
) {
17207 if (this.hashMode
) {
17210 this.push(this._update(data
))
17218 CipherBase
.prototype._flush = function (done
) {
17221 this.push(this.__final())
17228 CipherBase
.prototype._finalOrDigest = function (outputEnc
) {
17229 var outData
= this.__final() || Buffer
.alloc(0)
17231 outData
= this._toString(outData
, outputEnc
, true)
17236 CipherBase
.prototype._toString = function (value
, enc
, fin
) {
17237 if (!this._decoder
) {
17238 this._decoder
= new StringDecoder(enc
)
17239 this._encoding
= enc
17242 if (this._encoding
!== enc
) throw new Error('can\'t switch encodings')
17244 var out
= this._decoder
.write(value
)
17246 out
+= this._decoder
.end()
17252 module
.exports
= CipherBase
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.
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:
17266 // The above copyright notice and this permission notice shall be included
17267 // in all copies or substantial portions of the Software.
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.
17277 // NOTE: These type checking functions intentionally don't use `instanceof`
17278 // because it is fragile and can be easily faked with `Object.create()`.
17280 function isArray(arg
) {
17281 if (Array
.isArray
) {
17282 return Array
.isArray(arg
);
17284 return objectToString(arg
) === '[object Array]';
17286 exports
.isArray
= isArray
;
17288 function isBoolean(arg
) {
17289 return typeof arg
=== 'boolean';
17291 exports
.isBoolean
= isBoolean
;
17293 function isNull(arg
) {
17294 return arg
=== null;
17296 exports
.isNull
= isNull
;
17298 function isNullOrUndefined(arg
) {
17299 return arg
== null;
17301 exports
.isNullOrUndefined
= isNullOrUndefined
;
17303 function isNumber(arg
) {
17304 return typeof arg
=== 'number';
17306 exports
.isNumber
= isNumber
;
17308 function isString(arg
) {
17309 return typeof arg
=== 'string';
17311 exports
.isString
= isString
;
17313 function isSymbol(arg
) {
17314 return typeof arg
=== 'symbol';
17316 exports
.isSymbol
= isSymbol
;
17318 function isUndefined(arg
) {
17319 return arg
=== void 0;
17321 exports
.isUndefined
= isUndefined
;
17323 function isRegExp(re
) {
17324 return objectToString(re
) === '[object RegExp]';
17326 exports
.isRegExp
= isRegExp
;
17328 function isObject(arg
) {
17329 return typeof arg
=== 'object' && arg
!== null;
17331 exports
.isObject
= isObject
;
17333 function isDate(d
) {
17334 return objectToString(d
) === '[object Date]';
17336 exports
.isDate
= isDate
;
17338 function isError(e
) {
17339 return (objectToString(e
) === '[object Error]' || e
instanceof Error
);
17341 exports
.isError
= isError
;
17343 function isFunction(arg
) {
17344 return typeof arg
=== 'function';
17346 exports
.isFunction
= isFunction
;
17348 function 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';
17356 exports
.isPrimitive
= isPrimitive
;
17358 exports
.isBuffer
= Buffer
.isBuffer
;
17360 function objectToString(o
) {
17361 return Object
.prototype.toString
.call(o
);
17364 }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
17365 },{"../../is-buffer/index.js":164}],110:[function(require
,module
,exports
){
17366 (function (Buffer
){
17367 var elliptic
= require('elliptic');
17368 var BN
= require('bn.js');
17370 module
.exports
= function createECDH(curve
) {
17371 return new ECDH(curve
);
17405 aliases
.p224
= aliases
.secp224r1
;
17406 aliases
.p256
= aliases
.secp256r1
= aliases
.prime256v1
;
17407 aliases
.p192
= aliases
.secp192r1
= aliases
.prime192v1
;
17408 aliases
.p384
= aliases
.secp384r1
;
17409 aliases
.p521
= aliases
.secp521r1
;
17411 function ECDH(curve
) {
17412 this.curveType
= aliases
[curve
];
17413 if (!this.curveType
) {
17418 this.curve
= new elliptic
.ec(this.curveType
.name
);
17419 this.keys
= void 0;
17422 ECDH
.prototype.generateKeys = function (enc
, format
) {
17423 this.keys
= this.curve
.genKeyPair();
17424 return this.getPublicKey(enc
, format
);
17427 ECDH
.prototype.computeSecret = function (other
, inenc
, enc
) {
17428 inenc
= inenc
|| 'utf8';
17429 if (!Buffer
.isBuffer(other
)) {
17430 other
= new Buffer(other
, inenc
);
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
);
17437 ECDH
.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) {
17446 return formatReturnValue(key
, enc
);
17449 ECDH
.prototype.getPrivateKey = function (enc
) {
17450 return formatReturnValue(this.keys
.getPrivate(), enc
);
17453 ECDH
.prototype.setPublicKey = function (pub
, enc
) {
17454 enc
= enc
|| 'utf8';
17455 if (!Buffer
.isBuffer(pub
)) {
17456 pub
= new Buffer(pub
, enc
);
17458 this.keys
._importPublic(pub
);
17462 ECDH
.prototype.setPrivateKey = function (priv
, enc
) {
17463 enc
= enc
|| 'utf8';
17464 if (!Buffer
.isBuffer(priv
)) {
17465 priv
= new Buffer(priv
, enc
);
17467 var _priv
= new BN(priv
);
17468 _priv
= _priv
.toString(16);
17469 this.keys
._importPrivate(_priv
);
17473 function formatReturnValue(bn
, enc
, len
) {
17474 if (!Array
.isArray(bn
)) {
17477 var buf
= new Buffer(bn
);
17478 if (len
&& buf
.length
< len
) {
17479 var zeros
= new Buffer(len
- buf
.length
);
17481 buf
= Buffer
.concat([zeros
, buf
]);
17486 return buf
.toString(enc
);
17490 }).call(this,require("buffer").Buffer
)
17491 },{"bn.js":75,"buffer":107,"elliptic":127}],111:[function(require
,module
,exports
){
17492 (function (Buffer
){
17494 var inherits
= require('inherits')
17495 var md5
= require('./md5')
17496 var RIPEMD160
= require('ripemd160')
17497 var sha
= require('sha.js')
17499 var Base
= require('cipher-base')
17501 function HashNoConstructor (hash
) {
17502 Base
.call(this, 'digest')
17508 inherits(HashNoConstructor
, Base
)
17510 HashNoConstructor
.prototype._update = function (data
) {
17511 this.buffers
.push(data
)
17514 HashNoConstructor
.prototype._final = function () {
17515 var buf
= Buffer
.concat(this.buffers
)
17516 var r
= this._hash(buf
)
17517 this.buffers
= null
17522 function Hash (hash
) {
17523 Base
.call(this, 'digest')
17528 inherits(Hash
, Base
)
17530 Hash
.prototype._update = function (data
) {
17531 this._hash
.update(data
)
17534 Hash
.prototype._final = function () {
17535 return this._hash
.digest()
17538 module
.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())
17543 return new Hash(sha(alg
))
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
){
17551 var zeroBuffer
= new Buffer(intSize
)
17557 function toArray (buf
) {
17558 if ((buf
.length
% intSize
) !== 0) {
17559 var len
= buf
.length
+ (intSize
- (buf
.length
% intSize
))
17560 buf
= Buffer
.concat([buf
, zeroBuffer
], len
)
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
)
17571 module
.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)
17580 }).call(this,require("buffer").Buffer
)
17581 },{"buffer":107}],113:[function(require
,module
,exports
){
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.
17592 var makeHash
= require('./make-hash')
17595 * Calculate the MD5 of an array of little-endian words, and a bit length
17597 function core_md5 (x
, len
) {
17598 /* append padding */
17599 x
[len
>> 5] |= 0x80 << ((len
) % 32)
17600 x
[(((len
+ 64) >>> 9) << 4) + 14] = len
17604 var c
= -1732584194
17607 for (var i
= 0; i
< x
.length
; i
+= 16) {
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)
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)
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)
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)
17681 a
= safe_add(a
, olda
)
17682 b
= safe_add(b
, oldb
)
17683 c
= safe_add(c
, oldc
)
17684 d
= safe_add(d
, oldd
)
17687 return [a
, b
, c
, d
]
17691 * These functions implement the four basic operations the algorithm uses.
17693 function 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
)
17697 function md5_ff (a
, b
, c
, d
, x
, s
, t
) {
17698 return md5_cmn((b
& c
) | ((~b
) & d
), a
, b
, x
, s
, t
)
17701 function md5_gg (a
, b
, c
, d
, x
, s
, t
) {
17702 return md5_cmn((b
& d
) | (c
& (~d
)), a
, b
, x
, s
, t
)
17705 function md5_hh (a
, b
, c
, d
, x
, s
, t
) {
17706 return md5_cmn(b
^ c
^ d
, a
, b
, x
, s
, t
)
17709 function md5_ii (a
, b
, c
, d
, x
, s
, t
) {
17710 return md5_cmn(c
^ (b
| (~d
)), a
, b
, x
, s
, t
)
17714 * Add integers, wrapping at 2^32. This uses 16-bit operations internally
17715 * to work around bugs in some JS interpreters.
17717 function 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)
17724 * Bitwise rotate a 32-bit number to the left.
17726 function bit_rol (num
, cnt
) {
17727 return (num
<< cnt
) | (num
>>> (32 - cnt
))
17730 module
.exports
= function md5 (buf
) {
17731 return makeHash(buf
, core_md5
)
17734 },{"./make-hash":112}],114:[function(require
,module
,exports
){
17736 var inherits
= require('inherits')
17737 var Legacy
= require('./legacy')
17738 var Base
= require('cipher-base')
17739 var Buffer
= require('safe-buffer').Buffer
17740 var md5
= require('create-hash/md5')
17741 var RIPEMD160
= require('ripemd160')
17743 var sha
= require('sha.js')
17745 var ZEROS
= Buffer
.alloc(128)
17747 function Hmac (alg
, key
) {
17748 Base
.call(this, 'digest')
17749 if (typeof key
=== 'string') {
17750 key
= Buffer
.from(key
)
17753 var blocksize
= (alg
=== 'sha512' || alg
=== 'sha384') ? 128 : 64
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
)
17764 var ipad
= this._ipad
= Buffer
.allocUnsafe(blocksize
)
17765 var opad
= this._opad
= Buffer
.allocUnsafe(blocksize
)
17767 for (var i
= 0; i
< blocksize
; i
++) {
17768 ipad
[i
] = key
[i
] ^ 0x36
17769 opad
[i
] = key
[i
] ^ 0x5C
17771 this._hash
= alg
=== 'rmd160' ? new RIPEMD160() : sha(alg
)
17772 this._hash
.update(ipad
)
17775 inherits(Hmac
, Base
)
17777 Hmac
.prototype._update = function (data
) {
17778 this._hash
.update(data
)
17781 Hmac
.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()
17787 module
.exports
= function createHmac (alg
, key
) {
17788 alg
= alg
.toLowerCase()
17789 if (alg
=== 'rmd160' || alg
=== 'ripemd160') {
17790 return new Hmac('rmd160', key
)
17792 if (alg
=== 'md5') {
17793 return new Legacy(md5
, key
)
17795 return new Hmac(alg
, key
)
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
){
17800 var inherits
= require('inherits')
17801 var Buffer
= require('safe-buffer').Buffer
17803 var Base
= require('cipher-base')
17805 var ZEROS
= Buffer
.alloc(128)
17808 function Hmac (alg
, key
) {
17809 Base
.call(this, 'digest')
17810 if (typeof key
=== 'string') {
17811 key
= Buffer
.from(key
)
17817 if (key
.length
> blocksize
) {
17819 } else if (key
.length
< blocksize
) {
17820 key
= Buffer
.concat([key
, ZEROS
], blocksize
)
17823 var ipad
= this._ipad
= Buffer
.allocUnsafe(blocksize
)
17824 var opad
= this._opad
= Buffer
.allocUnsafe(blocksize
)
17826 for (var i
= 0; i
< blocksize
; i
++) {
17827 ipad
[i
] = key
[i
] ^ 0x36
17828 opad
[i
] = key
[i
] ^ 0x5C
17831 this._hash
= [ipad
]
17834 inherits(Hmac
, Base
)
17836 Hmac
.prototype._update = function (data
) {
17837 this._hash
.push(data
)
17840 Hmac
.prototype._final = function () {
17841 var h
= this._alg(Buffer
.concat(this._hash
))
17842 return this._alg(Buffer
.concat([this._opad
, h
]))
17844 module
.exports
= Hmac
17846 },{"cipher-base":108,"inherits":163,"safe-buffer":247}],116:[function(require
,module
,exports
){
17849 exports
.randomBytes
= exports
.rng
= exports
.pseudoRandomBytes
= exports
.prng
= require('randombytes')
17850 exports
.createHash
= exports
.Hash
= require('create-hash')
17851 exports
.createHmac
= exports
.Hmac
= require('create-hmac')
17853 var algos
= require('browserify-sign/algos')
17854 var algoKeys
= Object
.keys(algos
)
17855 var hashes
= ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys
)
17856 exports
.getHashes = function () {
17860 var p
= require('pbkdf2')
17861 exports
.pbkdf2
= p
.pbkdf2
17862 exports
.pbkdf2Sync
= p
.pbkdf2Sync
17864 var aes
= require('browserify-cipher')
17866 exports
.Cipher
= aes
.Cipher
17867 exports
.createCipher
= aes
.createCipher
17868 exports
.Cipheriv
= aes
.Cipheriv
17869 exports
.createCipheriv
= aes
.createCipheriv
17870 exports
.Decipher
= aes
.Decipher
17871 exports
.createDecipher
= aes
.createDecipher
17872 exports
.Decipheriv
= aes
.Decipheriv
17873 exports
.createDecipheriv
= aes
.createDecipheriv
17874 exports
.getCiphers
= aes
.getCiphers
17875 exports
.listCiphers
= aes
.listCiphers
17877 var dh
= require('diffie-hellman')
17879 exports
.DiffieHellmanGroup
= dh
.DiffieHellmanGroup
17880 exports
.createDiffieHellmanGroup
= dh
.createDiffieHellmanGroup
17881 exports
.getDiffieHellman
= dh
.getDiffieHellman
17882 exports
.createDiffieHellman
= dh
.createDiffieHellman
17883 exports
.DiffieHellman
= dh
.DiffieHellman
17885 var sign
= require('browserify-sign')
17887 exports
.createSign
= sign
.createSign
17888 exports
.Sign
= sign
.Sign
17889 exports
.createVerify
= sign
.createVerify
17890 exports
.Verify
= sign
.Verify
17892 exports
.createECDH
= require('create-ecdh')
17894 var publicEncrypt
= require('public-encrypt')
17896 exports
.publicEncrypt
= publicEncrypt
.publicEncrypt
17897 exports
.privateEncrypt
= publicEncrypt
.privateEncrypt
17898 exports
.publicDecrypt
= publicEncrypt
.publicDecrypt
17899 exports
.privateDecrypt
= publicEncrypt
.privateDecrypt
17901 // the least I can do is make error messages for the rest of the node.js/crypto api.
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'
17914 var rf
= require('randomfill')
17916 exports
.randomFill
= rf
.randomFill
17917 exports
.randomFillSync
= rf
.randomFillSync
17919 exports
.createCredentials = function () {
17921 'sorry, createCredentials is not implemented yet',
17922 'we accept pull requests',
17923 'https://github.com/crypto-browserify/crypto-browserify'
17927 exports
.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,
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
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
){
17948 exports
.utils
= require('./des/utils');
17949 exports
.Cipher
= require('./des/cipher');
17950 exports
.DES
= require('./des/des');
17951 exports
.CBC
= require('./des/cbc');
17952 exports
.EDE
= require('./des/ede');
17954 },{"./des/cbc":118,"./des/cipher":119,"./des/des":120,"./des/ede":121,"./des/utils":122}],118:[function(require
,module
,exports
){
17957 var assert
= require('minimalistic-assert');
17958 var inherits
= require('inherits');
17962 function CBCState(iv
) {
17963 assert
.equal(iv
.length
, 8, 'Invalid IV length');
17965 this.iv
= new Array(8);
17966 for (var i
= 0; i
< this.iv
.length
; i
++)
17967 this.iv
[i
] = iv
[i
];
17970 function instantiate(Base
) {
17971 function CBC(options
) {
17972 Base
.call(this, options
);
17975 inherits(CBC
, Base
);
17977 var keys
= Object
.keys(proto
);
17978 for (var i
= 0; i
< keys
.length
; i
++) {
17980 CBC
.prototype[key
] = proto
[key
];
17983 CBC
.create
= function create(options
) {
17984 return new CBC(options
);
17990 exports
.instantiate
= instantiate
;
17992 proto
._cbcInit
= function _cbcInit() {
17993 var state
= new CBCState(this.options
.iv
);
17994 this._cbcState
= state
;
17997 proto
._update
= function _update(inp
, inOff
, out
, outOff
) {
17998 var state
= this._cbcState
;
17999 var superProto
= this.constructor.super_
.prototype;
18002 if (this.type
=== 'encrypt') {
18003 for (var i
= 0; i
< this.blockSize
; i
++)
18004 iv
[i
] ^= inp
[inOff
+ i
];
18006 superProto
._update
.call(this, iv
, 0, out
, outOff
);
18008 for (var i
= 0; i
< this.blockSize
; i
++)
18009 iv
[i
] = out
[outOff
+ i
];
18011 superProto
._update
.call(this, inp
, inOff
, out
, outOff
);
18013 for (var i
= 0; i
< this.blockSize
; i
++)
18014 out
[outOff
+ i
] ^= iv
[i
];
18016 for (var i
= 0; i
< this.blockSize
; i
++)
18017 iv
[i
] = inp
[inOff
+ i
];
18021 },{"inherits":163,"minimalistic-assert":176}],119:[function(require
,module
,exports
){
18024 var assert
= require('minimalistic-assert');
18026 function Cipher(options
) {
18027 this.options
= options
;
18029 this.type
= this.options
.type
;
18030 this.blockSize
= 8;
18033 this.buffer
= new Array(this.blockSize
);
18034 this.bufferOff
= 0;
18036 module
.exports
= Cipher
;
18038 Cipher
.prototype._init
= function _init() {
18039 // Might be overrided
18042 Cipher
.prototype.update
= function update(data
) {
18043 if (data
.length
=== 0)
18046 if (this.type
=== 'decrypt')
18047 return this._updateDecrypt(data
);
18049 return this._updateEncrypt(data
);
18052 Cipher
.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
;
18063 Cipher
.prototype._flushBuffer
= function _flushBuffer(out
, off
) {
18064 this._update(this.buffer
, 0, out
, off
);
18065 this.bufferOff
= 0;
18066 return this.blockSize
;
18069 Cipher
.prototype._updateEncrypt
= function _updateEncrypt(data
) {
18073 var count
= ((this.bufferOff
+ data
.length
) / this.blockSize
) | 0;
18074 var out
= new Array(count
* this.blockSize
);
18076 if (this.bufferOff
!== 0) {
18077 inputOff
+= this._buffer(data
, inputOff
);
18079 if (this.bufferOff
=== this.buffer
.length
)
18080 outputOff
+= this._flushBuffer(out
, outputOff
);
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
;
18091 for (; inputOff
< data
.length
; inputOff
++, this.bufferOff
++)
18092 this.buffer
[this.bufferOff
] = data
[inputOff
];
18097 Cipher
.prototype._updateDecrypt
= function _updateDecrypt(data
) {
18101 var count
= Math
.ceil((this.bufferOff
+ data
.length
) / this.blockSize
) - 1;
18102 var out
= new Array(count
* this.blockSize
);
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
);
18110 // Buffer rest of the input
18111 inputOff
+= this._buffer(data
, inputOff
);
18116 Cipher
.prototype.final
= function final(buffer
) {
18119 first
= this.update(buffer
);
18122 if (this.type
=== 'encrypt')
18123 last
= this._finalEncrypt();
18125 last
= this._finalDecrypt();
18128 return first
.concat(last
);
18133 Cipher
.prototype._pad
= function _pad(buffer
, off
) {
18137 while (off
< buffer
.length
)
18143 Cipher
.prototype._finalEncrypt
= function _finalEncrypt() {
18144 if (!this._pad(this.buffer
, this.bufferOff
))
18147 var out
= new Array(this.blockSize
);
18148 this._update(this.buffer
, 0, out
, 0);
18152 Cipher
.prototype._unpad
= function _unpad(buffer
) {
18156 Cipher
.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);
18161 return this._unpad(out
);
18164 },{"minimalistic-assert":176}],120:[function(require
,module
,exports
){
18167 var assert
= require('minimalistic-assert');
18168 var inherits
= require('inherits');
18170 var des
= require('../des');
18171 var utils
= des
.utils
;
18172 var Cipher
= des
.Cipher
;
18174 function DESState() {
18175 this.tmp
= new Array(2);
18179 function DES(options
) {
18180 Cipher
.call(this, options
);
18182 var state
= new DESState();
18183 this._desState
= state
;
18185 this.deriveKeys(state
, options
.key
);
18187 inherits(DES
, Cipher
);
18188 module
.exports
= DES
;
18190 DES
.create
= function create(options
) {
18191 return new DES(options
);
18195 1, 1, 2, 2, 2, 2, 2, 2,
18196 1, 2, 2, 2, 2, 2, 2, 1
18199 DES
.prototype.deriveKeys
= function deriveKeys(state
, key
) {
18200 state
.keys
= new Array(16 * 2);
18202 assert
.equal(key
.length
, this.blockSize
, 'Invalid key length');
18204 var kL
= utils
.readUInt32BE(key
, 0);
18205 var kR
= utils
.readUInt32BE(key
, 4);
18207 utils
.pc1(kL
, kR
, state
.tmp
, 0);
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
);
18218 DES
.prototype._update
= function _update(inp
, inOff
, out
, outOff
) {
18219 var state
= this._desState
;
18221 var l
= utils
.readUInt32BE(inp
, inOff
);
18222 var r
= utils
.readUInt32BE(inp
, inOff
+ 4);
18224 // Initial Permutation
18225 utils
.ip(l
, r
, state
.tmp
, 0);
18229 if (this.type
=== 'encrypt')
18230 this._encrypt(state
, l
, r
, state
.tmp
, 0);
18232 this._decrypt(state
, l
, r
, state
.tmp
, 0);
18237 utils
.writeUInt32BE(out
, l
, outOff
);
18238 utils
.writeUInt32BE(out
, r
, outOff
+ 4);
18241 DES
.prototype._pad
= function _pad(buffer
, off
) {
18242 var value
= buffer
.length
- off
;
18243 for (var i
= off
; i
< buffer
.length
; i
++)
18249 DES
.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
);
18254 return buffer
.slice(0, buffer
.length
- pad
);
18257 DES
.prototype._encrypt
= function _encrypt(state
, lStart
, rStart
, out
, off
) {
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];
18267 utils
.expand(r
, state
.tmp
, 0);
18269 keyL
^= state
.tmp
[0];
18270 keyR
^= state
.tmp
[1];
18271 var s
= utils
.substitute(keyL
, keyR
);
18272 var f
= utils
.permute(s
);
18279 // Reverse Initial Permutation
18280 utils
.rip(r
, l
, out
, off
);
18283 DES
.prototype._decrypt
= function _decrypt(state
, lStart
, rStart
, out
, off
) {
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];
18293 utils
.expand(l
, state
.tmp
, 0);
18295 keyL
^= state
.tmp
[0];
18296 keyR
^= state
.tmp
[1];
18297 var s
= utils
.substitute(keyL
, keyR
);
18298 var f
= utils
.permute(s
);
18305 // Reverse Initial Permutation
18306 utils
.rip(l
, r
, out
, off
);
18309 },{"../des":117,"inherits":163,"minimalistic-assert":176}],121:[function(require
,module
,exports
){
18312 var assert
= require('minimalistic-assert');
18313 var inherits
= require('inherits');
18315 var des
= require('../des');
18316 var Cipher
= des
.Cipher
;
18319 function EDEState(type
, key
) {
18320 assert
.equal(key
.length
, 24, 'Invalid key length');
18322 var k1
= key
.slice(0, 8);
18323 var k2
= key
.slice(8, 16);
18324 var k3
= key
.slice(16, 24);
18326 if (type
=== 'encrypt') {
18328 DES
.create({ type: 'encrypt', key: k1
}),
18329 DES
.create({ type: 'decrypt', key: k2
}),
18330 DES
.create({ type: 'encrypt', key: k3
})
18334 DES
.create({ type: 'decrypt', key: k3
}),
18335 DES
.create({ type: 'encrypt', key: k2
}),
18336 DES
.create({ type: 'decrypt', key: k1
})
18341 function EDE(options
) {
18342 Cipher
.call(this, options
);
18344 var state
= new EDEState(this.type
, this.options
.key
);
18345 this._edeState
= state
;
18347 inherits(EDE
, Cipher
);
18349 module
.exports
= EDE
;
18351 EDE
.create
= function create(options
) {
18352 return new EDE(options
);
18355 EDE
.prototype._update
= function _update(inp
, inOff
, out
, outOff
) {
18356 var state
= this._edeState
;
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
);
18363 EDE
.prototype._pad
= DES
.prototype._pad
;
18364 EDE
.prototype._unpad
= DES
.prototype._unpad
;
18366 },{"../des":117,"inherits":163,"minimalistic-assert":176}],122:[function(require
,module
,exports
){
18369 exports
.readUInt32BE
= function readUInt32BE(bytes
, off
) {
18370 var res
= (bytes
[0 + off
] << 24) |
18371 (bytes
[1 + off
] << 16) |
18372 (bytes
[2 + off
] << 8) |
18377 exports
.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;
18384 exports
.ip
= function ip(inL
, inR
, out
, off
) {
18388 for (var i
= 6; i
>= 0; i
-= 2) {
18389 for (var j
= 0; j
<= 24; j
+= 8) {
18391 outL
|= (inR
>>> (j
+ i
)) & 1;
18393 for (var j
= 0; j
<= 24; j
+= 8) {
18395 outL
|= (inL
>>> (j
+ i
)) & 1;
18399 for (var i
= 6; i
>= 0; i
-= 2) {
18400 for (var j
= 1; j
<= 25; j
+= 8) {
18402 outR
|= (inR
>>> (j
+ i
)) & 1;
18404 for (var j
= 1; j
<= 25; j
+= 8) {
18406 outR
|= (inL
>>> (j
+ i
)) & 1;
18410 out
[off
+ 0] = outL
>>> 0;
18411 out
[off
+ 1] = outR
>>> 0;
18414 exports
.rip
= function rip(inL
, inR
, out
, off
) {
18418 for (var i
= 0; i
< 4; i
++) {
18419 for (var j
= 24; j
>= 0; j
-= 8) {
18421 outL
|= (inR
>>> (j
+ i
)) & 1;
18423 outL
|= (inL
>>> (j
+ i
)) & 1;
18426 for (var i
= 4; i
< 8; i
++) {
18427 for (var j
= 24; j
>= 0; j
-= 8) {
18429 outR
|= (inR
>>> (j
+ i
)) & 1;
18431 outR
|= (inL
>>> (j
+ i
)) & 1;
18435 out
[off
+ 0] = outL
>>> 0;
18436 out
[off
+ 1] = outR
>>> 0;
18439 exports
.pc1
= function pc1(inL
, inR
, out
, off
) {
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
18447 for (var i
= 7; i
>= 5; i
--) {
18448 for (var j
= 0; j
<= 24; j
+= 8) {
18450 outL
|= (inR
>> (j
+ i
)) & 1;
18452 for (var j
= 0; j
<= 24; j
+= 8) {
18454 outL
|= (inL
>> (j
+ i
)) & 1;
18457 for (var j
= 0; j
<= 24; j
+= 8) {
18459 outL
|= (inR
>> (j
+ i
)) & 1;
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
18466 for (var i
= 1; i
<= 3; i
++) {
18467 for (var j
= 0; j
<= 24; j
+= 8) {
18469 outR
|= (inR
>> (j
+ i
)) & 1;
18471 for (var j
= 0; j
<= 24; j
+= 8) {
18473 outR
|= (inL
>> (j
+ i
)) & 1;
18476 for (var j
= 0; j
<= 24; j
+= 8) {
18478 outR
|= (inL
>> (j
+ i
)) & 1;
18481 out
[off
+ 0] = outL
>>> 0;
18482 out
[off
+ 1] = outR
>>> 0;
18485 exports
.r28shl
= function r28shl(num
, shift
) {
18486 return ((num
<< shift
) & 0xfffffff) | (num
>>> (28 - shift
));
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,
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
18501 exports
.pc2
= function pc2(inL
, inR
, out
, off
) {
18505 var len
= pc2table
.length
>>> 1;
18506 for (var i
= 0; i
< len
; i
++) {
18508 outL
|= (inL
>>> pc2table
[i
]) & 0x1;
18510 for (var i
= len
; i
< pc2table
.length
; i
++) {
18512 outR
|= (inR
>>> pc2table
[i
]) & 0x1;
18515 out
[off
+ 0] = outL
>>> 0;
18516 out
[off
+ 1] = outR
>>> 0;
18519 exports
.expand
= function expand(r
, out
, off
) {
18523 outL
= ((r
& 1) << 5) | (r
>>> 27);
18524 for (var i
= 23; i
>= 15; i
-= 4) {
18526 outL
|= (r
>>> i
) & 0x3f;
18528 for (var i
= 11; i
>= 3; i
-= 4) {
18529 outR
|= (r
>>> i
) & 0x3f;
18532 outR
|= ((r
& 0x1f) << 1) | (r
>>> 31);
18534 out
[off
+ 0] = outL
>>> 0;
18535 out
[off
+ 1] = outR
>>> 0;
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,
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,
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,
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,
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,
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,
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,
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
18580 exports
.substitute
= function substitute(inL
, inR
) {
18582 for (var i
= 0; i
< 4; i
++) {
18583 var b
= (inL
>>> (18 - i
* 6)) & 0x3f;
18584 var sb
= sTable
[i
* 0x40 + b
];
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
];
18599 var 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
18604 exports
.permute
= function permute(num
) {
18606 for (var i
= 0; i
< permuteTable
.length
; i
++) {
18608 out
|= (num
>>> permuteTable
[i
]) & 0x1;
18613 exports
.padSplit
= function padSplit(num
, size
, group
) {
18614 var str
= num
.toString(2);
18615 while (str
.length
< size
)
18619 for (var i
= 0; i
< size
; i
+= group
)
18620 out
.push(str
.slice(i
, i
+ group
));
18621 return out
.join(' ');
18624 },{}],123:[function(require
,module
,exports
){
18625 (function (Buffer
){
18626 var generatePrime
= require('./lib/generatePrime')
18627 var primes
= require('./lib/primes.json')
18629 var DH
= require('./lib/dh')
18631 function getDiffieHellman (mod
) {
18632 var prime
= new Buffer(primes
[mod
].prime
, 'hex')
18633 var gen
= new Buffer(primes
[mod
].gen
, 'hex')
18635 return new DH(prime
, gen
)
18639 'binary': true, 'hex': true, 'base64': true
18642 function createDiffieHellman (prime
, enc
, generator
, genc
) {
18643 if (Buffer
.isBuffer(enc
) || ENCODINGS
[enc
] === undefined) {
18644 return createDiffieHellman(prime
, 'binary', enc
, generator
)
18647 enc
= enc
|| 'binary'
18648 genc
= genc
|| 'binary'
18649 generator
= generator
|| new Buffer([2])
18651 if (!Buffer
.isBuffer(generator
)) {
18652 generator
= new Buffer(generator
, genc
)
18655 if (typeof prime
=== 'number') {
18656 return new DH(generatePrime(prime
, generator
), generator
, true)
18659 if (!Buffer
.isBuffer(prime
)) {
18660 prime
= new Buffer(prime
, enc
)
18663 return new DH(prime
, generator
, true)
18666 exports
.DiffieHellmanGroup
= exports
.createDiffieHellmanGroup
= exports
.getDiffieHellman
= getDiffieHellman
18667 exports
.createDiffieHellman
= exports
.DiffieHellman
= createDiffieHellman
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
){
18672 var BN
= require('bn.js');
18673 var MillerRabin
= require('miller-rabin');
18674 var millerRabin
= new MillerRabin();
18675 var TWENTYFOUR
= new BN(24);
18676 var ELEVEN
= new BN(11);
18677 var TEN
= new BN(10);
18678 var THREE
= new BN(3);
18679 var SEVEN
= new BN(7);
18680 var primes
= require('./generatePrime');
18681 var randomBytes
= require('randombytes');
18682 module
.exports
= DH
;
18684 function setPublicKey(pub
, enc
) {
18685 enc
= enc
|| 'utf8';
18686 if (!Buffer
.isBuffer(pub
)) {
18687 pub
= new Buffer(pub
, enc
);
18689 this._pub
= new BN(pub
);
18693 function setPrivateKey(priv
, enc
) {
18694 enc
= enc
|| 'utf8';
18695 if (!Buffer
.isBuffer(priv
)) {
18696 priv
= new Buffer(priv
, enc
);
18698 this._priv
= new BN(priv
);
18702 var primeCache
= {};
18703 function 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
];
18711 if (prime
.isEven() ||
18712 !primes
.simpleSieve
||
18713 !primes
.fermatTest(prime
) ||
18714 !millerRabin
.test(prime
)) {
18715 //not a prime so +1
18718 if (gen
=== '02' || gen
=== '05') {
18719 // we'd be able to check the generator
18720 // it would fail so +8
18723 //we wouldn't be able to test the generator
18727 primeCache
[hex
] = error
;
18730 if (!millerRabin
.test(prime
.shrn(1))) {
18737 if (prime
.mod(TWENTYFOUR
).cmp(ELEVEN
)) {
18738 // unsuidable generator
18743 rem
= prime
.mod(TEN
);
18744 if (rem
.cmp(THREE
) && rem
.cmp(SEVEN
)) {
18745 // prime mod 10 needs to equal 3 or 7
18752 primeCache
[hex
] = error
;
18756 function 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;
18765 this.setPublicKey
= setPublicKey
;
18766 this.setPrivateKey
= setPrivateKey
;
18768 this._primeCode
= 8;
18771 Object
.defineProperty(DH
.prototype, 'verifyError', {
18774 if (typeof this._primeCode
!== 'number') {
18775 this._primeCode
= checkPrime(this.__prime
, this.__gen
);
18777 return this._primeCode
;
18780 DH
.prototype.generateKeys = function () {
18782 this._priv
= new BN(randomBytes(this._primeLen
));
18784 this._pub
= this._gen
.toRed(this._prime
).redPow(this._priv
).fromRed();
18785 return this.getPublicKey();
18788 DH
.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
);
18797 out
= Buffer
.concat([front
, out
]);
18802 DH
.prototype.getPublicKey
= function getPublicKey(enc
) {
18803 return formatReturnValue(this._pub
, enc
);
18806 DH
.prototype.getPrivateKey
= function getPrivateKey(enc
) {
18807 return formatReturnValue(this._priv
, enc
);
18810 DH
.prototype.getPrime = function (enc
) {
18811 return formatReturnValue(this.__prime
, enc
);
18814 DH
.prototype.getGenerator = function (enc
) {
18815 return formatReturnValue(this._gen
, enc
);
18818 DH
.prototype.setGenerator = function (gen
, enc
) {
18819 enc
= enc
|| 'utf8';
18820 if (!Buffer
.isBuffer(gen
)) {
18821 gen
= new Buffer(gen
, enc
);
18824 this._gen
= new BN(gen
);
18828 function formatReturnValue(bn
, enc
) {
18829 var buf
= new Buffer(bn
.toArray());
18833 return buf
.toString(enc
);
18837 }).call(this,require("buffer").Buffer
)
18838 },{"./generatePrime":125,"bn.js":75,"buffer":107,"miller-rabin":175,"randombytes":231}],125:[function(require
,module
,exports
){
18839 var randomBytes
= require('randombytes');
18840 module
.exports
= findPrime
;
18841 findPrime
.simpleSieve
= simpleSieve
;
18842 findPrime
.fermatTest
= fermatTest
;
18843 var BN
= require('bn.js');
18844 var TWENTYFOUR
= new BN(24);
18845 var MillerRabin
= require('miller-rabin');
18846 var millerRabin
= new MillerRabin();
18847 var ONE
= new BN(1);
18848 var TWO
= new BN(2);
18849 var FIVE
= new BN(5);
18850 var SIXTEEN
= new BN(16);
18851 var EIGHT
= new BN(8);
18852 var TEN
= new BN(10);
18853 var THREE
= new BN(3);
18854 var SEVEN
= new BN(7);
18855 var ELEVEN
= new BN(11);
18856 var FOUR
= new BN(4);
18857 var TWELVE
= new BN(12);
18860 function _getPrimes() {
18861 if (primes
!== null)
18864 var limit
= 0x100000;
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)
18873 if (i
!== j
&& res
[j
] <= sqrt
)
18882 function simpleSieve(p
) {
18883 var primes
= _getPrimes();
18885 for (var i
= 0; i
< primes
.length
; i
++)
18886 if (p
.modn(primes
[i
]) === 0) {
18887 if (p
.cmpn(primes
[i
]) === 0) {
18897 function fermatTest(p
) {
18898 var red
= BN
.mont(p
);
18899 return TWO
.toRed(red
).redPow(p
.subn(1)).fromRed().cmpn(1) === 0;
18902 function findPrime(bits
, gen
) {
18904 // this is what openssl does
18905 if (gen
=== 2 || gen
=== 5) {
18906 return new BN([0x8c, 0x7b]);
18908 return new BN([0x8c, 0x27]);
18916 num
= new BN(randomBytes(Math
.ceil(bits
/ 8)));
18917 while (num
.bitLength() > bits
) {
18920 if (num
.isEven()) {
18923 if (!num
.testn(1)) {
18926 if (!gen
.cmp(TWO
)) {
18927 while (num
.mod(TWENTYFOUR
).cmp(ELEVEN
)) {
18930 } else if (!gen
.cmp(FIVE
)) {
18931 while (num
.mod(TEN
).cmp(THREE
)) {
18936 if (simpleSieve(n2
) && simpleSieve(num
) &&
18937 fermatTest(n2
) && fermatTest(num
) &&
18938 millerRabin
.test(n2
) && millerRabin
.test(num
)) {
18945 },{"bn.js":75,"miller-rabin":175,"randombytes":231}],126:[function(require
,module
,exports
){
18949 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff"
18953 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff"
18957 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff"
18961 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff"
18965 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff"
18969 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff"
18973 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff"
18977 "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff"
18980 },{}],127:[function(require
,module
,exports
){
18983 var elliptic
= exports
;
18985 elliptic
.version
= require('../package.json').version
;
18986 elliptic
.utils
= require('./elliptic/utils');
18987 elliptic
.rand
= require('brorand');
18988 elliptic
.curve
= require('./elliptic/curve');
18989 elliptic
.curves
= require('./elliptic/curves');
18992 elliptic
.ec
= require('./elliptic/ec');
18993 elliptic
.eddsa
= require('./elliptic/eddsa');
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
){
18998 var BN
= require('bn.js');
18999 var elliptic
= require('../../elliptic');
19000 var utils
= elliptic
.utils
;
19001 var getNAF
= utils
.getNAF
;
19002 var getJSF
= utils
.getJSF
;
19003 var assert
= utils
.assert
;
19005 function BaseCurve(type
, conf
) {
19007 this.p
= new BN(conf
.p
, 16);
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
);
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
);
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
);
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);
19027 // Generalized Greg Maxwell's trick
19028 var adjustCount
= this.n
&& this.p
.div(this.n
);
19029 if (!adjustCount
|| adjustCount
.cmpn(100) > 0) {
19032 this._maxwellTrick
= true;
19033 this.redN
= this.n
.toRed(this.red
);
19036 module
.exports
= BaseCurve
;
19038 BaseCurve
.prototype.point
= function point() {
19039 throw new Error('Not implemented');
19042 BaseCurve
.prototype.validate
= function validate() {
19043 throw new Error('Not implemented');
19046 BaseCurve
.prototype._fixedNafMul
= function _fixedNafMul(p
, k
) {
19047 assert(p
.precomputed
);
19048 var doubles
= p
._getDoubles();
19050 var naf
= getNAF(k
, 1);
19051 var I
= (1 << (doubles
.step
+ 1)) - (doubles
.step
% 2 === 0 ? 2 : 1);
19054 // Translate into more windowed form
19056 for (var j
= 0; j
< naf
.length
; j
+= doubles
.step
) {
19058 for (var k
= j
+ doubles
.step
- 1; k
>= j
; k
--)
19059 nafW
= (nafW
<< 1) + naf
[k
];
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
];
19069 b
= b
.mixedAdd(doubles
.points
[j
]);
19070 else if (nafW
=== -i
)
19071 b
= b
.mixedAdd(doubles
.points
[j
].neg());
19078 BaseCurve
.prototype._wnafMul
= function _wnafMul(p
, k
) {
19081 // Precompute window
19082 var nafPoints
= p
._getNAFPoints(w
);
19084 var wnd
= nafPoints
.points
;
19087 var naf
= getNAF(k
, w
);
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
--) {
19093 for (var k
= 0; i
>= 0 && naf
[i
] === 0; i
--)
19103 if (p
.type
=== 'affine') {
19106 acc
= acc
.mixedAdd(wnd
[(z
- 1) >> 1]);
19108 acc
= acc
.mixedAdd(wnd
[(-z
- 1) >> 1].neg());
19112 acc
= acc
.add(wnd
[(z
- 1) >> 1]);
19114 acc
= acc
.add(wnd
[(-z
- 1) >> 1].neg());
19117 return p
.type
=== 'affine' ? acc
.toP() : acc
;
19120 BaseCurve
.prototype._wnafMulAdd
= function _wnafMulAdd(defW
,
19125 var wndWidth
= this._wnafT1
;
19126 var wnd
= this._wnafT2
;
19127 var naf
= this._wnafT3
;
19131 for (var i
= 0; i
< len
; i
++) {
19133 var nafPoints
= p
._getNAFPoints(defW
);
19134 wndWidth
[i
] = nafPoints
.wnd
;
19135 wnd
[i
] = nafPoints
.points
;
19138 // Comb small window NAFs
19139 for (var i
= len
- 1; i
>= 1; i
-= 2) {
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
);
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());
19165 comb
[1] = points
[a
].toJ().mixedAdd(points
[b
]);
19166 comb
[2] = points
[a
].toJ().mixedAdd(points
[b
].neg());
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;
19189 naf
[a
][j
] = index
[(ja
+ 1) * 3 + (jb
+ 1)];
19195 var acc
= this.jpoint(null, null, null);
19196 var tmp
= this._wnafT4
;
19197 for (var i
= max
; i
>= 0; i
--) {
19202 for (var j
= 0; j
< len
; j
++) {
19203 tmp
[j
] = naf
[j
][i
] | 0;
19218 for (var j
= 0; j
< len
; j
++) {
19224 p
= wnd
[j
][(z
- 1) >> 1];
19226 p
= wnd
[j
][(-z
- 1) >> 1].neg();
19228 if (p
.type
=== 'affine')
19229 acc
= acc
.mixedAdd(p
);
19234 // Zeroify references
19235 for (var i
= 0; i
< len
; i
++)
19238 if (jacobianResult
)
19244 function BasePoint(curve
, type
) {
19245 this.curve
= curve
;
19247 this.precomputed
= null;
19249 BaseCurve
.BasePoint
= BasePoint
;
19251 BasePoint
.prototype.eq
= function eq(/*other*/) {
19252 throw new Error('Not implemented');
19255 BasePoint
.prototype.validate
= function validate() {
19256 return this.curve
.validate(this);
19259 BaseCurve
.prototype.decodePoint
= function decodePoint(bytes
, enc
) {
19260 bytes
= utils
.toArray(bytes
, enc
);
19262 var len
= this.p
.byteLength();
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);
19272 var res
= this.point(bytes
.slice(1, 1 + len
),
19273 bytes
.slice(1 + len
, 1 + 2 * len
));
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);
19280 throw new Error('Unknown point format');
19283 BasePoint
.prototype.encodeCompressed
= function encodeCompressed(enc
) {
19284 return this.encode(enc
, true);
19287 BasePoint
.prototype._encode
= function _encode(compact
) {
19288 var len
= this.curve
.p
.byteLength();
19289 var x
= this.getX().toArray('be', len
);
19292 return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x
);
19294 return [ 0x04 ].concat(x
, this.getY().toArray('be', len
)) ;
19297 BasePoint
.prototype.encode
= function encode(enc
, compact
) {
19298 return utils
.encode(this._encode(compact
), enc
);
19301 BasePoint
.prototype.precompute
= function precompute(power
) {
19302 if (this.precomputed
)
19305 var precomputed
= {
19310 precomputed
.naf
= this._getNAFPoints(8);
19311 precomputed
.doubles
= this._getDoubles(4, power
);
19312 precomputed
.beta
= this._getBeta();
19313 this.precomputed
= precomputed
;
19318 BasePoint
.prototype._hasDoubles
= function _hasDoubles(k
) {
19319 if (!this.precomputed
)
19322 var doubles
= this.precomputed
.doubles
;
19326 return doubles
.points
.length
>= Math
.ceil((k
.bitLength() + 1) / doubles
.step
);
19329 BasePoint
.prototype._getDoubles
= function _getDoubles(step
, power
) {
19330 if (this.precomputed
&& this.precomputed
.doubles
)
19331 return this.precomputed
.doubles
;
19333 var doubles
= [ this ];
19335 for (var i
= 0; i
< power
; i
+= step
) {
19336 for (var j
= 0; j
< step
; j
++)
19346 BasePoint
.prototype._getNAFPoints
= function _getNAFPoints(wnd
) {
19347 if (this.precomputed
&& this.precomputed
.naf
)
19348 return this.precomputed
.naf
;
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
);
19361 BasePoint
.prototype._getBeta
= function _getBeta() {
19365 BasePoint
.prototype.dblp
= function dblp(k
) {
19367 for (var i
= 0; i
< k
; i
++)
19372 },{"../../elliptic":127,"bn.js":75}],129:[function(require
,module
,exports
){
19375 var curve
= require('../curve');
19376 var elliptic
= require('../../elliptic');
19377 var BN
= require('bn.js');
19378 var inherits
= require('inherits');
19379 var Base
= curve
.base
;
19381 var assert
= elliptic
.utils
.assert
;
19383 function 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
;
19389 Base
.call(this, 'edwards', conf
);
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
);
19398 assert(!this.twisted
|| this.c
.fromRed().cmpn(1) === 0);
19399 this.oneC
= (conf
.c
| 0) === 1;
19401 inherits(EdwardsCurve
, Base
);
19402 module
.exports
= EdwardsCurve
;
19404 EdwardsCurve
.prototype._mulA
= function _mulA(num
) {
19406 return num
.redNeg();
19408 return this.a
.redMul(num
);
19411 EdwardsCurve
.prototype._mulC
= function _mulC(num
) {
19415 return this.c
.redMul(num
);
19418 // Just for compatibility with Short curve
19419 EdwardsCurve
.prototype.jpoint
= function jpoint(x
, y
, z
, t
) {
19420 return this.point(x
, y
, z
, t
);
19423 EdwardsCurve
.prototype.pointFromX
= function pointFromX(x
, odd
) {
19426 x
= x
.toRed(this.red
);
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
));
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');
19437 var isOdd
= y
.fromRed().isOdd();
19438 if (odd
&& !isOdd
|| !odd
&& isOdd
)
19441 return this.point(x
, y
);
19444 EdwardsCurve
.prototype.pointFromY
= function pointFromY(y
, odd
) {
19447 y
= y
.toRed(this.red
);
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());
19455 if (x2
.cmp(this.zero
) === 0) {
19457 throw new Error('invalid point');
19459 return this.point(this.zero
, y
);
19462 var x
= x2
.redSqrt();
19463 if (x
.redSqr().redSub(x2
).cmp(this.zero
) !== 0)
19464 throw new Error('invalid point');
19466 if (x
.isOdd() !== odd
)
19469 return this.point(x
, y
);
19472 EdwardsCurve
.prototype.validate
= function validate(point
) {
19473 if (point
.isInfinity())
19476 // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2)
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
)));
19484 return lhs
.cmp(rhs
) === 0;
19487 function 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
;
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);
19501 this.x
= this.x
.toRed(this.curve
.red
);
19503 this.y
= this.y
.toRed(this.curve
.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
;
19510 // Use extended coordinates
19511 if (this.curve
.extended
&& !this.t
) {
19512 this.t
= this.x
.redMul(this.y
);
19514 this.t
= this.t
.redMul(this.z
.redInvm());
19518 inherits(Point
, Base
.BasePoint
);
19520 EdwardsCurve
.prototype.pointFromJSON
= function pointFromJSON(obj
) {
19521 return Point
.fromJSON(this, obj
);
19524 EdwardsCurve
.prototype.point
= function point(x
, y
, z
, t
) {
19525 return new Point(this, x
, y
, z
, t
);
19528 Point
.fromJSON
= function fromJSON(curve
, obj
) {
19529 return new Point(curve
, obj
[0], obj
[1], obj
[2]);
19532 Point
.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) + '>';
19540 Point
.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;
19546 Point
.prototype._extDbl
= function _extDbl() {
19547 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
19548 // #doubling-dbl-2008-hwcd
19552 var a
= this.x
.redSqr();
19554 var b
= this.y
.redSqr();
19556 var c
= this.z
.redSqr();
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
);
19563 var g
= d
.redAdd(b
);
19565 var f
= g
.redSub(c
);
19567 var h
= d
.redSub(b
);
19569 var nx
= e
.redMul(f
);
19571 var ny
= g
.redMul(h
);
19573 var nt
= e
.redMul(h
);
19575 var nz
= f
.redMul(g
);
19576 return this.curve
.point(nx
, ny
, nz
, nt
);
19579 Point
.prototype._projDbl
= function _projDbl() {
19580 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
19581 // #doubling-dbl-2008-bbjlp
19582 // #doubling-dbl-2007-bl
19584 // Generally 3M + 4S or 2M + 4S
19587 var b
= this.x
.redAdd(this.y
).redSqr();
19589 var c
= this.x
.redSqr();
19591 var d
= this.y
.redSqr();
19596 if (this.curve
.twisted
) {
19598 var e
= this.curve
._mulA(c
);
19600 var f
= e
.redAdd(d
);
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
);
19610 var h
= this.z
.redSqr();
19612 var j
= f
.redSub(h
).redISub(h
);
19614 nx
= b
.redSub(c
).redISub(d
).redMul(j
);
19615 // Y3 = F * (E - D)
19616 ny
= f
.redMul(e
.redSub(d
));
19622 var e
= c
.redAdd(d
);
19624 var h
= this.curve
._mulC(this.c
.redMul(this.z
)).redSqr();
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
));
19634 return this.curve
.point(nx
, ny
, nz
);
19637 Point
.prototype.dbl
= function dbl() {
19638 if (this.isInfinity())
19641 // Double in extended coordinates
19642 if (this.curve
.extended
)
19643 return this._extDbl();
19645 return this._projDbl();
19648 Point
.prototype._extAdd
= function _extAdd(p
) {
19649 // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html
19650 // #addition-add-2008-hwcd-3
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
));
19658 var c
= this.t
.redMul(this.curve
.dd
).redMul(p
.t
);
19660 var d
= this.z
.redMul(p
.z
.redAdd(p
.z
));
19662 var e
= b
.redSub(a
);
19664 var f
= d
.redSub(c
);
19666 var g
= d
.redAdd(c
);
19668 var h
= b
.redAdd(a
);
19670 var nx
= e
.redMul(f
);
19672 var ny
= g
.redMul(h
);
19674 var nt
= e
.redMul(h
);
19676 var nz
= f
.redMul(g
);
19677 return this.curve
.point(nx
, ny
, nz
, nt
);
19680 Point
.prototype._projAdd
= function _projAdd(p
) {
19681 // hyperelliptic.org/EFD/g1p/auto-twisted-projective.html
19682 // #addition-add-2008-bbjlp
19683 // #addition-add-2007-bl
19687 var a
= this.z
.redMul(p
.z
);
19689 var b
= a
.redSqr();
19691 var c
= this.x
.redMul(p
.x
);
19693 var d
= this.y
.redMul(p
.y
);
19695 var e
= this.curve
.d
.redMul(c
).redMul(d
);
19697 var f
= b
.redSub(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
);
19705 if (this.curve
.twisted
) {
19706 // Y3 = A * G * (D - a * C)
19707 ny
= a
.redMul(g
).redMul(d
.redSub(this.curve
._mulA(c
)));
19711 // Y3 = A * G * (D - C)
19712 ny
= a
.redMul(g
).redMul(d
.redSub(c
));
19714 nz
= this.curve
._mulC(f
).redMul(g
);
19716 return this.curve
.point(nx
, ny
, nz
);
19719 Point
.prototype.add
= function add(p
) {
19720 if (this.isInfinity())
19722 if (p
.isInfinity())
19725 if (this.curve
.extended
)
19726 return this._extAdd(p
);
19728 return this._projAdd(p
);
19731 Point
.prototype.mul
= function mul(k
) {
19732 if (this._hasDoubles(k
))
19733 return this.curve
._fixedNafMul(this, k
);
19735 return this.curve
._wnafMul(this, k
);
19738 Point
.prototype.mulAdd
= function mulAdd(k1
, p
, k2
) {
19739 return this.curve
._wnafMulAdd(1, [ this, p
], [ k1
, k2
], 2, false);
19742 Point
.prototype.jmulAdd
= function jmulAdd(k1
, p
, k2
) {
19743 return this.curve
._wnafMulAdd(1, [ this, p
], [ k1
, k2
], 2, true);
19746 Point
.prototype.normalize
= function normalize() {
19750 // Normalize coordinates
19751 var zi
= this.z
.redInvm();
19752 this.x
= this.x
.redMul(zi
);
19753 this.y
= this.y
.redMul(zi
);
19755 this.t
= this.t
.redMul(zi
);
19756 this.z
= this.curve
.one
;
19761 Point
.prototype.neg
= function neg() {
19762 return this.curve
.point(this.x
.redNeg(),
19765 this.t
&& this.t
.redNeg());
19768 Point
.prototype.getX
= function getX() {
19770 return this.x
.fromRed();
19773 Point
.prototype.getY
= function getY() {
19775 return this.y
.fromRed();
19778 Point
.prototype.eq
= function eq(other
) {
19779 return this === other
||
19780 this.getX().cmp(other
.getX()) === 0 &&
19781 this.getY().cmp(other
.getY()) === 0;
19784 Point
.prototype.eqXToP
= function eqXToP(x
) {
19785 var rx
= x
.toRed(this.curve
.red
).redMul(this.z
);
19786 if (this.x
.cmp(rx
) === 0)
19789 var xc
= x
.clone();
19790 var t
= this.curve
.redN
.redMul(this.z
);
19792 xc
.iadd(this.curve
.n
);
19793 if (xc
.cmp(this.curve
.p
) >= 0)
19797 if (this.x
.cmp(rx
) === 0)
19803 // Compatibility with BaseCurve
19804 Point
.prototype.toP
= Point
.prototype.normalize
;
19805 Point
.prototype.mixedAdd
= Point
.prototype.add
;
19807 },{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],130:[function(require
,module
,exports
){
19810 var curve
= exports
;
19812 curve
.base
= require('./base');
19813 curve
.short = require('./short');
19814 curve
.mont
= require('./mont');
19815 curve
.edwards
= require('./edwards');
19817 },{"./base":128,"./edwards":129,"./mont":131,"./short":132}],131:[function(require
,module
,exports
){
19820 var curve
= require('../curve');
19821 var BN
= require('bn.js');
19822 var inherits
= require('inherits');
19823 var Base
= curve
.base
;
19825 var elliptic
= require('../../elliptic');
19826 var utils
= elliptic
.utils
;
19828 function MontCurve(conf
) {
19829 Base
.call(this, 'mont', conf
);
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
));
19837 inherits(MontCurve
, Base
);
19838 module
.exports
= MontCurve
;
19840 MontCurve
.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();
19846 return y
.redSqr().cmp(rhs
) === 0;
19849 function 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
;
19855 this.x
= new BN(x
, 16);
19856 this.z
= new BN(z
, 16);
19858 this.x
= this.x
.toRed(this.curve
.red
);
19860 this.z
= this.z
.toRed(this.curve
.red
);
19863 inherits(Point
, Base
.BasePoint
);
19865 MontCurve
.prototype.decodePoint
= function decodePoint(bytes
, enc
) {
19866 return this.point(utils
.toArray(bytes
, enc
), 1);
19869 MontCurve
.prototype.point
= function point(x
, z
) {
19870 return new Point(this, x
, z
);
19873 MontCurve
.prototype.pointFromJSON
= function pointFromJSON(obj
) {
19874 return Point
.fromJSON(this, obj
);
19877 Point
.prototype.precompute
= function precompute() {
19881 Point
.prototype._encode
= function _encode() {
19882 return this.getX().toArray('be', this.curve
.p
.byteLength());
19885 Point
.fromJSON
= function fromJSON(curve
, obj
) {
19886 return new Point(curve
, obj
[0], obj
[1] || curve
.one
);
19889 Point
.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) + '>';
19896 Point
.prototype.isInfinity
= function isInfinity() {
19897 // XXX This code assumes that zero is always zero in red
19898 return this.z
.cmpn(0) === 0;
19901 Point
.prototype.dbl
= function dbl() {
19902 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3
19906 var a
= this.x
.redAdd(this.z
);
19908 var aa
= a
.redSqr();
19910 var b
= this.x
.redSub(this.z
);
19912 var bb
= b
.redSqr();
19914 var c
= aa
.redSub(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
);
19922 Point
.prototype.add
= function add() {
19923 throw new Error('Not supported on Montgomery curve');
19926 Point
.prototype.diffAdd
= function diffAdd(p
, diff
) {
19927 // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3
19931 var a
= this.x
.redAdd(this.z
);
19933 var b
= this.x
.redSub(this.z
);
19935 var c
= p
.x
.redAdd(p
.z
);
19937 var d
= p
.x
.redSub(p
.z
);
19939 var da
= d
.redMul(a
);
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
);
19949 Point
.prototype.mul
= function mul(k
) {
19951 var a
= this; // (N / 2) * Q + Q
19952 var b
= this.curve
.point(null, null); // (N / 2) * Q
19955 for (var bits
= []; t
.cmpn(0) !== 0; t
.iushrn(1))
19956 bits
.push(t
.andln(1));
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))
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)
19974 Point
.prototype.mulAdd
= function mulAdd() {
19975 throw new Error('Not supported on Montgomery curve');
19978 Point
.prototype.jumlAdd
= function jumlAdd() {
19979 throw new Error('Not supported on Montgomery curve');
19982 Point
.prototype.eq
= function eq(other
) {
19983 return this.getX().cmp(other
.getX()) === 0;
19986 Point
.prototype.normalize
= function normalize() {
19987 this.x
= this.x
.redMul(this.z
.redInvm());
19988 this.z
= this.curve
.one
;
19992 Point
.prototype.getX
= function getX() {
19993 // Normalize coordinates
19996 return this.x
.fromRed();
19999 },{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],132:[function(require
,module
,exports
){
20002 var curve
= require('../curve');
20003 var elliptic
= require('../../elliptic');
20004 var BN
= require('bn.js');
20005 var inherits
= require('inherits');
20006 var Base
= curve
.base
;
20008 var assert
= elliptic
.utils
.assert
;
20010 function ShortCurve(conf
) {
20011 Base
.call(this, 'short', conf
);
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();
20017 this.zeroA
= this.a
.fromRed().cmpn(0) === 0;
20018 this.threeA
= this.a
.fromRed().sub(this.p
).cmpn(-3) === 0;
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);
20025 inherits(ShortCurve
, Base
);
20026 module
.exports
= ShortCurve
;
20028 ShortCurve
.prototype._getEndomorphism
= function _getEndomorphism(conf
) {
20029 // No efficient endomorphism
20030 if (!this.zeroA
|| !this.g
|| !this.n
|| this.p
.modn(3) !== 1)
20033 // Compute beta and lambda, that lambda * P = (beta * Px; Py)
20037 beta
= new BN(conf
.beta
, 16).toRed(this.red
);
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
);
20045 lambda
= new BN(conf
.lambda
, 16);
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];
20052 lambda
= lambdas
[1];
20053 assert(this.g
.mul(lambda
).x
.cmp(this.g
.x
.redMul(beta
)) === 0);
20057 // Get basis vectors, used for balanced length-two representation
20060 basis
= conf
.basis
.map(function(vec
) {
20062 a: new BN(vec
.a
, 16),
20063 b: new BN(vec
.b
, 16)
20067 basis
= this._getEndoBasis(lambda
);
20077 ShortCurve
.prototype._getEndoRoots
= function _getEndoRoots(num
) {
20078 // Find roots of for x^2 + x + 1 in F
20079 // Root = (-1 +- Sqrt(-3)) / 2
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();
20085 var s
= new BN(3).toRed(red
).redNeg().redSqrt().redMul(tinv
);
20087 var l1
= ntinv
.redAdd(s
).fromRed();
20088 var l2
= ntinv
.redSub(s
).fromRed();
20092 ShortCurve
.prototype._getEndoBasis
= function _getEndoBasis(lambda
) {
20093 // aprxSqrt >= sqrt(this.n)
20094 var aprxSqrt
= this.n
.ushrn(Math
.floor(this.n
.bitLength() / 2));
20097 // Run EGCD, until r(L + 1) < aprxSqrt
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);
20105 // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n)
20119 while (u
.cmpn(0) !== 0) {
20121 r
= v
.sub(q
.mul(u
));
20122 x
= x2
.sub(q
.mul(x1
));
20123 var y
= y2
.sub(q
.mul(y1
));
20125 if (!a1
&& r
.cmp(aprxSqrt
) < 0) {
20130 } else if (a1
&& ++i
=== 2) {
20145 var len1
= a1
.sqr().add(b1
.sqr());
20146 var len2
= a2
.sqr().add(b2
.sqr());
20147 if (len2
.cmp(len1
) >= 0) {
20168 ShortCurve
.prototype._endoSplit
= function _endoSplit(k
) {
20169 var basis
= this.endo
.basis
;
20173 var c1
= v2
.b
.mul(k
).divRound(this.n
);
20174 var c2
= v1
.b
.neg().mul(k
).divRound(this.n
);
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
);
20181 // Calculate answer
20182 var k1
= k
.sub(p1
).sub(p2
);
20183 var k2
= q1
.add(q2
).neg();
20184 return { k1: k1
, k2: k2
};
20187 ShortCurve
.prototype.pointFromX
= function pointFromX(x
, odd
) {
20190 x
= x
.toRed(this.red
);
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');
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
)
20203 return this.point(x
, y
);
20206 ShortCurve
.prototype.validate
= function validate(point
) {
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;
20218 ShortCurve
.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
]);
20225 var beta
= p
._getBeta();
20227 if (split
.k1
.negative
) {
20231 if (split
.k2
.negative
) {
20233 beta
= beta
.neg(true);
20236 npoints
[i
* 2] = p
;
20237 npoints
[i
* 2 + 1] = beta
;
20238 ncoeffs
[i
* 2] = split
.k1
;
20239 ncoeffs
[i
* 2 + 1] = split
.k2
;
20241 var res
= this._wnafMulAdd(1, npoints
, ncoeffs
, i
* 2, jacobianResult
);
20243 // Clean-up references to points and coefficients
20244 for (var j
= 0; j
< i
* 2; j
++) {
20251 function Point(curve
, x
, y
, isRed
) {
20252 Base
.BasePoint
.call(this, curve
, 'affine');
20253 if (x
=== null && y
=== null) {
20258 this.x
= new BN(x
, 16);
20259 this.y
= new BN(y
, 16);
20260 // Force redgomery representation when loading from JSON
20262 this.x
.forceRed(this.curve
.red
);
20263 this.y
.forceRed(this.curve
.red
);
20266 this.x
= this.x
.toRed(this.curve
.red
);
20268 this.y
= this.y
.toRed(this.curve
.red
);
20272 inherits(Point
, Base
.BasePoint
);
20274 ShortCurve
.prototype.point
= function point(x
, y
, isRed
) {
20275 return new Point(this, x
, y
, isRed
);
20278 ShortCurve
.prototype.pointFromJSON
= function pointFromJSON(obj
, red
) {
20279 return Point
.fromJSON(this, obj
, red
);
20282 Point
.prototype._getBeta
= function _getBeta() {
20283 if (!this.curve
.endo
)
20286 var pre
= this.precomputed
;
20287 if (pre
&& pre
.beta
)
20290 var beta
= this.curve
.point(this.x
.redMul(this.curve
.endo
.beta
), this.y
);
20292 var curve
= this.curve
;
20293 var endoMul = function(p
) {
20294 return curve
.point(p
.x
.redMul(curve
.endo
.beta
), p
.y
);
20297 beta
.precomputed
= {
20301 points: pre
.naf
.points
.map(endoMul
)
20303 doubles: pre
.doubles
&& {
20304 step: pre
.doubles
.step
,
20305 points: pre
.doubles
.points
.map(endoMul
)
20312 Point
.prototype.toJSON
= function toJSON() {
20313 if (!this.precomputed
)
20314 return [ this.x
, this.y
];
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)
20321 naf: this.precomputed
.naf
&& {
20322 wnd: this.precomputed
.naf
.wnd
,
20323 points: this.precomputed
.naf
.points
.slice(1)
20328 Point
.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
);
20335 function obj2point(obj
) {
20336 return curve
.point(obj
[0], obj
[1], red
);
20340 res
.precomputed
= {
20342 doubles: pre
.doubles
&& {
20343 step: pre
.doubles
.step
,
20344 points: [ res
].concat(pre
.doubles
.points
.map(obj2point
))
20348 points: [ res
].concat(pre
.naf
.points
.map(obj2point
))
20354 Point
.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) + '>';
20361 Point
.prototype.isInfinity
= function isInfinity() {
20365 Point
.prototype.add
= function add(p
) {
20379 if (this.neg().eq(p
))
20380 return this.curve
.point(null, null);
20383 if (this.x
.cmp(p
.x
) === 0)
20384 return this.curve
.point(null, null);
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
);
20394 Point
.prototype.dbl
= function dbl() {
20399 var ys1
= this.y
.redAdd(this.y
);
20400 if (ys1
.cmpn(0) === 0)
20401 return this.curve
.point(null, null);
20403 var a
= this.curve
.a
;
20405 var x2
= this.x
.redSqr();
20406 var dyinv
= ys1
.redInvm();
20407 var c
= x2
.redAdd(x2
).redIAdd(x2
).redIAdd(a
).redMul(dyinv
);
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
);
20414 Point
.prototype.getX
= function getX() {
20415 return this.x
.fromRed();
20418 Point
.prototype.getY
= function getY() {
20419 return this.y
.fromRed();
20422 Point
.prototype.mul
= function mul(k
) {
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
]);
20430 return this.curve
._wnafMul(this, k
);
20433 Point
.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
);
20439 return this.curve
._wnafMulAdd(1, points
, coeffs
, 2);
20442 Point
.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);
20448 return this.curve
._wnafMulAdd(1, points
, coeffs
, 2, true);
20451 Point
.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);
20457 Point
.prototype.neg
= function neg(_precompute
) {
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
) {
20467 res
.precomputed
= {
20470 points: pre
.naf
.points
.map(negate
)
20472 doubles: pre
.doubles
&& {
20473 step: pre
.doubles
.step
,
20474 points: pre
.doubles
.points
.map(negate
)
20481 Point
.prototype.toJ
= function toJ() {
20483 return this.curve
.jpoint(null, null, null);
20485 var res
= this.curve
.jpoint(this.x
, this.y
, this.curve
.one
);
20489 function 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);
20496 this.x
= new BN(x
, 16);
20497 this.y
= new BN(y
, 16);
20498 this.z
= new BN(z
, 16);
20501 this.x
= this.x
.toRed(this.curve
.red
);
20503 this.y
= this.y
.toRed(this.curve
.red
);
20505 this.z
= this.z
.toRed(this.curve
.red
);
20507 this.zOne
= this.z
=== this.curve
.one
;
20509 inherits(JPoint
, Base
.BasePoint
);
20511 ShortCurve
.prototype.jpoint
= function jpoint(x
, y
, z
) {
20512 return new JPoint(this, x
, y
, z
);
20515 JPoint
.prototype.toP
= function toP() {
20516 if (this.isInfinity())
20517 return this.curve
.point(null, null);
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
);
20524 return this.curve
.point(ax
, ay
);
20527 JPoint
.prototype.neg
= function neg() {
20528 return this.curve
.jpoint(this.x
, this.y
.redNeg(), this.z
);
20531 JPoint
.prototype.add
= function add(p
) {
20533 if (this.isInfinity())
20537 if (p
.isInfinity())
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
));
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);
20557 var h2
= h
.redSqr();
20558 var h3
= h2
.redMul(h
);
20559 var v
= u1
.redMul(h2
);
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
);
20565 return this.curve
.jpoint(nx
, ny
, nz
);
20568 JPoint
.prototype.mixedAdd
= function mixedAdd(p
) {
20570 if (this.isInfinity())
20574 if (p
.isInfinity())
20578 var z2
= this.z
.redSqr();
20580 var u2
= p
.x
.redMul(z2
);
20582 var s2
= p
.y
.redMul(z2
).redMul(this.z
);
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);
20593 var h2
= h
.redSqr();
20594 var h3
= h2
.redMul(h
);
20595 var v
= u1
.redMul(h2
);
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
);
20601 return this.curve
.jpoint(nx
, ny
, nz
);
20604 JPoint
.prototype.dblp
= function dblp(pow
) {
20607 if (this.isInfinity())
20612 if (this.curve
.zeroA
|| this.curve
.threeA
) {
20614 for (var i
= 0; i
< pow
; i
++)
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
;
20627 var jz4
= jz
.redSqr().redSqr();
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
));
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
);
20644 jz4
= jz4
.redMul(jyd4
);
20651 return this.curve
.jpoint(jx
, jyd
.redMul(tinv
), jz
);
20654 JPoint
.prototype.dbl
= function dbl() {
20655 if (this.isInfinity())
20658 if (this.curve
.zeroA
)
20659 return this._zeroDbl();
20660 else if (this.curve
.threeA
)
20661 return this._threeDbl();
20663 return this._dbl();
20666 JPoint
.prototype._zeroDbl
= function _zeroDbl() {
20672 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
20673 // #doubling-mdbl-2007-bl
20677 var xx
= this.x
.redSqr();
20679 var yy
= this.y
.redSqr();
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
);
20685 // M = 3 * XX + a; a = 0
20686 var m
= xx
.redAdd(xx
).redIAdd(xx
);
20688 var t
= m
.redSqr().redISub(s
).redISub(s
);
20691 var yyyy8
= yyyy
.redIAdd(yyyy
);
20692 yyyy8
= yyyy8
.redIAdd(yyyy8
);
20693 yyyy8
= yyyy8
.redIAdd(yyyy8
);
20697 // Y3 = M * (S - T) - 8 * YYYY
20698 ny
= m
.redMul(s
.redISub(t
)).redISub(yyyy8
);
20700 nz
= this.y
.redAdd(this.y
);
20702 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html
20703 // #doubling-dbl-2009-l
20707 var a
= this.x
.redSqr();
20709 var b
= this.y
.redSqr();
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
);
20716 var e
= a
.redAdd(a
).redIAdd(a
);
20718 var f
= e
.redSqr();
20721 var c8
= c
.redIAdd(c
);
20722 c8
= c8
.redIAdd(c8
);
20723 c8
= c8
.redIAdd(c8
);
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
);
20734 return this.curve
.jpoint(nx
, ny
, nz
);
20737 JPoint
.prototype._threeDbl
= function _threeDbl() {
20743 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html
20744 // #doubling-mdbl-2007-bl
20748 var xx
= this.x
.redSqr();
20750 var yy
= this.y
.redSqr();
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
);
20757 var m
= xx
.redAdd(xx
).redIAdd(xx
).redIAdd(this.curve
.a
);
20759 var t
= m
.redSqr().redISub(s
).redISub(s
);
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
);
20768 nz
= this.y
.redAdd(this.y
);
20770 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b
20774 var delta
= this.z
.redSqr();
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
);
20797 return this.curve
.jpoint(nx
, ny
, nz
);
20800 JPoint
.prototype._dbl
= function _dbl() {
20801 var a
= this.curve
.a
;
20807 var jz4
= jz
.redSqr().redSqr();
20809 var jx2
= jx
.redSqr();
20810 var jy2
= jy
.redSqr();
20812 var c
= jx2
.redAdd(jx2
).redIAdd(jx2
).redIAdd(a
.redMul(jz4
));
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
);
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
);
20827 return this.curve
.jpoint(nx
, ny
, nz
);
20830 JPoint
.prototype.trpl
= function trpl() {
20831 if (!this.curve
.zeroA
)
20832 return this.dbl().add(this);
20834 // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl
20838 var xx
= this.x
.redSqr();
20840 var yy
= this.y
.redSqr();
20842 var zz
= this.z
.redSqr();
20844 var yyyy
= yy
.redSqr();
20845 // M = 3 * XX + a * ZZ2; a = 0
20846 var m
= xx
.redAdd(xx
).redIAdd(xx
);
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
);
20852 e
= e
.redAdd(e
).redIAdd(e
);
20855 var ee
= e
.redSqr();
20857 var t
= yyyy
.redIAdd(yyyy
);
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
);
20878 return this.curve
.jpoint(nx
, ny
, nz
);
20881 JPoint
.prototype.mul
= function mul(k
, kbase
) {
20882 k
= new BN(k
, kbase
);
20884 return this.curve
._wnafMul(this, k
);
20887 JPoint
.prototype.eq
= function eq(p
) {
20888 if (p
.type
=== 'affine')
20889 return this.eq(p
.toJ());
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)
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;
20906 JPoint
.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)
20912 var xc
= x
.clone();
20913 var t
= this.curve
.redN
.redMul(zs
);
20915 xc
.iadd(this.curve
.n
);
20916 if (xc
.cmp(this.curve
.p
) >= 0)
20920 if (this.x
.cmp(rx
) === 0)
20926 JPoint
.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) + '>';
20934 JPoint
.prototype.isInfinity
= function isInfinity() {
20935 // XXX This code assumes that zero is always zero in red
20936 return this.z
.cmpn(0) === 0;
20939 },{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],133:[function(require
,module
,exports
){
20942 var curves
= exports
;
20944 var hash
= require('hash.js');
20945 var elliptic
= require('../elliptic');
20947 var assert
= elliptic
.utils
.assert
;
20949 function 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
);
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
;
20960 assert(this.g
.validate(), 'Invalid curve');
20961 assert(this.g
.mul(this.n
).isInfinity(), 'Invalid curve, G*N != O');
20963 curves
.PresetCurve
= PresetCurve
;
20965 function defineCurve(name
, options
) {
20966 Object
.defineProperty(curves
, name
, {
20967 configurable: true,
20970 var curve
= new PresetCurve(options
);
20971 Object
.defineProperty(curves
, name
, {
20972 configurable: true,
20981 defineCurve('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',
20991 '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012',
20992 '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811'
20996 defineCurve('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',
21006 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21',
21007 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34'
21011 defineCurve('p256', {
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',
21021 '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296',
21022 '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5'
21026 defineCurve('p384', {
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',
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'
21047 defineCurve('p521', {
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',
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'
21074 defineCurve('curve25519', {
21077 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
21080 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
21088 defineCurve('ed25519', {
21091 p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed',
21094 // -121665 * (121666^(-1)) (mod P)
21095 d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3',
21096 n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed',
21100 '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a',
21103 '6666666666666666666666666666666666666666666666666666666666666658'
21109 pre
= require('./precomputed/secp256k1');
21114 defineCurve('secp256k1', {
21117 p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f',
21120 n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141',
21124 // Precomputed endomorphism
21125 beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee',
21126 lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72',
21129 a: '3086d221a7d46bcde86c90e49284eb15',
21130 b: '-e4437ed6010e88286f547fa90abfe4c3'
21133 a: '114ca50f7a8e2f3f657c1108d9d44cfd8',
21134 b: '3086d221a7d46bcde86c90e49284eb15'
21140 '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798',
21141 '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8',
21146 },{"../elliptic":127,"./precomputed/secp256k1":140,"hash.js":147}],134:[function(require
,module
,exports
){
21149 var BN
= require('bn.js');
21150 var HmacDRBG
= require('hmac-drbg');
21151 var elliptic
= require('../../elliptic');
21152 var utils
= elliptic
.utils
;
21153 var assert
= utils
.assert
;
21155 var KeyPair
= require('./key');
21156 var Signature
= require('./signature');
21158 function EC(options
) {
21159 if (!(this instanceof EC
))
21160 return new EC(options
);
21162 // Shortcut `elliptic.ec(curve-name)`
21163 if (typeof options
=== 'string') {
21164 assert(elliptic
.curves
.hasOwnProperty(options
), 'Unknown curve ' + options
);
21166 options
= elliptic
.curves
[options
];
21169 // Shortcut for `elliptic.ec(elliptic.curves.curveName)`
21170 if (options
instanceof elliptic
.curves
.PresetCurve
)
21171 options
= { curve: options
};
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
;
21179 this.g
= options
.curve
.g
;
21180 this.g
.precompute(options
.curve
.n
.bitLength() + 1);
21182 // Hash for function for DRBG
21183 this.hash
= options
.hash
|| options
.curve
.hash
;
21185 module
.exports
= EC
;
21187 EC
.prototype.keyPair
= function keyPair(options
) {
21188 return new KeyPair(this, options
);
21191 EC
.prototype.keyFromPrivate
= function keyFromPrivate(priv
, enc
) {
21192 return KeyPair
.fromPrivate(this, priv
, enc
);
21195 EC
.prototype.keyFromPublic
= function keyFromPublic(pub
, enc
) {
21196 return KeyPair
.fromPublic(this, pub
, enc
);
21199 EC
.prototype.genKeyPair
= function genKeyPair(options
) {
21203 // Instantiate Hmac_DRBG
21204 var drbg
= new HmacDRBG({
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()
21213 var bytes
= this.n
.byteLength();
21214 var ns2
= this.n
.sub(new BN(2));
21216 var priv
= new BN(drbg
.generate(bytes
));
21217 if (priv
.cmp(ns2
) > 0)
21221 return this.keyFromPrivate(priv
);
21225 EC
.prototype._truncateToN
= function truncateToN(msg
, truncOnly
) {
21226 var delta
= msg
.byteLength() * 8 - this.n
.bitLength();
21228 msg
= msg
.ushrn(delta
);
21229 if (!truncOnly
&& msg
.cmp(this.n
) >= 0)
21230 return msg
.sub(this.n
);
21235 EC
.prototype.sign
= function sign(msg
, key
, enc
, options
) {
21236 if (typeof enc
=== 'object') {
21243 key
= this.keyFromPrivate(key
, enc
);
21244 msg
= this._truncateToN(new BN(msg
, 16));
21246 // Zero-extend key to provide enough entropy
21247 var bytes
= this.n
.byteLength();
21248 var bkey
= key
.getPrivate().toArray('be', bytes
);
21250 // Zero-extend nonce to have the same byte size as N
21251 var nonce
= msg
.toArray('be', bytes
);
21253 // Instantiate Hmac_DRBG
21254 var drbg
= new HmacDRBG({
21258 pers: options
.pers
,
21259 persEnc: options
.persEnc
|| 'utf8'
21262 // Number of bytes to generate
21263 var ns1
= this.n
.sub(new BN(1));
21265 for (var iter
= 0; true; iter
++) {
21266 var k
= options
.k
?
21268 new BN(drbg
.generate(this.n
.byteLength()));
21269 k
= this._truncateToN(k
, true);
21270 if (k
.cmpn(1) <= 0 || k
.cmp(ns1
) >= 0)
21273 var kp
= this.g
.mul(k
);
21274 if (kp
.isInfinity())
21277 var kpX
= kp
.getX();
21278 var r
= kpX
.umod(this.n
);
21279 if (r
.cmpn(0) === 0)
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)
21287 var recoveryParam
= (kp
.getY().isOdd() ? 1 : 0) |
21288 (kpX
.cmp(r
) !== 0 ? 2 : 0);
21290 // Use complement of `s`, if it is > `n / 2`
21291 if (options
.canonical
&& s
.cmp(this.nh
) > 0) {
21293 recoveryParam
^= 1;
21296 return new Signature({ r: r
, s: s
, recoveryParam: recoveryParam
});
21300 EC
.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');
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)
21310 if (s
.cmpn(1) < 0 || s
.cmp(this.n
) >= 0)
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
);
21318 if (!this.curve
._maxwellTrick
) {
21319 var p
= this.g
.mulAdd(u1
, key
.getPublic(), u2
);
21320 if (p
.isInfinity())
21323 return p
.getX().umod(this.n
).cmp(r
) === 0;
21326 // NOTE: Greg Maxwell's trick, inspired by:
21327 // https://git.io/vad3K
21329 var p
= this.g
.jmulAdd(u1
, key
.getPublic(), u2
);
21330 if (p
.isInfinity())
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
);
21339 EC
.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
);
21344 var e
= new BN(msg
);
21345 var r
= signature
.r
;
21346 var s
= signature
.s
;
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');
21354 // 1.1. Let x = r + jn.
21356 r
= this.curve
.pointFromX(r
.add(this.curve
.n
), isYOdd
);
21358 r
= this.curve
.pointFromX(r
, isYOdd
);
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
);
21364 // 1.6.1 Compute Q = r^-1 (sR - eG)
21365 // Q = r^-1 (sR + -eG)
21366 return this.g
.mulAdd(s1
, r
, s2
);
21369 EC
.prototype.getKeyRecoveryParam = function(e
, signature
, Q
, enc
) {
21370 signature
= new Signature(signature
, enc
);
21371 if (signature
.recoveryParam
!== null)
21372 return signature
.recoveryParam
;
21374 for (var i
= 0; i
< 4; i
++) {
21377 Qprime
= this.recoverPubKey(e
, signature
, i
);
21385 throw new Error('Unable to find valid recovery factor');
21388 },{"../../elliptic":127,"./key":135,"./signature":136,"bn.js":75,"hmac-drbg":159}],135:[function(require
,module
,exports
){
21391 var BN
= require('bn.js');
21392 var elliptic
= require('../../elliptic');
21393 var utils
= elliptic
.utils
;
21394 var assert
= utils
.assert
;
21396 function KeyPair(ec
, options
) {
21401 // KeyPair(ec, { priv: ..., pub: ... })
21403 this._importPrivate(options
.priv
, options
.privEnc
);
21405 this._importPublic(options
.pub
, options
.pubEnc
);
21407 module
.exports
= KeyPair
;
21409 KeyPair
.fromPublic
= function fromPublic(ec
, pub
, enc
) {
21410 if (pub
instanceof KeyPair
)
21413 return new KeyPair(ec
, {
21419 KeyPair
.fromPrivate
= function fromPrivate(ec
, priv
, enc
) {
21420 if (priv
instanceof KeyPair
)
21423 return new KeyPair(ec
, {
21429 KeyPair
.prototype.validate
= function validate() {
21430 var pub
= this.getPublic();
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' };
21439 return { result: true, reason: null };
21442 KeyPair
.prototype.getPublic
= function getPublic(compact
, enc
) {
21443 // compact is optional argument
21444 if (typeof compact
=== 'string') {
21450 this.pub
= this.ec
.g
.mul(this.priv
);
21455 return this.pub
.encode(enc
, compact
);
21458 KeyPair
.prototype.getPrivate
= function getPrivate(enc
) {
21460 return this.priv
.toString(16, 2);
21465 KeyPair
.prototype._importPrivate
= function _importPrivate(key
, enc
) {
21466 this.priv
= new BN(key
, enc
|| 16);
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
);
21473 KeyPair
.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');
21484 this.pub
= this.ec
.curve
.point(key
.x
, key
.y
);
21487 this.pub
= this.ec
.curve
.decodePoint(key
, enc
);
21491 KeyPair
.prototype.derive
= function derive(pub
) {
21492 return pub
.mul(this.priv
).getX();
21496 KeyPair
.prototype.sign
= function sign(msg
, enc
, options
) {
21497 return this.ec
.sign(msg
, this, enc
, options
);
21500 KeyPair
.prototype.verify
= function verify(msg
, signature
) {
21501 return this.ec
.verify(msg
, signature
, this);
21504 KeyPair
.prototype.inspect
= function inspect() {
21505 return '<Key priv: ' + (this.priv
&& this.priv
.toString(16, 2)) +
21506 ' pub: ' + (this.pub
&& this.pub
.inspect()) + ' >';
21509 },{"../../elliptic":127,"bn.js":75}],136:[function(require
,module
,exports
){
21512 var BN
= require('bn.js');
21514 var elliptic
= require('../../elliptic');
21515 var utils
= elliptic
.utils
;
21516 var assert
= utils
.assert
;
21518 function Signature(options
, enc
) {
21519 if (options
instanceof Signature
)
21522 if (this._importDER(options
, enc
))
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;
21531 this.recoveryParam
= options
.recoveryParam
;
21533 module
.exports
= Signature
;
21535 function Position() {
21539 function getLength(buf
, p
) {
21540 var initial
= buf
[p
.place
++];
21541 if (!(initial
& 0x80)) {
21544 var octetLen
= initial
& 0xf;
21546 for (var i
= 0, off
= p
.place
; i
< octetLen
; i
++, off
++) {
21554 function rmPadding(buf
) {
21556 var len
= buf
.length
- 1;
21557 while (!buf
[i
] && !(buf
[i
+ 1] & 0x80) && i
< len
) {
21563 return buf
.slice(i
);
21566 Signature
.prototype._importDER
= function _importDER(data
, enc
) {
21567 data
= utils
.toArray(data
, enc
);
21568 var p
= new Position();
21569 if (data
[p
.place
++] !== 0x30) {
21572 var len
= getLength(data
, p
);
21573 if ((len
+ p
.place
) !== data
.length
) {
21576 if (data
[p
.place
++] !== 0x02) {
21579 var rlen
= getLength(data
, p
);
21580 var r
= data
.slice(p
.place
, rlen
+ p
.place
);
21582 if (data
[p
.place
++] !== 0x02) {
21585 var slen
= getLength(data
, p
);
21586 if (data
.length
!== slen
+ p
.place
) {
21589 var s
= data
.slice(p
.place
, slen
+ p
.place
);
21590 if (r
[0] === 0 && (r
[1] & 0x80)) {
21593 if (s
[0] === 0 && (s
[1] & 0x80)) {
21597 this.r
= new BN(r
);
21598 this.s
= new BN(s
);
21599 this.recoveryParam
= null;
21604 function constructLength(arr
, len
) {
21609 var octets
= 1 + (Math
.log(len
) / Math
.LN2
>>> 3);
21610 arr
.push(octets
| 0x80);
21612 arr
.push((len
>>> (octets
<< 3)) & 0xff);
21617 Signature
.prototype.toDER
= function toDER(enc
) {
21618 var r
= this.r
.toArray();
21619 var s
= this.s
.toArray();
21623 r
= [ 0 ].concat(r
);
21626 s
= [ 0 ].concat(s
);
21631 while (!s
[0] && !(s
[1] & 0x80)) {
21634 var arr
= [ 0x02 ];
21635 constructLength(arr
, r
.length
);
21636 arr
= arr
.concat(r
);
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
);
21646 },{"../../elliptic":127,"bn.js":75}],137:[function(require
,module
,exports
){
21649 var hash
= require('hash.js');
21650 var elliptic
= require('../../elliptic');
21651 var utils
= elliptic
.utils
;
21652 var assert
= utils
.assert
;
21653 var parseBytes
= utils
.parseBytes
;
21654 var KeyPair
= require('./key');
21655 var Signature
= require('./signature');
21657 function EDDSA(curve
) {
21658 assert(curve
=== 'ed25519', 'only tested with ed25519 so far');
21660 if (!(this instanceof EDDSA
))
21661 return new EDDSA(curve
);
21663 var curve
= elliptic
.curves
[curve
].curve
;
21664 this.curve
= curve
;
21666 this.g
.precompute(curve
.n
.bitLength() + 1);
21668 this.pointClass
= curve
.point().constructor;
21669 this.encodingLength
= Math
.ceil(curve
.n
.bitLength() / 8);
21670 this.hash
= hash
.sha512
;
21673 module
.exports
= EDDSA
;
21676 * @param {Array|String} message - message bytes
21677 * @param {Array|String|KeyPair} secret - secret bytes or a keypair
21678 * @returns {Signature} - signature
21680 EDDSA
.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
)
21688 var S
= r
.add(s_
).umod(this.curve
.n
);
21689 return this.makeSignature({ R: R
, S: S
, Rencoded: Rencoded
});
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
21698 EDDSA
.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
);
21708 EDDSA
.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
);
21715 EDDSA
.prototype.keyFromPublic
= function keyFromPublic(pub
) {
21716 return KeyPair
.fromPublic(this, pub
);
21719 EDDSA
.prototype.keyFromSecret
= function keyFromSecret(secret
) {
21720 return KeyPair
.fromSecret(this, secret
);
21723 EDDSA
.prototype.makeSignature
= function makeSignature(sig
) {
21724 if (sig
instanceof Signature
)
21726 return new Signature(this, sig
);
21730 * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2
21732 * EDDSA defines methods for encoding and decoding points and integers. These are
21733 * helper convenience methods, that pass along to utility functions implied
21737 EDDSA
.prototype.encodePoint
= function encodePoint(point
) {
21738 var enc
= point
.getY().toArray('le', this.encodingLength
);
21739 enc
[this.encodingLength
- 1] |= point
.getX().isOdd() ? 0x80 : 0;
21743 EDDSA
.prototype.decodePoint
= function decodePoint(bytes
) {
21744 bytes
= utils
.parseBytes(bytes
);
21746 var lastIx
= bytes
.length
- 1;
21747 var normed
= bytes
.slice(0, lastIx
).concat(bytes
[lastIx
] & ~0x80);
21748 var xIsOdd
= (bytes
[lastIx
] & 0x80) !== 0;
21750 var y
= utils
.intFromLE(normed
);
21751 return this.curve
.pointFromY(y
, xIsOdd
);
21754 EDDSA
.prototype.encodeInt
= function encodeInt(num
) {
21755 return num
.toArray('le', this.encodingLength
);
21758 EDDSA
.prototype.decodeInt
= function decodeInt(bytes
) {
21759 return utils
.intFromLE(bytes
);
21762 EDDSA
.prototype.isPoint
= function isPoint(val
) {
21763 return val
instanceof this.pointClass
;
21766 },{"../../elliptic":127,"./key":138,"./signature":139,"hash.js":147}],138:[function(require
,module
,exports
){
21769 var elliptic
= require('../../elliptic');
21770 var utils
= elliptic
.utils
;
21771 var assert
= utils
.assert
;
21772 var parseBytes
= utils
.parseBytes
;
21773 var cachedProperty
= utils
.cachedProperty
;
21776 * @param {EDDSA} eddsa - instance
21777 * @param {Object} params - public/private key parameters
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
21784 function KeyPair(eddsa
, params
) {
21785 this.eddsa
= eddsa
;
21786 this._secret
= parseBytes(params
.secret
);
21787 if (eddsa
.isPoint(params
.pub
))
21788 this._pub
= params
.pub
;
21790 this._pubBytes
= parseBytes(params
.pub
);
21793 KeyPair
.fromPublic
= function fromPublic(eddsa
, pub
) {
21794 if (pub
instanceof KeyPair
)
21796 return new KeyPair(eddsa
, { pub: pub
});
21799 KeyPair
.fromSecret
= function fromSecret(eddsa
, secret
) {
21800 if (secret
instanceof KeyPair
)
21802 return new KeyPair(eddsa
, { secret: secret
});
21805 KeyPair
.prototype.secret
= function secret() {
21806 return this._secret
;
21809 cachedProperty(KeyPair
, 'pubBytes', function pubBytes() {
21810 return this.eddsa
.encodePoint(this.pub());
21813 cachedProperty(KeyPair
, 'pub', function pub() {
21814 if (this._pubBytes
)
21815 return this.eddsa
.decodePoint(this._pubBytes
);
21816 return this.eddsa
.g
.mul(this.priv());
21819 cachedProperty(KeyPair
, 'privBytes', function privBytes() {
21820 var eddsa
= this.eddsa
;
21821 var hash
= this.hash();
21822 var lastIx
= eddsa
.encodingLength
- 1;
21824 var a
= hash
.slice(0, eddsa
.encodingLength
);
21832 cachedProperty(KeyPair
, 'priv', function priv() {
21833 return this.eddsa
.decodeInt(this.privBytes());
21836 cachedProperty(KeyPair
, 'hash', function hash() {
21837 return this.eddsa
.hash().update(this.secret()).digest();
21840 cachedProperty(KeyPair
, 'messagePrefix', function messagePrefix() {
21841 return this.hash().slice(this.eddsa
.encodingLength
);
21844 KeyPair
.prototype.sign
= function sign(message
) {
21845 assert(this._secret
, 'KeyPair can only verify');
21846 return this.eddsa
.sign(message
, this);
21849 KeyPair
.prototype.verify
= function verify(message
, sig
) {
21850 return this.eddsa
.verify(message
, sig
, this);
21853 KeyPair
.prototype.getSecret
= function getSecret(enc
) {
21854 assert(this._secret
, 'KeyPair is public only');
21855 return utils
.encode(this.secret(), enc
);
21858 KeyPair
.prototype.getPublic
= function getPublic(enc
) {
21859 return utils
.encode(this.pubBytes(), enc
);
21862 module
.exports
= KeyPair
;
21864 },{"../../elliptic":127}],139:[function(require
,module
,exports
){
21867 var BN
= require('bn.js');
21868 var elliptic
= require('../../elliptic');
21869 var utils
= elliptic
.utils
;
21870 var assert
= utils
.assert
;
21871 var cachedProperty
= utils
.cachedProperty
;
21872 var parseBytes
= utils
.parseBytes
;
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
21882 function Signature(eddsa
, sig
) {
21883 this.eddsa
= eddsa
;
21885 if (typeof sig
!== 'object')
21886 sig
= parseBytes(sig
);
21888 if (Array
.isArray(sig
)) {
21890 R: sig
.slice(0, eddsa
.encodingLength
),
21891 S: sig
.slice(eddsa
.encodingLength
)
21895 assert(sig
.R
&& sig
.S
, 'Signature without R or S');
21897 if (eddsa
.isPoint(sig
.R
))
21899 if (sig
.S
instanceof BN
)
21902 this._Rencoded
= Array
.isArray(sig
.R
) ? sig
.R : sig
.Rencoded
;
21903 this._Sencoded
= Array
.isArray(sig
.S
) ? sig
.S : sig
.Sencoded
;
21906 cachedProperty(Signature
, 'S', function S() {
21907 return this.eddsa
.decodeInt(this.Sencoded());
21910 cachedProperty(Signature
, 'R', function R() {
21911 return this.eddsa
.decodePoint(this.Rencoded());
21914 cachedProperty(Signature
, 'Rencoded', function Rencoded() {
21915 return this.eddsa
.encodePoint(this.R());
21918 cachedProperty(Signature
, 'Sencoded', function Sencoded() {
21919 return this.eddsa
.encodeInt(this.S());
21922 Signature
.prototype.toBytes
= function toBytes() {
21923 return this.Rencoded().concat(this.Sencoded());
21926 Signature
.prototype.toHex
= function toHex() {
21927 return utils
.encode(this.toBytes(), 'hex').toUpperCase();
21930 module
.exports
= Signature
;
21932 },{"../../elliptic":127,"bn.js":75}],140:[function(require
,module
,exports
){
21938 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a',
21939 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821'
21942 '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508',
21943 '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf'
21946 '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739',
21947 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695'
21950 '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640',
21951 '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9'
21954 '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c',
21955 '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36'
21958 '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda',
21959 '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f'
21962 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa',
21963 '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999'
21966 '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0',
21967 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09'
21970 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d',
21971 '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d'
21974 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d',
21975 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088'
21978 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1',
21979 '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d'
21982 '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0',
21983 '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8'
21986 '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047',
21987 '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a'
21990 '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862',
21991 '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453'
21994 '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7',
21995 '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160'
21998 '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd',
21999 '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0'
22002 '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83',
22003 '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6'
22006 '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a',
22007 '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589'
22010 '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8',
22011 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17'
22014 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d',
22015 '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda'
22018 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725',
22019 '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd'
22022 '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754',
22023 '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2'
22026 '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c',
22027 '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6'
22030 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6',
22031 '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f'
22034 '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39',
22035 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01'
22038 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891',
22039 '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3'
22042 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b',
22043 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f'
22046 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03',
22047 '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7'
22050 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d',
22051 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78'
22054 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070',
22055 '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1'
22058 '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4',
22059 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150'
22062 '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da',
22063 '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82'
22066 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11',
22067 '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc'
22070 '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e',
22071 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b'
22074 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41',
22075 '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51'
22078 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef',
22079 '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45'
22082 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8',
22083 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120'
22086 '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d',
22087 '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84'
22090 '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96',
22091 '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d'
22094 '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd',
22095 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d'
22098 '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5',
22099 '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8'
22102 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266',
22103 '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8'
22106 '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71',
22107 '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac'
22110 '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac',
22111 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f'
22114 '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751',
22115 '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962'
22118 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e',
22119 '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907'
22122 '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241',
22123 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec'
22126 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3',
22127 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d'
22130 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f',
22131 '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414'
22134 '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19',
22135 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd'
22138 '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be',
22139 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0'
22142 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9',
22143 '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811'
22146 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2',
22147 '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1'
22150 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13',
22151 '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c'
22154 '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c',
22155 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73'
22158 '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba',
22159 '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd'
22162 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151',
22163 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405'
22166 '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073',
22167 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589'
22170 '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458',
22171 '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e'
22174 '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b',
22175 '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27'
22178 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366',
22179 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1'
22182 '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa',
22183 '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482'
22186 '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0',
22187 '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945'
22190 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787',
22191 '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573'
22194 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e',
22195 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82'
22203 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9',
22204 '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672'
22207 '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4',
22208 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6'
22211 '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc',
22212 '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da'
22215 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe',
22216 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37'
22219 '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb',
22220 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b'
22223 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8',
22224 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81'
22227 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e',
22228 '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58'
22231 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34',
22232 '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77'
22235 '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c',
22236 '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a'
22239 '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5',
22240 '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c'
22243 '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f',
22244 '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67'
22247 '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714',
22248 '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402'
22251 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729',
22252 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55'
22255 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db',
22256 '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482'
22259 '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4',
22260 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82'
22263 '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5',
22264 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396'
22267 '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479',
22268 '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49'
22271 '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d',
22272 '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf'
22275 '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f',
22276 '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a'
22279 '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb',
22280 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7'
22283 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9',
22284 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933'
22287 '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963',
22288 '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a'
22291 '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74',
22292 '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6'
22295 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530',
22296 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37'
22299 '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b',
22300 '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e'
22303 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247',
22304 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6'
22307 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1',
22308 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476'
22311 '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120',
22312 '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40'
22315 '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435',
22316 '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61'
22319 '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18',
22320 '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683'
22323 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8',
22324 '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5'
22327 '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb',
22328 '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b'
22331 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f',
22332 '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417'
22335 '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143',
22336 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868'
22339 '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba',
22340 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a'
22343 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45',
22344 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6'
22347 '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a',
22348 '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996'
22351 '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e',
22352 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e'
22355 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8',
22356 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d'
22359 '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c',
22360 '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2'
22363 '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519',
22364 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e'
22367 '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab',
22368 '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437'
22371 '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca',
22372 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311'
22375 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf',
22376 '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4'
22379 '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610',
22380 '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575'
22383 '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4',
22384 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d'
22387 '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c',
22388 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d'
22391 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940',
22392 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629'
22395 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980',
22396 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06'
22399 '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3',
22400 '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374'
22403 '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf',
22404 '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee'
22407 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63',
22408 '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1'
22411 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448',
22412 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b'
22415 '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf',
22416 '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661'
22419 '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5',
22420 '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6'
22423 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6',
22424 '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e'
22427 '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5',
22428 '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d'
22431 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99',
22432 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc'
22435 '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51',
22436 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4'
22439 '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5',
22440 '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c'
22443 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5',
22444 '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b'
22447 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997',
22448 '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913'
22451 '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881',
22452 '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154'
22455 '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5',
22456 '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865'
22459 '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66',
22460 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc'
22463 '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726',
22464 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224'
22467 '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede',
22468 '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e'
22471 '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94',
22472 '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6'
22475 '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31',
22476 '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511'
22479 '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51',
22480 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b'
22483 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252',
22484 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2'
22487 '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5',
22488 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c'
22491 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b',
22492 '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3'
22495 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4',
22496 '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d'
22499 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f',
22500 '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700'
22503 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889',
22504 '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4'
22507 '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246',
22508 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196'
22511 '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984',
22512 '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4'
22515 '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a',
22516 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257'
22519 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030',
22520 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13'
22523 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197',
22524 '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096'
22527 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593',
22528 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38'
22531 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef',
22532 '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f'
22535 '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38',
22536 '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448'
22539 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a',
22540 '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a'
22543 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111',
22544 '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4'
22547 '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502',
22548 '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437'
22551 '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea',
22552 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7'
22555 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26',
22556 '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d'
22559 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986',
22560 '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a'
22563 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e',
22564 '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54'
22567 '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4',
22568 '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77'
22571 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda',
22572 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517'
22575 '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859',
22576 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10'
22579 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f',
22580 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125'
22583 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c',
22584 '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e'
22587 '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942',
22588 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1'
22591 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a',
22592 '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2'
22595 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80',
22596 '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423'
22599 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d',
22600 '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8'
22603 '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1',
22604 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758'
22607 '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63',
22608 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375'
22611 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352',
22612 '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d'
22615 '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193',
22616 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec'
22619 '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00',
22620 '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0'
22623 '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58',
22624 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c'
22627 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7',
22628 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4'
22631 '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8',
22632 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f'
22635 '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e',
22636 '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649'
22639 '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d',
22640 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826'
22643 '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b',
22644 '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5'
22647 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f',
22648 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87'
22651 '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6',
22652 '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b'
22655 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297',
22656 '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc'
22659 '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a',
22660 '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c'
22663 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c',
22664 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f'
22667 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52',
22668 '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a'
22671 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb',
22672 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46'
22675 '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065',
22676 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f'
22679 '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917',
22680 '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03'
22683 '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9',
22684 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08'
22687 '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3',
22688 '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8'
22691 '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57',
22692 '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373'
22695 '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66',
22696 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3'
22699 '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8',
22700 '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8'
22703 '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721',
22704 '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1'
22707 '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180',
22708 '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9'
22714 },{}],141:[function(require
,module
,exports
){
22717 var utils
= exports
;
22718 var BN
= require('bn.js');
22719 var minAssert
= require('minimalistic-assert');
22720 var minUtils
= require('minimalistic-crypto-utils');
22722 utils
.assert
= minAssert
;
22723 utils
.toArray
= minUtils
.toArray
;
22724 utils
.zero2
= minUtils
.zero2
;
22725 utils
.toHex
= minUtils
.toHex
;
22726 utils
.encode
= minUtils
.encode
;
22728 // Represent num in a w-NAF form
22729 function getNAF(num
, w
) {
22731 var ws
= 1 << (w
+ 1);
22732 var k
= num
.clone();
22733 while (k
.cmpn(1) >= 0) {
22736 var mod
= k
.andln(ws
- 1);
22737 if (mod
> (ws
>> 1) - 1)
22738 z
= (ws
>> 1) - mod
;
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
++)
22756 utils
.getNAF
= getNAF
;
22758 // Represent k1, k2 in a Joint Sparse Form
22759 function getJSF(k1
, k2
) {
22769 while (k1
.cmpn(-d1
) > 0 || k2
.cmpn(-d2
) > 0) {
22772 var m14
= (k1
.andln(3) + d1
) & 3;
22773 var m24
= (k2
.andln(3) + d2
) & 3;
22779 if ((m14
& 1) === 0) {
22782 var m8
= (k1
.andln(7) + d1
) & 7;
22783 if ((m8
=== 3 || m8
=== 5) && m24
=== 2)
22791 if ((m24
& 1) === 0) {
22794 var m8
= (k2
.andln(7) + d2
) & 7;
22795 if ((m8
=== 3 || m8
=== 5) && m14
=== 2)
22803 if (2 * d1
=== u1
+ 1)
22805 if (2 * d2
=== u2
+ 1)
22813 utils
.getJSF
= getJSF
;
22815 function 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);
22822 utils
.cachedProperty
= cachedProperty
;
22824 function parseBytes(bytes
) {
22825 return typeof bytes
=== 'string' ? utils
.toArray(bytes
, 'hex') :
22828 utils
.parseBytes
= parseBytes
;
22830 function intFromLE(bytes
) {
22831 return new BN(bytes
, 'hex', 'le');
22833 utils
.intFromLE
= intFromLE
;
22836 },{"bn.js":75,"minimalistic-assert":176,"minimalistic-crypto-utils":177}],142:[function(require
,module
,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": {},
22847 "raw": "elliptic@^6.0.0",
22848 "name": "elliptic",
22849 "escapedName": "elliptic",
22850 "rawSpec": "^6.0.0",
22852 "fetchSpec": "^6.0.0"
22855 "/browserify-sign",
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",
22863 "name": "Fedor Indutny",
22864 "email": "fedor@indutny.com"
22867 "url": "https://github.com/indutny/elliptic/issues"
22869 "bundleDependencies": false,
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"
22879 "deprecated": false,
22880 "description": "EC cryptography",
22881 "devDependencies": {
22883 "coveralls": "^2.11.3",
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",
22894 "jshint": "^2.6.0",
22900 "homepage": "https://github.com/indutny/elliptic",
22908 "main": "lib/elliptic.js",
22909 "name": "elliptic",
22912 "url": "git+ssh://git@github.com/indutny/elliptic.git"
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/"
22925 },{}],143:[function(require
,module
,exports
){
22926 // Copyright Joyent, Inc. and other Node contributors.
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:
22936 // The above copyright notice and this permission notice shall be included
22937 // in all copies or substantial portions of the Software.
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.
22947 function EventEmitter() {
22948 this._events
= this._events
|| {};
22949 this._maxListeners
= this._maxListeners
|| undefined;
22951 module
.exports
= EventEmitter
;
22953 // Backwards-compat with node 0.10.x
22954 EventEmitter
.EventEmitter
= EventEmitter
;
22956 EventEmitter
.prototype._events
= undefined;
22957 EventEmitter
.prototype._maxListeners
= undefined;
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.
22961 EventEmitter
.defaultMaxListeners
= 10;
22963 // Obviously not all Emitters should be limited to 10. This function allows
22964 // that to be increased. Set to zero for unlimited.
22965 EventEmitter
.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
;
22972 EventEmitter
.prototype.emit = function(type
) {
22973 var er
, handler
, len
, args
, i
, listeners
;
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
)) {
22983 if (er
instanceof Error
) {
22984 throw er
; // Unhandled 'error' event
22986 // At least give some kind of context to the user
22987 var err
= new Error('Uncaught, unspecified "error" event. (' + er
+ ')');
22994 handler
= this._events
[type
];
22996 if (isUndefined(handler
))
22999 if (isFunction(handler
)) {
23000 switch (arguments
.length
) {
23003 handler
.call(this);
23006 handler
.call(this, arguments
[1]);
23009 handler
.call(this, arguments
[1], arguments
[2]);
23013 args
= Array
.prototype.slice
.call(arguments
, 1);
23014 handler
.apply(this, args
);
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
);
23027 EventEmitter
.prototype.addListener = function(type
, listener
) {
23030 if (!isFunction(listener
))
23031 throw TypeError('listener must be a function');
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
);
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
);
23050 // Adding the second element, need to change to array.
23051 this._events
[type
] = [this._events
[type
], listener
];
23053 // Check for listener leak
23054 if (isObject(this._events
[type
]) && !this._events
[type
].warned
) {
23055 if (!isUndefined(this._maxListeners
)) {
23056 m
= this._maxListeners
;
23058 m
= EventEmitter
.defaultMaxListeners
;
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
23077 EventEmitter
.prototype.on
= EventEmitter
.prototype.addListener
;
23079 EventEmitter
.prototype.once = function(type
, listener
) {
23080 if (!isFunction(listener
))
23081 throw TypeError('listener must be a function');
23086 this.removeListener(type
, g
);
23090 listener
.apply(this, arguments
);
23094 g
.listener
= listener
;
23100 // emits a 'removeListener' event iff the listener was removed
23101 EventEmitter
.prototype.removeListener = function(type
, listener
) {
23102 var list
, position
, length
, i
;
23104 if (!isFunction(listener
))
23105 throw TypeError('listener must be a function');
23107 if (!this._events
|| !this._events
[type
])
23110 list
= this._events
[type
];
23111 length
= list
.length
;
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
);
23120 } else if (isObject(list
)) {
23121 for (i
= length
; i
-- > 0;) {
23122 if (list
[i
] === listener
||
23123 (list
[i
].listener
&& list
[i
].listener
=== listener
)) {
23132 if (list
.length
=== 1) {
23134 delete this._events
[type
];
23136 list
.splice(position
, 1);
23139 if (this._events
.removeListener
)
23140 this.emit('removeListener', type
, listener
);
23146 EventEmitter
.prototype.removeAllListeners = function(type
) {
23147 var key
, listeners
;
23152 // not listening for removeListener, no need to emit
23153 if (!this._events
.removeListener
) {
23154 if (arguments
.length
=== 0)
23156 else if (this._events
[type
])
23157 delete this._events
[type
];
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
);
23167 this.removeAllListeners('removeListener');
23172 listeners
= this._events
[type
];
23174 if (isFunction(listeners
)) {
23175 this.removeListener(type
, listeners
);
23176 } else if (listeners
) {
23178 while (listeners
.length
)
23179 this.removeListener(type
, listeners
[listeners
.length
- 1]);
23181 delete this._events
[type
];
23186 EventEmitter
.prototype.listeners = function(type
) {
23188 if (!this._events
|| !this._events
[type
])
23190 else if (isFunction(this._events
[type
]))
23191 ret
= [this._events
[type
]];
23193 ret
= this._events
[type
].slice();
23197 EventEmitter
.prototype.listenerCount = function(type
) {
23198 if (this._events
) {
23199 var evlistener
= this._events
[type
];
23201 if (isFunction(evlistener
))
23203 else if (evlistener
)
23204 return evlistener
.length
;
23209 EventEmitter
.listenerCount = function(emitter
, type
) {
23210 return emitter
.listenerCount(type
);
23213 function isFunction(arg
) {
23214 return typeof arg
=== 'function';
23217 function isNumber(arg
) {
23218 return typeof arg
=== 'number';
23221 function isObject(arg
) {
23222 return typeof arg
=== 'object' && arg
!== null;
23225 function isUndefined(arg
) {
23226 return arg
=== void 0;
23229 },{}],144:[function(require
,module
,exports
){
23230 var Buffer
= require('safe-buffer').Buffer
23231 var MD5
= require('md5.js')
23233 /* eslint-disable camelcase */
23234 function EVP_BytesToKey (password
, salt
, keyBits
, ivLen
) {
23235 if (!Buffer
.isBuffer(password
)) password
= Buffer
.from(password
, 'binary')
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')
23241 var keyLen
= keyBits
/ 8
23242 var key
= Buffer
.alloc(keyLen
)
23243 var iv
= Buffer
.alloc(ivLen
|| 0)
23244 var tmp
= Buffer
.alloc(0)
23246 while (keyLen
> 0 || ivLen
> 0) {
23247 var hash
= new MD5()
23249 hash
.update(password
)
23250 if (salt
) hash
.update(salt
)
23251 tmp
= hash
.digest()
23256 var keyStart
= key
.length
- keyLen
23257 used
= Math
.min(keyLen
, tmp
.length
)
23258 tmp
.copy(key
, keyStart
, 0, used
)
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
)
23271 return { key: key
, iv: iv
}
23274 module
.exports
= EVP_BytesToKey
23276 },{"md5.js":173,"safe-buffer":247}],145:[function(require
,module
,exports
){
23279 var hasOwn
= Object
.prototype.hasOwnProperty
;
23280 var toStr
= Object
.prototype.toString
;
23282 var isArray
= function isArray(arr
) {
23283 if (typeof Array
.isArray
=== 'function') {
23284 return Array
.isArray(arr
);
23287 return toStr
.call(arr
) === '[object Array]';
23290 var isPlainObject
= function isPlainObject(obj
) {
23291 if (!obj
|| toStr
.call(obj
) !== '[object Object]') {
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
) {
23302 // Own properties are enumerated firstly, so to speed up,
23303 // if last one is own, then all properties are own.
23305 for (key
in obj
) { /**/ }
23307 return typeof key
=== 'undefined' || hasOwn
.call(obj
, key
);
23310 module
.exports
= function extend() {
23311 var options
, name
, src
, copy
, copyIsArray
, clone
;
23312 var target
= arguments
[0];
23314 var length
= arguments
.length
;
23317 // Handle a deep copy situation
23318 if (typeof target
=== 'boolean') {
23320 target
= arguments
[1] || {};
23321 // skip the boolean and the target
23324 if (target
== null || (typeof target
!== 'object' && typeof target
!== 'function')) {
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
];
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
)))) {
23342 copyIsArray
= false;
23343 clone
= src
&& isArray(src
) ? src : [];
23345 clone
= src
&& isPlainObject(src
) ? src : {};
23348 // Never move original objects, clone them
23349 target
[name
] = extend(deep
, clone
, copy
);
23351 // Don't bring in undefined values
23352 } else if (typeof copy
!== 'undefined') {
23353 target
[name
] = copy
;
23360 // Return the modified object
23364 },{}],146:[function(require
,module
,exports
){
23365 (function (Buffer
){
23367 var Transform
= require('stream').Transform
23368 var inherits
= require('inherits')
23370 function HashBase (blockSize
) {
23371 Transform
.call(this)
23373 this._block
= new Buffer(blockSize
)
23374 this._blockSize
= blockSize
23375 this._blockOffset
= 0
23376 this._length
= [0, 0, 0, 0]
23378 this._finalized
= false
23381 inherits(HashBase
, Transform
)
23383 HashBase
.prototype._transform = function (chunk
, encoding
, callback
) {
23386 if (encoding
!== 'buffer') chunk
= new Buffer(chunk
, encoding
)
23395 HashBase
.prototype._flush = function (callback
) {
23398 this.push(this._digest())
23406 HashBase
.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')
23412 var block
= this._block
23414 while (this._blockOffset
+ data
.length
- offset
>= this._blockSize
) {
23415 for (var i
= this._blockOffset
; i
< this._blockSize
;) block
[i
++] = data
[offset
++]
23417 this._blockOffset
= 0
23419 while (offset
< data
.length
) block
[this._blockOffset
++] = data
[offset
++]
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
23431 HashBase
.prototype._update = function (data
) {
23432 throw new Error('_update is not implemented')
23435 HashBase
.prototype.digest = function (encoding
) {
23436 if (this._finalized
) throw new Error('Digest already called')
23437 this._finalized
= true
23439 var digest
= this._digest()
23440 if (encoding
!== undefined) digest
= digest
.toString(encoding
)
23444 HashBase
.prototype._digest = function () {
23445 throw new Error('_digest is not implemented')
23448 module
.exports
= HashBase
23450 }).call(this,require("buffer").Buffer
)
23451 },{"buffer":107,"inherits":163,"stream":263}],147:[function(require
,module
,exports
){
23452 var hash
= exports
;
23454 hash
.utils
= require('./hash/utils');
23455 hash
.common
= require('./hash/common');
23456 hash
.sha
= require('./hash/sha');
23457 hash
.ripemd
= require('./hash/ripemd');
23458 hash
.hmac
= require('./hash/hmac');
23460 // Proxy hash functions to the main object
23461 hash
.sha1
= hash
.sha
.sha1
;
23462 hash
.sha256
= hash
.sha
.sha256
;
23463 hash
.sha224
= hash
.sha
.sha224
;
23464 hash
.sha384
= hash
.sha
.sha384
;
23465 hash
.sha512
= hash
.sha
.sha512
;
23466 hash
.ripemd160
= hash
.ripemd
.ripemd160
;
23468 },{"./hash/common":148,"./hash/hmac":149,"./hash/ripemd":150,"./hash/sha":151,"./hash/utils":158}],148:[function(require
,module
,exports
){
23471 var utils
= require('./utils');
23472 var assert
= require('minimalistic-assert');
23474 function 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';
23483 this._delta8
= this.blockSize
/ 8;
23484 this._delta32
= this.blockSize
/ 32;
23486 exports
.BlockHash
= BlockHash
;
23488 BlockHash
.prototype.update
= function update(msg
, enc
) {
23489 // Convert message to array, pad it, and join into 32bit blocks
23490 msg
= utils
.toArray(msg
, enc
);
23492 this.pending
= msg
;
23494 this.pending
= this.pending
.concat(msg
);
23495 this.pendingTotal
+= msg
.length
;
23497 // Enough data, try updating
23498 if (this.pending
.length
>= this._delta8
) {
23499 msg
= this.pending
;
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;
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
);
23515 BlockHash
.prototype.digest
= function digest(enc
) {
23516 this.update(this._pad());
23517 assert(this.pending
=== null);
23519 return this._digest(enc
);
23522 BlockHash
.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
);
23528 for (var i
= 1; i
< k
; i
++)
23533 if (this.endian
=== 'big') {
23534 for (var t
= 8; t
< this.padLength
; t
++)
23541 res
[i
++] = (len
>>> 24) & 0xff;
23542 res
[i
++] = (len
>>> 16) & 0xff;
23543 res
[i
++] = (len
>>> 8) & 0xff;
23544 res
[i
++] = len
& 0xff;
23546 res
[i
++] = len
& 0xff;
23547 res
[i
++] = (len
>>> 8) & 0xff;
23548 res
[i
++] = (len
>>> 16) & 0xff;
23549 res
[i
++] = (len
>>> 24) & 0xff;
23555 for (t
= 8; t
< this.padLength
; t
++)
23562 },{"./utils":158,"minimalistic-assert":176}],149:[function(require
,module
,exports
){
23565 var utils
= require('./utils');
23566 var assert
= require('minimalistic-assert');
23568 function Hmac(hash
, key
, enc
) {
23569 if (!(this instanceof Hmac
))
23570 return new Hmac(hash
, key
, enc
);
23572 this.blockSize
= hash
.blockSize
/ 8;
23573 this.outSize
= hash
.outSize
/ 8;
23577 this._init(utils
.toArray(key
, enc
));
23579 module
.exports
= Hmac
;
23581 Hmac
.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
);
23587 // Add padding to key
23588 for (var i
= key
.length
; i
< this.blockSize
; i
++)
23591 for (i
= 0; i
< key
.length
; i
++)
23593 this.inner
= new this.Hash().update(key
);
23595 // 0x36 ^ 0x5c = 0x6a
23596 for (i
= 0; i
< key
.length
; i
++)
23598 this.outer
= new this.Hash().update(key
);
23601 Hmac
.prototype.update
= function update(msg
, enc
) {
23602 this.inner
.update(msg
, enc
);
23606 Hmac
.prototype.digest
= function digest(enc
) {
23607 this.outer
.update(this.inner
.digest());
23608 return this.outer
.digest(enc
);
23611 },{"./utils":158,"minimalistic-assert":176}],150:[function(require
,module
,exports
){
23614 var utils
= require('./utils');
23615 var common
= require('./common');
23617 var rotl32
= utils
.rotl32
;
23618 var sum32
= utils
.sum32
;
23619 var sum32_3
= utils
.sum32_3
;
23620 var sum32_4
= utils
.sum32_4
;
23621 var BlockHash
= common
.BlockHash
;
23623 function RIPEMD160() {
23624 if (!(this instanceof RIPEMD160
))
23625 return new RIPEMD160();
23627 BlockHash
.call(this);
23629 this.h
= [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ];
23630 this.endian
= 'little';
23632 utils
.inherits(RIPEMD160
, BlockHash
);
23633 exports
.ripemd160
= RIPEMD160
;
23635 RIPEMD160
.blockSize
= 512;
23636 RIPEMD160
.outSize
= 160;
23637 RIPEMD160
.hmacStrength
= 192;
23638 RIPEMD160
.padLength
= 64;
23640 RIPEMD160
.prototype._update
= function update(msg
, start
) {
23651 for (var j
= 0; j
< 80; j
++) {
23654 sum32_4(A
, f(j
, B
, C
, D
), msg
[r
[j
] + start
], K(j
)),
23664 sum32_4(Ah
, f(79 - j
, Bh
, Ch
, Dh
), msg
[rh
[j
] + start
], Kh(j
)),
23669 Dh
= rotl32(Ch
, 10);
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
);
23681 RIPEMD160
.prototype._digest
= function digest(enc
) {
23683 return utils
.toHex32(this.h
, 'little');
23685 return utils
.split32(this.h
, 'little');
23688 function f(j
, x
, y
, z
) {
23692 return (x
& y
) | ((~x
) & z
);
23694 return (x
| (~y
)) ^ z
;
23696 return (x
& z
) | (y
& (~z
));
23698 return x
^ (y
| (~z
));
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
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
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
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
23759 },{"./common":148,"./utils":158}],151:[function(require
,module
,exports
){
23762 exports
.sha1
= require('./sha/1');
23763 exports
.sha224
= require('./sha/224');
23764 exports
.sha256
= require('./sha/256');
23765 exports
.sha384
= require('./sha/384');
23766 exports
.sha512
= require('./sha/512');
23768 },{"./sha/1":152,"./sha/224":153,"./sha/256":154,"./sha/384":155,"./sha/512":156}],152:[function(require
,module
,exports
){
23771 var utils
= require('../utils');
23772 var common
= require('../common');
23773 var shaCommon
= require('./common');
23775 var rotl32
= utils
.rotl32
;
23776 var sum32
= utils
.sum32
;
23777 var sum32_5
= utils
.sum32_5
;
23778 var ft_1
= shaCommon
.ft_1
;
23779 var BlockHash
= common
.BlockHash
;
23782 0x5A827999, 0x6ED9EBA1,
23783 0x8F1BBCDC, 0xCA62C1D6
23787 if (!(this instanceof SHA1
))
23790 BlockHash
.call(this);
23792 0x67452301, 0xefcdab89, 0x98badcfe,
23793 0x10325476, 0xc3d2e1f0 ];
23794 this.W
= new Array(80);
23797 utils
.inherits(SHA1
, BlockHash
);
23798 module
.exports
= SHA1
;
23800 SHA1
.blockSize
= 512;
23801 SHA1
.outSize
= 160;
23802 SHA1
.hmacStrength
= 80;
23803 SHA1
.padLength
= 64;
23805 SHA1
.prototype._update
= function _update(msg
, start
) {
23808 for (var i
= 0; i
< 16; i
++)
23809 W
[i
] = msg
[start
+ i
];
23811 for(; i
< W
.length
; i
++)
23812 W
[i
] = rotl32(W
[i
- 3] ^ W
[i
- 8] ^ W
[i
- 14] ^ W
[i
- 16], 1);
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
]);
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
);
23837 SHA1
.prototype._digest
= function digest(enc
) {
23839 return utils
.toHex32(this.h
, 'big');
23841 return utils
.split32(this.h
, 'big');
23844 },{"../common":148,"../utils":158,"./common":157}],153:[function(require
,module
,exports
){
23847 var utils
= require('../utils');
23848 var SHA256
= require('./256');
23850 function SHA224() {
23851 if (!(this instanceof SHA224
))
23852 return new SHA224();
23856 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
23857 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ];
23859 utils
.inherits(SHA224
, SHA256
);
23860 module
.exports
= SHA224
;
23862 SHA224
.blockSize
= 512;
23863 SHA224
.outSize
= 224;
23864 SHA224
.hmacStrength
= 192;
23865 SHA224
.padLength
= 64;
23867 SHA224
.prototype._digest
= function digest(enc
) {
23868 // Just truncate output
23870 return utils
.toHex32(this.h
.slice(0, 7), 'big');
23872 return utils
.split32(this.h
.slice(0, 7), 'big');
23876 },{"../utils":158,"./256":154}],154:[function(require
,module
,exports
){
23879 var utils
= require('../utils');
23880 var common
= require('../common');
23881 var shaCommon
= require('./common');
23882 var assert
= require('minimalistic-assert');
23884 var sum32
= utils
.sum32
;
23885 var sum32_4
= utils
.sum32_4
;
23886 var sum32_5
= utils
.sum32_5
;
23887 var ch32
= shaCommon
.ch32
;
23888 var maj32
= shaCommon
.maj32
;
23889 var s0_256
= shaCommon
.s0_256
;
23890 var s1_256
= shaCommon
.s1_256
;
23891 var g0_256
= shaCommon
.g0_256
;
23892 var g1_256
= shaCommon
.g1_256
;
23894 var BlockHash
= common
.BlockHash
;
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
23915 function SHA256() {
23916 if (!(this instanceof SHA256
))
23917 return new SHA256();
23919 BlockHash
.call(this);
23921 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a,
23922 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19
23925 this.W
= new Array(64);
23927 utils
.inherits(SHA256
, BlockHash
);
23928 module
.exports
= SHA256
;
23930 SHA256
.blockSize
= 512;
23931 SHA256
.outSize
= 256;
23932 SHA256
.hmacStrength
= 192;
23933 SHA256
.padLength
= 64;
23935 SHA256
.prototype._update
= function _update(msg
, start
) {
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]);
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
));
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
);
23976 SHA256
.prototype._digest
= function digest(enc
) {
23978 return utils
.toHex32(this.h
, 'big');
23980 return utils
.split32(this.h
, 'big');
23983 },{"../common":148,"../utils":158,"./common":157,"minimalistic-assert":176}],155:[function(require
,module
,exports
){
23986 var utils
= require('../utils');
23988 var SHA512
= require('./512');
23990 function SHA384() {
23991 if (!(this instanceof SHA384
))
23992 return new SHA384();
23996 0xcbbb9d5d, 0xc1059ed8,
23997 0x629a292a, 0x367cd507,
23998 0x9159015a, 0x3070dd17,
23999 0x152fecd8, 0xf70e5939,
24000 0x67332667, 0xffc00b31,
24001 0x8eb44a87, 0x68581511,
24002 0xdb0c2e0d, 0x64f98fa7,
24003 0x47b5481d, 0xbefa4fa4 ];
24005 utils
.inherits(SHA384
, SHA512
);
24006 module
.exports
= SHA384
;
24008 SHA384
.blockSize
= 1024;
24009 SHA384
.outSize
= 384;
24010 SHA384
.hmacStrength
= 192;
24011 SHA384
.padLength
= 128;
24013 SHA384
.prototype._digest
= function digest(enc
) {
24015 return utils
.toHex32(this.h
.slice(0, 12), 'big');
24017 return utils
.split32(this.h
.slice(0, 12), 'big');
24020 },{"../utils":158,"./512":156}],156:[function(require
,module
,exports
){
24023 var utils
= require('../utils');
24024 var common
= require('../common');
24025 var assert
= require('minimalistic-assert');
24027 var rotr64_hi
= utils
.rotr64_hi
;
24028 var rotr64_lo
= utils
.rotr64_lo
;
24029 var shr64_hi
= utils
.shr64_hi
;
24030 var shr64_lo
= utils
.shr64_lo
;
24031 var sum64
= utils
.sum64
;
24032 var sum64_hi
= utils
.sum64_hi
;
24033 var sum64_lo
= utils
.sum64_lo
;
24034 var sum64_4_hi
= utils
.sum64_4_hi
;
24035 var sum64_4_lo
= utils
.sum64_4_lo
;
24036 var sum64_5_hi
= utils
.sum64_5_hi
;
24037 var sum64_5_lo
= utils
.sum64_5_lo
;
24039 var BlockHash
= common
.BlockHash
;
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
24084 function SHA512() {
24085 if (!(this instanceof SHA512
))
24086 return new SHA512();
24088 BlockHash
.call(this);
24090 0x6a09e667, 0xf3bcc908,
24091 0xbb67ae85, 0x84caa73b,
24092 0x3c6ef372, 0xfe94f82b,
24093 0xa54ff53a, 0x5f1d36f1,
24094 0x510e527f, 0xade682d1,
24095 0x9b05688c, 0x2b3e6c1f,
24096 0x1f83d9ab, 0xfb41bd6b,
24097 0x5be0cd19, 0x137e2179 ];
24099 this.W
= new Array(160);
24101 utils
.inherits(SHA512
, BlockHash
);
24102 module
.exports
= SHA512
;
24104 SHA512
.blockSize
= 1024;
24105 SHA512
.outSize
= 512;
24106 SHA512
.hmacStrength
= 192;
24107 SHA512
.padLength
= 128;
24109 SHA512
.prototype._prepareBlock
= function _prepareBlock(msg
, start
) {
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];
24130 W
[i
+ 1] = sum64_4_lo(
24138 SHA512
.prototype._update
= function _update(msg
, start
) {
24139 this._prepareBlock(msg
, start
);
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];
24160 assert(this.k
.length
=== W
.length
);
24161 for (var i
= 0; i
< W
.length
; i
+= 2) {
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];
24171 var c4_lo
= W
[i
+ 1];
24173 var T1_hi
= sum64_5_hi(
24179 var T1_lo
= sum64_5_lo(
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
);
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
);
24203 eh
= sum64_hi(dh
, dl
, T1_hi
, T1_lo
);
24204 el
= sum64_lo(dl
, dl
, T1_hi
, T1_lo
);
24215 ah
= sum64_hi(T1_hi
, T1_lo
, T2_hi
, T2_lo
);
24216 al
= sum64_lo(T1_hi
, T1_lo
, T2_hi
, T2_lo
);
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
);
24229 SHA512
.prototype._digest
= function digest(enc
) {
24231 return utils
.toHex32(this.h
, 'big');
24233 return utils
.split32(this.h
, 'big');
24236 function ch64_hi(xh
, xl
, yh
, yl
, zh
) {
24237 var r
= (xh
& yh
) ^ ((~xh
) & zh
);
24243 function ch64_lo(xh
, xl
, yh
, yl
, zh
, zl
) {
24244 var r
= (xl
& yl
) ^ ((~xl
) & zl
);
24250 function maj64_hi(xh
, xl
, yh
, yl
, zh
) {
24251 var r
= (xh
& yh
) ^ (xh
& zh
) ^ (yh
& zh
);
24257 function maj64_lo(xh
, xl
, yh
, yl
, zh
, zl
) {
24258 var r
= (xl
& yl
) ^ (xl
& zl
) ^ (yl
& zl
);
24264 function 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
24269 var r
= c0_hi
^ c1_hi
^ c2_hi
;
24275 function 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
24280 var r
= c0_lo
^ c1_lo
^ c2_lo
;
24286 function 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
24291 var r
= c0_hi
^ c1_hi
^ c2_hi
;
24297 function 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
24302 var r
= c0_lo
^ c1_lo
^ c2_lo
;
24308 function 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);
24313 var r
= c0_hi
^ c1_hi
^ c2_hi
;
24319 function 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);
24324 var r
= c0_lo
^ c1_lo
^ c2_lo
;
24330 function 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);
24335 var r
= c0_hi
^ c1_hi
^ c2_hi
;
24341 function 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);
24346 var r
= c0_lo
^ c1_lo
^ c2_lo
;
24352 },{"../common":148,"../utils":158,"minimalistic-assert":176}],157:[function(require
,module
,exports
){
24355 var utils
= require('../utils');
24356 var rotr32
= utils
.rotr32
;
24358 function ft_1(s
, x
, y
, z
) {
24360 return ch32(x
, y
, z
);
24361 if (s
=== 1 || s
=== 3)
24362 return p32(x
, y
, z
);
24364 return maj32(x
, y
, z
);
24366 exports
.ft_1
= ft_1
;
24368 function ch32(x
, y
, z
) {
24369 return (x
& y
) ^ ((~x
) & z
);
24371 exports
.ch32
= ch32
;
24373 function maj32(x
, y
, z
) {
24374 return (x
& y
) ^ (x
& z
) ^ (y
& z
);
24376 exports
.maj32
= maj32
;
24378 function p32(x
, y
, z
) {
24383 function s0_256(x
) {
24384 return rotr32(x
, 2) ^ rotr32(x
, 13) ^ rotr32(x
, 22);
24386 exports
.s0_256
= s0_256
;
24388 function s1_256(x
) {
24389 return rotr32(x
, 6) ^ rotr32(x
, 11) ^ rotr32(x
, 25);
24391 exports
.s1_256
= s1_256
;
24393 function g0_256(x
) {
24394 return rotr32(x
, 7) ^ rotr32(x
, 18) ^ (x
>>> 3);
24396 exports
.g0_256
= g0_256
;
24398 function g1_256(x
) {
24399 return rotr32(x
, 17) ^ rotr32(x
, 19) ^ (x
>>> 10);
24401 exports
.g1_256
= g1_256
;
24403 },{"../utils":158}],158:[function(require
,module
,exports
){
24406 var assert
= require('minimalistic-assert');
24407 var inherits
= require('inherits');
24409 exports
.inherits
= inherits
;
24411 function toArray(msg
, enc
) {
24412 if (Array
.isArray(msg
))
24413 return msg
.slice();
24417 if (typeof msg
=== 'string') {
24419 for (var i
= 0; i
< msg
.length
; i
++) {
24420 var c
= msg
.charCodeAt(i
);
24428 } else if (enc
=== 'hex') {
24429 msg
= msg
.replace(/[^a-z0-9]+/ig, '');
24430 if (msg
.length
% 2 !== 0)
24432 for (i
= 0; i
< msg
.length
; i
+= 2)
24433 res
.push(parseInt(msg
[i
] + msg
[i
+ 1], 16));
24436 for (i
= 0; i
< msg
.length
; i
++)
24437 res
[i
] = msg
[i
] | 0;
24441 exports
.toArray
= toArray
;
24443 function toHex(msg
) {
24445 for (var i
= 0; i
< msg
.length
; i
++)
24446 res
+= zero2(msg
[i
].toString(16));
24449 exports
.toHex
= toHex
;
24451 function htonl(w
) {
24452 var res
= (w
>>> 24) |
24453 ((w
>>> 8) & 0xff00) |
24454 ((w
<< 8) & 0xff0000) |
24455 ((w
& 0xff) << 24);
24458 exports
.htonl
= htonl
;
24460 function toHex32(msg
, endian
) {
24462 for (var i
= 0; i
< msg
.length
; i
++) {
24464 if (endian
=== 'little')
24466 res
+= zero8(w
.toString(16));
24470 exports
.toHex32
= toHex32
;
24472 function zero2(word
) {
24473 if (word
.length
=== 1)
24478 exports
.zero2
= zero2
;
24480 function zero8(word
) {
24481 if (word
.length
=== 7)
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
;
24498 exports
.zero8
= zero8
;
24500 function 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) {
24506 if (endian
=== 'big')
24507 w
= (msg
[k
] << 24) | (msg
[k
+ 1] << 16) | (msg
[k
+ 2] << 8) | msg
[k
+ 3];
24509 w
= (msg
[k
+ 3] << 24) | (msg
[k
+ 2] << 16) | (msg
[k
+ 1] << 8) | msg
[k
];
24514 exports
.join32
= join32
;
24516 function split32(msg
, endian
) {
24517 var res
= new Array(msg
.length
* 4);
24518 for (var i
= 0, k
= 0; i
< msg
.length
; i
++, k
+= 4) {
24520 if (endian
=== 'big') {
24522 res
[k
+ 1] = (m
>>> 16) & 0xff;
24523 res
[k
+ 2] = (m
>>> 8) & 0xff;
24524 res
[k
+ 3] = m
& 0xff;
24526 res
[k
+ 3] = m
>>> 24;
24527 res
[k
+ 2] = (m
>>> 16) & 0xff;
24528 res
[k
+ 1] = (m
>>> 8) & 0xff;
24534 exports
.split32
= split32
;
24536 function rotr32(w
, b
) {
24537 return (w
>>> b
) | (w
<< (32 - b
));
24539 exports
.rotr32
= rotr32
;
24541 function rotl32(w
, b
) {
24542 return (w
<< b
) | (w
>>> (32 - b
));
24544 exports
.rotl32
= rotl32
;
24546 function sum32(a
, b
) {
24547 return (a
+ b
) >>> 0;
24549 exports
.sum32
= sum32
;
24551 function sum32_3(a
, b
, c
) {
24552 return (a
+ b
+ c
) >>> 0;
24554 exports
.sum32_3
= sum32_3
;
24556 function sum32_4(a
, b
, c
, d
) {
24557 return (a
+ b
+ c
+ d
) >>> 0;
24559 exports
.sum32_4
= sum32_4
;
24561 function sum32_5(a
, b
, c
, d
, e
) {
24562 return (a
+ b
+ c
+ d
+ e
) >>> 0;
24564 exports
.sum32_5
= sum32_5
;
24566 function sum64(buf
, pos
, ah
, al
) {
24568 var bl
= buf
[pos
+ 1];
24570 var lo
= (al
+ bl
) >>> 0;
24571 var hi
= (lo
< al
? 1 : 0) + ah
+ bh
;
24572 buf
[pos
] = hi
>>> 0;
24575 exports
.sum64
= sum64
;
24577 function sum64_hi(ah
, al
, bh
, bl
) {
24578 var lo
= (al
+ bl
) >>> 0;
24579 var hi
= (lo
< al
? 1 : 0) + ah
+ bh
;
24582 exports
.sum64_hi
= sum64_hi
;
24584 function sum64_lo(ah
, al
, bh
, bl
) {
24588 exports
.sum64_lo
= sum64_lo
;
24590 function sum64_4_hi(ah
, al
, bh
, bl
, ch
, cl
, dh
, dl
) {
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;
24600 var hi
= ah
+ bh
+ ch
+ dh
+ carry
;
24603 exports
.sum64_4_hi
= sum64_4_hi
;
24605 function sum64_4_lo(ah
, al
, bh
, bl
, ch
, cl
, dh
, dl
) {
24606 var lo
= al
+ bl
+ cl
+ dl
;
24609 exports
.sum64_4_lo
= sum64_4_lo
;
24611 function sum64_5_hi(ah
, al
, bh
, bl
, ch
, cl
, dh
, dl
, eh
, el
) {
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;
24623 var hi
= ah
+ bh
+ ch
+ dh
+ eh
+ carry
;
24626 exports
.sum64_5_hi
= sum64_5_hi
;
24628 function sum64_5_lo(ah
, al
, bh
, bl
, ch
, cl
, dh
, dl
, eh
, el
) {
24629 var lo
= al
+ bl
+ cl
+ dl
+ el
;
24633 exports
.sum64_5_lo
= sum64_5_lo
;
24635 function rotr64_hi(ah
, al
, num
) {
24636 var r
= (al
<< (32 - num
)) | (ah
>>> num
);
24639 exports
.rotr64_hi
= rotr64_hi
;
24641 function rotr64_lo(ah
, al
, num
) {
24642 var r
= (ah
<< (32 - num
)) | (al
>>> num
);
24645 exports
.rotr64_lo
= rotr64_lo
;
24647 function shr64_hi(ah
, al
, num
) {
24650 exports
.shr64_hi
= shr64_hi
;
24652 function shr64_lo(ah
, al
, num
) {
24653 var r
= (ah
<< (32 - num
)) | (al
>>> num
);
24656 exports
.shr64_lo
= shr64_lo
;
24658 },{"inherits":163,"minimalistic-assert":176}],159:[function(require
,module
,exports
){
24661 var hash
= require('hash.js');
24662 var utils
= require('minimalistic-crypto-utils');
24663 var assert
= require('minimalistic-assert');
24665 function HmacDRBG(options
) {
24666 if (!(this instanceof HmacDRBG
))
24667 return new HmacDRBG(options
);
24668 this.hash
= options
.hash
;
24669 this.predResist
= !!options
.predResist
;
24671 this.outLen
= this.hash
.outSize
;
24672 this.minEntropy
= options
.minEntropy
|| this.hash
.hmacStrength
;
24674 this._reseed
= null;
24675 this.reseedInterval
= null;
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
);
24686 module
.exports
= HmacDRBG
;
24688 HmacDRBG
.prototype._init
= function init(entropy
, nonce
, pers
) {
24689 var seed
= entropy
.concat(nonce
).concat(pers
);
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
++) {
24698 this._update(seed
);
24700 this.reseedInterval
= 0x1000000000000; // 2^48
24703 HmacDRBG
.prototype._hmac
= function hmac() {
24704 return new hash
.hmac(this.hash
, this.K
);
24707 HmacDRBG
.prototype._update
= function update(seed
) {
24708 var kmac
= this._hmac()
24712 kmac
= kmac
.update(seed
);
24713 this.K
= kmac
.digest();
24714 this.V
= this._hmac().update(this.V
).digest();
24718 this.K
= this._hmac()
24723 this.V
= this._hmac().update(this.V
).digest();
24726 HmacDRBG
.prototype.reseed
= function reseed(entropy
, entropyEnc
, add
, addEnc
) {
24727 // Optional entropy enc
24728 if (typeof entropyEnc
!== 'string') {
24734 entropy
= utils
.toArray(entropy
, entropyEnc
);
24735 add
= utils
.toArray(add
, addEnc
);
24737 assert(entropy
.length
>= (this.minEntropy
/ 8),
24738 'Not enough entropy. Minimum is: ' + this.minEntropy
+ ' bits');
24740 this._update(entropy
.concat(add
|| []));
24744 HmacDRBG
.prototype.generate
= function generate(len
, enc
, add
, addEnc
) {
24745 if (this._reseed
> this.reseedInterval
)
24746 throw new Error('Reseed is required');
24748 // Optional encoding
24749 if (typeof enc
!== 'string') {
24755 // Optional additional data
24757 add
= utils
.toArray(add
, addEnc
|| 'hex');
24762 while (temp
.length
< len
) {
24763 this.V
= this._hmac().update(this.V
).digest();
24764 temp
= temp
.concat(this.V
);
24767 var res
= temp
.slice(0, len
);
24770 return utils
.encode(res
, enc
);
24773 },{"hash.js":147,"minimalistic-assert":176,"minimalistic-crypto-utils":177}],160:[function(require
,module
,exports
){
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
24782 var ESCAPE_LOOKUP
= {
24786 '\u2028': '\\u2028',
24787 '\u2029': '\\u2029'
24790 var ESCAPE_REGEX
= /[&><\u2028\u2029]/g;
24792 function escaper(match
) {
24793 return ESCAPE_LOOKUP
[match
];
24796 module
.exports = function(obj
) {
24797 return JSON
.stringify(obj
).replace(ESCAPE_REGEX
, escaper
);
24802 var TERMINATORS_LOOKUP
= {
24803 '\u2028': '\\u2028',
24804 '\u2029': '\\u2029'
24807 var TERMINATORS_REGEX
= /[\u2028\u2029]/g;
24809 function sanitizer(match
) {
24810 return TERMINATORS_LOOKUP
[match
];
24813 module
.exports
.sanitize = function(str
) {
24814 return str
.replace(TERMINATORS_REGEX
, sanitizer
);
24817 },{}],161:[function(require
,module
,exports
){
24818 exports
.read = function (buffer
, offset
, isLE
, mLen
, nBytes
) {
24820 var eLen
= nBytes
* 8 - mLen
- 1
24821 var eMax
= (1 << eLen
) - 1
24822 var eBias
= eMax
>> 1
24824 var i
= isLE
? (nBytes
- 1) : 0
24825 var d
= isLE
? -1 : 1
24826 var s
= buffer
[offset
+ i
]
24830 e
= s
& ((1 << (-nBits
)) - 1)
24833 for (; nBits
> 0; e
= e
* 256 + buffer
[offset
+ i
], i
+= d
, nBits
-= 8) {}
24835 m
= e
& ((1 << (-nBits
)) - 1)
24838 for (; nBits
> 0; m
= m
* 256 + buffer
[offset
+ i
], i
+= d
, nBits
-= 8) {}
24842 } else if (e
=== eMax
) {
24843 return m
? NaN : ((s
? -1 : 1) * Infinity
)
24845 m
= m
+ Math
.pow(2, mLen
)
24848 return (s
? -1 : 1) * m
* Math
.pow(2, e
- mLen
)
24851 exports
.write = function (buffer
, value
, offset
, isLE
, mLen
, nBytes
) {
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
24861 value
= Math
.abs(value
)
24863 if (isNaN(value
) || value
=== Infinity
) {
24864 m
= isNaN(value
) ? 1 : 0
24867 e
= Math
.floor(Math
.log(value
) / Math
.LN2
)
24868 if (value
* (c
= Math
.pow(2, -e
)) < 1) {
24872 if (e
+ eBias
>= 1) {
24875 value
+= rt
* Math
.pow(2, 1 - eBias
)
24877 if (value
* c
>= 2) {
24882 if (e
+ eBias
>= eMax
) {
24885 } else if (e
+ eBias
>= 1) {
24886 m
= (value
* c
- 1) * Math
.pow(2, mLen
)
24889 m
= value
* Math
.pow(2, eBias
- 1) * Math
.pow(2, mLen
)
24894 for (; mLen
>= 8; buffer
[offset
+ i
] = m
& 0xff, i
+= d
, m
/= 256, mLen
-= 8) {}
24896 e
= (e
<< mLen
) | m
24898 for (; eLen
> 0; buffer
[offset
+ i
] = e
& 0xff, i
+= d
, e
/= 256, eLen
-= 8) {}
24900 buffer
[offset
+ i
- d
] |= s
* 128
24903 },{}],162:[function(require
,module
,exports
){
24905 var indexOf
= [].indexOf
;
24907 module
.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
;
24914 },{}],163:[function(require
,module
,exports
){
24915 if (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, {
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
24939 },{}],164:[function(require
,module
,exports
){
24941 * Determine if an object is a Buffer
24943 * @author Feross Aboukhadijeh <https://feross.org>
24947 // The _isBuffer check is for Safari 5-7 support, because it's missing
24948 // Object.prototype.constructor. Remove this eventually
24949 module
.exports = function (obj
) {
24950 return obj
!= null && (isBuffer(obj
) || isSlowBuffer(obj
) || !!obj
._isBuffer
)
24953 function isBuffer (obj
) {
24954 return !!obj
.constructor && typeof obj
.constructor.isBuffer
=== 'function' && obj
.constructor.isBuffer(obj
)
24957 // For Node v0.10 support. Remove this eventually.
24958 function isSlowBuffer (obj
) {
24959 return typeof obj
.readFloatLE
=== 'function' && typeof obj
.slice
=== 'function' && isBuffer(obj
.slice(0, 0))
24962 },{}],165:[function(require
,module
,exports
){
24963 var toString
= {}.toString
;
24965 module
.exports
= Array
.isArray
|| function (arr
) {
24966 return toString
.call(arr
) == '[object Array]';
24969 },{}],166:[function(require
,module
,exports
){
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
24975 Copyright Brian Turek 2008-2017
24976 Distributed under the BSD License
24977 See http://caligatio.github.com/jsSHA/ for more information
24979 Several functions taken from Paul Johnston
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<<
24982 5)+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
,
24983 e
[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"===
24984 c
)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
%
24985 5][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);
24986 b
[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");
24987 f
=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
,
24988 0,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
||{};
24991 a
.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===
24993 b
?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
]),
24995 m
|=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
=
24996 function(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
>>>
24997 a
|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
&
24998 k
.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);
24999 c
=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
&
25001 65535)+(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),
25003 new 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
-
25004 3]^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
,
25005 a
,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
-
25006 16]),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
^
25007 m
.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,
25008 1426881987,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,
25009 2227730452,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),
25010 new 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),
25011 new 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],
25012 3733110249),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,
25013 1246189591)];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),
25014 new 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);
25016 },{}],167:[function(require
,module
,exports
){
25018 module
.exports
= require('./lib/api')(require('./lib/keccak'))
25020 },{"./lib/api":168,"./lib/keccak":172}],168:[function(require
,module
,exports
){
25022 var createKeccak
= require('./keccak')
25023 var createShake
= require('./shake')
25025 module
.exports = function (KeccakState
) {
25026 var Keccak
= createKeccak(KeccakState
)
25027 var Shake
= createShake(KeccakState
)
25029 return function (algorithm
, options
) {
25030 var hash
= typeof algorithm
=== 'string' ? algorithm
.toLowerCase() : algorithm
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
)
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
)
25042 case 'shake128': return new Shake(1344, 256, 0x1f, options
)
25043 case 'shake256': return new Shake(1088, 512, 0x1f, options
)
25045 default: throw new Error('Invald algorithm: ' + algorithm
)
25050 },{"./keccak":169,"./shake":170}],169:[function(require
,module
,exports
){
25052 var Buffer
= require('safe-buffer').Buffer
25053 var Transform
= require('stream').Transform
25054 var inherits
= require('inherits')
25056 module
.exports = function (KeccakState
) {
25057 function Keccak (rate
, capacity
, delimitedSuffix
, hashBitLength
, options
) {
25058 Transform
.call(this, options
)
25061 this._capacity
= capacity
25062 this._delimitedSuffix
= delimitedSuffix
25063 this._hashBitLength
= hashBitLength
25064 this._options
= options
25066 this._state
= new KeccakState()
25067 this._state
.initialize(rate
, capacity
)
25068 this._finalized
= false
25071 inherits(Keccak
, Transform
)
25073 Keccak
.prototype._transform = function (chunk
, encoding
, callback
) {
25076 this.update(chunk
, encoding
)
25084 Keccak
.prototype._flush = function (callback
) {
25087 this.push(this.digest())
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
)
25100 this._state
.absorb(data
)
25105 Keccak
.prototype.digest = function (encoding
) {
25106 if (this._finalized
) throw new Error('Digest already called')
25107 this._finalized
= true
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
)
25118 // remove result from memory
25119 Keccak
.prototype._resetState = function () {
25120 this._state
.initialize(this._rate
, this._capacity
)
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
25136 },{"inherits":163,"safe-buffer":247,"stream":263}],170:[function(require
,module
,exports
){
25138 var Buffer
= require('safe-buffer').Buffer
25139 var Transform
= require('stream').Transform
25140 var inherits
= require('inherits')
25142 module
.exports = function (KeccakState
) {
25143 function Shake (rate
, capacity
, delimitedSuffix
, options
) {
25144 Transform
.call(this, options
)
25147 this._capacity
= capacity
25148 this._delimitedSuffix
= delimitedSuffix
25149 this._options
= options
25151 this._state
= new KeccakState()
25152 this._state
.initialize(rate
, capacity
)
25153 this._finalized
= false
25156 inherits(Shake
, Transform
)
25158 Shake
.prototype._transform = function (chunk
, encoding
, callback
) {
25161 this.update(chunk
, encoding
)
25169 Shake
.prototype._flush = function () {}
25171 Shake
.prototype._read = function (size
) {
25172 this.push(this.squeeze(size
))
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
)
25180 this._state
.absorb(data
)
25185 Shake
.prototype.squeeze = function (dataByteLength
, encoding
) {
25186 if (!this._finalized
) {
25187 this._finalized
= true
25188 this._state
.absorbLastFewBits(this._delimitedSuffix
)
25191 var data
= this._state
.squeeze(dataByteLength
)
25192 if (encoding
!== undefined) data
= data
.toString(encoding
)
25197 Shake
.prototype._resetState = function () {
25198 this._state
.initialize(this._rate
, this._capacity
)
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
25213 },{"inherits":163,"safe-buffer":247,"stream":263}],171:[function(require
,module
,exports
){
25215 var 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]
25217 exports
.p1600 = function (s
) {
25218 for (var round
= 0; round
< 24; ++round
) {
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]
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
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)
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
)
25397 s
[0] ^= P1600_ROUND_CONSTANTS
[round
* 2]
25398 s
[1] ^= P1600_ROUND_CONSTANTS
[round
* 2 + 1]
25402 },{}],172:[function(require
,module
,exports
){
25404 var Buffer
= require('safe-buffer').Buffer
25405 var keccakState
= require('./keccak-state-unroll')
25407 function Keccak () {
25408 // much faster than `new Array(50)`
25417 this.blockSize
= null
25419 this.squeezing
= false
25422 Keccak
.prototype.initialize = function (rate
, capacity
) {
25423 for (var i
= 0; i
< 50; ++i
) this.state
[i
] = 0
25424 this.blockSize
= rate
/ 8
25426 this.squeezing
= false
25429 Keccak
.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))
25433 if (this.count
=== this.blockSize
) {
25434 keccakState
.p1600(this.state
)
25440 Keccak
.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
)
25446 this.squeezing
= true
25449 Keccak
.prototype.squeeze = function (length
) {
25450 if (!this.squeezing
) this.absorbLastFewBits(0x01)
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
25456 if (this.count
=== this.blockSize
) {
25457 keccakState
.p1600(this.state
)
25465 Keccak
.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
25472 module
.exports
= Keccak
25474 },{"./keccak-state-unroll":171,"safe-buffer":247}],173:[function(require
,module
,exports
){
25475 (function (Buffer
){
25477 var inherits
= require('inherits')
25478 var HashBase
= require('hash-base')
25480 var ARRAY16
= new Array(16)
25483 HashBase
.call(this, 64)
25486 this._a
= 0x67452301
25487 this._b
= 0xefcdab89
25488 this._c
= 0x98badcfe
25489 this._d
= 0x10325476
25492 inherits(MD5
, HashBase
)
25494 MD5
.prototype._update = function () {
25496 for (var i
= 0; i
< 16; ++i
) M
[i
] = this._block
.readInt32LE(i
* 4)
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)
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)
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)
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)
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
25577 MD5
.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)
25583 this._blockOffset
= 0
25586 this._block
.fill(0, this._blockOffset
, 56)
25587 this._block
.writeUInt32LE(this._length
[0], 56)
25588 this._block
.writeUInt32LE(this._length
[1], 60)
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)
25600 function rotl (x
, n
) {
25601 return (x
<< n
) | (x
>>> (32 - n
))
25604 function fnF (a
, b
, c
, d
, m
, k
, s
) {
25605 return (rotl((a
+ ((b
& c
) | ((~b
) & d
)) + m
+ k
) | 0, s
) + b
) | 0
25608 function fnG (a
, b
, c
, d
, m
, k
, s
) {
25609 return (rotl((a
+ ((b
& d
) | (c
& (~d
))) + m
+ k
) | 0, s
) + b
) | 0
25612 function fnH (a
, b
, c
, d
, m
, k
, s
) {
25613 return (rotl((a
+ (b
^ c
^ d
) + m
+ k
) | 0, s
) + b
) | 0
25616 function fnI (a
, b
, c
, d
, m
, k
, s
) {
25617 return (rotl((a
+ ((c
^ (b
| (~d
)))) + m
+ k
) | 0, s
) + b
) | 0
25620 module
.exports
= MD5
25622 }).call(this,require("buffer").Buffer
)
25623 },{"buffer":107,"hash-base":174,"inherits":163}],174:[function(require
,module
,exports
){
25625 var Buffer
= require('safe-buffer').Buffer
25626 var Transform
= require('stream').Transform
25627 var inherits
= require('inherits')
25629 function throwIfNotStringOrBuffer (val
, prefix
) {
25630 if (!Buffer
.isBuffer(val
) && typeof val
!== 'string') {
25631 throw new TypeError(prefix
+ ' must be a string or a buffer')
25635 function HashBase (blockSize
) {
25636 Transform
.call(this)
25638 this._block
= Buffer
.allocUnsafe(blockSize
)
25639 this._blockSize
= blockSize
25640 this._blockOffset
= 0
25641 this._length
= [0, 0, 0, 0]
25643 this._finalized
= false
25646 inherits(HashBase
, Transform
)
25648 HashBase
.prototype._transform = function (chunk
, encoding
, callback
) {
25651 this.update(chunk
, encoding
)
25659 HashBase
.prototype._flush = function (callback
) {
25662 this.push(this.digest())
25670 HashBase
.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
)
25676 var block
= this._block
25678 while (this._blockOffset
+ data
.length
- offset
>= this._blockSize
) {
25679 for (var i
= this._blockOffset
; i
< this._blockSize
;) block
[i
++] = data
[offset
++]
25681 this._blockOffset
= 0
25683 while (offset
< data
.length
) block
[this._blockOffset
++] = data
[offset
++]
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
25695 HashBase
.prototype._update = function () {
25696 throw new Error('_update is not implemented')
25699 HashBase
.prototype.digest = function (encoding
) {
25700 if (this._finalized
) throw new Error('Digest already called')
25701 this._finalized
= true
25703 var digest
= this._digest()
25704 if (encoding
!== undefined) digest
= digest
.toString(encoding
)
25707 this._block
.fill(0)
25708 this._blockOffset
= 0
25709 for (var i
= 0; i
< 4; ++i
) this._length
[i
] = 0
25714 HashBase
.prototype._digest = function () {
25715 throw new Error('_digest is not implemented')
25718 module
.exports
= HashBase
25720 },{"inherits":163,"safe-buffer":247,"stream":263}],175:[function(require
,module
,exports
){
25721 var bn
= require('bn.js');
25722 var brorand
= require('brorand');
25724 function MillerRabin(rand
) {
25725 this.rand
= rand
|| new brorand
.Rand();
25727 module
.exports
= MillerRabin
;
25729 MillerRabin
.create
= function create(rand
) {
25730 return new MillerRabin(rand
);
25733 MillerRabin
.prototype._randbelow
= function _randbelow(n
) {
25734 var len
= n
.bitLength();
25735 var min_bytes
= Math
.ceil(len
/ 8);
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.
25740 var a
= new bn(this.rand
.generate(min_bytes
));
25741 while (a
.cmp(n
) >= 0);
25746 MillerRabin
.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
));
25752 MillerRabin
.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
);
25758 k
= Math
.max(1, (len
/ 48) | 0);
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
++) {}
25765 var rn1
= n1
.toRed(red
);
25768 for (; k
> 0; k
--) {
25769 var a
= this._randrange(new bn(2), n1
);
25773 var x
= a
.toRed(red
).redPow(d
);
25774 if (x
.cmp(rone
) === 0 || x
.cmp(rn1
) === 0)
25777 for (var i
= 1; i
< s
; i
++) {
25780 if (x
.cmp(rone
) === 0)
25782 if (x
.cmp(rn1
) === 0)
25793 MillerRabin
.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
);
25799 k
= Math
.max(1, (len
/ 48) | 0);
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
++) {}
25806 var rn1
= n1
.toRed(red
);
25808 for (; k
> 0; k
--) {
25809 var a
= this._randrange(new bn(2), n1
);
25812 if (g
.cmpn(1) !== 0)
25815 var x
= a
.toRed(red
).redPow(d
);
25816 if (x
.cmp(rone
) === 0 || x
.cmp(rn1
) === 0)
25819 for (var i
= 1; i
< s
; i
++) {
25822 if (x
.cmp(rone
) === 0)
25823 return x
.fromRed().subn(1).gcd(n
);
25824 if (x
.cmp(rn1
) === 0)
25830 return x
.fromRed().subn(1).gcd(n
);
25837 },{"bn.js":75,"brorand":76}],176:[function(require
,module
,exports
){
25838 module
.exports
= assert
;
25840 function assert(val
, msg
) {
25842 throw new Error(msg
|| 'Assertion failed');
25845 assert
.equal
= function assertEqual(l
, r
, msg
) {
25847 throw new Error(msg
|| ('Assertion failed: ' + l
+ ' != ' + r
));
25850 },{}],177:[function(require
,module
,exports
){
25853 var utils
= exports
;
25855 function toArray(msg
, enc
) {
25856 if (Array
.isArray(msg
))
25857 return msg
.slice();
25861 if (typeof msg
!== 'string') {
25862 for (var i
= 0; i
< msg
.length
; i
++)
25863 res
[i
] = msg
[i
] | 0;
25866 if (enc
=== 'hex') {
25867 msg
= msg
.replace(/[^a-z0-9]+/ig, '');
25868 if (msg
.length
% 2 !== 0)
25870 for (var i
= 0; i
< msg
.length
; i
+= 2)
25871 res
.push(parseInt(msg
[i
] + msg
[i
+ 1], 16));
25873 for (var i
= 0; i
< msg
.length
; i
++) {
25874 var c
= msg
.charCodeAt(i
);
25885 utils
.toArray
= toArray
;
25887 function zero2(word
) {
25888 if (word
.length
=== 1)
25893 utils
.zero2
= zero2
;
25895 function toHex(msg
) {
25897 for (var i
= 0; i
< msg
.length
; i
++)
25898 res
+= zero2(msg
[i
].toString(16));
25901 utils
.toHex
= toHex
;
25903 utils
.encode
= function encode(arr
, enc
) {
25910 },{}],178:[function(require
,module
,exports
){
25911 module
.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"
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.
25929 var asn1
= require('asn1.js')
25931 exports
.certificate
= require('./certificate')
25933 var RSAPrivateKey
= asn1
.define('RSAPrivateKey', function () {
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()
25946 exports
.RSAPrivateKey
= RSAPrivateKey
25948 var RSAPublicKey
= asn1
.define('RSAPublicKey', function () {
25950 this.key('modulus').int(),
25951 this.key('publicExponent').int()
25954 exports
.RSAPublicKey
= RSAPublicKey
25956 var PublicKey
= asn1
.define('SubjectPublicKeyInfo', function () {
25958 this.key('algorithm').use(AlgorithmIdentifier
),
25959 this.key('subjectPublicKey').bitstr()
25962 exports
.PublicKey
= PublicKey
25964 var AlgorithmIdentifier
= asn1
.define('AlgorithmIdentifier', function () {
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()
25977 var PrivateKeyInfo
= asn1
.define('PrivateKeyInfo', function () {
25979 this.key('version').int(),
25980 this.key('algorithm').use(AlgorithmIdentifier
),
25981 this.key('subjectPrivateKey').octstr()
25984 exports
.PrivateKey
= PrivateKeyInfo
25985 var EncryptedPrivateKeyInfo
= asn1
.define('EncryptedPrivateKeyInfo', function () {
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()
25997 this.key('cipher').seq().obj(
25998 this.key('algo').objid(),
25999 this.key('iv').octstr()
26003 this.key('subjectPrivateKey').octstr()
26007 exports
.EncryptedPrivateKey
= EncryptedPrivateKeyInfo
26009 var DSAPrivateKey
= asn1
.define('DSAPrivateKey', function () {
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()
26019 exports
.DSAPrivateKey
= DSAPrivateKey
26021 exports
.DSAparam
= asn1
.define('DSAparam', function () {
26025 var ECPrivateKey
= asn1
.define('ECPrivateKey', function () {
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()
26033 exports
.ECPrivateKey
= ECPrivateKey
26035 var ECParameters
= asn1
.define('ECParameters', function () {
26037 namedCurve: this.objid()
26041 exports
.signature
= asn1
.define('signature', function () {
26043 this.key('r').int(),
26044 this.key('s').int()
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
26054 var asn
= require('asn1.js')
26056 var Time
= asn
.define('Time', function () {
26058 utcTime: this.utctime(),
26059 generalTime: this.gentime()
26063 var AttributeTypeValue
= asn
.define('AttributeTypeValue', function () {
26065 this.key('type').objid(),
26066 this.key('value').any()
26070 var AlgorithmIdentifier
= asn
.define('AlgorithmIdentifier', function () {
26072 this.key('algorithm').objid(),
26073 this.key('parameters').optional()
26077 var SubjectPublicKeyInfo
= asn
.define('SubjectPublicKeyInfo', function () {
26079 this.key('algorithm').use(AlgorithmIdentifier
),
26080 this.key('subjectPublicKey').bitstr()
26084 var RelativeDistinguishedName
= asn
.define('RelativeDistinguishedName', function () {
26085 this.setof(AttributeTypeValue
)
26088 var RDNSequence
= asn
.define('RDNSequence', function () {
26089 this.seqof(RelativeDistinguishedName
)
26092 var Name
= asn
.define('Name', function () {
26094 rdnSequence: this.use(RDNSequence
)
26098 var Validity
= asn
.define('Validity', function () {
26100 this.key('notBefore').use(Time
),
26101 this.key('notAfter').use(Time
)
26105 var Extension
= asn
.define('Extension', function () {
26107 this.key('extnID').objid(),
26108 this.key('critical').bool().def(false),
26109 this.key('extnValue').octstr()
26113 var TBSCertificate
= asn
.define('TBSCertificate', function () {
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()
26128 var X509Certificate
= asn
.define('X509Certificate', function () {
26130 this.key('tbsCertificate').use(TBSCertificate
),
26131 this.key('signatureAlgorithm').use(AlgorithmIdentifier
),
26132 this.key('signatureValue').bitstr()
26136 module
.exports
= X509Certificate
26138 },{"asn1.js":32}],181:[function(require
,module
,exports
){
26139 (function (Buffer
){
26140 // adapted from https://github.com/apatil/pemstrip
26141 var 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
26142 var startRegex
= /^-----BEGIN ((?:.* KEY
)|CERTIFICATE
)-----\n/m
26143 var fullRegex
= /^-----BEGIN ((?:.* KEY
)|CERTIFICATE
)-----\n\r?([0-9A
-z
\n\r\+\/\=]+)\n\r?-----END
\1-----$/m
26144 var evp
= require('evp_bytestokey')
26145 var ciphers
= require('browserify-aes')
26146 module
.exports = function (okey
, password
) {
26147 var key
= okey
.toString()
26148 var match
= key
.match(findProc
)
26151 var match2
= key
.match(fullRegex
)
26152 decrypted
= new Buffer(match2
[2].replace(/\r?\n/g, ''), 'base64')
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
26159 var cipher
= ciphers
.createDecipheriv(suite
, cipherKey
, iv
)
26160 out
.push(cipher
.update(cipherText
))
26161 out
.push(cipher
.final())
26162 decrypted
= Buffer
.concat(out
)
26164 var tag
= key
.match(startRegex
)[1]
26171 }).call(this,require("buffer").Buffer
)
26172 },{"browserify-aes":80,"buffer":107,"evp_bytestokey":144}],182:[function(require
,module
,exports
){
26173 (function (Buffer
){
26174 var asn1
= require('./asn1')
26175 var aesid
= require('./aesid.json')
26176 var fixProc
= require('./fixProc')
26177 var ciphers
= require('browserify-aes')
26178 var compat
= require('pbkdf2')
26179 module
.exports
= parseKeys
26181 function parseKeys (buffer
) {
26183 if (typeof buffer
=== 'object' && !Buffer
.isBuffer(buffer
)) {
26184 password
= buffer
.passphrase
26185 buffer
= buffer
.key
26187 if (typeof buffer
=== 'string') {
26188 buffer
= new Buffer(buffer
)
26191 var stripped
= fixProc(buffer
, password
)
26193 var type
= stripped
.tag
26194 var data
= stripped
.data
26197 case 'CERTIFICATE':
26198 ndata
= asn1
.certificate
.decode(data
, 'der').tbsCertificate
.subjectPublicKeyInfo
26202 ndata
= asn1
.PublicKey
.decode(data
, 'der')
26204 subtype
= ndata
.algorithm
.algorithm
.join('.')
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
26214 case '1.2.840.10040.4.1':
26215 ndata
.algorithm
.params
.pub_key
= asn1
.DSAparam
.decode(ndata
.subjectPublicKey
.data
, 'der')
26218 data: ndata
.algorithm
.params
26220 default: throw new Error('unknown key id ' + subtype
)
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
)
26227 case 'PRIVATE KEY':
26228 ndata
= asn1
.PrivateKey
.decode(data
, 'der')
26229 subtype
= ndata
.algorithm
.algorithm
.join('.')
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':
26235 curve: ndata
.algorithm
.curve
,
26236 privateKey: asn1
.ECPrivateKey
.decode(ndata
.subjectPrivateKey
, 'der').privateKey
26238 case '1.2.840.10040.4.1':
26239 ndata
.algorithm
.params
.priv_key
= asn1
.DSAparam
.decode(ndata
.subjectPrivateKey
, 'der')
26242 params: ndata
.algorithm
.params
26244 default: throw new Error('unknown key id ' + subtype
)
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':
26254 params: asn1
.DSAPrivateKey
.decode(data
, 'der')
26256 case 'EC PRIVATE KEY':
26257 data
= asn1
.ECPrivateKey
.decode(data
, 'der')
26259 curve: data
.parameters
.value
,
26260 privateKey: data
.privateKey
26262 default: throw new Error('unknown key type ' + type
)
26265 parseKeys
.signature
= asn1
.signature
26266 function 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
)
26276 out
.push(cipher
.update(cipherText
))
26277 out
.push(cipher
.final())
26278 return Buffer
.concat(out
)
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.
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:
26294 // The above copyright notice and this permission notice shall be included
26295 // in all copies or substantial portions of the Software.
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.
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)
26309 function normalizeArray(parts
, allowAboveRoot
) {
26310 // if the path tries to go above the root, `up` ends 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);
26320 parts
.splice(i
, 1);
26325 // if the path is allowed to go above the root, restore leading ..s
26326 if (allowAboveRoot
) {
26328 parts
.unshift('..');
26335 // Split a filename into [root, dir, basename, ext], unix version
26336 // 'root' is just a slash, or nothing.
26338 /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/;
26339 var splitPath = function(filename
) {
26340 return splitPathRe
.exec(filename
).slice(1);
26343 // path.resolve([from ...], to)
26345 exports
.resolve = function() {
26346 var resolvedPath
= '',
26347 resolvedAbsolute
= false;
26349 for (var i
= arguments
.length
- 1; i
>= -1 && !resolvedAbsolute
; i
--) {
26350 var path
= (i
>= 0) ? arguments
[i
] : process
.cwd();
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
) {
26359 resolvedPath
= path
+ '/' + resolvedPath
;
26360 resolvedAbsolute
= path
.charAt(0) === '/';
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)
26366 // Normalize the path
26367 resolvedPath
= normalizeArray(filter(resolvedPath
.split('/'), function(p
) {
26369 }), !resolvedAbsolute
).join('/');
26371 return ((resolvedAbsolute
? '/' : '') + resolvedPath
) || '.';
26374 // path.normalize(path)
26376 exports
.normalize = function(path
) {
26377 var isAbsolute
= exports
.isAbsolute(path
),
26378 trailingSlash
= substr(path
, -1) === '/';
26380 // Normalize the path
26381 path
= normalizeArray(filter(path
.split('/'), function(p
) {
26383 }), !isAbsolute
).join('/');
26385 if (!path
&& !isAbsolute
) {
26388 if (path
&& trailingSlash
) {
26392 return (isAbsolute
? '/' : '') + path
;
26396 exports
.isAbsolute = function(path
) {
26397 return path
.charAt(0) === '/';
26401 exports
.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');
26412 // path.relative(from, to)
26414 exports
.relative = function(from, to
) {
26415 from = exports
.resolve(from).substr(1);
26416 to
= exports
.resolve(to
).substr(1);
26418 function trim(arr
) {
26420 for (; start
< arr
.length
; start
++) {
26421 if (arr
[start
] !== '') break;
26424 var end
= arr
.length
- 1;
26425 for (; end
>= 0; end
--) {
26426 if (arr
[end
] !== '') break;
26429 if (start
> end
) return [];
26430 return arr
.slice(start
, end
- start
+ 1);
26433 var fromParts
= trim(from.split('/'));
26434 var toParts
= trim(to
.split('/'));
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
;
26445 var outputParts
= [];
26446 for (var i
= samePartsLength
; i
< fromParts
.length
; i
++) {
26447 outputParts
.push('..');
26450 outputParts
= outputParts
.concat(toParts
.slice(samePartsLength
));
26452 return outputParts
.join('/');
26456 exports
.delimiter
= ':';
26458 exports
.dirname = function(path
) {
26459 var result
= splitPath(path
),
26463 if (!root
&& !dir
) {
26464 // No dirname whatsoever
26469 // It has a dirname, strip trailing slash
26470 dir
= dir
.substr(0, dir
.length
- 1);
26477 exports
.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
);
26487 exports
.extname = function(path
) {
26488 return splitPath(path
)[3];
26491 function filter (xs
, f
) {
26492 if (xs
.filter
) return xs
.filter(f
);
26494 for (var i
= 0; i
< xs
.length
; i
++) {
26495 if (f(xs
[i
], i
, xs
)) res
.push(xs
[i
]);
26500 // String.prototype.substr - negative index don't work in IE8
26501 var 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
);
26509 }).call(this,require('_process'))
26510 },{"_process":190}],184:[function(require
,module
,exports
){
26512 exports
.pbkdf2
= require('./lib/async')
26514 exports
.pbkdf2Sync
= require('./lib/sync')
26516 },{"./lib/async":185,"./lib/sync":188}],185:[function(require
,module
,exports
){
26517 (function (process
,global
){
26518 var checkParameters
= require('./precondition')
26519 var defaultEncoding
= require('./default-encoding')
26520 var sync
= require('./sync')
26521 var Buffer
= require('safe-buffer').Buffer
26524 var subtle
= global
.crypto
&& global
.crypto
.subtle
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'
26537 function checkNative (algo
) {
26538 if (global
.process
&& !global
.process
.browser
) {
26539 return Promise
.resolve(false)
26541 if (!subtle
|| !subtle
.importKey
|| !subtle
.deriveBits
) {
26542 return Promise
.resolve(false)
26544 if (checks
[algo
] !== undefined) {
26545 return checks
[algo
]
26547 ZERO_BUF
= ZERO_BUF
|| Buffer
.alloc(8)
26548 var prom
= browserPbkdf2(ZERO_BUF
, ZERO_BUF
, 10, 128, algo
)
26549 .then(function () {
26551 }).catch(function () {
26554 checks
[algo
] = prom
26557 function 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({
26564 iterations: iterations
,
26568 }, key
, length
<< 3)
26569 }).then(function (res
) {
26570 return Buffer
.from(res
)
26573 function resolvePromise (promise
, callback
) {
26574 promise
.then(function (out
) {
26575 process
.nextTick(function () {
26576 callback(null, out
)
26579 process
.nextTick(function () {
26584 module
.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
)
26588 checkParameters(iterations
, keylen
)
26589 if (typeof digest
=== 'function') {
26593 if (typeof callback
!== 'function') throw new Error('No callback provided to pbkdf2')
26595 digest
= digest
|| 'sha1'
26596 var algo
= toBrowser
[digest
.toLowerCase()]
26597 if (!algo
|| typeof global
.Promise
!== 'function') {
26598 return process
.nextTick(function () {
26601 out
= sync(password
, salt
, iterations
, keylen
, digest
)
26605 callback(null, out
)
26608 resolvePromise(checkNative(algo
).then(function (resp
) {
26610 return browserPbkdf2(password
, salt
, iterations
, keylen
, algo
)
26612 return sync(password
, salt
, iterations
, keylen
, digest
)
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
){
26620 var defaultEncoding
26621 /* istanbul ignore next */
26622 if (process
.browser
) {
26623 defaultEncoding
= 'utf-8'
26625 var pVersionMajor
= parseInt(process
.version
.split('.')[0].slice(1), 10)
26627 defaultEncoding
= pVersionMajor
>= 6 ? 'utf-8' : 'binary'
26629 module
.exports
= defaultEncoding
26631 }).call(this,require('_process'))
26632 },{"_process":190}],187:[function(require
,module
,exports
){
26633 var MAX_ALLOC
= Math
.pow(2, 30) - 1 // default in iojs
26634 module
.exports = function (iterations
, keylen
) {
26635 if (typeof iterations
!== 'number') {
26636 throw new TypeError('Iterations not a number')
26639 if (iterations
< 0) {
26640 throw new TypeError('Bad iterations')
26643 if (typeof keylen
!== 'number') {
26644 throw new TypeError('Key length not a number')
26647 if (keylen
< 0 || keylen
> MAX_ALLOC
|| keylen
!== keylen
) { /* eslint no-self-compare: 0 */
26648 throw new TypeError('Bad key length')
26652 },{}],188:[function(require
,module
,exports
){
26653 var md5
= require('create-hash/md5')
26654 var rmd160
= require('ripemd160')
26655 var sha
= require('sha.js')
26657 var checkParameters
= require('./precondition')
26658 var defaultEncoding
= require('./default-encoding')
26659 var Buffer
= require('safe-buffer').Buffer
26660 var ZEROS
= Buffer
.alloc(128)
26672 function Hmac (alg
, key
, saltLen
) {
26673 var hash
= getDigest(alg
)
26674 var blocksize
= (alg
=== 'sha512' || alg
=== 'sha384') ? 128 : 64
26676 if (key
.length
> blocksize
) {
26678 } else if (key
.length
< blocksize
) {
26679 key
= Buffer
.concat([key
, ZEROS
], blocksize
)
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
26689 var ipad1
= Buffer
.allocUnsafe(blocksize
+ saltLen
+ 4)
26690 ipad
.copy(ipad1
, 0, 0, blocksize
)
26695 this.blocksize
= blocksize
26697 this.size
= sizes
[alg
]
26700 Hmac
.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
)
26707 function getDigest (alg
) {
26708 function shaFunc (data
) {
26709 return sha(alg
).update(data
).digest()
26712 if (alg
=== 'rmd160' || alg
=== 'ripemd160') return rmd160
26713 if (alg
=== 'md5') return md5
26717 function 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
)
26721 checkParameters(iterations
, keylen
)
26723 digest
= digest
|| 'sha1'
26725 var hmac
= new Hmac(digest
, password
, salt
.length
)
26727 var DK
= Buffer
.allocUnsafe(keylen
)
26728 var block1
= Buffer
.allocUnsafe(salt
.length
+ 4)
26729 salt
.copy(block1
, 0, 0, salt
.length
)
26732 var hLen
= sizes
[digest
]
26733 var l
= Math
.ceil(keylen
/ hLen
)
26735 for (var i
= 1; i
<= l
; i
++) {
26736 block1
.writeUInt32BE(i
, salt
.length
)
26738 var T
= hmac
.run(block1
, hmac
.ipad1
)
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
]
26746 T
.copy(DK
, destPos
)
26753 module
.exports
= pbkdf2
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
){
26759 if (!process
.version
||
26760 process
.version
.indexOf('v0.') === 0 ||
26761 process
.version
.indexOf('v1.') === 0 && process
.version
.indexOf('v1.8.') !== 0) {
26762 module
.exports
= nextTick
;
26764 module
.exports
= process
.nextTick
;
26767 function nextTick(fn
, arg1
, arg2
, arg3
) {
26768 if (typeof fn
!== 'function') {
26769 throw new TypeError('"callback" argument must be a function');
26771 var len
= arguments
.length
;
26776 return process
.nextTick(fn
);
26778 return process
.nextTick(function afterTickOne() {
26779 fn
.call(null, arg1
);
26782 return process
.nextTick(function afterTickTwo() {
26783 fn
.call(null, arg1
, arg2
);
26786 return process
.nextTick(function afterTickThree() {
26787 fn
.call(null, arg1
, arg2
, arg3
);
26790 args
= new Array(len
- 1);
26792 while (i
< args
.length
) {
26793 args
[i
++] = arguments
[i
];
26795 return process
.nextTick(function afterTick() {
26796 fn
.apply(null, args
);
26801 }).call(this,require('_process'))
26802 },{"_process":190}],190:[function(require
,module
,exports
){
26803 // shim for using process in browser
26804 var process
= module
.exports
= {};
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.
26811 var cachedSetTimeout
;
26812 var cachedClearTimeout
;
26814 function defaultSetTimout() {
26815 throw new Error('setTimeout has not been defined');
26817 function defaultClearTimeout () {
26818 throw new Error('clearTimeout has not been defined');
26822 if (typeof setTimeout
=== 'function') {
26823 cachedSetTimeout
= setTimeout
;
26825 cachedSetTimeout
= defaultSetTimout
;
26828 cachedSetTimeout
= defaultSetTimout
;
26831 if (typeof clearTimeout
=== 'function') {
26832 cachedClearTimeout
= clearTimeout
;
26834 cachedClearTimeout
= defaultClearTimeout
;
26837 cachedClearTimeout
= defaultClearTimeout
;
26840 function runTimeout(fun
) {
26841 if (cachedSetTimeout
=== setTimeout
) {
26842 //normal enviroments in sane situations
26843 return setTimeout(fun
, 0);
26845 // if setTimeout wasn't available but was latter defined
26846 if ((cachedSetTimeout
=== defaultSetTimout
|| !cachedSetTimeout
) && setTimeout
) {
26847 cachedSetTimeout
= setTimeout
;
26848 return setTimeout(fun
, 0);
26851 // when when somebody has screwed with setTimeout but no I.E. maddness
26852 return cachedSetTimeout(fun
, 0);
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);
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);
26865 function runClearTimeout(marker
) {
26866 if (cachedClearTimeout
=== clearTimeout
) {
26867 //normal enviroments in sane situations
26868 return clearTimeout(marker
);
26870 // if clearTimeout wasn't available but was latter defined
26871 if ((cachedClearTimeout
=== defaultClearTimeout
|| !cachedClearTimeout
) && clearTimeout
) {
26872 cachedClearTimeout
= clearTimeout
;
26873 return clearTimeout(marker
);
26876 // when when somebody has screwed with setTimeout but no I.E. maddness
26877 return cachedClearTimeout(marker
);
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
);
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
);
26893 var draining
= false;
26895 var queueIndex
= -1;
26897 function cleanUpNextTick() {
26898 if (!draining
|| !currentQueue
) {
26902 if (currentQueue
.length
) {
26903 queue
= currentQueue
.concat(queue
);
26907 if (queue
.length
) {
26912 function drainQueue() {
26916 var timeout
= runTimeout(cleanUpNextTick
);
26919 var len
= queue
.length
;
26921 currentQueue
= queue
;
26923 while (++queueIndex
< len
) {
26924 if (currentQueue
) {
26925 currentQueue
[queueIndex
].run();
26929 len
= queue
.length
;
26931 currentQueue
= null;
26933 runClearTimeout(timeout
);
26936 process
.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
];
26943 queue
.push(new Item(fun
, args
));
26944 if (queue
.length
=== 1 && !draining
) {
26945 runTimeout(drainQueue
);
26949 // v8 likes predictible objects
26950 function Item(fun
, array
) {
26952 this.array
= array
;
26954 Item
.prototype.run = function () {
26955 this.fun
.apply(null, this.array
);
26957 process
.title
= 'browser';
26958 process
.browser
= true;
26961 process
.version
= ''; // empty string to avoid regexp issues
26962 process
.versions
= {};
26967 process
.addListener
= noop
;
26968 process
.once
= noop
;
26969 process
.off
= noop
;
26970 process
.removeListener
= noop
;
26971 process
.removeAllListeners
= noop
;
26972 process
.emit
= noop
;
26973 process
.prependListener
= noop
;
26974 process
.prependOnceListener
= noop
;
26976 process
.listeners = function (name
) { return [] }
26978 process
.binding = function (name
) {
26979 throw new Error('process.binding is not supported');
26982 process
.cwd = function () { return '/' };
26983 process
.chdir = function (dir
) {
26984 throw new Error('process.chdir is not supported');
26986 process
.umask = function() { return 0; };
26988 },{}],191:[function(require
,module
,exports
){
26989 // full library entry point.
26992 module
.exports
= require("./src/index");
26994 },{"./src/index":200}],192:[function(require
,module
,exports
){
26996 module
.exports
= common
;
26998 var commonRe
= /\/|\./;
27001 * Provides common type definitions.
27002 * Can also be used to provide additional google types or your own custom types.
27003 * @param {string} name Short name as in `google/protobuf/[name].proto` or full file name
27004 * @param {Object.<string,*>} json JSON definition within `google.protobuf` if a short name, otherwise the file's root definition
27005 * @returns {undefined}
27006 * @property {INamespace} google/protobuf/any.proto Any
27007 * @property {INamespace} google/protobuf/duration.proto Duration
27008 * @property {INamespace} google/protobuf/empty.proto Empty
27009 * @property {INamespace} google/protobuf/field_mask.proto FieldMask
27010 * @property {INamespace} google/protobuf/struct.proto Struct, Value, NullValue and ListValue
27011 * @property {INamespace} google/protobuf/timestamp.proto Timestamp
27012 * @property {INamespace} google/protobuf/wrappers.proto Wrappers
27014 * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension)
27015 * protobuf.common("descriptor", descriptorJson);
27017 * // manually provides a custom definition (uses my.foo namespace)
27018 * protobuf.common("my/foo/bar.proto", myFooBarJson);
27020 function common(name
, json
) {
27021 if (!commonRe
.test(name
)) {
27022 name
= "google/protobuf/" + name
+ ".proto";
27023 json
= { nested: { google: { nested: { protobuf: { nested: json
} } } } };
27025 common
[name
] = json
;
27028 // Not provided because of limited use (feel free to discuss or to provide yourself):
27030 // google/protobuf/descriptor.proto
27031 // google/protobuf/source_context.proto
27032 // google/protobuf/type.proto
27034 // Stripped and pre-parsed versions of these non-bundled files are instead available as part of
27035 // the repository or package within the google/protobuf directory.
27040 * Properties of a google.protobuf.Any message.
27043 * @property {string} [typeUrl]
27044 * @property {Uint8Array} [bytes]
27063 common("duration", {
27066 * Properties of a google.protobuf.Duration message.
27067 * @interface IDuration
27069 * @property {number|Long} [seconds]
27070 * @property {number} [nanos]
27073 Duration: timeType
= {
27087 common("timestamp", {
27090 * Properties of a google.protobuf.Timestamp message.
27091 * @interface ITimestamp
27093 * @property {number|Long} [seconds]
27094 * @property {number} [nanos]
27097 Timestamp: timeType
27103 * Properties of a google.protobuf.Empty message.
27104 * @interface IEmpty
27115 * Properties of a google.protobuf.Struct message.
27116 * @interface IStruct
27118 * @property {Object.<string,IValue>} [fields]
27132 * Properties of a google.protobuf.Value message.
27133 * @interface IValue
27135 * @property {string} [kind]
27136 * @property {0} [nullValue]
27137 * @property {number} [numberValue]
27138 * @property {string} [stringValue]
27139 * @property {boolean} [boolValue]
27140 * @property {IStruct} [structValue]
27141 * @property {IListValue} [listValue]
27192 * Properties of a google.protobuf.ListValue message.
27193 * @interface IListValue
27195 * @property {Array.<IValue>} [values]
27209 common("wrappers", {
27212 * Properties of a google.protobuf.DoubleValue message.
27213 * @interface IDoubleValue
27215 * @property {number} [value]
27228 * Properties of a google.protobuf.FloatValue message.
27229 * @interface IFloatValue
27231 * @property {number} [value]
27244 * Properties of a google.protobuf.Int64Value message.
27245 * @interface IInt64Value
27247 * @property {number|Long} [value]
27260 * Properties of a google.protobuf.UInt64Value message.
27261 * @interface IUInt64Value
27263 * @property {number|Long} [value]
27276 * Properties of a google.protobuf.Int32Value message.
27277 * @interface IInt32Value
27279 * @property {number} [value]
27292 * Properties of a google.protobuf.UInt32Value message.
27293 * @interface IUInt32Value
27295 * @property {number} [value]
27308 * Properties of a google.protobuf.BoolValue message.
27309 * @interface IBoolValue
27311 * @property {boolean} [value]
27324 * Properties of a google.protobuf.StringValue message.
27325 * @interface IStringValue
27327 * @property {string} [value]
27340 * Properties of a google.protobuf.BytesValue message.
27341 * @interface IBytesValue
27343 * @property {Uint8Array} [value]
27356 common("field_mask", {
27359 * Properties of a google.protobuf.FieldMask message.
27360 * @interface IDoubleValue
27362 * @property {number} [value]
27377 * Gets the root definition of the specified common proto file.
27379 * Bundled definitions are:
27380 * - google/protobuf/any.proto
27381 * - google/protobuf/duration.proto
27382 * - google/protobuf/empty.proto
27383 * - google/protobuf/field_mask.proto
27384 * - google/protobuf/struct.proto
27385 * - google/protobuf/timestamp.proto
27386 * - google/protobuf/wrappers.proto
27388 * @param {string} file Proto file name
27389 * @returns {INamespace|null} Root definition or `null` if not defined
27391 common
.get = function get(file
) {
27392 return common
[file
] || null;
27395 },{}],193:[function(require
,module
,exports
){
27398 * Runtime message from/to plain object converters.
27401 var converter
= exports
;
27403 var Enum
= require("./enum"),
27404 util
= require("./util");
27407 * Generates a partial value fromObject conveter.
27408 * @param {Codegen} gen Codegen instance
27409 * @param {Field} field Reflected field
27410 * @param {number} fieldIndex Field index
27411 * @param {string} prop Property reference
27412 * @returns {Codegen} Codegen instance
27415 function genValuePartial_fromObject(gen
, field
, fieldIndex
, prop
) {
27416 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27417 if (field
.resolvedType
) {
27418 if (field
.resolvedType
instanceof Enum
) { gen
27419 ("switch(d%s){", prop
);
27420 for (var values
= field
.resolvedType
.values
, keys
= Object
.keys(values
), i
= 0; i
< keys
.length
; ++i
) {
27421 if (field
.repeated
&& values
[keys
[i
]] === field
.typeDefault
) gen
27424 ("case%j:", keys
[i
])
27425 ("case %i:", values
[keys
[i
]])
27426 ("m%s=%j", prop
, values
[keys
[i
]])
27431 ("if(typeof d%s!==\"object\")", prop
)
27432 ("throw TypeError(%j)", field
.fullName
+ ": object expected")
27433 ("m%s=types[%i].fromObject(d%s)", prop
, fieldIndex
, prop
);
27435 var isUnsigned
= false;
27436 switch (field
.type
) {
27439 ("m%s=Number(d%s)", prop
, prop
); // also catches "NaN", "Infinity"
27442 case "fixed32": gen
27443 ("m%s=d%s>>>0", prop
, prop
);
27447 case "sfixed32": gen
27448 ("m%s=d%s|0", prop
, prop
);
27452 // eslint-disable-line no-fallthrough
27456 case "sfixed64": gen
27458 ("(m%s=util.Long.fromValue(d%s)).unsigned=%j", prop
, prop
, isUnsigned
)
27459 ("else if(typeof d%s===\"string\")", prop
)
27460 ("m%s=parseInt(d%s,10)", prop
, prop
)
27461 ("else if(typeof d%s===\"number\")", prop
)
27462 ("m%s=d%s", prop
, prop
)
27463 ("else if(typeof d%s===\"object\")", prop
)
27464 ("m%s=new util.LongBits(d%s.low>>>0,d%s.high>>>0).toNumber(%s)", prop
, prop
, prop
, isUnsigned
? "true" : "");
27467 ("if(typeof d%s===\"string\")", prop
)
27468 ("util.base64.decode(d%s,m%s=util.newBuffer(util.base64.length(d%s)),0)", prop
, prop
, prop
)
27469 ("else if(d%s.length)", prop
)
27470 ("m%s=d%s", prop
, prop
);
27473 ("m%s=String(d%s)", prop
, prop
);
27476 ("m%s=Boolean(d%s)", prop
, prop
);
27479 ("m%s=d%s", prop, prop);
27484 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27488 * Generates a plain object to runtime message converter specific to the specified message type.
27489 * @param {Type} mtype Message type
27490 * @returns {Codegen} Codegen instance
27492 converter
.fromObject
= function fromObject(mtype
) {
27493 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27494 var fields
= mtype
.fieldsArray
;
27495 var gen
= util
.codegen(["d"], mtype
.name
+ "$fromObject")
27496 ("if(d instanceof this.ctor)")
27498 if (!fields
.length
) return gen
27499 ("return new this.ctor");
27501 ("var m=new this.ctor");
27502 for (var i
= 0; i
< fields
.length
; ++i
) {
27503 var field
= fields
[i
].resolve(),
27504 prop
= util
.safeProp(field
.name
);
27507 if (field
.map
) { gen
27509 ("if(typeof d%s!==\"object\")", prop
)
27510 ("throw TypeError(%j)", field
.fullName
+ ": object expected")
27512 ("for(var ks=Object.keys(d%s),i=0;i<ks.length;++i){", prop
);
27513 genValuePartial_fromObject(gen
, field
, /* not sorted */ i
, prop
+ "[ks[i]]")
27518 } else if (field
.repeated
) { gen
27520 ("if(!Array.isArray(d%s))", prop
)
27521 ("throw TypeError(%j)", field
.fullName
+ ": array expected")
27523 ("for(var i=0;i<d%s.length;++i){", prop
);
27524 genValuePartial_fromObject(gen
, field
, /* not sorted */ i
, prop
+ "[i]")
27528 // Non-repeated fields
27530 if (!(field
.resolvedType
instanceof Enum
)) gen
// no need to test for null/undefined if an enum (uses switch)
27531 ("if(d%s!=null){", prop
); // !== undefined && !== null
27532 genValuePartial_fromObject(gen
, field
, /* not sorted */ i
, prop
);
27533 if (!(field
.resolvedType
instanceof Enum
)) gen
27538 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27542 * Generates a partial value toObject converter.
27543 * @param {Codegen} gen Codegen instance
27544 * @param {Field} field Reflected field
27545 * @param {number} fieldIndex Field index
27546 * @param {string} prop Property reference
27547 * @returns {Codegen} Codegen instance
27550 function genValuePartial_toObject(gen
, field
, fieldIndex
, prop
) {
27551 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27552 if (field
.resolvedType
) {
27553 if (field
.resolvedType
instanceof Enum
) gen
27554 ("d%s=o.enums===String?types[%i].values[m%s]:m%s", prop
, fieldIndex
, prop
, prop
);
27556 ("d%s=types[%i].toObject(m%s,o)", prop
, fieldIndex
, prop
);
27558 var isUnsigned
= false;
27559 switch (field
.type
) {
27562 ("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", prop
, prop
, prop
, prop
);
27566 // eslint-disable-line no-fallthrough
27570 case "sfixed64": gen
27571 ("if(typeof m%s===\"number\")", prop
)
27572 ("d%s=o.longs===String?String(m%s):m%s", prop
, prop
, prop
)
27573 ("else") // Long-like
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
);
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
);
27580 ("d%s=m%s", prop
, prop
);
27585 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27589 * Generates a runtime message to plain object converter specific to the specified message type.
27590 * @param {Type} mtype Message type
27591 * @returns {Codegen} Codegen instance
27593 converter
.toObject
= function toObject(mtype
) {
27594 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27595 var fields
= mtype
.fieldsArray
.slice().sort(util
.compareFieldsById
);
27596 if (!fields
.length
)
27597 return util
.codegen()("return {}");
27598 var gen
= util
.codegen(["m", "o"], mtype
.name
+ "$toObject")
27603 var repeatedFields
= [],
27607 for (; i
< fields
.length
; ++i
)
27608 if (!fields
[i
].partOf
)
27609 ( fields
[i
].resolve().repeated
? repeatedFields
27610 : fields
[i
].map
? mapFields
27611 : normalFields
).push(fields
[i
]);
27613 if (repeatedFields
.length
) { gen
27614 ("if(o.arrays||o.defaults){");
27615 for (i
= 0; i
< repeatedFields
.length
; ++i
) gen
27616 ("d%s=[]", util
.safeProp(repeatedFields
[i
].name
));
27621 if (mapFields
.length
) { gen
27622 ("if(o.objects||o.defaults){");
27623 for (i
= 0; i
< mapFields
.length
; ++i
) gen
27624 ("d%s={}", util
.safeProp(mapFields
[i
].name
));
27629 if (normalFields
.length
) { gen
27630 ("if(o.defaults){");
27631 for (i
= 0; i
< normalFields
.length
; ++i
) {
27632 var field
= normalFields
[i
],
27633 prop
= util
.safeProp(field
.name
);
27634 if (field
.resolvedType
instanceof Enum
) gen
27635 ("d%s=o.enums===String?%j:%j", prop
, field
.resolvedType
.valuesById
[field
.typeDefault
], field
.typeDefault
);
27636 else if (field
.long) gen
27638 ("var n=new util.Long(%i,%i,%j)", field
.typeDefault
.low
, field
.typeDefault
.high
, field
.typeDefault
.unsigned
)
27639 ("d%s=o.longs===String?n.toString():o.longs===Number?n.toNumber():n", prop
)
27641 ("d%s=o.longs===String?%j:%i", prop
, field
.typeDefault
.toString(), field
.typeDefault
.toNumber());
27642 else if (field
.bytes
) gen
27643 ("d%s=o.bytes===String?%j:%s", prop
, String
.fromCharCode
.apply(String
, field
.typeDefault
), "[" + Array
.prototype.slice
.call(field
.typeDefault
).join(",") + "]");
27645 ("d%s=%j", prop
, field
.typeDefault
); // also messages (=null)
27649 var hasKs2
= false;
27650 for (i
= 0; i
< fields
.length
; ++i
) {
27651 var field
= fields
[i
],
27652 index
= mtype
._fieldsArray
.indexOf(field
),
27653 prop
= util
.safeProp(field
.name
);
27655 if (!hasKs2
) { hasKs2
= true; gen
27658 ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop
, prop
)
27660 ("for(var j=0;j<ks2.length;++j){");
27661 genValuePartial_toObject(gen
, field
, /* sorted */ index
, prop
+ "[ks2[j]]")
27663 } else if (field
.repeated
) { gen
27664 ("if(m%s&&m%s.length){", prop
, prop
)
27666 ("for(var j=0;j<m%s.length;++j){", prop
);
27667 genValuePartial_toObject(gen
, field
, /* sorted */ index
, prop
+ "[j]")
27670 ("if(m%s!=null&&m.hasOwnProperty(%j)){", prop
, field
.name
); // !== undefined && !== null
27671 genValuePartial_toObject(gen
, field
, /* sorted */ index
, prop
);
27672 if (field
.partOf
) gen
27674 ("d%s=%j", util
.safeProp(field
.partOf
.name
), field
.name
);
27681 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27684 },{"./enum":196,"./util":218}],194:[function(require
,module
,exports
){
27686 module
.exports
= decoder
;
27688 var Enum
= require("./enum"),
27689 types
= require("./types"),
27690 util
= require("./util");
27692 function missing(field
) {
27693 return "missing required '" + field
.name
+ "'";
27697 * Generates a decoder specific to the specified message type.
27698 * @param {Type} mtype Message type
27699 * @returns {Codegen} Codegen instance
27701 function decoder(mtype
) {
27702 /* eslint-disable no-unexpected-multiline */
27703 var gen
= util
.codegen(["r", "l"], mtype
.name
+ "$decode")
27704 ("if(!(r instanceof Reader))")
27705 ("r=Reader.create(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" : ""))
27707 ("while(r.pos<c){")
27708 ("var t=r.uint32()");
27709 if (mtype
.group
) gen
27713 ("switch(t>>>3){");
27716 for (; i
< /* initializes */ mtype
.fieldsArray
.length
; ++i
) {
27717 var field
= mtype
._fieldsArray
[i
].resolve(),
27718 type
= field
.resolvedType
instanceof Enum
? "int32" : field
.type
,
27719 ref
= "m" + util
.safeProp(field
.name
); gen
27720 ("case %i:", field
.id
);
27723 if (field
.map
) { gen
27724 ("r.skip().pos++") // assumes id 1 + key wireType
27725 ("if(%s===util.emptyObject)", ref
)
27727 ("k=r.%s()", field
.keyType
)
27728 ("r.pos++"); // assumes id 2 + value wireType
27729 if (types
.long[field
.keyType
] !== undefined) {
27730 if (types
.basic
[type
] === undefined) gen
27731 ("%s[typeof k===\"object\"?util.longToHash(k):k]=types[%i].decode(r,r.uint32())", ref
, i
); // can't be groups
27733 ("%s[typeof k===\"object\"?util.longToHash(k):k]=r.%s()", ref
, type
);
27735 if (types
.basic
[type
] === undefined) gen
27736 ("%s[k]=types[%i].decode(r,r.uint32())", ref
, i
); // can't be groups
27738 ("%s[k]=r.%s()", ref
, type
);
27742 } else if (field
.repeated
) { gen
27744 ("if(!(%s&&%s.length))", ref
, ref
)
27747 // Packable (always check for forward and backward compatiblity)
27748 if (types
.packed
[type
] !== undefined) gen
27750 ("var c2=r.uint32()+r.pos")
27751 ("while(r.pos<c2)")
27752 ("%s.push(r.%s())", ref
, type
)
27756 if (types
.basic
[type
] === undefined) gen(field
.resolvedType
.group
27757 ? "%s.push(types[%i].decode(r))"
27758 : "%s.push(types[%i].decode(r,r.uint32()))", ref
, i
);
27760 ("%s.push(r.%s())", ref
, type
);
27763 } else if (types
.basic
[type
] === undefined) gen(field
.resolvedType
.group
27764 ? "%s=types[%i].decode(r)"
27765 : "%s=types[%i].decode(r,r.uint32())", ref
, i
);
27767 ("%s=r.%s()", ref
, type
);
27773 ("r.skipType(t&7)")
27780 for (i
= 0; i
< mtype
._fieldsArray
.length
; ++i
) {
27781 var rfield
= mtype
._fieldsArray
[i
];
27782 if (rfield
.required
) gen
27783 ("if(!m.hasOwnProperty(%j))", rfield
.name
)
27784 ("throw util.ProtocolError(%j,{instance:m})", missing(rfield
));
27789 /* eslint-enable no-unexpected-multiline */
27792 },{"./enum":196,"./types":217,"./util":218}],195:[function(require
,module
,exports
){
27794 module
.exports
= encoder
;
27796 var Enum
= require("./enum"),
27797 types
= require("./types"),
27798 util
= require("./util");
27801 * Generates a partial message type encoder.
27802 * @param {Codegen} gen Codegen instance
27803 * @param {Field} field Reflected field
27804 * @param {number} fieldIndex Field index
27805 * @param {string} ref Variable reference
27806 * @returns {Codegen} Codegen instance
27809 function genTypePartial(gen
, field
, fieldIndex
, ref
) {
27810 return field
.resolvedType
.group
27811 ? gen("types[%i].encode(%s,w.uint32(%i)).uint32(%i)", fieldIndex
, ref
, (field
.id
<< 3 | 3) >>> 0, (field
.id
<< 3 | 4) >>> 0)
27812 : gen("types[%i].encode(%s,w.uint32(%i).fork()).ldelim()", fieldIndex
, ref
, (field
.id
<< 3 | 2) >>> 0);
27816 * Generates an encoder specific to the specified message type.
27817 * @param {Type} mtype Message type
27818 * @returns {Codegen} Codegen instance
27820 function encoder(mtype
) {
27821 /* eslint-disable no-unexpected-multiline, block-scoped-var, no-redeclare */
27822 var gen
= util
.codegen(["m", "w"], mtype
.name
+ "$encode")
27824 ("w=Writer.create()");
27828 // "when a message is serialized its known fields should be written sequentially by field number"
27829 var fields
= /* initializes */ mtype
.fieldsArray
.slice().sort(util
.compareFieldsById
);
27831 for (var i
= 0; i
< fields
.length
; ++i
) {
27832 var field
= fields
[i
].resolve(),
27833 index
= mtype
._fieldsArray
.indexOf(field
),
27834 type
= field
.resolvedType
instanceof Enum
? "int32" : field
.type
,
27835 wireType
= types
.basic
[type
];
27836 ref
= "m" + util
.safeProp(field
.name
);
27841 ("if(%s!=null&&m.hasOwnProperty(%j)){", ref
, field
.name
) // !== undefined && !== null
27842 ("for(var ks=Object.keys(%s),i=0;i<ks.length;++i){", ref
)
27843 ("w.uint32(%i).fork().uint32(%i).%s(ks[i])", (field
.id
<< 3 | 2) >>> 0, 8 | types
.mapKey
[field
.keyType
], field
.keyType
);
27844 if (wireType
=== undefined) gen
27845 ("types[%i].encode(%s[ks[i]],w.uint32(18).fork()).ldelim().ldelim()", index
, ref
); // can't be groups
27847 (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType
, type
, ref
);
27853 } else if (field
.repeated
) { gen
27854 ("if(%s!=null&&%s.length){", ref
, ref
); // !== undefined && !== null
27857 if (field
.packed
&& types
.packed
[type
] !== undefined) { gen
27859 ("w.uint32(%i).fork()", (field
.id
<< 3 | 2) >>> 0)
27860 ("for(var i=0;i<%s.length;++i)", ref
)
27861 ("w.%s(%s[i])", type
, ref
)
27867 ("for(var i=0;i<%s.length;++i)", ref
);
27868 if (wireType
=== undefined)
27869 genTypePartial(gen
, field
, index
, ref
+ "[i]");
27871 ("w.uint32(%i).%s(%s[i])", (field
.id
<< 3 | wireType
) >>> 0, type
, ref
);
27878 if (field
.optional
) gen
27879 ("if(%s!=null&&m.hasOwnProperty(%j))", ref
, field
.name
); // !== undefined && !== null
27881 if (wireType
=== undefined)
27882 genTypePartial(gen
, field
, index
, ref
);
27884 ("w.uint32(%i).%s(%s)", (field
.id
<< 3 | wireType
) >>> 0, type
, ref
);
27891 /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */
27893 },{"./enum":196,"./types":217,"./util":218}],196:[function(require
,module
,exports
){
27895 module
.exports
= Enum
;
27897 // extends ReflectionObject
27898 var ReflectionObject
= require("./object");
27899 ((Enum
.prototype = Object
.create(ReflectionObject
.prototype)).constructor = Enum
).className
= "Enum";
27901 var Namespace
= require("./namespace"),
27902 util
= require("./util");
27905 * Constructs a new enum instance.
27906 * @classdesc Reflected enum.
27907 * @extends ReflectionObject
27909 * @param {string} name Unique name within its namespace
27910 * @param {Object.<string,number>} [values] Enum values as an object, by name
27911 * @param {Object.<string,*>} [options] Declared options
27912 * @param {string} [comment] The comment for this enum
27913 * @param {Object.<string,string>} [comments] The value comments for this enum
27915 function Enum(name
, values
, options
, comment
, comments
) {
27916 ReflectionObject
.call(this, name
, options
);
27918 if (values
&& typeof values
!== "object")
27919 throw TypeError("values must be an object");
27922 * Enum values by id.
27923 * @type {Object.<number,string>}
27925 this.valuesById
= {};
27928 * Enum values by name.
27929 * @type {Object.<string,number>}
27931 this.values
= Object
.create(this.valuesById
); // toJSON, marker
27934 * Enum comment text.
27935 * @type {string|null}
27937 this.comment
= comment
;
27940 * Value comment texts, if any.
27941 * @type {Object.<string,string>}
27943 this.comments
= comments
|| {};
27946 * Reserved ranges, if any.
27947 * @type {Array.<number[]|string>}
27949 this.reserved
= undefined; // toJSON
27951 // Note that values inherit valuesById on their prototype which makes them a TypeScript-
27952 // compatible enum. This is used by pbts to write actual enum definitions that work for
27953 // static and reflection code alike instead of emitting generic object definitions.
27956 for (var keys
= Object
.keys(values
), i
= 0; i
< keys
.length
; ++i
)
27957 if (typeof values
[keys
[i
]] === "number") // use forward entries only
27958 this.valuesById
[ this.values
[keys
[i
]] = values
[keys
[i
]] ] = keys
[i
];
27964 * @property {Object.<string,number>} values Enum values
27965 * @property {Object.<string,*>} [options] Enum options
27969 * Constructs an enum from an enum descriptor.
27970 * @param {string} name Enum name
27971 * @param {IEnum} json Enum descriptor
27972 * @returns {Enum} Created enum
27973 * @throws {TypeError} If arguments are invalid
27975 Enum
.fromJSON
= function fromJSON(name
, json
) {
27976 var enm
= new Enum(name
, json
.values
, json
.options
, json
.comment
, json
.comments
);
27977 enm
.reserved
= json
.reserved
;
27982 * Converts this enum to an enum descriptor.
27983 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
27984 * @returns {IEnum} Enum descriptor
27986 Enum
.prototype.toJSON
= function toJSON(toJSONOptions
) {
27987 var keepComments
= toJSONOptions
? Boolean(toJSONOptions
.keepComments
) : false;
27988 return util
.toObject([
27989 "options" , this.options
,
27990 "values" , this.values
,
27991 "reserved" , this.reserved
&& this.reserved
.length
? this.reserved : undefined,
27992 "comment" , keepComments
? this.comment : undefined,
27993 "comments" , keepComments
? this.comments : undefined
27998 * Adds a value to this enum.
27999 * @param {string} name Value name
28000 * @param {number} id Value id
28001 * @param {string} [comment] Comment, if any
28002 * @returns {Enum} `this`
28003 * @throws {TypeError} If arguments are invalid
28004 * @throws {Error} If there is already a value with this name or id
28006 Enum
.prototype.add
= function add(name
, id
, comment
) {
28007 // utilized by the parser but not by .fromJSON
28009 if (!util
.isString(name
))
28010 throw TypeError("name must be a string");
28012 if (!util
.isInteger(id
))
28013 throw TypeError("id must be an integer");
28015 if (this.values
[name
] !== undefined)
28016 throw Error("duplicate name '" + name
+ "' in " + this);
28018 if (this.isReservedId(id
))
28019 throw Error("id " + id
+ " is reserved in " + this);
28021 if (this.isReservedName(name
))
28022 throw Error("name '" + name
+ "' is reserved in " + this);
28024 if (this.valuesById
[id
] !== undefined) {
28025 if (!(this.options
&& this.options
.allow_alias
))
28026 throw Error("duplicate id " + id
+ " in " + this);
28027 this.values
[name
] = id
;
28029 this.valuesById
[this.values
[name
] = id
] = name
;
28031 this.comments
[name
] = comment
|| null;
28036 * Removes a value from this enum
28037 * @param {string} name Value name
28038 * @returns {Enum} `this`
28039 * @throws {TypeError} If arguments are invalid
28040 * @throws {Error} If `name` is not a name of this enum
28042 Enum
.prototype.remove
= function remove(name
) {
28044 if (!util
.isString(name
))
28045 throw TypeError("name must be a string");
28047 var val
= this.values
[name
];
28049 throw Error("name '" + name
+ "' does not exist in " + this);
28051 delete this.valuesById
[val
];
28052 delete this.values
[name
];
28053 delete this.comments
[name
];
28059 * Tests if the specified id is reserved.
28060 * @param {number} id Id to test
28061 * @returns {boolean} `true` if reserved, otherwise `false`
28063 Enum
.prototype.isReservedId
= function isReservedId(id
) {
28064 return Namespace
.isReservedId(this.reserved
, id
);
28068 * Tests if the specified name is reserved.
28069 * @param {string} name Name to test
28070 * @returns {boolean} `true` if reserved, otherwise `false`
28072 Enum
.prototype.isReservedName
= function isReservedName(name
) {
28073 return Namespace
.isReservedName(this.reserved
, name
);
28076 },{"./namespace":204,"./object":205,"./util":218}],197:[function(require
,module
,exports
){
28078 module
.exports
= Field
;
28080 // extends ReflectionObject
28081 var ReflectionObject
= require("./object");
28082 ((Field
.prototype = Object
.create(ReflectionObject
.prototype)).constructor = Field
).className
= "Field";
28084 var Enum
= require("./enum"),
28085 types
= require("./types"),
28086 util
= require("./util");
28088 var Type
; // cyclic
28090 var ruleRe
= /^required|optional|repeated$/;
28093 * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class.
28095 * @classdesc Reflected message field.
28096 * @extends FieldBase
28098 * @param {string} name Unique name within its namespace
28099 * @param {number} id Unique id within its namespace
28100 * @param {string} type Value type
28101 * @param {string|Object.<string,*>} [rule="optional"] Field rule
28102 * @param {string|Object.<string,*>} [extend] Extended type if different from parent
28103 * @param {Object.<string,*>} [options] Declared options
28107 * Constructs a field from a field descriptor.
28108 * @param {string} name Field name
28109 * @param {IField} json Field descriptor
28110 * @returns {Field} Created field
28111 * @throws {TypeError} If arguments are invalid
28113 Field
.fromJSON
= function fromJSON(name
, json
) {
28114 return new Field(name
, json
.id
, json
.type
, json
.rule
, json
.extend
, json
.options
, json
.comment
);
28118 * Not an actual constructor. Use {@link Field} instead.
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.
28120 * @exports FieldBase
28121 * @extends ReflectionObject
28123 * @param {string} name Unique name within its namespace
28124 * @param {number} id Unique id within its namespace
28125 * @param {string} type Value type
28126 * @param {string|Object.<string,*>} [rule="optional"] Field rule
28127 * @param {string|Object.<string,*>} [extend] Extended type if different from parent
28128 * @param {Object.<string,*>} [options] Declared options
28129 * @param {string} [comment] Comment associated with this field
28131 function Field(name
, id
, type
, rule
, extend
, options
, comment
) {
28133 if (util
.isObject(rule
)) {
28136 rule
= extend
= undefined;
28137 } else if (util
.isObject(extend
)) {
28140 extend
= undefined;
28143 ReflectionObject
.call(this, name
, options
);
28145 if (!util
.isInteger(id
) || id
< 0)
28146 throw TypeError("id must be a non-negative integer");
28148 if (!util
.isString(type
))
28149 throw TypeError("type must be a string");
28151 if (rule
!== undefined && !ruleRe
.test(rule
= rule
.toString().toLowerCase()))
28152 throw TypeError("rule must be a string rule");
28154 if (extend
!== undefined && !util
.isString(extend
))
28155 throw TypeError("extend must be a string");
28158 * Field rule, if any.
28159 * @type {string|undefined}
28161 this.rule
= rule
&& rule
!== "optional" ? rule : undefined; // toJSON
28167 this.type
= type
; // toJSON
28173 this.id
= id
; // toJSON, marker
28176 * Extended type if different from parent.
28177 * @type {string|undefined}
28179 this.extend
= extend
|| undefined; // toJSON
28182 * Whether this field is required.
28185 this.required
= rule
=== "required";
28188 * Whether this field is optional.
28191 this.optional
= !this.required
;
28194 * Whether this field is repeated.
28197 this.repeated
= rule
=== "repeated";
28200 * Whether this field is a map or not.
28206 * Message this field belongs to.
28207 * @type {Type|null}
28209 this.message
= null;
28212 * OneOf this field belongs to, if any,
28213 * @type {OneOf|null}
28215 this.partOf
= null;
28218 * The field type's default value.
28221 this.typeDefault
= null;
28224 * The field's default value on prototypes.
28227 this.defaultValue
= null;
28230 * Whether this field's value should be treated as a long.
28233 this.long = util
.Long
? types
.long[type
] !== undefined : /* istanbul ignore next */ false;
28236 * Whether this field's value is a buffer.
28239 this.bytes
= type
=== "bytes";
28242 * Resolved type if not a basic type.
28243 * @type {Type|Enum|null}
28245 this.resolvedType
= null;
28248 * Sister-field within the extended type if a declaring extension field.
28249 * @type {Field|null}
28251 this.extensionField
= null;
28254 * Sister-field within the declaring namespace if an extended field.
28255 * @type {Field|null}
28257 this.declaringField
= null;
28260 * Internally remembers whether this field is packed.
28261 * @type {boolean|null}
28264 this._packed
= null;
28267 * Comment for this field.
28268 * @type {string|null}
28270 this.comment
= comment
;
28274 * Determines whether this field is packed. Only relevant when repeated and working with proto2.
28275 * @name Field#packed
28279 Object
.defineProperty(Field
.prototype, "packed", {
28281 // defaults to packed=true if not explicity set to false
28282 if (this._packed
=== null)
28283 this._packed
= this.getOption("packed") !== false;
28284 return this._packed
;
28291 Field
.prototype.setOption
= function setOption(name
, value
, ifNotSet
) {
28292 if (name
=== "packed") // clear cached before setting
28293 this._packed
= null;
28294 return ReflectionObject
.prototype.setOption
.call(this, name
, value
, ifNotSet
);
28298 * Field descriptor.
28299 * @interface IField
28300 * @property {string} [rule="optional"] Field rule
28301 * @property {string} type Field type
28302 * @property {number} id Field id
28303 * @property {Object.<string,*>} [options] Field options
28307 * Extension field descriptor.
28308 * @interface IExtensionField
28310 * @property {string} extend Extended type
28314 * Converts this field to a field descriptor.
28315 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
28316 * @returns {IField} Field descriptor
28318 Field
.prototype.toJSON
= function toJSON(toJSONOptions
) {
28319 var keepComments
= toJSONOptions
? Boolean(toJSONOptions
.keepComments
) : false;
28320 return util
.toObject([
28321 "rule" , this.rule
!== "optional" && this.rule
|| undefined,
28322 "type" , this.type
,
28324 "extend" , this.extend
,
28325 "options" , this.options
,
28326 "comment" , keepComments
? this.comment : undefined
28331 * Resolves this field's type references.
28332 * @returns {Field} `this`
28333 * @throws {Error} If any reference cannot be resolved
28335 Field
.prototype.resolve
= function resolve() {
28340 if ((this.typeDefault
= types
.defaults
[this.type
]) === undefined) { // if not a basic type, resolve it
28341 this.resolvedType
= (this.declaringField
? this.declaringField
.parent : this.parent
).lookupTypeOrEnum(this.type
);
28342 if (this.resolvedType
instanceof Type
)
28343 this.typeDefault
= null;
28344 else // instanceof Enum
28345 this.typeDefault
= this.resolvedType
.values
[Object
.keys(this.resolvedType
.values
)[0]]; // first defined
28348 // use explicitly set default value if present
28349 if (this.options
&& this.options
["default"] != null) {
28350 this.typeDefault
= this.options
["default"];
28351 if (this.resolvedType
instanceof Enum
&& typeof this.typeDefault
=== "string")
28352 this.typeDefault
= this.resolvedType
.values
[this.typeDefault
];
28355 // remove unnecessary options
28356 if (this.options
) {
28357 if (this.options
.packed
=== true || this.options
.packed
!== undefined && this.resolvedType
&& !(this.resolvedType
instanceof Enum
))
28358 delete this.options
.packed
;
28359 if (!Object
.keys(this.options
).length
)
28360 this.options
= undefined;
28363 // convert to internal data type if necesssary
28365 this.typeDefault
= util
.Long
.fromNumber(this.typeDefault
, this.type
.charAt(0) === "u");
28367 /* istanbul ignore else */
28369 Object
.freeze(this.typeDefault
); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it)
28371 } else if (this.bytes
&& typeof this.typeDefault
=== "string") {
28373 if (util
.base64
.test(this.typeDefault
))
28374 util
.base64
.decode(this.typeDefault
, buf
= util
.newBuffer(util
.base64
.length(this.typeDefault
)), 0);
28376 util
.utf8
.write(this.typeDefault
, buf
= util
.newBuffer(util
.utf8
.length(this.typeDefault
)), 0);
28377 this.typeDefault
= buf
;
28380 // take special care of maps and repeated fields
28382 this.defaultValue
= util
.emptyObject
;
28383 else if (this.repeated
)
28384 this.defaultValue
= util
.emptyArray
;
28386 this.defaultValue
= this.typeDefault
;
28388 // ensure proper value on prototype
28389 if (this.parent
instanceof Type
)
28390 this.parent
.ctor
.prototype[this.name
] = this.defaultValue
;
28392 return ReflectionObject
.prototype.resolve
.call(this);
28396 * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript).
28397 * @typedef FieldDecorator
28399 * @param {Object} prototype Target prototype
28400 * @param {string} fieldName Field name
28401 * @returns {undefined}
28405 * Field decorator (TypeScript).
28408 * @param {number} fieldId Field id
28409 * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"string"|"bool"|"bytes"|Object} fieldType Field type
28410 * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
28411 * @param {T} [defaultValue] Default value
28412 * @returns {FieldDecorator} Decorator function
28413 * @template T extends number | number[] | Long | Long[] | string | string[] | boolean | boolean[] | Uint8Array | Uint8Array[] | Buffer | Buffer[]
28415 Field
.d
= function decorateField(fieldId
, fieldType
, fieldRule
, defaultValue
) {
28417 // submessage: decorate the submessage and use its name as the type
28418 if (typeof fieldType
=== "function")
28419 fieldType
= util
.decorateType(fieldType
).name
;
28421 // enum reference: create a reflected copy of the enum and keep reuseing it
28422 else if (fieldType
&& typeof fieldType
=== "object")
28423 fieldType
= util
.decorateEnum(fieldType
).name
;
28425 return function fieldDecorator(prototype, fieldName
) {
28426 util
.decorateType(prototype.constructor)
28427 .add(new Field(fieldName
, fieldId
, fieldType
, fieldRule
, { "default": defaultValue
}));
28432 * Field decorator (TypeScript).
28435 * @param {number} fieldId Field id
28436 * @param {Constructor<T>|string} fieldType Field type
28437 * @param {"optional"|"required"|"repeated"} [fieldRule="optional"] Field rule
28438 * @returns {FieldDecorator} Decorator function
28439 * @template T extends Message<T>
28442 // like Field.d but without a default value
28444 Field
._configure
= function configure(Type_
) {
28448 },{"./enum":196,"./object":205,"./types":217,"./util":218}],198:[function(require
,module
,exports
){
28450 var protobuf
= module
.exports
= require("./index-minimal");
28452 protobuf
.build
= "light";
28455 * A node-style callback as used by {@link load} and {@link Root#load}.
28456 * @typedef LoadCallback
28458 * @param {Error|null} error Error, if any, otherwise `null`
28459 * @param {Root} [root] Root, if there hasn't been an error
28460 * @returns {undefined}
28464 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
28465 * @param {string|string[]} filename One or multiple files to load
28466 * @param {Root} root Root namespace, defaults to create a new one if omitted.
28467 * @param {LoadCallback} callback Callback function
28468 * @returns {undefined}
28469 * @see {@link Root#load}
28471 function load(filename
, root
, callback
) {
28472 if (typeof root
=== "function") {
28474 root
= new protobuf
.Root();
28476 root
= new protobuf
.Root();
28477 return root
.load(filename
, callback
);
28481 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback.
28484 * @param {string|string[]} filename One or multiple files to load
28485 * @param {LoadCallback} callback Callback function
28486 * @returns {undefined}
28487 * @see {@link Root#load}
28490 // function load(filename:string, callback:LoadCallback):undefined
28493 * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise.
28496 * @param {string|string[]} filename One or multiple files to load
28497 * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
28498 * @returns {Promise<Root>} Promise
28499 * @see {@link Root#load}
28502 // function load(filename:string, [root:Root]):Promise<Root>
28504 protobuf
.load
= load
;
28507 * Synchronously loads one or multiple .proto or preprocessed .json files into a common root namespace (node only).
28508 * @param {string|string[]} filename One or multiple files to load
28509 * @param {Root} [root] Root namespace, defaults to create a new one if omitted.
28510 * @returns {Root} Root namespace
28511 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
28512 * @see {@link Root#loadSync}
28514 function loadSync(filename
, root
) {
28516 root
= new protobuf
.Root();
28517 return root
.loadSync(filename
);
28520 protobuf
.loadSync
= loadSync
;
28523 protobuf
.encoder
= require("./encoder");
28524 protobuf
.decoder
= require("./decoder");
28525 protobuf
.verifier
= require("./verifier");
28526 protobuf
.converter
= require("./converter");
28529 protobuf
.ReflectionObject
= require("./object");
28530 protobuf
.Namespace
= require("./namespace");
28531 protobuf
.Root
= require("./root");
28532 protobuf
.Enum
= require("./enum");
28533 protobuf
.Type
= require("./type");
28534 protobuf
.Field
= require("./field");
28535 protobuf
.OneOf
= require("./oneof");
28536 protobuf
.MapField
= require("./mapfield");
28537 protobuf
.Service
= require("./service");
28538 protobuf
.Method
= require("./method");
28541 protobuf
.Message
= require("./message");
28542 protobuf
.wrappers
= require("./wrappers");
28545 protobuf
.types
= require("./types");
28546 protobuf
.util
= require("./util");
28548 // Configure reflection
28549 protobuf
.ReflectionObject
._configure(protobuf
.Root
);
28550 protobuf
.Namespace
._configure(protobuf
.Type
, protobuf
.Service
);
28551 protobuf
.Root
._configure(protobuf
.Type
);
28552 protobuf
.Field
._configure(protobuf
.Type
);
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
){
28556 var protobuf
= exports
;
28559 * Build type, one of `"full"`, `"light"` or `"minimal"`.
28564 protobuf
.build
= "minimal";
28567 protobuf
.Writer
= require("./writer");
28568 protobuf
.BufferWriter
= require("./writer_buffer");
28569 protobuf
.Reader
= require("./reader");
28570 protobuf
.BufferReader
= require("./reader_buffer");
28573 protobuf
.util
= require("./util/minimal");
28574 protobuf
.rpc
= require("./rpc");
28575 protobuf
.roots
= require("./roots");
28576 protobuf
.configure
= configure
;
28578 /* istanbul ignore next */
28580 * Reconfigures the library according to the environment.
28581 * @returns {undefined}
28583 function configure() {
28584 protobuf
.Reader
._configure(protobuf
.BufferReader
);
28585 protobuf
.util
._configure();
28588 // Configure serialization
28589 protobuf
.Writer
._configure(protobuf
.BufferWriter
);
28592 },{"./reader":208,"./reader_buffer":209,"./roots":211,"./rpc":212,"./util/minimal":220,"./writer":223,"./writer_buffer":224}],200:[function(require
,module
,exports
){
28594 var protobuf
= module
.exports
= require("./index-light");
28596 protobuf
.build
= "full";
28599 protobuf
.tokenize
= require("./tokenize");
28600 protobuf
.parse
= require("./parse");
28601 protobuf
.common
= require("./common");
28603 // Configure parser
28604 protobuf
.Root
._configure(protobuf
.Type
, protobuf
.parse
, protobuf
.common
);
28606 },{"./common":192,"./index-light":198,"./parse":207,"./tokenize":215}],201:[function(require
,module
,exports
){
28608 module
.exports
= MapField
;
28611 var Field
= require("./field");
28612 ((MapField
.prototype = Object
.create(Field
.prototype)).constructor = MapField
).className
= "MapField";
28614 var types
= require("./types"),
28615 util
= require("./util");
28618 * Constructs a new map field instance.
28619 * @classdesc Reflected map field.
28620 * @extends FieldBase
28622 * @param {string} name Unique name within its namespace
28623 * @param {number} id Unique id within its namespace
28624 * @param {string} keyType Key type
28625 * @param {string} type Value type
28626 * @param {Object.<string,*>} [options] Declared options
28627 * @param {string} [comment] Comment associated with this field
28629 function MapField(name
, id
, keyType
, type
, options
, comment
) {
28630 Field
.call(this, name
, id
, type
, undefined, undefined, options
, comment
);
28632 /* istanbul ignore if */
28633 if (!util
.isString(keyType
))
28634 throw TypeError("keyType must be a string");
28640 this.keyType
= keyType
; // toJSON, marker
28643 * Resolved key type if not a basic type.
28644 * @type {ReflectionObject|null}
28646 this.resolvedKeyType
= null;
28648 // Overrides Field#map
28653 * Map field descriptor.
28654 * @interface IMapField
28655 * @extends {IField}
28656 * @property {string} keyType Key type
28660 * Extension map field descriptor.
28661 * @interface IExtensionMapField
28662 * @extends IMapField
28663 * @property {string} extend Extended type
28667 * Constructs a map field from a map field descriptor.
28668 * @param {string} name Field name
28669 * @param {IMapField} json Map field descriptor
28670 * @returns {MapField} Created map field
28671 * @throws {TypeError} If arguments are invalid
28673 MapField
.fromJSON
= function fromJSON(name
, json
) {
28674 return new MapField(name
, json
.id
, json
.keyType
, json
.type
, json
.options
, json
.comment
);
28678 * Converts this map field to a map field descriptor.
28679 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
28680 * @returns {IMapField} Map field descriptor
28682 MapField
.prototype.toJSON
= function toJSON(toJSONOptions
) {
28683 var keepComments
= toJSONOptions
? Boolean(toJSONOptions
.keepComments
) : false;
28684 return util
.toObject([
28685 "keyType" , this.keyType
,
28686 "type" , this.type
,
28688 "extend" , this.extend
,
28689 "options" , this.options
,
28690 "comment" , keepComments
? this.comment : undefined
28697 MapField
.prototype.resolve
= function resolve() {
28701 // Besides a value type, map fields have a key type that may be "any scalar type except for floating point types and bytes"
28702 if (types
.mapKey
[this.keyType
] === undefined)
28703 throw Error("invalid key type: " + this.keyType
);
28705 return Field
.prototype.resolve
.call(this);
28709 * Map field decorator (TypeScript).
28712 * @param {number} fieldId Field id
28713 * @param {"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"} fieldKeyType Field key type
28714 * @param {"double"|"float"|"int32"|"uint32"|"sint32"|"fixed32"|"sfixed32"|"int64"|"uint64"|"sint64"|"fixed64"|"sfixed64"|"bool"|"string"|"bytes"|Object|Constructor<{}>} fieldValueType Field value type
28715 * @returns {FieldDecorator} Decorator function
28716 * @template T extends { [key: string]: number | Long | string | boolean | Uint8Array | Buffer | number[] | Message<{}> }
28718 MapField
.d
= function decorateMapField(fieldId
, fieldKeyType
, fieldValueType
) {
28720 // submessage value: decorate the submessage and use its name as the type
28721 if (typeof fieldValueType
=== "function")
28722 fieldValueType
= util
.decorateType(fieldValueType
).name
;
28724 // enum reference value: create a reflected copy of the enum and keep reuseing it
28725 else if (fieldValueType
&& typeof fieldValueType
=== "object")
28726 fieldValueType
= util
.decorateEnum(fieldValueType
).name
;
28728 return function mapFieldDecorator(prototype, fieldName
) {
28729 util
.decorateType(prototype.constructor)
28730 .add(new MapField(fieldName
, fieldId
, fieldKeyType
, fieldValueType
));
28734 },{"./field":197,"./types":217,"./util":218}],202:[function(require
,module
,exports
){
28736 module
.exports
= Message
;
28738 var util
= require("./util/minimal");
28741 * Constructs a new message instance.
28742 * @classdesc Abstract runtime message.
28744 * @param {Properties<T>} [properties] Properties to set
28745 * @template T extends object
28747 function Message(properties
) {
28748 // not used internally
28750 for (var keys
= Object
.keys(properties
), i
= 0; i
< keys
.length
; ++i
)
28751 this[keys
[i
]] = properties
[keys
[i
]];
28755 * Reference to the reflected type.
28756 * @name Message.$type
28762 * Reference to the reflected type.
28763 * @name Message#$type
28768 /*eslint-disable valid-jsdoc*/
28771 * Creates a new message of this type using the specified properties.
28772 * @param {Object.<string,*>} [properties] Properties to set
28773 * @returns {Message<T>} Message instance
28774 * @template T extends Message<T>
28775 * @this Constructor<T>
28777 Message
.create
= function create(properties
) {
28778 return this.$type
.create(properties
);
28782 * Encodes a message of this type.
28783 * @param {T|Object.<string,*>} message Message to encode
28784 * @param {Writer} [writer] Writer to use
28785 * @returns {Writer} Writer
28786 * @template T extends Message<T>
28787 * @this Constructor<T>
28789 Message
.encode
= function encode(message
, writer
) {
28790 return this.$type
.encode(message
, writer
);
28794 * Encodes a message of this type preceeded by its length as a varint.
28795 * @param {T|Object.<string,*>} message Message to encode
28796 * @param {Writer} [writer] Writer to use
28797 * @returns {Writer} Writer
28798 * @template T extends Message<T>
28799 * @this Constructor<T>
28801 Message
.encodeDelimited
= function encodeDelimited(message
, writer
) {
28802 return this.$type
.encodeDelimited(message
, writer
);
28806 * Decodes a message of this type.
28807 * @name Message.decode
28809 * @param {Reader|Uint8Array} reader Reader or buffer to decode
28810 * @returns {T} Decoded message
28811 * @template T extends Message<T>
28812 * @this Constructor<T>
28814 Message
.decode
= function decode(reader
) {
28815 return this.$type
.decode(reader
);
28819 * Decodes a message of this type preceeded by its length as a varint.
28820 * @name Message.decodeDelimited
28822 * @param {Reader|Uint8Array} reader Reader or buffer to decode
28823 * @returns {T} Decoded message
28824 * @template T extends Message<T>
28825 * @this Constructor<T>
28827 Message
.decodeDelimited
= function decodeDelimited(reader
) {
28828 return this.$type
.decodeDelimited(reader
);
28832 * Verifies a message of this type.
28833 * @name Message.verify
28835 * @param {Object.<string,*>} message Plain object to verify
28836 * @returns {string|null} `null` if valid, otherwise the reason why it is not
28838 Message
.verify
= function verify(message
) {
28839 return this.$type
.verify(message
);
28843 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
28844 * @param {Object.<string,*>} object Plain object
28845 * @returns {T} Message instance
28846 * @template T extends Message<T>
28847 * @this Constructor<T>
28849 Message
.fromObject
= function fromObject(object
) {
28850 return this.$type
.fromObject(object
);
28854 * Creates a plain object from a message of this type. Also converts values to other types if specified.
28855 * @param {T} message Message instance
28856 * @param {IConversionOptions} [options] Conversion options
28857 * @returns {Object.<string,*>} Plain object
28858 * @template T extends Message<T>
28859 * @this Constructor<T>
28861 Message
.toObject
= function toObject(message
, options
) {
28862 return this.$type
.toObject(message
, options
);
28866 * Converts this message to JSON.
28867 * @returns {Object.<string,*>} JSON object
28869 Message
.prototype.toJSON
= function toJSON() {
28870 return this.$type
.toObject(this, util
.toJSONOptions
);
28873 /*eslint-enable valid-jsdoc*/
28874 },{"./util/minimal":220}],203:[function(require
,module
,exports
){
28876 module
.exports
= Method
;
28878 // extends ReflectionObject
28879 var ReflectionObject
= require("./object");
28880 ((Method
.prototype = Object
.create(ReflectionObject
.prototype)).constructor = Method
).className
= "Method";
28882 var util
= require("./util");
28885 * Constructs a new service method instance.
28886 * @classdesc Reflected service method.
28887 * @extends ReflectionObject
28889 * @param {string} name Method name
28890 * @param {string|undefined} type Method type, usually `"rpc"`
28891 * @param {string} requestType Request message type
28892 * @param {string} responseType Response message type
28893 * @param {boolean|Object.<string,*>} [requestStream] Whether the request is streamed
28894 * @param {boolean|Object.<string,*>} [responseStream] Whether the response is streamed
28895 * @param {Object.<string,*>} [options] Declared options
28896 * @param {string} [comment] The comment for this method
28898 function Method(name
, type
, requestType
, responseType
, requestStream
, responseStream
, options
, comment
) {
28900 /* istanbul ignore next */
28901 if (util
.isObject(requestStream
)) {
28902 options
= requestStream
;
28903 requestStream
= responseStream
= undefined;
28904 } else if (util
.isObject(responseStream
)) {
28905 options
= responseStream
;
28906 responseStream
= undefined;
28909 /* istanbul ignore if */
28910 if (!(type
=== undefined || util
.isString(type
)))
28911 throw TypeError("type must be a string");
28913 /* istanbul ignore if */
28914 if (!util
.isString(requestType
))
28915 throw TypeError("requestType must be a string");
28917 /* istanbul ignore if */
28918 if (!util
.isString(responseType
))
28919 throw TypeError("responseType must be a string");
28921 ReflectionObject
.call(this, name
, options
);
28927 this.type
= type
|| "rpc"; // toJSON
28933 this.requestType
= requestType
; // toJSON, marker
28936 * Whether requests are streamed or not.
28937 * @type {boolean|undefined}
28939 this.requestStream
= requestStream
? true : undefined; // toJSON
28945 this.responseType
= responseType
; // toJSON
28948 * Whether responses are streamed or not.
28949 * @type {boolean|undefined}
28951 this.responseStream
= responseStream
? true : undefined; // toJSON
28954 * Resolved request type.
28955 * @type {Type|null}
28957 this.resolvedRequestType
= null;
28960 * Resolved response type.
28961 * @type {Type|null}
28963 this.resolvedResponseType
= null;
28966 * Comment for this method
28967 * @type {string|null}
28969 this.comment
= comment
;
28973 * Method descriptor.
28974 * @interface IMethod
28975 * @property {string} [type="rpc"] Method type
28976 * @property {string} requestType Request type
28977 * @property {string} responseType Response type
28978 * @property {boolean} [requestStream=false] Whether requests are streamed
28979 * @property {boolean} [responseStream=false] Whether responses are streamed
28980 * @property {Object.<string,*>} [options] Method options
28984 * Constructs a method from a method descriptor.
28985 * @param {string} name Method name
28986 * @param {IMethod} json Method descriptor
28987 * @returns {Method} Created method
28988 * @throws {TypeError} If arguments are invalid
28990 Method
.fromJSON
= function fromJSON(name
, json
) {
28991 return new Method(name
, json
.type
, json
.requestType
, json
.responseType
, json
.requestStream
, json
.responseStream
, json
.options
, json
.comment
);
28995 * Converts this method to a method descriptor.
28996 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
28997 * @returns {IMethod} Method descriptor
28999 Method
.prototype.toJSON
= function toJSON(toJSONOptions
) {
29000 var keepComments
= toJSONOptions
? Boolean(toJSONOptions
.keepComments
) : false;
29001 return util
.toObject([
29002 "type" , this.type
!== "rpc" && /* istanbul ignore next */ this.type
|| undefined,
29003 "requestType" , this.requestType
,
29004 "requestStream" , this.requestStream
,
29005 "responseType" , this.responseType
,
29006 "responseStream" , this.responseStream
,
29007 "options" , this.options
,
29008 "comment" , keepComments
? this.comment : undefined
29015 Method
.prototype.resolve
= function resolve() {
29017 /* istanbul ignore if */
29021 this.resolvedRequestType
= this.parent
.lookupType(this.requestType
);
29022 this.resolvedResponseType
= this.parent
.lookupType(this.responseType
);
29024 return ReflectionObject
.prototype.resolve
.call(this);
29027 },{"./object":205,"./util":218}],204:[function(require
,module
,exports
){
29029 module
.exports
= Namespace
;
29031 // extends ReflectionObject
29032 var ReflectionObject
= require("./object");
29033 ((Namespace
.prototype = Object
.create(ReflectionObject
.prototype)).constructor = Namespace
).className
= "Namespace";
29035 var Enum
= require("./enum"),
29036 Field
= require("./field"),
29037 util
= require("./util");
29039 var Type
, // cyclic
29043 * Constructs a new namespace instance.
29045 * @classdesc Reflected namespace.
29046 * @extends NamespaceBase
29048 * @param {string} name Namespace name
29049 * @param {Object.<string,*>} [options] Declared options
29053 * Constructs a namespace from JSON.
29054 * @memberof Namespace
29056 * @param {string} name Namespace name
29057 * @param {Object.<string,*>} json JSON object
29058 * @returns {Namespace} Created namespace
29059 * @throws {TypeError} If arguments are invalid
29061 Namespace
.fromJSON
= function fromJSON(name
, json
) {
29062 return new Namespace(name
, json
.options
).addJSON(json
.nested
);
29066 * Converts an array of reflection objects to JSON.
29067 * @memberof Namespace
29068 * @param {ReflectionObject[]} array Object array
29069 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
29070 * @returns {Object.<string,*>|undefined} JSON object or `undefined` when array is empty
29072 function arrayToJSON(array
, toJSONOptions
) {
29073 if (!(array
&& array
.length
))
29076 for (var i
= 0; i
< array
.length
; ++i
)
29077 obj
[array
[i
].name
] = array
[i
].toJSON(toJSONOptions
);
29081 Namespace
.arrayToJSON
= arrayToJSON
;
29084 * Tests if the specified id is reserved.
29085 * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
29086 * @param {number} id Id to test
29087 * @returns {boolean} `true` if reserved, otherwise `false`
29089 Namespace
.isReservedId
= function isReservedId(reserved
, id
) {
29091 for (var i
= 0; i
< reserved
.length
; ++i
)
29092 if (typeof reserved
[i
] !== "string" && reserved
[i
][0] <= id
&& reserved
[i
][1] >= id
)
29098 * Tests if the specified name is reserved.
29099 * @param {Array.<number[]|string>|undefined} reserved Array of reserved ranges and names
29100 * @param {string} name Name to test
29101 * @returns {boolean} `true` if reserved, otherwise `false`
29103 Namespace
.isReservedName
= function isReservedName(reserved
, name
) {
29105 for (var i
= 0; i
< reserved
.length
; ++i
)
29106 if (reserved
[i
] === name
)
29112 * Not an actual constructor. Use {@link Namespace} instead.
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.
29114 * @exports NamespaceBase
29115 * @extends ReflectionObject
29118 * @param {string} name Namespace name
29119 * @param {Object.<string,*>} [options] Declared options
29120 * @see {@link Namespace}
29122 function Namespace(name
, options
) {
29123 ReflectionObject
.call(this, name
, options
);
29126 * Nested objects by name.
29127 * @type {Object.<string,ReflectionObject>|undefined}
29129 this.nested
= undefined; // toJSON
29132 * Cached nested objects as an array.
29133 * @type {ReflectionObject[]|null}
29136 this._nestedArray
= null;
29139 function clearCache(namespace) {
29140 namespace._nestedArray
= null;
29145 * Nested objects of this namespace as an array for iteration.
29146 * @name NamespaceBase#nestedArray
29147 * @type {ReflectionObject[]}
29150 Object
.defineProperty(Namespace
.prototype, "nestedArray", {
29152 return this._nestedArray
|| (this._nestedArray
= util
.toArray(this.nested
));
29157 * Namespace descriptor.
29158 * @interface INamespace
29159 * @property {Object.<string,*>} [options] Namespace options
29160 * @property {Object.<string,AnyNestedObject>} [nested] Nested object descriptors
29164 * Any extension field descriptor.
29165 * @typedef AnyExtensionField
29166 * @type {IExtensionField|IExtensionMapField}
29170 * Any nested object descriptor.
29171 * @typedef AnyNestedObject
29172 * @type {IEnum|IType|IService|AnyExtensionField|INamespace}
29174 // ^ BEWARE: VSCode hangs forever when using more than 5 types (that's why AnyExtensionField exists in the first place)
29177 * Converts this namespace to a namespace descriptor.
29178 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
29179 * @returns {INamespace} Namespace descriptor
29181 Namespace
.prototype.toJSON
= function toJSON(toJSONOptions
) {
29182 return util
.toObject([
29183 "options" , this.options
,
29184 "nested" , arrayToJSON(this.nestedArray
, toJSONOptions
)
29189 * Adds nested objects to this namespace from nested object descriptors.
29190 * @param {Object.<string,AnyNestedObject>} nestedJson Any nested object descriptors
29191 * @returns {Namespace} `this`
29193 Namespace
.prototype.addJSON
= function addJSON(nestedJson
) {
29195 /* istanbul ignore else */
29197 for (var names
= Object
.keys(nestedJson
), i
= 0, nested
; i
< names
.length
; ++i
) {
29198 nested
= nestedJson
[names
[i
]];
29199 ns
.add( // most to least likely
29200 ( nested
.fields
!== undefined
29202 : nested
.values
!== undefined
29204 : nested
.methods
!== undefined
29206 : nested
.id
!== undefined
29208 : Namespace
.fromJSON
)(names
[i
], nested
)
29216 * Gets the nested object of the specified name.
29217 * @param {string} name Nested object name
29218 * @returns {ReflectionObject|null} The reflection object or `null` if it doesn't exist
29220 Namespace
.prototype.get = function get(name
) {
29221 return this.nested
&& this.nested
[name
]
29226 * Gets the values of the nested {@link Enum|enum} of the specified name.
29227 * This methods differs from {@link Namespace#get|get} in that it returns an enum's values directly and throws instead of returning `null`.
29228 * @param {string} name Nested enum name
29229 * @returns {Object.<string,number>} Enum values
29230 * @throws {Error} If there is no such enum
29232 Namespace
.prototype.getEnum
= function getEnum(name
) {
29233 if (this.nested
&& this.nested
[name
] instanceof Enum
)
29234 return this.nested
[name
].values
;
29235 throw Error("no such enum: " + name
);
29239 * Adds a nested object to this namespace.
29240 * @param {ReflectionObject} object Nested object to add
29241 * @returns {Namespace} `this`
29242 * @throws {TypeError} If arguments are invalid
29243 * @throws {Error} If there is already a nested object with this name
29245 Namespace
.prototype.add
= function add(object
) {
29247 if (!(object
instanceof Field
&& object
.extend
!== undefined || object
instanceof Type
|| object
instanceof Enum
|| object
instanceof Service
|| object
instanceof Namespace
))
29248 throw TypeError("object must be a valid nested object");
29253 var prev
= this.get(object
.name
);
29255 if (prev
instanceof Namespace
&& object
instanceof Namespace
&& !(prev
instanceof Type
|| prev
instanceof Service
)) {
29256 // replace plain namespace but keep existing nested elements and options
29257 var nested
= prev
.nestedArray
;
29258 for (var i
= 0; i
< nested
.length
; ++i
)
29259 object
.add(nested
[i
]);
29263 object
.setOptions(prev
.options
, true);
29266 throw Error("duplicate name '" + object
.name
+ "' in " + this);
29269 this.nested
[object
.name
] = object
;
29270 object
.onAdd(this);
29271 return clearCache(this);
29275 * Removes a nested object from this namespace.
29276 * @param {ReflectionObject} object Nested object to remove
29277 * @returns {Namespace} `this`
29278 * @throws {TypeError} If arguments are invalid
29279 * @throws {Error} If `object` is not a member of this namespace
29281 Namespace
.prototype.remove
= function remove(object
) {
29283 if (!(object
instanceof ReflectionObject
))
29284 throw TypeError("object must be a ReflectionObject");
29285 if (object
.parent
!== this)
29286 throw Error(object
+ " is not a member of " + this);
29288 delete this.nested
[object
.name
];
29289 if (!Object
.keys(this.nested
).length
)
29290 this.nested
= undefined;
29292 object
.onRemove(this);
29293 return clearCache(this);
29297 * Defines additial namespaces within this one if not yet existing.
29298 * @param {string|string[]} path Path to create
29299 * @param {*} [json] Nested types to create from JSON
29300 * @returns {Namespace} Pointer to the last namespace created or `this` if path is empty
29302 Namespace
.prototype.define
= function define(path
, json
) {
29304 if (util
.isString(path
))
29305 path
= path
.split(".");
29306 else if (!Array
.isArray(path
))
29307 throw TypeError("illegal path");
29308 if (path
&& path
.length
&& path
[0] === "")
29309 throw Error("path must be relative");
29312 while (path
.length
> 0) {
29313 var part
= path
.shift();
29314 if (ptr
.nested
&& ptr
.nested
[part
]) {
29315 ptr
= ptr
.nested
[part
];
29316 if (!(ptr
instanceof Namespace
))
29317 throw Error("path conflicts with non-namespace objects");
29319 ptr
.add(ptr
= new Namespace(part
));
29327 * Resolves this namespace's and all its nested objects' type references. Useful to validate a reflection tree, but comes at a cost.
29328 * @returns {Namespace} `this`
29330 Namespace
.prototype.resolveAll
= function resolveAll() {
29331 var nested
= this.nestedArray
, i
= 0;
29332 while (i
< nested
.length
)
29333 if (nested
[i
] instanceof Namespace
)
29334 nested
[i
++].resolveAll();
29336 nested
[i
++].resolve();
29337 return this.resolve();
29341 * Recursively looks up the reflection object matching the specified path in the scope of this namespace.
29342 * @param {string|string[]} path Path to look up
29343 * @param {*|Array.<*>} filterTypes Filter types, any combination of the constructors of `protobuf.Type`, `protobuf.Enum`, `protobuf.Service` etc.
29344 * @param {boolean} [parentAlreadyChecked=false] If known, whether the parent has already been checked
29345 * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
29347 Namespace
.prototype.lookup
= function lookup(path
, filterTypes
, parentAlreadyChecked
) {
29349 /* istanbul ignore next */
29350 if (typeof filterTypes
=== "boolean") {
29351 parentAlreadyChecked
= filterTypes
;
29352 filterTypes
= undefined;
29353 } else if (filterTypes
&& !Array
.isArray(filterTypes
))
29354 filterTypes
= [ filterTypes
];
29356 if (util
.isString(path
) && path
.length
) {
29359 path
= path
.split(".");
29360 } else if (!path
.length
)
29363 // Start at root if path is absolute
29364 if (path
[0] === "")
29365 return this.root
.lookup(path
.slice(1), filterTypes
);
29367 // Test if the first part matches any nested object, and if so, traverse if path contains more
29368 var found
= this.get(path
[0]);
29370 if (path
.length
=== 1) {
29371 if (!filterTypes
|| filterTypes
.indexOf(found
.constructor) > -1)
29373 } else if (found
instanceof Namespace
&& (found
= found
.lookup(path
.slice(1), filterTypes
, true)))
29376 // Otherwise try each nested namespace
29378 for (var i
= 0; i
< this.nestedArray
.length
; ++i
)
29379 if (this._nestedArray
[i
] instanceof Namespace
&& (found
= this._nestedArray
[i
].lookup(path
, filterTypes
, true)))
29382 // If there hasn't been a match, try again at the parent
29383 if (this.parent
=== null || parentAlreadyChecked
)
29385 return this.parent
.lookup(path
, filterTypes
);
29389 * Looks up the reflection object at the specified path, relative to this namespace.
29390 * @name NamespaceBase#lookup
29392 * @param {string|string[]} path Path to look up
29393 * @param {boolean} [parentAlreadyChecked=false] Whether the parent has already been checked
29394 * @returns {ReflectionObject|null} Looked up object or `null` if none could be found
29397 // lookup(path: string, [parentAlreadyChecked: boolean])
29400 * Looks up the {@link Type|type} at the specified path, relative to this namespace.
29401 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
29402 * @param {string|string[]} path Path to look up
29403 * @returns {Type} Looked up type
29404 * @throws {Error} If `path` does not point to a type
29406 Namespace
.prototype.lookupType
= function lookupType(path
) {
29407 var found
= this.lookup(path
, [ Type
]);
29409 throw Error("no such type: " + path
);
29414 * Looks up the values of the {@link Enum|enum} at the specified path, relative to this namespace.
29415 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
29416 * @param {string|string[]} path Path to look up
29417 * @returns {Enum} Looked up enum
29418 * @throws {Error} If `path` does not point to an enum
29420 Namespace
.prototype.lookupEnum
= function lookupEnum(path
) {
29421 var found
= this.lookup(path
, [ Enum
]);
29423 throw Error("no such Enum '" + path
+ "' in " + this);
29428 * Looks up the {@link Type|type} or {@link Enum|enum} at the specified path, relative to this namespace.
29429 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
29430 * @param {string|string[]} path Path to look up
29431 * @returns {Type} Looked up type or enum
29432 * @throws {Error} If `path` does not point to a type or enum
29434 Namespace
.prototype.lookupTypeOrEnum
= function lookupTypeOrEnum(path
) {
29435 var found
= this.lookup(path
, [ Type
, Enum
]);
29437 throw Error("no such Type or Enum '" + path
+ "' in " + this);
29442 * Looks up the {@link Service|service} at the specified path, relative to this namespace.
29443 * Besides its signature, this methods differs from {@link Namespace#lookup|lookup} in that it throws instead of returning `null`.
29444 * @param {string|string[]} path Path to look up
29445 * @returns {Service} Looked up service
29446 * @throws {Error} If `path` does not point to a service
29448 Namespace
.prototype.lookupService
= function lookupService(path
) {
29449 var found
= this.lookup(path
, [ Service
]);
29451 throw Error("no such Service '" + path
+ "' in " + this);
29455 Namespace
._configure = function(Type_
, Service_
) {
29457 Service
= Service_
;
29460 },{"./enum":196,"./field":197,"./object":205,"./util":218}],205:[function(require
,module
,exports
){
29462 module
.exports
= ReflectionObject
;
29464 ReflectionObject
.className
= "ReflectionObject";
29466 var util
= require("./util");
29468 var Root
; // cyclic
29471 * Constructs a new reflection object instance.
29472 * @classdesc Base class of all reflection objects.
29474 * @param {string} name Object name
29475 * @param {Object.<string,*>} [options] Declared options
29478 function ReflectionObject(name
, options
) {
29480 if (!util
.isString(name
))
29481 throw TypeError("name must be a string");
29483 if (options
&& !util
.isObject(options
))
29484 throw TypeError("options must be an object");
29488 * @type {Object.<string,*>|undefined}
29490 this.options
= options
; // toJSON
29493 * Unique name within its namespace.
29499 * Parent namespace.
29500 * @type {Namespace|null}
29502 this.parent
= null;
29505 * Whether already resolved or not.
29508 this.resolved
= false;
29511 * Comment text, if any.
29512 * @type {string|null}
29514 this.comment
= null;
29517 * Defining file name.
29518 * @type {string|null}
29520 this.filename
= null;
29523 Object
.defineProperties(ReflectionObject
.prototype, {
29526 * Reference to the root namespace.
29527 * @name ReflectionObject#root
29534 while (ptr
.parent
!== null)
29541 * Full name including leading dot.
29542 * @name ReflectionObject#fullName
29548 var path
= [ this.name
],
29551 path
.unshift(ptr
.name
);
29554 return path
.join(".");
29560 * Converts this reflection object to its descriptor representation.
29561 * @returns {Object.<string,*>} Descriptor
29564 ReflectionObject
.prototype.toJSON
= /* istanbul ignore next */ function toJSON() {
29565 throw Error(); // not implemented, shouldn't happen
29569 * Called when this object is added to a parent.
29570 * @param {ReflectionObject} parent Parent added to
29571 * @returns {undefined}
29573 ReflectionObject
.prototype.onAdd
= function onAdd(parent
) {
29574 if (this.parent
&& this.parent
!== parent
)
29575 this.parent
.remove(this);
29576 this.parent
= parent
;
29577 this.resolved
= false;
29578 var root
= parent
.root
;
29579 if (root
instanceof Root
)
29580 root
._handleAdd(this);
29584 * Called when this object is removed from a parent.
29585 * @param {ReflectionObject} parent Parent removed from
29586 * @returns {undefined}
29588 ReflectionObject
.prototype.onRemove
= function onRemove(parent
) {
29589 var root
= parent
.root
;
29590 if (root
instanceof Root
)
29591 root
._handleRemove(this);
29592 this.parent
= null;
29593 this.resolved
= false;
29597 * Resolves this objects type references.
29598 * @returns {ReflectionObject} `this`
29600 ReflectionObject
.prototype.resolve
= function resolve() {
29603 if (this.root
instanceof Root
)
29604 this.resolved
= true; // only if part of a root
29609 * Gets an option value.
29610 * @param {string} name Option name
29611 * @returns {*} Option value or `undefined` if not set
29613 ReflectionObject
.prototype.getOption
= function getOption(name
) {
29615 return this.options
[name
];
29621 * @param {string} name Option name
29622 * @param {*} value Option value
29623 * @param {boolean} [ifNotSet] Sets the option only if it isn't currently set
29624 * @returns {ReflectionObject} `this`
29626 ReflectionObject
.prototype.setOption
= function setOption(name
, value
, ifNotSet
) {
29627 if (!ifNotSet
|| !this.options
|| this.options
[name
] === undefined)
29628 (this.options
|| (this.options
= {}))[name
] = value
;
29633 * Sets multiple options.
29634 * @param {Object.<string,*>} options Options to set
29635 * @param {boolean} [ifNotSet] Sets an option only if it isn't currently set
29636 * @returns {ReflectionObject} `this`
29638 ReflectionObject
.prototype.setOptions
= function setOptions(options
, ifNotSet
) {
29640 for (var keys
= Object
.keys(options
), i
= 0; i
< keys
.length
; ++i
)
29641 this.setOption(keys
[i
], options
[keys
[i
]], ifNotSet
);
29646 * Converts this instance to its string representation.
29647 * @returns {string} Class name[, space, full name]
29649 ReflectionObject
.prototype.toString
= function toString() {
29650 var className
= this.constructor.className
,
29651 fullName
= this.fullName
;
29652 if (fullName
.length
)
29653 return className
+ " " + fullName
;
29657 ReflectionObject
._configure = function(Root_
) {
29661 },{"./util":218}],206:[function(require
,module
,exports
){
29663 module
.exports
= OneOf
;
29665 // extends ReflectionObject
29666 var ReflectionObject
= require("./object");
29667 ((OneOf
.prototype = Object
.create(ReflectionObject
.prototype)).constructor = OneOf
).className
= "OneOf";
29669 var Field
= require("./field"),
29670 util
= require("./util");
29673 * Constructs a new oneof instance.
29674 * @classdesc Reflected oneof.
29675 * @extends ReflectionObject
29677 * @param {string} name Oneof name
29678 * @param {string[]|Object.<string,*>} [fieldNames] Field names
29679 * @param {Object.<string,*>} [options] Declared options
29680 * @param {string} [comment] Comment associated with this field
29682 function OneOf(name
, fieldNames
, options
, comment
) {
29683 if (!Array
.isArray(fieldNames
)) {
29684 options
= fieldNames
;
29685 fieldNames
= undefined;
29687 ReflectionObject
.call(this, name
, options
);
29689 /* istanbul ignore if */
29690 if (!(fieldNames
=== undefined || Array
.isArray(fieldNames
)))
29691 throw TypeError("fieldNames must be an Array");
29694 * Field names that belong to this oneof.
29697 this.oneof
= fieldNames
|| []; // toJSON, marker
29700 * Fields that belong to this oneof as an array for iteration.
29704 this.fieldsArray
= []; // declared readonly for conformance, possibly not yet added to parent
29707 * Comment for this field.
29708 * @type {string|null}
29710 this.comment
= comment
;
29714 * Oneof descriptor.
29715 * @interface IOneOf
29716 * @property {Array.<string>} oneof Oneof field names
29717 * @property {Object.<string,*>} [options] Oneof options
29721 * Constructs a oneof from a oneof descriptor.
29722 * @param {string} name Oneof name
29723 * @param {IOneOf} json Oneof descriptor
29724 * @returns {OneOf} Created oneof
29725 * @throws {TypeError} If arguments are invalid
29727 OneOf
.fromJSON
= function fromJSON(name
, json
) {
29728 return new OneOf(name
, json
.oneof
, json
.options
, json
.comment
);
29732 * Converts this oneof to a oneof descriptor.
29733 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
29734 * @returns {IOneOf} Oneof descriptor
29736 OneOf
.prototype.toJSON
= function toJSON(toJSONOptions
) {
29737 var keepComments
= toJSONOptions
? Boolean(toJSONOptions
.keepComments
) : false;
29738 return util
.toObject([
29739 "options" , this.options
,
29740 "oneof" , this.oneof
,
29741 "comment" , keepComments
? this.comment : undefined
29746 * Adds the fields of the specified oneof to the parent if not already done so.
29747 * @param {OneOf} oneof The oneof
29748 * @returns {undefined}
29752 function addFieldsToParent(oneof
) {
29754 for (var i
= 0; i
< oneof
.fieldsArray
.length
; ++i
)
29755 if (!oneof
.fieldsArray
[i
].parent
)
29756 oneof
.parent
.add(oneof
.fieldsArray
[i
]);
29760 * Adds a field to this oneof and removes it from its current parent, if any.
29761 * @param {Field} field Field to add
29762 * @returns {OneOf} `this`
29764 OneOf
.prototype.add
= function add(field
) {
29766 /* istanbul ignore if */
29767 if (!(field
instanceof Field
))
29768 throw TypeError("field must be a Field");
29770 if (field
.parent
&& field
.parent
!== this.parent
)
29771 field
.parent
.remove(field
);
29772 this.oneof
.push(field
.name
);
29773 this.fieldsArray
.push(field
);
29774 field
.partOf
= this; // field.parent remains null
29775 addFieldsToParent(this);
29780 * Removes a field from this oneof and puts it back to the oneof's parent.
29781 * @param {Field} field Field to remove
29782 * @returns {OneOf} `this`
29784 OneOf
.prototype.remove
= function remove(field
) {
29786 /* istanbul ignore if */
29787 if (!(field
instanceof Field
))
29788 throw TypeError("field must be a Field");
29790 var index
= this.fieldsArray
.indexOf(field
);
29792 /* istanbul ignore if */
29794 throw Error(field
+ " is not a member of " + this);
29796 this.fieldsArray
.splice(index
, 1);
29797 index
= this.oneof
.indexOf(field
.name
);
29799 /* istanbul ignore else */
29800 if (index
> -1) // theoretical
29801 this.oneof
.splice(index
, 1);
29803 field
.partOf
= null;
29810 OneOf
.prototype.onAdd
= function onAdd(parent
) {
29811 ReflectionObject
.prototype.onAdd
.call(this, parent
);
29813 // Collect present fields
29814 for (var i
= 0; i
< this.oneof
.length
; ++i
) {
29815 var field
= parent
.get(this.oneof
[i
]);
29816 if (field
&& !field
.partOf
) {
29817 field
.partOf
= self
;
29818 self
.fieldsArray
.push(field
);
29821 // Add not yet present fields
29822 addFieldsToParent(this);
29828 OneOf
.prototype.onRemove
= function onRemove(parent
) {
29829 for (var i
= 0, field
; i
< this.fieldsArray
.length
; ++i
)
29830 if ((field
= this.fieldsArray
[i
]).parent
)
29831 field
.parent
.remove(field
);
29832 ReflectionObject
.prototype.onRemove
.call(this, parent
);
29836 * Decorator function as returned by {@link OneOf.d} (TypeScript).
29837 * @typedef OneOfDecorator
29839 * @param {Object} prototype Target prototype
29840 * @param {string} oneofName OneOf name
29841 * @returns {undefined}
29845 * OneOf decorator (TypeScript).
29847 * @param {...string} fieldNames Field names
29848 * @returns {OneOfDecorator} Decorator function
29849 * @template T extends string
29851 OneOf
.d
= function decorateOneOf() {
29852 var fieldNames
= new Array(arguments
.length
),
29854 while (index
< arguments
.length
)
29855 fieldNames
[index
] = arguments
[index
++];
29856 return function oneOfDecorator(prototype, oneofName
) {
29857 util
.decorateType(prototype.constructor)
29858 .add(new OneOf(oneofName
, fieldNames
));
29859 Object
.defineProperty(prototype, oneofName
, {
29860 get: util
.oneOfGetter(fieldNames
),
29861 set: util
.oneOfSetter(fieldNames
)
29866 },{"./field":197,"./object":205,"./util":218}],207:[function(require
,module
,exports
){
29868 module
.exports
= parse
;
29870 parse
.filename
= null;
29871 parse
.defaults
= { keepCase: false };
29873 var tokenize
= require("./tokenize"),
29874 Root
= require("./root"),
29875 Type
= require("./type"),
29876 Field
= require("./field"),
29877 MapField
= require("./mapfield"),
29878 OneOf
= require("./oneof"),
29879 Enum
= require("./enum"),
29880 Service
= require("./service"),
29881 Method
= require("./method"),
29882 types
= require("./types"),
29883 util
= require("./util");
29885 var base10Re
= /^[1-9][0-9]*$/,
29886 base10NegRe
= /^-?[1-9][0-9]*$/,
29887 base16Re
= /^0[x][0-9a-fA-F]+$/,
29888 base16NegRe
= /^-?0[x][0-9a-fA-F]+$/,
29889 base8Re
= /^0[0-7]+$/,
29890 base8NegRe
= /^-?0[0-7]+$/,
29891 numberRe
= /^(?![eE])[0-9]*(?:\.[0-9]*)?(?:[eE][+-]?[0-9]+)?$/,
29892 nameRe
= /^[a-zA-Z_][a-zA-Z_0-9]*$/,
29893 typeRefRe
= /^(?:\.?[a-zA-Z_][a-zA-Z_0-9]*)(?:\.[a-zA-Z_][a-zA-Z_0-9]*)*$/,
29894 fqTypeRefRe
= /^(?:\.[a-zA-Z_][a-zA-Z_0-9]*)+$/;
29897 * Result object returned from {@link parse}.
29898 * @interface IParserResult
29899 * @property {string|undefined} package Package name, if declared
29900 * @property {string[]|undefined} imports Imports, if any
29901 * @property {string[]|undefined} weakImports Weak imports, if any
29902 * @property {string|undefined} syntax Syntax, if specified (either `"proto2"` or `"proto3"`)
29903 * @property {Root} root Populated root instance
29907 * Options modifying the behavior of {@link parse}.
29908 * @interface IParseOptions
29909 * @property {boolean} [keepCase=false] Keeps field casing instead of converting to camel case
29910 * @property {boolean} [alternateCommentMode=false] Recognize double-slash comments in addition to doc-block comments.
29914 * Options modifying the behavior of JSON serialization.
29915 * @interface IToJSONOptions
29916 * @property {boolean} [keepComments=false] Serializes comments.
29920 * Parses the given .proto source and returns an object with the parsed contents.
29921 * @param {string} source Source contents
29922 * @param {Root} root Root to populate
29923 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
29924 * @returns {IParserResult} Parser result
29925 * @property {string} filename=null Currently processing file name for error reporting, if known
29926 * @property {IParseOptions} defaults Default {@link IParseOptions}
29928 function parse(source
, root
, options
) {
29929 /* eslint-disable callback-return */
29930 if (!(root
instanceof Root
)) {
29935 options
= parse
.defaults
;
29937 var tn
= tokenize(source
, options
.alternateCommentMode
|| false),
29953 var applyCase
= options
.keepCase
? function(name
) { return name
; } : util
.camelCase
;
29955 /* istanbul ignore next */
29956 function illegal(token
, name
, insideTryCatch
) {
29957 var filename
= parse
.filename
;
29958 if (!insideTryCatch
)
29959 parse
.filename
= null;
29960 return Error("illegal " + (name
|| "token") + " '" + token
+ "' (" + (filename
? filename
+ ", " : "") + "line " + tn
.line
+ ")");
29963 function readString() {
29967 /* istanbul ignore if */
29968 if ((token
= next()) !== "\"" && token
!== "'")
29969 throw illegal(token
);
29971 values
.push(next());
29974 } while (token
=== "\"" || token
=== "'");
29975 return values
.join("");
29978 function readValue(acceptTypeRef
) {
29979 var token
= next();
29984 return readString();
29985 case "true": case "TRUE":
29987 case "false": case "FALSE":
29991 return parseNumber(token
, /* insideTryCatch */ true);
29994 /* istanbul ignore else */
29995 if (acceptTypeRef
&& typeRefRe
.test(token
))
29998 /* istanbul ignore next */
29999 throw illegal(token
, "value");
30003 function readRanges(target
, acceptStrings
) {
30006 if (acceptStrings
&& ((token
= peek()) === "\"" || token
=== "'"))
30007 target
.push(readString());
30009 target
.push([ start
= parseId(next()), skip("to", true) ? parseId(next()) : start
]);
30010 } while (skip(",", true));
30014 function parseNumber(token
, insideTryCatch
) {
30016 if (token
.charAt(0) === "-") {
30018 token
= token
.substring(1);
30021 case "inf": case "INF": case "Inf":
30022 return sign
* Infinity
;
30023 case "nan": case "NAN": case "Nan": case "NaN":
30028 if (base10Re
.test(token
))
30029 return sign
* parseInt(token
, 10);
30030 if (base16Re
.test(token
))
30031 return sign
* parseInt(token
, 16);
30032 if (base8Re
.test(token
))
30033 return sign
* parseInt(token
, 8);
30035 /* istanbul ignore else */
30036 if (numberRe
.test(token
))
30037 return sign
* parseFloat(token
);
30039 /* istanbul ignore next */
30040 throw illegal(token
, "number", insideTryCatch
);
30043 function parseId(token
, acceptNegative
) {
30045 case "max": case "MAX": case "Max":
30051 /* istanbul ignore if */
30052 if (!acceptNegative
&& token
.charAt(0) === "-")
30053 throw illegal(token
, "id");
30055 if (base10NegRe
.test(token
))
30056 return parseInt(token
, 10);
30057 if (base16NegRe
.test(token
))
30058 return parseInt(token
, 16);
30060 /* istanbul ignore else */
30061 if (base8NegRe
.test(token
))
30062 return parseInt(token
, 8);
30064 /* istanbul ignore next */
30065 throw illegal(token
, "id");
30068 function parsePackage() {
30070 /* istanbul ignore if */
30071 if (pkg
!== undefined)
30072 throw illegal("package");
30076 /* istanbul ignore if */
30077 if (!typeRefRe
.test(pkg
))
30078 throw illegal(pkg
, "name");
30080 ptr
= ptr
.define(pkg
);
30084 function parseImport() {
30085 var token
= peek();
30089 whichImports
= weakImports
|| (weakImports
= []);
30094 // eslint-disable-line no-fallthrough
30096 whichImports
= imports
|| (imports
= []);
30099 token
= readString();
30101 whichImports
.push(token
);
30104 function parseSyntax() {
30106 syntax
= readString();
30107 isProto3
= syntax
=== "proto3";
30109 /* istanbul ignore if */
30110 if (!isProto3
&& syntax
!== "proto2")
30111 throw illegal(syntax
, "syntax");
30116 function parseCommon(parent
, token
) {
30120 parseOption(parent
, token
);
30125 parseType(parent
, token
);
30129 parseEnum(parent
, token
);
30133 parseService(parent
, token
);
30137 parseExtension(parent
, token
);
30143 function ifBlock(obj
, fnIf
, fnElse
) {
30144 var trailingLine
= tn
.line
;
30146 obj
.comment
= cmnt(); // try block-type comment
30147 obj
.filename
= parse
.filename
;
30149 if (skip("{", true)) {
30151 while ((token
= next()) !== "}")
30158 if (obj
&& typeof obj
.comment
!== "string")
30159 obj
.comment
= cmnt(trailingLine
); // try line-type comment if no block
30163 function parseType(parent
, token
) {
30165 /* istanbul ignore if */
30166 if (!nameRe
.test(token
= next()))
30167 throw illegal(token
, "type name");
30169 var type
= new Type(token
);
30170 ifBlock(type
, function parseType_block(token
) {
30171 if (parseCommon(type
, token
))
30177 parseMapField(type
, token
);
30183 parseField(type
, token
);
30187 parseOneOf(type
, token
);
30191 readRanges(type
.extensions
|| (type
.extensions
= []));
30195 readRanges(type
.reserved
|| (type
.reserved
= []), true);
30199 /* istanbul ignore if */
30200 if (!isProto3
|| !typeRefRe
.test(token
))
30201 throw illegal(token
);
30204 parseField(type
, "optional");
30211 function parseField(parent
, rule
, extend
) {
30213 if (type
=== "group") {
30214 parseGroup(parent
, rule
);
30218 /* istanbul ignore if */
30219 if (!typeRefRe
.test(type
))
30220 throw illegal(type
, "type");
30224 /* istanbul ignore if */
30225 if (!nameRe
.test(name
))
30226 throw illegal(name
, "name");
30228 name
= applyCase(name
);
30231 var field
= new Field(name
, parseId(next()), type
, rule
, extend
);
30232 ifBlock(field
, function parseField_block(token
) {
30234 /* istanbul ignore else */
30235 if (token
=== "option") {
30236 parseOption(field
, token
);
30239 throw illegal(token
);
30241 }, function parseField_line() {
30242 parseInlineOptions(field
);
30246 // JSON defaults to packed=true if not set so we have to set packed=false explicity when
30247 // parsing proto2 descriptors without the option, where applicable. This must be done for
30248 // all known packable types and anything that could be an enum (= is not a basic type).
30249 if (!isProto3
&& field
.repeated
&& (types
.packed
[type
] !== undefined || types
.basic
[type
] === undefined))
30250 field
.setOption("packed", false, /* ifNotSet */ true);
30253 function parseGroup(parent
, rule
) {
30256 /* istanbul ignore if */
30257 if (!nameRe
.test(name
))
30258 throw illegal(name
, "name");
30260 var fieldName
= util
.lcFirst(name
);
30261 if (name
=== fieldName
)
30262 name
= util
.ucFirst(name
);
30264 var id
= parseId(next());
30265 var type
= new Type(name
);
30267 var field
= new Field(fieldName
, id
, name
, rule
);
30268 field
.filename
= parse
.filename
;
30269 ifBlock(type
, function parseGroup_block(token
) {
30273 parseOption(type
, token
);
30280 parseField(type
, token
);
30283 /* istanbul ignore next */
30285 throw illegal(token
); // there are no groups with proto3 semantics
30292 function parseMapField(parent
) {
30294 var keyType
= next();
30296 /* istanbul ignore if */
30297 if (types
.mapKey
[keyType
] === undefined)
30298 throw illegal(keyType
, "type");
30301 var valueType
= next();
30303 /* istanbul ignore if */
30304 if (!typeRefRe
.test(valueType
))
30305 throw illegal(valueType
, "type");
30310 /* istanbul ignore if */
30311 if (!nameRe
.test(name
))
30312 throw illegal(name
, "name");
30315 var field
= new MapField(applyCase(name
), parseId(next()), keyType
, valueType
);
30316 ifBlock(field
, function parseMapField_block(token
) {
30318 /* istanbul ignore else */
30319 if (token
=== "option") {
30320 parseOption(field
, token
);
30323 throw illegal(token
);
30325 }, function parseMapField_line() {
30326 parseInlineOptions(field
);
30331 function parseOneOf(parent
, token
) {
30333 /* istanbul ignore if */
30334 if (!nameRe
.test(token
= next()))
30335 throw illegal(token
, "name");
30337 var oneof
= new OneOf(applyCase(token
));
30338 ifBlock(oneof
, function parseOneOf_block(token
) {
30339 if (token
=== "option") {
30340 parseOption(oneof
, token
);
30344 parseField(oneof
, "optional");
30350 function parseEnum(parent
, token
) {
30352 /* istanbul ignore if */
30353 if (!nameRe
.test(token
= next()))
30354 throw illegal(token
, "name");
30356 var enm
= new Enum(token
);
30357 ifBlock(enm
, function parseEnum_block(token
) {
30360 parseOption(enm
, token
);
30365 readRanges(enm
.reserved
|| (enm
.reserved
= []), true);
30369 parseEnumValue(enm
, token
);
30375 function parseEnumValue(parent
, token
) {
30377 /* istanbul ignore if */
30378 if (!nameRe
.test(token
))
30379 throw illegal(token
, "name");
30382 var value
= parseId(next(), true),
30384 ifBlock(dummy
, function parseEnumValue_block(token
) {
30386 /* istanbul ignore else */
30387 if (token
=== "option") {
30388 parseOption(dummy
, token
); // skip
30391 throw illegal(token
);
30393 }, function parseEnumValue_line() {
30394 parseInlineOptions(dummy
); // skip
30396 parent
.add(token
, value
, dummy
.comment
);
30399 function parseOption(parent
, token
) {
30400 var isCustom
= skip("(", true);
30402 /* istanbul ignore if */
30403 if (!typeRefRe
.test(token
= next()))
30404 throw illegal(token
, "name");
30409 name
= "(" + name
+ ")";
30411 if (fqTypeRefRe
.test(token
)) {
30417 parseOptionValue(parent
, name
);
30420 function parseOptionValue(parent
, name
) {
30421 if (skip("{", true)) { // { a: "foo" b { c: "bar" } }
30423 /* istanbul ignore if */
30424 if (!nameRe
.test(token
= next()))
30425 throw illegal(token
, "name");
30427 if (peek() === "{")
30428 parseOptionValue(parent
, name
+ "." + token
);
30431 if (peek() === "{")
30432 parseOptionValue(parent
, name
+ "." + token
);
30434 setOption(parent
, name
+ "." + token
, readValue(true));
30436 } while (!skip("}", true));
30438 setOption(parent
, name
, readValue(true));
30439 // Does not enforce a delimiter to be universal
30442 function setOption(parent
, name
, value
) {
30443 if (parent
.setOption
)
30444 parent
.setOption(name
, value
);
30447 function parseInlineOptions(parent
) {
30448 if (skip("[", true)) {
30450 parseOption(parent
, "option");
30451 } while (skip(",", true));
30457 function parseService(parent
, token
) {
30459 /* istanbul ignore if */
30460 if (!nameRe
.test(token
= next()))
30461 throw illegal(token
, "service name");
30463 var service
= new Service(token
);
30464 ifBlock(service
, function parseService_block(token
) {
30465 if (parseCommon(service
, token
))
30468 /* istanbul ignore else */
30469 if (token
=== "rpc")
30470 parseMethod(service
, token
);
30472 throw illegal(token
);
30474 parent
.add(service
);
30477 function parseMethod(parent
, token
) {
30480 /* istanbul ignore if */
30481 if (!nameRe
.test(token
= next()))
30482 throw illegal(token
, "name");
30485 requestType
, requestStream
,
30486 responseType
, responseStream
;
30489 if (skip("stream", true))
30490 requestStream
= true;
30492 /* istanbul ignore if */
30493 if (!typeRefRe
.test(token
= next()))
30494 throw illegal(token
);
30496 requestType
= token
;
30497 skip(")"); skip("returns"); skip("(");
30498 if (skip("stream", true))
30499 responseStream
= true;
30501 /* istanbul ignore if */
30502 if (!typeRefRe
.test(token
= next()))
30503 throw illegal(token
);
30505 responseType
= token
;
30508 var method
= new Method(name
, type
, requestType
, responseType
, requestStream
, responseStream
);
30509 ifBlock(method
, function parseMethod_block(token
) {
30511 /* istanbul ignore else */
30512 if (token
=== "option") {
30513 parseOption(method
, token
);
30516 throw illegal(token
);
30519 parent
.add(method
);
30522 function parseExtension(parent
, token
) {
30524 /* istanbul ignore if */
30525 if (!typeRefRe
.test(token
= next()))
30526 throw illegal(token
, "reference");
30528 var reference
= token
;
30529 ifBlock(null, function parseExtension_block(token
) {
30535 parseField(parent
, token
, reference
);
30539 /* istanbul ignore if */
30540 if (!isProto3
|| !typeRefRe
.test(token
))
30541 throw illegal(token
);
30543 parseField(parent
, "optional", reference
);
30550 while ((token
= next()) !== null) {
30555 /* istanbul ignore if */
30557 throw illegal(token
);
30564 /* istanbul ignore if */
30566 throw illegal(token
);
30573 /* istanbul ignore if */
30575 throw illegal(token
);
30582 /* istanbul ignore if */
30584 throw illegal(token
);
30586 parseOption(ptr
, token
);
30592 /* istanbul ignore else */
30593 if (parseCommon(ptr
, token
)) {
30598 /* istanbul ignore next */
30599 throw illegal(token
);
30603 parse
.filename
= null;
30606 "imports" : imports
,
30607 weakImports : weakImports
,
30614 * Parses the given .proto source and returns an object with the parsed contents.
30617 * @param {string} source Source contents
30618 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
30619 * @returns {IParserResult} Parser result
30620 * @property {string} filename=null Currently processing file name for error reporting, if known
30621 * @property {IParseOptions} defaults Default {@link IParseOptions}
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
){
30627 module
.exports
= Reader
;
30629 var util
= require("./util/minimal");
30631 var BufferReader
; // cyclic
30633 var LongBits
= util
.LongBits
,
30636 /* istanbul ignore next */
30637 function indexOutOfRange(reader
, writeLength
) {
30638 return RangeError("index out of range: " + reader
.pos
+ " + " + (writeLength
|| 1) + " > " + reader
.len
);
30642 * Constructs a new reader instance using the specified buffer.
30643 * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`.
30645 * @param {Uint8Array} buffer Buffer to read from
30647 function Reader(buffer
) {
30651 * @type {Uint8Array}
30656 * Read buffer position.
30662 * Read buffer length.
30665 this.len
= buffer
.length
;
30668 var create_array
= typeof Uint8Array
!== "undefined"
30669 ? function create_typed_array(buffer
) {
30670 if (buffer
instanceof Uint8Array
|| Array
.isArray(buffer
))
30671 return new Reader(buffer
);
30672 throw Error("illegal buffer");
30674 /* istanbul ignore next */
30675 : function create_array(buffer
) {
30676 if (Array
.isArray(buffer
))
30677 return new Reader(buffer
);
30678 throw Error("illegal buffer");
30682 * Creates a new reader using the specified buffer.
30684 * @param {Uint8Array|Buffer} buffer Buffer to read from
30685 * @returns {Reader|BufferReader} A {@link BufferReader} if `buffer` is a Buffer, otherwise a {@link Reader}
30686 * @throws {Error} If `buffer` is not a valid buffer
30688 Reader
.create
= util
.Buffer
30689 ? function create_buffer_setup(buffer
) {
30690 return (Reader
.create
= function create_buffer(buffer
) {
30691 return util
.Buffer
.isBuffer(buffer
)
30692 ? new BufferReader(buffer
)
30693 /* istanbul ignore next */
30694 : create_array(buffer
);
30697 /* istanbul ignore next */
30700 Reader
.prototype._slice
= util
.Array
.prototype.subarray
|| /* istanbul ignore next */ util
.Array
.prototype.slice
;
30703 * Reads a varint as an unsigned 32 bit value.
30705 * @returns {number} Value read
30707 Reader
.prototype.uint32
= (function read_uint32_setup() {
30708 var value
= 4294967295; // optimizer type-hint, tends to deopt otherwise (?!)
30709 return function read_uint32() {
30710 value
= ( this.buf
[this.pos
] & 127 ) >>> 0; if (this.buf
[this.pos
++] < 128) return value
;
30711 value
= (value
| (this.buf
[this.pos
] & 127) << 7) >>> 0; if (this.buf
[this.pos
++] < 128) return value
;
30712 value
= (value
| (this.buf
[this.pos
] & 127) << 14) >>> 0; if (this.buf
[this.pos
++] < 128) return value
;
30713 value
= (value
| (this.buf
[this.pos
] & 127) << 21) >>> 0; if (this.buf
[this.pos
++] < 128) return value
;
30714 value
= (value
| (this.buf
[this.pos
] & 15) << 28) >>> 0; if (this.buf
[this.pos
++] < 128) return value
;
30716 /* istanbul ignore if */
30717 if ((this.pos
+= 5) > this.len
) {
30718 this.pos
= this.len
;
30719 throw indexOutOfRange(this, 10);
30726 * Reads a varint as a signed 32 bit value.
30727 * @returns {number} Value read
30729 Reader
.prototype.int32
= function read_int32() {
30730 return this.uint32() | 0;
30734 * Reads a zig-zag encoded varint as a signed 32 bit value.
30735 * @returns {number} Value read
30737 Reader
.prototype.sint32
= function read_sint32() {
30738 var value
= this.uint32();
30739 return value
>>> 1 ^ -(value
& 1) | 0;
30742 /* eslint-disable no-invalid-this */
30744 function readLongVarint() {
30745 // tends to deopt with local vars for octet etc.
30746 var bits
= new LongBits(0, 0);
30748 if (this.len
- this.pos
> 4) { // fast route (lo)
30749 for (; i
< 4; ++i
) {
30751 bits
.lo
= (bits
.lo
| (this.buf
[this.pos
] & 127) << i
* 7) >>> 0;
30752 if (this.buf
[this.pos
++] < 128)
30756 bits
.lo
= (bits
.lo
| (this.buf
[this.pos
] & 127) << 28) >>> 0;
30757 bits
.hi
= (bits
.hi
| (this.buf
[this.pos
] & 127) >> 4) >>> 0;
30758 if (this.buf
[this.pos
++] < 128)
30762 for (; i
< 3; ++i
) {
30763 /* istanbul ignore if */
30764 if (this.pos
>= this.len
)
30765 throw indexOutOfRange(this);
30767 bits
.lo
= (bits
.lo
| (this.buf
[this.pos
] & 127) << i
* 7) >>> 0;
30768 if (this.buf
[this.pos
++] < 128)
30772 bits
.lo
= (bits
.lo
| (this.buf
[this.pos
++] & 127) << i
* 7) >>> 0;
30775 if (this.len
- this.pos
> 4) { // fast route (hi)
30776 for (; i
< 5; ++i
) {
30778 bits
.hi
= (bits
.hi
| (this.buf
[this.pos
] & 127) << i
* 7 + 3) >>> 0;
30779 if (this.buf
[this.pos
++] < 128)
30783 for (; i
< 5; ++i
) {
30784 /* istanbul ignore if */
30785 if (this.pos
>= this.len
)
30786 throw indexOutOfRange(this);
30788 bits
.hi
= (bits
.hi
| (this.buf
[this.pos
] & 127) << i
* 7 + 3) >>> 0;
30789 if (this.buf
[this.pos
++] < 128)
30793 /* istanbul ignore next */
30794 throw Error("invalid varint encoding");
30797 /* eslint-enable no-invalid-this */
30800 * Reads a varint as a signed 64 bit value.
30801 * @name Reader#int64
30803 * @returns {Long} Value read
30807 * Reads a varint as an unsigned 64 bit value.
30808 * @name Reader#uint64
30810 * @returns {Long} Value read
30814 * Reads a zig-zag encoded varint as a signed 64 bit value.
30815 * @name Reader#sint64
30817 * @returns {Long} Value read
30821 * Reads a varint as a boolean.
30822 * @returns {boolean} Value read
30824 Reader
.prototype.bool
= function read_bool() {
30825 return this.uint32() !== 0;
30828 function readFixed32_end(buf
, end
) { // note that this uses `end`, not `pos`
30829 return (buf
[end
- 4]
30830 | buf
[end
- 3] << 8
30831 | buf
[end
- 2] << 16
30832 | buf
[end
- 1] << 24) >>> 0;
30836 * Reads fixed 32 bits as an unsigned 32 bit integer.
30837 * @returns {number} Value read
30839 Reader
.prototype.fixed32
= function read_fixed32() {
30841 /* istanbul ignore if */
30842 if (this.pos
+ 4 > this.len
)
30843 throw indexOutOfRange(this, 4);
30845 return readFixed32_end(this.buf
, this.pos
+= 4);
30849 * Reads fixed 32 bits as a signed 32 bit integer.
30850 * @returns {number} Value read
30852 Reader
.prototype.sfixed32
= function read_sfixed32() {
30854 /* istanbul ignore if */
30855 if (this.pos
+ 4 > this.len
)
30856 throw indexOutOfRange(this, 4);
30858 return readFixed32_end(this.buf
, this.pos
+= 4) | 0;
30861 /* eslint-disable no-invalid-this */
30863 function readFixed64(/* this: Reader */) {
30865 /* istanbul ignore if */
30866 if (this.pos
+ 8 > this.len
)
30867 throw indexOutOfRange(this, 8);
30869 return new LongBits(readFixed32_end(this.buf
, this.pos
+= 4), readFixed32_end(this.buf
, this.pos
+= 4));
30872 /* eslint-enable no-invalid-this */
30875 * Reads fixed 64 bits.
30876 * @name Reader#fixed64
30878 * @returns {Long} Value read
30882 * Reads zig-zag encoded fixed 64 bits.
30883 * @name Reader#sfixed64
30885 * @returns {Long} Value read
30889 * Reads a float (32 bit) as a number.
30891 * @returns {number} Value read
30893 Reader
.prototype.float = function read_float() {
30895 /* istanbul ignore if */
30896 if (this.pos
+ 4 > this.len
)
30897 throw indexOutOfRange(this, 4);
30899 var value
= util
.float.readFloatLE(this.buf
, this.pos
);
30905 * Reads a double (64 bit float) as a number.
30907 * @returns {number} Value read
30909 Reader
.prototype.double = function read_double() {
30911 /* istanbul ignore if */
30912 if (this.pos
+ 8 > this.len
)
30913 throw indexOutOfRange(this, 4);
30915 var value
= util
.float.readDoubleLE(this.buf
, this.pos
);
30921 * Reads a sequence of bytes preceeded by its length as a varint.
30922 * @returns {Uint8Array} Value read
30924 Reader
.prototype.bytes
= function read_bytes() {
30925 var length
= this.uint32(),
30927 end
= this.pos
+ length
;
30929 /* istanbul ignore if */
30930 if (end
> this.len
)
30931 throw indexOutOfRange(this, length
);
30933 this.pos
+= length
;
30934 if (Array
.isArray(this.buf
)) // plain array
30935 return this.buf
.slice(start
, end
);
30936 return start
=== end
// fix for IE 10/Win8 and others' subarray returning array of size 1
30937 ? new this.buf
.constructor(0)
30938 : this._slice
.call(this.buf
, start
, end
);
30942 * Reads a string preceeded by its byte length as a varint.
30943 * @returns {string} Value read
30945 Reader
.prototype.string
= function read_string() {
30946 var bytes
= this.bytes();
30947 return utf8
.read(bytes
, 0, bytes
.length
);
30951 * Skips the specified number of bytes if specified, otherwise skips a varint.
30952 * @param {number} [length] Length if known, otherwise a varint is assumed
30953 * @returns {Reader} `this`
30955 Reader
.prototype.skip
= function skip(length
) {
30956 if (typeof length
=== "number") {
30957 /* istanbul ignore if */
30958 if (this.pos
+ length
> this.len
)
30959 throw indexOutOfRange(this, length
);
30960 this.pos
+= length
;
30963 /* istanbul ignore if */
30964 if (this.pos
>= this.len
)
30965 throw indexOutOfRange(this);
30966 } while (this.buf
[this.pos
++] & 128);
30972 * Skips the next element of the specified wire type.
30973 * @param {number} wireType Wire type received
30974 * @returns {Reader} `this`
30976 Reader
.prototype.skipType = function(wireType
) {
30977 switch (wireType
) {
30985 this.skip(this.uint32());
30988 do { // eslint-disable-line no-constant-condition
30989 if ((wireType
= this.uint32() & 7) === 4)
30991 this.skipType(wireType
);
30998 /* istanbul ignore next */
31000 throw Error("invalid wire type " + wireType
+ " at offset " + this.pos
);
31005 Reader
._configure = function(BufferReader_
) {
31006 BufferReader
= BufferReader_
;
31008 var fn
= util
.Long
? "toLong" : /* istanbul ignore next */ "toNumber";
31009 util
.merge(Reader
.prototype, {
31011 int64: function read_int64() {
31012 return readLongVarint
.call(this)[fn
](false);
31015 uint64: function read_uint64() {
31016 return readLongVarint
.call(this)[fn
](true);
31019 sint64: function read_sint64() {
31020 return readLongVarint
.call(this).zzDecode()[fn
](false);
31023 fixed64: function read_fixed64() {
31024 return readFixed64
.call(this)[fn
](true);
31027 sfixed64: function read_sfixed64() {
31028 return readFixed64
.call(this)[fn
](false);
31034 },{"./util/minimal":220}],209:[function(require
,module
,exports
){
31036 module
.exports
= BufferReader
;
31039 var Reader
= require("./reader");
31040 (BufferReader
.prototype = Object
.create(Reader
.prototype)).constructor = BufferReader
;
31042 var util
= require("./util/minimal");
31045 * Constructs a new buffer reader instance.
31046 * @classdesc Wire format reader using node buffers.
31049 * @param {Buffer} buffer Buffer to read from
31051 function BufferReader(buffer
) {
31052 Reader
.call(this, buffer
);
31056 * @name BufferReader#buf
31061 /* istanbul ignore else */
31063 BufferReader
.prototype._slice
= util
.Buffer
.prototype.slice
;
31068 BufferReader
.prototype.string
= function read_string_buffer() {
31069 var len
= this.uint32(); // modifies pos
31070 return this.buf
.utf8Slice(this.pos
, this.pos
= Math
.min(this.pos
+ len
, this.len
));
31074 * Reads a sequence of bytes preceeded by its length as a varint.
31075 * @name BufferReader#bytes
31077 * @returns {Buffer} Value read
31080 },{"./reader":208,"./util/minimal":220}],210:[function(require
,module
,exports
){
31082 module
.exports
= Root
;
31084 // extends Namespace
31085 var Namespace
= require("./namespace");
31086 ((Root
.prototype = Object
.create(Namespace
.prototype)).constructor = Root
).className
= "Root";
31088 var Field
= require("./field"),
31089 Enum
= require("./enum"),
31090 OneOf
= require("./oneof"),
31091 util
= require("./util");
31093 var Type
, // cyclic
31094 parse
, // might be excluded
31098 * Constructs a new root namespace instance.
31099 * @classdesc Root namespace wrapping all types, enums, services, sub-namespaces etc. that belong together.
31100 * @extends NamespaceBase
31102 * @param {Object.<string,*>} [options] Top level options
31104 function Root(options
) {
31105 Namespace
.call(this, "", options
);
31108 * Deferred extension fields.
31111 this.deferred
= [];
31114 * Resolved file names of loaded files.
31121 * Loads a namespace descriptor into a root namespace.
31122 * @param {INamespace} json Nameespace descriptor
31123 * @param {Root} [root] Root namespace, defaults to create a new one if omitted
31124 * @returns {Root} Root namespace
31126 Root
.fromJSON
= function fromJSON(json
, root
) {
31130 root
.setOptions(json
.options
);
31131 return root
.addJSON(json
.nested
);
31135 * Resolves the path of an imported file, relative to the importing origin.
31136 * This method exists so you can override it with your own logic in case your imports are scattered over multiple directories.
31138 * @param {string} origin The file name of the importing file
31139 * @param {string} target The file name being imported
31140 * @returns {string|null} Resolved path to `target` or `null` to skip the file
31142 Root
.prototype.resolvePath
= util
.path
.resolve
;
31144 // A symbol-like function to safely signal synchronous loading
31145 /* istanbul ignore next */
31146 function SYNC() {} // eslint-disable-line no-empty-function
31149 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
31150 * @param {string|string[]} filename Names of one or multiple files to load
31151 * @param {IParseOptions} options Parse options
31152 * @param {LoadCallback} callback Callback function
31153 * @returns {undefined}
31155 Root
.prototype.load
= function load(filename
, options
, callback
) {
31156 if (typeof options
=== "function") {
31157 callback
= options
;
31158 options
= undefined;
31162 return util
.asPromise(load
, self
, filename
, options
);
31164 var sync
= callback
=== SYNC
; // undocumented
31166 // Finishes loading by calling the callback (exactly once)
31167 function finish(err
, root
) {
31168 /* istanbul ignore if */
31178 // Processes a single file
31179 function process(filename
, source
) {
31181 if (util
.isString(source
) && source
.charAt(0) === "{")
31182 source
= JSON
.parse(source
);
31183 if (!util
.isString(source
))
31184 self
.setOptions(source
.options
).addJSON(source
.nested
);
31186 parse
.filename
= filename
;
31187 var parsed
= parse(source
, self
, options
),
31190 if (parsed
.imports
)
31191 for (; i
< parsed
.imports
.length
; ++i
)
31192 if (resolved
= self
.resolvePath(filename
, parsed
.imports
[i
]))
31194 if (parsed
.weakImports
)
31195 for (i
= 0; i
< parsed
.weakImports
.length
; ++i
)
31196 if (resolved
= self
.resolvePath(filename
, parsed
.weakImports
[i
]))
31197 fetch(resolved
, true);
31202 if (!sync
&& !queued
)
31203 finish(null, self
); // only once anyway
31206 // Fetches a single file
31207 function fetch(filename
, weak
) {
31209 // Strip path if this file references a bundled definition
31210 var idx
= filename
.lastIndexOf("google/protobuf/");
31212 var altname
= filename
.substring(idx
);
31213 if (altname
in common
)
31214 filename
= altname
;
31217 // Skip if already loaded / attempted
31218 if (self
.files
.indexOf(filename
) > -1)
31220 self
.files
.push(filename
);
31222 // Shortcut bundled definitions
31223 if (filename
in common
) {
31225 process(filename
, common
[filename
]);
31228 setTimeout(function() {
31230 process(filename
, common
[filename
]);
31236 // Otherwise fetch from disk or network
31240 source
= util
.fs
.readFileSync(filename
).toString("utf8");
31246 process(filename
, source
);
31249 util
.fetch(filename
, function(err
, source
) {
31251 /* istanbul ignore if */
31253 return; // terminated meanwhile
31255 /* istanbul ignore else */
31258 else if (!queued
) // can't be covered reliably
31259 finish(null, self
);
31262 process(filename
, source
);
31268 // Assembling the root namespace doesn't require working type
31269 // references anymore, so we can load everything in parallel
31270 if (util
.isString(filename
))
31271 filename
= [ filename
];
31272 for (var i
= 0, resolved
; i
< filename
.length
; ++i
)
31273 if (resolved
= self
.resolvePath("", filename
[i
]))
31279 finish(null, self
);
31282 // function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined
31285 * Loads one or multiple .proto or preprocessed .json files into this root namespace and calls the callback.
31286 * @function Root#load
31287 * @param {string|string[]} filename Names of one or multiple files to load
31288 * @param {LoadCallback} callback Callback function
31289 * @returns {undefined}
31292 // function load(filename:string, callback:LoadCallback):undefined
31295 * Loads one or multiple .proto or preprocessed .json files into this root namespace and returns a promise.
31296 * @function Root#load
31297 * @param {string|string[]} filename Names of one or multiple files to load
31298 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
31299 * @returns {Promise<Root>} Promise
31302 // function load(filename:string, [options:IParseOptions]):Promise<Root>
31305 * Synchronously loads one or multiple .proto or preprocessed .json files into this root namespace (node only).
31306 * @function Root#loadSync
31307 * @param {string|string[]} filename Names of one or multiple files to load
31308 * @param {IParseOptions} [options] Parse options. Defaults to {@link parse.defaults} when omitted.
31309 * @returns {Root} Root namespace
31310 * @throws {Error} If synchronous fetching is not supported (i.e. in browsers) or if a file's syntax is invalid
31312 Root
.prototype.loadSync
= function loadSync(filename
, options
) {
31314 throw Error("not supported");
31315 return this.load(filename
, options
, SYNC
);
31321 Root
.prototype.resolveAll
= function resolveAll() {
31322 if (this.deferred
.length
)
31323 throw Error("unresolvable extensions: " + this.deferred
.map(function(field
) {
31324 return "'extend " + field
.extend
+ "' in " + field
.parent
.fullName
;
31326 return Namespace
.prototype.resolveAll
.call(this);
31329 // only uppercased (and thus conflict-free) children are exposed, see below
31330 var exposeRe
= /^[A-Z]/;
31333 * Handles a deferred declaring extension field by creating a sister field to represent it within its extended type.
31334 * @param {Root} root Root instance
31335 * @param {Field} field Declaring extension field witin the declaring type
31336 * @returns {boolean} `true` if successfully added to the extended type, `false` otherwise
31340 function tryHandleExtension(root
, field
) {
31341 var extendedType
= field
.parent
.lookup(field
.extend
);
31342 if (extendedType
) {
31343 var sisterField
= new Field(field
.fullName
, field
.id
, field
.type
, field
.rule
, undefined, field
.options
);
31344 sisterField
.declaringField
= field
;
31345 field
.extensionField
= sisterField
;
31346 extendedType
.add(sisterField
);
31353 * Called when any object is added to this root or its sub-namespaces.
31354 * @param {ReflectionObject} object Object added
31355 * @returns {undefined}
31358 Root
.prototype._handleAdd
= function _handleAdd(object
) {
31359 if (object
instanceof Field
) {
31361 if (/* an extension field (implies not part of a oneof) */ object
.extend
!== undefined && /* not already handled */ !object
.extensionField
)
31362 if (!tryHandleExtension(this, object
))
31363 this.deferred
.push(object
);
31365 } else if (object
instanceof Enum
) {
31367 if (exposeRe
.test(object
.name
))
31368 object
.parent
[object
.name
] = object
.values
; // expose enum values as property of its parent
31370 } else if (!(object
instanceof OneOf
)) /* everything else is a namespace */ {
31372 if (object
instanceof Type
) // Try to handle any deferred extensions
31373 for (var i
= 0; i
< this.deferred
.length
;)
31374 if (tryHandleExtension(this, this.deferred
[i
]))
31375 this.deferred
.splice(i
, 1);
31378 for (var j
= 0; j
< /* initializes */ object
.nestedArray
.length
; ++j
) // recurse into the namespace
31379 this._handleAdd(object
._nestedArray
[j
]);
31380 if (exposeRe
.test(object
.name
))
31381 object
.parent
[object
.name
] = object
; // expose namespace as property of its parent
31384 // The above also adds uppercased (and thus conflict-free) nested types, services and enums as
31385 // properties of namespaces just like static code does. This allows using a .d.ts generated for
31386 // a static module with reflection-based solutions where the condition is met.
31390 * Called when any object is removed from this root or its sub-namespaces.
31391 * @param {ReflectionObject} object Object removed
31392 * @returns {undefined}
31395 Root
.prototype._handleRemove
= function _handleRemove(object
) {
31396 if (object
instanceof Field
) {
31398 if (/* an extension field */ object
.extend
!== undefined) {
31399 if (/* already handled */ object
.extensionField
) { // remove its sister field
31400 object
.extensionField
.parent
.remove(object
.extensionField
);
31401 object
.extensionField
= null;
31402 } else { // cancel the extension
31403 var index
= this.deferred
.indexOf(object
);
31404 /* istanbul ignore else */
31406 this.deferred
.splice(index
, 1);
31410 } else if (object
instanceof Enum
) {
31412 if (exposeRe
.test(object
.name
))
31413 delete object
.parent
[object
.name
]; // unexpose enum values
31415 } else if (object
instanceof Namespace
) {
31417 for (var i
= 0; i
< /* initializes */ object
.nestedArray
.length
; ++i
) // recurse into the namespace
31418 this._handleRemove(object
._nestedArray
[i
]);
31420 if (exposeRe
.test(object
.name
))
31421 delete object
.parent
[object
.name
]; // unexpose namespaces
31426 Root
._configure = function(Type_
, parse_
, common_
) {
31432 },{"./enum":196,"./field":197,"./namespace":204,"./oneof":206,"./util":218}],211:[function(require
,module
,exports
){
31434 module
.exports
= {};
31438 * This is where pbjs stores generated structures (the option `-r, --root` specifies a name).
31439 * Can also be used manually to make roots available accross modules.
31441 * @type {Object.<string,Root>}
31443 * // pbjs -r myroot -o compiled.js ...
31445 * // in another module:
31446 * require("./compiled.js");
31448 * // in any subsequent module:
31449 * var root = protobuf.roots["myroot"];
31452 },{}],212:[function(require
,module
,exports
){
31456 * Streaming RPC helpers.
31462 * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets.
31465 * @param {Method|rpc.ServiceMethod<Message<{}>,Message<{}>>} method Reflected or static method being called
31466 * @param {Uint8Array} requestData Request data
31467 * @param {RPCImplCallback} callback Callback function
31468 * @returns {undefined}
31470 * function rpcImpl(method, requestData, callback) {
31471 * if (protobuf.util.lcFirst(method.name) !== "myMethod") // compatible with static code
31472 * throw Error("no such method");
31473 * asynchronouslyObtainAResponse(requestData, function(err, responseData) {
31474 * callback(err, responseData);
31480 * Node-style callback as used by {@link RPCImpl}.
31481 * @typedef RPCImplCallback
31483 * @param {Error|null} error Error, if any, otherwise `null`
31484 * @param {Uint8Array|null} [response] Response data or `null` to signal end of stream, if there hasn't been an error
31485 * @returns {undefined}
31488 rpc
.Service
= require("./rpc/service");
31490 },{"./rpc/service":213}],213:[function(require
,module
,exports
){
31492 module
.exports
= Service
;
31494 var util
= require("../util/minimal");
31496 // Extends EventEmitter
31497 (Service
.prototype = Object
.create(util
.EventEmitter
.prototype)).constructor = Service
;
31500 * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}.
31502 * Differs from {@link RPCImplCallback} in that it is an actual callback of a service method which may not return `response = null`.
31503 * @typedef rpc.ServiceMethodCallback
31504 * @template TRes extends Message<TRes>
31506 * @param {Error|null} error Error, if any
31507 * @param {TRes} [response] Response message
31508 * @returns {undefined}
31512 * A service method part of a {@link rpc.Service} as created by {@link Service.create}.
31513 * @typedef rpc.ServiceMethod
31514 * @template TReq extends Message<TReq>
31515 * @template TRes extends Message<TRes>
31517 * @param {TReq|Properties<TReq>} request Request message or plain object
31518 * @param {rpc.ServiceMethodCallback<TRes>} [callback] Node-style callback called with the error, if any, and the response message
31519 * @returns {Promise<Message<TRes>>} Promise if `callback` has been omitted, otherwise `undefined`
31523 * Constructs a new RPC service instance.
31524 * @classdesc An RPC service as returned by {@link Service#create}.
31525 * @exports rpc.Service
31526 * @extends util.EventEmitter
31528 * @param {RPCImpl} rpcImpl RPC implementation
31529 * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
31530 * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
31532 function Service(rpcImpl
, requestDelimited
, responseDelimited
) {
31534 if (typeof rpcImpl
!== "function")
31535 throw TypeError("rpcImpl must be a function");
31537 util
.EventEmitter
.call(this);
31540 * RPC implementation. Becomes `null` once the service is ended.
31541 * @type {RPCImpl|null}
31543 this.rpcImpl
= rpcImpl
;
31546 * Whether requests are length-delimited.
31549 this.requestDelimited
= Boolean(requestDelimited
);
31552 * Whether responses are length-delimited.
31555 this.responseDelimited
= Boolean(responseDelimited
);
31559 * Calls a service method through {@link rpc.Service#rpcImpl|rpcImpl}.
31560 * @param {Method|rpc.ServiceMethod<TReq,TRes>} method Reflected or static method
31561 * @param {Constructor<TReq>} requestCtor Request constructor
31562 * @param {Constructor<TRes>} responseCtor Response constructor
31563 * @param {TReq|Properties<TReq>} request Request message or plain object
31564 * @param {rpc.ServiceMethodCallback<TRes>} callback Service callback
31565 * @returns {undefined}
31566 * @template TReq extends Message<TReq>
31567 * @template TRes extends Message<TRes>
31569 Service
.prototype.rpcCall
= function rpcCall(method
, requestCtor
, responseCtor
, request
, callback
) {
31572 throw TypeError("request must be specified");
31576 return util
.asPromise(rpcCall
, self
, method
, requestCtor
, responseCtor
, request
);
31578 if (!self
.rpcImpl
) {
31579 setTimeout(function() { callback(Error("already ended")); }, 0);
31584 return self
.rpcImpl(
31586 requestCtor
[self
.requestDelimited
? "encodeDelimited" : "encode"](request
).finish(),
31587 function rpcCallback(err
, response
) {
31590 self
.emit("error", err
, method
);
31591 return callback(err
);
31594 if (response
=== null) {
31595 self
.end(/* endedByRPC */ true);
31599 if (!(response
instanceof responseCtor
)) {
31601 response
= responseCtor
[self
.responseDelimited
? "decodeDelimited" : "decode"](response
);
31603 self
.emit("error", err
, method
);
31604 return callback(err
);
31608 self
.emit("data", response
, method
);
31609 return callback(null, response
);
31613 self
.emit("error", err
, method
);
31614 setTimeout(function() { callback(err
); }, 0);
31620 * Ends this service and emits the `end` event.
31621 * @param {boolean} [endedByRPC=false] Whether the service has been ended by the RPC implementation.
31622 * @returns {rpc.Service} `this`
31624 Service
.prototype.end
= function end(endedByRPC
) {
31625 if (this.rpcImpl
) {
31626 if (!endedByRPC
) // signal end to rpcImpl
31627 this.rpcImpl(null, null, null);
31628 this.rpcImpl
= null;
31629 this.emit("end").off();
31634 },{"../util/minimal":220}],214:[function(require
,module
,exports
){
31636 module
.exports
= Service
;
31638 // extends Namespace
31639 var Namespace
= require("./namespace");
31640 ((Service
.prototype = Object
.create(Namespace
.prototype)).constructor = Service
).className
= "Service";
31642 var Method
= require("./method"),
31643 util
= require("./util"),
31644 rpc
= require("./rpc");
31647 * Constructs a new service instance.
31648 * @classdesc Reflected service.
31649 * @extends NamespaceBase
31651 * @param {string} name Service name
31652 * @param {Object.<string,*>} [options] Service options
31653 * @throws {TypeError} If arguments are invalid
31655 function Service(name
, options
) {
31656 Namespace
.call(this, name
, options
);
31660 * @type {Object.<string,Method>}
31662 this.methods
= {}; // toJSON, marker
31665 * Cached methods as an array.
31666 * @type {Method[]|null}
31669 this._methodsArray
= null;
31673 * Service descriptor.
31674 * @interface IService
31675 * @extends INamespace
31676 * @property {Object.<string,IMethod>} methods Method descriptors
31680 * Constructs a service from a service descriptor.
31681 * @param {string} name Service name
31682 * @param {IService} json Service descriptor
31683 * @returns {Service} Created service
31684 * @throws {TypeError} If arguments are invalid
31686 Service
.fromJSON
= function fromJSON(name
, json
) {
31687 var service
= new Service(name
, json
.options
);
31688 /* istanbul ignore else */
31690 for (var names
= Object
.keys(json
.methods
), i
= 0; i
< names
.length
; ++i
)
31691 service
.add(Method
.fromJSON(names
[i
], json
.methods
[names
[i
]]));
31693 service
.addJSON(json
.nested
);
31694 service
.comment
= json
.comment
;
31699 * Converts this service to a service descriptor.
31700 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
31701 * @returns {IService} Service descriptor
31703 Service
.prototype.toJSON
= function toJSON(toJSONOptions
) {
31704 var inherited
= Namespace
.prototype.toJSON
.call(this, toJSONOptions
);
31705 var keepComments
= toJSONOptions
? Boolean(toJSONOptions
.keepComments
) : false;
31706 return util
.toObject([
31707 "options" , inherited
&& inherited
.options
|| undefined,
31708 "methods" , Namespace
.arrayToJSON(this.methodsArray
, toJSONOptions
) || /* istanbul ignore next */ {},
31709 "nested" , inherited
&& inherited
.nested
|| undefined,
31710 "comment" , keepComments
? this.comment : undefined
31715 * Methods of this service as an array for iteration.
31716 * @name Service#methodsArray
31720 Object
.defineProperty(Service
.prototype, "methodsArray", {
31722 return this._methodsArray
|| (this._methodsArray
= util
.toArray(this.methods
));
31726 function clearCache(service
) {
31727 service
._methodsArray
= null;
31734 Service
.prototype.get = function get(name
) {
31735 return this.methods
[name
]
31736 || Namespace
.prototype.get.call(this, name
);
31742 Service
.prototype.resolveAll
= function resolveAll() {
31743 var methods
= this.methodsArray
;
31744 for (var i
= 0; i
< methods
.length
; ++i
)
31745 methods
[i
].resolve();
31746 return Namespace
.prototype.resolve
.call(this);
31752 Service
.prototype.add
= function add(object
) {
31754 /* istanbul ignore if */
31755 if (this.get(object
.name
))
31756 throw Error("duplicate name '" + object
.name
+ "' in " + this);
31758 if (object
instanceof Method
) {
31759 this.methods
[object
.name
] = object
;
31760 object
.parent
= this;
31761 return clearCache(this);
31763 return Namespace
.prototype.add
.call(this, object
);
31769 Service
.prototype.remove
= function remove(object
) {
31770 if (object
instanceof Method
) {
31772 /* istanbul ignore if */
31773 if (this.methods
[object
.name
] !== object
)
31774 throw Error(object
+ " is not a member of " + this);
31776 delete this.methods
[object
.name
];
31777 object
.parent
= null;
31778 return clearCache(this);
31780 return Namespace
.prototype.remove
.call(this, object
);
31784 * Creates a runtime service using the specified rpc implementation.
31785 * @param {RPCImpl} rpcImpl RPC implementation
31786 * @param {boolean} [requestDelimited=false] Whether requests are length-delimited
31787 * @param {boolean} [responseDelimited=false] Whether responses are length-delimited
31788 * @returns {rpc.Service} RPC service. Useful where requests and/or responses are streamed.
31790 Service
.prototype.create
= function create(rpcImpl
, requestDelimited
, responseDelimited
) {
31791 var rpcService
= new rpc
.Service(rpcImpl
, requestDelimited
, responseDelimited
);
31792 for (var i
= 0, method
; i
< /* initializes */ this.methodsArray
.length
; ++i
) {
31793 var methodName
= util
.lcFirst((method
= this._methodsArray
[i
]).resolve().name
).replace(/[^$\w_]/g, "");
31794 rpcService
[methodName
] = util
.codegen(["r","c"], util
.isReserved(methodName
) ? methodName
+ "_" : methodName
)("return this.rpcCall(m,q,s,r,c)")({
31796 q: method
.resolvedRequestType
.ctor
,
31797 s: method
.resolvedResponseType
.ctor
31803 },{"./method":203,"./namespace":204,"./rpc":212,"./util":218}],215:[function(require
,module
,exports
){
31805 module
.exports
= tokenize
;
31807 var delimRe
= /[\s{}=;:[\],'"()<>]/g,
31808 stringDoubleRe
= /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g,
31809 stringSingleRe
= /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g;
31811 var setCommentRe
= /^ *[*/
]+ */
,
31812 setCommentAltRe
= /^\s*\*?\/*/,
31813 setCommentSplitRe
= /\n/g,
31814 whitespaceRe
= /\s/,
31815 unescapeRe
= /\\(.?)/g;
31817 var unescapeMap
= {
31825 * Unescapes a string.
31826 * @param {string} str String to unescape
31827 * @returns {string} Unescaped string
31828 * @property {Object.<string,string>} map Special characters map
31829 * @memberof tokenize
31831 function unescape(str
) {
31832 return str
.replace(unescapeRe
, function($0, $1) {
31838 return unescapeMap
[$1] || "";
31843 tokenize
.unescape
= unescape
;
31846 * Gets the next token and advances.
31847 * @typedef TokenizerHandleNext
31849 * @returns {string|null} Next token or `null` on eof
31853 * Peeks for the next token.
31854 * @typedef TokenizerHandlePeek
31856 * @returns {string|null} Next token or `null` on eof
31860 * Pushes a token back to the stack.
31861 * @typedef TokenizerHandlePush
31863 * @param {string} token Token
31864 * @returns {undefined}
31868 * Skips the next token.
31869 * @typedef TokenizerHandleSkip
31871 * @param {string} expected Expected token
31872 * @param {boolean} [optional=false] If optional
31873 * @returns {boolean} Whether the token matched
31874 * @throws {Error} If the token didn't match and is not optional
31878 * Gets the comment on the previous line or, alternatively, the line comment on the specified line.
31879 * @typedef TokenizerHandleCmnt
31881 * @param {number} [line] Line number
31882 * @returns {string|null} Comment text or `null` if none
31886 * Handle object returned from {@link tokenize}.
31887 * @interface ITokenizerHandle
31888 * @property {TokenizerHandleNext} next Gets the next token and advances (`null` on eof)
31889 * @property {TokenizerHandlePeek} peek Peeks for the next token (`null` on eof)
31890 * @property {TokenizerHandlePush} push Pushes a token back to the stack
31891 * @property {TokenizerHandleSkip} skip Skips a token, returns its presence and advances or, if non-optional and not present, throws
31892 * @property {TokenizerHandleCmnt} cmnt Gets the comment on the previous line or the line comment on the specified line, if any
31893 * @property {number} line Current line number
31897 * Tokenizes the given .proto source and returns an object with useful utility functions.
31898 * @param {string} source Source contents
31899 * @param {boolean} alternateCommentMode Whether we should activate alternate comment parsing mode.
31900 * @returns {ITokenizerHandle} Tokenizer handle
31902 function tokenize(source
, alternateCommentMode
) {
31903 /* eslint-disable callback-return */
31904 source
= source
.toString();
31907 length
= source
.length
,
31909 commentType
= null,
31910 commentText
= null,
31912 commentLineEmpty
= false;
31916 var stringDelim
= null;
31918 /* istanbul ignore next */
31920 * Creates an error for illegal syntax.
31921 * @param {string} subject Subject
31922 * @returns {Error} Error created
31925 function illegal(subject
) {
31926 return Error("illegal " + subject
+ " (line " + line
+ ")");
31930 * Reads a string till its end.
31931 * @returns {string} String read
31934 function readString() {
31935 var re
= stringDelim
=== "'" ? stringSingleRe : stringDoubleRe
;
31936 re
.lastIndex
= offset
- 1;
31937 var match
= re
.exec(source
);
31939 throw illegal("string");
31940 offset
= re
.lastIndex
;
31942 stringDelim
= null;
31943 return unescape(match
[1]);
31947 * Gets the character at `pos` within the source.
31948 * @param {number} pos Position
31949 * @returns {string} Character
31952 function charAt(pos
) {
31953 return source
.charAt(pos
);
31957 * Sets the current comment text.
31958 * @param {number} start Start offset
31959 * @param {number} end End offset
31960 * @returns {undefined}
31963 function setComment(start
, end
) {
31964 commentType
= source
.charAt(start
++);
31965 commentLine
= line
;
31966 commentLineEmpty
= false;
31968 if (alternateCommentMode
) {
31969 lookback
= 2; // alternate comment parsing: "//" or "/*"
31971 lookback
= 3; // "///" or "/**"
31973 var commentOffset
= start
- lookback
,
31976 if (--commentOffset
< 0 ||
31977 (c
= source
.charAt(commentOffset
)) === "\n") {
31978 commentLineEmpty
= true;
31981 } while (c
=== " " || c
=== "\t");
31983 .substring(start
, end
)
31984 .split(setCommentSplitRe
);
31985 for (var i
= 0; i
< lines
.length
; ++i
)
31986 lines
[i
] = lines
[i
]
31987 .replace(alternateCommentMode
? setCommentAltRe : setCommentRe
, "")
31989 commentText
= lines
31994 function isDoubleSlashCommentLine(startOffset
) {
31995 var endOffset
= findEndOfLine(startOffset
);
31997 // see if remaining line matches comment pattern
31998 var lineText
= source
.substring(startOffset
, endOffset
);
31999 // look for 1 or 2 slashes since startOffset would already point past
32000 // the first slash that started the comment.
32001 var isComment
= /^\s*\/{1,2}/.test(lineText
);
32005 function findEndOfLine(cursor
) {
32006 // find end of cursor's line
32007 var endOffset
= cursor
;
32008 while (endOffset
< length
&& charAt(endOffset
) !== "\n") {
32015 * Obtains the next token.
32016 * @returns {string|null} Next token or `null` on eof
32020 if (stack
.length
> 0)
32021 return stack
.shift();
32023 return readString();
32030 if (offset
=== length
)
32033 while (whitespaceRe
.test(curr
= charAt(offset
))) {
32036 if (++offset
=== length
)
32040 if (charAt(offset
) === "/") {
32041 if (++offset
=== length
) {
32042 throw illegal("comment");
32044 if (charAt(offset
) === "/") { // Line
32045 if (!alternateCommentMode
) {
32046 // check for triple-slash comment
32047 isDoc
= charAt(start
= offset
+ 1) === "/";
32049 while (charAt(++offset
) !== "\n") {
32050 if (offset
=== length
) {
32056 setComment(start
, offset
- 1);
32061 // check for double-slash comments, consolidating consecutive lines
32064 if (isDoubleSlashCommentLine(offset
)) {
32067 offset
= findEndOfLine(offset
);
32068 if (offset
=== length
) {
32072 } while (isDoubleSlashCommentLine(offset
));
32074 offset
= Math
.min(length
, findEndOfLine(offset
) + 1);
32077 setComment(start
, offset
);
32082 } else if ((curr
= charAt(offset
)) === "*") { /* Block */
32083 // check for /** (regular comment mode) or /* (alternate comment mode)
32084 start
= offset
+ 1;
32085 isDoc
= alternateCommentMode
|| charAt(start
) === "*";
32087 if (curr
=== "\n") {
32090 if (++offset
=== length
) {
32091 throw illegal("comment");
32094 curr
= charAt(offset
);
32095 } while (prev
!== "*" || curr
!== "/");
32098 setComment(start
, offset
- 2);
32107 // offset !== length if we got here
32110 delimRe
.lastIndex
= 0;
32111 var delim
= delimRe
.test(charAt(end
++));
32113 while (end
< length
&& !delimRe
.test(charAt(end
)))
32115 var token
= source
.substring(offset
, offset
= end
);
32116 if (token
=== "\"" || token
=== "'")
32117 stringDelim
= token
;
32122 * Pushes a token back to the stack.
32123 * @param {string} token Token
32124 * @returns {undefined}
32127 function push(token
) {
32132 * Peeks for the next token.
32133 * @returns {string|null} Token or `null` on eof
32137 if (!stack
.length
) {
32138 var token
= next();
32139 if (token
=== null)
32148 * @param {string} expected Expected token
32149 * @param {boolean} [optional=false] Whether the token is optional
32150 * @returns {boolean} `true` when skipped, `false` if not
32151 * @throws {Error} When a required token is not present
32154 function skip(expected
, optional
) {
32155 var actual
= peek(),
32156 equals
= actual
=== expected
;
32162 throw illegal("token '" + actual
+ "', '" + expected
+ "' expected");
32168 * @param {number} [trailingLine] Line number if looking for a trailing comment
32169 * @returns {string|null} Comment text
32172 function cmnt(trailingLine
) {
32174 if (trailingLine
=== undefined) {
32175 if (commentLine
=== line
- 1 && (alternateCommentMode
|| commentType
=== "*" || commentLineEmpty
)) {
32179 /* istanbul ignore else */
32180 if (commentLine
< trailingLine
) {
32183 if (commentLine
=== trailingLine
&& !commentLineEmpty
&& (alternateCommentMode
|| commentType
=== "/")) {
32190 return Object
.defineProperty({
32197 get: function() { return line
; }
32199 /* eslint-enable callback-return */
32202 },{}],216:[function(require
,module
,exports
){
32204 module
.exports
= Type
;
32206 // extends Namespace
32207 var Namespace
= require("./namespace");
32208 ((Type
.prototype = Object
.create(Namespace
.prototype)).constructor = Type
).className
= "Type";
32210 var Enum
= require("./enum"),
32211 OneOf
= require("./oneof"),
32212 Field
= require("./field"),
32213 MapField
= require("./mapfield"),
32214 Service
= require("./service"),
32215 Message
= require("./message"),
32216 Reader
= require("./reader"),
32217 Writer
= require("./writer"),
32218 util
= require("./util"),
32219 encoder
= require("./encoder"),
32220 decoder
= require("./decoder"),
32221 verifier
= require("./verifier"),
32222 converter
= require("./converter"),
32223 wrappers
= require("./wrappers");
32226 * Constructs a new reflected message type instance.
32227 * @classdesc Reflected message type.
32228 * @extends NamespaceBase
32230 * @param {string} name Message name
32231 * @param {Object.<string,*>} [options] Declared options
32233 function Type(name
, options
) {
32234 Namespace
.call(this, name
, options
);
32238 * @type {Object.<string,Field>}
32240 this.fields
= {}; // toJSON, marker
32243 * Oneofs declared within this namespace, if any.
32244 * @type {Object.<string,OneOf>}
32246 this.oneofs
= undefined; // toJSON
32249 * Extension ranges, if any.
32250 * @type {number[][]}
32252 this.extensions
= undefined; // toJSON
32255 * Reserved ranges, if any.
32256 * @type {Array.<number[]|string>}
32258 this.reserved
= undefined; // toJSON
32261 * Whether this type is a legacy group.
32262 * @type {boolean|undefined}
32264 this.group
= undefined; // toJSON
32267 * Cached fields by id.
32268 * @type {Object.<number,Field>|null}
32271 this._fieldsById
= null;
32274 * Cached fields as an array.
32275 * @type {Field[]|null}
32278 this._fieldsArray
= null;
32281 * Cached oneofs as an array.
32282 * @type {OneOf[]|null}
32285 this._oneofsArray
= null;
32288 * Cached constructor.
32289 * @type {Constructor<{}>}
32295 Object
.defineProperties(Type
.prototype, {
32298 * Message fields by id.
32299 * @name Type#fieldsById
32300 * @type {Object.<number,Field>}
32306 /* istanbul ignore if */
32307 if (this._fieldsById
)
32308 return this._fieldsById
;
32310 this._fieldsById
= {};
32311 for (var names
= Object
.keys(this.fields
), i
= 0; i
< names
.length
; ++i
) {
32312 var field
= this.fields
[names
[i
]],
32315 /* istanbul ignore if */
32316 if (this._fieldsById
[id
])
32317 throw Error("duplicate id " + id
+ " in " + this);
32319 this._fieldsById
[id
] = field
;
32321 return this._fieldsById
;
32326 * Fields of this message as an array for iteration.
32327 * @name Type#fieldsArray
32333 return this._fieldsArray
|| (this._fieldsArray
= util
.toArray(this.fields
));
32338 * Oneofs of this message as an array for iteration.
32339 * @name Type#oneofsArray
32345 return this._oneofsArray
|| (this._oneofsArray
= util
.toArray(this.oneofs
));
32350 * The registered constructor, if any registered, otherwise a generic constructor.
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.
32353 * @type {Constructor<{}>}
32357 return this._ctor
|| (this.ctor
= Type
.generateConstructor(this)());
32359 set: function(ctor
) {
32361 // Ensure proper prototype
32362 var prototype = ctor
.prototype;
32363 if (!(prototype instanceof Message
)) {
32364 (ctor
.prototype = new Message()).constructor = ctor
;
32365 util
.merge(ctor
.prototype, prototype);
32368 // Classes and messages reference their reflected type
32369 ctor
.$type
= ctor
.prototype.$type
= this;
32371 // Mix in static methods
32372 util
.merge(ctor
, Message
, true);
32376 // Messages have non-enumerable default values on their prototype
32378 for (; i
< /* initializes */ this.fieldsArray
.length
; ++i
)
32379 this._fieldsArray
[i
].resolve(); // ensures a proper value
32381 // Messages have non-enumerable getters and setters for each virtual oneof field
32382 var ctorProperties
= {};
32383 for (i
= 0; i
< /* initializes */ this.oneofsArray
.length
; ++i
)
32384 ctorProperties
[this._oneofsArray
[i
].resolve().name
] = {
32385 get: util
.oneOfGetter(this._oneofsArray
[i
].oneof
),
32386 set: util
.oneOfSetter(this._oneofsArray
[i
].oneof
)
32389 Object
.defineProperties(ctor
.prototype, ctorProperties
);
32395 * Generates a constructor function for the specified type.
32396 * @param {Type} mtype Message type
32397 * @returns {Codegen} Codegen instance
32399 Type
.generateConstructor
= function generateConstructor(mtype
) {
32400 /* eslint-disable no-unexpected-multiline */
32401 var gen
= util
.codegen(["p"], mtype
.name
);
32402 // explicitly initialize mutable object/array fields so that these aren't just inherited from the prototype
32403 for (var i
= 0, field
; i
< mtype
.fieldsArray
.length
; ++i
)
32404 if ((field
= mtype
._fieldsArray
[i
]).map
) gen
32405 ("this%s={}", util
.safeProp(field
.name
));
32406 else if (field
.repeated
) gen
32407 ("this%s=[]", util
.safeProp(field
.name
));
32409 ("if(p)for(var ks=Object.keys(p),i=0;i<ks.length;++i)if(p[ks[i]]!=null)") // omit undefined or null
32410 ("this[ks[i]]=p[ks[i]]");
32411 /* eslint-enable no-unexpected-multiline */
32414 function clearCache(type
) {
32415 type
._fieldsById
= type
._fieldsArray
= type
._oneofsArray
= null;
32416 delete type
.encode
;
32417 delete type
.decode
;
32418 delete type
.verify
;
32423 * Message type descriptor.
32425 * @extends INamespace
32426 * @property {Object.<string,IOneOf>} [oneofs] Oneof descriptors
32427 * @property {Object.<string,IField>} fields Field descriptors
32428 * @property {number[][]} [extensions] Extension ranges
32429 * @property {number[][]} [reserved] Reserved ranges
32430 * @property {boolean} [group=false] Whether a legacy group or not
32434 * Creates a message type from a message type descriptor.
32435 * @param {string} name Message name
32436 * @param {IType} json Message type descriptor
32437 * @returns {Type} Created message type
32439 Type
.fromJSON
= function fromJSON(name
, json
) {
32440 var type
= new Type(name
, json
.options
);
32441 type
.extensions
= json
.extensions
;
32442 type
.reserved
= json
.reserved
;
32443 var names
= Object
.keys(json
.fields
),
32445 for (; i
< names
.length
; ++i
)
32447 ( typeof json
.fields
[names
[i
]].keyType
!== "undefined"
32448 ? MapField
.fromJSON
32449 : Field
.fromJSON
)(names
[i
], json
.fields
[names
[i
]])
32452 for (names
= Object
.keys(json
.oneofs
), i
= 0; i
< names
.length
; ++i
)
32453 type
.add(OneOf
.fromJSON(names
[i
], json
.oneofs
[names
[i
]]));
32455 for (names
= Object
.keys(json
.nested
), i
= 0; i
< names
.length
; ++i
) {
32456 var nested
= json
.nested
[names
[i
]];
32457 type
.add( // most to least likely
32458 ( nested
.id
!== undefined
32460 : nested
.fields
!== undefined
32462 : nested
.values
!== undefined
32464 : nested
.methods
!== undefined
32466 : Namespace
.fromJSON
)(names
[i
], nested
)
32469 if (json
.extensions
&& json
.extensions
.length
)
32470 type
.extensions
= json
.extensions
;
32471 if (json
.reserved
&& json
.reserved
.length
)
32472 type
.reserved
= json
.reserved
;
32476 type
.comment
= json
.comment
;
32481 * Converts this message type to a message type descriptor.
32482 * @param {IToJSONOptions} [toJSONOptions] JSON conversion options
32483 * @returns {IType} Message type descriptor
32485 Type
.prototype.toJSON
= function toJSON(toJSONOptions
) {
32486 var inherited
= Namespace
.prototype.toJSON
.call(this, toJSONOptions
);
32487 var keepComments
= toJSONOptions
? Boolean(toJSONOptions
.keepComments
) : false;
32488 return util
.toObject([
32489 "options" , inherited
&& inherited
.options
|| undefined,
32490 "oneofs" , Namespace
.arrayToJSON(this.oneofsArray
, toJSONOptions
),
32491 "fields" , Namespace
.arrayToJSON(this.fieldsArray
.filter(function(obj
) { return !obj
.declaringField
; }), toJSONOptions
) || {},
32492 "extensions" , this.extensions
&& this.extensions
.length
? this.extensions : undefined,
32493 "reserved" , this.reserved
&& this.reserved
.length
? this.reserved : undefined,
32494 "group" , this.group
|| undefined,
32495 "nested" , inherited
&& inherited
.nested
|| undefined,
32496 "comment" , keepComments
? this.comment : undefined
32503 Type
.prototype.resolveAll
= function resolveAll() {
32504 var fields
= this.fieldsArray
, i
= 0;
32505 while (i
< fields
.length
)
32506 fields
[i
++].resolve();
32507 var oneofs
= this.oneofsArray
; i
= 0;
32508 while (i
< oneofs
.length
)
32509 oneofs
[i
++].resolve();
32510 return Namespace
.prototype.resolveAll
.call(this);
32516 Type
.prototype.get = function get(name
) {
32517 return this.fields
[name
]
32518 || this.oneofs
&& this.oneofs
[name
]
32519 || this.nested
&& this.nested
[name
]
32524 * Adds a nested object to this type.
32525 * @param {ReflectionObject} object Nested object to add
32526 * @returns {Type} `this`
32527 * @throws {TypeError} If arguments are invalid
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
32530 Type
.prototype.add
= function add(object
) {
32532 if (this.get(object
.name
))
32533 throw Error("duplicate name '" + object
.name
+ "' in " + this);
32535 if (object
instanceof Field
&& object
.extend
=== undefined) {
32536 // NOTE: Extension fields aren't actual fields on the declaring type, but nested objects.
32537 // The root object takes care of adding distinct sister-fields to the respective extended
32540 // avoids calling the getter if not absolutely necessary because it's called quite frequently
32541 if (this._fieldsById
? /* istanbul ignore next */ this._fieldsById
[object
.id
] : this.fieldsById
[object
.id
])
32542 throw Error("duplicate id " + object
.id
+ " in " + this);
32543 if (this.isReservedId(object
.id
))
32544 throw Error("id " + object
.id
+ " is reserved in " + this);
32545 if (this.isReservedName(object
.name
))
32546 throw Error("name '" + object
.name
+ "' is reserved in " + this);
32549 object
.parent
.remove(object
);
32550 this.fields
[object
.name
] = object
;
32551 object
.message
= this;
32552 object
.onAdd(this);
32553 return clearCache(this);
32555 if (object
instanceof OneOf
) {
32558 this.oneofs
[object
.name
] = object
;
32559 object
.onAdd(this);
32560 return clearCache(this);
32562 return Namespace
.prototype.add
.call(this, object
);
32566 * Removes a nested object from this type.
32567 * @param {ReflectionObject} object Nested object to remove
32568 * @returns {Type} `this`
32569 * @throws {TypeError} If arguments are invalid
32570 * @throws {Error} If `object` is not a member of this type
32572 Type
.prototype.remove
= function remove(object
) {
32573 if (object
instanceof Field
&& object
.extend
=== undefined) {
32574 // See Type#add for the reason why extension fields are excluded here.
32576 /* istanbul ignore if */
32577 if (!this.fields
|| this.fields
[object
.name
] !== object
)
32578 throw Error(object
+ " is not a member of " + this);
32580 delete this.fields
[object
.name
];
32581 object
.parent
= null;
32582 object
.onRemove(this);
32583 return clearCache(this);
32585 if (object
instanceof OneOf
) {
32587 /* istanbul ignore if */
32588 if (!this.oneofs
|| this.oneofs
[object
.name
] !== object
)
32589 throw Error(object
+ " is not a member of " + this);
32591 delete this.oneofs
[object
.name
];
32592 object
.parent
= null;
32593 object
.onRemove(this);
32594 return clearCache(this);
32596 return Namespace
.prototype.remove
.call(this, object
);
32600 * Tests if the specified id is reserved.
32601 * @param {number} id Id to test
32602 * @returns {boolean} `true` if reserved, otherwise `false`
32604 Type
.prototype.isReservedId
= function isReservedId(id
) {
32605 return Namespace
.isReservedId(this.reserved
, id
);
32609 * Tests if the specified name is reserved.
32610 * @param {string} name Name to test
32611 * @returns {boolean} `true` if reserved, otherwise `false`
32613 Type
.prototype.isReservedName
= function isReservedName(name
) {
32614 return Namespace
.isReservedName(this.reserved
, name
);
32618 * Creates a new message of this type using the specified properties.
32619 * @param {Object.<string,*>} [properties] Properties to set
32620 * @returns {Message<{}>} Message instance
32622 Type
.prototype.create
= function create(properties
) {
32623 return new this.ctor(properties
);
32627 * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}.
32628 * @returns {Type} `this`
32630 Type
.prototype.setup
= function setup() {
32631 // Sets up everything at once so that the prototype chain does not have to be re-evaluated
32632 // multiple times (V8, soft-deopt prototype-check).
32634 var fullName
= this.fullName
,
32636 for (var i
= 0; i
< /* initializes */ this.fieldsArray
.length
; ++i
)
32637 types
.push(this._fieldsArray
[i
].resolve().resolvedType
);
32639 // Replace setup methods with type-specific generated functions
32640 this.encode
= encoder(this)({
32645 this.decode
= decoder(this)({
32650 this.verify
= verifier(this)({
32654 this.fromObject
= converter
.fromObject(this)({
32658 this.toObject
= converter
.toObject(this)({
32663 // Inject custom wrappers for common types
32664 var wrapper
= wrappers
[fullName
];
32666 var originalThis
= Object
.create(this);
32667 // if (wrapper.fromObject) {
32668 originalThis
.fromObject
= this.fromObject
;
32669 this.fromObject
= wrapper
.fromObject
.bind(originalThis
);
32671 // if (wrapper.toObject) {
32672 originalThis
.toObject
= this.toObject
;
32673 this.toObject
= wrapper
.toObject
.bind(originalThis
);
32681 * Encodes a message of this type. Does not implicitly {@link Type#verify|verify} messages.
32682 * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
32683 * @param {Writer} [writer] Writer to encode to
32684 * @returns {Writer} writer
32686 Type
.prototype.encode
= function encode_setup(message
, writer
) {
32687 return this.setup().encode(message
, writer
); // overrides this method
32691 * Encodes a message of this type preceeded by its byte length as a varint. Does not implicitly {@link Type#verify|verify} messages.
32692 * @param {Message<{}>|Object.<string,*>} message Message instance or plain object
32693 * @param {Writer} [writer] Writer to encode to
32694 * @returns {Writer} writer
32696 Type
.prototype.encodeDelimited
= function encodeDelimited(message
, writer
) {
32697 return this.encode(message
, writer
&& writer
.len
? writer
.fork() : writer
).ldelim();
32701 * Decodes a message of this type.
32702 * @param {Reader|Uint8Array} reader Reader or buffer to decode from
32703 * @param {number} [length] Length of the message, if known beforehand
32704 * @returns {Message<{}>} Decoded message
32705 * @throws {Error} If the payload is not a reader or valid buffer
32706 * @throws {util.ProtocolError<{}>} If required fields are missing
32708 Type
.prototype.decode
= function decode_setup(reader
, length
) {
32709 return this.setup().decode(reader
, length
); // overrides this method
32713 * Decodes a message of this type preceeded by its byte length as a varint.
32714 * @param {Reader|Uint8Array} reader Reader or buffer to decode from
32715 * @returns {Message<{}>} Decoded message
32716 * @throws {Error} If the payload is not a reader or valid buffer
32717 * @throws {util.ProtocolError} If required fields are missing
32719 Type
.prototype.decodeDelimited
= function decodeDelimited(reader
) {
32720 if (!(reader
instanceof Reader
))
32721 reader
= Reader
.create(reader
);
32722 return this.decode(reader
, reader
.uint32());
32726 * Verifies that field values are valid and that required fields are present.
32727 * @param {Object.<string,*>} message Plain object to verify
32728 * @returns {null|string} `null` if valid, otherwise the reason why it is not
32730 Type
.prototype.verify
= function verify_setup(message
) {
32731 return this.setup().verify(message
); // overrides this method
32735 * Creates a new message of this type from a plain object. Also converts values to their respective internal types.
32736 * @param {Object.<string,*>} object Plain object to convert
32737 * @returns {Message<{}>} Message instance
32739 Type
.prototype.fromObject
= function fromObject(object
) {
32740 return this.setup().fromObject(object
);
32744 * Conversion options as used by {@link Type#toObject} and {@link Message.toObject}.
32745 * @interface IConversionOptions
32746 * @property {Function} [longs] Long conversion type.
32747 * Valid values are `String` and `Number` (the global types).
32748 * Defaults to copy the present value, which is a possibly unsafe number without and a {@link Long} with a long library.
32749 * @property {Function} [enums] Enum value conversion type.
32750 * Only valid value is `String` (the global type).
32751 * Defaults to copy the present value, which is the numeric id.
32752 * @property {Function} [bytes] Bytes value conversion type.
32753 * Valid values are `Array` and (a base64 encoded) `String` (the global types).
32754 * Defaults to copy the present value, which usually is a Buffer under node and an Uint8Array in the browser.
32755 * @property {boolean} [defaults=false] Also sets default values on the resulting object
32756 * @property {boolean} [arrays=false] Sets empty arrays for missing repeated fields even if `defaults=false`
32757 * @property {boolean} [objects=false] Sets empty objects for missing map fields even if `defaults=false`
32758 * @property {boolean} [oneofs=false] Includes virtual oneof properties set to the present field's name, if any
32759 * @property {boolean} [json=false] Performs additional JSON compatibility conversions, i.e. NaN and Infinity to strings
32763 * Creates a plain object from a message of this type. Also converts values to other types if specified.
32764 * @param {Message<{}>} message Message instance
32765 * @param {IConversionOptions} [options] Conversion options
32766 * @returns {Object.<string,*>} Plain object
32768 Type
.prototype.toObject
= function toObject(message
, options
) {
32769 return this.setup().toObject(message
, options
);
32773 * Decorator function as returned by {@link Type.d} (TypeScript).
32774 * @typedef TypeDecorator
32776 * @param {Constructor<T>} target Target constructor
32777 * @returns {undefined}
32778 * @template T extends Message<T>
32782 * Type decorator (TypeScript).
32783 * @param {string} [typeName] Type name, defaults to the constructor's name
32784 * @returns {TypeDecorator<T>} Decorator function
32785 * @template T extends Message<T>
32787 Type
.d
= function decorateType(typeName
) {
32788 return function typeDecorator(target
) {
32789 util
.decorateType(target
, typeName
);
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
){
32797 * Common type constants.
32800 var types
= exports
;
32802 var util
= require("./util");
32822 function bake(values
, offset
) {
32825 while (i
< values
.length
) o
[s
[i
+ offset
]] = values
[i
++];
32830 * Basic type wire types.
32831 * @type {Object.<string,number>}
32833 * @property {number} double=1 Fixed64 wire type
32834 * @property {number} float=5 Fixed32 wire type
32835 * @property {number} int32=0 Varint wire type
32836 * @property {number} uint32=0 Varint wire type
32837 * @property {number} sint32=0 Varint wire type
32838 * @property {number} fixed32=5 Fixed32 wire type
32839 * @property {number} sfixed32=5 Fixed32 wire type
32840 * @property {number} int64=0 Varint wire type
32841 * @property {number} uint64=0 Varint wire type
32842 * @property {number} sint64=0 Varint wire type
32843 * @property {number} fixed64=1 Fixed64 wire type
32844 * @property {number} sfixed64=1 Fixed64 wire type
32845 * @property {number} bool=0 Varint wire type
32846 * @property {number} string=2 Ldelim wire type
32847 * @property {number} bytes=2 Ldelim wire type
32849 types
.basic
= bake([
32868 * Basic type defaults.
32869 * @type {Object.<string,*>}
32871 * @property {number} double=0 Double default
32872 * @property {number} float=0 Float default
32873 * @property {number} int32=0 Int32 default
32874 * @property {number} uint32=0 Uint32 default
32875 * @property {number} sint32=0 Sint32 default
32876 * @property {number} fixed32=0 Fixed32 default
32877 * @property {number} sfixed32=0 Sfixed32 default
32878 * @property {number} int64=0 Int64 default
32879 * @property {number} uint64=0 Uint64 default
32880 * @property {number} sint64=0 Sint32 default
32881 * @property {number} fixed64=0 Fixed64 default
32882 * @property {number} sfixed64=0 Sfixed64 default
32883 * @property {boolean} bool=false Bool default
32884 * @property {string} string="" String default
32885 * @property {Array.<number>} bytes=Array(0) Bytes default
32886 * @property {null} message=null Message default
32888 types
.defaults
= bake([
32903 /* bytes */ util
.emptyArray
,
32908 * Basic long type wire types.
32909 * @type {Object.<string,number>}
32911 * @property {number} int64=0 Varint wire type
32912 * @property {number} uint64=0 Varint wire type
32913 * @property {number} sint64=0 Varint wire type
32914 * @property {number} fixed64=1 Fixed64 wire type
32915 * @property {number} sfixed64=1 Fixed64 wire type
32917 types
.long = bake([
32926 * Allowed types for map keys with their associated wire type.
32927 * @type {Object.<string,number>}
32929 * @property {number} int32=0 Varint wire type
32930 * @property {number} uint32=0 Varint wire type
32931 * @property {number} sint32=0 Varint wire type
32932 * @property {number} fixed32=5 Fixed32 wire type
32933 * @property {number} sfixed32=5 Fixed32 wire type
32934 * @property {number} int64=0 Varint wire type
32935 * @property {number} uint64=0 Varint wire type
32936 * @property {number} sint64=0 Varint wire type
32937 * @property {number} fixed64=1 Fixed64 wire type
32938 * @property {number} sfixed64=1 Fixed64 wire type
32939 * @property {number} bool=0 Varint wire type
32940 * @property {number} string=2 Ldelim wire type
32942 types
.mapKey
= bake([
32958 * Allowed types for packed repeated fields with their associated wire type.
32959 * @type {Object.<string,number>}
32961 * @property {number} double=1 Fixed64 wire type
32962 * @property {number} float=5 Fixed32 wire type
32963 * @property {number} int32=0 Varint wire type
32964 * @property {number} uint32=0 Varint wire type
32965 * @property {number} sint32=0 Varint wire type
32966 * @property {number} fixed32=5 Fixed32 wire type
32967 * @property {number} sfixed32=5 Fixed32 wire type
32968 * @property {number} int64=0 Varint wire type
32969 * @property {number} uint64=0 Varint wire type
32970 * @property {number} sint64=0 Varint wire type
32971 * @property {number} fixed64=1 Fixed64 wire type
32972 * @property {number} sfixed64=1 Fixed64 wire type
32973 * @property {number} bool=0 Varint wire type
32975 types
.packed
= bake([
32991 },{"./util":218}],218:[function(require
,module
,exports
){
32995 * Various utility functions.
32998 var util
= module
.exports
= require("./util/minimal");
33000 var roots
= require("./roots");
33002 var Type
, // cyclic
33005 util
.codegen
= require("@protobufjs/codegen");
33006 util
.fetch
= require("@protobufjs/fetch");
33007 util
.path
= require("@protobufjs/path");
33010 * Node's fs module if available.
33011 * @type {Object.<string,*>}
33013 util
.fs
= util
.inquire("fs");
33016 * Converts an object's values to an array.
33017 * @param {Object.<string,*>} object Object to convert
33018 * @returns {Array.<*>} Converted array
33020 util
.toArray
= function toArray(object
) {
33022 var keys
= Object
.keys(object
),
33023 array
= new Array(keys
.length
),
33025 while (index
< keys
.length
)
33026 array
[index
] = object
[keys
[index
++]];
33033 * Converts an array of keys immediately followed by their respective value to an object, omitting undefined values.
33034 * @param {Array.<*>} array Array to convert
33035 * @returns {Object.<string,*>} Converted object
33037 util
.toObject
= function toObject(array
) {
33040 while (index
< array
.length
) {
33041 var key
= array
[index
++],
33042 val
= array
[index
++];
33043 if (val
!== undefined)
33049 var safePropBackslashRe
= /\\/g
,
33050 safePropQuoteRe
= /"/g;
33053 * Tests whether the specified name is a reserved word in JS.
33054 * @param {string} name Name to test
33055 * @returns {boolean} `true` if reserved, otherwise `false`
33057 util.isReserved = function isReserved(name) {
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);
33062 * Returns a safe property accessor for the specified property name.
33063 * @param {string} prop Property name
33064 * @returns {string} Safe accessor
33066 util.safeProp = function safeProp(prop) {
33067 if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop))
33068 return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]";
33073 * Converts the first character of a string to upper case.
33074 * @param {string} str String to convert
33075 * @returns {string} Converted string
33077 util.ucFirst = function ucFirst(str) {
33078 return str.charAt(0).toUpperCase() + str.substring(1);
33081 var camelCaseRe = /_([a-z])/g;
33084 * Converts a string to camel case.
33085 * @param {string} str String to convert
33086 * @returns {string} Converted string
33088 util.camelCase = function camelCase(str) {
33089 return str.substring(0, 1)
33091 .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); });
33095 * Compares reflected fields by id.
33096 * @param {Field} a First field
33097 * @param {Field} b Second field
33098 * @returns {number} Comparison value
33100 util.compareFieldsById = function compareFieldsById(a, b) {
33101 return a.id - b.id;
33105 * Decorator helper for types (TypeScript).
33106 * @param {Constructor<T>} ctor Constructor function
33107 * @param {string} [typeName] Type name, defaults to the constructor's name
33108 * @returns {Type} Reflected type
33109 * @template T extends Message<T>
33110 * @property {Root} root Decorators root
33112 util.decorateType = function decorateType(ctor, typeName) {
33114 /* istanbul ignore if */
33116 if (typeName && ctor.$type.name !== typeName) {
33117 util.decorateRoot.remove(ctor.$type);
33118 ctor.$type.name = typeName;
33119 util.decorateRoot.add(ctor.$type);
33124 /* istanbul ignore next */
33126 Type = require("./type
");
33128 var type = new Type(typeName || ctor.name);
33129 util.decorateRoot.add(type);
33130 type.ctor = ctor; // sets up .encode, .decode etc.
33131 Object.defineProperty(ctor, "$type
", { value: type, enumerable: false });
33132 Object.defineProperty(ctor.prototype, "$type
", { value: type, enumerable: false });
33136 var decorateEnumIndex = 0;
33139 * Decorator helper for enums (TypeScript).
33140 * @param {Object} object Enum object
33141 * @returns {Enum} Reflected enum
33143 util.decorateEnum = function decorateEnum(object) {
33145 /* istanbul ignore if */
33147 return object.$type;
33149 /* istanbul ignore next */
33151 Enum = require("./enum");
33153 var enm = new Enum("Enum
" + decorateEnumIndex++, object);
33154 util.decorateRoot.add(enm);
33155 Object.defineProperty(object, "$type
", { value: enm, enumerable: false });
33160 * Decorator root (TypeScript).
33161 * @name util.decorateRoot
33165 Object.defineProperty(util, "decorateRoot
", {
33167 return roots["decorated
"] || (roots["decorated
"] = new (require("./root
"))());
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){
33173 module.exports = LongBits;
33175 var util = require("../util/minimal");
33178 * Constructs new long bits.
33179 * @classdesc Helper class for working with the low and high bits of a 64 bit value.
33182 * @param {number} lo Low 32 bits, unsigned
33183 * @param {number} hi High 32 bits, unsigned
33185 function LongBits(lo, hi) {
33187 // note that the casts below are theoretically unnecessary as of today, but older statically
33188 // generated converter code might still call the ctor with signed 32bits. kept for compat.
33194 this.lo = lo >>> 0;
33200 this.hi = hi >>> 0;
33205 * @memberof util.LongBits
33206 * @type {util.LongBits}
33208 var zero = LongBits.zero = new LongBits(0, 0);
33210 zero.toNumber = function() { return 0; };
33211 zero.zzEncode = zero.zzDecode = function() { return this; };
33212 zero.length = function() { return 1; };
33216 * @memberof util.LongBits
33219 var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0";
33222 * Constructs new long bits from the specified number.
33223 * @param {number} value Value
33224 * @returns {util.LongBits} Instance
33226 LongBits.fromNumber = function fromNumber(value) {
33229 var sign = value < 0;
33232 var lo = value >>> 0,
33233 hi = (value - lo) / 4294967296 >>> 0;
33237 if (++lo > 4294967295) {
33239 if (++hi > 4294967295)
33243 return new LongBits(lo, hi);
33247 * Constructs new long bits from a number, long or string.
33248 * @param {Long|number|string} value Value
33249 * @returns {util.LongBits} Instance
33251 LongBits.from = function from(value) {
33252 if (typeof value === "number
")
33253 return LongBits.fromNumber(value);
33254 if (util.isString(value)) {
33255 /* istanbul ignore else */
33257 value = util.Long.fromString(value);
33259 return LongBits.fromNumber(parseInt(value, 10));
33261 return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero;
33265 * Converts this long bits to a possibly unsafe JavaScript number.
33266 * @param {boolean} [unsigned=false] Whether unsigned or not
33267 * @returns {number} Possibly unsafe number
33269 LongBits.prototype.toNumber = function toNumber(unsigned) {
33270 if (!unsigned && this.hi >>> 31) {
33271 var lo = ~this.lo + 1 >>> 0,
33272 hi = ~this.hi >>> 0;
33275 return -(lo + hi * 4294967296);
33277 return this.lo + this.hi * 4294967296;
33281 * Converts this long bits to a long.
33282 * @param {boolean} [unsigned=false] Whether unsigned or not
33283 * @returns {Long} Long
33285 LongBits.prototype.toLong = function toLong(unsigned) {
33287 ? new util.Long(this.lo | 0, this.hi | 0, Boolean(unsigned))
33288 /* istanbul ignore next */
33289 : { low: this.lo | 0, high: this.hi | 0, unsigned: Boolean(unsigned) };
33292 var charCodeAt = String.prototype.charCodeAt;
33295 * Constructs new long bits from the specified 8 characters long hash.
33296 * @param {string} hash Hash
33297 * @returns {util.LongBits} Bits
33299 LongBits.fromHash = function fromHash(hash) {
33300 if (hash === zeroHash)
33302 return new LongBits(
33303 ( charCodeAt.call(hash, 0)
33304 | charCodeAt.call(hash, 1) << 8
33305 | charCodeAt.call(hash, 2) << 16
33306 | charCodeAt.call(hash, 3) << 24) >>> 0
33308 ( charCodeAt.call(hash, 4)
33309 | charCodeAt.call(hash, 5) << 8
33310 | charCodeAt.call(hash, 6) << 16
33311 | charCodeAt.call(hash, 7) << 24) >>> 0
33316 * Converts this long bits to a 8 characters long hash.
33317 * @returns {string} Hash
33319 LongBits.prototype.toHash = function toHash() {
33320 return String.fromCharCode(
33322 this.lo >>> 8 & 255,
33323 this.lo >>> 16 & 255,
33326 this.hi >>> 8 & 255,
33327 this.hi >>> 16 & 255,
33333 * Zig-zag encodes this long bits.
33334 * @returns {util.LongBits} `this`
33336 LongBits.prototype.zzEncode = function zzEncode() {
33337 var mask = this.hi >> 31;
33338 this.hi = ((this.hi << 1 | this.lo >>> 31) ^ mask) >>> 0;
33339 this.lo = ( this.lo << 1 ^ mask) >>> 0;
33344 * Zig-zag decodes this long bits.
33345 * @returns {util.LongBits} `this`
33347 LongBits.prototype.zzDecode = function zzDecode() {
33348 var mask = -(this.lo & 1);
33349 this.lo = ((this.lo >>> 1 | this.hi << 31) ^ mask) >>> 0;
33350 this.hi = ( this.hi >>> 1 ^ mask) >>> 0;
33355 * Calculates the length of this longbits when encoded as a varint.
33356 * @returns {number} Length
33358 LongBits.prototype.length = function length() {
33359 var part0 = this.lo,
33360 part1 = (this.lo >>> 28 | this.hi << 4) >>> 0,
33361 part2 = this.hi >>> 24;
33365 ? part0 < 128 ? 1 : 2
33366 : part0 < 2097152 ? 3 : 4
33368 ? part1 < 128 ? 5 : 6
33369 : part1 < 2097152 ? 7 : 8
33370 : part2 < 128 ? 9 : 10;
33373 },{"../util/minimal":220}],220:[function(require,module,exports){
33374 (function (global){
33376 var util = exports;
33378 // used to return a Promise where callback is omitted
33379 util.asPromise = require("@protobufjs
/aspromise
");
33381 // converts to / from base64 encoded strings
33382 util.base64 = require("@protobufjs
/base64
");
33384 // base class of rpc.Service
33385 util.EventEmitter = require("@protobufjs
/eventemitter
");
33387 // float handling accross browsers
33388 util.float = require("@protobufjs
/float");
33390 // requires modules optionally and hides the call from bundlers
33391 util.inquire = require("@protobufjs
/inquire
");
33393 // converts to / from utf8 encoded strings
33394 util.utf8 = require("@protobufjs
/utf8
");
33396 // provides a node-like buffer pool in the browser
33397 util.pool = require("@protobufjs
/pool
");
33399 // utility to work with the low and high bits of a 64 bit value
33400 util.LongBits = require("./longbits
");
33403 * An immuable empty array.
33405 * @type {Array.<*>}
33408 util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes
33411 * An immutable empty object.
33415 util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes
33418 * Whether running within node or not.
33423 util.isNode = Boolean(global.process && global.process.versions && global.process.versions.node);
33426 * Tests if the specified value is an integer.
33428 * @param {*} value Value to test
33429 * @returns {boolean} `true` if the value is an integer
33431 util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) {
33432 return typeof value === "number
" && isFinite(value) && Math.floor(value) === value;
33436 * Tests if the specified value is a string.
33437 * @param {*} value Value to test
33438 * @returns {boolean} `true` if the value is a string
33440 util.isString = function isString(value) {
33441 return typeof value === "string
" || value instanceof String;
33445 * Tests if the specified value is a non-null object.
33446 * @param {*} value Value to test
33447 * @returns {boolean} `true` if the value is a non-null object
33449 util.isObject = function isObject(value) {
33450 return value && typeof value === "object
";
33454 * Checks if a property on a message is considered to be present.
33455 * This is an alias of {@link util.isSet}.
33457 * @param {Object} obj Plain object or message instance
33458 * @param {string} prop Property name
33459 * @returns {boolean} `true` if considered to be present, otherwise `false`
33464 * Checks if a property on a message is considered to be present.
33465 * @param {Object} obj Plain object or message instance
33466 * @param {string} prop Property name
33467 * @returns {boolean} `true` if considered to be present, otherwise `false`
33469 util.isSet = function isSet(obj, prop) {
33470 var value = obj[prop];
33471 if (value != null && obj.hasOwnProperty(prop)) // eslint-disable-line eqeqeq, no-prototype-builtins
33472 return typeof value !== "object
" || (Array.isArray(value) ? value.length : Object.keys(value).length) > 0;
33477 * Any compatible Buffer instance.
33478 * This is a minimal stand-alone definition of a Buffer instance. The actual type is that exported by node's typings.
33479 * @interface Buffer
33480 * @extends Uint8Array
33484 * Node's Buffer class if available.
33485 * @type {Constructor<Buffer>}
33487 util.Buffer = (function() {
33489 var Buffer = util.inquire("buffer
").Buffer;
33490 // refuse to use non-node buffers if not explicitly assigned (perf reasons):
33491 return Buffer.prototype.utf8Write ? Buffer : /* istanbul ignore next */ null;
33493 /* istanbul ignore next */
33498 // Internal alias of or polyfull for Buffer.from.
33499 util._Buffer_from = null;
33501 // Internal alias of or polyfill for Buffer.allocUnsafe.
33502 util._Buffer_allocUnsafe = null;
33505 * Creates a new buffer of whatever type supported by the environment.
33506 * @param {number|number[]} [sizeOrArray=0] Buffer size or number array
33507 * @returns {Uint8Array|Buffer} Buffer
33509 util.newBuffer = function newBuffer(sizeOrArray) {
33510 /* istanbul ignore next */
33511 return typeof sizeOrArray === "number
"
33513 ? util._Buffer_allocUnsafe(sizeOrArray)
33514 : new util.Array(sizeOrArray)
33516 ? util._Buffer_from(sizeOrArray)
33517 : typeof Uint8Array === "undefined"
33519 : new Uint8Array(sizeOrArray);
33523 * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`.
33524 * @type {Constructor<Uint8Array>}
33526 util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array;
33529 * Any compatible Long instance.
33530 * This is a minimal stand-alone definition of a Long instance. The actual type is that exported by long.js.
33532 * @property {number} low Low bits
33533 * @property {number} high High bits
33534 * @property {boolean} unsigned Whether unsigned or not
33538 * Long.js's Long class if available.
33539 * @type {Constructor<Long>}
33541 util.Long = /* istanbul ignore next */ global.dcodeIO && /* istanbul ignore next */ global.dcodeIO.Long || util.inquire("long");
33544 * Regular expression used to verify 2 bit (`bool`) map keys.
33548 util.key2Re = /^true|false|0|1$/;
33551 * Regular expression used to verify 32 bit (`int32` etc.) map keys.
33555 util.key32Re = /^-?(?:0|[1-9][0-9]*)$/;
33558 * Regular expression used to verify 64 bit (`int64` etc.) map keys.
33562 util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/;
33565 * Converts a number or long to an 8 characters long hash string.
33566 * @param {Long|number} value Value to convert
33567 * @returns {string} Hash
33569 util.longToHash = function longToHash(value) {
33571 ? util.LongBits.from(value).toHash()
33572 : util.LongBits.zeroHash;
33576 * Converts an 8 characters long hash string to a long or number.
33577 * @param {string} hash Hash
33578 * @param {boolean} [unsigned=false] Whether unsigned or not
33579 * @returns {Long|number} Original value
33581 util.longFromHash = function longFromHash(hash, unsigned) {
33582 var bits = util.LongBits.fromHash(hash);
33584 return util.Long.fromBits(bits.lo, bits.hi, unsigned);
33585 return bits.toNumber(Boolean(unsigned));
33589 * Merges the properties of the source object into the destination object.
33591 * @param {Object.<string,*>} dst Destination object
33592 * @param {Object.<string,*>} src Source object
33593 * @param {boolean} [ifNotSet=false] Merges only if the key is not already set
33594 * @returns {Object.<string,*>} Destination object
33596 function merge(dst, src, ifNotSet) { // used by converters
33597 for (var keys = Object.keys(src), i = 0; i < keys.length; ++i)
33598 if (dst[keys[i]] === undefined || !ifNotSet)
33599 dst[keys[i]] = src[keys[i]];
33603 util.merge = merge;
33606 * Converts the first character of a string to lower case.
33607 * @param {string} str String to convert
33608 * @returns {string} Converted string
33610 util.lcFirst = function lcFirst(str) {
33611 return str.charAt(0).toLowerCase() + str.substring(1);
33615 * Creates a custom error constructor.
33617 * @param {string} name Error name
33618 * @returns {Constructor<Error>} Custom error constructor
33620 function newError(name) {
33622 function CustomError(message, properties) {
33624 if (!(this instanceof CustomError))
33625 return new CustomError(message, properties);
33627 // Error.call(this, message);
33628 // ^ just returns a new error instance because the ctor can be called as a function
33630 Object.defineProperty(this, "message
", { get: function() { return message; } });
33632 /* istanbul ignore next */
33633 if (Error.captureStackTrace) // node
33634 Error.captureStackTrace(this, CustomError);
33636 Object.defineProperty(this, "stack
", { value: (new Error()).stack || "" });
33639 merge(this, properties);
33642 (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError;
33644 Object.defineProperty(CustomError.prototype, "name
", { get: function() { return name; } });
33646 CustomError.prototype.toString = function toString() {
33647 return this.name + ": " + this.message;
33650 return CustomError;
33653 util.newError = newError;
33656 * Constructs a new protocol error.
33657 * @classdesc Error subclass indicating a protocol specifc error.
33660 * @template T extends Message<T>
33662 * @param {string} message Error message
33663 * @param {Object.<string,*>} [properties] Additional properties
33666 * MyMessage.decode(someBuffer); // throws if required fields are missing
33668 * if (e instanceof ProtocolError && e.instance)
33669 * console.log("decoded so
far: " + JSON.stringify(e.instance));
33672 util.ProtocolError = newError("ProtocolError
");
33675 * So far decoded message instance.
33676 * @name util.ProtocolError#instance
33677 * @type {Message<T>}
33681 * A OneOf getter as returned by {@link util.oneOfGetter}.
33682 * @typedef OneOfGetter
33684 * @returns {string|undefined} Set field name, if any
33688 * Builds a getter for a oneof's present field name.
33689 * @param {string[]} fieldNames Field names
33690 * @returns {OneOfGetter} Unbound getter
33692 util.oneOfGetter = function getOneOf(fieldNames) {
33694 for (var i = 0; i < fieldNames.length; ++i)
33695 fieldMap[fieldNames[i]] = 1;
33698 * @returns {string|undefined} Set field name, if any
33702 return function() { // eslint-disable-line consistent-return
33703 for (var keys = Object.keys(this), i = keys.length - 1; i > -1; --i)
33704 if (fieldMap[keys[i]] === 1 && this[keys[i]] !== undefined && this[keys[i]] !== null)
33710 * A OneOf setter as returned by {@link util.oneOfSetter}.
33711 * @typedef OneOfSetter
33713 * @param {string|undefined} value Field name
33714 * @returns {undefined}
33718 * Builds a setter for a oneof's present field name.
33719 * @param {string[]} fieldNames Field names
33720 * @returns {OneOfSetter} Unbound setter
33722 util.oneOfSetter = function setOneOf(fieldNames) {
33725 * @param {string} name Field name
33726 * @returns {undefined}
33730 return function(name) {
33731 for (var i = 0; i < fieldNames.length; ++i)
33732 if (fieldNames[i] !== name)
33733 delete this[fieldNames[i]];
33738 * Default conversion options used for {@link Message#toJSON} implementations.
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:
33742 * - Longs become strings
33743 * - Enums become string keys
33744 * - Bytes become base64 encoded strings
33745 * - (Sub-)Messages become plain objects
33746 * - Maps become plain objects with all string keys
33747 * - Repeated fields become arrays
33748 * - NaN and Infinity for float and double fields become strings
33750 * @type {IConversionOptions}
33751 * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json
33753 util.toJSONOptions = {
33760 util._configure = function() {
33761 var Buffer = util.Buffer;
33762 /* istanbul ignore if */
33764 util._Buffer_from = util._Buffer_allocUnsafe = null;
33767 // because node 4.x buffers are incompatible & immutable
33768 // see: https://github.com/dcodeIO/protobuf.js/pull/665
33769 util._Buffer_from = Buffer.from !== Uint8Array.from && Buffer.from ||
33770 /* istanbul ignore next */
33771 function Buffer_from(value, encoding) {
33772 return new Buffer(value, encoding);
33774 util._Buffer_allocUnsafe = Buffer.allocUnsafe ||
33775 /* istanbul ignore next */
33776 function Buffer_allocUnsafe(size) {
33777 return new Buffer(size);
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){
33784 module.exports = verifier;
33786 var Enum = require("./enum"),
33787 util = require("./util
");
33789 function invalid(field, expected) {
33790 return field.name + ": " + expected + (field.repeated && expected !== "array
" ? "[]" : field.map && expected !== "object
" ? "{k:"+field.keyType+"}" : "") + " expected
";
33794 * Generates a partial value verifier.
33795 * @param {Codegen} gen Codegen instance
33796 * @param {Field} field Reflected field
33797 * @param {number} fieldIndex Field index
33798 * @param {string} ref Variable reference
33799 * @returns {Codegen} Codegen instance
33802 function genVerifyValue(gen, field, fieldIndex, ref) {
33803 /* eslint-disable no-unexpected-multiline */
33804 if (field.resolvedType) {
33805 if (field.resolvedType instanceof Enum) { gen
33806 ("switch(%s
){", ref)
33808 ("return%j
", invalid(field, "enum value
"));
33809 for (var keys = Object.keys(field.resolvedType.values), j = 0; j < keys.length; ++j) gen
33810 ("case %i:", field.resolvedType.values[keys[j]]);
33817 ("var e
=types
[%i
].verify(%s
);", fieldIndex, ref)
33819 ("return%j
+e
", field.name + ".")
33823 switch (field.type) {
33828 case "sfixed32
": gen
33829 ("if(!util
.isInteger(%s
))", ref)
33830 ("return%j
", invalid(field, "integer
"));
33836 case "sfixed64
": gen
33837 ("if(!util
.isInteger(%s
)&&!(%s
&&util
.isInteger(%s
.low
)&&util
.isInteger(%s
.high
)))", ref, ref, ref, ref)
33838 ("return%j
", invalid(field, "integer
|Long
"));
33842 ("if(typeof %s
!==\"number
\")", ref)
33843 ("return%j
", invalid(field, "number
"));
33846 ("if(typeof %s
!==\"boolean\")", ref)
33847 ("return%j
", invalid(field, "boolean"));
33850 ("if(!util
.isString(%s
))", ref)
33851 ("return%j
", invalid(field, "string
"));
33854 ("if(!(%s
&&typeof %s
.length
===\"number
\"||util
.isString(%s
)))", ref, ref, ref)
33855 ("return%j
", invalid(field, "buffer
"));
33860 /* eslint-enable no-unexpected-multiline */
33864 * Generates a partial key verifier.
33865 * @param {Codegen} gen Codegen instance
33866 * @param {Field} field Reflected field
33867 * @param {string} ref Variable reference
33868 * @returns {Codegen} Codegen instance
33871 function genVerifyKey(gen, field, ref) {
33872 /* eslint-disable no-unexpected-multiline */
33873 switch (field.keyType) {
33878 case "sfixed32
": gen
33879 ("if(!util
.key32Re
.test(%s
))", ref)
33880 ("return%j
", invalid(field, "integer key
"));
33886 case "sfixed64
": gen
33887 ("if(!util
.key64Re
.test(%s
))", ref) // see comment above: x is ok, d is not
33888 ("return%j
", invalid(field, "integer
|Long key
"));
33891 ("if(!util
.key2Re
.test(%s
))", ref)
33892 ("return%j
", invalid(field, "boolean key
"));
33896 /* eslint-enable no-unexpected-multiline */
33900 * Generates a verifier specific to the specified message type.
33901 * @param {Type} mtype Message type
33902 * @returns {Codegen} Codegen instance
33904 function verifier(mtype) {
33905 /* eslint-disable no-unexpected-multiline */
33907 var gen = util.codegen(["m
"], mtype.name + "$verify
")
33908 ("if(typeof m
!==\"object
\"||m
===null)")
33909 ("return%j
", "object expected
");
33910 var oneofs = mtype.oneofsArray,
33911 seenFirstField = {};
33912 if (oneofs.length) gen
33915 for (var i = 0; i < /* initializes */ mtype.fieldsArray.length; ++i) {
33916 var field = mtype._fieldsArray[i].resolve(),
33917 ref = "m
" + util.safeProp(field.name);
33919 if (field.optional) gen
33920 ("if(%s
!=null&&m
.hasOwnProperty(%j
)){", ref, field.name); // !== undefined && !== null
33923 if (field.map) { gen
33924 ("if(!util
.isObject(%s
))", ref)
33925 ("return%j
", invalid(field, "object
"))
33926 ("var k
=Object
.keys(%s
)", ref)
33927 ("for(var i
=0;i
<k
.length
;++i
){");
33928 genVerifyKey(gen, field, "k
[i
]");
33929 genVerifyValue(gen, field, i, ref + "[k
[i
]]")
33933 } else if (field.repeated) { gen
33934 ("if(!Array
.isArray(%s
))", ref)
33935 ("return%j
", invalid(field, "array
"))
33936 ("for(var i
=0;i
<%s
.length
;++i
){", ref);
33937 genVerifyValue(gen, field, i, ref + "[i
]")
33940 // required or present fields
33942 if (field.partOf) {
33943 var oneofProp = util.safeProp(field.partOf.name);
33944 if (seenFirstField[field.partOf.name] === 1) gen
33945 ("if(p
%s
===1)", oneofProp)
33946 ("return%j
", field.partOf.name + ": multiple values
");
33947 seenFirstField[field.partOf.name] = 1;
33949 ("p
%s
=1", oneofProp);
33951 genVerifyValue(gen, field, i, ref);
33953 if (field.optional) gen
33958 /* eslint-enable no-unexpected-multiline */
33960 },{"./enum":196,"./util":218}],222:[function(require,module,exports){
33964 * Wrappers for common types.
33965 * @type {Object.<string,IWrapper>}
33968 var wrappers = exports;
33970 var Message = require("./message
");
33973 * From object converter part of an {@link IWrapper}.
33974 * @typedef WrapperFromObjectConverter
33976 * @param {Object.<string,*>} object Plain object
33977 * @returns {Message<{}>} Message instance
33982 * To object converter part of an {@link IWrapper}.
33983 * @typedef WrapperToObjectConverter
33985 * @param {Message<{}>} message Message instance
33986 * @param {IConversionOptions} [options] Conversion options
33987 * @returns {Object.<string,*>} Plain object
33992 * Common type wrapper part of {@link wrappers}.
33993 * @interface IWrapper
33994 * @property {WrapperFromObjectConverter} [fromObject] From object converter
33995 * @property {WrapperToObjectConverter} [toObject] To object converter
33998 // Custom wrapper for Any
33999 wrappers[".google
.protobuf
.Any
"] = {
34001 fromObject: function(object) {
34003 // unwrap value type if mapped
34004 if (object && object["@type
"]) {
34005 var type = this.lookup(object["@type
"]);
34006 /* istanbul ignore else */
34008 // type_url does not accept leading "."
34009 var type_url = object["@type
"].charAt(0) === "." ?
34010 object["@type
"].substr(1) : object["@type
"];
34011 // type_url prefix is optional, but path seperator is required
34012 return this.create({
34013 type_url: "/" + type_url,
34014 value: type.encode(type.fromObject(object)).finish()
34019 return this.fromObject(object);
34022 toObject: function(message, options) {
34024 // decode value if requested and unmapped
34025 if (options && options.json && message.type_url && message.value) {
34026 // Only use fully qualified type name after the last '/'
34027 var name = message.type_url.substring(message.type_url.lastIndexOf("/") + 1);
34028 var type = this.lookup(name);
34029 /* istanbul ignore else */
34031 message = type.decode(message.value);
34034 // wrap value if unmapped
34035 if (!(message instanceof this.ctor) && message instanceof Message) {
34036 var object = message.$type.toObject(message, options);
34037 object["@type
"] = message.$type.fullName;
34041 return this.toObject(message, options);
34045 },{"./message
":202}],223:[function(require,module,exports){
34047 module.exports = Writer;
34049 var util = require("./util/minimal");
34051 var BufferWriter; // cyclic
34053 var LongBits = util.LongBits,
34054 base64 = util.base64,
34058 * Constructs a new writer operation instance.
34059 * @classdesc Scheduled writer operation.
34061 * @param {function(*, Uint8Array, number)} fn Function to call
34062 * @param {number} len Value byte length
34063 * @param {*} val Value to write
34066 function Op(fn, len, val) {
34069 * Function to call.
34070 * @type {function(Uint8Array, number, *)}
34075 * Value byte length.
34082 * @type {Writer.Op|undefined}
34084 this.next = undefined;
34090 this.val = val; // type varies
34093 /* istanbul ignore next */
34094 function noop() {} // eslint-disable-line no-empty-function
34097 * Constructs a new writer state instance.
34098 * @classdesc Copied writer state.
34101 * @param {Writer} writer Writer to copy state from
34104 function State(writer) {
34108 * @type {Writer.Op}
34110 this.head = writer.head;
34114 * @type {Writer.Op}
34116 this.tail = writer.tail;
34119 * Current buffer length.
34122 this.len = writer.len;
34126 * @type {State|null}
34128 this.next = writer.states;
34132 * Constructs a new writer instance.
34133 * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`.
34136 function Writer() {
34148 this.head = new Op(noop, 0, 0);
34154 this.tail = this.head;
34157 * Linked forked states.
34158 * @type {Object|null}
34160 this.states = null;
34162 // When a value is written, the writer calculates its byte length and puts it into a linked
34163 // list of operations to perform when finish() is called. This both allows us to allocate
34164 // buffers of the exact required size and reduces the amount of work we have to do compared
34165 // to first calculating over objects and then encoding over objects. In our case, the encoding
34166 // part is just a linked list walk calling operations with already prepared values.
34170 * Creates a new writer.
34172 * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer}
34174 Writer.create = util.Buffer
34175 ? function create_buffer_setup() {
34176 return (Writer.create = function create_buffer() {
34177 return new BufferWriter();
34180 /* istanbul ignore next */
34181 : function create_array() {
34182 return new Writer();
34186 * Allocates a buffer of the specified size.
34187 * @param {number} size Buffer size
34188 * @returns {Uint8Array} Buffer
34190 Writer.alloc = function alloc(size) {
34191 return new util.Array(size);
34194 // Use Uint8Array buffer pool in the browser, just like node does with buffers
34195 /* istanbul ignore else */
34196 if (util.Array !== Array)
34197 Writer.alloc = util.pool(Writer.alloc, util.Array.prototype.subarray);
34200 * Pushes a new operation to the queue.
34201 * @param {function(Uint8Array, number, *)} fn Function to call
34202 * @param {number} len Value byte length
34203 * @param {number} val Value to write
34204 * @returns {Writer} `this`
34207 Writer.prototype._push = function push(fn, len, val) {
34208 this.tail = this.tail.next = new Op(fn, len, val);
34213 function writeByte(val, buf, pos) {
34214 buf[pos] = val & 255;
34217 function writeVarint32(val, buf, pos) {
34218 while (val > 127) {
34219 buf[pos++] = val & 127 | 128;
34226 * Constructs a new varint writer operation instance.
34227 * @classdesc Scheduled varint writer operation.
34230 * @param {number} len Value byte length
34231 * @param {number} val Value to write
34234 function VarintOp(len, val) {
34236 this.next = undefined;
34240 VarintOp.prototype = Object.create(Op.prototype);
34241 VarintOp.prototype.fn = writeVarint32;
34244 * Writes an unsigned 32 bit value as a varint.
34245 * @param {number} value Value to write
34246 * @returns {Writer} `this`
34248 Writer.prototype.uint32 = function write_uint32(value) {
34249 // here, the call to this.push has been inlined and a varint specific Op subclass is used.
34250 // uint32 is by far the most frequently used operation and benefits significantly from this.
34251 this.len += (this.tail = this.tail.next = new VarintOp(
34252 (value = value >>> 0)
34254 : value < 16384 ? 2
34255 : value < 2097152 ? 3
34256 : value < 268435456 ? 4
34263 * Writes a signed 32 bit value as a varint.
34265 * @param {number} value Value to write
34266 * @returns {Writer} `this`
34268 Writer.prototype.int32 = function write_int32(value) {
34270 ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec
34271 : this.uint32(value);
34275 * Writes a 32 bit value as a varint, zig-zag encoded.
34276 * @param {number} value Value to write
34277 * @returns {Writer} `this`
34279 Writer.prototype.sint32 = function write_sint32(value) {
34280 return this.uint32((value << 1 ^ value >> 31) >>> 0);
34283 function writeVarint64(val, buf, pos) {
34285 buf[pos++] = val.lo & 127 | 128;
34286 val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0;
34289 while (val.lo > 127) {
34290 buf[pos++] = val.lo & 127 | 128;
34291 val.lo = val.lo >>> 7;
34293 buf[pos++] = val.lo;
34297 * Writes an unsigned 64 bit value as a varint.
34298 * @param {Long|number|string} value Value to write
34299 * @returns {Writer} `this`
34300 * @throws {TypeError} If `value` is a string and no long library is present.
34302 Writer.prototype.uint64 = function write_uint64(value) {
34303 var bits = LongBits.from(value);
34304 return this._push(writeVarint64, bits.length(), bits);
34308 * Writes a signed 64 bit value as a varint.
34310 * @param {Long|number|string} value Value to write
34311 * @returns {Writer} `this`
34312 * @throws {TypeError} If `value` is a string and no long library is present.
34314 Writer.prototype.int64 = Writer.prototype.uint64;
34317 * Writes a signed 64 bit value as a varint, zig-zag encoded.
34318 * @param {Long|number|string} value Value to write
34319 * @returns {Writer} `this`
34320 * @throws {TypeError} If `value` is a string and no long library is present.
34322 Writer.prototype.sint64 = function write_sint64(value) {
34323 var bits = LongBits.from(value).zzEncode();
34324 return this._push(writeVarint64, bits.length(), bits);
34328 * Writes a boolish value as a varint.
34329 * @param {boolean} value Value to write
34330 * @returns {Writer} `this`
34332 Writer.prototype.bool = function write_bool(value) {
34333 return this._push(writeByte, 1, value ? 1 : 0);
34336 function writeFixed32(val, buf, pos) {
34337 buf[pos ] = val & 255;
34338 buf[pos + 1] = val >>> 8 & 255;
34339 buf[pos + 2] = val >>> 16 & 255;
34340 buf[pos + 3] = val >>> 24;
34344 * Writes an unsigned 32 bit value as fixed 32 bits.
34345 * @param {number} value Value to write
34346 * @returns {Writer} `this`
34348 Writer.prototype.fixed32 = function write_fixed32(value) {
34349 return this._push(writeFixed32, 4, value >>> 0);
34353 * Writes a signed 32 bit value as fixed 32 bits.
34355 * @param {number} value Value to write
34356 * @returns {Writer} `this`
34358 Writer.prototype.sfixed32 = Writer.prototype.fixed32;
34361 * Writes an unsigned 64 bit value as fixed 64 bits.
34362 * @param {Long|number|string} value Value to write
34363 * @returns {Writer} `this`
34364 * @throws {TypeError} If `value` is a string and no long library is present.
34366 Writer.prototype.fixed64 = function write_fixed64(value) {
34367 var bits = LongBits.from(value);
34368 return this._push(writeFixed32, 4, bits.lo)._push(writeFixed32, 4, bits.hi);
34372 * Writes a signed 64 bit value as fixed 64 bits.
34374 * @param {Long|number|string} value Value to write
34375 * @returns {Writer} `this`
34376 * @throws {TypeError} If `value` is a string and no long library is present.
34378 Writer.prototype.sfixed64 = Writer.prototype.fixed64;
34381 * Writes a float (32 bit).
34383 * @param {number} value Value to write
34384 * @returns {Writer} `this`
34386 Writer.prototype.float = function write_float(value) {
34387 return this._push(util.float.writeFloatLE, 4, value);
34391 * Writes a double (64 bit float).
34393 * @param {number} value Value to write
34394 * @returns {Writer} `this`
34396 Writer.prototype.double = function write_double(value) {
34397 return this._push(util.float.writeDoubleLE, 8, value);
34400 var writeBytes = util.Array.prototype.set
34401 ? function writeBytes_set(val, buf, pos) {
34402 buf.set(val, pos); // also works for plain array values
34404 /* istanbul ignore next */
34405 : function writeBytes_for(val, buf, pos) {
34406 for (var i = 0; i < val.length; ++i)
34407 buf[pos + i] = val[i];
34411 * Writes a sequence of bytes.
34412 * @param {Uint8Array|string} value Buffer or base64 encoded string to write
34413 * @returns {Writer} `this`
34415 Writer.prototype.bytes = function write_bytes(value) {
34416 var len = value.length >>> 0;
34418 return this._push(writeByte, 1, 0);
34419 if (util.isString(value)) {
34420 var buf = Writer.alloc(len = base64.length(value));
34421 base64.decode(value, buf, 0);
34424 return this.uint32(len)._push(writeBytes, len, value);
34429 * @param {string} value Value to write
34430 * @returns {Writer} `this`
34432 Writer.prototype.string = function write_string(value) {
34433 var len = utf8.length(value);
34435 ? this.uint32(len)._push(utf8.write, len, value)
34436 : this._push(writeByte, 1, 0);
34440 * Forks this writer's state by pushing it to a stack.
34441 * Calling {@link Writer#reset|reset} or {@link Writer#ldelim|ldelim} resets the writer to the previous state.
34442 * @returns {Writer} `this`
34444 Writer.prototype.fork = function fork() {
34445 this.states = new State(this);
34446 this.head = this.tail = new Op(noop, 0, 0);
34452 * Resets this instance to the last state.
34453 * @returns {Writer} `this`
34455 Writer.prototype.reset = function reset() {
34457 this.head = this.states.head;
34458 this.tail = this.states.tail;
34459 this.len = this.states.len;
34460 this.states = this.states.next;
34462 this.head = this.tail = new Op(noop, 0, 0);
34469 * Resets to the last state and appends the fork state's current write length as a varint followed by its operations.
34470 * @returns {Writer} `this`
34472 Writer.prototype.ldelim = function ldelim() {
34473 var head = this.head,
34476 this.reset().uint32(len);
34478 this.tail.next = head.next; // skip noop
34486 * Finishes the write operation.
34487 * @returns {Uint8Array} Finished buffer
34489 Writer.prototype.finish = function finish() {
34490 var head = this.head.next, // skip noop
34491 buf = this.constructor.alloc(this.len),
34494 head.fn(head.val, buf, pos);
34498 // this.head = this.tail = null;
34502 Writer._configure = function(BufferWriter_) {
34503 BufferWriter = BufferWriter_;
34506 },{"./util/minimal":220}],224:[function(require,module,exports){
34508 module.exports = BufferWriter;
34511 var Writer = require("./writer
");
34512 (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter;
34514 var util = require("./util/minimal");
34516 var Buffer = util.Buffer;
34519 * Constructs a new buffer writer instance.
34520 * @classdesc Wire format writer using node buffers.
34524 function BufferWriter() {
34529 * Allocates a buffer of the specified size.
34530 * @param {number} size Buffer size
34531 * @returns {Buffer} Buffer
34533 BufferWriter.alloc = function alloc_buffer(size) {
34534 return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size);
34537 var writeBytesBuffer = Buffer && Buffer.prototype instanceof Uint8Array && Buffer.prototype.set.name === "set"
34538 ? function writeBytesBuffer_set(val, buf, pos) {
34539 buf.set(val, pos); // faster than copy (requires node >= 4 where Buffers extend Uint8Array and set is properly inherited)
34540 // also works for plain array values
34542 /* istanbul ignore next */
34543 : function writeBytesBuffer_copy(val, buf, pos) {
34544 if (val.copy) // Buffer values
34545 val.copy(buf, pos, 0, val.length);
34546 else for (var i = 0; i < val.length;) // plain array values
34547 buf[pos++] = val[i++];
34553 BufferWriter.prototype.bytes = function write_bytes_buffer(value) {
34554 if (util.isString(value))
34555 value = util._Buffer_from(value, "base64
");
34556 var len = value.length >>> 0;
34559 this._push(writeBytesBuffer, len, value);
34563 function writeStringBuffer(val, buf, pos) {
34564 if (val.length < 40) // plain js is faster for short strings (probably due to redundant assertions)
34565 util.utf8.write(val, buf, pos);
34567 buf.utf8Write(val, pos);
34573 BufferWriter.prototype.string = function write_string_buffer(value) {
34574 var len = Buffer.byteLength(value);
34577 this._push(writeStringBuffer, len, value);
34583 * Finishes the write operation.
34584 * @name BufferWriter#finish
34586 * @returns {Buffer} Finished buffer
34589 },{"./util/minimal":220,"./writer
":223}],225:[function(require,module,exports){
34590 exports.publicEncrypt = require('./publicEncrypt');
34591 exports.privateDecrypt = require('./privateDecrypt');
34593 exports.privateEncrypt = function privateEncrypt(key, buf) {
34594 return exports.publicEncrypt(key, buf, true);
34597 exports.publicDecrypt = function publicDecrypt(key, buf) {
34598 return exports.privateDecrypt(key, buf, true);
34600 },{"./privateDecrypt":227,"./publicEncrypt":228}],226:[function(require,module,exports){
34601 (function (Buffer){
34602 var createHash = require('create-hash');
34603 module.exports = function (seed, len) {
34604 var t = new Buffer('');
34606 while (t.length < len) {
34608 t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]);
34610 return t.slice(0, len);
34613 function i2ops(c) {
34614 var out = new Buffer(4);
34615 out.writeUInt32BE(c,0);
34618 }).call(this,require("buffer
").Buffer)
34619 },{"buffer
":107,"create
-hash
":111}],227:[function(require,module,exports){
34620 (function (Buffer){
34621 var parseKeys = require('parse-asn1');
34622 var mgf = require('./mgf');
34623 var xor = require('./xor');
34624 var bn = require('bn.js');
34625 var crt = require('browserify-rsa');
34626 var createHash = require('create-hash');
34627 var withPublic = require('./withPublic');
34628 module.exports = function privateDecrypt(private_key, enc, reverse) {
34630 if (private_key.padding) {
34631 padding = private_key.padding;
34632 } else if (reverse) {
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');
34645 msg = withPublic(new bn(enc), key);
34647 msg = crt(enc, key);
34649 var zBuffer = new Buffer(k - msg.length);
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) {
34659 throw new Error('unknown padding');
34663 function 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');
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');
34681 while (db[i] === 0) {
34684 if (db[i++] !== 1) {
34685 throw new Error('decryption error');
34687 return db.slice(i);
34690 function pkcs1(key, msg, reverse){
34691 var p1 = msg.slice(0, 2);
34694 while (msg[i++] !== 0) {
34695 if (i >= msg.length) {
34700 var ps = msg.slice(2, i - 1);
34701 var p2 = msg.slice(i - 1, i);
34703 if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){
34706 if (ps.length < 8) {
34710 throw new Error('decryption error');
34712 return msg.slice(i);
34714 function compare(a, b){
34718 var len = a.length;
34719 if (a.length !== b.length) {
34721 len = Math.min(a.length, b.length);
34724 while (++i < len) {
34725 dif += (a[i] ^ b[i]);
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){
34732 var parseKeys = require('parse-asn1');
34733 var randomBytes = require('randombytes');
34734 var createHash = require('create-hash');
34735 var mgf = require('./mgf');
34736 var xor = require('./xor');
34737 var bn = require('bn.js');
34738 var withPublic = require('./withPublic');
34739 var crt = require('browserify-rsa');
34742 RSA_PKCS1_OAEP_PADDING: 4,
34743 RSA_PKCS1_PADDIN: 1,
34747 module.exports = function publicEncrypt(public_key, msg, reverse) {
34749 if (public_key.padding) {
34750 padding = public_key.padding;
34751 } else if (reverse) {
34756 var key = parseKeys(public_key);
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');
34768 throw new Error('unknown padding');
34771 return crt(paddedMsg, key);
34773 return withPublic(paddedMsg, key);
34777 function 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');
34786 var ps = new Buffer(k - mLen - hLen2 - 2);
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));
34794 function 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');
34802 ps = new Buffer(k - mLen - 3);
34805 ps = nonZero(k - mLen - 3);
34807 return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k));
34809 function nonZero(len, crypto) {
34810 var out = new Buffer(len);
34812 var cache = randomBytes(len*2);
34816 if (cur === cache.length) {
34817 cache = randomBytes(len*2);
34820 num = cache[cur++];
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){
34830 var bn = require('bn.js');
34831 function withPublic(paddedMsg, key) {
34832 return new Buffer(paddedMsg
34833 .toRed(bn.mont(key.modulus))
34834 .redPow(new bn(key.publicExponent))
34839 module.exports = withPublic;
34840 }).call(this,require("buffer
").Buffer)
34841 },{"bn
.js
":75,"buffer
":107}],230:[function(require,module,exports){
34842 module.exports = function xor(a, b) {
34843 var len = a.length;
34845 while (++i < len) {
34850 },{}],231:[function(require,module,exports){
34851 (function (process,global){
34854 function oldBrowser () {
34855 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
34858 var Buffer = require('safe-buffer').Buffer
34859 var crypto = global.crypto || global.msCrypto
34861 if (crypto && crypto.getRandomValues) {
34862 module.exports = randomBytes
34864 module.exports = oldBrowser
34867 function 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)
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)
34879 // XXX: phantomjs doesn't like a buffer being passed here
34880 var bytes = Buffer.from(rawBytes.buffer)
34882 if (typeof cb === 'function') {
34883 return process.nextTick(function () {
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){
34896 function oldBrowser () {
34897 throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11')
34899 var safeBuffer = require('safe-buffer')
34900 var randombytes = require('randombytes')
34901 var Buffer = safeBuffer.Buffer
34902 var kBufferMaxLength = safeBuffer.kMaxLength
34903 var crypto = global.crypto || global.msCrypto
34904 var kMaxUint32 = Math.pow(2, 32) - 1
34905 function 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')
34910 if (offset > kMaxUint32 || offset < 0) {
34911 throw new TypeError('offset must be a uint32')
34914 if (offset > kBufferMaxLength || offset > length) {
34915 throw new RangeError('offset out of range')
34919 function 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')
34924 if (size > kMaxUint32 || size < 0) {
34925 throw new TypeError('size must be a uint32')
34928 if (size + offset > length || size > kBufferMaxLength) {
34929 throw new RangeError('buffer too small')
34932 if ((crypto && crypto.getRandomValues) || !process.browser) {
34933 exports.randomFill = randomFill
34934 exports.randomFillSync = randomFillSync
34936 exports.randomFill = oldBrowser
34937 exports.randomFillSync = oldBrowser
34939 function 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')
34944 if (typeof offset === 'function') {
34948 } else if (typeof size === 'function') {
34950 size = buf.length - offset
34951 } else if (typeof cb !== 'function') {
34952 throw new TypeError('"cb
" argument must be a function')
34954 assertOffset(offset, buf.length)
34955 assertSize(size, offset, buf.length)
34956 return actualFill(buf, offset, size, cb)
34959 function 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)
34965 process.nextTick(function () {
34973 randombytes(size, function (err, bytes) {
34977 bytes.copy(buf, offset)
34982 var bytes = randombytes(size)
34983 bytes.copy(buf, offset)
34986 function randomFillSync (buf, offset, size) {
34987 if (typeof offset === 'undefined') {
34990 if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) {
34991 throw new TypeError('"buf
" argument must be a Buffer or Uint8Array')
34994 assertOffset(offset, buf.length)
34996 if (size === undefined) size = buf.length - offset
34998 assertSize(size, offset, buf.length)
35000 return actualFill(buf, offset, size)
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){
35005 module.exports = require('./lib/_stream_duplex.js');
35007 },{"./lib/_stream_duplex
.js
":234}],234:[function(require,module,exports){
35008 // Copyright Joyent, Inc. and other Node contributors.
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:
35018 // The above copyright notice and this permission notice shall be included
35019 // in all copies or substantial portions of the Software.
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.
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
35038 var processNextTick = require('process-nextick-args');
35042 var objectKeys = Object.keys || function (obj) {
35044 for (var key in obj) {
35050 module.exports = Duplex;
35053 var util = require('core-util-is');
35054 util.inherits = require('inherits');
35057 var Readable = require('./_stream_readable');
35058 var Writable = require('./_stream_writable');
35060 util.inherits(Duplex, Readable);
35062 var keys = objectKeys(Writable.prototype);
35063 for (var v = 0; v < keys.length; v++) {
35064 var method = keys[v];
35065 if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method];
35068 function Duplex(options) {
35069 if (!(this instanceof Duplex)) return new Duplex(options);
35071 Readable.call(this, options);
35072 Writable.call(this, options);
35074 if (options && options.readable === false) this.readable = false;
35076 if (options && options.writable === false) this.writable = false;
35078 this.allowHalfOpen = true;
35079 if (options && options.allowHalfOpen === false) this.allowHalfOpen = false;
35081 this.once('end', onend);
35084 // the no-half-open enforcer
35086 // if we allow half-open state, or if the writable side ended,
35088 if (this.allowHalfOpen || this._writableState.ended) return;
35090 // no more data can be written.
35091 // But allow more writes to happen in this tick.
35092 processNextTick(onEndNT, this);
35095 function onEndNT(self) {
35099 Object.defineProperty(Duplex.prototype, 'destroyed', {
35101 if (this._readableState === undefined || this._writableState === undefined) {
35104 return this._readableState.destroyed && this._writableState.destroyed;
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) {
35113 // backward compatibility, the user is explicitly
35114 // managing destroyed
35115 this._readableState.destroyed = value;
35116 this._writableState.destroyed = value;
35120 Duplex.prototype._destroy = function (err, cb) {
35124 processNextTick(cb, err);
35127 function forEach(xs, f) {
35128 for (var i = 0, l = xs.length; i < l; i++) {
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.
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:
35143 // The above copyright notice and this permission notice shall be included
35144 // in all copies or substantial portions of the Software.
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.
35154 // a passthrough stream.
35155 // basically just the most minimal sort of Transform stream.
35156 // Every written chunk gets output as-is.
35160 module.exports = PassThrough;
35162 var Transform = require('./_stream_transform');
35165 var util = require('core-util-is');
35166 util.inherits = require('inherits');
35169 util.inherits(PassThrough, Transform);
35171 function PassThrough(options) {
35172 if (!(this instanceof PassThrough)) return new PassThrough(options);
35174 Transform.call(this, options);
35177 PassThrough.prototype._transform = function (chunk, encoding, cb) {
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.
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:
35192 // The above copyright notice and this permission notice shall be included
35193 // in all copies or substantial portions of the Software.
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.
35207 var processNextTick = require('process-nextick-args');
35210 module.exports = Readable;
35213 var isArray = require('isarray');
35220 Readable.ReadableState = ReadableState;
35223 var EE = require('events').EventEmitter;
35225 var EElistenerCount = function (emitter, type) {
35226 return emitter.listeners(type).length;
35231 var Stream = require('./internal/streams/stream');
35234 // TODO(bmeurer): Change this back to const once hole checks are
35235 // properly optimized away early in Ignition+TurboFan.
35237 var Buffer = require('safe-buffer').Buffer;
35238 var OurUint8Array = global.Uint8Array || function () {};
35239 function _uint8ArrayToBuffer(chunk) {
35240 return Buffer.from(chunk);
35242 function _isUint8Array(obj) {
35243 return Buffer.isBuffer(obj) || obj instanceof OurUint8Array;
35248 var util = require('core-util-is');
35249 util.inherits = require('inherits');
35253 var debugUtil = require('util');
35254 var debug = void 0;
35255 if (debugUtil && debugUtil.debuglog) {
35256 debug = debugUtil.debuglog('stream');
35258 debug = function () {};
35262 var BufferList = require('./internal/streams/BufferList');
35263 var destroyImpl = require('./internal/streams/destroy');
35266 util.inherits(Readable, Stream);
35268 var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume'];
35270 function 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);
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]];
35284 function ReadableState(options, stream) {
35285 Duplex = Duplex || require('./_stream_duplex');
35287 options = options || {};
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;
35293 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode;
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;
35302 this.highWaterMark = Math.floor(this.highWaterMark);
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
35307 this.buffer = new BufferList();
35310 this.pipesCount = 0;
35311 this.flowing = null;
35312 this.ended = false;
35313 this.endEmitted = false;
35314 this.reading = false;
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.
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;
35329 // has it been destroyed
35330 this.destroyed
= false;
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';
35337 // the number of writers that are awaiting a drain event in .pipe()s
35338 this.awaitDrain
= 0;
35340 // if true, a maybeReadMore has been scheduled
35341 this.readingMore
= false;
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
;
35352 function Readable(options
) {
35353 Duplex
= Duplex
|| require('./_stream_duplex');
35355 if (!(this instanceof Readable
)) return new Readable(options
);
35357 this._readableState
= new ReadableState(options
, this);
35360 this.readable
= true;
35363 if (typeof options
.read
=== 'function') this._read
= options
.read
;
35365 if (typeof options
.destroy
=== 'function') this._destroy
= options
.destroy
;
35371 Object
.defineProperty(Readable
.prototype, 'destroyed', {
35373 if (this._readableState
=== undefined) {
35376 return this._readableState
.destroyed
;
35378 set: function (value
) {
35379 // we ignore the value if the stream
35380 // has not been initialized yet
35381 if (!this._readableState
) {
35385 // backward compatibility, the user is explicitly
35386 // managing destroyed
35387 this._readableState
.destroyed
= value
;
35391 Readable
.prototype.destroy
= destroyImpl
.destroy
;
35392 Readable
.prototype._undestroy
= destroyImpl
.undestroy
;
35393 Readable
.prototype._destroy = function (err
, cb
) {
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.
35402 Readable
.prototype.push = function (chunk
, encoding
) {
35403 var state
= this._readableState
;
35404 var skipChunkCheck
;
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
);
35413 skipChunkCheck
= true;
35416 skipChunkCheck
= true;
35419 return readableAddChunk(this, chunk
, encoding
, false, skipChunkCheck
);
35422 // Unshift should *always* be something directly out of read()
35423 Readable
.prototype.unshift = function (chunk
) {
35424 return readableAddChunk(this, chunk
, null, true, false);
35427 function readableAddChunk(stream
, chunk
, encoding
, addToFront
, skipChunkCheck
) {
35428 var state
= stream
._readableState
;
35429 if (chunk
=== null) {
35430 state
.reading
= false;
35431 onEofChunk(stream
, state
);
35434 if (!skipChunkCheck
) er
= chunkInvalid(state
, chunk
);
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
);
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'));
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
);
35452 addChunk(stream
, state
, chunk
, false);
35455 } else if (!addToFront
) {
35456 state
.reading
= false;
35460 return needMoreData(state
);
35463 function addChunk(stream
, state
, chunk
, addToFront
) {
35464 if (state
.flowing
&& state
.length
=== 0 && !state
.sync
) {
35465 stream
.emit('data', chunk
);
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
);
35472 if (state
.needReadable
) emitReadable(stream
);
35474 maybeReadMore(stream
, state
);
35477 function chunkInvalid(state
, chunk
) {
35479 if (!_isUint8Array(chunk
) && typeof chunk
!== 'string' && chunk
!== undefined && !state
.objectMode
) {
35480 er
= new TypeError('Invalid non-string/buffer chunk');
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.
35492 function needMoreData(state
) {
35493 return !state
.ended
&& (state
.needReadable
|| state
.length
< state
.highWaterMark
|| state
.length
=== 0);
35496 Readable
.prototype.isPaused = function () {
35497 return this._readableState
.flowing
=== false;
35500 // backwards compatibility.
35501 Readable
.prototype.setEncoding = function (enc
) {
35502 if (!StringDecoder
) StringDecoder
= require('string_decoder/').StringDecoder
;
35503 this._readableState
.decoder
= new StringDecoder(enc
);
35504 this._readableState
.encoding
= enc
;
35508 // Don't raise the hwm > 8MB
35509 var MAX_HWM
= 0x800000;
35510 function computeNewHighWaterMark(n
) {
35511 if (n
>= MAX_HWM
) {
35514 // Get the next highest power of 2 to prevent increasing hwm excessively in
35527 // This function is designed to be inlinable, so please take care when making
35528 // changes to the function body.
35529 function howMuchToRead(n
, state
) {
35530 if (n
<= 0 || state
.length
=== 0 && state
.ended
) return 0;
35531 if (state
.objectMode
) return 1;
35533 // Only flow one buffer at a time
35534 if (state
.flowing
&& state
.length
) return state
.buffer
.head
.data
.length
;else return state
.length
;
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;
35544 return state
.length
;
35547 // you can override either this method, or the async _read(n) below.
35548 Readable
.prototype.read = function (n
) {
35550 n
= parseInt(n
, 10);
35551 var state
= this._readableState
;
35554 if (n
!== 0) state
.emittedReadable
= false;
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);
35565 n
= howMuchToRead(n
, state
);
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);
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.
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.
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
35593 // 3. Actually pull the requested chunks out of the buffer and return.
35595 // if we need a readable event, then we need to do some reading.
35596 var doRead
= state
.needReadable
;
35597 debug('need readable', doRead
);
35599 // if we currently have less than the highWaterMark, then also read some
35600 if (state
.length
=== 0 || state
.length
- n
< state
.highWaterMark
) {
35602 debug('length less than watermark', doRead
);
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
) {
35609 debug('reading or ended', doRead
);
35610 } else if (doRead
) {
35612 state
.reading
= 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
);
35625 if (n
> 0) ret
= fromList(n
, state
);else ret
= null;
35627 if (ret
=== null) {
35628 state
.needReadable
= true;
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;
35639 // If we tried to read() past the EOF, then emit end on the next tick.
35640 if (nOrig
!== n
&& state
.ended
) endReadable(this);
35643 if (ret
!== null) this.emit('data', ret
);
35648 function 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
;
35657 state
.ended
= true;
35659 // emit 'readable' now to make sure it gets picked up.
35660 emitReadable(stream
);
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.
35666 function 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
);
35676 function emitReadable_(stream
) {
35677 debug('emit readable');
35678 stream
.emit('readable');
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.
35688 function maybeReadMore(stream
, state
) {
35689 if (!state
.readingMore
) {
35690 state
.readingMore
= true;
35691 processNextTick(maybeReadMore_
, stream
, state
);
35695 function 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');
35700 if (len
=== state
.length
)
35701 // didn't get any data, stop spinning.
35702 break;else len
= state
.length
;
35704 state
.readingMore
= false;
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.
35711 Readable
.prototype._read = function (n
) {
35712 this.emit('error', new Error('_read() is not implemented'));
35715 Readable
.prototype.pipe = function (dest
, pipeOpts
) {
35717 var state
= this._readableState
;
35719 switch (state
.pipesCount
) {
35721 state
.pipes
= dest
;
35724 state
.pipes
= [state
.pipes
, dest
];
35727 state
.pipes
.push(dest
);
35730 state
.pipesCount
+= 1;
35731 debug('pipe count=%d opts=%j', state
.pipesCount
, pipeOpts
);
35733 var doEnd
= (!pipeOpts
|| pipeOpts
.end
!== false) && dest
!== process
.stdout
&& dest
!== process
.stderr
;
35735 var endFn
= doEnd
? onend : unpipe
;
35736 if (state
.endEmitted
) processNextTick(endFn
);else src
.once('end', endFn
);
35738 dest
.on('unpipe', onunpipe
);
35739 function onunpipe(readable
, unpipeInfo
) {
35741 if (readable
=== src
) {
35742 if (unpipeInfo
&& unpipeInfo
.hasUnpiped
=== false) {
35743 unpipeInfo
.hasUnpiped
= true;
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
35758 var ondrain
= pipeOnDrain(src
);
35759 dest
.on('drain', ondrain
);
35761 var cleanedUp
= false;
35762 function 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
);
35776 // if the reader is waiting for a drain event from this
35777 // specific writer, then it would cause it to never start
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();
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
) {
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;
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
);
35813 dest
.removeListener('error', onerror
);
35814 if (EElistenerCount(dest
, 'error') === 0) dest
.emit('error', er
);
35817 // Make sure our error handler is attached before userland ones.
35818 prependListener(dest
, 'error', onerror
);
35820 // Both close and finish should trigger unpipe, but only once.
35821 function onclose() {
35822 dest
.removeListener('finish', onfinish
);
35825 dest
.once('close', onclose
);
35826 function onfinish() {
35828 dest
.removeListener('close', onclose
);
35831 dest
.once('finish', onfinish
);
35833 function unpipe() {
35838 // tell the dest that it's being piped to
35839 dest
.emit('pipe', src
);
35841 // start the flow if it hasn't been started already.
35842 if (!state
.flowing
) {
35843 debug('pipe resume');
35850 function 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;
35862 Readable
.prototype.unpipe = function (dest
) {
35863 var state
= this._readableState
;
35864 var unpipeInfo
= { hasUnpiped: false };
35866 // if we're not piping anywhere, then do nothing.
35867 if (state
.pipesCount
=== 0) return this;
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;
35874 if (!dest
) dest
= state
.pipes
;
35877 state
.pipes
= null;
35878 state
.pipesCount
= 0;
35879 state
.flowing
= false;
35880 if (dest
) dest
.emit('unpipe', this, unpipeInfo
);
35884 // slow case. multiple pipe destinations.
35888 var dests
= state
.pipes
;
35889 var len
= state
.pipesCount
;
35890 state
.pipes
= null;
35891 state
.pipesCount
= 0;
35892 state
.flowing
= false;
35894 for (var i
= 0; i
< len
; i
++) {
35895 dests
[i
].emit('unpipe', this, unpipeInfo
);
35899 // try to find the right one.
35900 var index
= indexOf(state
.pipes
, dest
);
35901 if (index
=== -1) return this;
35903 state
.pipes
.splice(index
, 1);
35904 state
.pipesCount
-= 1;
35905 if (state
.pipesCount
=== 1) state
.pipes
= state
.pipes
[0];
35907 dest
.emit('unpipe', this, unpipeInfo
);
35912 // set up data events if they are asked for
35913 // Ensure readable listeners eventually get something
35914 Readable
.prototype.on = function (ev
, fn
) {
35915 var res
= Stream
.prototype.on
.call(this, ev
, fn
);
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);
35935 Readable
.prototype.addListener
= Readable
.prototype.on
;
35937 function nReadingNextTick(self
) {
35938 debug('readable nexttick read 0');
35942 // pause() and resume() are remnants of the legacy readable stream API
35943 // If the user uses them, then switch into old mode.
35944 Readable
.prototype.resume = function () {
35945 var state
= this._readableState
;
35946 if (!state
.flowing
) {
35948 state
.flowing
= true;
35949 resume(this, state
);
35954 function resume(stream
, state
) {
35955 if (!state
.resumeScheduled
) {
35956 state
.resumeScheduled
= true;
35957 processNextTick(resume_
, stream
, state
);
35961 function resume_(stream
, state
) {
35962 if (!state
.reading
) {
35963 debug('resume read 0');
35967 state
.resumeScheduled
= false;
35968 state
.awaitDrain
= 0;
35969 stream
.emit('resume');
35971 if (state
.flowing
&& !state
.reading
) stream
.read(0);
35974 Readable
.prototype.pause = function () {
35975 debug('call pause flowing=%j', this._readableState
.flowing
);
35976 if (false !== this._readableState
.flowing
) {
35978 this._readableState
.flowing
= false;
35979 this.emit('pause');
35984 function flow(stream
) {
35985 var state
= stream
._readableState
;
35986 debug('flow', state
.flowing
);
35987 while (state
.flowing
&& stream
.read() !== null) {}
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.
35993 Readable
.prototype.wrap = function (stream
) {
35994 var state
= this._readableState
;
35995 var paused
= false;
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
);
36008 stream
.on('data', function (chunk
) {
36009 debug('wrapped data');
36010 if (state
.decoder
) chunk
= state
.decoder
.write(chunk
);
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;
36015 var ret
= self
.push(chunk
);
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
);
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
]));
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
);
36052 // exposed for testing purposes only.
36053 Readable
._fromList
= fromList
;
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.
36059 function fromList(n
, state
) {
36060 // nothing buffered
36061 if (state
.length
=== 0) return null;
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();
36069 // read part of list
36070 ret
= fromListPartial(n
, state
.buffer
, state
.decoder
);
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.
36079 function fromListPartial(n
, list
, hasStrings
) {
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();
36089 // result spans more than one buffer
36090 ret
= hasStrings
? copyFromBufferString(n
, list
) : copyFromBuffer(n
, list
);
36095 // Copies a specified amount of characters from the list of buffered data
36097 // This function is designed to be inlinable, so please take care when making
36098 // changes to the function body.
36099 function copyFromBufferString(n
, list
) {
36104 while (p
= p
.next
) {
36106 var nb
= n
> str
.length
? str
.length : n
;
36107 if (nb
=== str
.length
) ret
+= str
;else ret
+= str
.slice(0, n
);
36110 if (nb
=== str
.length
) {
36112 if (p
.next
) list
.head
= p
.next
;else list
.head
= list
.tail
= null;
36115 p
.data
= str
.slice(nb
);
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.
36128 function copyFromBuffer(n
, list
) {
36129 var ret
= Buffer
.allocUnsafe(n
);
36133 n
-= p
.data
.length
;
36134 while (p
= p
.next
) {
36136 var nb
= n
> buf
.length
? buf
.length : n
;
36137 buf
.copy(ret
, ret
.length
- n
, 0, nb
);
36140 if (nb
=== buf
.length
) {
36142 if (p
.next
) list
.head
= p
.next
;else list
.head
= list
.tail
= null;
36145 p
.data
= buf
.slice(nb
);
36155 function endReadable(stream
) {
36156 var state
= stream
._readableState
;
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');
36162 if (!state
.endEmitted
) {
36163 state
.ended
= true;
36164 processNextTick(endReadableNT
, state
, stream
);
36168 function 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');
36177 function forEach(xs
, f
) {
36178 for (var i
= 0, l
= xs
.length
; i
< l
; i
++) {
36183 function indexOf(xs
, x
) {
36184 for (var i
= 0, l
= xs
.length
; i
< l
; i
++) {
36185 if (xs
[i
] === x
) return i
;
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.
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:
36201 // The above copyright notice and this permission notice shall be included
36202 // in all copies or substantial portions of the Software.
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.
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.)
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.
36223 // Here's how this works:
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.
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.
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.
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.
36256 module
.exports
= Transform
;
36258 var Duplex
= require('./_stream_duplex');
36261 var util
= require('core-util-is');
36262 util
.inherits
= require('inherits');
36265 util.inherits(Transform, Duplex);
36267 function TransformState(stream) {
36268 this.afterTransform = function (er, data) {
36269 return afterTransform(stream, er, data);
36272 this.needTransform = false;
36273 this.transforming = false;
36274 this.writecb = null;
36275 this.writechunk = null;
36276 this.writeencoding = null;
36279 function afterTransform(stream, er, data) {
36280 var ts = stream._transformState;
36281 ts.transforming = false;
36283 var cb = ts.writecb;
36286 return stream.emit('error', new Error('write callback called multiple times'));
36289 ts.writechunk = null;
36292 if (data !== null && data !== undefined) stream.push(data);
36296 var rs = stream._readableState;
36297 rs.reading = false;
36298 if (rs.needReadable || rs.length < rs.highWaterMark) {
36299 stream._read(rs.highWaterMark);
36303 function Transform(options) {
36304 if (!(this instanceof Transform)) return new Transform(options);
36306 Duplex.call(this, options);
36308 this._transformState = new TransformState(this);
36312 // start out asking for a readable event once data is transformed.
36313 this._readableState.needReadable = true;
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;
36321 if (typeof options.transform === 'function') this._transform = options.transform;
36323 if (typeof options.flush === 'function') this._flush = options.flush;
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);
36334 Transform.prototype.push = function (chunk, encoding) {
36335 this._transformState.needTransform = false;
36336 return Duplex.prototype.push.call(this, chunk, encoding);
36339 // This is the part where you do stuff!
36340 // override this function in implementation classes.
36341 // 'chunk' is an input chunk.
36343 // Call `push(newChunk)` to pass along transformed output
36344 // to the readable side. You may call 'push' zero or more times.
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.
36349 Transform.prototype._transform = function (chunk, encoding, cb) {
36350 throw new Error('_transform() is not implemented');
36353 Transform.prototype._write = function (chunk, encoding, cb) {
36354 var ts = this._transformState;
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);
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.
36367 Transform.prototype._read = function (n) {
36368 var ts = this._transformState;
36370 if (ts.writechunk !== null && ts.writecb && !ts.transforming) {
36371 ts.transforming = true;
36372 this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform);
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;
36380 Transform.prototype._destroy = function (err, cb) {
36383 Duplex.prototype._destroy.call(this, err, function (err2) {
36385 _this.emit('close');
36389 function done(stream, er, data) {
36390 if (er) return stream.emit('error', er);
36392 if (data !== null && data !== undefined) stream.push(data);
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;
36399 if (ws.length) throw new Error('Calling transform done when ws.length != 0');
36401 if (ts.transforming) throw new Error('Calling transform done when still transforming');
36403 return stream.push(null);
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.
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:
36417 // The above copyright notice and this permission notice shall be included
36418 // in all copies or substantial portions of the Software.
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.
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.
36436 var processNextTick
= require('process-nextick-args');
36439 module.exports = Writable;
36441 /* <replacement> */
36442 function WriteReq(chunk
, encoding
, cb
) {
36443 this.chunk
= chunk
;
36444 this.encoding
= encoding
;
36445 this.callback
= cb
;
36449 // It seems a linked list but it is not
36450 // there will be only 2 of these for each stream
36451 function CorkedRequest(state
) {
36456 this.finish = function () {
36457 onCorkedFinish(_this
, state
);
36460 /* </replacement> */
36463 var asyncWrite
= !process
.browser
&& ['v0.10', 'v0.9.'].indexOf(process
.version
.slice(0, 5)) > -1 ? setImmediate : processNextTick
;
36470 Writable.WritableState = WritableState;
36473 var util
= require('core-util-is');
36474 util
.inherits
= require('inherits');
36478 var internalUtil
= {
36479 deprecate: require('util-deprecate')
36484 var Stream
= require('./internal/streams/stream');
36488 var Buffer
= require('safe-buffer').Buffer
;
36489 var OurUint8Array
= global
.Uint8Array
|| function () {};
36490 function _uint8ArrayToBuffer(chunk
) {
36491 return Buffer
.from(chunk
);
36493 function _isUint8Array(obj
) {
36494 return Buffer
.isBuffer(obj
) || obj
instanceof OurUint8Array
;
36498 var destroyImpl = require('./internal/streams/destroy');
36500 util.inherits(Writable, Stream);
36504 function WritableState(options, stream) {
36505 Duplex = Duplex || require('./_stream_duplex');
36507 options = options || {};
36509 // object stream flag to indicate whether or not this stream
36510 // contains buffers or objects.
36511 this.objectMode = !!options.objectMode;
36513 if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode;
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;
36523 this.highWaterMark = Math.floor(this.highWaterMark);
36525 // if _final has been called
36526 this.finalCalled = false;
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;
36537 // has it been destroyed
36538 this.destroyed = false;
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;
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';
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
36556 // a flag to see when we're in the middle of a write.
36557 this.writing = false;
36559 // when true all writes will be buffered until .uncork() call
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.
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;
36573 // the callback that's passed to _write(chunk,cb)
36574 this.onwrite = function (er) {
36575 onwrite(stream, er);
36578 // the callback that the user supplies to write(chunk,encoding,cb)
36579 this.writecb = null;
36581 // the amount that is being written when _write is called.
36584 this.bufferedRequest = null;
36585 this.lastBufferedRequest = null;
36587 // number of pending user-supplied write callbacks
36588 // this must be 0 before 'finish' can be emitted
36589 this.pendingcb = 0;
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;
36595 // True if the error was already emitted and should not be thrown again
36596 this.errorEmitted = false;
36598 // count buffered requests
36599 this.bufferedRequestCount = 0;
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);
36606 WritableState.prototype.getBuffer = function getBuffer() {
36607 var current = this.bufferedRequest;
36611 current = current.next;
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')
36626 // Test _writableState for inheritance to account for Duplex streams,
36627 // whose prototype chain only points to Readable.
36628 var realHasInstance;
36629 if (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;
36635 return object && object._writableState instanceof WritableState;
36639 realHasInstance = function (object) {
36640 return object instanceof this;
36644 function Writable(options) {
36645 Duplex = Duplex || require('./_stream_duplex');
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.
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);
36658 this._writableState = new WritableState(options, this);
36661 this.writable = true;
36664 if (typeof options.write === 'function') this._write = options.write;
36666 if (typeof options.writev === 'function') this._writev = options.writev;
36668 if (typeof options.destroy === 'function') this._destroy = options.destroy;
36670 if (typeof options.final === 'function') this._final = options.final;
36676 // Otherwise people can pipe Writable streams, which is just wrong.
36677 Writable.prototype.pipe = function () {
36678 this.emit('error', new Error('Cannot pipe, not readable'));
36681 function 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);
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.
36691 function validChunk(stream, state, chunk, cb) {
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');
36701 stream.emit('error', er);
36702 processNextTick(cb, er);
36708 Writable.prototype.write = function (chunk, encoding, cb) {
36709 var state = this._writableState;
36711 var isBuf = _isUint8Array(chunk) && !state.objectMode;
36713 if (isBuf && !Buffer.isBuffer(chunk)) {
36714 chunk = _uint8ArrayToBuffer(chunk);
36717 if (typeof encoding === 'function') {
36722 if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding;
36724 if (typeof cb !== 'function') cb = nop;
36726 if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) {
36728 ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb);
36734 Writable.prototype.cork = function () {
36735 var state = this._writableState;
36740 Writable.prototype.uncork = function () {
36741 var state = this._writableState;
36743 if (state.corked) {
36746 if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state);
36750 Writable.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;
36758 function decodeChunk(state, chunk, encoding) {
36759 if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') {
36760 chunk = Buffer.from(chunk, encoding);
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.
36768 function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) {
36770 var newChunk = decodeChunk(state, chunk, encoding);
36771 if (chunk !== newChunk) {
36773 encoding = 'buffer';
36777 var len = state.objectMode ? 1 : chunk.length;
36779 state.length += len;
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;
36785 if (state.writing || state.corked) {
36786 var last = state.lastBufferedRequest;
36787 state.lastBufferedRequest = {
36789 encoding: encoding,
36795 last.next = state.lastBufferedRequest;
36797 state.bufferedRequest = state.lastBufferedRequest;
36799 state.bufferedRequestCount += 1;
36801 doWrite(stream, state, false, len, chunk, encoding, cb);
36807 function doWrite(stream, state, writev, len, chunk, encoding, cb) {
36808 state.writelen = len;
36809 state.writecb = cb;
36810 state.writing = true;
36812 if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite);
36813 state.sync = false;
36816 function onwriteError(stream, state, sync, er, cb) {
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
36825 processNextTick(finishMaybe, stream, state);
36826 stream._writableState.errorEmitted = true;
36827 stream.emit('error', er);
36829 // the caller expect this to happen before if
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);
36840 function onwriteStateUpdate(state) {
36841 state.writing = false;
36842 state.writecb = null;
36843 state.length -= state.writelen;
36844 state.writelen = 0;
36847 function onwrite(stream, er) {
36848 var state = stream._writableState;
36849 var sync = state.sync;
36850 var cb = state.writecb;
36852 onwriteStateUpdate(state);
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);
36858 if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) {
36859 clearBuffer(stream, state);
36864 asyncWrite(afterWrite
, stream
, state
, finished
, cb
);
36867 afterWrite(stream, state, finished, cb);
36872 function afterWrite(stream, state, finished, cb) {
36873 if (!finished) onwriteDrain(stream, state);
36876 finishMaybe(stream, state);
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.
36882 function onwriteDrain(stream, state) {
36883 if (state.length === 0 && state.needDrain) {
36884 state.needDrain = false;
36885 stream.emit('drain');
36889 // if there's something in the buffer waiting, then process it
36890 function clearBuffer(stream, state) {
36891 state.bufferProcessing = true;
36892 var entry = state.bufferedRequest;
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;
36902 var allBuffers = true;
36904 buffer[count] = entry;
36905 if (!entry.isBuf) allBuffers = false;
36906 entry = entry.next;
36909 buffer.allBuffers = allBuffers;
36911 doWrite(stream, state, true, state.length, buffer, '', holder.finish);
36913 // doWrite is almost always async, defer these to save a bit of time
36914 // as the hot path ends with doWrite
36916 state.lastBufferedRequest = null;
36918 state.corkedRequestsFree = holder.next;
36919 holder.next = null;
36921 state.corkedRequestsFree = new CorkedRequest(state);
36924 // Slow case, write chunks one-by-one
36926 var chunk = entry.chunk;
36927 var encoding = entry.encoding;
36928 var cb = entry.callback;
36929 var len = state.objectMode ? 1 : chunk.length;
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) {
36942 if (entry === null) state.lastBufferedRequest = null;
36945 state.bufferedRequestCount = 0;
36946 state.bufferedRequest = entry;
36947 state.bufferProcessing = false;
36950 Writable.prototype._write = function (chunk, encoding, cb) {
36951 cb(new Error('_write() is not implemented'));
36954 Writable.prototype._writev = null;
36956 Writable.prototype.end = function (chunk, encoding, cb) {
36957 var state = this._writableState;
36959 if (typeof chunk === 'function') {
36963 } else if (typeof encoding === 'function') {
36968 if (chunk !== null && chunk !== undefined) this.write(chunk, encoding);
36970 // .end() fully uncorks
36971 if (state.corked) {
36976 // ignore unnecessary end() calls.
36977 if (!state.ending && !state.finished) endWritable(this, state, cb);
36980 function needFinish(state) {
36981 return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing;
36983 function callFinal(stream, state) {
36984 stream._final(function (err) {
36987 stream.emit('error', err);
36989 state.prefinished = true;
36990 stream.emit('prefinish');
36991 finishMaybe(stream, state);
36994 function prefinish(stream, state) {
36995 if (!state.prefinished && !state.finalCalled) {
36996 if (typeof stream._final === 'function') {
36998 state.finalCalled = true;
36999 processNextTick(callFinal, stream, state);
37001 state.prefinished = true;
37002 stream.emit('prefinish');
37007 function finishMaybe(stream, state) {
37008 var need = needFinish(state);
37010 prefinish(stream, state);
37011 if (state.pendingcb === 0) {
37012 state.finished = true;
37013 stream.emit('finish');
37019 function endWritable(stream, state, cb) {
37020 state.ending = true;
37021 finishMaybe(stream, state);
37023 if (state.finished) processNextTick(cb);else stream.once('finish', cb);
37025 state.ended = true;
37026 stream.writable = false;
37029 function onCorkedFinish(corkReq, state, err) {
37030 var entry = corkReq.entry;
37031 corkReq.entry = null;
37033 var cb = entry.callback;
37036 entry = entry.next;
37038 if (state.corkedRequestsFree) {
37039 state.corkedRequestsFree.next = corkReq;
37041 state.corkedRequestsFree = corkReq;
37045 Object.defineProperty(Writable.prototype, 'destroyed', {
37047 if (this._writableState === undefined) {
37050 return this._writableState.destroyed;
37052 set: function (value) {
37053 // we ignore the value if the stream
37054 // has not been initialized yet
37055 if (!this._writableState) {
37059 // backward compatibility, the user is explicitly
37060 // managing destroyed
37061 this._writableState.destroyed = value;
37065 Writable.prototype.destroy = destroyImpl.destroy;
37066 Writable.prototype._undestroy = destroyImpl.undestroy;
37067 Writable.prototype._destroy = function (err, cb) {
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){
37077 function _classCallCheck(instance
, Constructor
) { if (!(instance
instanceof Constructor
)) { throw new TypeError("Cannot call a class as a function"); } }
37079 var Buffer
= require('safe-buffer').Buffer
;
37082 function copyBuffer(src, target, offset) {
37083 src.copy(target, offset);
37086 module.exports = function () {
37087 function BufferList() {
37088 _classCallCheck(this, BufferList);
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;
37102 BufferList.prototype.unshift = function unshift(v) {
37103 var entry = { data: v, next: this.head };
37104 if (this.length === 0) this.tail = entry;
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;
37117 BufferList.prototype.clear = function clear() {
37118 this.head = this.tail = null;
37122 BufferList.prototype.join = function join(s) {
37123 if (this.length === 0) return '';
37125 var ret = '' + p.data;
37126 while (p = p.next) {
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);
37138 copyBuffer(p.data, ret, i);
37139 i += p.data.length;
37147 },{"safe-buffer":247}],240:[function(require,module,exports){
37152 var processNextTick
= require('process-nextick-args');
37155 // undocumented cb() API, needed for core, not for public API
37156 function destroy(err, cb) {
37159 var readableDestroyed = this._readableState && this._readableState.destroyed;
37160 var writableDestroyed = this._writableState && this._writableState.destroyed;
37162 if (readableDestroyed || writableDestroyed) {
37165 } else if (err && (!this._writableState || !this._writableState.errorEmitted)) {
37166 processNextTick(emitErrorNT, this, err);
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
37174 if (this._readableState) {
37175 this._readableState.destroyed = true;
37178 // if this is a duplex stream mark the writable part as destroyed as well
37179 if (this._writableState) {
37180 this._writableState.destroyed = true;
37183 this._destroy(err || null, function (err) {
37185 processNextTick(emitErrorNT, _this, err);
37186 if (_this._writableState) {
37187 _this._writableState.errorEmitted = true;
37195 function 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;
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;
37212 function emitErrorNT(self, err) {
37213 self.emit('error', err);
37218 undestroy: undestroy
37220 },{"process-nextick-args":189}],241:[function(require,module,exports){
37221 module.exports = require('events').EventEmitter;
37223 },{"events":143}],242:[function(require,module,exports){
37224 module.exports = require('./readable').PassThrough
37226 },{"./readable":243}],243:[function(require,module,exports){
37227 exports = module.exports = require('./lib/_stream_readable.js');
37228 exports.Stream = exports;
37229 exports.Readable = exports;
37230 exports.Writable = require('./lib/_stream_writable.js');
37231 exports.Duplex = require('./lib/_stream_duplex.js');
37232 exports.Transform = require('./lib/_stream_transform.js');
37233 exports.PassThrough = require('./lib/_stream_passthrough.js');
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){
37236 module.exports = require('./readable').Transform
37238 },{"./readable":243}],245:[function(require,module,exports){
37239 module.exports = require('./lib/_stream_writable.js');
37241 },{"./lib/_stream_writable.js":238}],246:[function(require,module,exports){
37242 (function (Buffer){
37244 var inherits = require('inherits')
37245 var HashBase = require('hash-base')
37247 function RIPEMD160 () {
37248 HashBase.call(this, 64)
37251 this._a = 0x67452301
37252 this._b = 0xefcdab89
37253 this._c = 0x98badcfe
37254 this._d = 0x10325476
37255 this._e = 0xc3d2e1f0
37258 inherits(RIPEMD160, HashBase)
37260 RIPEMD160.prototype._update = function () {
37261 var m = new Array(16)
37262 for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4)
37270 // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15
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)
37290 // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8
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)
37310 // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12
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)
37330 // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2
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)
37350 // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13
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)
37376 // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12
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)
37396 // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2
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)
37416 // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13
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)
37436 // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14
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)
37456 // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11
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)
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
37485 RIPEMD160.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)
37491 this._blockOffset = 0
37494 this._block.fill(0, this._blockOffset, 56)
37495 this._block.writeUInt32LE(this._length[0], 56)
37496 this._block.writeUInt32LE(this._length[1], 60)
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)
37509 function rotl (x, n) {
37510 return (x << n) | (x >>> (32 - n))
37513 function fn1 (a, b, c, d, e, m, k, s) {
37514 return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0
37517 function fn2 (a, b, c, d, e, m, k, s) {
37518 return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0
37521 function fn3 (a, b, c, d, e, m, k, s) {
37522 return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0
37525 function fn4 (a, b, c, d, e, m, k, s) {
37526 return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0
37529 function fn5 (a, b, c, d, e, m, k, s) {
37530 return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0
37533 module.exports = RIPEMD160
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 */
37538 var buffer
= require('buffer')
37539 var Buffer
= buffer
.Buffer
37541 // alternative to using Object.keys for old browsers
37542 function copyProps (src
, dst
) {
37543 for (var key
in src
) {
37544 dst
[key
] = src
[key
]
37547 if (Buffer
.from && Buffer
.alloc
&& Buffer
.allocUnsafe
&& Buffer
.allocUnsafeSlow
) {
37548 module
.exports
= buffer
37550 // Copy properties from require('buffer')
37551 copyProps(buffer
, exports
)
37552 exports
.Buffer
= SafeBuffer
37555 function SafeBuffer (arg
, encodingOrOffset
, length
) {
37556 return Buffer(arg
, encodingOrOffset
, length
)
37559 // Copy static methods from Buffer
37560 copyProps(Buffer
, SafeBuffer
)
37562 SafeBuffer
.from = function (arg
, encodingOrOffset
, length
) {
37563 if (typeof arg
=== 'number') {
37564 throw new TypeError('Argument must not be a number')
37566 return Buffer(arg
, encodingOrOffset
, length
)
37569 SafeBuffer
.alloc = function (size
, fill
, encoding
) {
37570 if (typeof size
!== 'number') {
37571 throw new TypeError('Argument must be a number')
37573 var buf
= Buffer(size
)
37574 if (fill
!== undefined) {
37575 if (typeof encoding
=== 'string') {
37576 buf
.fill(fill
, encoding
)
37586 SafeBuffer
.allocUnsafe = function (size
) {
37587 if (typeof size
!== 'number') {
37588 throw new TypeError('Argument must be a number')
37590 return Buffer(size
)
37593 SafeBuffer
.allocUnsafeSlow = function (size
) {
37594 if (typeof size
!== 'number') {
37595 throw new TypeError('Argument must be a number')
37597 return buffer
.SlowBuffer(size
)
37600 },{"buffer":107}],248:[function(require
,module
,exports
){
37601 (function (Buffer
){
37602 var crypto
= require('crypto')
37603 /* eslint-disable camelcase */
37605 var MAX_VALUE
= 0x7fffffff
37607 // N = Cpu cost, r = Memory cost, p = parallelization cost
37608 function 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')
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')
37614 var XY
= new Buffer(256 * r
)
37615 var V
= new Buffer(128 * r
* N
)
37618 var B32
= new Int32Array(16) // salsa20_8
37619 var x
= new Int32Array(16) // salsa20_8
37620 var _X
= new Buffer(64) // blockmix_salsa8
37623 var B
= crypto
.pbkdf2Sync(key
, salt
, 1, p
* 128 * r
, 'sha256')
37626 if (progressCallback
) {
37627 var totalOps
= p
* N
* 2
37630 tickCallback = function () {
37633 // send progress notifications once every 1,000 ops
37634 if (currentOp
% 1000 === 0) {
37636 current: currentOp
,
37638 percent: (currentOp
/ totalOps
) * 100.0
37644 for (var i
= 0; i
< p
; i
++) {
37645 smix(B
, i
* 128 * r
, r
, N
, V
, XY
)
37648 return crypto
.pbkdf2Sync(key
, B
, 1, dkLen
, 'sha256')
37650 // all of these functions are actually moved to the top
37651 // due to function hoisting
37653 function smix (B
, Bi
, r
, N
, V
, XY
) {
37658 B
.copy(XY
, Xi
, Bi
, Bi
+ Yi
)
37660 for (i
= 0; i
< N
; i
++) {
37661 XY
.copy(V
, i
* Yi
, Xi
, Xi
+ Yi
)
37662 blockmix_salsa8(XY
, Xi
, Yi
, r
)
37664 if (tickCallback
) tickCallback()
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
)
37673 if (tickCallback
) tickCallback()
37676 XY
.copy(B
, Bi
, Xi
, Xi
+ Yi
)
37679 function blockmix_salsa8 (BY
, Bi
, Yi
, r
) {
37682 arraycopy(BY
, Bi
+ (2 * r
- 1) * 64, _X
, 0, 64)
37684 for (i
= 0; i
< 2 * r
; i
++) {
37685 blockxor(BY
, i
* 64, _X
, 0, 64)
37687 arraycopy(_X
, 0, BY
, Yi
+ (i
* 64), 64)
37690 for (i
= 0; i
< r
; i
++) {
37691 arraycopy(BY
, Yi
+ (i
* 2) * 64, BY
, Bi
+ (i
* 64), 64)
37694 for (i
= 0; i
< r
; i
++) {
37695 arraycopy(BY
, Yi
+ (i
* 2 + 1) * 64, BY
, Bi
+ (i
+ r
) * 64, 64)
37699 function R (a
, b
) {
37700 return (a
<< b
) | (a
>>> (32 - b
))
37703 function salsa20_8 (B
) {
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
37714 arraycopy(B32
, 0, x
, 0, 16)
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)
37751 for (i
= 0; i
< 16; ++i
) B32
[i
] = x
[i
] + B32
[i
]
37753 for (i
= 0; i
< 16; i
++) {
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
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
]
37771 function arraycopy (src
, srcPos
, dest
, destPos
, length
) {
37772 if (Buffer
.isBuffer(src
) && Buffer
.isBuffer(dest
)) {
37773 src
.copy(dest
, destPos
, srcPos
, srcPos
+ length
)
37776 dest
[destPos
++] = src
[srcPos
++]
37781 module
.exports
= scrypt
37783 }).call(this,require("buffer").Buffer
)
37784 },{"buffer":107,"crypto":116}],249:[function(require
,module
,exports
){
37786 module
.exports
= require('./lib')(require('./lib/elliptic'))
37788 },{"./lib":253,"./lib/elliptic":252}],250:[function(require
,module
,exports
){
37789 (function (Buffer
){
37791 var toString
= Object
.prototype.toString
37794 exports
.isArray = function (value
, message
) {
37795 if (!Array
.isArray(value
)) throw TypeError(message
)
37798 exports
.isBoolean = function (value
, message
) {
37799 if (toString
.call(value
) !== '[object Boolean]') throw TypeError(message
)
37802 exports
.isBuffer = function (value
, message
) {
37803 if (!Buffer
.isBuffer(value
)) throw TypeError(message
)
37806 exports
.isFunction = function (value
, message
) {
37807 if (toString
.call(value
) !== '[object Function]') throw TypeError(message
)
37810 exports
.isNumber = function (value
, message
) {
37811 if (toString
.call(value
) !== '[object Number]') throw TypeError(message
)
37814 exports
.isObject = function (value
, message
) {
37815 if (toString
.call(value
) !== '[object Object]') throw TypeError(message
)
37819 exports
.isBufferLength = function (buffer
, length
, message
) {
37820 if (buffer
.length
!== length
) throw RangeError(message
)
37823 exports
.isBufferLength2 = function (buffer
, length1
, length2
, message
) {
37824 if (buffer
.length
!== length1
&& buffer
.length
!== length2
) throw RangeError(message
)
37827 exports
.isLengthGTZero = function (value
, message
) {
37828 if (value
.length
=== 0) throw RangeError(message
)
37831 exports
.isNumberInInterval = function (number
, x
, y
, message
) {
37832 if (number
<= x
|| number
>= y
) throw RangeError(message
)
37835 }).call(this,{"isBuffer":require("../../is-buffer/index.js")})
37836 },{"../../is-buffer/index.js":164}],251:[function(require
,module
,exports
){
37838 var Buffer
= require('safe-buffer').Buffer
37839 var bip66
= require('bip66')
37841 var EC_PRIVKEY_EXPORT_DER_COMPRESSED
= Buffer
.from([
37843 0x30, 0x81, 0xd3, 0x02, 0x01, 0x01, 0x04, 0x20,
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,
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,
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,
37863 var EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED
= Buffer
.from([
37865 0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20,
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,
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,
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,
37889 exports
.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)
37896 exports
.privateKeyImport = function (privateKey
) {
37897 var length
= privateKey
.length
37901 if (length
< index
+ 1 || privateKey
[index
] !== 0x30) return
37904 // sequence length constructor
37905 if (length
< index
+ 1 || !(privateKey
[index
] & 0x80)) return
37907 var lenb
= privateKey
[index
] & 0x7f
37909 if (lenb
< 1 || lenb
> 2) return
37910 if (length
< index
+ lenb
) return
37913 var len
= privateKey
[index
+ lenb
- 1] | (lenb
> 1 ? privateKey
[index
+ lenb
- 2] << 8 : 0)
37915 if (length
< index
+ len
) return
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) {
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]) {
37934 return privateKey
.slice(index
+ 2, index
+ 2 + privateKey
[index
+ 1])
37937 exports
.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
);
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
);
37944 return bip66
.encode(r
.slice(posR
), s
.slice(posS
))
37947 exports
.signatureImport = function (sig
) {
37948 var r
= Buffer
.alloc(32, 0)
37949 var s
= Buffer
.alloc(32, 0)
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')
37961 sigObj
.r
.copy(r
, 32 - sigObj
.r
.length
)
37962 sigObj
.s
.copy(s
, 32 - sigObj
.s
.length
)
37964 return { r: r
, s: s
}
37967 exports
.signatureImportLax = function (sig
) {
37968 var r
= Buffer
.alloc(32, 0)
37969 var s
= Buffer
.alloc(32, 0)
37971 var length
= sig
.length
37974 // sequence tag byte
37975 if (sig
[index
++] !== 0x30) return
37977 // sequence length byte
37978 var lenbyte
= sig
[index
++]
37979 if (lenbyte
& 0x80) {
37980 index
+= lenbyte
- 0x80
37981 if (index
> length
) return
37984 // sequence tag byte for r
37985 if (sig
[index
++] !== 0x02) return
37988 var rlen
= sig
[index
++]
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
]
37995 if (rlen
> length
- index
) return
37999 // sequence tag byte for s
38000 if (sig
[index
++] !== 0x02) return
38003 var slen
= sig
[index
++]
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
]
38010 if (slen
> length
- index
) return
38014 // ignore leading zeros in r
38015 for (; rlen
> 0 && sig
[rindex
] === 0x00; rlen
-= 1, rindex
+= 1);
38017 if (rlen
> 32) return
38018 var rvalue
= sig
.slice(rindex
, rindex
+ rlen
)
38019 rvalue
.copy(r
, 32 - rvalue
.length
)
38021 // ignore leading zeros in s
38022 for (; slen
> 0 && sig
[sindex
] === 0x00; slen
-= 1, sindex
+= 1);
38024 if (slen
> 32) return
38025 var svalue
= sig
.slice(sindex
, sindex
+ slen
)
38026 svalue
.copy(s
, 32 - svalue
.length
)
38028 return { r: r
, s: s
}
38031 },{"bip66":74,"safe-buffer":247}],252:[function(require
,module
,exports
){
38033 var Buffer
= require('safe-buffer').Buffer
38034 var createHash
= require('create-hash')
38035 var BN
= require('bn.js')
38036 var EC
= require('elliptic').ec
38038 var messages
= require('../messages.json')
38040 var ec
= new EC('secp256k1')
38041 var ecparams
= ec
.curve
38043 function loadCompressedPublicKey (first
, xBuffer
) {
38044 var x
= new BN(xBuffer
)
38047 if (x
.cmp(ecparams
.p
) >= 0) return null
38048 x
= x
.toRed(ecparams
.red
)
38050 // compute corresponding Y
38051 var y
= x
.redSqr().redIMul(x
).redIAdd(ecparams
.b
).redSqrt()
38052 if ((first
=== 0x03) !== y
.isOdd()) y
= y
.redNeg()
38054 return ec
.keyPair({ pub: { x: x
, y: y
} })
38057 function loadUncompressedPublicKey (first
, xBuffer
, yBuffer
) {
38058 var x
= new BN(xBuffer
)
38059 var y
= new BN(yBuffer
)
38062 if (x
.cmp(ecparams
.p
) >= 0 || y
.cmp(ecparams
.p
) >= 0) return null
38064 x
= x
.toRed(ecparams
.red
)
38065 y
= y
.toRed(ecparams
.red
)
38068 if ((first
=== 0x06 || first
=== 0x07) && y
.isOdd() !== (first
=== 0x07)) return null
38071 var x3
= x
.redSqr().redIMul(x
)
38072 if (!y
.redSqr().redISub(x3
.redIAdd(ecparams
.b
)).isZero()) return null
38074 return ec
.keyPair({ pub: { x: x
, y: y
} })
38077 function loadPublicKey (publicKey
) {
38078 var first
= publicKey
[0]
38082 if (publicKey
.length
!== 33) return null
38083 return loadCompressedPublicKey(first
, publicKey
.slice(1, 33))
38087 if (publicKey
.length
!== 65) return null
38088 return loadUncompressedPublicKey(first
, publicKey
.slice(1, 33), publicKey
.slice(33, 65))
38094 exports
.privateKeyVerify = function (privateKey
) {
38095 var bn
= new BN(privateKey
)
38096 return bn
.cmp(ecparams
.n
) < 0 && !bn
.isZero()
38099 exports
.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
)
38103 return Buffer
.from(ec
.keyFromPrivate(privateKey
).getPublic(compressed
, true))
38106 exports
.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)
38111 exports
.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
)
38115 return bn
.invm(ecparams
.n
).toArrayLike(Buffer
, 'be', 32)
38118 exports
.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
)
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
)
38126 return bn
.toArrayLike(Buffer
, 'be', 32)
38129 exports
.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
)
38133 bn
.imul(new BN(privateKey
))
38134 if (bn
.cmp(ecparams
.n
)) bn
= bn
.umod(ecparams
.n
)
38136 return bn
.toArrayLike(Buffer
, 'be', 32)
38139 exports
.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
)
38143 return Buffer
.from(ec
.keyFromPrivate(privateKey
).getPublic(compressed
, true))
38146 exports
.publicKeyConvert = function (publicKey
, compressed
) {
38147 var pair
= loadPublicKey(publicKey
)
38148 if (pair
=== null) throw new Error(messages
.EC_PUBLIC_KEY_PARSE_FAIL
)
38150 return Buffer
.from(pair
.getPublic(compressed
, true))
38153 exports
.publicKeyVerify = function (publicKey
) {
38154 return loadPublicKey(publicKey
) !== null
38157 exports
.publicKeyTweakAdd = function (publicKey
, tweak
, compressed
) {
38158 var pair
= loadPublicKey(publicKey
)
38159 if (pair
=== null) throw new Error(messages
.EC_PUBLIC_KEY_PARSE_FAIL
)
38161 tweak
= new BN(tweak
)
38162 if (tweak
.cmp(ecparams
.n
) >= 0) throw new Error(messages
.EC_PUBLIC_KEY_TWEAK_ADD_FAIL
)
38164 return Buffer
.from(ecparams
.g
.mul(tweak
).add(pair
.pub
).encode(true, compressed
))
38167 exports
.publicKeyTweakMul = function (publicKey
, tweak
, compressed
) {
38168 var pair
= loadPublicKey(publicKey
)
38169 if (pair
=== null) throw new Error(messages
.EC_PUBLIC_KEY_PARSE_FAIL
)
38171 tweak
= new BN(tweak
)
38172 if (tweak
.cmp(ecparams
.n
) >= 0 || tweak
.isZero()) throw new Error(messages
.EC_PUBLIC_KEY_TWEAK_MUL_FAIL
)
38174 return Buffer
.from(pair
.pub
.mul(tweak
).encode(true, compressed
))
38177 exports
.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
)
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
)
38188 return Buffer
.from(point
.encode(true, compressed
))
38191 exports
.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
)
38196 var result
= Buffer
.from(signature
)
38197 if (s
.cmp(ec
.nh
) === 1) ecparams
.n
.sub(s
).toArrayLike(Buffer
, 'be', 32).copy(result
, 32)
38202 exports
.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
)
38207 return { r: r
, s: s
}
38210 exports
.signatureImport = function (sigObj
) {
38211 var r
= new BN(sigObj
.r
)
38212 if (r
.cmp(ecparams
.n
) >= 0) r
= new BN(0)
38214 var s
= new BN(sigObj
.s
)
38215 if (s
.cmp(ecparams
.n
) >= 0) s
= new BN(0)
38217 return Buffer
.concat([
38218 r
.toArrayLike(Buffer
, 'be', 32),
38219 s
.toArrayLike(Buffer
, 'be', 32)
38223 exports
.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
)
38230 return new BN(nonce
)
38234 var d
= new BN(privateKey
)
38235 if (d
.cmp(ecparams
.n
) >= 0 || d
.isZero()) throw new Error(messages
.ECDSA_SIGN_FAIL
)
38237 var result
= ec
.sign(message
, privateKey
, { canonical: true, k: noncefn
, pers: data
})
38239 signature: Buffer
.concat([
38240 result
.r
.toArrayLike(Buffer
, 'be', 32),
38241 result
.s
.toArrayLike(Buffer
, 'be', 32)
38243 recovery: result
.recoveryParam
38247 exports
.verify = function (message
, signature
, publicKey
) {
38248 var sigObj
= {r: signature
.slice(0, 32), s: signature
.slice(32, 64)}
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
38255 var pair
= loadPublicKey(publicKey
)
38256 if (pair
=== null) throw new Error(messages
.EC_PUBLIC_KEY_PARSE_FAIL
)
38258 return ec
.verify(message
, sigObj
, {x: pair
.pub
.x
, y: pair
.pub
.y
})
38261 exports
.recover = function (message
, signature
, recovery
, compressed
) {
38262 var sigObj
= {r: signature
.slice(0, 32), s: signature
.slice(32, 64)}
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
)
38269 if (sigr
.isZero() || sigs
.isZero()) throw new Error()
38271 var point
= ec
.recoverPubKey(message
, sigObj
, recovery
)
38272 return Buffer
.from(point
.encode(true, compressed
))
38274 throw new Error(messages
.ECDSA_RECOVER_FAIL
)
38278 exports
.ecdh = function (publicKey
, privateKey
) {
38279 var shared
= exports
.ecdhUnsafe(publicKey
, privateKey
, true)
38280 return createHash('sha256').update(shared
).digest()
38283 exports
.ecdhUnsafe = function (publicKey
, privateKey
, compressed
) {
38284 var pair
= loadPublicKey(publicKey
)
38285 if (pair
=== null) throw new Error(messages
.EC_PUBLIC_KEY_PARSE_FAIL
)
38287 var scalar
= new BN(privateKey
)
38288 if (scalar
.cmp(ecparams
.n
) >= 0 || scalar
.isZero()) throw new Error(messages
.ECDH_FAIL
)
38290 return Buffer
.from(pair
.pub
.mul(scalar
).encode(true, compressed
))
38293 },{"../messages.json":254,"bn.js":75,"create-hash":111,"elliptic":127,"safe-buffer":247}],253:[function(require
,module
,exports
){
38295 var assert
= require('./assert')
38296 var der
= require('./der')
38297 var messages
= require('./messages.json')
38299 function initCompressedValue (value
, defaultValue
) {
38300 if (value
=== undefined) return defaultValue
38302 assert
.isBoolean(value
, messages
.COMPRESSED_TYPE_INVALID
)
38306 module
.exports = function (secp256k1
) {
38308 privateKeyVerify: function (privateKey
) {
38309 assert
.isBuffer(privateKey
, messages
.EC_PRIVATE_KEY_TYPE_INVALID
)
38310 return privateKey
.length
=== 32 && secp256k1
.privateKeyVerify(privateKey
)
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
)
38317 compressed
= initCompressedValue(compressed
, true)
38318 var publicKey
= secp256k1
.privateKeyExport(privateKey
, compressed
)
38320 return der
.privateKeyExport(privateKey
, publicKey
, compressed
)
38323 privateKeyImport: function (privateKey
) {
38324 assert
.isBuffer(privateKey
, messages
.EC_PRIVATE_KEY_TYPE_INVALID
)
38326 privateKey
= der
.privateKeyImport(privateKey
)
38327 if (privateKey
&& privateKey
.length
=== 32 && secp256k1
.privateKeyVerify(privateKey
)) return privateKey
38329 throw new Error(messages
.EC_PRIVATE_KEY_IMPORT_DER_FAIL
)
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
)
38336 return secp256k1
.privateKeyNegate(privateKey
)
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
)
38343 return secp256k1
.privateKeyModInverse(privateKey
)
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
)
38350 assert
.isBuffer(tweak
, messages
.TWEAK_TYPE_INVALID
)
38351 assert
.isBufferLength(tweak
, 32, messages
.TWEAK_LENGTH_INVALID
)
38353 return secp256k1
.privateKeyTweakAdd(privateKey
, tweak
)
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
)
38360 assert
.isBuffer(tweak
, messages
.TWEAK_TYPE_INVALID
)
38361 assert
.isBufferLength(tweak
, 32, messages
.TWEAK_LENGTH_INVALID
)
38363 return secp256k1
.privateKeyTweakMul(privateKey
, tweak
)
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
)
38370 compressed
= initCompressedValue(compressed
, true)
38372 return secp256k1
.publicKeyCreate(privateKey
, compressed
)
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
)
38379 compressed
= initCompressedValue(compressed
, true)
38381 return secp256k1
.publicKeyConvert(publicKey
, compressed
)
38384 publicKeyVerify: function (publicKey
) {
38385 assert
.isBuffer(publicKey
, messages
.EC_PUBLIC_KEY_TYPE_INVALID
)
38386 return secp256k1
.publicKeyVerify(publicKey
)
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
)
38393 assert
.isBuffer(tweak
, messages
.TWEAK_TYPE_INVALID
)
38394 assert
.isBufferLength(tweak
, 32, messages
.TWEAK_LENGTH_INVALID
)
38396 compressed
= initCompressedValue(compressed
, true)
38398 return secp256k1
.publicKeyTweakAdd(publicKey
, tweak
, compressed
)
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
)
38405 assert
.isBuffer(tweak
, messages
.TWEAK_TYPE_INVALID
)
38406 assert
.isBufferLength(tweak
, 32, messages
.TWEAK_LENGTH_INVALID
)
38408 compressed
= initCompressedValue(compressed
, true)
38410 return secp256k1
.publicKeyTweakMul(publicKey
, tweak
, compressed
)
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
)
38421 compressed
= initCompressedValue(compressed
, true)
38423 return secp256k1
.publicKeyCombine(publicKeys
, compressed
)
38426 signatureNormalize: function (signature
) {
38427 assert
.isBuffer(signature
, messages
.ECDSA_SIGNATURE_TYPE_INVALID
)
38428 assert
.isBufferLength(signature
, 64, messages
.ECDSA_SIGNATURE_LENGTH_INVALID
)
38430 return secp256k1
.signatureNormalize(signature
)
38433 signatureExport: function (signature
) {
38434 assert
.isBuffer(signature
, messages
.ECDSA_SIGNATURE_TYPE_INVALID
)
38435 assert
.isBufferLength(signature
, 64, messages
.ECDSA_SIGNATURE_LENGTH_INVALID
)
38437 var sigObj
= secp256k1
.signatureExport(signature
)
38438 return der
.signatureExport(sigObj
)
38441 signatureImport: function (sig
) {
38442 assert
.isBuffer(sig
, messages
.ECDSA_SIGNATURE_TYPE_INVALID
)
38443 assert
.isLengthGTZero(sig
, messages
.ECDSA_SIGNATURE_LENGTH_INVALID
)
38445 var sigObj
= der
.signatureImport(sig
)
38446 if (sigObj
) return secp256k1
.signatureImport(sigObj
)
38448 throw new Error(messages
.ECDSA_SIGNATURE_PARSE_DER_FAIL
)
38451 signatureImportLax: function (sig
) {
38452 assert
.isBuffer(sig
, messages
.ECDSA_SIGNATURE_TYPE_INVALID
)
38453 assert
.isLengthGTZero(sig
, messages
.ECDSA_SIGNATURE_LENGTH_INVALID
)
38455 var sigObj
= der
.signatureImportLax(sig
)
38456 if (sigObj
) return secp256k1
.signatureImport(sigObj
)
38458 throw new Error(messages
.ECDSA_SIGNATURE_PARSE_DER_FAIL
)
38461 sign: function (message
, privateKey
, options
) {
38462 assert
.isBuffer(message
, messages
.MSG32_TYPE_INVALID
)
38463 assert
.isBufferLength(message
, 32, messages
.MSG32_LENGTH_INVALID
)
38465 assert
.isBuffer(privateKey
, messages
.EC_PRIVATE_KEY_TYPE_INVALID
)
38466 assert
.isBufferLength(privateKey
, 32, messages
.EC_PRIVATE_KEY_LENGTH_INVALID
)
38470 if (options
!== undefined) {
38471 assert
.isObject(options
, messages
.OPTIONS_TYPE_INVALID
)
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
38479 if (options
.noncefn
!== undefined) {
38480 assert
.isFunction(options
.noncefn
, messages
.OPTIONS_NONCEFN_TYPE_INVALID
)
38481 noncefn
= options
.noncefn
38485 return secp256k1
.sign(message
, privateKey
, noncefn
, data
)
38488 verify: function (message
, signature
, publicKey
) {
38489 assert
.isBuffer(message
, messages
.MSG32_TYPE_INVALID
)
38490 assert
.isBufferLength(message
, 32, messages
.MSG32_LENGTH_INVALID
)
38492 assert
.isBuffer(signature
, messages
.ECDSA_SIGNATURE_TYPE_INVALID
)
38493 assert
.isBufferLength(signature
, 64, messages
.ECDSA_SIGNATURE_LENGTH_INVALID
)
38495 assert
.isBuffer(publicKey
, messages
.EC_PUBLIC_KEY_TYPE_INVALID
)
38496 assert
.isBufferLength2(publicKey
, 33, 65, messages
.EC_PUBLIC_KEY_LENGTH_INVALID
)
38498 return secp256k1
.verify(message
, signature
, publicKey
)
38501 recover: function (message
, signature
, recovery
, compressed
) {
38502 assert
.isBuffer(message
, messages
.MSG32_TYPE_INVALID
)
38503 assert
.isBufferLength(message
, 32, messages
.MSG32_LENGTH_INVALID
)
38505 assert
.isBuffer(signature
, messages
.ECDSA_SIGNATURE_TYPE_INVALID
)
38506 assert
.isBufferLength(signature
, 64, messages
.ECDSA_SIGNATURE_LENGTH_INVALID
)
38508 assert
.isNumber(recovery
, messages
.RECOVERY_ID_TYPE_INVALID
)
38509 assert
.isNumberInInterval(recovery
, -1, 4, messages
.RECOVERY_ID_VALUE_INVALID
)
38511 compressed
= initCompressedValue(compressed
, true)
38513 return secp256k1
.recover(message
, signature
, recovery
, compressed
)
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
)
38520 assert
.isBuffer(privateKey
, messages
.EC_PRIVATE_KEY_TYPE_INVALID
)
38521 assert
.isBufferLength(privateKey
, 32, messages
.EC_PRIVATE_KEY_LENGTH_INVALID
)
38523 return secp256k1
.ecdh(publicKey
, privateKey
)
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
)
38530 assert
.isBuffer(privateKey
, messages
.EC_PRIVATE_KEY_TYPE_INVALID
)
38531 assert
.isBufferLength(privateKey
, 32, messages
.EC_PRIVATE_KEY_LENGTH_INVALID
)
38533 compressed
= initCompressedValue(compressed
, true)
38535 return secp256k1
.ecdhUnsafe(publicKey
, privateKey
, compressed
)
38540 },{"./assert":250,"./der":251,"./messages.json":254}],254:[function(require
,module
,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"
38579 },{}],255:[function(require
,module
,exports
){
38580 var Buffer
= require('safe-buffer').Buffer
38582 // prototype class for hash functions
38583 function Hash (blockSize
, finalSize
) {
38584 this._block
= Buffer
.alloc(blockSize
)
38585 this._finalSize
= finalSize
38586 this._blockSize
= blockSize
38590 Hash
.prototype.update = function (data
, enc
) {
38591 if (typeof data
=== 'string') {
38592 enc
= enc
|| 'utf8'
38593 data
= Buffer
.from(data
, enc
)
38596 var block
= this._block
38597 var blockSize
= this._blockSize
38598 var length
= data
.length
38599 var accum
= this._len
38601 for (var offset
= 0; offset
< length
;) {
38602 var assigned
= accum
% blockSize
38603 var remainder
= Math
.min(length
- offset
, blockSize
- assigned
)
38605 for (var i
= 0; i
< remainder
; i
++) {
38606 block
[assigned
+ i
] = data
[offset
+ i
]
38610 offset
+= remainder
38612 if ((accum
% blockSize
) === 0) {
38613 this._update(block
)
38617 this._len
+= length
38621 Hash
.prototype.digest = function (enc
) {
38622 var rem
= this._len
% this._blockSize
38624 this._block
[rem
] = 0x80
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)
38630 if (rem
>= this._finalSize
) {
38631 this._update(this._block
)
38632 this._block
.fill(0)
38635 var bits
= this._len
* 8
38638 if (bits
<= 0xffffffff) {
38639 this._block
.writeUInt32BE(bits
, this._blockSize
- 4)
38643 var lowBits
= bits
& 0xffffffff
38644 var highBits
= (bits
- lowBits
) / 0x100000000
38646 this._block
.writeUInt32BE(highBits
, this._blockSize
- 8)
38647 this._block
.writeUInt32BE(lowBits
, this._blockSize
- 4)
38650 this._update(this._block
)
38651 var hash
= this._hash()
38653 return enc
? hash
.toString(enc
) : hash
38656 Hash
.prototype._update = function () {
38657 throw new Error('_update must be implemented by subclass')
38660 module
.exports
= Hash
38662 },{"safe-buffer":247}],256:[function(require
,module
,exports
){
38663 var exports
= module
.exports
= function SHA (algorithm
) {
38664 algorithm
= algorithm
.toLowerCase()
38666 var Algorithm
= exports
[algorithm
]
38667 if (!Algorithm
) throw new Error(algorithm
+ ' is not supported (we accept pull requests)')
38669 return new Algorithm()
38672 exports
.sha
= require('./sha')
38673 exports
.sha1
= require('./sha1')
38674 exports
.sha224
= require('./sha224')
38675 exports
.sha256
= require('./sha256')
38676 exports
.sha384
= require('./sha384')
38677 exports
.sha512
= require('./sha512')
38679 },{"./sha":257,"./sha1":258,"./sha224":259,"./sha256":260,"./sha384":261,"./sha512":262}],257:[function(require
,module
,exports
){
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.
38688 var inherits
= require('inherits')
38689 var Hash
= require('./hash')
38690 var Buffer
= require('safe-buffer').Buffer
38693 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
38696 var W
= new Array(80)
38702 Hash
.call(this, 64, 56)
38705 inherits(Sha
, Hash
)
38707 Sha
.prototype.init = function () {
38708 this._a
= 0x67452301
38709 this._b
= 0xefcdab89
38710 this._c
= 0x98badcfe
38711 this._d
= 0x10325476
38712 this._e
= 0xc3d2e1f0
38717 function rotl5 (num
) {
38718 return (num
<< 5) | (num
>>> 27)
38721 function rotl30 (num
) {
38722 return (num
<< 30) | (num
>>> 2)
38725 function 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
)
38731 Sha
.prototype._update = function (M
) {
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
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]
38743 for (var j
= 0; j
< 80; ++j
) {
38745 var t
= (rotl5(a
) + ft(s
, b
, c
, d
) + e
+ W
[j
] + K
[s
]) | 0
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
38761 Sha
.prototype._hash = function () {
38762 var H
= Buffer
.allocUnsafe(20)
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)
38773 module
.exports
= Sha
38775 },{"./hash":255,"inherits":163,"safe-buffer":247}],258:[function(require
,module
,exports
){
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.
38785 var inherits
= require('inherits')
38786 var Hash
= require('./hash')
38787 var Buffer
= require('safe-buffer').Buffer
38790 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0
38793 var W
= new Array(80)
38799 Hash
.call(this, 64, 56)
38802 inherits(Sha1
, Hash
)
38804 Sha1
.prototype.init = function () {
38805 this._a
= 0x67452301
38806 this._b
= 0xefcdab89
38807 this._c
= 0x98badcfe
38808 this._d
= 0x10325476
38809 this._e
= 0xc3d2e1f0
38814 function rotl1 (num
) {
38815 return (num
<< 1) | (num
>>> 31)
38818 function rotl5 (num
) {
38819 return (num
<< 5) | (num
>>> 27)
38822 function rotl30 (num
) {
38823 return (num
<< 30) | (num
>>> 2)
38826 function 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
)
38832 Sha1
.prototype._update = function (M
) {
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
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])
38844 for (var j
= 0; j
< 80; ++j
) {
38846 var t
= (rotl5(a
) + ft(s
, b
, c
, d
) + e
+ W
[j
] + K
[s
]) | 0
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
38862 Sha1
.prototype._hash = function () {
38863 var H
= Buffer
.allocUnsafe(20)
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)
38874 module
.exports
= Sha1
38876 },{"./hash":255,"inherits":163,"safe-buffer":247}],259:[function(require
,module
,exports
){
38878 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
38880 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
38881 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
38885 var inherits
= require('inherits')
38886 var Sha256
= require('./sha256')
38887 var Hash
= require('./hash')
38888 var Buffer
= require('safe-buffer').Buffer
38890 var W
= new Array(64)
38892 function Sha224 () {
38895 this._w
= W
// new Array(64)
38897 Hash
.call(this, 64, 56)
38900 inherits(Sha224
, Sha256
)
38902 Sha224
.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
38915 Sha224
.prototype._hash = function () {
38916 var H
= Buffer
.allocUnsafe(28)
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)
38929 module
.exports
= Sha224
38931 },{"./hash":255,"./sha256":260,"inherits":163,"safe-buffer":247}],260:[function(require
,module
,exports
){
38933 * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined
38935 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009.
38936 * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
38940 var inherits
= require('inherits')
38941 var Hash
= require('./hash')
38942 var Buffer
= require('safe-buffer').Buffer
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
38963 var W
= new Array(64)
38965 function Sha256 () {
38968 this._w
= W
// new Array(64)
38970 Hash
.call(this, 64, 56)
38973 inherits(Sha256
, Hash
)
38975 Sha256
.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
38988 function ch (x
, y
, z
) {
38989 return z
^ (x
& (y
^ z
))
38992 function maj (x
, y
, z
) {
38993 return (x
& y
) | (z
& (x
| y
))
38996 function sigma0 (x
) {
38997 return (x
>>> 2 | x
<< 30) ^ (x
>>> 13 | x
<< 19) ^ (x
>>> 22 | x
<< 10)
39000 function sigma1 (x
) {
39001 return (x
>>> 6 | x
<< 26) ^ (x
>>> 11 | x
<< 21) ^ (x
>>> 25 | x
<< 7)
39004 function gamma0 (x
) {
39005 return (x
>>> 7 | x
<< 25) ^ (x
>>> 18 | x
<< 14) ^ (x
>>> 3)
39008 function gamma1 (x
) {
39009 return (x
>>> 17 | x
<< 15) ^ (x
>>> 19 | x
<< 13) ^ (x
>>> 10)
39012 Sha256
.prototype._update = function (M
) {
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
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
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
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
39051 Sha256
.prototype._hash = function () {
39052 var H
= Buffer
.allocUnsafe(32)
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)
39066 module
.exports
= Sha256
39068 },{"./hash":255,"inherits":163,"safe-buffer":247}],261:[function(require
,module
,exports
){
39069 var inherits
= require('inherits')
39070 var SHA512
= require('./sha512')
39071 var Hash
= require('./hash')
39072 var Buffer
= require('safe-buffer').Buffer
39074 var W
= new Array(160)
39076 function Sha384 () {
39080 Hash
.call(this, 128, 112)
39083 inherits(Sha384
, SHA512
)
39085 Sha384
.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
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
39107 Sha384
.prototype._hash = function () {
39108 var H
= Buffer
.allocUnsafe(48)
39110 function writeInt64BE (h
, l
, offset
) {
39111 H
.writeInt32BE(h
, offset
)
39112 H
.writeInt32BE(l
, offset
+ 4)
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)
39125 module
.exports
= Sha384
39127 },{"./hash":255,"./sha512":262,"inherits":163,"safe-buffer":247}],262:[function(require
,module
,exports
){
39128 var inherits
= require('inherits')
39129 var Hash
= require('./hash')
39130 var Buffer
= require('safe-buffer').Buffer
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
39175 var W
= new Array(160)
39177 function Sha512 () {
39181 Hash
.call(this, 128, 112)
39184 inherits(Sha512
, Hash
)
39186 Sha512
.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
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
39208 function Ch (x
, y
, z
) {
39209 return z
^ (x
& (y
^ z
))
39212 function maj (x
, y
, z
) {
39213 return (x
& y
) | (z
& (x
| y
))
39216 function sigma0 (x
, xl
) {
39217 return (x
>>> 28 | xl
<< 4) ^ (xl
>>> 2 | x
<< 30) ^ (xl
>>> 7 | x
<< 25)
39220 function sigma1 (x
, xl
) {
39221 return (x
>>> 14 | xl
<< 18) ^ (x
>>> 18 | xl
<< 14) ^ (xl
>>> 9 | x
<< 23)
39224 function Gamma0 (x
, xl
) {
39225 return (x
>>> 1 | xl
<< 31) ^ (x
>>> 8 | xl
<< 24) ^ (x
>>> 7)
39228 function Gamma0l (x
, xl
) {
39229 return (x
>>> 1 | xl
<< 31) ^ (x
>>> 8 | xl
<< 24) ^ (x
>>> 7 | xl
<< 25)
39232 function Gamma1 (x
, xl
) {
39233 return (x
>>> 19 | xl
<< 13) ^ (xl
>>> 29 | x
<< 3) ^ (x
>>> 6)
39236 function Gamma1l (x
, xl
) {
39237 return (x
>>> 19 | xl
<< 13) ^ (xl
>>> 29 | x
<< 3) ^ (x
>>> 6 | xl
<< 26)
39240 function getCarry (a
, b
) {
39241 return (a
>>> 0) < (b
>>> 0) ? 1 : 0
39244 Sha512
.prototype._update = function (M
) {
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
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
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)
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
)
39276 xl
= W
[i
- 2 * 2 + 1]
39277 var gamma1
= Gamma1(xh
, xl
)
39278 var gamma1l
= Gamma1l(xl
, xh
)
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]
39284 var Wi16h
= W
[i
- 16 * 2]
39285 var Wi16l
= W
[i
- 16 * 2 + 1]
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
39298 for (var j
= 0; j
< 160; j
+= 2) {
39302 var majh
= maj(ah
, bh
, ch
)
39303 var majl
= maj(al
, bl
, cl
)
39305 var sigma0h
= sigma0(ah
, al
)
39306 var sigma0l
= sigma0(al
, ah
)
39307 var sigma1h
= sigma1(eh
, el
)
39308 var sigma1l
= sigma1(el
, eh
)
39310 // t1 = h + sigma1 + ch + K[j] + W[j]
39314 var chh
= Ch(eh
, fh
, gh
)
39315 var chl
= Ch(el
, fl
, gl
)
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
39326 // t2 = sigma0 + maj
39327 var t2l
= (sigma0l
+ majl
) | 0
39328 var t2h
= (sigma0h
+ majh
+ getCarry(t2l
, sigma0l
)) | 0
39336 el
= (dl
+ t1l
) | 0
39337 eh
= (dh
+ t1h
+ getCarry(el
, dl
)) | 0
39344 al
= (t1l
+ t2l
) | 0
39345 ah
= (t1h
+ t2h
+ getCarry(al
, t1l
)) | 0
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
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
39367 Sha512
.prototype._hash = function () {
39368 var H
= Buffer
.allocUnsafe(64)
39370 function writeInt64BE (h
, l
, offset
) {
39371 H
.writeInt32BE(h
, offset
)
39372 H
.writeInt32BE(l
, offset
+ 4)
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)
39387 module
.exports
= Sha512
39389 },{"./hash":255,"inherits":163,"safe-buffer":247}],263:[function(require
,module
,exports
){
39390 // Copyright Joyent, Inc. and other Node contributors.
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:
39400 // The above copyright notice and this permission notice shall be included
39401 // in all copies or substantial portions of the Software.
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.
39411 module
.exports
= Stream
;
39413 var EE
= require('events').EventEmitter
;
39414 var inherits
= require('inherits');
39416 inherits(Stream
, EE
);
39417 Stream
.Readable
= require('readable-stream/readable.js');
39418 Stream
.Writable
= require('readable-stream/writable.js');
39419 Stream
.Duplex
= require('readable-stream/duplex.js');
39420 Stream
.Transform
= require('readable-stream/transform.js');
39421 Stream
.PassThrough
= require('readable-stream/passthrough.js');
39423 // Backwards-compat with node 0.4.x
39424 Stream
.Stream
= Stream
;
39428 // old-style streams. Note that the pipe method (the only relevant
39429 // part of this class) is overridden in the Readable class.
39431 function Stream() {
39435 Stream
.prototype.pipe = function(dest
, options
) {
39438 function ondata(chunk
) {
39439 if (dest
.writable
) {
39440 if (false === dest
.write(chunk
) && source
.pause
) {
39446 source
.on('data', ondata
);
39448 function ondrain() {
39449 if (source
.readable
&& source
.resume
) {
39454 dest
.on('drain', ondrain
);
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
);
39463 var didOnEnd
= false;
39465 if (didOnEnd
) return;
39472 function onclose() {
39473 if (didOnEnd
) return;
39476 if (typeof dest
.destroy
=== 'function') dest
.destroy();
39479 // don't leave dangling pipes when there are errors.
39480 function onerror(er
) {
39482 if (EE
.listenerCount(this, 'error') === 0) {
39483 throw er
; // Unhandled stream error in pipe.
39487 source
.on('error', onerror
);
39488 dest
.on('error', onerror
);
39490 // remove all the event listeners that were added.
39491 function cleanup() {
39492 source
.removeListener('data', ondata
);
39493 dest
.removeListener('drain', ondrain
);
39495 source
.removeListener('end', onend
);
39496 source
.removeListener('close', onclose
);
39498 source
.removeListener('error', onerror
);
39499 dest
.removeListener('error', onerror
);
39501 source
.removeListener('end', cleanup
);
39502 source
.removeListener('close', cleanup
);
39504 dest
.removeListener('close', cleanup
);
39507 source
.on('end', cleanup
);
39508 source
.on('close', cleanup
);
39510 dest
.on('close', cleanup
);
39512 dest
.emit('pipe', source
);
39514 // Allow for unix-like usage: A.pipe(B).pipe(C)
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
){
39521 var Buffer
= require('safe-buffer').Buffer
;
39523 var 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':
39533 function _normalizeEncoding(enc
) {
39534 if (!enc
) return 'utf8';
39554 if (retried
) return; // undefined
39555 enc
= ('' + enc
).toLowerCase();
39561 // Do not cache `Buffer.isEncoding` when checking encoding names as some
39562 // modules monkey-patch it to support additional encodings
39563 function 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
;
39569 // StringDecoder provides an interface for efficiently splitting a series of
39570 // buffers into a series of JS strings without breaking apart multi-byte
39572 exports
.StringDecoder
= StringDecoder
;
39573 function StringDecoder(encoding
) {
39574 this.encoding
= normalizeEncoding(encoding
);
39576 switch (this.encoding
) {
39578 this.text
= utf16Text
;
39579 this.end
= utf16End
;
39583 this.fillLast
= utf8FillLast
;
39587 this.text
= base64Text
;
39588 this.end
= base64End
;
39592 this.write
= simpleWrite
;
39593 this.end
= simpleEnd
;
39597 this.lastTotal
= 0;
39598 this.lastChar
= Buffer
.allocUnsafe(nb
);
39601 StringDecoder
.prototype.write = function (buf
) {
39602 if (buf
.length
=== 0) return '';
39605 if (this.lastNeed
) {
39606 r
= this.fillLast(buf
);
39607 if (r
=== undefined) return '';
39613 if (i
< buf
.length
) return r
? r
+ this.text(buf
, i
) : this.text(buf
, i
);
39617 StringDecoder
.prototype.end
= utf8End
;
39619 // Returns only complete characters in a Buffer
39620 StringDecoder
.prototype.text
= utf8Text
;
39622 // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer
39623 StringDecoder
.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
);
39628 buf
.copy(this.lastChar
, this.lastTotal
- this.lastNeed
, 0, buf
.length
);
39629 this.lastNeed
-= buf
.length
;
39632 // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a
39633 // continuation byte.
39634 function 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;
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.
39642 function utf8CheckIncomplete(self
, buf
, i
) {
39643 var j
= buf
.length
- 1;
39644 if (j
< i
) return 0;
39645 var nb
= utf8CheckByte(buf
[j
]);
39647 if (nb
> 0) self
.lastNeed
= nb
- 1;
39650 if (--j
< i
) return 0;
39651 nb
= utf8CheckByte(buf
[j
]);
39653 if (nb
> 0) self
.lastNeed
= nb
- 2;
39656 if (--j
< i
) return 0;
39657 nb
= utf8CheckByte(buf
[j
]);
39660 if (nb
=== 2) nb
= 0;else self
.lastNeed
= nb
- 3;
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
39675 function utf8CheckExtraBytes(self
, buf
, p
) {
39676 if ((buf
[0] & 0xC0) !== 0x80) {
39678 return '\ufffd'.repeat(p
);
39680 if (self
.lastNeed
> 1 && buf
.length
> 1) {
39681 if ((buf
[1] & 0xC0) !== 0x80) {
39683 return '\ufffd'.repeat(p
+ 1);
39685 if (self
.lastNeed
> 2 && buf
.length
> 2) {
39686 if ((buf
[2] & 0xC0) !== 0x80) {
39688 return '\ufffd'.repeat(p
+ 2);
39694 // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer.
39695 function 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
);
39703 buf
.copy(this.lastChar
, p
, 0, buf
.length
);
39704 this.lastNeed
-= buf
.length
;
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.
39710 function 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
);
39719 // For UTF-8, a replacement character for each buffered byte of a (partial)
39720 // character needs to be added to the output.
39721 function utf8End(buf
) {
39722 var r
= buf
&& buf
.length
? this.write(buf
) : '';
39723 if (this.lastNeed
) return r
+ '\ufffd'.repeat(this.lastTotal
- this.lastNeed
);
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.
39731 function utf16Text(buf
, i
) {
39732 if ((buf
.length
- i
) % 2 === 0) {
39733 var r
= buf
.toString('utf16le', i
);
39735 var c
= r
.charCodeAt(r
.length
- 1);
39736 if (c
>= 0xD800 && c
<= 0xDBFF) {
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);
39747 this.lastTotal
= 2;
39748 this.lastChar
[0] = buf
[buf
.length
- 1];
39749 return buf
.toString('utf16le', i
, buf
.length
- 1);
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.
39754 function 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
);
39763 function 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;
39769 this.lastChar
[0] = buf
[buf
.length
- 1];
39771 this.lastChar
[0] = buf
[buf
.length
- 2];
39772 this.lastChar
[1] = buf
[buf
.length
- 1];
39774 return buf
.toString('base64', i
, buf
.length
- n
);
39777 function 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
);
39783 // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex)
39784 function simpleWrite(buf
) {
39785 return buf
.toString(this.encoding
);
39788 function simpleEnd(buf
) {
39789 return buf
&& buf
.length
? this.write(buf
) : '';
39791 },{"safe-buffer":247}],265:[function(require
,module
,exports
){
39792 (function (global
){
39798 module
.exports
= deprecate
;
39801 * Mark that a method should not be used.
39802 * Returns a modified function which warns once by default.
39804 * If `localStorage.noDeprecation = true` is set, then it is a no-op.
39806 * If `localStorage.throwDeprecation = true` is set, then deprecated functions
39807 * will throw an Error when invoked.
39809 * If `localStorage.traceDeprecation = true` is set, then deprecated functions
39810 * will invoke `console.trace()` instead of `console.error()`.
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`
39818 function deprecate (fn
, msg
) {
39819 if (config('noDeprecation')) {
39823 var warned
= false;
39824 function deprecated() {
39826 if (config('throwDeprecation')) {
39827 throw new Error(msg
);
39828 } else if (config('traceDeprecation')) {
39829 console
.trace(msg
);
39835 return fn
.apply(this, arguments
);
39842 * Checks `localStorage` for boolean values for the given `name`.
39844 * @param {String} name
39845 * @returns {Boolean}
39849 function config (name
) {
39850 // accessing global.localStorage can trigger a DOMException in sandboxed iframes
39852 if (!global
.localStorage
) return false;
39856 var val
= global
.localStorage
[name
];
39857 if (null == val
) return false;
39858 return String(val
).toLowerCase() === 'true';
39861 }).call(this,typeof global
!== "undefined" ? global : typeof self
!== "undefined" ? self : typeof window
!== "undefined" ? window : {})
39862 },{}],266:[function(require
,module
,exports
){
39863 var v1
= require('./v1');
39864 var v4
= require('./v4');
39870 module
.exports
= uuid
;
39872 },{"./v1":269,"./v4":270}],267:[function(require
,module
,exports
){
39874 * Convert array of 16 byte values to UUID string format of the form:
39875 * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
39877 var byteToHex
= [];
39878 for (var i
= 0; i
< 256; ++i
) {
39879 byteToHex
[i
] = (i
+ 0x100).toString(16).substr(1);
39882 function 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
++]];
39895 module
.exports
= bytesToUuid
;
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
39905 var crypto
= global
.crypto
|| global
.msCrypto
; // for IE 11
39906 if (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
);
39916 // Math.random()-based (RNG)
39918 // If all else fails, use Math.random(). It's fast, but is of unspecified
39920 var rnds
= new Array(16);
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;
39931 module
.exports
= rng
;
39933 }).call(this,typeof global
!== "undefined" ? global : typeof self
!== "undefined" ? self : typeof window
!== "undefined" ? window : {})
39934 },{}],269:[function(require
,module
,exports
){
39935 var rng
= require('./lib/rng');
39936 var bytesToUuid
= require('./lib/bytesToUuid');
39938 // **`v1()` - Generate time-based UUID**
39940 // Inspired by https://github.com/LiosK/UUID.js
39941 // and http://docs.python.org/library/uuid.html
39943 // random #'s we need to init node and clockseq
39944 var _seedBytes
= rng();
39946 // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1)
39948 _seedBytes
[0] | 0x01,
39949 _seedBytes
[1], _seedBytes
[2], _seedBytes
[3], _seedBytes
[4], _seedBytes
[5]
39952 // Per 4.2.2, randomize (14 bit) clockseq
39953 var _clockseq
= (_seedBytes
[6] << 8 | _seedBytes
[7]) & 0x3fff;
39955 // Previous uuid creation time
39956 var _lastMSecs
= 0, _lastNSecs
= 0;
39958 // See https://github.com/broofa/node-uuid for API details
39959 function v1(options
, buf
, offset
) {
39960 var i
= buf
&& offset
|| 0;
39963 options
= options
|| {};
39965 var clockseq
= options
.clockseq
!== undefined ? options
.clockseq : _clockseq
;
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();
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;
39977 // Time since last uuid creation (in msecs)
39978 var dt
= (msecs
- _lastMSecs
) + (nsecs
- _lastNSecs
)/10000;
39980 // Per 4.2.1.2, Bump clockseq on clock regression
39981 if (dt
< 0 && options
.clockseq
=== undefined) {
39982 clockseq
= clockseq
+ 1 & 0x3fff;
39985 // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new
39987 if ((dt
< 0 || msecs
> _lastMSecs
) && options
.nsecs
=== undefined) {
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');
39996 _lastMSecs
= msecs
;
39997 _lastNSecs
= nsecs
;
39998 _clockseq
= clockseq
;
40000 // Per 4.1.4 - Convert from unix epoch to Gregorian epoch
40001 msecs
+= 12219292800000;
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;
40011 var tmh
= (msecs
/ 0x100000000 * 10000) & 0xfffffff;
40012 b
[i
++] = tmh
>>> 8 & 0xff;
40013 b
[i
++] = tmh
& 0xff;
40015 // `time_high_and_version`
40016 b
[i
++] = tmh
>>> 24 & 0xf | 0x10; // include version
40017 b
[i
++] = tmh
>>> 16 & 0xff;
40019 // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant)
40020 b
[i
++] = clockseq
>>> 8 | 0x80;
40023 b
[i
++] = clockseq
& 0xff;
40026 var node
= options
.node
|| _nodeId
;
40027 for (var n
= 0; n
< 6; ++n
) {
40028 b
[i
+ n
] = node
[n
];
40031 return buf
? buf : bytesToUuid(b
);
40034 module
.exports
= v1
;
40036 },{"./lib/bytesToUuid":267,"./lib/rng":268}],270:[function(require
,module
,exports
){
40037 var rng
= require('./lib/rng');
40038 var bytesToUuid
= require('./lib/bytesToUuid');
40040 function v4(options
, buf
, offset
) {
40041 var i
= buf
&& offset
|| 0;
40043 if (typeof(options
) == 'string') {
40044 buf
= options
== 'binary' ? new Array(16) : null;
40047 options
= options
|| {};
40049 var rnds
= options
.random
|| (options
.rng
|| rng
)();
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;
40055 // Copy bytes to buffer, if provided
40057 for (var ii
= 0; ii
< 16; ++ii
) {
40058 buf
[i
+ ii
] = rnds
[ii
];
40062 return buf
|| bytesToUuid(rnds
);
40065 module
.exports
= v4
;
40067 },{"./lib/bytesToUuid":267,"./lib/rng":268}],271:[function(require
,module
,exports
){
40068 var indexOf
= require('indexof');
40070 var Object_keys = function (obj
) {
40071 if (Object
.keys
) return Object
.keys(obj
)
40074 for (var key
in obj
) res
.push(key
)
40079 var forEach = function (xs
, fn
) {
40080 if (xs
.forEach
) return xs
.forEach(fn
)
40081 else for (var i
= 0; i
< xs
.length
; i
++) {
40086 var defineProp
= (function() {
40088 Object
.defineProperty({}, '_', {});
40089 return function(obj
, name
, value
) {
40090 Object
.defineProperty(obj
, name
, {
40093 configurable: true,
40098 return function(obj
, name
, value
) {
40104 var 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'];
40110 function Context() {}
40111 Context
.prototype = {};
40113 var Script
= exports
.Script
= function NodeScript (code
) {
40114 if (!(this instanceof Script
)) return new Script(code
);
40118 Script
.prototype.runInContext = function (context
) {
40119 if (!(context
instanceof Context
)) {
40120 throw new TypeError("needs a 'context' argument.");
40123 var iframe
= document
.createElement('iframe');
40124 if (!iframe
.style
) iframe
.style
= {};
40125 iframe
.style
.display
= 'none';
40127 document
.body
.appendChild(iframe
);
40129 var win
= iframe
.contentWindow
;
40130 var wEval
= win
.eval
, wExecScript
= win
.execScript
;
40132 if (!wEval
&& wExecScript
) {
40133 // win.eval() magically appears when this is called in IE:
40134 wExecScript
.call(win
, 'null');
40138 forEach(Object_keys(context
), function (key
) {
40139 win
[key
] = context
[key
];
40141 forEach(globals
, function (key
) {
40142 if (context
[key
]) {
40143 win
[key
] = context
[key
];
40147 var winKeys
= Object_keys(win
);
40149 var res
= wEval
.call(win
, this.code
);
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
];
40160 forEach(globals
, function (key
) {
40161 if (!(key
in context
)) {
40162 defineProp(context
, key
, win
[key
]);
40166 document
.body
.removeChild(iframe
);
40171 Script
.prototype.runInThisContext = function () {
40172 return eval(this.code
); // maybe...
40175 Script
.prototype.runInNewContext = function (context
) {
40176 var ctx
= Script
.createContext(context
);
40177 var res
= this.runInContext(ctx
);
40179 forEach(Object_keys(ctx
), function (key
) {
40180 context
[key
] = ctx
[key
];
40186 forEach(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));
40193 exports
.createScript = function (code
) {
40194 return exports
.Script(code
);
40197 exports
.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
];
40207 },{"indexof":162}],"nebulas":[function(require
,module
,exports
){
40208 var HttpRequest
= require("./lib/httprequest");
40209 var Neb
= require('./lib/neb');
40210 var Account
= require('./lib/account');
40211 var Transaction
= require('./lib/transaction');
40212 var Utils
= require('./lib/utils/utils');
40213 var CryptoUtils
= require('./lib/utils/crypto-utils');
40214 var Unit
= require('./lib/utils/unit');
40215 var NVM
= require('./lib/nvm/nvm');
40217 // dont override global variable
40218 if (typeof window
!== 'undefined' && typeof window
.Neb
=== 'undefined') {
40223 HttpRequest: HttpRequest
,
40226 Transaction: Transaction
,
40228 CryptoUtils: CryptoUtils
,
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
){
40236 // go env doesn't have and need localStorage
40238 if (typeof localStorage
=== 'undefined') {
40239 exports
.localStorage
= {};
40241 exports
.localStorage
= localStorage
; // jshint ignore:line