diff options
-rw-r--r-- | src/index.html | 1 | ||||
-rw-r--r-- | src/js/index.js | 20 | ||||
-rw-r--r-- | src/js/nebulas.js | 40244 |
3 files changed, 40265 insertions, 0 deletions
diff --git a/src/index.html b/src/index.html index 63372a5..73d0084 100644 --- a/src/index.html +++ b/src/index.html | |||
@@ -927,6 +927,7 @@ | |||
927 | <script src="js/ethereumjs-util.js"></script> | 927 | <script src="js/ethereumjs-util.js"></script> |
928 | <script src="js/ripple-util.js"></script> | 928 | <script src="js/ripple-util.js"></script> |
929 | <script src="js/bchaddrjs-0.2.1.js"></script> | 929 | <script src="js/bchaddrjs-0.2.1.js"></script> |
930 | <script src="js/nebulas.js"></script> | ||
930 | <script src="js/sjcl-bip39.js"></script> | 931 | <script src="js/sjcl-bip39.js"></script> |
931 | <script src="js/wordlist_english.js"></script> | 932 | <script src="js/wordlist_english.js"></script> |
932 | <script src="js/wordlist_japanese.js"></script> | 933 | <script src="js/wordlist_japanese.js"></script> |
diff --git a/src/js/index.js b/src/js/index.js index bc15559..8699733 100644 --- a/src/js/index.js +++ b/src/js/index.js | |||
@@ -928,6 +928,19 @@ | |||
928 | privkey = ethUtil.addHexPrefix(privkey); | 928 | privkey = ethUtil.addHexPrefix(privkey); |
929 | pubkey = ethUtil.addHexPrefix(pubkey); | 929 | pubkey = ethUtil.addHexPrefix(pubkey); |
930 | } | 930 | } |
931 | if ((networks[DOM.network.val()].name == "NAS - Nebulas")) { | ||
932 | var NasAccount = require("nebulas").Account; | ||
933 | var privKeyBuffer = keyPair.d.toBuffer(32); | ||
934 | // privkey = privKeyBuffer.toString('hex'); | ||
935 | console.log(privkey); | ||
936 | var nasAccount = NasAccount.NewAccount(privKeyBuffer); | ||
937 | // var addressBuffer = ethUtil.privateToAddress(privKeyBuffer); | ||
938 | // var hexAddress = addressBuffer.toString('hex'); | ||
939 | // var checksumAddress = ethUtil.toChecksumAddress(hexAddress); | ||
940 | address = nasAccount.getAddressString(); | ||
941 | privkey = nasAccount.getPrivateKeyString(); | ||
942 | pubkey = nasAccount.getPublicKeyString(); | ||
943 | } | ||
931 | // Ripple values are different | 944 | // Ripple values are different |
932 | if (networks[DOM.network.val()].name == "XRP - Ripple") { | 945 | if (networks[DOM.network.val()].name == "XRP - Ripple") { |
933 | privkey = convertRipplePriv(privkey); | 946 | privkey = convertRipplePriv(privkey); |
@@ -2224,6 +2237,13 @@ | |||
2224 | }, | 2237 | }, |
2225 | }, | 2238 | }, |
2226 | { | 2239 | { |
2240 | name: "NAS - Nebulas", | ||
2241 | onSelect: function() { | ||
2242 | network = bitcoinjs.bitcoin.networks.bitcoin; | ||
2243 | setHdCoin(2718); | ||
2244 | }, | ||
2245 | }, | ||
2246 | { | ||
2227 | name: "NEBL - Neblio", | 2247 | name: "NEBL - Neblio", |
2228 | onSelect: function() { | 2248 | onSelect: function() { |
2229 | network = bitcoinjs.bitcoin.networks.neblio; | 2249 | network = bitcoinjs.bitcoin.networks.neblio; |
diff --git a/src/js/nebulas.js b/src/js/nebulas.js new file mode 100644 index 0000000..b8983f7 --- /dev/null +++ b/src/js/nebulas.js | |||
@@ -0,0 +1,40244 @@ | |||
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){ | ||
2 | "use strict"; | ||
3 | |||
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'); | ||
8 | |||
9 | var AddressLength = 26; | ||
10 | var AddressPrefix = 25; | ||
11 | var NormalType = 87; | ||
12 | var ContractType = 88; | ||
13 | |||
14 | var KeyVersion3 = 3; | ||
15 | var KeyCurrentVersion = 4; | ||
16 | |||
17 | /** | ||
18 | * @typedef {Object} KeyOptions | ||
19 | * @property {Buffer} salt | ||
20 | * @property {Buffer} iv | ||
21 | * @property {String} kdf | ||
22 | * @property {Number} dklen | ||
23 | * @property {Number} c | ||
24 | * @property {Number} n | ||
25 | * @property {Number} r | ||
26 | * @property {Number} p | ||
27 | * @property {String} cipher | ||
28 | * @property {Buffer} uuid | ||
29 | * @global | ||
30 | */ | ||
31 | |||
32 | /** | ||
33 | * Key Object. | ||
34 | * @typedef {Object} Key | ||
35 | * @property {Number} version | ||
36 | * @property {Buffer} id | ||
37 | * @property {HexString} address | ||
38 | * @property {Object} crypto | ||
39 | * @global | ||
40 | */ | ||
41 | |||
42 | /** | ||
43 | * Account constructor. | ||
44 | * Class encapsulate main operation with account entity. | ||
45 | * @constructor | ||
46 | * | ||
47 | * @param {Hash} priv Account private key. | ||
48 | * @param {String} path | ||
49 | * | ||
50 | * @example var account = new Account(new Buffer("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6", "hex") ); | ||
51 | * | ||
52 | */ | ||
53 | var Account = function (priv, path) { | ||
54 | priv = priv || cryptoUtils.crypto.randomBytes(32); | ||
55 | this.setPrivateKey(priv); | ||
56 | this.path = path; | ||
57 | }; | ||
58 | |||
59 | /** | ||
60 | * Account factory method. | ||
61 | * Create random account. | ||
62 | * @static | ||
63 | * | ||
64 | * @return {Account} Instance of Account constructor. | ||
65 | * | ||
66 | * @example var account = Account.NewAccount(); | ||
67 | */ | ||
68 | Account.NewAccount = function () { | ||
69 | return new Account(cryptoUtils.crypto.randomBytes(32)); | ||
70 | }; | ||
71 | |||
72 | /** | ||
73 | * Address validation method. | ||
74 | * | ||
75 | * @static | ||
76 | * @param {String/Hash} addr - Account address. | ||
77 | * @param {Number} type - NormalType / ContractType | ||
78 | * | ||
79 | * @return {Boolean} Is address has correct format. | ||
80 | * | ||
81 | * @example | ||
82 | * if ( Account.isValidAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5") ) { | ||
83 | * // some code | ||
84 | * }; | ||
85 | */ | ||
86 | Account.isValidAddress = function (addr, type) { | ||
87 | /*jshint maxcomplexity:10 */ | ||
88 | |||
89 | if (utils.isString(addr)) { | ||
90 | try { | ||
91 | addr = Base58.decode(addr); | ||
92 | } catch (e) { | ||
93 | console.log("invalid address."); | ||
94 | // if address can't be base58 decode, return false. | ||
95 | return false; | ||
96 | } | ||
97 | } else if (!Buffer.isBuffer(addr)) { | ||
98 | return false; | ||
99 | } | ||
100 | // address not equal to 26 | ||
101 | if (addr.length !== AddressLength) { | ||
102 | return false; | ||
103 | } | ||
104 | |||
105 | // check if address start with AddressPrefix | ||
106 | var buff = Buffer.from(addr); | ||
107 | if (buff.readUIntBE(0, 1) !== AddressPrefix) { | ||
108 | return false; | ||
109 | } | ||
110 | |||
111 | // check if address type is NormalType or ContractType | ||
112 | var t = buff.readUIntBE(1, 1); | ||
113 | if (utils.isNumber(type) && (type === NormalType || type === ContractType)) { | ||
114 | if (t !== type) { | ||
115 | return false; | ||
116 | } | ||
117 | } else if (t !== NormalType && t !== ContractType) { | ||
118 | return false; | ||
119 | } | ||
120 | var content = addr.slice(0, 22); | ||
121 | var checksum = addr.slice(-4); | ||
122 | return Buffer.compare(cryptoUtils.sha3(content).slice(0, 4), checksum) === 0; | ||
123 | }; | ||
124 | |||
125 | /** | ||
126 | * Restore account from address. | ||
127 | * Receive addr or Account instance. | ||
128 | * If addr is Account instance return new Account instance with same PrivateKey. | ||
129 | * | ||
130 | * @static | ||
131 | * @param {(Hash|Object)} - Client address or Account instance. | ||
132 | * | ||
133 | * @return {Account} Instance of Account restored from address. | ||
134 | * | ||
135 | * @example var account = Account.fromAddress("n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5"); | ||
136 | */ | ||
137 | Account.fromAddress = function (addr) { | ||
138 | var acc = new Account(); | ||
139 | if (addr instanceof Account) { | ||
140 | acc.setPrivateKey(addr.getPrivateKey()); | ||
141 | return acc; | ||
142 | } | ||
143 | if (utils.isString(addr) && this.isValidAddress(addr)) { | ||
144 | acc.address = Base58.decode(addr); | ||
145 | return acc; | ||
146 | } | ||
147 | |||
148 | var buf = cryptoUtils.toBuffer(addr); | ||
149 | if (this.isValidAddress(buf)) { | ||
150 | acc.address = buf; | ||
151 | return acc; | ||
152 | } | ||
153 | throw new Error("invalid address"); | ||
154 | }; | ||
155 | |||
156 | /** | ||
157 | * Restore account from public key. | ||
158 | * | ||
159 | * @static | ||
160 | * @param {(String/Hash)} - Public key. | ||
161 | * | ||
162 | * @return {Account} Instance of Account restored from address. | ||
163 | * | ||
164 | * @example var account = Account.fromPubKey("f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7"); | ||
165 | */ | ||
166 | Account.fromPubKey = function (publicKey) { | ||
167 | var acc = new Account(); | ||
168 | acc.pubKey = cryptoUtils.toBuffer(publicKey); | ||
169 | return acc; | ||
170 | }; | ||
171 | |||
172 | Account.getNormalType = function () { | ||
173 | return NormalType; | ||
174 | }; | ||
175 | |||
176 | Account.getContractType = function () { | ||
177 | return ContractType; | ||
178 | }; | ||
179 | |||
180 | Account.prototype = { | ||
181 | /** | ||
182 | * Private Key setter. | ||
183 | * | ||
184 | * @param {Hash} priv - Account private key. | ||
185 | * | ||
186 | * @example account.setPrivateKey("ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6"); | ||
187 | */ | ||
188 | setPrivateKey: function (priv) { | ||
189 | if (utils.isString(priv) || Buffer.isBuffer(priv)) { | ||
190 | this.privKey = priv.length === 32 ? priv : Buffer(priv, 'hex'); | ||
191 | this.pubKey = null; | ||
192 | this.address = null; | ||
193 | } | ||
194 | }, | ||
195 | /** | ||
196 | * Private Key getter. | ||
197 | * | ||
198 | * @return {Buffer} Account private key. | ||
199 | * | ||
200 | * @example var privKey = account.getPrivateKey(); | ||
201 | * //<Buffer 5b ed 67 f9 9c b3 31 9e 0c 6f 6a 03 54 8b e3 c8 c5 2a 83 64 46 4f 88 6f> 24 | ||
202 | */ | ||
203 | getPrivateKey: function () { | ||
204 | return this.privKey; | ||
205 | }, | ||
206 | /** | ||
207 | * Get Private Key in hex string format. | ||
208 | * | ||
209 | * @return {HexString} Account private key in String format. | ||
210 | * | ||
211 | * @example var privKey = account.getPrivateKeyString(); | ||
212 | * //"ac3773e06ae74c0fa566b0e421d4e391333f31aef90b383f0c0e83e4873609d6" | ||
213 | */ | ||
214 | getPrivateKeyString: function () { | ||
215 | return this.getPrivateKey().toString('hex'); | ||
216 | }, | ||
217 | /** | ||
218 | * Public Key getter. | ||
219 | * | ||
220 | * @return {Buffer} Account public key. | ||
221 | * | ||
222 | * @example var publicKey = account.getPublicKey(); | ||
223 | * //<Buffer c0 96 aa 4e 66 c7 4a 9a c7 18 31 f1 24 72 2a c1 3e b5 df 7f 97 1b 13 1d 46 a2 8a e6 81 c6 1d 96 f7 07 d0 aa e9 a7 67 436b 68 af a8 f0 96 65 17 24 29 ... > | ||
224 | */ | ||
225 | getPublicKey: function () { | ||
226 | if (utils.isNull(this.pubKey)) { | ||
227 | this.pubKey = cryptoUtils.privateToPublic(this.privKey); | ||
228 | } | ||
229 | return this.pubKey; | ||
230 | }, | ||
231 | /** | ||
232 | * Get Public Key in hex string format. | ||
233 | * | ||
234 | * @return {HexString} Account public key in String format. | ||
235 | * | ||
236 | * @example var publicKey = account.getPublicKey(); | ||
237 | * //"f18ec04019dd131bbcfada4020b001d547244d768f144ef947577ce53a13ad690eb43e4b02a8daa3c168045cd122c0685f083e1656756ba7982721322ebe4da7" | ||
238 | */ | ||
239 | getPublicKeyString: function () { | ||
240 | return this.getPublicKey().toString('hex'); | ||
241 | }, | ||
242 | /** | ||
243 | * Accaunt address getter. | ||
244 | * | ||
245 | * @return {Buffer} Account address. | ||
246 | * | ||
247 | * @example var publicKey = account.getAddress(); | ||
248 | * //<Buffer 7f 87 83 58 46 96 12 7d 1a c0 57 1a 42 87 c6 25 36 08 ff 32 61 36 51 7c> | ||
249 | */ | ||
250 | getAddress: function () { | ||
251 | if (utils.isNull(this.address)) { | ||
252 | |||
253 | var pubKey = this.getPublicKey(); | ||
254 | if (pubKey.length !== 64) { | ||
255 | pubKey = cryptoUtils.secp256k1.publicKeyConvert(pubKey, false).slice(1); | ||
256 | } | ||
257 | |||
258 | // The uncompressed form consists of a 0x04 (in analogy to the DER OCTET STRING tag) plus | ||
259 | // the concatenation of the binary representation of the X coordinate plus the binary | ||
260 | // representation of the y coordinate of the public point. | ||
261 | pubKey = Buffer.concat([cryptoUtils.toBuffer(4), pubKey]); | ||
262 | |||
263 | // Only take the lower 160bits of the hash | ||
264 | var content = cryptoUtils.sha3(pubKey); | ||
265 | content = cryptoUtils.ripemd160(content); | ||
266 | // content = AddressPrefix + NormalType + content(local address only use normal type) | ||
267 | content = Buffer.concat([cryptoUtils.toBuffer(AddressPrefix), cryptoUtils.toBuffer(NormalType), content]); | ||
268 | var checksum = cryptoUtils.sha3(content).slice(0, 4); | ||
269 | this.address = Buffer.concat([content, checksum]); | ||
270 | } | ||
271 | return this.address; | ||
272 | }, | ||
273 | /** | ||
274 | * Get account address in hex string format. | ||
275 | * | ||
276 | * @return {HexString} Account address in String format. | ||
277 | * | ||
278 | * @example var publicKey = account.getAddressString(); | ||
279 | * //"802d529bf55d6693b3ac72c59b4a7d159da53cae5a7bf99c" | ||
280 | */ | ||
281 | getAddressString: function () { | ||
282 | var addr = this.getAddress(); | ||
283 | return Base58.encode(addr); | ||
284 | }, | ||
285 | /** | ||
286 | * Generate key buy passphrase and options. | ||
287 | * | ||
288 | * @param {Password} password - Provided password. | ||
289 | * @param {KeyOptions} opts - Key options. | ||
290 | * | ||
291 | * @return {Key} Key Object. | ||
292 | * | ||
293 | * @example var key = account.toKey("passphrase"); | ||
294 | */ | ||
295 | toKey: function (password, opts) { | ||
296 | /*jshint maxcomplexity:17 */ | ||
297 | |||
298 | opts = opts || {}; | ||
299 | var salt = opts.salt || cryptoUtils.crypto.randomBytes(32); | ||
300 | var iv = opts.iv || cryptoUtils.crypto.randomBytes(16); | ||
301 | var derivedKey; | ||
302 | var kdf = opts.kdf || 'scrypt'; | ||
303 | var kdfparams = { | ||
304 | dklen: opts.dklen || 32, | ||
305 | salt: salt.toString('hex') | ||
306 | }; | ||
307 | if (kdf === 'pbkdf2') { | ||
308 | kdfparams.c = opts.c || 262144; | ||
309 | kdfparams.prf = 'hmac-sha256'; | ||
310 | derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), salt, kdfparams.c, kdfparams.dklen, 'sha256'); | ||
311 | } else if (kdf === 'scrypt') { | ||
312 | kdfparams.n = opts.n || 4096; | ||
313 | kdfparams.r = opts.r || 8; | ||
314 | kdfparams.p = opts.p || 1; | ||
315 | derivedKey = cryptoUtils.scrypt(new Buffer(password), salt, kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); | ||
316 | } else { | ||
317 | throw new Error('Unsupported kdf'); | ||
318 | } | ||
319 | var cipher = cryptoUtils.crypto.createCipheriv(opts.cipher || 'aes-128-ctr', derivedKey.slice(0, 16), iv); | ||
320 | if (!cipher) { | ||
321 | throw new Error('Unsupported cipher'); | ||
322 | } | ||
323 | var ciphertext = Buffer.concat([cipher.update(this.privKey), cipher.final()]); | ||
324 | // var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex')])); // KeyVersion3 deprecated | ||
325 | var mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), new Buffer(ciphertext, 'hex'), iv, new Buffer(opts.cipher || 'aes-128-ctr')])); | ||
326 | return { | ||
327 | version: KeyCurrentVersion, | ||
328 | id: cryptoUtils.uuid.v4({ | ||
329 | random: opts.uuid || cryptoUtils.crypto.randomBytes(16) | ||
330 | }), | ||
331 | address: this.getAddressString(), | ||
332 | crypto: { | ||
333 | ciphertext: ciphertext.toString('hex'), | ||
334 | cipherparams: { | ||
335 | iv: iv.toString('hex') | ||
336 | }, | ||
337 | cipher: opts.cipher || 'aes-128-ctr', | ||
338 | kdf: kdf, | ||
339 | kdfparams: kdfparams, | ||
340 | mac: mac.toString('hex'), | ||
341 | machash: "sha3256" | ||
342 | } | ||
343 | }; | ||
344 | }, | ||
345 | /** | ||
346 | * Generate key buy passphrase and options. | ||
347 | * Return in JSON format. | ||
348 | * | ||
349 | * @param {Password} password - Provided password. | ||
350 | * @param {KeyOptions} opts - Key options. | ||
351 | * | ||
352 | * @return {String} JSON stringify Key. | ||
353 | * | ||
354 | * @example var key = account.toKeyString("passphrase"); | ||
355 | */ | ||
356 | toKeyString: function (password, opts) { | ||
357 | return JSON.stringify(this.toKey(password, opts)); | ||
358 | }, | ||
359 | /** | ||
360 | * Restore account from key and passphrase. | ||
361 | * | ||
362 | * @param {Key} input - Key Object. | ||
363 | * @param {Password} password - Provided password. | ||
364 | * @param {Boolean} nonStrict - Strict сase sensitivity flag. | ||
365 | * | ||
366 | * @return {@link Account} - Instance of Account restored from key and passphrase. | ||
367 | */ | ||
368 | fromKey: function (input, password, nonStrict) { | ||
369 | /*jshint maxcomplexity:10 */ | ||
370 | |||
371 | var json = typeof input === 'object' ? input : JSON.parse(nonStrict ? input.toLowerCase() : input); | ||
372 | if (json.version !== KeyVersion3 && json.version !== KeyCurrentVersion) { | ||
373 | throw new Error('Not supported wallet version'); | ||
374 | } | ||
375 | var derivedKey; | ||
376 | var kdfparams; | ||
377 | if (json.crypto.kdf === 'scrypt') { | ||
378 | kdfparams = json.crypto.kdfparams; | ||
379 | derivedKey = cryptoUtils.scrypt(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.n, kdfparams.r, kdfparams.p, kdfparams.dklen); | ||
380 | } else if (json.crypto.kdf === 'pbkdf2') { | ||
381 | kdfparams = json.crypto.kdfparams; | ||
382 | if (kdfparams.prf !== 'hmac-sha256') { | ||
383 | throw new Error('Unsupported parameters to PBKDF2'); | ||
384 | } | ||
385 | derivedKey = cryptoUtils.crypto.pbkdf2Sync(new Buffer(password), new Buffer(kdfparams.salt, 'hex'), kdfparams.c, kdfparams.dklen, 'sha256'); | ||
386 | } else { | ||
387 | throw new Error('Unsupported key derivation scheme'); | ||
388 | } | ||
389 | var ciphertext = new Buffer(json.crypto.ciphertext, 'hex'); | ||
390 | var mac; | ||
391 | |||
392 | if (json.version === KeyCurrentVersion) { | ||
393 | mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext, new Buffer(json.crypto.cipherparams.iv, 'hex'), new Buffer(json.crypto.cipher)])); | ||
394 | } else { | ||
395 | // KeyVersion3 | ||
396 | mac = cryptoUtils.sha3(Buffer.concat([derivedKey.slice(16, 32), ciphertext])); | ||
397 | } | ||
398 | |||
399 | if (mac.toString('hex') !== json.crypto.mac) { | ||
400 | throw new Error('Key derivation failed - possibly wrong passphrase'); | ||
401 | } | ||
402 | var decipher = cryptoUtils.crypto.createDecipheriv(json.crypto.cipher, derivedKey.slice(0, 16), new Buffer(json.crypto.cipherparams.iv, 'hex')); | ||
403 | var seed = Buffer.concat([decipher.update(ciphertext), decipher.final()]); | ||
404 | while (seed.length < 32) { | ||
405 | var nullBuff = new Buffer([0x00]); | ||
406 | seed = Buffer.concat([nullBuff, seed]); | ||
407 | } | ||
408 | this.setPrivateKey(seed); | ||
409 | return this; | ||
410 | } | ||
411 | |||
412 | }; | ||
413 | |||
414 | module.exports = Account; | ||
415 | |||
416 | },{"./utils/crypto-utils.js":19,"./utils/utils.js":21,"bs58":105,"safe-buffer":247}],2:[function(require,module,exports){ | ||
417 | |||
418 | "use strict"; | ||
419 | |||
420 | var utils = require('./utils/utils.js'); | ||
421 | |||
422 | /** | ||
423 | * Admin API constructor. | ||
424 | * Class encapsulate methods for admin APIs commands. | ||
425 | * @see [Admin API documentation:]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md}. | ||
426 | * @constructor | ||
427 | * | ||
428 | * @param {Neb} neb - Instance of Neb library. | ||
429 | * | ||
430 | * @example | ||
431 | * var admin = new Admin( new Neb() ); | ||
432 | * // or just | ||
433 | * var admin = new Neb().admin; | ||
434 | */ | ||
435 | var Admin = function (neb) { | ||
436 | this._setRequest(neb._request); | ||
437 | }; | ||
438 | |||
439 | /** | ||
440 | * @private | ||
441 | * @param {Request} request - transport wrapper. | ||
442 | */ | ||
443 | Admin.prototype._setRequest = function (request) { | ||
444 | this._request = request; | ||
445 | this._path = '/admin'; | ||
446 | }; | ||
447 | |||
448 | /** | ||
449 | * Method get info about nodes in Nebulas Network. | ||
450 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#nodeinfo} | ||
451 | * | ||
452 | * @return [nodeInfoObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#nodeinfo} | ||
453 | * | ||
454 | * @example | ||
455 | * var admin = new Neb().admin; | ||
456 | * admin.nodeInfo().then(function(info) { | ||
457 | * //code | ||
458 | * }); | ||
459 | */ | ||
460 | Admin.prototype.nodeInfo = function () { | ||
461 | return this._sendRequest("get", "/nodeinfo", null); | ||
462 | }; | ||
463 | |||
464 | /** | ||
465 | * Method get list of available addresses. | ||
466 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#accounts} | ||
467 | * | ||
468 | * @return [accountsList]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#accounts} | ||
469 | * | ||
470 | * @example | ||
471 | * var admin = new Neb().admin; | ||
472 | * admin.accounts().then(function(accounts) { | ||
473 | * //code | ||
474 | * }); | ||
475 | */ | ||
476 | Admin.prototype.accounts = function () { | ||
477 | return this._sendRequest("get", "/accounts", null); | ||
478 | }; | ||
479 | |||
480 | /** | ||
481 | * Method create a new account in Nebulas network with provided passphrase. | ||
482 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#newaccount} | ||
483 | * | ||
484 | * @param {Object} options | ||
485 | * @param {Password} options.passphrase | ||
486 | * | ||
487 | * @return [address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#newaccount} | ||
488 | * | ||
489 | * @example | ||
490 | * var admin = new Neb().admin; | ||
491 | * admin.newAccount({passphrase: "passphrase"}).then(function(address) { | ||
492 | * //code | ||
493 | * }); | ||
494 | */ | ||
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); | ||
499 | }; | ||
500 | |||
501 | /** | ||
502 | * Method unlock account with provided passphrase. | ||
503 | * After the default unlock time, the account will be locked. | ||
504 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#unlockaccount} | ||
505 | * | ||
506 | * @param {Object} options | ||
507 | * @param {HexString} options.address | ||
508 | * @param {Password} options.passphrase | ||
509 | * @param {Number} options.duration | ||
510 | * | ||
511 | * @return [isUnLocked]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#unlockaccount} | ||
512 | * | ||
513 | * @example | ||
514 | * var admin = new Neb().admin; | ||
515 | * admin.unlockAccount({ | ||
516 | * address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh", | ||
517 | * passphrase: "passphrase", | ||
518 | * duration: 1000000000 | ||
519 | * }).then(function(isUnLocked) { | ||
520 | * //code | ||
521 | * }); | ||
522 | */ | ||
523 | Admin.prototype.unlockAccount = function (options) { | ||
524 | options = utils.argumentsToObject(['address', 'passphrase', 'duration'], arguments); | ||
525 | var params = { | ||
526 | "address": options.address, | ||
527 | "passphrase": options.passphrase, | ||
528 | "duration": options.duration | ||
529 | }; | ||
530 | return this._sendRequest("post", "/account/unlock", params); | ||
531 | }; | ||
532 | |||
533 | /** | ||
534 | * Method lock account. | ||
535 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#lockaccount} | ||
536 | * | ||
537 | * @param {Object} options | ||
538 | * @param {HexString} options.address | ||
539 | * | ||
540 | * @return [isLocked]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#lockaccount} | ||
541 | * | ||
542 | * @example | ||
543 | * var admin = new Neb().admin; | ||
544 | * admin.lockAccount({address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh"}).then(function(isLocked) { | ||
545 | * //code | ||
546 | * }); | ||
547 | */ | ||
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); | ||
552 | }; | ||
553 | |||
554 | /** | ||
555 | * Method wrap transaction sending functionality. | ||
556 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransaction} | ||
557 | * | ||
558 | * @param {TransactionOptions} options | ||
559 | * | ||
560 | * @return [Transcation hash and contract address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransaction} | ||
561 | * | ||
562 | * @example | ||
563 | * var admin = new Neb().admin; | ||
564 | * admin.sendTransaction({ | ||
565 | * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5", | ||
566 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
567 | * value: 10, | ||
568 | * nonce: 12, | ||
569 | * gasPrice: 1000000, | ||
570 | * gasLimit: 2000000 | ||
571 | * }).then(function(tx) { | ||
572 | * //code | ||
573 | * }); | ||
574 | */ | ||
575 | Admin.prototype.sendTransaction = function (options) { | ||
576 | options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary'], arguments); | ||
577 | var params = { | ||
578 | "from": options.from, | ||
579 | "to": options.to, | ||
580 | "value": utils.toString(options.value), | ||
581 | "nonce": options.nonce, | ||
582 | "gasPrice": utils.toString(options.gasPrice), | ||
583 | "gasLimit": utils.toString(options.gasLimit), | ||
584 | "contract": options.contract, | ||
585 | "binary": options.binary | ||
586 | }; | ||
587 | return this._sendRequest("post", "/transaction", params); | ||
588 | }; | ||
589 | |||
590 | /** | ||
591 | * Method sign hash. | ||
592 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signhash} | ||
593 | * | ||
594 | * @param {Object} options | ||
595 | * @param {HexString} options.address | ||
596 | * @param {Base64} options.hash of hash bytes with base64 encode. | ||
597 | * @param {UInt32} options.alg | ||
598 | * | ||
599 | * @return [data]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signhash} | ||
600 | * | ||
601 | * @example | ||
602 | * var admin = new Neb().admin; | ||
603 | * admin.SignHash({ | ||
604 | * address: "n1cYKNHTeVW9v1NQRWuhZZn9ETbqAYozckh", | ||
605 | * hash: "OGQ5NjllZWY2ZWNhZDNjMjlhM2E2MjkyODBlNjg2Y2YwYzNmNWQ1YTg2YWZmM2NhMTIwMjBjOTIzYWRjNmM5Mg==", | ||
606 | * alg: 1 | ||
607 | * }).then(function(data) { | ||
608 | * //code | ||
609 | * }); | ||
610 | */ | ||
611 | Admin.prototype.signHash = function (options) { | ||
612 | options = utils.argumentsToObject(['address', 'hash', 'alg'], arguments); | ||
613 | var params = { | ||
614 | "address": options.address, | ||
615 | "hash": options.hash, | ||
616 | "alg": options.alg | ||
617 | }; | ||
618 | return this._sendRequest("post", "/sign/hash", params); | ||
619 | }; | ||
620 | |||
621 | /** | ||
622 | * Method sign transaction with passphrase. | ||
623 | * The transaction's from addrees must be unlock before sign call. | ||
624 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signtransactionwithpassphrase} | ||
625 | * | ||
626 | * @param {TransactionOptions} options | ||
627 | * @param {Password} options.passphrase | ||
628 | * | ||
629 | * @return [Transcation hash and contract address]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#signtransactionwithpassphrase} | ||
630 | * | ||
631 | * @example | ||
632 | * var admin = new Neb().admin; | ||
633 | * admin.signTransactionWithPassphrase({ | ||
634 | * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5", | ||
635 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
636 | * value: 10, | ||
637 | * nonce: 12, | ||
638 | * gasPrice: 1000000, | ||
639 | * gasLimit: 2000000, | ||
640 | * passphrase: "passphrase" | ||
641 | * }).then(function(tx) { | ||
642 | * //code | ||
643 | * }); | ||
644 | */ | ||
645 | Admin.prototype.signTransactionWithPassphrase = function (options) { | ||
646 | options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary', 'passphrase'], arguments); | ||
647 | var tx = { | ||
648 | "from": options.from, | ||
649 | "to": options.to, | ||
650 | "value": utils.toString(options.value), | ||
651 | "nonce": options.nonce, | ||
652 | "gasPrice": utils.toString(options.gasPrice), | ||
653 | "gasLimit": utils.toString(options.gasLimit), | ||
654 | "contract": options.contract, | ||
655 | "binary": options.binary | ||
656 | }; | ||
657 | var params = { | ||
658 | "transaction": tx, | ||
659 | "passphrase": options.passphrase | ||
660 | }; | ||
661 | return this._sendRequest("post", "/sign", params); | ||
662 | }; | ||
663 | |||
664 | /** | ||
665 | * Method send transaction with passphrase. | ||
666 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransactionwithpassphrase} | ||
667 | * | ||
668 | * @param {TransactionOptions} options | ||
669 | * @param {Password} options.passphrase | ||
670 | * | ||
671 | * @return [data]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#sendtransactionwithpassphrase} | ||
672 | * | ||
673 | * @example | ||
674 | * var admin = new Neb().admin; | ||
675 | * admin.sendTransactionWithPassphrase({ | ||
676 | * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5", | ||
677 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
678 | * value: 10, | ||
679 | * nonce: 12, | ||
680 | * gasPrice: 1000000, | ||
681 | * gasLimit: 2000000, | ||
682 | * passphrase: "passphrase" | ||
683 | * }).then(function(tx) { | ||
684 | * //code | ||
685 | * }); | ||
686 | */ | ||
687 | Admin.prototype.sendTransactionWithPassphrase = function (options) { | ||
688 | options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary', 'passphrase'], arguments); | ||
689 | var tx = { | ||
690 | "from": options.from, | ||
691 | "to": options.to, | ||
692 | "value": utils.toString(options.value), | ||
693 | "nonce": options.nonce, | ||
694 | "gasPrice": utils.toString(options.gasPrice), | ||
695 | "gasLimit": utils.toString(options.gasLimit), | ||
696 | "contract": options.contract, | ||
697 | "binary": options.binary | ||
698 | }; | ||
699 | var params = { | ||
700 | "transaction": tx, | ||
701 | "passphrase": options.passphrase | ||
702 | }; | ||
703 | return this._sendRequest("post", "/transactionWithPassphrase", params); | ||
704 | }; | ||
705 | |||
706 | /** | ||
707 | * Method start listen provided port. | ||
708 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#startpprof} | ||
709 | * | ||
710 | * @param {Object} options | ||
711 | * @param {String} options.listen - Listen port. | ||
712 | * | ||
713 | * @return [isListenStrted]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#startpprof} | ||
714 | * | ||
715 | * @example | ||
716 | * var admin = new Neb().admin; | ||
717 | * admin.startPprof({listen: '8080'}).then(function(isListenStrted) { | ||
718 | * //code | ||
719 | * }); | ||
720 | */ | ||
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); | ||
725 | }; | ||
726 | |||
727 | /** | ||
728 | * Method get config of node in Nebulas Network. | ||
729 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#getConfig} | ||
730 | * | ||
731 | * @return [config]{@link https://github.com/nebulasio/wiki/blob/master/rpc_admin.md#getConfig} | ||
732 | * | ||
733 | * @example | ||
734 | * var admin = new Neb().admin; | ||
735 | * admin.getConfig().then(function(info) { | ||
736 | * //code | ||
737 | * }); | ||
738 | */ | ||
739 | Admin.prototype.getConfig = function () { | ||
740 | return this._sendRequest("get", "/getConfig", null); | ||
741 | }; | ||
742 | |||
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); | ||
747 | } else { | ||
748 | return this._request.request(method, action, params); | ||
749 | } | ||
750 | }; | ||
751 | |||
752 | module.exports = Admin; | ||
753 | |||
754 | },{"./utils/utils.js":21}],3:[function(require,module,exports){ | ||
755 | |||
756 | "use strict"; | ||
757 | |||
758 | var utils = require('./utils/utils.js'); | ||
759 | |||
760 | /** | ||
761 | * User API constructor. | ||
762 | * Class encapsulate methods for building distributed applications and services. | ||
763 | * | ||
764 | * @see [API documentation]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md} | ||
765 | * @constructor | ||
766 | * | ||
767 | * @param {Neb} neb - Instance of Neb library. | ||
768 | * | ||
769 | * @example | ||
770 | * var api = new API ( new Neb() ); | ||
771 | * // or just | ||
772 | * var api = new Neb().api; | ||
773 | */ | ||
774 | var API = function (neb) { | ||
775 | this._setRequest(neb._request); | ||
776 | }; | ||
777 | |||
778 | /** | ||
779 | * @private | ||
780 | * @param {Request} request - transport wrapper. | ||
781 | */ | ||
782 | API.prototype._setRequest = function (request) { | ||
783 | this._request = request; | ||
784 | this._path = '/user'; | ||
785 | }; | ||
786 | |||
787 | /** | ||
788 | * Method get state of Nebulas Network. | ||
789 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getnebstate} | ||
790 | * | ||
791 | * @return [NebStateObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getnebstate} | ||
792 | * | ||
793 | * @example | ||
794 | * var api = new Neb().api; | ||
795 | * api.getNebState().then(function(state) { | ||
796 | * //code | ||
797 | * }); | ||
798 | */ | ||
799 | API.prototype.getNebState = function () { | ||
800 | return this._sendRequest("get", "/nebstate", null); | ||
801 | }; | ||
802 | |||
803 | /** | ||
804 | * Method get latest irreversible block of Nebulas Network. | ||
805 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#latestirreversibleblock} | ||
806 | * | ||
807 | * @return [dataBlockInfo.]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#latestirreversibleblock} | ||
808 | * | ||
809 | * @example | ||
810 | * var api = new Neb().api; | ||
811 | * api.latestIrreversibleBlock().then(function(blockData) { | ||
812 | * //code | ||
813 | * }); | ||
814 | */ | ||
815 | API.prototype.latestIrreversibleBlock = function () { | ||
816 | return this._sendRequest("get", "/lib", null); | ||
817 | }; | ||
818 | |||
819 | /** | ||
820 | * Method return the state of the account. Balance and nonce. | ||
821 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getaccountstate} | ||
822 | * | ||
823 | * @param {Object} options | ||
824 | * @param {HexString} options.address | ||
825 | * @param {String} options.height | ||
826 | * | ||
827 | * @return [accaountStateObject]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getaccountstate} | ||
828 | * | ||
829 | * @example | ||
830 | * var api = new Neb().api; | ||
831 | * api.getAccountState({address: "n1QsosVXKxiV3B4iDWNmxfN4VqpHn2TeUcn"}).then(function(state) { | ||
832 | * //code | ||
833 | * }); | ||
834 | */ | ||
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); | ||
839 | }; | ||
840 | |||
841 | /** | ||
842 | * Method wrap smart contract call functionality. | ||
843 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#call} | ||
844 | * | ||
845 | * @param {TransactionOptions} options | ||
846 | * | ||
847 | * @return [Transcation hash]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#call} | ||
848 | * | ||
849 | * @example | ||
850 | * var api = new Neb().api; | ||
851 | * api.call({ | ||
852 | * chainID: 1, | ||
853 | * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5", | ||
854 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
855 | * value: 10, | ||
856 | * nonce: 12, | ||
857 | * gasPrice: 1000000, | ||
858 | * gasLimit: 2000000, | ||
859 | * contract: { | ||
860 | * function: "save", | ||
861 | * args: "[0]" | ||
862 | * } | ||
863 | * }).then(function(tx) { | ||
864 | * //code | ||
865 | * }); | ||
866 | */ | ||
867 | API.prototype.call = function (options) { | ||
868 | options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments); | ||
869 | var params = { | ||
870 | "from": options.from, | ||
871 | "to": options.to, | ||
872 | "value": utils.toString(options.value), | ||
873 | "nonce": options.nonce, | ||
874 | "gasPrice": utils.toString(options.gasPrice), | ||
875 | "gasLimit": utils.toString(options.gasLimit), | ||
876 | "contract": options.contract | ||
877 | }; | ||
878 | return this._sendRequest("post", "/call", params); | ||
879 | }; | ||
880 | |||
881 | /** | ||
882 | * Method wrap submit the signed transaction. | ||
883 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction} | ||
884 | * | ||
885 | * @param {Object} options | ||
886 | * @param {String} options.data | ||
887 | * | ||
888 | * @return [Transcation hash]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction} | ||
889 | * | ||
890 | * @example | ||
891 | * var api = new Neb().api; | ||
892 | * var tx = new Transaction({ | ||
893 | * chainID: 1, | ||
894 | * from: acc1, | ||
895 | * to: acc2, | ||
896 | * value: 10, | ||
897 | * nonce: 12, | ||
898 | * gasPrice: 1000000, | ||
899 | * gasLimit: 2000000 | ||
900 | * }); | ||
901 | * tx.signTransaction(); | ||
902 | * api.sendRawTransaction( {data: tx.toProtoString()} ).then(function(hash) { | ||
903 | * //code | ||
904 | * }); | ||
905 | */ | ||
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); | ||
910 | }; | ||
911 | |||
912 | /** | ||
913 | * Get block header info by the block hash. | ||
914 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyhash} | ||
915 | * | ||
916 | * @param {Object} options | ||
917 | * @param {HexString} options.hash | ||
918 | * @param {Boolean} options.fullTransaction | ||
919 | * | ||
920 | * @return [Block]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyhash} | ||
921 | * | ||
922 | * @example | ||
923 | * var api = new Neb().api; | ||
924 | * api.getBlockByHash({ | ||
925 | * hash: "00000658397a90df6459b8e7e63ad3f4ce8f0a40b8803ff2f29c611b2e0190b8", | ||
926 | * fullTransaction: true | ||
927 | * }).then(function(block) { | ||
928 | * //code | ||
929 | * }); | ||
930 | */ | ||
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); | ||
935 | }; | ||
936 | |||
937 | /** | ||
938 | * Get block header info by the block height. | ||
939 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyheight} | ||
940 | * | ||
941 | * @param {Object} options | ||
942 | * @param {Number} options.height | ||
943 | * @param {Boolean} options.fullTransaction | ||
944 | * | ||
945 | * @return [Block]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getblockbyheight} | ||
946 | * | ||
947 | * @example | ||
948 | * var api = new Neb().api; | ||
949 | * api.getBlockByHeight({height:2, fullTransaction:true}).then(function(block) { | ||
950 | * //code | ||
951 | * }); | ||
952 | */ | ||
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); | ||
957 | }; | ||
958 | |||
959 | /** | ||
960 | * Get transactionReceipt info by tansaction hash. | ||
961 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt} | ||
962 | * | ||
963 | * @param {Object} options | ||
964 | * @param {HexString} options.hash | ||
965 | * | ||
966 | * @return [TransactionReceipt]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt} | ||
967 | * | ||
968 | * @example | ||
969 | * var api = new Neb().api; | ||
970 | * api.getTransactionReceipt({hash: "cc7133643a9ae90ec9fa222871b85349ccb6f04452b835851280285ed72b008c"}).then(function(receipt) { | ||
971 | * //code | ||
972 | * }); | ||
973 | */ | ||
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); | ||
978 | }; | ||
979 | |||
980 | /** | ||
981 | * Get transactionReceipt info by contract address. | ||
982 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionbycontract} | ||
983 | * | ||
984 | * @param {Object} options | ||
985 | * @param {HexString} options.address contract address | ||
986 | * | ||
987 | * @returns the same as [TransactionReceipt]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#gettransactionreceipt} | ||
988 | * | ||
989 | * @example | ||
990 | * var api = new Neb().api; | ||
991 | * api.getTransactionByContract({address: "n1sqDHGjYtX6rMqFoq5Tow3s3LqF4ZxBvE3"}).then(function(receipt) { | ||
992 | * //code | ||
993 | * }); | ||
994 | */ | ||
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); | ||
999 | }; | ||
1000 | |||
1001 | /** | ||
1002 | * Return the subscribed events of transaction & block. | ||
1003 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#subscribe} | ||
1004 | * | ||
1005 | * @param {Object} options | ||
1006 | * @param {Array|String} options.topics | ||
1007 | * @param {Function} options.onDownloadProgress - On progress callback function. Recive chunk. | ||
1008 | * | ||
1009 | * @return [eventData]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#subscribe} | ||
1010 | * | ||
1011 | * @example | ||
1012 | * var api = new Neb().api; | ||
1013 | * api.subscribe({topics: ["chain.linkBlock", "chain.pendingTransaction"]}).then(function(eventData) { | ||
1014 | * //code | ||
1015 | * }); | ||
1016 | */ | ||
1017 | API.prototype.subscribe = function (options) { | ||
1018 | options = utils.argumentsToObject(['topics', 'onDownloadProgress'], arguments); | ||
1019 | var params = { "topics": options.topics }; | ||
1020 | var axiosOptions; | ||
1021 | if (typeof options.onDownloadProgress === 'function') { | ||
1022 | axiosOptions = { | ||
1023 | onDownloadProgress: function (e) { | ||
1024 | if (typeof e.target._readLength === 'undefined') { | ||
1025 | e.target._readLength = 0; | ||
1026 | } | ||
1027 | var chunk = e.target.responseText.substr(e.target._readLength); | ||
1028 | // TODO check and split multi events | ||
1029 | if (chunk && chunk.trim().length > 0) { | ||
1030 | e.target._readLength += chunk.length; | ||
1031 | options.onDownloadProgress(chunk); | ||
1032 | } | ||
1033 | } | ||
1034 | }; | ||
1035 | } | ||
1036 | return this._sendRequest("post", "/subscribe", params, null, axiosOptions); | ||
1037 | }; | ||
1038 | |||
1039 | /** | ||
1040 | * Return current gasPrice. | ||
1041 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getgasprice} | ||
1042 | * | ||
1043 | * @return [Gas Price]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getgasprice} | ||
1044 | * | ||
1045 | * @example | ||
1046 | * var api = new Neb().api; | ||
1047 | * api.gasPrice().then(function(gasPrice) { | ||
1048 | * //code | ||
1049 | * }); | ||
1050 | */ | ||
1051 | API.prototype.gasPrice = function () { | ||
1052 | return this._sendRequest("get", "/getGasPrice", null); | ||
1053 | }; | ||
1054 | |||
1055 | /** | ||
1056 | * Return the estimate gas of transaction. | ||
1057 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#estimategas} | ||
1058 | * | ||
1059 | * @param {TransactionOptions} options | ||
1060 | * | ||
1061 | * @return [Gas]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#estimategas} | ||
1062 | * | ||
1063 | * @example | ||
1064 | * var api = new Neb().api; | ||
1065 | * api.estimateGas({ | ||
1066 | * chainID: 1, | ||
1067 | * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5", | ||
1068 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
1069 | * value: 10, | ||
1070 | * nonce: 12, | ||
1071 | * gasPrice: 1000000, | ||
1072 | * gasLimit: 2000000 | ||
1073 | * }).then(function(gas) { | ||
1074 | * //code | ||
1075 | * }); | ||
1076 | */ | ||
1077 | API.prototype.estimateGas = function (options) { | ||
1078 | options = utils.argumentsToObject(['from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract', 'binary'], arguments); | ||
1079 | var params = { | ||
1080 | "from": options.from, | ||
1081 | "to": options.to, | ||
1082 | "value": utils.toString(options.value), | ||
1083 | "nonce": options.nonce, | ||
1084 | "gasPrice": utils.toString(options.gasPrice), | ||
1085 | "gasLimit": utils.toString(options.gasLimit), | ||
1086 | "contract": options.contract, | ||
1087 | "binary": options.binary | ||
1088 | }; | ||
1089 | return this._sendRequest("post", "/estimateGas", params); | ||
1090 | }; | ||
1091 | |||
1092 | /** | ||
1093 | * Return the events list of transaction. | ||
1094 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#geteventsbyhash} | ||
1095 | * | ||
1096 | * @param {Object} options | ||
1097 | * @param {HexString} options.hash | ||
1098 | * | ||
1099 | * @return [Events]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#geteventsbyhash} | ||
1100 | * | ||
1101 | * @example | ||
1102 | * var api = new Neb().api; | ||
1103 | * api.getEventsByHash({hash: "ec239d532249f84f158ef8ec9262e1d3d439709ebf4dd5f7c1036b26c6fe8073"}).then(function(events) { | ||
1104 | * //code | ||
1105 | * }); | ||
1106 | */ | ||
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); | ||
1111 | }; | ||
1112 | |||
1113 | /** | ||
1114 | * Method getter for dpos dynasty. | ||
1115 | * @see {@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getdynasty} | ||
1116 | * | ||
1117 | * @param {Object} options | ||
1118 | * @param {Number} options.height | ||
1119 | * | ||
1120 | * @return [delegatees]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#getdynasty} | ||
1121 | * | ||
1122 | * @example | ||
1123 | * var api = new Neb().api; | ||
1124 | * api.getDynasty({height: 1}).then(function(delegatees) { | ||
1125 | * //code | ||
1126 | * }); | ||
1127 | */ | ||
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); | ||
1132 | }; | ||
1133 | |||
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); | ||
1138 | } else { | ||
1139 | return this._request.request(method, action, params, axiosOptions); | ||
1140 | } | ||
1141 | }; | ||
1142 | |||
1143 | module.exports = API; | ||
1144 | |||
1145 | },{"./utils/utils.js":21}],4:[function(require,module,exports){ | ||
1146 | "use strict"; | ||
1147 | |||
1148 | var axios = require("axios"); | ||
1149 | |||
1150 | var debugLog = false; | ||
1151 | |||
1152 | var HttpRequest = function (host, timeout, apiVersion) { | ||
1153 | this.host = host || "http://localhost:8685"; | ||
1154 | this.timeout = timeout || 0; | ||
1155 | this.apiVersion = apiVersion || "v1"; | ||
1156 | }; | ||
1157 | |||
1158 | HttpRequest.prototype.setHost = function (host) { | ||
1159 | this.host = host; | ||
1160 | }; | ||
1161 | |||
1162 | HttpRequest.prototype.setAPIVersion = function (apiVersion) { | ||
1163 | this.apiVersion = apiVersion; | ||
1164 | }; | ||
1165 | |||
1166 | HttpRequest.prototype.createUrl = function (api) { | ||
1167 | return this.host + "/" + this.apiVersion + api; | ||
1168 | }; | ||
1169 | |||
1170 | HttpRequest.prototype.request = function (method, api, payload, axiosOptions) { | ||
1171 | if (debugLog) { | ||
1172 | console.log("[debug] HttpRequest: " + method + " " + this.createUrl(api) + " " + JSON.stringify(payload)); | ||
1173 | } | ||
1174 | |||
1175 | var axiosParams = { | ||
1176 | method: method, | ||
1177 | url: this.createUrl(api), | ||
1178 | data: payload | ||
1179 | }; | ||
1180 | if (axiosOptions && typeof axiosOptions.onDownloadProgress === 'function') { | ||
1181 | axiosParams.onDownloadProgress = axiosOptions.onDownloadProgress; | ||
1182 | } | ||
1183 | return axios(axiosParams).then(function (resp) { | ||
1184 | if ("text/html; charset=UTF-8" === resp.headers['content-type']) { | ||
1185 | throw new Error(resp.status + ' - ' + resp.statusText); | ||
1186 | } | ||
1187 | if (typeof resp.data === "string") { | ||
1188 | try { | ||
1189 | resp.data = JSON.parse(resp.data); | ||
1190 | } catch (e) { | ||
1191 | throw new Error('Response is invalid json'); | ||
1192 | } | ||
1193 | } | ||
1194 | return resp.data.result || resp.data; | ||
1195 | }).catch(function (e) { | ||
1196 | if (typeof e.response !== "undefined") { | ||
1197 | if (typeof e.response.data === 'object') { | ||
1198 | //400 error | ||
1199 | throw new Error(e.response.data.error); | ||
1200 | } else { | ||
1201 | //500 error | ||
1202 | var err = e.response.status + ' - ' + e.response.statusText; | ||
1203 | err += "\n" + api + " " + JSON.stringify(payload); | ||
1204 | throw new Error(err); | ||
1205 | } | ||
1206 | } else { | ||
1207 | throw new Error(e.message); | ||
1208 | } | ||
1209 | }); | ||
1210 | }; | ||
1211 | |||
1212 | HttpRequest.prototype.asyncRequest = function (method, api, payload, callback) { | ||
1213 | return this.request(method, api, payload).then(function (data) { | ||
1214 | callback(data); | ||
1215 | }).catch(function (err) { | ||
1216 | callback(err); | ||
1217 | }); | ||
1218 | }; | ||
1219 | |||
1220 | module.exports = HttpRequest; | ||
1221 | |||
1222 | },{"axios":46}],5:[function(require,module,exports){ | ||
1223 | |||
1224 | "use strict"; | ||
1225 | |||
1226 | var API = require("./api.js"); | ||
1227 | var Admin = require("./admin.js"); | ||
1228 | |||
1229 | var Unit = require("./utils/unit.js"); | ||
1230 | |||
1231 | /** | ||
1232 | * Neb API library constructor. | ||
1233 | * @constructor | ||
1234 | * @param {Request} request - transport wrapper. | ||
1235 | */ | ||
1236 | var Neb = function (request) { | ||
1237 | if (request) { | ||
1238 | this._request = request; | ||
1239 | } | ||
1240 | |||
1241 | this.api = new API(this); | ||
1242 | this.admin = new Admin(this); | ||
1243 | }; | ||
1244 | |||
1245 | Neb.prototype.setRequest = function (request) { | ||
1246 | this._request = request; | ||
1247 | this.api._setRequest(request); | ||
1248 | this.admin._setRequest(request); | ||
1249 | }; | ||
1250 | |||
1251 | Neb.prototype.toBasic = Unit.toBasic; | ||
1252 | Neb.prototype.fromBasic = Unit.fromBasic; | ||
1253 | Neb.prototype.nasToBasic = Unit.nasToBasic; | ||
1254 | |||
1255 | module.exports = Neb; | ||
1256 | |||
1257 | },{"./admin.js":2,"./api.js":3,"./utils/unit.js":20}],6:[function(require,module,exports){ | ||
1258 | "use strict"; | ||
1259 | |||
1260 | var block = { | ||
1261 | timestamp: 0, | ||
1262 | height: 1, | ||
1263 | seed: "s" | ||
1264 | }; | ||
1265 | |||
1266 | var transaction = { | ||
1267 | hash: "", | ||
1268 | from: "", | ||
1269 | to: "", | ||
1270 | value: "0", | ||
1271 | nonce: 1, | ||
1272 | timestamp: 0, | ||
1273 | gasPrice: "0", | ||
1274 | gasLimit: "0" | ||
1275 | }; | ||
1276 | |||
1277 | var state = function () {}; | ||
1278 | |||
1279 | module.exports = { | ||
1280 | block: block, | ||
1281 | transaction: transaction, | ||
1282 | state: state | ||
1283 | }; | ||
1284 | |||
1285 | },{}],7:[function(require,module,exports){ | ||
1286 | // Copyright (C) 2017 go-nebulas authors | ||
1287 | // | ||
1288 | // This file is part of the go-nebulas library. | ||
1289 | // | ||
1290 | // the go-nebulas library is free software: you can redistribute it and/or modify | ||
1291 | // it under the terms of the GNU General Public License as published by | ||
1292 | // the Free Software Foundation, either version 3 of the License, or | ||
1293 | // (at your option) any later version. | ||
1294 | // | ||
1295 | // the go-nebulas library is distributed in the hope that it will be useful, | ||
1296 | // but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1297 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1298 | // GNU General Public License for more details. | ||
1299 | // | ||
1300 | // You should have received a copy of the GNU General Public License | ||
1301 | // along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>. | ||
1302 | // | ||
1303 | |||
1304 | 'use strict'; | ||
1305 | |||
1306 | var Blockchain = function () { | ||
1307 | Object.defineProperty(this, "nativeBlockchain", { | ||
1308 | configurable: false, | ||
1309 | enumerable: false, | ||
1310 | get: function () { | ||
1311 | return _native_blockchain; | ||
1312 | } | ||
1313 | }); | ||
1314 | }; | ||
1315 | |||
1316 | Blockchain.prototype = { | ||
1317 | AccountAddress: 0x57, | ||
1318 | ContractAddress: 0x58, | ||
1319 | |||
1320 | blockParse: function (str) { | ||
1321 | this.block = JSON.parse(str); | ||
1322 | }, | ||
1323 | transactionParse: function (str) { | ||
1324 | var tx = JSON.parse(str); | ||
1325 | if (tx != null) { | ||
1326 | var value = tx.value === undefined || tx.value.length === 0 ? "0" : tx.value; | ||
1327 | tx.value = new BigNumber(value); | ||
1328 | var gasPrice = tx.gasPrice === undefined || tx.gasPrice.length === 0 ? "0" : tx.gasPrice; | ||
1329 | tx.gasPrice = new BigNumber(gasPrice); | ||
1330 | var gasLimit = tx.gasLimit === undefined || tx.gasLimit.length === 0 ? "0" : tx.gasLimit; | ||
1331 | tx.gasLimit = new BigNumber(gasLimit); | ||
1332 | this.transaction = tx; | ||
1333 | } | ||
1334 | }, | ||
1335 | transfer: function (address, value) { | ||
1336 | if (!(value instanceof BigNumber)) { | ||
1337 | value = new BigNumber(value); | ||
1338 | } | ||
1339 | var ret = this.nativeBlockchain.transfer(address, value.toString(10)); | ||
1340 | return ret == 0; | ||
1341 | }, | ||
1342 | verifyAddress: function (address) { | ||
1343 | return this.nativeBlockchain.verifyAddress(address); | ||
1344 | } | ||
1345 | }; | ||
1346 | module.exports = new Blockchain(); | ||
1347 | |||
1348 | },{}],8:[function(require,module,exports){ | ||
1349 | // Copyright (C) 2017 go-nebulas authors | ||
1350 | // | ||
1351 | // This file is part of the go-nebulas library. | ||
1352 | // | ||
1353 | // the go-nebulas library is free software: you can redistribute it and/or modify | ||
1354 | // it under the terms of the GNU General Public License as published by | ||
1355 | // the Free Software Foundation, either version 3 of the License, or | ||
1356 | // (at your option) any later version. | ||
1357 | // | ||
1358 | // the go-nebulas library is distributed in the hope that it will be useful, | ||
1359 | // but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1360 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1361 | // GNU General Public License for more details. | ||
1362 | // | ||
1363 | // You should have received a copy of the GNU General Public License | ||
1364 | // along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>. | ||
1365 | // | ||
1366 | |||
1367 | 'use strict'; | ||
1368 | |||
1369 | function Console() {} | ||
1370 | |||
1371 | function log(...args) { | ||
1372 | var level = args.shift(); | ||
1373 | if (typeof level != 'number') { | ||
1374 | throw 'level must be number.'; | ||
1375 | } | ||
1376 | |||
1377 | var msg = ''; | ||
1378 | for (var i = 0; i < args.length - 1; i++) { | ||
1379 | msg += format(args[i]) + ' '; | ||
1380 | } | ||
1381 | msg += format(args[args.length - 1]); | ||
1382 | |||
1383 | _native_log(level, msg); | ||
1384 | } | ||
1385 | |||
1386 | function format(obj) { | ||
1387 | if (typeof obj == 'object') { | ||
1388 | return JSON.stringify(obj); | ||
1389 | } | ||
1390 | return obj; | ||
1391 | } | ||
1392 | |||
1393 | [['debug', 1], ['warn', 2], ['info', 3], ['log', 3], ['error', 4]].forEach(function (val) { | ||
1394 | Console.prototype[val[0]] = log.bind(null, val[1]); | ||
1395 | }); | ||
1396 | |||
1397 | module.exports = new Console(); | ||
1398 | module.exports.Console = Console; | ||
1399 | |||
1400 | },{}],9:[function(require,module,exports){ | ||
1401 | // Copyright (C) 2017 go-nebulas authors | ||
1402 | // | ||
1403 | // This file is part of the go-nebulas library. | ||
1404 | // | ||
1405 | // the go-nebulas library is free software: you can redistribute it and/or modify | ||
1406 | // it under the terms of the GNU General Public License as published by | ||
1407 | // the Free Software Foundation, either version 3 of the License, or | ||
1408 | // (at your option) any later version. | ||
1409 | // | ||
1410 | // the go-nebulas library is distributed in the hope that it will be useful, | ||
1411 | // but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1412 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1413 | // GNU General Public License for more details. | ||
1414 | // | ||
1415 | // You should have received a copy of the GNU General Public License | ||
1416 | // along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>. | ||
1417 | // | ||
1418 | |||
1419 | 'use strict'; | ||
1420 | |||
1421 | exports["Trigger"] = function (topic, data) { | ||
1422 | _native_event_trigger(topic, JSON.stringify(data)); | ||
1423 | }; | ||
1424 | |||
1425 | },{}],10:[function(require,module,exports){ | ||
1426 | // Copyright (C) 2017 go-nebulas authors | ||
1427 | // | ||
1428 | // This file is part of the go-nebulas library. | ||
1429 | // | ||
1430 | // the go-nebulas library is free software: you can redistribute it and/or modify | ||
1431 | // it under the terms of the GNU General Public License as published by | ||
1432 | // the Free Software Foundation, either version 3 of the License, or | ||
1433 | // (at your option) any later version. | ||
1434 | // | ||
1435 | // the go-nebulas library is distributed in the hope that it will be useful, | ||
1436 | // but WITHOUT ANY WARRANTY; without even the implied warranty of | ||
1437 | // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the | ||
1438 | // GNU General Public License for more details. | ||
1439 | // | ||
1440 | // You should have received a copy of the GNU General Public License | ||
1441 | // along with the go-nebulas library. If not, see <http://www.gnu.org/licenses/>. | ||
1442 | // | ||
1443 | |||
1444 | 'use strict'; | ||
1445 | |||
1446 | var fieldNameRe = /^[a-zA-Z_$][a-zA-Z0-9_]+$/; | ||
1447 | |||
1448 | var combineStorageMapKey = function (fieldName, key) { | ||
1449 | return "@" + fieldName + "[" + key + "]"; | ||
1450 | }; | ||
1451 | |||
1452 | var applyMapDescriptor = function (obj, descriptor) { | ||
1453 | descriptor = Object.assign({ | ||
1454 | stringify: JSON.stringify, | ||
1455 | parse: JSON.parse | ||
1456 | }, descriptor || {}); | ||
1457 | |||
1458 | if (typeof descriptor.stringify !== 'function' || typeof descriptor.parse !== 'function') { | ||
1459 | throw new Error("descriptor.stringify and descriptor.parse must be function."); | ||
1460 | } | ||
1461 | |||
1462 | Object.defineProperty(obj, "stringify", { | ||
1463 | configurable: false, | ||
1464 | enumerable: false, | ||
1465 | get: function () { | ||
1466 | return descriptor.stringify; | ||
1467 | } | ||
1468 | }); | ||
1469 | |||
1470 | Object.defineProperty(obj, "parse", { | ||
1471 | configurable: false, | ||
1472 | enumerable: false, | ||
1473 | get: function () { | ||
1474 | return descriptor.parse; | ||
1475 | } | ||
1476 | }); | ||
1477 | }; | ||
1478 | |||
1479 | var applyFieldDescriptor = function (obj, fieldName, descriptor) { | ||
1480 | descriptor = Object.assign({ | ||
1481 | stringify: JSON.stringify, | ||
1482 | parse: JSON.parse | ||
1483 | }, descriptor || {}); | ||
1484 | |||
1485 | if (typeof descriptor.stringify !== 'function' || typeof descriptor.parse !== 'function') { | ||
1486 | throw new Error("descriptor.stringify and descriptor.parse must be function."); | ||
1487 | } | ||
1488 | |||
1489 | Object.defineProperty(obj, "__stringify__" + fieldName, { | ||
1490 | configurable: false, | ||
1491 | enumerable: false, | ||
1492 | get: function () { | ||
1493 | return descriptor.stringify; | ||
1494 | } | ||
1495 | }); | ||
1496 | |||
1497 | Object.defineProperty(obj, "__parse__" + fieldName, { | ||
1498 | configurable: false, | ||
1499 | enumerable: false, | ||
1500 | get: function () { | ||
1501 | return descriptor.parse; | ||
1502 | } | ||
1503 | }); | ||
1504 | }; | ||
1505 | |||
1506 | var ContractStorage = function (handler) { | ||
1507 | var ns = new NativeStorage(handler); | ||
1508 | Object.defineProperty(this, "nativeStorage", { | ||
1509 | configurable: false, | ||
1510 | enumerable: false, | ||
1511 | get: function () { | ||
1512 | return ns; | ||
1513 | } | ||
1514 | }); | ||
1515 | }; | ||
1516 | |||
1517 | var StorageMap = function (contractStorage, fieldName, descriptor) { | ||
1518 | if (!contractStorage instanceof ContractStorage) { | ||
1519 | throw new Error("StorageMap only accept instance of ContractStorage"); | ||
1520 | } | ||
1521 | |||
1522 | if (typeof fieldName !== "string" || fieldNameRe.exec(fieldName) == null) { | ||
1523 | throw new Error("StorageMap fieldName must match regex /^[a-zA-Z_$].*$/"); | ||
1524 | } | ||
1525 | |||
1526 | Object.defineProperty(this, "contractStorage", { | ||
1527 | configurable: false, | ||
1528 | enumerable: false, | ||
1529 | get: function () { | ||
1530 | return contractStorage; | ||
1531 | } | ||
1532 | }); | ||
1533 | Object.defineProperty(this, "fieldName", { | ||
1534 | configurable: false, | ||
1535 | enumerable: false, | ||
1536 | get: function () { | ||
1537 | return fieldName; | ||
1538 | } | ||
1539 | }); | ||
1540 | |||
1541 | applyMapDescriptor(this, descriptor); | ||
1542 | }; | ||
1543 | |||
1544 | StorageMap.prototype = { | ||
1545 | del: function (key) { | ||
1546 | return this.contractStorage.del(combineStorageMapKey(this.fieldName, key)); | ||
1547 | }, | ||
1548 | get: function (key) { | ||
1549 | var val = this.contractStorage.rawGet(combineStorageMapKey(this.fieldName, key)); | ||
1550 | if (val != null) { | ||
1551 | val = this.parse(val); | ||
1552 | } | ||
1553 | return val; | ||
1554 | }, | ||
1555 | set: function (key, value) { | ||
1556 | var val = this.stringify(value); | ||
1557 | return this.contractStorage.rawSet(combineStorageMapKey(this.fieldName, key), val); | ||
1558 | } | ||
1559 | }; | ||
1560 | StorageMap.prototype.put = StorageMap.prototype.set; | ||
1561 | StorageMap.prototype.delete = StorageMap.prototype.del; | ||
1562 | |||
1563 | ContractStorage.prototype = { | ||
1564 | rawGet: function (key) { | ||
1565 | return this.nativeStorage.get(key); | ||
1566 | }, | ||
1567 | rawSet: function (key, value) { | ||
1568 | var ret = this.nativeStorage.set(key, value); | ||
1569 | if (ret != 0) { | ||
1570 | throw new Error("set key " + key + " failed."); | ||
1571 | } | ||
1572 | return ret; | ||
1573 | }, | ||
1574 | del: function (key) { | ||
1575 | var ret = this.nativeStorage.del(key); | ||
1576 | if (ret != 0) { | ||
1577 | throw new Error("del key " + key + " failed."); | ||
1578 | } | ||
1579 | return ret; | ||
1580 | }, | ||
1581 | get: function (key) { | ||
1582 | var val = this.rawGet(key); | ||
1583 | if (val != null) { | ||
1584 | val = JSON.parse(val); | ||
1585 | } | ||
1586 | return val; | ||
1587 | }, | ||
1588 | set: function (key, value) { | ||
1589 | return this.rawSet(key, JSON.stringify(value)); | ||
1590 | }, | ||
1591 | defineProperty: function (obj, fieldName, descriptor) { | ||
1592 | if (!obj || !fieldName) { | ||
1593 | throw new Error("defineProperty requires at least two parameters."); | ||
1594 | } | ||
1595 | var $this = this; | ||
1596 | Object.defineProperty(obj, fieldName, { | ||
1597 | configurable: false, | ||
1598 | enumerable: true, | ||
1599 | get: function () { | ||
1600 | var val = $this.rawGet(fieldName); | ||
1601 | if (val != null) { | ||
1602 | val = obj["__parse__" + fieldName](val); | ||
1603 | } | ||
1604 | return val; | ||
1605 | }, | ||
1606 | set: function (val) { | ||
1607 | val = obj["__stringify__" + fieldName](val); | ||
1608 | return $this.rawSet(fieldName, val); | ||
1609 | } | ||
1610 | }); | ||
1611 | applyFieldDescriptor(obj, fieldName, descriptor); | ||
1612 | return this; | ||
1613 | }, | ||
1614 | defineProperties: function (obj, props) { | ||
1615 | if (!obj || !props) { | ||
1616 | throw new Error("defineProperties requires two parameters."); | ||
1617 | } | ||
1618 | |||
1619 | for (const fieldName in props) { | ||
1620 | this.defineProperty(obj, fieldName, props[fieldName]); | ||
1621 | } | ||
1622 | return this; | ||
1623 | }, | ||
1624 | defineMapProperty: function (obj, fieldName, descriptor) { | ||
1625 | if (!obj || !fieldName) { | ||
1626 | throw new Error("defineMapProperty requires two parameters."); | ||
1627 | } | ||
1628 | |||
1629 | var mapObj = new StorageMap(this, fieldName, descriptor); | ||
1630 | Object.defineProperty(obj, fieldName, { | ||
1631 | configurable: false, | ||
1632 | enumerable: true, | ||
1633 | get: function () { | ||
1634 | return mapObj; | ||
1635 | } | ||
1636 | }); | ||
1637 | return this; | ||
1638 | }, | ||
1639 | defineMapProperties: function (obj, props) { | ||
1640 | if (!obj || !props) { | ||
1641 | throw new Error("defineMapProperties requires two parameters."); | ||
1642 | } | ||
1643 | |||
1644 | for (const fieldName in props) { | ||
1645 | this.defineMapProperty(obj, fieldName, props[fieldName]); | ||
1646 | } | ||
1647 | return this; | ||
1648 | } | ||
1649 | }; | ||
1650 | |||
1651 | ContractStorage.prototype.put = ContractStorage.prototype.set; | ||
1652 | ContractStorage.prototype.delete = ContractStorage.prototype.del; | ||
1653 | |||
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, | ||
1659 | enumerable: false, | ||
1660 | get: function () { | ||
1661 | return lcs; | ||
1662 | } | ||
1663 | }); | ||
1664 | |||
1665 | Object.defineProperty(obj, "gcs", { | ||
1666 | configurable: false, | ||
1667 | enumerable: false, | ||
1668 | get: function () { | ||
1669 | return gcs; | ||
1670 | } | ||
1671 | }); | ||
1672 | |||
1673 | module.exports = Object.freeze(obj); | ||
1674 | |||
1675 | },{}],11:[function(require,module,exports){ | ||
1676 | (function (global,__dirname){ | ||
1677 | |||
1678 | |||
1679 | global; | ||
1680 | |||
1681 | if (typeof window !== "undefined") { | ||
1682 | global = window; | ||
1683 | } | ||
1684 | |||
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); | ||
1690 | } | ||
1691 | |||
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; | ||
1698 | |||
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"); | ||
1707 | |||
1708 | // global.Date = require('./libs/date'); | ||
1709 | // global.Math.random = require('./libs/random'); | ||
1710 | // global.BigNumber.random = global.Math.random; | ||
1711 | |||
1712 | module.exports = { | ||
1713 | context: global.context | ||
1714 | }; | ||
1715 | |||
1716 | }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {},"/lib/nvm") | ||
1717 | },{"./context":6,"./libs/blockchain":7,"./libs/console":8,"./libs/event":9,"./libs/storage":10,"./native/blockchain":12,"./native/event":13,"./native/log":14,"./native/storage":15,"bignumber.js":73,"node-localstorage":"node-localstorage.js","path":183}],12:[function(require,module,exports){ | ||
1718 | "use strict"; | ||
1719 | |||
1720 | var Account = require("../../account"); | ||
1721 | |||
1722 | var transfer = function (to, value) { | ||
1723 | // TODO: mock the transfer func in nebulas | ||
1724 | return 0; | ||
1725 | }; | ||
1726 | |||
1727 | var verifyAddress = function (address) { | ||
1728 | return Account.isValidAddress(address); | ||
1729 | }; | ||
1730 | |||
1731 | module.exports = { | ||
1732 | transfer: transfer, | ||
1733 | verifyAddress: verifyAddress | ||
1734 | }; | ||
1735 | |||
1736 | },{"../../account":1}],13:[function(require,module,exports){ | ||
1737 | "use strict"; | ||
1738 | |||
1739 | var trigger = function (topic, data) { | ||
1740 | var event = { | ||
1741 | Topic: topic, | ||
1742 | Data: data | ||
1743 | }; | ||
1744 | var key = context.transaction.hash; | ||
1745 | var events = localStorage.getItem(key); | ||
1746 | if (events === null || typeof events === "undefined") { | ||
1747 | events = new Array(); | ||
1748 | } else { | ||
1749 | events = Array.from(events); | ||
1750 | } | ||
1751 | events.push(event); | ||
1752 | localStorage.setItem(key, events); | ||
1753 | }; | ||
1754 | |||
1755 | module.exports = trigger; | ||
1756 | |||
1757 | },{}],14:[function(require,module,exports){ | ||
1758 | "use strict"; | ||
1759 | |||
1760 | var log = function (level, msg) { | ||
1761 | var levelStr; | ||
1762 | switch (level) { | ||
1763 | case 1: | ||
1764 | levelStr = "debug"; | ||
1765 | case 2: | ||
1766 | levelStr = "warn"; | ||
1767 | case 3: | ||
1768 | levelStr = "info"; | ||
1769 | case 4: | ||
1770 | levelStr = "error"; | ||
1771 | default: | ||
1772 | levelStr = "info"; | ||
1773 | } | ||
1774 | var log = levelStr + ":" + msg; | ||
1775 | nativeConsole.log(log); | ||
1776 | }; | ||
1777 | |||
1778 | module.exports = log; | ||
1779 | |||
1780 | },{}],15:[function(require,module,exports){ | ||
1781 | "use strict"; | ||
1782 | |||
1783 | var handlers = { | ||
1784 | lcs: 1, | ||
1785 | gcs: 2 | ||
1786 | }; | ||
1787 | |||
1788 | var NativeStorage = function (handler) { | ||
1789 | this.handler = handler; | ||
1790 | }; | ||
1791 | |||
1792 | NativeStorage.prototype = { | ||
1793 | get: function (key) { | ||
1794 | return localStorage.getItem(key); | ||
1795 | }, | ||
1796 | set: function (key, value) { | ||
1797 | localStorage.setItem(key, value); | ||
1798 | return 0; | ||
1799 | }, | ||
1800 | del: function (key) { | ||
1801 | localStorage.removeItem(key); | ||
1802 | return 0; | ||
1803 | } | ||
1804 | }; | ||
1805 | |||
1806 | module.exports = { | ||
1807 | handlers: handlers, | ||
1808 | NativeStorage: NativeStorage | ||
1809 | }; | ||
1810 | |||
1811 | },{}],16:[function(require,module,exports){ | ||
1812 | "use strict"; | ||
1813 | |||
1814 | var extend = require('extend'); | ||
1815 | var native = require("./native"); | ||
1816 | |||
1817 | var funcRegex = new RegExp("^[a-zA-Z$][A-Za-z0-9_$]*$"); | ||
1818 | |||
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); | ||
1824 | }; | ||
1825 | |||
1826 | NVM.prototype = { | ||
1827 | deploy: function (source, args) { | ||
1828 | return this.run(source, "init", args); | ||
1829 | }, | ||
1830 | call: function (source, func, args) { | ||
1831 | if (funcRegex.test(func)) { | ||
1832 | return this.run(source, func, args); | ||
1833 | } else { | ||
1834 | throw new Error("invalid func"); | ||
1835 | } | ||
1836 | }, | ||
1837 | run: function (source, func, args) { | ||
1838 | Blockchain.blockParse(JSON.stringify(native.context.block)); | ||
1839 | Blockchain.transactionParse(JSON.stringify(native.context.transaction)); | ||
1840 | var Contract = eval(source); | ||
1841 | // console.log("contract:", Contract); | ||
1842 | var contract = new Contract(); | ||
1843 | if (args === undefined || args.length === 0) { | ||
1844 | args = "[]"; | ||
1845 | } | ||
1846 | if (contract[func] != undefined) { | ||
1847 | return contract[func].apply(contract, JSON.parse(args)); | ||
1848 | } else { | ||
1849 | throw new Error("function not found"); | ||
1850 | } | ||
1851 | } | ||
1852 | }; | ||
1853 | |||
1854 | module.exports = NVM; | ||
1855 | |||
1856 | },{"./native":11,"extend":145}],17:[function(require,module,exports){ | ||
1857 | module.exports={ | ||
1858 | "nested": { | ||
1859 | "corepb": { | ||
1860 | "nested": { | ||
1861 | "Data": { | ||
1862 | "fields": { | ||
1863 | "type": { | ||
1864 | "type": "string", | ||
1865 | "id": 1 | ||
1866 | }, | ||
1867 | "payload": { | ||
1868 | "type": "bytes", | ||
1869 | "id": 2 | ||
1870 | } | ||
1871 | } | ||
1872 | }, | ||
1873 | "Transaction": { | ||
1874 | "fields": { | ||
1875 | "hash": { | ||
1876 | "type": "bytes", | ||
1877 | "id": 1 | ||
1878 | }, | ||
1879 | "from": { | ||
1880 | "type": "bytes", | ||
1881 | "id": 2 | ||
1882 | }, | ||
1883 | "to": { | ||
1884 | "type": "bytes", | ||
1885 | "id": 3 | ||
1886 | }, | ||
1887 | "value": { | ||
1888 | "type": "bytes", | ||
1889 | "id": 4 | ||
1890 | }, | ||
1891 | "nonce": { | ||
1892 | "type": "uint64", | ||
1893 | "id": 5 | ||
1894 | }, | ||
1895 | "timestamp": { | ||
1896 | "type": "int64", | ||
1897 | "id": 6 | ||
1898 | }, | ||
1899 | "data": { | ||
1900 | "type": "Data", | ||
1901 | "id": 7 | ||
1902 | }, | ||
1903 | "chainId": { | ||
1904 | "type": "uint32", | ||
1905 | "id": 8 | ||
1906 | }, | ||
1907 | "gasPrice": { | ||
1908 | "type": "bytes", | ||
1909 | "id": 9 | ||
1910 | }, | ||
1911 | "gasLimit": { | ||
1912 | "type": "bytes", | ||
1913 | "id": 10 | ||
1914 | }, | ||
1915 | "alg": { | ||
1916 | "type": "uint32", | ||
1917 | "id": 11 | ||
1918 | }, | ||
1919 | "sign": { | ||
1920 | "type": "bytes", | ||
1921 | "id": 12 | ||
1922 | } | ||
1923 | } | ||
1924 | } | ||
1925 | } | ||
1926 | } | ||
1927 | } | ||
1928 | } | ||
1929 | },{}],18:[function(require,module,exports){ | ||
1930 | "use strict"; | ||
1931 | |||
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'); | ||
1938 | |||
1939 | var SECP256K1 = 1; | ||
1940 | var root = protobuf.Root.fromJSON(require("./transaction.json")); | ||
1941 | |||
1942 | var TxPayloadBinaryType = "binary"; | ||
1943 | var TxPayloadDeployType = "deploy"; | ||
1944 | var TxPayloadCallType = "call"; | ||
1945 | |||
1946 | /** | ||
1947 | * @typedef TransactionInit | ||
1948 | * @example | ||
1949 | * var acc = Account.NewAccount(); | ||
1950 | * | ||
1951 | * var tx = new Transaction({ | ||
1952 | * chainID: 1, | ||
1953 | * from: acc, | ||
1954 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
1955 | * value: 10, | ||
1956 | * nonce: 12, | ||
1957 | * gasPrice: 1000000, | ||
1958 | * gasLimit: 2000000 | ||
1959 | * }); | ||
1960 | */ | ||
1961 | |||
1962 | /** | ||
1963 | * Represent of smart contract payload data. | ||
1964 | * | ||
1965 | * @typedef {Object} Contract | ||
1966 | * @property {String} source - Contract source code for deploy contract. | ||
1967 | * @property {String} sourceType - Contract source type for deploy contract. Currently support js and ts. | ||
1968 | * @property {String} args - The params of contract. The args content is JSON string of parameters array. | ||
1969 | * @property {String} function - The contract call function. | ||
1970 | * @property {Buffer} binary - Binary contract representation. | ||
1971 | * | ||
1972 | * @see [Create own smart contract in Nebulas.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md} | ||
1973 | * @see [More about transaction parameters.]{@link https://github.com/nebulasio/wiki/blob/c3f5ce8908c80e9104e3b512a7fdfd75f16ac38c/rpc.md#sendtransaction} | ||
1974 | * | ||
1975 | * @example | ||
1976 | * // It's example of possible fields values. | ||
1977 | * // For deploy, and execute smart contracts follow this link - https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md | ||
1978 | * { | ||
1979 | * 'source': '"use strict";var DepositeContent=function(t){if(t){let n=JSON.parse(t);' + | ||
1980 | * 'this.balance=new BigNumber(n.balance),this.expiryHeight=new BigNumber(n.expiryHeight)' + | ||
1981 | * '}else this.balance=new BigNumber(0),this.expiryHeight=new BigNumber(0)};' + | ||
1982 | * 'DepositeContent.prototype={toString:function(){return JSON.stringify(this)}};' + | ||
1983 | * 'var BankVaultContract=function(){LocalContractStorage.defineMapProperty(this,"bankVault",' + | ||
1984 | * '{parse:function(t){return new DepositeContent(t)},stringify:function(t){return t.toString()}})};' + | ||
1985 | * 'BankVaultContract.prototype={init:function(){},save:function(t){var n=Blockchain.transaction.from,' + | ||
1986 | * 'e=Blockchain.transaction.value,a=new BigNumber(Blockchain.block.height),r=this.bankVault.get(n);' + | ||
1987 | * 'r&&(e=e.plus(r.balance));var i=new DepositeContent;i.balance=e,i.expiryHeight=a.plus(t),' + | ||
1988 | * 'this.bankVault.put(n,i)},takeout:function(t){var n=Blockchain.transaction.from,' + | ||
1989 | * 'e=new BigNumber(Blockchain.block.height),a=new BigNumber(t),r=this.bankVault.get(n);' + | ||
1990 | * 'if(!r)throw new Error("No deposit before.");if(e.lt(r.expiryHeight))throw new Error("Can't takeout before expiryHeight.");' + | ||
1991 | * 'if(a.gt(r.balance))throw new Error("Insufficient balance.");if(0!=Blockchain.transfer(n,a))throw new Error("transfer failed.");' + | ||
1992 | * 'Event.Trigger("BankVault",{Transfer:{from:Blockchain.transaction.to,to:n,value:a.toString()}}),' + | ||
1993 | * 'r.balance=r.balance.sub(a),this.bankVault.put(n,r)},balanceOf:function(){var t=Blockchain.transaction.from;' + | ||
1994 | * 'return this.bankVault.get(t)}},module.exports=BankVaultContract;', | ||
1995 | * 'sourceType': 'js', | ||
1996 | * 'args': '[0]', | ||
1997 | * 'function': 'save' | ||
1998 | * } | ||
1999 | */ | ||
2000 | |||
2001 | /** | ||
2002 | * Represent Transaction parameters | ||
2003 | * | ||
2004 | * @typedef {Object} TransactionOptions | ||
2005 | * @property {Number} options.chainID - Transaction chain id. | ||
2006 | * @property {HexString} options.from - Hex string of the sender account addresss.. | ||
2007 | * @property {HexString} options.to - Hex string of the receiver account addresss.. | ||
2008 | * @property {Number} options.value - Value of transaction. | ||
2009 | * @property {Number} options.nonce - Transaction nonce. | ||
2010 | * @property {Number} options.gasPrice - Gas price. The unit is 10^-18 NAS. | ||
2011 | * @property {Number} options.gasLimit - Transaction gas limit. | ||
2012 | * @property {Contract} [options.contract] | ||
2013 | * | ||
2014 | * @example | ||
2015 | * { | ||
2016 | * chainID: 1, | ||
2017 | * from: "n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5", | ||
2018 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
2019 | * value: 10, | ||
2020 | * nonce: 12, | ||
2021 | * gasPrice: 1000000, | ||
2022 | * gasLimit: 2000000 | ||
2023 | * } | ||
2024 | */ | ||
2025 | |||
2026 | /** | ||
2027 | * Transaction constructor. | ||
2028 | * Class encapsulate main operation with transactions. | ||
2029 | * @see [For more information about parameters, follow this link]{@link https://github.com/nebulasio/wiki/blob/master/rpc.md#sendrawtransaction} | ||
2030 | * @constructor | ||
2031 | * | ||
2032 | * @param {TransactionOptions} options - Transaction options. | ||
2033 | * | ||
2034 | * @see [Transaction tutorial.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2002%20Transaction.md} | ||
2035 | * @see [Create own smart contract in Nebulas.]{@link https://github.com/nebulasio/wiki/blob/master/tutorials/%5BEnglish%5D%20Nebulas%20101%20-%2003%20Smart%20Contracts%20JavaScript.md} | ||
2036 | * @see [More about transaction parameters.]{@link https://github.com/nebulasio/wiki/blob/c3f5ce8908c80e9104e3b512a7fdfd75f16ac38c/rpc.md#sendtransaction} | ||
2037 | * | ||
2038 | * @example | ||
2039 | * var acc = Account.NewAccount(); | ||
2040 | * | ||
2041 | * var tx = new Transaction({ | ||
2042 | * chainID: 1, | ||
2043 | * from: acc, | ||
2044 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
2045 | * value: 10, | ||
2046 | * nonce: 12, | ||
2047 | * gasPrice: 1000000, | ||
2048 | * gasLimit: 2000000, | ||
2049 | * contract: { | ||
2050 | * function: "save", | ||
2051 | * args: "[0]" | ||
2052 | * } | ||
2053 | * }); | ||
2054 | * | ||
2055 | */ | ||
2056 | var Transaction = function (options) { | ||
2057 | if (arguments.length > 0) { | ||
2058 | options = utils.argumentsToObject(['chainID', 'from', 'to', 'value', 'nonce', 'gasPrice', 'gasLimit', 'contract'], arguments); | ||
2059 | |||
2060 | this.chainID = options.chainID; | ||
2061 | this.from = account.fromAddress(options.from); | ||
2062 | this.to = account.fromAddress(options.to); | ||
2063 | this.value = utils.toBigNumber(options.value); | ||
2064 | if (!this.value.isInteger()) throw new Error("Invalid value! The minimum unit is wei (1^-18nas)"); | ||
2065 | this.nonce = parseInt(options.nonce); // An error will be thrown is nonce is string. Error: "nonce: integer|Long expected" | ||
2066 | this.timestamp = Math.floor(new Date().getTime() / 1000); | ||
2067 | this.contract = options.contract; | ||
2068 | this.gasPrice = utils.toBigNumber(options.gasPrice); | ||
2069 | this.gasLimit = utils.toBigNumber(options.gasLimit); | ||
2070 | |||
2071 | this.data = parseContract(this.contract); | ||
2072 | if (this.gasPrice.lessThanOrEqualTo(0)) { | ||
2073 | this.gasPrice = new BigNumber(1000000); | ||
2074 | } | ||
2075 | |||
2076 | if (this.gasLimit.lessThanOrEqualTo(0)) { | ||
2077 | this.gasLimit = new BigNumber(20000); | ||
2078 | } | ||
2079 | } | ||
2080 | this.signErrorMessage = "You should sign transaction before this operation."; | ||
2081 | }; | ||
2082 | |||
2083 | var parseContract = function (obj) { | ||
2084 | /*jshint maxcomplexity:7 */ | ||
2085 | |||
2086 | var payloadType, payload; | ||
2087 | if (obj && utils.isString(obj.source) && obj.source.length > 0) { | ||
2088 | payloadType = TxPayloadDeployType; | ||
2089 | payload = { | ||
2090 | SourceType: obj.sourceType, | ||
2091 | Source: obj.source, | ||
2092 | Args: obj.args | ||
2093 | }; | ||
2094 | } else if (obj && utils.isString(obj.function) && obj.function.length > 0) { | ||
2095 | payloadType = TxPayloadCallType; | ||
2096 | payload = { | ||
2097 | Function: obj.function, | ||
2098 | Args: obj.args | ||
2099 | }; | ||
2100 | } else { | ||
2101 | payloadType = TxPayloadBinaryType; | ||
2102 | if (obj) { | ||
2103 | payload = { | ||
2104 | Data: cryptoUtils.toBuffer(obj.binary) | ||
2105 | }; | ||
2106 | } | ||
2107 | } | ||
2108 | var payloadData = utils.isNull(payload) ? null : cryptoUtils.toBuffer(htmlescape(payload)); | ||
2109 | |||
2110 | return { type: payloadType, payload: payloadData }; | ||
2111 | }; | ||
2112 | |||
2113 | /** | ||
2114 | * Transaction recover method. | ||
2115 | * | ||
2116 | * @static | ||
2117 | * @param {String/Hash} message - Transaction hash. | ||
2118 | * @param {String/Hash} signature - Transaction sign | ||
2119 | * | ||
2120 | * @return {Hash} Transaction from address public key. | ||
2121 | * | ||
2122 | * @example | ||
2123 | * var pubKey = Transaction.recover("82bc718bfd24392b3872eb5a874927a327ab19b156c5584bd5f93b08fab5b1a2", "003d4064f16cbc72367b0fa3870bdcd1044bdb166019d87cdaac6dcfb8c09ac9471570e5b2e1dc249a8642ba67e585e3f43e6383c3b87532f5eb1fe2e718a5ab00"); | ||
2124 | */ | ||
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; | ||
2132 | } | ||
2133 | var compressed = false; | ||
2134 | var pub = cryptoUtils.recover(message, sign, recovery, compressed); | ||
2135 | return pub; | ||
2136 | }; | ||
2137 | |||
2138 | /** | ||
2139 | * Transaction fromProto method, parse rawData to transaction object. | ||
2140 | * | ||
2141 | * @static | ||
2142 | * @param {String/Hash} data - Transaction raw data. | ||
2143 | * | ||
2144 | * @return {Object} Transaction object. | ||
2145 | * | ||
2146 | * @example | ||
2147 | * var tx = Transaction.fromProto("EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA=="); | ||
2148 | */ | ||
2149 | Transaction.fromProto = function (data) { | ||
2150 | var tx = new Transaction(); | ||
2151 | tx.fromProto(data); | ||
2152 | return tx; | ||
2153 | }; | ||
2154 | |||
2155 | Transaction.prototype = { | ||
2156 | /** | ||
2157 | * Convert transaction to hash by SHA3-256 algorithm. | ||
2158 | * | ||
2159 | * @return {Hash} hash of Transaction. | ||
2160 | * | ||
2161 | * @example | ||
2162 | * var acc = Account.NewAccount(); | ||
2163 | * | ||
2164 | * var tx = new Transaction({ | ||
2165 | * chainID: 1, | ||
2166 | * from: acc, | ||
2167 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
2168 | * value: 10, | ||
2169 | * nonce: 12, | ||
2170 | * gasPrice: 1000000, | ||
2171 | * gasLimit: 2000000 | ||
2172 | * }); | ||
2173 | * var txHash = tx.hashTransaction(); | ||
2174 | * //Uint8Array(32) [211, 213, 102, 103, 23, 231, 246, 141, 20, 202, 210, 25, 92, 142, 162, 242, 232, 95, 44, 239, 45, 57, 241, 61, 34, 2, 213, 160, 17, 207, 75, 40] | ||
2175 | */ | ||
2176 | hashTransaction: function () { | ||
2177 | var Data = root.lookup("corepb.Data"); | ||
2178 | var err = Data.verify(this.data); | ||
2179 | if (err) { | ||
2180 | throw new Error(err); | ||
2181 | } | ||
2182 | var data = Data.create(this.data); | ||
2183 | var dataBuffer = Data.encode(data).finish(); | ||
2184 | var hash = cryptoUtils.sha3(this.from.getAddress(), this.to.getAddress(), cryptoUtils.padToBigEndian(this.value, 128), cryptoUtils.padToBigEndian(this.nonce, 64), cryptoUtils.padToBigEndian(this.timestamp, 64), dataBuffer, cryptoUtils.padToBigEndian(this.chainID, 32), cryptoUtils.padToBigEndian(this.gasPrice, 128), cryptoUtils.padToBigEndian(this.gasLimit, 128)); | ||
2185 | return hash; | ||
2186 | }, | ||
2187 | /** | ||
2188 | * Sign transaction with the specified algorithm. | ||
2189 | * | ||
2190 | * @example | ||
2191 | * var acc = Account.NewAccount(); | ||
2192 | * | ||
2193 | * var tx = new Transaction({ | ||
2194 | * chainID: 1, | ||
2195 | * from: acc, | ||
2196 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
2197 | * value: 10, | ||
2198 | * nonce: 12, | ||
2199 | * gasPrice: 1000000, | ||
2200 | * gasLimit: 2000000 | ||
2201 | * }); | ||
2202 | * tx.signTransaction(); | ||
2203 | */ | ||
2204 | signTransaction: function () { | ||
2205 | if (this.from.getPrivateKey() !== null) { | ||
2206 | this.hash = this.hashTransaction(); | ||
2207 | this.alg = SECP256K1; | ||
2208 | this.sign = cryptoUtils.sign(this.hash, this.from.getPrivateKey()); | ||
2209 | } else { | ||
2210 | throw new Error("transaction from address's private key is invalid"); | ||
2211 | } | ||
2212 | }, | ||
2213 | /** | ||
2214 | * Conver transaction data to plain JavaScript object. | ||
2215 | * | ||
2216 | * @return {Object} Plain JavaScript object with Transaction fields. | ||
2217 | * @example | ||
2218 | * var acc = Account.NewAccount(); | ||
2219 | * var tx = new Transaction({ | ||
2220 | * chainID: 1, | ||
2221 | * from: acc, | ||
2222 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
2223 | * value: 10, | ||
2224 | * nonce: 12, | ||
2225 | * gasPrice: 1000000, | ||
2226 | * gasLimit: 2000000 | ||
2227 | * }); | ||
2228 | * txData = tx.toPlainObject(); | ||
2229 | * // {chainID: 1001, from: "n1USdDKeZXQYubA44W2ZVUdW1cjiJuqswxp", to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", value: 1000000000000000000, nonce: 1, …} | ||
2230 | */ | ||
2231 | toPlainObject: function () { | ||
2232 | return { | ||
2233 | chainID: this.chainID, | ||
2234 | from: this.from.getAddressString(), | ||
2235 | to: this.to.getAddressString(), | ||
2236 | value: utils.isBigNumber(this.value) ? this.value.toNumber() : this.value, | ||
2237 | nonce: this.nonce, | ||
2238 | gasPrice: utils.isBigNumber(this.gasPrice) ? this.gasPrice.toNumber() : this.gasPrice, | ||
2239 | gasLimit: utils.isBigNumber(this.gasLimit) ? this.gasLimit.toNumber() : this.gasLimit, | ||
2240 | contract: this.contract | ||
2241 | }; | ||
2242 | }, | ||
2243 | /** | ||
2244 | * Convert transaction to JSON string. | ||
2245 | * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting. | ||
2246 | * | ||
2247 | * @return {String} JSON stringify of transaction data. | ||
2248 | * @example | ||
2249 | * var acc = Account.NewAccount(); | ||
2250 | * | ||
2251 | * var tx = new Transaction({ | ||
2252 | * chainID: 1, | ||
2253 | * from: acc, | ||
2254 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
2255 | * value: 10, | ||
2256 | * nonce: 12, | ||
2257 | * gasPrice: 1000000, | ||
2258 | * gasLimit: 2000000 | ||
2259 | * }); | ||
2260 | * tx.signTransaction(); | ||
2261 | * var txHash = tx.toString(); | ||
2262 | * // "{"chainID":1001,"from":"n1QZMXSZtW7BUerroSms4axNfyBGyFGkrh5","to":"n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17","value":"1000000000000000000","nonce":1,"timestamp":1521905294,"data":{"payloadType":"binary","payload":null},"gasPrice":"1000000","gasLimit":"20000","hash":"f52668b853dd476fd309f21b22ade6bb468262f55402965c3460175b10cb2f20","alg":1,"sign":"cf30d5f61e67bbeb73bb9724ba5ba3744dcbc995521c62f9b5f43efabd9b82f10aaadf19a9cdb05f039d8bf074849ef4b508905bcdea76ae57e464e79c958fa900"}" | ||
2263 | */ | ||
2264 | toString: function () { | ||
2265 | if (!this.sign) { | ||
2266 | throw new Error(this.signErrorMessage); | ||
2267 | } | ||
2268 | var payload = utils.isNull(this.data.payload) ? null : JSON.parse(this.data.payload.toString()); | ||
2269 | var tx = { | ||
2270 | chainID: this.chainID, | ||
2271 | from: this.from.getAddressString(), | ||
2272 | to: this.to.getAddressString(), | ||
2273 | value: this.value.toString(10), | ||
2274 | nonce: this.nonce, | ||
2275 | timestamp: this.timestamp, | ||
2276 | data: { payloadType: this.data.type, payload: payload }, | ||
2277 | gasPrice: this.gasPrice.toString(10), | ||
2278 | gasLimit: this.gasLimit.toString(10), | ||
2279 | hash: this.hash.toString("hex"), | ||
2280 | alg: this.alg, | ||
2281 | sign: this.sign.toString("hex") | ||
2282 | |||
2283 | }; | ||
2284 | return JSON.stringify(tx); | ||
2285 | }, | ||
2286 | /** | ||
2287 | * Convert transaction to Protobuf format. | ||
2288 | * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting. | ||
2289 | * | ||
2290 | * @return {Buffer} Transaction data in Protobuf format | ||
2291 | * | ||
2292 | * @example | ||
2293 | * var acc = Account.NewAccount(); | ||
2294 | * | ||
2295 | * var tx = new Transaction({ | ||
2296 | * chainID: 1, | ||
2297 | * from: acc, | ||
2298 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
2299 | * value: 10, | ||
2300 | * nonce: 12, | ||
2301 | * gasPrice: 1000000, | ||
2302 | * gasLimit: 2000000 | ||
2303 | * }); | ||
2304 | * tx.signTransaction(); | ||
2305 | * var txHash = tx.toProto(); | ||
2306 | * // Uint8Array(127) | ||
2307 | */ | ||
2308 | toProto: function () { | ||
2309 | if (!this.sign) { | ||
2310 | throw new Error(this.signErrorMessage); | ||
2311 | } | ||
2312 | var Data = root.lookup("corepb.Data"); | ||
2313 | var err = Data.verify(this.data); | ||
2314 | if (err) { | ||
2315 | throw err; | ||
2316 | } | ||
2317 | var data = Data.create(this.data); | ||
2318 | |||
2319 | var TransactionProto = root.lookup("corepb.Transaction"); | ||
2320 | |||
2321 | var txData = { | ||
2322 | hash: this.hash, | ||
2323 | from: this.from.getAddress(), | ||
2324 | to: this.to.getAddress(), | ||
2325 | value: cryptoUtils.padToBigEndian(this.value, 128), | ||
2326 | nonce: this.nonce, | ||
2327 | timestamp: this.timestamp, | ||
2328 | data: data, | ||
2329 | chainId: this.chainID, | ||
2330 | gasPrice: cryptoUtils.padToBigEndian(this.gasPrice, 128), | ||
2331 | gasLimit: cryptoUtils.padToBigEndian(this.gasLimit, 128), | ||
2332 | alg: this.alg, | ||
2333 | sign: this.sign | ||
2334 | }; | ||
2335 | |||
2336 | err = TransactionProto.verify(txData); | ||
2337 | if (err) { | ||
2338 | throw err; | ||
2339 | } | ||
2340 | var tx = TransactionProto.create(txData); | ||
2341 | |||
2342 | var txBuffer = TransactionProto.encode(tx).finish(); | ||
2343 | return txBuffer; | ||
2344 | }, | ||
2345 | /** | ||
2346 | * Convert transaction to Protobuf hash string. | ||
2347 | * </br><b>Note:</b> Transaction should be [sign]{@link Transaction#signTransaction} before converting. | ||
2348 | * | ||
2349 | * @return {Base64} Transaction string. | ||
2350 | * | ||
2351 | * @example | ||
2352 | * var acc = Account.NewAccount(); | ||
2353 | * | ||
2354 | * var tx = new Transaction({ | ||
2355 | * chainID: 1, | ||
2356 | * from: acc, | ||
2357 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
2358 | * value: 10, | ||
2359 | * nonce: 12, | ||
2360 | * gasPrice: 1000000, | ||
2361 | * gasLimit: 2000000 | ||
2362 | * }); | ||
2363 | * tx.signTransaction(); | ||
2364 | * var txHash = tx.toProtoString(); | ||
2365 | * // "EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA==" | ||
2366 | */ | ||
2367 | toProtoString: function () { | ||
2368 | var txBuffer = this.toProto(); | ||
2369 | return protobuf.util.base64.encode(txBuffer, 0, txBuffer.length); | ||
2370 | }, | ||
2371 | /** | ||
2372 | * Restore Transaction from Protobuf format. | ||
2373 | * @property {Buffer|String} data - Buffer or stringify Buffer. | ||
2374 | * | ||
2375 | * @return {Transaction} Restored transaction. | ||
2376 | * | ||
2377 | * @example | ||
2378 | * var acc = Account.NewAccount(); | ||
2379 | * | ||
2380 | * var tx = new Transaction({ | ||
2381 | * chainID: 1, | ||
2382 | * from: acc, | ||
2383 | * to: "n1SAeQRVn33bamxN4ehWUT7JGdxipwn8b17", | ||
2384 | * value: 10, | ||
2385 | * nonce: 12, | ||
2386 | * gasPrice: 1000000, | ||
2387 | * gasLimit: 2000000 | ||
2388 | * }); | ||
2389 | * var tx = tx.fromProto("EhjZTY/gKLhWVVMZ+xoY9GiHOHJcxhc4uxkaGNlNj+AouFZVUxn7Ghj0aIc4clzGFzi7GSIQAAAAAAAAAAAN4Lazp2QAACgBMPCz6tUFOggKBmJpbmFyeUDpB0oQAAAAAAAAAAAAAAAAAA9CQFIQAAAAAAAAAAAAAAAAAABOIA=="); | ||
2390 | */ | ||
2391 | fromProto: function (data) { | ||
2392 | |||
2393 | var txBuffer; | ||
2394 | if (utils.isString(data)) { | ||
2395 | txBuffer = new Array(protobuf.util.base64.length(data)); | ||
2396 | protobuf.util.base64.decode(data, txBuffer, 0); | ||
2397 | } else { | ||
2398 | txBuffer = data; | ||
2399 | } | ||
2400 | |||
2401 | var TransactionProto = root.lookup("corepb.Transaction"); | ||
2402 | var txProto = TransactionProto.decode(txBuffer); | ||
2403 | |||
2404 | this.hash = cryptoUtils.toBuffer(txProto.hash); | ||
2405 | this.from = account.fromAddress(txProto.from); | ||
2406 | this.to = account.fromAddress(txProto.to); | ||
2407 | this.value = utils.toBigNumber("0x" + cryptoUtils.toBuffer(txProto.value).toString("hex")); | ||
2408 | // long number is object, should convert to int | ||
2409 | this.nonce = parseInt(txProto.nonce.toString()); | ||
2410 | this.timestamp = parseInt(txProto.timestamp.toString()); | ||
2411 | this.data = txProto.data; | ||
2412 | if (this.data.payload.length === 0) { | ||
2413 | this.data.payload = null; | ||
2414 | } | ||
2415 | this.chainID = txProto.chainId; | ||
2416 | this.gasPrice = utils.toBigNumber("0x" + cryptoUtils.toBuffer(txProto.gasPrice).toString("hex")); | ||
2417 | this.gasLimit = utils.toBigNumber("0x" + cryptoUtils.toBuffer(txProto.gasLimit).toString("hex")); | ||
2418 | this.alg = txProto.alg; | ||
2419 | this.sign = cryptoUtils.toBuffer(txProto.sign); | ||
2420 | |||
2421 | return this; | ||
2422 | } | ||
2423 | }; | ||
2424 | |||
2425 | module.exports = Transaction; | ||
2426 | |||
2427 | },{"./account.js":1,"./transaction.json":17,"./utils/crypto-utils.js":19,"./utils/utils.js":21,"bignumber.js":73,"htmlescape":160,"protobufjs":191}],19:[function(require,module,exports){ | ||
2428 | |||
2429 | "use strict"; | ||
2430 | |||
2431 | var Buffer = require('safe-buffer').Buffer; | ||
2432 | |||
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'); | ||
2439 | |||
2440 | var uuid = require('uuid'); | ||
2441 | |||
2442 | var utils = require('./utils.js'); | ||
2443 | |||
2444 | var keccak = function (a, bits) { | ||
2445 | a = toBuffer(a); | ||
2446 | if (!bits) bits = 256; | ||
2447 | |||
2448 | return createKeccakHash('keccak' + bits).update(a).digest(); | ||
2449 | }; | ||
2450 | |||
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")); | ||
2456 | } | ||
2457 | return Buffer.from(shaObj.getHash("HEX"), "hex"); | ||
2458 | }; | ||
2459 | |||
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); | ||
2465 | } | ||
2466 | return ripemd160stream.digest(); | ||
2467 | }; | ||
2468 | |||
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."); | ||
2473 | } | ||
2474 | |||
2475 | return str.slice(0, 2) === '0x'; | ||
2476 | }; | ||
2477 | |||
2478 | // returns hex string without 0x | ||
2479 | var stripHexPrefix = function (str) { | ||
2480 | if (typeof str !== 'string') { | ||
2481 | return str; | ||
2482 | } | ||
2483 | return isHexPrefixed(str) ? str.slice(2) : str; | ||
2484 | }; | ||
2485 | |||
2486 | function isHexString(value, length) { | ||
2487 | if (typeof value !== 'string' || !value.match(/^0x[0-9A-Fa-f]*$/)) { | ||
2488 | return false; | ||
2489 | } | ||
2490 | |||
2491 | if (length && value.length !== 2 + 2 * length) { | ||
2492 | return false; | ||
2493 | } | ||
2494 | |||
2495 | return true; | ||
2496 | } | ||
2497 | |||
2498 | // returns hex string from int | ||
2499 | function intToHex(i) { | ||
2500 | var hex = i.toString(16); // eslint-disable-line | ||
2501 | |||
2502 | return '0x' + padToEven(hex); | ||
2503 | } | ||
2504 | |||
2505 | // returns buffer from int | ||
2506 | function intToBuffer(i) { | ||
2507 | var hex = intToHex(i); | ||
2508 | |||
2509 | return new Buffer(hex.slice(2), 'hex'); | ||
2510 | } | ||
2511 | |||
2512 | // returns a buffer filled with 0 | ||
2513 | var zeros = function (bytes) { | ||
2514 | return Buffer.allocUnsafe(bytes).fill(0); | ||
2515 | }; | ||
2516 | |||
2517 | var padToEven = function (value) { | ||
2518 | var a = value; // eslint-disable-line | ||
2519 | |||
2520 | if (typeof a !== 'string') { | ||
2521 | throw new Error('padToEven only support string'); | ||
2522 | } | ||
2523 | |||
2524 | if (a.length % 2) { | ||
2525 | a = '0' + a; | ||
2526 | } | ||
2527 | |||
2528 | return a; | ||
2529 | }; | ||
2530 | |||
2531 | // convert value to digit/8 buffer with BigEndian. | ||
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; | ||
2537 | if (start >= 0) { | ||
2538 | buff[start] = value[i]; | ||
2539 | } | ||
2540 | } | ||
2541 | return buff; | ||
2542 | }; | ||
2543 | |||
2544 | // attempts to turn a value to buffer, the input can be buffer, string,number | ||
2545 | var toBuffer = function (v) { | ||
2546 | /*jshint maxcomplexity:13 */ | ||
2547 | if (!Buffer.isBuffer(v)) { | ||
2548 | if (Array.isArray(v)) { | ||
2549 | v = Buffer.from(v); | ||
2550 | } else if (typeof v === 'string') { | ||
2551 | if (isHexString(v)) { | ||
2552 | v = Buffer.from(padToEven(stripHexPrefix(v)), 'hex'); | ||
2553 | } else { | ||
2554 | v = Buffer.from(v); | ||
2555 | } | ||
2556 | } else if (typeof v === 'number') { | ||
2557 | v = intToBuffer(v); | ||
2558 | } else if (v === null || v === undefined) { | ||
2559 | v = Buffer.allocUnsafe(0); | ||
2560 | } else if (utils.isBigNumber(v)) { | ||
2561 | // TODO: neb number is a big int, not support if v is decimal, later fix it. | ||
2562 | v = Buffer.from(padToEven(v.toString(16)), 'hex'); | ||
2563 | } else if (v.toArray) { | ||
2564 | v = Buffer.from(v.toArray()); | ||
2565 | } else if (v.subarray) { | ||
2566 | v = Buffer.from(v); | ||
2567 | } else if (v === null || typeof v === "undefined") { | ||
2568 | v = Buffer.allocUnsafe(0); | ||
2569 | } else { | ||
2570 | throw new Error('invalid type'); | ||
2571 | } | ||
2572 | } | ||
2573 | return v; | ||
2574 | }; | ||
2575 | |||
2576 | var bufferToHex = function (buf) { | ||
2577 | buf = toBuffer(buf); | ||
2578 | return '0x' + buf.toString('hex'); | ||
2579 | }; | ||
2580 | |||
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); | ||
2586 | }; | ||
2587 | |||
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])); | ||
2592 | } | ||
2593 | |||
2594 | if (!sanitize) { | ||
2595 | return false; | ||
2596 | } | ||
2597 | |||
2598 | return secp256k1.publicKeyVerify(publicKey); | ||
2599 | }; | ||
2600 | |||
2601 | // sign transaction hash | ||
2602 | var sign = function (msgHash, privateKey) { | ||
2603 | |||
2604 | var sig = secp256k1.sign(toBuffer(msgHash), toBuffer(privateKey)); | ||
2605 | // var ret = {} | ||
2606 | // ret.r = sig.signature.slice(0, 32) | ||
2607 | // ret.s = sig.signature.slice(32, 64) | ||
2608 | // ret.v = sig.recovery | ||
2609 | return Buffer.concat([toBuffer(sig.signature), toBuffer(sig.recovery)]); | ||
2610 | }; | ||
2611 | |||
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)); | ||
2616 | }; | ||
2617 | |||
2618 | var recover = function (message, signature, recovery, compressed) { | ||
2619 | return secp256k1.recover(toBuffer(message), toBuffer(signature), recovery, compressed); | ||
2620 | }; | ||
2621 | |||
2622 | module.exports = { | ||
2623 | secp256k1: secp256k1, | ||
2624 | keccak: keccak, | ||
2625 | sha3: sha3, | ||
2626 | ripemd160: ripemd160, | ||
2627 | crypto: crypto, | ||
2628 | scrypt: scrypt, | ||
2629 | uuid: uuid, | ||
2630 | |||
2631 | zeros: zeros, | ||
2632 | isHexPrefixed: isHexPrefixed, | ||
2633 | padToBigEndian: padToBigEndian, | ||
2634 | toBuffer: toBuffer, | ||
2635 | bufferToHex: bufferToHex, | ||
2636 | privateToPublic: privateToPublic, | ||
2637 | isValidPublic: isValidPublic, | ||
2638 | sign: sign, | ||
2639 | verify: verify, | ||
2640 | recover: recover | ||
2641 | }; | ||
2642 | |||
2643 | },{"./utils.js":21,"crypto":116,"jssha":166,"keccak":167,"ripemd160":246,"safe-buffer":247,"scryptsy":248,"secp256k1":249,"uuid":266}],20:[function(require,module,exports){ | ||
2644 | |||
2645 | "use strict"; | ||
2646 | |||
2647 | var BigNumber = require('bignumber.js'); | ||
2648 | var utils = require('./utils.js'); | ||
2649 | |||
2650 | var unitMap = { | ||
2651 | 'none': '0', | ||
2652 | 'None': '0', | ||
2653 | 'wei': '1', | ||
2654 | 'Wei': '1', | ||
2655 | 'kwei': '1000', | ||
2656 | 'Kwei': '1000', | ||
2657 | 'mwei': '1000000', | ||
2658 | 'Mwei': '1000000', | ||
2659 | 'gwei': '1000000000', | ||
2660 | 'Gwei': '1000000000', | ||
2661 | 'nas': '1000000000000000000', | ||
2662 | 'NAS': '1000000000000000000' | ||
2663 | }; | ||
2664 | |||
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)); | ||
2670 | } | ||
2671 | return new BigNumber(unitValue, 10); | ||
2672 | }; | ||
2673 | |||
2674 | var toBasic = function (number, unit) { | ||
2675 | return utils.toBigNumber(number).times(unitValue(unit)); | ||
2676 | }; | ||
2677 | |||
2678 | var fromBasic = function (number, unit) { | ||
2679 | return utils.toBigNumber(number).dividedBy(unitValue(unit)); | ||
2680 | }; | ||
2681 | |||
2682 | var nasToBasic = function (number) { | ||
2683 | return utils.toBigNumber(number).times(unitValue("nas")); | ||
2684 | }; | ||
2685 | |||
2686 | module.exports = { | ||
2687 | toBasic: toBasic, | ||
2688 | fromBasic: fromBasic, | ||
2689 | nasToBasic: nasToBasic | ||
2690 | }; | ||
2691 | |||
2692 | },{"./utils.js":21,"bignumber.js":73}],21:[function(require,module,exports){ | ||
2693 | |||
2694 | "use strict"; | ||
2695 | |||
2696 | var BigNumber = require('bignumber.js'); | ||
2697 | |||
2698 | var isNull = function (v) { | ||
2699 | return v === null || typeof v === "undefined"; | ||
2700 | }; | ||
2701 | |||
2702 | var isBrowser = function () { | ||
2703 | return typeof window !== "undefined"; | ||
2704 | }; | ||
2705 | |||
2706 | var isBigNumber = function (obj) { | ||
2707 | return obj instanceof BigNumber || obj && obj.constructor && obj.constructor.name === 'BigNumber'; | ||
2708 | }; | ||
2709 | |||
2710 | var isString = function (obj) { | ||
2711 | return typeof obj === 'string' && obj.constructor === String; | ||
2712 | }; | ||
2713 | |||
2714 | var isObject = function (obj) { | ||
2715 | return obj !== null && typeof obj === 'object'; | ||
2716 | }; | ||
2717 | |||
2718 | var isFunction = function (object) { | ||
2719 | return typeof object === 'function'; | ||
2720 | }; | ||
2721 | |||
2722 | var isNumber = function (object) { | ||
2723 | return typeof object === 'number'; | ||
2724 | }; | ||
2725 | |||
2726 | var toBigNumber = function (number) { | ||
2727 | number = number || 0; | ||
2728 | if (isBigNumber(number)) { | ||
2729 | return number; | ||
2730 | } | ||
2731 | if (isString(number) && number.indexOf('0x') === 0) { | ||
2732 | return new BigNumber(number.replace('0x', ''), 16); | ||
2733 | } | ||
2734 | return new BigNumber(number.toString(10), 10); | ||
2735 | }; | ||
2736 | |||
2737 | var toString = function (obj) { | ||
2738 | if (isString(obj)) { | ||
2739 | return obj; | ||
2740 | } else if (isBigNumber(obj)) { | ||
2741 | return obj.toString(10); | ||
2742 | } else if (isObject(obj)) { | ||
2743 | return JSON.stringify(obj); | ||
2744 | } else { | ||
2745 | return obj + ""; | ||
2746 | } | ||
2747 | }; | ||
2748 | |||
2749 | // Transform Array-like arguments object to common array. | ||
2750 | var argumentsToArray = function (args) { | ||
2751 | var len = args.length, | ||
2752 | resultArray = new Array(len); | ||
2753 | |||
2754 | for (var i = 0; i < len; i += 1) { | ||
2755 | resultArray[i] = args[i]; | ||
2756 | } | ||
2757 | return resultArray; | ||
2758 | }; | ||
2759 | |||
2760 | // Create object based on provided arrays | ||
2761 | var zipArraysToObject = function (keysArr, valuesArr) { | ||
2762 | var resultObject = {}; | ||
2763 | |||
2764 | for (var i = 0; i < keysArr.length; i += 1) { | ||
2765 | resultObject[keysArr[i]] = valuesArr[i]; | ||
2766 | } | ||
2767 | return resultObject; | ||
2768 | }; | ||
2769 | |||
2770 | // Function what make overall view for arguments. | ||
2771 | // If arguments was provided separated by commas like "func(arg1 ,arg2)" we create | ||
2772 | // ArgumentsObject and write keys from argsNames and value from args. | ||
2773 | // in case wheare we provide args in object like "func({arg1: value})" | ||
2774 | // we just return that object | ||
2775 | var argumentsToObject = function (keys, args) { | ||
2776 | var ArgumentsObject = {}; | ||
2777 | |||
2778 | args = argumentsToArray(args); | ||
2779 | if (isObject(args[0])) { | ||
2780 | ArgumentsObject = args[0]; | ||
2781 | } else { | ||
2782 | ArgumentsObject = zipArraysToObject(keys, args); | ||
2783 | } | ||
2784 | |||
2785 | return ArgumentsObject; | ||
2786 | }; | ||
2787 | |||
2788 | module.exports = { | ||
2789 | isNull: isNull, | ||
2790 | isBrowser: isBrowser, | ||
2791 | isBigNumber: isBigNumber, | ||
2792 | isString: isString, | ||
2793 | isObject: isObject, | ||
2794 | isFunction: isFunction, | ||
2795 | isNumber: isNumber, | ||
2796 | toBigNumber: toBigNumber, | ||
2797 | toString: toString, | ||
2798 | argumentsToObject: argumentsToObject, | ||
2799 | zipArraysToObject: zipArraysToObject | ||
2800 | }; | ||
2801 | |||
2802 | },{"bignumber.js":73}],22:[function(require,module,exports){ | ||
2803 | "use strict"; | ||
2804 | module.exports = asPromise; | ||
2805 | |||
2806 | /** | ||
2807 | * Callback as used by {@link util.asPromise}. | ||
2808 | * @typedef asPromiseCallback | ||
2809 | * @type {function} | ||
2810 | * @param {Error|null} error Error, if any | ||
2811 | * @param {...*} params Additional arguments | ||
2812 | * @returns {undefined} | ||
2813 | */ | ||
2814 | |||
2815 | /** | ||
2816 | * Returns a promise from a node-style callback function. | ||
2817 | * @memberof util | ||
2818 | * @param {asPromiseCallback} fn Function to call | ||
2819 | * @param {*} ctx Function context | ||
2820 | * @param {...*} params Function arguments | ||
2821 | * @returns {Promise<*>} Promisified function | ||
2822 | */ | ||
2823 | function asPromise(fn, ctx/*, varargs */) { | ||
2824 | var params = new Array(arguments.length - 1), | ||
2825 | offset = 0, | ||
2826 | index = 2, | ||
2827 | pending = true; | ||
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 */) { | ||
2832 | if (pending) { | ||
2833 | pending = false; | ||
2834 | if (err) | ||
2835 | reject(err); | ||
2836 | else { | ||
2837 | var params = new Array(arguments.length - 1), | ||
2838 | offset = 0; | ||
2839 | while (offset < params.length) | ||
2840 | params[offset++] = arguments[offset]; | ||
2841 | resolve.apply(null, params); | ||
2842 | } | ||
2843 | } | ||
2844 | }; | ||
2845 | try { | ||
2846 | fn.apply(ctx || null, params); | ||
2847 | } catch (err) { | ||
2848 | if (pending) { | ||
2849 | pending = false; | ||
2850 | reject(err); | ||
2851 | } | ||
2852 | } | ||
2853 | }); | ||
2854 | } | ||
2855 | |||
2856 | },{}],23:[function(require,module,exports){ | ||
2857 | "use strict"; | ||
2858 | |||
2859 | /** | ||
2860 | * A minimal base64 implementation for number arrays. | ||
2861 | * @memberof util | ||
2862 | * @namespace | ||
2863 | */ | ||
2864 | var base64 = exports; | ||
2865 | |||
2866 | /** | ||
2867 | * Calculates the byte length of a base64 encoded string. | ||
2868 | * @param {string} string Base64 encoded string | ||
2869 | * @returns {number} Byte length | ||
2870 | */ | ||
2871 | base64.length = function length(string) { | ||
2872 | var p = string.length; | ||
2873 | if (!p) | ||
2874 | return 0; | ||
2875 | var n = 0; | ||
2876 | while (--p % 4 > 1 && string.charAt(p) === "=") | ||
2877 | ++n; | ||
2878 | return Math.ceil(string.length * 3) / 4 - n; | ||
2879 | }; | ||
2880 | |||
2881 | // Base64 encoding table | ||
2882 | var b64 = new Array(64); | ||
2883 | |||
2884 | // Base64 decoding table | ||
2885 | var s64 = new Array(123); | ||
2886 | |||
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++; | ||
2890 | |||
2891 | /** | ||
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 | ||
2897 | */ | ||
2898 | base64.encode = function encode(buffer, start, end) { | ||
2899 | var parts = null, | ||
2900 | chunk = []; | ||
2901 | var i = 0, // output index | ||
2902 | j = 0, // goto index | ||
2903 | t; // temporary | ||
2904 | while (start < end) { | ||
2905 | var b = buffer[start++]; | ||
2906 | switch (j) { | ||
2907 | case 0: | ||
2908 | chunk[i++] = b64[b >> 2]; | ||
2909 | t = (b & 3) << 4; | ||
2910 | j = 1; | ||
2911 | break; | ||
2912 | case 1: | ||
2913 | chunk[i++] = b64[t | b >> 4]; | ||
2914 | t = (b & 15) << 2; | ||
2915 | j = 2; | ||
2916 | break; | ||
2917 | case 2: | ||
2918 | chunk[i++] = b64[t | b >> 6]; | ||
2919 | chunk[i++] = b64[b & 63]; | ||
2920 | j = 0; | ||
2921 | break; | ||
2922 | } | ||
2923 | if (i > 8191) { | ||
2924 | (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); | ||
2925 | i = 0; | ||
2926 | } | ||
2927 | } | ||
2928 | if (j) { | ||
2929 | chunk[i++] = b64[t]; | ||
2930 | chunk[i++] = 61; | ||
2931 | if (j === 1) | ||
2932 | chunk[i++] = 61; | ||
2933 | } | ||
2934 | if (parts) { | ||
2935 | if (i) | ||
2936 | parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); | ||
2937 | return parts.join(""); | ||
2938 | } | ||
2939 | return String.fromCharCode.apply(String, chunk.slice(0, i)); | ||
2940 | }; | ||
2941 | |||
2942 | var invalidEncoding = "invalid encoding"; | ||
2943 | |||
2944 | /** | ||
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 | ||
2951 | */ | ||
2952 | base64.decode = function decode(string, buffer, offset) { | ||
2953 | var start = offset; | ||
2954 | var j = 0, // goto index | ||
2955 | t; // temporary | ||
2956 | for (var i = 0; i < string.length;) { | ||
2957 | var c = string.charCodeAt(i++); | ||
2958 | if (c === 61 && j > 1) | ||
2959 | break; | ||
2960 | if ((c = s64[c]) === undefined) | ||
2961 | throw Error(invalidEncoding); | ||
2962 | switch (j) { | ||
2963 | case 0: | ||
2964 | t = c; | ||
2965 | j = 1; | ||
2966 | break; | ||
2967 | case 1: | ||
2968 | buffer[offset++] = t << 2 | (c & 48) >> 4; | ||
2969 | t = c; | ||
2970 | j = 2; | ||
2971 | break; | ||
2972 | case 2: | ||
2973 | buffer[offset++] = (t & 15) << 4 | (c & 60) >> 2; | ||
2974 | t = c; | ||
2975 | j = 3; | ||
2976 | break; | ||
2977 | case 3: | ||
2978 | buffer[offset++] = (t & 3) << 6 | c; | ||
2979 | j = 0; | ||
2980 | break; | ||
2981 | } | ||
2982 | } | ||
2983 | if (j === 1) | ||
2984 | throw Error(invalidEncoding); | ||
2985 | return offset - start; | ||
2986 | }; | ||
2987 | |||
2988 | /** | ||
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 | ||
2992 | */ | ||
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); | ||
2995 | }; | ||
2996 | |||
2997 | },{}],24:[function(require,module,exports){ | ||
2998 | "use strict"; | ||
2999 | module.exports = codegen; | ||
3000 | |||
3001 | /** | ||
3002 | * Begins generating a function. | ||
3003 | * @memberof util | ||
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 | ||
3007 | */ | ||
3008 | function codegen(functionParams, functionName) { | ||
3009 | |||
3010 | /* istanbul ignore if */ | ||
3011 | if (typeof functionParams === "string") { | ||
3012 | functionName = functionParams; | ||
3013 | functionParams = undefined; | ||
3014 | } | ||
3015 | |||
3016 | var body = []; | ||
3017 | |||
3018 | /** | ||
3019 | * Appends code to the function's body or finishes generation. | ||
3020 | * @typedef Codegen | ||
3021 | * @type {function} | ||
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 | ||
3026 | */ | ||
3027 | |||
3028 | function Codegen(formatStringOrScope) { | ||
3029 | // note that explicit array handling below makes this ~50% faster | ||
3030 | |||
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), | ||
3041 | scopeOffset = 0; | ||
3042 | while (scopeOffset < scopeKeys.length) { | ||
3043 | scopeParams[scopeOffset] = scopeKeys[scopeOffset]; | ||
3044 | scopeValues[scopeOffset] = formatStringOrScope[scopeKeys[scopeOffset++]]; | ||
3045 | } | ||
3046 | scopeParams[scopeOffset] = source; | ||
3047 | return Function.apply(null, scopeParams).apply(null, scopeValues); // eslint-disable-line no-new-func | ||
3048 | } | ||
3049 | return Function(source)(); // eslint-disable-line no-new-func | ||
3050 | } | ||
3051 | |||
3052 | // otherwise append to body | ||
3053 | var formatParams = new Array(arguments.length - 1), | ||
3054 | formatOffset = 0; | ||
3055 | while (formatOffset < formatParams.length) | ||
3056 | formatParams[formatOffset] = arguments[++formatOffset]; | ||
3057 | formatOffset = 0; | ||
3058 | formatStringOrScope = formatStringOrScope.replace(/%([%dfijs])/g, function replace($0, $1) { | ||
3059 | var value = formatParams[formatOffset++]; | ||
3060 | switch ($1) { | ||
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); | ||
3065 | } | ||
3066 | return "%"; | ||
3067 | }); | ||
3068 | if (formatOffset !== formatParams.length) | ||
3069 | throw Error("parameter count mismatch"); | ||
3070 | body.push(formatStringOrScope); | ||
3071 | return Codegen; | ||
3072 | } | ||
3073 | |||
3074 | function toString(functionNameOverride) { | ||
3075 | return "function " + (functionNameOverride || functionName || "") + "(" + (functionParams && functionParams.join(",") || "") + "){\n " + body.join("\n ") + "\n}"; | ||
3076 | } | ||
3077 | |||
3078 | Codegen.toString = toString; | ||
3079 | return Codegen; | ||
3080 | } | ||
3081 | |||
3082 | /** | ||
3083 | * Begins generating a function. | ||
3084 | * @memberof util | ||
3085 | * @function codegen | ||
3086 | * @param {string} [functionName] Function name if not anonymous | ||
3087 | * @returns {Codegen} Appender that appends code to the function's body | ||
3088 | * @variation 2 | ||
3089 | */ | ||
3090 | |||
3091 | /** | ||
3092 | * When set to `true`, codegen will log generated code to console. Useful for debugging. | ||
3093 | * @name util.codegen.verbose | ||
3094 | * @type {boolean} | ||
3095 | */ | ||
3096 | codegen.verbose = false; | ||
3097 | |||
3098 | },{}],25:[function(require,module,exports){ | ||
3099 | "use strict"; | ||
3100 | module.exports = EventEmitter; | ||
3101 | |||
3102 | /** | ||
3103 | * Constructs a new event emitter instance. | ||
3104 | * @classdesc A minimal event emitter. | ||
3105 | * @memberof util | ||
3106 | * @constructor | ||
3107 | */ | ||
3108 | function EventEmitter() { | ||
3109 | |||
3110 | /** | ||
3111 | * Registered listeners. | ||
3112 | * @type {Object.<string,*>} | ||
3113 | * @private | ||
3114 | */ | ||
3115 | this._listeners = {}; | ||
3116 | } | ||
3117 | |||
3118 | /** | ||
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` | ||
3124 | */ | ||
3125 | EventEmitter.prototype.on = function on(evt, fn, ctx) { | ||
3126 | (this._listeners[evt] || (this._listeners[evt] = [])).push({ | ||
3127 | fn : fn, | ||
3128 | ctx : ctx || this | ||
3129 | }); | ||
3130 | return this; | ||
3131 | }; | ||
3132 | |||
3133 | /** | ||
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` | ||
3138 | */ | ||
3139 | EventEmitter.prototype.off = function off(evt, fn) { | ||
3140 | if (evt === undefined) | ||
3141 | this._listeners = {}; | ||
3142 | else { | ||
3143 | if (fn === undefined) | ||
3144 | this._listeners[evt] = []; | ||
3145 | else { | ||
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); | ||
3150 | else | ||
3151 | ++i; | ||
3152 | } | ||
3153 | } | ||
3154 | return this; | ||
3155 | }; | ||
3156 | |||
3157 | /** | ||
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` | ||
3162 | */ | ||
3163 | EventEmitter.prototype.emit = function emit(evt) { | ||
3164 | var listeners = this._listeners[evt]; | ||
3165 | if (listeners) { | ||
3166 | var args = [], | ||
3167 | i = 1; | ||
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); | ||
3172 | } | ||
3173 | return this; | ||
3174 | }; | ||
3175 | |||
3176 | },{}],26:[function(require,module,exports){ | ||
3177 | "use strict"; | ||
3178 | module.exports = fetch; | ||
3179 | |||
3180 | var asPromise = require("@protobufjs/aspromise"), | ||
3181 | inquire = require("@protobufjs/inquire"); | ||
3182 | |||
3183 | var fs = inquire("fs"); | ||
3184 | |||
3185 | /** | ||
3186 | * Node-style callback as used by {@link util.fetch}. | ||
3187 | * @typedef FetchCallback | ||
3188 | * @type {function} | ||
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} | ||
3192 | */ | ||
3193 | |||
3194 | /** | ||
3195 | * Options as used by {@link util.fetch}. | ||
3196 | * @typedef FetchOptions | ||
3197 | * @type {Object} | ||
3198 | * @property {boolean} [binary=false] Whether expecting a binary response | ||
3199 | * @property {boolean} [xhr=false] If `true`, forces the use of XMLHttpRequest | ||
3200 | */ | ||
3201 | |||
3202 | /** | ||
3203 | * Fetches the contents of a file. | ||
3204 | * @memberof util | ||
3205 | * @param {string} filename File path or url | ||
3206 | * @param {FetchOptions} options Fetch options | ||
3207 | * @param {FetchCallback} callback Callback function | ||
3208 | * @returns {undefined} | ||
3209 | */ | ||
3210 | function fetch(filename, options, callback) { | ||
3211 | if (typeof options === "function") { | ||
3212 | callback = options; | ||
3213 | options = {}; | ||
3214 | } else if (!options) | ||
3215 | options = {}; | ||
3216 | |||
3217 | if (!callback) | ||
3218 | return asPromise(fetch, this, filename, options); // eslint-disable-line no-invalid-this | ||
3219 | |||
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) | ||
3225 | : err | ||
3226 | ? callback(err) | ||
3227 | : callback(null, options.binary ? contents : contents.toString("utf8")); | ||
3228 | }); | ||
3229 | |||
3230 | // use the XHR version otherwise. | ||
3231 | return fetch.xhr(filename, options, callback); | ||
3232 | } | ||
3233 | |||
3234 | /** | ||
3235 | * Fetches the contents of a file. | ||
3236 | * @name util.fetch | ||
3237 | * @function | ||
3238 | * @param {string} path File path or url | ||
3239 | * @param {FetchCallback} callback Callback function | ||
3240 | * @returns {undefined} | ||
3241 | * @variation 2 | ||
3242 | */ | ||
3243 | |||
3244 | /** | ||
3245 | * Fetches the contents of a file. | ||
3246 | * @name util.fetch | ||
3247 | * @function | ||
3248 | * @param {string} path File path or url | ||
3249 | * @param {FetchOptions} [options] Fetch options | ||
3250 | * @returns {Promise<string|Uint8Array>} Promise | ||
3251 | * @variation 3 | ||
3252 | */ | ||
3253 | |||
3254 | /**/ | ||
3255 | fetch.xhr = function fetch_xhr(filename, options, callback) { | ||
3256 | var xhr = new XMLHttpRequest(); | ||
3257 | xhr.onreadystatechange /* works everywhere */ = function fetchOnReadyStateChange() { | ||
3258 | |||
3259 | if (xhr.readyState !== 4) | ||
3260 | return undefined; | ||
3261 | |||
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)); | ||
3267 | |||
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; | ||
3272 | if (!buffer) { | ||
3273 | buffer = []; | ||
3274 | for (var i = 0; i < xhr.responseText.length; ++i) | ||
3275 | buffer.push(xhr.responseText.charCodeAt(i) & 255); | ||
3276 | } | ||
3277 | return callback(null, typeof Uint8Array !== "undefined" ? new Uint8Array(buffer) : buffer); | ||
3278 | } | ||
3279 | return callback(null, xhr.responseText); | ||
3280 | }; | ||
3281 | |||
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"; | ||
3287 | } | ||
3288 | |||
3289 | xhr.open("GET", filename); | ||
3290 | xhr.send(); | ||
3291 | }; | ||
3292 | |||
3293 | },{"@protobufjs/aspromise":22,"@protobufjs/inquire":28}],27:[function(require,module,exports){ | ||
3294 | "use strict"; | ||
3295 | |||
3296 | module.exports = factory(factory); | ||
3297 | |||
3298 | /** | ||
3299 | * Reads / writes floats / doubles from / to buffers. | ||
3300 | * @name util.float | ||
3301 | * @namespace | ||
3302 | */ | ||
3303 | |||
3304 | /** | ||
3305 | * Writes a 32 bit float to a buffer using little endian byte order. | ||
3306 | * @name util.float.writeFloatLE | ||
3307 | * @function | ||
3308 | * @param {number} val Value to write | ||
3309 | * @param {Uint8Array} buf Target buffer | ||
3310 | * @param {number} pos Target buffer offset | ||
3311 | * @returns {undefined} | ||
3312 | */ | ||
3313 | |||
3314 | /** | ||
3315 | * Writes a 32 bit float to a buffer using big endian byte order. | ||
3316 | * @name util.float.writeFloatBE | ||
3317 | * @function | ||
3318 | * @param {number} val Value to write | ||
3319 | * @param {Uint8Array} buf Target buffer | ||
3320 | * @param {number} pos Target buffer offset | ||
3321 | * @returns {undefined} | ||
3322 | */ | ||
3323 | |||
3324 | /** | ||
3325 | * Reads a 32 bit float from a buffer using little endian byte order. | ||
3326 | * @name util.float.readFloatLE | ||
3327 | * @function | ||
3328 | * @param {Uint8Array} buf Source buffer | ||
3329 | * @param {number} pos Source buffer offset | ||
3330 | * @returns {number} Value read | ||
3331 | */ | ||
3332 | |||
3333 | /** | ||
3334 | * Reads a 32 bit float from a buffer using big endian byte order. | ||
3335 | * @name util.float.readFloatBE | ||
3336 | * @function | ||
3337 | * @param {Uint8Array} buf Source buffer | ||
3338 | * @param {number} pos Source buffer offset | ||
3339 | * @returns {number} Value read | ||
3340 | */ | ||
3341 | |||
3342 | /** | ||
3343 | * Writes a 64 bit double to a buffer using little endian byte order. | ||
3344 | * @name util.float.writeDoubleLE | ||
3345 | * @function | ||
3346 | * @param {number} val Value to write | ||
3347 | * @param {Uint8Array} buf Target buffer | ||
3348 | * @param {number} pos Target buffer offset | ||
3349 | * @returns {undefined} | ||
3350 | */ | ||
3351 | |||
3352 | /** | ||
3353 | * Writes a 64 bit double to a buffer using big endian byte order. | ||
3354 | * @name util.float.writeDoubleBE | ||
3355 | * @function | ||
3356 | * @param {number} val Value to write | ||
3357 | * @param {Uint8Array} buf Target buffer | ||
3358 | * @param {number} pos Target buffer offset | ||
3359 | * @returns {undefined} | ||
3360 | */ | ||
3361 | |||
3362 | /** | ||
3363 | * Reads a 64 bit double from a buffer using little endian byte order. | ||
3364 | * @name util.float.readDoubleLE | ||
3365 | * @function | ||
3366 | * @param {Uint8Array} buf Source buffer | ||
3367 | * @param {number} pos Source buffer offset | ||
3368 | * @returns {number} Value read | ||
3369 | */ | ||
3370 | |||
3371 | /** | ||
3372 | * Reads a 64 bit double from a buffer using big endian byte order. | ||
3373 | * @name util.float.readDoubleBE | ||
3374 | * @function | ||
3375 | * @param {Uint8Array} buf Source buffer | ||
3376 | * @param {number} pos Source buffer offset | ||
3377 | * @returns {number} Value read | ||
3378 | */ | ||
3379 | |||
3380 | // Factory function for the purpose of node-based testing in modified global environments | ||
3381 | function factory(exports) { | ||
3382 | |||
3383 | // float: typed array | ||
3384 | if (typeof Float32Array !== "undefined") (function() { | ||
3385 | |||
3386 | var f32 = new Float32Array([ -0 ]), | ||
3387 | f8b = new Uint8Array(f32.buffer), | ||
3388 | le = f8b[3] === 128; | ||
3389 | |||
3390 | function writeFloat_f32_cpy(val, buf, pos) { | ||
3391 | f32[0] = val; | ||
3392 | buf[pos ] = f8b[0]; | ||
3393 | buf[pos + 1] = f8b[1]; | ||
3394 | buf[pos + 2] = f8b[2]; | ||
3395 | buf[pos + 3] = f8b[3]; | ||
3396 | } | ||
3397 | |||
3398 | function writeFloat_f32_rev(val, buf, pos) { | ||
3399 | f32[0] = val; | ||
3400 | buf[pos ] = f8b[3]; | ||
3401 | buf[pos + 1] = f8b[2]; | ||
3402 | buf[pos + 2] = f8b[1]; | ||
3403 | buf[pos + 3] = f8b[0]; | ||
3404 | } | ||
3405 | |||
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; | ||
3410 | |||
3411 | function readFloat_f32_cpy(buf, pos) { | ||
3412 | f8b[0] = buf[pos ]; | ||
3413 | f8b[1] = buf[pos + 1]; | ||
3414 | f8b[2] = buf[pos + 2]; | ||
3415 | f8b[3] = buf[pos + 3]; | ||
3416 | return f32[0]; | ||
3417 | } | ||
3418 | |||
3419 | function readFloat_f32_rev(buf, pos) { | ||
3420 | f8b[3] = buf[pos ]; | ||
3421 | f8b[2] = buf[pos + 1]; | ||
3422 | f8b[1] = buf[pos + 2]; | ||
3423 | f8b[0] = buf[pos + 3]; | ||
3424 | return f32[0]; | ||
3425 | } | ||
3426 | |||
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; | ||
3431 | |||
3432 | // float: ieee754 | ||
3433 | })(); else (function() { | ||
3434 | |||
3435 | function writeFloat_ieee754(writeUint, val, buf, pos) { | ||
3436 | var sign = val < 0 ? 1 : 0; | ||
3437 | if (sign) | ||
3438 | val = -val; | ||
3439 | if (val === 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); | ||
3447 | else { | ||
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); | ||
3451 | } | ||
3452 | } | ||
3453 | |||
3454 | exports.writeFloatLE = writeFloat_ieee754.bind(null, writeUintLE); | ||
3455 | exports.writeFloatBE = writeFloat_ieee754.bind(null, writeUintBE); | ||
3456 | |||
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 | ||
3463 | ? mantissa | ||
3464 | ? NaN | ||
3465 | : sign * Infinity | ||
3466 | : exponent === 0 // denormal | ||
3467 | ? sign * 1.401298464324817e-45 * mantissa | ||
3468 | : sign * Math.pow(2, exponent - 150) * (mantissa + 8388608); | ||
3469 | } | ||
3470 | |||
3471 | exports.readFloatLE = readFloat_ieee754.bind(null, readUintLE); | ||
3472 | exports.readFloatBE = readFloat_ieee754.bind(null, readUintBE); | ||
3473 | |||
3474 | })(); | ||
3475 | |||
3476 | // double: typed array | ||
3477 | if (typeof Float64Array !== "undefined") (function() { | ||
3478 | |||
3479 | var f64 = new Float64Array([-0]), | ||
3480 | f8b = new Uint8Array(f64.buffer), | ||
3481 | le = f8b[7] === 128; | ||
3482 | |||
3483 | function writeDouble_f64_cpy(val, buf, pos) { | ||
3484 | f64[0] = val; | ||
3485 | buf[pos ] = f8b[0]; | ||
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]; | ||
3493 | } | ||
3494 | |||
3495 | function writeDouble_f64_rev(val, buf, pos) { | ||
3496 | f64[0] = val; | ||
3497 | buf[pos ] = f8b[7]; | ||
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]; | ||
3505 | } | ||
3506 | |||
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; | ||
3511 | |||
3512 | function readDouble_f64_cpy(buf, pos) { | ||
3513 | f8b[0] = 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]; | ||
3521 | return f64[0]; | ||
3522 | } | ||
3523 | |||
3524 | function readDouble_f64_rev(buf, pos) { | ||
3525 | f8b[7] = 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]; | ||
3533 | return f64[0]; | ||
3534 | } | ||
3535 | |||
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; | ||
3540 | |||
3541 | // double: ieee754 | ||
3542 | })(); else (function() { | ||
3543 | |||
3544 | function writeDouble_ieee754(writeUint, off0, off1, val, buf, pos) { | ||
3545 | var sign = val < 0 ? 1 : 0; | ||
3546 | if (sign) | ||
3547 | val = -val; | ||
3548 | if (val === 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); | ||
3557 | } else { | ||
3558 | var mantissa; | ||
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); | ||
3563 | } else { | ||
3564 | var exponent = Math.floor(Math.log(val) / Math.LN2); | ||
3565 | if (exponent === 1024) | ||
3566 | exponent = 1023; | ||
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); | ||
3570 | } | ||
3571 | } | ||
3572 | } | ||
3573 | |||
3574 | exports.writeDoubleLE = writeDouble_ieee754.bind(null, writeUintLE, 0, 4); | ||
3575 | exports.writeDoubleBE = writeDouble_ieee754.bind(null, writeUintBE, 4, 0); | ||
3576 | |||
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 | ||
3584 | ? mantissa | ||
3585 | ? NaN | ||
3586 | : sign * Infinity | ||
3587 | : exponent === 0 // denormal | ||
3588 | ? sign * 5e-324 * mantissa | ||
3589 | : sign * Math.pow(2, exponent - 1075) * (mantissa + 4503599627370496); | ||
3590 | } | ||
3591 | |||
3592 | exports.readDoubleLE = readDouble_ieee754.bind(null, readUintLE, 0, 4); | ||
3593 | exports.readDoubleBE = readDouble_ieee754.bind(null, readUintBE, 4, 0); | ||
3594 | |||
3595 | })(); | ||
3596 | |||
3597 | return exports; | ||
3598 | } | ||
3599 | |||
3600 | // uint helpers | ||
3601 | |||
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; | ||
3607 | } | ||
3608 | |||
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; | ||
3614 | } | ||
3615 | |||
3616 | function readUintLE(buf, pos) { | ||
3617 | return (buf[pos ] | ||
3618 | | buf[pos + 1] << 8 | ||
3619 | | buf[pos + 2] << 16 | ||
3620 | | buf[pos + 3] << 24) >>> 0; | ||
3621 | } | ||
3622 | |||
3623 | function readUintBE(buf, pos) { | ||
3624 | return (buf[pos ] << 24 | ||
3625 | | buf[pos + 1] << 16 | ||
3626 | | buf[pos + 2] << 8 | ||
3627 | | buf[pos + 3]) >>> 0; | ||
3628 | } | ||
3629 | |||
3630 | },{}],28:[function(require,module,exports){ | ||
3631 | "use strict"; | ||
3632 | module.exports = inquire; | ||
3633 | |||
3634 | /** | ||
3635 | * Requires a module only if available. | ||
3636 | * @memberof util | ||
3637 | * @param {string} moduleName Module to require | ||
3638 | * @returns {?Object} Required module if available and not empty, otherwise `null` | ||
3639 | */ | ||
3640 | function inquire(moduleName) { | ||
3641 | try { | ||
3642 | var mod = eval("quire".replace(/^/,"re"))(moduleName); // eslint-disable-line no-eval | ||
3643 | if (mod && (mod.length || Object.keys(mod).length)) | ||
3644 | return mod; | ||
3645 | } catch (e) {} // eslint-disable-line no-empty | ||
3646 | return null; | ||
3647 | } | ||
3648 | |||
3649 | },{}],29:[function(require,module,exports){ | ||
3650 | "use strict"; | ||
3651 | |||
3652 | /** | ||
3653 | * A minimal path module to resolve Unix, Windows and URL paths alike. | ||
3654 | * @memberof util | ||
3655 | * @namespace | ||
3656 | */ | ||
3657 | var path = exports; | ||
3658 | |||
3659 | var isAbsolute = | ||
3660 | /** | ||
3661 | * Tests if the specified path is absolute. | ||
3662 | * @param {string} path Path to test | ||
3663 | * @returns {boolean} `true` if path is absolute | ||
3664 | */ | ||
3665 | path.isAbsolute = function isAbsolute(path) { | ||
3666 | return /^(?:\/|\w+:)/.test(path); | ||
3667 | }; | ||
3668 | |||
3669 | var normalize = | ||
3670 | /** | ||
3671 | * Normalizes the specified path. | ||
3672 | * @param {string} path Path to normalize | ||
3673 | * @returns {string} Normalized path | ||
3674 | */ | ||
3675 | path.normalize = function normalize(path) { | ||
3676 | path = path.replace(/\\/g, "/") | ||
3677 | .replace(/\/{2,}/g, "/"); | ||
3678 | var parts = path.split("/"), | ||
3679 | absolute = isAbsolute(path), | ||
3680 | prefix = ""; | ||
3681 | if (absolute) | ||
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); | ||
3687 | else if (absolute) | ||
3688 | parts.splice(i, 1); | ||
3689 | else | ||
3690 | ++i; | ||
3691 | } else if (parts[i] === ".") | ||
3692 | parts.splice(i, 1); | ||
3693 | else | ||
3694 | ++i; | ||
3695 | } | ||
3696 | return prefix + parts.join("/"); | ||
3697 | }; | ||
3698 | |||
3699 | /** | ||
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 | ||
3705 | */ | ||
3706 | path.resolve = function resolve(originPath, includePath, alreadyNormalized) { | ||
3707 | if (!alreadyNormalized) | ||
3708 | includePath = normalize(includePath); | ||
3709 | if (isAbsolute(includePath)) | ||
3710 | return includePath; | ||
3711 | if (!alreadyNormalized) | ||
3712 | originPath = normalize(originPath); | ||
3713 | return (originPath = originPath.replace(/(?:\/|^)[^/]+$/, "")).length ? normalize(originPath + "/" + includePath) : includePath; | ||
3714 | }; | ||
3715 | |||
3716 | },{}],30:[function(require,module,exports){ | ||
3717 | "use strict"; | ||
3718 | module.exports = pool; | ||
3719 | |||
3720 | /** | ||
3721 | * An allocator as used by {@link util.pool}. | ||
3722 | * @typedef PoolAllocator | ||
3723 | * @type {function} | ||
3724 | * @param {number} size Buffer size | ||
3725 | * @returns {Uint8Array} Buffer | ||
3726 | */ | ||
3727 | |||
3728 | /** | ||
3729 | * A slicer as used by {@link util.pool}. | ||
3730 | * @typedef PoolSlicer | ||
3731 | * @type {function} | ||
3732 | * @param {number} start Start offset | ||
3733 | * @param {number} end End offset | ||
3734 | * @returns {Uint8Array} Buffer slice | ||
3735 | * @this {Uint8Array} | ||
3736 | */ | ||
3737 | |||
3738 | /** | ||
3739 | * A general purpose buffer pool. | ||
3740 | * @memberof util | ||
3741 | * @function | ||
3742 | * @param {PoolAllocator} alloc Allocator | ||
3743 | * @param {PoolSlicer} slice Slicer | ||
3744 | * @param {number} [size=8192] Slab size | ||
3745 | * @returns {PoolAllocator} Pooled allocator | ||
3746 | */ | ||
3747 | function pool(alloc, slice, size) { | ||
3748 | var SIZE = size || 8192; | ||
3749 | var MAX = SIZE >>> 1; | ||
3750 | var slab = null; | ||
3751 | var offset = SIZE; | ||
3752 | return function pool_alloc(size) { | ||
3753 | if (size < 1 || size > MAX) | ||
3754 | return alloc(size); | ||
3755 | if (offset + size > SIZE) { | ||
3756 | slab = alloc(SIZE); | ||
3757 | offset = 0; | ||
3758 | } | ||
3759 | var buf = slice.call(slab, offset, offset += size); | ||
3760 | if (offset & 7) // align to 32 bit | ||
3761 | offset = (offset | 7) + 1; | ||
3762 | return buf; | ||
3763 | }; | ||
3764 | } | ||
3765 | |||
3766 | },{}],31:[function(require,module,exports){ | ||
3767 | "use strict"; | ||
3768 | |||
3769 | /** | ||
3770 | * A minimal UTF8 implementation for number arrays. | ||
3771 | * @memberof util | ||
3772 | * @namespace | ||
3773 | */ | ||
3774 | var utf8 = exports; | ||
3775 | |||
3776 | /** | ||
3777 | * Calculates the UTF8 byte length of a string. | ||
3778 | * @param {string} string String | ||
3779 | * @returns {number} Byte length | ||
3780 | */ | ||
3781 | utf8.length = function utf8_length(string) { | ||
3782 | var len = 0, | ||
3783 | c = 0; | ||
3784 | for (var i = 0; i < string.length; ++i) { | ||
3785 | c = string.charCodeAt(i); | ||
3786 | if (c < 128) | ||
3787 | len += 1; | ||
3788 | else if (c < 2048) | ||
3789 | len += 2; | ||
3790 | else if ((c & 0xFC00) === 0xD800 && (string.charCodeAt(i + 1) & 0xFC00) === 0xDC00) { | ||
3791 | ++i; | ||
3792 | len += 4; | ||
3793 | } else | ||
3794 | len += 3; | ||
3795 | } | ||
3796 | return len; | ||
3797 | }; | ||
3798 | |||
3799 | /** | ||
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 | ||
3805 | */ | ||
3806 | utf8.read = function utf8_read(buffer, start, end) { | ||
3807 | var len = end - start; | ||
3808 | if (len < 1) | ||
3809 | return ""; | ||
3810 | var parts = null, | ||
3811 | chunk = [], | ||
3812 | i = 0, // char offset | ||
3813 | t; // temporary | ||
3814 | while (start < end) { | ||
3815 | t = buffer[start++]; | ||
3816 | if (t < 128) | ||
3817 | chunk[i++] = t; | ||
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); | ||
3824 | } else | ||
3825 | chunk[i++] = (t & 15) << 12 | (buffer[start++] & 63) << 6 | buffer[start++] & 63; | ||
3826 | if (i > 8191) { | ||
3827 | (parts || (parts = [])).push(String.fromCharCode.apply(String, chunk)); | ||
3828 | i = 0; | ||
3829 | } | ||
3830 | } | ||
3831 | if (parts) { | ||
3832 | if (i) | ||
3833 | parts.push(String.fromCharCode.apply(String, chunk.slice(0, i))); | ||
3834 | return parts.join(""); | ||
3835 | } | ||
3836 | return String.fromCharCode.apply(String, chunk.slice(0, i)); | ||
3837 | }; | ||
3838 | |||
3839 | /** | ||
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 | ||
3845 | */ | ||
3846 | utf8.write = function utf8_write(string, buffer, offset) { | ||
3847 | var start = offset, | ||
3848 | c1, // character 1 | ||
3849 | c2; // character 2 | ||
3850 | for (var i = 0; i < string.length; ++i) { | ||
3851 | c1 = string.charCodeAt(i); | ||
3852 | if (c1 < 128) { | ||
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); | ||
3859 | ++i; | ||
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; | ||
3864 | } else { | ||
3865 | buffer[offset++] = c1 >> 12 | 224; | ||
3866 | buffer[offset++] = c1 >> 6 & 63 | 128; | ||
3867 | buffer[offset++] = c1 & 63 | 128; | ||
3868 | } | ||
3869 | } | ||
3870 | return offset - start; | ||
3871 | }; | ||
3872 | |||
3873 | },{}],32:[function(require,module,exports){ | ||
3874 | var asn1 = exports; | ||
3875 | |||
3876 | asn1.bignum = require('bn.js'); | ||
3877 | |||
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'); | ||
3883 | |||
3884 | },{"./asn1/api":33,"./asn1/base":35,"./asn1/constants":39,"./asn1/decoders":41,"./asn1/encoders":44,"bn.js":75}],33:[function(require,module,exports){ | ||
3885 | var asn1 = require('../asn1'); | ||
3886 | var inherits = require('inherits'); | ||
3887 | |||
3888 | var api = exports; | ||
3889 | |||
3890 | api.define = function define(name, body) { | ||
3891 | return new Entity(name, body); | ||
3892 | }; | ||
3893 | |||
3894 | function Entity(name, body) { | ||
3895 | this.name = name; | ||
3896 | this.body = body; | ||
3897 | |||
3898 | this.decoders = {}; | ||
3899 | this.encoders = {}; | ||
3900 | }; | ||
3901 | |||
3902 | Entity.prototype._createNamed = function createNamed(base) { | ||
3903 | var named; | ||
3904 | try { | ||
3905 | named = require('vm').runInThisContext( | ||
3906 | '(function ' + this.name + '(entity) {\n' + | ||
3907 | ' this._initNamed(entity);\n' + | ||
3908 | '})' | ||
3909 | ); | ||
3910 | } catch (e) { | ||
3911 | named = function (entity) { | ||
3912 | this._initNamed(entity); | ||
3913 | }; | ||
3914 | } | ||
3915 | inherits(named, base); | ||
3916 | named.prototype._initNamed = function initnamed(entity) { | ||
3917 | base.call(this, entity); | ||
3918 | }; | ||
3919 | |||
3920 | return new named(this); | ||
3921 | }; | ||
3922 | |||
3923 | Entity.prototype._getDecoder = function _getDecoder(enc) { | ||
3924 | enc = enc || 'der'; | ||
3925 | // Lazily create decoder | ||
3926 | if (!this.decoders.hasOwnProperty(enc)) | ||
3927 | this.decoders[enc] = this._createNamed(asn1.decoders[enc]); | ||
3928 | return this.decoders[enc]; | ||
3929 | }; | ||
3930 | |||
3931 | Entity.prototype.decode = function decode(data, enc, options) { | ||
3932 | return this._getDecoder(enc).decode(data, options); | ||
3933 | }; | ||
3934 | |||
3935 | Entity.prototype._getEncoder = function _getEncoder(enc) { | ||
3936 | enc = enc || 'der'; | ||
3937 | // Lazily create encoder | ||
3938 | if (!this.encoders.hasOwnProperty(enc)) | ||
3939 | this.encoders[enc] = this._createNamed(asn1.encoders[enc]); | ||
3940 | return this.encoders[enc]; | ||
3941 | }; | ||
3942 | |||
3943 | Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { | ||
3944 | return this._getEncoder(enc).encode(data, reporter); | ||
3945 | }; | ||
3946 | |||
3947 | },{"../asn1":32,"inherits":163,"vm":271}],34:[function(require,module,exports){ | ||
3948 | var inherits = require('inherits'); | ||
3949 | var Reporter = require('../base').Reporter; | ||
3950 | var Buffer = require('buffer').Buffer; | ||
3951 | |||
3952 | function DecoderBuffer(base, options) { | ||
3953 | Reporter.call(this, options); | ||
3954 | if (!Buffer.isBuffer(base)) { | ||
3955 | this.error('Input not Buffer'); | ||
3956 | return; | ||
3957 | } | ||
3958 | |||
3959 | this.base = base; | ||
3960 | this.offset = 0; | ||
3961 | this.length = base.length; | ||
3962 | } | ||
3963 | inherits(DecoderBuffer, Reporter); | ||
3964 | exports.DecoderBuffer = DecoderBuffer; | ||
3965 | |||
3966 | DecoderBuffer.prototype.save = function save() { | ||
3967 | return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; | ||
3968 | }; | ||
3969 | |||
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; | ||
3975 | |||
3976 | this.offset = save.offset; | ||
3977 | Reporter.prototype.restore.call(this, save.reporter); | ||
3978 | |||
3979 | return res; | ||
3980 | }; | ||
3981 | |||
3982 | DecoderBuffer.prototype.isEmpty = function isEmpty() { | ||
3983 | return this.offset === this.length; | ||
3984 | }; | ||
3985 | |||
3986 | DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { | ||
3987 | if (this.offset + 1 <= this.length) | ||
3988 | return this.base.readUInt8(this.offset++, true); | ||
3989 | else | ||
3990 | return this.error(fail || 'DecoderBuffer overrun'); | ||
3991 | } | ||
3992 | |||
3993 | DecoderBuffer.prototype.skip = function skip(bytes, fail) { | ||
3994 | if (!(this.offset + bytes <= this.length)) | ||
3995 | return this.error(fail || 'DecoderBuffer overrun'); | ||
3996 | |||
3997 | var res = new DecoderBuffer(this.base); | ||
3998 | |||
3999 | // Share reporter state | ||
4000 | res._reporterState = this._reporterState; | ||
4001 | |||
4002 | res.offset = this.offset; | ||
4003 | res.length = this.offset + bytes; | ||
4004 | this.offset += bytes; | ||
4005 | return res; | ||
4006 | } | ||
4007 | |||
4008 | DecoderBuffer.prototype.raw = function raw(save) { | ||
4009 | return this.base.slice(save ? save.offset : this.offset, this.length); | ||
4010 | } | ||
4011 | |||
4012 | function EncoderBuffer(value, reporter) { | ||
4013 | if (Array.isArray(value)) { | ||
4014 | this.length = 0; | ||
4015 | this.value = value.map(function(item) { | ||
4016 | if (!(item instanceof EncoderBuffer)) | ||
4017 | item = new EncoderBuffer(item, reporter); | ||
4018 | this.length += item.length; | ||
4019 | return item; | ||
4020 | }, this); | ||
4021 | } else if (typeof value === 'number') { | ||
4022 | if (!(0 <= value && value <= 0xff)) | ||
4023 | return reporter.error('non-byte EncoderBuffer value'); | ||
4024 | this.value = value; | ||
4025 | this.length = 1; | ||
4026 | } else if (typeof value === 'string') { | ||
4027 | this.value = value; | ||
4028 | this.length = Buffer.byteLength(value); | ||
4029 | } else if (Buffer.isBuffer(value)) { | ||
4030 | this.value = value; | ||
4031 | this.length = value.length; | ||
4032 | } else { | ||
4033 | return reporter.error('Unsupported type: ' + typeof value); | ||
4034 | } | ||
4035 | } | ||
4036 | exports.EncoderBuffer = EncoderBuffer; | ||
4037 | |||
4038 | EncoderBuffer.prototype.join = function join(out, offset) { | ||
4039 | if (!out) | ||
4040 | out = new Buffer(this.length); | ||
4041 | if (!offset) | ||
4042 | offset = 0; | ||
4043 | |||
4044 | if (this.length === 0) | ||
4045 | return out; | ||
4046 | |||
4047 | if (Array.isArray(this.value)) { | ||
4048 | this.value.forEach(function(item) { | ||
4049 | item.join(out, offset); | ||
4050 | offset += item.length; | ||
4051 | }); | ||
4052 | } else { | ||
4053 | if (typeof this.value === 'number') | ||
4054 | out[offset] = this.value; | ||
4055 | else if (typeof this.value === 'string') | ||
4056 | out.write(this.value, offset); | ||
4057 | else if (Buffer.isBuffer(this.value)) | ||
4058 | this.value.copy(out, offset); | ||
4059 | offset += this.length; | ||
4060 | } | ||
4061 | |||
4062 | return out; | ||
4063 | }; | ||
4064 | |||
4065 | },{"../base":35,"buffer":107,"inherits":163}],35:[function(require,module,exports){ | ||
4066 | var base = exports; | ||
4067 | |||
4068 | base.Reporter = require('./reporter').Reporter; | ||
4069 | base.DecoderBuffer = require('./buffer').DecoderBuffer; | ||
4070 | base.EncoderBuffer = require('./buffer').EncoderBuffer; | ||
4071 | base.Node = require('./node'); | ||
4072 | |||
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'); | ||
4078 | |||
4079 | // Supported tags | ||
4080 | var tags = [ | ||
4081 | 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', | ||
4082 | 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', | ||
4083 | 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', | ||
4084 | 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' | ||
4085 | ]; | ||
4086 | |||
4087 | // Public methods list | ||
4088 | var methods = [ | ||
4089 | 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', | ||
4090 | 'any', 'contains' | ||
4091 | ].concat(tags); | ||
4092 | |||
4093 | // Overrided methods list | ||
4094 | var overrided = [ | ||
4095 | '_peekTag', '_decodeTag', '_use', | ||
4096 | '_decodeStr', '_decodeObjid', '_decodeTime', | ||
4097 | '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', | ||
4098 | |||
4099 | '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', | ||
4100 | '_encodeNull', '_encodeInt', '_encodeBool' | ||
4101 | ]; | ||
4102 | |||
4103 | function Node(enc, parent) { | ||
4104 | var state = {}; | ||
4105 | this._baseState = state; | ||
4106 | |||
4107 | state.enc = enc; | ||
4108 | |||
4109 | state.parent = parent || null; | ||
4110 | state.children = null; | ||
4111 | |||
4112 | // State | ||
4113 | state.tag = null; | ||
4114 | state.args = null; | ||
4115 | state.reverseArgs = null; | ||
4116 | state.choice = null; | ||
4117 | state.optional = false; | ||
4118 | state.any = false; | ||
4119 | state.obj = false; | ||
4120 | state.use = null; | ||
4121 | state.useDecoder = null; | ||
4122 | state.key = null; | ||
4123 | state['default'] = null; | ||
4124 | state.explicit = null; | ||
4125 | state.implicit = null; | ||
4126 | state.contains = null; | ||
4127 | |||
4128 | // Should create new instance on each method | ||
4129 | if (!state.parent) { | ||
4130 | state.children = []; | ||
4131 | this._wrap(); | ||
4132 | } | ||
4133 | } | ||
4134 | module.exports = Node; | ||
4135 | |||
4136 | var stateProps = [ | ||
4137 | 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', | ||
4138 | 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', | ||
4139 | 'implicit', 'contains' | ||
4140 | ]; | ||
4141 | |||
4142 | Node.prototype.clone = function clone() { | ||
4143 | var state = this._baseState; | ||
4144 | var cstate = {}; | ||
4145 | stateProps.forEach(function(prop) { | ||
4146 | cstate[prop] = state[prop]; | ||
4147 | }); | ||
4148 | var res = new this.constructor(cstate.parent); | ||
4149 | res._baseState = cstate; | ||
4150 | return res; | ||
4151 | }; | ||
4152 | |||
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); | ||
4160 | }; | ||
4161 | }, this); | ||
4162 | }; | ||
4163 | |||
4164 | Node.prototype._init = function init(body) { | ||
4165 | var state = this._baseState; | ||
4166 | |||
4167 | assert(state.parent === null); | ||
4168 | body.call(this); | ||
4169 | |||
4170 | // Filter children | ||
4171 | state.children = state.children.filter(function(child) { | ||
4172 | return child._baseState.parent === this; | ||
4173 | }, this); | ||
4174 | assert.equal(state.children.length, 1, 'Root node can have only one child'); | ||
4175 | }; | ||
4176 | |||
4177 | Node.prototype._useArgs = function useArgs(args) { | ||
4178 | var state = this._baseState; | ||
4179 | |||
4180 | // Filter children and args | ||
4181 | var children = args.filter(function(arg) { | ||
4182 | return arg instanceof this.constructor; | ||
4183 | }, this); | ||
4184 | args = args.filter(function(arg) { | ||
4185 | return !(arg instanceof this.constructor); | ||
4186 | }, this); | ||
4187 | |||
4188 | if (children.length !== 0) { | ||
4189 | assert(state.children === null); | ||
4190 | state.children = children; | ||
4191 | |||
4192 | // Replace parent to maintain backward link | ||
4193 | children.forEach(function(child) { | ||
4194 | child._baseState.parent = this; | ||
4195 | }, this); | ||
4196 | } | ||
4197 | if (args.length !== 0) { | ||
4198 | assert(state.args === null); | ||
4199 | state.args = args; | ||
4200 | state.reverseArgs = args.map(function(arg) { | ||
4201 | if (typeof arg !== 'object' || arg.constructor !== Object) | ||
4202 | return arg; | ||
4203 | |||
4204 | var res = {}; | ||
4205 | Object.keys(arg).forEach(function(key) { | ||
4206 | if (key == (key | 0)) | ||
4207 | key |= 0; | ||
4208 | var value = arg[key]; | ||
4209 | res[value] = key; | ||
4210 | }); | ||
4211 | return res; | ||
4212 | }); | ||
4213 | } | ||
4214 | }; | ||
4215 | |||
4216 | // | ||
4217 | // Overrided methods | ||
4218 | // | ||
4219 | |||
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); | ||
4224 | }; | ||
4225 | }); | ||
4226 | |||
4227 | // | ||
4228 | // Public methods | ||
4229 | // | ||
4230 | |||
4231 | tags.forEach(function(tag) { | ||
4232 | Node.prototype[tag] = function _tagMethod() { | ||
4233 | var state = this._baseState; | ||
4234 | var args = Array.prototype.slice.call(arguments); | ||
4235 | |||
4236 | assert(state.tag === null); | ||
4237 | state.tag = tag; | ||
4238 | |||
4239 | this._useArgs(args); | ||
4240 | |||
4241 | return this; | ||
4242 | }; | ||
4243 | }); | ||
4244 | |||
4245 | Node.prototype.use = function use(item) { | ||
4246 | assert(item); | ||
4247 | var state = this._baseState; | ||
4248 | |||
4249 | assert(state.use === null); | ||
4250 | state.use = item; | ||
4251 | |||
4252 | return this; | ||
4253 | }; | ||
4254 | |||
4255 | Node.prototype.optional = function optional() { | ||
4256 | var state = this._baseState; | ||
4257 | |||
4258 | state.optional = true; | ||
4259 | |||
4260 | return this; | ||
4261 | }; | ||
4262 | |||
4263 | Node.prototype.def = function def(val) { | ||
4264 | var state = this._baseState; | ||
4265 | |||
4266 | assert(state['default'] === null); | ||
4267 | state['default'] = val; | ||
4268 | state.optional = true; | ||
4269 | |||
4270 | return this; | ||
4271 | }; | ||
4272 | |||
4273 | Node.prototype.explicit = function explicit(num) { | ||
4274 | var state = this._baseState; | ||
4275 | |||
4276 | assert(state.explicit === null && state.implicit === null); | ||
4277 | state.explicit = num; | ||
4278 | |||
4279 | return this; | ||
4280 | }; | ||
4281 | |||
4282 | Node.prototype.implicit = function implicit(num) { | ||
4283 | var state = this._baseState; | ||
4284 | |||
4285 | assert(state.explicit === null && state.implicit === null); | ||
4286 | state.implicit = num; | ||
4287 | |||
4288 | return this; | ||
4289 | }; | ||
4290 | |||
4291 | Node.prototype.obj = function obj() { | ||
4292 | var state = this._baseState; | ||
4293 | var args = Array.prototype.slice.call(arguments); | ||
4294 | |||
4295 | state.obj = true; | ||
4296 | |||
4297 | if (args.length !== 0) | ||
4298 | this._useArgs(args); | ||
4299 | |||
4300 | return this; | ||
4301 | }; | ||
4302 | |||
4303 | Node.prototype.key = function key(newKey) { | ||
4304 | var state = this._baseState; | ||
4305 | |||
4306 | assert(state.key === null); | ||
4307 | state.key = newKey; | ||
4308 | |||
4309 | return this; | ||
4310 | }; | ||
4311 | |||
4312 | Node.prototype.any = function any() { | ||
4313 | var state = this._baseState; | ||
4314 | |||
4315 | state.any = true; | ||
4316 | |||
4317 | return this; | ||
4318 | }; | ||
4319 | |||
4320 | Node.prototype.choice = function choice(obj) { | ||
4321 | var state = this._baseState; | ||
4322 | |||
4323 | assert(state.choice === null); | ||
4324 | state.choice = obj; | ||
4325 | this._useArgs(Object.keys(obj).map(function(key) { | ||
4326 | return obj[key]; | ||
4327 | })); | ||
4328 | |||
4329 | return this; | ||
4330 | }; | ||
4331 | |||
4332 | Node.prototype.contains = function contains(item) { | ||
4333 | var state = this._baseState; | ||
4334 | |||
4335 | assert(state.use === null); | ||
4336 | state.contains = item; | ||
4337 | |||
4338 | return this; | ||
4339 | }; | ||
4340 | |||
4341 | // | ||
4342 | // Decoding | ||
4343 | // | ||
4344 | |||
4345 | Node.prototype._decode = function decode(input, options) { | ||
4346 | var state = this._baseState; | ||
4347 | |||
4348 | // Decode root node | ||
4349 | if (state.parent === null) | ||
4350 | return input.wrapResult(state.children[0]._decode(input, options)); | ||
4351 | |||
4352 | var result = state['default']; | ||
4353 | var present = true; | ||
4354 | |||
4355 | var prevKey = null; | ||
4356 | if (state.key !== null) | ||
4357 | prevKey = input.enterKey(state.key); | ||
4358 | |||
4359 | // Check if tag is there | ||
4360 | if (state.optional) { | ||
4361 | var tag = null; | ||
4362 | if (state.explicit !== null) | ||
4363 | tag = state.explicit; | ||
4364 | else if (state.implicit !== null) | ||
4365 | tag = state.implicit; | ||
4366 | else if (state.tag !== null) | ||
4367 | tag = state.tag; | ||
4368 | |||
4369 | if (tag === null && !state.any) { | ||
4370 | // Trial and Error | ||
4371 | var save = input.save(); | ||
4372 | try { | ||
4373 | if (state.choice === null) | ||
4374 | this._decodeGeneric(state.tag, input, options); | ||
4375 | else | ||
4376 | this._decodeChoice(input, options); | ||
4377 | present = true; | ||
4378 | } catch (e) { | ||
4379 | present = false; | ||
4380 | } | ||
4381 | input.restore(save); | ||
4382 | } else { | ||
4383 | present = this._peekTag(input, tag, state.any); | ||
4384 | |||
4385 | if (input.isError(present)) | ||
4386 | return present; | ||
4387 | } | ||
4388 | } | ||
4389 | |||
4390 | // Push object on stack | ||
4391 | var prevObj; | ||
4392 | if (state.obj && present) | ||
4393 | prevObj = input.enterObject(); | ||
4394 | |||
4395 | if (present) { | ||
4396 | // Unwrap explicit values | ||
4397 | if (state.explicit !== null) { | ||
4398 | var explicit = this._decodeTag(input, state.explicit); | ||
4399 | if (input.isError(explicit)) | ||
4400 | return explicit; | ||
4401 | input = explicit; | ||
4402 | } | ||
4403 | |||
4404 | var start = input.offset; | ||
4405 | |||
4406 | // Unwrap implicit and normal values | ||
4407 | if (state.use === null && state.choice === null) { | ||
4408 | if (state.any) | ||
4409 | var save = input.save(); | ||
4410 | var body = this._decodeTag( | ||
4411 | input, | ||
4412 | state.implicit !== null ? state.implicit : state.tag, | ||
4413 | state.any | ||
4414 | ); | ||
4415 | if (input.isError(body)) | ||
4416 | return body; | ||
4417 | |||
4418 | if (state.any) | ||
4419 | result = input.raw(save); | ||
4420 | else | ||
4421 | input = body; | ||
4422 | } | ||
4423 | |||
4424 | if (options && options.track && state.tag !== null) | ||
4425 | options.track(input.path(), start, input.length, 'tagged'); | ||
4426 | |||
4427 | if (options && options.track && state.tag !== null) | ||
4428 | options.track(input.path(), input.offset, input.length, 'content'); | ||
4429 | |||
4430 | // Select proper method for tag | ||
4431 | if (state.any) | ||
4432 | result = result; | ||
4433 | else if (state.choice === null) | ||
4434 | result = this._decodeGeneric(state.tag, input, options); | ||
4435 | else | ||
4436 | result = this._decodeChoice(input, options); | ||
4437 | |||
4438 | if (input.isError(result)) | ||
4439 | return result; | ||
4440 | |||
4441 | // Decode children | ||
4442 | if (!state.any && state.choice === null && state.children !== null) { | ||
4443 | state.children.forEach(function decodeChildren(child) { | ||
4444 | // NOTE: We are ignoring errors here, to let parser continue with other | ||
4445 | // parts of encoded data | ||
4446 | child._decode(input, options); | ||
4447 | }); | ||
4448 | } | ||
4449 | |||
4450 | // Decode contained/encoded by schema, only in bit or octet strings | ||
4451 | if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { | ||
4452 | var data = new DecoderBuffer(result); | ||
4453 | result = this._getUse(state.contains, input._reporterState.obj) | ||
4454 | ._decode(data, options); | ||
4455 | } | ||
4456 | } | ||
4457 | |||
4458 | // Pop object | ||
4459 | if (state.obj && present) | ||
4460 | result = input.leaveObject(prevObj); | ||
4461 | |||
4462 | // Set key | ||
4463 | if (state.key !== null && (result !== null || present === true)) | ||
4464 | input.leaveKey(prevKey, state.key, result); | ||
4465 | else if (prevKey !== null) | ||
4466 | input.exitKey(prevKey); | ||
4467 | |||
4468 | return result; | ||
4469 | }; | ||
4470 | |||
4471 | Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { | ||
4472 | var state = this._baseState; | ||
4473 | |||
4474 | if (tag === 'seq' || tag === 'set') | ||
4475 | return null; | ||
4476 | if (tag === 'seqof' || tag === 'setof') | ||
4477 | return this._decodeList(input, tag, state.args[0], options); | ||
4478 | else if (/str$/.test(tag)) | ||
4479 | return this._decodeStr(input, tag, options); | ||
4480 | else if (tag === 'objid' && state.args) | ||
4481 | return this._decodeObjid(input, state.args[0], state.args[1], options); | ||
4482 | else if (tag === 'objid') | ||
4483 | return this._decodeObjid(input, null, null, options); | ||
4484 | else if (tag === 'gentime' || tag === 'utctime') | ||
4485 | return this._decodeTime(input, tag, options); | ||
4486 | else if (tag === 'null_') | ||
4487 | return this._decodeNull(input, options); | ||
4488 | else if (tag === 'bool') | ||
4489 | return this._decodeBool(input, options); | ||
4490 | else if (tag === 'objDesc') | ||
4491 | return this._decodeStr(input, tag, options); | ||
4492 | else if (tag === 'int' || tag === 'enum') | ||
4493 | return this._decodeInt(input, state.args && state.args[0], options); | ||
4494 | |||
4495 | if (state.use !== null) { | ||
4496 | return this._getUse(state.use, input._reporterState.obj) | ||
4497 | ._decode(input, options); | ||
4498 | } else { | ||
4499 | return input.error('unknown tag: ' + tag); | ||
4500 | } | ||
4501 | }; | ||
4502 | |||
4503 | Node.prototype._getUse = function _getUse(entity, obj) { | ||
4504 | |||
4505 | var state = this._baseState; | ||
4506 | // Create altered use decoder if implicit is set | ||
4507 | state.useDecoder = this._use(entity, obj); | ||
4508 | assert(state.useDecoder._baseState.parent === null); | ||
4509 | state.useDecoder = state.useDecoder._baseState.children[0]; | ||
4510 | if (state.implicit !== state.useDecoder._baseState.implicit) { | ||
4511 | state.useDecoder = state.useDecoder.clone(); | ||
4512 | state.useDecoder._baseState.implicit = state.implicit; | ||
4513 | } | ||
4514 | return state.useDecoder; | ||
4515 | }; | ||
4516 | |||
4517 | Node.prototype._decodeChoice = function decodeChoice(input, options) { | ||
4518 | var state = this._baseState; | ||
4519 | var result = null; | ||
4520 | var match = false; | ||
4521 | |||
4522 | Object.keys(state.choice).some(function(key) { | ||
4523 | var save = input.save(); | ||
4524 | var node = state.choice[key]; | ||
4525 | try { | ||
4526 | var value = node._decode(input, options); | ||
4527 | if (input.isError(value)) | ||
4528 | return false; | ||
4529 | |||
4530 | result = { type: key, value: value }; | ||
4531 | match = true; | ||
4532 | } catch (e) { | ||
4533 | input.restore(save); | ||
4534 | return false; | ||
4535 | } | ||
4536 | return true; | ||
4537 | }, this); | ||
4538 | |||
4539 | if (!match) | ||
4540 | return input.error('Choice not matched'); | ||
4541 | |||
4542 | return result; | ||
4543 | }; | ||
4544 | |||
4545 | // | ||
4546 | // Encoding | ||
4547 | // | ||
4548 | |||
4549 | Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { | ||
4550 | return new EncoderBuffer(data, this.reporter); | ||
4551 | }; | ||
4552 | |||
4553 | Node.prototype._encode = function encode(data, reporter, parent) { | ||
4554 | var state = this._baseState; | ||
4555 | if (state['default'] !== null && state['default'] === data) | ||
4556 | return; | ||
4557 | |||
4558 | var result = this._encodeValue(data, reporter, parent); | ||
4559 | if (result === undefined) | ||
4560 | return; | ||
4561 | |||
4562 | if (this._skipDefault(result, reporter, parent)) | ||
4563 | return; | ||
4564 | |||
4565 | return result; | ||
4566 | }; | ||
4567 | |||
4568 | Node.prototype._encodeValue = function encode(data, reporter, parent) { | ||
4569 | var state = this._baseState; | ||
4570 | |||
4571 | // Decode root node | ||
4572 | if (state.parent === null) | ||
4573 | return state.children[0]._encode(data, reporter || new Reporter()); | ||
4574 | |||
4575 | var result = null; | ||
4576 | |||
4577 | // Set reporter to share it with a child class | ||
4578 | this.reporter = reporter; | ||
4579 | |||
4580 | // Check if data is there | ||
4581 | if (state.optional && data === undefined) { | ||
4582 | if (state['default'] !== null) | ||
4583 | data = state['default'] | ||
4584 | else | ||
4585 | return; | ||
4586 | } | ||
4587 | |||
4588 | // Encode children first | ||
4589 | var content = null; | ||
4590 | var primitive = false; | ||
4591 | if (state.any) { | ||
4592 | // Anything that was given is translated to buffer | ||
4593 | result = this._createEncoderBuffer(data); | ||
4594 | } else if (state.choice) { | ||
4595 | result = this._encodeChoice(data, reporter); | ||
4596 | } else if (state.contains) { | ||
4597 | content = this._getUse(state.contains, parent)._encode(data, reporter); | ||
4598 | primitive = true; | ||
4599 | } else if (state.children) { | ||
4600 | content = state.children.map(function(child) { | ||
4601 | if (child._baseState.tag === 'null_') | ||
4602 | return child._encode(null, reporter, data); | ||
4603 | |||
4604 | if (child._baseState.key === null) | ||
4605 | return reporter.error('Child should have a key'); | ||
4606 | var prevKey = reporter.enterKey(child._baseState.key); | ||
4607 | |||
4608 | if (typeof data !== 'object') | ||
4609 | return reporter.error('Child expected, but input is not object'); | ||
4610 | |||
4611 | var res = child._encode(data[child._baseState.key], reporter, data); | ||
4612 | reporter.leaveKey(prevKey); | ||
4613 | |||
4614 | return res; | ||
4615 | }, this).filter(function(child) { | ||
4616 | return child; | ||
4617 | }); | ||
4618 | content = this._createEncoderBuffer(content); | ||
4619 | } else { | ||
4620 | if (state.tag === 'seqof' || state.tag === 'setof') { | ||
4621 | // TODO(indutny): this should be thrown on DSL level | ||
4622 | if (!(state.args && state.args.length === 1)) | ||
4623 | return reporter.error('Too many args for : ' + state.tag); | ||
4624 | |||
4625 | if (!Array.isArray(data)) | ||
4626 | return reporter.error('seqof/setof, but data is not Array'); | ||
4627 | |||
4628 | var child = this.clone(); | ||
4629 | child._baseState.implicit = null; | ||
4630 | content = this._createEncoderBuffer(data.map(function(item) { | ||
4631 | var state = this._baseState; | ||
4632 | |||
4633 | return this._getUse(state.args[0], data)._encode(item, reporter); | ||
4634 | }, child)); | ||
4635 | } else if (state.use !== null) { | ||
4636 | result = this._getUse(state.use, parent)._encode(data, reporter); | ||
4637 | } else { | ||
4638 | content = this._encodePrimitive(state.tag, data); | ||
4639 | primitive = true; | ||
4640 | } | ||
4641 | } | ||
4642 | |||
4643 | // Encode data itself | ||
4644 | var result; | ||
4645 | if (!state.any && state.choice === null) { | ||
4646 | var tag = state.implicit !== null ? state.implicit : state.tag; | ||
4647 | var cls = state.implicit === null ? 'universal' : 'context'; | ||
4648 | |||
4649 | if (tag === null) { | ||
4650 | if (state.use === null) | ||
4651 | reporter.error('Tag could be omitted only for .use()'); | ||
4652 | } else { | ||
4653 | if (state.use === null) | ||
4654 | result = this._encodeComposite(tag, primitive, cls, content); | ||
4655 | } | ||
4656 | } | ||
4657 | |||
4658 | // Wrap in explicit | ||
4659 | if (state.explicit !== null) | ||
4660 | result = this._encodeComposite(state.explicit, false, 'context', result); | ||
4661 | |||
4662 | return result; | ||
4663 | }; | ||
4664 | |||
4665 | Node.prototype._encodeChoice = function encodeChoice(data, reporter) { | ||
4666 | var state = this._baseState; | ||
4667 | |||
4668 | var node = state.choice[data.type]; | ||
4669 | if (!node) { | ||
4670 | assert( | ||
4671 | false, | ||
4672 | data.type + ' not found in ' + | ||
4673 | JSON.stringify(Object.keys(state.choice))); | ||
4674 | } | ||
4675 | return node._encode(data.value, reporter); | ||
4676 | }; | ||
4677 | |||
4678 | Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { | ||
4679 | var state = this._baseState; | ||
4680 | |||
4681 | if (/str$/.test(tag)) | ||
4682 | return this._encodeStr(data, tag); | ||
4683 | else if (tag === 'objid' && state.args) | ||
4684 | return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); | ||
4685 | else if (tag === 'objid') | ||
4686 | return this._encodeObjid(data, null, null); | ||
4687 | else if (tag === 'gentime' || tag === 'utctime') | ||
4688 | return this._encodeTime(data, tag); | ||
4689 | else if (tag === 'null_') | ||
4690 | return this._encodeNull(); | ||
4691 | else if (tag === 'int' || tag === 'enum') | ||
4692 | return this._encodeInt(data, state.args && state.reverseArgs[0]); | ||
4693 | else if (tag === 'bool') | ||
4694 | return this._encodeBool(data); | ||
4695 | else if (tag === 'objDesc') | ||
4696 | return this._encodeStr(data, tag); | ||
4697 | else | ||
4698 | throw new Error('Unsupported tag: ' + tag); | ||
4699 | }; | ||
4700 | |||
4701 | Node.prototype._isNumstr = function isNumstr(str) { | ||
4702 | return /^[0-9 ]*$/.test(str); | ||
4703 | }; | ||
4704 | |||
4705 | Node.prototype._isPrintstr = function isPrintstr(str) { | ||
4706 | return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); | ||
4707 | }; | ||
4708 | |||
4709 | },{"../base":35,"minimalistic-assert":176}],37:[function(require,module,exports){ | ||
4710 | var inherits = require('inherits'); | ||
4711 | |||
4712 | function Reporter(options) { | ||
4713 | this._reporterState = { | ||
4714 | obj: null, | ||
4715 | path: [], | ||
4716 | options: options || {}, | ||
4717 | errors: [] | ||
4718 | }; | ||
4719 | } | ||
4720 | exports.Reporter = Reporter; | ||
4721 | |||
4722 | Reporter.prototype.isError = function isError(obj) { | ||
4723 | return obj instanceof ReporterError; | ||
4724 | }; | ||
4725 | |||
4726 | Reporter.prototype.save = function save() { | ||
4727 | var state = this._reporterState; | ||
4728 | |||
4729 | return { obj: state.obj, pathLen: state.path.length }; | ||
4730 | }; | ||
4731 | |||
4732 | Reporter.prototype.restore = function restore(data) { | ||
4733 | var state = this._reporterState; | ||
4734 | |||
4735 | state.obj = data.obj; | ||
4736 | state.path = state.path.slice(0, data.pathLen); | ||
4737 | }; | ||
4738 | |||
4739 | Reporter.prototype.enterKey = function enterKey(key) { | ||
4740 | return this._reporterState.path.push(key); | ||
4741 | }; | ||
4742 | |||
4743 | Reporter.prototype.exitKey = function exitKey(index) { | ||
4744 | var state = this._reporterState; | ||
4745 | |||
4746 | state.path = state.path.slice(0, index - 1); | ||
4747 | }; | ||
4748 | |||
4749 | Reporter.prototype.leaveKey = function leaveKey(index, key, value) { | ||
4750 | var state = this._reporterState; | ||
4751 | |||
4752 | this.exitKey(index); | ||
4753 | if (state.obj !== null) | ||
4754 | state.obj[key] = value; | ||
4755 | }; | ||
4756 | |||
4757 | Reporter.prototype.path = function path() { | ||
4758 | return this._reporterState.path.join('/'); | ||
4759 | }; | ||
4760 | |||
4761 | Reporter.prototype.enterObject = function enterObject() { | ||
4762 | var state = this._reporterState; | ||
4763 | |||
4764 | var prev = state.obj; | ||
4765 | state.obj = {}; | ||
4766 | return prev; | ||
4767 | }; | ||
4768 | |||
4769 | Reporter.prototype.leaveObject = function leaveObject(prev) { | ||
4770 | var state = this._reporterState; | ||
4771 | |||
4772 | var now = state.obj; | ||
4773 | state.obj = prev; | ||
4774 | return now; | ||
4775 | }; | ||
4776 | |||
4777 | Reporter.prototype.error = function error(msg) { | ||
4778 | var err; | ||
4779 | var state = this._reporterState; | ||
4780 | |||
4781 | var inherited = msg instanceof ReporterError; | ||
4782 | if (inherited) { | ||
4783 | err = msg; | ||
4784 | } else { | ||
4785 | err = new ReporterError(state.path.map(function(elem) { | ||
4786 | return '[' + JSON.stringify(elem) + ']'; | ||
4787 | }).join(''), msg.message || msg, msg.stack); | ||
4788 | } | ||
4789 | |||
4790 | if (!state.options.partial) | ||
4791 | throw err; | ||
4792 | |||
4793 | if (!inherited) | ||
4794 | state.errors.push(err); | ||
4795 | |||
4796 | return err; | ||
4797 | }; | ||
4798 | |||
4799 | Reporter.prototype.wrapResult = function wrapResult(result) { | ||
4800 | var state = this._reporterState; | ||
4801 | if (!state.options.partial) | ||
4802 | return result; | ||
4803 | |||
4804 | return { | ||
4805 | result: this.isError(result) ? null : result, | ||
4806 | errors: state.errors | ||
4807 | }; | ||
4808 | }; | ||
4809 | |||
4810 | function ReporterError(path, msg) { | ||
4811 | this.path = path; | ||
4812 | this.rethrow(msg); | ||
4813 | }; | ||
4814 | inherits(ReporterError, Error); | ||
4815 | |||
4816 | ReporterError.prototype.rethrow = function rethrow(msg) { | ||
4817 | this.message = msg + ' at: ' + (this.path || '(shallow)'); | ||
4818 | if (Error.captureStackTrace) | ||
4819 | Error.captureStackTrace(this, ReporterError); | ||
4820 | |||
4821 | if (!this.stack) { | ||
4822 | try { | ||
4823 | // IE only adds stack when thrown | ||
4824 | throw new Error(this.message); | ||
4825 | } catch (e) { | ||
4826 | this.stack = e.stack; | ||
4827 | } | ||
4828 | } | ||
4829 | return this; | ||
4830 | }; | ||
4831 | |||
4832 | },{"inherits":163}],38:[function(require,module,exports){ | ||
4833 | var constants = require('../constants'); | ||
4834 | |||
4835 | exports.tagClass = { | ||
4836 | 0: 'universal', | ||
4837 | 1: 'application', | ||
4838 | 2: 'context', | ||
4839 | 3: 'private' | ||
4840 | }; | ||
4841 | exports.tagClassByName = constants._reverse(exports.tagClass); | ||
4842 | |||
4843 | exports.tag = { | ||
4844 | 0x00: 'end', | ||
4845 | 0x01: 'bool', | ||
4846 | 0x02: 'int', | ||
4847 | 0x03: 'bitstr', | ||
4848 | 0x04: 'octstr', | ||
4849 | 0x05: 'null_', | ||
4850 | 0x06: 'objid', | ||
4851 | 0x07: 'objDesc', | ||
4852 | 0x08: 'external', | ||
4853 | 0x09: 'real', | ||
4854 | 0x0a: 'enum', | ||
4855 | 0x0b: 'embed', | ||
4856 | 0x0c: 'utf8str', | ||
4857 | 0x0d: 'relativeOid', | ||
4858 | 0x10: 'seq', | ||
4859 | 0x11: 'set', | ||
4860 | 0x12: 'numstr', | ||
4861 | 0x13: 'printstr', | ||
4862 | 0x14: 't61str', | ||
4863 | 0x15: 'videostr', | ||
4864 | 0x16: 'ia5str', | ||
4865 | 0x17: 'utctime', | ||
4866 | 0x18: 'gentime', | ||
4867 | 0x19: 'graphstr', | ||
4868 | 0x1a: 'iso646str', | ||
4869 | 0x1b: 'genstr', | ||
4870 | 0x1c: 'unistr', | ||
4871 | 0x1d: 'charstr', | ||
4872 | 0x1e: 'bmpstr' | ||
4873 | }; | ||
4874 | exports.tagByName = constants._reverse(exports.tag); | ||
4875 | |||
4876 | },{"../constants":39}],39:[function(require,module,exports){ | ||
4877 | var constants = exports; | ||
4878 | |||
4879 | // Helper | ||
4880 | constants._reverse = function reverse(map) { | ||
4881 | var res = {}; | ||
4882 | |||
4883 | Object.keys(map).forEach(function(key) { | ||
4884 | // Convert key to integer if it is stringified | ||
4885 | if ((key | 0) == key) | ||
4886 | key = key | 0; | ||
4887 | |||
4888 | var value = map[key]; | ||
4889 | res[value] = key; | ||
4890 | }); | ||
4891 | |||
4892 | return res; | ||
4893 | }; | ||
4894 | |||
4895 | constants.der = require('./der'); | ||
4896 | |||
4897 | },{"./der":38}],40:[function(require,module,exports){ | ||
4898 | var inherits = require('inherits'); | ||
4899 | |||
4900 | var asn1 = require('../../asn1'); | ||
4901 | var base = asn1.base; | ||
4902 | var bignum = asn1.bignum; | ||
4903 | |||
4904 | // Import DER constants | ||
4905 | var der = asn1.constants.der; | ||
4906 | |||
4907 | function DERDecoder(entity) { | ||
4908 | this.enc = 'der'; | ||
4909 | this.name = entity.name; | ||
4910 | this.entity = entity; | ||
4911 | |||
4912 | // Construct base tree | ||
4913 | this.tree = new DERNode(); | ||
4914 | this.tree._init(entity.body); | ||
4915 | }; | ||
4916 | module.exports = DERDecoder; | ||
4917 | |||
4918 | DERDecoder.prototype.decode = function decode(data, options) { | ||
4919 | if (!(data instanceof base.DecoderBuffer)) | ||
4920 | data = new base.DecoderBuffer(data, options); | ||
4921 | |||
4922 | return this.tree._decode(data, options); | ||
4923 | }; | ||
4924 | |||
4925 | // Tree methods | ||
4926 | |||
4927 | function DERNode(parent) { | ||
4928 | base.Node.call(this, 'der', parent); | ||
4929 | } | ||
4930 | inherits(DERNode, base.Node); | ||
4931 | |||
4932 | DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { | ||
4933 | if (buffer.isEmpty()) | ||
4934 | return false; | ||
4935 | |||
4936 | var state = buffer.save(); | ||
4937 | var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); | ||
4938 | if (buffer.isError(decodedTag)) | ||
4939 | return decodedTag; | ||
4940 | |||
4941 | buffer.restore(state); | ||
4942 | |||
4943 | return decodedTag.tag === tag || decodedTag.tagStr === tag || | ||
4944 | (decodedTag.tagStr + 'of') === tag || any; | ||
4945 | }; | ||
4946 | |||
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)) | ||
4951 | return decodedTag; | ||
4952 | |||
4953 | var len = derDecodeLen(buffer, | ||
4954 | decodedTag.primitive, | ||
4955 | 'Failed to get length of "' + tag + '"'); | ||
4956 | |||
4957 | // Failure | ||
4958 | if (buffer.isError(len)) | ||
4959 | return len; | ||
4960 | |||
4961 | if (!any && | ||
4962 | decodedTag.tag !== tag && | ||
4963 | decodedTag.tagStr !== tag && | ||
4964 | decodedTag.tagStr + 'of' !== tag) { | ||
4965 | return buffer.error('Failed to match tag: "' + tag + '"'); | ||
4966 | } | ||
4967 | |||
4968 | if (decodedTag.primitive || len !== null) | ||
4969 | return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); | ||
4970 | |||
4971 | // Indefinite length... find END tag | ||
4972 | var state = buffer.save(); | ||
4973 | var res = this._skipUntilEnd( | ||
4974 | buffer, | ||
4975 | 'Failed to skip indefinite length body: "' + this.tag + '"'); | ||
4976 | if (buffer.isError(res)) | ||
4977 | return res; | ||
4978 | |||
4979 | len = buffer.offset - state.offset; | ||
4980 | buffer.restore(state); | ||
4981 | return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); | ||
4982 | }; | ||
4983 | |||
4984 | DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { | ||
4985 | while (true) { | ||
4986 | var tag = derDecodeTag(buffer, fail); | ||
4987 | if (buffer.isError(tag)) | ||
4988 | return tag; | ||
4989 | var len = derDecodeLen(buffer, tag.primitive, fail); | ||
4990 | if (buffer.isError(len)) | ||
4991 | return len; | ||
4992 | |||
4993 | var res; | ||
4994 | if (tag.primitive || len !== null) | ||
4995 | res = buffer.skip(len) | ||
4996 | else | ||
4997 | res = this._skipUntilEnd(buffer, fail); | ||
4998 | |||
4999 | // Failure | ||
5000 | if (buffer.isError(res)) | ||
5001 | return res; | ||
5002 | |||
5003 | if (tag.tagStr === 'end') | ||
5004 | break; | ||
5005 | } | ||
5006 | }; | ||
5007 | |||
5008 | DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, | ||
5009 | options) { | ||
5010 | var result = []; | ||
5011 | while (!buffer.isEmpty()) { | ||
5012 | var possibleEnd = this._peekTag(buffer, 'end'); | ||
5013 | if (buffer.isError(possibleEnd)) | ||
5014 | return possibleEnd; | ||
5015 | |||
5016 | var res = decoder.decode(buffer, 'der', options); | ||
5017 | if (buffer.isError(res) && possibleEnd) | ||
5018 | break; | ||
5019 | result.push(res); | ||
5020 | } | ||
5021 | return result; | ||
5022 | }; | ||
5023 | |||
5024 | DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { | ||
5025 | if (tag === 'bitstr') { | ||
5026 | var unused = buffer.readUInt8(); | ||
5027 | if (buffer.isError(unused)) | ||
5028 | return unused; | ||
5029 | return { unused: unused, data: buffer.raw() }; | ||
5030 | } else if (tag === 'bmpstr') { | ||
5031 | var raw = buffer.raw(); | ||
5032 | if (raw.length % 2 === 1) | ||
5033 | return buffer.error('Decoding of string type: bmpstr length mismatch'); | ||
5034 | |||
5035 | var str = ''; | ||
5036 | for (var i = 0; i < raw.length / 2; i++) { | ||
5037 | str += String.fromCharCode(raw.readUInt16BE(i * 2)); | ||
5038 | } | ||
5039 | return str; | ||
5040 | } else if (tag === 'numstr') { | ||
5041 | var numstr = buffer.raw().toString('ascii'); | ||
5042 | if (!this._isNumstr(numstr)) { | ||
5043 | return buffer.error('Decoding of string type: ' + | ||
5044 | 'numstr unsupported characters'); | ||
5045 | } | ||
5046 | return numstr; | ||
5047 | } else if (tag === 'octstr') { | ||
5048 | return buffer.raw(); | ||
5049 | } else if (tag === 'objDesc') { | ||
5050 | return buffer.raw(); | ||
5051 | } else if (tag === 'printstr') { | ||
5052 | var printstr = buffer.raw().toString('ascii'); | ||
5053 | if (!this._isPrintstr(printstr)) { | ||
5054 | return buffer.error('Decoding of string type: ' + | ||
5055 | 'printstr unsupported characters'); | ||
5056 | } | ||
5057 | return printstr; | ||
5058 | } else if (/str$/.test(tag)) { | ||
5059 | return buffer.raw().toString(); | ||
5060 | } else { | ||
5061 | return buffer.error('Decoding of string type: ' + tag + ' unsupported'); | ||
5062 | } | ||
5063 | }; | ||
5064 | |||
5065 | DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { | ||
5066 | var result; | ||
5067 | var identifiers = []; | ||
5068 | var ident = 0; | ||
5069 | while (!buffer.isEmpty()) { | ||
5070 | var subident = buffer.readUInt8(); | ||
5071 | ident <<= 7; | ||
5072 | ident |= subident & 0x7f; | ||
5073 | if ((subident & 0x80) === 0) { | ||
5074 | identifiers.push(ident); | ||
5075 | ident = 0; | ||
5076 | } | ||
5077 | } | ||
5078 | if (subident & 0x80) | ||
5079 | identifiers.push(ident); | ||
5080 | |||
5081 | var first = (identifiers[0] / 40) | 0; | ||
5082 | var second = identifiers[0] % 40; | ||
5083 | |||
5084 | if (relative) | ||
5085 | result = identifiers; | ||
5086 | else | ||
5087 | result = [first, second].concat(identifiers.slice(1)); | ||
5088 | |||
5089 | if (values) { | ||
5090 | var tmp = values[result.join(' ')]; | ||
5091 | if (tmp === undefined) | ||
5092 | tmp = values[result.join('.')]; | ||
5093 | if (tmp !== undefined) | ||
5094 | result = tmp; | ||
5095 | } | ||
5096 | |||
5097 | return result; | ||
5098 | }; | ||
5099 | |||
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; | ||
5116 | if (year < 70) | ||
5117 | year = 2000 + year; | ||
5118 | else | ||
5119 | year = 1900 + year; | ||
5120 | } else { | ||
5121 | return buffer.error('Decoding ' + tag + ' time is not supported yet'); | ||
5122 | } | ||
5123 | |||
5124 | return Date.UTC(year, mon - 1, day, hour, min, sec, 0); | ||
5125 | }; | ||
5126 | |||
5127 | DERNode.prototype._decodeNull = function decodeNull(buffer) { | ||
5128 | return null; | ||
5129 | }; | ||
5130 | |||
5131 | DERNode.prototype._decodeBool = function decodeBool(buffer) { | ||
5132 | var res = buffer.readUInt8(); | ||
5133 | if (buffer.isError(res)) | ||
5134 | return res; | ||
5135 | else | ||
5136 | return res !== 0; | ||
5137 | }; | ||
5138 | |||
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); | ||
5143 | |||
5144 | if (values) | ||
5145 | res = values[res.toString(10)] || res; | ||
5146 | |||
5147 | return res; | ||
5148 | }; | ||
5149 | |||
5150 | DERNode.prototype._use = function use(entity, obj) { | ||
5151 | if (typeof entity === 'function') | ||
5152 | entity = entity(obj); | ||
5153 | return entity._getDecoder('der').tree; | ||
5154 | }; | ||
5155 | |||
5156 | // Utility methods | ||
5157 | |||
5158 | function derDecodeTag(buf, fail) { | ||
5159 | var tag = buf.readUInt8(fail); | ||
5160 | if (buf.isError(tag)) | ||
5161 | return tag; | ||
5162 | |||
5163 | var cls = der.tagClass[tag >> 6]; | ||
5164 | var primitive = (tag & 0x20) === 0; | ||
5165 | |||
5166 | // Multi-octet tag - load | ||
5167 | if ((tag & 0x1f) === 0x1f) { | ||
5168 | var oct = tag; | ||
5169 | tag = 0; | ||
5170 | while ((oct & 0x80) === 0x80) { | ||
5171 | oct = buf.readUInt8(fail); | ||
5172 | if (buf.isError(oct)) | ||
5173 | return oct; | ||
5174 | |||
5175 | tag <<= 7; | ||
5176 | tag |= oct & 0x7f; | ||
5177 | } | ||
5178 | } else { | ||
5179 | tag &= 0x1f; | ||
5180 | } | ||
5181 | var tagStr = der.tag[tag]; | ||
5182 | |||
5183 | return { | ||
5184 | cls: cls, | ||
5185 | primitive: primitive, | ||
5186 | tag: tag, | ||
5187 | tagStr: tagStr | ||
5188 | }; | ||
5189 | } | ||
5190 | |||
5191 | function derDecodeLen(buf, primitive, fail) { | ||
5192 | var len = buf.readUInt8(fail); | ||
5193 | if (buf.isError(len)) | ||
5194 | return len; | ||
5195 | |||
5196 | // Indefinite form | ||
5197 | if (!primitive && len === 0x80) | ||
5198 | return null; | ||
5199 | |||
5200 | // Definite form | ||
5201 | if ((len & 0x80) === 0) { | ||
5202 | // Short form | ||
5203 | return len; | ||
5204 | } | ||
5205 | |||
5206 | // Long form | ||
5207 | var num = len & 0x7f; | ||
5208 | if (num > 4) | ||
5209 | return buf.error('length octect is too long'); | ||
5210 | |||
5211 | len = 0; | ||
5212 | for (var i = 0; i < num; i++) { | ||
5213 | len <<= 8; | ||
5214 | var j = buf.readUInt8(fail); | ||
5215 | if (buf.isError(j)) | ||
5216 | return j; | ||
5217 | len |= j; | ||
5218 | } | ||
5219 | |||
5220 | return len; | ||
5221 | } | ||
5222 | |||
5223 | },{"../../asn1":32,"inherits":163}],41:[function(require,module,exports){ | ||
5224 | var decoders = exports; | ||
5225 | |||
5226 | decoders.der = require('./der'); | ||
5227 | decoders.pem = require('./pem'); | ||
5228 | |||
5229 | },{"./der":40,"./pem":42}],42:[function(require,module,exports){ | ||
5230 | var inherits = require('inherits'); | ||
5231 | var Buffer = require('buffer').Buffer; | ||
5232 | |||
5233 | var DERDecoder = require('./der'); | ||
5234 | |||
5235 | function PEMDecoder(entity) { | ||
5236 | DERDecoder.call(this, entity); | ||
5237 | this.enc = 'pem'; | ||
5238 | }; | ||
5239 | inherits(PEMDecoder, DERDecoder); | ||
5240 | module.exports = PEMDecoder; | ||
5241 | |||
5242 | PEMDecoder.prototype.decode = function decode(data, options) { | ||
5243 | var lines = data.toString().split(/[\r\n]+/g); | ||
5244 | |||
5245 | var label = options.label.toUpperCase(); | ||
5246 | |||
5247 | var re = /^-----(BEGIN|END) ([^-]+)-----$/; | ||
5248 | var start = -1; | ||
5249 | var end = -1; | ||
5250 | for (var i = 0; i < lines.length; i++) { | ||
5251 | var match = lines[i].match(re); | ||
5252 | if (match === null) | ||
5253 | continue; | ||
5254 | |||
5255 | if (match[2] !== label) | ||
5256 | continue; | ||
5257 | |||
5258 | if (start === -1) { | ||
5259 | if (match[1] !== 'BEGIN') | ||
5260 | break; | ||
5261 | start = i; | ||
5262 | } else { | ||
5263 | if (match[1] !== 'END') | ||
5264 | break; | ||
5265 | end = i; | ||
5266 | break; | ||
5267 | } | ||
5268 | } | ||
5269 | if (start === -1 || end === -1) | ||
5270 | throw new Error('PEM section not found for: ' + label); | ||
5271 | |||
5272 | var base64 = lines.slice(start + 1, end).join(''); | ||
5273 | // Remove excessive symbols | ||
5274 | base64.replace(/[^a-z0-9\+\/=]+/gi, ''); | ||
5275 | |||
5276 | var input = new Buffer(base64, 'base64'); | ||
5277 | return DERDecoder.prototype.decode.call(this, input, options); | ||
5278 | }; | ||
5279 | |||
5280 | },{"./der":40,"buffer":107,"inherits":163}],43:[function(require,module,exports){ | ||
5281 | var inherits = require('inherits'); | ||
5282 | var Buffer = require('buffer').Buffer; | ||
5283 | |||
5284 | var asn1 = require('../../asn1'); | ||
5285 | var base = asn1.base; | ||
5286 | |||
5287 | // Import DER constants | ||
5288 | var der = asn1.constants.der; | ||
5289 | |||
5290 | function DEREncoder(entity) { | ||
5291 | this.enc = 'der'; | ||
5292 | this.name = entity.name; | ||
5293 | this.entity = entity; | ||
5294 | |||
5295 | // Construct base tree | ||
5296 | this.tree = new DERNode(); | ||
5297 | this.tree._init(entity.body); | ||
5298 | }; | ||
5299 | module.exports = DEREncoder; | ||
5300 | |||
5301 | DEREncoder.prototype.encode = function encode(data, reporter) { | ||
5302 | return this.tree._encode(data, reporter).join(); | ||
5303 | }; | ||
5304 | |||
5305 | // Tree methods | ||
5306 | |||
5307 | function DERNode(parent) { | ||
5308 | base.Node.call(this, 'der', parent); | ||
5309 | } | ||
5310 | inherits(DERNode, base.Node); | ||
5311 | |||
5312 | DERNode.prototype._encodeComposite = function encodeComposite(tag, | ||
5313 | primitive, | ||
5314 | cls, | ||
5315 | content) { | ||
5316 | var encodedTag = encodeTag(tag, primitive, cls, this.reporter); | ||
5317 | |||
5318 | // Short form | ||
5319 | if (content.length < 0x80) { | ||
5320 | var header = new Buffer(2); | ||
5321 | header[0] = encodedTag; | ||
5322 | header[1] = content.length; | ||
5323 | return this._createEncoderBuffer([ header, content ]); | ||
5324 | } | ||
5325 | |||
5326 | // Long form | ||
5327 | // Count octets required to store length | ||
5328 | var lenOctets = 1; | ||
5329 | for (var i = content.length; i >= 0x100; i >>= 8) | ||
5330 | lenOctets++; | ||
5331 | |||
5332 | var header = new Buffer(1 + 1 + lenOctets); | ||
5333 | header[0] = encodedTag; | ||
5334 | header[1] = 0x80 | lenOctets; | ||
5335 | |||
5336 | for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) | ||
5337 | header[i] = j & 0xff; | ||
5338 | |||
5339 | return this._createEncoderBuffer([ header, content ]); | ||
5340 | }; | ||
5341 | |||
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); | ||
5349 | } | ||
5350 | return this._createEncoderBuffer(buf); | ||
5351 | } else if (tag === 'numstr') { | ||
5352 | if (!this._isNumstr(str)) { | ||
5353 | return this.reporter.error('Encoding of string type: numstr supports ' + | ||
5354 | 'only digits and space'); | ||
5355 | } | ||
5356 | return this._createEncoderBuffer(str); | ||
5357 | } else if (tag === 'printstr') { | ||
5358 | if (!this._isPrintstr(str)) { | ||
5359 | return this.reporter.error('Encoding of string type: printstr supports ' + | ||
5360 | 'only latin upper and lower case letters, ' + | ||
5361 | 'digits, space, apostrophe, left and rigth ' + | ||
5362 | 'parenthesis, plus sign, comma, hyphen, ' + | ||
5363 | 'dot, slash, colon, equal sign, ' + | ||
5364 | 'question mark'); | ||
5365 | } | ||
5366 | return this._createEncoderBuffer(str); | ||
5367 | } else if (/str$/.test(tag)) { | ||
5368 | return this._createEncoderBuffer(str); | ||
5369 | } else if (tag === 'objDesc') { | ||
5370 | return this._createEncoderBuffer(str); | ||
5371 | } else { | ||
5372 | return this.reporter.error('Encoding of string type: ' + tag + | ||
5373 | ' unsupported'); | ||
5374 | } | ||
5375 | }; | ||
5376 | |||
5377 | DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { | ||
5378 | if (typeof id === 'string') { | ||
5379 | if (!values) | ||
5380 | return this.reporter.error('string objid given, but no values map found'); | ||
5381 | if (!values.hasOwnProperty(id)) | ||
5382 | return this.reporter.error('objid not found in values map'); | ||
5383 | id = values[id].split(/[\s\.]+/g); | ||
5384 | for (var i = 0; i < id.length; i++) | ||
5385 | id[i] |= 0; | ||
5386 | } else if (Array.isArray(id)) { | ||
5387 | id = id.slice(); | ||
5388 | for (var i = 0; i < id.length; i++) | ||
5389 | id[i] |= 0; | ||
5390 | } | ||
5391 | |||
5392 | if (!Array.isArray(id)) { | ||
5393 | return this.reporter.error('objid() should be either array or string, ' + | ||
5394 | 'got: ' + JSON.stringify(id)); | ||
5395 | } | ||
5396 | |||
5397 | if (!relative) { | ||
5398 | if (id[1] >= 40) | ||
5399 | return this.reporter.error('Second objid identifier OOB'); | ||
5400 | id.splice(0, 2, id[0] * 40 + id[1]); | ||
5401 | } | ||
5402 | |||
5403 | // Count number of octets | ||
5404 | var size = 0; | ||
5405 | for (var i = 0; i < id.length; i++) { | ||
5406 | var ident = id[i]; | ||
5407 | for (size++; ident >= 0x80; ident >>= 7) | ||
5408 | size++; | ||
5409 | } | ||
5410 | |||
5411 | var objid = new Buffer(size); | ||
5412 | var offset = objid.length - 1; | ||
5413 | for (var i = id.length - 1; i >= 0; i--) { | ||
5414 | var ident = id[i]; | ||
5415 | objid[offset--] = ident & 0x7f; | ||
5416 | while ((ident >>= 7) > 0) | ||
5417 | objid[offset--] = 0x80 | (ident & 0x7f); | ||
5418 | } | ||
5419 | |||
5420 | return this._createEncoderBuffer(objid); | ||
5421 | }; | ||
5422 | |||
5423 | function two(num) { | ||
5424 | if (num < 10) | ||
5425 | return '0' + num; | ||
5426 | else | ||
5427 | return num; | ||
5428 | } | ||
5429 | |||
5430 | DERNode.prototype._encodeTime = function encodeTime(time, tag) { | ||
5431 | var str; | ||
5432 | var date = new Date(time); | ||
5433 | |||
5434 | if (tag === 'gentime') { | ||
5435 | str = [ | ||
5436 | two(date.getFullYear()), | ||
5437 | two(date.getUTCMonth() + 1), | ||
5438 | two(date.getUTCDate()), | ||
5439 | two(date.getUTCHours()), | ||
5440 | two(date.getUTCMinutes()), | ||
5441 | two(date.getUTCSeconds()), | ||
5442 | 'Z' | ||
5443 | ].join(''); | ||
5444 | } else if (tag === 'utctime') { | ||
5445 | str = [ | ||
5446 | two(date.getFullYear() % 100), | ||
5447 | two(date.getUTCMonth() + 1), | ||
5448 | two(date.getUTCDate()), | ||
5449 | two(date.getUTCHours()), | ||
5450 | two(date.getUTCMinutes()), | ||
5451 | two(date.getUTCSeconds()), | ||
5452 | 'Z' | ||
5453 | ].join(''); | ||
5454 | } else { | ||
5455 | this.reporter.error('Encoding ' + tag + ' time is not supported yet'); | ||
5456 | } | ||
5457 | |||
5458 | return this._encodeStr(str, 'octstr'); | ||
5459 | }; | ||
5460 | |||
5461 | DERNode.prototype._encodeNull = function encodeNull() { | ||
5462 | return this._createEncoderBuffer(''); | ||
5463 | }; | ||
5464 | |||
5465 | DERNode.prototype._encodeInt = function encodeInt(num, values) { | ||
5466 | if (typeof num === 'string') { | ||
5467 | if (!values) | ||
5468 | return this.reporter.error('String int or enum given, but no values map'); | ||
5469 | if (!values.hasOwnProperty(num)) { | ||
5470 | return this.reporter.error('Values map doesn\'t contain: ' + | ||
5471 | JSON.stringify(num)); | ||
5472 | } | ||
5473 | num = values[num]; | ||
5474 | } | ||
5475 | |||
5476 | // Bignum, assume big endian | ||
5477 | if (typeof num !== 'number' && !Buffer.isBuffer(num)) { | ||
5478 | var numArray = num.toArray(); | ||
5479 | if (!num.sign && numArray[0] & 0x80) { | ||
5480 | numArray.unshift(0); | ||
5481 | } | ||
5482 | num = new Buffer(numArray); | ||
5483 | } | ||
5484 | |||
5485 | if (Buffer.isBuffer(num)) { | ||
5486 | var size = num.length; | ||
5487 | if (num.length === 0) | ||
5488 | size++; | ||
5489 | |||
5490 | var out = new Buffer(size); | ||
5491 | num.copy(out); | ||
5492 | if (num.length === 0) | ||
5493 | out[0] = 0 | ||
5494 | return this._createEncoderBuffer(out); | ||
5495 | } | ||
5496 | |||
5497 | if (num < 0x80) | ||
5498 | return this._createEncoderBuffer(num); | ||
5499 | |||
5500 | if (num < 0x100) | ||
5501 | return this._createEncoderBuffer([0, num]); | ||
5502 | |||
5503 | var size = 1; | ||
5504 | for (var i = num; i >= 0x100; i >>= 8) | ||
5505 | size++; | ||
5506 | |||
5507 | var out = new Array(size); | ||
5508 | for (var i = out.length - 1; i >= 0; i--) { | ||
5509 | out[i] = num & 0xff; | ||
5510 | num >>= 8; | ||
5511 | } | ||
5512 | if(out[0] & 0x80) { | ||
5513 | out.unshift(0); | ||
5514 | } | ||
5515 | |||
5516 | return this._createEncoderBuffer(new Buffer(out)); | ||
5517 | }; | ||
5518 | |||
5519 | DERNode.prototype._encodeBool = function encodeBool(value) { | ||
5520 | return this._createEncoderBuffer(value ? 0xff : 0); | ||
5521 | }; | ||
5522 | |||
5523 | DERNode.prototype._use = function use(entity, obj) { | ||
5524 | if (typeof entity === 'function') | ||
5525 | entity = entity(obj); | ||
5526 | return entity._getEncoder('der').tree; | ||
5527 | }; | ||
5528 | |||
5529 | DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { | ||
5530 | var state = this._baseState; | ||
5531 | var i; | ||
5532 | if (state['default'] === null) | ||
5533 | return false; | ||
5534 | |||
5535 | var data = dataBuffer.join(); | ||
5536 | if (state.defaultBuffer === undefined) | ||
5537 | state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); | ||
5538 | |||
5539 | if (data.length !== state.defaultBuffer.length) | ||
5540 | return false; | ||
5541 | |||
5542 | for (i=0; i < data.length; i++) | ||
5543 | if (data[i] !== state.defaultBuffer[i]) | ||
5544 | return false; | ||
5545 | |||
5546 | return true; | ||
5547 | }; | ||
5548 | |||
5549 | // Utility methods | ||
5550 | |||
5551 | function encodeTag(tag, primitive, cls, reporter) { | ||
5552 | var res; | ||
5553 | |||
5554 | if (tag === 'seqof') | ||
5555 | tag = 'seq'; | ||
5556 | else if (tag === 'setof') | ||
5557 | tag = 'set'; | ||
5558 | |||
5559 | if (der.tagByName.hasOwnProperty(tag)) | ||
5560 | res = der.tagByName[tag]; | ||
5561 | else if (typeof tag === 'number' && (tag | 0) === tag) | ||
5562 | res = tag; | ||
5563 | else | ||
5564 | return reporter.error('Unknown tag: ' + tag); | ||
5565 | |||
5566 | if (res >= 0x1f) | ||
5567 | return reporter.error('Multi-octet tag encoding unsupported'); | ||
5568 | |||
5569 | if (!primitive) | ||
5570 | res |= 0x20; | ||
5571 | |||
5572 | res |= (der.tagClassByName[cls || 'universal'] << 6); | ||
5573 | |||
5574 | return res; | ||
5575 | } | ||
5576 | |||
5577 | },{"../../asn1":32,"buffer":107,"inherits":163}],44:[function(require,module,exports){ | ||
5578 | var encoders = exports; | ||
5579 | |||
5580 | encoders.der = require('./der'); | ||
5581 | encoders.pem = require('./pem'); | ||
5582 | |||
5583 | },{"./der":43,"./pem":45}],45:[function(require,module,exports){ | ||
5584 | var inherits = require('inherits'); | ||
5585 | |||
5586 | var DEREncoder = require('./der'); | ||
5587 | |||
5588 | function PEMEncoder(entity) { | ||
5589 | DEREncoder.call(this, entity); | ||
5590 | this.enc = 'pem'; | ||
5591 | }; | ||
5592 | inherits(PEMEncoder, DEREncoder); | ||
5593 | module.exports = PEMEncoder; | ||
5594 | |||
5595 | PEMEncoder.prototype.encode = function encode(data, options) { | ||
5596 | var buf = DEREncoder.prototype.encode.call(this, data); | ||
5597 | |||
5598 | var p = buf.toString('base64'); | ||
5599 | var out = [ '-----BEGIN ' + options.label + '-----' ]; | ||
5600 | for (var i = 0; i < p.length; i += 64) | ||
5601 | out.push(p.slice(i, i + 64)); | ||
5602 | out.push('-----END ' + options.label + '-----'); | ||
5603 | return out.join('\n'); | ||
5604 | }; | ||
5605 | |||
5606 | },{"./der":43,"inherits":163}],46:[function(require,module,exports){ | ||
5607 | module.exports = require('./lib/axios'); | ||
5608 | },{"./lib/axios":48}],47:[function(require,module,exports){ | ||
5609 | (function (process){ | ||
5610 | 'use strict'; | ||
5611 | |||
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'); | ||
5619 | |||
5620 | module.exports = function xhrAdapter(config) { | ||
5621 | return new Promise(function dispatchXhrRequest(resolve, reject) { | ||
5622 | var requestData = config.data; | ||
5623 | var requestHeaders = config.headers; | ||
5624 | |||
5625 | if (utils.isFormData(requestData)) { | ||
5626 | delete requestHeaders['Content-Type']; // Let the browser set it | ||
5627 | } | ||
5628 | |||
5629 | var request = new XMLHttpRequest(); | ||
5630 | var loadEvent = 'onreadystatechange'; | ||
5631 | var xDomain = false; | ||
5632 | |||
5633 | // For IE 8/9 CORS support | ||
5634 | // Only supports POST and GET calls and doesn't returns the response headers. | ||
5635 | // DON'T do this for testing b/c XMLHttpRequest is mocked, not XDomainRequest. | ||
5636 | if (process.env.NODE_ENV !== 'test' && | ||
5637 | typeof window !== 'undefined' && | ||
5638 | window.XDomainRequest && !('withCredentials' in request) && | ||
5639 | !isURLSameOrigin(config.url)) { | ||
5640 | request = new window.XDomainRequest(); | ||
5641 | loadEvent = 'onload'; | ||
5642 | xDomain = true; | ||
5643 | request.onprogress = function handleProgress() {}; | ||
5644 | request.ontimeout = function handleTimeout() {}; | ||
5645 | } | ||
5646 | |||
5647 | // HTTP basic authentication | ||
5648 | if (config.auth) { | ||
5649 | var username = config.auth.username || ''; | ||
5650 | var password = config.auth.password || ''; | ||
5651 | requestHeaders.Authorization = 'Basic ' + btoa(username + ':' + password); | ||
5652 | } | ||
5653 | |||
5654 | request.open(config.method.toUpperCase(), buildURL(config.url, config.params, config.paramsSerializer), true); | ||
5655 | |||
5656 | // Set the request timeout in MS | ||
5657 | request.timeout = config.timeout; | ||
5658 | |||
5659 | // Listen for ready state | ||
5660 | request[loadEvent] = function handleLoad() { | ||
5661 | if (!request || (request.readyState !== 4 && !xDomain)) { | ||
5662 | return; | ||
5663 | } | ||
5664 | |||
5665 | // The request errored out and we didn't get a response, this will be | ||
5666 | // handled by onerror instead | ||
5667 | // With one exception: request that using file: protocol, most browsers | ||
5668 | // will return status as 0 even though it's a successful request | ||
5669 | if (request.status === 0 && !(request.responseURL && request.responseURL.indexOf('file:') === 0)) { | ||
5670 | return; | ||
5671 | } | ||
5672 | |||
5673 | // Prepare the response | ||
5674 | var responseHeaders = 'getAllResponseHeaders' in request ? parseHeaders(request.getAllResponseHeaders()) : null; | ||
5675 | var responseData = !config.responseType || config.responseType === 'text' ? request.responseText : request.response; | ||
5676 | var response = { | ||
5677 | data: responseData, | ||
5678 | // IE sends 1223 instead of 204 (https://github.com/axios/axios/issues/201) | ||
5679 | status: request.status === 1223 ? 204 : request.status, | ||
5680 | statusText: request.status === 1223 ? 'No Content' : request.statusText, | ||
5681 | headers: responseHeaders, | ||
5682 | config: config, | ||
5683 | request: request | ||
5684 | }; | ||
5685 | |||
5686 | settle(resolve, reject, response); | ||
5687 | |||
5688 | // Clean up request | ||
5689 | request = null; | ||
5690 | }; | ||
5691 | |||
5692 | // Handle low level network errors | ||
5693 | request.onerror = function handleError() { | ||
5694 | // Real errors are hidden from us by the browser | ||
5695 | // onerror should only fire if it's a network error | ||
5696 | reject(createError('Network Error', config, null, request)); | ||
5697 | |||
5698 | // Clean up request | ||
5699 | request = null; | ||
5700 | }; | ||
5701 | |||
5702 | // Handle timeout | ||
5703 | request.ontimeout = function handleTimeout() { | ||
5704 | reject(createError('timeout of ' + config.timeout + 'ms exceeded', config, 'ECONNABORTED', | ||
5705 | request)); | ||
5706 | |||
5707 | // Clean up request | ||
5708 | request = null; | ||
5709 | }; | ||
5710 | |||
5711 | // Add xsrf header | ||
5712 | // This is only done if running in a standard browser environment. | ||
5713 | // Specifically not if we're in a web worker, or react-native. | ||
5714 | if (utils.isStandardBrowserEnv()) { | ||
5715 | var cookies = require('./../helpers/cookies'); | ||
5716 | |||
5717 | // Add xsrf header | ||
5718 | var xsrfValue = (config.withCredentials || isURLSameOrigin(config.url)) && config.xsrfCookieName ? | ||
5719 | cookies.read(config.xsrfCookieName) : | ||
5720 | undefined; | ||
5721 | |||
5722 | if (xsrfValue) { | ||
5723 | requestHeaders[config.xsrfHeaderName] = xsrfValue; | ||
5724 | } | ||
5725 | } | ||
5726 | |||
5727 | // Add headers to the request | ||
5728 | if ('setRequestHeader' in request) { | ||
5729 | utils.forEach(requestHeaders, function setRequestHeader(val, key) { | ||
5730 | if (typeof requestData === 'undefined' && key.toLowerCase() === 'content-type') { | ||
5731 | // Remove Content-Type if data is undefined | ||
5732 | delete requestHeaders[key]; | ||
5733 | } else { | ||
5734 | // Otherwise add header to the request | ||
5735 | request.setRequestHeader(key, val); | ||
5736 | } | ||
5737 | }); | ||
5738 | } | ||
5739 | |||
5740 | // Add withCredentials to request if needed | ||
5741 | if (config.withCredentials) { | ||
5742 | request.withCredentials = true; | ||
5743 | } | ||
5744 | |||
5745 | // Add responseType to request if needed | ||
5746 | if (config.responseType) { | ||
5747 | try { | ||
5748 | request.responseType = config.responseType; | ||
5749 | } catch (e) { | ||
5750 | // Expected DOMException thrown by browsers not compatible XMLHttpRequest Level 2. | ||
5751 | // But, this can be suppressed for 'json' type as it can be parsed by default 'transformResponse' function. | ||
5752 | if (config.responseType !== 'json') { | ||
5753 | throw e; | ||
5754 | } | ||
5755 | } | ||
5756 | } | ||
5757 | |||
5758 | // Handle progress if needed | ||
5759 | if (typeof config.onDownloadProgress === 'function') { | ||
5760 | request.addEventListener('progress', config.onDownloadProgress); | ||
5761 | } | ||
5762 | |||
5763 | // Not all browsers support upload events | ||
5764 | if (typeof config.onUploadProgress === 'function' && request.upload) { | ||
5765 | request.upload.addEventListener('progress', config.onUploadProgress); | ||
5766 | } | ||
5767 | |||
5768 | if (config.cancelToken) { | ||
5769 | // Handle cancellation | ||
5770 | config.cancelToken.promise.then(function onCanceled(cancel) { | ||
5771 | if (!request) { | ||
5772 | return; | ||
5773 | } | ||
5774 | |||
5775 | request.abort(); | ||
5776 | reject(cancel); | ||
5777 | // Clean up request | ||
5778 | request = null; | ||
5779 | }); | ||
5780 | } | ||
5781 | |||
5782 | if (requestData === undefined) { | ||
5783 | requestData = null; | ||
5784 | } | ||
5785 | |||
5786 | // Send the request | ||
5787 | request.send(requestData); | ||
5788 | }); | ||
5789 | }; | ||
5790 | |||
5791 | }).call(this,require('_process')) | ||
5792 | },{"../core/createError":54,"./../core/settle":57,"./../helpers/btoa":61,"./../helpers/buildURL":62,"./../helpers/cookies":64,"./../helpers/isURLSameOrigin":66,"./../helpers/parseHeaders":68,"./../utils":70,"_process":190}],48:[function(require,module,exports){ | ||
5793 | 'use strict'; | ||
5794 | |||
5795 | var utils = require('./utils'); | ||
5796 | var bind = require('./helpers/bind'); | ||
5797 | var Axios = require('./core/Axios'); | ||
5798 | var defaults = require('./defaults'); | ||
5799 | |||
5800 | /** | ||
5801 | * Create an instance of Axios | ||
5802 | * | ||
5803 | * @param {Object} defaultConfig The default config for the instance | ||
5804 | * @return {Axios} A new instance of Axios | ||
5805 | */ | ||
5806 | function createInstance(defaultConfig) { | ||
5807 | var context = new Axios(defaultConfig); | ||
5808 | var instance = bind(Axios.prototype.request, context); | ||
5809 | |||
5810 | // Copy axios.prototype to instance | ||
5811 | utils.extend(instance, Axios.prototype, context); | ||
5812 | |||
5813 | // Copy context to instance | ||
5814 | utils.extend(instance, context); | ||
5815 | |||
5816 | return instance; | ||
5817 | } | ||
5818 | |||
5819 | // Create the default instance to be exported | ||
5820 | var axios = createInstance(defaults); | ||
5821 | |||
5822 | // Expose Axios class to allow class inheritance | ||
5823 | axios.Axios = Axios; | ||
5824 | |||
5825 | // Factory for creating new instances | ||
5826 | axios.create = function create(instanceConfig) { | ||
5827 | return createInstance(utils.merge(defaults, instanceConfig)); | ||
5828 | }; | ||
5829 | |||
5830 | // Expose Cancel & CancelToken | ||
5831 | axios.Cancel = require('./cancel/Cancel'); | ||
5832 | axios.CancelToken = require('./cancel/CancelToken'); | ||
5833 | axios.isCancel = require('./cancel/isCancel'); | ||
5834 | |||
5835 | // Expose all/spread | ||
5836 | axios.all = function all(promises) { | ||
5837 | return Promise.all(promises); | ||
5838 | }; | ||
5839 | axios.spread = require('./helpers/spread'); | ||
5840 | |||
5841 | module.exports = axios; | ||
5842 | |||
5843 | // Allow use of default import syntax in TypeScript | ||
5844 | module.exports.default = axios; | ||
5845 | |||
5846 | },{"./cancel/Cancel":49,"./cancel/CancelToken":50,"./cancel/isCancel":51,"./core/Axios":52,"./defaults":59,"./helpers/bind":60,"./helpers/spread":69,"./utils":70}],49:[function(require,module,exports){ | ||
5847 | 'use strict'; | ||
5848 | |||
5849 | /** | ||
5850 | * A `Cancel` is an object that is thrown when an operation is canceled. | ||
5851 | * | ||
5852 | * @class | ||
5853 | * @param {string=} message The message. | ||
5854 | */ | ||
5855 | function Cancel(message) { | ||
5856 | this.message = message; | ||
5857 | } | ||
5858 | |||
5859 | Cancel.prototype.toString = function toString() { | ||
5860 | return 'Cancel' + (this.message ? ': ' + this.message : ''); | ||
5861 | }; | ||
5862 | |||
5863 | Cancel.prototype.__CANCEL__ = true; | ||
5864 | |||
5865 | module.exports = Cancel; | ||
5866 | |||
5867 | },{}],50:[function(require,module,exports){ | ||
5868 | 'use strict'; | ||
5869 | |||
5870 | var Cancel = require('./Cancel'); | ||
5871 | |||
5872 | /** | ||
5873 | * A `CancelToken` is an object that can be used to request cancellation of an operation. | ||
5874 | * | ||
5875 | * @class | ||
5876 | * @param {Function} executor The executor function. | ||
5877 | */ | ||
5878 | function CancelToken(executor) { | ||
5879 | if (typeof executor !== 'function') { | ||
5880 | throw new TypeError('executor must be a function.'); | ||
5881 | } | ||
5882 | |||
5883 | var resolvePromise; | ||
5884 | this.promise = new Promise(function promiseExecutor(resolve) { | ||
5885 | resolvePromise = resolve; | ||
5886 | }); | ||
5887 | |||
5888 | var token = this; | ||
5889 | executor(function cancel(message) { | ||
5890 | if (token.reason) { | ||
5891 | // Cancellation has already been requested | ||
5892 | return; | ||
5893 | } | ||
5894 | |||
5895 | token.reason = new Cancel(message); | ||
5896 | resolvePromise(token.reason); | ||
5897 | }); | ||
5898 | } | ||
5899 | |||
5900 | /** | ||
5901 | * Throws a `Cancel` if cancellation has been requested. | ||
5902 | */ | ||
5903 | CancelToken.prototype.throwIfRequested = function throwIfRequested() { | ||
5904 | if (this.reason) { | ||
5905 | throw this.reason; | ||
5906 | } | ||
5907 | }; | ||
5908 | |||
5909 | /** | ||
5910 | * Returns an object that contains a new `CancelToken` and a function that, when called, | ||
5911 | * cancels the `CancelToken`. | ||
5912 | */ | ||
5913 | CancelToken.source = function source() { | ||
5914 | var cancel; | ||
5915 | var token = new CancelToken(function executor(c) { | ||
5916 | cancel = c; | ||
5917 | }); | ||
5918 | return { | ||
5919 | token: token, | ||
5920 | cancel: cancel | ||
5921 | }; | ||
5922 | }; | ||
5923 | |||
5924 | module.exports = CancelToken; | ||
5925 | |||
5926 | },{"./Cancel":49}],51:[function(require,module,exports){ | ||
5927 | 'use strict'; | ||
5928 | |||
5929 | module.exports = function isCancel(value) { | ||
5930 | return !!(value && value.__CANCEL__); | ||
5931 | }; | ||
5932 | |||
5933 | },{}],52:[function(require,module,exports){ | ||
5934 | 'use strict'; | ||
5935 | |||
5936 | var defaults = require('./../defaults'); | ||
5937 | var utils = require('./../utils'); | ||
5938 | var InterceptorManager = require('./InterceptorManager'); | ||
5939 | var dispatchRequest = require('./dispatchRequest'); | ||
5940 | |||
5941 | /** | ||
5942 | * Create a new instance of Axios | ||
5943 | * | ||
5944 | * @param {Object} instanceConfig The default config for the instance | ||
5945 | */ | ||
5946 | function Axios(instanceConfig) { | ||
5947 | this.defaults = instanceConfig; | ||
5948 | this.interceptors = { | ||
5949 | request: new InterceptorManager(), | ||
5950 | response: new InterceptorManager() | ||
5951 | }; | ||
5952 | } | ||
5953 | |||
5954 | /** | ||
5955 | * Dispatch a request | ||
5956 | * | ||
5957 | * @param {Object} config The config specific for this request (merged with this.defaults) | ||
5958 | */ | ||
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({ | ||
5964 | url: arguments[0] | ||
5965 | }, arguments[1]); | ||
5966 | } | ||
5967 | |||
5968 | config = utils.merge(defaults, {method: 'get'}, this.defaults, config); | ||
5969 | config.method = config.method.toLowerCase(); | ||
5970 | |||
5971 | // Hook up interceptors middleware | ||
5972 | var chain = [dispatchRequest, undefined]; | ||
5973 | var promise = Promise.resolve(config); | ||
5974 | |||
5975 | this.interceptors.request.forEach(function unshiftRequestInterceptors(interceptor) { | ||
5976 | chain.unshift(interceptor.fulfilled, interceptor.rejected); | ||
5977 | }); | ||
5978 | |||
5979 | this.interceptors.response.forEach(function pushResponseInterceptors(interceptor) { | ||
5980 | chain.push(interceptor.fulfilled, interceptor.rejected); | ||
5981 | }); | ||
5982 | |||
5983 | while (chain.length) { | ||
5984 | promise = promise.then(chain.shift(), chain.shift()); | ||
5985 | } | ||
5986 | |||
5987 | return promise; | ||
5988 | }; | ||
5989 | |||
5990 | // Provide aliases for supported request methods | ||
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 || {}, { | ||
5995 | method: method, | ||
5996 | url: url | ||
5997 | })); | ||
5998 | }; | ||
5999 | }); | ||
6000 | |||
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 || {}, { | ||
6005 | method: method, | ||
6006 | url: url, | ||
6007 | data: data | ||
6008 | })); | ||
6009 | }; | ||
6010 | }); | ||
6011 | |||
6012 | module.exports = Axios; | ||
6013 | |||
6014 | },{"./../defaults":59,"./../utils":70,"./InterceptorManager":53,"./dispatchRequest":55}],53:[function(require,module,exports){ | ||
6015 | 'use strict'; | ||
6016 | |||
6017 | var utils = require('./../utils'); | ||
6018 | |||
6019 | function InterceptorManager() { | ||
6020 | this.handlers = []; | ||
6021 | } | ||
6022 | |||
6023 | /** | ||
6024 | * Add a new interceptor to the stack | ||
6025 | * | ||
6026 | * @param {Function} fulfilled The function to handle `then` for a `Promise` | ||
6027 | * @param {Function} rejected The function to handle `reject` for a `Promise` | ||
6028 | * | ||
6029 | * @return {Number} An ID used to remove interceptor later | ||
6030 | */ | ||
6031 | InterceptorManager.prototype.use = function use(fulfilled, rejected) { | ||
6032 | this.handlers.push({ | ||
6033 | fulfilled: fulfilled, | ||
6034 | rejected: rejected | ||
6035 | }); | ||
6036 | return this.handlers.length - 1; | ||
6037 | }; | ||
6038 | |||
6039 | /** | ||
6040 | * Remove an interceptor from the stack | ||
6041 | * | ||
6042 | * @param {Number} id The ID that was returned by `use` | ||
6043 | */ | ||
6044 | InterceptorManager.prototype.eject = function eject(id) { | ||
6045 | if (this.handlers[id]) { | ||
6046 | this.handlers[id] = null; | ||
6047 | } | ||
6048 | }; | ||
6049 | |||
6050 | /** | ||
6051 | * Iterate over all the registered interceptors | ||
6052 | * | ||
6053 | * This method is particularly useful for skipping over any | ||
6054 | * interceptors that may have become `null` calling `eject`. | ||
6055 | * | ||
6056 | * @param {Function} fn The function to call for each interceptor | ||
6057 | */ | ||
6058 | InterceptorManager.prototype.forEach = function forEach(fn) { | ||
6059 | utils.forEach(this.handlers, function forEachHandler(h) { | ||
6060 | if (h !== null) { | ||
6061 | fn(h); | ||
6062 | } | ||
6063 | }); | ||
6064 | }; | ||
6065 | |||
6066 | module.exports = InterceptorManager; | ||
6067 | |||
6068 | },{"./../utils":70}],54:[function(require,module,exports){ | ||
6069 | 'use strict'; | ||
6070 | |||
6071 | var enhanceError = require('./enhanceError'); | ||
6072 | |||
6073 | /** | ||
6074 | * Create an Error with the specified message, config, error code, request and response. | ||
6075 | * | ||
6076 | * @param {string} message The error message. | ||
6077 | * @param {Object} config The config. | ||
6078 | * @param {string} [code] The error code (for example, 'ECONNABORTED'). | ||
6079 | * @param {Object} [request] The request. | ||
6080 | * @param {Object} [response] The response. | ||
6081 | * @returns {Error} The created error. | ||
6082 | */ | ||
6083 | module.exports = function createError(message, config, code, request, response) { | ||
6084 | var error = new Error(message); | ||
6085 | return enhanceError(error, config, code, request, response); | ||
6086 | }; | ||
6087 | |||
6088 | },{"./enhanceError":56}],55:[function(require,module,exports){ | ||
6089 | 'use strict'; | ||
6090 | |||
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'); | ||
6097 | |||
6098 | /** | ||
6099 | * Throws a `Cancel` if cancellation has been requested. | ||
6100 | */ | ||
6101 | function throwIfCancellationRequested(config) { | ||
6102 | if (config.cancelToken) { | ||
6103 | config.cancelToken.throwIfRequested(); | ||
6104 | } | ||
6105 | } | ||
6106 | |||
6107 | /** | ||
6108 | * Dispatch a request to the server using the configured adapter. | ||
6109 | * | ||
6110 | * @param {object} config The config that is to be used for the request | ||
6111 | * @returns {Promise} The Promise to be fulfilled | ||
6112 | */ | ||
6113 | module.exports = function dispatchRequest(config) { | ||
6114 | throwIfCancellationRequested(config); | ||
6115 | |||
6116 | // Support baseURL config | ||
6117 | if (config.baseURL && !isAbsoluteURL(config.url)) { | ||
6118 | config.url = combineURLs(config.baseURL, config.url); | ||
6119 | } | ||
6120 | |||
6121 | // Ensure headers exist | ||
6122 | config.headers = config.headers || {}; | ||
6123 | |||
6124 | // Transform request data | ||
6125 | config.data = transformData( | ||
6126 | config.data, | ||
6127 | config.headers, | ||
6128 | config.transformRequest | ||
6129 | ); | ||
6130 | |||
6131 | // Flatten headers | ||
6132 | config.headers = utils.merge( | ||
6133 | config.headers.common || {}, | ||
6134 | config.headers[config.method] || {}, | ||
6135 | config.headers || {} | ||
6136 | ); | ||
6137 | |||
6138 | utils.forEach( | ||
6139 | ['delete', 'get', 'head', 'post', 'put', 'patch', 'common'], | ||
6140 | function cleanHeaderConfig(method) { | ||
6141 | delete config.headers[method]; | ||
6142 | } | ||
6143 | ); | ||
6144 | |||
6145 | var adapter = config.adapter || defaults.adapter; | ||
6146 | |||
6147 | return adapter(config).then(function onAdapterResolution(response) { | ||
6148 | throwIfCancellationRequested(config); | ||
6149 | |||
6150 | // Transform response data | ||
6151 | response.data = transformData( | ||
6152 | response.data, | ||
6153 | response.headers, | ||
6154 | config.transformResponse | ||
6155 | ); | ||
6156 | |||
6157 | return response; | ||
6158 | }, function onAdapterRejection(reason) { | ||
6159 | if (!isCancel(reason)) { | ||
6160 | throwIfCancellationRequested(config); | ||
6161 | |||
6162 | // Transform response data | ||
6163 | if (reason && reason.response) { | ||
6164 | reason.response.data = transformData( | ||
6165 | reason.response.data, | ||
6166 | reason.response.headers, | ||
6167 | config.transformResponse | ||
6168 | ); | ||
6169 | } | ||
6170 | } | ||
6171 | |||
6172 | return Promise.reject(reason); | ||
6173 | }); | ||
6174 | }; | ||
6175 | |||
6176 | },{"../cancel/isCancel":51,"../defaults":59,"./../helpers/combineURLs":63,"./../helpers/isAbsoluteURL":65,"./../utils":70,"./transformData":58}],56:[function(require,module,exports){ | ||
6177 | 'use strict'; | ||
6178 | |||
6179 | /** | ||
6180 | * Update an Error with the specified config, error code, and response. | ||
6181 | * | ||
6182 | * @param {Error} error The error to update. | ||
6183 | * @param {Object} config The config. | ||
6184 | * @param {string} [code] The error code (for example, 'ECONNABORTED'). | ||
6185 | * @param {Object} [request] The request. | ||
6186 | * @param {Object} [response] The response. | ||
6187 | * @returns {Error} The error. | ||
6188 | */ | ||
6189 | module.exports = function enhanceError(error, config, code, request, response) { | ||
6190 | error.config = config; | ||
6191 | if (code) { | ||
6192 | error.code = code; | ||
6193 | } | ||
6194 | error.request = request; | ||
6195 | error.response = response; | ||
6196 | return error; | ||
6197 | }; | ||
6198 | |||
6199 | },{}],57:[function(require,module,exports){ | ||
6200 | 'use strict'; | ||
6201 | |||
6202 | var createError = require('./createError'); | ||
6203 | |||
6204 | /** | ||
6205 | * Resolve or reject a Promise based on response status. | ||
6206 | * | ||
6207 | * @param {Function} resolve A function that resolves the promise. | ||
6208 | * @param {Function} reject A function that rejects the promise. | ||
6209 | * @param {object} response The response. | ||
6210 | */ | ||
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)) { | ||
6215 | resolve(response); | ||
6216 | } else { | ||
6217 | reject(createError( | ||
6218 | 'Request failed with status code ' + response.status, | ||
6219 | response.config, | ||
6220 | null, | ||
6221 | response.request, | ||
6222 | response | ||
6223 | )); | ||
6224 | } | ||
6225 | }; | ||
6226 | |||
6227 | },{"./createError":54}],58:[function(require,module,exports){ | ||
6228 | 'use strict'; | ||
6229 | |||
6230 | var utils = require('./../utils'); | ||
6231 | |||
6232 | /** | ||
6233 | * Transform the data for a request or a response | ||
6234 | * | ||
6235 | * @param {Object|String} data The data to be transformed | ||
6236 | * @param {Array} headers The headers for the request or response | ||
6237 | * @param {Array|Function} fns A single function or Array of functions | ||
6238 | * @returns {*} The resulting transformed data | ||
6239 | */ | ||
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); | ||
6244 | }); | ||
6245 | |||
6246 | return data; | ||
6247 | }; | ||
6248 | |||
6249 | },{"./../utils":70}],59:[function(require,module,exports){ | ||
6250 | (function (process){ | ||
6251 | 'use strict'; | ||
6252 | |||
6253 | var utils = require('./utils'); | ||
6254 | var normalizeHeaderName = require('./helpers/normalizeHeaderName'); | ||
6255 | |||
6256 | var DEFAULT_CONTENT_TYPE = { | ||
6257 | 'Content-Type': 'application/x-www-form-urlencoded' | ||
6258 | }; | ||
6259 | |||
6260 | function setContentTypeIfUnset(headers, value) { | ||
6261 | if (!utils.isUndefined(headers) && utils.isUndefined(headers['Content-Type'])) { | ||
6262 | headers['Content-Type'] = value; | ||
6263 | } | ||
6264 | } | ||
6265 | |||
6266 | function getDefaultAdapter() { | ||
6267 | var adapter; | ||
6268 | if (typeof XMLHttpRequest !== 'undefined') { | ||
6269 | // For browsers use XHR adapter | ||
6270 | adapter = require('./adapters/xhr'); | ||
6271 | } else if (typeof process !== 'undefined') { | ||
6272 | // For node use HTTP adapter | ||
6273 | adapter = require('./adapters/http'); | ||
6274 | } | ||
6275 | return adapter; | ||
6276 | } | ||
6277 | |||
6278 | var defaults = { | ||
6279 | adapter: getDefaultAdapter(), | ||
6280 | |||
6281 | transformRequest: [function transformRequest(data, headers) { | ||
6282 | normalizeHeaderName(headers, 'Content-Type'); | ||
6283 | if (utils.isFormData(data) || | ||
6284 | utils.isArrayBuffer(data) || | ||
6285 | utils.isBuffer(data) || | ||
6286 | utils.isStream(data) || | ||
6287 | utils.isFile(data) || | ||
6288 | utils.isBlob(data) | ||
6289 | ) { | ||
6290 | return data; | ||
6291 | } | ||
6292 | if (utils.isArrayBufferView(data)) { | ||
6293 | return data.buffer; | ||
6294 | } | ||
6295 | if (utils.isURLSearchParams(data)) { | ||
6296 | setContentTypeIfUnset(headers, 'application/x-www-form-urlencoded;charset=utf-8'); | ||
6297 | return data.toString(); | ||
6298 | } | ||
6299 | if (utils.isObject(data)) { | ||
6300 | setContentTypeIfUnset(headers, 'application/json;charset=utf-8'); | ||
6301 | return JSON.stringify(data); | ||
6302 | } | ||
6303 | return data; | ||
6304 | }], | ||
6305 | |||
6306 | transformResponse: [function transformResponse(data) { | ||
6307 | /*eslint no-param-reassign:0*/ | ||
6308 | if (typeof data === 'string') { | ||
6309 | try { | ||
6310 | data = JSON.parse(data); | ||
6311 | } catch (e) { /* Ignore */ } | ||
6312 | } | ||
6313 | return data; | ||
6314 | }], | ||
6315 | |||
6316 | /** | ||
6317 | * A timeout in milliseconds to abort a request. If set to 0 (default) a | ||
6318 | * timeout is not created. | ||
6319 | */ | ||
6320 | timeout: 0, | ||
6321 | |||
6322 | xsrfCookieName: 'XSRF-TOKEN', | ||
6323 | xsrfHeaderName: 'X-XSRF-TOKEN', | ||
6324 | |||
6325 | maxContentLength: -1, | ||
6326 | |||
6327 | validateStatus: function validateStatus(status) { | ||
6328 | return status >= 200 && status < 300; | ||
6329 | } | ||
6330 | }; | ||
6331 | |||
6332 | defaults.headers = { | ||
6333 | common: { | ||
6334 | 'Accept': 'application/json, text/plain, */*' | ||
6335 | } | ||
6336 | }; | ||
6337 | |||
6338 | utils.forEach(['delete', 'get', 'head'], function forEachMethodNoData(method) { | ||
6339 | defaults.headers[method] = {}; | ||
6340 | }); | ||
6341 | |||
6342 | utils.forEach(['post', 'put', 'patch'], function forEachMethodWithData(method) { | ||
6343 | defaults.headers[method] = utils.merge(DEFAULT_CONTENT_TYPE); | ||
6344 | }); | ||
6345 | |||
6346 | module.exports = defaults; | ||
6347 | |||
6348 | }).call(this,require('_process')) | ||
6349 | },{"./adapters/http":47,"./adapters/xhr":47,"./helpers/normalizeHeaderName":67,"./utils":70,"_process":190}],60:[function(require,module,exports){ | ||
6350 | 'use strict'; | ||
6351 | |||
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]; | ||
6357 | } | ||
6358 | return fn.apply(thisArg, args); | ||
6359 | }; | ||
6360 | }; | ||
6361 | |||
6362 | },{}],61:[function(require,module,exports){ | ||
6363 | 'use strict'; | ||
6364 | |||
6365 | // btoa polyfill for IE<10 courtesy https://github.com/davidchambers/Base64.js | ||
6366 | |||
6367 | var chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='; | ||
6368 | |||
6369 | function E() { | ||
6370 | this.message = 'String contains an invalid character'; | ||
6371 | } | ||
6372 | E.prototype = new Error; | ||
6373 | E.prototype.code = 5; | ||
6374 | E.prototype.name = 'InvalidCharacterError'; | ||
6375 | |||
6376 | function btoa(input) { | ||
6377 | var str = String(input); | ||
6378 | var output = ''; | ||
6379 | for ( | ||
6380 | // initialize result and counter | ||
6381 | var block, charCode, idx = 0, map = chars; | ||
6382 | // if the next str index does not exist: | ||
6383 | // change the mapping table to "=" | ||
6384 | // check if d has no fractional digits | ||
6385 | str.charAt(idx | 0) || (map = '=', idx % 1); | ||
6386 | // "8 - idx % 1 * 8" generates the sequence 2, 4, 6, 8 | ||
6387 | output += map.charAt(63 & block >> 8 - idx % 1 * 8) | ||
6388 | ) { | ||
6389 | charCode = str.charCodeAt(idx += 3 / 4); | ||
6390 | if (charCode > 0xFF) { | ||
6391 | throw new E(); | ||
6392 | } | ||
6393 | block = block << 8 | charCode; | ||
6394 | } | ||
6395 | return output; | ||
6396 | } | ||
6397 | |||
6398 | module.exports = btoa; | ||
6399 | |||
6400 | },{}],62:[function(require,module,exports){ | ||
6401 | 'use strict'; | ||
6402 | |||
6403 | var utils = require('./../utils'); | ||
6404 | |||
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, ']'); | ||
6414 | } | ||
6415 | |||
6416 | /** | ||
6417 | * Build a URL by appending params to the end | ||
6418 | * | ||
6419 | * @param {string} url The base of the url (e.g., http://www.google.com) | ||
6420 | * @param {object} [params] The params to be appended | ||
6421 | * @returns {string} The formatted url | ||
6422 | */ | ||
6423 | module.exports = function buildURL(url, params, paramsSerializer) { | ||
6424 | /*eslint no-param-reassign:0*/ | ||
6425 | if (!params) { | ||
6426 | return url; | ||
6427 | } | ||
6428 | |||
6429 | var serializedParams; | ||
6430 | if (paramsSerializer) { | ||
6431 | serializedParams = paramsSerializer(params); | ||
6432 | } else if (utils.isURLSearchParams(params)) { | ||
6433 | serializedParams = params.toString(); | ||
6434 | } else { | ||
6435 | var parts = []; | ||
6436 | |||
6437 | utils.forEach(params, function serialize(val, key) { | ||
6438 | if (val === null || typeof val === 'undefined') { | ||
6439 | return; | ||
6440 | } | ||
6441 | |||
6442 | if (utils.isArray(val)) { | ||
6443 | key = key + '[]'; | ||
6444 | } else { | ||
6445 | val = [val]; | ||
6446 | } | ||
6447 | |||
6448 | utils.forEach(val, function parseValue(v) { | ||
6449 | if (utils.isDate(v)) { | ||
6450 | v = v.toISOString(); | ||
6451 | } else if (utils.isObject(v)) { | ||
6452 | v = JSON.stringify(v); | ||
6453 | } | ||
6454 | parts.push(encode(key) + '=' + encode(v)); | ||
6455 | }); | ||
6456 | }); | ||
6457 | |||
6458 | serializedParams = parts.join('&'); | ||
6459 | } | ||
6460 | |||
6461 | if (serializedParams) { | ||
6462 | url += (url.indexOf('?') === -1 ? '?' : '&') + serializedParams; | ||
6463 | } | ||
6464 | |||
6465 | return url; | ||
6466 | }; | ||
6467 | |||
6468 | },{"./../utils":70}],63:[function(require,module,exports){ | ||
6469 | 'use strict'; | ||
6470 | |||
6471 | /** | ||
6472 | * Creates a new URL by combining the specified URLs | ||
6473 | * | ||
6474 | * @param {string} baseURL The base URL | ||
6475 | * @param {string} relativeURL The relative URL | ||
6476 | * @returns {string} The combined URL | ||
6477 | */ | ||
6478 | module.exports = function combineURLs(baseURL, relativeURL) { | ||
6479 | return relativeURL | ||
6480 | ? baseURL.replace(/\/+$/, '') + '/' + relativeURL.replace(/^\/+/, '') | ||
6481 | : baseURL; | ||
6482 | }; | ||
6483 | |||
6484 | },{}],64:[function(require,module,exports){ | ||
6485 | 'use strict'; | ||
6486 | |||
6487 | var utils = require('./../utils'); | ||
6488 | |||
6489 | module.exports = ( | ||
6490 | utils.isStandardBrowserEnv() ? | ||
6491 | |||
6492 | // Standard browser envs support document.cookie | ||
6493 | (function standardBrowserEnv() { | ||
6494 | return { | ||
6495 | write: function write(name, value, expires, path, domain, secure) { | ||
6496 | var cookie = []; | ||
6497 | cookie.push(name + '=' + encodeURIComponent(value)); | ||
6498 | |||
6499 | if (utils.isNumber(expires)) { | ||
6500 | cookie.push('expires=' + new Date(expires).toGMTString()); | ||
6501 | } | ||
6502 | |||
6503 | if (utils.isString(path)) { | ||
6504 | cookie.push('path=' + path); | ||
6505 | } | ||
6506 | |||
6507 | if (utils.isString(domain)) { | ||
6508 | cookie.push('domain=' + domain); | ||
6509 | } | ||
6510 | |||
6511 | if (secure === true) { | ||
6512 | cookie.push('secure'); | ||
6513 | } | ||
6514 | |||
6515 | document.cookie = cookie.join('; '); | ||
6516 | }, | ||
6517 | |||
6518 | read: function read(name) { | ||
6519 | var match = document.cookie.match(new RegExp('(^|;\\s*)(' + name + ')=([^;]*)')); | ||
6520 | return (match ? decodeURIComponent(match[3]) : null); | ||
6521 | }, | ||
6522 | |||
6523 | remove: function remove(name) { | ||
6524 | this.write(name, '', Date.now() - 86400000); | ||
6525 | } | ||
6526 | }; | ||
6527 | })() : | ||
6528 | |||
6529 | // Non standard browser env (web workers, react-native) lack needed support. | ||
6530 | (function nonStandardBrowserEnv() { | ||
6531 | return { | ||
6532 | write: function write() {}, | ||
6533 | read: function read() { return null; }, | ||
6534 | remove: function remove() {} | ||
6535 | }; | ||
6536 | })() | ||
6537 | ); | ||
6538 | |||
6539 | },{"./../utils":70}],65:[function(require,module,exports){ | ||
6540 | 'use strict'; | ||
6541 | |||
6542 | /** | ||
6543 | * Determines whether the specified URL is absolute | ||
6544 | * | ||
6545 | * @param {string} url The URL to test | ||
6546 | * @returns {boolean} True if the specified URL is absolute, otherwise false | ||
6547 | */ | ||
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); | ||
6553 | }; | ||
6554 | |||
6555 | },{}],66:[function(require,module,exports){ | ||
6556 | 'use strict'; | ||
6557 | |||
6558 | var utils = require('./../utils'); | ||
6559 | |||
6560 | module.exports = ( | ||
6561 | utils.isStandardBrowserEnv() ? | ||
6562 | |||
6563 | // Standard browser envs have full support of the APIs needed to test | ||
6564 | // whether the request URL is of the same origin as current location. | ||
6565 | (function standardBrowserEnv() { | ||
6566 | var msie = /(msie|trident)/i.test(navigator.userAgent); | ||
6567 | var urlParsingNode = document.createElement('a'); | ||
6568 | var originURL; | ||
6569 | |||
6570 | /** | ||
6571 | * Parse a URL to discover it's components | ||
6572 | * | ||
6573 | * @param {String} url The URL to be parsed | ||
6574 | * @returns {Object} | ||
6575 | */ | ||
6576 | function resolveURL(url) { | ||
6577 | var href = url; | ||
6578 | |||
6579 | if (msie) { | ||
6580 | // IE needs attribute set twice to normalize properties | ||
6581 | urlParsingNode.setAttribute('href', href); | ||
6582 | href = urlParsingNode.href; | ||
6583 | } | ||
6584 | |||
6585 | urlParsingNode.setAttribute('href', href); | ||
6586 | |||
6587 | // urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils | ||
6588 | return { | ||
6589 | href: urlParsingNode.href, | ||
6590 | protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '', | ||
6591 | host: urlParsingNode.host, | ||
6592 | search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '', | ||
6593 | hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '', | ||
6594 | hostname: urlParsingNode.hostname, | ||
6595 | port: urlParsingNode.port, | ||
6596 | pathname: (urlParsingNode.pathname.charAt(0) === '/') ? | ||
6597 | urlParsingNode.pathname : | ||
6598 | '/' + urlParsingNode.pathname | ||
6599 | }; | ||
6600 | } | ||
6601 | |||
6602 | originURL = resolveURL(window.location.href); | ||
6603 | |||
6604 | /** | ||
6605 | * Determine if a URL shares the same origin as the current location | ||
6606 | * | ||
6607 | * @param {String} requestURL The URL to test | ||
6608 | * @returns {boolean} True if URL shares the same origin, otherwise false | ||
6609 | */ | ||
6610 | return function isURLSameOrigin(requestURL) { | ||
6611 | var parsed = (utils.isString(requestURL)) ? resolveURL(requestURL) : requestURL; | ||
6612 | return (parsed.protocol === originURL.protocol && | ||
6613 | parsed.host === originURL.host); | ||
6614 | }; | ||
6615 | })() : | ||
6616 | |||
6617 | // Non standard browser envs (web workers, react-native) lack needed support. | ||
6618 | (function nonStandardBrowserEnv() { | ||
6619 | return function isURLSameOrigin() { | ||
6620 | return true; | ||
6621 | }; | ||
6622 | })() | ||
6623 | ); | ||
6624 | |||
6625 | },{"./../utils":70}],67:[function(require,module,exports){ | ||
6626 | 'use strict'; | ||
6627 | |||
6628 | var utils = require('../utils'); | ||
6629 | |||
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]; | ||
6635 | } | ||
6636 | }); | ||
6637 | }; | ||
6638 | |||
6639 | },{"../utils":70}],68:[function(require,module,exports){ | ||
6640 | 'use strict'; | ||
6641 | |||
6642 | var utils = require('./../utils'); | ||
6643 | |||
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' | ||
6651 | ]; | ||
6652 | |||
6653 | /** | ||
6654 | * Parse headers into an object | ||
6655 | * | ||
6656 | * ``` | ||
6657 | * Date: Wed, 27 Aug 2014 08:58:49 GMT | ||
6658 | * Content-Type: application/json | ||
6659 | * Connection: keep-alive | ||
6660 | * Transfer-Encoding: chunked | ||
6661 | * ``` | ||
6662 | * | ||
6663 | * @param {String} headers Headers needing to be parsed | ||
6664 | * @returns {Object} Headers parsed into an object | ||
6665 | */ | ||
6666 | module.exports = function parseHeaders(headers) { | ||
6667 | var parsed = {}; | ||
6668 | var key; | ||
6669 | var val; | ||
6670 | var i; | ||
6671 | |||
6672 | if (!headers) { return parsed; } | ||
6673 | |||
6674 | utils.forEach(headers.split('\n'), function parser(line) { | ||
6675 | i = line.indexOf(':'); | ||
6676 | key = utils.trim(line.substr(0, i)).toLowerCase(); | ||
6677 | val = utils.trim(line.substr(i + 1)); | ||
6678 | |||
6679 | if (key) { | ||
6680 | if (parsed[key] && ignoreDuplicateOf.indexOf(key) >= 0) { | ||
6681 | return; | ||
6682 | } | ||
6683 | if (key === 'set-cookie') { | ||
6684 | parsed[key] = (parsed[key] ? parsed[key] : []).concat([val]); | ||
6685 | } else { | ||
6686 | parsed[key] = parsed[key] ? parsed[key] + ', ' + val : val; | ||
6687 | } | ||
6688 | } | ||
6689 | }); | ||
6690 | |||
6691 | return parsed; | ||
6692 | }; | ||
6693 | |||
6694 | },{"./../utils":70}],69:[function(require,module,exports){ | ||
6695 | 'use strict'; | ||
6696 | |||
6697 | /** | ||
6698 | * Syntactic sugar for invoking a function and expanding an array for arguments. | ||
6699 | * | ||
6700 | * Common use case would be to use `Function.prototype.apply`. | ||
6701 | * | ||
6702 | * ```js | ||
6703 | * function f(x, y, z) {} | ||
6704 | * var args = [1, 2, 3]; | ||
6705 | * f.apply(null, args); | ||
6706 | * ``` | ||
6707 | * | ||
6708 | * With `spread` this example can be re-written. | ||
6709 | * | ||
6710 | * ```js | ||
6711 | * spread(function(x, y, z) {})([1, 2, 3]); | ||
6712 | * ``` | ||
6713 | * | ||
6714 | * @param {Function} callback | ||
6715 | * @returns {Function} | ||
6716 | */ | ||
6717 | module.exports = function spread(callback) { | ||
6718 | return function wrap(arr) { | ||
6719 | return callback.apply(null, arr); | ||
6720 | }; | ||
6721 | }; | ||
6722 | |||
6723 | },{}],70:[function(require,module,exports){ | ||
6724 | 'use strict'; | ||
6725 | |||
6726 | var bind = require('./helpers/bind'); | ||
6727 | var isBuffer = require('is-buffer'); | ||
6728 | |||
6729 | /*global toString:true*/ | ||
6730 | |||
6731 | // utils is a library of generic helper functions non-specific to axios | ||
6732 | |||
6733 | var toString = Object.prototype.toString; | ||
6734 | |||
6735 | /** | ||
6736 | * Determine if a value is an Array | ||
6737 | * | ||
6738 | * @param {Object} val The value to test | ||
6739 | * @returns {boolean} True if value is an Array, otherwise false | ||
6740 | */ | ||
6741 | function isArray(val) { | ||
6742 | return toString.call(val) === '[object Array]'; | ||
6743 | } | ||
6744 | |||
6745 | /** | ||
6746 | * Determine if a value is an ArrayBuffer | ||
6747 | * | ||
6748 | * @param {Object} val The value to test | ||
6749 | * @returns {boolean} True if value is an ArrayBuffer, otherwise false | ||
6750 | */ | ||
6751 | function isArrayBuffer(val) { | ||
6752 | return toString.call(val) === '[object ArrayBuffer]'; | ||
6753 | } | ||
6754 | |||
6755 | /** | ||
6756 | * Determine if a value is a FormData | ||
6757 | * | ||
6758 | * @param {Object} val The value to test | ||
6759 | * @returns {boolean} True if value is an FormData, otherwise false | ||
6760 | */ | ||
6761 | function isFormData(val) { | ||
6762 | return (typeof FormData !== 'undefined') && (val instanceof FormData); | ||
6763 | } | ||
6764 | |||
6765 | /** | ||
6766 | * Determine if a value is a view on an ArrayBuffer | ||
6767 | * | ||
6768 | * @param {Object} val The value to test | ||
6769 | * @returns {boolean} True if value is a view on an ArrayBuffer, otherwise false | ||
6770 | */ | ||
6771 | function isArrayBufferView(val) { | ||
6772 | var result; | ||
6773 | if ((typeof ArrayBuffer !== 'undefined') && (ArrayBuffer.isView)) { | ||
6774 | result = ArrayBuffer.isView(val); | ||
6775 | } else { | ||
6776 | result = (val) && (val.buffer) && (val.buffer instanceof ArrayBuffer); | ||
6777 | } | ||
6778 | return result; | ||
6779 | } | ||
6780 | |||
6781 | /** | ||
6782 | * Determine if a value is a String | ||
6783 | * | ||
6784 | * @param {Object} val The value to test | ||
6785 | * @returns {boolean} True if value is a String, otherwise false | ||
6786 | */ | ||
6787 | function isString(val) { | ||
6788 | return typeof val === 'string'; | ||
6789 | } | ||
6790 | |||
6791 | /** | ||
6792 | * Determine if a value is a Number | ||
6793 | * | ||
6794 | * @param {Object} val The value to test | ||
6795 | * @returns {boolean} True if value is a Number, otherwise false | ||
6796 | */ | ||
6797 | function isNumber(val) { | ||
6798 | return typeof val === 'number'; | ||
6799 | } | ||
6800 | |||
6801 | /** | ||
6802 | * Determine if a value is undefined | ||
6803 | * | ||
6804 | * @param {Object} val The value to test | ||
6805 | * @returns {boolean} True if the value is undefined, otherwise false | ||
6806 | */ | ||
6807 | function isUndefined(val) { | ||
6808 | return typeof val === 'undefined'; | ||
6809 | } | ||
6810 | |||
6811 | /** | ||
6812 | * Determine if a value is an Object | ||
6813 | * | ||
6814 | * @param {Object} val The value to test | ||
6815 | * @returns {boolean} True if value is an Object, otherwise false | ||
6816 | */ | ||
6817 | function isObject(val) { | ||
6818 | return val !== null && typeof val === 'object'; | ||
6819 | } | ||
6820 | |||
6821 | /** | ||
6822 | * Determine if a value is a Date | ||
6823 | * | ||
6824 | * @param {Object} val The value to test | ||
6825 | * @returns {boolean} True if value is a Date, otherwise false | ||
6826 | */ | ||
6827 | function isDate(val) { | ||
6828 | return toString.call(val) === '[object Date]'; | ||
6829 | } | ||
6830 | |||
6831 | /** | ||
6832 | * Determine if a value is a File | ||
6833 | * | ||
6834 | * @param {Object} val The value to test | ||
6835 | * @returns {boolean} True if value is a File, otherwise false | ||
6836 | */ | ||
6837 | function isFile(val) { | ||
6838 | return toString.call(val) === '[object File]'; | ||
6839 | } | ||
6840 | |||
6841 | /** | ||
6842 | * Determine if a value is a Blob | ||
6843 | * | ||
6844 | * @param {Object} val The value to test | ||
6845 | * @returns {boolean} True if value is a Blob, otherwise false | ||
6846 | */ | ||
6847 | function isBlob(val) { | ||
6848 | return toString.call(val) === '[object Blob]'; | ||
6849 | } | ||
6850 | |||
6851 | /** | ||
6852 | * Determine if a value is a Function | ||
6853 | * | ||
6854 | * @param {Object} val The value to test | ||
6855 | * @returns {boolean} True if value is a Function, otherwise false | ||
6856 | */ | ||
6857 | function isFunction(val) { | ||
6858 | return toString.call(val) === '[object Function]'; | ||
6859 | } | ||
6860 | |||
6861 | /** | ||
6862 | * Determine if a value is a Stream | ||
6863 | * | ||
6864 | * @param {Object} val The value to test | ||
6865 | * @returns {boolean} True if value is a Stream, otherwise false | ||
6866 | */ | ||
6867 | function isStream(val) { | ||
6868 | return isObject(val) && isFunction(val.pipe); | ||
6869 | } | ||
6870 | |||
6871 | /** | ||
6872 | * Determine if a value is a URLSearchParams object | ||
6873 | * | ||
6874 | * @param {Object} val The value to test | ||
6875 | * @returns {boolean} True if value is a URLSearchParams object, otherwise false | ||
6876 | */ | ||
6877 | function isURLSearchParams(val) { | ||
6878 | return typeof URLSearchParams !== 'undefined' && val instanceof URLSearchParams; | ||
6879 | } | ||
6880 | |||
6881 | /** | ||
6882 | * Trim excess whitespace off the beginning and end of a string | ||
6883 | * | ||
6884 | * @param {String} str The String to trim | ||
6885 | * @returns {String} The String freed of excess whitespace | ||
6886 | */ | ||
6887 | function trim(str) { | ||
6888 | return str.replace(/^\s*/, '').replace(/\s*$/, ''); | ||
6889 | } | ||
6890 | |||
6891 | /** | ||
6892 | * Determine if we're running in a standard browser environment | ||
6893 | * | ||
6894 | * This allows axios to run in a web worker, and react-native. | ||
6895 | * Both environments support XMLHttpRequest, but not fully standard globals. | ||
6896 | * | ||
6897 | * web workers: | ||
6898 | * typeof window -> undefined | ||
6899 | * typeof document -> undefined | ||
6900 | * | ||
6901 | * react-native: | ||
6902 | * navigator.product -> 'ReactNative' | ||
6903 | */ | ||
6904 | function isStandardBrowserEnv() { | ||
6905 | if (typeof navigator !== 'undefined' && navigator.product === 'ReactNative') { | ||
6906 | return false; | ||
6907 | } | ||
6908 | return ( | ||
6909 | typeof window !== 'undefined' && | ||
6910 | typeof document !== 'undefined' | ||
6911 | ); | ||
6912 | } | ||
6913 | |||
6914 | /** | ||
6915 | * Iterate over an Array or an Object invoking a function for each item. | ||
6916 | * | ||
6917 | * If `obj` is an Array callback will be called passing | ||
6918 | * the value, index, and complete array for each item. | ||
6919 | * | ||
6920 | * If 'obj' is an Object callback will be called passing | ||
6921 | * the value, key, and complete object for each property. | ||
6922 | * | ||
6923 | * @param {Object|Array} obj The object to iterate | ||
6924 | * @param {Function} fn The callback to invoke for each item | ||
6925 | */ | ||
6926 | function forEach(obj, fn) { | ||
6927 | // Don't bother if no value provided | ||
6928 | if (obj === null || typeof obj === 'undefined') { | ||
6929 | return; | ||
6930 | } | ||
6931 | |||
6932 | // Force an array if not already something iterable | ||
6933 | if (typeof obj !== 'object') { | ||
6934 | /*eslint no-param-reassign:0*/ | ||
6935 | obj = [obj]; | ||
6936 | } | ||
6937 | |||
6938 | if (isArray(obj)) { | ||
6939 | // Iterate over array values | ||
6940 | for (var i = 0, l = obj.length; i < l; i++) { | ||
6941 | fn.call(null, obj[i], i, obj); | ||
6942 | } | ||
6943 | } else { | ||
6944 | // Iterate over object keys | ||
6945 | for (var key in obj) { | ||
6946 | if (Object.prototype.hasOwnProperty.call(obj, key)) { | ||
6947 | fn.call(null, obj[key], key, obj); | ||
6948 | } | ||
6949 | } | ||
6950 | } | ||
6951 | } | ||
6952 | |||
6953 | /** | ||
6954 | * Accepts varargs expecting each argument to be an object, then | ||
6955 | * immutably merges the properties of each object and returns result. | ||
6956 | * | ||
6957 | * When multiple objects contain the same key the later object in | ||
6958 | * the arguments list will take precedence. | ||
6959 | * | ||
6960 | * Example: | ||
6961 | * | ||
6962 | * ```js | ||
6963 | * var result = merge({foo: 123}, {foo: 456}); | ||
6964 | * console.log(result.foo); // outputs 456 | ||
6965 | * ``` | ||
6966 | * | ||
6967 | * @param {Object} obj1 Object to merge | ||
6968 | * @returns {Object} Result of all merge properties | ||
6969 | */ | ||
6970 | function merge(/* obj1, obj2, obj3, ... */) { | ||
6971 | var result = {}; | ||
6972 | function assignValue(val, key) { | ||
6973 | if (typeof result[key] === 'object' && typeof val === 'object') { | ||
6974 | result[key] = merge(result[key], val); | ||
6975 | } else { | ||
6976 | result[key] = val; | ||
6977 | } | ||
6978 | } | ||
6979 | |||
6980 | for (var i = 0, l = arguments.length; i < l; i++) { | ||
6981 | forEach(arguments[i], assignValue); | ||
6982 | } | ||
6983 | return result; | ||
6984 | } | ||
6985 | |||
6986 | /** | ||
6987 | * Extends object a by mutably adding to it the properties of object b. | ||
6988 | * | ||
6989 | * @param {Object} a The object to be extended | ||
6990 | * @param {Object} b The object to copy properties from | ||
6991 | * @param {Object} thisArg The object to bind function to | ||
6992 | * @return {Object} The resulting value of object a | ||
6993 | */ | ||
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); | ||
6998 | } else { | ||
6999 | a[key] = val; | ||
7000 | } | ||
7001 | }); | ||
7002 | return a; | ||
7003 | } | ||
7004 | |||
7005 | module.exports = { | ||
7006 | isArray: isArray, | ||
7007 | isArrayBuffer: isArrayBuffer, | ||
7008 | isBuffer: isBuffer, | ||
7009 | isFormData: isFormData, | ||
7010 | isArrayBufferView: isArrayBufferView, | ||
7011 | isString: isString, | ||
7012 | isNumber: isNumber, | ||
7013 | isObject: isObject, | ||
7014 | isUndefined: isUndefined, | ||
7015 | isDate: isDate, | ||
7016 | isFile: isFile, | ||
7017 | isBlob: isBlob, | ||
7018 | isFunction: isFunction, | ||
7019 | isStream: isStream, | ||
7020 | isURLSearchParams: isURLSearchParams, | ||
7021 | isStandardBrowserEnv: isStandardBrowserEnv, | ||
7022 | forEach: forEach, | ||
7023 | merge: merge, | ||
7024 | extend: extend, | ||
7025 | trim: trim | ||
7026 | }; | ||
7027 | |||
7028 | },{"./helpers/bind":60,"is-buffer":164}],71:[function(require,module,exports){ | ||
7029 | // base-x encoding | ||
7030 | // Forked from https://github.com/cryptocoinjs/bs58 | ||
7031 | // Originally written by Mike Hearn for BitcoinJ | ||
7032 | // Copyright (c) 2011 Google Inc | ||
7033 | // Ported to JavaScript by Stefan Thomas | ||
7034 | // Merged Buffer refactorings from base58-native by Stephen Pair | ||
7035 | // Copyright (c) 2013 BitPay Inc | ||
7036 | |||
7037 | var Buffer = require('safe-buffer').Buffer | ||
7038 | |||
7039 | module.exports = function base (ALPHABET) { | ||
7040 | var ALPHABET_MAP = {} | ||
7041 | var BASE = ALPHABET.length | ||
7042 | var LEADER = ALPHABET.charAt(0) | ||
7043 | |||
7044 | // pre-compute lookup table | ||
7045 | for (var z = 0; z < ALPHABET.length; z++) { | ||
7046 | var x = ALPHABET.charAt(z) | ||
7047 | |||
7048 | if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') | ||
7049 | ALPHABET_MAP[x] = z | ||
7050 | } | ||
7051 | |||
7052 | function encode (source) { | ||
7053 | if (source.length === 0) return '' | ||
7054 | |||
7055 | var digits = [0] | ||
7056 | for (var i = 0; i < source.length; ++i) { | ||
7057 | for (var j = 0, carry = source[i]; j < digits.length; ++j) { | ||
7058 | carry += digits[j] << 8 | ||
7059 | digits[j] = carry % BASE | ||
7060 | carry = (carry / BASE) | 0 | ||
7061 | } | ||
7062 | |||
7063 | while (carry > 0) { | ||
7064 | digits.push(carry % BASE) | ||
7065 | carry = (carry / BASE) | 0 | ||
7066 | } | ||
7067 | } | ||
7068 | |||
7069 | var string = '' | ||
7070 | |||
7071 | // deal with leading zeros | ||
7072 | for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER | ||
7073 | // convert digits to a string | ||
7074 | for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]] | ||
7075 | |||
7076 | return string | ||
7077 | } | ||
7078 | |||
7079 | function decodeUnsafe (string) { | ||
7080 | if (typeof string !== 'string') throw new TypeError('Expected String') | ||
7081 | if (string.length === 0) return Buffer.allocUnsafe(0) | ||
7082 | |||
7083 | var bytes = [0] | ||
7084 | for (var i = 0; i < string.length; i++) { | ||
7085 | var value = ALPHABET_MAP[string[i]] | ||
7086 | if (value === undefined) return | ||
7087 | |||
7088 | for (var j = 0, carry = value; j < bytes.length; ++j) { | ||
7089 | carry += bytes[j] * BASE | ||
7090 | bytes[j] = carry & 0xff | ||
7091 | carry >>= 8 | ||
7092 | } | ||
7093 | |||
7094 | while (carry > 0) { | ||
7095 | bytes.push(carry & 0xff) | ||
7096 | carry >>= 8 | ||
7097 | } | ||
7098 | } | ||
7099 | |||
7100 | // deal with leading zeros | ||
7101 | for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) { | ||
7102 | bytes.push(0) | ||
7103 | } | ||
7104 | |||
7105 | return Buffer.from(bytes.reverse()) | ||
7106 | } | ||
7107 | |||
7108 | function decode (string) { | ||
7109 | var buffer = decodeUnsafe(string) | ||
7110 | if (buffer) return buffer | ||
7111 | |||
7112 | throw new Error('Non-base' + BASE + ' character') | ||
7113 | } | ||
7114 | |||
7115 | return { | ||
7116 | encode: encode, | ||
7117 | decodeUnsafe: decodeUnsafe, | ||
7118 | decode: decode | ||
7119 | } | ||
7120 | } | ||
7121 | |||
7122 | },{"safe-buffer":247}],72:[function(require,module,exports){ | ||
7123 | 'use strict' | ||
7124 | |||
7125 | exports.byteLength = byteLength | ||
7126 | exports.toByteArray = toByteArray | ||
7127 | exports.fromByteArray = fromByteArray | ||
7128 | |||
7129 | var lookup = [] | ||
7130 | var revLookup = [] | ||
7131 | var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array | ||
7132 | |||
7133 | var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' | ||
7134 | for (var i = 0, len = code.length; i < len; ++i) { | ||
7135 | lookup[i] = code[i] | ||
7136 | revLookup[code.charCodeAt(i)] = i | ||
7137 | } | ||
7138 | |||
7139 | revLookup['-'.charCodeAt(0)] = 62 | ||
7140 | revLookup['_'.charCodeAt(0)] = 63 | ||
7141 | |||
7142 | function placeHoldersCount (b64) { | ||
7143 | var len = b64.length | ||
7144 | if (len % 4 > 0) { | ||
7145 | throw new Error('Invalid string. Length must be a multiple of 4') | ||
7146 | } | ||
7147 | |||
7148 | // the number of equal signs (place holders) | ||
7149 | // if there are two placeholders, than the two characters before it | ||
7150 | // represent one byte | ||
7151 | // if there is only one, then the three characters before it represent 2 bytes | ||
7152 | // this is just a cheap hack to not do indexOf twice | ||
7153 | return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 | ||
7154 | } | ||
7155 | |||
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) | ||
7159 | } | ||
7160 | |||
7161 | function toByteArray (b64) { | ||
7162 | var i, l, tmp, placeHolders, arr | ||
7163 | var len = b64.length | ||
7164 | placeHolders = placeHoldersCount(b64) | ||
7165 | |||
7166 | arr = new Arr((len * 3 / 4) - placeHolders) | ||
7167 | |||
7168 | // if there are placeholders, only get up to the last complete 4 chars | ||
7169 | l = placeHolders > 0 ? len - 4 : len | ||
7170 | |||
7171 | var L = 0 | ||
7172 | |||
7173 | for (i = 0; i < l; i += 4) { | ||
7174 | tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] | ||
7175 | arr[L++] = (tmp >> 16) & 0xFF | ||
7176 | arr[L++] = (tmp >> 8) & 0xFF | ||
7177 | arr[L++] = tmp & 0xFF | ||
7178 | } | ||
7179 | |||
7180 | if (placeHolders === 2) { | ||
7181 | tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) | ||
7182 | arr[L++] = tmp & 0xFF | ||
7183 | } else if (placeHolders === 1) { | ||
7184 | tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) | ||
7185 | arr[L++] = (tmp >> 8) & 0xFF | ||
7186 | arr[L++] = tmp & 0xFF | ||
7187 | } | ||
7188 | |||
7189 | return arr | ||
7190 | } | ||
7191 | |||
7192 | function tripletToBase64 (num) { | ||
7193 | return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] | ||
7194 | } | ||
7195 | |||
7196 | function encodeChunk (uint8, start, end) { | ||
7197 | var tmp | ||
7198 | var output = [] | ||
7199 | for (var i = start; i < end; i += 3) { | ||
7200 | tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) | ||
7201 | output.push(tripletToBase64(tmp)) | ||
7202 | } | ||
7203 | return output.join('') | ||
7204 | } | ||
7205 | |||
7206 | function fromByteArray (uint8) { | ||
7207 | var tmp | ||
7208 | var len = uint8.length | ||
7209 | var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes | ||
7210 | var output = '' | ||
7211 | var parts = [] | ||
7212 | var maxChunkLength = 16383 // must be multiple of 3 | ||
7213 | |||
7214 | // go through the array every three bytes, we'll deal with trailing stuff later | ||
7215 | for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { | ||
7216 | parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) | ||
7217 | } | ||
7218 | |||
7219 | // pad the end with zeros, but make sure to not forget the extra bytes | ||
7220 | if (extraBytes === 1) { | ||
7221 | tmp = uint8[len - 1] | ||
7222 | output += lookup[tmp >> 2] | ||
7223 | output += lookup[(tmp << 4) & 0x3F] | ||
7224 | output += '==' | ||
7225 | } else if (extraBytes === 2) { | ||
7226 | tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) | ||
7227 | output += lookup[tmp >> 10] | ||
7228 | output += lookup[(tmp >> 4) & 0x3F] | ||
7229 | output += lookup[(tmp << 2) & 0x3F] | ||
7230 | output += '=' | ||
7231 | } | ||
7232 | |||
7233 | parts.push(output) | ||
7234 | |||
7235 | return parts.join('') | ||
7236 | } | ||
7237 | |||
7238 | },{}],73:[function(require,module,exports){ | ||
7239 | /*! bignumber.js v5.0.0 https://github.com/MikeMcl/bignumber.js/LICENCE */ | ||
7240 | |||
7241 | ;(function (globalObj) { | ||
7242 | 'use strict'; | ||
7243 | |||
7244 | /* | ||
7245 | bignumber.js v5.0.0 | ||
7246 | A JavaScript library for arbitrary-precision arithmetic. | ||
7247 | https://github.com/MikeMcl/bignumber.js | ||
7248 | Copyright (c) 2017 Michael Mclaughlin <M8ch88l@gmail.com> | ||
7249 | MIT Expat Licence | ||
7250 | */ | ||
7251 | |||
7252 | |||
7253 | var BigNumber, | ||
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$_', | ||
7261 | BASE = 1e14, | ||
7262 | LOG_BASE = 14, | ||
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], | ||
7266 | SQRT_BASE = 1e7, | ||
7267 | |||
7268 | /* | ||
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). | ||
7272 | */ | ||
7273 | MAX = 1E9; // 0 to MAX_INT32 | ||
7274 | |||
7275 | |||
7276 | /* | ||
7277 | * Create and return a BigNumber constructor. | ||
7278 | */ | ||
7279 | function constructorFactory(config) { | ||
7280 | var div, parseNumeric, | ||
7281 | |||
7282 | // id tracks the caller function, so its name can be included in error messages. | ||
7283 | id = 0, | ||
7284 | P = BigNumber.prototype, | ||
7285 | ONE = new BigNumber(1), | ||
7286 | |||
7287 | |||
7288 | /********************************* EDITABLE DEFAULTS **********************************/ | ||
7289 | |||
7290 | |||
7291 | /* | ||
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. | ||
7294 | */ | ||
7295 | |||
7296 | // The maximum number of decimal places for operations involving division. | ||
7297 | DECIMAL_PLACES = 20, // 0 to MAX | ||
7298 | |||
7299 | /* | ||
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. | ||
7311 | */ | ||
7312 | ROUNDING_MODE = 4, // 0 to 8 | ||
7313 | |||
7314 | // EXPONENTIAL_AT : [TO_EXP_NEG , TO_EXP_POS] | ||
7315 | |||
7316 | // The exponent value at and beneath which toString returns exponential notation. | ||
7317 | // Number type: -7 | ||
7318 | TO_EXP_NEG = -7, // 0 to -MAX | ||
7319 | |||
7320 | // The exponent value at and above which toString returns exponential notation. | ||
7321 | // Number type: 21 | ||
7322 | TO_EXP_POS = 21, // 0 to MAX | ||
7323 | |||
7324 | // RANGE : [MIN_EXP, MAX_EXP] | ||
7325 | |||
7326 | // The minimum exponent value, beneath which underflow to zero occurs. | ||
7327 | // Number type: -324 (5e-324) | ||
7328 | MIN_EXP = -1e7, // -1 to -MAX | ||
7329 | |||
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 | ||
7334 | |||
7335 | // Whether BigNumber Errors are ever thrown. | ||
7336 | ERRORS = true, // true or false | ||
7337 | |||
7338 | // Change to intValidatorNoErrors if ERRORS is false. | ||
7339 | isValidInt = intValidatorWithErrors, // intValidatorWithErrors/intValidatorNoErrors | ||
7340 | |||
7341 | // Whether to use cryptographically-secure random number generation, if available. | ||
7342 | CRYPTO = false, // true or false | ||
7343 | |||
7344 | /* | ||
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. | ||
7348 | * | ||
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. | ||
7357 | * | ||
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. | ||
7361 | */ | ||
7362 | MODULO_MODE = 1, // 0 to 9 | ||
7363 | |||
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 | ||
7367 | |||
7368 | // The format specification used by the BigNumber.prototype.toFormat method. | ||
7369 | FORMAT = { | ||
7370 | decimalSeparator: '.', | ||
7371 | groupSeparator: ',', | ||
7372 | groupSize: 3, | ||
7373 | secondaryGroupSize: 0, | ||
7374 | fractionGroupSeparator: '\xA0', // non-breaking space | ||
7375 | fractionGroupSize: 0 | ||
7376 | }; | ||
7377 | |||
7378 | |||
7379 | /******************************************************************************************/ | ||
7380 | |||
7381 | |||
7382 | // CONSTRUCTOR | ||
7383 | |||
7384 | |||
7385 | /* | ||
7386 | * The BigNumber constructor and exported function. | ||
7387 | * Create and return a new instance of a BigNumber object. | ||
7388 | * | ||
7389 | * n {number|string|BigNumber} A numeric value. | ||
7390 | * [b] {number} The base of n. Integer, 2 to 64 inclusive. | ||
7391 | */ | ||
7392 | function BigNumber( n, b ) { | ||
7393 | var c, e, i, num, len, str, | ||
7394 | x = this; | ||
7395 | |||
7396 | // Enable constructor usage without new. | ||
7397 | if ( !( x instanceof BigNumber ) ) { | ||
7398 | |||
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 ); | ||
7403 | } | ||
7404 | |||
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' ) ) { | ||
7408 | |||
7409 | // Duplicate. | ||
7410 | if ( n instanceof BigNumber ) { | ||
7411 | x.s = n.s; | ||
7412 | x.e = n.e; | ||
7413 | x.c = ( n = n.c ) ? n.slice() : n; | ||
7414 | id = 0; | ||
7415 | return; | ||
7416 | } | ||
7417 | |||
7418 | if ( ( num = typeof n == 'number' ) && n * 0 == 0 ) { | ||
7419 | x.s = 1 / n < 0 ? ( n = -n, -1 ) : 1; | ||
7420 | |||
7421 | // Fast path for integers. | ||
7422 | if ( n === ~~n ) { | ||
7423 | for ( e = 0, i = n; i >= 10; i /= 10, e++ ); | ||
7424 | x.e = e; | ||
7425 | x.c = [n]; | ||
7426 | id = 0; | ||
7427 | return; | ||
7428 | } | ||
7429 | |||
7430 | str = n + ''; | ||
7431 | } else { | ||
7432 | if ( !isNumeric.test( str = n + '' ) ) return parseNumeric( x, str, num ); | ||
7433 | x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; | ||
7434 | } | ||
7435 | } else { | ||
7436 | b = b | 0; | ||
7437 | str = n + ''; | ||
7438 | |||
7439 | // Ensure return value is rounded to DECIMAL_PLACES as with other bases. | ||
7440 | // Allow exponential notation to be used with base 10 argument. | ||
7441 | if ( b == 10 ) { | ||
7442 | x = new BigNumber( n instanceof BigNumber ? n : str ); | ||
7443 | return round( x, DECIMAL_PLACES + x.e + 1, ROUNDING_MODE ); | ||
7444 | } | ||
7445 | |||
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 ); | ||
7452 | } | ||
7453 | |||
7454 | if (num) { | ||
7455 | x.s = 1 / n < 0 ? ( str = str.slice(1), -1 ) : 1; | ||
7456 | |||
7457 | if ( ERRORS && str.replace( /^0\.0*|\./, '' ).length > 15 ) { | ||
7458 | |||
7459 | // 'new BigNumber() number type has more than 15 significant digits: {n}' | ||
7460 | raise( id, tooManyDigits, n ); | ||
7461 | } | ||
7462 | |||
7463 | // Prevent later check for length on converted number. | ||
7464 | num = false; | ||
7465 | } else { | ||
7466 | x.s = str.charCodeAt(0) === 45 ? ( str = str.slice(1), -1 ) : 1; | ||
7467 | } | ||
7468 | |||
7469 | str = convertBase( str, 10, b, x.s ); | ||
7470 | } | ||
7471 | |||
7472 | // Decimal point? | ||
7473 | if ( ( e = str.indexOf('.') ) > -1 ) str = str.replace( '.', '' ); | ||
7474 | |||
7475 | // Exponential form? | ||
7476 | if ( ( i = str.search( /e/i ) ) > 0 ) { | ||
7477 | |||
7478 | // Determine exponent. | ||
7479 | if ( e < 0 ) e = i; | ||
7480 | e += +str.slice( i + 1 ); | ||
7481 | str = str.substring( 0, i ); | ||
7482 | } else if ( e < 0 ) { | ||
7483 | |||
7484 | // Integer. | ||
7485 | e = str.length; | ||
7486 | } | ||
7487 | |||
7488 | // Determine leading zeros. | ||
7489 | for ( i = 0; str.charCodeAt(i) === 48; i++ ); | ||
7490 | |||
7491 | // Determine trailing zeros. | ||
7492 | for ( len = str.length; str.charCodeAt(--len) === 48; ); | ||
7493 | str = str.slice( i, len + 1 ); | ||
7494 | |||
7495 | if (str) { | ||
7496 | len = str.length; | ||
7497 | |||
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 ); | ||
7502 | } | ||
7503 | |||
7504 | e = e - i - 1; | ||
7505 | |||
7506 | // Overflow? | ||
7507 | if ( e > MAX_EXP ) { | ||
7508 | |||
7509 | // Infinity. | ||
7510 | x.c = x.e = null; | ||
7511 | |||
7512 | // Underflow? | ||
7513 | } else if ( e < MIN_EXP ) { | ||
7514 | |||
7515 | // Zero. | ||
7516 | x.c = [ x.e = 0 ]; | ||
7517 | } else { | ||
7518 | x.e = e; | ||
7519 | x.c = []; | ||
7520 | |||
7521 | // Transform base | ||
7522 | |||
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; | ||
7527 | |||
7528 | if ( i < len ) { | ||
7529 | if (i) x.c.push( +str.slice( 0, i ) ); | ||
7530 | |||
7531 | for ( len -= LOG_BASE; i < len; ) { | ||
7532 | x.c.push( +str.slice( i, i += LOG_BASE ) ); | ||
7533 | } | ||
7534 | |||
7535 | str = str.slice(i); | ||
7536 | i = LOG_BASE - str.length; | ||
7537 | } else { | ||
7538 | i -= len; | ||
7539 | } | ||
7540 | |||
7541 | for ( ; i--; str += '0' ); | ||
7542 | x.c.push( +str ); | ||
7543 | } | ||
7544 | } else { | ||
7545 | |||
7546 | // Zero. | ||
7547 | x.c = [ x.e = 0 ]; | ||
7548 | } | ||
7549 | |||
7550 | id = 0; | ||
7551 | } | ||
7552 | |||
7553 | |||
7554 | // CONSTRUCTOR PROPERTIES | ||
7555 | |||
7556 | |||
7557 | BigNumber.another = constructorFactory; | ||
7558 | |||
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; | ||
7569 | |||
7570 | |||
7571 | /* | ||
7572 | * Configure infrequently-changing library-wide settings. | ||
7573 | * | ||
7574 | * Accept an object or an argument list, with one or many of the following properties or | ||
7575 | * parameters respectively: | ||
7576 | * | ||
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} | ||
7594 | * | ||
7595 | * (The values assigned to the above FORMAT object properties are not checked for validity.) | ||
7596 | * | ||
7597 | * E.g. | ||
7598 | * BigNumber.config(20, 4) is equivalent to | ||
7599 | * BigNumber.config({ DECIMAL_PLACES : 20, ROUNDING_MODE : 4 }) | ||
7600 | * | ||
7601 | * Ignore properties/parameters set to null or undefined. | ||
7602 | * Return an object with the properties current values. | ||
7603 | */ | ||
7604 | BigNumber.config = BigNumber.set = function () { | ||
7605 | var v, p, | ||
7606 | i = 0, | ||
7607 | r = {}, | ||
7608 | a = arguments, | ||
7609 | o = a[0], | ||
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; }; | ||
7613 | |||
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; | ||
7619 | } | ||
7620 | r[p] = DECIMAL_PLACES; | ||
7621 | |||
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; | ||
7627 | } | ||
7628 | r[p] = ROUNDING_MODE; | ||
7629 | |||
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' ) ) { | ||
7635 | |||
7636 | if ( isArray(v) ) { | ||
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; | ||
7640 | } | ||
7641 | } else if ( isValidInt( v, -MAX, MAX, 2, p ) ) { | ||
7642 | TO_EXP_NEG = -( TO_EXP_POS = ( v < 0 ? -v : v ) | 0 ); | ||
7643 | } | ||
7644 | } | ||
7645 | r[p] = [ TO_EXP_NEG, TO_EXP_POS ]; | ||
7646 | |||
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' ) ) { | ||
7653 | |||
7654 | if ( isArray(v) ) { | ||
7655 | if ( isValidInt( v[0], -MAX, -1, 2, p ) && isValidInt( v[1], 1, MAX, 2, p ) ) { | ||
7656 | MIN_EXP = v[0] | 0; | ||
7657 | MAX_EXP = v[1] | 0; | ||
7658 | } | ||
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 ); | ||
7662 | } | ||
7663 | } | ||
7664 | r[p] = [ MIN_EXP, MAX_EXP ]; | ||
7665 | |||
7666 | // ERRORS {boolean|number} true, false, 1 or 0. | ||
7667 | // 'config() ERRORS not a boolean or binary digit: {v}' | ||
7668 | if ( has( p = 'ERRORS' ) ) { | ||
7669 | |||
7670 | if ( v === !!v || v === 1 || v === 0 ) { | ||
7671 | id = 0; | ||
7672 | isValidInt = ( ERRORS = !!v ) ? intValidatorWithErrors : intValidatorNoErrors; | ||
7673 | } else if (ERRORS) { | ||
7674 | raise( 2, p + notBool, v ); | ||
7675 | } | ||
7676 | } | ||
7677 | r[p] = ERRORS; | ||
7678 | |||
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' ) ) { | ||
7683 | |||
7684 | if ( v === true || v === false || v === 1 || v === 0 ) { | ||
7685 | if (v) { | ||
7686 | v = typeof crypto == 'undefined'; | ||
7687 | if ( !v && crypto && (crypto.getRandomValues || crypto.randomBytes)) { | ||
7688 | CRYPTO = true; | ||
7689 | } else if (ERRORS) { | ||
7690 | raise( 2, 'crypto unavailable', v ? void 0 : crypto ); | ||
7691 | } else { | ||
7692 | CRYPTO = false; | ||
7693 | } | ||
7694 | } else { | ||
7695 | CRYPTO = false; | ||
7696 | } | ||
7697 | } else if (ERRORS) { | ||
7698 | raise( 2, p + notBool, v ); | ||
7699 | } | ||
7700 | } | ||
7701 | r[p] = CRYPTO; | ||
7702 | |||
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; | ||
7708 | } | ||
7709 | r[p] = MODULO_MODE; | ||
7710 | |||
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; | ||
7716 | } | ||
7717 | r[p] = POW_PRECISION; | ||
7718 | |||
7719 | // FORMAT {object} | ||
7720 | // 'config() FORMAT not an object: {v}' | ||
7721 | if ( has( p = 'FORMAT' ) ) { | ||
7722 | |||
7723 | if ( typeof v == 'object' ) { | ||
7724 | FORMAT = v; | ||
7725 | } else if (ERRORS) { | ||
7726 | raise( 2, p + ' not an object', v ); | ||
7727 | } | ||
7728 | } | ||
7729 | r[p] = FORMAT; | ||
7730 | |||
7731 | return r; | ||
7732 | }; | ||
7733 | |||
7734 | |||
7735 | /* | ||
7736 | * Return a new BigNumber whose value is the maximum of the arguments. | ||
7737 | * | ||
7738 | * arguments {number|string|BigNumber} | ||
7739 | */ | ||
7740 | BigNumber.max = function () { return maxOrMin( arguments, P.lt ); }; | ||
7741 | |||
7742 | |||
7743 | /* | ||
7744 | * Return a new BigNumber whose value is the minimum of the arguments. | ||
7745 | * | ||
7746 | * arguments {number|string|BigNumber} | ||
7747 | */ | ||
7748 | BigNumber.min = function () { return maxOrMin( arguments, P.gt ); }; | ||
7749 | |||
7750 | |||
7751 | /* | ||
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). | ||
7755 | * | ||
7756 | * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. | ||
7757 | * | ||
7758 | * 'random() decimal places not an integer: {dp}' | ||
7759 | * 'random() decimal places out of range: {dp}' | ||
7760 | * 'random() crypto unavailable: {crypto}' | ||
7761 | */ | ||
7762 | BigNumber.random = (function () { | ||
7763 | var pow2_53 = 0x20000000000000; | ||
7764 | |||
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); }; | ||
7773 | |||
7774 | return function (dp) { | ||
7775 | var a, b, e, k, v, | ||
7776 | i = 0, | ||
7777 | c = [], | ||
7778 | rand = new BigNumber(ONE); | ||
7779 | |||
7780 | dp = dp == null || !isValidInt( dp, 0, MAX, 14 ) ? DECIMAL_PLACES : dp | 0; | ||
7781 | k = mathceil( dp / LOG_BASE ); | ||
7782 | |||
7783 | if (CRYPTO) { | ||
7784 | |||
7785 | // Browsers supporting crypto.getRandomValues. | ||
7786 | if (crypto.getRandomValues) { | ||
7787 | |||
7788 | a = crypto.getRandomValues( new Uint32Array( k *= 2 ) ); | ||
7789 | |||
7790 | for ( ; i < k; ) { | ||
7791 | |||
7792 | // 53 bits: | ||
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 | ||
7797 | // 0x20000 is 2^21. | ||
7798 | v = a[i] * 0x20000 + (a[i + 1] >>> 11); | ||
7799 | |||
7800 | // Rejection sampling: | ||
7801 | // 0 <= v < 9007199254740992 | ||
7802 | // Probability that v >= 9e15, is | ||
7803 | // 7199254740992 / 9007199254740992 ~= 0.0008, i.e. 1 in 1251 | ||
7804 | if ( v >= 9e15 ) { | ||
7805 | b = crypto.getRandomValues( new Uint32Array(2) ); | ||
7806 | a[i] = b[0]; | ||
7807 | a[i + 1] = b[1]; | ||
7808 | } else { | ||
7809 | |||
7810 | // 0 <= v <= 8999999999999999 | ||
7811 | // 0 <= (v % 1e14) <= 99999999999999 | ||
7812 | c.push( v % 1e14 ); | ||
7813 | i += 2; | ||
7814 | } | ||
7815 | } | ||
7816 | i = k / 2; | ||
7817 | |||
7818 | // Node.js supporting crypto.randomBytes. | ||
7819 | } else if (crypto.randomBytes) { | ||
7820 | |||
7821 | // buffer | ||
7822 | a = crypto.randomBytes( k *= 7 ); | ||
7823 | |||
7824 | for ( ; i < k; ) { | ||
7825 | |||
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]; | ||
7833 | |||
7834 | if ( v >= 9e15 ) { | ||
7835 | crypto.randomBytes(7).copy( a, i ); | ||
7836 | } else { | ||
7837 | |||
7838 | // 0 <= (v % 1e14) <= 99999999999999 | ||
7839 | c.push( v % 1e14 ); | ||
7840 | i += 7; | ||
7841 | } | ||
7842 | } | ||
7843 | i = k / 7; | ||
7844 | } else { | ||
7845 | CRYPTO = false; | ||
7846 | if (ERRORS) raise( 14, 'crypto unavailable', crypto ); | ||
7847 | } | ||
7848 | } | ||
7849 | |||
7850 | // Use Math.random. | ||
7851 | if (!CRYPTO) { | ||
7852 | |||
7853 | for ( ; i < k; ) { | ||
7854 | v = random53bitInt(); | ||
7855 | if ( v < 9e15 ) c[i++] = v % 1e14; | ||
7856 | } | ||
7857 | } | ||
7858 | |||
7859 | k = c[--i]; | ||
7860 | dp %= LOG_BASE; | ||
7861 | |||
7862 | // Convert trailing digits to zeros according to dp. | ||
7863 | if ( k && dp ) { | ||
7864 | v = POWS_TEN[LOG_BASE - dp]; | ||
7865 | c[i] = mathfloor( k / v ) * v; | ||
7866 | } | ||
7867 | |||
7868 | // Remove trailing elements which are zero. | ||
7869 | for ( ; c[i] === 0; c.pop(), i-- ); | ||
7870 | |||
7871 | // Zero? | ||
7872 | if ( i < 0 ) { | ||
7873 | c = [ e = 0 ]; | ||
7874 | } else { | ||
7875 | |||
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); | ||
7878 | |||
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++); | ||
7881 | |||
7882 | // adjust the exponent accordingly. | ||
7883 | if ( i < LOG_BASE ) e -= LOG_BASE - i; | ||
7884 | } | ||
7885 | |||
7886 | rand.e = e; | ||
7887 | rand.c = c; | ||
7888 | return rand; | ||
7889 | }; | ||
7890 | })(); | ||
7891 | |||
7892 | |||
7893 | // PRIVATE FUNCTIONS | ||
7894 | |||
7895 | |||
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, | ||
7901 | rm = ROUNDING_MODE; | ||
7902 | |||
7903 | if ( baseIn < 37 ) str = str.toLowerCase(); | ||
7904 | |||
7905 | // Non-integer. | ||
7906 | if ( i >= 0 ) { | ||
7907 | k = POW_PRECISION; | ||
7908 | |||
7909 | // Unlimited precision. | ||
7910 | POW_PRECISION = 0; | ||
7911 | str = str.replace( '.', '' ); | ||
7912 | y = new BigNumber(baseIn); | ||
7913 | x = y.pow( str.length - i ); | ||
7914 | POW_PRECISION = k; | ||
7915 | |||
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 ); | ||
7919 | y.e = y.c.length; | ||
7920 | } | ||
7921 | |||
7922 | // Convert the number as integer. | ||
7923 | xc = toBaseOut( str, baseIn, baseOut ); | ||
7924 | e = k = xc.length; | ||
7925 | |||
7926 | // Remove trailing zeros. | ||
7927 | for ( ; xc[--k] == 0; xc.pop() ); | ||
7928 | if ( !xc[0] ) return '0'; | ||
7929 | |||
7930 | if ( i < 0 ) { | ||
7931 | --e; | ||
7932 | } else { | ||
7933 | x.c = xc; | ||
7934 | x.e = e; | ||
7935 | |||
7936 | // sign is needed for correct rounding. | ||
7937 | x.s = sign; | ||
7938 | x = div( x, y, dp, rm, baseOut ); | ||
7939 | xc = x.c; | ||
7940 | r = x.r; | ||
7941 | e = x.e; | ||
7942 | } | ||
7943 | |||
7944 | d = e + dp + 1; | ||
7945 | |||
7946 | // The rounding digit, i.e. the digit to the right of the digit that may be rounded up. | ||
7947 | i = xc[d]; | ||
7948 | k = baseOut / 2; | ||
7949 | r = r || d < 0 || xc[d + 1] != null; | ||
7950 | |||
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 ) ); | ||
7954 | |||
7955 | if ( d < 1 || !xc[0] ) { | ||
7956 | |||
7957 | // 1^-dp or 0. | ||
7958 | str = r ? toFixedPoint( '1', -dp ) : '0'; | ||
7959 | } else { | ||
7960 | xc.length = d; | ||
7961 | |||
7962 | if (r) { | ||
7963 | |||
7964 | // Rounding up may mean the previous digit has to be rounded up and so on. | ||
7965 | for ( --baseOut; ++xc[--d] > baseOut; ) { | ||
7966 | xc[d] = 0; | ||
7967 | |||
7968 | if ( !d ) { | ||
7969 | ++e; | ||
7970 | xc = [1].concat(xc); | ||
7971 | } | ||
7972 | } | ||
7973 | } | ||
7974 | |||
7975 | // Determine trailing zeros. | ||
7976 | for ( k = xc.length; !xc[--k]; ); | ||
7977 | |||
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 ); | ||
7981 | } | ||
7982 | |||
7983 | // The caller will add the sign. | ||
7984 | return str; | ||
7985 | } | ||
7986 | |||
7987 | |||
7988 | // Perform division in the specified base. Called by div and convertBase. | ||
7989 | div = (function () { | ||
7990 | |||
7991 | // Assume non-zero x and k. | ||
7992 | function multiply( x, k, base ) { | ||
7993 | var m, temp, xlo, xhi, | ||
7994 | carry = 0, | ||
7995 | i = x.length, | ||
7996 | klo = k % SQRT_BASE, | ||
7997 | khi = k / SQRT_BASE | 0; | ||
7998 | |||
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; | ||
8005 | x[i] = temp % base; | ||
8006 | } | ||
8007 | |||
8008 | if (carry) x = [carry].concat(x); | ||
8009 | |||
8010 | return x; | ||
8011 | } | ||
8012 | |||
8013 | function compare( a, b, aL, bL ) { | ||
8014 | var i, cmp; | ||
8015 | |||
8016 | if ( aL != bL ) { | ||
8017 | cmp = aL > bL ? 1 : -1; | ||
8018 | } else { | ||
8019 | |||
8020 | for ( i = cmp = 0; i < aL; i++ ) { | ||
8021 | |||
8022 | if ( a[i] != b[i] ) { | ||
8023 | cmp = a[i] > b[i] ? 1 : -1; | ||
8024 | break; | ||
8025 | } | ||
8026 | } | ||
8027 | } | ||
8028 | return cmp; | ||
8029 | } | ||
8030 | |||
8031 | function subtract( a, b, aL, base ) { | ||
8032 | var i = 0; | ||
8033 | |||
8034 | // Subtract b from a. | ||
8035 | for ( ; aL--; ) { | ||
8036 | a[aL] -= i; | ||
8037 | i = a[aL] < b[aL] ? 1 : 0; | ||
8038 | a[aL] = i * base + a[aL] - b[aL]; | ||
8039 | } | ||
8040 | |||
8041 | // Remove leading zeros. | ||
8042 | for ( ; !a[0] && a.length > 1; a.splice(0, 1) ); | ||
8043 | } | ||
8044 | |||
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, | ||
8048 | yL, yz, | ||
8049 | s = x.s == y.s ? 1 : -1, | ||
8050 | xc = x.c, | ||
8051 | yc = y.c; | ||
8052 | |||
8053 | // Either NaN, Infinity or 0? | ||
8054 | if ( !xc || !xc[0] || !yc || !yc[0] ) { | ||
8055 | |||
8056 | return new BigNumber( | ||
8057 | |||
8058 | // Return NaN if either NaN, or both Infinity or 0. | ||
8059 | !x.s || !y.s || ( xc ? yc && xc[0] == yc[0] : !yc ) ? NaN : | ||
8060 | |||
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 | ||
8063 | ); | ||
8064 | } | ||
8065 | |||
8066 | q = new BigNumber(s); | ||
8067 | qc = q.c = []; | ||
8068 | e = x.e - y.e; | ||
8069 | s = dp + e + 1; | ||
8070 | |||
8071 | if ( !base ) { | ||
8072 | base = BASE; | ||
8073 | e = bitFloor( x.e / LOG_BASE ) - bitFloor( y.e / LOG_BASE ); | ||
8074 | s = s / LOG_BASE | 0; | ||
8075 | } | ||
8076 | |||
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--; | ||
8081 | |||
8082 | if ( s < 0 ) { | ||
8083 | qc.push(1); | ||
8084 | more = true; | ||
8085 | } else { | ||
8086 | xL = xc.length; | ||
8087 | yL = yc.length; | ||
8088 | i = 0; | ||
8089 | s += 2; | ||
8090 | |||
8091 | // Normalise xc and yc so highest order digit of yc is >= base / 2. | ||
8092 | |||
8093 | n = mathfloor( base / ( yc[0] + 1 ) ); | ||
8094 | |||
8095 | // Not necessary, but to handle odd bases where yc[0] == ( base / 2 ) - 1. | ||
8096 | // if ( n > 1 || n++ == 1 && yc[0] < base / 2 ) { | ||
8097 | if ( n > 1 ) { | ||
8098 | yc = multiply( yc, n, base ); | ||
8099 | xc = multiply( xc, n, base ); | ||
8100 | yL = yc.length; | ||
8101 | xL = xc.length; | ||
8102 | } | ||
8103 | |||
8104 | xi = yL; | ||
8105 | rem = xc.slice( 0, yL ); | ||
8106 | remL = rem.length; | ||
8107 | |||
8108 | // Add zeros to make remainder as long as divisor. | ||
8109 | for ( ; remL < yL; rem[remL++] = 0 ); | ||
8110 | yz = yc.slice(); | ||
8111 | yz = [0].concat(yz); | ||
8112 | yc0 = yc[0]; | ||
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; | ||
8116 | |||
8117 | do { | ||
8118 | n = 0; | ||
8119 | |||
8120 | // Compare divisor and remainder. | ||
8121 | cmp = compare( yc, rem, yL, remL ); | ||
8122 | |||
8123 | // If divisor < remainder. | ||
8124 | if ( cmp < 0 ) { | ||
8125 | |||
8126 | // Calculate trial digit, n. | ||
8127 | |||
8128 | rem0 = rem[0]; | ||
8129 | if ( yL != remL ) rem0 = rem0 * base + ( rem[1] || 0 ); | ||
8130 | |||
8131 | // n is how many times the divisor goes into the current remainder. | ||
8132 | n = mathfloor( rem0 / yc0 ); | ||
8133 | |||
8134 | // Algorithm: | ||
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++ | ||
8141 | |||
8142 | if ( n > 1 ) { | ||
8143 | |||
8144 | // n may be > base only when base is 3. | ||
8145 | if (n >= base) n = base - 1; | ||
8146 | |||
8147 | // product = divisor * trial digit. | ||
8148 | prod = multiply( yc, n, base ); | ||
8149 | prodL = prod.length; | ||
8150 | remL = rem.length; | ||
8151 | |||
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 ) { | ||
8158 | n--; | ||
8159 | |||
8160 | // Subtract divisor from product. | ||
8161 | subtract( prod, yL < prodL ? yz : yc, prodL, base ); | ||
8162 | prodL = prod.length; | ||
8163 | cmp = 1; | ||
8164 | } | ||
8165 | } else { | ||
8166 | |||
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. | ||
8171 | if ( n == 0 ) { | ||
8172 | |||
8173 | // divisor < remainder, so n must be at least 1. | ||
8174 | cmp = n = 1; | ||
8175 | } | ||
8176 | |||
8177 | // product = divisor | ||
8178 | prod = yc.slice(); | ||
8179 | prodL = prod.length; | ||
8180 | } | ||
8181 | |||
8182 | if ( prodL < remL ) prod = [0].concat(prod); | ||
8183 | |||
8184 | // Subtract product from remainder. | ||
8185 | subtract( rem, prod, remL, base ); | ||
8186 | remL = rem.length; | ||
8187 | |||
8188 | // If product was < remainder. | ||
8189 | if ( cmp == -1 ) { | ||
8190 | |||
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 ) { | ||
8196 | n++; | ||
8197 | |||
8198 | // Subtract divisor from remainder. | ||
8199 | subtract( rem, yL < remL ? yz : yc, remL, base ); | ||
8200 | remL = rem.length; | ||
8201 | } | ||
8202 | } | ||
8203 | } else if ( cmp === 0 ) { | ||
8204 | n++; | ||
8205 | rem = [0]; | ||
8206 | } // else cmp === 1 and n will be 0 | ||
8207 | |||
8208 | // Add the next digit, n, to the result array. | ||
8209 | qc[i++] = n; | ||
8210 | |||
8211 | // Update the remainder. | ||
8212 | if ( rem[0] ) { | ||
8213 | rem[remL++] = xc[xi] || 0; | ||
8214 | } else { | ||
8215 | rem = [ xc[xi] ]; | ||
8216 | remL = 1; | ||
8217 | } | ||
8218 | } while ( ( xi++ < xL || rem[0] != null ) && s-- ); | ||
8219 | |||
8220 | more = rem[0] != null; | ||
8221 | |||
8222 | // Leading zero? | ||
8223 | if ( !qc[0] ) qc.splice(0, 1); | ||
8224 | } | ||
8225 | |||
8226 | if ( base == BASE ) { | ||
8227 | |||
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 ); | ||
8231 | |||
8232 | // Caller is convertBase. | ||
8233 | } else { | ||
8234 | q.e = e; | ||
8235 | q.r = +more; | ||
8236 | } | ||
8237 | |||
8238 | return q; | ||
8239 | }; | ||
8240 | })(); | ||
8241 | |||
8242 | |||
8243 | /* | ||
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. | ||
8246 | * | ||
8247 | * n is a BigNumber. | ||
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. | ||
8251 | */ | ||
8252 | function format( n, i, rm, caller ) { | ||
8253 | var c0, e, ne, len, str; | ||
8254 | |||
8255 | rm = rm != null && isValidInt( rm, 0, 8, caller, roundingMode ) | ||
8256 | ? rm | 0 : ROUNDING_MODE; | ||
8257 | |||
8258 | if ( !n.c ) return n.toString(); | ||
8259 | c0 = n.c[0]; | ||
8260 | ne = n.e; | ||
8261 | |||
8262 | if ( i == null ) { | ||
8263 | str = coeffToString( n.c ); | ||
8264 | str = caller == 19 || caller == 24 && ne <= TO_EXP_NEG | ||
8265 | ? toExponential( str, ne ) | ||
8266 | : toFixedPoint( str, ne ); | ||
8267 | } else { | ||
8268 | n = round( new BigNumber(n), i, rm ); | ||
8269 | |||
8270 | // n.e may have changed if the value was rounded up. | ||
8271 | e = n.e; | ||
8272 | |||
8273 | str = coeffToString( n.c ); | ||
8274 | len = str.length; | ||
8275 | |||
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. | ||
8279 | |||
8280 | // Exponential notation. | ||
8281 | if ( caller == 19 || caller == 24 && ( i <= e || e <= TO_EXP_NEG ) ) { | ||
8282 | |||
8283 | // Append zeros? | ||
8284 | for ( ; len < i; str += '0', len++ ); | ||
8285 | str = toExponential( str, e ); | ||
8286 | |||
8287 | // Fixed-point notation. | ||
8288 | } else { | ||
8289 | i -= ne; | ||
8290 | str = toFixedPoint( str, e ); | ||
8291 | |||
8292 | // Append zeros? | ||
8293 | if ( e + 1 > len ) { | ||
8294 | if ( --i > 0 ) for ( str += '.'; i--; str += '0' ); | ||
8295 | } else { | ||
8296 | i += e - len; | ||
8297 | if ( i > 0 ) { | ||
8298 | if ( e + 1 == len ) str += '.'; | ||
8299 | for ( ; i--; str += '0' ); | ||
8300 | } | ||
8301 | } | ||
8302 | } | ||
8303 | } | ||
8304 | |||
8305 | return n.s < 0 && c0 ? '-' + str : str; | ||
8306 | } | ||
8307 | |||
8308 | |||
8309 | // Handle BigNumber.max and BigNumber.min. | ||
8310 | function maxOrMin( args, method ) { | ||
8311 | var m, n, | ||
8312 | i = 0; | ||
8313 | |||
8314 | if ( isArray( args[0] ) ) args = args[0]; | ||
8315 | m = new BigNumber( args[0] ); | ||
8316 | |||
8317 | for ( ; ++i < args.length; ) { | ||
8318 | n = new BigNumber( args[i] ); | ||
8319 | |||
8320 | // If any number is NaN, return NaN. | ||
8321 | if ( !n.s ) { | ||
8322 | m = n; | ||
8323 | break; | ||
8324 | } else if ( method.call( m, n ) ) { | ||
8325 | m = n; | ||
8326 | } | ||
8327 | } | ||
8328 | |||
8329 | return m; | ||
8330 | } | ||
8331 | |||
8332 | |||
8333 | /* | ||
8334 | * Return true if n is an integer in range, otherwise throw. | ||
8335 | * Use for argument validation when ERRORS is true. | ||
8336 | */ | ||
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 ); | ||
8341 | } | ||
8342 | |||
8343 | return true; | ||
8344 | } | ||
8345 | |||
8346 | |||
8347 | /* | ||
8348 | * Strip trailing zeros, calculate base 10 exponent and check against MIN_EXP and MAX_EXP. | ||
8349 | * Called by minus, plus and times. | ||
8350 | */ | ||
8351 | function normalise( n, c, e ) { | ||
8352 | var i = 1, | ||
8353 | j = c.length; | ||
8354 | |||
8355 | // Remove trailing zeros. | ||
8356 | for ( ; !c[--j]; c.pop() ); | ||
8357 | |||
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++ ); | ||
8360 | |||
8361 | // Overflow? | ||
8362 | if ( ( e = i + e * LOG_BASE - 1 ) > MAX_EXP ) { | ||
8363 | |||
8364 | // Infinity. | ||
8365 | n.c = n.e = null; | ||
8366 | |||
8367 | // Underflow? | ||
8368 | } else if ( e < MIN_EXP ) { | ||
8369 | |||
8370 | // Zero. | ||
8371 | n.c = [ n.e = 0 ]; | ||
8372 | } else { | ||
8373 | n.e = e; | ||
8374 | n.c = c; | ||
8375 | } | ||
8376 | |||
8377 | return n; | ||
8378 | } | ||
8379 | |||
8380 | |||
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; | ||
8388 | |||
8389 | return function ( x, str, num, b ) { | ||
8390 | var base, | ||
8391 | s = num ? str : str.replace( whitespaceOrPlus, '' ); | ||
8392 | |||
8393 | // No exception on ±Infinity or NaN. | ||
8394 | if ( isInfinityOrNaN.test(s) ) { | ||
8395 | x.s = isNaN(s) ? null : s < 0 ? -1 : 1; | ||
8396 | } else { | ||
8397 | if ( !num ) { | ||
8398 | |||
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; | ||
8403 | }); | ||
8404 | |||
8405 | if (b) { | ||
8406 | base = b; | ||
8407 | |||
8408 | // E.g. '1.' to '1', '.1' to '0.1' | ||
8409 | s = s.replace( dotAfter, '$1' ).replace( dotBefore, '0.$1' ); | ||
8410 | } | ||
8411 | |||
8412 | if ( str != s ) return new BigNumber( s, base ); | ||
8413 | } | ||
8414 | |||
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 ); | ||
8418 | x.s = null; | ||
8419 | } | ||
8420 | |||
8421 | x.c = x.e = null; | ||
8422 | id = 0; | ||
8423 | } | ||
8424 | })(); | ||
8425 | |||
8426 | |||
8427 | // Throw a BigNumber Error. | ||
8428 | function raise( caller, msg, val ) { | ||
8429 | var error = new Error( [ | ||
8430 | 'new BigNumber', // 0 | ||
8431 | 'cmp', // 1 | ||
8432 | 'config', // 2 | ||
8433 | 'div', // 3 | ||
8434 | 'divToInt', // 4 | ||
8435 | 'eq', // 5 | ||
8436 | 'gt', // 6 | ||
8437 | 'gte', // 7 | ||
8438 | 'lt', // 8 | ||
8439 | 'lte', // 9 | ||
8440 | 'minus', // 10 | ||
8441 | 'mod', // 11 | ||
8442 | 'plus', // 12 | ||
8443 | 'precision', // 13 | ||
8444 | 'random', // 14 | ||
8445 | 'round', // 15 | ||
8446 | 'shift', // 16 | ||
8447 | 'times', // 17 | ||
8448 | 'toDigits', // 18 | ||
8449 | 'toExponential', // 19 | ||
8450 | 'toFixed', // 20 | ||
8451 | 'toFormat', // 21 | ||
8452 | 'toFraction', // 22 | ||
8453 | 'pow', // 23 | ||
8454 | 'toPrecision', // 24 | ||
8455 | 'toString', // 25 | ||
8456 | 'BigNumber' // 26 | ||
8457 | ][caller] + '() ' + msg + ': ' + val ); | ||
8458 | |||
8459 | error.name = 'BigNumber Error'; | ||
8460 | id = 0; | ||
8461 | throw error; | ||
8462 | } | ||
8463 | |||
8464 | |||
8465 | /* | ||
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. | ||
8468 | */ | ||
8469 | function round( x, sd, rm, r ) { | ||
8470 | var d, i, j, k, n, ni, rd, | ||
8471 | xc = x.c, | ||
8472 | pows10 = POWS_TEN; | ||
8473 | |||
8474 | // if x is not Infinity or NaN... | ||
8475 | if (xc) { | ||
8476 | |||
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). | ||
8483 | out: { | ||
8484 | |||
8485 | // Get the number of digits of the first element of xc. | ||
8486 | for ( d = 1, k = xc[0]; k >= 10; k /= 10, d++ ); | ||
8487 | i = sd - d; | ||
8488 | |||
8489 | // If the rounding digit is in the first element of xc... | ||
8490 | if ( i < 0 ) { | ||
8491 | i += LOG_BASE; | ||
8492 | j = sd; | ||
8493 | n = xc[ ni = 0 ]; | ||
8494 | |||
8495 | // Get the rounding digit at index j of n. | ||
8496 | rd = n / pows10[ d - j - 1 ] % 10 | 0; | ||
8497 | } else { | ||
8498 | ni = mathceil( ( i + 1 ) / LOG_BASE ); | ||
8499 | |||
8500 | if ( ni >= xc.length ) { | ||
8501 | |||
8502 | if (r) { | ||
8503 | |||
8504 | // Needed by sqrt. | ||
8505 | for ( ; xc.length <= ni; xc.push(0) ); | ||
8506 | n = rd = 0; | ||
8507 | d = 1; | ||
8508 | i %= LOG_BASE; | ||
8509 | j = i - LOG_BASE + 1; | ||
8510 | } else { | ||
8511 | break out; | ||
8512 | } | ||
8513 | } else { | ||
8514 | n = k = xc[ni]; | ||
8515 | |||
8516 | // Get the number of digits of n. | ||
8517 | for ( d = 1; k >= 10; k /= 10, d++ ); | ||
8518 | |||
8519 | // Get the index of rd within n. | ||
8520 | i %= LOG_BASE; | ||
8521 | |||
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; | ||
8525 | |||
8526 | // Get the rounding digit at index j of n. | ||
8527 | rd = j < 0 ? 0 : n / pows10[ d - j - 1 ] % 10 | 0; | ||
8528 | } | ||
8529 | } | ||
8530 | |||
8531 | r = r || sd < 0 || | ||
8532 | |||
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 ] ); | ||
8537 | |||
8538 | r = rm < 4 | ||
8539 | ? ( rd || r ) && ( rm == 0 || rm == ( x.s < 0 ? 3 : 2 ) ) | ||
8540 | : rd > 5 || rd == 5 && ( rm == 4 || r || rm == 6 && | ||
8541 | |||
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 ) ); | ||
8545 | |||
8546 | if ( sd < 1 || !xc[0] ) { | ||
8547 | xc.length = 0; | ||
8548 | |||
8549 | if (r) { | ||
8550 | |||
8551 | // Convert sd to decimal places. | ||
8552 | sd -= x.e + 1; | ||
8553 | |||
8554 | // 1, 0.1, 0.01, 0.001, 0.0001 etc. | ||
8555 | xc[0] = pows10[ ( LOG_BASE - sd % LOG_BASE ) % LOG_BASE ]; | ||
8556 | x.e = -sd || 0; | ||
8557 | } else { | ||
8558 | |||
8559 | // Zero. | ||
8560 | xc[0] = x.e = 0; | ||
8561 | } | ||
8562 | |||
8563 | return x; | ||
8564 | } | ||
8565 | |||
8566 | // Remove excess digits. | ||
8567 | if ( i == 0 ) { | ||
8568 | xc.length = ni; | ||
8569 | k = 1; | ||
8570 | ni--; | ||
8571 | } else { | ||
8572 | xc.length = ni + 1; | ||
8573 | k = pows10[ LOG_BASE - i ]; | ||
8574 | |||
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; | ||
8578 | } | ||
8579 | |||
8580 | // Round up? | ||
8581 | if (r) { | ||
8582 | |||
8583 | for ( ; ; ) { | ||
8584 | |||
8585 | // If the digit to be rounded up is in the first element of xc... | ||
8586 | if ( ni == 0 ) { | ||
8587 | |||
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++ ); | ||
8590 | j = xc[0] += k; | ||
8591 | for ( k = 1; j >= 10; j /= 10, k++ ); | ||
8592 | |||
8593 | // if i != k the length has increased. | ||
8594 | if ( i != k ) { | ||
8595 | x.e++; | ||
8596 | if ( xc[0] == BASE ) xc[0] = 1; | ||
8597 | } | ||
8598 | |||
8599 | break; | ||
8600 | } else { | ||
8601 | xc[ni] += k; | ||
8602 | if ( xc[ni] != BASE ) break; | ||
8603 | xc[ni--] = 0; | ||
8604 | k = 1; | ||
8605 | } | ||
8606 | } | ||
8607 | } | ||
8608 | |||
8609 | // Remove trailing zeros. | ||
8610 | for ( i = xc.length; xc[--i] === 0; xc.pop() ); | ||
8611 | } | ||
8612 | |||
8613 | // Overflow? Infinity. | ||
8614 | if ( x.e > MAX_EXP ) { | ||
8615 | x.c = x.e = null; | ||
8616 | |||
8617 | // Underflow? Zero. | ||
8618 | } else if ( x.e < MIN_EXP ) { | ||
8619 | x.c = [ x.e = 0 ]; | ||
8620 | } | ||
8621 | } | ||
8622 | |||
8623 | return x; | ||
8624 | } | ||
8625 | |||
8626 | |||
8627 | // PROTOTYPE/INSTANCE METHODS | ||
8628 | |||
8629 | |||
8630 | /* | ||
8631 | * Return a new BigNumber whose value is the absolute value of this BigNumber. | ||
8632 | */ | ||
8633 | P.absoluteValue = P.abs = function () { | ||
8634 | var x = new BigNumber(this); | ||
8635 | if ( x.s < 0 ) x.s = 1; | ||
8636 | return x; | ||
8637 | }; | ||
8638 | |||
8639 | |||
8640 | /* | ||
8641 | * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole | ||
8642 | * number in the direction of Infinity. | ||
8643 | */ | ||
8644 | P.ceil = function () { | ||
8645 | return round( new BigNumber(this), this.e + 1, 2 ); | ||
8646 | }; | ||
8647 | |||
8648 | |||
8649 | /* | ||
8650 | * Return | ||
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. | ||
8655 | */ | ||
8656 | P.comparedTo = P.cmp = function ( y, b ) { | ||
8657 | id = 1; | ||
8658 | return compare( this, new BigNumber( y, b ) ); | ||
8659 | }; | ||
8660 | |||
8661 | |||
8662 | /* | ||
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. | ||
8665 | */ | ||
8666 | P.decimalPlaces = P.dp = function () { | ||
8667 | var n, v, | ||
8668 | c = this.c; | ||
8669 | |||
8670 | if ( !c ) return null; | ||
8671 | n = ( ( v = c.length - 1 ) - bitFloor( this.e / LOG_BASE ) ) * LOG_BASE; | ||
8672 | |||
8673 | // Subtract the number of trailing zeros of the last number. | ||
8674 | if ( v = c[v] ) for ( ; v % 10 == 0; v /= 10, n-- ); | ||
8675 | if ( n < 0 ) n = 0; | ||
8676 | |||
8677 | return n; | ||
8678 | }; | ||
8679 | |||
8680 | |||
8681 | /* | ||
8682 | * n / 0 = I | ||
8683 | * n / N = N | ||
8684 | * n / I = 0 | ||
8685 | * 0 / n = 0 | ||
8686 | * 0 / 0 = N | ||
8687 | * 0 / N = N | ||
8688 | * 0 / I = 0 | ||
8689 | * N / n = N | ||
8690 | * N / 0 = N | ||
8691 | * N / N = N | ||
8692 | * N / I = N | ||
8693 | * I / n = I | ||
8694 | * I / 0 = I | ||
8695 | * I / N = N | ||
8696 | * I / I = N | ||
8697 | * | ||
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. | ||
8700 | */ | ||
8701 | P.dividedBy = P.div = function ( y, b ) { | ||
8702 | id = 3; | ||
8703 | return div( this, new BigNumber( y, b ), DECIMAL_PLACES, ROUNDING_MODE ); | ||
8704 | }; | ||
8705 | |||
8706 | |||
8707 | /* | ||
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). | ||
8710 | */ | ||
8711 | P.dividedToIntegerBy = P.divToInt = function ( y, b ) { | ||
8712 | id = 4; | ||
8713 | return div( this, new BigNumber( y, b ), 0, 1 ); | ||
8714 | }; | ||
8715 | |||
8716 | |||
8717 | /* | ||
8718 | * Return true if the value of this BigNumber is equal to the value of BigNumber(y, b), | ||
8719 | * otherwise returns false. | ||
8720 | */ | ||
8721 | P.equals = P.eq = function ( y, b ) { | ||
8722 | id = 5; | ||
8723 | return compare( this, new BigNumber( y, b ) ) === 0; | ||
8724 | }; | ||
8725 | |||
8726 | |||
8727 | /* | ||
8728 | * Return a new BigNumber whose value is the value of this BigNumber rounded to a whole | ||
8729 | * number in the direction of -Infinity. | ||
8730 | */ | ||
8731 | P.floor = function () { | ||
8732 | return round( new BigNumber(this), this.e + 1, 3 ); | ||
8733 | }; | ||
8734 | |||
8735 | |||
8736 | /* | ||
8737 | * Return true if the value of this BigNumber is greater than the value of BigNumber(y, b), | ||
8738 | * otherwise returns false. | ||
8739 | */ | ||
8740 | P.greaterThan = P.gt = function ( y, b ) { | ||
8741 | id = 6; | ||
8742 | return compare( this, new BigNumber( y, b ) ) > 0; | ||
8743 | }; | ||
8744 | |||
8745 | |||
8746 | /* | ||
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. | ||
8749 | */ | ||
8750 | P.greaterThanOrEqualTo = P.gte = function ( y, b ) { | ||
8751 | id = 7; | ||
8752 | return ( b = compare( this, new BigNumber( y, b ) ) ) === 1 || b === 0; | ||
8753 | |||
8754 | }; | ||
8755 | |||
8756 | |||
8757 | /* | ||
8758 | * Return true if the value of this BigNumber is a finite number, otherwise returns false. | ||
8759 | */ | ||
8760 | P.isFinite = function () { | ||
8761 | return !!this.c; | ||
8762 | }; | ||
8763 | |||
8764 | |||
8765 | /* | ||
8766 | * Return true if the value of this BigNumber is an integer, otherwise return false. | ||
8767 | */ | ||
8768 | P.isInteger = P.isInt = function () { | ||
8769 | return !!this.c && bitFloor( this.e / LOG_BASE ) > this.c.length - 2; | ||
8770 | }; | ||
8771 | |||
8772 | |||
8773 | /* | ||
8774 | * Return true if the value of this BigNumber is NaN, otherwise returns false. | ||
8775 | */ | ||
8776 | P.isNaN = function () { | ||
8777 | return !this.s; | ||
8778 | }; | ||
8779 | |||
8780 | |||
8781 | /* | ||
8782 | * Return true if the value of this BigNumber is negative, otherwise returns false. | ||
8783 | */ | ||
8784 | P.isNegative = P.isNeg = function () { | ||
8785 | return this.s < 0; | ||
8786 | }; | ||
8787 | |||
8788 | |||
8789 | /* | ||
8790 | * Return true if the value of this BigNumber is 0 or -0, otherwise returns false. | ||
8791 | */ | ||
8792 | P.isZero = function () { | ||
8793 | return !!this.c && this.c[0] == 0; | ||
8794 | }; | ||
8795 | |||
8796 | |||
8797 | /* | ||
8798 | * Return true if the value of this BigNumber is less than the value of BigNumber(y, b), | ||
8799 | * otherwise returns false. | ||
8800 | */ | ||
8801 | P.lessThan = P.lt = function ( y, b ) { | ||
8802 | id = 8; | ||
8803 | return compare( this, new BigNumber( y, b ) ) < 0; | ||
8804 | }; | ||
8805 | |||
8806 | |||
8807 | /* | ||
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. | ||
8810 | */ | ||
8811 | P.lessThanOrEqualTo = P.lte = function ( y, b ) { | ||
8812 | id = 9; | ||
8813 | return ( b = compare( this, new BigNumber( y, b ) ) ) === -1 || b === 0; | ||
8814 | }; | ||
8815 | |||
8816 | |||
8817 | /* | ||
8818 | * n - 0 = n | ||
8819 | * n - N = N | ||
8820 | * n - I = -I | ||
8821 | * 0 - n = -n | ||
8822 | * 0 - 0 = 0 | ||
8823 | * 0 - N = N | ||
8824 | * 0 - I = -I | ||
8825 | * N - n = N | ||
8826 | * N - 0 = N | ||
8827 | * N - N = N | ||
8828 | * N - I = N | ||
8829 | * I - n = I | ||
8830 | * I - 0 = I | ||
8831 | * I - N = N | ||
8832 | * I - I = N | ||
8833 | * | ||
8834 | * Return a new BigNumber whose value is the value of this BigNumber minus the value of | ||
8835 | * BigNumber(y, b). | ||
8836 | */ | ||
8837 | P.minus = P.sub = function ( y, b ) { | ||
8838 | var i, j, t, xLTy, | ||
8839 | x = this, | ||
8840 | a = x.s; | ||
8841 | |||
8842 | id = 10; | ||
8843 | y = new BigNumber( y, b ); | ||
8844 | b = y.s; | ||
8845 | |||
8846 | // Either NaN? | ||
8847 | if ( !a || !b ) return new BigNumber(NaN); | ||
8848 | |||
8849 | // Signs differ? | ||
8850 | if ( a != b ) { | ||
8851 | y.s = -b; | ||
8852 | return x.plus(y); | ||
8853 | } | ||
8854 | |||
8855 | var xe = x.e / LOG_BASE, | ||
8856 | ye = y.e / LOG_BASE, | ||
8857 | xc = x.c, | ||
8858 | yc = y.c; | ||
8859 | |||
8860 | if ( !xe || !ye ) { | ||
8861 | |||
8862 | // Either Infinity? | ||
8863 | if ( !xc || !yc ) return xc ? ( y.s = -b, y ) : new BigNumber( yc ? x : NaN ); | ||
8864 | |||
8865 | // Either zero? | ||
8866 | if ( !xc[0] || !yc[0] ) { | ||
8867 | |||
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 : | ||
8870 | |||
8871 | // IEEE 754 (2008) 6.3: n - n = -0 when rounding to -Infinity | ||
8872 | ROUNDING_MODE == 3 ? -0 : 0 ); | ||
8873 | } | ||
8874 | } | ||
8875 | |||
8876 | xe = bitFloor(xe); | ||
8877 | ye = bitFloor(ye); | ||
8878 | xc = xc.slice(); | ||
8879 | |||
8880 | // Determine which is the bigger number. | ||
8881 | if ( a = xe - ye ) { | ||
8882 | |||
8883 | if ( xLTy = a < 0 ) { | ||
8884 | a = -a; | ||
8885 | t = xc; | ||
8886 | } else { | ||
8887 | ye = xe; | ||
8888 | t = yc; | ||
8889 | } | ||
8890 | |||
8891 | t.reverse(); | ||
8892 | |||
8893 | // Prepend zeros to equalise exponents. | ||
8894 | for ( b = a; b--; t.push(0) ); | ||
8895 | t.reverse(); | ||
8896 | } else { | ||
8897 | |||
8898 | // Exponents equal. Check digit by digit. | ||
8899 | j = ( xLTy = ( a = xc.length ) < ( b = yc.length ) ) ? a : b; | ||
8900 | |||
8901 | for ( a = b = 0; b < j; b++ ) { | ||
8902 | |||
8903 | if ( xc[b] != yc[b] ) { | ||
8904 | xLTy = xc[b] < yc[b]; | ||
8905 | break; | ||
8906 | } | ||
8907 | } | ||
8908 | } | ||
8909 | |||
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; | ||
8912 | |||
8913 | b = ( j = yc.length ) - ( i = xc.length ); | ||
8914 | |||
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 ); | ||
8918 | b = BASE - 1; | ||
8919 | |||
8920 | // Subtract yc from xc. | ||
8921 | for ( ; j > a; ) { | ||
8922 | |||
8923 | if ( xc[--j] < yc[j] ) { | ||
8924 | for ( i = j; i && !xc[--i]; xc[i] = b ); | ||
8925 | --xc[i]; | ||
8926 | xc[j] += BASE; | ||
8927 | } | ||
8928 | |||
8929 | xc[j] -= yc[j]; | ||
8930 | } | ||
8931 | |||
8932 | // Remove leading zeros and adjust exponent accordingly. | ||
8933 | for ( ; xc[0] == 0; xc.splice(0, 1), --ye ); | ||
8934 | |||
8935 | // Zero? | ||
8936 | if ( !xc[0] ) { | ||
8937 | |||
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; | ||
8941 | y.c = [ y.e = 0 ]; | ||
8942 | return y; | ||
8943 | } | ||
8944 | |||
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 ); | ||
8948 | }; | ||
8949 | |||
8950 | |||
8951 | /* | ||
8952 | * n % 0 = N | ||
8953 | * n % N = N | ||
8954 | * n % I = n | ||
8955 | * 0 % n = 0 | ||
8956 | * -0 % n = -0 | ||
8957 | * 0 % 0 = N | ||
8958 | * 0 % N = N | ||
8959 | * 0 % I = 0 | ||
8960 | * N % n = N | ||
8961 | * N % 0 = N | ||
8962 | * N % N = N | ||
8963 | * N % I = N | ||
8964 | * I % n = N | ||
8965 | * I % 0 = N | ||
8966 | * I % N = N | ||
8967 | * I % I = N | ||
8968 | * | ||
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. | ||
8971 | */ | ||
8972 | P.modulo = P.mod = function ( y, b ) { | ||
8973 | var q, s, | ||
8974 | x = this; | ||
8975 | |||
8976 | id = 11; | ||
8977 | y = new BigNumber( y, b ); | ||
8978 | |||
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); | ||
8982 | |||
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); | ||
8986 | } | ||
8987 | |||
8988 | if ( MODULO_MODE == 9 ) { | ||
8989 | |||
8990 | // Euclidian division: q = sign(y) * floor(x / abs(y)) | ||
8991 | // r = x - qy where 0 <= r < abs(y) | ||
8992 | s = y.s; | ||
8993 | y.s = 1; | ||
8994 | q = div( x, y, 0, 3 ); | ||
8995 | y.s = s; | ||
8996 | q.s *= s; | ||
8997 | } else { | ||
8998 | q = div( x, y, 0, MODULO_MODE ); | ||
8999 | } | ||
9000 | |||
9001 | return x.minus( q.times(y) ); | ||
9002 | }; | ||
9003 | |||
9004 | |||
9005 | /* | ||
9006 | * Return a new BigNumber whose value is the value of this BigNumber negated, | ||
9007 | * i.e. multiplied by -1. | ||
9008 | */ | ||
9009 | P.negated = P.neg = function () { | ||
9010 | var x = new BigNumber(this); | ||
9011 | x.s = -x.s || null; | ||
9012 | return x; | ||
9013 | }; | ||
9014 | |||
9015 | |||
9016 | /* | ||
9017 | * n + 0 = n | ||
9018 | * n + N = N | ||
9019 | * n + I = I | ||
9020 | * 0 + n = n | ||
9021 | * 0 + 0 = 0 | ||
9022 | * 0 + N = N | ||
9023 | * 0 + I = I | ||
9024 | * N + n = N | ||
9025 | * N + 0 = N | ||
9026 | * N + N = N | ||
9027 | * N + I = N | ||
9028 | * I + n = I | ||
9029 | * I + 0 = I | ||
9030 | * I + N = N | ||
9031 | * I + I = I | ||
9032 | * | ||
9033 | * Return a new BigNumber whose value is the value of this BigNumber plus the value of | ||
9034 | * BigNumber(y, b). | ||
9035 | */ | ||
9036 | P.plus = P.add = function ( y, b ) { | ||
9037 | var t, | ||
9038 | x = this, | ||
9039 | a = x.s; | ||
9040 | |||
9041 | id = 12; | ||
9042 | y = new BigNumber( y, b ); | ||
9043 | b = y.s; | ||
9044 | |||
9045 | // Either NaN? | ||
9046 | if ( !a || !b ) return new BigNumber(NaN); | ||
9047 | |||
9048 | // Signs differ? | ||
9049 | if ( a != b ) { | ||
9050 | y.s = -b; | ||
9051 | return x.minus(y); | ||
9052 | } | ||
9053 | |||
9054 | var xe = x.e / LOG_BASE, | ||
9055 | ye = y.e / LOG_BASE, | ||
9056 | xc = x.c, | ||
9057 | yc = y.c; | ||
9058 | |||
9059 | if ( !xe || !ye ) { | ||
9060 | |||
9061 | // Return ±Infinity if either ±Infinity. | ||
9062 | if ( !xc || !yc ) return new BigNumber( a / 0 ); | ||
9063 | |||
9064 | // Either zero? | ||
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 ); | ||
9067 | } | ||
9068 | |||
9069 | xe = bitFloor(xe); | ||
9070 | ye = bitFloor(ye); | ||
9071 | xc = xc.slice(); | ||
9072 | |||
9073 | // Prepend zeros to equalise exponents. Faster to use reverse then do unshifts. | ||
9074 | if ( a = xe - ye ) { | ||
9075 | if ( a > 0 ) { | ||
9076 | ye = xe; | ||
9077 | t = yc; | ||
9078 | } else { | ||
9079 | a = -a; | ||
9080 | t = xc; | ||
9081 | } | ||
9082 | |||
9083 | t.reverse(); | ||
9084 | for ( ; a--; t.push(0) ); | ||
9085 | t.reverse(); | ||
9086 | } | ||
9087 | |||
9088 | a = xc.length; | ||
9089 | b = yc.length; | ||
9090 | |||
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; | ||
9093 | |||
9094 | // Only start adding at yc.length - 1 as the further digits of xc can be ignored. | ||
9095 | for ( a = 0; b; ) { | ||
9096 | a = ( xc[--b] = xc[b] + yc[b] + a ) / BASE | 0; | ||
9097 | xc[b] = BASE === xc[b] ? 0 : xc[b] % BASE; | ||
9098 | } | ||
9099 | |||
9100 | if (a) { | ||
9101 | xc = [a].concat(xc); | ||
9102 | ++ye; | ||
9103 | } | ||
9104 | |||
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 ); | ||
9108 | }; | ||
9109 | |||
9110 | |||
9111 | /* | ||
9112 | * Return the number of significant digits of the value of this BigNumber. | ||
9113 | * | ||
9114 | * [z] {boolean|number} Whether to count integer-part trailing zeros: true, false, 1 or 0. | ||
9115 | */ | ||
9116 | P.precision = P.sd = function (z) { | ||
9117 | var n, v, | ||
9118 | x = this, | ||
9119 | c = x.c; | ||
9120 | |||
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; | ||
9125 | } | ||
9126 | |||
9127 | if ( !c ) return null; | ||
9128 | v = c.length - 1; | ||
9129 | n = v * LOG_BASE + 1; | ||
9130 | |||
9131 | if ( v = c[v] ) { | ||
9132 | |||
9133 | // Subtract the number of trailing zeros of the last element. | ||
9134 | for ( ; v % 10 == 0; v /= 10, n-- ); | ||
9135 | |||
9136 | // Add the number of digits of the first element. | ||
9137 | for ( v = c[0]; v >= 10; v /= 10, n++ ); | ||
9138 | } | ||
9139 | |||
9140 | if ( z && x.e + 1 > n ) n = x.e + 1; | ||
9141 | |||
9142 | return n; | ||
9143 | }; | ||
9144 | |||
9145 | |||
9146 | /* | ||
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 | ||
9149 | * omitted. | ||
9150 | * | ||
9151 | * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. | ||
9152 | * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. | ||
9153 | * | ||
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}' | ||
9158 | */ | ||
9159 | P.round = function ( dp, rm ) { | ||
9160 | var n = new BigNumber(this); | ||
9161 | |||
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 ); | ||
9165 | } | ||
9166 | |||
9167 | return n; | ||
9168 | }; | ||
9169 | |||
9170 | |||
9171 | /* | ||
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. | ||
9174 | * | ||
9175 | * k {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. | ||
9176 | * | ||
9177 | * If k is out of range and ERRORS is false, the result will be ±0 if k < 0, or ±Infinity | ||
9178 | * otherwise. | ||
9179 | * | ||
9180 | * 'shift() argument not an integer: {k}' | ||
9181 | * 'shift() argument out of range: {k}' | ||
9182 | */ | ||
9183 | P.shift = function (k) { | ||
9184 | var n = this; | ||
9185 | return isValidInt( k, -MAX_SAFE_INTEGER, MAX_SAFE_INTEGER, 16, 'argument' ) | ||
9186 | |||
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 ) | ||
9191 | : n ); | ||
9192 | }; | ||
9193 | |||
9194 | |||
9195 | /* | ||
9196 | * sqrt(-n) = N | ||
9197 | * sqrt( N) = N | ||
9198 | * sqrt(-I) = N | ||
9199 | * sqrt( I) = I | ||
9200 | * sqrt( 0) = 0 | ||
9201 | * sqrt(-0) = -0 | ||
9202 | * | ||
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. | ||
9205 | */ | ||
9206 | P.squareRoot = P.sqrt = function () { | ||
9207 | var m, n, r, rep, t, | ||
9208 | x = this, | ||
9209 | c = x.c, | ||
9210 | s = x.s, | ||
9211 | e = x.e, | ||
9212 | dp = DECIMAL_PLACES + 4, | ||
9213 | half = new BigNumber('0.5'); | ||
9214 | |||
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 ); | ||
9218 | } | ||
9219 | |||
9220 | // Initial estimate. | ||
9221 | s = Math.sqrt( +x ); | ||
9222 | |||
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'; | ||
9228 | s = Math.sqrt(n); | ||
9229 | e = bitFloor( ( e + 1 ) / 2 ) - ( e < 0 || e % 2 ); | ||
9230 | |||
9231 | if ( s == 1 / 0 ) { | ||
9232 | n = '1e' + e; | ||
9233 | } else { | ||
9234 | n = s.toExponential(); | ||
9235 | n = n.slice( 0, n.indexOf('e') + 1 ) + e; | ||
9236 | } | ||
9237 | |||
9238 | r = new BigNumber(n); | ||
9239 | } else { | ||
9240 | r = new BigNumber( s + '' ); | ||
9241 | } | ||
9242 | |||
9243 | // Check for zero. | ||
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. | ||
9247 | if ( r.c[0] ) { | ||
9248 | e = r.e; | ||
9249 | s = e + dp; | ||
9250 | if ( s < 3 ) s = 0; | ||
9251 | |||
9252 | // Newton-Raphson iteration. | ||
9253 | for ( ; ; ) { | ||
9254 | t = r; | ||
9255 | r = half.times( t.plus( div( x, t, dp, 1 ) ) ); | ||
9256 | |||
9257 | if ( coeffToString( t.c ).slice( 0, s ) === ( n = | ||
9258 | coeffToString( r.c ) ).slice( 0, s ) ) { | ||
9259 | |||
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. | ||
9263 | if ( r.e < e ) --s; | ||
9264 | n = n.slice( s - 3, s + 1 ); | ||
9265 | |||
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 | ||
9268 | // iteration. | ||
9269 | if ( n == '9999' || !rep && n == '4999' ) { | ||
9270 | |||
9271 | // On the first iteration only, check to see if rounding up gives the | ||
9272 | // exact result as the nines may infinitely repeat. | ||
9273 | if ( !rep ) { | ||
9274 | round( t, t.e + DECIMAL_PLACES + 2, 0 ); | ||
9275 | |||
9276 | if ( t.times(t).eq(x) ) { | ||
9277 | r = t; | ||
9278 | break; | ||
9279 | } | ||
9280 | } | ||
9281 | |||
9282 | dp += 4; | ||
9283 | s += 4; | ||
9284 | rep = 1; | ||
9285 | } else { | ||
9286 | |||
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' ) { | ||
9290 | |||
9291 | // Truncate to the first rounding digit. | ||
9292 | round( r, r.e + DECIMAL_PLACES + 2, 1 ); | ||
9293 | m = !r.times(r).eq(x); | ||
9294 | } | ||
9295 | |||
9296 | break; | ||
9297 | } | ||
9298 | } | ||
9299 | } | ||
9300 | } | ||
9301 | |||
9302 | return round( r, r.e + DECIMAL_PLACES + 1, ROUNDING_MODE, m ); | ||
9303 | }; | ||
9304 | |||
9305 | |||
9306 | /* | ||
9307 | * n * 0 = 0 | ||
9308 | * n * N = N | ||
9309 | * n * I = I | ||
9310 | * 0 * n = 0 | ||
9311 | * 0 * 0 = 0 | ||
9312 | * 0 * N = N | ||
9313 | * 0 * I = N | ||
9314 | * N * n = N | ||
9315 | * N * 0 = N | ||
9316 | * N * N = N | ||
9317 | * N * I = N | ||
9318 | * I * n = I | ||
9319 | * I * 0 = N | ||
9320 | * I * N = N | ||
9321 | * I * I = I | ||
9322 | * | ||
9323 | * Return a new BigNumber whose value is the value of this BigNumber times the value of | ||
9324 | * BigNumber(y, b). | ||
9325 | */ | ||
9326 | P.times = P.mul = function ( y, b ) { | ||
9327 | var c, e, i, j, k, m, xcL, xlo, xhi, ycL, ylo, yhi, zc, | ||
9328 | base, sqrtBase, | ||
9329 | x = this, | ||
9330 | xc = x.c, | ||
9331 | yc = ( id = 17, y = new BigNumber( y, b ) ).c; | ||
9332 | |||
9333 | // Either NaN, ±Infinity or ±0? | ||
9334 | if ( !xc || !yc || !xc[0] || !yc[0] ) { | ||
9335 | |||
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; | ||
9339 | } else { | ||
9340 | y.s *= x.s; | ||
9341 | |||
9342 | // Return ±Infinity if either is ±Infinity. | ||
9343 | if ( !xc || !yc ) { | ||
9344 | y.c = y.e = null; | ||
9345 | |||
9346 | // Return ±0 if either is ±0. | ||
9347 | } else { | ||
9348 | y.c = [0]; | ||
9349 | y.e = 0; | ||
9350 | } | ||
9351 | } | ||
9352 | |||
9353 | return y; | ||
9354 | } | ||
9355 | |||
9356 | e = bitFloor( x.e / LOG_BASE ) + bitFloor( y.e / LOG_BASE ); | ||
9357 | y.s *= x.s; | ||
9358 | xcL = xc.length; | ||
9359 | ycL = yc.length; | ||
9360 | |||
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; | ||
9363 | |||
9364 | // Initialise the result array with zeros. | ||
9365 | for ( i = xcL + ycL, zc = []; i--; zc.push(0) ); | ||
9366 | |||
9367 | base = BASE; | ||
9368 | sqrtBase = SQRT_BASE; | ||
9369 | |||
9370 | for ( i = ycL; --i >= 0; ) { | ||
9371 | c = 0; | ||
9372 | ylo = yc[i] % sqrtBase; | ||
9373 | yhi = yc[i] / sqrtBase | 0; | ||
9374 | |||
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; | ||
9382 | } | ||
9383 | |||
9384 | zc[j] = c; | ||
9385 | } | ||
9386 | |||
9387 | if (c) { | ||
9388 | ++e; | ||
9389 | } else { | ||
9390 | zc.splice(0, 1); | ||
9391 | } | ||
9392 | |||
9393 | return normalise( y, zc, e ); | ||
9394 | }; | ||
9395 | |||
9396 | |||
9397 | /* | ||
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. | ||
9400 | * | ||
9401 | * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. | ||
9402 | * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. | ||
9403 | * | ||
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}' | ||
9408 | */ | ||
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; | ||
9414 | }; | ||
9415 | |||
9416 | |||
9417 | /* | ||
9418 | * Return a string representing the value of this BigNumber in exponential notation and | ||
9419 | * rounded using ROUNDING_MODE to dp fixed decimal places. | ||
9420 | * | ||
9421 | * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. | ||
9422 | * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. | ||
9423 | * | ||
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}' | ||
9428 | */ | ||
9429 | P.toExponential = function ( dp, rm ) { | ||
9430 | return format( this, | ||
9431 | dp != null && isValidInt( dp, 0, MAX, 19 ) ? ~~dp + 1 : null, rm, 19 ); | ||
9432 | }; | ||
9433 | |||
9434 | |||
9435 | /* | ||
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. | ||
9438 | * | ||
9439 | * Note: as with JavaScript's number type, (-0).toFixed(0) is '0', | ||
9440 | * but e.g. (-0.00001).toFixed(0) is '-0'. | ||
9441 | * | ||
9442 | * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. | ||
9443 | * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. | ||
9444 | * | ||
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}' | ||
9449 | */ | ||
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 ); | ||
9453 | }; | ||
9454 | |||
9455 | |||
9456 | /* | ||
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). | ||
9460 | * | ||
9461 | * FORMAT = { | ||
9462 | * decimalSeparator : '.', | ||
9463 | * groupSeparator : ',', | ||
9464 | * groupSize : 3, | ||
9465 | * secondaryGroupSize : 0, | ||
9466 | * fractionGroupSeparator : '\xA0', // non-breaking space | ||
9467 | * fractionGroupSize : 0 | ||
9468 | * }; | ||
9469 | * | ||
9470 | * [dp] {number} Decimal places. Integer, 0 to MAX inclusive. | ||
9471 | * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. | ||
9472 | * | ||
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}' | ||
9477 | */ | ||
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 ); | ||
9481 | |||
9482 | if ( this.c ) { | ||
9483 | var i, | ||
9484 | arr = str.split('.'), | ||
9485 | g1 = +FORMAT.groupSize, | ||
9486 | g2 = +FORMAT.secondaryGroupSize, | ||
9487 | groupSeparator = FORMAT.groupSeparator, | ||
9488 | intPart = arr[0], | ||
9489 | fractionPart = arr[1], | ||
9490 | isNeg = this.s < 0, | ||
9491 | intDigits = isNeg ? intPart.slice(1) : intPart, | ||
9492 | len = intDigits.length; | ||
9493 | |||
9494 | if (g2) i = g1, g1 = g2, g2 = i, len -= i; | ||
9495 | |||
9496 | if ( g1 > 0 && len > 0 ) { | ||
9497 | i = len % g1 || g1; | ||
9498 | intPart = intDigits.substr( 0, i ); | ||
9499 | |||
9500 | for ( ; i < len; i += g1 ) { | ||
9501 | intPart += groupSeparator + intDigits.substr( i, g1 ); | ||
9502 | } | ||
9503 | |||
9504 | if ( g2 > 0 ) intPart += groupSeparator + intDigits.slice(i); | ||
9505 | if (isNeg) intPart = '-' + intPart; | ||
9506 | } | ||
9507 | |||
9508 | str = fractionPart | ||
9509 | ? intPart + FORMAT.decimalSeparator + ( ( g2 = +FORMAT.fractionGroupSize ) | ||
9510 | ? fractionPart.replace( new RegExp( '\\d{' + g2 + '}\\B', 'g' ), | ||
9511 | '$&' + FORMAT.fractionGroupSeparator ) | ||
9512 | : fractionPart ) | ||
9513 | : intPart; | ||
9514 | } | ||
9515 | |||
9516 | return str; | ||
9517 | }; | ||
9518 | |||
9519 | |||
9520 | /* | ||
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. | ||
9526 | * | ||
9527 | * [md] {number|string|BigNumber} Integer >= 1 and < Infinity. The maximum denominator. | ||
9528 | * | ||
9529 | * 'toFraction() max denominator not an integer: {md}' | ||
9530 | * 'toFraction() max denominator out of range: {md}' | ||
9531 | */ | ||
9532 | P.toFraction = function (md) { | ||
9533 | var arr, d0, d2, e, exp, n, n0, q, s, | ||
9534 | k = ERRORS, | ||
9535 | x = this, | ||
9536 | xc = x.c, | ||
9537 | d = new BigNumber(ONE), | ||
9538 | n1 = d0 = new BigNumber(ONE), | ||
9539 | d1 = n0 = new BigNumber(ONE); | ||
9540 | |||
9541 | if ( md != null ) { | ||
9542 | ERRORS = false; | ||
9543 | n = new BigNumber(md); | ||
9544 | ERRORS = k; | ||
9545 | |||
9546 | if ( !( k = n.isInt() ) || n.lt(ONE) ) { | ||
9547 | |||
9548 | if (ERRORS) { | ||
9549 | raise( 22, | ||
9550 | 'max denominator ' + ( k ? 'out of range' : 'not an integer' ), md ); | ||
9551 | } | ||
9552 | |||
9553 | // ERRORS is false: | ||
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; | ||
9556 | } | ||
9557 | } | ||
9558 | |||
9559 | if ( !xc ) return x.toString(); | ||
9560 | s = coeffToString(xc); | ||
9561 | |||
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; | ||
9567 | |||
9568 | exp = MAX_EXP; | ||
9569 | MAX_EXP = 1 / 0; | ||
9570 | n = new BigNumber(s); | ||
9571 | |||
9572 | // n0 = d1 = 0 | ||
9573 | n0.c[0] = 0; | ||
9574 | |||
9575 | for ( ; ; ) { | ||
9576 | q = div( n, d, 0, 1 ); | ||
9577 | d2 = d0.plus( q.times(d1) ); | ||
9578 | if ( d2.cmp(md) == 1 ) break; | ||
9579 | d0 = d1; | ||
9580 | d1 = d2; | ||
9581 | n1 = n0.plus( q.times( d2 = n1 ) ); | ||
9582 | n0 = d2; | ||
9583 | d = n.minus( q.times( d2 = d ) ); | ||
9584 | n = d2; | ||
9585 | } | ||
9586 | |||
9587 | d2 = div( md.minus(d0), d1, 0, 1 ); | ||
9588 | n0 = n0.plus( d2.times(n1) ); | ||
9589 | d0 = d0.plus( d2.times(d1) ); | ||
9590 | n0.s = n1.s = x.s; | ||
9591 | e *= 2; | ||
9592 | |||
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() ]; | ||
9598 | |||
9599 | MAX_EXP = exp; | ||
9600 | return arr; | ||
9601 | }; | ||
9602 | |||
9603 | |||
9604 | /* | ||
9605 | * Return the value of this BigNumber converted to a number primitive. | ||
9606 | */ | ||
9607 | P.toNumber = function () { | ||
9608 | return +this; | ||
9609 | }; | ||
9610 | |||
9611 | |||
9612 | /* | ||
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 | ||
9617 | * ROUNDING_MODE. | ||
9618 | * | ||
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). | ||
9621 | * | ||
9622 | * n {number} Integer, -MAX_SAFE_INTEGER to MAX_SAFE_INTEGER inclusive. | ||
9623 | * [m] {number|string|BigNumber} The modulus. | ||
9624 | * | ||
9625 | * 'pow() exponent not an integer: {n}' | ||
9626 | * 'pow() exponent out of range: {n}' | ||
9627 | * | ||
9628 | * Performs 54 loop iterations for n of 9007199254740991. | ||
9629 | */ | ||
9630 | P.toPower = P.pow = function ( n, m ) { | ||
9631 | var k, y, z, | ||
9632 | i = mathfloor( n < 0 ? -n : +n ), | ||
9633 | x = this; | ||
9634 | |||
9635 | if ( m != null ) { | ||
9636 | id = 23; | ||
9637 | m = new BigNumber(m); | ||
9638 | } | ||
9639 | |||
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 ); | ||
9646 | } | ||
9647 | |||
9648 | if (m) { | ||
9649 | if ( n > 1 && x.gt(ONE) && x.isInt() && m.gt(ONE) && m.isInt() ) { | ||
9650 | x = x.mod(m); | ||
9651 | } else { | ||
9652 | z = m; | ||
9653 | |||
9654 | // Nullify m so only a single mod operation is performed at the end. | ||
9655 | m = null; | ||
9656 | } | ||
9657 | } else if (POW_PRECISION) { | ||
9658 | |||
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 ); | ||
9664 | } | ||
9665 | |||
9666 | y = new BigNumber(ONE); | ||
9667 | |||
9668 | for ( ; ; ) { | ||
9669 | if ( i % 2 ) { | ||
9670 | y = y.times(x); | ||
9671 | if ( !y.c ) break; | ||
9672 | if (k) { | ||
9673 | if ( y.c.length > k ) y.c.length = k; | ||
9674 | } else if (m) { | ||
9675 | y = y.mod(m); | ||
9676 | } | ||
9677 | } | ||
9678 | |||
9679 | i = mathfloor( i / 2 ); | ||
9680 | if ( !i ) break; | ||
9681 | x = x.times(x); | ||
9682 | if (k) { | ||
9683 | if ( x.c && x.c.length > k ) x.c.length = k; | ||
9684 | } else if (m) { | ||
9685 | x = x.mod(m); | ||
9686 | } | ||
9687 | } | ||
9688 | |||
9689 | if (m) return y; | ||
9690 | if ( n < 0 ) y = ONE.div(y); | ||
9691 | |||
9692 | return z ? y.mod(z) : k ? round( y, POW_PRECISION, ROUNDING_MODE ) : y; | ||
9693 | }; | ||
9694 | |||
9695 | |||
9696 | /* | ||
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. | ||
9701 | * | ||
9702 | * [sd] {number} Significant digits. Integer, 1 to MAX inclusive. | ||
9703 | * [rm] {number} Rounding mode. Integer, 0 to 8 inclusive. | ||
9704 | * | ||
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}' | ||
9709 | */ | ||
9710 | P.toPrecision = function ( sd, rm ) { | ||
9711 | return format( this, sd != null && isValidInt( sd, 1, MAX, 24, 'precision' ) | ||
9712 | ? sd | 0 : null, rm, 24 ); | ||
9713 | }; | ||
9714 | |||
9715 | |||
9716 | /* | ||
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. | ||
9722 | * | ||
9723 | * [b] {number} Integer, 2 to 64 inclusive. | ||
9724 | * | ||
9725 | * 'toString() base not an integer: {b}' | ||
9726 | * 'toString() base out of range: {b}' | ||
9727 | */ | ||
9728 | P.toString = function (b) { | ||
9729 | var str, | ||
9730 | n = this, | ||
9731 | s = n.s, | ||
9732 | e = n.e; | ||
9733 | |||
9734 | // Infinity or NaN? | ||
9735 | if ( e === null ) { | ||
9736 | |||
9737 | if (s) { | ||
9738 | str = 'Infinity'; | ||
9739 | if ( s < 0 ) str = '-' + str; | ||
9740 | } else { | ||
9741 | str = 'NaN'; | ||
9742 | } | ||
9743 | } else { | ||
9744 | str = coeffToString( n.c ); | ||
9745 | |||
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 ); | ||
9750 | } else { | ||
9751 | str = convertBase( toFixedPoint( str, e ), b | 0, 10, s ); | ||
9752 | } | ||
9753 | |||
9754 | if ( s < 0 && n.c[0] ) str = '-' + str; | ||
9755 | } | ||
9756 | |||
9757 | return str; | ||
9758 | }; | ||
9759 | |||
9760 | |||
9761 | /* | ||
9762 | * Return a new BigNumber whose value is the value of this BigNumber truncated to a whole | ||
9763 | * number. | ||
9764 | */ | ||
9765 | P.truncated = P.trunc = function () { | ||
9766 | return round( new BigNumber(this), this.e + 1, 1 ); | ||
9767 | }; | ||
9768 | |||
9769 | |||
9770 | /* | ||
9771 | * Return as toString, but do not accept a base argument, and include the minus sign for | ||
9772 | * negative zero. | ||
9773 | */ | ||
9774 | P.valueOf = P.toJSON = function () { | ||
9775 | var str, | ||
9776 | n = this, | ||
9777 | e = n.e; | ||
9778 | |||
9779 | if ( e === null ) return n.toString(); | ||
9780 | |||
9781 | str = coeffToString( n.c ); | ||
9782 | |||
9783 | str = e <= TO_EXP_NEG || e >= TO_EXP_POS | ||
9784 | ? toExponential( str, e ) | ||
9785 | : toFixedPoint( str, e ); | ||
9786 | |||
9787 | return n.s < 0 ? '-' + str : str; | ||
9788 | }; | ||
9789 | |||
9790 | |||
9791 | P.isBigNumber = true; | ||
9792 | |||
9793 | if ( config != null ) BigNumber.config(config); | ||
9794 | |||
9795 | return BigNumber; | ||
9796 | } | ||
9797 | |||
9798 | |||
9799 | // PRIVATE HELPER FUNCTIONS | ||
9800 | |||
9801 | |||
9802 | function bitFloor(n) { | ||
9803 | var i = n | 0; | ||
9804 | return n > 0 || n === i ? i : i - 1; | ||
9805 | } | ||
9806 | |||
9807 | |||
9808 | // Return a coefficient array as a string of base 10 digits. | ||
9809 | function coeffToString(a) { | ||
9810 | var s, z, | ||
9811 | i = 1, | ||
9812 | j = a.length, | ||
9813 | r = a[0] + ''; | ||
9814 | |||
9815 | for ( ; i < j; ) { | ||
9816 | s = a[i++] + ''; | ||
9817 | z = LOG_BASE - s.length; | ||
9818 | for ( ; z--; s = '0' + s ); | ||
9819 | r += s; | ||
9820 | } | ||
9821 | |||
9822 | // Determine trailing zeros. | ||
9823 | for ( j = r.length; r.charCodeAt(--j) === 48; ); | ||
9824 | return r.slice( 0, j + 1 || 1 ); | ||
9825 | } | ||
9826 | |||
9827 | |||
9828 | // Compare the value of BigNumbers x and y. | ||
9829 | function compare( x, y ) { | ||
9830 | var a, b, | ||
9831 | xc = x.c, | ||
9832 | yc = y.c, | ||
9833 | i = x.s, | ||
9834 | j = y.s, | ||
9835 | k = x.e, | ||
9836 | l = y.e; | ||
9837 | |||
9838 | // Either NaN? | ||
9839 | if ( !i || !j ) return null; | ||
9840 | |||
9841 | a = xc && !xc[0]; | ||
9842 | b = yc && !yc[0]; | ||
9843 | |||
9844 | // Either zero? | ||
9845 | if ( a || b ) return a ? b ? 0 : -j : i; | ||
9846 | |||
9847 | // Signs differ? | ||
9848 | if ( i != j ) return i; | ||
9849 | |||
9850 | a = i < 0; | ||
9851 | b = k == l; | ||
9852 | |||
9853 | // Either Infinity? | ||
9854 | if ( !xc || !yc ) return b ? 0 : !xc ^ a ? 1 : -1; | ||
9855 | |||
9856 | // Compare exponents. | ||
9857 | if ( !b ) return k > l ^ a ? 1 : -1; | ||
9858 | |||
9859 | j = ( k = xc.length ) < ( l = yc.length ) ? k : l; | ||
9860 | |||
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; | ||
9863 | |||
9864 | // Compare lengths. | ||
9865 | return k == l ? 0 : k > l ^ a ? 1 : -1; | ||
9866 | } | ||
9867 | |||
9868 | |||
9869 | /* | ||
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. | ||
9873 | */ | ||
9874 | function intValidatorNoErrors( n, min, max ) { | ||
9875 | return ( n = truncate(n) ) >= min && n <= max; | ||
9876 | } | ||
9877 | |||
9878 | |||
9879 | function isArray(obj) { | ||
9880 | return Object.prototype.toString.call(obj) == '[object Array]'; | ||
9881 | } | ||
9882 | |||
9883 | |||
9884 | /* | ||
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]. | ||
9888 | */ | ||
9889 | function toBaseOut( str, baseIn, baseOut ) { | ||
9890 | var j, | ||
9891 | arr = [0], | ||
9892 | arrL, | ||
9893 | i = 0, | ||
9894 | len = str.length; | ||
9895 | |||
9896 | for ( ; i < len; ) { | ||
9897 | for ( arrL = arr.length; arrL--; arr[arrL] *= baseIn ); | ||
9898 | arr[ j = 0 ] += ALPHABET.indexOf( str.charAt( i++ ) ); | ||
9899 | |||
9900 | for ( ; j < arr.length; j++ ) { | ||
9901 | |||
9902 | if ( arr[j] > baseOut - 1 ) { | ||
9903 | if ( arr[j + 1] == null ) arr[j + 1] = 0; | ||
9904 | arr[j + 1] += arr[j] / baseOut | 0; | ||
9905 | arr[j] %= baseOut; | ||
9906 | } | ||
9907 | } | ||
9908 | } | ||
9909 | |||
9910 | return arr.reverse(); | ||
9911 | } | ||
9912 | |||
9913 | |||
9914 | function toExponential( str, e ) { | ||
9915 | return ( str.length > 1 ? str.charAt(0) + '.' + str.slice(1) : str ) + | ||
9916 | ( e < 0 ? 'e' : 'e+' ) + e; | ||
9917 | } | ||
9918 | |||
9919 | |||
9920 | function toFixedPoint( str, e ) { | ||
9921 | var len, z; | ||
9922 | |||
9923 | // Negative exponent? | ||
9924 | if ( e < 0 ) { | ||
9925 | |||
9926 | // Prepend zeros. | ||
9927 | for ( z = '0.'; ++e; z += '0' ); | ||
9928 | str = z + str; | ||
9929 | |||
9930 | // Positive exponent | ||
9931 | } else { | ||
9932 | len = str.length; | ||
9933 | |||
9934 | // Append zeros. | ||
9935 | if ( ++e > len ) { | ||
9936 | for ( z = '0', e -= len; --e; z += '0' ); | ||
9937 | str += z; | ||
9938 | } else if ( e < len ) { | ||
9939 | str = str.slice( 0, e ) + '.' + str.slice(e); | ||
9940 | } | ||
9941 | } | ||
9942 | |||
9943 | return str; | ||
9944 | } | ||
9945 | |||
9946 | |||
9947 | function truncate(n) { | ||
9948 | n = parseFloat(n); | ||
9949 | return n < 0 ? mathceil(n) : mathfloor(n); | ||
9950 | } | ||
9951 | |||
9952 | |||
9953 | // EXPORT | ||
9954 | |||
9955 | |||
9956 | BigNumber = constructorFactory(); | ||
9957 | BigNumber['default'] = BigNumber.BigNumber = BigNumber; | ||
9958 | |||
9959 | |||
9960 | // AMD. | ||
9961 | if ( typeof define == 'function' && define.amd ) { | ||
9962 | define( function () { return BigNumber; } ); | ||
9963 | |||
9964 | // Node.js and other environments that support module.exports. | ||
9965 | } else if ( typeof module != 'undefined' && module.exports ) { | ||
9966 | module.exports = BigNumber; | ||
9967 | |||
9968 | // Browser. | ||
9969 | } else { | ||
9970 | if ( !globalObj ) globalObj = typeof self != 'undefined' ? self : Function('return this')(); | ||
9971 | globalObj.BigNumber = BigNumber; | ||
9972 | } | ||
9973 | })(this); | ||
9974 | |||
9975 | },{}],74:[function(require,module,exports){ | ||
9976 | // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki | ||
9977 | // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] | ||
9978 | // NOTE: SIGHASH byte ignored AND restricted, truncate before use | ||
9979 | |||
9980 | var Buffer = require('safe-buffer').Buffer | ||
9981 | |||
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 | ||
9988 | |||
9989 | var lenR = buffer[3] | ||
9990 | if (lenR === 0) return false | ||
9991 | if (5 + lenR >= buffer.length) return false | ||
9992 | if (buffer[4 + lenR] !== 0x02) return false | ||
9993 | |||
9994 | var lenS = buffer[5 + lenR] | ||
9995 | if (lenS === 0) return false | ||
9996 | if ((6 + lenR + lenS) !== buffer.length) return false | ||
9997 | |||
9998 | if (buffer[4] & 0x80) return false | ||
9999 | if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false | ||
10000 | |||
10001 | if (buffer[lenR + 6] & 0x80) return false | ||
10002 | if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false | ||
10003 | return true | ||
10004 | } | ||
10005 | |||
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') | ||
10012 | |||
10013 | var lenR = buffer[3] | ||
10014 | if (lenR === 0) throw new Error('R length is zero') | ||
10015 | if (5 + lenR >= buffer.length) throw new Error('R length is too long') | ||
10016 | if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') | ||
10017 | |||
10018 | var lenS = buffer[5 + lenR] | ||
10019 | if (lenS === 0) throw new Error('S length is zero') | ||
10020 | if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') | ||
10021 | |||
10022 | if (buffer[4] & 0x80) throw new Error('R value is negative') | ||
10023 | if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') | ||
10024 | |||
10025 | if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') | ||
10026 | if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') | ||
10027 | |||
10028 | // non-BIP66 - extract R, S values | ||
10029 | return { | ||
10030 | r: buffer.slice(4, 4 + lenR), | ||
10031 | s: buffer.slice(6 + lenR) | ||
10032 | } | ||
10033 | } | ||
10034 | |||
10035 | /* | ||
10036 | * Expects r and s to be positive DER integers. | ||
10037 | * | ||
10038 | * The DER format uses the most significant bit as a sign bit (& 0x80). | ||
10039 | * If the significant bit is set AND the integer is positive, a 0x00 is prepended. | ||
10040 | * | ||
10041 | * Examples: | ||
10042 | * | ||
10043 | * 0 => 0x00 | ||
10044 | * 1 => 0x01 | ||
10045 | * -1 => 0xff | ||
10046 | * 127 => 0x7f | ||
10047 | * -127 => 0x81 | ||
10048 | * 128 => 0x0080 | ||
10049 | * -128 => 0x80 | ||
10050 | * 255 => 0x00ff | ||
10051 | * -255 => 0xff01 | ||
10052 | * 16300 => 0x3fac | ||
10053 | * -16300 => 0xc054 | ||
10054 | * 62300 => 0x00f35c | ||
10055 | * -62300 => 0xff0ca4 | ||
10056 | */ | ||
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') | ||
10068 | |||
10069 | var signature = Buffer.allocUnsafe(6 + lenR + lenS) | ||
10070 | |||
10071 | // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] | ||
10072 | signature[0] = 0x30 | ||
10073 | signature[1] = signature.length - 2 | ||
10074 | signature[2] = 0x02 | ||
10075 | signature[3] = r.length | ||
10076 | r.copy(signature, 4) | ||
10077 | signature[4 + lenR] = 0x02 | ||
10078 | signature[5 + lenR] = s.length | ||
10079 | s.copy(signature, 6 + lenR) | ||
10080 | |||
10081 | return signature | ||
10082 | } | ||
10083 | |||
10084 | module.exports = { | ||
10085 | check: check, | ||
10086 | decode: decode, | ||
10087 | encode: encode | ||
10088 | } | ||
10089 | |||
10090 | },{"safe-buffer":247}],75:[function(require,module,exports){ | ||
10091 | (function (module, exports) { | ||
10092 | 'use strict'; | ||
10093 | |||
10094 | // Utils | ||
10095 | function assert (val, msg) { | ||
10096 | if (!val) throw new Error(msg || 'Assertion failed'); | ||
10097 | } | ||
10098 | |||
10099 | // Could use `inherits` module, but don't want to move from single file | ||
10100 | // architecture yet. | ||
10101 | function inherits (ctor, superCtor) { | ||
10102 | ctor.super_ = superCtor; | ||
10103 | var TempCtor = function () {}; | ||
10104 | TempCtor.prototype = superCtor.prototype; | ||
10105 | ctor.prototype = new TempCtor(); | ||
10106 | ctor.prototype.constructor = ctor; | ||
10107 | } | ||
10108 | |||
10109 | // BN | ||
10110 | |||
10111 | function BN (number, base, endian) { | ||
10112 | if (BN.isBN(number)) { | ||
10113 | return number; | ||
10114 | } | ||
10115 | |||
10116 | this.negative = 0; | ||
10117 | this.words = null; | ||
10118 | this.length = 0; | ||
10119 | |||
10120 | // Reduction context | ||
10121 | this.red = null; | ||
10122 | |||
10123 | if (number !== null) { | ||
10124 | if (base === 'le' || base === 'be') { | ||
10125 | endian = base; | ||
10126 | base = 10; | ||
10127 | } | ||
10128 | |||
10129 | this._init(number || 0, base || 10, endian || 'be'); | ||
10130 | } | ||
10131 | } | ||
10132 | if (typeof module === 'object') { | ||
10133 | module.exports = BN; | ||
10134 | } else { | ||
10135 | exports.BN = BN; | ||
10136 | } | ||
10137 | |||
10138 | BN.BN = BN; | ||
10139 | BN.wordSize = 26; | ||
10140 | |||
10141 | var Buffer; | ||
10142 | try { | ||
10143 | Buffer = require('buffer').Buffer; | ||
10144 | } catch (e) { | ||
10145 | } | ||
10146 | |||
10147 | BN.isBN = function isBN (num) { | ||
10148 | if (num instanceof BN) { | ||
10149 | return true; | ||
10150 | } | ||
10151 | |||
10152 | return num !== null && typeof num === 'object' && | ||
10153 | num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); | ||
10154 | }; | ||
10155 | |||
10156 | BN.max = function max (left, right) { | ||
10157 | if (left.cmp(right) > 0) return left; | ||
10158 | return right; | ||
10159 | }; | ||
10160 | |||
10161 | BN.min = function min (left, right) { | ||
10162 | if (left.cmp(right) < 0) return left; | ||
10163 | return right; | ||
10164 | }; | ||
10165 | |||
10166 | BN.prototype._init = function init (number, base, endian) { | ||
10167 | if (typeof number === 'number') { | ||
10168 | return this._initNumber(number, base, endian); | ||
10169 | } | ||
10170 | |||
10171 | if (typeof number === 'object') { | ||
10172 | return this._initArray(number, base, endian); | ||
10173 | } | ||
10174 | |||
10175 | if (base === 'hex') { | ||
10176 | base = 16; | ||
10177 | } | ||
10178 | assert(base === (base | 0) && base >= 2 && base <= 36); | ||
10179 | |||
10180 | number = number.toString().replace(/\s+/g, ''); | ||
10181 | var start = 0; | ||
10182 | if (number[0] === '-') { | ||
10183 | start++; | ||
10184 | } | ||
10185 | |||
10186 | if (base === 16) { | ||
10187 | this._parseHex(number, start); | ||
10188 | } else { | ||
10189 | this._parseBase(number, base, start); | ||
10190 | } | ||
10191 | |||
10192 | if (number[0] === '-') { | ||
10193 | this.negative = 1; | ||
10194 | } | ||
10195 | |||
10196 | this.strip(); | ||
10197 | |||
10198 | if (endian !== 'le') return; | ||
10199 | |||
10200 | this._initArray(this.toArray(), base, endian); | ||
10201 | }; | ||
10202 | |||
10203 | BN.prototype._initNumber = function _initNumber (number, base, endian) { | ||
10204 | if (number < 0) { | ||
10205 | this.negative = 1; | ||
10206 | number = -number; | ||
10207 | } | ||
10208 | if (number < 0x4000000) { | ||
10209 | this.words = [ number & 0x3ffffff ]; | ||
10210 | this.length = 1; | ||
10211 | } else if (number < 0x10000000000000) { | ||
10212 | this.words = [ | ||
10213 | number & 0x3ffffff, | ||
10214 | (number / 0x4000000) & 0x3ffffff | ||
10215 | ]; | ||
10216 | this.length = 2; | ||
10217 | } else { | ||
10218 | assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) | ||
10219 | this.words = [ | ||
10220 | number & 0x3ffffff, | ||
10221 | (number / 0x4000000) & 0x3ffffff, | ||
10222 | 1 | ||
10223 | ]; | ||
10224 | this.length = 3; | ||
10225 | } | ||
10226 | |||
10227 | if (endian !== 'le') return; | ||
10228 | |||
10229 | // Reverse the bytes | ||
10230 | this._initArray(this.toArray(), base, endian); | ||
10231 | }; | ||
10232 | |||
10233 | BN.prototype._initArray = function _initArray (number, base, endian) { | ||
10234 | // Perhaps a Uint8Array | ||
10235 | assert(typeof number.length === 'number'); | ||
10236 | if (number.length <= 0) { | ||
10237 | this.words = [ 0 ]; | ||
10238 | this.length = 1; | ||
10239 | return this; | ||
10240 | } | ||
10241 | |||
10242 | this.length = Math.ceil(number.length / 3); | ||
10243 | this.words = new Array(this.length); | ||
10244 | for (var i = 0; i < this.length; i++) { | ||
10245 | this.words[i] = 0; | ||
10246 | } | ||
10247 | |||
10248 | var j, w; | ||
10249 | var off = 0; | ||
10250 | if (endian === 'be') { | ||
10251 | for (i = number.length - 1, j = 0; i >= 0; i -= 3) { | ||
10252 | w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); | ||
10253 | this.words[j] |= (w << off) & 0x3ffffff; | ||
10254 | this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; | ||
10255 | off += 24; | ||
10256 | if (off >= 26) { | ||
10257 | off -= 26; | ||
10258 | j++; | ||
10259 | } | ||
10260 | } | ||
10261 | } else if (endian === 'le') { | ||
10262 | for (i = 0, j = 0; i < number.length; i += 3) { | ||
10263 | w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); | ||
10264 | this.words[j] |= (w << off) & 0x3ffffff; | ||
10265 | this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; | ||
10266 | off += 24; | ||
10267 | if (off >= 26) { | ||
10268 | off -= 26; | ||
10269 | j++; | ||
10270 | } | ||
10271 | } | ||
10272 | } | ||
10273 | return this.strip(); | ||
10274 | }; | ||
10275 | |||
10276 | function parseHex (str, start, end) { | ||
10277 | var r = 0; | ||
10278 | var len = Math.min(str.length, end); | ||
10279 | for (var i = start; i < len; i++) { | ||
10280 | var c = str.charCodeAt(i) - 48; | ||
10281 | |||
10282 | r <<= 4; | ||
10283 | |||
10284 | // 'a' - 'f' | ||
10285 | if (c >= 49 && c <= 54) { | ||
10286 | r |= c - 49 + 0xa; | ||
10287 | |||
10288 | // 'A' - 'F' | ||
10289 | } else if (c >= 17 && c <= 22) { | ||
10290 | r |= c - 17 + 0xa; | ||
10291 | |||
10292 | // '0' - '9' | ||
10293 | } else { | ||
10294 | r |= c & 0xf; | ||
10295 | } | ||
10296 | } | ||
10297 | return r; | ||
10298 | } | ||
10299 | |||
10300 | BN.prototype._parseHex = function _parseHex (number, start) { | ||
10301 | // Create possibly bigger array to ensure that it fits the number | ||
10302 | this.length = Math.ceil((number.length - start) / 6); | ||
10303 | this.words = new Array(this.length); | ||
10304 | for (var i = 0; i < this.length; i++) { | ||
10305 | this.words[i] = 0; | ||
10306 | } | ||
10307 | |||
10308 | var j, w; | ||
10309 | // Scan 24-bit chunks and add them to the number | ||
10310 | var off = 0; | ||
10311 | for (i = number.length - 6, j = 0; i >= start; i -= 6) { | ||
10312 | w = parseHex(number, i, i + 6); | ||
10313 | this.words[j] |= (w << off) & 0x3ffffff; | ||
10314 | // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb | ||
10315 | this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; | ||
10316 | off += 24; | ||
10317 | if (off >= 26) { | ||
10318 | off -= 26; | ||
10319 | j++; | ||
10320 | } | ||
10321 | } | ||
10322 | if (i + 6 !== start) { | ||
10323 | w = parseHex(number, start, i + 6); | ||
10324 | this.words[j] |= (w << off) & 0x3ffffff; | ||
10325 | this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; | ||
10326 | } | ||
10327 | this.strip(); | ||
10328 | }; | ||
10329 | |||
10330 | function parseBase (str, start, end, mul) { | ||
10331 | var r = 0; | ||
10332 | var len = Math.min(str.length, end); | ||
10333 | for (var i = start; i < len; i++) { | ||
10334 | var c = str.charCodeAt(i) - 48; | ||
10335 | |||
10336 | r *= mul; | ||
10337 | |||
10338 | // 'a' | ||
10339 | if (c >= 49) { | ||
10340 | r += c - 49 + 0xa; | ||
10341 | |||
10342 | // 'A' | ||
10343 | } else if (c >= 17) { | ||
10344 | r += c - 17 + 0xa; | ||
10345 | |||
10346 | // '0' - '9' | ||
10347 | } else { | ||
10348 | r += c; | ||
10349 | } | ||
10350 | } | ||
10351 | return r; | ||
10352 | } | ||
10353 | |||
10354 | BN.prototype._parseBase = function _parseBase (number, base, start) { | ||
10355 | // Initialize as zero | ||
10356 | this.words = [ 0 ]; | ||
10357 | this.length = 1; | ||
10358 | |||
10359 | // Find length of limb in base | ||
10360 | for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { | ||
10361 | limbLen++; | ||
10362 | } | ||
10363 | limbLen--; | ||
10364 | limbPow = (limbPow / base) | 0; | ||
10365 | |||
10366 | var total = number.length - start; | ||
10367 | var mod = total % limbLen; | ||
10368 | var end = Math.min(total, total - mod) + start; | ||
10369 | |||
10370 | var word = 0; | ||
10371 | for (var i = start; i < end; i += limbLen) { | ||
10372 | word = parseBase(number, i, i + limbLen, base); | ||
10373 | |||
10374 | this.imuln(limbPow); | ||
10375 | if (this.words[0] + word < 0x4000000) { | ||
10376 | this.words[0] += word; | ||
10377 | } else { | ||
10378 | this._iaddn(word); | ||
10379 | } | ||
10380 | } | ||
10381 | |||
10382 | if (mod !== 0) { | ||
10383 | var pow = 1; | ||
10384 | word = parseBase(number, i, number.length, base); | ||
10385 | |||
10386 | for (i = 0; i < mod; i++) { | ||
10387 | pow *= base; | ||
10388 | } | ||
10389 | |||
10390 | this.imuln(pow); | ||
10391 | if (this.words[0] + word < 0x4000000) { | ||
10392 | this.words[0] += word; | ||
10393 | } else { | ||
10394 | this._iaddn(word); | ||
10395 | } | ||
10396 | } | ||
10397 | }; | ||
10398 | |||
10399 | BN.prototype.copy = function copy (dest) { | ||
10400 | dest.words = new Array(this.length); | ||
10401 | for (var i = 0; i < this.length; i++) { | ||
10402 | dest.words[i] = this.words[i]; | ||
10403 | } | ||
10404 | dest.length = this.length; | ||
10405 | dest.negative = this.negative; | ||
10406 | dest.red = this.red; | ||
10407 | }; | ||
10408 | |||
10409 | BN.prototype.clone = function clone () { | ||
10410 | var r = new BN(null); | ||
10411 | this.copy(r); | ||
10412 | return r; | ||
10413 | }; | ||
10414 | |||
10415 | BN.prototype._expand = function _expand (size) { | ||
10416 | while (this.length < size) { | ||
10417 | this.words[this.length++] = 0; | ||
10418 | } | ||
10419 | return this; | ||
10420 | }; | ||
10421 | |||
10422 | // Remove leading `0` from `this` | ||
10423 | BN.prototype.strip = function strip () { | ||
10424 | while (this.length > 1 && this.words[this.length - 1] === 0) { | ||
10425 | this.length--; | ||
10426 | } | ||
10427 | return this._normSign(); | ||
10428 | }; | ||
10429 | |||
10430 | BN.prototype._normSign = function _normSign () { | ||
10431 | // -0 = 0 | ||
10432 | if (this.length === 1 && this.words[0] === 0) { | ||
10433 | this.negative = 0; | ||
10434 | } | ||
10435 | return this; | ||
10436 | }; | ||
10437 | |||
10438 | BN.prototype.inspect = function inspect () { | ||
10439 | return (this.red ? '<BN-R: ' : '<BN: ') + this.toString(16) + '>'; | ||
10440 | }; | ||
10441 | |||
10442 | /* | ||
10443 | |||
10444 | var zeros = []; | ||
10445 | var groupSizes = []; | ||
10446 | var groupBases = []; | ||
10447 | |||
10448 | var s = ''; | ||
10449 | var i = -1; | ||
10450 | while (++i < BN.wordSize) { | ||
10451 | zeros[i] = s; | ||
10452 | s += '0'; | ||
10453 | } | ||
10454 | groupSizes[0] = 0; | ||
10455 | groupSizes[1] = 0; | ||
10456 | groupBases[0] = 0; | ||
10457 | groupBases[1] = 0; | ||
10458 | var base = 2 - 1; | ||
10459 | while (++base < 36 + 1) { | ||
10460 | var groupSize = 0; | ||
10461 | var groupBase = 1; | ||
10462 | while (groupBase < (1 << BN.wordSize) / base) { | ||
10463 | groupBase *= base; | ||
10464 | groupSize += 1; | ||
10465 | } | ||
10466 | groupSizes[base] = groupSize; | ||
10467 | groupBases[base] = groupBase; | ||
10468 | } | ||
10469 | |||
10470 | */ | ||
10471 | |||
10472 | var zeros = [ | ||
10473 | '', | ||
10474 | '0', | ||
10475 | '00', | ||
10476 | '000', | ||
10477 | '0000', | ||
10478 | '00000', | ||
10479 | '000000', | ||
10480 | '0000000', | ||
10481 | '00000000', | ||
10482 | '000000000', | ||
10483 | '0000000000', | ||
10484 | '00000000000', | ||
10485 | '000000000000', | ||
10486 | '0000000000000', | ||
10487 | '00000000000000', | ||
10488 | '000000000000000', | ||
10489 | '0000000000000000', | ||
10490 | '00000000000000000', | ||
10491 | '000000000000000000', | ||
10492 | '0000000000000000000', | ||
10493 | '00000000000000000000', | ||
10494 | '000000000000000000000', | ||
10495 | '0000000000000000000000', | ||
10496 | '00000000000000000000000', | ||
10497 | '000000000000000000000000', | ||
10498 | '0000000000000000000000000' | ||
10499 | ]; | ||
10500 | |||
10501 | var groupSizes = [ | ||
10502 | 0, 0, | ||
10503 | 25, 16, 12, 11, 10, 9, 8, | ||
10504 | 8, 7, 7, 7, 7, 6, 6, | ||
10505 | 6, 6, 6, 6, 6, 5, 5, | ||
10506 | 5, 5, 5, 5, 5, 5, 5, | ||
10507 | 5, 5, 5, 5, 5, 5, 5 | ||
10508 | ]; | ||
10509 | |||
10510 | var groupBases = [ | ||
10511 | 0, 0, | ||
10512 | 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, | ||
10513 | 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, | ||
10514 | 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, | ||
10515 | 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, | ||
10516 | 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 | ||
10517 | ]; | ||
10518 | |||
10519 | BN.prototype.toString = function toString (base, padding) { | ||
10520 | base = base || 10; | ||
10521 | padding = padding | 0 || 1; | ||
10522 | |||
10523 | var out; | ||
10524 | if (base === 16 || base === 'hex') { | ||
10525 | out = ''; | ||
10526 | var off = 0; | ||
10527 | var carry = 0; | ||
10528 | for (var i = 0; i < this.length; i++) { | ||
10529 | var w = this.words[i]; | ||
10530 | var word = (((w << off) | carry) & 0xffffff).toString(16); | ||
10531 | carry = (w >>> (24 - off)) & 0xffffff; | ||
10532 | if (carry !== 0 || i !== this.length - 1) { | ||
10533 | out = zeros[6 - word.length] + word + out; | ||
10534 | } else { | ||
10535 | out = word + out; | ||
10536 | } | ||
10537 | off += 2; | ||
10538 | if (off >= 26) { | ||
10539 | off -= 26; | ||
10540 | i--; | ||
10541 | } | ||
10542 | } | ||
10543 | if (carry !== 0) { | ||
10544 | out = carry.toString(16) + out; | ||
10545 | } | ||
10546 | while (out.length % padding !== 0) { | ||
10547 | out = '0' + out; | ||
10548 | } | ||
10549 | if (this.negative !== 0) { | ||
10550 | out = '-' + out; | ||
10551 | } | ||
10552 | return out; | ||
10553 | } | ||
10554 | |||
10555 | if (base === (base | 0) && base >= 2 && base <= 36) { | ||
10556 | // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); | ||
10557 | var groupSize = groupSizes[base]; | ||
10558 | // var groupBase = Math.pow(base, groupSize); | ||
10559 | var groupBase = groupBases[base]; | ||
10560 | out = ''; | ||
10561 | var c = this.clone(); | ||
10562 | c.negative = 0; | ||
10563 | while (!c.isZero()) { | ||
10564 | var r = c.modn(groupBase).toString(base); | ||
10565 | c = c.idivn(groupBase); | ||
10566 | |||
10567 | if (!c.isZero()) { | ||
10568 | out = zeros[groupSize - r.length] + r + out; | ||
10569 | } else { | ||
10570 | out = r + out; | ||
10571 | } | ||
10572 | } | ||
10573 | if (this.isZero()) { | ||
10574 | out = '0' + out; | ||
10575 | } | ||
10576 | while (out.length % padding !== 0) { | ||
10577 | out = '0' + out; | ||
10578 | } | ||
10579 | if (this.negative !== 0) { | ||
10580 | out = '-' + out; | ||
10581 | } | ||
10582 | return out; | ||
10583 | } | ||
10584 | |||
10585 | assert(false, 'Base should be between 2 and 36'); | ||
10586 | }; | ||
10587 | |||
10588 | BN.prototype.toNumber = function toNumber () { | ||
10589 | var ret = this.words[0]; | ||
10590 | if (this.length === 2) { | ||
10591 | ret += this.words[1] * 0x4000000; | ||
10592 | } else if (this.length === 3 && this.words[2] === 0x01) { | ||
10593 | // NOTE: at this stage it is known that the top bit is set | ||
10594 | ret += 0x10000000000000 + (this.words[1] * 0x4000000); | ||
10595 | } else if (this.length > 2) { | ||
10596 | assert(false, 'Number can only safely store up to 53 bits'); | ||
10597 | } | ||
10598 | return (this.negative !== 0) ? -ret : ret; | ||
10599 | }; | ||
10600 | |||
10601 | BN.prototype.toJSON = function toJSON () { | ||
10602 | return this.toString(16); | ||
10603 | }; | ||
10604 | |||
10605 | BN.prototype.toBuffer = function toBuffer (endian, length) { | ||
10606 | assert(typeof Buffer !== 'undefined'); | ||
10607 | return this.toArrayLike(Buffer, endian, length); | ||
10608 | }; | ||
10609 | |||
10610 | BN.prototype.toArray = function toArray (endian, length) { | ||
10611 | return this.toArrayLike(Array, endian, length); | ||
10612 | }; | ||
10613 | |||
10614 | BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { | ||
10615 | var byteLength = this.byteLength(); | ||
10616 | var reqLength = length || Math.max(1, byteLength); | ||
10617 | assert(byteLength <= reqLength, 'byte array longer than desired length'); | ||
10618 | assert(reqLength > 0, 'Requested array length <= 0'); | ||
10619 | |||
10620 | this.strip(); | ||
10621 | var littleEndian = endian === 'le'; | ||
10622 | var res = new ArrayType(reqLength); | ||
10623 | |||
10624 | var b, i; | ||
10625 | var q = this.clone(); | ||
10626 | if (!littleEndian) { | ||
10627 | // Assume big-endian | ||
10628 | for (i = 0; i < reqLength - byteLength; i++) { | ||
10629 | res[i] = 0; | ||
10630 | } | ||
10631 | |||
10632 | for (i = 0; !q.isZero(); i++) { | ||
10633 | b = q.andln(0xff); | ||
10634 | q.iushrn(8); | ||
10635 | |||
10636 | res[reqLength - i - 1] = b; | ||
10637 | } | ||
10638 | } else { | ||
10639 | for (i = 0; !q.isZero(); i++) { | ||
10640 | b = q.andln(0xff); | ||
10641 | q.iushrn(8); | ||
10642 | |||
10643 | res[i] = b; | ||
10644 | } | ||
10645 | |||
10646 | for (; i < reqLength; i++) { | ||
10647 | res[i] = 0; | ||
10648 | } | ||
10649 | } | ||
10650 | |||
10651 | return res; | ||
10652 | }; | ||
10653 | |||
10654 | if (Math.clz32) { | ||
10655 | BN.prototype._countBits = function _countBits (w) { | ||
10656 | return 32 - Math.clz32(w); | ||
10657 | }; | ||
10658 | } else { | ||
10659 | BN.prototype._countBits = function _countBits (w) { | ||
10660 | var t = w; | ||
10661 | var r = 0; | ||
10662 | if (t >= 0x1000) { | ||
10663 | r += 13; | ||
10664 | t >>>= 13; | ||
10665 | } | ||
10666 | if (t >= 0x40) { | ||
10667 | r += 7; | ||
10668 | t >>>= 7; | ||
10669 | } | ||
10670 | if (t >= 0x8) { | ||
10671 | r += 4; | ||
10672 | t >>>= 4; | ||
10673 | } | ||
10674 | if (t >= 0x02) { | ||
10675 | r += 2; | ||
10676 | t >>>= 2; | ||
10677 | } | ||
10678 | return r + t; | ||
10679 | }; | ||
10680 | } | ||
10681 | |||
10682 | BN.prototype._zeroBits = function _zeroBits (w) { | ||
10683 | // Short-cut | ||
10684 | if (w === 0) return 26; | ||
10685 | |||
10686 | var t = w; | ||
10687 | var r = 0; | ||
10688 | if ((t & 0x1fff) === 0) { | ||
10689 | r += 13; | ||
10690 | t >>>= 13; | ||
10691 | } | ||
10692 | if ((t & 0x7f) === 0) { | ||
10693 | r += 7; | ||
10694 | t >>>= 7; | ||
10695 | } | ||
10696 | if ((t & 0xf) === 0) { | ||
10697 | r += 4; | ||
10698 | t >>>= 4; | ||
10699 | } | ||
10700 | if ((t & 0x3) === 0) { | ||
10701 | r += 2; | ||
10702 | t >>>= 2; | ||
10703 | } | ||
10704 | if ((t & 0x1) === 0) { | ||
10705 | r++; | ||
10706 | } | ||
10707 | return r; | ||
10708 | }; | ||
10709 | |||
10710 | // Return number of used bits in a BN | ||
10711 | BN.prototype.bitLength = function bitLength () { | ||
10712 | var w = this.words[this.length - 1]; | ||
10713 | var hi = this._countBits(w); | ||
10714 | return (this.length - 1) * 26 + hi; | ||
10715 | }; | ||
10716 | |||
10717 | function toBitArray (num) { | ||
10718 | var w = new Array(num.bitLength()); | ||
10719 | |||
10720 | for (var bit = 0; bit < w.length; bit++) { | ||
10721 | var off = (bit / 26) | 0; | ||
10722 | var wbit = bit % 26; | ||
10723 | |||
10724 | w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; | ||
10725 | } | ||
10726 | |||
10727 | return w; | ||
10728 | } | ||
10729 | |||
10730 | // Number of trailing zero bits | ||
10731 | BN.prototype.zeroBits = function zeroBits () { | ||
10732 | if (this.isZero()) return 0; | ||
10733 | |||
10734 | var r = 0; | ||
10735 | for (var i = 0; i < this.length; i++) { | ||
10736 | var b = this._zeroBits(this.words[i]); | ||
10737 | r += b; | ||
10738 | if (b !== 26) break; | ||
10739 | } | ||
10740 | return r; | ||
10741 | }; | ||
10742 | |||
10743 | BN.prototype.byteLength = function byteLength () { | ||
10744 | return Math.ceil(this.bitLength() / 8); | ||
10745 | }; | ||
10746 | |||
10747 | BN.prototype.toTwos = function toTwos (width) { | ||
10748 | if (this.negative !== 0) { | ||
10749 | return this.abs().inotn(width).iaddn(1); | ||
10750 | } | ||
10751 | return this.clone(); | ||
10752 | }; | ||
10753 | |||
10754 | BN.prototype.fromTwos = function fromTwos (width) { | ||
10755 | if (this.testn(width - 1)) { | ||
10756 | return this.notn(width).iaddn(1).ineg(); | ||
10757 | } | ||
10758 | return this.clone(); | ||
10759 | }; | ||
10760 | |||
10761 | BN.prototype.isNeg = function isNeg () { | ||
10762 | return this.negative !== 0; | ||
10763 | }; | ||
10764 | |||
10765 | // Return negative clone of `this` | ||
10766 | BN.prototype.neg = function neg () { | ||
10767 | return this.clone().ineg(); | ||
10768 | }; | ||
10769 | |||
10770 | BN.prototype.ineg = function ineg () { | ||
10771 | if (!this.isZero()) { | ||
10772 | this.negative ^= 1; | ||
10773 | } | ||
10774 | |||
10775 | return this; | ||
10776 | }; | ||
10777 | |||
10778 | // Or `num` with `this` in-place | ||
10779 | BN.prototype.iuor = function iuor (num) { | ||
10780 | while (this.length < num.length) { | ||
10781 | this.words[this.length++] = 0; | ||
10782 | } | ||
10783 | |||
10784 | for (var i = 0; i < num.length; i++) { | ||
10785 | this.words[i] = this.words[i] | num.words[i]; | ||
10786 | } | ||
10787 | |||
10788 | return this.strip(); | ||
10789 | }; | ||
10790 | |||
10791 | BN.prototype.ior = function ior (num) { | ||
10792 | assert((this.negative | num.negative) === 0); | ||
10793 | return this.iuor(num); | ||
10794 | }; | ||
10795 | |||
10796 | // Or `num` with `this` | ||
10797 | BN.prototype.or = function or (num) { | ||
10798 | if (this.length > num.length) return this.clone().ior(num); | ||
10799 | return num.clone().ior(this); | ||
10800 | }; | ||
10801 | |||
10802 | BN.prototype.uor = function uor (num) { | ||
10803 | if (this.length > num.length) return this.clone().iuor(num); | ||
10804 | return num.clone().iuor(this); | ||
10805 | }; | ||
10806 | |||
10807 | // And `num` with `this` in-place | ||
10808 | BN.prototype.iuand = function iuand (num) { | ||
10809 | // b = min-length(num, this) | ||
10810 | var b; | ||
10811 | if (this.length > num.length) { | ||
10812 | b = num; | ||
10813 | } else { | ||
10814 | b = this; | ||
10815 | } | ||
10816 | |||
10817 | for (var i = 0; i < b.length; i++) { | ||
10818 | this.words[i] = this.words[i] & num.words[i]; | ||
10819 | } | ||
10820 | |||
10821 | this.length = b.length; | ||
10822 | |||
10823 | return this.strip(); | ||
10824 | }; | ||
10825 | |||
10826 | BN.prototype.iand = function iand (num) { | ||
10827 | assert((this.negative | num.negative) === 0); | ||
10828 | return this.iuand(num); | ||
10829 | }; | ||
10830 | |||
10831 | // And `num` with `this` | ||
10832 | BN.prototype.and = function and (num) { | ||
10833 | if (this.length > num.length) return this.clone().iand(num); | ||
10834 | return num.clone().iand(this); | ||
10835 | }; | ||
10836 | |||
10837 | BN.prototype.uand = function uand (num) { | ||
10838 | if (this.length > num.length) return this.clone().iuand(num); | ||
10839 | return num.clone().iuand(this); | ||
10840 | }; | ||
10841 | |||
10842 | // Xor `num` with `this` in-place | ||
10843 | BN.prototype.iuxor = function iuxor (num) { | ||
10844 | // a.length > b.length | ||
10845 | var a; | ||
10846 | var b; | ||
10847 | if (this.length > num.length) { | ||
10848 | a = this; | ||
10849 | b = num; | ||
10850 | } else { | ||
10851 | a = num; | ||
10852 | b = this; | ||
10853 | } | ||
10854 | |||
10855 | for (var i = 0; i < b.length; i++) { | ||
10856 | this.words[i] = a.words[i] ^ b.words[i]; | ||
10857 | } | ||
10858 | |||
10859 | if (this !== a) { | ||
10860 | for (; i < a.length; i++) { | ||
10861 | this.words[i] = a.words[i]; | ||
10862 | } | ||
10863 | } | ||
10864 | |||
10865 | this.length = a.length; | ||
10866 | |||
10867 | return this.strip(); | ||
10868 | }; | ||
10869 | |||
10870 | BN.prototype.ixor = function ixor (num) { | ||
10871 | assert((this.negative | num.negative) === 0); | ||
10872 | return this.iuxor(num); | ||
10873 | }; | ||
10874 | |||
10875 | // Xor `num` with `this` | ||
10876 | BN.prototype.xor = function xor (num) { | ||
10877 | if (this.length > num.length) return this.clone().ixor(num); | ||
10878 | return num.clone().ixor(this); | ||
10879 | }; | ||
10880 | |||
10881 | BN.prototype.uxor = function uxor (num) { | ||
10882 | if (this.length > num.length) return this.clone().iuxor(num); | ||
10883 | return num.clone().iuxor(this); | ||
10884 | }; | ||
10885 | |||
10886 | // Not ``this`` with ``width`` bitwidth | ||
10887 | BN.prototype.inotn = function inotn (width) { | ||
10888 | assert(typeof width === 'number' && width >= 0); | ||
10889 | |||
10890 | var bytesNeeded = Math.ceil(width / 26) | 0; | ||
10891 | var bitsLeft = width % 26; | ||
10892 | |||
10893 | // Extend the buffer with leading zeroes | ||
10894 | this._expand(bytesNeeded); | ||
10895 | |||
10896 | if (bitsLeft > 0) { | ||
10897 | bytesNeeded--; | ||
10898 | } | ||
10899 | |||
10900 | // Handle complete words | ||
10901 | for (var i = 0; i < bytesNeeded; i++) { | ||
10902 | this.words[i] = ~this.words[i] & 0x3ffffff; | ||
10903 | } | ||
10904 | |||
10905 | // Handle the residue | ||
10906 | if (bitsLeft > 0) { | ||
10907 | this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); | ||
10908 | } | ||
10909 | |||
10910 | // And remove leading zeroes | ||
10911 | return this.strip(); | ||
10912 | }; | ||
10913 | |||
10914 | BN.prototype.notn = function notn (width) { | ||
10915 | return this.clone().inotn(width); | ||
10916 | }; | ||
10917 | |||
10918 | // Set `bit` of `this` | ||
10919 | BN.prototype.setn = function setn (bit, val) { | ||
10920 | assert(typeof bit === 'number' && bit >= 0); | ||
10921 | |||
10922 | var off = (bit / 26) | 0; | ||
10923 | var wbit = bit % 26; | ||
10924 | |||
10925 | this._expand(off + 1); | ||
10926 | |||
10927 | if (val) { | ||
10928 | this.words[off] = this.words[off] | (1 << wbit); | ||
10929 | } else { | ||
10930 | this.words[off] = this.words[off] & ~(1 << wbit); | ||
10931 | } | ||
10932 | |||
10933 | return this.strip(); | ||
10934 | }; | ||
10935 | |||
10936 | // Add `num` to `this` in-place | ||
10937 | BN.prototype.iadd = function iadd (num) { | ||
10938 | var r; | ||
10939 | |||
10940 | // negative + positive | ||
10941 | if (this.negative !== 0 && num.negative === 0) { | ||
10942 | this.negative = 0; | ||
10943 | r = this.isub(num); | ||
10944 | this.negative ^= 1; | ||
10945 | return this._normSign(); | ||
10946 | |||
10947 | // positive + negative | ||
10948 | } else if (this.negative === 0 && num.negative !== 0) { | ||
10949 | num.negative = 0; | ||
10950 | r = this.isub(num); | ||
10951 | num.negative = 1; | ||
10952 | return r._normSign(); | ||
10953 | } | ||
10954 | |||
10955 | // a.length > b.length | ||
10956 | var a, b; | ||
10957 | if (this.length > num.length) { | ||
10958 | a = this; | ||
10959 | b = num; | ||
10960 | } else { | ||
10961 | a = num; | ||
10962 | b = this; | ||
10963 | } | ||
10964 | |||
10965 | var carry = 0; | ||
10966 | for (var i = 0; i < b.length; i++) { | ||
10967 | r = (a.words[i] | 0) + (b.words[i] | 0) + carry; | ||
10968 | this.words[i] = r & 0x3ffffff; | ||
10969 | carry = r >>> 26; | ||
10970 | } | ||
10971 | for (; carry !== 0 && i < a.length; i++) { | ||
10972 | r = (a.words[i] | 0) + carry; | ||
10973 | this.words[i] = r & 0x3ffffff; | ||
10974 | carry = r >>> 26; | ||
10975 | } | ||
10976 | |||
10977 | this.length = a.length; | ||
10978 | if (carry !== 0) { | ||
10979 | this.words[this.length] = carry; | ||
10980 | this.length++; | ||
10981 | // Copy the rest of the words | ||
10982 | } else if (a !== this) { | ||
10983 | for (; i < a.length; i++) { | ||
10984 | this.words[i] = a.words[i]; | ||
10985 | } | ||
10986 | } | ||
10987 | |||
10988 | return this; | ||
10989 | }; | ||
10990 | |||
10991 | // Add `num` to `this` | ||
10992 | BN.prototype.add = function add (num) { | ||
10993 | var res; | ||
10994 | if (num.negative !== 0 && this.negative === 0) { | ||
10995 | num.negative = 0; | ||
10996 | res = this.sub(num); | ||
10997 | num.negative ^= 1; | ||
10998 | return res; | ||
10999 | } else if (num.negative === 0 && this.negative !== 0) { | ||
11000 | this.negative = 0; | ||
11001 | res = num.sub(this); | ||
11002 | this.negative = 1; | ||
11003 | return res; | ||
11004 | } | ||
11005 | |||
11006 | if (this.length > num.length) return this.clone().iadd(num); | ||
11007 | |||
11008 | return num.clone().iadd(this); | ||
11009 | }; | ||
11010 | |||
11011 | // Subtract `num` from `this` in-place | ||
11012 | BN.prototype.isub = function isub (num) { | ||
11013 | // this - (-num) = this + num | ||
11014 | if (num.negative !== 0) { | ||
11015 | num.negative = 0; | ||
11016 | var r = this.iadd(num); | ||
11017 | num.negative = 1; | ||
11018 | return r._normSign(); | ||
11019 | |||
11020 | // -this - num = -(this + num) | ||
11021 | } else if (this.negative !== 0) { | ||
11022 | this.negative = 0; | ||
11023 | this.iadd(num); | ||
11024 | this.negative = 1; | ||
11025 | return this._normSign(); | ||
11026 | } | ||
11027 | |||
11028 | // At this point both numbers are positive | ||
11029 | var cmp = this.cmp(num); | ||
11030 | |||
11031 | // Optimization - zeroify | ||
11032 | if (cmp === 0) { | ||
11033 | this.negative = 0; | ||
11034 | this.length = 1; | ||
11035 | this.words[0] = 0; | ||
11036 | return this; | ||
11037 | } | ||
11038 | |||
11039 | // a > b | ||
11040 | var a, b; | ||
11041 | if (cmp > 0) { | ||
11042 | a = this; | ||
11043 | b = num; | ||
11044 | } else { | ||
11045 | a = num; | ||
11046 | b = this; | ||
11047 | } | ||
11048 | |||
11049 | var carry = 0; | ||
11050 | for (var i = 0; i < b.length; i++) { | ||
11051 | r = (a.words[i] | 0) - (b.words[i] | 0) + carry; | ||
11052 | carry = r >> 26; | ||
11053 | this.words[i] = r & 0x3ffffff; | ||
11054 | } | ||
11055 | for (; carry !== 0 && i < a.length; i++) { | ||
11056 | r = (a.words[i] | 0) + carry; | ||
11057 | carry = r >> 26; | ||
11058 | this.words[i] = r & 0x3ffffff; | ||
11059 | } | ||
11060 | |||
11061 | // Copy rest of the words | ||
11062 | if (carry === 0 && i < a.length && a !== this) { | ||
11063 | for (; i < a.length; i++) { | ||
11064 | this.words[i] = a.words[i]; | ||
11065 | } | ||
11066 | } | ||
11067 | |||
11068 | this.length = Math.max(this.length, i); | ||
11069 | |||
11070 | if (a !== this) { | ||
11071 | this.negative = 1; | ||
11072 | } | ||
11073 | |||
11074 | return this.strip(); | ||
11075 | }; | ||
11076 | |||
11077 | // Subtract `num` from `this` | ||
11078 | BN.prototype.sub = function sub (num) { | ||
11079 | return this.clone().isub(num); | ||
11080 | }; | ||
11081 | |||
11082 | function smallMulTo (self, num, out) { | ||
11083 | out.negative = num.negative ^ self.negative; | ||
11084 | var len = (self.length + num.length) | 0; | ||
11085 | out.length = len; | ||
11086 | len = (len - 1) | 0; | ||
11087 | |||
11088 | // Peel one iteration (compiler can't do it, because of code complexity) | ||
11089 | var a = self.words[0] | 0; | ||
11090 | var b = num.words[0] | 0; | ||
11091 | var r = a * b; | ||
11092 | |||
11093 | var lo = r & 0x3ffffff; | ||
11094 | var carry = (r / 0x4000000) | 0; | ||
11095 | out.words[0] = lo; | ||
11096 | |||
11097 | for (var k = 1; k < len; k++) { | ||
11098 | // Sum all words with the same `i + j = k` and accumulate `ncarry`, | ||
11099 | // note that ncarry could be >= 0x3ffffff | ||
11100 | var ncarry = carry >>> 26; | ||
11101 | var rword = carry & 0x3ffffff; | ||
11102 | var maxJ = Math.min(k, num.length - 1); | ||
11103 | for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { | ||
11104 | var i = (k - j) | 0; | ||
11105 | a = self.words[i] | 0; | ||
11106 | b = num.words[j] | 0; | ||
11107 | r = a * b + rword; | ||
11108 | ncarry += (r / 0x4000000) | 0; | ||
11109 | rword = r & 0x3ffffff; | ||
11110 | } | ||
11111 | out.words[k] = rword | 0; | ||
11112 | carry = ncarry | 0; | ||
11113 | } | ||
11114 | if (carry !== 0) { | ||
11115 | out.words[k] = carry | 0; | ||
11116 | } else { | ||
11117 | out.length--; | ||
11118 | } | ||
11119 | |||
11120 | return out.strip(); | ||
11121 | } | ||
11122 | |||
11123 | // TODO(indutny): it may be reasonable to omit it for users who don't need | ||
11124 | // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit | ||
11125 | // multiplication (like elliptic secp256k1). | ||
11126 | var comb10MulTo = function comb10MulTo (self, num, out) { | ||
11127 | var a = self.words; | ||
11128 | var b = num.words; | ||
11129 | var o = out.words; | ||
11130 | var c = 0; | ||
11131 | var lo; | ||
11132 | var mid; | ||
11133 | var hi; | ||
11134 | var a0 = a[0] | 0; | ||
11135 | var al0 = a0 & 0x1fff; | ||
11136 | var ah0 = a0 >>> 13; | ||
11137 | var a1 = a[1] | 0; | ||
11138 | var al1 = a1 & 0x1fff; | ||
11139 | var ah1 = a1 >>> 13; | ||
11140 | var a2 = a[2] | 0; | ||
11141 | var al2 = a2 & 0x1fff; | ||
11142 | var ah2 = a2 >>> 13; | ||
11143 | var a3 = a[3] | 0; | ||
11144 | var al3 = a3 & 0x1fff; | ||
11145 | var ah3 = a3 >>> 13; | ||
11146 | var a4 = a[4] | 0; | ||
11147 | var al4 = a4 & 0x1fff; | ||
11148 | var ah4 = a4 >>> 13; | ||
11149 | var a5 = a[5] | 0; | ||
11150 | var al5 = a5 & 0x1fff; | ||
11151 | var ah5 = a5 >>> 13; | ||
11152 | var a6 = a[6] | 0; | ||
11153 | var al6 = a6 & 0x1fff; | ||
11154 | var ah6 = a6 >>> 13; | ||
11155 | var a7 = a[7] | 0; | ||
11156 | var al7 = a7 & 0x1fff; | ||
11157 | var ah7 = a7 >>> 13; | ||
11158 | var a8 = a[8] | 0; | ||
11159 | var al8 = a8 & 0x1fff; | ||
11160 | var ah8 = a8 >>> 13; | ||
11161 | var a9 = a[9] | 0; | ||
11162 | var al9 = a9 & 0x1fff; | ||
11163 | var ah9 = a9 >>> 13; | ||
11164 | var b0 = b[0] | 0; | ||
11165 | var bl0 = b0 & 0x1fff; | ||
11166 | var bh0 = b0 >>> 13; | ||
11167 | var b1 = b[1] | 0; | ||
11168 | var bl1 = b1 & 0x1fff; | ||
11169 | var bh1 = b1 >>> 13; | ||
11170 | var b2 = b[2] | 0; | ||
11171 | var bl2 = b2 & 0x1fff; | ||
11172 | var bh2 = b2 >>> 13; | ||
11173 | var b3 = b[3] | 0; | ||
11174 | var bl3 = b3 & 0x1fff; | ||
11175 | var bh3 = b3 >>> 13; | ||
11176 | var b4 = b[4] | 0; | ||
11177 | var bl4 = b4 & 0x1fff; | ||
11178 | var bh4 = b4 >>> 13; | ||
11179 | var b5 = b[5] | 0; | ||
11180 | var bl5 = b5 & 0x1fff; | ||
11181 | var bh5 = b5 >>> 13; | ||
11182 | var b6 = b[6] | 0; | ||
11183 | var bl6 = b6 & 0x1fff; | ||
11184 | var bh6 = b6 >>> 13; | ||
11185 | var b7 = b[7] | 0; | ||
11186 | var bl7 = b7 & 0x1fff; | ||
11187 | var bh7 = b7 >>> 13; | ||
11188 | var b8 = b[8] | 0; | ||
11189 | var bl8 = b8 & 0x1fff; | ||
11190 | var bh8 = b8 >>> 13; | ||
11191 | var b9 = b[9] | 0; | ||
11192 | var bl9 = b9 & 0x1fff; | ||
11193 | var bh9 = b9 >>> 13; | ||
11194 | |||
11195 | out.negative = self.negative ^ num.negative; | ||
11196 | out.length = 19; | ||
11197 | /* k = 0 */ | ||
11198 | lo = Math.imul(al0, bl0); | ||
11199 | mid = Math.imul(al0, bh0); | ||
11200 | mid = (mid + Math.imul(ah0, bl0)) | 0; | ||
11201 | hi = Math.imul(ah0, bh0); | ||
11202 | var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11203 | c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; | ||
11204 | w0 &= 0x3ffffff; | ||
11205 | /* k = 1 */ | ||
11206 | lo = Math.imul(al1, bl0); | ||
11207 | mid = Math.imul(al1, bh0); | ||
11208 | mid = (mid + Math.imul(ah1, bl0)) | 0; | ||
11209 | hi = Math.imul(ah1, bh0); | ||
11210 | lo = (lo + Math.imul(al0, bl1)) | 0; | ||
11211 | mid = (mid + Math.imul(al0, bh1)) | 0; | ||
11212 | mid = (mid + Math.imul(ah0, bl1)) | 0; | ||
11213 | hi = (hi + Math.imul(ah0, bh1)) | 0; | ||
11214 | var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11215 | c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; | ||
11216 | w1 &= 0x3ffffff; | ||
11217 | /* k = 2 */ | ||
11218 | lo = Math.imul(al2, bl0); | ||
11219 | mid = Math.imul(al2, bh0); | ||
11220 | mid = (mid + Math.imul(ah2, bl0)) | 0; | ||
11221 | hi = Math.imul(ah2, bh0); | ||
11222 | lo = (lo + Math.imul(al1, bl1)) | 0; | ||
11223 | mid = (mid + Math.imul(al1, bh1)) | 0; | ||
11224 | mid = (mid + Math.imul(ah1, bl1)) | 0; | ||
11225 | hi = (hi + Math.imul(ah1, bh1)) | 0; | ||
11226 | lo = (lo + Math.imul(al0, bl2)) | 0; | ||
11227 | mid = (mid + Math.imul(al0, bh2)) | 0; | ||
11228 | mid = (mid + Math.imul(ah0, bl2)) | 0; | ||
11229 | hi = (hi + Math.imul(ah0, bh2)) | 0; | ||
11230 | var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11231 | c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; | ||
11232 | w2 &= 0x3ffffff; | ||
11233 | /* k = 3 */ | ||
11234 | lo = Math.imul(al3, bl0); | ||
11235 | mid = Math.imul(al3, bh0); | ||
11236 | mid = (mid + Math.imul(ah3, bl0)) | 0; | ||
11237 | hi = Math.imul(ah3, bh0); | ||
11238 | lo = (lo + Math.imul(al2, bl1)) | 0; | ||
11239 | mid = (mid + Math.imul(al2, bh1)) | 0; | ||
11240 | mid = (mid + Math.imul(ah2, bl1)) | 0; | ||
11241 | hi = (hi + Math.imul(ah2, bh1)) | 0; | ||
11242 | lo = (lo + Math.imul(al1, bl2)) | 0; | ||
11243 | mid = (mid + Math.imul(al1, bh2)) | 0; | ||
11244 | mid = (mid + Math.imul(ah1, bl2)) | 0; | ||
11245 | hi = (hi + Math.imul(ah1, bh2)) | 0; | ||
11246 | lo = (lo + Math.imul(al0, bl3)) | 0; | ||
11247 | mid = (mid + Math.imul(al0, bh3)) | 0; | ||
11248 | mid = (mid + Math.imul(ah0, bl3)) | 0; | ||
11249 | hi = (hi + Math.imul(ah0, bh3)) | 0; | ||
11250 | var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11251 | c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; | ||
11252 | w3 &= 0x3ffffff; | ||
11253 | /* k = 4 */ | ||
11254 | lo = Math.imul(al4, bl0); | ||
11255 | mid = Math.imul(al4, bh0); | ||
11256 | mid = (mid + Math.imul(ah4, bl0)) | 0; | ||
11257 | hi = Math.imul(ah4, bh0); | ||
11258 | lo = (lo + Math.imul(al3, bl1)) | 0; | ||
11259 | mid = (mid + Math.imul(al3, bh1)) | 0; | ||
11260 | mid = (mid + Math.imul(ah3, bl1)) | 0; | ||
11261 | hi = (hi + Math.imul(ah3, bh1)) | 0; | ||
11262 | lo = (lo + Math.imul(al2, bl2)) | 0; | ||
11263 | mid = (mid + Math.imul(al2, bh2)) | 0; | ||
11264 | mid = (mid + Math.imul(ah2, bl2)) | 0; | ||
11265 | hi = (hi + Math.imul(ah2, bh2)) | 0; | ||
11266 | lo = (lo + Math.imul(al1, bl3)) | 0; | ||
11267 | mid = (mid + Math.imul(al1, bh3)) | 0; | ||
11268 | mid = (mid + Math.imul(ah1, bl3)) | 0; | ||
11269 | hi = (hi + Math.imul(ah1, bh3)) | 0; | ||
11270 | lo = (lo + Math.imul(al0, bl4)) | 0; | ||
11271 | mid = (mid + Math.imul(al0, bh4)) | 0; | ||
11272 | mid = (mid + Math.imul(ah0, bl4)) | 0; | ||
11273 | hi = (hi + Math.imul(ah0, bh4)) | 0; | ||
11274 | var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11275 | c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; | ||
11276 | w4 &= 0x3ffffff; | ||
11277 | /* k = 5 */ | ||
11278 | lo = Math.imul(al5, bl0); | ||
11279 | mid = Math.imul(al5, bh0); | ||
11280 | mid = (mid + Math.imul(ah5, bl0)) | 0; | ||
11281 | hi = Math.imul(ah5, bh0); | ||
11282 | lo = (lo + Math.imul(al4, bl1)) | 0; | ||
11283 | mid = (mid + Math.imul(al4, bh1)) | 0; | ||
11284 | mid = (mid + Math.imul(ah4, bl1)) | 0; | ||
11285 | hi = (hi + Math.imul(ah4, bh1)) | 0; | ||
11286 | lo = (lo + Math.imul(al3, bl2)) | 0; | ||
11287 | mid = (mid + Math.imul(al3, bh2)) | 0; | ||
11288 | mid = (mid + Math.imul(ah3, bl2)) | 0; | ||
11289 | hi = (hi + Math.imul(ah3, bh2)) | 0; | ||
11290 | lo = (lo + Math.imul(al2, bl3)) | 0; | ||
11291 | mid = (mid + Math.imul(al2, bh3)) | 0; | ||
11292 | mid = (mid + Math.imul(ah2, bl3)) | 0; | ||
11293 | hi = (hi + Math.imul(ah2, bh3)) | 0; | ||
11294 | lo = (lo + Math.imul(al1, bl4)) | 0; | ||
11295 | mid = (mid + Math.imul(al1, bh4)) | 0; | ||
11296 | mid = (mid + Math.imul(ah1, bl4)) | 0; | ||
11297 | hi = (hi + Math.imul(ah1, bh4)) | 0; | ||
11298 | lo = (lo + Math.imul(al0, bl5)) | 0; | ||
11299 | mid = (mid + Math.imul(al0, bh5)) | 0; | ||
11300 | mid = (mid + Math.imul(ah0, bl5)) | 0; | ||
11301 | hi = (hi + Math.imul(ah0, bh5)) | 0; | ||
11302 | var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11303 | c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; | ||
11304 | w5 &= 0x3ffffff; | ||
11305 | /* k = 6 */ | ||
11306 | lo = Math.imul(al6, bl0); | ||
11307 | mid = Math.imul(al6, bh0); | ||
11308 | mid = (mid + Math.imul(ah6, bl0)) | 0; | ||
11309 | hi = Math.imul(ah6, bh0); | ||
11310 | lo = (lo + Math.imul(al5, bl1)) | 0; | ||
11311 | mid = (mid + Math.imul(al5, bh1)) | 0; | ||
11312 | mid = (mid + Math.imul(ah5, bl1)) | 0; | ||
11313 | hi = (hi + Math.imul(ah5, bh1)) | 0; | ||
11314 | lo = (lo + Math.imul(al4, bl2)) | 0; | ||
11315 | mid = (mid + Math.imul(al4, bh2)) | 0; | ||
11316 | mid = (mid + Math.imul(ah4, bl2)) | 0; | ||
11317 | hi = (hi + Math.imul(ah4, bh2)) | 0; | ||
11318 | lo = (lo + Math.imul(al3, bl3)) | 0; | ||
11319 | mid = (mid + Math.imul(al3, bh3)) | 0; | ||
11320 | mid = (mid + Math.imul(ah3, bl3)) | 0; | ||
11321 | hi = (hi + Math.imul(ah3, bh3)) | 0; | ||
11322 | lo = (lo + Math.imul(al2, bl4)) | 0; | ||
11323 | mid = (mid + Math.imul(al2, bh4)) | 0; | ||
11324 | mid = (mid + Math.imul(ah2, bl4)) | 0; | ||
11325 | hi = (hi + Math.imul(ah2, bh4)) | 0; | ||
11326 | lo = (lo + Math.imul(al1, bl5)) | 0; | ||
11327 | mid = (mid + Math.imul(al1, bh5)) | 0; | ||
11328 | mid = (mid + Math.imul(ah1, bl5)) | 0; | ||
11329 | hi = (hi + Math.imul(ah1, bh5)) | 0; | ||
11330 | lo = (lo + Math.imul(al0, bl6)) | 0; | ||
11331 | mid = (mid + Math.imul(al0, bh6)) | 0; | ||
11332 | mid = (mid + Math.imul(ah0, bl6)) | 0; | ||
11333 | hi = (hi + Math.imul(ah0, bh6)) | 0; | ||
11334 | var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11335 | c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; | ||
11336 | w6 &= 0x3ffffff; | ||
11337 | /* k = 7 */ | ||
11338 | lo = Math.imul(al7, bl0); | ||
11339 | mid = Math.imul(al7, bh0); | ||
11340 | mid = (mid + Math.imul(ah7, bl0)) | 0; | ||
11341 | hi = Math.imul(ah7, bh0); | ||
11342 | lo = (lo + Math.imul(al6, bl1)) | 0; | ||
11343 | mid = (mid + Math.imul(al6, bh1)) | 0; | ||
11344 | mid = (mid + Math.imul(ah6, bl1)) | 0; | ||
11345 | hi = (hi + Math.imul(ah6, bh1)) | 0; | ||
11346 | lo = (lo + Math.imul(al5, bl2)) | 0; | ||
11347 | mid = (mid + Math.imul(al5, bh2)) | 0; | ||
11348 | mid = (mid + Math.imul(ah5, bl2)) | 0; | ||
11349 | hi = (hi + Math.imul(ah5, bh2)) | 0; | ||
11350 | lo = (lo + Math.imul(al4, bl3)) | 0; | ||
11351 | mid = (mid + Math.imul(al4, bh3)) | 0; | ||
11352 | mid = (mid + Math.imul(ah4, bl3)) | 0; | ||
11353 | hi = (hi + Math.imul(ah4, bh3)) | 0; | ||
11354 | lo = (lo + Math.imul(al3, bl4)) | 0; | ||
11355 | mid = (mid + Math.imul(al3, bh4)) | 0; | ||
11356 | mid = (mid + Math.imul(ah3, bl4)) | 0; | ||
11357 | hi = (hi + Math.imul(ah3, bh4)) | 0; | ||
11358 | lo = (lo + Math.imul(al2, bl5)) | 0; | ||
11359 | mid = (mid + Math.imul(al2, bh5)) | 0; | ||
11360 | mid = (mid + Math.imul(ah2, bl5)) | 0; | ||
11361 | hi = (hi + Math.imul(ah2, bh5)) | 0; | ||
11362 | lo = (lo + Math.imul(al1, bl6)) | 0; | ||
11363 | mid = (mid + Math.imul(al1, bh6)) | 0; | ||
11364 | mid = (mid + Math.imul(ah1, bl6)) | 0; | ||
11365 | hi = (hi + Math.imul(ah1, bh6)) | 0; | ||
11366 | lo = (lo + Math.imul(al0, bl7)) | 0; | ||
11367 | mid = (mid + Math.imul(al0, bh7)) | 0; | ||
11368 | mid = (mid + Math.imul(ah0, bl7)) | 0; | ||
11369 | hi = (hi + Math.imul(ah0, bh7)) | 0; | ||
11370 | var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11371 | c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; | ||
11372 | w7 &= 0x3ffffff; | ||
11373 | /* k = 8 */ | ||
11374 | lo = Math.imul(al8, bl0); | ||
11375 | mid = Math.imul(al8, bh0); | ||
11376 | mid = (mid + Math.imul(ah8, bl0)) | 0; | ||
11377 | hi = Math.imul(ah8, bh0); | ||
11378 | lo = (lo + Math.imul(al7, bl1)) | 0; | ||
11379 | mid = (mid + Math.imul(al7, bh1)) | 0; | ||
11380 | mid = (mid + Math.imul(ah7, bl1)) | 0; | ||
11381 | hi = (hi + Math.imul(ah7, bh1)) | 0; | ||
11382 | lo = (lo + Math.imul(al6, bl2)) | 0; | ||
11383 | mid = (mid + Math.imul(al6, bh2)) | 0; | ||
11384 | mid = (mid + Math.imul(ah6, bl2)) | 0; | ||
11385 | hi = (hi + Math.imul(ah6, bh2)) | 0; | ||
11386 | lo = (lo + Math.imul(al5, bl3)) | 0; | ||
11387 | mid = (mid + Math.imul(al5, bh3)) | 0; | ||
11388 | mid = (mid + Math.imul(ah5, bl3)) | 0; | ||
11389 | hi = (hi + Math.imul(ah5, bh3)) | 0; | ||
11390 | lo = (lo + Math.imul(al4, bl4)) | 0; | ||
11391 | mid = (mid + Math.imul(al4, bh4)) | 0; | ||
11392 | mid = (mid + Math.imul(ah4, bl4)) | 0; | ||
11393 | hi = (hi + Math.imul(ah4, bh4)) | 0; | ||
11394 | lo = (lo + Math.imul(al3, bl5)) | 0; | ||
11395 | mid = (mid + Math.imul(al3, bh5)) | 0; | ||
11396 | mid = (mid + Math.imul(ah3, bl5)) | 0; | ||
11397 | hi = (hi + Math.imul(ah3, bh5)) | 0; | ||
11398 | lo = (lo + Math.imul(al2, bl6)) | 0; | ||
11399 | mid = (mid + Math.imul(al2, bh6)) | 0; | ||
11400 | mid = (mid + Math.imul(ah2, bl6)) | 0; | ||
11401 | hi = (hi + Math.imul(ah2, bh6)) | 0; | ||
11402 | lo = (lo + Math.imul(al1, bl7)) | 0; | ||
11403 | mid = (mid + Math.imul(al1, bh7)) | 0; | ||
11404 | mid = (mid + Math.imul(ah1, bl7)) | 0; | ||
11405 | hi = (hi + Math.imul(ah1, bh7)) | 0; | ||
11406 | lo = (lo + Math.imul(al0, bl8)) | 0; | ||
11407 | mid = (mid + Math.imul(al0, bh8)) | 0; | ||
11408 | mid = (mid + Math.imul(ah0, bl8)) | 0; | ||
11409 | hi = (hi + Math.imul(ah0, bh8)) | 0; | ||
11410 | var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11411 | c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; | ||
11412 | w8 &= 0x3ffffff; | ||
11413 | /* k = 9 */ | ||
11414 | lo = Math.imul(al9, bl0); | ||
11415 | mid = Math.imul(al9, bh0); | ||
11416 | mid = (mid + Math.imul(ah9, bl0)) | 0; | ||
11417 | hi = Math.imul(ah9, bh0); | ||
11418 | lo = (lo + Math.imul(al8, bl1)) | 0; | ||
11419 | mid = (mid + Math.imul(al8, bh1)) | 0; | ||
11420 | mid = (mid + Math.imul(ah8, bl1)) | 0; | ||
11421 | hi = (hi + Math.imul(ah8, bh1)) | 0; | ||
11422 | lo = (lo + Math.imul(al7, bl2)) | 0; | ||
11423 | mid = (mid + Math.imul(al7, bh2)) | 0; | ||
11424 | mid = (mid + Math.imul(ah7, bl2)) | 0; | ||
11425 | hi = (hi + Math.imul(ah7, bh2)) | 0; | ||
11426 | lo = (lo + Math.imul(al6, bl3)) | 0; | ||
11427 | mid = (mid + Math.imul(al6, bh3)) | 0; | ||
11428 | mid = (mid + Math.imul(ah6, bl3)) | 0; | ||
11429 | hi = (hi + Math.imul(ah6, bh3)) | 0; | ||
11430 | lo = (lo + Math.imul(al5, bl4)) | 0; | ||
11431 | mid = (mid + Math.imul(al5, bh4)) | 0; | ||
11432 | mid = (mid + Math.imul(ah5, bl4)) | 0; | ||
11433 | hi = (hi + Math.imul(ah5, bh4)) | 0; | ||
11434 | lo = (lo + Math.imul(al4, bl5)) | 0; | ||
11435 | mid = (mid + Math.imul(al4, bh5)) | 0; | ||
11436 | mid = (mid + Math.imul(ah4, bl5)) | 0; | ||
11437 | hi = (hi + Math.imul(ah4, bh5)) | 0; | ||
11438 | lo = (lo + Math.imul(al3, bl6)) | 0; | ||
11439 | mid = (mid + Math.imul(al3, bh6)) | 0; | ||
11440 | mid = (mid + Math.imul(ah3, bl6)) | 0; | ||
11441 | hi = (hi + Math.imul(ah3, bh6)) | 0; | ||
11442 | lo = (lo + Math.imul(al2, bl7)) | 0; | ||
11443 | mid = (mid + Math.imul(al2, bh7)) | 0; | ||
11444 | mid = (mid + Math.imul(ah2, bl7)) | 0; | ||
11445 | hi = (hi + Math.imul(ah2, bh7)) | 0; | ||
11446 | lo = (lo + Math.imul(al1, bl8)) | 0; | ||
11447 | mid = (mid + Math.imul(al1, bh8)) | 0; | ||
11448 | mid = (mid + Math.imul(ah1, bl8)) | 0; | ||
11449 | hi = (hi + Math.imul(ah1, bh8)) | 0; | ||
11450 | lo = (lo + Math.imul(al0, bl9)) | 0; | ||
11451 | mid = (mid + Math.imul(al0, bh9)) | 0; | ||
11452 | mid = (mid + Math.imul(ah0, bl9)) | 0; | ||
11453 | hi = (hi + Math.imul(ah0, bh9)) | 0; | ||
11454 | var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11455 | c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; | ||
11456 | w9 &= 0x3ffffff; | ||
11457 | /* k = 10 */ | ||
11458 | lo = Math.imul(al9, bl1); | ||
11459 | mid = Math.imul(al9, bh1); | ||
11460 | mid = (mid + Math.imul(ah9, bl1)) | 0; | ||
11461 | hi = Math.imul(ah9, bh1); | ||
11462 | lo = (lo + Math.imul(al8, bl2)) | 0; | ||
11463 | mid = (mid + Math.imul(al8, bh2)) | 0; | ||
11464 | mid = (mid + Math.imul(ah8, bl2)) | 0; | ||
11465 | hi = (hi + Math.imul(ah8, bh2)) | 0; | ||
11466 | lo = (lo + Math.imul(al7, bl3)) | 0; | ||
11467 | mid = (mid + Math.imul(al7, bh3)) | 0; | ||
11468 | mid = (mid + Math.imul(ah7, bl3)) | 0; | ||
11469 | hi = (hi + Math.imul(ah7, bh3)) | 0; | ||
11470 | lo = (lo + Math.imul(al6, bl4)) | 0; | ||
11471 | mid = (mid + Math.imul(al6, bh4)) | 0; | ||
11472 | mid = (mid + Math.imul(ah6, bl4)) | 0; | ||
11473 | hi = (hi + Math.imul(ah6, bh4)) | 0; | ||
11474 | lo = (lo + Math.imul(al5, bl5)) | 0; | ||
11475 | mid = (mid + Math.imul(al5, bh5)) | 0; | ||
11476 | mid = (mid + Math.imul(ah5, bl5)) | 0; | ||
11477 | hi = (hi + Math.imul(ah5, bh5)) | 0; | ||
11478 | lo = (lo + Math.imul(al4, bl6)) | 0; | ||
11479 | mid = (mid + Math.imul(al4, bh6)) | 0; | ||
11480 | mid = (mid + Math.imul(ah4, bl6)) | 0; | ||
11481 | hi = (hi + Math.imul(ah4, bh6)) | 0; | ||
11482 | lo = (lo + Math.imul(al3, bl7)) | 0; | ||
11483 | mid = (mid + Math.imul(al3, bh7)) | 0; | ||
11484 | mid = (mid + Math.imul(ah3, bl7)) | 0; | ||
11485 | hi = (hi + Math.imul(ah3, bh7)) | 0; | ||
11486 | lo = (lo + Math.imul(al2, bl8)) | 0; | ||
11487 | mid = (mid + Math.imul(al2, bh8)) | 0; | ||
11488 | mid = (mid + Math.imul(ah2, bl8)) | 0; | ||
11489 | hi = (hi + Math.imul(ah2, bh8)) | 0; | ||
11490 | lo = (lo + Math.imul(al1, bl9)) | 0; | ||
11491 | mid = (mid + Math.imul(al1, bh9)) | 0; | ||
11492 | mid = (mid + Math.imul(ah1, bl9)) | 0; | ||
11493 | hi = (hi + Math.imul(ah1, bh9)) | 0; | ||
11494 | var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11495 | c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; | ||
11496 | w10 &= 0x3ffffff; | ||
11497 | /* k = 11 */ | ||
11498 | lo = Math.imul(al9, bl2); | ||
11499 | mid = Math.imul(al9, bh2); | ||
11500 | mid = (mid + Math.imul(ah9, bl2)) | 0; | ||
11501 | hi = Math.imul(ah9, bh2); | ||
11502 | lo = (lo + Math.imul(al8, bl3)) | 0; | ||
11503 | mid = (mid + Math.imul(al8, bh3)) | 0; | ||
11504 | mid = (mid + Math.imul(ah8, bl3)) | 0; | ||
11505 | hi = (hi + Math.imul(ah8, bh3)) | 0; | ||
11506 | lo = (lo + Math.imul(al7, bl4)) | 0; | ||
11507 | mid = (mid + Math.imul(al7, bh4)) | 0; | ||
11508 | mid = (mid + Math.imul(ah7, bl4)) | 0; | ||
11509 | hi = (hi + Math.imul(ah7, bh4)) | 0; | ||
11510 | lo = (lo + Math.imul(al6, bl5)) | 0; | ||
11511 | mid = (mid + Math.imul(al6, bh5)) | 0; | ||
11512 | mid = (mid + Math.imul(ah6, bl5)) | 0; | ||
11513 | hi = (hi + Math.imul(ah6, bh5)) | 0; | ||
11514 | lo = (lo + Math.imul(al5, bl6)) | 0; | ||
11515 | mid = (mid + Math.imul(al5, bh6)) | 0; | ||
11516 | mid = (mid + Math.imul(ah5, bl6)) | 0; | ||
11517 | hi = (hi + Math.imul(ah5, bh6)) | 0; | ||
11518 | lo = (lo + Math.imul(al4, bl7)) | 0; | ||
11519 | mid = (mid + Math.imul(al4, bh7)) | 0; | ||
11520 | mid = (mid + Math.imul(ah4, bl7)) | 0; | ||
11521 | hi = (hi + Math.imul(ah4, bh7)) | 0; | ||
11522 | lo = (lo + Math.imul(al3, bl8)) | 0; | ||
11523 | mid = (mid + Math.imul(al3, bh8)) | 0; | ||
11524 | mid = (mid + Math.imul(ah3, bl8)) | 0; | ||
11525 | hi = (hi + Math.imul(ah3, bh8)) | 0; | ||
11526 | lo = (lo + Math.imul(al2, bl9)) | 0; | ||
11527 | mid = (mid + Math.imul(al2, bh9)) | 0; | ||
11528 | mid = (mid + Math.imul(ah2, bl9)) | 0; | ||
11529 | hi = (hi + Math.imul(ah2, bh9)) | 0; | ||
11530 | var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11531 | c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; | ||
11532 | w11 &= 0x3ffffff; | ||
11533 | /* k = 12 */ | ||
11534 | lo = Math.imul(al9, bl3); | ||
11535 | mid = Math.imul(al9, bh3); | ||
11536 | mid = (mid + Math.imul(ah9, bl3)) | 0; | ||
11537 | hi = Math.imul(ah9, bh3); | ||
11538 | lo = (lo + Math.imul(al8, bl4)) | 0; | ||
11539 | mid = (mid + Math.imul(al8, bh4)) | 0; | ||
11540 | mid = (mid + Math.imul(ah8, bl4)) | 0; | ||
11541 | hi = (hi + Math.imul(ah8, bh4)) | 0; | ||
11542 | lo = (lo + Math.imul(al7, bl5)) | 0; | ||
11543 | mid = (mid + Math.imul(al7, bh5)) | 0; | ||
11544 | mid = (mid + Math.imul(ah7, bl5)) | 0; | ||
11545 | hi = (hi + Math.imul(ah7, bh5)) | 0; | ||
11546 | lo = (lo + Math.imul(al6, bl6)) | 0; | ||
11547 | mid = (mid + Math.imul(al6, bh6)) | 0; | ||
11548 | mid = (mid + Math.imul(ah6, bl6)) | 0; | ||
11549 | hi = (hi + Math.imul(ah6, bh6)) | 0; | ||
11550 | lo = (lo + Math.imul(al5, bl7)) | 0; | ||
11551 | mid = (mid + Math.imul(al5, bh7)) | 0; | ||
11552 | mid = (mid + Math.imul(ah5, bl7)) | 0; | ||
11553 | hi = (hi + Math.imul(ah5, bh7)) | 0; | ||
11554 | lo = (lo + Math.imul(al4, bl8)) | 0; | ||
11555 | mid = (mid + Math.imul(al4, bh8)) | 0; | ||
11556 | mid = (mid + Math.imul(ah4, bl8)) | 0; | ||
11557 | hi = (hi + Math.imul(ah4, bh8)) | 0; | ||
11558 | lo = (lo + Math.imul(al3, bl9)) | 0; | ||
11559 | mid = (mid + Math.imul(al3, bh9)) | 0; | ||
11560 | mid = (mid + Math.imul(ah3, bl9)) | 0; | ||
11561 | hi = (hi + Math.imul(ah3, bh9)) | 0; | ||
11562 | var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11563 | c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; | ||
11564 | w12 &= 0x3ffffff; | ||
11565 | /* k = 13 */ | ||
11566 | lo = Math.imul(al9, bl4); | ||
11567 | mid = Math.imul(al9, bh4); | ||
11568 | mid = (mid + Math.imul(ah9, bl4)) | 0; | ||
11569 | hi = Math.imul(ah9, bh4); | ||
11570 | lo = (lo + Math.imul(al8, bl5)) | 0; | ||
11571 | mid = (mid + Math.imul(al8, bh5)) | 0; | ||
11572 | mid = (mid + Math.imul(ah8, bl5)) | 0; | ||
11573 | hi = (hi + Math.imul(ah8, bh5)) | 0; | ||
11574 | lo = (lo + Math.imul(al7, bl6)) | 0; | ||
11575 | mid = (mid + Math.imul(al7, bh6)) | 0; | ||
11576 | mid = (mid + Math.imul(ah7, bl6)) | 0; | ||
11577 | hi = (hi + Math.imul(ah7, bh6)) | 0; | ||
11578 | lo = (lo + Math.imul(al6, bl7)) | 0; | ||
11579 | mid = (mid + Math.imul(al6, bh7)) | 0; | ||
11580 | mid = (mid + Math.imul(ah6, bl7)) | 0; | ||
11581 | hi = (hi + Math.imul(ah6, bh7)) | 0; | ||
11582 | lo = (lo + Math.imul(al5, bl8)) | 0; | ||
11583 | mid = (mid + Math.imul(al5, bh8)) | 0; | ||
11584 | mid = (mid + Math.imul(ah5, bl8)) | 0; | ||
11585 | hi = (hi + Math.imul(ah5, bh8)) | 0; | ||
11586 | lo = (lo + Math.imul(al4, bl9)) | 0; | ||
11587 | mid = (mid + Math.imul(al4, bh9)) | 0; | ||
11588 | mid = (mid + Math.imul(ah4, bl9)) | 0; | ||
11589 | hi = (hi + Math.imul(ah4, bh9)) | 0; | ||
11590 | var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11591 | c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; | ||
11592 | w13 &= 0x3ffffff; | ||
11593 | /* k = 14 */ | ||
11594 | lo = Math.imul(al9, bl5); | ||
11595 | mid = Math.imul(al9, bh5); | ||
11596 | mid = (mid + Math.imul(ah9, bl5)) | 0; | ||
11597 | hi = Math.imul(ah9, bh5); | ||
11598 | lo = (lo + Math.imul(al8, bl6)) | 0; | ||
11599 | mid = (mid + Math.imul(al8, bh6)) | 0; | ||
11600 | mid = (mid + Math.imul(ah8, bl6)) | 0; | ||
11601 | hi = (hi + Math.imul(ah8, bh6)) | 0; | ||
11602 | lo = (lo + Math.imul(al7, bl7)) | 0; | ||
11603 | mid = (mid + Math.imul(al7, bh7)) | 0; | ||
11604 | mid = (mid + Math.imul(ah7, bl7)) | 0; | ||
11605 | hi = (hi + Math.imul(ah7, bh7)) | 0; | ||
11606 | lo = (lo + Math.imul(al6, bl8)) | 0; | ||
11607 | mid = (mid + Math.imul(al6, bh8)) | 0; | ||
11608 | mid = (mid + Math.imul(ah6, bl8)) | 0; | ||
11609 | hi = (hi + Math.imul(ah6, bh8)) | 0; | ||
11610 | lo = (lo + Math.imul(al5, bl9)) | 0; | ||
11611 | mid = (mid + Math.imul(al5, bh9)) | 0; | ||
11612 | mid = (mid + Math.imul(ah5, bl9)) | 0; | ||
11613 | hi = (hi + Math.imul(ah5, bh9)) | 0; | ||
11614 | var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11615 | c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; | ||
11616 | w14 &= 0x3ffffff; | ||
11617 | /* k = 15 */ | ||
11618 | lo = Math.imul(al9, bl6); | ||
11619 | mid = Math.imul(al9, bh6); | ||
11620 | mid = (mid + Math.imul(ah9, bl6)) | 0; | ||
11621 | hi = Math.imul(ah9, bh6); | ||
11622 | lo = (lo + Math.imul(al8, bl7)) | 0; | ||
11623 | mid = (mid + Math.imul(al8, bh7)) | 0; | ||
11624 | mid = (mid + Math.imul(ah8, bl7)) | 0; | ||
11625 | hi = (hi + Math.imul(ah8, bh7)) | 0; | ||
11626 | lo = (lo + Math.imul(al7, bl8)) | 0; | ||
11627 | mid = (mid + Math.imul(al7, bh8)) | 0; | ||
11628 | mid = (mid + Math.imul(ah7, bl8)) | 0; | ||
11629 | hi = (hi + Math.imul(ah7, bh8)) | 0; | ||
11630 | lo = (lo + Math.imul(al6, bl9)) | 0; | ||
11631 | mid = (mid + Math.imul(al6, bh9)) | 0; | ||
11632 | mid = (mid + Math.imul(ah6, bl9)) | 0; | ||
11633 | hi = (hi + Math.imul(ah6, bh9)) | 0; | ||
11634 | var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11635 | c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; | ||
11636 | w15 &= 0x3ffffff; | ||
11637 | /* k = 16 */ | ||
11638 | lo = Math.imul(al9, bl7); | ||
11639 | mid = Math.imul(al9, bh7); | ||
11640 | mid = (mid + Math.imul(ah9, bl7)) | 0; | ||
11641 | hi = Math.imul(ah9, bh7); | ||
11642 | lo = (lo + Math.imul(al8, bl8)) | 0; | ||
11643 | mid = (mid + Math.imul(al8, bh8)) | 0; | ||
11644 | mid = (mid + Math.imul(ah8, bl8)) | 0; | ||
11645 | hi = (hi + Math.imul(ah8, bh8)) | 0; | ||
11646 | lo = (lo + Math.imul(al7, bl9)) | 0; | ||
11647 | mid = (mid + Math.imul(al7, bh9)) | 0; | ||
11648 | mid = (mid + Math.imul(ah7, bl9)) | 0; | ||
11649 | hi = (hi + Math.imul(ah7, bh9)) | 0; | ||
11650 | var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11651 | c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; | ||
11652 | w16 &= 0x3ffffff; | ||
11653 | /* k = 17 */ | ||
11654 | lo = Math.imul(al9, bl8); | ||
11655 | mid = Math.imul(al9, bh8); | ||
11656 | mid = (mid + Math.imul(ah9, bl8)) | 0; | ||
11657 | hi = Math.imul(ah9, bh8); | ||
11658 | lo = (lo + Math.imul(al8, bl9)) | 0; | ||
11659 | mid = (mid + Math.imul(al8, bh9)) | 0; | ||
11660 | mid = (mid + Math.imul(ah8, bl9)) | 0; | ||
11661 | hi = (hi + Math.imul(ah8, bh9)) | 0; | ||
11662 | var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11663 | c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; | ||
11664 | w17 &= 0x3ffffff; | ||
11665 | /* k = 18 */ | ||
11666 | lo = Math.imul(al9, bl9); | ||
11667 | mid = Math.imul(al9, bh9); | ||
11668 | mid = (mid + Math.imul(ah9, bl9)) | 0; | ||
11669 | hi = Math.imul(ah9, bh9); | ||
11670 | var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; | ||
11671 | c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; | ||
11672 | w18 &= 0x3ffffff; | ||
11673 | o[0] = w0; | ||
11674 | o[1] = w1; | ||
11675 | o[2] = w2; | ||
11676 | o[3] = w3; | ||
11677 | o[4] = w4; | ||
11678 | o[5] = w5; | ||
11679 | o[6] = w6; | ||
11680 | o[7] = w7; | ||
11681 | o[8] = w8; | ||
11682 | o[9] = w9; | ||
11683 | o[10] = w10; | ||
11684 | o[11] = w11; | ||
11685 | o[12] = w12; | ||
11686 | o[13] = w13; | ||
11687 | o[14] = w14; | ||
11688 | o[15] = w15; | ||
11689 | o[16] = w16; | ||
11690 | o[17] = w17; | ||
11691 | o[18] = w18; | ||
11692 | if (c !== 0) { | ||
11693 | o[19] = c; | ||
11694 | out.length++; | ||
11695 | } | ||
11696 | return out; | ||
11697 | }; | ||
11698 | |||
11699 | // Polyfill comb | ||
11700 | if (!Math.imul) { | ||
11701 | comb10MulTo = smallMulTo; | ||
11702 | } | ||
11703 | |||
11704 | function bigMulTo (self, num, out) { | ||
11705 | out.negative = num.negative ^ self.negative; | ||
11706 | out.length = self.length + num.length; | ||
11707 | |||
11708 | var carry = 0; | ||
11709 | var hncarry = 0; | ||
11710 | for (var k = 0; k < out.length - 1; k++) { | ||
11711 | // Sum all words with the same `i + j = k` and accumulate `ncarry`, | ||
11712 | // note that ncarry could be >= 0x3ffffff | ||
11713 | var ncarry = hncarry; | ||
11714 | hncarry = 0; | ||
11715 | var rword = carry & 0x3ffffff; | ||
11716 | var maxJ = Math.min(k, num.length - 1); | ||
11717 | for (var j = Math.max(0, k - self.length + 1); j <= maxJ; j++) { | ||
11718 | var i = k - j; | ||
11719 | var a = self.words[i] | 0; | ||
11720 | var b = num.words[j] | 0; | ||
11721 | var r = a * b; | ||
11722 | |||
11723 | var lo = r & 0x3ffffff; | ||
11724 | ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; | ||
11725 | lo = (lo + rword) | 0; | ||
11726 | rword = lo & 0x3ffffff; | ||
11727 | ncarry = (ncarry + (lo >>> 26)) | 0; | ||
11728 | |||
11729 | hncarry += ncarry >>> 26; | ||
11730 | ncarry &= 0x3ffffff; | ||
11731 | } | ||
11732 | out.words[k] = rword; | ||
11733 | carry = ncarry; | ||
11734 | ncarry = hncarry; | ||
11735 | } | ||
11736 | if (carry !== 0) { | ||
11737 | out.words[k] = carry; | ||
11738 | } else { | ||
11739 | out.length--; | ||
11740 | } | ||
11741 | |||
11742 | return out.strip(); | ||
11743 | } | ||
11744 | |||
11745 | function jumboMulTo (self, num, out) { | ||
11746 | var fftm = new FFTM(); | ||
11747 | return fftm.mulp(self, num, out); | ||
11748 | } | ||
11749 | |||
11750 | BN.prototype.mulTo = function mulTo (num, out) { | ||
11751 | var res; | ||
11752 | var len = this.length + num.length; | ||
11753 | if (this.length === 10 && num.length === 10) { | ||
11754 | res = comb10MulTo(this, num, out); | ||
11755 | } else if (len < 63) { | ||
11756 | res = smallMulTo(this, num, out); | ||
11757 | } else if (len < 1024) { | ||
11758 | res = bigMulTo(this, num, out); | ||
11759 | } else { | ||
11760 | res = jumboMulTo(this, num, out); | ||
11761 | } | ||
11762 | |||
11763 | return res; | ||
11764 | }; | ||
11765 | |||
11766 | // Cooley-Tukey algorithm for FFT | ||
11767 | // slightly revisited to rely on looping instead of recursion | ||
11768 | |||
11769 | function FFTM (x, y) { | ||
11770 | this.x = x; | ||
11771 | this.y = y; | ||
11772 | } | ||
11773 | |||
11774 | FFTM.prototype.makeRBT = function makeRBT (N) { | ||
11775 | var t = new Array(N); | ||
11776 | var l = BN.prototype._countBits(N) - 1; | ||
11777 | for (var i = 0; i < N; i++) { | ||
11778 | t[i] = this.revBin(i, l, N); | ||
11779 | } | ||
11780 | |||
11781 | return t; | ||
11782 | }; | ||
11783 | |||
11784 | // Returns binary-reversed representation of `x` | ||
11785 | FFTM.prototype.revBin = function revBin (x, l, N) { | ||
11786 | if (x === 0 || x === N - 1) return x; | ||
11787 | |||
11788 | var rb = 0; | ||
11789 | for (var i = 0; i < l; i++) { | ||
11790 | rb |= (x & 1) << (l - i - 1); | ||
11791 | x >>= 1; | ||
11792 | } | ||
11793 | |||
11794 | return rb; | ||
11795 | }; | ||
11796 | |||
11797 | // Performs "tweedling" phase, therefore 'emulating' | ||
11798 | // behaviour of the recursive algorithm | ||
11799 | FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { | ||
11800 | for (var i = 0; i < N; i++) { | ||
11801 | rtws[i] = rws[rbt[i]]; | ||
11802 | itws[i] = iws[rbt[i]]; | ||
11803 | } | ||
11804 | }; | ||
11805 | |||
11806 | FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { | ||
11807 | this.permute(rbt, rws, iws, rtws, itws, N); | ||
11808 | |||
11809 | for (var s = 1; s < N; s <<= 1) { | ||
11810 | var l = s << 1; | ||
11811 | |||
11812 | var rtwdf = Math.cos(2 * Math.PI / l); | ||
11813 | var itwdf = Math.sin(2 * Math.PI / l); | ||
11814 | |||
11815 | for (var p = 0; p < N; p += l) { | ||
11816 | var rtwdf_ = rtwdf; | ||
11817 | var itwdf_ = itwdf; | ||
11818 | |||
11819 | for (var j = 0; j < s; j++) { | ||
11820 | var re = rtws[p + j]; | ||
11821 | var ie = itws[p + j]; | ||
11822 | |||
11823 | var ro = rtws[p + j + s]; | ||
11824 | var io = itws[p + j + s]; | ||
11825 | |||
11826 | var rx = rtwdf_ * ro - itwdf_ * io; | ||
11827 | |||
11828 | io = rtwdf_ * io + itwdf_ * ro; | ||
11829 | ro = rx; | ||
11830 | |||
11831 | rtws[p + j] = re + ro; | ||
11832 | itws[p + j] = ie + io; | ||
11833 | |||
11834 | rtws[p + j + s] = re - ro; | ||
11835 | itws[p + j + s] = ie - io; | ||
11836 | |||
11837 | /* jshint maxdepth : false */ | ||
11838 | if (j !== l) { | ||
11839 | rx = rtwdf * rtwdf_ - itwdf * itwdf_; | ||
11840 | |||
11841 | itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; | ||
11842 | rtwdf_ = rx; | ||
11843 | } | ||
11844 | } | ||
11845 | } | ||
11846 | } | ||
11847 | }; | ||
11848 | |||
11849 | FFTM.prototype.guessLen13b = function guessLen13b (n, m) { | ||
11850 | var N = Math.max(m, n) | 1; | ||
11851 | var odd = N & 1; | ||
11852 | var i = 0; | ||
11853 | for (N = N / 2 | 0; N; N = N >>> 1) { | ||
11854 | i++; | ||
11855 | } | ||
11856 | |||
11857 | return 1 << i + 1 + odd; | ||
11858 | }; | ||
11859 | |||
11860 | FFTM.prototype.conjugate = function conjugate (rws, iws, N) { | ||
11861 | if (N <= 1) return; | ||
11862 | |||
11863 | for (var i = 0; i < N / 2; i++) { | ||
11864 | var t = rws[i]; | ||
11865 | |||
11866 | rws[i] = rws[N - i - 1]; | ||
11867 | rws[N - i - 1] = t; | ||
11868 | |||
11869 | t = iws[i]; | ||
11870 | |||
11871 | iws[i] = -iws[N - i - 1]; | ||
11872 | iws[N - i - 1] = -t; | ||
11873 | } | ||
11874 | }; | ||
11875 | |||
11876 | FFTM.prototype.normalize13b = function normalize13b (ws, N) { | ||
11877 | var carry = 0; | ||
11878 | for (var i = 0; i < N / 2; i++) { | ||
11879 | var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + | ||
11880 | Math.round(ws[2 * i] / N) + | ||
11881 | carry; | ||
11882 | |||
11883 | ws[i] = w & 0x3ffffff; | ||
11884 | |||
11885 | if (w < 0x4000000) { | ||
11886 | carry = 0; | ||
11887 | } else { | ||
11888 | carry = w / 0x4000000 | 0; | ||
11889 | } | ||
11890 | } | ||
11891 | |||
11892 | return ws; | ||
11893 | }; | ||
11894 | |||
11895 | FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { | ||
11896 | var carry = 0; | ||
11897 | for (var i = 0; i < len; i++) { | ||
11898 | carry = carry + (ws[i] | 0); | ||
11899 | |||
11900 | rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; | ||
11901 | rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; | ||
11902 | } | ||
11903 | |||
11904 | // Pad with zeroes | ||
11905 | for (i = 2 * len; i < N; ++i) { | ||
11906 | rws[i] = 0; | ||
11907 | } | ||
11908 | |||
11909 | assert(carry === 0); | ||
11910 | assert((carry & ~0x1fff) === 0); | ||
11911 | }; | ||
11912 | |||
11913 | FFTM.prototype.stub = function stub (N) { | ||
11914 | var ph = new Array(N); | ||
11915 | for (var i = 0; i < N; i++) { | ||
11916 | ph[i] = 0; | ||
11917 | } | ||
11918 | |||
11919 | return ph; | ||
11920 | }; | ||
11921 | |||
11922 | FFTM.prototype.mulp = function mulp (x, y, out) { | ||
11923 | var N = 2 * this.guessLen13b(x.length, y.length); | ||
11924 | |||
11925 | var rbt = this.makeRBT(N); | ||
11926 | |||
11927 | var _ = this.stub(N); | ||
11928 | |||
11929 | var rws = new Array(N); | ||
11930 | var rwst = new Array(N); | ||
11931 | var iwst = new Array(N); | ||
11932 | |||
11933 | var nrws = new Array(N); | ||
11934 | var nrwst = new Array(N); | ||
11935 | var niwst = new Array(N); | ||
11936 | |||
11937 | var rmws = out.words; | ||
11938 | rmws.length = N; | ||
11939 | |||
11940 | this.convert13b(x.words, x.length, rws, N); | ||
11941 | this.convert13b(y.words, y.length, nrws, N); | ||
11942 | |||
11943 | this.transform(rws, _, rwst, iwst, N, rbt); | ||
11944 | this.transform(nrws, _, nrwst, niwst, N, rbt); | ||
11945 | |||
11946 | for (var i = 0; i < N; i++) { | ||
11947 | var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; | ||
11948 | iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; | ||
11949 | rwst[i] = rx; | ||
11950 | } | ||
11951 | |||
11952 | this.conjugate(rwst, iwst, N); | ||
11953 | this.transform(rwst, iwst, rmws, _, N, rbt); | ||
11954 | this.conjugate(rmws, _, N); | ||
11955 | this.normalize13b(rmws, N); | ||
11956 | |||
11957 | out.negative = x.negative ^ y.negative; | ||
11958 | out.length = x.length + y.length; | ||
11959 | return out.strip(); | ||
11960 | }; | ||
11961 | |||
11962 | // Multiply `this` by `num` | ||
11963 | BN.prototype.mul = function mul (num) { | ||
11964 | var out = new BN(null); | ||
11965 | out.words = new Array(this.length + num.length); | ||
11966 | return this.mulTo(num, out); | ||
11967 | }; | ||
11968 | |||
11969 | // Multiply employing FFT | ||
11970 | BN.prototype.mulf = function mulf (num) { | ||
11971 | var out = new BN(null); | ||
11972 | out.words = new Array(this.length + num.length); | ||
11973 | return jumboMulTo(this, num, out); | ||
11974 | }; | ||
11975 | |||
11976 | // In-place Multiplication | ||
11977 | BN.prototype.imul = function imul (num) { | ||
11978 | return this.clone().mulTo(num, this); | ||
11979 | }; | ||
11980 | |||
11981 | BN.prototype.imuln = function imuln (num) { | ||
11982 | assert(typeof num === 'number'); | ||
11983 | assert(num < 0x4000000); | ||
11984 | |||
11985 | // Carry | ||
11986 | var carry = 0; | ||
11987 | for (var i = 0; i < this.length; i++) { | ||
11988 | var w = (this.words[i] | 0) * num; | ||
11989 | var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); | ||
11990 | carry >>= 26; | ||
11991 | carry += (w / 0x4000000) | 0; | ||
11992 | // NOTE: lo is 27bit maximum | ||
11993 | carry += lo >>> 26; | ||
11994 | this.words[i] = lo & 0x3ffffff; | ||
11995 | } | ||
11996 | |||
11997 | if (carry !== 0) { | ||
11998 | this.words[i] = carry; | ||
11999 | this.length++; | ||
12000 | } | ||
12001 | |||
12002 | return this; | ||
12003 | }; | ||
12004 | |||
12005 | BN.prototype.muln = function muln (num) { | ||
12006 | return this.clone().imuln(num); | ||
12007 | }; | ||
12008 | |||
12009 | // `this` * `this` | ||
12010 | BN.prototype.sqr = function sqr () { | ||
12011 | return this.mul(this); | ||
12012 | }; | ||
12013 | |||
12014 | // `this` * `this` in-place | ||
12015 | BN.prototype.isqr = function isqr () { | ||
12016 | return this.imul(this.clone()); | ||
12017 | }; | ||
12018 | |||
12019 | // Math.pow(`this`, `num`) | ||
12020 | BN.prototype.pow = function pow (num) { | ||
12021 | var w = toBitArray(num); | ||
12022 | if (w.length === 0) return new BN(1); | ||
12023 | |||
12024 | // Skip leading zeroes | ||
12025 | var res = this; | ||
12026 | for (var i = 0; i < w.length; i++, res = res.sqr()) { | ||
12027 | if (w[i] !== 0) break; | ||
12028 | } | ||
12029 | |||
12030 | if (++i < w.length) { | ||
12031 | for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { | ||
12032 | if (w[i] === 0) continue; | ||
12033 | |||
12034 | res = res.mul(q); | ||
12035 | } | ||
12036 | } | ||
12037 | |||
12038 | return res; | ||
12039 | }; | ||
12040 | |||
12041 | // Shift-left in-place | ||
12042 | BN.prototype.iushln = function iushln (bits) { | ||
12043 | assert(typeof bits === 'number' && bits >= 0); | ||
12044 | var r = bits % 26; | ||
12045 | var s = (bits - r) / 26; | ||
12046 | var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); | ||
12047 | var i; | ||
12048 | |||
12049 | if (r !== 0) { | ||
12050 | var carry = 0; | ||
12051 | |||
12052 | for (i = 0; i < this.length; i++) { | ||
12053 | var newCarry = this.words[i] & carryMask; | ||
12054 | var c = ((this.words[i] | 0) - newCarry) << r; | ||
12055 | this.words[i] = c | carry; | ||
12056 | carry = newCarry >>> (26 - r); | ||
12057 | } | ||
12058 | |||
12059 | if (carry) { | ||
12060 | this.words[i] = carry; | ||
12061 | this.length++; | ||
12062 | } | ||
12063 | } | ||
12064 | |||
12065 | if (s !== 0) { | ||
12066 | for (i = this.length - 1; i >= 0; i--) { | ||
12067 | this.words[i + s] = this.words[i]; | ||
12068 | } | ||
12069 | |||
12070 | for (i = 0; i < s; i++) { | ||
12071 | this.words[i] = 0; | ||
12072 | } | ||
12073 | |||
12074 | this.length += s; | ||
12075 | } | ||
12076 | |||
12077 | return this.strip(); | ||
12078 | }; | ||
12079 | |||
12080 | BN.prototype.ishln = function ishln (bits) { | ||
12081 | // TODO(indutny): implement me | ||
12082 | assert(this.negative === 0); | ||
12083 | return this.iushln(bits); | ||
12084 | }; | ||
12085 | |||
12086 | // Shift-right in-place | ||
12087 | // NOTE: `hint` is a lowest bit before trailing zeroes | ||
12088 | // NOTE: if `extended` is present - it will be filled with destroyed bits | ||
12089 | BN.prototype.iushrn = function iushrn (bits, hint, extended) { | ||
12090 | assert(typeof bits === 'number' && bits >= 0); | ||
12091 | var h; | ||
12092 | if (hint) { | ||
12093 | h = (hint - (hint % 26)) / 26; | ||
12094 | } else { | ||
12095 | h = 0; | ||
12096 | } | ||
12097 | |||
12098 | var r = bits % 26; | ||
12099 | var s = Math.min((bits - r) / 26, this.length); | ||
12100 | var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); | ||
12101 | var maskedWords = extended; | ||
12102 | |||
12103 | h -= s; | ||
12104 | h = Math.max(0, h); | ||
12105 | |||
12106 | // Extended mode, copy masked part | ||
12107 | if (maskedWords) { | ||
12108 | for (var i = 0; i < s; i++) { | ||
12109 | maskedWords.words[i] = this.words[i]; | ||
12110 | } | ||
12111 | maskedWords.length = s; | ||
12112 | } | ||
12113 | |||
12114 | if (s === 0) { | ||
12115 | // No-op, we should not move anything at all | ||
12116 | } else if (this.length > s) { | ||
12117 | this.length -= s; | ||
12118 | for (i = 0; i < this.length; i++) { | ||
12119 | this.words[i] = this.words[i + s]; | ||
12120 | } | ||
12121 | } else { | ||
12122 | this.words[0] = 0; | ||
12123 | this.length = 1; | ||
12124 | } | ||
12125 | |||
12126 | var carry = 0; | ||
12127 | for (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { | ||
12128 | var word = this.words[i] | 0; | ||
12129 | this.words[i] = (carry << (26 - r)) | (word >>> r); | ||
12130 | carry = word & mask; | ||
12131 | } | ||
12132 | |||
12133 | // Push carried bits as a mask | ||
12134 | if (maskedWords && carry !== 0) { | ||
12135 | maskedWords.words[maskedWords.length++] = carry; | ||
12136 | } | ||
12137 | |||
12138 | if (this.length === 0) { | ||
12139 | this.words[0] = 0; | ||
12140 | this.length = 1; | ||
12141 | } | ||
12142 | |||
12143 | return this.strip(); | ||
12144 | }; | ||
12145 | |||
12146 | BN.prototype.ishrn = function ishrn (bits, hint, extended) { | ||
12147 | // TODO(indutny): implement me | ||
12148 | assert(this.negative === 0); | ||
12149 | return this.iushrn(bits, hint, extended); | ||
12150 | }; | ||
12151 | |||
12152 | // Shift-left | ||
12153 | BN.prototype.shln = function shln (bits) { | ||
12154 | return this.clone().ishln(bits); | ||
12155 | }; | ||
12156 | |||
12157 | BN.prototype.ushln = function ushln (bits) { | ||
12158 | return this.clone().iushln(bits); | ||
12159 | }; | ||
12160 | |||
12161 | // Shift-right | ||
12162 | BN.prototype.shrn = function shrn (bits) { | ||
12163 | return this.clone().ishrn(bits); | ||
12164 | }; | ||
12165 | |||
12166 | BN.prototype.ushrn = function ushrn (bits) { | ||
12167 | return this.clone().iushrn(bits); | ||
12168 | }; | ||
12169 | |||
12170 | // Test if n bit is set | ||
12171 | BN.prototype.testn = function testn (bit) { | ||
12172 | assert(typeof bit === 'number' && bit >= 0); | ||
12173 | var r = bit % 26; | ||
12174 | var s = (bit - r) / 26; | ||
12175 | var q = 1 << r; | ||
12176 | |||
12177 | // Fast case: bit is much higher than all existing words | ||
12178 | if (this.length <= s) return false; | ||
12179 | |||
12180 | // Check bit and return | ||
12181 | var w = this.words[s]; | ||
12182 | |||
12183 | return !!(w & q); | ||
12184 | }; | ||
12185 | |||
12186 | // Return only lowers bits of number (in-place) | ||
12187 | BN.prototype.imaskn = function imaskn (bits) { | ||
12188 | assert(typeof bits === 'number' && bits >= 0); | ||
12189 | var r = bits % 26; | ||
12190 | var s = (bits - r) / 26; | ||
12191 | |||
12192 | assert(this.negative === 0, 'imaskn works only with positive numbers'); | ||
12193 | |||
12194 | if (this.length <= s) { | ||
12195 | return this; | ||
12196 | } | ||
12197 | |||
12198 | if (r !== 0) { | ||
12199 | s++; | ||
12200 | } | ||
12201 | this.length = Math.min(s, this.length); | ||
12202 | |||
12203 | if (r !== 0) { | ||
12204 | var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); | ||
12205 | this.words[this.length - 1] &= mask; | ||
12206 | } | ||
12207 | |||
12208 | return this.strip(); | ||
12209 | }; | ||
12210 | |||
12211 | // Return only lowers bits of number | ||
12212 | BN.prototype.maskn = function maskn (bits) { | ||
12213 | return this.clone().imaskn(bits); | ||
12214 | }; | ||
12215 | |||
12216 | // Add plain number `num` to `this` | ||
12217 | BN.prototype.iaddn = function iaddn (num) { | ||
12218 | assert(typeof num === 'number'); | ||
12219 | assert(num < 0x4000000); | ||
12220 | if (num < 0) return this.isubn(-num); | ||
12221 | |||
12222 | // Possible sign change | ||
12223 | if (this.negative !== 0) { | ||
12224 | if (this.length === 1 && (this.words[0] | 0) < num) { | ||
12225 | this.words[0] = num - (this.words[0] | 0); | ||
12226 | this.negative = 0; | ||
12227 | return this; | ||
12228 | } | ||
12229 | |||
12230 | this.negative = 0; | ||
12231 | this.isubn(num); | ||
12232 | this.negative = 1; | ||
12233 | return this; | ||
12234 | } | ||
12235 | |||
12236 | // Add without checks | ||
12237 | return this._iaddn(num); | ||
12238 | }; | ||
12239 | |||
12240 | BN.prototype._iaddn = function _iaddn (num) { | ||
12241 | this.words[0] += num; | ||
12242 | |||
12243 | // Carry | ||
12244 | for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { | ||
12245 | this.words[i] -= 0x4000000; | ||
12246 | if (i === this.length - 1) { | ||
12247 | this.words[i + 1] = 1; | ||
12248 | } else { | ||
12249 | this.words[i + 1]++; | ||
12250 | } | ||
12251 | } | ||
12252 | this.length = Math.max(this.length, i + 1); | ||
12253 | |||
12254 | return this; | ||
12255 | }; | ||
12256 | |||
12257 | // Subtract plain number `num` from `this` | ||
12258 | BN.prototype.isubn = function isubn (num) { | ||
12259 | assert(typeof num === 'number'); | ||
12260 | assert(num < 0x4000000); | ||
12261 | if (num < 0) return this.iaddn(-num); | ||
12262 | |||
12263 | if (this.negative !== 0) { | ||
12264 | this.negative = 0; | ||
12265 | this.iaddn(num); | ||
12266 | this.negative = 1; | ||
12267 | return this; | ||
12268 | } | ||
12269 | |||
12270 | this.words[0] -= num; | ||
12271 | |||
12272 | if (this.length === 1 && this.words[0] < 0) { | ||
12273 | this.words[0] = -this.words[0]; | ||
12274 | this.negative = 1; | ||
12275 | } else { | ||
12276 | // Carry | ||
12277 | for (var i = 0; i < this.length && this.words[i] < 0; i++) { | ||
12278 | this.words[i] += 0x4000000; | ||
12279 | this.words[i + 1] -= 1; | ||
12280 | } | ||
12281 | } | ||
12282 | |||
12283 | return this.strip(); | ||
12284 | }; | ||
12285 | |||
12286 | BN.prototype.addn = function addn (num) { | ||
12287 | return this.clone().iaddn(num); | ||
12288 | }; | ||
12289 | |||
12290 | BN.prototype.subn = function subn (num) { | ||
12291 | return this.clone().isubn(num); | ||
12292 | }; | ||
12293 | |||
12294 | BN.prototype.iabs = function iabs () { | ||
12295 | this.negative = 0; | ||
12296 | |||
12297 | return this; | ||
12298 | }; | ||
12299 | |||
12300 | BN.prototype.abs = function abs () { | ||
12301 | return this.clone().iabs(); | ||
12302 | }; | ||
12303 | |||
12304 | BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { | ||
12305 | var len = num.length + shift; | ||
12306 | var i; | ||
12307 | |||
12308 | this._expand(len); | ||
12309 | |||
12310 | var w; | ||
12311 | var carry = 0; | ||
12312 | for (i = 0; i < num.length; i++) { | ||
12313 | w = (this.words[i + shift] | 0) + carry; | ||
12314 | var right = (num.words[i] | 0) * mul; | ||
12315 | w -= right & 0x3ffffff; | ||
12316 | carry = (w >> 26) - ((right / 0x4000000) | 0); | ||
12317 | this.words[i + shift] = w & 0x3ffffff; | ||
12318 | } | ||
12319 | for (; i < this.length - shift; i++) { | ||
12320 | w = (this.words[i + shift] | 0) + carry; | ||
12321 | carry = w >> 26; | ||
12322 | this.words[i + shift] = w & 0x3ffffff; | ||
12323 | } | ||
12324 | |||
12325 | if (carry === 0) return this.strip(); | ||
12326 | |||
12327 | // Subtraction overflow | ||
12328 | assert(carry === -1); | ||
12329 | carry = 0; | ||
12330 | for (i = 0; i < this.length; i++) { | ||
12331 | w = -(this.words[i] | 0) + carry; | ||
12332 | carry = w >> 26; | ||
12333 | this.words[i] = w & 0x3ffffff; | ||
12334 | } | ||
12335 | this.negative = 1; | ||
12336 | |||
12337 | return this.strip(); | ||
12338 | }; | ||
12339 | |||
12340 | BN.prototype._wordDiv = function _wordDiv (num, mode) { | ||
12341 | var shift = this.length - num.length; | ||
12342 | |||
12343 | var a = this.clone(); | ||
12344 | var b = num; | ||
12345 | |||
12346 | // Normalize | ||
12347 | var bhi = b.words[b.length - 1] | 0; | ||
12348 | var bhiBits = this._countBits(bhi); | ||
12349 | shift = 26 - bhiBits; | ||
12350 | if (shift !== 0) { | ||
12351 | b = b.ushln(shift); | ||
12352 | a.iushln(shift); | ||
12353 | bhi = b.words[b.length - 1] | 0; | ||
12354 | } | ||
12355 | |||
12356 | // Initialize quotient | ||
12357 | var m = a.length - b.length; | ||
12358 | var q; | ||
12359 | |||
12360 | if (mode !== 'mod') { | ||
12361 | q = new BN(null); | ||
12362 | q.length = m + 1; | ||
12363 | q.words = new Array(q.length); | ||
12364 | for (var i = 0; i < q.length; i++) { | ||
12365 | q.words[i] = 0; | ||
12366 | } | ||
12367 | } | ||
12368 | |||
12369 | var diff = a.clone()._ishlnsubmul(b, 1, m); | ||
12370 | if (diff.negative === 0) { | ||
12371 | a = diff; | ||
12372 | if (q) { | ||
12373 | q.words[m] = 1; | ||
12374 | } | ||
12375 | } | ||
12376 | |||
12377 | for (var j = m - 1; j >= 0; j--) { | ||
12378 | var qj = (a.words[b.length + j] | 0) * 0x4000000 + | ||
12379 | (a.words[b.length + j - 1] | 0); | ||
12380 | |||
12381 | // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max | ||
12382 | // (0x7ffffff) | ||
12383 | qj = Math.min((qj / bhi) | 0, 0x3ffffff); | ||
12384 | |||
12385 | a._ishlnsubmul(b, qj, j); | ||
12386 | while (a.negative !== 0) { | ||
12387 | qj--; | ||
12388 | a.negative = 0; | ||
12389 | a._ishlnsubmul(b, 1, j); | ||
12390 | if (!a.isZero()) { | ||
12391 | a.negative ^= 1; | ||
12392 | } | ||
12393 | } | ||
12394 | if (q) { | ||
12395 | q.words[j] = qj; | ||
12396 | } | ||
12397 | } | ||
12398 | if (q) { | ||
12399 | q.strip(); | ||
12400 | } | ||
12401 | a.strip(); | ||
12402 | |||
12403 | // Denormalize | ||
12404 | if (mode !== 'div' && shift !== 0) { | ||
12405 | a.iushrn(shift); | ||
12406 | } | ||
12407 | |||
12408 | return { | ||
12409 | div: q || null, | ||
12410 | mod: a | ||
12411 | }; | ||
12412 | }; | ||
12413 | |||
12414 | // NOTE: 1) `mode` can be set to `mod` to request mod only, | ||
12415 | // to `div` to request div only, or be absent to | ||
12416 | // request both div & mod | ||
12417 | // 2) `positive` is true if unsigned mod is requested | ||
12418 | BN.prototype.divmod = function divmod (num, mode, positive) { | ||
12419 | assert(!num.isZero()); | ||
12420 | |||
12421 | if (this.isZero()) { | ||
12422 | return { | ||
12423 | div: new BN(0), | ||
12424 | mod: new BN(0) | ||
12425 | }; | ||
12426 | } | ||
12427 | |||
12428 | var div, mod, res; | ||
12429 | if (this.negative !== 0 && num.negative === 0) { | ||
12430 | res = this.neg().divmod(num, mode); | ||
12431 | |||
12432 | if (mode !== 'mod') { | ||
12433 | div = res.div.neg(); | ||
12434 | } | ||
12435 | |||
12436 | if (mode !== 'div') { | ||
12437 | mod = res.mod.neg(); | ||
12438 | if (positive && mod.negative !== 0) { | ||
12439 | mod.iadd(num); | ||
12440 | } | ||
12441 | } | ||
12442 | |||
12443 | return { | ||
12444 | div: div, | ||
12445 | mod: mod | ||
12446 | }; | ||
12447 | } | ||
12448 | |||
12449 | if (this.negative === 0 && num.negative !== 0) { | ||
12450 | res = this.divmod(num.neg(), mode); | ||
12451 | |||
12452 | if (mode !== 'mod') { | ||
12453 | div = res.div.neg(); | ||
12454 | } | ||
12455 | |||
12456 | return { | ||
12457 | div: div, | ||
12458 | mod: res.mod | ||
12459 | }; | ||
12460 | } | ||
12461 | |||
12462 | if ((this.negative & num.negative) !== 0) { | ||
12463 | res = this.neg().divmod(num.neg(), mode); | ||
12464 | |||
12465 | if (mode !== 'div') { | ||
12466 | mod = res.mod.neg(); | ||
12467 | if (positive && mod.negative !== 0) { | ||
12468 | mod.isub(num); | ||
12469 | } | ||
12470 | } | ||
12471 | |||
12472 | return { | ||
12473 | div: res.div, | ||
12474 | mod: mod | ||
12475 | }; | ||
12476 | } | ||
12477 | |||
12478 | // Both numbers are positive at this point | ||
12479 | |||
12480 | // Strip both numbers to approximate shift value | ||
12481 | if (num.length > this.length || this.cmp(num) < 0) { | ||
12482 | return { | ||
12483 | div: new BN(0), | ||
12484 | mod: this | ||
12485 | }; | ||
12486 | } | ||
12487 | |||
12488 | // Very short reduction | ||
12489 | if (num.length === 1) { | ||
12490 | if (mode === 'div') { | ||
12491 | return { | ||
12492 | div: this.divn(num.words[0]), | ||
12493 | mod: null | ||
12494 | }; | ||
12495 | } | ||
12496 | |||
12497 | if (mode === 'mod') { | ||
12498 | return { | ||
12499 | div: null, | ||
12500 | mod: new BN(this.modn(num.words[0])) | ||
12501 | }; | ||
12502 | } | ||
12503 | |||
12504 | return { | ||
12505 | div: this.divn(num.words[0]), | ||
12506 | mod: new BN(this.modn(num.words[0])) | ||
12507 | }; | ||
12508 | } | ||
12509 | |||
12510 | return this._wordDiv(num, mode); | ||
12511 | }; | ||
12512 | |||
12513 | // Find `this` / `num` | ||
12514 | BN.prototype.div = function div (num) { | ||
12515 | return this.divmod(num, 'div', false).div; | ||
12516 | }; | ||
12517 | |||
12518 | // Find `this` % `num` | ||
12519 | BN.prototype.mod = function mod (num) { | ||
12520 | return this.divmod(num, 'mod', false).mod; | ||
12521 | }; | ||
12522 | |||
12523 | BN.prototype.umod = function umod (num) { | ||
12524 | return this.divmod(num, 'mod', true).mod; | ||
12525 | }; | ||
12526 | |||
12527 | // Find Round(`this` / `num`) | ||
12528 | BN.prototype.divRound = function divRound (num) { | ||
12529 | var dm = this.divmod(num); | ||
12530 | |||
12531 | // Fast case - exact division | ||
12532 | if (dm.mod.isZero()) return dm.div; | ||
12533 | |||
12534 | var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; | ||
12535 | |||
12536 | var half = num.ushrn(1); | ||
12537 | var r2 = num.andln(1); | ||
12538 | var cmp = mod.cmp(half); | ||
12539 | |||
12540 | // Round down | ||
12541 | if (cmp < 0 || r2 === 1 && cmp === 0) return dm.div; | ||
12542 | |||
12543 | // Round up | ||
12544 | return dm.div.negative !== 0 ? dm.div.isubn(1) : dm.div.iaddn(1); | ||
12545 | }; | ||
12546 | |||
12547 | BN.prototype.modn = function modn (num) { | ||
12548 | assert(num <= 0x3ffffff); | ||
12549 | var p = (1 << 26) % num; | ||
12550 | |||
12551 | var acc = 0; | ||
12552 | for (var i = this.length - 1; i >= 0; i--) { | ||
12553 | acc = (p * acc + (this.words[i] | 0)) % num; | ||
12554 | } | ||
12555 | |||
12556 | return acc; | ||
12557 | }; | ||
12558 | |||
12559 | // In-place division by number | ||
12560 | BN.prototype.idivn = function idivn (num) { | ||
12561 | assert(num <= 0x3ffffff); | ||
12562 | |||
12563 | var carry = 0; | ||
12564 | for (var i = this.length - 1; i >= 0; i--) { | ||
12565 | var w = (this.words[i] | 0) + carry * 0x4000000; | ||
12566 | this.words[i] = (w / num) | 0; | ||
12567 | carry = w % num; | ||
12568 | } | ||
12569 | |||
12570 | return this.strip(); | ||
12571 | }; | ||
12572 | |||
12573 | BN.prototype.divn = function divn (num) { | ||
12574 | return this.clone().idivn(num); | ||
12575 | }; | ||
12576 | |||
12577 | BN.prototype.egcd = function egcd (p) { | ||
12578 | assert(p.negative === 0); | ||
12579 | assert(!p.isZero()); | ||
12580 | |||
12581 | var x = this; | ||
12582 | var y = p.clone(); | ||
12583 | |||
12584 | if (x.negative !== 0) { | ||
12585 | x = x.umod(p); | ||
12586 | } else { | ||
12587 | x = x.clone(); | ||
12588 | } | ||
12589 | |||
12590 | // A * x + B * y = x | ||
12591 | var A = new BN(1); | ||
12592 | var B = new BN(0); | ||
12593 | |||
12594 | // C * x + D * y = y | ||
12595 | var C = new BN(0); | ||
12596 | var D = new BN(1); | ||
12597 | |||
12598 | var g = 0; | ||
12599 | |||
12600 | while (x.isEven() && y.isEven()) { | ||
12601 | x.iushrn(1); | ||
12602 | y.iushrn(1); | ||
12603 | ++g; | ||
12604 | } | ||
12605 | |||
12606 | var yp = y.clone(); | ||
12607 | var xp = x.clone(); | ||
12608 | |||
12609 | while (!x.isZero()) { | ||
12610 | for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); | ||
12611 | if (i > 0) { | ||
12612 | x.iushrn(i); | ||
12613 | while (i-- > 0) { | ||
12614 | if (A.isOdd() || B.isOdd()) { | ||
12615 | A.iadd(yp); | ||
12616 | B.isub(xp); | ||
12617 | } | ||
12618 | |||
12619 | A.iushrn(1); | ||
12620 | B.iushrn(1); | ||
12621 | } | ||
12622 | } | ||
12623 | |||
12624 | for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); | ||
12625 | if (j > 0) { | ||
12626 | y.iushrn(j); | ||
12627 | while (j-- > 0) { | ||
12628 | if (C.isOdd() || D.isOdd()) { | ||
12629 | C.iadd(yp); | ||
12630 | D.isub(xp); | ||
12631 | } | ||
12632 | |||
12633 | C.iushrn(1); | ||
12634 | D.iushrn(1); | ||
12635 | } | ||
12636 | } | ||
12637 | |||
12638 | if (x.cmp(y) >= 0) { | ||
12639 | x.isub(y); | ||
12640 | A.isub(C); | ||
12641 | B.isub(D); | ||
12642 | } else { | ||
12643 | y.isub(x); | ||
12644 | C.isub(A); | ||
12645 | D.isub(B); | ||
12646 | } | ||
12647 | } | ||
12648 | |||
12649 | return { | ||
12650 | a: C, | ||
12651 | b: D, | ||
12652 | gcd: y.iushln(g) | ||
12653 | }; | ||
12654 | }; | ||
12655 | |||
12656 | // This is reduced incarnation of the binary EEA | ||
12657 | // above, designated to invert members of the | ||
12658 | // _prime_ fields F(p) at a maximal speed | ||
12659 | BN.prototype._invmp = function _invmp (p) { | ||
12660 | assert(p.negative === 0); | ||
12661 | assert(!p.isZero()); | ||
12662 | |||
12663 | var a = this; | ||
12664 | var b = p.clone(); | ||
12665 | |||
12666 | if (a.negative !== 0) { | ||
12667 | a = a.umod(p); | ||
12668 | } else { | ||
12669 | a = a.clone(); | ||
12670 | } | ||
12671 | |||
12672 | var x1 = new BN(1); | ||
12673 | var x2 = new BN(0); | ||
12674 | |||
12675 | var delta = b.clone(); | ||
12676 | |||
12677 | while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { | ||
12678 | for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); | ||
12679 | if (i > 0) { | ||
12680 | a.iushrn(i); | ||
12681 | while (i-- > 0) { | ||
12682 | if (x1.isOdd()) { | ||
12683 | x1.iadd(delta); | ||
12684 | } | ||
12685 | |||
12686 | x1.iushrn(1); | ||
12687 | } | ||
12688 | } | ||
12689 | |||
12690 | for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); | ||
12691 | if (j > 0) { | ||
12692 | b.iushrn(j); | ||
12693 | while (j-- > 0) { | ||
12694 | if (x2.isOdd()) { | ||
12695 | x2.iadd(delta); | ||
12696 | } | ||
12697 | |||
12698 | x2.iushrn(1); | ||
12699 | } | ||
12700 | } | ||
12701 | |||
12702 | if (a.cmp(b) >= 0) { | ||
12703 | a.isub(b); | ||
12704 | x1.isub(x2); | ||
12705 | } else { | ||
12706 | b.isub(a); | ||
12707 | x2.isub(x1); | ||
12708 | } | ||
12709 | } | ||
12710 | |||
12711 | var res; | ||
12712 | if (a.cmpn(1) === 0) { | ||
12713 | res = x1; | ||
12714 | } else { | ||
12715 | res = x2; | ||
12716 | } | ||
12717 | |||
12718 | if (res.cmpn(0) < 0) { | ||
12719 | res.iadd(p); | ||
12720 | } | ||
12721 | |||
12722 | return res; | ||
12723 | }; | ||
12724 | |||
12725 | BN.prototype.gcd = function gcd (num) { | ||
12726 | if (this.isZero()) return num.abs(); | ||
12727 | if (num.isZero()) return this.abs(); | ||
12728 | |||
12729 | var a = this.clone(); | ||
12730 | var b = num.clone(); | ||
12731 | a.negative = 0; | ||
12732 | b.negative = 0; | ||
12733 | |||
12734 | // Remove common factor of two | ||
12735 | for (var shift = 0; a.isEven() && b.isEven(); shift++) { | ||
12736 | a.iushrn(1); | ||
12737 | b.iushrn(1); | ||
12738 | } | ||
12739 | |||
12740 | do { | ||
12741 | while (a.isEven()) { | ||
12742 | a.iushrn(1); | ||
12743 | } | ||
12744 | while (b.isEven()) { | ||
12745 | b.iushrn(1); | ||
12746 | } | ||
12747 | |||
12748 | var r = a.cmp(b); | ||
12749 | if (r < 0) { | ||
12750 | // Swap `a` and `b` to make `a` always bigger than `b` | ||
12751 | var t = a; | ||
12752 | a = b; | ||
12753 | b = t; | ||
12754 | } else if (r === 0 || b.cmpn(1) === 0) { | ||
12755 | break; | ||
12756 | } | ||
12757 | |||
12758 | a.isub(b); | ||
12759 | } while (true); | ||
12760 | |||
12761 | return b.iushln(shift); | ||
12762 | }; | ||
12763 | |||
12764 | // Invert number in the field F(num) | ||
12765 | BN.prototype.invm = function invm (num) { | ||
12766 | return this.egcd(num).a.umod(num); | ||
12767 | }; | ||
12768 | |||
12769 | BN.prototype.isEven = function isEven () { | ||
12770 | return (this.words[0] & 1) === 0; | ||
12771 | }; | ||
12772 | |||
12773 | BN.prototype.isOdd = function isOdd () { | ||
12774 | return (this.words[0] & 1) === 1; | ||
12775 | }; | ||
12776 | |||
12777 | // And first word and num | ||
12778 | BN.prototype.andln = function andln (num) { | ||
12779 | return this.words[0] & num; | ||
12780 | }; | ||
12781 | |||
12782 | // Increment at the bit position in-line | ||
12783 | BN.prototype.bincn = function bincn (bit) { | ||
12784 | assert(typeof bit === 'number'); | ||
12785 | var r = bit % 26; | ||
12786 | var s = (bit - r) / 26; | ||
12787 | var q = 1 << r; | ||
12788 | |||
12789 | // Fast case: bit is much higher than all existing words | ||
12790 | if (this.length <= s) { | ||
12791 | this._expand(s + 1); | ||
12792 | this.words[s] |= q; | ||
12793 | return this; | ||
12794 | } | ||
12795 | |||
12796 | // Add bit and propagate, if needed | ||
12797 | var carry = q; | ||
12798 | for (var i = s; carry !== 0 && i < this.length; i++) { | ||
12799 | var w = this.words[i] | 0; | ||
12800 | w += carry; | ||
12801 | carry = w >>> 26; | ||
12802 | w &= 0x3ffffff; | ||
12803 | this.words[i] = w; | ||
12804 | } | ||
12805 | if (carry !== 0) { | ||
12806 | this.words[i] = carry; | ||
12807 | this.length++; | ||
12808 | } | ||
12809 | return this; | ||
12810 | }; | ||
12811 | |||
12812 | BN.prototype.isZero = function isZero () { | ||
12813 | return this.length === 1 && this.words[0] === 0; | ||
12814 | }; | ||
12815 | |||
12816 | BN.prototype.cmpn = function cmpn (num) { | ||
12817 | var negative = num < 0; | ||
12818 | |||
12819 | if (this.negative !== 0 && !negative) return -1; | ||
12820 | if (this.negative === 0 && negative) return 1; | ||
12821 | |||
12822 | this.strip(); | ||
12823 | |||
12824 | var res; | ||
12825 | if (this.length > 1) { | ||
12826 | res = 1; | ||
12827 | } else { | ||
12828 | if (negative) { | ||
12829 | num = -num; | ||
12830 | } | ||
12831 | |||
12832 | assert(num <= 0x3ffffff, 'Number is too big'); | ||
12833 | |||
12834 | var w = this.words[0] | 0; | ||
12835 | res = w === num ? 0 : w < num ? -1 : 1; | ||
12836 | } | ||
12837 | if (this.negative !== 0) return -res | 0; | ||
12838 | return res; | ||
12839 | }; | ||
12840 | |||
12841 | // Compare two numbers and return: | ||
12842 | // 1 - if `this` > `num` | ||
12843 | // 0 - if `this` == `num` | ||
12844 | // -1 - if `this` < `num` | ||
12845 | BN.prototype.cmp = function cmp (num) { | ||
12846 | if (this.negative !== 0 && num.negative === 0) return -1; | ||
12847 | if (this.negative === 0 && num.negative !== 0) return 1; | ||
12848 | |||
12849 | var res = this.ucmp(num); | ||
12850 | if (this.negative !== 0) return -res | 0; | ||
12851 | return res; | ||
12852 | }; | ||
12853 | |||
12854 | // Unsigned comparison | ||
12855 | BN.prototype.ucmp = function ucmp (num) { | ||
12856 | // At this point both numbers have the same sign | ||
12857 | if (this.length > num.length) return 1; | ||
12858 | if (this.length < num.length) return -1; | ||
12859 | |||
12860 | var res = 0; | ||
12861 | for (var i = this.length - 1; i >= 0; i--) { | ||
12862 | var a = this.words[i] | 0; | ||
12863 | var b = num.words[i] | 0; | ||
12864 | |||
12865 | if (a === b) continue; | ||
12866 | if (a < b) { | ||
12867 | res = -1; | ||
12868 | } else if (a > b) { | ||
12869 | res = 1; | ||
12870 | } | ||
12871 | break; | ||
12872 | } | ||
12873 | return res; | ||
12874 | }; | ||
12875 | |||
12876 | BN.prototype.gtn = function gtn (num) { | ||
12877 | return this.cmpn(num) === 1; | ||
12878 | }; | ||
12879 | |||
12880 | BN.prototype.gt = function gt (num) { | ||
12881 | return this.cmp(num) === 1; | ||
12882 | }; | ||
12883 | |||
12884 | BN.prototype.gten = function gten (num) { | ||
12885 | return this.cmpn(num) >= 0; | ||
12886 | }; | ||
12887 | |||
12888 | BN.prototype.gte = function gte (num) { | ||
12889 | return this.cmp(num) >= 0; | ||
12890 | }; | ||
12891 | |||
12892 | BN.prototype.ltn = function ltn (num) { | ||
12893 | return this.cmpn(num) === -1; | ||
12894 | }; | ||
12895 | |||
12896 | BN.prototype.lt = function lt (num) { | ||
12897 | return this.cmp(num) === -1; | ||
12898 | }; | ||
12899 | |||
12900 | BN.prototype.lten = function lten (num) { | ||
12901 | return this.cmpn(num) <= 0; | ||
12902 | }; | ||
12903 | |||
12904 | BN.prototype.lte = function lte (num) { | ||
12905 | return this.cmp(num) <= 0; | ||
12906 | }; | ||
12907 | |||
12908 | BN.prototype.eqn = function eqn (num) { | ||
12909 | return this.cmpn(num) === 0; | ||
12910 | }; | ||
12911 | |||
12912 | BN.prototype.eq = function eq (num) { | ||
12913 | return this.cmp(num) === 0; | ||
12914 | }; | ||
12915 | |||
12916 | // | ||
12917 | // A reduce context, could be using montgomery or something better, depending | ||
12918 | // on the `m` itself. | ||
12919 | // | ||
12920 | BN.red = function red (num) { | ||
12921 | return new Red(num); | ||
12922 | }; | ||
12923 | |||
12924 | BN.prototype.toRed = function toRed (ctx) { | ||
12925 | assert(!this.red, 'Already a number in reduction context'); | ||
12926 | assert(this.negative === 0, 'red works only with positives'); | ||
12927 | return ctx.convertTo(this)._forceRed(ctx); | ||
12928 | }; | ||
12929 | |||
12930 | BN.prototype.fromRed = function fromRed () { | ||
12931 | assert(this.red, 'fromRed works only with numbers in reduction context'); | ||
12932 | return this.red.convertFrom(this); | ||
12933 | }; | ||
12934 | |||
12935 | BN.prototype._forceRed = function _forceRed (ctx) { | ||
12936 | this.red = ctx; | ||
12937 | return this; | ||
12938 | }; | ||
12939 | |||
12940 | BN.prototype.forceRed = function forceRed (ctx) { | ||
12941 | assert(!this.red, 'Already a number in reduction context'); | ||
12942 | return this._forceRed(ctx); | ||
12943 | }; | ||
12944 | |||
12945 | BN.prototype.redAdd = function redAdd (num) { | ||
12946 | assert(this.red, 'redAdd works only with red numbers'); | ||
12947 | return this.red.add(this, num); | ||
12948 | }; | ||
12949 | |||
12950 | BN.prototype.redIAdd = function redIAdd (num) { | ||
12951 | assert(this.red, 'redIAdd works only with red numbers'); | ||
12952 | return this.red.iadd(this, num); | ||
12953 | }; | ||
12954 | |||
12955 | BN.prototype.redSub = function redSub (num) { | ||
12956 | assert(this.red, 'redSub works only with red numbers'); | ||
12957 | return this.red.sub(this, num); | ||
12958 | }; | ||
12959 | |||
12960 | BN.prototype.redISub = function redISub (num) { | ||
12961 | assert(this.red, 'redISub works only with red numbers'); | ||
12962 | return this.red.isub(this, num); | ||
12963 | }; | ||
12964 | |||
12965 | BN.prototype.redShl = function redShl (num) { | ||
12966 | assert(this.red, 'redShl works only with red numbers'); | ||
12967 | return this.red.shl(this, num); | ||
12968 | }; | ||
12969 | |||
12970 | BN.prototype.redMul = function redMul (num) { | ||
12971 | assert(this.red, 'redMul works only with red numbers'); | ||
12972 | this.red._verify2(this, num); | ||
12973 | return this.red.mul(this, num); | ||
12974 | }; | ||
12975 | |||
12976 | BN.prototype.redIMul = function redIMul (num) { | ||
12977 | assert(this.red, 'redMul works only with red numbers'); | ||
12978 | this.red._verify2(this, num); | ||
12979 | return this.red.imul(this, num); | ||
12980 | }; | ||
12981 | |||
12982 | BN.prototype.redSqr = function redSqr () { | ||
12983 | assert(this.red, 'redSqr works only with red numbers'); | ||
12984 | this.red._verify1(this); | ||
12985 | return this.red.sqr(this); | ||
12986 | }; | ||
12987 | |||
12988 | BN.prototype.redISqr = function redISqr () { | ||
12989 | assert(this.red, 'redISqr works only with red numbers'); | ||
12990 | this.red._verify1(this); | ||
12991 | return this.red.isqr(this); | ||
12992 | }; | ||
12993 | |||
12994 | // Square root over p | ||
12995 | BN.prototype.redSqrt = function redSqrt () { | ||
12996 | assert(this.red, 'redSqrt works only with red numbers'); | ||
12997 | this.red._verify1(this); | ||
12998 | return this.red.sqrt(this); | ||
12999 | }; | ||
13000 | |||
13001 | BN.prototype.redInvm = function redInvm () { | ||
13002 | assert(this.red, 'redInvm works only with red numbers'); | ||
13003 | this.red._verify1(this); | ||
13004 | return this.red.invm(this); | ||
13005 | }; | ||
13006 | |||
13007 | // Return negative clone of `this` % `red modulo` | ||
13008 | BN.prototype.redNeg = function redNeg () { | ||
13009 | assert(this.red, 'redNeg works only with red numbers'); | ||
13010 | this.red._verify1(this); | ||
13011 | return this.red.neg(this); | ||
13012 | }; | ||
13013 | |||
13014 | BN.prototype.redPow = function redPow (num) { | ||
13015 | assert(this.red && !num.red, 'redPow(normalNum)'); | ||
13016 | this.red._verify1(this); | ||
13017 | return this.red.pow(this, num); | ||
13018 | }; | ||
13019 | |||
13020 | // Prime numbers with efficient reduction | ||
13021 | var primes = { | ||
13022 | k256: null, | ||
13023 | p224: null, | ||
13024 | p192: null, | ||
13025 | p25519: null | ||
13026 | }; | ||
13027 | |||
13028 | // Pseudo-Mersenne prime | ||
13029 | function MPrime (name, p) { | ||
13030 | // P = 2 ^ N - K | ||
13031 | this.name = name; | ||
13032 | this.p = new BN(p, 16); | ||
13033 | this.n = this.p.bitLength(); | ||
13034 | this.k = new BN(1).iushln(this.n).isub(this.p); | ||
13035 | |||
13036 | this.tmp = this._tmp(); | ||
13037 | } | ||
13038 | |||
13039 | MPrime.prototype._tmp = function _tmp () { | ||
13040 | var tmp = new BN(null); | ||
13041 | tmp.words = new Array(Math.ceil(this.n / 13)); | ||
13042 | return tmp; | ||
13043 | }; | ||
13044 | |||
13045 | MPrime.prototype.ireduce = function ireduce (num) { | ||
13046 | // Assumes that `num` is less than `P^2` | ||
13047 | // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) | ||
13048 | var r = num; | ||
13049 | var rlen; | ||
13050 | |||
13051 | do { | ||
13052 | this.split(r, this.tmp); | ||
13053 | r = this.imulK(r); | ||
13054 | r = r.iadd(this.tmp); | ||
13055 | rlen = r.bitLength(); | ||
13056 | } while (rlen > this.n); | ||
13057 | |||
13058 | var cmp = rlen < this.n ? -1 : r.ucmp(this.p); | ||
13059 | if (cmp === 0) { | ||
13060 | r.words[0] = 0; | ||
13061 | r.length = 1; | ||
13062 | } else if (cmp > 0) { | ||
13063 | r.isub(this.p); | ||
13064 | } else { | ||
13065 | r.strip(); | ||
13066 | } | ||
13067 | |||
13068 | return r; | ||
13069 | }; | ||
13070 | |||
13071 | MPrime.prototype.split = function split (input, out) { | ||
13072 | input.iushrn(this.n, 0, out); | ||
13073 | }; | ||
13074 | |||
13075 | MPrime.prototype.imulK = function imulK (num) { | ||
13076 | return num.imul(this.k); | ||
13077 | }; | ||
13078 | |||
13079 | function K256 () { | ||
13080 | MPrime.call( | ||
13081 | this, | ||
13082 | 'k256', | ||
13083 | 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); | ||
13084 | } | ||
13085 | inherits(K256, MPrime); | ||
13086 | |||
13087 | K256.prototype.split = function split (input, output) { | ||
13088 | // 256 = 9 * 26 + 22 | ||
13089 | var mask = 0x3fffff; | ||
13090 | |||
13091 | var outLen = Math.min(input.length, 9); | ||
13092 | for (var i = 0; i < outLen; i++) { | ||
13093 | output.words[i] = input.words[i]; | ||
13094 | } | ||
13095 | output.length = outLen; | ||
13096 | |||
13097 | if (input.length <= 9) { | ||
13098 | input.words[0] = 0; | ||
13099 | input.length = 1; | ||
13100 | return; | ||
13101 | } | ||
13102 | |||
13103 | // Shift by 9 limbs | ||
13104 | var prev = input.words[9]; | ||
13105 | output.words[output.length++] = prev & mask; | ||
13106 | |||
13107 | for (i = 10; i < input.length; i++) { | ||
13108 | var next = input.words[i] | 0; | ||
13109 | input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); | ||
13110 | prev = next; | ||
13111 | } | ||
13112 | prev >>>= 22; | ||
13113 | input.words[i - 10] = prev; | ||
13114 | if (prev === 0 && input.length > 10) { | ||
13115 | input.length -= 10; | ||
13116 | } else { | ||
13117 | input.length -= 9; | ||
13118 | } | ||
13119 | }; | ||
13120 | |||
13121 | K256.prototype.imulK = function imulK (num) { | ||
13122 | // K = 0x1000003d1 = [ 0x40, 0x3d1 ] | ||
13123 | num.words[num.length] = 0; | ||
13124 | num.words[num.length + 1] = 0; | ||
13125 | num.length += 2; | ||
13126 | |||
13127 | // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 | ||
13128 | var lo = 0; | ||
13129 | for (var i = 0; i < num.length; i++) { | ||
13130 | var w = num.words[i] | 0; | ||
13131 | lo += w * 0x3d1; | ||
13132 | num.words[i] = lo & 0x3ffffff; | ||
13133 | lo = w * 0x40 + ((lo / 0x4000000) | 0); | ||
13134 | } | ||
13135 | |||
13136 | // Fast length reduction | ||
13137 | if (num.words[num.length - 1] === 0) { | ||
13138 | num.length--; | ||
13139 | if (num.words[num.length - 1] === 0) { | ||
13140 | num.length--; | ||
13141 | } | ||
13142 | } | ||
13143 | return num; | ||
13144 | }; | ||
13145 | |||
13146 | function P224 () { | ||
13147 | MPrime.call( | ||
13148 | this, | ||
13149 | 'p224', | ||
13150 | 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); | ||
13151 | } | ||
13152 | inherits(P224, MPrime); | ||
13153 | |||
13154 | function P192 () { | ||
13155 | MPrime.call( | ||
13156 | this, | ||
13157 | 'p192', | ||
13158 | 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); | ||
13159 | } | ||
13160 | inherits(P192, MPrime); | ||
13161 | |||
13162 | function P25519 () { | ||
13163 | // 2 ^ 255 - 19 | ||
13164 | MPrime.call( | ||
13165 | this, | ||
13166 | '25519', | ||
13167 | '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); | ||
13168 | } | ||
13169 | inherits(P25519, MPrime); | ||
13170 | |||
13171 | P25519.prototype.imulK = function imulK (num) { | ||
13172 | // K = 0x13 | ||
13173 | var carry = 0; | ||
13174 | for (var i = 0; i < num.length; i++) { | ||
13175 | var hi = (num.words[i] | 0) * 0x13 + carry; | ||
13176 | var lo = hi & 0x3ffffff; | ||
13177 | hi >>>= 26; | ||
13178 | |||
13179 | num.words[i] = lo; | ||
13180 | carry = hi; | ||
13181 | } | ||
13182 | if (carry !== 0) { | ||
13183 | num.words[num.length++] = carry; | ||
13184 | } | ||
13185 | return num; | ||
13186 | }; | ||
13187 | |||
13188 | // Exported mostly for testing purposes, use plain name instead | ||
13189 | BN._prime = function prime (name) { | ||
13190 | // Cached version of prime | ||
13191 | if (primes[name]) return primes[name]; | ||
13192 | |||
13193 | var prime; | ||
13194 | if (name === 'k256') { | ||
13195 | prime = new K256(); | ||
13196 | } else if (name === 'p224') { | ||
13197 | prime = new P224(); | ||
13198 | } else if (name === 'p192') { | ||
13199 | prime = new P192(); | ||
13200 | } else if (name === 'p25519') { | ||
13201 | prime = new P25519(); | ||
13202 | } else { | ||
13203 | throw new Error('Unknown prime ' + name); | ||
13204 | } | ||
13205 | primes[name] = prime; | ||
13206 | |||
13207 | return prime; | ||
13208 | }; | ||
13209 | |||
13210 | // | ||
13211 | // Base reduction engine | ||
13212 | // | ||
13213 | function Red (m) { | ||
13214 | if (typeof m === 'string') { | ||
13215 | var prime = BN._prime(m); | ||
13216 | this.m = prime.p; | ||
13217 | this.prime = prime; | ||
13218 | } else { | ||
13219 | assert(m.gtn(1), 'modulus must be greater than 1'); | ||
13220 | this.m = m; | ||
13221 | this.prime = null; | ||
13222 | } | ||
13223 | } | ||
13224 | |||
13225 | Red.prototype._verify1 = function _verify1 (a) { | ||
13226 | assert(a.negative === 0, 'red works only with positives'); | ||
13227 | assert(a.red, 'red works only with red numbers'); | ||
13228 | }; | ||
13229 | |||
13230 | Red.prototype._verify2 = function _verify2 (a, b) { | ||
13231 | assert((a.negative | b.negative) === 0, 'red works only with positives'); | ||
13232 | assert(a.red && a.red === b.red, | ||
13233 | 'red works only with red numbers'); | ||
13234 | }; | ||
13235 | |||
13236 | Red.prototype.imod = function imod (a) { | ||
13237 | if (this.prime) return this.prime.ireduce(a)._forceRed(this); | ||
13238 | return a.umod(this.m)._forceRed(this); | ||
13239 | }; | ||
13240 | |||
13241 | Red.prototype.neg = function neg (a) { | ||
13242 | if (a.isZero()) { | ||
13243 | return a.clone(); | ||
13244 | } | ||
13245 | |||
13246 | return this.m.sub(a)._forceRed(this); | ||
13247 | }; | ||
13248 | |||
13249 | Red.prototype.add = function add (a, b) { | ||
13250 | this._verify2(a, b); | ||
13251 | |||
13252 | var res = a.add(b); | ||
13253 | if (res.cmp(this.m) >= 0) { | ||
13254 | res.isub(this.m); | ||
13255 | } | ||
13256 | return res._forceRed(this); | ||
13257 | }; | ||
13258 | |||
13259 | Red.prototype.iadd = function iadd (a, b) { | ||
13260 | this._verify2(a, b); | ||
13261 | |||
13262 | var res = a.iadd(b); | ||
13263 | if (res.cmp(this.m) >= 0) { | ||
13264 | res.isub(this.m); | ||
13265 | } | ||
13266 | return res; | ||
13267 | }; | ||
13268 | |||
13269 | Red.prototype.sub = function sub (a, b) { | ||
13270 | this._verify2(a, b); | ||
13271 | |||
13272 | var res = a.sub(b); | ||
13273 | if (res.cmpn(0) < 0) { | ||
13274 | res.iadd(this.m); | ||
13275 | } | ||
13276 | return res._forceRed(this); | ||
13277 | }; | ||
13278 | |||
13279 | Red.prototype.isub = function isub (a, b) { | ||
13280 | this._verify2(a, b); | ||
13281 | |||
13282 | var res = a.isub(b); | ||
13283 | if (res.cmpn(0) < 0) { | ||
13284 | res.iadd(this.m); | ||
13285 | } | ||
13286 | return res; | ||
13287 | }; | ||
13288 | |||
13289 | Red.prototype.shl = function shl (a, num) { | ||
13290 | this._verify1(a); | ||
13291 | return this.imod(a.ushln(num)); | ||
13292 | }; | ||
13293 | |||
13294 | Red.prototype.imul = function imul (a, b) { | ||
13295 | this._verify2(a, b); | ||
13296 | return this.imod(a.imul(b)); | ||
13297 | }; | ||
13298 | |||
13299 | Red.prototype.mul = function mul (a, b) { | ||
13300 | this._verify2(a, b); | ||
13301 | return this.imod(a.mul(b)); | ||
13302 | }; | ||
13303 | |||
13304 | Red.prototype.isqr = function isqr (a) { | ||
13305 | return this.imul(a, a.clone()); | ||
13306 | }; | ||
13307 | |||
13308 | Red.prototype.sqr = function sqr (a) { | ||
13309 | return this.mul(a, a); | ||
13310 | }; | ||
13311 | |||
13312 | Red.prototype.sqrt = function sqrt (a) { | ||
13313 | if (a.isZero()) return a.clone(); | ||
13314 | |||
13315 | var mod3 = this.m.andln(3); | ||
13316 | assert(mod3 % 2 === 1); | ||
13317 | |||
13318 | // Fast case | ||
13319 | if (mod3 === 3) { | ||
13320 | var pow = this.m.add(new BN(1)).iushrn(2); | ||
13321 | return this.pow(a, pow); | ||
13322 | } | ||
13323 | |||
13324 | // Tonelli-Shanks algorithm (Totally unoptimized and slow) | ||
13325 | // | ||
13326 | // Find Q and S, that Q * 2 ^ S = (P - 1) | ||
13327 | var q = this.m.subn(1); | ||
13328 | var s = 0; | ||
13329 | while (!q.isZero() && q.andln(1) === 0) { | ||
13330 | s++; | ||
13331 | q.iushrn(1); | ||
13332 | } | ||
13333 | assert(!q.isZero()); | ||
13334 | |||
13335 | var one = new BN(1).toRed(this); | ||
13336 | var nOne = one.redNeg(); | ||
13337 | |||
13338 | // Find quadratic non-residue | ||
13339 | // NOTE: Max is such because of generalized Riemann hypothesis. | ||
13340 | var lpow = this.m.subn(1).iushrn(1); | ||
13341 | var z = this.m.bitLength(); | ||
13342 | z = new BN(2 * z * z).toRed(this); | ||
13343 | |||
13344 | while (this.pow(z, lpow).cmp(nOne) !== 0) { | ||
13345 | z.redIAdd(nOne); | ||
13346 | } | ||
13347 | |||
13348 | var c = this.pow(z, q); | ||
13349 | var r = this.pow(a, q.addn(1).iushrn(1)); | ||
13350 | var t = this.pow(a, q); | ||
13351 | var m = s; | ||
13352 | while (t.cmp(one) !== 0) { | ||
13353 | var tmp = t; | ||
13354 | for (var i = 0; tmp.cmp(one) !== 0; i++) { | ||
13355 | tmp = tmp.redSqr(); | ||
13356 | } | ||
13357 | assert(i < m); | ||
13358 | var b = this.pow(c, new BN(1).iushln(m - i - 1)); | ||
13359 | |||
13360 | r = r.redMul(b); | ||
13361 | c = b.redSqr(); | ||
13362 | t = t.redMul(c); | ||
13363 | m = i; | ||
13364 | } | ||
13365 | |||
13366 | return r; | ||
13367 | }; | ||
13368 | |||
13369 | Red.prototype.invm = function invm (a) { | ||
13370 | var inv = a._invmp(this.m); | ||
13371 | if (inv.negative !== 0) { | ||
13372 | inv.negative = 0; | ||
13373 | return this.imod(inv).redNeg(); | ||
13374 | } else { | ||
13375 | return this.imod(inv); | ||
13376 | } | ||
13377 | }; | ||
13378 | |||
13379 | Red.prototype.pow = function pow (a, num) { | ||
13380 | if (num.isZero()) return new BN(1).toRed(this); | ||
13381 | if (num.cmpn(1) === 0) return a.clone(); | ||
13382 | |||
13383 | var windowSize = 4; | ||
13384 | var wnd = new Array(1 << windowSize); | ||
13385 | wnd[0] = new BN(1).toRed(this); | ||
13386 | wnd[1] = a; | ||
13387 | for (var i = 2; i < wnd.length; i++) { | ||
13388 | wnd[i] = this.mul(wnd[i - 1], a); | ||
13389 | } | ||
13390 | |||
13391 | var res = wnd[0]; | ||
13392 | var current = 0; | ||
13393 | var currentLen = 0; | ||
13394 | var start = num.bitLength() % 26; | ||
13395 | if (start === 0) { | ||
13396 | start = 26; | ||
13397 | } | ||
13398 | |||
13399 | for (i = num.length - 1; i >= 0; i--) { | ||
13400 | var word = num.words[i]; | ||
13401 | for (var j = start - 1; j >= 0; j--) { | ||
13402 | var bit = (word >> j) & 1; | ||
13403 | if (res !== wnd[0]) { | ||
13404 | res = this.sqr(res); | ||
13405 | } | ||
13406 | |||
13407 | if (bit === 0 && current === 0) { | ||
13408 | currentLen = 0; | ||
13409 | continue; | ||
13410 | } | ||
13411 | |||
13412 | current <<= 1; | ||
13413 | current |= bit; | ||
13414 | currentLen++; | ||
13415 | if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; | ||
13416 | |||
13417 | res = this.mul(res, wnd[current]); | ||
13418 | currentLen = 0; | ||
13419 | current = 0; | ||
13420 | } | ||
13421 | start = 26; | ||
13422 | } | ||
13423 | |||
13424 | return res; | ||
13425 | }; | ||
13426 | |||
13427 | Red.prototype.convertTo = function convertTo (num) { | ||
13428 | var r = num.umod(this.m); | ||
13429 | |||
13430 | return r === num ? r.clone() : r; | ||
13431 | }; | ||
13432 | |||
13433 | Red.prototype.convertFrom = function convertFrom (num) { | ||
13434 | var res = num.clone(); | ||
13435 | res.red = null; | ||
13436 | return res; | ||
13437 | }; | ||
13438 | |||
13439 | // | ||
13440 | // Montgomery method engine | ||
13441 | // | ||
13442 | |||
13443 | BN.mont = function mont (num) { | ||
13444 | return new Mont(num); | ||
13445 | }; | ||
13446 | |||
13447 | function Mont (m) { | ||
13448 | Red.call(this, m); | ||
13449 | |||
13450 | this.shift = this.m.bitLength(); | ||
13451 | if (this.shift % 26 !== 0) { | ||
13452 | this.shift += 26 - (this.shift % 26); | ||
13453 | } | ||
13454 | |||
13455 | this.r = new BN(1).iushln(this.shift); | ||
13456 | this.r2 = this.imod(this.r.sqr()); | ||
13457 | this.rinv = this.r._invmp(this.m); | ||
13458 | |||
13459 | this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); | ||
13460 | this.minv = this.minv.umod(this.r); | ||
13461 | this.minv = this.r.sub(this.minv); | ||
13462 | } | ||
13463 | inherits(Mont, Red); | ||
13464 | |||
13465 | Mont.prototype.convertTo = function convertTo (num) { | ||
13466 | return this.imod(num.ushln(this.shift)); | ||
13467 | }; | ||
13468 | |||
13469 | Mont.prototype.convertFrom = function convertFrom (num) { | ||
13470 | var r = this.imod(num.mul(this.rinv)); | ||
13471 | r.red = null; | ||
13472 | return r; | ||
13473 | }; | ||
13474 | |||
13475 | Mont.prototype.imul = function imul (a, b) { | ||
13476 | if (a.isZero() || b.isZero()) { | ||
13477 | a.words[0] = 0; | ||
13478 | a.length = 1; | ||
13479 | return a; | ||
13480 | } | ||
13481 | |||
13482 | var t = a.imul(b); | ||
13483 | var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); | ||
13484 | var u = t.isub(c).iushrn(this.shift); | ||
13485 | var res = u; | ||
13486 | |||
13487 | if (u.cmp(this.m) >= 0) { | ||
13488 | res = u.isub(this.m); | ||
13489 | } else if (u.cmpn(0) < 0) { | ||
13490 | res = u.iadd(this.m); | ||
13491 | } | ||
13492 | |||
13493 | return res._forceRed(this); | ||
13494 | }; | ||
13495 | |||
13496 | Mont.prototype.mul = function mul (a, b) { | ||
13497 | if (a.isZero() || b.isZero()) return new BN(0)._forceRed(this); | ||
13498 | |||
13499 | var t = a.mul(b); | ||
13500 | var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); | ||
13501 | var u = t.isub(c).iushrn(this.shift); | ||
13502 | var res = u; | ||
13503 | if (u.cmp(this.m) >= 0) { | ||
13504 | res = u.isub(this.m); | ||
13505 | } else if (u.cmpn(0) < 0) { | ||
13506 | res = u.iadd(this.m); | ||
13507 | } | ||
13508 | |||
13509 | return res._forceRed(this); | ||
13510 | }; | ||
13511 | |||
13512 | Mont.prototype.invm = function invm (a) { | ||
13513 | // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R | ||
13514 | var res = this.imod(a._invmp(this.m).mul(this.r2)); | ||
13515 | return res._forceRed(this); | ||
13516 | }; | ||
13517 | })(typeof module === 'undefined' || module, this); | ||
13518 | |||
13519 | },{"buffer":77}],76:[function(require,module,exports){ | ||
13520 | var r; | ||
13521 | |||
13522 | module.exports = function rand(len) { | ||
13523 | if (!r) | ||
13524 | r = new Rand(null); | ||
13525 | |||
13526 | return r.generate(len); | ||
13527 | }; | ||
13528 | |||
13529 | function Rand(rand) { | ||
13530 | this.rand = rand; | ||
13531 | } | ||
13532 | module.exports.Rand = Rand; | ||
13533 | |||
13534 | Rand.prototype.generate = function generate(len) { | ||
13535 | return this._rand(len); | ||
13536 | }; | ||
13537 | |||
13538 | // Emulate crypto API using randy | ||
13539 | Rand.prototype._rand = function _rand(n) { | ||
13540 | if (this.rand.getBytes) | ||
13541 | return this.rand.getBytes(n); | ||
13542 | |||
13543 | var res = new Uint8Array(n); | ||
13544 | for (var i = 0; i < res.length; i++) | ||
13545 | res[i] = this.rand.getByte(); | ||
13546 | return res; | ||
13547 | }; | ||
13548 | |||
13549 | if (typeof self === 'object') { | ||
13550 | if (self.crypto && self.crypto.getRandomValues) { | ||
13551 | // Modern browsers | ||
13552 | Rand.prototype._rand = function _rand(n) { | ||
13553 | var arr = new Uint8Array(n); | ||
13554 | self.crypto.getRandomValues(arr); | ||
13555 | return arr; | ||
13556 | }; | ||
13557 | } else if (self.msCrypto && self.msCrypto.getRandomValues) { | ||
13558 | // IE | ||
13559 | Rand.prototype._rand = function _rand(n) { | ||
13560 | var arr = new Uint8Array(n); | ||
13561 | self.msCrypto.getRandomValues(arr); | ||
13562 | return arr; | ||
13563 | }; | ||
13564 | |||
13565 | // Safari's WebWorkers do not have `crypto` | ||
13566 | } else if (typeof window === 'object') { | ||
13567 | // Old junk | ||
13568 | Rand.prototype._rand = function() { | ||
13569 | throw new Error('Not implemented yet'); | ||
13570 | }; | ||
13571 | } | ||
13572 | } else { | ||
13573 | // Node.js or Web worker with no crypto support | ||
13574 | try { | ||
13575 | var crypto = require('crypto'); | ||
13576 | if (typeof crypto.randomBytes !== 'function') | ||
13577 | throw new Error('Not supported'); | ||
13578 | |||
13579 | Rand.prototype._rand = function _rand(n) { | ||
13580 | return crypto.randomBytes(n); | ||
13581 | }; | ||
13582 | } catch (e) { | ||
13583 | } | ||
13584 | } | ||
13585 | |||
13586 | },{"crypto":77}],77:[function(require,module,exports){ | ||
13587 | |||
13588 | },{}],78:[function(require,module,exports){ | ||
13589 | // based on the aes implimentation in triple sec | ||
13590 | // https://github.com/keybase/triplesec | ||
13591 | // which is in turn based on the one from crypto-js | ||
13592 | // https://code.google.com/p/crypto-js/ | ||
13593 | |||
13594 | var Buffer = require('safe-buffer').Buffer | ||
13595 | |||
13596 | function asUInt32Array (buf) { | ||
13597 | if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) | ||
13598 | |||
13599 | var len = (buf.length / 4) | 0 | ||
13600 | var out = new Array(len) | ||
13601 | |||
13602 | for (var i = 0; i < len; i++) { | ||
13603 | out[i] = buf.readUInt32BE(i * 4) | ||
13604 | } | ||
13605 | |||
13606 | return out | ||
13607 | } | ||
13608 | |||
13609 | function scrubVec (v) { | ||
13610 | for (var i = 0; i < v.length; v++) { | ||
13611 | v[i] = 0 | ||
13612 | } | ||
13613 | } | ||
13614 | |||
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] | ||
13620 | |||
13621 | var s0 = M[0] ^ keySchedule[0] | ||
13622 | var s1 = M[1] ^ keySchedule[1] | ||
13623 | var s2 = M[2] ^ keySchedule[2] | ||
13624 | var s3 = M[3] ^ keySchedule[3] | ||
13625 | var t0, t1, t2, t3 | ||
13626 | var ksRow = 4 | ||
13627 | |||
13628 | for (var round = 1; round < nRounds; round++) { | ||
13629 | t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] | ||
13630 | t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] | ||
13631 | t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] | ||
13632 | t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] | ||
13633 | s0 = t0 | ||
13634 | s1 = t1 | ||
13635 | s2 = t2 | ||
13636 | s3 = t3 | ||
13637 | } | ||
13638 | |||
13639 | t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] | ||
13640 | t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] | ||
13641 | t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] | ||
13642 | t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] | ||
13643 | t0 = t0 >>> 0 | ||
13644 | t1 = t1 >>> 0 | ||
13645 | t2 = t2 >>> 0 | ||
13646 | t3 = t3 >>> 0 | ||
13647 | |||
13648 | return [t0, t1, t2, t3] | ||
13649 | } | ||
13650 | |||
13651 | // AES constants | ||
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++) { | ||
13657 | if (j < 128) { | ||
13658 | d[j] = j << 1 | ||
13659 | } else { | ||
13660 | d[j] = (j << 1) ^ 0x11b | ||
13661 | } | ||
13662 | } | ||
13663 | |||
13664 | var SBOX = [] | ||
13665 | var INV_SBOX = [] | ||
13666 | var SUB_MIX = [[], [], [], []] | ||
13667 | var INV_SUB_MIX = [[], [], [], []] | ||
13668 | |||
13669 | // Walk GF(2^8) | ||
13670 | var x = 0 | ||
13671 | var xi = 0 | ||
13672 | for (var i = 0; i < 256; ++i) { | ||
13673 | // Compute sbox | ||
13674 | var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) | ||
13675 | sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 | ||
13676 | SBOX[x] = sx | ||
13677 | INV_SBOX[sx] = x | ||
13678 | |||
13679 | // Compute multiplication | ||
13680 | var x2 = d[x] | ||
13681 | var x4 = d[x2] | ||
13682 | var x8 = d[x4] | ||
13683 | |||
13684 | // Compute sub bytes, mix columns tables | ||
13685 | var t = (d[sx] * 0x101) ^ (sx * 0x1010100) | ||
13686 | SUB_MIX[0][x] = (t << 24) | (t >>> 8) | ||
13687 | SUB_MIX[1][x] = (t << 16) | (t >>> 16) | ||
13688 | SUB_MIX[2][x] = (t << 8) | (t >>> 24) | ||
13689 | SUB_MIX[3][x] = t | ||
13690 | |||
13691 | // Compute inv sub bytes, inv mix columns tables | ||
13692 | t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) | ||
13693 | INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) | ||
13694 | INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) | ||
13695 | INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) | ||
13696 | INV_SUB_MIX[3][sx] = t | ||
13697 | |||
13698 | if (x === 0) { | ||
13699 | x = xi = 1 | ||
13700 | } else { | ||
13701 | x = x2 ^ d[d[d[x8 ^ x2]]] | ||
13702 | xi ^= d[d[xi]] | ||
13703 | } | ||
13704 | } | ||
13705 | |||
13706 | return { | ||
13707 | SBOX: SBOX, | ||
13708 | INV_SBOX: INV_SBOX, | ||
13709 | SUB_MIX: SUB_MIX, | ||
13710 | INV_SUB_MIX: INV_SUB_MIX | ||
13711 | } | ||
13712 | })() | ||
13713 | |||
13714 | function AES (key) { | ||
13715 | this._key = asUInt32Array(key) | ||
13716 | this._reset() | ||
13717 | } | ||
13718 | |||
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 | ||
13728 | |||
13729 | var keySchedule = [] | ||
13730 | for (var k = 0; k < keySize; k++) { | ||
13731 | keySchedule[k] = keyWords[k] | ||
13732 | } | ||
13733 | |||
13734 | for (k = keySize; k < ksRows; k++) { | ||
13735 | var t = keySchedule[k - 1] | ||
13736 | |||
13737 | if (k % keySize === 0) { | ||
13738 | t = (t << 8) | (t >>> 24) | ||
13739 | t = | ||
13740 | (G.SBOX[t >>> 24] << 24) | | ||
13741 | (G.SBOX[(t >>> 16) & 0xff] << 16) | | ||
13742 | (G.SBOX[(t >>> 8) & 0xff] << 8) | | ||
13743 | (G.SBOX[t & 0xff]) | ||
13744 | |||
13745 | t ^= RCON[(k / keySize) | 0] << 24 | ||
13746 | } else if (keySize > 6 && k % keySize === 4) { | ||
13747 | t = | ||
13748 | (G.SBOX[t >>> 24] << 24) | | ||
13749 | (G.SBOX[(t >>> 16) & 0xff] << 16) | | ||
13750 | (G.SBOX[(t >>> 8) & 0xff] << 8) | | ||
13751 | (G.SBOX[t & 0xff]) | ||
13752 | } | ||
13753 | |||
13754 | keySchedule[k] = keySchedule[k - keySize] ^ t | ||
13755 | } | ||
13756 | |||
13757 | var invKeySchedule = [] | ||
13758 | for (var ik = 0; ik < ksRows; ik++) { | ||
13759 | var ksR = ksRows - ik | ||
13760 | var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] | ||
13761 | |||
13762 | if (ik < 4 || ksR <= 4) { | ||
13763 | invKeySchedule[ik] = tt | ||
13764 | } else { | ||
13765 | invKeySchedule[ik] = | ||
13766 | G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ | ||
13767 | G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ | ||
13768 | G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ | ||
13769 | G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] | ||
13770 | } | ||
13771 | } | ||
13772 | |||
13773 | this._nRounds = nRounds | ||
13774 | this._keySchedule = keySchedule | ||
13775 | this._invKeySchedule = invKeySchedule | ||
13776 | } | ||
13777 | |||
13778 | AES.prototype.encryptBlockRaw = function (M) { | ||
13779 | M = asUInt32Array(M) | ||
13780 | return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) | ||
13781 | } | ||
13782 | |||
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) | ||
13790 | return buf | ||
13791 | } | ||
13792 | |||
13793 | AES.prototype.decryptBlock = function (M) { | ||
13794 | M = asUInt32Array(M) | ||
13795 | |||
13796 | // swap | ||
13797 | var m1 = M[1] | ||
13798 | M[1] = M[3] | ||
13799 | M[3] = m1 | ||
13800 | |||
13801 | var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) | ||
13802 | var buf = Buffer.allocUnsafe(16) | ||
13803 | buf.writeUInt32BE(out[0], 0) | ||
13804 | buf.writeUInt32BE(out[3], 4) | ||
13805 | buf.writeUInt32BE(out[2], 8) | ||
13806 | buf.writeUInt32BE(out[1], 12) | ||
13807 | return buf | ||
13808 | } | ||
13809 | |||
13810 | AES.prototype.scrub = function () { | ||
13811 | scrubVec(this._keySchedule) | ||
13812 | scrubVec(this._invKeySchedule) | ||
13813 | scrubVec(this._key) | ||
13814 | } | ||
13815 | |||
13816 | module.exports.AES = AES | ||
13817 | |||
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') | ||
13826 | |||
13827 | function xorTest (a, b) { | ||
13828 | var out = 0 | ||
13829 | if (a.length !== b.length) out++ | ||
13830 | |||
13831 | var len = Math.min(a.length, b.length) | ||
13832 | for (var i = 0; i < len; ++i) { | ||
13833 | out += (a[i] ^ b[i]) | ||
13834 | } | ||
13835 | |||
13836 | return out | ||
13837 | } | ||
13838 | |||
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])]) | ||
13843 | } | ||
13844 | var ghash = new GHASH(ck) | ||
13845 | var len = iv.length | ||
13846 | var toPad = len % 16 | ||
13847 | ghash.update(iv) | ||
13848 | if (toPad) { | ||
13849 | toPad = 16 - toPad | ||
13850 | ghash.update(Buffer.alloc(toPad, 0)) | ||
13851 | } | ||
13852 | ghash.update(Buffer.alloc(8, 0)) | ||
13853 | var ivBits = len * 8 | ||
13854 | var tail = Buffer.alloc(8) | ||
13855 | tail.writeUIntBE(ivBits, 0, 8) | ||
13856 | ghash.update(tail) | ||
13857 | self._finID = ghash.state | ||
13858 | var out = Buffer.from(self._finID) | ||
13859 | incr32(out) | ||
13860 | return out | ||
13861 | } | ||
13862 | function StreamCipher (mode, key, iv, decrypt) { | ||
13863 | Transform.call(this) | ||
13864 | |||
13865 | var h = Buffer.alloc(4, 0) | ||
13866 | |||
13867 | this._cipher = new aes.AES(key) | ||
13868 | var ck = this._cipher.encryptBlock(h) | ||
13869 | this._ghash = new GHASH(ck) | ||
13870 | iv = calcIv(this, iv, ck) | ||
13871 | |||
13872 | this._prev = Buffer.from(iv) | ||
13873 | this._cache = Buffer.allocUnsafe(0) | ||
13874 | this._secCache = Buffer.allocUnsafe(0) | ||
13875 | this._decrypt = decrypt | ||
13876 | this._alen = 0 | ||
13877 | this._len = 0 | ||
13878 | this._mode = mode | ||
13879 | |||
13880 | this._authTag = null | ||
13881 | this._called = false | ||
13882 | } | ||
13883 | |||
13884 | inherits(StreamCipher, Transform) | ||
13885 | |||
13886 | StreamCipher.prototype._update = function (chunk) { | ||
13887 | if (!this._called && this._alen) { | ||
13888 | var rump = 16 - (this._alen % 16) | ||
13889 | if (rump < 16) { | ||
13890 | rump = Buffer.alloc(rump, 0) | ||
13891 | this._ghash.update(rump) | ||
13892 | } | ||
13893 | } | ||
13894 | |||
13895 | this._called = true | ||
13896 | var out = this._mode.encrypt(this, chunk) | ||
13897 | if (this._decrypt) { | ||
13898 | this._ghash.update(chunk) | ||
13899 | } else { | ||
13900 | this._ghash.update(out) | ||
13901 | } | ||
13902 | this._len += chunk.length | ||
13903 | return out | ||
13904 | } | ||
13905 | |||
13906 | StreamCipher.prototype._final = function () { | ||
13907 | if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') | ||
13908 | |||
13909 | var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) | ||
13910 | if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') | ||
13911 | |||
13912 | this._authTag = tag | ||
13913 | this._cipher.scrub() | ||
13914 | } | ||
13915 | |||
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') | ||
13918 | |||
13919 | return this._authTag | ||
13920 | } | ||
13921 | |||
13922 | StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { | ||
13923 | if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') | ||
13924 | |||
13925 | this._authTag = tag | ||
13926 | } | ||
13927 | |||
13928 | StreamCipher.prototype.setAAD = function setAAD (buf) { | ||
13929 | if (this._called) throw new Error('Attempting to set AAD in unsupported state') | ||
13930 | |||
13931 | this._ghash.update(buf) | ||
13932 | this._alen += buf.length | ||
13933 | } | ||
13934 | |||
13935 | module.exports = StreamCipher | ||
13936 | |||
13937 | },{"./aes":78,"./ghash":83,"./incr32":84,"buffer-xor":106,"cipher-base":108,"inherits":163,"safe-buffer":247}],80:[function(require,module,exports){ | ||
13938 | var ciphers = require('./encrypter') | ||
13939 | var deciphers = require('./decrypter') | ||
13940 | var modes = require('./modes/list.json') | ||
13941 | |||
13942 | function getCiphers () { | ||
13943 | return Object.keys(modes) | ||
13944 | } | ||
13945 | |||
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 | ||
13951 | |||
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') | ||
13961 | |||
13962 | function Decipher (mode, key, iv) { | ||
13963 | Transform.call(this) | ||
13964 | |||
13965 | this._cache = new Splitter() | ||
13966 | this._last = void 0 | ||
13967 | this._cipher = new aes.AES(key) | ||
13968 | this._prev = Buffer.from(iv) | ||
13969 | this._mode = mode | ||
13970 | this._autopadding = true | ||
13971 | } | ||
13972 | |||
13973 | inherits(Decipher, Transform) | ||
13974 | |||
13975 | Decipher.prototype._update = function (data) { | ||
13976 | this._cache.add(data) | ||
13977 | var chunk | ||
13978 | var thing | ||
13979 | var out = [] | ||
13980 | while ((chunk = this._cache.get(this._autopadding))) { | ||
13981 | thing = this._mode.decrypt(this, chunk) | ||
13982 | out.push(thing) | ||
13983 | } | ||
13984 | return Buffer.concat(out) | ||
13985 | } | ||
13986 | |||
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') | ||
13993 | } | ||
13994 | } | ||
13995 | |||
13996 | Decipher.prototype.setAutoPadding = function (setTo) { | ||
13997 | this._autopadding = !!setTo | ||
13998 | return this | ||
13999 | } | ||
14000 | |||
14001 | function Splitter () { | ||
14002 | this.cache = Buffer.allocUnsafe(0) | ||
14003 | } | ||
14004 | |||
14005 | Splitter.prototype.add = function (data) { | ||
14006 | this.cache = Buffer.concat([this.cache, data]) | ||
14007 | } | ||
14008 | |||
14009 | Splitter.prototype.get = function (autoPadding) { | ||
14010 | var out | ||
14011 | if (autoPadding) { | ||
14012 | if (this.cache.length > 16) { | ||
14013 | out = this.cache.slice(0, 16) | ||
14014 | this.cache = this.cache.slice(16) | ||
14015 | return out | ||
14016 | } | ||
14017 | } else { | ||
14018 | if (this.cache.length >= 16) { | ||
14019 | out = this.cache.slice(0, 16) | ||
14020 | this.cache = this.cache.slice(16) | ||
14021 | return out | ||
14022 | } | ||
14023 | } | ||
14024 | |||
14025 | return null | ||
14026 | } | ||
14027 | |||
14028 | Splitter.prototype.flush = function () { | ||
14029 | if (this.cache.length) return this.cache | ||
14030 | } | ||
14031 | |||
14032 | function unpad (last) { | ||
14033 | var padded = last[15] | ||
14034 | var i = -1 | ||
14035 | while (++i < padded) { | ||
14036 | if (last[(i + (16 - padded))] !== padded) { | ||
14037 | throw new Error('unable to decrypt data') | ||
14038 | } | ||
14039 | } | ||
14040 | if (padded === 16) return | ||
14041 | |||
14042 | return last.slice(0, 16 - padded) | ||
14043 | } | ||
14044 | |||
14045 | function createDecipheriv (suite, password, iv) { | ||
14046 | var config = MODES[suite.toLowerCase()] | ||
14047 | if (!config) throw new TypeError('invalid suite type') | ||
14048 | |||
14049 | if (typeof iv === 'string') iv = Buffer.from(iv) | ||
14050 | if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) | ||
14051 | |||
14052 | if (typeof password === 'string') password = Buffer.from(password) | ||
14053 | if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) | ||
14054 | |||
14055 | if (config.type === 'stream') { | ||
14056 | return new StreamCipher(config.module, password, iv, true) | ||
14057 | } else if (config.type === 'auth') { | ||
14058 | return new AuthCipher(config.module, password, iv, true) | ||
14059 | } | ||
14060 | |||
14061 | return new Decipher(config.module, password, iv) | ||
14062 | } | ||
14063 | |||
14064 | function createDecipher (suite, password) { | ||
14065 | var config = MODES[suite.toLowerCase()] | ||
14066 | if (!config) throw new TypeError('invalid suite type') | ||
14067 | |||
14068 | var keys = ebtk(password, false, config.key, config.iv) | ||
14069 | return createDecipheriv(suite, keys.key, keys.iv) | ||
14070 | } | ||
14071 | |||
14072 | exports.createDecipher = createDecipher | ||
14073 | exports.createDecipheriv = createDecipheriv | ||
14074 | |||
14075 | },{"./aes":78,"./authCipher":79,"./modes":91,"./streamCipher":94,"cipher-base":108,"evp_bytestokey":144,"inherits":163,"safe-buffer":247}],82:[function(require,module,exports){ | ||
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') | ||
14084 | |||
14085 | function Cipher (mode, key, iv) { | ||
14086 | Transform.call(this) | ||
14087 | |||
14088 | this._cache = new Splitter() | ||
14089 | this._cipher = new aes.AES(key) | ||
14090 | this._prev = Buffer.from(iv) | ||
14091 | this._mode = mode | ||
14092 | this._autopadding = true | ||
14093 | } | ||
14094 | |||
14095 | inherits(Cipher, Transform) | ||
14096 | |||
14097 | Cipher.prototype._update = function (data) { | ||
14098 | this._cache.add(data) | ||
14099 | var chunk | ||
14100 | var thing | ||
14101 | var out = [] | ||
14102 | |||
14103 | while ((chunk = this._cache.get())) { | ||
14104 | thing = this._mode.encrypt(this, chunk) | ||
14105 | out.push(thing) | ||
14106 | } | ||
14107 | |||
14108 | return Buffer.concat(out) | ||
14109 | } | ||
14110 | |||
14111 | var PADDING = Buffer.alloc(16, 0x10) | ||
14112 | |||
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() | ||
14118 | return chunk | ||
14119 | } | ||
14120 | |||
14121 | if (!chunk.equals(PADDING)) { | ||
14122 | this._cipher.scrub() | ||
14123 | throw new Error('data not multiple of block length') | ||
14124 | } | ||
14125 | } | ||
14126 | |||
14127 | Cipher.prototype.setAutoPadding = function (setTo) { | ||
14128 | this._autopadding = !!setTo | ||
14129 | return this | ||
14130 | } | ||
14131 | |||
14132 | function Splitter () { | ||
14133 | this.cache = Buffer.allocUnsafe(0) | ||
14134 | } | ||
14135 | |||
14136 | Splitter.prototype.add = function (data) { | ||
14137 | this.cache = Buffer.concat([this.cache, data]) | ||
14138 | } | ||
14139 | |||
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) | ||
14144 | return out | ||
14145 | } | ||
14146 | return null | ||
14147 | } | ||
14148 | |||
14149 | Splitter.prototype.flush = function () { | ||
14150 | var len = 16 - this.cache.length | ||
14151 | var padBuff = Buffer.allocUnsafe(len) | ||
14152 | |||
14153 | var i = -1 | ||
14154 | while (++i < len) { | ||
14155 | padBuff.writeUInt8(len, i) | ||
14156 | } | ||
14157 | |||
14158 | return Buffer.concat([this.cache, padBuff]) | ||
14159 | } | ||
14160 | |||
14161 | function createCipheriv (suite, password, iv) { | ||
14162 | var config = MODES[suite.toLowerCase()] | ||
14163 | if (!config) throw new TypeError('invalid suite type') | ||
14164 | |||
14165 | if (typeof password === 'string') password = Buffer.from(password) | ||
14166 | if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) | ||
14167 | |||
14168 | if (typeof iv === 'string') iv = Buffer.from(iv) | ||
14169 | if (config.mode !== 'GCM' && iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) | ||
14170 | |||
14171 | if (config.type === 'stream') { | ||
14172 | return new StreamCipher(config.module, password, iv) | ||
14173 | } else if (config.type === 'auth') { | ||
14174 | return new AuthCipher(config.module, password, iv) | ||
14175 | } | ||
14176 | |||
14177 | return new Cipher(config.module, password, iv) | ||
14178 | } | ||
14179 | |||
14180 | function createCipher (suite, password) { | ||
14181 | var config = MODES[suite.toLowerCase()] | ||
14182 | if (!config) throw new TypeError('invalid suite type') | ||
14183 | |||
14184 | var keys = ebtk(password, false, config.key, config.iv) | ||
14185 | return createCipheriv(suite, keys.key, keys.iv) | ||
14186 | } | ||
14187 | |||
14188 | exports.createCipheriv = createCipheriv | ||
14189 | exports.createCipher = createCipher | ||
14190 | |||
14191 | },{"./aes":78,"./authCipher":79,"./modes":91,"./streamCipher":94,"cipher-base":108,"evp_bytestokey":144,"inherits":163,"safe-buffer":247}],83:[function(require,module,exports){ | ||
14192 | var Buffer = require('safe-buffer').Buffer | ||
14193 | var ZEROES = Buffer.alloc(16, 0) | ||
14194 | |||
14195 | function toArray (buf) { | ||
14196 | return [ | ||
14197 | buf.readUInt32BE(0), | ||
14198 | buf.readUInt32BE(4), | ||
14199 | buf.readUInt32BE(8), | ||
14200 | buf.readUInt32BE(12) | ||
14201 | ] | ||
14202 | } | ||
14203 | |||
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) | ||
14210 | return buf | ||
14211 | } | ||
14212 | |||
14213 | function GHASH (key) { | ||
14214 | this.h = key | ||
14215 | this.state = Buffer.alloc(16, 0) | ||
14216 | this.cache = Buffer.allocUnsafe(0) | ||
14217 | } | ||
14218 | |||
14219 | // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html | ||
14220 | // by Juho Vähä-Herttua | ||
14221 | GHASH.prototype.ghash = function (block) { | ||
14222 | var i = -1 | ||
14223 | while (++i < block.length) { | ||
14224 | this.state[i] ^= block[i] | ||
14225 | } | ||
14226 | this._multiply() | ||
14227 | } | ||
14228 | |||
14229 | GHASH.prototype._multiply = function () { | ||
14230 | var Vi = toArray(this.h) | ||
14231 | var Zi = [0, 0, 0, 0] | ||
14232 | var j, xi, lsbVi | ||
14233 | var i = -1 | ||
14234 | while (++i < 128) { | ||
14235 | xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 | ||
14236 | if (xi) { | ||
14237 | // Z_i+1 = Z_i ^ V_i | ||
14238 | Zi[0] ^= Vi[0] | ||
14239 | Zi[1] ^= Vi[1] | ||
14240 | Zi[2] ^= Vi[2] | ||
14241 | Zi[3] ^= Vi[3] | ||
14242 | } | ||
14243 | |||
14244 | // Store the value of LSB(V_i) | ||
14245 | lsbVi = (Vi[3] & 1) !== 0 | ||
14246 | |||
14247 | // V_i+1 = V_i >> 1 | ||
14248 | for (j = 3; j > 0; j--) { | ||
14249 | Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) | ||
14250 | } | ||
14251 | Vi[0] = Vi[0] >>> 1 | ||
14252 | |||
14253 | // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R | ||
14254 | if (lsbVi) { | ||
14255 | Vi[0] = Vi[0] ^ (0xe1 << 24) | ||
14256 | } | ||
14257 | } | ||
14258 | this.state = fromArray(Zi) | ||
14259 | } | ||
14260 | |||
14261 | GHASH.prototype.update = function (buf) { | ||
14262 | this.cache = Buffer.concat([this.cache, buf]) | ||
14263 | var chunk | ||
14264 | while (this.cache.length >= 16) { | ||
14265 | chunk = this.cache.slice(0, 16) | ||
14266 | this.cache = this.cache.slice(16) | ||
14267 | this.ghash(chunk) | ||
14268 | } | ||
14269 | } | ||
14270 | |||
14271 | GHASH.prototype.final = function (abl, bl) { | ||
14272 | if (this.cache.length) { | ||
14273 | this.ghash(Buffer.concat([this.cache, ZEROES], 16)) | ||
14274 | } | ||
14275 | |||
14276 | this.ghash(fromArray([0, abl, 0, bl])) | ||
14277 | return this.state | ||
14278 | } | ||
14279 | |||
14280 | module.exports = GHASH | ||
14281 | |||
14282 | },{"safe-buffer":247}],84:[function(require,module,exports){ | ||
14283 | function incr32 (iv) { | ||
14284 | var len = iv.length | ||
14285 | var item | ||
14286 | while (len--) { | ||
14287 | item = iv.readUInt8(len) | ||
14288 | if (item === 255) { | ||
14289 | iv.writeUInt8(0, len) | ||
14290 | } else { | ||
14291 | item++ | ||
14292 | iv.writeUInt8(item, len) | ||
14293 | break | ||
14294 | } | ||
14295 | } | ||
14296 | } | ||
14297 | module.exports = incr32 | ||
14298 | |||
14299 | },{}],85:[function(require,module,exports){ | ||
14300 | var xor = require('buffer-xor') | ||
14301 | |||
14302 | exports.encrypt = function (self, block) { | ||
14303 | var data = xor(block, self._prev) | ||
14304 | |||
14305 | self._prev = self._cipher.encryptBlock(data) | ||
14306 | return self._prev | ||
14307 | } | ||
14308 | |||
14309 | exports.decrypt = function (self, block) { | ||
14310 | var pad = self._prev | ||
14311 | |||
14312 | self._prev = block | ||
14313 | var out = self._cipher.decryptBlock(block) | ||
14314 | |||
14315 | return xor(out, pad) | ||
14316 | } | ||
14317 | |||
14318 | },{"buffer-xor":106}],86:[function(require,module,exports){ | ||
14319 | var Buffer = require('safe-buffer').Buffer | ||
14320 | var xor = require('buffer-xor') | ||
14321 | |||
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]) | ||
14327 | return out | ||
14328 | } | ||
14329 | |||
14330 | exports.encrypt = function (self, data, decrypt) { | ||
14331 | var out = Buffer.allocUnsafe(0) | ||
14332 | var len | ||
14333 | |||
14334 | while (data.length) { | ||
14335 | if (self._cache.length === 0) { | ||
14336 | self._cache = self._cipher.encryptBlock(self._prev) | ||
14337 | self._prev = Buffer.allocUnsafe(0) | ||
14338 | } | ||
14339 | |||
14340 | if (self._cache.length <= data.length) { | ||
14341 | len = self._cache.length | ||
14342 | out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) | ||
14343 | data = data.slice(len) | ||
14344 | } else { | ||
14345 | out = Buffer.concat([out, encryptStart(self, data, decrypt)]) | ||
14346 | break | ||
14347 | } | ||
14348 | } | ||
14349 | |||
14350 | return out | ||
14351 | } | ||
14352 | |||
14353 | },{"buffer-xor":106,"safe-buffer":247}],87:[function(require,module,exports){ | ||
14354 | var Buffer = require('safe-buffer').Buffer | ||
14355 | |||
14356 | function encryptByte (self, byteParam, decrypt) { | ||
14357 | var pad | ||
14358 | var i = -1 | ||
14359 | var len = 8 | ||
14360 | var out = 0 | ||
14361 | var bit, value | ||
14362 | while (++i < len) { | ||
14363 | pad = self._cipher.encryptBlock(self._prev) | ||
14364 | bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 | ||
14365 | value = pad[0] ^ bit | ||
14366 | out += ((value & 0x80) >> (i % 8)) | ||
14367 | self._prev = shiftIn(self._prev, decrypt ? bit : value) | ||
14368 | } | ||
14369 | return out | ||
14370 | } | ||
14371 | |||
14372 | function shiftIn (buffer, value) { | ||
14373 | var len = buffer.length | ||
14374 | var i = -1 | ||
14375 | var out = Buffer.allocUnsafe(buffer.length) | ||
14376 | buffer = Buffer.concat([buffer, Buffer.from([value])]) | ||
14377 | |||
14378 | while (++i < len) { | ||
14379 | out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) | ||
14380 | } | ||
14381 | |||
14382 | return out | ||
14383 | } | ||
14384 | |||
14385 | exports.encrypt = function (self, chunk, decrypt) { | ||
14386 | var len = chunk.length | ||
14387 | var out = Buffer.allocUnsafe(len) | ||
14388 | var i = -1 | ||
14389 | |||
14390 | while (++i < len) { | ||
14391 | out[i] = encryptByte(self, chunk[i], decrypt) | ||
14392 | } | ||
14393 | |||
14394 | return out | ||
14395 | } | ||
14396 | |||
14397 | },{"safe-buffer":247}],88:[function(require,module,exports){ | ||
14398 | var Buffer = require('safe-buffer').Buffer | ||
14399 | |||
14400 | function encryptByte (self, byteParam, decrypt) { | ||
14401 | var pad = self._cipher.encryptBlock(self._prev) | ||
14402 | var out = pad[0] ^ byteParam | ||
14403 | |||
14404 | self._prev = Buffer.concat([ | ||
14405 | self._prev.slice(1), | ||
14406 | Buffer.from([decrypt ? byteParam : out]) | ||
14407 | ]) | ||
14408 | |||
14409 | return out | ||
14410 | } | ||
14411 | |||
14412 | exports.encrypt = function (self, chunk, decrypt) { | ||
14413 | var len = chunk.length | ||
14414 | var out = Buffer.allocUnsafe(len) | ||
14415 | var i = -1 | ||
14416 | |||
14417 | while (++i < len) { | ||
14418 | out[i] = encryptByte(self, chunk[i], decrypt) | ||
14419 | } | ||
14420 | |||
14421 | return out | ||
14422 | } | ||
14423 | |||
14424 | },{"safe-buffer":247}],89:[function(require,module,exports){ | ||
14425 | var xor = require('buffer-xor') | ||
14426 | var Buffer = require('safe-buffer').Buffer | ||
14427 | var incr32 = require('../incr32') | ||
14428 | |||
14429 | function getBlock (self) { | ||
14430 | var out = self._cipher.encryptBlockRaw(self._prev) | ||
14431 | incr32(self._prev) | ||
14432 | return out | ||
14433 | } | ||
14434 | |||
14435 | var blockSize = 16 | ||
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([ | ||
14440 | self._cache, | ||
14441 | Buffer.allocUnsafe(chunkNum * blockSize) | ||
14442 | ]) | ||
14443 | for (var i = 0; i < chunkNum; i++) { | ||
14444 | var out = getBlock(self) | ||
14445 | var offset = start + i * blockSize | ||
14446 | self._cache.writeUInt32BE(out[0], offset + 0) | ||
14447 | self._cache.writeUInt32BE(out[1], offset + 4) | ||
14448 | self._cache.writeUInt32BE(out[2], offset + 8) | ||
14449 | self._cache.writeUInt32BE(out[3], offset + 12) | ||
14450 | } | ||
14451 | var pad = self._cache.slice(0, chunk.length) | ||
14452 | self._cache = self._cache.slice(chunk.length) | ||
14453 | return xor(chunk, pad) | ||
14454 | } | ||
14455 | |||
14456 | },{"../incr32":84,"buffer-xor":106,"safe-buffer":247}],90:[function(require,module,exports){ | ||
14457 | exports.encrypt = function (self, block) { | ||
14458 | return self._cipher.encryptBlock(block) | ||
14459 | } | ||
14460 | |||
14461 | exports.decrypt = function (self, block) { | ||
14462 | return self._cipher.decryptBlock(block) | ||
14463 | } | ||
14464 | |||
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') | ||
14475 | } | ||
14476 | |||
14477 | var modes = require('./list.json') | ||
14478 | |||
14479 | for (var key in modes) { | ||
14480 | modes[key].module = modeModules[modes[key].mode] | ||
14481 | } | ||
14482 | |||
14483 | module.exports = modes | ||
14484 | |||
14485 | },{"./cbc":85,"./cfb":86,"./cfb1":87,"./cfb8":88,"./ctr":89,"./ecb":90,"./list.json":92,"./ofb":93}],92:[function(require,module,exports){ | ||
14486 | module.exports={ | ||
14487 | "aes-128-ecb": { | ||
14488 | "cipher": "AES", | ||
14489 | "key": 128, | ||
14490 | "iv": 0, | ||
14491 | "mode": "ECB", | ||
14492 | "type": "block" | ||
14493 | }, | ||
14494 | "aes-192-ecb": { | ||
14495 | "cipher": "AES", | ||
14496 | "key": 192, | ||
14497 | "iv": 0, | ||
14498 | "mode": "ECB", | ||
14499 | "type": "block" | ||
14500 | }, | ||
14501 | "aes-256-ecb": { | ||
14502 | "cipher": "AES", | ||
14503 | "key": 256, | ||
14504 | "iv": 0, | ||
14505 | "mode": "ECB", | ||
14506 | "type": "block" | ||
14507 | }, | ||
14508 | "aes-128-cbc": { | ||
14509 | "cipher": "AES", | ||
14510 | "key": 128, | ||
14511 | "iv": 16, | ||
14512 | "mode": "CBC", | ||
14513 | "type": "block" | ||
14514 | }, | ||
14515 | "aes-192-cbc": { | ||
14516 | "cipher": "AES", | ||
14517 | "key": 192, | ||
14518 | "iv": 16, | ||
14519 | "mode": "CBC", | ||
14520 | "type": "block" | ||
14521 | }, | ||
14522 | "aes-256-cbc": { | ||
14523 | "cipher": "AES", | ||
14524 | "key": 256, | ||
14525 | "iv": 16, | ||
14526 | "mode": "CBC", | ||
14527 | "type": "block" | ||
14528 | }, | ||
14529 | "aes128": { | ||
14530 | "cipher": "AES", | ||
14531 | "key": 128, | ||
14532 | "iv": 16, | ||
14533 | "mode": "CBC", | ||
14534 | "type": "block" | ||
14535 | }, | ||
14536 | "aes192": { | ||
14537 | "cipher": "AES", | ||
14538 | "key": 192, | ||
14539 | "iv": 16, | ||
14540 | "mode": "CBC", | ||
14541 | "type": "block" | ||
14542 | }, | ||
14543 | "aes256": { | ||
14544 | "cipher": "AES", | ||
14545 | "key": 256, | ||
14546 | "iv": 16, | ||
14547 | "mode": "CBC", | ||
14548 | "type": "block" | ||
14549 | }, | ||
14550 | "aes-128-cfb": { | ||
14551 | "cipher": "AES", | ||
14552 | "key": 128, | ||
14553 | "iv": 16, | ||
14554 | "mode": "CFB", | ||
14555 | "type": "stream" | ||
14556 | }, | ||
14557 | "aes-192-cfb": { | ||
14558 | "cipher": "AES", | ||
14559 | "key": 192, | ||
14560 | "iv": 16, | ||
14561 | "mode": "CFB", | ||
14562 | "type": "stream" | ||
14563 | }, | ||
14564 | "aes-256-cfb": { | ||
14565 | "cipher": "AES", | ||
14566 | "key": 256, | ||
14567 | "iv": 16, | ||
14568 | "mode": "CFB", | ||
14569 | "type": "stream" | ||
14570 | }, | ||
14571 | "aes-128-cfb8": { | ||
14572 | "cipher": "AES", | ||
14573 | "key": 128, | ||
14574 | "iv": 16, | ||
14575 | "mode": "CFB8", | ||
14576 | "type": "stream" | ||
14577 | }, | ||
14578 | "aes-192-cfb8": { | ||
14579 | "cipher": "AES", | ||
14580 | "key": 192, | ||
14581 | "iv": 16, | ||
14582 | "mode": "CFB8", | ||
14583 | "type": "stream" | ||
14584 | }, | ||
14585 | "aes-256-cfb8": { | ||
14586 | "cipher": "AES", | ||
14587 | "key": 256, | ||
14588 | "iv": 16, | ||
14589 | "mode": "CFB8", | ||
14590 | "type": "stream" | ||
14591 | }, | ||
14592 | "aes-128-cfb1": { | ||
14593 | "cipher": "AES", | ||
14594 | "key": 128, | ||
14595 | "iv": 16, | ||
14596 | "mode": "CFB1", | ||
14597 | "type": "stream" | ||
14598 | }, | ||
14599 | "aes-192-cfb1": { | ||
14600 | "cipher": "AES", | ||
14601 | "key": 192, | ||
14602 | "iv": 16, | ||
14603 | "mode": "CFB1", | ||
14604 | "type": "stream" | ||
14605 | }, | ||
14606 | "aes-256-cfb1": { | ||
14607 | "cipher": "AES", | ||
14608 | "key": 256, | ||
14609 | "iv": 16, | ||
14610 | "mode": "CFB1", | ||
14611 | "type": "stream" | ||
14612 | }, | ||
14613 | "aes-128-ofb": { | ||
14614 | "cipher": "AES", | ||
14615 | "key": 128, | ||
14616 | "iv": 16, | ||
14617 | "mode": "OFB", | ||
14618 | "type": "stream" | ||
14619 | }, | ||
14620 | "aes-192-ofb": { | ||
14621 | "cipher": "AES", | ||
14622 | "key": 192, | ||
14623 | "iv": 16, | ||
14624 | "mode": "OFB", | ||
14625 | "type": "stream" | ||
14626 | }, | ||
14627 | "aes-256-ofb": { | ||
14628 | "cipher": "AES", | ||
14629 | "key": 256, | ||
14630 | "iv": 16, | ||
14631 | "mode": "OFB", | ||
14632 | "type": "stream" | ||
14633 | }, | ||
14634 | "aes-128-ctr": { | ||
14635 | "cipher": "AES", | ||
14636 | "key": 128, | ||
14637 | "iv": 16, | ||
14638 | "mode": "CTR", | ||
14639 | "type": "stream" | ||
14640 | }, | ||
14641 | "aes-192-ctr": { | ||
14642 | "cipher": "AES", | ||
14643 | "key": 192, | ||
14644 | "iv": 16, | ||
14645 | "mode": "CTR", | ||
14646 | "type": "stream" | ||
14647 | }, | ||
14648 | "aes-256-ctr": { | ||
14649 | "cipher": "AES", | ||
14650 | "key": 256, | ||
14651 | "iv": 16, | ||
14652 | "mode": "CTR", | ||
14653 | "type": "stream" | ||
14654 | }, | ||
14655 | "aes-128-gcm": { | ||
14656 | "cipher": "AES", | ||
14657 | "key": 128, | ||
14658 | "iv": 12, | ||
14659 | "mode": "GCM", | ||
14660 | "type": "auth" | ||
14661 | }, | ||
14662 | "aes-192-gcm": { | ||
14663 | "cipher": "AES", | ||
14664 | "key": 192, | ||
14665 | "iv": 12, | ||
14666 | "mode": "GCM", | ||
14667 | "type": "auth" | ||
14668 | }, | ||
14669 | "aes-256-gcm": { | ||
14670 | "cipher": "AES", | ||
14671 | "key": 256, | ||
14672 | "iv": 12, | ||
14673 | "mode": "GCM", | ||
14674 | "type": "auth" | ||
14675 | } | ||
14676 | } | ||
14677 | |||
14678 | },{}],93:[function(require,module,exports){ | ||
14679 | (function (Buffer){ | ||
14680 | var xor = require('buffer-xor') | ||
14681 | |||
14682 | function getBlock (self) { | ||
14683 | self._prev = self._cipher.encryptBlock(self._prev) | ||
14684 | return self._prev | ||
14685 | } | ||
14686 | |||
14687 | exports.encrypt = function (self, chunk) { | ||
14688 | while (self._cache.length < chunk.length) { | ||
14689 | self._cache = Buffer.concat([self._cache, getBlock(self)]) | ||
14690 | } | ||
14691 | |||
14692 | var pad = self._cache.slice(0, chunk.length) | ||
14693 | self._cache = self._cache.slice(chunk.length) | ||
14694 | return xor(chunk, pad) | ||
14695 | } | ||
14696 | |||
14697 | }).call(this,require("buffer").Buffer) | ||
14698 | },{"buffer":107,"buffer-xor":106}],94:[function(require,module,exports){ | ||
14699 | var aes = require('./aes') | ||
14700 | var Buffer = require('safe-buffer').Buffer | ||
14701 | var Transform = require('cipher-base') | ||
14702 | var inherits = require('inherits') | ||
14703 | |||
14704 | function StreamCipher (mode, key, iv, decrypt) { | ||
14705 | Transform.call(this) | ||
14706 | |||
14707 | this._cipher = new aes.AES(key) | ||
14708 | this._prev = Buffer.from(iv) | ||
14709 | this._cache = Buffer.allocUnsafe(0) | ||
14710 | this._secCache = Buffer.allocUnsafe(0) | ||
14711 | this._decrypt = decrypt | ||
14712 | this._mode = mode | ||
14713 | } | ||
14714 | |||
14715 | inherits(StreamCipher, Transform) | ||
14716 | |||
14717 | StreamCipher.prototype._update = function (chunk) { | ||
14718 | return this._mode.encrypt(this, chunk, this._decrypt) | ||
14719 | } | ||
14720 | |||
14721 | StreamCipher.prototype._final = function () { | ||
14722 | this._cipher.scrub() | ||
14723 | } | ||
14724 | |||
14725 | module.exports = StreamCipher | ||
14726 | |||
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) { | ||
14734 | var keyLen, ivLen | ||
14735 | suite = suite.toLowerCase() | ||
14736 | if (aesModes[suite]) { | ||
14737 | keyLen = aesModes[suite].key | ||
14738 | ivLen = aesModes[suite].iv | ||
14739 | } else if (desModes[suite]) { | ||
14740 | keyLen = desModes[suite].key * 8 | ||
14741 | ivLen = desModes[suite].iv | ||
14742 | } else { | ||
14743 | throw new TypeError('invalid suite type') | ||
14744 | } | ||
14745 | var keys = ebtk(password, false, keyLen, ivLen) | ||
14746 | return createCipheriv(suite, keys.key, keys.iv) | ||
14747 | } | ||
14748 | function createDecipher (suite, password) { | ||
14749 | var keyLen, ivLen | ||
14750 | suite = suite.toLowerCase() | ||
14751 | if (aesModes[suite]) { | ||
14752 | keyLen = aesModes[suite].key | ||
14753 | ivLen = aesModes[suite].iv | ||
14754 | } else if (desModes[suite]) { | ||
14755 | keyLen = desModes[suite].key * 8 | ||
14756 | ivLen = desModes[suite].iv | ||
14757 | } else { | ||
14758 | throw new TypeError('invalid suite type') | ||
14759 | } | ||
14760 | var keys = ebtk(password, false, keyLen, ivLen) | ||
14761 | return createDecipheriv(suite, keys.key, keys.iv) | ||
14762 | } | ||
14763 | |||
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]) { | ||
14769 | return new DES({ | ||
14770 | key: key, | ||
14771 | iv: iv, | ||
14772 | mode: suite | ||
14773 | }) | ||
14774 | } else { | ||
14775 | throw new TypeError('invalid suite type') | ||
14776 | } | ||
14777 | } | ||
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]) { | ||
14783 | return new DES({ | ||
14784 | key: key, | ||
14785 | iv: iv, | ||
14786 | mode: suite, | ||
14787 | decrypt: true | ||
14788 | }) | ||
14789 | } else { | ||
14790 | throw new TypeError('invalid suite type') | ||
14791 | } | ||
14792 | } | ||
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()) | ||
14799 | } | ||
14800 | exports.listCiphers = exports.getCiphers = getCiphers | ||
14801 | |||
14802 | },{"browserify-aes/browser":80,"browserify-aes/modes":91,"browserify-des":96,"browserify-des/modes":97,"evp_bytestokey":144}],96:[function(require,module,exports){ | ||
14803 | (function (Buffer){ | ||
14804 | var CipherBase = require('cipher-base') | ||
14805 | var des = require('des.js') | ||
14806 | var inherits = require('inherits') | ||
14807 | |||
14808 | var modes = { | ||
14809 | 'des-ede3-cbc': des.CBC.instantiate(des.EDE), | ||
14810 | 'des-ede3': des.EDE, | ||
14811 | 'des-ede-cbc': des.CBC.instantiate(des.EDE), | ||
14812 | 'des-ede': des.EDE, | ||
14813 | 'des-cbc': des.CBC.instantiate(des.DES), | ||
14814 | 'des-ecb': des.DES | ||
14815 | } | ||
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] | ||
14824 | var type | ||
14825 | if (opts.decrypt) { | ||
14826 | type = 'decrypt' | ||
14827 | } else { | ||
14828 | type = 'encrypt' | ||
14829 | } | ||
14830 | var key = opts.key | ||
14831 | if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { | ||
14832 | key = Buffer.concat([key, key.slice(0, 8)]) | ||
14833 | } | ||
14834 | var iv = opts.iv | ||
14835 | this._des = mode.create({ | ||
14836 | key: key, | ||
14837 | iv: iv, | ||
14838 | type: type | ||
14839 | }) | ||
14840 | } | ||
14841 | DES.prototype._update = function (data) { | ||
14842 | return new Buffer(this._des.update(data)) | ||
14843 | } | ||
14844 | DES.prototype._final = function () { | ||
14845 | return new Buffer(this._des.final()) | ||
14846 | } | ||
14847 | |||
14848 | }).call(this,require("buffer").Buffer) | ||
14849 | },{"buffer":107,"cipher-base":108,"des.js":117,"inherits":163}],97:[function(require,module,exports){ | ||
14850 | exports['des-ecb'] = { | ||
14851 | key: 8, | ||
14852 | iv: 0 | ||
14853 | } | ||
14854 | exports['des-cbc'] = exports.des = { | ||
14855 | key: 8, | ||
14856 | iv: 8 | ||
14857 | } | ||
14858 | exports['des-ede3-cbc'] = exports.des3 = { | ||
14859 | key: 24, | ||
14860 | iv: 8 | ||
14861 | } | ||
14862 | exports['des-ede3'] = { | ||
14863 | key: 24, | ||
14864 | iv: 0 | ||
14865 | } | ||
14866 | exports['des-ede-cbc'] = { | ||
14867 | key: 16, | ||
14868 | iv: 8 | ||
14869 | } | ||
14870 | exports['des-ede'] = { | ||
14871 | key: 16, | ||
14872 | iv: 0 | ||
14873 | } | ||
14874 | |||
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(); | ||
14884 | return { | ||
14885 | blinder: blinder, | ||
14886 | unblinder:r.invm(priv.modulus) | ||
14887 | }; | ||
14888 | } | ||
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); | ||
14901 | m1 = m1.fromRed(); | ||
14902 | m2 = m2.fromRed(); | ||
14903 | var h = m1.isub(m2).imul(qinv).umod(p); | ||
14904 | h.imul(q); | ||
14905 | m2.iadd(h); | ||
14906 | return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len)); | ||
14907 | } | ||
14908 | crt.getr = getr; | ||
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)); | ||
14914 | } | ||
14915 | return r; | ||
14916 | } | ||
14917 | |||
14918 | }).call(this,require("buffer").Buffer) | ||
14919 | },{"bn.js":75,"buffer":107,"randombytes":231}],99:[function(require,module,exports){ | ||
14920 | module.exports = require('./browser/algorithms.json') | ||
14921 | |||
14922 | },{"./browser/algorithms.json":100}],100:[function(require,module,exports){ | ||
14923 | module.exports={ | ||
14924 | "sha224WithRSAEncryption": { | ||
14925 | "sign": "rsa", | ||
14926 | "hash": "sha224", | ||
14927 | "id": "302d300d06096086480165030402040500041c" | ||
14928 | }, | ||
14929 | "RSA-SHA224": { | ||
14930 | "sign": "ecdsa/rsa", | ||
14931 | "hash": "sha224", | ||
14932 | "id": "302d300d06096086480165030402040500041c" | ||
14933 | }, | ||
14934 | "sha256WithRSAEncryption": { | ||
14935 | "sign": "rsa", | ||
14936 | "hash": "sha256", | ||
14937 | "id": "3031300d060960864801650304020105000420" | ||
14938 | }, | ||
14939 | "RSA-SHA256": { | ||
14940 | "sign": "ecdsa/rsa", | ||
14941 | "hash": "sha256", | ||
14942 | "id": "3031300d060960864801650304020105000420" | ||
14943 | }, | ||
14944 | "sha384WithRSAEncryption": { | ||
14945 | "sign": "rsa", | ||
14946 | "hash": "sha384", | ||
14947 | "id": "3041300d060960864801650304020205000430" | ||
14948 | }, | ||
14949 | "RSA-SHA384": { | ||
14950 | "sign": "ecdsa/rsa", | ||
14951 | "hash": "sha384", | ||
14952 | "id": "3041300d060960864801650304020205000430" | ||
14953 | }, | ||
14954 | "sha512WithRSAEncryption": { | ||
14955 | "sign": "rsa", | ||
14956 | "hash": "sha512", | ||
14957 | "id": "3051300d060960864801650304020305000440" | ||
14958 | }, | ||
14959 | "RSA-SHA512": { | ||
14960 | "sign": "ecdsa/rsa", | ||
14961 | "hash": "sha512", | ||
14962 | "id": "3051300d060960864801650304020305000440" | ||
14963 | }, | ||
14964 | "RSA-SHA1": { | ||
14965 | "sign": "rsa", | ||
14966 | "hash": "sha1", | ||
14967 | "id": "3021300906052b0e03021a05000414" | ||
14968 | }, | ||
14969 | "ecdsa-with-SHA1": { | ||
14970 | "sign": "ecdsa", | ||
14971 | "hash": "sha1", | ||
14972 | "id": "" | ||
14973 | }, | ||
14974 | "sha256": { | ||
14975 | "sign": "ecdsa", | ||
14976 | "hash": "sha256", | ||
14977 | "id": "" | ||
14978 | }, | ||
14979 | "sha224": { | ||
14980 | "sign": "ecdsa", | ||
14981 | "hash": "sha224", | ||
14982 | "id": "" | ||
14983 | }, | ||
14984 | "sha384": { | ||
14985 | "sign": "ecdsa", | ||
14986 | "hash": "sha384", | ||
14987 | "id": "" | ||
14988 | }, | ||
14989 | "sha512": { | ||
14990 | "sign": "ecdsa", | ||
14991 | "hash": "sha512", | ||
14992 | "id": "" | ||
14993 | }, | ||
14994 | "DSA-SHA": { | ||
14995 | "sign": "dsa", | ||
14996 | "hash": "sha1", | ||
14997 | "id": "" | ||
14998 | }, | ||
14999 | "DSA-SHA1": { | ||
15000 | "sign": "dsa", | ||
15001 | "hash": "sha1", | ||
15002 | "id": "" | ||
15003 | }, | ||
15004 | "DSA": { | ||
15005 | "sign": "dsa", | ||
15006 | "hash": "sha1", | ||
15007 | "id": "" | ||
15008 | }, | ||
15009 | "DSA-WITH-SHA224": { | ||
15010 | "sign": "dsa", | ||
15011 | "hash": "sha224", | ||
15012 | "id": "" | ||
15013 | }, | ||
15014 | "DSA-SHA224": { | ||
15015 | "sign": "dsa", | ||
15016 | "hash": "sha224", | ||
15017 | "id": "" | ||
15018 | }, | ||
15019 | "DSA-WITH-SHA256": { | ||
15020 | "sign": "dsa", | ||
15021 | "hash": "sha256", | ||
15022 | "id": "" | ||
15023 | }, | ||
15024 | "DSA-SHA256": { | ||
15025 | "sign": "dsa", | ||
15026 | "hash": "sha256", | ||
15027 | "id": "" | ||
15028 | }, | ||
15029 | "DSA-WITH-SHA384": { | ||
15030 | "sign": "dsa", | ||
15031 | "hash": "sha384", | ||
15032 | "id": "" | ||
15033 | }, | ||
15034 | "DSA-SHA384": { | ||
15035 | "sign": "dsa", | ||
15036 | "hash": "sha384", | ||
15037 | "id": "" | ||
15038 | }, | ||
15039 | "DSA-WITH-SHA512": { | ||
15040 | "sign": "dsa", | ||
15041 | "hash": "sha512", | ||
15042 | "id": "" | ||
15043 | }, | ||
15044 | "DSA-SHA512": { | ||
15045 | "sign": "dsa", | ||
15046 | "hash": "sha512", | ||
15047 | "id": "" | ||
15048 | }, | ||
15049 | "DSA-RIPEMD160": { | ||
15050 | "sign": "dsa", | ||
15051 | "hash": "rmd160", | ||
15052 | "id": "" | ||
15053 | }, | ||
15054 | "ripemd160WithRSA": { | ||
15055 | "sign": "rsa", | ||
15056 | "hash": "rmd160", | ||
15057 | "id": "3021300906052b2403020105000414" | ||
15058 | }, | ||
15059 | "RSA-RIPEMD160": { | ||
15060 | "sign": "rsa", | ||
15061 | "hash": "rmd160", | ||
15062 | "id": "3021300906052b2403020105000414" | ||
15063 | }, | ||
15064 | "md5WithRSAEncryption": { | ||
15065 | "sign": "rsa", | ||
15066 | "hash": "md5", | ||
15067 | "id": "3020300c06082a864886f70d020505000410" | ||
15068 | }, | ||
15069 | "RSA-MD5": { | ||
15070 | "sign": "rsa", | ||
15071 | "hash": "md5", | ||
15072 | "id": "3020300c06082a864886f70d020505000410" | ||
15073 | } | ||
15074 | } | ||
15075 | |||
15076 | },{}],101:[function(require,module,exports){ | ||
15077 | 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" | ||
15084 | } | ||
15085 | |||
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') | ||
15093 | |||
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] | ||
15098 | }) | ||
15099 | |||
15100 | function Sign (algorithm) { | ||
15101 | stream.Writable.call(this) | ||
15102 | |||
15103 | var data = algorithms[algorithm] | ||
15104 | if (!data) throw new Error('Unknown message digest') | ||
15105 | |||
15106 | this._hashType = data.hash | ||
15107 | this._hash = createHash(data.hash) | ||
15108 | this._tag = data.id | ||
15109 | this._signType = data.sign | ||
15110 | } | ||
15111 | inherits(Sign, stream.Writable) | ||
15112 | |||
15113 | Sign.prototype._write = function _write (data, _, done) { | ||
15114 | this._hash.update(data) | ||
15115 | done() | ||
15116 | } | ||
15117 | |||
15118 | Sign.prototype.update = function update (data, enc) { | ||
15119 | if (typeof data === 'string') data = new Buffer(data, enc) | ||
15120 | |||
15121 | this._hash.update(data) | ||
15122 | return this | ||
15123 | } | ||
15124 | |||
15125 | Sign.prototype.sign = function signMethod (key, enc) { | ||
15126 | this.end() | ||
15127 | var hash = this._hash.digest() | ||
15128 | var sig = sign(hash, key, this._hashType, this._signType, this._tag) | ||
15129 | |||
15130 | return enc ? sig.toString(enc) : sig | ||
15131 | } | ||
15132 | |||
15133 | function Verify (algorithm) { | ||
15134 | stream.Writable.call(this) | ||
15135 | |||
15136 | var data = algorithms[algorithm] | ||
15137 | if (!data) throw new Error('Unknown message digest') | ||
15138 | |||
15139 | this._hash = createHash(data.hash) | ||
15140 | this._tag = data.id | ||
15141 | this._signType = data.sign | ||
15142 | } | ||
15143 | inherits(Verify, stream.Writable) | ||
15144 | |||
15145 | Verify.prototype._write = function _write (data, _, done) { | ||
15146 | this._hash.update(data) | ||
15147 | done() | ||
15148 | } | ||
15149 | |||
15150 | Verify.prototype.update = function update (data, enc) { | ||
15151 | if (typeof data === 'string') data = new Buffer(data, enc) | ||
15152 | |||
15153 | this._hash.update(data) | ||
15154 | return this | ||
15155 | } | ||
15156 | |||
15157 | Verify.prototype.verify = function verifyMethod (key, sig, enc) { | ||
15158 | if (typeof sig === 'string') sig = new Buffer(sig, enc) | ||
15159 | |||
15160 | this.end() | ||
15161 | var hash = this._hash.digest() | ||
15162 | return verify(sig, hash, key, this._signType, this._tag) | ||
15163 | } | ||
15164 | |||
15165 | function createSign (algorithm) { | ||
15166 | return new Sign(algorithm) | ||
15167 | } | ||
15168 | |||
15169 | function createVerify (algorithm) { | ||
15170 | return new Verify(algorithm) | ||
15171 | } | ||
15172 | |||
15173 | module.exports = { | ||
15174 | Sign: createSign, | ||
15175 | Verify: createVerify, | ||
15176 | createSign: createSign, | ||
15177 | createVerify: createVerify | ||
15178 | } | ||
15179 | |||
15180 | }).call(this,require("buffer").Buffer) | ||
15181 | },{"./algorithms.json":100,"./sign":103,"./verify":104,"buffer":107,"create-hash":111,"inherits":163,"stream":263}],103:[function(require,module,exports){ | ||
15182 | (function (Buffer){ | ||
15183 | // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js | ||
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') | ||
15190 | |||
15191 | function sign (hash, key, hashType, signType, tag) { | ||
15192 | var priv = parseKeys(key) | ||
15193 | if (priv.curve) { | ||
15194 | // rsa keys can be interpreted as ecdsa ones in openssl | ||
15195 | if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') | ||
15196 | return ecSign(hash, priv) | ||
15197 | } else if (priv.type === 'dsa') { | ||
15198 | if (signType !== 'dsa') throw new Error('wrong private key type') | ||
15199 | return dsaSign(hash, priv, hashType) | ||
15200 | } else { | ||
15201 | if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') | ||
15202 | } | ||
15203 | hash = Buffer.concat([tag, hash]) | ||
15204 | var len = priv.modulus.byteLength() | ||
15205 | var pad = [ 0, 1 ] | ||
15206 | while (hash.length + pad.length + 1 < len) pad.push(0xff) | ||
15207 | pad.push(0x00) | ||
15208 | var i = -1 | ||
15209 | while (++i < hash.length) pad.push(hash[i]) | ||
15210 | |||
15211 | var out = crt(pad, priv) | ||
15212 | return out | ||
15213 | } | ||
15214 | |||
15215 | function ecSign (hash, priv) { | ||
15216 | var curveId = curves[priv.curve.join('.')] | ||
15217 | if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.')) | ||
15218 | |||
15219 | var curve = new EC(curveId) | ||
15220 | var key = curve.keyFromPrivate(priv.privateKey) | ||
15221 | var out = key.sign(hash) | ||
15222 | |||
15223 | return new Buffer(out.toDER()) | ||
15224 | } | ||
15225 | |||
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 | ||
15231 | var r = new BN(0) | ||
15232 | var k | ||
15233 | var H = bits2int(hash, q).mod(q) | ||
15234 | var s = false | ||
15235 | var kv = getKey(x, q, hash, algo) | ||
15236 | while (s === false) { | ||
15237 | k = makeKey(q, kv, algo) | ||
15238 | r = makeR(g, k, p, q) | ||
15239 | s = k.invm(q).imul(H.add(x.mul(r))).mod(q) | ||
15240 | if (s.cmpn(0) === 0) { | ||
15241 | s = false | ||
15242 | r = new BN(0) | ||
15243 | } | ||
15244 | } | ||
15245 | return toDER(r, s) | ||
15246 | } | ||
15247 | |||
15248 | function toDER (r, s) { | ||
15249 | r = r.toArray() | ||
15250 | s = s.toArray() | ||
15251 | |||
15252 | // Pad values | ||
15253 | if (r[0] & 0x80) r = [ 0 ].concat(r) | ||
15254 | if (s[0] & 0x80) s = [ 0 ].concat(s) | ||
15255 | |||
15256 | var total = r.length + s.length + 4 | ||
15257 | var res = [ 0x30, total, 0x02, r.length ] | ||
15258 | res = res.concat(r, [ 0x02, s.length ], s) | ||
15259 | return new Buffer(res) | ||
15260 | } | ||
15261 | |||
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) | ||
15266 | zeros.fill(0) | ||
15267 | x = Buffer.concat([ zeros, x ]) | ||
15268 | } | ||
15269 | var hlen = hash.length | ||
15270 | var hbits = bits2octets(hash, q) | ||
15271 | var v = new Buffer(hlen) | ||
15272 | v.fill(1) | ||
15273 | var k = new Buffer(hlen) | ||
15274 | k.fill(0) | ||
15275 | k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest() | ||
15276 | v = createHmac(algo, k).update(v).digest() | ||
15277 | k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest() | ||
15278 | v = createHmac(algo, k).update(v).digest() | ||
15279 | return { k: k, v: v } | ||
15280 | } | ||
15281 | |||
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) | ||
15286 | return bits | ||
15287 | } | ||
15288 | |||
15289 | function bits2octets (bits, q) { | ||
15290 | bits = bits2int(bits, q) | ||
15291 | bits = bits.mod(q) | ||
15292 | var out = new Buffer(bits.toArray()) | ||
15293 | if (out.length < q.byteLength()) { | ||
15294 | var zeros = new Buffer(q.byteLength() - out.length) | ||
15295 | zeros.fill(0) | ||
15296 | out = Buffer.concat([ zeros, out ]) | ||
15297 | } | ||
15298 | return out | ||
15299 | } | ||
15300 | |||
15301 | function makeKey (q, kv, algo) { | ||
15302 | var t | ||
15303 | var k | ||
15304 | |||
15305 | do { | ||
15306 | t = new Buffer(0) | ||
15307 | |||
15308 | while (t.length * 8 < q.bitLength()) { | ||
15309 | kv.v = createHmac(algo, kv.k).update(kv.v).digest() | ||
15310 | t = Buffer.concat([ t, kv.v ]) | ||
15311 | } | ||
15312 | |||
15313 | k = bits2int(t, q) | ||
15314 | kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest() | ||
15315 | kv.v = createHmac(algo, kv.k).update(kv.v).digest() | ||
15316 | } while (k.cmp(q) !== -1) | ||
15317 | |||
15318 | return k | ||
15319 | } | ||
15320 | |||
15321 | function makeR (g, k, p, q) { | ||
15322 | return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q) | ||
15323 | } | ||
15324 | |||
15325 | module.exports = sign | ||
15326 | module.exports.getKey = getKey | ||
15327 | module.exports.makeKey = makeKey | ||
15328 | |||
15329 | }).call(this,require("buffer").Buffer) | ||
15330 | },{"./curves.json":101,"bn.js":75,"browserify-rsa":98,"buffer":107,"create-hmac":114,"elliptic":127,"parse-asn1":182}],104:[function(require,module,exports){ | ||
15331 | (function (Buffer){ | ||
15332 | // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js | ||
15333 | var BN = require('bn.js') | ||
15334 | var EC = require('elliptic').ec | ||
15335 | var parseKeys = require('parse-asn1') | ||
15336 | var curves = require('./curves.json') | ||
15337 | |||
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) | ||
15347 | } else { | ||
15348 | if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') | ||
15349 | } | ||
15350 | hash = Buffer.concat([tag, hash]) | ||
15351 | var len = pub.modulus.byteLength() | ||
15352 | var pad = [ 1 ] | ||
15353 | var padNum = 0 | ||
15354 | while (hash.length + pad.length + 2 < len) { | ||
15355 | pad.push(0xff) | ||
15356 | padNum++ | ||
15357 | } | ||
15358 | pad.push(0x00) | ||
15359 | var i = -1 | ||
15360 | while (++i < hash.length) { | ||
15361 | pad.push(hash[i]) | ||
15362 | } | ||
15363 | pad = new Buffer(pad) | ||
15364 | var red = BN.mont(pub.modulus) | ||
15365 | sig = new BN(sig).toRed(red) | ||
15366 | |||
15367 | sig = sig.redPow(new BN(pub.publicExponent)) | ||
15368 | sig = new Buffer(sig.fromRed().toArray()) | ||
15369 | var out = padNum < 8 ? 1 : 0 | ||
15370 | len = Math.min(sig.length, pad.length) | ||
15371 | if (sig.length !== pad.length) out = 1 | ||
15372 | |||
15373 | i = -1 | ||
15374 | while (++i < len) out |= sig[i] ^ pad[i] | ||
15375 | return out === 0 | ||
15376 | } | ||
15377 | |||
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('.')) | ||
15381 | |||
15382 | var curve = new EC(curveId) | ||
15383 | var pubkey = pub.data.subjectPrivateKey.data | ||
15384 | |||
15385 | return curve.verify(hash, sig, pubkey) | ||
15386 | } | ||
15387 | |||
15388 | function dsaVerify (sig, hash, pub) { | ||
15389 | var p = pub.data.p | ||
15390 | var q = pub.data.q | ||
15391 | var g = pub.data.g | ||
15392 | var y = pub.data.pub_key | ||
15393 | var unpacked = parseKeys.signature.decode(sig, 'der') | ||
15394 | var s = unpacked.s | ||
15395 | var r = unpacked.r | ||
15396 | checkValue(s, q) | ||
15397 | checkValue(r, q) | ||
15398 | var montp = BN.mont(p) | ||
15399 | var w = s.invm(q) | ||
15400 | var v = g.toRed(montp) | ||
15401 | .redPow(new BN(hash).mul(w).mod(q)) | ||
15402 | .fromRed() | ||
15403 | .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) | ||
15404 | .mod(p) | ||
15405 | .mod(q) | ||
15406 | return v.cmp(r) === 0 | ||
15407 | } | ||
15408 | |||
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') | ||
15412 | } | ||
15413 | |||
15414 | module.exports = verify | ||
15415 | |||
15416 | }).call(this,require("buffer").Buffer) | ||
15417 | },{"./curves.json":101,"bn.js":75,"buffer":107,"elliptic":127,"parse-asn1":182}],105:[function(require,module,exports){ | ||
15418 | var basex = require('base-x') | ||
15419 | var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' | ||
15420 | |||
15421 | module.exports = basex(ALPHABET) | ||
15422 | |||
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) | ||
15428 | |||
15429 | for (var i = 0; i < length; ++i) { | ||
15430 | buffer[i] = a[i] ^ b[i] | ||
15431 | } | ||
15432 | |||
15433 | return buffer | ||
15434 | } | ||
15435 | |||
15436 | }).call(this,require("buffer").Buffer) | ||
15437 | },{"buffer":107}],107:[function(require,module,exports){ | ||
15438 | /*! | ||
15439 | * The buffer module from node.js, for the browser. | ||
15440 | * | ||
15441 | * @author Feross Aboukhadijeh <https://feross.org> | ||
15442 | * @license MIT | ||
15443 | */ | ||
15444 | /* eslint-disable no-proto */ | ||
15445 | |||
15446 | 'use strict' | ||
15447 | |||
15448 | var base64 = require('base64-js') | ||
15449 | var ieee754 = require('ieee754') | ||
15450 | |||
15451 | exports.Buffer = Buffer | ||
15452 | exports.SlowBuffer = SlowBuffer | ||
15453 | exports.INSPECT_MAX_BYTES = 50 | ||
15454 | |||
15455 | var K_MAX_LENGTH = 0x7fffffff | ||
15456 | exports.kMaxLength = K_MAX_LENGTH | ||
15457 | |||
15458 | /** | ||
15459 | * If `Buffer.TYPED_ARRAY_SUPPORT`: | ||
15460 | * === true Use Uint8Array implementation (fastest) | ||
15461 | * === false Print warning and recommend using `buffer` v4.x which has an Object | ||
15462 | * implementation (most compatible, even IE6) | ||
15463 | * | ||
15464 | * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, | ||
15465 | * Opera 11.6+, iOS 4.2+. | ||
15466 | * | ||
15467 | * We report that the browser does not support typed arrays if the are not subclassable | ||
15468 | * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` | ||
15469 | * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support | ||
15470 | * for __proto__ and has a buggy typed array implementation. | ||
15471 | */ | ||
15472 | Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport() | ||
15473 | |||
15474 | if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && | ||
15475 | typeof console.error === 'function') { | ||
15476 | console.error( | ||
15477 | 'This browser lacks typed array (Uint8Array) support which is required by ' + | ||
15478 | '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' | ||
15479 | ) | ||
15480 | } | ||
15481 | |||
15482 | function typedArraySupport () { | ||
15483 | // Can typed array instances can be augmented? | ||
15484 | try { | ||
15485 | var arr = new Uint8Array(1) | ||
15486 | arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} | ||
15487 | return arr.foo() === 42 | ||
15488 | } catch (e) { | ||
15489 | return false | ||
15490 | } | ||
15491 | } | ||
15492 | |||
15493 | function createBuffer (length) { | ||
15494 | if (length > K_MAX_LENGTH) { | ||
15495 | throw new RangeError('Invalid typed array length') | ||
15496 | } | ||
15497 | // Return an augmented `Uint8Array` instance | ||
15498 | var buf = new Uint8Array(length) | ||
15499 | buf.__proto__ = Buffer.prototype | ||
15500 | return buf | ||
15501 | } | ||
15502 | |||
15503 | /** | ||
15504 | * The Buffer constructor returns instances of `Uint8Array` that have their | ||
15505 | * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of | ||
15506 | * `Uint8Array`, so the returned instances will have all the node `Buffer` methods | ||
15507 | * and the `Uint8Array` methods. Square bracket notation works as expected -- it | ||
15508 | * returns a single octet. | ||
15509 | * | ||
15510 | * The `Uint8Array` prototype remains unmodified. | ||
15511 | */ | ||
15512 | |||
15513 | function Buffer (arg, encodingOrOffset, length) { | ||
15514 | // Common case. | ||
15515 | if (typeof arg === 'number') { | ||
15516 | if (typeof encodingOrOffset === 'string') { | ||
15517 | throw new Error( | ||
15518 | 'If encoding is specified then the first argument must be a string' | ||
15519 | ) | ||
15520 | } | ||
15521 | return allocUnsafe(arg) | ||
15522 | } | ||
15523 | return from(arg, encodingOrOffset, length) | ||
15524 | } | ||
15525 | |||
15526 | // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 | ||
15527 | if (typeof Symbol !== 'undefined' && Symbol.species && | ||
15528 | Buffer[Symbol.species] === Buffer) { | ||
15529 | Object.defineProperty(Buffer, Symbol.species, { | ||
15530 | value: null, | ||
15531 | configurable: true, | ||
15532 | enumerable: false, | ||
15533 | writable: false | ||
15534 | }) | ||
15535 | } | ||
15536 | |||
15537 | Buffer.poolSize = 8192 // not used by this implementation | ||
15538 | |||
15539 | function from (value, encodingOrOffset, length) { | ||
15540 | if (typeof value === 'number') { | ||
15541 | throw new TypeError('"value" argument must not be a number') | ||
15542 | } | ||
15543 | |||
15544 | if (isArrayBuffer(value)) { | ||
15545 | return fromArrayBuffer(value, encodingOrOffset, length) | ||
15546 | } | ||
15547 | |||
15548 | if (typeof value === 'string') { | ||
15549 | return fromString(value, encodingOrOffset) | ||
15550 | } | ||
15551 | |||
15552 | return fromObject(value) | ||
15553 | } | ||
15554 | |||
15555 | /** | ||
15556 | * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError | ||
15557 | * if value is a number. | ||
15558 | * Buffer.from(str[, encoding]) | ||
15559 | * Buffer.from(array) | ||
15560 | * Buffer.from(buffer) | ||
15561 | * Buffer.from(arrayBuffer[, byteOffset[, length]]) | ||
15562 | **/ | ||
15563 | Buffer.from = function (value, encodingOrOffset, length) { | ||
15564 | return from(value, encodingOrOffset, length) | ||
15565 | } | ||
15566 | |||
15567 | // Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: | ||
15568 | // https://github.com/feross/buffer/pull/148 | ||
15569 | Buffer.prototype.__proto__ = Uint8Array.prototype | ||
15570 | Buffer.__proto__ = Uint8Array | ||
15571 | |||
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') | ||
15577 | } | ||
15578 | } | ||
15579 | |||
15580 | function alloc (size, fill, encoding) { | ||
15581 | assertSize(size) | ||
15582 | if (size <= 0) { | ||
15583 | return createBuffer(size) | ||
15584 | } | ||
15585 | if (fill !== undefined) { | ||
15586 | // Only pay attention to encoding if it's a string. This | ||
15587 | // prevents accidentally sending in a number that would | ||
15588 | // be interpretted as a start offset. | ||
15589 | return typeof encoding === 'string' | ||
15590 | ? createBuffer(size).fill(fill, encoding) | ||
15591 | : createBuffer(size).fill(fill) | ||
15592 | } | ||
15593 | return createBuffer(size) | ||
15594 | } | ||
15595 | |||
15596 | /** | ||
15597 | * Creates a new filled Buffer instance. | ||
15598 | * alloc(size[, fill[, encoding]]) | ||
15599 | **/ | ||
15600 | Buffer.alloc = function (size, fill, encoding) { | ||
15601 | return alloc(size, fill, encoding) | ||
15602 | } | ||
15603 | |||
15604 | function allocUnsafe (size) { | ||
15605 | assertSize(size) | ||
15606 | return createBuffer(size < 0 ? 0 : checked(size) | 0) | ||
15607 | } | ||
15608 | |||
15609 | /** | ||
15610 | * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. | ||
15611 | * */ | ||
15612 | Buffer.allocUnsafe = function (size) { | ||
15613 | return allocUnsafe(size) | ||
15614 | } | ||
15615 | /** | ||
15616 | * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. | ||
15617 | */ | ||
15618 | Buffer.allocUnsafeSlow = function (size) { | ||
15619 | return allocUnsafe(size) | ||
15620 | } | ||
15621 | |||
15622 | function fromString (string, encoding) { | ||
15623 | if (typeof encoding !== 'string' || encoding === '') { | ||
15624 | encoding = 'utf8' | ||
15625 | } | ||
15626 | |||
15627 | if (!Buffer.isEncoding(encoding)) { | ||
15628 | throw new TypeError('"encoding" must be a valid string encoding') | ||
15629 | } | ||
15630 | |||
15631 | var length = byteLength(string, encoding) | 0 | ||
15632 | var buf = createBuffer(length) | ||
15633 | |||
15634 | var actual = buf.write(string, encoding) | ||
15635 | |||
15636 | if (actual !== length) { | ||
15637 | // Writing a hex string, for example, that contains invalid characters will | ||
15638 | // cause everything after the first invalid character to be ignored. (e.g. | ||
15639 | // 'abxxcd' will be treated as 'ab') | ||
15640 | buf = buf.slice(0, actual) | ||
15641 | } | ||
15642 | |||
15643 | return buf | ||
15644 | } | ||
15645 | |||
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 | ||
15651 | } | ||
15652 | return buf | ||
15653 | } | ||
15654 | |||
15655 | function fromArrayBuffer (array, byteOffset, length) { | ||
15656 | if (byteOffset < 0 || array.byteLength < byteOffset) { | ||
15657 | throw new RangeError('\'offset\' is out of bounds') | ||
15658 | } | ||
15659 | |||
15660 | if (array.byteLength < byteOffset + (length || 0)) { | ||
15661 | throw new RangeError('\'length\' is out of bounds') | ||
15662 | } | ||
15663 | |||
15664 | var buf | ||
15665 | if (byteOffset === undefined && length === undefined) { | ||
15666 | buf = new Uint8Array(array) | ||
15667 | } else if (length === undefined) { | ||
15668 | buf = new Uint8Array(array, byteOffset) | ||
15669 | } else { | ||
15670 | buf = new Uint8Array(array, byteOffset, length) | ||
15671 | } | ||
15672 | |||
15673 | // Return an augmented `Uint8Array` instance | ||
15674 | buf.__proto__ = Buffer.prototype | ||
15675 | return buf | ||
15676 | } | ||
15677 | |||
15678 | function fromObject (obj) { | ||
15679 | if (Buffer.isBuffer(obj)) { | ||
15680 | var len = checked(obj.length) | 0 | ||
15681 | var buf = createBuffer(len) | ||
15682 | |||
15683 | if (buf.length === 0) { | ||
15684 | return buf | ||
15685 | } | ||
15686 | |||
15687 | obj.copy(buf, 0, 0, len) | ||
15688 | return buf | ||
15689 | } | ||
15690 | |||
15691 | if (obj) { | ||
15692 | if (isArrayBufferView(obj) || 'length' in obj) { | ||
15693 | if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { | ||
15694 | return createBuffer(0) | ||
15695 | } | ||
15696 | return fromArrayLike(obj) | ||
15697 | } | ||
15698 | |||
15699 | if (obj.type === 'Buffer' && Array.isArray(obj.data)) { | ||
15700 | return fromArrayLike(obj.data) | ||
15701 | } | ||
15702 | } | ||
15703 | |||
15704 | throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') | ||
15705 | } | ||
15706 | |||
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') | ||
15713 | } | ||
15714 | return length | 0 | ||
15715 | } | ||
15716 | |||
15717 | function SlowBuffer (length) { | ||
15718 | if (+length != length) { // eslint-disable-line eqeqeq | ||
15719 | length = 0 | ||
15720 | } | ||
15721 | return Buffer.alloc(+length) | ||
15722 | } | ||
15723 | |||
15724 | Buffer.isBuffer = function isBuffer (b) { | ||
15725 | return b != null && b._isBuffer === true | ||
15726 | } | ||
15727 | |||
15728 | Buffer.compare = function compare (a, b) { | ||
15729 | if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { | ||
15730 | throw new TypeError('Arguments must be Buffers') | ||
15731 | } | ||
15732 | |||
15733 | if (a === b) return 0 | ||
15734 | |||
15735 | var x = a.length | ||
15736 | var y = b.length | ||
15737 | |||
15738 | for (var i = 0, len = Math.min(x, y); i < len; ++i) { | ||
15739 | if (a[i] !== b[i]) { | ||
15740 | x = a[i] | ||
15741 | y = b[i] | ||
15742 | break | ||
15743 | } | ||
15744 | } | ||
15745 | |||
15746 | if (x < y) return -1 | ||
15747 | if (y < x) return 1 | ||
15748 | return 0 | ||
15749 | } | ||
15750 | |||
15751 | Buffer.isEncoding = function isEncoding (encoding) { | ||
15752 | switch (String(encoding).toLowerCase()) { | ||
15753 | case 'hex': | ||
15754 | case 'utf8': | ||
15755 | case 'utf-8': | ||
15756 | case 'ascii': | ||
15757 | case 'latin1': | ||
15758 | case 'binary': | ||
15759 | case 'base64': | ||
15760 | case 'ucs2': | ||
15761 | case 'ucs-2': | ||
15762 | case 'utf16le': | ||
15763 | case 'utf-16le': | ||
15764 | return true | ||
15765 | default: | ||
15766 | return false | ||
15767 | } | ||
15768 | } | ||
15769 | |||
15770 | Buffer.concat = function concat (list, length) { | ||
15771 | if (!Array.isArray(list)) { | ||
15772 | throw new TypeError('"list" argument must be an Array of Buffers') | ||
15773 | } | ||
15774 | |||
15775 | if (list.length === 0) { | ||
15776 | return Buffer.alloc(0) | ||
15777 | } | ||
15778 | |||
15779 | var i | ||
15780 | if (length === undefined) { | ||
15781 | length = 0 | ||
15782 | for (i = 0; i < list.length; ++i) { | ||
15783 | length += list[i].length | ||
15784 | } | ||
15785 | } | ||
15786 | |||
15787 | var buffer = Buffer.allocUnsafe(length) | ||
15788 | var pos = 0 | ||
15789 | for (i = 0; i < list.length; ++i) { | ||
15790 | var buf = list[i] | ||
15791 | if (!Buffer.isBuffer(buf)) { | ||
15792 | throw new TypeError('"list" argument must be an Array of Buffers') | ||
15793 | } | ||
15794 | buf.copy(buffer, pos) | ||
15795 | pos += buf.length | ||
15796 | } | ||
15797 | return buffer | ||
15798 | } | ||
15799 | |||
15800 | function byteLength (string, encoding) { | ||
15801 | if (Buffer.isBuffer(string)) { | ||
15802 | return string.length | ||
15803 | } | ||
15804 | if (isArrayBufferView(string) || isArrayBuffer(string)) { | ||
15805 | return string.byteLength | ||
15806 | } | ||
15807 | if (typeof string !== 'string') { | ||
15808 | string = '' + string | ||
15809 | } | ||
15810 | |||
15811 | var len = string.length | ||
15812 | if (len === 0) return 0 | ||
15813 | |||
15814 | // Use a for loop to avoid recursion | ||
15815 | var loweredCase = false | ||
15816 | for (;;) { | ||
15817 | switch (encoding) { | ||
15818 | case 'ascii': | ||
15819 | case 'latin1': | ||
15820 | case 'binary': | ||
15821 | return len | ||
15822 | case 'utf8': | ||
15823 | case 'utf-8': | ||
15824 | case undefined: | ||
15825 | return utf8ToBytes(string).length | ||
15826 | case 'ucs2': | ||
15827 | case 'ucs-2': | ||
15828 | case 'utf16le': | ||
15829 | case 'utf-16le': | ||
15830 | return len * 2 | ||
15831 | case 'hex': | ||
15832 | return len >>> 1 | ||
15833 | case 'base64': | ||
15834 | return base64ToBytes(string).length | ||
15835 | default: | ||
15836 | if (loweredCase) return utf8ToBytes(string).length // assume utf8 | ||
15837 | encoding = ('' + encoding).toLowerCase() | ||
15838 | loweredCase = true | ||
15839 | } | ||
15840 | } | ||
15841 | } | ||
15842 | Buffer.byteLength = byteLength | ||
15843 | |||
15844 | function slowToString (encoding, start, end) { | ||
15845 | var loweredCase = false | ||
15846 | |||
15847 | // No need to verify that "this.length <= MAX_UINT32" since it's a read-only | ||
15848 | // property of a typed array. | ||
15849 | |||
15850 | // This behaves neither like String nor Uint8Array in that we set start/end | ||
15851 | // to their upper/lower bounds if the value passed is out of range. | ||
15852 | // undefined is handled specially as per ECMA-262 6th Edition, | ||
15853 | // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. | ||
15854 | if (start === undefined || start < 0) { | ||
15855 | start = 0 | ||
15856 | } | ||
15857 | // Return early if start > this.length. Done here to prevent potential uint32 | ||
15858 | // coercion fail below. | ||
15859 | if (start > this.length) { | ||
15860 | return '' | ||
15861 | } | ||
15862 | |||
15863 | if (end === undefined || end > this.length) { | ||
15864 | end = this.length | ||
15865 | } | ||
15866 | |||
15867 | if (end <= 0) { | ||
15868 | return '' | ||
15869 | } | ||
15870 | |||
15871 | // Force coersion to uint32. This will also coerce falsey/NaN values to 0. | ||
15872 | end >>>= 0 | ||
15873 | start >>>= 0 | ||
15874 | |||
15875 | if (end <= start) { | ||
15876 | return '' | ||
15877 | } | ||
15878 | |||
15879 | if (!encoding) encoding = 'utf8' | ||
15880 | |||
15881 | while (true) { | ||
15882 | switch (encoding) { | ||
15883 | case 'hex': | ||
15884 | return hexSlice(this, start, end) | ||
15885 | |||
15886 | case 'utf8': | ||
15887 | case 'utf-8': | ||
15888 | return utf8Slice(this, start, end) | ||
15889 | |||
15890 | case 'ascii': | ||
15891 | return asciiSlice(this, start, end) | ||
15892 | |||
15893 | case 'latin1': | ||
15894 | case 'binary': | ||
15895 | return latin1Slice(this, start, end) | ||
15896 | |||
15897 | case 'base64': | ||
15898 | return base64Slice(this, start, end) | ||
15899 | |||
15900 | case 'ucs2': | ||
15901 | case 'ucs-2': | ||
15902 | case 'utf16le': | ||
15903 | case 'utf-16le': | ||
15904 | return utf16leSlice(this, start, end) | ||
15905 | |||
15906 | default: | ||
15907 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) | ||
15908 | encoding = (encoding + '').toLowerCase() | ||
15909 | loweredCase = true | ||
15910 | } | ||
15911 | } | ||
15912 | } | ||
15913 | |||
15914 | // This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) | ||
15915 | // to detect a Buffer instance. It's not possible to use `instanceof Buffer` | ||
15916 | // reliably in a browserify context because there could be multiple different | ||
15917 | // copies of the 'buffer' package in use. This method works even for Buffer | ||
15918 | // instances that were created from another copy of the `buffer` package. | ||
15919 | // See: https://github.com/feross/buffer/issues/154 | ||
15920 | Buffer.prototype._isBuffer = true | ||
15921 | |||
15922 | function swap (b, n, m) { | ||
15923 | var i = b[n] | ||
15924 | b[n] = b[m] | ||
15925 | b[m] = i | ||
15926 | } | ||
15927 | |||
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') | ||
15932 | } | ||
15933 | for (var i = 0; i < len; i += 2) { | ||
15934 | swap(this, i, i + 1) | ||
15935 | } | ||
15936 | return this | ||
15937 | } | ||
15938 | |||
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') | ||
15943 | } | ||
15944 | for (var i = 0; i < len; i += 4) { | ||
15945 | swap(this, i, i + 3) | ||
15946 | swap(this, i + 1, i + 2) | ||
15947 | } | ||
15948 | return this | ||
15949 | } | ||
15950 | |||
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') | ||
15955 | } | ||
15956 | for (var i = 0; i < len; i += 8) { | ||
15957 | swap(this, i, i + 7) | ||
15958 | swap(this, i + 1, i + 6) | ||
15959 | swap(this, i + 2, i + 5) | ||
15960 | swap(this, i + 3, i + 4) | ||
15961 | } | ||
15962 | return this | ||
15963 | } | ||
15964 | |||
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) | ||
15970 | } | ||
15971 | |||
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 | ||
15976 | } | ||
15977 | |||
15978 | Buffer.prototype.inspect = function inspect () { | ||
15979 | var str = '' | ||
15980 | var max = exports.INSPECT_MAX_BYTES | ||
15981 | if (this.length > 0) { | ||
15982 | str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') | ||
15983 | if (this.length > max) str += ' ... ' | ||
15984 | } | ||
15985 | return '<Buffer ' + str + '>' | ||
15986 | } | ||
15987 | |||
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') | ||
15991 | } | ||
15992 | |||
15993 | if (start === undefined) { | ||
15994 | start = 0 | ||
15995 | } | ||
15996 | if (end === undefined) { | ||
15997 | end = target ? target.length : 0 | ||
15998 | } | ||
15999 | if (thisStart === undefined) { | ||
16000 | thisStart = 0 | ||
16001 | } | ||
16002 | if (thisEnd === undefined) { | ||
16003 | thisEnd = this.length | ||
16004 | } | ||
16005 | |||
16006 | if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { | ||
16007 | throw new RangeError('out of range index') | ||
16008 | } | ||
16009 | |||
16010 | if (thisStart >= thisEnd && start >= end) { | ||
16011 | return 0 | ||
16012 | } | ||
16013 | if (thisStart >= thisEnd) { | ||
16014 | return -1 | ||
16015 | } | ||
16016 | if (start >= end) { | ||
16017 | return 1 | ||
16018 | } | ||
16019 | |||
16020 | start >>>= 0 | ||
16021 | end >>>= 0 | ||
16022 | thisStart >>>= 0 | ||
16023 | thisEnd >>>= 0 | ||
16024 | |||
16025 | if (this === target) return 0 | ||
16026 | |||
16027 | var x = thisEnd - thisStart | ||
16028 | var y = end - start | ||
16029 | var len = Math.min(x, y) | ||
16030 | |||
16031 | var thisCopy = this.slice(thisStart, thisEnd) | ||
16032 | var targetCopy = target.slice(start, end) | ||
16033 | |||
16034 | for (var i = 0; i < len; ++i) { | ||
16035 | if (thisCopy[i] !== targetCopy[i]) { | ||
16036 | x = thisCopy[i] | ||
16037 | y = targetCopy[i] | ||
16038 | break | ||
16039 | } | ||
16040 | } | ||
16041 | |||
16042 | if (x < y) return -1 | ||
16043 | if (y < x) return 1 | ||
16044 | return 0 | ||
16045 | } | ||
16046 | |||
16047 | // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, | ||
16048 | // OR the last index of `val` in `buffer` at offset <= `byteOffset`. | ||
16049 | // | ||
16050 | // Arguments: | ||
16051 | // - buffer - a Buffer to search | ||
16052 | // - val - a string, Buffer, or number | ||
16053 | // - byteOffset - an index into `buffer`; will be clamped to an int32 | ||
16054 | // - encoding - an optional encoding, relevant is val is a string | ||
16055 | // - dir - true for indexOf, false for lastIndexOf | ||
16056 | function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { | ||
16057 | // Empty buffer means no match | ||
16058 | if (buffer.length === 0) return -1 | ||
16059 | |||
16060 | // Normalize byteOffset | ||
16061 | if (typeof byteOffset === 'string') { | ||
16062 | encoding = byteOffset | ||
16063 | byteOffset = 0 | ||
16064 | } else if (byteOffset > 0x7fffffff) { | ||
16065 | byteOffset = 0x7fffffff | ||
16066 | } else if (byteOffset < -0x80000000) { | ||
16067 | byteOffset = -0x80000000 | ||
16068 | } | ||
16069 | byteOffset = +byteOffset // Coerce to Number. | ||
16070 | if (numberIsNaN(byteOffset)) { | ||
16071 | // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer | ||
16072 | byteOffset = dir ? 0 : (buffer.length - 1) | ||
16073 | } | ||
16074 | |||
16075 | // Normalize byteOffset: negative offsets start from the end of the buffer | ||
16076 | if (byteOffset < 0) byteOffset = buffer.length + byteOffset | ||
16077 | if (byteOffset >= buffer.length) { | ||
16078 | if (dir) return -1 | ||
16079 | else byteOffset = buffer.length - 1 | ||
16080 | } else if (byteOffset < 0) { | ||
16081 | if (dir) byteOffset = 0 | ||
16082 | else return -1 | ||
16083 | } | ||
16084 | |||
16085 | // Normalize val | ||
16086 | if (typeof val === 'string') { | ||
16087 | val = Buffer.from(val, encoding) | ||
16088 | } | ||
16089 | |||
16090 | // Finally, search either indexOf (if dir is true) or lastIndexOf | ||
16091 | if (Buffer.isBuffer(val)) { | ||
16092 | // Special case: looking for empty string/buffer always fails | ||
16093 | if (val.length === 0) { | ||
16094 | return -1 | ||
16095 | } | ||
16096 | return arrayIndexOf(buffer, val, byteOffset, encoding, dir) | ||
16097 | } else if (typeof val === 'number') { | ||
16098 | val = val & 0xFF // Search for a byte value [0-255] | ||
16099 | if (typeof Uint8Array.prototype.indexOf === 'function') { | ||
16100 | if (dir) { | ||
16101 | return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) | ||
16102 | } else { | ||
16103 | return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) | ||
16104 | } | ||
16105 | } | ||
16106 | return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) | ||
16107 | } | ||
16108 | |||
16109 | throw new TypeError('val must be string, number or Buffer') | ||
16110 | } | ||
16111 | |||
16112 | function arrayIndexOf (arr, val, byteOffset, encoding, dir) { | ||
16113 | var indexSize = 1 | ||
16114 | var arrLength = arr.length | ||
16115 | var valLength = val.length | ||
16116 | |||
16117 | if (encoding !== undefined) { | ||
16118 | encoding = String(encoding).toLowerCase() | ||
16119 | if (encoding === 'ucs2' || encoding === 'ucs-2' || | ||
16120 | encoding === 'utf16le' || encoding === 'utf-16le') { | ||
16121 | if (arr.length < 2 || val.length < 2) { | ||
16122 | return -1 | ||
16123 | } | ||
16124 | indexSize = 2 | ||
16125 | arrLength /= 2 | ||
16126 | valLength /= 2 | ||
16127 | byteOffset /= 2 | ||
16128 | } | ||
16129 | } | ||
16130 | |||
16131 | function read (buf, i) { | ||
16132 | if (indexSize === 1) { | ||
16133 | return buf[i] | ||
16134 | } else { | ||
16135 | return buf.readUInt16BE(i * indexSize) | ||
16136 | } | ||
16137 | } | ||
16138 | |||
16139 | var i | ||
16140 | if (dir) { | ||
16141 | var foundIndex = -1 | ||
16142 | for (i = byteOffset; i < arrLength; i++) { | ||
16143 | if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { | ||
16144 | if (foundIndex === -1) foundIndex = i | ||
16145 | if (i - foundIndex + 1 === valLength) return foundIndex * indexSize | ||
16146 | } else { | ||
16147 | if (foundIndex !== -1) i -= i - foundIndex | ||
16148 | foundIndex = -1 | ||
16149 | } | ||
16150 | } | ||
16151 | } else { | ||
16152 | if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength | ||
16153 | for (i = byteOffset; i >= 0; i--) { | ||
16154 | var found = true | ||
16155 | for (var j = 0; j < valLength; j++) { | ||
16156 | if (read(arr, i + j) !== read(val, j)) { | ||
16157 | found = false | ||
16158 | break | ||
16159 | } | ||
16160 | } | ||
16161 | if (found) return i | ||
16162 | } | ||
16163 | } | ||
16164 | |||
16165 | return -1 | ||
16166 | } | ||
16167 | |||
16168 | Buffer.prototype.includes = function includes (val, byteOffset, encoding) { | ||
16169 | return this.indexOf(val, byteOffset, encoding) !== -1 | ||
16170 | } | ||
16171 | |||
16172 | Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { | ||
16173 | return bidirectionalIndexOf(this, val, byteOffset, encoding, true) | ||
16174 | } | ||
16175 | |||
16176 | Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { | ||
16177 | return bidirectionalIndexOf(this, val, byteOffset, encoding, false) | ||
16178 | } | ||
16179 | |||
16180 | function hexWrite (buf, string, offset, length) { | ||
16181 | offset = Number(offset) || 0 | ||
16182 | var remaining = buf.length - offset | ||
16183 | if (!length) { | ||
16184 | length = remaining | ||
16185 | } else { | ||
16186 | length = Number(length) | ||
16187 | if (length > remaining) { | ||
16188 | length = remaining | ||
16189 | } | ||
16190 | } | ||
16191 | |||
16192 | // must be an even number of digits | ||
16193 | var strLen = string.length | ||
16194 | if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') | ||
16195 | |||
16196 | if (length > strLen / 2) { | ||
16197 | length = strLen / 2 | ||
16198 | } | ||
16199 | for (var i = 0; i < length; ++i) { | ||
16200 | var parsed = parseInt(string.substr(i * 2, 2), 16) | ||
16201 | if (numberIsNaN(parsed)) return i | ||
16202 | buf[offset + i] = parsed | ||
16203 | } | ||
16204 | return i | ||
16205 | } | ||
16206 | |||
16207 | function utf8Write (buf, string, offset, length) { | ||
16208 | return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) | ||
16209 | } | ||
16210 | |||
16211 | function asciiWrite (buf, string, offset, length) { | ||
16212 | return blitBuffer(asciiToBytes(string), buf, offset, length) | ||
16213 | } | ||
16214 | |||
16215 | function latin1Write (buf, string, offset, length) { | ||
16216 | return asciiWrite(buf, string, offset, length) | ||
16217 | } | ||
16218 | |||
16219 | function base64Write (buf, string, offset, length) { | ||
16220 | return blitBuffer(base64ToBytes(string), buf, offset, length) | ||
16221 | } | ||
16222 | |||
16223 | function ucs2Write (buf, string, offset, length) { | ||
16224 | return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) | ||
16225 | } | ||
16226 | |||
16227 | Buffer.prototype.write = function write (string, offset, length, encoding) { | ||
16228 | // Buffer#write(string) | ||
16229 | if (offset === undefined) { | ||
16230 | encoding = 'utf8' | ||
16231 | length = this.length | ||
16232 | offset = 0 | ||
16233 | // Buffer#write(string, encoding) | ||
16234 | } else if (length === undefined && typeof offset === 'string') { | ||
16235 | encoding = offset | ||
16236 | length = this.length | ||
16237 | offset = 0 | ||
16238 | // Buffer#write(string, offset[, length][, encoding]) | ||
16239 | } else if (isFinite(offset)) { | ||
16240 | offset = offset >>> 0 | ||
16241 | if (isFinite(length)) { | ||
16242 | length = length >>> 0 | ||
16243 | if (encoding === undefined) encoding = 'utf8' | ||
16244 | } else { | ||
16245 | encoding = length | ||
16246 | length = undefined | ||
16247 | } | ||
16248 | } else { | ||
16249 | throw new Error( | ||
16250 | 'Buffer.write(string, encoding, offset[, length]) is no longer supported' | ||
16251 | ) | ||
16252 | } | ||
16253 | |||
16254 | var remaining = this.length - offset | ||
16255 | if (length === undefined || length > remaining) length = remaining | ||
16256 | |||
16257 | if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { | ||
16258 | throw new RangeError('Attempt to write outside buffer bounds') | ||
16259 | } | ||
16260 | |||
16261 | if (!encoding) encoding = 'utf8' | ||
16262 | |||
16263 | var loweredCase = false | ||
16264 | for (;;) { | ||
16265 | switch (encoding) { | ||
16266 | case 'hex': | ||
16267 | return hexWrite(this, string, offset, length) | ||
16268 | |||
16269 | case 'utf8': | ||
16270 | case 'utf-8': | ||
16271 | return utf8Write(this, string, offset, length) | ||
16272 | |||
16273 | case 'ascii': | ||
16274 | return asciiWrite(this, string, offset, length) | ||
16275 | |||
16276 | case 'latin1': | ||
16277 | case 'binary': | ||
16278 | return latin1Write(this, string, offset, length) | ||
16279 | |||
16280 | case 'base64': | ||
16281 | // Warning: maxLength not taken into account in base64Write | ||
16282 | return base64Write(this, string, offset, length) | ||
16283 | |||
16284 | case 'ucs2': | ||
16285 | case 'ucs-2': | ||
16286 | case 'utf16le': | ||
16287 | case 'utf-16le': | ||
16288 | return ucs2Write(this, string, offset, length) | ||
16289 | |||
16290 | default: | ||
16291 | if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) | ||
16292 | encoding = ('' + encoding).toLowerCase() | ||
16293 | loweredCase = true | ||
16294 | } | ||
16295 | } | ||
16296 | } | ||
16297 | |||
16298 | Buffer.prototype.toJSON = function toJSON () { | ||
16299 | return { | ||
16300 | type: 'Buffer', | ||
16301 | data: Array.prototype.slice.call(this._arr || this, 0) | ||
16302 | } | ||
16303 | } | ||
16304 | |||
16305 | function base64Slice (buf, start, end) { | ||
16306 | if (start === 0 && end === buf.length) { | ||
16307 | return base64.fromByteArray(buf) | ||
16308 | } else { | ||
16309 | return base64.fromByteArray(buf.slice(start, end)) | ||
16310 | } | ||
16311 | } | ||
16312 | |||
16313 | function utf8Slice (buf, start, end) { | ||
16314 | end = Math.min(buf.length, end) | ||
16315 | var res = [] | ||
16316 | |||
16317 | var i = start | ||
16318 | while (i < end) { | ||
16319 | var firstByte = buf[i] | ||
16320 | var codePoint = null | ||
16321 | var bytesPerSequence = (firstByte > 0xEF) ? 4 | ||
16322 | : (firstByte > 0xDF) ? 3 | ||
16323 | : (firstByte > 0xBF) ? 2 | ||
16324 | : 1 | ||
16325 | |||
16326 | if (i + bytesPerSequence <= end) { | ||
16327 | var secondByte, thirdByte, fourthByte, tempCodePoint | ||
16328 | |||
16329 | switch (bytesPerSequence) { | ||
16330 | case 1: | ||
16331 | if (firstByte < 0x80) { | ||
16332 | codePoint = firstByte | ||
16333 | } | ||
16334 | break | ||
16335 | case 2: | ||
16336 | secondByte = buf[i + 1] | ||
16337 | if ((secondByte & 0xC0) === 0x80) { | ||
16338 | tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) | ||
16339 | if (tempCodePoint > 0x7F) { | ||
16340 | codePoint = tempCodePoint | ||
16341 | } | ||
16342 | } | ||
16343 | break | ||
16344 | case 3: | ||
16345 | secondByte = buf[i + 1] | ||
16346 | thirdByte = buf[i + 2] | ||
16347 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { | ||
16348 | tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) | ||
16349 | if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { | ||
16350 | codePoint = tempCodePoint | ||
16351 | } | ||
16352 | } | ||
16353 | break | ||
16354 | case 4: | ||
16355 | secondByte = buf[i + 1] | ||
16356 | thirdByte = buf[i + 2] | ||
16357 | fourthByte = buf[i + 3] | ||
16358 | if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { | ||
16359 | tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) | ||
16360 | if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { | ||
16361 | codePoint = tempCodePoint | ||
16362 | } | ||
16363 | } | ||
16364 | } | ||
16365 | } | ||
16366 | |||
16367 | if (codePoint === null) { | ||
16368 | // we did not generate a valid codePoint so insert a | ||
16369 | // replacement char (U+FFFD) and advance only 1 byte | ||
16370 | codePoint = 0xFFFD | ||
16371 | bytesPerSequence = 1 | ||
16372 | } else if (codePoint > 0xFFFF) { | ||
16373 | // encode to utf16 (surrogate pair dance) | ||
16374 | codePoint -= 0x10000 | ||
16375 | res.push(codePoint >>> 10 & 0x3FF | 0xD800) | ||
16376 | codePoint = 0xDC00 | codePoint & 0x3FF | ||
16377 | } | ||
16378 | |||
16379 | res.push(codePoint) | ||
16380 | i += bytesPerSequence | ||
16381 | } | ||
16382 | |||
16383 | return decodeCodePointsArray(res) | ||
16384 | } | ||
16385 | |||
16386 | // Based on http://stackoverflow.com/a/22747272/680742, the browser with | ||
16387 | // the lowest limit is Chrome, with 0x10000 args. | ||
16388 | // We go 1 magnitude less, for safety | ||
16389 | var MAX_ARGUMENTS_LENGTH = 0x1000 | ||
16390 | |||
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() | ||
16395 | } | ||
16396 | |||
16397 | // Decode in chunks to avoid "call stack size exceeded". | ||
16398 | var res = '' | ||
16399 | var i = 0 | ||
16400 | while (i < len) { | ||
16401 | res += String.fromCharCode.apply( | ||
16402 | String, | ||
16403 | codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) | ||
16404 | ) | ||
16405 | } | ||
16406 | return res | ||
16407 | } | ||
16408 | |||
16409 | function asciiSlice (buf, start, end) { | ||
16410 | var ret = '' | ||
16411 | end = Math.min(buf.length, end) | ||
16412 | |||
16413 | for (var i = start; i < end; ++i) { | ||
16414 | ret += String.fromCharCode(buf[i] & 0x7F) | ||
16415 | } | ||
16416 | return ret | ||
16417 | } | ||
16418 | |||
16419 | function latin1Slice (buf, start, end) { | ||
16420 | var ret = '' | ||
16421 | end = Math.min(buf.length, end) | ||
16422 | |||
16423 | for (var i = start; i < end; ++i) { | ||
16424 | ret += String.fromCharCode(buf[i]) | ||
16425 | } | ||
16426 | return ret | ||
16427 | } | ||
16428 | |||
16429 | function hexSlice (buf, start, end) { | ||
16430 | var len = buf.length | ||
16431 | |||
16432 | if (!start || start < 0) start = 0 | ||
16433 | if (!end || end < 0 || end > len) end = len | ||
16434 | |||
16435 | var out = '' | ||
16436 | for (var i = start; i < end; ++i) { | ||
16437 | out += toHex(buf[i]) | ||
16438 | } | ||
16439 | return out | ||
16440 | } | ||
16441 | |||
16442 | function utf16leSlice (buf, start, end) { | ||
16443 | var bytes = buf.slice(start, end) | ||
16444 | var res = '' | ||
16445 | for (var i = 0; i < bytes.length; i += 2) { | ||
16446 | res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)) | ||
16447 | } | ||
16448 | return res | ||
16449 | } | ||
16450 | |||
16451 | Buffer.prototype.slice = function slice (start, end) { | ||
16452 | var len = this.length | ||
16453 | start = ~~start | ||
16454 | end = end === undefined ? len : ~~end | ||
16455 | |||
16456 | if (start < 0) { | ||
16457 | start += len | ||
16458 | if (start < 0) start = 0 | ||
16459 | } else if (start > len) { | ||
16460 | start = len | ||
16461 | } | ||
16462 | |||
16463 | if (end < 0) { | ||
16464 | end += len | ||
16465 | if (end < 0) end = 0 | ||
16466 | } else if (end > len) { | ||
16467 | end = len | ||
16468 | } | ||
16469 | |||
16470 | if (end < start) end = start | ||
16471 | |||
16472 | var newBuf = this.subarray(start, end) | ||
16473 | // Return an augmented `Uint8Array` instance | ||
16474 | newBuf.__proto__ = Buffer.prototype | ||
16475 | return newBuf | ||
16476 | } | ||
16477 | |||
16478 | /* | ||
16479 | * Need to make sure that buffer isn't trying to write out of bounds. | ||
16480 | */ | ||
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') | ||
16484 | } | ||
16485 | |||
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) | ||
16490 | |||
16491 | var val = this[offset] | ||
16492 | var mul = 1 | ||
16493 | var i = 0 | ||
16494 | while (++i < byteLength && (mul *= 0x100)) { | ||
16495 | val += this[offset + i] * mul | ||
16496 | } | ||
16497 | |||
16498 | return val | ||
16499 | } | ||
16500 | |||
16501 | Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { | ||
16502 | offset = offset >>> 0 | ||
16503 | byteLength = byteLength >>> 0 | ||
16504 | if (!noAssert) { | ||
16505 | checkOffset(offset, byteLength, this.length) | ||
16506 | } | ||
16507 | |||
16508 | var val = this[offset + --byteLength] | ||
16509 | var mul = 1 | ||
16510 | while (byteLength > 0 && (mul *= 0x100)) { | ||
16511 | val += this[offset + --byteLength] * mul | ||
16512 | } | ||
16513 | |||
16514 | return val | ||
16515 | } | ||
16516 | |||
16517 | Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { | ||
16518 | offset = offset >>> 0 | ||
16519 | if (!noAssert) checkOffset(offset, 1, this.length) | ||
16520 | return this[offset] | ||
16521 | } | ||
16522 | |||
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) | ||
16527 | } | ||
16528 | |||
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] | ||
16533 | } | ||
16534 | |||
16535 | Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { | ||
16536 | offset = offset >>> 0 | ||
16537 | if (!noAssert) checkOffset(offset, 4, this.length) | ||
16538 | |||
16539 | return ((this[offset]) | | ||
16540 | (this[offset + 1] << 8) | | ||
16541 | (this[offset + 2] << 16)) + | ||
16542 | (this[offset + 3] * 0x1000000) | ||
16543 | } | ||
16544 | |||
16545 | Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { | ||
16546 | offset = offset >>> 0 | ||
16547 | if (!noAssert) checkOffset(offset, 4, this.length) | ||
16548 | |||
16549 | return (this[offset] * 0x1000000) + | ||
16550 | ((this[offset + 1] << 16) | | ||
16551 | (this[offset + 2] << 8) | | ||
16552 | this[offset + 3]) | ||
16553 | } | ||
16554 | |||
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) | ||
16559 | |||
16560 | var val = this[offset] | ||
16561 | var mul = 1 | ||
16562 | var i = 0 | ||
16563 | while (++i < byteLength && (mul *= 0x100)) { | ||
16564 | val += this[offset + i] * mul | ||
16565 | } | ||
16566 | mul *= 0x80 | ||
16567 | |||
16568 | if (val >= mul) val -= Math.pow(2, 8 * byteLength) | ||
16569 | |||
16570 | return val | ||
16571 | } | ||
16572 | |||
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) | ||
16577 | |||
16578 | var i = byteLength | ||
16579 | var mul = 1 | ||
16580 | var val = this[offset + --i] | ||
16581 | while (i > 0 && (mul *= 0x100)) { | ||
16582 | val += this[offset + --i] * mul | ||
16583 | } | ||
16584 | mul *= 0x80 | ||
16585 | |||
16586 | if (val >= mul) val -= Math.pow(2, 8 * byteLength) | ||
16587 | |||
16588 | return val | ||
16589 | } | ||
16590 | |||
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) | ||
16596 | } | ||
16597 | |||
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 | ||
16603 | } | ||
16604 | |||
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 | ||
16610 | } | ||
16611 | |||
16612 | Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { | ||
16613 | offset = offset >>> 0 | ||
16614 | if (!noAssert) checkOffset(offset, 4, this.length) | ||
16615 | |||
16616 | return (this[offset]) | | ||
16617 | (this[offset + 1] << 8) | | ||
16618 | (this[offset + 2] << 16) | | ||
16619 | (this[offset + 3] << 24) | ||
16620 | } | ||
16621 | |||
16622 | Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { | ||
16623 | offset = offset >>> 0 | ||
16624 | if (!noAssert) checkOffset(offset, 4, this.length) | ||
16625 | |||
16626 | return (this[offset] << 24) | | ||
16627 | (this[offset + 1] << 16) | | ||
16628 | (this[offset + 2] << 8) | | ||
16629 | (this[offset + 3]) | ||
16630 | } | ||
16631 | |||
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) | ||
16636 | } | ||
16637 | |||
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) | ||
16642 | } | ||
16643 | |||
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) | ||
16648 | } | ||
16649 | |||
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) | ||
16654 | } | ||
16655 | |||
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') | ||
16660 | } | ||
16661 | |||
16662 | Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { | ||
16663 | value = +value | ||
16664 | offset = offset >>> 0 | ||
16665 | byteLength = byteLength >>> 0 | ||
16666 | if (!noAssert) { | ||
16667 | var maxBytes = Math.pow(2, 8 * byteLength) - 1 | ||
16668 | checkInt(this, value, offset, byteLength, maxBytes, 0) | ||
16669 | } | ||
16670 | |||
16671 | var mul = 1 | ||
16672 | var i = 0 | ||
16673 | this[offset] = value & 0xFF | ||
16674 | while (++i < byteLength && (mul *= 0x100)) { | ||
16675 | this[offset + i] = (value / mul) & 0xFF | ||
16676 | } | ||
16677 | |||
16678 | return offset + byteLength | ||
16679 | } | ||
16680 | |||
16681 | Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { | ||
16682 | value = +value | ||
16683 | offset = offset >>> 0 | ||
16684 | byteLength = byteLength >>> 0 | ||
16685 | if (!noAssert) { | ||
16686 | var maxBytes = Math.pow(2, 8 * byteLength) - 1 | ||
16687 | checkInt(this, value, offset, byteLength, maxBytes, 0) | ||
16688 | } | ||
16689 | |||
16690 | var i = byteLength - 1 | ||
16691 | var mul = 1 | ||
16692 | this[offset + i] = value & 0xFF | ||
16693 | while (--i >= 0 && (mul *= 0x100)) { | ||
16694 | this[offset + i] = (value / mul) & 0xFF | ||
16695 | } | ||
16696 | |||
16697 | return offset + byteLength | ||
16698 | } | ||
16699 | |||
16700 | Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { | ||
16701 | value = +value | ||
16702 | offset = offset >>> 0 | ||
16703 | if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) | ||
16704 | this[offset] = (value & 0xff) | ||
16705 | return offset + 1 | ||
16706 | } | ||
16707 | |||
16708 | Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { | ||
16709 | value = +value | ||
16710 | offset = offset >>> 0 | ||
16711 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) | ||
16712 | this[offset] = (value & 0xff) | ||
16713 | this[offset + 1] = (value >>> 8) | ||
16714 | return offset + 2 | ||
16715 | } | ||
16716 | |||
16717 | Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { | ||
16718 | value = +value | ||
16719 | offset = offset >>> 0 | ||
16720 | if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) | ||
16721 | this[offset] = (value >>> 8) | ||
16722 | this[offset + 1] = (value & 0xff) | ||
16723 | return offset + 2 | ||
16724 | } | ||
16725 | |||
16726 | Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { | ||
16727 | value = +value | ||
16728 | offset = offset >>> 0 | ||
16729 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) | ||
16730 | this[offset + 3] = (value >>> 24) | ||
16731 | this[offset + 2] = (value >>> 16) | ||
16732 | this[offset + 1] = (value >>> 8) | ||
16733 | this[offset] = (value & 0xff) | ||
16734 | return offset + 4 | ||
16735 | } | ||
16736 | |||
16737 | Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { | ||
16738 | value = +value | ||
16739 | offset = offset >>> 0 | ||
16740 | if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) | ||
16741 | this[offset] = (value >>> 24) | ||
16742 | this[offset + 1] = (value >>> 16) | ||
16743 | this[offset + 2] = (value >>> 8) | ||
16744 | this[offset + 3] = (value & 0xff) | ||
16745 | return offset + 4 | ||
16746 | } | ||
16747 | |||
16748 | Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { | ||
16749 | value = +value | ||
16750 | offset = offset >>> 0 | ||
16751 | if (!noAssert) { | ||
16752 | var limit = Math.pow(2, (8 * byteLength) - 1) | ||
16753 | |||
16754 | checkInt(this, value, offset, byteLength, limit - 1, -limit) | ||
16755 | } | ||
16756 | |||
16757 | var i = 0 | ||
16758 | var mul = 1 | ||
16759 | var sub = 0 | ||
16760 | this[offset] = value & 0xFF | ||
16761 | while (++i < byteLength && (mul *= 0x100)) { | ||
16762 | if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { | ||
16763 | sub = 1 | ||
16764 | } | ||
16765 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF | ||
16766 | } | ||
16767 | |||
16768 | return offset + byteLength | ||
16769 | } | ||
16770 | |||
16771 | Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { | ||
16772 | value = +value | ||
16773 | offset = offset >>> 0 | ||
16774 | if (!noAssert) { | ||
16775 | var limit = Math.pow(2, (8 * byteLength) - 1) | ||
16776 | |||
16777 | checkInt(this, value, offset, byteLength, limit - 1, -limit) | ||
16778 | } | ||
16779 | |||
16780 | var i = byteLength - 1 | ||
16781 | var mul = 1 | ||
16782 | var sub = 0 | ||
16783 | this[offset + i] = value & 0xFF | ||
16784 | while (--i >= 0 && (mul *= 0x100)) { | ||
16785 | if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { | ||
16786 | sub = 1 | ||
16787 | } | ||
16788 | this[offset + i] = ((value / mul) >> 0) - sub & 0xFF | ||
16789 | } | ||
16790 | |||
16791 | return offset + byteLength | ||
16792 | } | ||
16793 | |||
16794 | Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { | ||
16795 | value = +value | ||
16796 | offset = offset >>> 0 | ||
16797 | if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) | ||
16798 | if (value < 0) value = 0xff + value + 1 | ||
16799 | this[offset] = (value & 0xff) | ||
16800 | return offset + 1 | ||
16801 | } | ||
16802 | |||
16803 | Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { | ||
16804 | value = +value | ||
16805 | offset = offset >>> 0 | ||
16806 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) | ||
16807 | this[offset] = (value & 0xff) | ||
16808 | this[offset + 1] = (value >>> 8) | ||
16809 | return offset + 2 | ||
16810 | } | ||
16811 | |||
16812 | Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { | ||
16813 | value = +value | ||
16814 | offset = offset >>> 0 | ||
16815 | if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) | ||
16816 | this[offset] = (value >>> 8) | ||
16817 | this[offset + 1] = (value & 0xff) | ||
16818 | return offset + 2 | ||
16819 | } | ||
16820 | |||
16821 | Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { | ||
16822 | value = +value | ||
16823 | offset = offset >>> 0 | ||
16824 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) | ||
16825 | this[offset] = (value & 0xff) | ||
16826 | this[offset + 1] = (value >>> 8) | ||
16827 | this[offset + 2] = (value >>> 16) | ||
16828 | this[offset + 3] = (value >>> 24) | ||
16829 | return offset + 4 | ||
16830 | } | ||
16831 | |||
16832 | Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { | ||
16833 | value = +value | ||
16834 | offset = offset >>> 0 | ||
16835 | if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) | ||
16836 | if (value < 0) value = 0xffffffff + value + 1 | ||
16837 | this[offset] = (value >>> 24) | ||
16838 | this[offset + 1] = (value >>> 16) | ||
16839 | this[offset + 2] = (value >>> 8) | ||
16840 | this[offset + 3] = (value & 0xff) | ||
16841 | return offset + 4 | ||
16842 | } | ||
16843 | |||
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') | ||
16847 | } | ||
16848 | |||
16849 | function writeFloat (buf, value, offset, littleEndian, noAssert) { | ||
16850 | value = +value | ||
16851 | offset = offset >>> 0 | ||
16852 | if (!noAssert) { | ||
16853 | checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) | ||
16854 | } | ||
16855 | ieee754.write(buf, value, offset, littleEndian, 23, 4) | ||
16856 | return offset + 4 | ||
16857 | } | ||
16858 | |||
16859 | Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { | ||
16860 | return writeFloat(this, value, offset, true, noAssert) | ||
16861 | } | ||
16862 | |||
16863 | Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { | ||
16864 | return writeFloat(this, value, offset, false, noAssert) | ||
16865 | } | ||
16866 | |||
16867 | function writeDouble (buf, value, offset, littleEndian, noAssert) { | ||
16868 | value = +value | ||
16869 | offset = offset >>> 0 | ||
16870 | if (!noAssert) { | ||
16871 | checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) | ||
16872 | } | ||
16873 | ieee754.write(buf, value, offset, littleEndian, 52, 8) | ||
16874 | return offset + 8 | ||
16875 | } | ||
16876 | |||
16877 | Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { | ||
16878 | return writeDouble(this, value, offset, true, noAssert) | ||
16879 | } | ||
16880 | |||
16881 | Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { | ||
16882 | return writeDouble(this, value, offset, false, noAssert) | ||
16883 | } | ||
16884 | |||
16885 | // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) | ||
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 | ||
16892 | |||
16893 | // Copy 0 bytes; we're done | ||
16894 | if (end === start) return 0 | ||
16895 | if (target.length === 0 || this.length === 0) return 0 | ||
16896 | |||
16897 | // Fatal error conditions | ||
16898 | if (targetStart < 0) { | ||
16899 | throw new RangeError('targetStart out of bounds') | ||
16900 | } | ||
16901 | if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') | ||
16902 | if (end < 0) throw new RangeError('sourceEnd out of bounds') | ||
16903 | |||
16904 | // Are we oob? | ||
16905 | if (end > this.length) end = this.length | ||
16906 | if (target.length - targetStart < end - start) { | ||
16907 | end = target.length - targetStart + start | ||
16908 | } | ||
16909 | |||
16910 | var len = end - start | ||
16911 | var i | ||
16912 | |||
16913 | if (this === target && start < targetStart && targetStart < end) { | ||
16914 | // descending copy from end | ||
16915 | for (i = len - 1; i >= 0; --i) { | ||
16916 | target[i + targetStart] = this[i + start] | ||
16917 | } | ||
16918 | } else if (len < 1000) { | ||
16919 | // ascending copy from start | ||
16920 | for (i = 0; i < len; ++i) { | ||
16921 | target[i + targetStart] = this[i + start] | ||
16922 | } | ||
16923 | } else { | ||
16924 | Uint8Array.prototype.set.call( | ||
16925 | target, | ||
16926 | this.subarray(start, start + len), | ||
16927 | targetStart | ||
16928 | ) | ||
16929 | } | ||
16930 | |||
16931 | return len | ||
16932 | } | ||
16933 | |||
16934 | // Usage: | ||
16935 | // buffer.fill(number[, offset[, end]]) | ||
16936 | // buffer.fill(buffer[, offset[, end]]) | ||
16937 | // buffer.fill(string[, offset[, end]][, encoding]) | ||
16938 | Buffer.prototype.fill = function fill (val, start, end, encoding) { | ||
16939 | // Handle string cases: | ||
16940 | if (typeof val === 'string') { | ||
16941 | if (typeof start === 'string') { | ||
16942 | encoding = start | ||
16943 | start = 0 | ||
16944 | end = this.length | ||
16945 | } else if (typeof end === 'string') { | ||
16946 | encoding = end | ||
16947 | end = this.length | ||
16948 | } | ||
16949 | if (val.length === 1) { | ||
16950 | var code = val.charCodeAt(0) | ||
16951 | if (code < 256) { | ||
16952 | val = code | ||
16953 | } | ||
16954 | } | ||
16955 | if (encoding !== undefined && typeof encoding !== 'string') { | ||
16956 | throw new TypeError('encoding must be a string') | ||
16957 | } | ||
16958 | if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { | ||
16959 | throw new TypeError('Unknown encoding: ' + encoding) | ||
16960 | } | ||
16961 | } else if (typeof val === 'number') { | ||
16962 | val = val & 255 | ||
16963 | } | ||
16964 | |||
16965 | // Invalid ranges are not set to a default, so can range check early. | ||
16966 | if (start < 0 || this.length < start || this.length < end) { | ||
16967 | throw new RangeError('Out of range index') | ||
16968 | } | ||
16969 | |||
16970 | if (end <= start) { | ||
16971 | return this | ||
16972 | } | ||
16973 | |||
16974 | start = start >>> 0 | ||
16975 | end = end === undefined ? this.length : end >>> 0 | ||
16976 | |||
16977 | if (!val) val = 0 | ||
16978 | |||
16979 | var i | ||
16980 | if (typeof val === 'number') { | ||
16981 | for (i = start; i < end; ++i) { | ||
16982 | this[i] = val | ||
16983 | } | ||
16984 | } else { | ||
16985 | var bytes = Buffer.isBuffer(val) | ||
16986 | ? val | ||
16987 | : new Buffer(val, encoding) | ||
16988 | var len = bytes.length | ||
16989 | for (i = 0; i < end - start; ++i) { | ||
16990 | this[i + start] = bytes[i % len] | ||
16991 | } | ||
16992 | } | ||
16993 | |||
16994 | return this | ||
16995 | } | ||
16996 | |||
16997 | // HELPER FUNCTIONS | ||
16998 | // ================ | ||
16999 | |||
17000 | var INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g | ||
17001 | |||
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) { | ||
17009 | str = str + '=' | ||
17010 | } | ||
17011 | return str | ||
17012 | } | ||
17013 | |||
17014 | function toHex (n) { | ||
17015 | if (n < 16) return '0' + n.toString(16) | ||
17016 | return n.toString(16) | ||
17017 | } | ||
17018 | |||
17019 | function utf8ToBytes (string, units) { | ||
17020 | units = units || Infinity | ||
17021 | var codePoint | ||
17022 | var length = string.length | ||
17023 | var leadSurrogate = null | ||
17024 | var bytes = [] | ||
17025 | |||
17026 | for (var i = 0; i < length; ++i) { | ||
17027 | codePoint = string.charCodeAt(i) | ||
17028 | |||
17029 | // is surrogate component | ||
17030 | if (codePoint > 0xD7FF && codePoint < 0xE000) { | ||
17031 | // last char was a lead | ||
17032 | if (!leadSurrogate) { | ||
17033 | // no lead yet | ||
17034 | if (codePoint > 0xDBFF) { | ||
17035 | // unexpected trail | ||
17036 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) | ||
17037 | continue | ||
17038 | } else if (i + 1 === length) { | ||
17039 | // unpaired lead | ||
17040 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) | ||
17041 | continue | ||
17042 | } | ||
17043 | |||
17044 | // valid lead | ||
17045 | leadSurrogate = codePoint | ||
17046 | |||
17047 | continue | ||
17048 | } | ||
17049 | |||
17050 | // 2 leads in a row | ||
17051 | if (codePoint < 0xDC00) { | ||
17052 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) | ||
17053 | leadSurrogate = codePoint | ||
17054 | continue | ||
17055 | } | ||
17056 | |||
17057 | // valid surrogate pair | ||
17058 | codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 | ||
17059 | } else if (leadSurrogate) { | ||
17060 | // valid bmp char, but last char was a lead | ||
17061 | if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) | ||
17062 | } | ||
17063 | |||
17064 | leadSurrogate = null | ||
17065 | |||
17066 | // encode utf8 | ||
17067 | if (codePoint < 0x80) { | ||
17068 | if ((units -= 1) < 0) break | ||
17069 | bytes.push(codePoint) | ||
17070 | } else if (codePoint < 0x800) { | ||
17071 | if ((units -= 2) < 0) break | ||
17072 | bytes.push( | ||
17073 | codePoint >> 0x6 | 0xC0, | ||
17074 | codePoint & 0x3F | 0x80 | ||
17075 | ) | ||
17076 | } else if (codePoint < 0x10000) { | ||
17077 | if ((units -= 3) < 0) break | ||
17078 | bytes.push( | ||
17079 | codePoint >> 0xC | 0xE0, | ||
17080 | codePoint >> 0x6 & 0x3F | 0x80, | ||
17081 | codePoint & 0x3F | 0x80 | ||
17082 | ) | ||
17083 | } else if (codePoint < 0x110000) { | ||
17084 | if ((units -= 4) < 0) break | ||
17085 | bytes.push( | ||
17086 | codePoint >> 0x12 | 0xF0, | ||
17087 | codePoint >> 0xC & 0x3F | 0x80, | ||
17088 | codePoint >> 0x6 & 0x3F | 0x80, | ||
17089 | codePoint & 0x3F | 0x80 | ||
17090 | ) | ||
17091 | } else { | ||
17092 | throw new Error('Invalid code point') | ||
17093 | } | ||
17094 | } | ||
17095 | |||
17096 | return bytes | ||
17097 | } | ||
17098 | |||
17099 | function asciiToBytes (str) { | ||
17100 | var byteArray = [] | ||
17101 | for (var i = 0; i < str.length; ++i) { | ||
17102 | // Node's code seems to be doing this and not & 0x7F.. | ||
17103 | byteArray.push(str.charCodeAt(i) & 0xFF) | ||
17104 | } | ||
17105 | return byteArray | ||
17106 | } | ||
17107 | |||
17108 | function utf16leToBytes (str, units) { | ||
17109 | var c, hi, lo | ||
17110 | var byteArray = [] | ||
17111 | for (var i = 0; i < str.length; ++i) { | ||
17112 | if ((units -= 2) < 0) break | ||
17113 | |||
17114 | c = str.charCodeAt(i) | ||
17115 | hi = c >> 8 | ||
17116 | lo = c % 256 | ||
17117 | byteArray.push(lo) | ||
17118 | byteArray.push(hi) | ||
17119 | } | ||
17120 | |||
17121 | return byteArray | ||
17122 | } | ||
17123 | |||
17124 | function base64ToBytes (str) { | ||
17125 | return base64.toByteArray(base64clean(str)) | ||
17126 | } | ||
17127 | |||
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] | ||
17132 | } | ||
17133 | return i | ||
17134 | } | ||
17135 | |||
17136 | // ArrayBuffers from another context (i.e. an iframe) do not pass the `instanceof` check | ||
17137 | // but they should be treated as valid. See: https://github.com/feross/buffer/issues/166 | ||
17138 | function isArrayBuffer (obj) { | ||
17139 | return obj instanceof ArrayBuffer || | ||
17140 | (obj != null && obj.constructor != null && obj.constructor.name === 'ArrayBuffer' && | ||
17141 | typeof obj.byteLength === 'number') | ||
17142 | } | ||
17143 | |||
17144 | // Node 0.10 supports `ArrayBuffer` but lacks `ArrayBuffer.isView` | ||
17145 | function isArrayBufferView (obj) { | ||
17146 | return (typeof ArrayBuffer.isView === 'function') && ArrayBuffer.isView(obj) | ||
17147 | } | ||
17148 | |||
17149 | function numberIsNaN (obj) { | ||
17150 | return obj !== obj // eslint-disable-line no-self-compare | ||
17151 | } | ||
17152 | |||
17153 | },{"base64-js":72,"ieee754":161}],108:[function(require,module,exports){ | ||
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') | ||
17158 | |||
17159 | function CipherBase (hashMode) { | ||
17160 | Transform.call(this) | ||
17161 | this.hashMode = typeof hashMode === 'string' | ||
17162 | if (this.hashMode) { | ||
17163 | this[hashMode] = this._finalOrDigest | ||
17164 | } else { | ||
17165 | this.final = this._finalOrDigest | ||
17166 | } | ||
17167 | if (this._final) { | ||
17168 | this.__final = this._final | ||
17169 | this._final = null | ||
17170 | } | ||
17171 | this._decoder = null | ||
17172 | this._encoding = null | ||
17173 | } | ||
17174 | inherits(CipherBase, Transform) | ||
17175 | |||
17176 | CipherBase.prototype.update = function (data, inputEnc, outputEnc) { | ||
17177 | if (typeof data === 'string') { | ||
17178 | data = Buffer.from(data, inputEnc) | ||
17179 | } | ||
17180 | |||
17181 | var outData = this._update(data) | ||
17182 | if (this.hashMode) return this | ||
17183 | |||
17184 | if (outputEnc) { | ||
17185 | outData = this._toString(outData, outputEnc) | ||
17186 | } | ||
17187 | |||
17188 | return outData | ||
17189 | } | ||
17190 | |||
17191 | CipherBase.prototype.setAutoPadding = function () {} | ||
17192 | CipherBase.prototype.getAuthTag = function () { | ||
17193 | throw new Error('trying to get auth tag in unsupported state') | ||
17194 | } | ||
17195 | |||
17196 | CipherBase.prototype.setAuthTag = function () { | ||
17197 | throw new Error('trying to set auth tag in unsupported state') | ||
17198 | } | ||
17199 | |||
17200 | CipherBase.prototype.setAAD = function () { | ||
17201 | throw new Error('trying to set aad in unsupported state') | ||
17202 | } | ||
17203 | |||
17204 | CipherBase.prototype._transform = function (data, _, next) { | ||
17205 | var err | ||
17206 | try { | ||
17207 | if (this.hashMode) { | ||
17208 | this._update(data) | ||
17209 | } else { | ||
17210 | this.push(this._update(data)) | ||
17211 | } | ||
17212 | } catch (e) { | ||
17213 | err = e | ||
17214 | } finally { | ||
17215 | next(err) | ||
17216 | } | ||
17217 | } | ||
17218 | CipherBase.prototype._flush = function (done) { | ||
17219 | var err | ||
17220 | try { | ||
17221 | this.push(this.__final()) | ||
17222 | } catch (e) { | ||
17223 | err = e | ||
17224 | } | ||
17225 | |||
17226 | done(err) | ||
17227 | } | ||
17228 | CipherBase.prototype._finalOrDigest = function (outputEnc) { | ||
17229 | var outData = this.__final() || Buffer.alloc(0) | ||
17230 | if (outputEnc) { | ||
17231 | outData = this._toString(outData, outputEnc, true) | ||
17232 | } | ||
17233 | return outData | ||
17234 | } | ||
17235 | |||
17236 | CipherBase.prototype._toString = function (value, enc, fin) { | ||
17237 | if (!this._decoder) { | ||
17238 | this._decoder = new StringDecoder(enc) | ||
17239 | this._encoding = enc | ||
17240 | } | ||
17241 | |||
17242 | if (this._encoding !== enc) throw new Error('can\'t switch encodings') | ||
17243 | |||
17244 | var out = this._decoder.write(value) | ||
17245 | if (fin) { | ||
17246 | out += this._decoder.end() | ||
17247 | } | ||
17248 | |||
17249 | return out | ||
17250 | } | ||
17251 | |||
17252 | module.exports = CipherBase | ||
17253 | |||
17254 | },{"inherits":163,"safe-buffer":247,"stream":263,"string_decoder":264}],109:[function(require,module,exports){ | ||
17255 | (function (Buffer){ | ||
17256 | // Copyright Joyent, Inc. and other Node contributors. | ||
17257 | // | ||
17258 | // Permission is hereby granted, free of charge, to any person obtaining a | ||
17259 | // copy of this software and associated documentation files (the | ||
17260 | // "Software"), to deal in the Software without restriction, including | ||
17261 | // without limitation the rights to use, copy, modify, merge, publish, | ||
17262 | // distribute, sublicense, and/or sell copies of the Software, and to permit | ||
17263 | // persons to whom the Software is furnished to do so, subject to the | ||
17264 | // following conditions: | ||
17265 | // | ||
17266 | // The above copyright notice and this permission notice shall be included | ||
17267 | // in all copies or substantial portions of the Software. | ||
17268 | // | ||
17269 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
17270 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
17271 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | ||
17272 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | ||
17273 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
17274 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
17275 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
17276 | |||
17277 | // NOTE: These type checking functions intentionally don't use `instanceof` | ||
17278 | // because it is fragile and can be easily faked with `Object.create()`. | ||
17279 | |||
17280 | function isArray(arg) { | ||
17281 | if (Array.isArray) { | ||
17282 | return Array.isArray(arg); | ||
17283 | } | ||
17284 | return objectToString(arg) === '[object Array]'; | ||
17285 | } | ||
17286 | exports.isArray = isArray; | ||
17287 | |||
17288 | function isBoolean(arg) { | ||
17289 | return typeof arg === 'boolean'; | ||
17290 | } | ||
17291 | exports.isBoolean = isBoolean; | ||
17292 | |||
17293 | function isNull(arg) { | ||
17294 | return arg === null; | ||
17295 | } | ||
17296 | exports.isNull = isNull; | ||
17297 | |||
17298 | function isNullOrUndefined(arg) { | ||
17299 | return arg == null; | ||
17300 | } | ||
17301 | exports.isNullOrUndefined = isNullOrUndefined; | ||
17302 | |||
17303 | function isNumber(arg) { | ||
17304 | return typeof arg === 'number'; | ||
17305 | } | ||
17306 | exports.isNumber = isNumber; | ||
17307 | |||
17308 | function isString(arg) { | ||
17309 | return typeof arg === 'string'; | ||
17310 | } | ||
17311 | exports.isString = isString; | ||
17312 | |||
17313 | function isSymbol(arg) { | ||
17314 | return typeof arg === 'symbol'; | ||
17315 | } | ||
17316 | exports.isSymbol = isSymbol; | ||
17317 | |||
17318 | function isUndefined(arg) { | ||
17319 | return arg === void 0; | ||
17320 | } | ||
17321 | exports.isUndefined = isUndefined; | ||
17322 | |||
17323 | function isRegExp(re) { | ||
17324 | return objectToString(re) === '[object RegExp]'; | ||
17325 | } | ||
17326 | exports.isRegExp = isRegExp; | ||
17327 | |||
17328 | function isObject(arg) { | ||
17329 | return typeof arg === 'object' && arg !== null; | ||
17330 | } | ||
17331 | exports.isObject = isObject; | ||
17332 | |||
17333 | function isDate(d) { | ||
17334 | return objectToString(d) === '[object Date]'; | ||
17335 | } | ||
17336 | exports.isDate = isDate; | ||
17337 | |||
17338 | function isError(e) { | ||
17339 | return (objectToString(e) === '[object Error]' || e instanceof Error); | ||
17340 | } | ||
17341 | exports.isError = isError; | ||
17342 | |||
17343 | function isFunction(arg) { | ||
17344 | return typeof arg === 'function'; | ||
17345 | } | ||
17346 | exports.isFunction = isFunction; | ||
17347 | |||
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'; | ||
17355 | } | ||
17356 | exports.isPrimitive = isPrimitive; | ||
17357 | |||
17358 | exports.isBuffer = Buffer.isBuffer; | ||
17359 | |||
17360 | function objectToString(o) { | ||
17361 | return Object.prototype.toString.call(o); | ||
17362 | } | ||
17363 | |||
17364 | }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) | ||
17365 | },{"../../is-buffer/index.js":164}],110:[function(require,module,exports){ | ||
17366 | (function (Buffer){ | ||
17367 | var elliptic = require('elliptic'); | ||
17368 | var BN = require('bn.js'); | ||
17369 | |||
17370 | module.exports = function createECDH(curve) { | ||
17371 | return new ECDH(curve); | ||
17372 | }; | ||
17373 | |||
17374 | var aliases = { | ||
17375 | secp256k1: { | ||
17376 | name: 'secp256k1', | ||
17377 | byteLength: 32 | ||
17378 | }, | ||
17379 | secp224r1: { | ||
17380 | name: 'p224', | ||
17381 | byteLength: 28 | ||
17382 | }, | ||
17383 | prime256v1: { | ||
17384 | name: 'p256', | ||
17385 | byteLength: 32 | ||
17386 | }, | ||
17387 | prime192v1: { | ||
17388 | name: 'p192', | ||
17389 | byteLength: 24 | ||
17390 | }, | ||
17391 | ed25519: { | ||
17392 | name: 'ed25519', | ||
17393 | byteLength: 32 | ||
17394 | }, | ||
17395 | secp384r1: { | ||
17396 | name: 'p384', | ||
17397 | byteLength: 48 | ||
17398 | }, | ||
17399 | secp521r1: { | ||
17400 | name: 'p521', | ||
17401 | byteLength: 66 | ||
17402 | } | ||
17403 | }; | ||
17404 | |||
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; | ||
17410 | |||
17411 | function ECDH(curve) { | ||
17412 | this.curveType = aliases[curve]; | ||
17413 | if (!this.curveType ) { | ||
17414 | this.curveType = { | ||
17415 | name: curve | ||
17416 | }; | ||
17417 | } | ||
17418 | this.curve = new elliptic.ec(this.curveType.name); | ||
17419 | this.keys = void 0; | ||
17420 | } | ||
17421 | |||
17422 | ECDH.prototype.generateKeys = function (enc, format) { | ||
17423 | this.keys = this.curve.genKeyPair(); | ||
17424 | return this.getPublicKey(enc, format); | ||
17425 | }; | ||
17426 | |||
17427 | ECDH.prototype.computeSecret = function (other, inenc, enc) { | ||
17428 | inenc = inenc || 'utf8'; | ||
17429 | if (!Buffer.isBuffer(other)) { | ||
17430 | other = new Buffer(other, inenc); | ||
17431 | } | ||
17432 | var otherPub = this.curve.keyFromPublic(other).getPublic(); | ||
17433 | var out = otherPub.mul(this.keys.getPrivate()).getX(); | ||
17434 | return formatReturnValue(out, enc, this.curveType.byteLength); | ||
17435 | }; | ||
17436 | |||
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) { | ||
17441 | key[0] = 7; | ||
17442 | } else { | ||
17443 | key [0] = 6; | ||
17444 | } | ||
17445 | } | ||
17446 | return formatReturnValue(key, enc); | ||
17447 | }; | ||
17448 | |||
17449 | ECDH.prototype.getPrivateKey = function (enc) { | ||
17450 | return formatReturnValue(this.keys.getPrivate(), enc); | ||
17451 | }; | ||
17452 | |||
17453 | ECDH.prototype.setPublicKey = function (pub, enc) { | ||
17454 | enc = enc || 'utf8'; | ||
17455 | if (!Buffer.isBuffer(pub)) { | ||
17456 | pub = new Buffer(pub, enc); | ||
17457 | } | ||
17458 | this.keys._importPublic(pub); | ||
17459 | return this; | ||
17460 | }; | ||
17461 | |||
17462 | ECDH.prototype.setPrivateKey = function (priv, enc) { | ||
17463 | enc = enc || 'utf8'; | ||
17464 | if (!Buffer.isBuffer(priv)) { | ||
17465 | priv = new Buffer(priv, enc); | ||
17466 | } | ||
17467 | var _priv = new BN(priv); | ||
17468 | _priv = _priv.toString(16); | ||
17469 | this.keys._importPrivate(_priv); | ||
17470 | return this; | ||
17471 | }; | ||
17472 | |||
17473 | function formatReturnValue(bn, enc, len) { | ||
17474 | if (!Array.isArray(bn)) { | ||
17475 | bn = bn.toArray(); | ||
17476 | } | ||
17477 | var buf = new Buffer(bn); | ||
17478 | if (len && buf.length < len) { | ||
17479 | var zeros = new Buffer(len - buf.length); | ||
17480 | zeros.fill(0); | ||
17481 | buf = Buffer.concat([zeros, buf]); | ||
17482 | } | ||
17483 | if (!enc) { | ||
17484 | return buf; | ||
17485 | } else { | ||
17486 | return buf.toString(enc); | ||
17487 | } | ||
17488 | } | ||
17489 | |||
17490 | }).call(this,require("buffer").Buffer) | ||
17491 | },{"bn.js":75,"buffer":107,"elliptic":127}],111:[function(require,module,exports){ | ||
17492 | (function (Buffer){ | ||
17493 | 'use strict' | ||
17494 | var inherits = require('inherits') | ||
17495 | var md5 = require('./md5') | ||
17496 | var RIPEMD160 = require('ripemd160') | ||
17497 | var sha = require('sha.js') | ||
17498 | |||
17499 | var Base = require('cipher-base') | ||
17500 | |||
17501 | function HashNoConstructor (hash) { | ||
17502 | Base.call(this, 'digest') | ||
17503 | |||
17504 | this._hash = hash | ||
17505 | this.buffers = [] | ||
17506 | } | ||
17507 | |||
17508 | inherits(HashNoConstructor, Base) | ||
17509 | |||
17510 | HashNoConstructor.prototype._update = function (data) { | ||
17511 | this.buffers.push(data) | ||
17512 | } | ||
17513 | |||
17514 | HashNoConstructor.prototype._final = function () { | ||
17515 | var buf = Buffer.concat(this.buffers) | ||
17516 | var r = this._hash(buf) | ||
17517 | this.buffers = null | ||
17518 | |||
17519 | return r | ||
17520 | } | ||
17521 | |||
17522 | function Hash (hash) { | ||
17523 | Base.call(this, 'digest') | ||
17524 | |||
17525 | this._hash = hash | ||
17526 | } | ||
17527 | |||
17528 | inherits(Hash, Base) | ||
17529 | |||
17530 | Hash.prototype._update = function (data) { | ||
17531 | this._hash.update(data) | ||
17532 | } | ||
17533 | |||
17534 | Hash.prototype._final = function () { | ||
17535 | return this._hash.digest() | ||
17536 | } | ||
17537 | |||
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()) | ||
17542 | |||
17543 | return new Hash(sha(alg)) | ||
17544 | } | ||
17545 | |||
17546 | }).call(this,require("buffer").Buffer) | ||
17547 | },{"./md5":113,"buffer":107,"cipher-base":108,"inherits":163,"ripemd160":246,"sha.js":256}],112:[function(require,module,exports){ | ||
17548 | (function (Buffer){ | ||
17549 | 'use strict' | ||
17550 | var intSize = 4 | ||
17551 | var zeroBuffer = new Buffer(intSize) | ||
17552 | zeroBuffer.fill(0) | ||
17553 | |||
17554 | var charSize = 8 | ||
17555 | var hashSize = 16 | ||
17556 | |||
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) | ||
17561 | } | ||
17562 | |||
17563 | var arr = new Array(buf.length >>> 2) | ||
17564 | for (var i = 0, j = 0; i < buf.length; i += intSize, j++) { | ||
17565 | arr[j] = buf.readInt32LE(i) | ||
17566 | } | ||
17567 | |||
17568 | return arr | ||
17569 | } | ||
17570 | |||
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) | ||
17576 | } | ||
17577 | return buf | ||
17578 | } | ||
17579 | |||
17580 | }).call(this,require("buffer").Buffer) | ||
17581 | },{"buffer":107}],113:[function(require,module,exports){ | ||
17582 | 'use strict' | ||
17583 | /* | ||
17584 | * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message | ||
17585 | * Digest Algorithm, as defined in RFC 1321. | ||
17586 | * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. | ||
17587 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet | ||
17588 | * Distributed under the BSD License | ||
17589 | * See http://pajhome.org.uk/crypt/md5 for more info. | ||
17590 | */ | ||
17591 | |||
17592 | var makeHash = require('./make-hash') | ||
17593 | |||
17594 | /* | ||
17595 | * Calculate the MD5 of an array of little-endian words, and a bit length | ||
17596 | */ | ||
17597 | function core_md5 (x, len) { | ||
17598 | /* append padding */ | ||
17599 | x[len >> 5] |= 0x80 << ((len) % 32) | ||
17600 | x[(((len + 64) >>> 9) << 4) + 14] = len | ||
17601 | |||
17602 | var a = 1732584193 | ||
17603 | var b = -271733879 | ||
17604 | var c = -1732584194 | ||
17605 | var d = 271733878 | ||
17606 | |||
17607 | for (var i = 0; i < x.length; i += 16) { | ||
17608 | var olda = a | ||
17609 | var oldb = b | ||
17610 | var oldc = c | ||
17611 | var oldd = d | ||
17612 | |||
17613 | a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936) | ||
17614 | d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586) | ||
17615 | c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819) | ||
17616 | b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330) | ||
17617 | a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897) | ||
17618 | d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426) | ||
17619 | c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341) | ||
17620 | b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983) | ||
17621 | a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416) | ||
17622 | d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417) | ||
17623 | c = md5_ff(c, d, a, b, x[i + 10], 17, -42063) | ||
17624 | b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162) | ||
17625 | a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682) | ||
17626 | d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101) | ||
17627 | c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290) | ||
17628 | b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329) | ||
17629 | |||
17630 | a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510) | ||
17631 | d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632) | ||
17632 | c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713) | ||
17633 | b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302) | ||
17634 | a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691) | ||
17635 | d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083) | ||
17636 | c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335) | ||
17637 | b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848) | ||
17638 | a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438) | ||
17639 | d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690) | ||
17640 | c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961) | ||
17641 | b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501) | ||
17642 | a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467) | ||
17643 | d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784) | ||
17644 | c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473) | ||
17645 | b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734) | ||
17646 | |||
17647 | a = md5_hh(a, b, c, d, x[i + 5], 4, -378558) | ||
17648 | d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463) | ||
17649 | c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562) | ||
17650 | b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556) | ||
17651 | a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060) | ||
17652 | d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353) | ||
17653 | c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632) | ||
17654 | b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640) | ||
17655 | a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174) | ||
17656 | d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222) | ||
17657 | c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979) | ||
17658 | b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189) | ||
17659 | a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487) | ||
17660 | d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835) | ||
17661 | c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520) | ||
17662 | b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651) | ||
17663 | |||
17664 | a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844) | ||
17665 | d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415) | ||
17666 | c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905) | ||
17667 | b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055) | ||
17668 | a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571) | ||
17669 | d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606) | ||
17670 | c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523) | ||
17671 | b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799) | ||
17672 | a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359) | ||
17673 | d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744) | ||
17674 | c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380) | ||
17675 | b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649) | ||
17676 | a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070) | ||
17677 | d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379) | ||
17678 | c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259) | ||
17679 | b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551) | ||
17680 | |||
17681 | a = safe_add(a, olda) | ||
17682 | b = safe_add(b, oldb) | ||
17683 | c = safe_add(c, oldc) | ||
17684 | d = safe_add(d, oldd) | ||
17685 | } | ||
17686 | |||
17687 | return [a, b, c, d] | ||
17688 | } | ||
17689 | |||
17690 | /* | ||
17691 | * These functions implement the four basic operations the algorithm uses. | ||
17692 | */ | ||
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) | ||
17695 | } | ||
17696 | |||
17697 | function md5_ff (a, b, c, d, x, s, t) { | ||
17698 | return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t) | ||
17699 | } | ||
17700 | |||
17701 | function md5_gg (a, b, c, d, x, s, t) { | ||
17702 | return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t) | ||
17703 | } | ||
17704 | |||
17705 | function md5_hh (a, b, c, d, x, s, t) { | ||
17706 | return md5_cmn(b ^ c ^ d, a, b, x, s, t) | ||
17707 | } | ||
17708 | |||
17709 | function md5_ii (a, b, c, d, x, s, t) { | ||
17710 | return md5_cmn(c ^ (b | (~d)), a, b, x, s, t) | ||
17711 | } | ||
17712 | |||
17713 | /* | ||
17714 | * Add integers, wrapping at 2^32. This uses 16-bit operations internally | ||
17715 | * to work around bugs in some JS interpreters. | ||
17716 | */ | ||
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) | ||
17721 | } | ||
17722 | |||
17723 | /* | ||
17724 | * Bitwise rotate a 32-bit number to the left. | ||
17725 | */ | ||
17726 | function bit_rol (num, cnt) { | ||
17727 | return (num << cnt) | (num >>> (32 - cnt)) | ||
17728 | } | ||
17729 | |||
17730 | module.exports = function md5 (buf) { | ||
17731 | return makeHash(buf, core_md5) | ||
17732 | } | ||
17733 | |||
17734 | },{"./make-hash":112}],114:[function(require,module,exports){ | ||
17735 | 'use strict' | ||
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') | ||
17742 | |||
17743 | var sha = require('sha.js') | ||
17744 | |||
17745 | var ZEROS = Buffer.alloc(128) | ||
17746 | |||
17747 | function Hmac (alg, key) { | ||
17748 | Base.call(this, 'digest') | ||
17749 | if (typeof key === 'string') { | ||
17750 | key = Buffer.from(key) | ||
17751 | } | ||
17752 | |||
17753 | var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 | ||
17754 | |||
17755 | this._alg = alg | ||
17756 | this._key = key | ||
17757 | if (key.length > blocksize) { | ||
17758 | var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) | ||
17759 | key = hash.update(key).digest() | ||
17760 | } else if (key.length < blocksize) { | ||
17761 | key = Buffer.concat([key, ZEROS], blocksize) | ||
17762 | } | ||
17763 | |||
17764 | var ipad = this._ipad = Buffer.allocUnsafe(blocksize) | ||
17765 | var opad = this._opad = Buffer.allocUnsafe(blocksize) | ||
17766 | |||
17767 | for (var i = 0; i < blocksize; i++) { | ||
17768 | ipad[i] = key[i] ^ 0x36 | ||
17769 | opad[i] = key[i] ^ 0x5C | ||
17770 | } | ||
17771 | this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) | ||
17772 | this._hash.update(ipad) | ||
17773 | } | ||
17774 | |||
17775 | inherits(Hmac, Base) | ||
17776 | |||
17777 | Hmac.prototype._update = function (data) { | ||
17778 | this._hash.update(data) | ||
17779 | } | ||
17780 | |||
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() | ||
17785 | } | ||
17786 | |||
17787 | module.exports = function createHmac (alg, key) { | ||
17788 | alg = alg.toLowerCase() | ||
17789 | if (alg === 'rmd160' || alg === 'ripemd160') { | ||
17790 | return new Hmac('rmd160', key) | ||
17791 | } | ||
17792 | if (alg === 'md5') { | ||
17793 | return new Legacy(md5, key) | ||
17794 | } | ||
17795 | return new Hmac(alg, key) | ||
17796 | } | ||
17797 | |||
17798 | },{"./legacy":115,"cipher-base":108,"create-hash/md5":113,"inherits":163,"ripemd160":246,"safe-buffer":247,"sha.js":256}],115:[function(require,module,exports){ | ||
17799 | 'use strict' | ||
17800 | var inherits = require('inherits') | ||
17801 | var Buffer = require('safe-buffer').Buffer | ||
17802 | |||
17803 | var Base = require('cipher-base') | ||
17804 | |||
17805 | var ZEROS = Buffer.alloc(128) | ||
17806 | var blocksize = 64 | ||
17807 | |||
17808 | function Hmac (alg, key) { | ||
17809 | Base.call(this, 'digest') | ||
17810 | if (typeof key === 'string') { | ||
17811 | key = Buffer.from(key) | ||
17812 | } | ||
17813 | |||
17814 | this._alg = alg | ||
17815 | this._key = key | ||
17816 | |||
17817 | if (key.length > blocksize) { | ||
17818 | key = alg(key) | ||
17819 | } else if (key.length < blocksize) { | ||
17820 | key = Buffer.concat([key, ZEROS], blocksize) | ||
17821 | } | ||
17822 | |||
17823 | var ipad = this._ipad = Buffer.allocUnsafe(blocksize) | ||
17824 | var opad = this._opad = Buffer.allocUnsafe(blocksize) | ||
17825 | |||
17826 | for (var i = 0; i < blocksize; i++) { | ||
17827 | ipad[i] = key[i] ^ 0x36 | ||
17828 | opad[i] = key[i] ^ 0x5C | ||
17829 | } | ||
17830 | |||
17831 | this._hash = [ipad] | ||
17832 | } | ||
17833 | |||
17834 | inherits(Hmac, Base) | ||
17835 | |||
17836 | Hmac.prototype._update = function (data) { | ||
17837 | this._hash.push(data) | ||
17838 | } | ||
17839 | |||
17840 | Hmac.prototype._final = function () { | ||
17841 | var h = this._alg(Buffer.concat(this._hash)) | ||
17842 | return this._alg(Buffer.concat([this._opad, h])) | ||
17843 | } | ||
17844 | module.exports = Hmac | ||
17845 | |||
17846 | },{"cipher-base":108,"inherits":163,"safe-buffer":247}],116:[function(require,module,exports){ | ||
17847 | 'use strict' | ||
17848 | |||
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') | ||
17852 | |||
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 () { | ||
17857 | return hashes | ||
17858 | } | ||
17859 | |||
17860 | var p = require('pbkdf2') | ||
17861 | exports.pbkdf2 = p.pbkdf2 | ||
17862 | exports.pbkdf2Sync = p.pbkdf2Sync | ||
17863 | |||
17864 | var aes = require('browserify-cipher') | ||
17865 | |||
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 | ||
17876 | |||
17877 | var dh = require('diffie-hellman') | ||
17878 | |||
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 | ||
17884 | |||
17885 | var sign = require('browserify-sign') | ||
17886 | |||
17887 | exports.createSign = sign.createSign | ||
17888 | exports.Sign = sign.Sign | ||
17889 | exports.createVerify = sign.createVerify | ||
17890 | exports.Verify = sign.Verify | ||
17891 | |||
17892 | exports.createECDH = require('create-ecdh') | ||
17893 | |||
17894 | var publicEncrypt = require('public-encrypt') | ||
17895 | |||
17896 | exports.publicEncrypt = publicEncrypt.publicEncrypt | ||
17897 | exports.privateEncrypt = publicEncrypt.privateEncrypt | ||
17898 | exports.publicDecrypt = publicEncrypt.publicDecrypt | ||
17899 | exports.privateDecrypt = publicEncrypt.privateDecrypt | ||
17900 | |||
17901 | // the least I can do is make error messages for the rest of the node.js/crypto api. | ||
17902 | // ;[ | ||
17903 | // 'createCredentials' | ||
17904 | // ].forEach(function (name) { | ||
17905 | // exports[name] = function () { | ||
17906 | // throw new Error([ | ||
17907 | // 'sorry, ' + name + ' is not implemented yet', | ||
17908 | // 'we accept pull requests', | ||
17909 | // 'https://github.com/crypto-browserify/crypto-browserify' | ||
17910 | // ].join('\n')) | ||
17911 | // } | ||
17912 | // }) | ||
17913 | |||
17914 | var rf = require('randomfill') | ||
17915 | |||
17916 | exports.randomFill = rf.randomFill | ||
17917 | exports.randomFillSync = rf.randomFillSync | ||
17918 | |||
17919 | exports.createCredentials = function () { | ||
17920 | throw new Error([ | ||
17921 | 'sorry, createCredentials is not implemented yet', | ||
17922 | 'we accept pull requests', | ||
17923 | 'https://github.com/crypto-browserify/crypto-browserify' | ||
17924 | ].join('\n')) | ||
17925 | } | ||
17926 | |||
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, | ||
17932 | 'NPN_ENABLED': 1, | ||
17933 | 'ALPN_ENABLED': 1, | ||
17934 | 'RSA_PKCS1_PADDING': 1, | ||
17935 | 'RSA_SSLV23_PADDING': 2, | ||
17936 | 'RSA_NO_PADDING': 3, | ||
17937 | 'RSA_PKCS1_OAEP_PADDING': 4, | ||
17938 | 'RSA_X931_PADDING': 5, | ||
17939 | 'RSA_PKCS1_PSS_PADDING': 6, | ||
17940 | 'POINT_CONVERSION_COMPRESSED': 2, | ||
17941 | 'POINT_CONVERSION_UNCOMPRESSED': 4, | ||
17942 | 'POINT_CONVERSION_HYBRID': 6 | ||
17943 | } | ||
17944 | |||
17945 | },{"browserify-cipher":95,"browserify-sign":102,"browserify-sign/algos":99,"create-ecdh":110,"create-hash":111,"create-hmac":114,"diffie-hellman":123,"pbkdf2":184,"public-encrypt":225,"randombytes":231,"randomfill":232}],117:[function(require,module,exports){ | ||
17946 | 'use strict'; | ||
17947 | |||
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'); | ||
17953 | |||
17954 | },{"./des/cbc":118,"./des/cipher":119,"./des/des":120,"./des/ede":121,"./des/utils":122}],118:[function(require,module,exports){ | ||
17955 | 'use strict'; | ||
17956 | |||
17957 | var assert = require('minimalistic-assert'); | ||
17958 | var inherits = require('inherits'); | ||
17959 | |||
17960 | var proto = {}; | ||
17961 | |||
17962 | function CBCState(iv) { | ||
17963 | assert.equal(iv.length, 8, 'Invalid IV length'); | ||
17964 | |||
17965 | this.iv = new Array(8); | ||
17966 | for (var i = 0; i < this.iv.length; i++) | ||
17967 | this.iv[i] = iv[i]; | ||
17968 | } | ||
17969 | |||
17970 | function instantiate(Base) { | ||
17971 | function CBC(options) { | ||
17972 | Base.call(this, options); | ||
17973 | this._cbcInit(); | ||
17974 | } | ||
17975 | inherits(CBC, Base); | ||
17976 | |||
17977 | var keys = Object.keys(proto); | ||
17978 | for (var i = 0; i < keys.length; i++) { | ||
17979 | var key = keys[i]; | ||
17980 | CBC.prototype[key] = proto[key]; | ||
17981 | } | ||
17982 | |||
17983 | CBC.create = function create(options) { | ||
17984 | return new CBC(options); | ||
17985 | }; | ||
17986 | |||
17987 | return CBC; | ||
17988 | } | ||
17989 | |||
17990 | exports.instantiate = instantiate; | ||
17991 | |||
17992 | proto._cbcInit = function _cbcInit() { | ||
17993 | var state = new CBCState(this.options.iv); | ||
17994 | this._cbcState = state; | ||
17995 | }; | ||
17996 | |||
17997 | proto._update = function _update(inp, inOff, out, outOff) { | ||
17998 | var state = this._cbcState; | ||
17999 | var superProto = this.constructor.super_.prototype; | ||
18000 | |||
18001 | var iv = state.iv; | ||
18002 | if (this.type === 'encrypt') { | ||
18003 | for (var i = 0; i < this.blockSize; i++) | ||
18004 | iv[i] ^= inp[inOff + i]; | ||
18005 | |||
18006 | superProto._update.call(this, iv, 0, out, outOff); | ||
18007 | |||
18008 | for (var i = 0; i < this.blockSize; i++) | ||
18009 | iv[i] = out[outOff + i]; | ||
18010 | } else { | ||
18011 | superProto._update.call(this, inp, inOff, out, outOff); | ||
18012 | |||
18013 | for (var i = 0; i < this.blockSize; i++) | ||
18014 | out[outOff + i] ^= iv[i]; | ||
18015 | |||
18016 | for (var i = 0; i < this.blockSize; i++) | ||
18017 | iv[i] = inp[inOff + i]; | ||
18018 | } | ||
18019 | }; | ||
18020 | |||
18021 | },{"inherits":163,"minimalistic-assert":176}],119:[function(require,module,exports){ | ||
18022 | 'use strict'; | ||
18023 | |||
18024 | var assert = require('minimalistic-assert'); | ||
18025 | |||
18026 | function Cipher(options) { | ||
18027 | this.options = options; | ||
18028 | |||
18029 | this.type = this.options.type; | ||
18030 | this.blockSize = 8; | ||
18031 | this._init(); | ||
18032 | |||
18033 | this.buffer = new Array(this.blockSize); | ||
18034 | this.bufferOff = 0; | ||
18035 | } | ||
18036 | module.exports = Cipher; | ||
18037 | |||
18038 | Cipher.prototype._init = function _init() { | ||
18039 | // Might be overrided | ||
18040 | }; | ||
18041 | |||
18042 | Cipher.prototype.update = function update(data) { | ||
18043 | if (data.length === 0) | ||
18044 | return []; | ||
18045 | |||
18046 | if (this.type === 'decrypt') | ||
18047 | return this._updateDecrypt(data); | ||
18048 | else | ||
18049 | return this._updateEncrypt(data); | ||
18050 | }; | ||
18051 | |||
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; | ||
18058 | |||
18059 | // Shift next | ||
18060 | return min; | ||
18061 | }; | ||
18062 | |||
18063 | Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { | ||
18064 | this._update(this.buffer, 0, out, off); | ||
18065 | this.bufferOff = 0; | ||
18066 | return this.blockSize; | ||
18067 | }; | ||
18068 | |||
18069 | Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { | ||
18070 | var inputOff = 0; | ||
18071 | var outputOff = 0; | ||
18072 | |||
18073 | var count = ((this.bufferOff + data.length) / this.blockSize) | 0; | ||
18074 | var out = new Array(count * this.blockSize); | ||
18075 | |||
18076 | if (this.bufferOff !== 0) { | ||
18077 | inputOff += this._buffer(data, inputOff); | ||
18078 | |||
18079 | if (this.bufferOff === this.buffer.length) | ||
18080 | outputOff += this._flushBuffer(out, outputOff); | ||
18081 | } | ||
18082 | |||
18083 | // Write blocks | ||
18084 | var max = data.length - ((data.length - inputOff) % this.blockSize); | ||
18085 | for (; inputOff < max; inputOff += this.blockSize) { | ||
18086 | this._update(data, inputOff, out, outputOff); | ||
18087 | outputOff += this.blockSize; | ||
18088 | } | ||
18089 | |||
18090 | // Queue rest | ||
18091 | for (; inputOff < data.length; inputOff++, this.bufferOff++) | ||
18092 | this.buffer[this.bufferOff] = data[inputOff]; | ||
18093 | |||
18094 | return out; | ||
18095 | }; | ||
18096 | |||
18097 | Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { | ||
18098 | var inputOff = 0; | ||
18099 | var outputOff = 0; | ||
18100 | |||
18101 | var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; | ||
18102 | var out = new Array(count * this.blockSize); | ||
18103 | |||
18104 | // TODO(indutny): optimize it, this is far from optimal | ||
18105 | for (; count > 0; count--) { | ||
18106 | inputOff += this._buffer(data, inputOff); | ||
18107 | outputOff += this._flushBuffer(out, outputOff); | ||
18108 | } | ||
18109 | |||
18110 | // Buffer rest of the input | ||
18111 | inputOff += this._buffer(data, inputOff); | ||
18112 | |||
18113 | return out; | ||
18114 | }; | ||
18115 | |||
18116 | Cipher.prototype.final = function final(buffer) { | ||
18117 | var first; | ||
18118 | if (buffer) | ||
18119 | first = this.update(buffer); | ||
18120 | |||
18121 | var last; | ||
18122 | if (this.type === 'encrypt') | ||
18123 | last = this._finalEncrypt(); | ||
18124 | else | ||
18125 | last = this._finalDecrypt(); | ||
18126 | |||
18127 | if (first) | ||
18128 | return first.concat(last); | ||
18129 | else | ||
18130 | return last; | ||
18131 | }; | ||
18132 | |||
18133 | Cipher.prototype._pad = function _pad(buffer, off) { | ||
18134 | if (off === 0) | ||
18135 | return false; | ||
18136 | |||
18137 | while (off < buffer.length) | ||
18138 | buffer[off++] = 0; | ||
18139 | |||
18140 | return true; | ||
18141 | }; | ||
18142 | |||
18143 | Cipher.prototype._finalEncrypt = function _finalEncrypt() { | ||
18144 | if (!this._pad(this.buffer, this.bufferOff)) | ||
18145 | return []; | ||
18146 | |||
18147 | var out = new Array(this.blockSize); | ||
18148 | this._update(this.buffer, 0, out, 0); | ||
18149 | return out; | ||
18150 | }; | ||
18151 | |||
18152 | Cipher.prototype._unpad = function _unpad(buffer) { | ||
18153 | return buffer; | ||
18154 | }; | ||
18155 | |||
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); | ||
18160 | |||
18161 | return this._unpad(out); | ||
18162 | }; | ||
18163 | |||
18164 | },{"minimalistic-assert":176}],120:[function(require,module,exports){ | ||
18165 | 'use strict'; | ||
18166 | |||
18167 | var assert = require('minimalistic-assert'); | ||
18168 | var inherits = require('inherits'); | ||
18169 | |||
18170 | var des = require('../des'); | ||
18171 | var utils = des.utils; | ||
18172 | var Cipher = des.Cipher; | ||
18173 | |||
18174 | function DESState() { | ||
18175 | this.tmp = new Array(2); | ||
18176 | this.keys = null; | ||
18177 | } | ||
18178 | |||
18179 | function DES(options) { | ||
18180 | Cipher.call(this, options); | ||
18181 | |||
18182 | var state = new DESState(); | ||
18183 | this._desState = state; | ||
18184 | |||
18185 | this.deriveKeys(state, options.key); | ||
18186 | } | ||
18187 | inherits(DES, Cipher); | ||
18188 | module.exports = DES; | ||
18189 | |||
18190 | DES.create = function create(options) { | ||
18191 | return new DES(options); | ||
18192 | }; | ||
18193 | |||
18194 | var shiftTable = [ | ||
18195 | 1, 1, 2, 2, 2, 2, 2, 2, | ||
18196 | 1, 2, 2, 2, 2, 2, 2, 1 | ||
18197 | ]; | ||
18198 | |||
18199 | DES.prototype.deriveKeys = function deriveKeys(state, key) { | ||
18200 | state.keys = new Array(16 * 2); | ||
18201 | |||
18202 | assert.equal(key.length, this.blockSize, 'Invalid key length'); | ||
18203 | |||
18204 | var kL = utils.readUInt32BE(key, 0); | ||
18205 | var kR = utils.readUInt32BE(key, 4); | ||
18206 | |||
18207 | utils.pc1(kL, kR, state.tmp, 0); | ||
18208 | kL = state.tmp[0]; | ||
18209 | kR = state.tmp[1]; | ||
18210 | for (var i = 0; i < state.keys.length; i += 2) { | ||
18211 | var shift = shiftTable[i >>> 1]; | ||
18212 | kL = utils.r28shl(kL, shift); | ||
18213 | kR = utils.r28shl(kR, shift); | ||
18214 | utils.pc2(kL, kR, state.keys, i); | ||
18215 | } | ||
18216 | }; | ||
18217 | |||
18218 | DES.prototype._update = function _update(inp, inOff, out, outOff) { | ||
18219 | var state = this._desState; | ||
18220 | |||
18221 | var l = utils.readUInt32BE(inp, inOff); | ||
18222 | var r = utils.readUInt32BE(inp, inOff + 4); | ||
18223 | |||
18224 | // Initial Permutation | ||
18225 | utils.ip(l, r, state.tmp, 0); | ||
18226 | l = state.tmp[0]; | ||
18227 | r = state.tmp[1]; | ||
18228 | |||
18229 | if (this.type === 'encrypt') | ||
18230 | this._encrypt(state, l, r, state.tmp, 0); | ||
18231 | else | ||
18232 | this._decrypt(state, l, r, state.tmp, 0); | ||
18233 | |||
18234 | l = state.tmp[0]; | ||
18235 | r = state.tmp[1]; | ||
18236 | |||
18237 | utils.writeUInt32BE(out, l, outOff); | ||
18238 | utils.writeUInt32BE(out, r, outOff + 4); | ||
18239 | }; | ||
18240 | |||
18241 | DES.prototype._pad = function _pad(buffer, off) { | ||
18242 | var value = buffer.length - off; | ||
18243 | for (var i = off; i < buffer.length; i++) | ||
18244 | buffer[i] = value; | ||
18245 | |||
18246 | return true; | ||
18247 | }; | ||
18248 | |||
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); | ||
18253 | |||
18254 | return buffer.slice(0, buffer.length - pad); | ||
18255 | }; | ||
18256 | |||
18257 | DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { | ||
18258 | var l = lStart; | ||
18259 | var r = rStart; | ||
18260 | |||
18261 | // Apply f() x16 times | ||
18262 | for (var i = 0; i < state.keys.length; i += 2) { | ||
18263 | var keyL = state.keys[i]; | ||
18264 | var keyR = state.keys[i + 1]; | ||
18265 | |||
18266 | // f(r, k) | ||
18267 | utils.expand(r, state.tmp, 0); | ||
18268 | |||
18269 | keyL ^= state.tmp[0]; | ||
18270 | keyR ^= state.tmp[1]; | ||
18271 | var s = utils.substitute(keyL, keyR); | ||
18272 | var f = utils.permute(s); | ||
18273 | |||
18274 | var t = r; | ||
18275 | r = (l ^ f) >>> 0; | ||
18276 | l = t; | ||
18277 | } | ||
18278 | |||
18279 | // Reverse Initial Permutation | ||
18280 | utils.rip(r, l, out, off); | ||
18281 | }; | ||
18282 | |||
18283 | DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { | ||
18284 | var l = rStart; | ||
18285 | var r = lStart; | ||
18286 | |||
18287 | // Apply f() x16 times | ||
18288 | for (var i = state.keys.length - 2; i >= 0; i -= 2) { | ||
18289 | var keyL = state.keys[i]; | ||
18290 | var keyR = state.keys[i + 1]; | ||
18291 | |||
18292 | // f(r, k) | ||
18293 | utils.expand(l, state.tmp, 0); | ||
18294 | |||
18295 | keyL ^= state.tmp[0]; | ||
18296 | keyR ^= state.tmp[1]; | ||
18297 | var s = utils.substitute(keyL, keyR); | ||
18298 | var f = utils.permute(s); | ||
18299 | |||
18300 | var t = l; | ||
18301 | l = (r ^ f) >>> 0; | ||
18302 | r = t; | ||
18303 | } | ||
18304 | |||
18305 | // Reverse Initial Permutation | ||
18306 | utils.rip(l, r, out, off); | ||
18307 | }; | ||
18308 | |||
18309 | },{"../des":117,"inherits":163,"minimalistic-assert":176}],121:[function(require,module,exports){ | ||
18310 | 'use strict'; | ||
18311 | |||
18312 | var assert = require('minimalistic-assert'); | ||
18313 | var inherits = require('inherits'); | ||
18314 | |||
18315 | var des = require('../des'); | ||
18316 | var Cipher = des.Cipher; | ||
18317 | var DES = des.DES; | ||
18318 | |||
18319 | function EDEState(type, key) { | ||
18320 | assert.equal(key.length, 24, 'Invalid key length'); | ||
18321 | |||
18322 | var k1 = key.slice(0, 8); | ||
18323 | var k2 = key.slice(8, 16); | ||
18324 | var k3 = key.slice(16, 24); | ||
18325 | |||
18326 | if (type === 'encrypt') { | ||
18327 | this.ciphers = [ | ||
18328 | DES.create({ type: 'encrypt', key: k1 }), | ||
18329 | DES.create({ type: 'decrypt', key: k2 }), | ||
18330 | DES.create({ type: 'encrypt', key: k3 }) | ||
18331 | ]; | ||
18332 | } else { | ||
18333 | this.ciphers = [ | ||
18334 | DES.create({ type: 'decrypt', key: k3 }), | ||
18335 | DES.create({ type: 'encrypt', key: k2 }), | ||
18336 | DES.create({ type: 'decrypt', key: k1 }) | ||
18337 | ]; | ||
18338 | } | ||
18339 | } | ||
18340 | |||
18341 | function EDE(options) { | ||
18342 | Cipher.call(this, options); | ||
18343 | |||
18344 | var state = new EDEState(this.type, this.options.key); | ||
18345 | this._edeState = state; | ||
18346 | } | ||
18347 | inherits(EDE, Cipher); | ||
18348 | |||
18349 | module.exports = EDE; | ||
18350 | |||
18351 | EDE.create = function create(options) { | ||
18352 | return new EDE(options); | ||
18353 | }; | ||
18354 | |||
18355 | EDE.prototype._update = function _update(inp, inOff, out, outOff) { | ||
18356 | var state = this._edeState; | ||
18357 | |||
18358 | state.ciphers[0]._update(inp, inOff, out, outOff); | ||
18359 | state.ciphers[1]._update(out, outOff, out, outOff); | ||
18360 | state.ciphers[2]._update(out, outOff, out, outOff); | ||
18361 | }; | ||
18362 | |||
18363 | EDE.prototype._pad = DES.prototype._pad; | ||
18364 | EDE.prototype._unpad = DES.prototype._unpad; | ||
18365 | |||
18366 | },{"../des":117,"inherits":163,"minimalistic-assert":176}],122:[function(require,module,exports){ | ||
18367 | 'use strict'; | ||
18368 | |||
18369 | exports.readUInt32BE = function readUInt32BE(bytes, off) { | ||
18370 | var res = (bytes[0 + off] << 24) | | ||
18371 | (bytes[1 + off] << 16) | | ||
18372 | (bytes[2 + off] << 8) | | ||
18373 | bytes[3 + off]; | ||
18374 | return res >>> 0; | ||
18375 | }; | ||
18376 | |||
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; | ||
18382 | }; | ||
18383 | |||
18384 | exports.ip = function ip(inL, inR, out, off) { | ||
18385 | var outL = 0; | ||
18386 | var outR = 0; | ||
18387 | |||
18388 | for (var i = 6; i >= 0; i -= 2) { | ||
18389 | for (var j = 0; j <= 24; j += 8) { | ||
18390 | outL <<= 1; | ||
18391 | outL |= (inR >>> (j + i)) & 1; | ||
18392 | } | ||
18393 | for (var j = 0; j <= 24; j += 8) { | ||
18394 | outL <<= 1; | ||
18395 | outL |= (inL >>> (j + i)) & 1; | ||
18396 | } | ||
18397 | } | ||
18398 | |||
18399 | for (var i = 6; i >= 0; i -= 2) { | ||
18400 | for (var j = 1; j <= 25; j += 8) { | ||
18401 | outR <<= 1; | ||
18402 | outR |= (inR >>> (j + i)) & 1; | ||
18403 | } | ||
18404 | for (var j = 1; j <= 25; j += 8) { | ||
18405 | outR <<= 1; | ||
18406 | outR |= (inL >>> (j + i)) & 1; | ||
18407 | } | ||
18408 | } | ||
18409 | |||
18410 | out[off + 0] = outL >>> 0; | ||
18411 | out[off + 1] = outR >>> 0; | ||
18412 | }; | ||
18413 | |||
18414 | exports.rip = function rip(inL, inR, out, off) { | ||
18415 | var outL = 0; | ||
18416 | var outR = 0; | ||
18417 | |||
18418 | for (var i = 0; i < 4; i++) { | ||
18419 | for (var j = 24; j >= 0; j -= 8) { | ||
18420 | outL <<= 1; | ||
18421 | outL |= (inR >>> (j + i)) & 1; | ||
18422 | outL <<= 1; | ||
18423 | outL |= (inL >>> (j + i)) & 1; | ||
18424 | } | ||
18425 | } | ||
18426 | for (var i = 4; i < 8; i++) { | ||
18427 | for (var j = 24; j >= 0; j -= 8) { | ||
18428 | outR <<= 1; | ||
18429 | outR |= (inR >>> (j + i)) & 1; | ||
18430 | outR <<= 1; | ||
18431 | outR |= (inL >>> (j + i)) & 1; | ||
18432 | } | ||
18433 | } | ||
18434 | |||
18435 | out[off + 0] = outL >>> 0; | ||
18436 | out[off + 1] = outR >>> 0; | ||
18437 | }; | ||
18438 | |||
18439 | exports.pc1 = function pc1(inL, inR, out, off) { | ||
18440 | var outL = 0; | ||
18441 | var outR = 0; | ||
18442 | |||
18443 | // 7, 15, 23, 31, 39, 47, 55, 63 | ||
18444 | // 6, 14, 22, 30, 39, 47, 55, 63 | ||
18445 | // 5, 13, 21, 29, 39, 47, 55, 63 | ||
18446 | // 4, 12, 20, 28 | ||
18447 | for (var i = 7; i >= 5; i--) { | ||
18448 | for (var j = 0; j <= 24; j += 8) { | ||
18449 | outL <<= 1; | ||
18450 | outL |= (inR >> (j + i)) & 1; | ||
18451 | } | ||
18452 | for (var j = 0; j <= 24; j += 8) { | ||
18453 | outL <<= 1; | ||
18454 | outL |= (inL >> (j + i)) & 1; | ||
18455 | } | ||
18456 | } | ||
18457 | for (var j = 0; j <= 24; j += 8) { | ||
18458 | outL <<= 1; | ||
18459 | outL |= (inR >> (j + i)) & 1; | ||
18460 | } | ||
18461 | |||
18462 | // 1, 9, 17, 25, 33, 41, 49, 57 | ||
18463 | // 2, 10, 18, 26, 34, 42, 50, 58 | ||
18464 | // 3, 11, 19, 27, 35, 43, 51, 59 | ||
18465 | // 36, 44, 52, 60 | ||
18466 | for (var i = 1; i <= 3; i++) { | ||
18467 | for (var j = 0; j <= 24; j += 8) { | ||
18468 | outR <<= 1; | ||
18469 | outR |= (inR >> (j + i)) & 1; | ||
18470 | } | ||
18471 | for (var j = 0; j <= 24; j += 8) { | ||
18472 | outR <<= 1; | ||
18473 | outR |= (inL >> (j + i)) & 1; | ||
18474 | } | ||
18475 | } | ||
18476 | for (var j = 0; j <= 24; j += 8) { | ||
18477 | outR <<= 1; | ||
18478 | outR |= (inL >> (j + i)) & 1; | ||
18479 | } | ||
18480 | |||
18481 | out[off + 0] = outL >>> 0; | ||
18482 | out[off + 1] = outR >>> 0; | ||
18483 | }; | ||
18484 | |||
18485 | exports.r28shl = function r28shl(num, shift) { | ||
18486 | return ((num << shift) & 0xfffffff) | (num >>> (28 - shift)); | ||
18487 | }; | ||
18488 | |||
18489 | var pc2table = [ | ||
18490 | // inL => outL | ||
18491 | 14, 11, 17, 4, 27, 23, 25, 0, | ||
18492 | 13, 22, 7, 18, 5, 9, 16, 24, | ||
18493 | 2, 20, 12, 21, 1, 8, 15, 26, | ||
18494 | |||
18495 | // inR => outR | ||
18496 | 15, 4, 25, 19, 9, 1, 26, 16, | ||
18497 | 5, 11, 23, 8, 12, 7, 17, 0, | ||
18498 | 22, 3, 10, 14, 6, 20, 27, 24 | ||
18499 | ]; | ||
18500 | |||
18501 | exports.pc2 = function pc2(inL, inR, out, off) { | ||
18502 | var outL = 0; | ||
18503 | var outR = 0; | ||
18504 | |||
18505 | var len = pc2table.length >>> 1; | ||
18506 | for (var i = 0; i < len; i++) { | ||
18507 | outL <<= 1; | ||
18508 | outL |= (inL >>> pc2table[i]) & 0x1; | ||
18509 | } | ||
18510 | for (var i = len; i < pc2table.length; i++) { | ||
18511 | outR <<= 1; | ||
18512 | outR |= (inR >>> pc2table[i]) & 0x1; | ||
18513 | } | ||
18514 | |||
18515 | out[off + 0] = outL >>> 0; | ||
18516 | out[off + 1] = outR >>> 0; | ||
18517 | }; | ||
18518 | |||
18519 | exports.expand = function expand(r, out, off) { | ||
18520 | var outL = 0; | ||
18521 | var outR = 0; | ||
18522 | |||
18523 | outL = ((r & 1) << 5) | (r >>> 27); | ||
18524 | for (var i = 23; i >= 15; i -= 4) { | ||
18525 | outL <<= 6; | ||
18526 | outL |= (r >>> i) & 0x3f; | ||
18527 | } | ||
18528 | for (var i = 11; i >= 3; i -= 4) { | ||
18529 | outR |= (r >>> i) & 0x3f; | ||
18530 | outR <<= 6; | ||
18531 | } | ||
18532 | outR |= ((r & 0x1f) << 1) | (r >>> 31); | ||
18533 | |||
18534 | out[off + 0] = outL >>> 0; | ||
18535 | out[off + 1] = outR >>> 0; | ||
18536 | }; | ||
18537 | |||
18538 | var sTable = [ | ||
18539 | 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, | ||
18540 | 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, | ||
18541 | 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, | ||
18542 | 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, | ||
18543 | |||
18544 | 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, | ||
18545 | 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, | ||
18546 | 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, | ||
18547 | 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, | ||
18548 | |||
18549 | 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, | ||
18550 | 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, | ||
18551 | 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, | ||
18552 | 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, | ||
18553 | |||
18554 | 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, | ||
18555 | 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, | ||
18556 | 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, | ||
18557 | 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, | ||
18558 | |||
18559 | 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, | ||
18560 | 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, | ||
18561 | 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, | ||
18562 | 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, | ||
18563 | |||
18564 | 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, | ||
18565 | 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, | ||
18566 | 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, | ||
18567 | 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, | ||
18568 | |||
18569 | 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, | ||
18570 | 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, | ||
18571 | 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, | ||
18572 | 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, | ||
18573 | |||
18574 | 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, | ||
18575 | 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, | ||
18576 | 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, | ||
18577 | 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 | ||
18578 | ]; | ||
18579 | |||
18580 | exports.substitute = function substitute(inL, inR) { | ||
18581 | var out = 0; | ||
18582 | for (var i = 0; i < 4; i++) { | ||
18583 | var b = (inL >>> (18 - i * 6)) & 0x3f; | ||
18584 | var sb = sTable[i * 0x40 + b]; | ||
18585 | |||
18586 | out <<= 4; | ||
18587 | out |= sb; | ||
18588 | } | ||
18589 | for (var i = 0; i < 4; i++) { | ||
18590 | var b = (inR >>> (18 - i * 6)) & 0x3f; | ||
18591 | var sb = sTable[4 * 0x40 + i * 0x40 + b]; | ||
18592 | |||
18593 | out <<= 4; | ||
18594 | out |= sb; | ||
18595 | } | ||
18596 | return out >>> 0; | ||
18597 | }; | ||
18598 | |||
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 | ||
18602 | ]; | ||
18603 | |||
18604 | exports.permute = function permute(num) { | ||
18605 | var out = 0; | ||
18606 | for (var i = 0; i < permuteTable.length; i++) { | ||
18607 | out <<= 1; | ||
18608 | out |= (num >>> permuteTable[i]) & 0x1; | ||
18609 | } | ||
18610 | return out >>> 0; | ||
18611 | }; | ||
18612 | |||
18613 | exports.padSplit = function padSplit(num, size, group) { | ||
18614 | var str = num.toString(2); | ||
18615 | while (str.length < size) | ||
18616 | str = '0' + str; | ||
18617 | |||
18618 | var out = []; | ||
18619 | for (var i = 0; i < size; i += group) | ||
18620 | out.push(str.slice(i, i + group)); | ||
18621 | return out.join(' '); | ||
18622 | }; | ||
18623 | |||
18624 | },{}],123:[function(require,module,exports){ | ||
18625 | (function (Buffer){ | ||
18626 | var generatePrime = require('./lib/generatePrime') | ||
18627 | var primes = require('./lib/primes.json') | ||
18628 | |||
18629 | var DH = require('./lib/dh') | ||
18630 | |||
18631 | function getDiffieHellman (mod) { | ||
18632 | var prime = new Buffer(primes[mod].prime, 'hex') | ||
18633 | var gen = new Buffer(primes[mod].gen, 'hex') | ||
18634 | |||
18635 | return new DH(prime, gen) | ||
18636 | } | ||
18637 | |||
18638 | var ENCODINGS = { | ||
18639 | 'binary': true, 'hex': true, 'base64': true | ||
18640 | } | ||
18641 | |||
18642 | function createDiffieHellman (prime, enc, generator, genc) { | ||
18643 | if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { | ||
18644 | return createDiffieHellman(prime, 'binary', enc, generator) | ||
18645 | } | ||
18646 | |||
18647 | enc = enc || 'binary' | ||
18648 | genc = genc || 'binary' | ||
18649 | generator = generator || new Buffer([2]) | ||
18650 | |||
18651 | if (!Buffer.isBuffer(generator)) { | ||
18652 | generator = new Buffer(generator, genc) | ||
18653 | } | ||
18654 | |||
18655 | if (typeof prime === 'number') { | ||
18656 | return new DH(generatePrime(prime, generator), generator, true) | ||
18657 | } | ||
18658 | |||
18659 | if (!Buffer.isBuffer(prime)) { | ||
18660 | prime = new Buffer(prime, enc) | ||
18661 | } | ||
18662 | |||
18663 | return new DH(prime, generator, true) | ||
18664 | } | ||
18665 | |||
18666 | exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman | ||
18667 | exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman | ||
18668 | |||
18669 | }).call(this,require("buffer").Buffer) | ||
18670 | },{"./lib/dh":124,"./lib/generatePrime":125,"./lib/primes.json":126,"buffer":107}],124:[function(require,module,exports){ | ||
18671 | (function (Buffer){ | ||
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; | ||
18683 | |||
18684 | function setPublicKey(pub, enc) { | ||
18685 | enc = enc || 'utf8'; | ||
18686 | if (!Buffer.isBuffer(pub)) { | ||
18687 | pub = new Buffer(pub, enc); | ||
18688 | } | ||
18689 | this._pub = new BN(pub); | ||
18690 | return this; | ||
18691 | } | ||
18692 | |||
18693 | function setPrivateKey(priv, enc) { | ||
18694 | enc = enc || 'utf8'; | ||
18695 | if (!Buffer.isBuffer(priv)) { | ||
18696 | priv = new Buffer(priv, enc); | ||
18697 | } | ||
18698 | this._priv = new BN(priv); | ||
18699 | return this; | ||
18700 | } | ||
18701 | |||
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]; | ||
18708 | } | ||
18709 | var error = 0; | ||
18710 | |||
18711 | if (prime.isEven() || | ||
18712 | !primes.simpleSieve || | ||
18713 | !primes.fermatTest(prime) || | ||
18714 | !millerRabin.test(prime)) { | ||
18715 | //not a prime so +1 | ||
18716 | error += 1; | ||
18717 | |||
18718 | if (gen === '02' || gen === '05') { | ||
18719 | // we'd be able to check the generator | ||
18720 | // it would fail so +8 | ||
18721 | error += 8; | ||
18722 | } else { | ||
18723 | //we wouldn't be able to test the generator | ||
18724 | // so +4 | ||
18725 | error += 4; | ||
18726 | } | ||
18727 | primeCache[hex] = error; | ||
18728 | return error; | ||
18729 | } | ||
18730 | if (!millerRabin.test(prime.shrn(1))) { | ||
18731 | //not a safe prime | ||
18732 | error += 2; | ||
18733 | } | ||
18734 | var rem; | ||
18735 | switch (gen) { | ||
18736 | case '02': | ||
18737 | if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { | ||
18738 | // unsuidable generator | ||
18739 | error += 8; | ||
18740 | } | ||
18741 | break; | ||
18742 | case '05': | ||
18743 | rem = prime.mod(TEN); | ||
18744 | if (rem.cmp(THREE) && rem.cmp(SEVEN)) { | ||
18745 | // prime mod 10 needs to equal 3 or 7 | ||
18746 | error += 8; | ||
18747 | } | ||
18748 | break; | ||
18749 | default: | ||
18750 | error += 4; | ||
18751 | } | ||
18752 | primeCache[hex] = error; | ||
18753 | return error; | ||
18754 | } | ||
18755 | |||
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; | ||
18764 | if (malleable) { | ||
18765 | this.setPublicKey = setPublicKey; | ||
18766 | this.setPrivateKey = setPrivateKey; | ||
18767 | } else { | ||
18768 | this._primeCode = 8; | ||
18769 | } | ||
18770 | } | ||
18771 | Object.defineProperty(DH.prototype, 'verifyError', { | ||
18772 | enumerable: true, | ||
18773 | get: function () { | ||
18774 | if (typeof this._primeCode !== 'number') { | ||
18775 | this._primeCode = checkPrime(this.__prime, this.__gen); | ||
18776 | } | ||
18777 | return this._primeCode; | ||
18778 | } | ||
18779 | }); | ||
18780 | DH.prototype.generateKeys = function () { | ||
18781 | if (!this._priv) { | ||
18782 | this._priv = new BN(randomBytes(this._primeLen)); | ||
18783 | } | ||
18784 | this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); | ||
18785 | return this.getPublicKey(); | ||
18786 | }; | ||
18787 | |||
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); | ||
18796 | front.fill(0); | ||
18797 | out = Buffer.concat([front, out]); | ||
18798 | } | ||
18799 | return out; | ||
18800 | }; | ||
18801 | |||
18802 | DH.prototype.getPublicKey = function getPublicKey(enc) { | ||
18803 | return formatReturnValue(this._pub, enc); | ||
18804 | }; | ||
18805 | |||
18806 | DH.prototype.getPrivateKey = function getPrivateKey(enc) { | ||
18807 | return formatReturnValue(this._priv, enc); | ||
18808 | }; | ||
18809 | |||
18810 | DH.prototype.getPrime = function (enc) { | ||
18811 | return formatReturnValue(this.__prime, enc); | ||
18812 | }; | ||
18813 | |||
18814 | DH.prototype.getGenerator = function (enc) { | ||
18815 | return formatReturnValue(this._gen, enc); | ||
18816 | }; | ||
18817 | |||
18818 | DH.prototype.setGenerator = function (gen, enc) { | ||
18819 | enc = enc || 'utf8'; | ||
18820 | if (!Buffer.isBuffer(gen)) { | ||
18821 | gen = new Buffer(gen, enc); | ||
18822 | } | ||
18823 | this.__gen = gen; | ||
18824 | this._gen = new BN(gen); | ||
18825 | return this; | ||
18826 | }; | ||
18827 | |||
18828 | function formatReturnValue(bn, enc) { | ||
18829 | var buf = new Buffer(bn.toArray()); | ||
18830 | if (!enc) { | ||
18831 | return buf; | ||
18832 | } else { | ||
18833 | return buf.toString(enc); | ||
18834 | } | ||
18835 | } | ||
18836 | |||
18837 | }).call(this,require("buffer").Buffer) | ||
18838 | },{"./generatePrime":125,"bn.js":75,"buffer":107,"miller-rabin":175,"randombytes":231}],125:[function(require,module,exports){ | ||
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); | ||
18858 | var primes = null; | ||
18859 | |||
18860 | function _getPrimes() { | ||
18861 | if (primes !== null) | ||
18862 | return primes; | ||
18863 | |||
18864 | var limit = 0x100000; | ||
18865 | var res = []; | ||
18866 | res[0] = 2; | ||
18867 | for (var i = 1, k = 3; k < limit; k += 2) { | ||
18868 | var sqrt = Math.ceil(Math.sqrt(k)); | ||
18869 | for (var j = 0; j < i && res[j] <= sqrt; j++) | ||
18870 | if (k % res[j] === 0) | ||
18871 | break; | ||
18872 | |||
18873 | if (i !== j && res[j] <= sqrt) | ||
18874 | continue; | ||
18875 | |||
18876 | res[i++] = k; | ||
18877 | } | ||
18878 | primes = res; | ||
18879 | return res; | ||
18880 | } | ||
18881 | |||
18882 | function simpleSieve(p) { | ||
18883 | var primes = _getPrimes(); | ||
18884 | |||
18885 | for (var i = 0; i < primes.length; i++) | ||
18886 | if (p.modn(primes[i]) === 0) { | ||
18887 | if (p.cmpn(primes[i]) === 0) { | ||
18888 | return true; | ||
18889 | } else { | ||
18890 | return false; | ||
18891 | } | ||
18892 | } | ||
18893 | |||
18894 | return true; | ||
18895 | } | ||
18896 | |||
18897 | function fermatTest(p) { | ||
18898 | var red = BN.mont(p); | ||
18899 | return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; | ||
18900 | } | ||
18901 | |||
18902 | function findPrime(bits, gen) { | ||
18903 | if (bits < 16) { | ||
18904 | // this is what openssl does | ||
18905 | if (gen === 2 || gen === 5) { | ||
18906 | return new BN([0x8c, 0x7b]); | ||
18907 | } else { | ||
18908 | return new BN([0x8c, 0x27]); | ||
18909 | } | ||
18910 | } | ||
18911 | gen = new BN(gen); | ||
18912 | |||
18913 | var num, n2; | ||
18914 | |||
18915 | while (true) { | ||
18916 | num = new BN(randomBytes(Math.ceil(bits / 8))); | ||
18917 | while (num.bitLength() > bits) { | ||
18918 | num.ishrn(1); | ||
18919 | } | ||
18920 | if (num.isEven()) { | ||
18921 | num.iadd(ONE); | ||
18922 | } | ||
18923 | if (!num.testn(1)) { | ||
18924 | num.iadd(TWO); | ||
18925 | } | ||
18926 | if (!gen.cmp(TWO)) { | ||
18927 | while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { | ||
18928 | num.iadd(FOUR); | ||
18929 | } | ||
18930 | } else if (!gen.cmp(FIVE)) { | ||
18931 | while (num.mod(TEN).cmp(THREE)) { | ||
18932 | num.iadd(FOUR); | ||
18933 | } | ||
18934 | } | ||
18935 | n2 = num.shrn(1); | ||
18936 | if (simpleSieve(n2) && simpleSieve(num) && | ||
18937 | fermatTest(n2) && fermatTest(num) && | ||
18938 | millerRabin.test(n2) && millerRabin.test(num)) { | ||
18939 | return num; | ||
18940 | } | ||
18941 | } | ||
18942 | |||
18943 | } | ||
18944 | |||
18945 | },{"bn.js":75,"miller-rabin":175,"randombytes":231}],126:[function(require,module,exports){ | ||
18946 | module.exports={ | ||
18947 | "modp1": { | ||
18948 | "gen": "02", | ||
18949 | "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" | ||
18950 | }, | ||
18951 | "modp2": { | ||
18952 | "gen": "02", | ||
18953 | "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" | ||
18954 | }, | ||
18955 | "modp5": { | ||
18956 | "gen": "02", | ||
18957 | "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" | ||
18958 | }, | ||
18959 | "modp14": { | ||
18960 | "gen": "02", | ||
18961 | "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" | ||
18962 | }, | ||
18963 | "modp15": { | ||
18964 | "gen": "02", | ||
18965 | "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" | ||
18966 | }, | ||
18967 | "modp16": { | ||
18968 | "gen": "02", | ||
18969 | "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" | ||
18970 | }, | ||
18971 | "modp17": { | ||
18972 | "gen": "02", | ||
18973 | "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" | ||
18974 | }, | ||
18975 | "modp18": { | ||
18976 | "gen": "02", | ||
18977 | "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" | ||
18978 | } | ||
18979 | } | ||
18980 | },{}],127:[function(require,module,exports){ | ||
18981 | 'use strict'; | ||
18982 | |||
18983 | var elliptic = exports; | ||
18984 | |||
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'); | ||
18990 | |||
18991 | // Protocols | ||
18992 | elliptic.ec = require('./elliptic/ec'); | ||
18993 | elliptic.eddsa = require('./elliptic/eddsa'); | ||
18994 | |||
18995 | },{"../package.json":142,"./elliptic/curve":130,"./elliptic/curves":133,"./elliptic/ec":134,"./elliptic/eddsa":137,"./elliptic/utils":141,"brorand":76}],128:[function(require,module,exports){ | ||
18996 | 'use strict'; | ||
18997 | |||
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; | ||
19004 | |||
19005 | function BaseCurve(type, conf) { | ||
19006 | this.type = type; | ||
19007 | this.p = new BN(conf.p, 16); | ||
19008 | |||
19009 | // Use Montgomery, when there is no fast reduction for the prime | ||
19010 | this.red = conf.prime ? BN.red(conf.prime) : BN.mont(this.p); | ||
19011 | |||
19012 | // Useful for many curves | ||
19013 | this.zero = new BN(0).toRed(this.red); | ||
19014 | this.one = new BN(1).toRed(this.red); | ||
19015 | this.two = new BN(2).toRed(this.red); | ||
19016 | |||
19017 | // Curve configuration, optional | ||
19018 | this.n = conf.n && new BN(conf.n, 16); | ||
19019 | this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); | ||
19020 | |||
19021 | // Temporary arrays | ||
19022 | this._wnafT1 = new Array(4); | ||
19023 | this._wnafT2 = new Array(4); | ||
19024 | this._wnafT3 = new Array(4); | ||
19025 | this._wnafT4 = new Array(4); | ||
19026 | |||
19027 | // Generalized Greg Maxwell's trick | ||
19028 | var adjustCount = this.n && this.p.div(this.n); | ||
19029 | if (!adjustCount || adjustCount.cmpn(100) > 0) { | ||
19030 | this.redN = null; | ||
19031 | } else { | ||
19032 | this._maxwellTrick = true; | ||
19033 | this.redN = this.n.toRed(this.red); | ||
19034 | } | ||
19035 | } | ||
19036 | module.exports = BaseCurve; | ||
19037 | |||
19038 | BaseCurve.prototype.point = function point() { | ||
19039 | throw new Error('Not implemented'); | ||
19040 | }; | ||
19041 | |||
19042 | BaseCurve.prototype.validate = function validate() { | ||
19043 | throw new Error('Not implemented'); | ||
19044 | }; | ||
19045 | |||
19046 | BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { | ||
19047 | assert(p.precomputed); | ||
19048 | var doubles = p._getDoubles(); | ||
19049 | |||
19050 | var naf = getNAF(k, 1); | ||
19051 | var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); | ||
19052 | I /= 3; | ||
19053 | |||
19054 | // Translate into more windowed form | ||
19055 | var repr = []; | ||
19056 | for (var j = 0; j < naf.length; j += doubles.step) { | ||
19057 | var nafW = 0; | ||
19058 | for (var k = j + doubles.step - 1; k >= j; k--) | ||
19059 | nafW = (nafW << 1) + naf[k]; | ||
19060 | repr.push(nafW); | ||
19061 | } | ||
19062 | |||
19063 | var a = this.jpoint(null, null, null); | ||
19064 | var b = this.jpoint(null, null, null); | ||
19065 | for (var i = I; i > 0; i--) { | ||
19066 | for (var j = 0; j < repr.length; j++) { | ||
19067 | var nafW = repr[j]; | ||
19068 | if (nafW === i) | ||
19069 | b = b.mixedAdd(doubles.points[j]); | ||
19070 | else if (nafW === -i) | ||
19071 | b = b.mixedAdd(doubles.points[j].neg()); | ||
19072 | } | ||
19073 | a = a.add(b); | ||
19074 | } | ||
19075 | return a.toP(); | ||
19076 | }; | ||
19077 | |||
19078 | BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { | ||
19079 | var w = 4; | ||
19080 | |||
19081 | // Precompute window | ||
19082 | var nafPoints = p._getNAFPoints(w); | ||
19083 | w = nafPoints.wnd; | ||
19084 | var wnd = nafPoints.points; | ||
19085 | |||
19086 | // Get NAF form | ||
19087 | var naf = getNAF(k, w); | ||
19088 | |||
19089 | // Add `this`*(N+1) for every w-NAF index | ||
19090 | var acc = this.jpoint(null, null, null); | ||
19091 | for (var i = naf.length - 1; i >= 0; i--) { | ||
19092 | // Count zeroes | ||
19093 | for (var k = 0; i >= 0 && naf[i] === 0; i--) | ||
19094 | k++; | ||
19095 | if (i >= 0) | ||
19096 | k++; | ||
19097 | acc = acc.dblp(k); | ||
19098 | |||
19099 | if (i < 0) | ||
19100 | break; | ||
19101 | var z = naf[i]; | ||
19102 | assert(z !== 0); | ||
19103 | if (p.type === 'affine') { | ||
19104 | // J +- P | ||
19105 | if (z > 0) | ||
19106 | acc = acc.mixedAdd(wnd[(z - 1) >> 1]); | ||
19107 | else | ||
19108 | acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); | ||
19109 | } else { | ||
19110 | // J +- J | ||
19111 | if (z > 0) | ||
19112 | acc = acc.add(wnd[(z - 1) >> 1]); | ||
19113 | else | ||
19114 | acc = acc.add(wnd[(-z - 1) >> 1].neg()); | ||
19115 | } | ||
19116 | } | ||
19117 | return p.type === 'affine' ? acc.toP() : acc; | ||
19118 | }; | ||
19119 | |||
19120 | BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, | ||
19121 | points, | ||
19122 | coeffs, | ||
19123 | len, | ||
19124 | jacobianResult) { | ||
19125 | var wndWidth = this._wnafT1; | ||
19126 | var wnd = this._wnafT2; | ||
19127 | var naf = this._wnafT3; | ||
19128 | |||
19129 | // Fill all arrays | ||
19130 | var max = 0; | ||
19131 | for (var i = 0; i < len; i++) { | ||
19132 | var p = points[i]; | ||
19133 | var nafPoints = p._getNAFPoints(defW); | ||
19134 | wndWidth[i] = nafPoints.wnd; | ||
19135 | wnd[i] = nafPoints.points; | ||
19136 | } | ||
19137 | |||
19138 | // Comb small window NAFs | ||
19139 | for (var i = len - 1; i >= 1; i -= 2) { | ||
19140 | var a = i - 1; | ||
19141 | var b = i; | ||
19142 | if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { | ||
19143 | naf[a] = getNAF(coeffs[a], wndWidth[a]); | ||
19144 | naf[b] = getNAF(coeffs[b], wndWidth[b]); | ||
19145 | max = Math.max(naf[a].length, max); | ||
19146 | max = Math.max(naf[b].length, max); | ||
19147 | continue; | ||
19148 | } | ||
19149 | |||
19150 | var comb = [ | ||
19151 | points[a], /* 1 */ | ||
19152 | null, /* 3 */ | ||
19153 | null, /* 5 */ | ||
19154 | points[b] /* 7 */ | ||
19155 | ]; | ||
19156 | |||
19157 | // Try to avoid Projective points, if possible | ||
19158 | if (points[a].y.cmp(points[b].y) === 0) { | ||
19159 | comb[1] = points[a].add(points[b]); | ||
19160 | comb[2] = points[a].toJ().mixedAdd(points[b].neg()); | ||
19161 | } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { | ||
19162 | comb[1] = points[a].toJ().mixedAdd(points[b]); | ||
19163 | comb[2] = points[a].add(points[b].neg()); | ||
19164 | } else { | ||
19165 | comb[1] = points[a].toJ().mixedAdd(points[b]); | ||
19166 | comb[2] = points[a].toJ().mixedAdd(points[b].neg()); | ||
19167 | } | ||
19168 | |||
19169 | var index = [ | ||
19170 | -3, /* -1 -1 */ | ||
19171 | -1, /* -1 0 */ | ||
19172 | -5, /* -1 1 */ | ||
19173 | -7, /* 0 -1 */ | ||
19174 | 0, /* 0 0 */ | ||
19175 | 7, /* 0 1 */ | ||
19176 | 5, /* 1 -1 */ | ||
19177 | 1, /* 1 0 */ | ||
19178 | 3 /* 1 1 */ | ||
19179 | ]; | ||
19180 | |||
19181 | var jsf = getJSF(coeffs[a], coeffs[b]); | ||
19182 | max = Math.max(jsf[0].length, max); | ||
19183 | naf[a] = new Array(max); | ||
19184 | naf[b] = new Array(max); | ||
19185 | for (var j = 0; j < max; j++) { | ||
19186 | var ja = jsf[0][j] | 0; | ||
19187 | var jb = jsf[1][j] | 0; | ||
19188 | |||
19189 | naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; | ||
19190 | naf[b][j] = 0; | ||
19191 | wnd[a] = comb; | ||
19192 | } | ||
19193 | } | ||
19194 | |||
19195 | var acc = this.jpoint(null, null, null); | ||
19196 | var tmp = this._wnafT4; | ||
19197 | for (var i = max; i >= 0; i--) { | ||
19198 | var k = 0; | ||
19199 | |||
19200 | while (i >= 0) { | ||
19201 | var zero = true; | ||
19202 | for (var j = 0; j < len; j++) { | ||
19203 | tmp[j] = naf[j][i] | 0; | ||
19204 | if (tmp[j] !== 0) | ||
19205 | zero = false; | ||
19206 | } | ||
19207 | if (!zero) | ||
19208 | break; | ||
19209 | k++; | ||
19210 | i--; | ||
19211 | } | ||
19212 | if (i >= 0) | ||
19213 | k++; | ||
19214 | acc = acc.dblp(k); | ||
19215 | if (i < 0) | ||
19216 | break; | ||
19217 | |||
19218 | for (var j = 0; j < len; j++) { | ||
19219 | var z = tmp[j]; | ||
19220 | var p; | ||
19221 | if (z === 0) | ||
19222 | continue; | ||
19223 | else if (z > 0) | ||
19224 | p = wnd[j][(z - 1) >> 1]; | ||
19225 | else if (z < 0) | ||
19226 | p = wnd[j][(-z - 1) >> 1].neg(); | ||
19227 | |||
19228 | if (p.type === 'affine') | ||
19229 | acc = acc.mixedAdd(p); | ||
19230 | else | ||
19231 | acc = acc.add(p); | ||
19232 | } | ||
19233 | } | ||
19234 | // Zeroify references | ||
19235 | for (var i = 0; i < len; i++) | ||
19236 | wnd[i] = null; | ||
19237 | |||
19238 | if (jacobianResult) | ||
19239 | return acc; | ||
19240 | else | ||
19241 | return acc.toP(); | ||
19242 | }; | ||
19243 | |||
19244 | function BasePoint(curve, type) { | ||
19245 | this.curve = curve; | ||
19246 | this.type = type; | ||
19247 | this.precomputed = null; | ||
19248 | } | ||
19249 | BaseCurve.BasePoint = BasePoint; | ||
19250 | |||
19251 | BasePoint.prototype.eq = function eq(/*other*/) { | ||
19252 | throw new Error('Not implemented'); | ||
19253 | }; | ||
19254 | |||
19255 | BasePoint.prototype.validate = function validate() { | ||
19256 | return this.curve.validate(this); | ||
19257 | }; | ||
19258 | |||
19259 | BaseCurve.prototype.decodePoint = function decodePoint(bytes, enc) { | ||
19260 | bytes = utils.toArray(bytes, enc); | ||
19261 | |||
19262 | var len = this.p.byteLength(); | ||
19263 | |||
19264 | // uncompressed, hybrid-odd, hybrid-even | ||
19265 | if ((bytes[0] === 0x04 || bytes[0] === 0x06 || bytes[0] === 0x07) && | ||
19266 | bytes.length - 1 === 2 * len) { | ||
19267 | if (bytes[0] === 0x06) | ||
19268 | assert(bytes[bytes.length - 1] % 2 === 0); | ||
19269 | else if (bytes[0] === 0x07) | ||
19270 | assert(bytes[bytes.length - 1] % 2 === 1); | ||
19271 | |||
19272 | var res = this.point(bytes.slice(1, 1 + len), | ||
19273 | bytes.slice(1 + len, 1 + 2 * len)); | ||
19274 | |||
19275 | return res; | ||
19276 | } else if ((bytes[0] === 0x02 || bytes[0] === 0x03) && | ||
19277 | bytes.length - 1 === len) { | ||
19278 | return this.pointFromX(bytes.slice(1, 1 + len), bytes[0] === 0x03); | ||
19279 | } | ||
19280 | throw new Error('Unknown point format'); | ||
19281 | }; | ||
19282 | |||
19283 | BasePoint.prototype.encodeCompressed = function encodeCompressed(enc) { | ||
19284 | return this.encode(enc, true); | ||
19285 | }; | ||
19286 | |||
19287 | BasePoint.prototype._encode = function _encode(compact) { | ||
19288 | var len = this.curve.p.byteLength(); | ||
19289 | var x = this.getX().toArray('be', len); | ||
19290 | |||
19291 | if (compact) | ||
19292 | return [ this.getY().isEven() ? 0x02 : 0x03 ].concat(x); | ||
19293 | |||
19294 | return [ 0x04 ].concat(x, this.getY().toArray('be', len)) ; | ||
19295 | }; | ||
19296 | |||
19297 | BasePoint.prototype.encode = function encode(enc, compact) { | ||
19298 | return utils.encode(this._encode(compact), enc); | ||
19299 | }; | ||
19300 | |||
19301 | BasePoint.prototype.precompute = function precompute(power) { | ||
19302 | if (this.precomputed) | ||
19303 | return this; | ||
19304 | |||
19305 | var precomputed = { | ||
19306 | doubles: null, | ||
19307 | naf: null, | ||
19308 | beta: null | ||
19309 | }; | ||
19310 | precomputed.naf = this._getNAFPoints(8); | ||
19311 | precomputed.doubles = this._getDoubles(4, power); | ||
19312 | precomputed.beta = this._getBeta(); | ||
19313 | this.precomputed = precomputed; | ||
19314 | |||
19315 | return this; | ||
19316 | }; | ||
19317 | |||
19318 | BasePoint.prototype._hasDoubles = function _hasDoubles(k) { | ||
19319 | if (!this.precomputed) | ||
19320 | return false; | ||
19321 | |||
19322 | var doubles = this.precomputed.doubles; | ||
19323 | if (!doubles) | ||
19324 | return false; | ||
19325 | |||
19326 | return doubles.points.length >= Math.ceil((k.bitLength() + 1) / doubles.step); | ||
19327 | }; | ||
19328 | |||
19329 | BasePoint.prototype._getDoubles = function _getDoubles(step, power) { | ||
19330 | if (this.precomputed && this.precomputed.doubles) | ||
19331 | return this.precomputed.doubles; | ||
19332 | |||
19333 | var doubles = [ this ]; | ||
19334 | var acc = this; | ||
19335 | for (var i = 0; i < power; i += step) { | ||
19336 | for (var j = 0; j < step; j++) | ||
19337 | acc = acc.dbl(); | ||
19338 | doubles.push(acc); | ||
19339 | } | ||
19340 | return { | ||
19341 | step: step, | ||
19342 | points: doubles | ||
19343 | }; | ||
19344 | }; | ||
19345 | |||
19346 | BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { | ||
19347 | if (this.precomputed && this.precomputed.naf) | ||
19348 | return this.precomputed.naf; | ||
19349 | |||
19350 | var res = [ this ]; | ||
19351 | var max = (1 << wnd) - 1; | ||
19352 | var dbl = max === 1 ? null : this.dbl(); | ||
19353 | for (var i = 1; i < max; i++) | ||
19354 | res[i] = res[i - 1].add(dbl); | ||
19355 | return { | ||
19356 | wnd: wnd, | ||
19357 | points: res | ||
19358 | }; | ||
19359 | }; | ||
19360 | |||
19361 | BasePoint.prototype._getBeta = function _getBeta() { | ||
19362 | return null; | ||
19363 | }; | ||
19364 | |||
19365 | BasePoint.prototype.dblp = function dblp(k) { | ||
19366 | var r = this; | ||
19367 | for (var i = 0; i < k; i++) | ||
19368 | r = r.dbl(); | ||
19369 | return r; | ||
19370 | }; | ||
19371 | |||
19372 | },{"../../elliptic":127,"bn.js":75}],129:[function(require,module,exports){ | ||
19373 | 'use strict'; | ||
19374 | |||
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; | ||
19380 | |||
19381 | var assert = elliptic.utils.assert; | ||
19382 | |||
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; | ||
19388 | |||
19389 | Base.call(this, 'edwards', conf); | ||
19390 | |||
19391 | this.a = new BN(conf.a, 16).umod(this.red.m); | ||
19392 | this.a = this.a.toRed(this.red); | ||
19393 | this.c = new BN(conf.c, 16).toRed(this.red); | ||
19394 | this.c2 = this.c.redSqr(); | ||
19395 | this.d = new BN(conf.d, 16).toRed(this.red); | ||
19396 | this.dd = this.d.redAdd(this.d); | ||
19397 | |||
19398 | assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); | ||
19399 | this.oneC = (conf.c | 0) === 1; | ||
19400 | } | ||
19401 | inherits(EdwardsCurve, Base); | ||
19402 | module.exports = EdwardsCurve; | ||
19403 | |||
19404 | EdwardsCurve.prototype._mulA = function _mulA(num) { | ||
19405 | if (this.mOneA) | ||
19406 | return num.redNeg(); | ||
19407 | else | ||
19408 | return this.a.redMul(num); | ||
19409 | }; | ||
19410 | |||
19411 | EdwardsCurve.prototype._mulC = function _mulC(num) { | ||
19412 | if (this.oneC) | ||
19413 | return num; | ||
19414 | else | ||
19415 | return this.c.redMul(num); | ||
19416 | }; | ||
19417 | |||
19418 | // Just for compatibility with Short curve | ||
19419 | EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { | ||
19420 | return this.point(x, y, z, t); | ||
19421 | }; | ||
19422 | |||
19423 | EdwardsCurve.prototype.pointFromX = function pointFromX(x, odd) { | ||
19424 | x = new BN(x, 16); | ||
19425 | if (!x.red) | ||
19426 | x = x.toRed(this.red); | ||
19427 | |||
19428 | var x2 = x.redSqr(); | ||
19429 | var rhs = this.c2.redSub(this.a.redMul(x2)); | ||
19430 | var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); | ||
19431 | |||
19432 | var y2 = rhs.redMul(lhs.redInvm()); | ||
19433 | var y = y2.redSqrt(); | ||
19434 | if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) | ||
19435 | throw new Error('invalid point'); | ||
19436 | |||
19437 | var isOdd = y.fromRed().isOdd(); | ||
19438 | if (odd && !isOdd || !odd && isOdd) | ||
19439 | y = y.redNeg(); | ||
19440 | |||
19441 | return this.point(x, y); | ||
19442 | }; | ||
19443 | |||
19444 | EdwardsCurve.prototype.pointFromY = function pointFromY(y, odd) { | ||
19445 | y = new BN(y, 16); | ||
19446 | if (!y.red) | ||
19447 | y = y.toRed(this.red); | ||
19448 | |||
19449 | // x^2 = (y^2 - 1) / (d y^2 + 1) | ||
19450 | var y2 = y.redSqr(); | ||
19451 | var lhs = y2.redSub(this.one); | ||
19452 | var rhs = y2.redMul(this.d).redAdd(this.one); | ||
19453 | var x2 = lhs.redMul(rhs.redInvm()); | ||
19454 | |||
19455 | if (x2.cmp(this.zero) === 0) { | ||
19456 | if (odd) | ||
19457 | throw new Error('invalid point'); | ||
19458 | else | ||
19459 | return this.point(this.zero, y); | ||
19460 | } | ||
19461 | |||
19462 | var x = x2.redSqrt(); | ||
19463 | if (x.redSqr().redSub(x2).cmp(this.zero) !== 0) | ||
19464 | throw new Error('invalid point'); | ||
19465 | |||
19466 | if (x.isOdd() !== odd) | ||
19467 | x = x.redNeg(); | ||
19468 | |||
19469 | return this.point(x, y); | ||
19470 | }; | ||
19471 | |||
19472 | EdwardsCurve.prototype.validate = function validate(point) { | ||
19473 | if (point.isInfinity()) | ||
19474 | return true; | ||
19475 | |||
19476 | // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) | ||
19477 | point.normalize(); | ||
19478 | |||
19479 | var x2 = point.x.redSqr(); | ||
19480 | var y2 = point.y.redSqr(); | ||
19481 | var lhs = x2.redMul(this.a).redAdd(y2); | ||
19482 | var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); | ||
19483 | |||
19484 | return lhs.cmp(rhs) === 0; | ||
19485 | }; | ||
19486 | |||
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; | ||
19494 | this.zOne = true; | ||
19495 | } else { | ||
19496 | this.x = new BN(x, 16); | ||
19497 | this.y = new BN(y, 16); | ||
19498 | this.z = z ? new BN(z, 16) : this.curve.one; | ||
19499 | this.t = t && new BN(t, 16); | ||
19500 | if (!this.x.red) | ||
19501 | this.x = this.x.toRed(this.curve.red); | ||
19502 | if (!this.y.red) | ||
19503 | this.y = this.y.toRed(this.curve.red); | ||
19504 | if (!this.z.red) | ||
19505 | this.z = this.z.toRed(this.curve.red); | ||
19506 | if (this.t && !this.t.red) | ||
19507 | this.t = this.t.toRed(this.curve.red); | ||
19508 | this.zOne = this.z === this.curve.one; | ||
19509 | |||
19510 | // Use extended coordinates | ||
19511 | if (this.curve.extended && !this.t) { | ||
19512 | this.t = this.x.redMul(this.y); | ||
19513 | if (!this.zOne) | ||
19514 | this.t = this.t.redMul(this.z.redInvm()); | ||
19515 | } | ||
19516 | } | ||
19517 | } | ||
19518 | inherits(Point, Base.BasePoint); | ||
19519 | |||
19520 | EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { | ||
19521 | return Point.fromJSON(this, obj); | ||
19522 | }; | ||
19523 | |||
19524 | EdwardsCurve.prototype.point = function point(x, y, z, t) { | ||
19525 | return new Point(this, x, y, z, t); | ||
19526 | }; | ||
19527 | |||
19528 | Point.fromJSON = function fromJSON(curve, obj) { | ||
19529 | return new Point(curve, obj[0], obj[1], obj[2]); | ||
19530 | }; | ||
19531 | |||
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) + '>'; | ||
19538 | }; | ||
19539 | |||
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; | ||
19544 | }; | ||
19545 | |||
19546 | Point.prototype._extDbl = function _extDbl() { | ||
19547 | // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html | ||
19548 | // #doubling-dbl-2008-hwcd | ||
19549 | // 4M + 4S | ||
19550 | |||
19551 | // A = X1^2 | ||
19552 | var a = this.x.redSqr(); | ||
19553 | // B = Y1^2 | ||
19554 | var b = this.y.redSqr(); | ||
19555 | // C = 2 * Z1^2 | ||
19556 | var c = this.z.redSqr(); | ||
19557 | c = c.redIAdd(c); | ||
19558 | // D = a * A | ||
19559 | var d = this.curve._mulA(a); | ||
19560 | // E = (X1 + Y1)^2 - A - B | ||
19561 | var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); | ||
19562 | // G = D + B | ||
19563 | var g = d.redAdd(b); | ||
19564 | // F = G - C | ||
19565 | var f = g.redSub(c); | ||
19566 | // H = D - B | ||
19567 | var h = d.redSub(b); | ||
19568 | // X3 = E * F | ||
19569 | var nx = e.redMul(f); | ||
19570 | // Y3 = G * H | ||
19571 | var ny = g.redMul(h); | ||
19572 | // T3 = E * H | ||
19573 | var nt = e.redMul(h); | ||
19574 | // Z3 = F * G | ||
19575 | var nz = f.redMul(g); | ||
19576 | return this.curve.point(nx, ny, nz, nt); | ||
19577 | }; | ||
19578 | |||
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 | ||
19583 | // and others | ||
19584 | // Generally 3M + 4S or 2M + 4S | ||
19585 | |||
19586 | // B = (X1 + Y1)^2 | ||
19587 | var b = this.x.redAdd(this.y).redSqr(); | ||
19588 | // C = X1^2 | ||
19589 | var c = this.x.redSqr(); | ||
19590 | // D = Y1^2 | ||
19591 | var d = this.y.redSqr(); | ||
19592 | |||
19593 | var nx; | ||
19594 | var ny; | ||
19595 | var nz; | ||
19596 | if (this.curve.twisted) { | ||
19597 | // E = a * C | ||
19598 | var e = this.curve._mulA(c); | ||
19599 | // F = E + D | ||
19600 | var f = e.redAdd(d); | ||
19601 | if (this.zOne) { | ||
19602 | // X3 = (B - C - D) * (F - 2) | ||
19603 | nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); | ||
19604 | // Y3 = F * (E - D) | ||
19605 | ny = f.redMul(e.redSub(d)); | ||
19606 | // Z3 = F^2 - 2 * F | ||
19607 | nz = f.redSqr().redSub(f).redSub(f); | ||
19608 | } else { | ||
19609 | // H = Z1^2 | ||
19610 | var h = this.z.redSqr(); | ||
19611 | // J = F - 2 * H | ||
19612 | var j = f.redSub(h).redISub(h); | ||
19613 | // X3 = (B-C-D)*J | ||
19614 | nx = b.redSub(c).redISub(d).redMul(j); | ||
19615 | // Y3 = F * (E - D) | ||
19616 | ny = f.redMul(e.redSub(d)); | ||
19617 | // Z3 = F * J | ||
19618 | nz = f.redMul(j); | ||
19619 | } | ||
19620 | } else { | ||
19621 | // E = C + D | ||
19622 | var e = c.redAdd(d); | ||
19623 | // H = (c * Z1)^2 | ||
19624 | var h = this.curve._mulC(this.c.redMul(this.z)).redSqr(); | ||
19625 | // J = E - 2 * H | ||
19626 | var j = e.redSub(h).redSub(h); | ||
19627 | // X3 = c * (B - E) * J | ||
19628 | nx = this.curve._mulC(b.redISub(e)).redMul(j); | ||
19629 | // Y3 = c * E * (C - D) | ||
19630 | ny = this.curve._mulC(e).redMul(c.redISub(d)); | ||
19631 | // Z3 = E * J | ||
19632 | nz = e.redMul(j); | ||
19633 | } | ||
19634 | return this.curve.point(nx, ny, nz); | ||
19635 | }; | ||
19636 | |||
19637 | Point.prototype.dbl = function dbl() { | ||
19638 | if (this.isInfinity()) | ||
19639 | return this; | ||
19640 | |||
19641 | // Double in extended coordinates | ||
19642 | if (this.curve.extended) | ||
19643 | return this._extDbl(); | ||
19644 | else | ||
19645 | return this._projDbl(); | ||
19646 | }; | ||
19647 | |||
19648 | Point.prototype._extAdd = function _extAdd(p) { | ||
19649 | // hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html | ||
19650 | // #addition-add-2008-hwcd-3 | ||
19651 | // 8M | ||
19652 | |||
19653 | // A = (Y1 - X1) * (Y2 - X2) | ||
19654 | var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); | ||
19655 | // B = (Y1 + X1) * (Y2 + X2) | ||
19656 | var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); | ||
19657 | // C = T1 * k * T2 | ||
19658 | var c = this.t.redMul(this.curve.dd).redMul(p.t); | ||
19659 | // D = Z1 * 2 * Z2 | ||
19660 | var d = this.z.redMul(p.z.redAdd(p.z)); | ||
19661 | // E = B - A | ||
19662 | var e = b.redSub(a); | ||
19663 | // F = D - C | ||
19664 | var f = d.redSub(c); | ||
19665 | // G = D + C | ||
19666 | var g = d.redAdd(c); | ||
19667 | // H = B + A | ||
19668 | var h = b.redAdd(a); | ||
19669 | // X3 = E * F | ||
19670 | var nx = e.redMul(f); | ||
19671 | // Y3 = G * H | ||
19672 | var ny = g.redMul(h); | ||
19673 | // T3 = E * H | ||
19674 | var nt = e.redMul(h); | ||
19675 | // Z3 = F * G | ||
19676 | var nz = f.redMul(g); | ||
19677 | return this.curve.point(nx, ny, nz, nt); | ||
19678 | }; | ||
19679 | |||
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 | ||
19684 | // 10M + 1S | ||
19685 | |||
19686 | // A = Z1 * Z2 | ||
19687 | var a = this.z.redMul(p.z); | ||
19688 | // B = A^2 | ||
19689 | var b = a.redSqr(); | ||
19690 | // C = X1 * X2 | ||
19691 | var c = this.x.redMul(p.x); | ||
19692 | // D = Y1 * Y2 | ||
19693 | var d = this.y.redMul(p.y); | ||
19694 | // E = d * C * D | ||
19695 | var e = this.curve.d.redMul(c).redMul(d); | ||
19696 | // F = B - E | ||
19697 | var f = b.redSub(e); | ||
19698 | // G = B + E | ||
19699 | var g = b.redAdd(e); | ||
19700 | // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) | ||
19701 | var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); | ||
19702 | var nx = a.redMul(f).redMul(tmp); | ||
19703 | var ny; | ||
19704 | var nz; | ||
19705 | if (this.curve.twisted) { | ||
19706 | // Y3 = A * G * (D - a * C) | ||
19707 | ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); | ||
19708 | // Z3 = F * G | ||
19709 | nz = f.redMul(g); | ||
19710 | } else { | ||
19711 | // Y3 = A * G * (D - C) | ||
19712 | ny = a.redMul(g).redMul(d.redSub(c)); | ||
19713 | // Z3 = c * F * G | ||
19714 | nz = this.curve._mulC(f).redMul(g); | ||
19715 | } | ||
19716 | return this.curve.point(nx, ny, nz); | ||
19717 | }; | ||
19718 | |||
19719 | Point.prototype.add = function add(p) { | ||
19720 | if (this.isInfinity()) | ||
19721 | return p; | ||
19722 | if (p.isInfinity()) | ||
19723 | return this; | ||
19724 | |||
19725 | if (this.curve.extended) | ||
19726 | return this._extAdd(p); | ||
19727 | else | ||
19728 | return this._projAdd(p); | ||
19729 | }; | ||
19730 | |||
19731 | Point.prototype.mul = function mul(k) { | ||
19732 | if (this._hasDoubles(k)) | ||
19733 | return this.curve._fixedNafMul(this, k); | ||
19734 | else | ||
19735 | return this.curve._wnafMul(this, k); | ||
19736 | }; | ||
19737 | |||
19738 | Point.prototype.mulAdd = function mulAdd(k1, p, k2) { | ||
19739 | return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, false); | ||
19740 | }; | ||
19741 | |||
19742 | Point.prototype.jmulAdd = function jmulAdd(k1, p, k2) { | ||
19743 | return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2, true); | ||
19744 | }; | ||
19745 | |||
19746 | Point.prototype.normalize = function normalize() { | ||
19747 | if (this.zOne) | ||
19748 | return this; | ||
19749 | |||
19750 | // Normalize coordinates | ||
19751 | var zi = this.z.redInvm(); | ||
19752 | this.x = this.x.redMul(zi); | ||
19753 | this.y = this.y.redMul(zi); | ||
19754 | if (this.t) | ||
19755 | this.t = this.t.redMul(zi); | ||
19756 | this.z = this.curve.one; | ||
19757 | this.zOne = true; | ||
19758 | return this; | ||
19759 | }; | ||
19760 | |||
19761 | Point.prototype.neg = function neg() { | ||
19762 | return this.curve.point(this.x.redNeg(), | ||
19763 | this.y, | ||
19764 | this.z, | ||
19765 | this.t && this.t.redNeg()); | ||
19766 | }; | ||
19767 | |||
19768 | Point.prototype.getX = function getX() { | ||
19769 | this.normalize(); | ||
19770 | return this.x.fromRed(); | ||
19771 | }; | ||
19772 | |||
19773 | Point.prototype.getY = function getY() { | ||
19774 | this.normalize(); | ||
19775 | return this.y.fromRed(); | ||
19776 | }; | ||
19777 | |||
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; | ||
19782 | }; | ||
19783 | |||
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) | ||
19787 | return true; | ||
19788 | |||
19789 | var xc = x.clone(); | ||
19790 | var t = this.curve.redN.redMul(this.z); | ||
19791 | for (;;) { | ||
19792 | xc.iadd(this.curve.n); | ||
19793 | if (xc.cmp(this.curve.p) >= 0) | ||
19794 | return false; | ||
19795 | |||
19796 | rx.redIAdd(t); | ||
19797 | if (this.x.cmp(rx) === 0) | ||
19798 | return true; | ||
19799 | } | ||
19800 | return false; | ||
19801 | }; | ||
19802 | |||
19803 | // Compatibility with BaseCurve | ||
19804 | Point.prototype.toP = Point.prototype.normalize; | ||
19805 | Point.prototype.mixedAdd = Point.prototype.add; | ||
19806 | |||
19807 | },{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],130:[function(require,module,exports){ | ||
19808 | 'use strict'; | ||
19809 | |||
19810 | var curve = exports; | ||
19811 | |||
19812 | curve.base = require('./base'); | ||
19813 | curve.short = require('./short'); | ||
19814 | curve.mont = require('./mont'); | ||
19815 | curve.edwards = require('./edwards'); | ||
19816 | |||
19817 | },{"./base":128,"./edwards":129,"./mont":131,"./short":132}],131:[function(require,module,exports){ | ||
19818 | 'use strict'; | ||
19819 | |||
19820 | var curve = require('../curve'); | ||
19821 | var BN = require('bn.js'); | ||
19822 | var inherits = require('inherits'); | ||
19823 | var Base = curve.base; | ||
19824 | |||
19825 | var elliptic = require('../../elliptic'); | ||
19826 | var utils = elliptic.utils; | ||
19827 | |||
19828 | function MontCurve(conf) { | ||
19829 | Base.call(this, 'mont', conf); | ||
19830 | |||
19831 | this.a = new BN(conf.a, 16).toRed(this.red); | ||
19832 | this.b = new BN(conf.b, 16).toRed(this.red); | ||
19833 | this.i4 = new BN(4).toRed(this.red).redInvm(); | ||
19834 | this.two = new BN(2).toRed(this.red); | ||
19835 | this.a24 = this.i4.redMul(this.a.redAdd(this.two)); | ||
19836 | } | ||
19837 | inherits(MontCurve, Base); | ||
19838 | module.exports = MontCurve; | ||
19839 | |||
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(); | ||
19845 | |||
19846 | return y.redSqr().cmp(rhs) === 0; | ||
19847 | }; | ||
19848 | |||
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; | ||
19854 | } else { | ||
19855 | this.x = new BN(x, 16); | ||
19856 | this.z = new BN(z, 16); | ||
19857 | if (!this.x.red) | ||
19858 | this.x = this.x.toRed(this.curve.red); | ||
19859 | if (!this.z.red) | ||
19860 | this.z = this.z.toRed(this.curve.red); | ||
19861 | } | ||
19862 | } | ||
19863 | inherits(Point, Base.BasePoint); | ||
19864 | |||
19865 | MontCurve.prototype.decodePoint = function decodePoint(bytes, enc) { | ||
19866 | return this.point(utils.toArray(bytes, enc), 1); | ||
19867 | }; | ||
19868 | |||
19869 | MontCurve.prototype.point = function point(x, z) { | ||
19870 | return new Point(this, x, z); | ||
19871 | }; | ||
19872 | |||
19873 | MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { | ||
19874 | return Point.fromJSON(this, obj); | ||
19875 | }; | ||
19876 | |||
19877 | Point.prototype.precompute = function precompute() { | ||
19878 | // No-op | ||
19879 | }; | ||
19880 | |||
19881 | Point.prototype._encode = function _encode() { | ||
19882 | return this.getX().toArray('be', this.curve.p.byteLength()); | ||
19883 | }; | ||
19884 | |||
19885 | Point.fromJSON = function fromJSON(curve, obj) { | ||
19886 | return new Point(curve, obj[0], obj[1] || curve.one); | ||
19887 | }; | ||
19888 | |||
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) + '>'; | ||
19894 | }; | ||
19895 | |||
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; | ||
19899 | }; | ||
19900 | |||
19901 | Point.prototype.dbl = function dbl() { | ||
19902 | // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 | ||
19903 | // 2M + 2S + 4A | ||
19904 | |||
19905 | // A = X1 + Z1 | ||
19906 | var a = this.x.redAdd(this.z); | ||
19907 | // AA = A^2 | ||
19908 | var aa = a.redSqr(); | ||
19909 | // B = X1 - Z1 | ||
19910 | var b = this.x.redSub(this.z); | ||
19911 | // BB = B^2 | ||
19912 | var bb = b.redSqr(); | ||
19913 | // C = AA - BB | ||
19914 | var c = aa.redSub(bb); | ||
19915 | // X3 = AA * BB | ||
19916 | var nx = aa.redMul(bb); | ||
19917 | // Z3 = C * (BB + A24 * C) | ||
19918 | var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); | ||
19919 | return this.curve.point(nx, nz); | ||
19920 | }; | ||
19921 | |||
19922 | Point.prototype.add = function add() { | ||
19923 | throw new Error('Not supported on Montgomery curve'); | ||
19924 | }; | ||
19925 | |||
19926 | Point.prototype.diffAdd = function diffAdd(p, diff) { | ||
19927 | // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 | ||
19928 | // 4M + 2S + 6A | ||
19929 | |||
19930 | // A = X2 + Z2 | ||
19931 | var a = this.x.redAdd(this.z); | ||
19932 | // B = X2 - Z2 | ||
19933 | var b = this.x.redSub(this.z); | ||
19934 | // C = X3 + Z3 | ||
19935 | var c = p.x.redAdd(p.z); | ||
19936 | // D = X3 - Z3 | ||
19937 | var d = p.x.redSub(p.z); | ||
19938 | // DA = D * A | ||
19939 | var da = d.redMul(a); | ||
19940 | // CB = C * B | ||
19941 | var cb = c.redMul(b); | ||
19942 | // X5 = Z1 * (DA + CB)^2 | ||
19943 | var nx = diff.z.redMul(da.redAdd(cb).redSqr()); | ||
19944 | // Z5 = X1 * (DA - CB)^2 | ||
19945 | var nz = diff.x.redMul(da.redISub(cb).redSqr()); | ||
19946 | return this.curve.point(nx, nz); | ||
19947 | }; | ||
19948 | |||
19949 | Point.prototype.mul = function mul(k) { | ||
19950 | var t = k.clone(); | ||
19951 | var a = this; // (N / 2) * Q + Q | ||
19952 | var b = this.curve.point(null, null); // (N / 2) * Q | ||
19953 | var c = this; // Q | ||
19954 | |||
19955 | for (var bits = []; t.cmpn(0) !== 0; t.iushrn(1)) | ||
19956 | bits.push(t.andln(1)); | ||
19957 | |||
19958 | for (var i = bits.length - 1; i >= 0; i--) { | ||
19959 | if (bits[i] === 0) { | ||
19960 | // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q | ||
19961 | a = a.diffAdd(b, c); | ||
19962 | // N * Q = 2 * ((N / 2) * Q + Q)) | ||
19963 | b = b.dbl(); | ||
19964 | } else { | ||
19965 | // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) | ||
19966 | b = a.diffAdd(b, c); | ||
19967 | // N * Q + Q = 2 * ((N / 2) * Q + Q) | ||
19968 | a = a.dbl(); | ||
19969 | } | ||
19970 | } | ||
19971 | return b; | ||
19972 | }; | ||
19973 | |||
19974 | Point.prototype.mulAdd = function mulAdd() { | ||
19975 | throw new Error('Not supported on Montgomery curve'); | ||
19976 | }; | ||
19977 | |||
19978 | Point.prototype.jumlAdd = function jumlAdd() { | ||
19979 | throw new Error('Not supported on Montgomery curve'); | ||
19980 | }; | ||
19981 | |||
19982 | Point.prototype.eq = function eq(other) { | ||
19983 | return this.getX().cmp(other.getX()) === 0; | ||
19984 | }; | ||
19985 | |||
19986 | Point.prototype.normalize = function normalize() { | ||
19987 | this.x = this.x.redMul(this.z.redInvm()); | ||
19988 | this.z = this.curve.one; | ||
19989 | return this; | ||
19990 | }; | ||
19991 | |||
19992 | Point.prototype.getX = function getX() { | ||
19993 | // Normalize coordinates | ||
19994 | this.normalize(); | ||
19995 | |||
19996 | return this.x.fromRed(); | ||
19997 | }; | ||
19998 | |||
19999 | },{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],132:[function(require,module,exports){ | ||
20000 | 'use strict'; | ||
20001 | |||
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; | ||
20007 | |||
20008 | var assert = elliptic.utils.assert; | ||
20009 | |||
20010 | function ShortCurve(conf) { | ||
20011 | Base.call(this, 'short', conf); | ||
20012 | |||
20013 | this.a = new BN(conf.a, 16).toRed(this.red); | ||
20014 | this.b = new BN(conf.b, 16).toRed(this.red); | ||
20015 | this.tinv = this.two.redInvm(); | ||
20016 | |||
20017 | this.zeroA = this.a.fromRed().cmpn(0) === 0; | ||
20018 | this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; | ||
20019 | |||
20020 | // If the curve is endomorphic, precalculate beta and lambda | ||
20021 | this.endo = this._getEndomorphism(conf); | ||
20022 | this._endoWnafT1 = new Array(4); | ||
20023 | this._endoWnafT2 = new Array(4); | ||
20024 | } | ||
20025 | inherits(ShortCurve, Base); | ||
20026 | module.exports = ShortCurve; | ||
20027 | |||
20028 | ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { | ||
20029 | // No efficient endomorphism | ||
20030 | if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) | ||
20031 | return; | ||
20032 | |||
20033 | // Compute beta and lambda, that lambda * P = (beta * Px; Py) | ||
20034 | var beta; | ||
20035 | var lambda; | ||
20036 | if (conf.beta) { | ||
20037 | beta = new BN(conf.beta, 16).toRed(this.red); | ||
20038 | } else { | ||
20039 | var betas = this._getEndoRoots(this.p); | ||
20040 | // Choose the smallest beta | ||
20041 | beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; | ||
20042 | beta = beta.toRed(this.red); | ||
20043 | } | ||
20044 | if (conf.lambda) { | ||
20045 | lambda = new BN(conf.lambda, 16); | ||
20046 | } else { | ||
20047 | // Choose the lambda that is matching selected beta | ||
20048 | var lambdas = this._getEndoRoots(this.n); | ||
20049 | if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { | ||
20050 | lambda = lambdas[0]; | ||
20051 | } else { | ||
20052 | lambda = lambdas[1]; | ||
20053 | assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); | ||
20054 | } | ||
20055 | } | ||
20056 | |||
20057 | // Get basis vectors, used for balanced length-two representation | ||
20058 | var basis; | ||
20059 | if (conf.basis) { | ||
20060 | basis = conf.basis.map(function(vec) { | ||
20061 | return { | ||
20062 | a: new BN(vec.a, 16), | ||
20063 | b: new BN(vec.b, 16) | ||
20064 | }; | ||
20065 | }); | ||
20066 | } else { | ||
20067 | basis = this._getEndoBasis(lambda); | ||
20068 | } | ||
20069 | |||
20070 | return { | ||
20071 | beta: beta, | ||
20072 | lambda: lambda, | ||
20073 | basis: basis | ||
20074 | }; | ||
20075 | }; | ||
20076 | |||
20077 | ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { | ||
20078 | // Find roots of for x^2 + x + 1 in F | ||
20079 | // Root = (-1 +- Sqrt(-3)) / 2 | ||
20080 | // | ||
20081 | var red = num === this.p ? this.red : BN.mont(num); | ||
20082 | var tinv = new BN(2).toRed(red).redInvm(); | ||
20083 | var ntinv = tinv.redNeg(); | ||
20084 | |||
20085 | var s = new BN(3).toRed(red).redNeg().redSqrt().redMul(tinv); | ||
20086 | |||
20087 | var l1 = ntinv.redAdd(s).fromRed(); | ||
20088 | var l2 = ntinv.redSub(s).fromRed(); | ||
20089 | return [ l1, l2 ]; | ||
20090 | }; | ||
20091 | |||
20092 | ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { | ||
20093 | // aprxSqrt >= sqrt(this.n) | ||
20094 | var aprxSqrt = this.n.ushrn(Math.floor(this.n.bitLength() / 2)); | ||
20095 | |||
20096 | // 3.74 | ||
20097 | // Run EGCD, until r(L + 1) < aprxSqrt | ||
20098 | var u = lambda; | ||
20099 | var v = this.n.clone(); | ||
20100 | var x1 = new BN(1); | ||
20101 | var y1 = new BN(0); | ||
20102 | var x2 = new BN(0); | ||
20103 | var y2 = new BN(1); | ||
20104 | |||
20105 | // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) | ||
20106 | var a0; | ||
20107 | var b0; | ||
20108 | // First vector | ||
20109 | var a1; | ||
20110 | var b1; | ||
20111 | // Second vector | ||
20112 | var a2; | ||
20113 | var b2; | ||
20114 | |||
20115 | var prevR; | ||
20116 | var i = 0; | ||
20117 | var r; | ||
20118 | var x; | ||
20119 | while (u.cmpn(0) !== 0) { | ||
20120 | var q = v.div(u); | ||
20121 | r = v.sub(q.mul(u)); | ||
20122 | x = x2.sub(q.mul(x1)); | ||
20123 | var y = y2.sub(q.mul(y1)); | ||
20124 | |||
20125 | if (!a1 && r.cmp(aprxSqrt) < 0) { | ||
20126 | a0 = prevR.neg(); | ||
20127 | b0 = x1; | ||
20128 | a1 = r.neg(); | ||
20129 | b1 = x; | ||
20130 | } else if (a1 && ++i === 2) { | ||
20131 | break; | ||
20132 | } | ||
20133 | prevR = r; | ||
20134 | |||
20135 | v = u; | ||
20136 | u = r; | ||
20137 | x2 = x1; | ||
20138 | x1 = x; | ||
20139 | y2 = y1; | ||
20140 | y1 = y; | ||
20141 | } | ||
20142 | a2 = r.neg(); | ||
20143 | b2 = x; | ||
20144 | |||
20145 | var len1 = a1.sqr().add(b1.sqr()); | ||
20146 | var len2 = a2.sqr().add(b2.sqr()); | ||
20147 | if (len2.cmp(len1) >= 0) { | ||
20148 | a2 = a0; | ||
20149 | b2 = b0; | ||
20150 | } | ||
20151 | |||
20152 | // Normalize signs | ||
20153 | if (a1.negative) { | ||
20154 | a1 = a1.neg(); | ||
20155 | b1 = b1.neg(); | ||
20156 | } | ||
20157 | if (a2.negative) { | ||
20158 | a2 = a2.neg(); | ||
20159 | b2 = b2.neg(); | ||
20160 | } | ||
20161 | |||
20162 | return [ | ||
20163 | { a: a1, b: b1 }, | ||
20164 | { a: a2, b: b2 } | ||
20165 | ]; | ||
20166 | }; | ||
20167 | |||
20168 | ShortCurve.prototype._endoSplit = function _endoSplit(k) { | ||
20169 | var basis = this.endo.basis; | ||
20170 | var v1 = basis[0]; | ||
20171 | var v2 = basis[1]; | ||
20172 | |||
20173 | var c1 = v2.b.mul(k).divRound(this.n); | ||
20174 | var c2 = v1.b.neg().mul(k).divRound(this.n); | ||
20175 | |||
20176 | var p1 = c1.mul(v1.a); | ||
20177 | var p2 = c2.mul(v2.a); | ||
20178 | var q1 = c1.mul(v1.b); | ||
20179 | var q2 = c2.mul(v2.b); | ||
20180 | |||
20181 | // Calculate answer | ||
20182 | var k1 = k.sub(p1).sub(p2); | ||
20183 | var k2 = q1.add(q2).neg(); | ||
20184 | return { k1: k1, k2: k2 }; | ||
20185 | }; | ||
20186 | |||
20187 | ShortCurve.prototype.pointFromX = function pointFromX(x, odd) { | ||
20188 | x = new BN(x, 16); | ||
20189 | if (!x.red) | ||
20190 | x = x.toRed(this.red); | ||
20191 | |||
20192 | var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); | ||
20193 | var y = y2.redSqrt(); | ||
20194 | if (y.redSqr().redSub(y2).cmp(this.zero) !== 0) | ||
20195 | throw new Error('invalid point'); | ||
20196 | |||
20197 | // XXX Is there any way to tell if the number is odd without converting it | ||
20198 | // to non-red form? | ||
20199 | var isOdd = y.fromRed().isOdd(); | ||
20200 | if (odd && !isOdd || !odd && isOdd) | ||
20201 | y = y.redNeg(); | ||
20202 | |||
20203 | return this.point(x, y); | ||
20204 | }; | ||
20205 | |||
20206 | ShortCurve.prototype.validate = function validate(point) { | ||
20207 | if (point.inf) | ||
20208 | return true; | ||
20209 | |||
20210 | var x = point.x; | ||
20211 | var y = point.y; | ||
20212 | |||
20213 | var ax = this.a.redMul(x); | ||
20214 | var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); | ||
20215 | return y.redSqr().redISub(rhs).cmpn(0) === 0; | ||
20216 | }; | ||
20217 | |||
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]); | ||
20224 | var p = points[i]; | ||
20225 | var beta = p._getBeta(); | ||
20226 | |||
20227 | if (split.k1.negative) { | ||
20228 | split.k1.ineg(); | ||
20229 | p = p.neg(true); | ||
20230 | } | ||
20231 | if (split.k2.negative) { | ||
20232 | split.k2.ineg(); | ||
20233 | beta = beta.neg(true); | ||
20234 | } | ||
20235 | |||
20236 | npoints[i * 2] = p; | ||
20237 | npoints[i * 2 + 1] = beta; | ||
20238 | ncoeffs[i * 2] = split.k1; | ||
20239 | ncoeffs[i * 2 + 1] = split.k2; | ||
20240 | } | ||
20241 | var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2, jacobianResult); | ||
20242 | |||
20243 | // Clean-up references to points and coefficients | ||
20244 | for (var j = 0; j < i * 2; j++) { | ||
20245 | npoints[j] = null; | ||
20246 | ncoeffs[j] = null; | ||
20247 | } | ||
20248 | return res; | ||
20249 | }; | ||
20250 | |||
20251 | function Point(curve, x, y, isRed) { | ||
20252 | Base.BasePoint.call(this, curve, 'affine'); | ||
20253 | if (x === null && y === null) { | ||
20254 | this.x = null; | ||
20255 | this.y = null; | ||
20256 | this.inf = true; | ||
20257 | } else { | ||
20258 | this.x = new BN(x, 16); | ||
20259 | this.y = new BN(y, 16); | ||
20260 | // Force redgomery representation when loading from JSON | ||
20261 | if (isRed) { | ||
20262 | this.x.forceRed(this.curve.red); | ||
20263 | this.y.forceRed(this.curve.red); | ||
20264 | } | ||
20265 | if (!this.x.red) | ||
20266 | this.x = this.x.toRed(this.curve.red); | ||
20267 | if (!this.y.red) | ||
20268 | this.y = this.y.toRed(this.curve.red); | ||
20269 | this.inf = false; | ||
20270 | } | ||
20271 | } | ||
20272 | inherits(Point, Base.BasePoint); | ||
20273 | |||
20274 | ShortCurve.prototype.point = function point(x, y, isRed) { | ||
20275 | return new Point(this, x, y, isRed); | ||
20276 | }; | ||
20277 | |||
20278 | ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { | ||
20279 | return Point.fromJSON(this, obj, red); | ||
20280 | }; | ||
20281 | |||
20282 | Point.prototype._getBeta = function _getBeta() { | ||
20283 | if (!this.curve.endo) | ||
20284 | return; | ||
20285 | |||
20286 | var pre = this.precomputed; | ||
20287 | if (pre && pre.beta) | ||
20288 | return pre.beta; | ||
20289 | |||
20290 | var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); | ||
20291 | if (pre) { | ||
20292 | var curve = this.curve; | ||
20293 | var endoMul = function(p) { | ||
20294 | return curve.point(p.x.redMul(curve.endo.beta), p.y); | ||
20295 | }; | ||
20296 | pre.beta = beta; | ||
20297 | beta.precomputed = { | ||
20298 | beta: null, | ||
20299 | naf: pre.naf && { | ||
20300 | wnd: pre.naf.wnd, | ||
20301 | points: pre.naf.points.map(endoMul) | ||
20302 | }, | ||
20303 | doubles: pre.doubles && { | ||
20304 | step: pre.doubles.step, | ||
20305 | points: pre.doubles.points.map(endoMul) | ||
20306 | } | ||
20307 | }; | ||
20308 | } | ||
20309 | return beta; | ||
20310 | }; | ||
20311 | |||
20312 | Point.prototype.toJSON = function toJSON() { | ||
20313 | if (!this.precomputed) | ||
20314 | return [ this.x, this.y ]; | ||
20315 | |||
20316 | return [ this.x, this.y, this.precomputed && { | ||
20317 | doubles: this.precomputed.doubles && { | ||
20318 | step: this.precomputed.doubles.step, | ||
20319 | points: this.precomputed.doubles.points.slice(1) | ||
20320 | }, | ||
20321 | naf: this.precomputed.naf && { | ||
20322 | wnd: this.precomputed.naf.wnd, | ||
20323 | points: this.precomputed.naf.points.slice(1) | ||
20324 | } | ||
20325 | } ]; | ||
20326 | }; | ||
20327 | |||
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); | ||
20332 | if (!obj[2]) | ||
20333 | return res; | ||
20334 | |||
20335 | function obj2point(obj) { | ||
20336 | return curve.point(obj[0], obj[1], red); | ||
20337 | } | ||
20338 | |||
20339 | var pre = obj[2]; | ||
20340 | res.precomputed = { | ||
20341 | beta: null, | ||
20342 | doubles: pre.doubles && { | ||
20343 | step: pre.doubles.step, | ||
20344 | points: [ res ].concat(pre.doubles.points.map(obj2point)) | ||
20345 | }, | ||
20346 | naf: pre.naf && { | ||
20347 | wnd: pre.naf.wnd, | ||
20348 | points: [ res ].concat(pre.naf.points.map(obj2point)) | ||
20349 | } | ||
20350 | }; | ||
20351 | return res; | ||
20352 | }; | ||
20353 | |||
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) + '>'; | ||
20359 | }; | ||
20360 | |||
20361 | Point.prototype.isInfinity = function isInfinity() { | ||
20362 | return this.inf; | ||
20363 | }; | ||
20364 | |||
20365 | Point.prototype.add = function add(p) { | ||
20366 | // O + P = P | ||
20367 | if (this.inf) | ||
20368 | return p; | ||
20369 | |||
20370 | // P + O = P | ||
20371 | if (p.inf) | ||
20372 | return this; | ||
20373 | |||
20374 | // P + P = 2P | ||
20375 | if (this.eq(p)) | ||
20376 | return this.dbl(); | ||
20377 | |||
20378 | // P + (-P) = O | ||
20379 | if (this.neg().eq(p)) | ||
20380 | return this.curve.point(null, null); | ||
20381 | |||
20382 | // P + Q = O | ||
20383 | if (this.x.cmp(p.x) === 0) | ||
20384 | return this.curve.point(null, null); | ||
20385 | |||
20386 | var c = this.y.redSub(p.y); | ||
20387 | if (c.cmpn(0) !== 0) | ||
20388 | c = c.redMul(this.x.redSub(p.x).redInvm()); | ||
20389 | var nx = c.redSqr().redISub(this.x).redISub(p.x); | ||
20390 | var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); | ||
20391 | return this.curve.point(nx, ny); | ||
20392 | }; | ||
20393 | |||
20394 | Point.prototype.dbl = function dbl() { | ||
20395 | if (this.inf) | ||
20396 | return this; | ||
20397 | |||
20398 | // 2P = O | ||
20399 | var ys1 = this.y.redAdd(this.y); | ||
20400 | if (ys1.cmpn(0) === 0) | ||
20401 | return this.curve.point(null, null); | ||
20402 | |||
20403 | var a = this.curve.a; | ||
20404 | |||
20405 | var x2 = this.x.redSqr(); | ||
20406 | var dyinv = ys1.redInvm(); | ||
20407 | var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); | ||
20408 | |||
20409 | var nx = c.redSqr().redISub(this.x.redAdd(this.x)); | ||
20410 | var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); | ||
20411 | return this.curve.point(nx, ny); | ||
20412 | }; | ||
20413 | |||
20414 | Point.prototype.getX = function getX() { | ||
20415 | return this.x.fromRed(); | ||
20416 | }; | ||
20417 | |||
20418 | Point.prototype.getY = function getY() { | ||
20419 | return this.y.fromRed(); | ||
20420 | }; | ||
20421 | |||
20422 | Point.prototype.mul = function mul(k) { | ||
20423 | k = new BN(k, 16); | ||
20424 | |||
20425 | if (this._hasDoubles(k)) | ||
20426 | return this.curve._fixedNafMul(this, k); | ||
20427 | else if (this.curve.endo) | ||
20428 | return this.curve._endoWnafMulAdd([ this ], [ k ]); | ||
20429 | else | ||
20430 | return this.curve._wnafMul(this, k); | ||
20431 | }; | ||
20432 | |||
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); | ||
20438 | else | ||
20439 | return this.curve._wnafMulAdd(1, points, coeffs, 2); | ||
20440 | }; | ||
20441 | |||
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); | ||
20447 | else | ||
20448 | return this.curve._wnafMulAdd(1, points, coeffs, 2, true); | ||
20449 | }; | ||
20450 | |||
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); | ||
20455 | }; | ||
20456 | |||
20457 | Point.prototype.neg = function neg(_precompute) { | ||
20458 | if (this.inf) | ||
20459 | return this; | ||
20460 | |||
20461 | var res = this.curve.point(this.x, this.y.redNeg()); | ||
20462 | if (_precompute && this.precomputed) { | ||
20463 | var pre = this.precomputed; | ||
20464 | var negate = function(p) { | ||
20465 | return p.neg(); | ||
20466 | }; | ||
20467 | res.precomputed = { | ||
20468 | naf: pre.naf && { | ||
20469 | wnd: pre.naf.wnd, | ||
20470 | points: pre.naf.points.map(negate) | ||
20471 | }, | ||
20472 | doubles: pre.doubles && { | ||
20473 | step: pre.doubles.step, | ||
20474 | points: pre.doubles.points.map(negate) | ||
20475 | } | ||
20476 | }; | ||
20477 | } | ||
20478 | return res; | ||
20479 | }; | ||
20480 | |||
20481 | Point.prototype.toJ = function toJ() { | ||
20482 | if (this.inf) | ||
20483 | return this.curve.jpoint(null, null, null); | ||
20484 | |||
20485 | var res = this.curve.jpoint(this.x, this.y, this.curve.one); | ||
20486 | return res; | ||
20487 | }; | ||
20488 | |||
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); | ||
20495 | } else { | ||
20496 | this.x = new BN(x, 16); | ||
20497 | this.y = new BN(y, 16); | ||
20498 | this.z = new BN(z, 16); | ||
20499 | } | ||
20500 | if (!this.x.red) | ||
20501 | this.x = this.x.toRed(this.curve.red); | ||
20502 | if (!this.y.red) | ||
20503 | this.y = this.y.toRed(this.curve.red); | ||
20504 | if (!this.z.red) | ||
20505 | this.z = this.z.toRed(this.curve.red); | ||
20506 | |||
20507 | this.zOne = this.z === this.curve.one; | ||
20508 | } | ||
20509 | inherits(JPoint, Base.BasePoint); | ||
20510 | |||
20511 | ShortCurve.prototype.jpoint = function jpoint(x, y, z) { | ||
20512 | return new JPoint(this, x, y, z); | ||
20513 | }; | ||
20514 | |||
20515 | JPoint.prototype.toP = function toP() { | ||
20516 | if (this.isInfinity()) | ||
20517 | return this.curve.point(null, null); | ||
20518 | |||
20519 | var zinv = this.z.redInvm(); | ||
20520 | var zinv2 = zinv.redSqr(); | ||
20521 | var ax = this.x.redMul(zinv2); | ||
20522 | var ay = this.y.redMul(zinv2).redMul(zinv); | ||
20523 | |||
20524 | return this.curve.point(ax, ay); | ||
20525 | }; | ||
20526 | |||
20527 | JPoint.prototype.neg = function neg() { | ||
20528 | return this.curve.jpoint(this.x, this.y.redNeg(), this.z); | ||
20529 | }; | ||
20530 | |||
20531 | JPoint.prototype.add = function add(p) { | ||
20532 | // O + P = P | ||
20533 | if (this.isInfinity()) | ||
20534 | return p; | ||
20535 | |||
20536 | // P + O = P | ||
20537 | if (p.isInfinity()) | ||
20538 | return this; | ||
20539 | |||
20540 | // 12M + 4S + 7A | ||
20541 | var pz2 = p.z.redSqr(); | ||
20542 | var z2 = this.z.redSqr(); | ||
20543 | var u1 = this.x.redMul(pz2); | ||
20544 | var u2 = p.x.redMul(z2); | ||
20545 | var s1 = this.y.redMul(pz2.redMul(p.z)); | ||
20546 | var s2 = p.y.redMul(z2.redMul(this.z)); | ||
20547 | |||
20548 | var h = u1.redSub(u2); | ||
20549 | var r = s1.redSub(s2); | ||
20550 | if (h.cmpn(0) === 0) { | ||
20551 | if (r.cmpn(0) !== 0) | ||
20552 | return this.curve.jpoint(null, null, null); | ||
20553 | else | ||
20554 | return this.dbl(); | ||
20555 | } | ||
20556 | |||
20557 | var h2 = h.redSqr(); | ||
20558 | var h3 = h2.redMul(h); | ||
20559 | var v = u1.redMul(h2); | ||
20560 | |||
20561 | var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); | ||
20562 | var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); | ||
20563 | var nz = this.z.redMul(p.z).redMul(h); | ||
20564 | |||
20565 | return this.curve.jpoint(nx, ny, nz); | ||
20566 | }; | ||
20567 | |||
20568 | JPoint.prototype.mixedAdd = function mixedAdd(p) { | ||
20569 | // O + P = P | ||
20570 | if (this.isInfinity()) | ||
20571 | return p.toJ(); | ||
20572 | |||
20573 | // P + O = P | ||
20574 | if (p.isInfinity()) | ||
20575 | return this; | ||
20576 | |||
20577 | // 8M + 3S + 7A | ||
20578 | var z2 = this.z.redSqr(); | ||
20579 | var u1 = this.x; | ||
20580 | var u2 = p.x.redMul(z2); | ||
20581 | var s1 = this.y; | ||
20582 | var s2 = p.y.redMul(z2).redMul(this.z); | ||
20583 | |||
20584 | var h = u1.redSub(u2); | ||
20585 | var r = s1.redSub(s2); | ||
20586 | if (h.cmpn(0) === 0) { | ||
20587 | if (r.cmpn(0) !== 0) | ||
20588 | return this.curve.jpoint(null, null, null); | ||
20589 | else | ||
20590 | return this.dbl(); | ||
20591 | } | ||
20592 | |||
20593 | var h2 = h.redSqr(); | ||
20594 | var h3 = h2.redMul(h); | ||
20595 | var v = u1.redMul(h2); | ||
20596 | |||
20597 | var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); | ||
20598 | var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); | ||
20599 | var nz = this.z.redMul(h); | ||
20600 | |||
20601 | return this.curve.jpoint(nx, ny, nz); | ||
20602 | }; | ||
20603 | |||
20604 | JPoint.prototype.dblp = function dblp(pow) { | ||
20605 | if (pow === 0) | ||
20606 | return this; | ||
20607 | if (this.isInfinity()) | ||
20608 | return this; | ||
20609 | if (!pow) | ||
20610 | return this.dbl(); | ||
20611 | |||
20612 | if (this.curve.zeroA || this.curve.threeA) { | ||
20613 | var r = this; | ||
20614 | for (var i = 0; i < pow; i++) | ||
20615 | r = r.dbl(); | ||
20616 | return r; | ||
20617 | } | ||
20618 | |||
20619 | // 1M + 2S + 1A + N * (4S + 5M + 8A) | ||
20620 | // N = 1 => 6M + 6S + 9A | ||
20621 | var a = this.curve.a; | ||
20622 | var tinv = this.curve.tinv; | ||
20623 | |||
20624 | var jx = this.x; | ||
20625 | var jy = this.y; | ||
20626 | var jz = this.z; | ||
20627 | var jz4 = jz.redSqr().redSqr(); | ||
20628 | |||
20629 | // Reuse results | ||
20630 | var jyd = jy.redAdd(jy); | ||
20631 | for (var i = 0; i < pow; i++) { | ||
20632 | var jx2 = jx.redSqr(); | ||
20633 | var jyd2 = jyd.redSqr(); | ||
20634 | var jyd4 = jyd2.redSqr(); | ||
20635 | var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); | ||
20636 | |||
20637 | var t1 = jx.redMul(jyd2); | ||
20638 | var nx = c.redSqr().redISub(t1.redAdd(t1)); | ||
20639 | var t2 = t1.redISub(nx); | ||
20640 | var dny = c.redMul(t2); | ||
20641 | dny = dny.redIAdd(dny).redISub(jyd4); | ||
20642 | var nz = jyd.redMul(jz); | ||
20643 | if (i + 1 < pow) | ||
20644 | jz4 = jz4.redMul(jyd4); | ||
20645 | |||
20646 | jx = nx; | ||
20647 | jz = nz; | ||
20648 | jyd = dny; | ||
20649 | } | ||
20650 | |||
20651 | return this.curve.jpoint(jx, jyd.redMul(tinv), jz); | ||
20652 | }; | ||
20653 | |||
20654 | JPoint.prototype.dbl = function dbl() { | ||
20655 | if (this.isInfinity()) | ||
20656 | return this; | ||
20657 | |||
20658 | if (this.curve.zeroA) | ||
20659 | return this._zeroDbl(); | ||
20660 | else if (this.curve.threeA) | ||
20661 | return this._threeDbl(); | ||
20662 | else | ||
20663 | return this._dbl(); | ||
20664 | }; | ||
20665 | |||
20666 | JPoint.prototype._zeroDbl = function _zeroDbl() { | ||
20667 | var nx; | ||
20668 | var ny; | ||
20669 | var nz; | ||
20670 | // Z = 1 | ||
20671 | if (this.zOne) { | ||
20672 | // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html | ||
20673 | // #doubling-mdbl-2007-bl | ||
20674 | // 1M + 5S + 14A | ||
20675 | |||
20676 | // XX = X1^2 | ||
20677 | var xx = this.x.redSqr(); | ||
20678 | // YY = Y1^2 | ||
20679 | var yy = this.y.redSqr(); | ||
20680 | // YYYY = YY^2 | ||
20681 | var yyyy = yy.redSqr(); | ||
20682 | // S = 2 * ((X1 + YY)^2 - XX - YYYY) | ||
20683 | var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); | ||
20684 | s = s.redIAdd(s); | ||
20685 | // M = 3 * XX + a; a = 0 | ||
20686 | var m = xx.redAdd(xx).redIAdd(xx); | ||
20687 | // T = M ^ 2 - 2*S | ||
20688 | var t = m.redSqr().redISub(s).redISub(s); | ||
20689 | |||
20690 | // 8 * YYYY | ||
20691 | var yyyy8 = yyyy.redIAdd(yyyy); | ||
20692 | yyyy8 = yyyy8.redIAdd(yyyy8); | ||
20693 | yyyy8 = yyyy8.redIAdd(yyyy8); | ||
20694 | |||
20695 | // X3 = T | ||
20696 | nx = t; | ||
20697 | // Y3 = M * (S - T) - 8 * YYYY | ||
20698 | ny = m.redMul(s.redISub(t)).redISub(yyyy8); | ||
20699 | // Z3 = 2*Y1 | ||
20700 | nz = this.y.redAdd(this.y); | ||
20701 | } else { | ||
20702 | // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html | ||
20703 | // #doubling-dbl-2009-l | ||
20704 | // 2M + 5S + 13A | ||
20705 | |||
20706 | // A = X1^2 | ||
20707 | var a = this.x.redSqr(); | ||
20708 | // B = Y1^2 | ||
20709 | var b = this.y.redSqr(); | ||
20710 | // C = B^2 | ||
20711 | var c = b.redSqr(); | ||
20712 | // D = 2 * ((X1 + B)^2 - A - C) | ||
20713 | var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); | ||
20714 | d = d.redIAdd(d); | ||
20715 | // E = 3 * A | ||
20716 | var e = a.redAdd(a).redIAdd(a); | ||
20717 | // F = E^2 | ||
20718 | var f = e.redSqr(); | ||
20719 | |||
20720 | // 8 * C | ||
20721 | var c8 = c.redIAdd(c); | ||
20722 | c8 = c8.redIAdd(c8); | ||
20723 | c8 = c8.redIAdd(c8); | ||
20724 | |||
20725 | // X3 = F - 2 * D | ||
20726 | nx = f.redISub(d).redISub(d); | ||
20727 | // Y3 = E * (D - X3) - 8 * C | ||
20728 | ny = e.redMul(d.redISub(nx)).redISub(c8); | ||
20729 | // Z3 = 2 * Y1 * Z1 | ||
20730 | nz = this.y.redMul(this.z); | ||
20731 | nz = nz.redIAdd(nz); | ||
20732 | } | ||
20733 | |||
20734 | return this.curve.jpoint(nx, ny, nz); | ||
20735 | }; | ||
20736 | |||
20737 | JPoint.prototype._threeDbl = function _threeDbl() { | ||
20738 | var nx; | ||
20739 | var ny; | ||
20740 | var nz; | ||
20741 | // Z = 1 | ||
20742 | if (this.zOne) { | ||
20743 | // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html | ||
20744 | // #doubling-mdbl-2007-bl | ||
20745 | // 1M + 5S + 15A | ||
20746 | |||
20747 | // XX = X1^2 | ||
20748 | var xx = this.x.redSqr(); | ||
20749 | // YY = Y1^2 | ||
20750 | var yy = this.y.redSqr(); | ||
20751 | // YYYY = YY^2 | ||
20752 | var yyyy = yy.redSqr(); | ||
20753 | // S = 2 * ((X1 + YY)^2 - XX - YYYY) | ||
20754 | var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); | ||
20755 | s = s.redIAdd(s); | ||
20756 | // M = 3 * XX + a | ||
20757 | var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); | ||
20758 | // T = M^2 - 2 * S | ||
20759 | var t = m.redSqr().redISub(s).redISub(s); | ||
20760 | // X3 = T | ||
20761 | nx = t; | ||
20762 | // Y3 = M * (S - T) - 8 * YYYY | ||
20763 | var yyyy8 = yyyy.redIAdd(yyyy); | ||
20764 | yyyy8 = yyyy8.redIAdd(yyyy8); | ||
20765 | yyyy8 = yyyy8.redIAdd(yyyy8); | ||
20766 | ny = m.redMul(s.redISub(t)).redISub(yyyy8); | ||
20767 | // Z3 = 2 * Y1 | ||
20768 | nz = this.y.redAdd(this.y); | ||
20769 | } else { | ||
20770 | // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b | ||
20771 | // 3M + 5S | ||
20772 | |||
20773 | // delta = Z1^2 | ||
20774 | var delta = this.z.redSqr(); | ||
20775 | // gamma = Y1^2 | ||
20776 | var gamma = this.y.redSqr(); | ||
20777 | // beta = X1 * gamma | ||
20778 | var beta = this.x.redMul(gamma); | ||
20779 | // alpha = 3 * (X1 - delta) * (X1 + delta) | ||
20780 | var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); | ||
20781 | alpha = alpha.redAdd(alpha).redIAdd(alpha); | ||
20782 | // X3 = alpha^2 - 8 * beta | ||
20783 | var beta4 = beta.redIAdd(beta); | ||
20784 | beta4 = beta4.redIAdd(beta4); | ||
20785 | var beta8 = beta4.redAdd(beta4); | ||
20786 | nx = alpha.redSqr().redISub(beta8); | ||
20787 | // Z3 = (Y1 + Z1)^2 - gamma - delta | ||
20788 | nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); | ||
20789 | // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 | ||
20790 | var ggamma8 = gamma.redSqr(); | ||
20791 | ggamma8 = ggamma8.redIAdd(ggamma8); | ||
20792 | ggamma8 = ggamma8.redIAdd(ggamma8); | ||
20793 | ggamma8 = ggamma8.redIAdd(ggamma8); | ||
20794 | ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); | ||
20795 | } | ||
20796 | |||
20797 | return this.curve.jpoint(nx, ny, nz); | ||
20798 | }; | ||
20799 | |||
20800 | JPoint.prototype._dbl = function _dbl() { | ||
20801 | var a = this.curve.a; | ||
20802 | |||
20803 | // 4M + 6S + 10A | ||
20804 | var jx = this.x; | ||
20805 | var jy = this.y; | ||
20806 | var jz = this.z; | ||
20807 | var jz4 = jz.redSqr().redSqr(); | ||
20808 | |||
20809 | var jx2 = jx.redSqr(); | ||
20810 | var jy2 = jy.redSqr(); | ||
20811 | |||
20812 | var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); | ||
20813 | |||
20814 | var jxd4 = jx.redAdd(jx); | ||
20815 | jxd4 = jxd4.redIAdd(jxd4); | ||
20816 | var t1 = jxd4.redMul(jy2); | ||
20817 | var nx = c.redSqr().redISub(t1.redAdd(t1)); | ||
20818 | var t2 = t1.redISub(nx); | ||
20819 | |||
20820 | var jyd8 = jy2.redSqr(); | ||
20821 | jyd8 = jyd8.redIAdd(jyd8); | ||
20822 | jyd8 = jyd8.redIAdd(jyd8); | ||
20823 | jyd8 = jyd8.redIAdd(jyd8); | ||
20824 | var ny = c.redMul(t2).redISub(jyd8); | ||
20825 | var nz = jy.redAdd(jy).redMul(jz); | ||
20826 | |||
20827 | return this.curve.jpoint(nx, ny, nz); | ||
20828 | }; | ||
20829 | |||
20830 | JPoint.prototype.trpl = function trpl() { | ||
20831 | if (!this.curve.zeroA) | ||
20832 | return this.dbl().add(this); | ||
20833 | |||
20834 | // hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl | ||
20835 | // 5M + 10S + ... | ||
20836 | |||
20837 | // XX = X1^2 | ||
20838 | var xx = this.x.redSqr(); | ||
20839 | // YY = Y1^2 | ||
20840 | var yy = this.y.redSqr(); | ||
20841 | // ZZ = Z1^2 | ||
20842 | var zz = this.z.redSqr(); | ||
20843 | // YYYY = YY^2 | ||
20844 | var yyyy = yy.redSqr(); | ||
20845 | // M = 3 * XX + a * ZZ2; a = 0 | ||
20846 | var m = xx.redAdd(xx).redIAdd(xx); | ||
20847 | // MM = M^2 | ||
20848 | var mm = m.redSqr(); | ||
20849 | // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM | ||
20850 | var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); | ||
20851 | e = e.redIAdd(e); | ||
20852 | e = e.redAdd(e).redIAdd(e); | ||
20853 | e = e.redISub(mm); | ||
20854 | // EE = E^2 | ||
20855 | var ee = e.redSqr(); | ||
20856 | // T = 16*YYYY | ||
20857 | var t = yyyy.redIAdd(yyyy); | ||
20858 | t = t.redIAdd(t); | ||
20859 | t = t.redIAdd(t); | ||
20860 | t = t.redIAdd(t); | ||
20861 | // U = (M + E)^2 - MM - EE - T | ||
20862 | var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); | ||
20863 | // X3 = 4 * (X1 * EE - 4 * YY * U) | ||
20864 | var yyu4 = yy.redMul(u); | ||
20865 | yyu4 = yyu4.redIAdd(yyu4); | ||
20866 | yyu4 = yyu4.redIAdd(yyu4); | ||
20867 | var nx = this.x.redMul(ee).redISub(yyu4); | ||
20868 | nx = nx.redIAdd(nx); | ||
20869 | nx = nx.redIAdd(nx); | ||
20870 | // Y3 = 8 * Y1 * (U * (T - U) - E * EE) | ||
20871 | var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); | ||
20872 | ny = ny.redIAdd(ny); | ||
20873 | ny = ny.redIAdd(ny); | ||
20874 | ny = ny.redIAdd(ny); | ||
20875 | // Z3 = (Z1 + E)^2 - ZZ - EE | ||
20876 | var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); | ||
20877 | |||
20878 | return this.curve.jpoint(nx, ny, nz); | ||
20879 | }; | ||
20880 | |||
20881 | JPoint.prototype.mul = function mul(k, kbase) { | ||
20882 | k = new BN(k, kbase); | ||
20883 | |||
20884 | return this.curve._wnafMul(this, k); | ||
20885 | }; | ||
20886 | |||
20887 | JPoint.prototype.eq = function eq(p) { | ||
20888 | if (p.type === 'affine') | ||
20889 | return this.eq(p.toJ()); | ||
20890 | |||
20891 | if (this === p) | ||
20892 | return true; | ||
20893 | |||
20894 | // x1 * z2^2 == x2 * z1^2 | ||
20895 | var z2 = this.z.redSqr(); | ||
20896 | var pz2 = p.z.redSqr(); | ||
20897 | if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) | ||
20898 | return false; | ||
20899 | |||
20900 | // y1 * z2^3 == y2 * z1^3 | ||
20901 | var z3 = z2.redMul(this.z); | ||
20902 | var pz3 = pz2.redMul(p.z); | ||
20903 | return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; | ||
20904 | }; | ||
20905 | |||
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) | ||
20910 | return true; | ||
20911 | |||
20912 | var xc = x.clone(); | ||
20913 | var t = this.curve.redN.redMul(zs); | ||
20914 | for (;;) { | ||
20915 | xc.iadd(this.curve.n); | ||
20916 | if (xc.cmp(this.curve.p) >= 0) | ||
20917 | return false; | ||
20918 | |||
20919 | rx.redIAdd(t); | ||
20920 | if (this.x.cmp(rx) === 0) | ||
20921 | return true; | ||
20922 | } | ||
20923 | return false; | ||
20924 | }; | ||
20925 | |||
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) + '>'; | ||
20932 | }; | ||
20933 | |||
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; | ||
20937 | }; | ||
20938 | |||
20939 | },{"../../elliptic":127,"../curve":130,"bn.js":75,"inherits":163}],133:[function(require,module,exports){ | ||
20940 | 'use strict'; | ||
20941 | |||
20942 | var curves = exports; | ||
20943 | |||
20944 | var hash = require('hash.js'); | ||
20945 | var elliptic = require('../elliptic'); | ||
20946 | |||
20947 | var assert = elliptic.utils.assert; | ||
20948 | |||
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); | ||
20954 | else | ||
20955 | this.curve = new elliptic.curve.mont(options); | ||
20956 | this.g = this.curve.g; | ||
20957 | this.n = this.curve.n; | ||
20958 | this.hash = options.hash; | ||
20959 | |||
20960 | assert(this.g.validate(), 'Invalid curve'); | ||
20961 | assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); | ||
20962 | } | ||
20963 | curves.PresetCurve = PresetCurve; | ||
20964 | |||
20965 | function defineCurve(name, options) { | ||
20966 | Object.defineProperty(curves, name, { | ||
20967 | configurable: true, | ||
20968 | enumerable: true, | ||
20969 | get: function() { | ||
20970 | var curve = new PresetCurve(options); | ||
20971 | Object.defineProperty(curves, name, { | ||
20972 | configurable: true, | ||
20973 | enumerable: true, | ||
20974 | value: curve | ||
20975 | }); | ||
20976 | return curve; | ||
20977 | } | ||
20978 | }); | ||
20979 | } | ||
20980 | |||
20981 | defineCurve('p192', { | ||
20982 | type: 'short', | ||
20983 | prime: 'p192', | ||
20984 | p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', | ||
20985 | a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', | ||
20986 | b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', | ||
20987 | n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', | ||
20988 | hash: hash.sha256, | ||
20989 | gRed: false, | ||
20990 | g: [ | ||
20991 | '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', | ||
20992 | '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' | ||
20993 | ] | ||
20994 | }); | ||
20995 | |||
20996 | defineCurve('p224', { | ||
20997 | type: 'short', | ||
20998 | prime: 'p224', | ||
20999 | p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', | ||
21000 | a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', | ||
21001 | b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', | ||
21002 | n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', | ||
21003 | hash: hash.sha256, | ||
21004 | gRed: false, | ||
21005 | g: [ | ||
21006 | 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', | ||
21007 | 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' | ||
21008 | ] | ||
21009 | }); | ||
21010 | |||
21011 | defineCurve('p256', { | ||
21012 | type: 'short', | ||
21013 | prime: null, | ||
21014 | p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', | ||
21015 | a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', | ||
21016 | b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', | ||
21017 | n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', | ||
21018 | hash: hash.sha256, | ||
21019 | gRed: false, | ||
21020 | g: [ | ||
21021 | '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', | ||
21022 | '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' | ||
21023 | ] | ||
21024 | }); | ||
21025 | |||
21026 | defineCurve('p384', { | ||
21027 | type: 'short', | ||
21028 | prime: null, | ||
21029 | p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + | ||
21030 | 'fffffffe ffffffff 00000000 00000000 ffffffff', | ||
21031 | a: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + | ||
21032 | 'fffffffe ffffffff 00000000 00000000 fffffffc', | ||
21033 | b: 'b3312fa7 e23ee7e4 988e056b e3f82d19 181d9c6e fe814112 0314088f ' + | ||
21034 | '5013875a c656398d 8a2ed19d 2a85c8ed d3ec2aef', | ||
21035 | n: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff c7634d81 ' + | ||
21036 | 'f4372ddf 581a0db2 48b0a77a ecec196a ccc52973', | ||
21037 | hash: hash.sha384, | ||
21038 | gRed: false, | ||
21039 | g: [ | ||
21040 | 'aa87ca22 be8b0537 8eb1c71e f320ad74 6e1d3b62 8ba79b98 59f741e0 82542a38 ' + | ||
21041 | '5502f25d bf55296c 3a545e38 72760ab7', | ||
21042 | '3617de4a 96262c6f 5d9e98bf 9292dc29 f8f41dbd 289a147c e9da3113 b5f0b8c0 ' + | ||
21043 | '0a60b1ce 1d7e819d 7a431d7c 90ea0e5f' | ||
21044 | ] | ||
21045 | }); | ||
21046 | |||
21047 | defineCurve('p521', { | ||
21048 | type: 'short', | ||
21049 | prime: null, | ||
21050 | p: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + | ||
21051 | 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + | ||
21052 | 'ffffffff ffffffff ffffffff ffffffff ffffffff', | ||
21053 | a: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + | ||
21054 | 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff ' + | ||
21055 | 'ffffffff ffffffff ffffffff ffffffff fffffffc', | ||
21056 | b: '00000051 953eb961 8e1c9a1f 929a21a0 b68540ee a2da725b ' + | ||
21057 | '99b315f3 b8b48991 8ef109e1 56193951 ec7e937b 1652c0bd ' + | ||
21058 | '3bb1bf07 3573df88 3d2c34f1 ef451fd4 6b503f00', | ||
21059 | n: '000001ff ffffffff ffffffff ffffffff ffffffff ffffffff ' + | ||
21060 | 'ffffffff ffffffff fffffffa 51868783 bf2f966b 7fcc0148 ' + | ||
21061 | 'f709a5d0 3bb5c9b8 899c47ae bb6fb71e 91386409', | ||
21062 | hash: hash.sha512, | ||
21063 | gRed: false, | ||
21064 | g: [ | ||
21065 | '000000c6 858e06b7 0404e9cd 9e3ecb66 2395b442 9c648139 ' + | ||
21066 | '053fb521 f828af60 6b4d3dba a14b5e77 efe75928 fe1dc127 ' + | ||
21067 | 'a2ffa8de 3348b3c1 856a429b f97e7e31 c2e5bd66', | ||
21068 | '00000118 39296a78 9a3bc004 5c8a5fb4 2c7d1bd9 98f54449 ' + | ||
21069 | '579b4468 17afbd17 273e662c 97ee7299 5ef42640 c550b901 ' + | ||
21070 | '3fad0761 353c7086 a272c240 88be9476 9fd16650' | ||
21071 | ] | ||
21072 | }); | ||
21073 | |||
21074 | defineCurve('curve25519', { | ||
21075 | type: 'mont', | ||
21076 | prime: 'p25519', | ||
21077 | p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', | ||
21078 | a: '76d06', | ||
21079 | b: '1', | ||
21080 | n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', | ||
21081 | hash: hash.sha256, | ||
21082 | gRed: false, | ||
21083 | g: [ | ||
21084 | '9' | ||
21085 | ] | ||
21086 | }); | ||
21087 | |||
21088 | defineCurve('ed25519', { | ||
21089 | type: 'edwards', | ||
21090 | prime: 'p25519', | ||
21091 | p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', | ||
21092 | a: '-1', | ||
21093 | c: '1', | ||
21094 | // -121665 * (121666^(-1)) (mod P) | ||
21095 | d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', | ||
21096 | n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', | ||
21097 | hash: hash.sha256, | ||
21098 | gRed: false, | ||
21099 | g: [ | ||
21100 | '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', | ||
21101 | |||
21102 | // 4/5 | ||
21103 | '6666666666666666666666666666666666666666666666666666666666666658' | ||
21104 | ] | ||
21105 | }); | ||
21106 | |||
21107 | var pre; | ||
21108 | try { | ||
21109 | pre = require('./precomputed/secp256k1'); | ||
21110 | } catch (e) { | ||
21111 | pre = undefined; | ||
21112 | } | ||
21113 | |||
21114 | defineCurve('secp256k1', { | ||
21115 | type: 'short', | ||
21116 | prime: 'k256', | ||
21117 | p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', | ||
21118 | a: '0', | ||
21119 | b: '7', | ||
21120 | n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', | ||
21121 | h: '1', | ||
21122 | hash: hash.sha256, | ||
21123 | |||
21124 | // Precomputed endomorphism | ||
21125 | beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', | ||
21126 | lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', | ||
21127 | basis: [ | ||
21128 | { | ||
21129 | a: '3086d221a7d46bcde86c90e49284eb15', | ||
21130 | b: '-e4437ed6010e88286f547fa90abfe4c3' | ||
21131 | }, | ||
21132 | { | ||
21133 | a: '114ca50f7a8e2f3f657c1108d9d44cfd8', | ||
21134 | b: '3086d221a7d46bcde86c90e49284eb15' | ||
21135 | } | ||
21136 | ], | ||
21137 | |||
21138 | gRed: false, | ||
21139 | g: [ | ||
21140 | '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', | ||
21141 | '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', | ||
21142 | pre | ||
21143 | ] | ||
21144 | }); | ||
21145 | |||
21146 | },{"../elliptic":127,"./precomputed/secp256k1":140,"hash.js":147}],134:[function(require,module,exports){ | ||
21147 | 'use strict'; | ||
21148 | |||
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; | ||
21154 | |||
21155 | var KeyPair = require('./key'); | ||
21156 | var Signature = require('./signature'); | ||
21157 | |||
21158 | function EC(options) { | ||
21159 | if (!(this instanceof EC)) | ||
21160 | return new EC(options); | ||
21161 | |||
21162 | // Shortcut `elliptic.ec(curve-name)` | ||
21163 | if (typeof options === 'string') { | ||
21164 | assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); | ||
21165 | |||
21166 | options = elliptic.curves[options]; | ||
21167 | } | ||
21168 | |||
21169 | // Shortcut for `elliptic.ec(elliptic.curves.curveName)` | ||
21170 | if (options instanceof elliptic.curves.PresetCurve) | ||
21171 | options = { curve: options }; | ||
21172 | |||
21173 | this.curve = options.curve.curve; | ||
21174 | this.n = this.curve.n; | ||
21175 | this.nh = this.n.ushrn(1); | ||
21176 | this.g = this.curve.g; | ||
21177 | |||
21178 | // Point on curve | ||
21179 | this.g = options.curve.g; | ||
21180 | this.g.precompute(options.curve.n.bitLength() + 1); | ||
21181 | |||
21182 | // Hash for function for DRBG | ||
21183 | this.hash = options.hash || options.curve.hash; | ||
21184 | } | ||
21185 | module.exports = EC; | ||
21186 | |||
21187 | EC.prototype.keyPair = function keyPair(options) { | ||
21188 | return new KeyPair(this, options); | ||
21189 | }; | ||
21190 | |||
21191 | EC.prototype.keyFromPrivate = function keyFromPrivate(priv, enc) { | ||
21192 | return KeyPair.fromPrivate(this, priv, enc); | ||
21193 | }; | ||
21194 | |||
21195 | EC.prototype.keyFromPublic = function keyFromPublic(pub, enc) { | ||
21196 | return KeyPair.fromPublic(this, pub, enc); | ||
21197 | }; | ||
21198 | |||
21199 | EC.prototype.genKeyPair = function genKeyPair(options) { | ||
21200 | if (!options) | ||
21201 | options = {}; | ||
21202 | |||
21203 | // Instantiate Hmac_DRBG | ||
21204 | var drbg = new HmacDRBG({ | ||
21205 | hash: this.hash, | ||
21206 | pers: options.pers, | ||
21207 | persEnc: options.persEnc || 'utf8', | ||
21208 | entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), | ||
21209 | entropyEnc: options.entropy && options.entropyEnc || 'utf8', | ||
21210 | nonce: this.n.toArray() | ||
21211 | }); | ||
21212 | |||
21213 | var bytes = this.n.byteLength(); | ||
21214 | var ns2 = this.n.sub(new BN(2)); | ||
21215 | do { | ||
21216 | var priv = new BN(drbg.generate(bytes)); | ||
21217 | if (priv.cmp(ns2) > 0) | ||
21218 | continue; | ||
21219 | |||
21220 | priv.iaddn(1); | ||
21221 | return this.keyFromPrivate(priv); | ||
21222 | } while (true); | ||
21223 | }; | ||
21224 | |||
21225 | EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { | ||
21226 | var delta = msg.byteLength() * 8 - this.n.bitLength(); | ||
21227 | if (delta > 0) | ||
21228 | msg = msg.ushrn(delta); | ||
21229 | if (!truncOnly && msg.cmp(this.n) >= 0) | ||
21230 | return msg.sub(this.n); | ||
21231 | else | ||
21232 | return msg; | ||
21233 | }; | ||
21234 | |||
21235 | EC.prototype.sign = function sign(msg, key, enc, options) { | ||
21236 | if (typeof enc === 'object') { | ||
21237 | options = enc; | ||
21238 | enc = null; | ||
21239 | } | ||
21240 | if (!options) | ||
21241 | options = {}; | ||
21242 | |||
21243 | key = this.keyFromPrivate(key, enc); | ||
21244 | msg = this._truncateToN(new BN(msg, 16)); | ||
21245 | |||
21246 | // Zero-extend key to provide enough entropy | ||
21247 | var bytes = this.n.byteLength(); | ||
21248 | var bkey = key.getPrivate().toArray('be', bytes); | ||
21249 | |||
21250 | // Zero-extend nonce to have the same byte size as N | ||
21251 | var nonce = msg.toArray('be', bytes); | ||
21252 | |||
21253 | // Instantiate Hmac_DRBG | ||
21254 | var drbg = new HmacDRBG({ | ||
21255 | hash: this.hash, | ||
21256 | entropy: bkey, | ||
21257 | nonce: nonce, | ||
21258 | pers: options.pers, | ||
21259 | persEnc: options.persEnc || 'utf8' | ||
21260 | }); | ||
21261 | |||
21262 | // Number of bytes to generate | ||
21263 | var ns1 = this.n.sub(new BN(1)); | ||
21264 | |||
21265 | for (var iter = 0; true; iter++) { | ||
21266 | var k = options.k ? | ||
21267 | options.k(iter) : | ||
21268 | new BN(drbg.generate(this.n.byteLength())); | ||
21269 | k = this._truncateToN(k, true); | ||
21270 | if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) | ||
21271 | continue; | ||
21272 | |||
21273 | var kp = this.g.mul(k); | ||
21274 | if (kp.isInfinity()) | ||
21275 | continue; | ||
21276 | |||
21277 | var kpX = kp.getX(); | ||
21278 | var r = kpX.umod(this.n); | ||
21279 | if (r.cmpn(0) === 0) | ||
21280 | continue; | ||
21281 | |||
21282 | var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)); | ||
21283 | s = s.umod(this.n); | ||
21284 | if (s.cmpn(0) === 0) | ||
21285 | continue; | ||
21286 | |||
21287 | var recoveryParam = (kp.getY().isOdd() ? 1 : 0) | | ||
21288 | (kpX.cmp(r) !== 0 ? 2 : 0); | ||
21289 | |||
21290 | // Use complement of `s`, if it is > `n / 2` | ||
21291 | if (options.canonical && s.cmp(this.nh) > 0) { | ||
21292 | s = this.n.sub(s); | ||
21293 | recoveryParam ^= 1; | ||
21294 | } | ||
21295 | |||
21296 | return new Signature({ r: r, s: s, recoveryParam: recoveryParam }); | ||
21297 | } | ||
21298 | }; | ||
21299 | |||
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'); | ||
21304 | |||
21305 | // Perform primitive values validation | ||
21306 | var r = signature.r; | ||
21307 | var s = signature.s; | ||
21308 | if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) | ||
21309 | return false; | ||
21310 | if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) | ||
21311 | return false; | ||
21312 | |||
21313 | // Validate signature | ||
21314 | var sinv = s.invm(this.n); | ||
21315 | var u1 = sinv.mul(msg).umod(this.n); | ||
21316 | var u2 = sinv.mul(r).umod(this.n); | ||
21317 | |||
21318 | if (!this.curve._maxwellTrick) { | ||
21319 | var p = this.g.mulAdd(u1, key.getPublic(), u2); | ||
21320 | if (p.isInfinity()) | ||
21321 | return false; | ||
21322 | |||
21323 | return p.getX().umod(this.n).cmp(r) === 0; | ||
21324 | } | ||
21325 | |||
21326 | // NOTE: Greg Maxwell's trick, inspired by: | ||
21327 | // https://git.io/vad3K | ||
21328 | |||
21329 | var p = this.g.jmulAdd(u1, key.getPublic(), u2); | ||
21330 | if (p.isInfinity()) | ||
21331 | return false; | ||
21332 | |||
21333 | // Compare `p.x` of Jacobian point with `r`, | ||
21334 | // this will do `p.x == r * p.z^2` instead of multiplying `p.x` by the | ||
21335 | // inverse of `p.z^2` | ||
21336 | return p.eqXToP(r); | ||
21337 | }; | ||
21338 | |||
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); | ||
21342 | |||
21343 | var n = this.n; | ||
21344 | var e = new BN(msg); | ||
21345 | var r = signature.r; | ||
21346 | var s = signature.s; | ||
21347 | |||
21348 | // A set LSB signifies that the y-coordinate is odd | ||
21349 | var isYOdd = j & 1; | ||
21350 | var isSecondKey = j >> 1; | ||
21351 | if (r.cmp(this.curve.p.umod(this.curve.n)) >= 0 && isSecondKey) | ||
21352 | throw new Error('Unable to find sencond key candinate'); | ||
21353 | |||
21354 | // 1.1. Let x = r + jn. | ||
21355 | if (isSecondKey) | ||
21356 | r = this.curve.pointFromX(r.add(this.curve.n), isYOdd); | ||
21357 | else | ||
21358 | r = this.curve.pointFromX(r, isYOdd); | ||
21359 | |||
21360 | var rInv = signature.r.invm(n); | ||
21361 | var s1 = n.sub(e).mul(rInv).umod(n); | ||
21362 | var s2 = s.mul(rInv).umod(n); | ||
21363 | |||
21364 | // 1.6.1 Compute Q = r^-1 (sR - eG) | ||
21365 | // Q = r^-1 (sR + -eG) | ||
21366 | return this.g.mulAdd(s1, r, s2); | ||
21367 | }; | ||
21368 | |||
21369 | EC.prototype.getKeyRecoveryParam = function(e, signature, Q, enc) { | ||
21370 | signature = new Signature(signature, enc); | ||
21371 | if (signature.recoveryParam !== null) | ||
21372 | return signature.recoveryParam; | ||
21373 | |||
21374 | for (var i = 0; i < 4; i++) { | ||
21375 | var Qprime; | ||
21376 | try { | ||
21377 | Qprime = this.recoverPubKey(e, signature, i); | ||
21378 | } catch (e) { | ||
21379 | continue; | ||
21380 | } | ||
21381 | |||
21382 | if (Qprime.eq(Q)) | ||
21383 | return i; | ||
21384 | } | ||
21385 | throw new Error('Unable to find valid recovery factor'); | ||
21386 | }; | ||
21387 | |||
21388 | },{"../../elliptic":127,"./key":135,"./signature":136,"bn.js":75,"hmac-drbg":159}],135:[function(require,module,exports){ | ||
21389 | 'use strict'; | ||
21390 | |||
21391 | var BN = require('bn.js'); | ||
21392 | var elliptic = require('../../elliptic'); | ||
21393 | var utils = elliptic.utils; | ||
21394 | var assert = utils.assert; | ||
21395 | |||
21396 | function KeyPair(ec, options) { | ||
21397 | this.ec = ec; | ||
21398 | this.priv = null; | ||
21399 | this.pub = null; | ||
21400 | |||
21401 | // KeyPair(ec, { priv: ..., pub: ... }) | ||
21402 | if (options.priv) | ||
21403 | this._importPrivate(options.priv, options.privEnc); | ||
21404 | if (options.pub) | ||
21405 | this._importPublic(options.pub, options.pubEnc); | ||
21406 | } | ||
21407 | module.exports = KeyPair; | ||
21408 | |||
21409 | KeyPair.fromPublic = function fromPublic(ec, pub, enc) { | ||
21410 | if (pub instanceof KeyPair) | ||
21411 | return pub; | ||
21412 | |||
21413 | return new KeyPair(ec, { | ||
21414 | pub: pub, | ||
21415 | pubEnc: enc | ||
21416 | }); | ||
21417 | }; | ||
21418 | |||
21419 | KeyPair.fromPrivate = function fromPrivate(ec, priv, enc) { | ||
21420 | if (priv instanceof KeyPair) | ||
21421 | return priv; | ||
21422 | |||
21423 | return new KeyPair(ec, { | ||
21424 | priv: priv, | ||
21425 | privEnc: enc | ||
21426 | }); | ||
21427 | }; | ||
21428 | |||
21429 | KeyPair.prototype.validate = function validate() { | ||
21430 | var pub = this.getPublic(); | ||
21431 | |||
21432 | if (pub.isInfinity()) | ||
21433 | return { result: false, reason: 'Invalid public key' }; | ||
21434 | if (!pub.validate()) | ||
21435 | return { result: false, reason: 'Public key is not a point' }; | ||
21436 | if (!pub.mul(this.ec.curve.n).isInfinity()) | ||
21437 | return { result: false, reason: 'Public key * N != O' }; | ||
21438 | |||
21439 | return { result: true, reason: null }; | ||
21440 | }; | ||
21441 | |||
21442 | KeyPair.prototype.getPublic = function getPublic(compact, enc) { | ||
21443 | // compact is optional argument | ||
21444 | if (typeof compact === 'string') { | ||
21445 | enc = compact; | ||
21446 | compact = null; | ||
21447 | } | ||
21448 | |||
21449 | if (!this.pub) | ||
21450 | this.pub = this.ec.g.mul(this.priv); | ||
21451 | |||
21452 | if (!enc) | ||
21453 | return this.pub; | ||
21454 | |||
21455 | return this.pub.encode(enc, compact); | ||
21456 | }; | ||
21457 | |||
21458 | KeyPair.prototype.getPrivate = function getPrivate(enc) { | ||
21459 | if (enc === 'hex') | ||
21460 | return this.priv.toString(16, 2); | ||
21461 | else | ||
21462 | return this.priv; | ||
21463 | }; | ||
21464 | |||
21465 | KeyPair.prototype._importPrivate = function _importPrivate(key, enc) { | ||
21466 | this.priv = new BN(key, enc || 16); | ||
21467 | |||
21468 | // Ensure that the priv won't be bigger than n, otherwise we may fail | ||
21469 | // in fixed multiplication method | ||
21470 | this.priv = this.priv.umod(this.ec.curve.n); | ||
21471 | }; | ||
21472 | |||
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'); | ||
21483 | } | ||
21484 | this.pub = this.ec.curve.point(key.x, key.y); | ||
21485 | return; | ||
21486 | } | ||
21487 | this.pub = this.ec.curve.decodePoint(key, enc); | ||
21488 | }; | ||
21489 | |||
21490 | // ECDH | ||
21491 | KeyPair.prototype.derive = function derive(pub) { | ||
21492 | return pub.mul(this.priv).getX(); | ||
21493 | }; | ||
21494 | |||
21495 | // ECDSA | ||
21496 | KeyPair.prototype.sign = function sign(msg, enc, options) { | ||
21497 | return this.ec.sign(msg, this, enc, options); | ||
21498 | }; | ||
21499 | |||
21500 | KeyPair.prototype.verify = function verify(msg, signature) { | ||
21501 | return this.ec.verify(msg, signature, this); | ||
21502 | }; | ||
21503 | |||
21504 | KeyPair.prototype.inspect = function inspect() { | ||
21505 | return '<Key priv: ' + (this.priv && this.priv.toString(16, 2)) + | ||
21506 | ' pub: ' + (this.pub && this.pub.inspect()) + ' >'; | ||
21507 | }; | ||
21508 | |||
21509 | },{"../../elliptic":127,"bn.js":75}],136:[function(require,module,exports){ | ||
21510 | 'use strict'; | ||
21511 | |||
21512 | var BN = require('bn.js'); | ||
21513 | |||
21514 | var elliptic = require('../../elliptic'); | ||
21515 | var utils = elliptic.utils; | ||
21516 | var assert = utils.assert; | ||
21517 | |||
21518 | function Signature(options, enc) { | ||
21519 | if (options instanceof Signature) | ||
21520 | return options; | ||
21521 | |||
21522 | if (this._importDER(options, enc)) | ||
21523 | return; | ||
21524 | |||
21525 | assert(options.r && options.s, 'Signature without r or s'); | ||
21526 | this.r = new BN(options.r, 16); | ||
21527 | this.s = new BN(options.s, 16); | ||
21528 | if (options.recoveryParam === undefined) | ||
21529 | this.recoveryParam = null; | ||
21530 | else | ||
21531 | this.recoveryParam = options.recoveryParam; | ||
21532 | } | ||
21533 | module.exports = Signature; | ||
21534 | |||
21535 | function Position() { | ||
21536 | this.place = 0; | ||
21537 | } | ||
21538 | |||
21539 | function getLength(buf, p) { | ||
21540 | var initial = buf[p.place++]; | ||
21541 | if (!(initial & 0x80)) { | ||
21542 | return initial; | ||
21543 | } | ||
21544 | var octetLen = initial & 0xf; | ||
21545 | var val = 0; | ||
21546 | for (var i = 0, off = p.place; i < octetLen; i++, off++) { | ||
21547 | val <<= 8; | ||
21548 | val |= buf[off]; | ||
21549 | } | ||
21550 | p.place = off; | ||
21551 | return val; | ||
21552 | } | ||
21553 | |||
21554 | function rmPadding(buf) { | ||
21555 | var i = 0; | ||
21556 | var len = buf.length - 1; | ||
21557 | while (!buf[i] && !(buf[i + 1] & 0x80) && i < len) { | ||
21558 | i++; | ||
21559 | } | ||
21560 | if (i === 0) { | ||
21561 | return buf; | ||
21562 | } | ||
21563 | return buf.slice(i); | ||
21564 | } | ||
21565 | |||
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) { | ||
21570 | return false; | ||
21571 | } | ||
21572 | var len = getLength(data, p); | ||
21573 | if ((len + p.place) !== data.length) { | ||
21574 | return false; | ||
21575 | } | ||
21576 | if (data[p.place++] !== 0x02) { | ||
21577 | return false; | ||
21578 | } | ||
21579 | var rlen = getLength(data, p); | ||
21580 | var r = data.slice(p.place, rlen + p.place); | ||
21581 | p.place += rlen; | ||
21582 | if (data[p.place++] !== 0x02) { | ||
21583 | return false; | ||
21584 | } | ||
21585 | var slen = getLength(data, p); | ||
21586 | if (data.length !== slen + p.place) { | ||
21587 | return false; | ||
21588 | } | ||
21589 | var s = data.slice(p.place, slen + p.place); | ||
21590 | if (r[0] === 0 && (r[1] & 0x80)) { | ||
21591 | r = r.slice(1); | ||
21592 | } | ||
21593 | if (s[0] === 0 && (s[1] & 0x80)) { | ||
21594 | s = s.slice(1); | ||
21595 | } | ||
21596 | |||
21597 | this.r = new BN(r); | ||
21598 | this.s = new BN(s); | ||
21599 | this.recoveryParam = null; | ||
21600 | |||
21601 | return true; | ||
21602 | }; | ||
21603 | |||
21604 | function constructLength(arr, len) { | ||
21605 | if (len < 0x80) { | ||
21606 | arr.push(len); | ||
21607 | return; | ||
21608 | } | ||
21609 | var octets = 1 + (Math.log(len) / Math.LN2 >>> 3); | ||
21610 | arr.push(octets | 0x80); | ||
21611 | while (--octets) { | ||
21612 | arr.push((len >>> (octets << 3)) & 0xff); | ||
21613 | } | ||
21614 | arr.push(len); | ||
21615 | } | ||
21616 | |||
21617 | Signature.prototype.toDER = function toDER(enc) { | ||
21618 | var r = this.r.toArray(); | ||
21619 | var s = this.s.toArray(); | ||
21620 | |||
21621 | // Pad values | ||
21622 | if (r[0] & 0x80) | ||
21623 | r = [ 0 ].concat(r); | ||
21624 | // Pad values | ||
21625 | if (s[0] & 0x80) | ||
21626 | s = [ 0 ].concat(s); | ||
21627 | |||
21628 | r = rmPadding(r); | ||
21629 | s = rmPadding(s); | ||
21630 | |||
21631 | while (!s[0] && !(s[1] & 0x80)) { | ||
21632 | s = s.slice(1); | ||
21633 | } | ||
21634 | var arr = [ 0x02 ]; | ||
21635 | constructLength(arr, r.length); | ||
21636 | arr = arr.concat(r); | ||
21637 | arr.push(0x02); | ||
21638 | constructLength(arr, s.length); | ||
21639 | var backHalf = arr.concat(s); | ||
21640 | var res = [ 0x30 ]; | ||
21641 | constructLength(res, backHalf.length); | ||
21642 | res = res.concat(backHalf); | ||
21643 | return utils.encode(res, enc); | ||
21644 | }; | ||
21645 | |||
21646 | },{"../../elliptic":127,"bn.js":75}],137:[function(require,module,exports){ | ||
21647 | 'use strict'; | ||
21648 | |||
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'); | ||
21656 | |||
21657 | function EDDSA(curve) { | ||
21658 | assert(curve === 'ed25519', 'only tested with ed25519 so far'); | ||
21659 | |||
21660 | if (!(this instanceof EDDSA)) | ||
21661 | return new EDDSA(curve); | ||
21662 | |||
21663 | var curve = elliptic.curves[curve].curve; | ||
21664 | this.curve = curve; | ||
21665 | this.g = curve.g; | ||
21666 | this.g.precompute(curve.n.bitLength() + 1); | ||
21667 | |||
21668 | this.pointClass = curve.point().constructor; | ||
21669 | this.encodingLength = Math.ceil(curve.n.bitLength() / 8); | ||
21670 | this.hash = hash.sha512; | ||
21671 | } | ||
21672 | |||
21673 | module.exports = EDDSA; | ||
21674 | |||
21675 | /** | ||
21676 | * @param {Array|String} message - message bytes | ||
21677 | * @param {Array|String|KeyPair} secret - secret bytes or a keypair | ||
21678 | * @returns {Signature} - signature | ||
21679 | */ | ||
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) | ||
21687 | .mul(key.priv()); | ||
21688 | var S = r.add(s_).umod(this.curve.n); | ||
21689 | return this.makeSignature({ R: R, S: S, Rencoded: Rencoded }); | ||
21690 | }; | ||
21691 | |||
21692 | /** | ||
21693 | * @param {Array} message - message bytes | ||
21694 | * @param {Array|String|Signature} sig - sig bytes | ||
21695 | * @param {Array|String|Point|KeyPair} pub - public key | ||
21696 | * @returns {Boolean} - true if public key matches sig of message | ||
21697 | */ | ||
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); | ||
21706 | }; | ||
21707 | |||
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); | ||
21713 | }; | ||
21714 | |||
21715 | EDDSA.prototype.keyFromPublic = function keyFromPublic(pub) { | ||
21716 | return KeyPair.fromPublic(this, pub); | ||
21717 | }; | ||
21718 | |||
21719 | EDDSA.prototype.keyFromSecret = function keyFromSecret(secret) { | ||
21720 | return KeyPair.fromSecret(this, secret); | ||
21721 | }; | ||
21722 | |||
21723 | EDDSA.prototype.makeSignature = function makeSignature(sig) { | ||
21724 | if (sig instanceof Signature) | ||
21725 | return sig; | ||
21726 | return new Signature(this, sig); | ||
21727 | }; | ||
21728 | |||
21729 | /** | ||
21730 | * * https://tools.ietf.org/html/draft-josefsson-eddsa-ed25519-03#section-5.2 | ||
21731 | * | ||
21732 | * EDDSA defines methods for encoding and decoding points and integers. These are | ||
21733 | * helper convenience methods, that pass along to utility functions implied | ||
21734 | * parameters. | ||
21735 | * | ||
21736 | */ | ||
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; | ||
21740 | return enc; | ||
21741 | }; | ||
21742 | |||
21743 | EDDSA.prototype.decodePoint = function decodePoint(bytes) { | ||
21744 | bytes = utils.parseBytes(bytes); | ||
21745 | |||
21746 | var lastIx = bytes.length - 1; | ||
21747 | var normed = bytes.slice(0, lastIx).concat(bytes[lastIx] & ~0x80); | ||
21748 | var xIsOdd = (bytes[lastIx] & 0x80) !== 0; | ||
21749 | |||
21750 | var y = utils.intFromLE(normed); | ||
21751 | return this.curve.pointFromY(y, xIsOdd); | ||
21752 | }; | ||
21753 | |||
21754 | EDDSA.prototype.encodeInt = function encodeInt(num) { | ||
21755 | return num.toArray('le', this.encodingLength); | ||
21756 | }; | ||
21757 | |||
21758 | EDDSA.prototype.decodeInt = function decodeInt(bytes) { | ||
21759 | return utils.intFromLE(bytes); | ||
21760 | }; | ||
21761 | |||
21762 | EDDSA.prototype.isPoint = function isPoint(val) { | ||
21763 | return val instanceof this.pointClass; | ||
21764 | }; | ||
21765 | |||
21766 | },{"../../elliptic":127,"./key":138,"./signature":139,"hash.js":147}],138:[function(require,module,exports){ | ||
21767 | 'use strict'; | ||
21768 | |||
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; | ||
21774 | |||
21775 | /** | ||
21776 | * @param {EDDSA} eddsa - instance | ||
21777 | * @param {Object} params - public/private key parameters | ||
21778 | * | ||
21779 | * @param {Array<Byte>} [params.secret] - secret seed bytes | ||
21780 | * @param {Point} [params.pub] - public key point (aka `A` in eddsa terms) | ||
21781 | * @param {Array<Byte>} [params.pub] - public key point encoded as bytes | ||
21782 | * | ||
21783 | */ | ||
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; | ||
21789 | else | ||
21790 | this._pubBytes = parseBytes(params.pub); | ||
21791 | } | ||
21792 | |||
21793 | KeyPair.fromPublic = function fromPublic(eddsa, pub) { | ||
21794 | if (pub instanceof KeyPair) | ||
21795 | return pub; | ||
21796 | return new KeyPair(eddsa, { pub: pub }); | ||
21797 | }; | ||
21798 | |||
21799 | KeyPair.fromSecret = function fromSecret(eddsa, secret) { | ||
21800 | if (secret instanceof KeyPair) | ||
21801 | return secret; | ||
21802 | return new KeyPair(eddsa, { secret: secret }); | ||
21803 | }; | ||
21804 | |||
21805 | KeyPair.prototype.secret = function secret() { | ||
21806 | return this._secret; | ||
21807 | }; | ||
21808 | |||
21809 | cachedProperty(KeyPair, 'pubBytes', function pubBytes() { | ||
21810 | return this.eddsa.encodePoint(this.pub()); | ||
21811 | }); | ||
21812 | |||
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()); | ||
21817 | }); | ||
21818 | |||
21819 | cachedProperty(KeyPair, 'privBytes', function privBytes() { | ||
21820 | var eddsa = this.eddsa; | ||
21821 | var hash = this.hash(); | ||
21822 | var lastIx = eddsa.encodingLength - 1; | ||
21823 | |||
21824 | var a = hash.slice(0, eddsa.encodingLength); | ||
21825 | a[0] &= 248; | ||
21826 | a[lastIx] &= 127; | ||
21827 | a[lastIx] |= 64; | ||
21828 | |||
21829 | return a; | ||
21830 | }); | ||
21831 | |||
21832 | cachedProperty(KeyPair, 'priv', function priv() { | ||
21833 | return this.eddsa.decodeInt(this.privBytes()); | ||
21834 | }); | ||
21835 | |||
21836 | cachedProperty(KeyPair, 'hash', function hash() { | ||
21837 | return this.eddsa.hash().update(this.secret()).digest(); | ||
21838 | }); | ||
21839 | |||
21840 | cachedProperty(KeyPair, 'messagePrefix', function messagePrefix() { | ||
21841 | return this.hash().slice(this.eddsa.encodingLength); | ||
21842 | }); | ||
21843 | |||
21844 | KeyPair.prototype.sign = function sign(message) { | ||
21845 | assert(this._secret, 'KeyPair can only verify'); | ||
21846 | return this.eddsa.sign(message, this); | ||
21847 | }; | ||
21848 | |||
21849 | KeyPair.prototype.verify = function verify(message, sig) { | ||
21850 | return this.eddsa.verify(message, sig, this); | ||
21851 | }; | ||
21852 | |||
21853 | KeyPair.prototype.getSecret = function getSecret(enc) { | ||
21854 | assert(this._secret, 'KeyPair is public only'); | ||
21855 | return utils.encode(this.secret(), enc); | ||
21856 | }; | ||
21857 | |||
21858 | KeyPair.prototype.getPublic = function getPublic(enc) { | ||
21859 | return utils.encode(this.pubBytes(), enc); | ||
21860 | }; | ||
21861 | |||
21862 | module.exports = KeyPair; | ||
21863 | |||
21864 | },{"../../elliptic":127}],139:[function(require,module,exports){ | ||
21865 | 'use strict'; | ||
21866 | |||
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; | ||
21873 | |||
21874 | /** | ||
21875 | * @param {EDDSA} eddsa - eddsa instance | ||
21876 | * @param {Array<Bytes>|Object} sig - | ||
21877 | * @param {Array<Bytes>|Point} [sig.R] - R point as Point or bytes | ||
21878 | * @param {Array<Bytes>|bn} [sig.S] - S scalar as bn or bytes | ||
21879 | * @param {Array<Bytes>} [sig.Rencoded] - R point encoded | ||
21880 | * @param {Array<Bytes>} [sig.Sencoded] - S scalar encoded | ||
21881 | */ | ||
21882 | function Signature(eddsa, sig) { | ||
21883 | this.eddsa = eddsa; | ||
21884 | |||
21885 | if (typeof sig !== 'object') | ||
21886 | sig = parseBytes(sig); | ||
21887 | |||
21888 | if (Array.isArray(sig)) { | ||
21889 | sig = { | ||
21890 | R: sig.slice(0, eddsa.encodingLength), | ||
21891 | S: sig.slice(eddsa.encodingLength) | ||
21892 | }; | ||
21893 | } | ||
21894 | |||
21895 | assert(sig.R && sig.S, 'Signature without R or S'); | ||
21896 | |||
21897 | if (eddsa.isPoint(sig.R)) | ||
21898 | this._R = sig.R; | ||
21899 | if (sig.S instanceof BN) | ||
21900 | this._S = sig.S; | ||
21901 | |||
21902 | this._Rencoded = Array.isArray(sig.R) ? sig.R : sig.Rencoded; | ||
21903 | this._Sencoded = Array.isArray(sig.S) ? sig.S : sig.Sencoded; | ||
21904 | } | ||
21905 | |||
21906 | cachedProperty(Signature, 'S', function S() { | ||
21907 | return this.eddsa.decodeInt(this.Sencoded()); | ||
21908 | }); | ||
21909 | |||
21910 | cachedProperty(Signature, 'R', function R() { | ||
21911 | return this.eddsa.decodePoint(this.Rencoded()); | ||
21912 | }); | ||
21913 | |||
21914 | cachedProperty(Signature, 'Rencoded', function Rencoded() { | ||
21915 | return this.eddsa.encodePoint(this.R()); | ||
21916 | }); | ||
21917 | |||
21918 | cachedProperty(Signature, 'Sencoded', function Sencoded() { | ||
21919 | return this.eddsa.encodeInt(this.S()); | ||
21920 | }); | ||
21921 | |||
21922 | Signature.prototype.toBytes = function toBytes() { | ||
21923 | return this.Rencoded().concat(this.Sencoded()); | ||
21924 | }; | ||
21925 | |||
21926 | Signature.prototype.toHex = function toHex() { | ||
21927 | return utils.encode(this.toBytes(), 'hex').toUpperCase(); | ||
21928 | }; | ||
21929 | |||
21930 | module.exports = Signature; | ||
21931 | |||
21932 | },{"../../elliptic":127,"bn.js":75}],140:[function(require,module,exports){ | ||
21933 | module.exports = { | ||
21934 | doubles: { | ||
21935 | step: 4, | ||
21936 | points: [ | ||
21937 | [ | ||
21938 | 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', | ||
21939 | 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' | ||
21940 | ], | ||
21941 | [ | ||
21942 | '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', | ||
21943 | '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' | ||
21944 | ], | ||
21945 | [ | ||
21946 | '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', | ||
21947 | 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' | ||
21948 | ], | ||
21949 | [ | ||
21950 | '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', | ||
21951 | '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' | ||
21952 | ], | ||
21953 | [ | ||
21954 | '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', | ||
21955 | '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' | ||
21956 | ], | ||
21957 | [ | ||
21958 | '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', | ||
21959 | '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' | ||
21960 | ], | ||
21961 | [ | ||
21962 | 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', | ||
21963 | '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' | ||
21964 | ], | ||
21965 | [ | ||
21966 | '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', | ||
21967 | 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' | ||
21968 | ], | ||
21969 | [ | ||
21970 | 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', | ||
21971 | '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' | ||
21972 | ], | ||
21973 | [ | ||
21974 | 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', | ||
21975 | 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' | ||
21976 | ], | ||
21977 | [ | ||
21978 | 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', | ||
21979 | '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' | ||
21980 | ], | ||
21981 | [ | ||
21982 | '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', | ||
21983 | '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' | ||
21984 | ], | ||
21985 | [ | ||
21986 | '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', | ||
21987 | '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' | ||
21988 | ], | ||
21989 | [ | ||
21990 | '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', | ||
21991 | '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' | ||
21992 | ], | ||
21993 | [ | ||
21994 | '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', | ||
21995 | '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' | ||
21996 | ], | ||
21997 | [ | ||
21998 | '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', | ||
21999 | '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' | ||
22000 | ], | ||
22001 | [ | ||
22002 | '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', | ||
22003 | '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' | ||
22004 | ], | ||
22005 | [ | ||
22006 | '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', | ||
22007 | '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' | ||
22008 | ], | ||
22009 | [ | ||
22010 | '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', | ||
22011 | 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' | ||
22012 | ], | ||
22013 | [ | ||
22014 | 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', | ||
22015 | '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' | ||
22016 | ], | ||
22017 | [ | ||
22018 | 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', | ||
22019 | '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' | ||
22020 | ], | ||
22021 | [ | ||
22022 | '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', | ||
22023 | '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' | ||
22024 | ], | ||
22025 | [ | ||
22026 | '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', | ||
22027 | '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' | ||
22028 | ], | ||
22029 | [ | ||
22030 | 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', | ||
22031 | '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' | ||
22032 | ], | ||
22033 | [ | ||
22034 | '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', | ||
22035 | 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' | ||
22036 | ], | ||
22037 | [ | ||
22038 | 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', | ||
22039 | '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' | ||
22040 | ], | ||
22041 | [ | ||
22042 | 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', | ||
22043 | 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' | ||
22044 | ], | ||
22045 | [ | ||
22046 | 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', | ||
22047 | '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' | ||
22048 | ], | ||
22049 | [ | ||
22050 | 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', | ||
22051 | 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' | ||
22052 | ], | ||
22053 | [ | ||
22054 | 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', | ||
22055 | '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' | ||
22056 | ], | ||
22057 | [ | ||
22058 | '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', | ||
22059 | 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' | ||
22060 | ], | ||
22061 | [ | ||
22062 | '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', | ||
22063 | '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' | ||
22064 | ], | ||
22065 | [ | ||
22066 | 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', | ||
22067 | '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' | ||
22068 | ], | ||
22069 | [ | ||
22070 | '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', | ||
22071 | 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' | ||
22072 | ], | ||
22073 | [ | ||
22074 | 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', | ||
22075 | '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' | ||
22076 | ], | ||
22077 | [ | ||
22078 | 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', | ||
22079 | '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' | ||
22080 | ], | ||
22081 | [ | ||
22082 | 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', | ||
22083 | 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' | ||
22084 | ], | ||
22085 | [ | ||
22086 | '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', | ||
22087 | '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' | ||
22088 | ], | ||
22089 | [ | ||
22090 | '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', | ||
22091 | '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' | ||
22092 | ], | ||
22093 | [ | ||
22094 | '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', | ||
22095 | 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' | ||
22096 | ], | ||
22097 | [ | ||
22098 | '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', | ||
22099 | '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' | ||
22100 | ], | ||
22101 | [ | ||
22102 | 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', | ||
22103 | '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' | ||
22104 | ], | ||
22105 | [ | ||
22106 | '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', | ||
22107 | '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' | ||
22108 | ], | ||
22109 | [ | ||
22110 | '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', | ||
22111 | 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' | ||
22112 | ], | ||
22113 | [ | ||
22114 | '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', | ||
22115 | '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' | ||
22116 | ], | ||
22117 | [ | ||
22118 | 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', | ||
22119 | '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' | ||
22120 | ], | ||
22121 | [ | ||
22122 | '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', | ||
22123 | 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' | ||
22124 | ], | ||
22125 | [ | ||
22126 | 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', | ||
22127 | 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' | ||
22128 | ], | ||
22129 | [ | ||
22130 | 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', | ||
22131 | '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' | ||
22132 | ], | ||
22133 | [ | ||
22134 | '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', | ||
22135 | 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' | ||
22136 | ], | ||
22137 | [ | ||
22138 | '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', | ||
22139 | 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' | ||
22140 | ], | ||
22141 | [ | ||
22142 | 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', | ||
22143 | '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' | ||
22144 | ], | ||
22145 | [ | ||
22146 | 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', | ||
22147 | '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' | ||
22148 | ], | ||
22149 | [ | ||
22150 | 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', | ||
22151 | '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' | ||
22152 | ], | ||
22153 | [ | ||
22154 | '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', | ||
22155 | 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' | ||
22156 | ], | ||
22157 | [ | ||
22158 | '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', | ||
22159 | '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' | ||
22160 | ], | ||
22161 | [ | ||
22162 | 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', | ||
22163 | 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' | ||
22164 | ], | ||
22165 | [ | ||
22166 | '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', | ||
22167 | 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' | ||
22168 | ], | ||
22169 | [ | ||
22170 | '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', | ||
22171 | '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' | ||
22172 | ], | ||
22173 | [ | ||
22174 | '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', | ||
22175 | '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' | ||
22176 | ], | ||
22177 | [ | ||
22178 | 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', | ||
22179 | 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' | ||
22180 | ], | ||
22181 | [ | ||
22182 | '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', | ||
22183 | '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' | ||
22184 | ], | ||
22185 | [ | ||
22186 | '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', | ||
22187 | '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' | ||
22188 | ], | ||
22189 | [ | ||
22190 | 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', | ||
22191 | '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' | ||
22192 | ], | ||
22193 | [ | ||
22194 | 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', | ||
22195 | 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' | ||
22196 | ] | ||
22197 | ] | ||
22198 | }, | ||
22199 | naf: { | ||
22200 | wnd: 7, | ||
22201 | points: [ | ||
22202 | [ | ||
22203 | 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', | ||
22204 | '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' | ||
22205 | ], | ||
22206 | [ | ||
22207 | '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', | ||
22208 | 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' | ||
22209 | ], | ||
22210 | [ | ||
22211 | '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', | ||
22212 | '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' | ||
22213 | ], | ||
22214 | [ | ||
22215 | 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', | ||
22216 | 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' | ||
22217 | ], | ||
22218 | [ | ||
22219 | '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', | ||
22220 | 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' | ||
22221 | ], | ||
22222 | [ | ||
22223 | 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', | ||
22224 | 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' | ||
22225 | ], | ||
22226 | [ | ||
22227 | 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', | ||
22228 | '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' | ||
22229 | ], | ||
22230 | [ | ||
22231 | 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', | ||
22232 | '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' | ||
22233 | ], | ||
22234 | [ | ||
22235 | '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', | ||
22236 | '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' | ||
22237 | ], | ||
22238 | [ | ||
22239 | '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', | ||
22240 | '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' | ||
22241 | ], | ||
22242 | [ | ||
22243 | '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', | ||
22244 | '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' | ||
22245 | ], | ||
22246 | [ | ||
22247 | '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', | ||
22248 | '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' | ||
22249 | ], | ||
22250 | [ | ||
22251 | 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', | ||
22252 | 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' | ||
22253 | ], | ||
22254 | [ | ||
22255 | 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', | ||
22256 | '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' | ||
22257 | ], | ||
22258 | [ | ||
22259 | '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', | ||
22260 | 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' | ||
22261 | ], | ||
22262 | [ | ||
22263 | '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', | ||
22264 | 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' | ||
22265 | ], | ||
22266 | [ | ||
22267 | '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', | ||
22268 | '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' | ||
22269 | ], | ||
22270 | [ | ||
22271 | '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', | ||
22272 | '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' | ||
22273 | ], | ||
22274 | [ | ||
22275 | '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', | ||
22276 | '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' | ||
22277 | ], | ||
22278 | [ | ||
22279 | '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', | ||
22280 | 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' | ||
22281 | ], | ||
22282 | [ | ||
22283 | 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', | ||
22284 | 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' | ||
22285 | ], | ||
22286 | [ | ||
22287 | '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', | ||
22288 | '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' | ||
22289 | ], | ||
22290 | [ | ||
22291 | '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', | ||
22292 | '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' | ||
22293 | ], | ||
22294 | [ | ||
22295 | 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', | ||
22296 | 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' | ||
22297 | ], | ||
22298 | [ | ||
22299 | '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', | ||
22300 | '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' | ||
22301 | ], | ||
22302 | [ | ||
22303 | 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', | ||
22304 | 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' | ||
22305 | ], | ||
22306 | [ | ||
22307 | 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', | ||
22308 | 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' | ||
22309 | ], | ||
22310 | [ | ||
22311 | '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', | ||
22312 | '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' | ||
22313 | ], | ||
22314 | [ | ||
22315 | '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', | ||
22316 | '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' | ||
22317 | ], | ||
22318 | [ | ||
22319 | '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', | ||
22320 | '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' | ||
22321 | ], | ||
22322 | [ | ||
22323 | 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', | ||
22324 | '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' | ||
22325 | ], | ||
22326 | [ | ||
22327 | '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', | ||
22328 | '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' | ||
22329 | ], | ||
22330 | [ | ||
22331 | 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', | ||
22332 | '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' | ||
22333 | ], | ||
22334 | [ | ||
22335 | '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', | ||
22336 | 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' | ||
22337 | ], | ||
22338 | [ | ||
22339 | '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', | ||
22340 | 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' | ||
22341 | ], | ||
22342 | [ | ||
22343 | 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', | ||
22344 | 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' | ||
22345 | ], | ||
22346 | [ | ||
22347 | '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', | ||
22348 | '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' | ||
22349 | ], | ||
22350 | [ | ||
22351 | '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', | ||
22352 | 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' | ||
22353 | ], | ||
22354 | [ | ||
22355 | 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', | ||
22356 | 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' | ||
22357 | ], | ||
22358 | [ | ||
22359 | '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', | ||
22360 | '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' | ||
22361 | ], | ||
22362 | [ | ||
22363 | '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', | ||
22364 | 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' | ||
22365 | ], | ||
22366 | [ | ||
22367 | '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', | ||
22368 | '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' | ||
22369 | ], | ||
22370 | [ | ||
22371 | '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', | ||
22372 | 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' | ||
22373 | ], | ||
22374 | [ | ||
22375 | 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', | ||
22376 | '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' | ||
22377 | ], | ||
22378 | [ | ||
22379 | '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', | ||
22380 | '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' | ||
22381 | ], | ||
22382 | [ | ||
22383 | '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', | ||
22384 | 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' | ||
22385 | ], | ||
22386 | [ | ||
22387 | '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', | ||
22388 | 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' | ||
22389 | ], | ||
22390 | [ | ||
22391 | 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', | ||
22392 | 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' | ||
22393 | ], | ||
22394 | [ | ||
22395 | 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', | ||
22396 | 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' | ||
22397 | ], | ||
22398 | [ | ||
22399 | '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', | ||
22400 | '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' | ||
22401 | ], | ||
22402 | [ | ||
22403 | '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', | ||
22404 | '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' | ||
22405 | ], | ||
22406 | [ | ||
22407 | 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', | ||
22408 | '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' | ||
22409 | ], | ||
22410 | [ | ||
22411 | 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', | ||
22412 | 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' | ||
22413 | ], | ||
22414 | [ | ||
22415 | '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', | ||
22416 | '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' | ||
22417 | ], | ||
22418 | [ | ||
22419 | '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', | ||
22420 | '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' | ||
22421 | ], | ||
22422 | [ | ||
22423 | 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', | ||
22424 | '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' | ||
22425 | ], | ||
22426 | [ | ||
22427 | '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', | ||
22428 | '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' | ||
22429 | ], | ||
22430 | [ | ||
22431 | 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', | ||
22432 | 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' | ||
22433 | ], | ||
22434 | [ | ||
22435 | '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', | ||
22436 | 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' | ||
22437 | ], | ||
22438 | [ | ||
22439 | '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', | ||
22440 | '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' | ||
22441 | ], | ||
22442 | [ | ||
22443 | 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', | ||
22444 | '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' | ||
22445 | ], | ||
22446 | [ | ||
22447 | 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', | ||
22448 | '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' | ||
22449 | ], | ||
22450 | [ | ||
22451 | '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', | ||
22452 | '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' | ||
22453 | ], | ||
22454 | [ | ||
22455 | '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', | ||
22456 | '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' | ||
22457 | ], | ||
22458 | [ | ||
22459 | '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', | ||
22460 | 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' | ||
22461 | ], | ||
22462 | [ | ||
22463 | '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', | ||
22464 | 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' | ||
22465 | ], | ||
22466 | [ | ||
22467 | '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', | ||
22468 | '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' | ||
22469 | ], | ||
22470 | [ | ||
22471 | '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', | ||
22472 | '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' | ||
22473 | ], | ||
22474 | [ | ||
22475 | '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', | ||
22476 | '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' | ||
22477 | ], | ||
22478 | [ | ||
22479 | '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', | ||
22480 | 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' | ||
22481 | ], | ||
22482 | [ | ||
22483 | 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', | ||
22484 | 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' | ||
22485 | ], | ||
22486 | [ | ||
22487 | '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', | ||
22488 | 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' | ||
22489 | ], | ||
22490 | [ | ||
22491 | 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', | ||
22492 | '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' | ||
22493 | ], | ||
22494 | [ | ||
22495 | 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', | ||
22496 | '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' | ||
22497 | ], | ||
22498 | [ | ||
22499 | 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', | ||
22500 | '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' | ||
22501 | ], | ||
22502 | [ | ||
22503 | 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', | ||
22504 | '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' | ||
22505 | ], | ||
22506 | [ | ||
22507 | '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', | ||
22508 | 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' | ||
22509 | ], | ||
22510 | [ | ||
22511 | '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', | ||
22512 | '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' | ||
22513 | ], | ||
22514 | [ | ||
22515 | '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', | ||
22516 | 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' | ||
22517 | ], | ||
22518 | [ | ||
22519 | 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', | ||
22520 | 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' | ||
22521 | ], | ||
22522 | [ | ||
22523 | 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', | ||
22524 | '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' | ||
22525 | ], | ||
22526 | [ | ||
22527 | 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', | ||
22528 | 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' | ||
22529 | ], | ||
22530 | [ | ||
22531 | 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', | ||
22532 | '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' | ||
22533 | ], | ||
22534 | [ | ||
22535 | '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', | ||
22536 | '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' | ||
22537 | ], | ||
22538 | [ | ||
22539 | 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', | ||
22540 | '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' | ||
22541 | ], | ||
22542 | [ | ||
22543 | 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', | ||
22544 | '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' | ||
22545 | ], | ||
22546 | [ | ||
22547 | '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', | ||
22548 | '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' | ||
22549 | ], | ||
22550 | [ | ||
22551 | '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', | ||
22552 | 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' | ||
22553 | ], | ||
22554 | [ | ||
22555 | 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', | ||
22556 | '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' | ||
22557 | ], | ||
22558 | [ | ||
22559 | 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', | ||
22560 | '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' | ||
22561 | ], | ||
22562 | [ | ||
22563 | 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', | ||
22564 | '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' | ||
22565 | ], | ||
22566 | [ | ||
22567 | '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', | ||
22568 | '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' | ||
22569 | ], | ||
22570 | [ | ||
22571 | 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', | ||
22572 | 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' | ||
22573 | ], | ||
22574 | [ | ||
22575 | '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', | ||
22576 | 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' | ||
22577 | ], | ||
22578 | [ | ||
22579 | 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', | ||
22580 | 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' | ||
22581 | ], | ||
22582 | [ | ||
22583 | 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', | ||
22584 | '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' | ||
22585 | ], | ||
22586 | [ | ||
22587 | '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', | ||
22588 | 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' | ||
22589 | ], | ||
22590 | [ | ||
22591 | 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', | ||
22592 | '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' | ||
22593 | ], | ||
22594 | [ | ||
22595 | 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', | ||
22596 | '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' | ||
22597 | ], | ||
22598 | [ | ||
22599 | 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', | ||
22600 | '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' | ||
22601 | ], | ||
22602 | [ | ||
22603 | '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', | ||
22604 | 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' | ||
22605 | ], | ||
22606 | [ | ||
22607 | '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', | ||
22608 | 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' | ||
22609 | ], | ||
22610 | [ | ||
22611 | 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', | ||
22612 | '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' | ||
22613 | ], | ||
22614 | [ | ||
22615 | '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', | ||
22616 | 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' | ||
22617 | ], | ||
22618 | [ | ||
22619 | '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', | ||
22620 | '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' | ||
22621 | ], | ||
22622 | [ | ||
22623 | '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', | ||
22624 | 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' | ||
22625 | ], | ||
22626 | [ | ||
22627 | 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', | ||
22628 | 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' | ||
22629 | ], | ||
22630 | [ | ||
22631 | '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', | ||
22632 | 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' | ||
22633 | ], | ||
22634 | [ | ||
22635 | '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', | ||
22636 | '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' | ||
22637 | ], | ||
22638 | [ | ||
22639 | '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', | ||
22640 | 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' | ||
22641 | ], | ||
22642 | [ | ||
22643 | '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', | ||
22644 | '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' | ||
22645 | ], | ||
22646 | [ | ||
22647 | 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', | ||
22648 | 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' | ||
22649 | ], | ||
22650 | [ | ||
22651 | '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', | ||
22652 | '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' | ||
22653 | ], | ||
22654 | [ | ||
22655 | 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', | ||
22656 | '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' | ||
22657 | ], | ||
22658 | [ | ||
22659 | '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', | ||
22660 | '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' | ||
22661 | ], | ||
22662 | [ | ||
22663 | 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', | ||
22664 | 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' | ||
22665 | ], | ||
22666 | [ | ||
22667 | 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', | ||
22668 | '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' | ||
22669 | ], | ||
22670 | [ | ||
22671 | 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', | ||
22672 | 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' | ||
22673 | ], | ||
22674 | [ | ||
22675 | '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', | ||
22676 | 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' | ||
22677 | ], | ||
22678 | [ | ||
22679 | '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', | ||
22680 | '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' | ||
22681 | ], | ||
22682 | [ | ||
22683 | '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', | ||
22684 | 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' | ||
22685 | ], | ||
22686 | [ | ||
22687 | '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', | ||
22688 | '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' | ||
22689 | ], | ||
22690 | [ | ||
22691 | '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', | ||
22692 | '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' | ||
22693 | ], | ||
22694 | [ | ||
22695 | '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', | ||
22696 | 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' | ||
22697 | ], | ||
22698 | [ | ||
22699 | '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', | ||
22700 | '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' | ||
22701 | ], | ||
22702 | [ | ||
22703 | '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', | ||
22704 | '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' | ||
22705 | ], | ||
22706 | [ | ||
22707 | '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', | ||
22708 | '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' | ||
22709 | ] | ||
22710 | ] | ||
22711 | } | ||
22712 | }; | ||
22713 | |||
22714 | },{}],141:[function(require,module,exports){ | ||
22715 | 'use strict'; | ||
22716 | |||
22717 | var utils = exports; | ||
22718 | var BN = require('bn.js'); | ||
22719 | var minAssert = require('minimalistic-assert'); | ||
22720 | var minUtils = require('minimalistic-crypto-utils'); | ||
22721 | |||
22722 | utils.assert = minAssert; | ||
22723 | utils.toArray = minUtils.toArray; | ||
22724 | utils.zero2 = minUtils.zero2; | ||
22725 | utils.toHex = minUtils.toHex; | ||
22726 | utils.encode = minUtils.encode; | ||
22727 | |||
22728 | // Represent num in a w-NAF form | ||
22729 | function getNAF(num, w) { | ||
22730 | var naf = []; | ||
22731 | var ws = 1 << (w + 1); | ||
22732 | var k = num.clone(); | ||
22733 | while (k.cmpn(1) >= 0) { | ||
22734 | var z; | ||
22735 | if (k.isOdd()) { | ||
22736 | var mod = k.andln(ws - 1); | ||
22737 | if (mod > (ws >> 1) - 1) | ||
22738 | z = (ws >> 1) - mod; | ||
22739 | else | ||
22740 | z = mod; | ||
22741 | k.isubn(z); | ||
22742 | } else { | ||
22743 | z = 0; | ||
22744 | } | ||
22745 | naf.push(z); | ||
22746 | |||
22747 | // Optimization, shift by word if possible | ||
22748 | var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; | ||
22749 | for (var i = 1; i < shift; i++) | ||
22750 | naf.push(0); | ||
22751 | k.iushrn(shift); | ||
22752 | } | ||
22753 | |||
22754 | return naf; | ||
22755 | } | ||
22756 | utils.getNAF = getNAF; | ||
22757 | |||
22758 | // Represent k1, k2 in a Joint Sparse Form | ||
22759 | function getJSF(k1, k2) { | ||
22760 | var jsf = [ | ||
22761 | [], | ||
22762 | [] | ||
22763 | ]; | ||
22764 | |||
22765 | k1 = k1.clone(); | ||
22766 | k2 = k2.clone(); | ||
22767 | var d1 = 0; | ||
22768 | var d2 = 0; | ||
22769 | while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { | ||
22770 | |||
22771 | // First phase | ||
22772 | var m14 = (k1.andln(3) + d1) & 3; | ||
22773 | var m24 = (k2.andln(3) + d2) & 3; | ||
22774 | if (m14 === 3) | ||
22775 | m14 = -1; | ||
22776 | if (m24 === 3) | ||
22777 | m24 = -1; | ||
22778 | var u1; | ||
22779 | if ((m14 & 1) === 0) { | ||
22780 | u1 = 0; | ||
22781 | } else { | ||
22782 | var m8 = (k1.andln(7) + d1) & 7; | ||
22783 | if ((m8 === 3 || m8 === 5) && m24 === 2) | ||
22784 | u1 = -m14; | ||
22785 | else | ||
22786 | u1 = m14; | ||
22787 | } | ||
22788 | jsf[0].push(u1); | ||
22789 | |||
22790 | var u2; | ||
22791 | if ((m24 & 1) === 0) { | ||
22792 | u2 = 0; | ||
22793 | } else { | ||
22794 | var m8 = (k2.andln(7) + d2) & 7; | ||
22795 | if ((m8 === 3 || m8 === 5) && m14 === 2) | ||
22796 | u2 = -m24; | ||
22797 | else | ||
22798 | u2 = m24; | ||
22799 | } | ||
22800 | jsf[1].push(u2); | ||
22801 | |||
22802 | // Second phase | ||
22803 | if (2 * d1 === u1 + 1) | ||
22804 | d1 = 1 - d1; | ||
22805 | if (2 * d2 === u2 + 1) | ||
22806 | d2 = 1 - d2; | ||
22807 | k1.iushrn(1); | ||
22808 | k2.iushrn(1); | ||
22809 | } | ||
22810 | |||
22811 | return jsf; | ||
22812 | } | ||
22813 | utils.getJSF = getJSF; | ||
22814 | |||
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); | ||
22820 | }; | ||
22821 | } | ||
22822 | utils.cachedProperty = cachedProperty; | ||
22823 | |||
22824 | function parseBytes(bytes) { | ||
22825 | return typeof bytes === 'string' ? utils.toArray(bytes, 'hex') : | ||
22826 | bytes; | ||
22827 | } | ||
22828 | utils.parseBytes = parseBytes; | ||
22829 | |||
22830 | function intFromLE(bytes) { | ||
22831 | return new BN(bytes, 'hex', 'le'); | ||
22832 | } | ||
22833 | utils.intFromLE = intFromLE; | ||
22834 | |||
22835 | |||
22836 | },{"bn.js":75,"minimalistic-assert":176,"minimalistic-crypto-utils":177}],142:[function(require,module,exports){ | ||
22837 | 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": {}, | ||
22844 | "_requested": { | ||
22845 | "type": "range", | ||
22846 | "registry": true, | ||
22847 | "raw": "elliptic@^6.0.0", | ||
22848 | "name": "elliptic", | ||
22849 | "escapedName": "elliptic", | ||
22850 | "rawSpec": "^6.0.0", | ||
22851 | "saveSpec": null, | ||
22852 | "fetchSpec": "^6.0.0" | ||
22853 | }, | ||
22854 | "_requiredBy": [ | ||
22855 | "/browserify-sign", | ||
22856 | "/create-ecdh" | ||
22857 | ], | ||
22858 | "_resolved": "http://registry.npm.taobao.org/elliptic/download/elliptic-6.4.0.tgz", | ||
22859 | "_shasum": "cac9af8762c85836187003c8dfe193e5e2eae5df", | ||
22860 | "_spec": "elliptic@^6.0.0", | ||
22861 | "_where": "/Users/qywang/workspace/go/src/github.com/nebulasio/go-nebulas/cmd/console/neb.js/node_modules/browserify-sign", | ||
22862 | "author": { | ||
22863 | "name": "Fedor Indutny", | ||
22864 | "email": "fedor@indutny.com" | ||
22865 | }, | ||
22866 | "bugs": { | ||
22867 | "url": "https://github.com/indutny/elliptic/issues" | ||
22868 | }, | ||
22869 | "bundleDependencies": false, | ||
22870 | "dependencies": { | ||
22871 | "bn.js": "^4.4.0", | ||
22872 | "brorand": "^1.0.1", | ||
22873 | "hash.js": "^1.0.0", | ||
22874 | "hmac-drbg": "^1.0.0", | ||
22875 | "inherits": "^2.0.1", | ||
22876 | "minimalistic-assert": "^1.0.0", | ||
22877 | "minimalistic-crypto-utils": "^1.0.0" | ||
22878 | }, | ||
22879 | "deprecated": false, | ||
22880 | "description": "EC cryptography", | ||
22881 | "devDependencies": { | ||
22882 | "brfs": "^1.4.3", | ||
22883 | "coveralls": "^2.11.3", | ||
22884 | "grunt": "^0.4.5", | ||
22885 | "grunt-browserify": "^5.0.0", | ||
22886 | "grunt-cli": "^1.2.0", | ||
22887 | "grunt-contrib-connect": "^1.0.0", | ||
22888 | "grunt-contrib-copy": "^1.0.0", | ||
22889 | "grunt-contrib-uglify": "^1.0.1", | ||
22890 | "grunt-mocha-istanbul": "^3.0.1", | ||
22891 | "grunt-saucelabs": "^8.6.2", | ||
22892 | "istanbul": "^0.4.2", | ||
22893 | "jscs": "^2.9.0", | ||
22894 | "jshint": "^2.6.0", | ||
22895 | "mocha": "^2.1.0" | ||
22896 | }, | ||
22897 | "files": [ | ||
22898 | "lib" | ||
22899 | ], | ||
22900 | "homepage": "https://github.com/indutny/elliptic", | ||
22901 | "keywords": [ | ||
22902 | "EC", | ||
22903 | "Elliptic", | ||
22904 | "curve", | ||
22905 | "Cryptography" | ||
22906 | ], | ||
22907 | "license": "MIT", | ||
22908 | "main": "lib/elliptic.js", | ||
22909 | "name": "elliptic", | ||
22910 | "repository": { | ||
22911 | "type": "git", | ||
22912 | "url": "git+ssh://git@github.com/indutny/elliptic.git" | ||
22913 | }, | ||
22914 | "scripts": { | ||
22915 | "jscs": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", | ||
22916 | "jshint": "jscs benchmarks/*.js lib/*.js lib/**/*.js lib/**/**/*.js test/index.js", | ||
22917 | "lint": "npm run jscs && npm run jshint", | ||
22918 | "test": "npm run lint && npm run unit", | ||
22919 | "unit": "istanbul test _mocha --reporter=spec test/index.js", | ||
22920 | "version": "grunt dist && git add dist/" | ||
22921 | }, | ||
22922 | "version": "6.4.0" | ||
22923 | } | ||
22924 | |||
22925 | },{}],143:[function(require,module,exports){ | ||
22926 | // Copyright Joyent, Inc. and other Node contributors. | ||
22927 | // | ||
22928 | // Permission is hereby granted, free of charge, to any person obtaining a | ||
22929 | // copy of this software and associated documentation files (the | ||
22930 | // "Software"), to deal in the Software without restriction, including | ||
22931 | // without limitation the rights to use, copy, modify, merge, publish, | ||
22932 | // distribute, sublicense, and/or sell copies of the Software, and to permit | ||
22933 | // persons to whom the Software is furnished to do so, subject to the | ||
22934 | // following conditions: | ||
22935 | // | ||
22936 | // The above copyright notice and this permission notice shall be included | ||
22937 | // in all copies or substantial portions of the Software. | ||
22938 | // | ||
22939 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
22940 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
22941 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | ||
22942 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | ||
22943 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
22944 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
22945 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
22946 | |||
22947 | function EventEmitter() { | ||
22948 | this._events = this._events || {}; | ||
22949 | this._maxListeners = this._maxListeners || undefined; | ||
22950 | } | ||
22951 | module.exports = EventEmitter; | ||
22952 | |||
22953 | // Backwards-compat with node 0.10.x | ||
22954 | EventEmitter.EventEmitter = EventEmitter; | ||
22955 | |||
22956 | EventEmitter.prototype._events = undefined; | ||
22957 | EventEmitter.prototype._maxListeners = undefined; | ||
22958 | |||
22959 | // By default EventEmitters will print a warning if more than 10 listeners are | ||
22960 | // added to it. This is a useful default which helps finding memory leaks. | ||
22961 | EventEmitter.defaultMaxListeners = 10; | ||
22962 | |||
22963 | // Obviously not all Emitters should be limited to 10. This function allows | ||
22964 | // that to be increased. Set to zero for unlimited. | ||
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; | ||
22969 | return this; | ||
22970 | }; | ||
22971 | |||
22972 | EventEmitter.prototype.emit = function(type) { | ||
22973 | var er, handler, len, args, i, listeners; | ||
22974 | |||
22975 | if (!this._events) | ||
22976 | this._events = {}; | ||
22977 | |||
22978 | // If there is no 'error' event listener then throw. | ||
22979 | if (type === 'error') { | ||
22980 | if (!this._events.error || | ||
22981 | (isObject(this._events.error) && !this._events.error.length)) { | ||
22982 | er = arguments[1]; | ||
22983 | if (er instanceof Error) { | ||
22984 | throw er; // Unhandled 'error' event | ||
22985 | } else { | ||
22986 | // At least give some kind of context to the user | ||
22987 | var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); | ||
22988 | err.context = er; | ||
22989 | throw err; | ||
22990 | } | ||
22991 | } | ||
22992 | } | ||
22993 | |||
22994 | handler = this._events[type]; | ||
22995 | |||
22996 | if (isUndefined(handler)) | ||
22997 | return false; | ||
22998 | |||
22999 | if (isFunction(handler)) { | ||
23000 | switch (arguments.length) { | ||
23001 | // fast cases | ||
23002 | case 1: | ||
23003 | handler.call(this); | ||
23004 | break; | ||
23005 | case 2: | ||
23006 | handler.call(this, arguments[1]); | ||
23007 | break; | ||
23008 | case 3: | ||
23009 | handler.call(this, arguments[1], arguments[2]); | ||
23010 | break; | ||
23011 | // slower | ||
23012 | default: | ||
23013 | args = Array.prototype.slice.call(arguments, 1); | ||
23014 | handler.apply(this, args); | ||
23015 | } | ||
23016 | } else if (isObject(handler)) { | ||
23017 | args = Array.prototype.slice.call(arguments, 1); | ||
23018 | listeners = handler.slice(); | ||
23019 | len = listeners.length; | ||
23020 | for (i = 0; i < len; i++) | ||
23021 | listeners[i].apply(this, args); | ||
23022 | } | ||
23023 | |||
23024 | return true; | ||
23025 | }; | ||
23026 | |||
23027 | EventEmitter.prototype.addListener = function(type, listener) { | ||
23028 | var m; | ||
23029 | |||
23030 | if (!isFunction(listener)) | ||
23031 | throw TypeError('listener must be a function'); | ||
23032 | |||
23033 | if (!this._events) | ||
23034 | this._events = {}; | ||
23035 | |||
23036 | // To avoid recursion in the case that type === "newListener"! Before | ||
23037 | // adding it to the listeners, first emit "newListener". | ||
23038 | if (this._events.newListener) | ||
23039 | this.emit('newListener', type, | ||
23040 | isFunction(listener.listener) ? | ||
23041 | listener.listener : listener); | ||
23042 | |||
23043 | if (!this._events[type]) | ||
23044 | // Optimize the case of one listener. Don't need the extra array object. | ||
23045 | this._events[type] = listener; | ||
23046 | else if (isObject(this._events[type])) | ||
23047 | // If we've already got an array, just append. | ||
23048 | this._events[type].push(listener); | ||
23049 | else | ||
23050 | // Adding the second element, need to change to array. | ||
23051 | this._events[type] = [this._events[type], listener]; | ||
23052 | |||
23053 | // Check for listener leak | ||
23054 | if (isObject(this._events[type]) && !this._events[type].warned) { | ||
23055 | if (!isUndefined(this._maxListeners)) { | ||
23056 | m = this._maxListeners; | ||
23057 | } else { | ||
23058 | m = EventEmitter.defaultMaxListeners; | ||
23059 | } | ||
23060 | |||
23061 | if (m && m > 0 && this._events[type].length > m) { | ||
23062 | this._events[type].warned = true; | ||
23063 | console.error('(node) warning: possible EventEmitter memory ' + | ||
23064 | 'leak detected. %d listeners added. ' + | ||
23065 | 'Use emitter.setMaxListeners() to increase limit.', | ||
23066 | this._events[type].length); | ||
23067 | if (typeof console.trace === 'function') { | ||
23068 | // not supported in IE 10 | ||
23069 | console.trace(); | ||
23070 | } | ||
23071 | } | ||
23072 | } | ||
23073 | |||
23074 | return this; | ||
23075 | }; | ||
23076 | |||
23077 | EventEmitter.prototype.on = EventEmitter.prototype.addListener; | ||
23078 | |||
23079 | EventEmitter.prototype.once = function(type, listener) { | ||
23080 | if (!isFunction(listener)) | ||
23081 | throw TypeError('listener must be a function'); | ||
23082 | |||
23083 | var fired = false; | ||
23084 | |||
23085 | function g() { | ||
23086 | this.removeListener(type, g); | ||
23087 | |||
23088 | if (!fired) { | ||
23089 | fired = true; | ||
23090 | listener.apply(this, arguments); | ||
23091 | } | ||
23092 | } | ||
23093 | |||
23094 | g.listener = listener; | ||
23095 | this.on(type, g); | ||
23096 | |||
23097 | return this; | ||
23098 | }; | ||
23099 | |||
23100 | // emits a 'removeListener' event iff the listener was removed | ||
23101 | EventEmitter.prototype.removeListener = function(type, listener) { | ||
23102 | var list, position, length, i; | ||
23103 | |||
23104 | if (!isFunction(listener)) | ||
23105 | throw TypeError('listener must be a function'); | ||
23106 | |||
23107 | if (!this._events || !this._events[type]) | ||
23108 | return this; | ||
23109 | |||
23110 | list = this._events[type]; | ||
23111 | length = list.length; | ||
23112 | position = -1; | ||
23113 | |||
23114 | if (list === listener || | ||
23115 | (isFunction(list.listener) && list.listener === listener)) { | ||
23116 | delete this._events[type]; | ||
23117 | if (this._events.removeListener) | ||
23118 | this.emit('removeListener', type, listener); | ||
23119 | |||
23120 | } else if (isObject(list)) { | ||
23121 | for (i = length; i-- > 0;) { | ||
23122 | if (list[i] === listener || | ||
23123 | (list[i].listener && list[i].listener === listener)) { | ||
23124 | position = i; | ||
23125 | break; | ||
23126 | } | ||
23127 | } | ||
23128 | |||
23129 | if (position < 0) | ||
23130 | return this; | ||
23131 | |||
23132 | if (list.length === 1) { | ||
23133 | list.length = 0; | ||
23134 | delete this._events[type]; | ||
23135 | } else { | ||
23136 | list.splice(position, 1); | ||
23137 | } | ||
23138 | |||
23139 | if (this._events.removeListener) | ||
23140 | this.emit('removeListener', type, listener); | ||
23141 | } | ||
23142 | |||
23143 | return this; | ||
23144 | }; | ||
23145 | |||
23146 | EventEmitter.prototype.removeAllListeners = function(type) { | ||
23147 | var key, listeners; | ||
23148 | |||
23149 | if (!this._events) | ||
23150 | return this; | ||
23151 | |||
23152 | // not listening for removeListener, no need to emit | ||
23153 | if (!this._events.removeListener) { | ||
23154 | if (arguments.length === 0) | ||
23155 | this._events = {}; | ||
23156 | else if (this._events[type]) | ||
23157 | delete this._events[type]; | ||
23158 | return this; | ||
23159 | } | ||
23160 | |||
23161 | // emit removeListener for all listeners on all events | ||
23162 | if (arguments.length === 0) { | ||
23163 | for (key in this._events) { | ||
23164 | if (key === 'removeListener') continue; | ||
23165 | this.removeAllListeners(key); | ||
23166 | } | ||
23167 | this.removeAllListeners('removeListener'); | ||
23168 | this._events = {}; | ||
23169 | return this; | ||
23170 | } | ||
23171 | |||
23172 | listeners = this._events[type]; | ||
23173 | |||
23174 | if (isFunction(listeners)) { | ||
23175 | this.removeListener(type, listeners); | ||
23176 | } else if (listeners) { | ||
23177 | // LIFO order | ||
23178 | while (listeners.length) | ||
23179 | this.removeListener(type, listeners[listeners.length - 1]); | ||
23180 | } | ||
23181 | delete this._events[type]; | ||
23182 | |||
23183 | return this; | ||
23184 | }; | ||
23185 | |||
23186 | EventEmitter.prototype.listeners = function(type) { | ||
23187 | var ret; | ||
23188 | if (!this._events || !this._events[type]) | ||
23189 | ret = []; | ||
23190 | else if (isFunction(this._events[type])) | ||
23191 | ret = [this._events[type]]; | ||
23192 | else | ||
23193 | ret = this._events[type].slice(); | ||
23194 | return ret; | ||
23195 | }; | ||
23196 | |||
23197 | EventEmitter.prototype.listenerCount = function(type) { | ||
23198 | if (this._events) { | ||
23199 | var evlistener = this._events[type]; | ||
23200 | |||
23201 | if (isFunction(evlistener)) | ||
23202 | return 1; | ||
23203 | else if (evlistener) | ||
23204 | return evlistener.length; | ||
23205 | } | ||
23206 | return 0; | ||
23207 | }; | ||
23208 | |||
23209 | EventEmitter.listenerCount = function(emitter, type) { | ||
23210 | return emitter.listenerCount(type); | ||
23211 | }; | ||
23212 | |||
23213 | function isFunction(arg) { | ||
23214 | return typeof arg === 'function'; | ||
23215 | } | ||
23216 | |||
23217 | function isNumber(arg) { | ||
23218 | return typeof arg === 'number'; | ||
23219 | } | ||
23220 | |||
23221 | function isObject(arg) { | ||
23222 | return typeof arg === 'object' && arg !== null; | ||
23223 | } | ||
23224 | |||
23225 | function isUndefined(arg) { | ||
23226 | return arg === void 0; | ||
23227 | } | ||
23228 | |||
23229 | },{}],144:[function(require,module,exports){ | ||
23230 | var Buffer = require('safe-buffer').Buffer | ||
23231 | var MD5 = require('md5.js') | ||
23232 | |||
23233 | /* eslint-disable camelcase */ | ||
23234 | function EVP_BytesToKey (password, salt, keyBits, ivLen) { | ||
23235 | if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') | ||
23236 | if (salt) { | ||
23237 | if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') | ||
23238 | if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') | ||
23239 | } | ||
23240 | |||
23241 | var keyLen = keyBits / 8 | ||
23242 | var key = Buffer.alloc(keyLen) | ||
23243 | var iv = Buffer.alloc(ivLen || 0) | ||
23244 | var tmp = Buffer.alloc(0) | ||
23245 | |||
23246 | while (keyLen > 0 || ivLen > 0) { | ||
23247 | var hash = new MD5() | ||
23248 | hash.update(tmp) | ||
23249 | hash.update(password) | ||
23250 | if (salt) hash.update(salt) | ||
23251 | tmp = hash.digest() | ||
23252 | |||
23253 | var used = 0 | ||
23254 | |||
23255 | if (keyLen > 0) { | ||
23256 | var keyStart = key.length - keyLen | ||
23257 | used = Math.min(keyLen, tmp.length) | ||
23258 | tmp.copy(key, keyStart, 0, used) | ||
23259 | keyLen -= used | ||
23260 | } | ||
23261 | |||
23262 | if (used < tmp.length && ivLen > 0) { | ||
23263 | var ivStart = iv.length - ivLen | ||
23264 | var length = Math.min(ivLen, tmp.length - used) | ||
23265 | tmp.copy(iv, ivStart, used, used + length) | ||
23266 | ivLen -= length | ||
23267 | } | ||
23268 | } | ||
23269 | |||
23270 | tmp.fill(0) | ||
23271 | return { key: key, iv: iv } | ||
23272 | } | ||
23273 | |||
23274 | module.exports = EVP_BytesToKey | ||
23275 | |||
23276 | },{"md5.js":173,"safe-buffer":247}],145:[function(require,module,exports){ | ||
23277 | 'use strict'; | ||
23278 | |||
23279 | var hasOwn = Object.prototype.hasOwnProperty; | ||
23280 | var toStr = Object.prototype.toString; | ||
23281 | |||
23282 | var isArray = function isArray(arr) { | ||
23283 | if (typeof Array.isArray === 'function') { | ||
23284 | return Array.isArray(arr); | ||
23285 | } | ||
23286 | |||
23287 | return toStr.call(arr) === '[object Array]'; | ||
23288 | }; | ||
23289 | |||
23290 | var isPlainObject = function isPlainObject(obj) { | ||
23291 | if (!obj || toStr.call(obj) !== '[object Object]') { | ||
23292 | return false; | ||
23293 | } | ||
23294 | |||
23295 | var hasOwnConstructor = hasOwn.call(obj, 'constructor'); | ||
23296 | var hasIsPrototypeOf = obj.constructor && obj.constructor.prototype && hasOwn.call(obj.constructor.prototype, 'isPrototypeOf'); | ||
23297 | // Not own constructor property must be Object | ||
23298 | if (obj.constructor && !hasOwnConstructor && !hasIsPrototypeOf) { | ||
23299 | return false; | ||
23300 | } | ||
23301 | |||
23302 | // Own properties are enumerated firstly, so to speed up, | ||
23303 | // if last one is own, then all properties are own. | ||
23304 | var key; | ||
23305 | for (key in obj) { /**/ } | ||
23306 | |||
23307 | return typeof key === 'undefined' || hasOwn.call(obj, key); | ||
23308 | }; | ||
23309 | |||
23310 | module.exports = function extend() { | ||
23311 | var options, name, src, copy, copyIsArray, clone; | ||
23312 | var target = arguments[0]; | ||
23313 | var i = 1; | ||
23314 | var length = arguments.length; | ||
23315 | var deep = false; | ||
23316 | |||
23317 | // Handle a deep copy situation | ||
23318 | if (typeof target === 'boolean') { | ||
23319 | deep = target; | ||
23320 | target = arguments[1] || {}; | ||
23321 | // skip the boolean and the target | ||
23322 | i = 2; | ||
23323 | } | ||
23324 | if (target == null || (typeof target !== 'object' && typeof target !== 'function')) { | ||
23325 | target = {}; | ||
23326 | } | ||
23327 | |||
23328 | for (; i < length; ++i) { | ||
23329 | options = arguments[i]; | ||
23330 | // Only deal with non-null/undefined values | ||
23331 | if (options != null) { | ||
23332 | // Extend the base object | ||
23333 | for (name in options) { | ||
23334 | src = target[name]; | ||
23335 | copy = options[name]; | ||
23336 | |||
23337 | // Prevent never-ending loop | ||
23338 | if (target !== copy) { | ||
23339 | // Recurse if we're merging plain objects or arrays | ||
23340 | if (deep && copy && (isPlainObject(copy) || (copyIsArray = isArray(copy)))) { | ||
23341 | if (copyIsArray) { | ||
23342 | copyIsArray = false; | ||
23343 | clone = src && isArray(src) ? src : []; | ||
23344 | } else { | ||
23345 | clone = src && isPlainObject(src) ? src : {}; | ||
23346 | } | ||
23347 | |||
23348 | // Never move original objects, clone them | ||
23349 | target[name] = extend(deep, clone, copy); | ||
23350 | |||
23351 | // Don't bring in undefined values | ||
23352 | } else if (typeof copy !== 'undefined') { | ||
23353 | target[name] = copy; | ||
23354 | } | ||
23355 | } | ||
23356 | } | ||
23357 | } | ||
23358 | } | ||
23359 | |||
23360 | // Return the modified object | ||
23361 | return target; | ||
23362 | }; | ||
23363 | |||
23364 | },{}],146:[function(require,module,exports){ | ||
23365 | (function (Buffer){ | ||
23366 | 'use strict' | ||
23367 | var Transform = require('stream').Transform | ||
23368 | var inherits = require('inherits') | ||
23369 | |||
23370 | function HashBase (blockSize) { | ||
23371 | Transform.call(this) | ||
23372 | |||
23373 | this._block = new Buffer(blockSize) | ||
23374 | this._blockSize = blockSize | ||
23375 | this._blockOffset = 0 | ||
23376 | this._length = [0, 0, 0, 0] | ||
23377 | |||
23378 | this._finalized = false | ||
23379 | } | ||
23380 | |||
23381 | inherits(HashBase, Transform) | ||
23382 | |||
23383 | HashBase.prototype._transform = function (chunk, encoding, callback) { | ||
23384 | var error = null | ||
23385 | try { | ||
23386 | if (encoding !== 'buffer') chunk = new Buffer(chunk, encoding) | ||
23387 | this.update(chunk) | ||
23388 | } catch (err) { | ||
23389 | error = err | ||
23390 | } | ||
23391 | |||
23392 | callback(error) | ||
23393 | } | ||
23394 | |||
23395 | HashBase.prototype._flush = function (callback) { | ||
23396 | var error = null | ||
23397 | try { | ||
23398 | this.push(this._digest()) | ||
23399 | } catch (err) { | ||
23400 | error = err | ||
23401 | } | ||
23402 | |||
23403 | callback(error) | ||
23404 | } | ||
23405 | |||
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') | ||
23410 | |||
23411 | // consume data | ||
23412 | var block = this._block | ||
23413 | var offset = 0 | ||
23414 | while (this._blockOffset + data.length - offset >= this._blockSize) { | ||
23415 | for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] | ||
23416 | this._update() | ||
23417 | this._blockOffset = 0 | ||
23418 | } | ||
23419 | while (offset < data.length) block[this._blockOffset++] = data[offset++] | ||
23420 | |||
23421 | // update length | ||
23422 | for (var j = 0, carry = data.length * 8; carry > 0; ++j) { | ||
23423 | this._length[j] += carry | ||
23424 | carry = (this._length[j] / 0x0100000000) | 0 | ||
23425 | if (carry > 0) this._length[j] -= 0x0100000000 * carry | ||
23426 | } | ||
23427 | |||
23428 | return this | ||
23429 | } | ||
23430 | |||
23431 | HashBase.prototype._update = function (data) { | ||
23432 | throw new Error('_update is not implemented') | ||
23433 | } | ||
23434 | |||
23435 | HashBase.prototype.digest = function (encoding) { | ||
23436 | if (this._finalized) throw new Error('Digest already called') | ||
23437 | this._finalized = true | ||
23438 | |||
23439 | var digest = this._digest() | ||
23440 | if (encoding !== undefined) digest = digest.toString(encoding) | ||
23441 | return digest | ||
23442 | } | ||
23443 | |||
23444 | HashBase.prototype._digest = function () { | ||
23445 | throw new Error('_digest is not implemented') | ||
23446 | } | ||
23447 | |||
23448 | module.exports = HashBase | ||
23449 | |||
23450 | }).call(this,require("buffer").Buffer) | ||
23451 | },{"buffer":107,"inherits":163,"stream":263}],147:[function(require,module,exports){ | ||
23452 | var hash = exports; | ||
23453 | |||
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'); | ||
23459 | |||
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; | ||
23467 | |||
23468 | },{"./hash/common":148,"./hash/hmac":149,"./hash/ripemd":150,"./hash/sha":151,"./hash/utils":158}],148:[function(require,module,exports){ | ||
23469 | 'use strict'; | ||
23470 | |||
23471 | var utils = require('./utils'); | ||
23472 | var assert = require('minimalistic-assert'); | ||
23473 | |||
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'; | ||
23482 | |||
23483 | this._delta8 = this.blockSize / 8; | ||
23484 | this._delta32 = this.blockSize / 32; | ||
23485 | } | ||
23486 | exports.BlockHash = BlockHash; | ||
23487 | |||
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); | ||
23491 | if (!this.pending) | ||
23492 | this.pending = msg; | ||
23493 | else | ||
23494 | this.pending = this.pending.concat(msg); | ||
23495 | this.pendingTotal += msg.length; | ||
23496 | |||
23497 | // Enough data, try updating | ||
23498 | if (this.pending.length >= this._delta8) { | ||
23499 | msg = this.pending; | ||
23500 | |||
23501 | // Process pending data in blocks | ||
23502 | var r = msg.length % this._delta8; | ||
23503 | this.pending = msg.slice(msg.length - r, msg.length); | ||
23504 | if (this.pending.length === 0) | ||
23505 | this.pending = null; | ||
23506 | |||
23507 | msg = utils.join32(msg, 0, msg.length - r, this.endian); | ||
23508 | for (var i = 0; i < msg.length; i += this._delta32) | ||
23509 | this._update(msg, i, i + this._delta32); | ||
23510 | } | ||
23511 | |||
23512 | return this; | ||
23513 | }; | ||
23514 | |||
23515 | BlockHash.prototype.digest = function digest(enc) { | ||
23516 | this.update(this._pad()); | ||
23517 | assert(this.pending === null); | ||
23518 | |||
23519 | return this._digest(enc); | ||
23520 | }; | ||
23521 | |||
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); | ||
23527 | res[0] = 0x80; | ||
23528 | for (var i = 1; i < k; i++) | ||
23529 | res[i] = 0; | ||
23530 | |||
23531 | // Append length | ||
23532 | len <<= 3; | ||
23533 | if (this.endian === 'big') { | ||
23534 | for (var t = 8; t < this.padLength; t++) | ||
23535 | res[i++] = 0; | ||
23536 | |||
23537 | res[i++] = 0; | ||
23538 | res[i++] = 0; | ||
23539 | res[i++] = 0; | ||
23540 | res[i++] = 0; | ||
23541 | res[i++] = (len >>> 24) & 0xff; | ||
23542 | res[i++] = (len >>> 16) & 0xff; | ||
23543 | res[i++] = (len >>> 8) & 0xff; | ||
23544 | res[i++] = len & 0xff; | ||
23545 | } else { | ||
23546 | res[i++] = len & 0xff; | ||
23547 | res[i++] = (len >>> 8) & 0xff; | ||
23548 | res[i++] = (len >>> 16) & 0xff; | ||
23549 | res[i++] = (len >>> 24) & 0xff; | ||
23550 | res[i++] = 0; | ||
23551 | res[i++] = 0; | ||
23552 | res[i++] = 0; | ||
23553 | res[i++] = 0; | ||
23554 | |||
23555 | for (t = 8; t < this.padLength; t++) | ||
23556 | res[i++] = 0; | ||
23557 | } | ||
23558 | |||
23559 | return res; | ||
23560 | }; | ||
23561 | |||
23562 | },{"./utils":158,"minimalistic-assert":176}],149:[function(require,module,exports){ | ||
23563 | 'use strict'; | ||
23564 | |||
23565 | var utils = require('./utils'); | ||
23566 | var assert = require('minimalistic-assert'); | ||
23567 | |||
23568 | function Hmac(hash, key, enc) { | ||
23569 | if (!(this instanceof Hmac)) | ||
23570 | return new Hmac(hash, key, enc); | ||
23571 | this.Hash = hash; | ||
23572 | this.blockSize = hash.blockSize / 8; | ||
23573 | this.outSize = hash.outSize / 8; | ||
23574 | this.inner = null; | ||
23575 | this.outer = null; | ||
23576 | |||
23577 | this._init(utils.toArray(key, enc)); | ||
23578 | } | ||
23579 | module.exports = Hmac; | ||
23580 | |||
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); | ||
23586 | |||
23587 | // Add padding to key | ||
23588 | for (var i = key.length; i < this.blockSize; i++) | ||
23589 | key.push(0); | ||
23590 | |||
23591 | for (i = 0; i < key.length; i++) | ||
23592 | key[i] ^= 0x36; | ||
23593 | this.inner = new this.Hash().update(key); | ||
23594 | |||
23595 | // 0x36 ^ 0x5c = 0x6a | ||
23596 | for (i = 0; i < key.length; i++) | ||
23597 | key[i] ^= 0x6a; | ||
23598 | this.outer = new this.Hash().update(key); | ||
23599 | }; | ||
23600 | |||
23601 | Hmac.prototype.update = function update(msg, enc) { | ||
23602 | this.inner.update(msg, enc); | ||
23603 | return this; | ||
23604 | }; | ||
23605 | |||
23606 | Hmac.prototype.digest = function digest(enc) { | ||
23607 | this.outer.update(this.inner.digest()); | ||
23608 | return this.outer.digest(enc); | ||
23609 | }; | ||
23610 | |||
23611 | },{"./utils":158,"minimalistic-assert":176}],150:[function(require,module,exports){ | ||
23612 | 'use strict'; | ||
23613 | |||
23614 | var utils = require('./utils'); | ||
23615 | var common = require('./common'); | ||
23616 | |||
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; | ||
23622 | |||
23623 | function RIPEMD160() { | ||
23624 | if (!(this instanceof RIPEMD160)) | ||
23625 | return new RIPEMD160(); | ||
23626 | |||
23627 | BlockHash.call(this); | ||
23628 | |||
23629 | this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; | ||
23630 | this.endian = 'little'; | ||
23631 | } | ||
23632 | utils.inherits(RIPEMD160, BlockHash); | ||
23633 | exports.ripemd160 = RIPEMD160; | ||
23634 | |||
23635 | RIPEMD160.blockSize = 512; | ||
23636 | RIPEMD160.outSize = 160; | ||
23637 | RIPEMD160.hmacStrength = 192; | ||
23638 | RIPEMD160.padLength = 64; | ||
23639 | |||
23640 | RIPEMD160.prototype._update = function update(msg, start) { | ||
23641 | var A = this.h[0]; | ||
23642 | var B = this.h[1]; | ||
23643 | var C = this.h[2]; | ||
23644 | var D = this.h[3]; | ||
23645 | var E = this.h[4]; | ||
23646 | var Ah = A; | ||
23647 | var Bh = B; | ||
23648 | var Ch = C; | ||
23649 | var Dh = D; | ||
23650 | var Eh = E; | ||
23651 | for (var j = 0; j < 80; j++) { | ||
23652 | var T = sum32( | ||
23653 | rotl32( | ||
23654 | sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), | ||
23655 | s[j]), | ||
23656 | E); | ||
23657 | A = E; | ||
23658 | E = D; | ||
23659 | D = rotl32(C, 10); | ||
23660 | C = B; | ||
23661 | B = T; | ||
23662 | T = sum32( | ||
23663 | rotl32( | ||
23664 | sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), | ||
23665 | sh[j]), | ||
23666 | Eh); | ||
23667 | Ah = Eh; | ||
23668 | Eh = Dh; | ||
23669 | Dh = rotl32(Ch, 10); | ||
23670 | Ch = Bh; | ||
23671 | Bh = T; | ||
23672 | } | ||
23673 | T = sum32_3(this.h[1], C, Dh); | ||
23674 | this.h[1] = sum32_3(this.h[2], D, Eh); | ||
23675 | this.h[2] = sum32_3(this.h[3], E, Ah); | ||
23676 | this.h[3] = sum32_3(this.h[4], A, Bh); | ||
23677 | this.h[4] = sum32_3(this.h[0], B, Ch); | ||
23678 | this.h[0] = T; | ||
23679 | }; | ||
23680 | |||
23681 | RIPEMD160.prototype._digest = function digest(enc) { | ||
23682 | if (enc === 'hex') | ||
23683 | return utils.toHex32(this.h, 'little'); | ||
23684 | else | ||
23685 | return utils.split32(this.h, 'little'); | ||
23686 | }; | ||
23687 | |||
23688 | function f(j, x, y, z) { | ||
23689 | if (j <= 15) | ||
23690 | return x ^ y ^ z; | ||
23691 | else if (j <= 31) | ||
23692 | return (x & y) | ((~x) & z); | ||
23693 | else if (j <= 47) | ||
23694 | return (x | (~y)) ^ z; | ||
23695 | else if (j <= 63) | ||
23696 | return (x & z) | (y & (~z)); | ||
23697 | else | ||
23698 | return x ^ (y | (~z)); | ||
23699 | } | ||
23700 | |||
23701 | function K(j) { | ||
23702 | if (j <= 15) | ||
23703 | return 0x00000000; | ||
23704 | else if (j <= 31) | ||
23705 | return 0x5a827999; | ||
23706 | else if (j <= 47) | ||
23707 | return 0x6ed9eba1; | ||
23708 | else if (j <= 63) | ||
23709 | return 0x8f1bbcdc; | ||
23710 | else | ||
23711 | return 0xa953fd4e; | ||
23712 | } | ||
23713 | |||
23714 | function Kh(j) { | ||
23715 | if (j <= 15) | ||
23716 | return 0x50a28be6; | ||
23717 | else if (j <= 31) | ||
23718 | return 0x5c4dd124; | ||
23719 | else if (j <= 47) | ||
23720 | return 0x6d703ef3; | ||
23721 | else if (j <= 63) | ||
23722 | return 0x7a6d76e9; | ||
23723 | else | ||
23724 | return 0x00000000; | ||
23725 | } | ||
23726 | |||
23727 | var r = [ | ||
23728 | 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, | ||
23729 | 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, | ||
23730 | 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, | ||
23731 | 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, | ||
23732 | 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 | ||
23733 | ]; | ||
23734 | |||
23735 | var rh = [ | ||
23736 | 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, | ||
23737 | 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, | ||
23738 | 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, | ||
23739 | 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, | ||
23740 | 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 | ||
23741 | ]; | ||
23742 | |||
23743 | var s = [ | ||
23744 | 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, | ||
23745 | 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, | ||
23746 | 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, | ||
23747 | 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, | ||
23748 | 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 | ||
23749 | ]; | ||
23750 | |||
23751 | var sh = [ | ||
23752 | 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, | ||
23753 | 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, | ||
23754 | 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, | ||
23755 | 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, | ||
23756 | 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 | ||
23757 | ]; | ||
23758 | |||
23759 | },{"./common":148,"./utils":158}],151:[function(require,module,exports){ | ||
23760 | 'use strict'; | ||
23761 | |||
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'); | ||
23767 | |||
23768 | },{"./sha/1":152,"./sha/224":153,"./sha/256":154,"./sha/384":155,"./sha/512":156}],152:[function(require,module,exports){ | ||
23769 | 'use strict'; | ||
23770 | |||
23771 | var utils = require('../utils'); | ||
23772 | var common = require('../common'); | ||
23773 | var shaCommon = require('./common'); | ||
23774 | |||
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; | ||
23780 | |||
23781 | var sha1_K = [ | ||
23782 | 0x5A827999, 0x6ED9EBA1, | ||
23783 | 0x8F1BBCDC, 0xCA62C1D6 | ||
23784 | ]; | ||
23785 | |||
23786 | function SHA1() { | ||
23787 | if (!(this instanceof SHA1)) | ||
23788 | return new SHA1(); | ||
23789 | |||
23790 | BlockHash.call(this); | ||
23791 | this.h = [ | ||
23792 | 0x67452301, 0xefcdab89, 0x98badcfe, | ||
23793 | 0x10325476, 0xc3d2e1f0 ]; | ||
23794 | this.W = new Array(80); | ||
23795 | } | ||
23796 | |||
23797 | utils.inherits(SHA1, BlockHash); | ||
23798 | module.exports = SHA1; | ||
23799 | |||
23800 | SHA1.blockSize = 512; | ||
23801 | SHA1.outSize = 160; | ||
23802 | SHA1.hmacStrength = 80; | ||
23803 | SHA1.padLength = 64; | ||
23804 | |||
23805 | SHA1.prototype._update = function _update(msg, start) { | ||
23806 | var W = this.W; | ||
23807 | |||
23808 | for (var i = 0; i < 16; i++) | ||
23809 | W[i] = msg[start + i]; | ||
23810 | |||
23811 | for(; i < W.length; i++) | ||
23812 | W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); | ||
23813 | |||
23814 | var a = this.h[0]; | ||
23815 | var b = this.h[1]; | ||
23816 | var c = this.h[2]; | ||
23817 | var d = this.h[3]; | ||
23818 | var e = this.h[4]; | ||
23819 | |||
23820 | for (i = 0; i < W.length; i++) { | ||
23821 | var s = ~~(i / 20); | ||
23822 | var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); | ||
23823 | e = d; | ||
23824 | d = c; | ||
23825 | c = rotl32(b, 30); | ||
23826 | b = a; | ||
23827 | a = t; | ||
23828 | } | ||
23829 | |||
23830 | this.h[0] = sum32(this.h[0], a); | ||
23831 | this.h[1] = sum32(this.h[1], b); | ||
23832 | this.h[2] = sum32(this.h[2], c); | ||
23833 | this.h[3] = sum32(this.h[3], d); | ||
23834 | this.h[4] = sum32(this.h[4], e); | ||
23835 | }; | ||
23836 | |||
23837 | SHA1.prototype._digest = function digest(enc) { | ||
23838 | if (enc === 'hex') | ||
23839 | return utils.toHex32(this.h, 'big'); | ||
23840 | else | ||
23841 | return utils.split32(this.h, 'big'); | ||
23842 | }; | ||
23843 | |||
23844 | },{"../common":148,"../utils":158,"./common":157}],153:[function(require,module,exports){ | ||
23845 | 'use strict'; | ||
23846 | |||
23847 | var utils = require('../utils'); | ||
23848 | var SHA256 = require('./256'); | ||
23849 | |||
23850 | function SHA224() { | ||
23851 | if (!(this instanceof SHA224)) | ||
23852 | return new SHA224(); | ||
23853 | |||
23854 | SHA256.call(this); | ||
23855 | this.h = [ | ||
23856 | 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, | ||
23857 | 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; | ||
23858 | } | ||
23859 | utils.inherits(SHA224, SHA256); | ||
23860 | module.exports = SHA224; | ||
23861 | |||
23862 | SHA224.blockSize = 512; | ||
23863 | SHA224.outSize = 224; | ||
23864 | SHA224.hmacStrength = 192; | ||
23865 | SHA224.padLength = 64; | ||
23866 | |||
23867 | SHA224.prototype._digest = function digest(enc) { | ||
23868 | // Just truncate output | ||
23869 | if (enc === 'hex') | ||
23870 | return utils.toHex32(this.h.slice(0, 7), 'big'); | ||
23871 | else | ||
23872 | return utils.split32(this.h.slice(0, 7), 'big'); | ||
23873 | }; | ||
23874 | |||
23875 | |||
23876 | },{"../utils":158,"./256":154}],154:[function(require,module,exports){ | ||
23877 | 'use strict'; | ||
23878 | |||
23879 | var utils = require('../utils'); | ||
23880 | var common = require('../common'); | ||
23881 | var shaCommon = require('./common'); | ||
23882 | var assert = require('minimalistic-assert'); | ||
23883 | |||
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; | ||
23893 | |||
23894 | var BlockHash = common.BlockHash; | ||
23895 | |||
23896 | var sha256_K = [ | ||
23897 | 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, | ||
23898 | 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, | ||
23899 | 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, | ||
23900 | 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, | ||
23901 | 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, | ||
23902 | 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, | ||
23903 | 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, | ||
23904 | 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, | ||
23905 | 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, | ||
23906 | 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, | ||
23907 | 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, | ||
23908 | 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, | ||
23909 | 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, | ||
23910 | 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, | ||
23911 | 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, | ||
23912 | 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 | ||
23913 | ]; | ||
23914 | |||
23915 | function SHA256() { | ||
23916 | if (!(this instanceof SHA256)) | ||
23917 | return new SHA256(); | ||
23918 | |||
23919 | BlockHash.call(this); | ||
23920 | this.h = [ | ||
23921 | 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, | ||
23922 | 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 | ||
23923 | ]; | ||
23924 | this.k = sha256_K; | ||
23925 | this.W = new Array(64); | ||
23926 | } | ||
23927 | utils.inherits(SHA256, BlockHash); | ||
23928 | module.exports = SHA256; | ||
23929 | |||
23930 | SHA256.blockSize = 512; | ||
23931 | SHA256.outSize = 256; | ||
23932 | SHA256.hmacStrength = 192; | ||
23933 | SHA256.padLength = 64; | ||
23934 | |||
23935 | SHA256.prototype._update = function _update(msg, start) { | ||
23936 | var W = this.W; | ||
23937 | |||
23938 | for (var i = 0; i < 16; i++) | ||
23939 | W[i] = msg[start + i]; | ||
23940 | for (; i < W.length; i++) | ||
23941 | W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); | ||
23942 | |||
23943 | var a = this.h[0]; | ||
23944 | var b = this.h[1]; | ||
23945 | var c = this.h[2]; | ||
23946 | var d = this.h[3]; | ||
23947 | var e = this.h[4]; | ||
23948 | var f = this.h[5]; | ||
23949 | var g = this.h[6]; | ||
23950 | var h = this.h[7]; | ||
23951 | |||
23952 | assert(this.k.length === W.length); | ||
23953 | for (i = 0; i < W.length; i++) { | ||
23954 | var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); | ||
23955 | var T2 = sum32(s0_256(a), maj32(a, b, c)); | ||
23956 | h = g; | ||
23957 | g = f; | ||
23958 | f = e; | ||
23959 | e = sum32(d, T1); | ||
23960 | d = c; | ||
23961 | c = b; | ||
23962 | b = a; | ||
23963 | a = sum32(T1, T2); | ||
23964 | } | ||
23965 | |||
23966 | this.h[0] = sum32(this.h[0], a); | ||
23967 | this.h[1] = sum32(this.h[1], b); | ||
23968 | this.h[2] = sum32(this.h[2], c); | ||
23969 | this.h[3] = sum32(this.h[3], d); | ||
23970 | this.h[4] = sum32(this.h[4], e); | ||
23971 | this.h[5] = sum32(this.h[5], f); | ||
23972 | this.h[6] = sum32(this.h[6], g); | ||
23973 | this.h[7] = sum32(this.h[7], h); | ||
23974 | }; | ||
23975 | |||
23976 | SHA256.prototype._digest = function digest(enc) { | ||
23977 | if (enc === 'hex') | ||
23978 | return utils.toHex32(this.h, 'big'); | ||
23979 | else | ||
23980 | return utils.split32(this.h, 'big'); | ||
23981 | }; | ||
23982 | |||
23983 | },{"../common":148,"../utils":158,"./common":157,"minimalistic-assert":176}],155:[function(require,module,exports){ | ||
23984 | 'use strict'; | ||
23985 | |||
23986 | var utils = require('../utils'); | ||
23987 | |||
23988 | var SHA512 = require('./512'); | ||
23989 | |||
23990 | function SHA384() { | ||
23991 | if (!(this instanceof SHA384)) | ||
23992 | return new SHA384(); | ||
23993 | |||
23994 | SHA512.call(this); | ||
23995 | this.h = [ | ||
23996 | 0xcbbb9d5d, 0xc1059ed8, | ||
23997 | 0x629a292a, 0x367cd507, | ||
23998 | 0x9159015a, 0x3070dd17, | ||
23999 | 0x152fecd8, 0xf70e5939, | ||
24000 | 0x67332667, 0xffc00b31, | ||
24001 | 0x8eb44a87, 0x68581511, | ||
24002 | 0xdb0c2e0d, 0x64f98fa7, | ||
24003 | 0x47b5481d, 0xbefa4fa4 ]; | ||
24004 | } | ||
24005 | utils.inherits(SHA384, SHA512); | ||
24006 | module.exports = SHA384; | ||
24007 | |||
24008 | SHA384.blockSize = 1024; | ||
24009 | SHA384.outSize = 384; | ||
24010 | SHA384.hmacStrength = 192; | ||
24011 | SHA384.padLength = 128; | ||
24012 | |||
24013 | SHA384.prototype._digest = function digest(enc) { | ||
24014 | if (enc === 'hex') | ||
24015 | return utils.toHex32(this.h.slice(0, 12), 'big'); | ||
24016 | else | ||
24017 | return utils.split32(this.h.slice(0, 12), 'big'); | ||
24018 | }; | ||
24019 | |||
24020 | },{"../utils":158,"./512":156}],156:[function(require,module,exports){ | ||
24021 | 'use strict'; | ||
24022 | |||
24023 | var utils = require('../utils'); | ||
24024 | var common = require('../common'); | ||
24025 | var assert = require('minimalistic-assert'); | ||
24026 | |||
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; | ||
24038 | |||
24039 | var BlockHash = common.BlockHash; | ||
24040 | |||
24041 | var sha512_K = [ | ||
24042 | 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, | ||
24043 | 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, | ||
24044 | 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, | ||
24045 | 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, | ||
24046 | 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, | ||
24047 | 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, | ||
24048 | 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, | ||
24049 | 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, | ||
24050 | 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, | ||
24051 | 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, | ||
24052 | 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, | ||
24053 | 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, | ||
24054 | 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, | ||
24055 | 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, | ||
24056 | 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, | ||
24057 | 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, | ||
24058 | 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, | ||
24059 | 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, | ||
24060 | 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, | ||
24061 | 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, | ||
24062 | 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, | ||
24063 | 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, | ||
24064 | 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, | ||
24065 | 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, | ||
24066 | 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, | ||
24067 | 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, | ||
24068 | 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, | ||
24069 | 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, | ||
24070 | 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, | ||
24071 | 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, | ||
24072 | 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, | ||
24073 | 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, | ||
24074 | 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, | ||
24075 | 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, | ||
24076 | 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, | ||
24077 | 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, | ||
24078 | 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, | ||
24079 | 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, | ||
24080 | 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, | ||
24081 | 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 | ||
24082 | ]; | ||
24083 | |||
24084 | function SHA512() { | ||
24085 | if (!(this instanceof SHA512)) | ||
24086 | return new SHA512(); | ||
24087 | |||
24088 | BlockHash.call(this); | ||
24089 | this.h = [ | ||
24090 | 0x6a09e667, 0xf3bcc908, | ||
24091 | 0xbb67ae85, 0x84caa73b, | ||
24092 | 0x3c6ef372, 0xfe94f82b, | ||
24093 | 0xa54ff53a, 0x5f1d36f1, | ||
24094 | 0x510e527f, 0xade682d1, | ||
24095 | 0x9b05688c, 0x2b3e6c1f, | ||
24096 | 0x1f83d9ab, 0xfb41bd6b, | ||
24097 | 0x5be0cd19, 0x137e2179 ]; | ||
24098 | this.k = sha512_K; | ||
24099 | this.W = new Array(160); | ||
24100 | } | ||
24101 | utils.inherits(SHA512, BlockHash); | ||
24102 | module.exports = SHA512; | ||
24103 | |||
24104 | SHA512.blockSize = 1024; | ||
24105 | SHA512.outSize = 512; | ||
24106 | SHA512.hmacStrength = 192; | ||
24107 | SHA512.padLength = 128; | ||
24108 | |||
24109 | SHA512.prototype._prepareBlock = function _prepareBlock(msg, start) { | ||
24110 | var W = this.W; | ||
24111 | |||
24112 | // 32 x 32bit words | ||
24113 | for (var i = 0; i < 32; i++) | ||
24114 | W[i] = msg[start + i]; | ||
24115 | for (; i < W.length; i += 2) { | ||
24116 | var c0_hi = g1_512_hi(W[i - 4], W[i - 3]); // i - 2 | ||
24117 | var c0_lo = g1_512_lo(W[i - 4], W[i - 3]); | ||
24118 | var c1_hi = W[i - 14]; // i - 7 | ||
24119 | var c1_lo = W[i - 13]; | ||
24120 | var c2_hi = g0_512_hi(W[i - 30], W[i - 29]); // i - 15 | ||
24121 | var c2_lo = g0_512_lo(W[i - 30], W[i - 29]); | ||
24122 | var c3_hi = W[i - 32]; // i - 16 | ||
24123 | var c3_lo = W[i - 31]; | ||
24124 | |||
24125 | W[i] = sum64_4_hi( | ||
24126 | c0_hi, c0_lo, | ||
24127 | c1_hi, c1_lo, | ||
24128 | c2_hi, c2_lo, | ||
24129 | c3_hi, c3_lo); | ||
24130 | W[i + 1] = sum64_4_lo( | ||
24131 | c0_hi, c0_lo, | ||
24132 | c1_hi, c1_lo, | ||
24133 | c2_hi, c2_lo, | ||
24134 | c3_hi, c3_lo); | ||
24135 | } | ||
24136 | }; | ||
24137 | |||
24138 | SHA512.prototype._update = function _update(msg, start) { | ||
24139 | this._prepareBlock(msg, start); | ||
24140 | |||
24141 | var W = this.W; | ||
24142 | |||
24143 | var ah = this.h[0]; | ||
24144 | var al = this.h[1]; | ||
24145 | var bh = this.h[2]; | ||
24146 | var bl = this.h[3]; | ||
24147 | var ch = this.h[4]; | ||
24148 | var cl = this.h[5]; | ||
24149 | var dh = this.h[6]; | ||
24150 | var dl = this.h[7]; | ||
24151 | var eh = this.h[8]; | ||
24152 | var el = this.h[9]; | ||
24153 | var fh = this.h[10]; | ||
24154 | var fl = this.h[11]; | ||
24155 | var gh = this.h[12]; | ||
24156 | var gl = this.h[13]; | ||
24157 | var hh = this.h[14]; | ||
24158 | var hl = this.h[15]; | ||
24159 | |||
24160 | assert(this.k.length === W.length); | ||
24161 | for (var i = 0; i < W.length; i += 2) { | ||
24162 | var c0_hi = hh; | ||
24163 | var c0_lo = hl; | ||
24164 | var c1_hi = s1_512_hi(eh, el); | ||
24165 | var c1_lo = s1_512_lo(eh, el); | ||
24166 | var c2_hi = ch64_hi(eh, el, fh, fl, gh, gl); | ||
24167 | var c2_lo = ch64_lo(eh, el, fh, fl, gh, gl); | ||
24168 | var c3_hi = this.k[i]; | ||
24169 | var c3_lo = this.k[i + 1]; | ||
24170 | var c4_hi = W[i]; | ||
24171 | var c4_lo = W[i + 1]; | ||
24172 | |||
24173 | var T1_hi = sum64_5_hi( | ||
24174 | c0_hi, c0_lo, | ||
24175 | c1_hi, c1_lo, | ||
24176 | c2_hi, c2_lo, | ||
24177 | c3_hi, c3_lo, | ||
24178 | c4_hi, c4_lo); | ||
24179 | var T1_lo = sum64_5_lo( | ||
24180 | c0_hi, c0_lo, | ||
24181 | c1_hi, c1_lo, | ||
24182 | c2_hi, c2_lo, | ||
24183 | c3_hi, c3_lo, | ||
24184 | c4_hi, c4_lo); | ||
24185 | |||
24186 | c0_hi = s0_512_hi(ah, al); | ||
24187 | c0_lo = s0_512_lo(ah, al); | ||
24188 | c1_hi = maj64_hi(ah, al, bh, bl, ch, cl); | ||
24189 | c1_lo = maj64_lo(ah, al, bh, bl, ch, cl); | ||
24190 | |||
24191 | var T2_hi = sum64_hi(c0_hi, c0_lo, c1_hi, c1_lo); | ||
24192 | var T2_lo = sum64_lo(c0_hi, c0_lo, c1_hi, c1_lo); | ||
24193 | |||
24194 | hh = gh; | ||
24195 | hl = gl; | ||
24196 | |||
24197 | gh = fh; | ||
24198 | gl = fl; | ||
24199 | |||
24200 | fh = eh; | ||
24201 | fl = el; | ||
24202 | |||
24203 | eh = sum64_hi(dh, dl, T1_hi, T1_lo); | ||
24204 | el = sum64_lo(dl, dl, T1_hi, T1_lo); | ||
24205 | |||
24206 | dh = ch; | ||
24207 | dl = cl; | ||
24208 | |||
24209 | ch = bh; | ||
24210 | cl = bl; | ||
24211 | |||
24212 | bh = ah; | ||
24213 | bl = al; | ||
24214 | |||
24215 | ah = sum64_hi(T1_hi, T1_lo, T2_hi, T2_lo); | ||
24216 | al = sum64_lo(T1_hi, T1_lo, T2_hi, T2_lo); | ||
24217 | } | ||
24218 | |||
24219 | sum64(this.h, 0, ah, al); | ||
24220 | sum64(this.h, 2, bh, bl); | ||
24221 | sum64(this.h, 4, ch, cl); | ||
24222 | sum64(this.h, 6, dh, dl); | ||
24223 | sum64(this.h, 8, eh, el); | ||
24224 | sum64(this.h, 10, fh, fl); | ||
24225 | sum64(this.h, 12, gh, gl); | ||
24226 | sum64(this.h, 14, hh, hl); | ||
24227 | }; | ||
24228 | |||
24229 | SHA512.prototype._digest = function digest(enc) { | ||
24230 | if (enc === 'hex') | ||
24231 | return utils.toHex32(this.h, 'big'); | ||
24232 | else | ||
24233 | return utils.split32(this.h, 'big'); | ||
24234 | }; | ||
24235 | |||
24236 | function ch64_hi(xh, xl, yh, yl, zh) { | ||
24237 | var r = (xh & yh) ^ ((~xh) & zh); | ||
24238 | if (r < 0) | ||
24239 | r += 0x100000000; | ||
24240 | return r; | ||
24241 | } | ||
24242 | |||
24243 | function ch64_lo(xh, xl, yh, yl, zh, zl) { | ||
24244 | var r = (xl & yl) ^ ((~xl) & zl); | ||
24245 | if (r < 0) | ||
24246 | r += 0x100000000; | ||
24247 | return r; | ||
24248 | } | ||
24249 | |||
24250 | function maj64_hi(xh, xl, yh, yl, zh) { | ||
24251 | var r = (xh & yh) ^ (xh & zh) ^ (yh & zh); | ||
24252 | if (r < 0) | ||
24253 | r += 0x100000000; | ||
24254 | return r; | ||
24255 | } | ||
24256 | |||
24257 | function maj64_lo(xh, xl, yh, yl, zh, zl) { | ||
24258 | var r = (xl & yl) ^ (xl & zl) ^ (yl & zl); | ||
24259 | if (r < 0) | ||
24260 | r += 0x100000000; | ||
24261 | return r; | ||
24262 | } | ||
24263 | |||
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 | ||
24268 | |||
24269 | var r = c0_hi ^ c1_hi ^ c2_hi; | ||
24270 | if (r < 0) | ||
24271 | r += 0x100000000; | ||
24272 | return r; | ||
24273 | } | ||
24274 | |||
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 | ||
24279 | |||
24280 | var r = c0_lo ^ c1_lo ^ c2_lo; | ||
24281 | if (r < 0) | ||
24282 | r += 0x100000000; | ||
24283 | return r; | ||
24284 | } | ||
24285 | |||
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 | ||
24290 | |||
24291 | var r = c0_hi ^ c1_hi ^ c2_hi; | ||
24292 | if (r < 0) | ||
24293 | r += 0x100000000; | ||
24294 | return r; | ||
24295 | } | ||
24296 | |||
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 | ||
24301 | |||
24302 | var r = c0_lo ^ c1_lo ^ c2_lo; | ||
24303 | if (r < 0) | ||
24304 | r += 0x100000000; | ||
24305 | return r; | ||
24306 | } | ||
24307 | |||
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); | ||
24312 | |||
24313 | var r = c0_hi ^ c1_hi ^ c2_hi; | ||
24314 | if (r < 0) | ||
24315 | r += 0x100000000; | ||
24316 | return r; | ||
24317 | } | ||
24318 | |||
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); | ||
24323 | |||
24324 | var r = c0_lo ^ c1_lo ^ c2_lo; | ||
24325 | if (r < 0) | ||
24326 | r += 0x100000000; | ||
24327 | return r; | ||
24328 | } | ||
24329 | |||
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); | ||
24334 | |||
24335 | var r = c0_hi ^ c1_hi ^ c2_hi; | ||
24336 | if (r < 0) | ||
24337 | r += 0x100000000; | ||
24338 | return r; | ||
24339 | } | ||
24340 | |||
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); | ||
24345 | |||
24346 | var r = c0_lo ^ c1_lo ^ c2_lo; | ||
24347 | if (r < 0) | ||
24348 | r += 0x100000000; | ||
24349 | return r; | ||
24350 | } | ||
24351 | |||
24352 | },{"../common":148,"../utils":158,"minimalistic-assert":176}],157:[function(require,module,exports){ | ||
24353 | 'use strict'; | ||
24354 | |||
24355 | var utils = require('../utils'); | ||
24356 | var rotr32 = utils.rotr32; | ||
24357 | |||
24358 | function ft_1(s, x, y, z) { | ||
24359 | if (s === 0) | ||
24360 | return ch32(x, y, z); | ||
24361 | if (s === 1 || s === 3) | ||
24362 | return p32(x, y, z); | ||
24363 | if (s === 2) | ||
24364 | return maj32(x, y, z); | ||
24365 | } | ||
24366 | exports.ft_1 = ft_1; | ||
24367 | |||
24368 | function ch32(x, y, z) { | ||
24369 | return (x & y) ^ ((~x) & z); | ||
24370 | } | ||
24371 | exports.ch32 = ch32; | ||
24372 | |||
24373 | function maj32(x, y, z) { | ||
24374 | return (x & y) ^ (x & z) ^ (y & z); | ||
24375 | } | ||
24376 | exports.maj32 = maj32; | ||
24377 | |||
24378 | function p32(x, y, z) { | ||
24379 | return x ^ y ^ z; | ||
24380 | } | ||
24381 | exports.p32 = p32; | ||
24382 | |||
24383 | function s0_256(x) { | ||
24384 | return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); | ||
24385 | } | ||
24386 | exports.s0_256 = s0_256; | ||
24387 | |||
24388 | function s1_256(x) { | ||
24389 | return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); | ||
24390 | } | ||
24391 | exports.s1_256 = s1_256; | ||
24392 | |||
24393 | function g0_256(x) { | ||
24394 | return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); | ||
24395 | } | ||
24396 | exports.g0_256 = g0_256; | ||
24397 | |||
24398 | function g1_256(x) { | ||
24399 | return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); | ||
24400 | } | ||
24401 | exports.g1_256 = g1_256; | ||
24402 | |||
24403 | },{"../utils":158}],158:[function(require,module,exports){ | ||
24404 | 'use strict'; | ||
24405 | |||
24406 | var assert = require('minimalistic-assert'); | ||
24407 | var inherits = require('inherits'); | ||
24408 | |||
24409 | exports.inherits = inherits; | ||
24410 | |||
24411 | function toArray(msg, enc) { | ||
24412 | if (Array.isArray(msg)) | ||
24413 | return msg.slice(); | ||
24414 | if (!msg) | ||
24415 | return []; | ||
24416 | var res = []; | ||
24417 | if (typeof msg === 'string') { | ||
24418 | if (!enc) { | ||
24419 | for (var i = 0; i < msg.length; i++) { | ||
24420 | var c = msg.charCodeAt(i); | ||
24421 | var hi = c >> 8; | ||
24422 | var lo = c & 0xff; | ||
24423 | if (hi) | ||
24424 | res.push(hi, lo); | ||
24425 | else | ||
24426 | res.push(lo); | ||
24427 | } | ||
24428 | } else if (enc === 'hex') { | ||
24429 | msg = msg.replace(/[^a-z0-9]+/ig, ''); | ||
24430 | if (msg.length % 2 !== 0) | ||
24431 | msg = '0' + msg; | ||
24432 | for (i = 0; i < msg.length; i += 2) | ||
24433 | res.push(parseInt(msg[i] + msg[i + 1], 16)); | ||
24434 | } | ||
24435 | } else { | ||
24436 | for (i = 0; i < msg.length; i++) | ||
24437 | res[i] = msg[i] | 0; | ||
24438 | } | ||
24439 | return res; | ||
24440 | } | ||
24441 | exports.toArray = toArray; | ||
24442 | |||
24443 | function toHex(msg) { | ||
24444 | var res = ''; | ||
24445 | for (var i = 0; i < msg.length; i++) | ||
24446 | res += zero2(msg[i].toString(16)); | ||
24447 | return res; | ||
24448 | } | ||
24449 | exports.toHex = toHex; | ||
24450 | |||
24451 | function htonl(w) { | ||
24452 | var res = (w >>> 24) | | ||
24453 | ((w >>> 8) & 0xff00) | | ||
24454 | ((w << 8) & 0xff0000) | | ||
24455 | ((w & 0xff) << 24); | ||
24456 | return res >>> 0; | ||
24457 | } | ||
24458 | exports.htonl = htonl; | ||
24459 | |||
24460 | function toHex32(msg, endian) { | ||
24461 | var res = ''; | ||
24462 | for (var i = 0; i < msg.length; i++) { | ||
24463 | var w = msg[i]; | ||
24464 | if (endian === 'little') | ||
24465 | w = htonl(w); | ||
24466 | res += zero8(w.toString(16)); | ||
24467 | } | ||
24468 | return res; | ||
24469 | } | ||
24470 | exports.toHex32 = toHex32; | ||
24471 | |||
24472 | function zero2(word) { | ||
24473 | if (word.length === 1) | ||
24474 | return '0' + word; | ||
24475 | else | ||
24476 | return word; | ||
24477 | } | ||
24478 | exports.zero2 = zero2; | ||
24479 | |||
24480 | function zero8(word) { | ||
24481 | if (word.length === 7) | ||
24482 | return '0' + word; | ||
24483 | else if (word.length === 6) | ||
24484 | return '00' + word; | ||
24485 | else if (word.length === 5) | ||
24486 | return '000' + word; | ||
24487 | else if (word.length === 4) | ||
24488 | return '0000' + word; | ||
24489 | else if (word.length === 3) | ||
24490 | return '00000' + word; | ||
24491 | else if (word.length === 2) | ||
24492 | return '000000' + word; | ||
24493 | else if (word.length === 1) | ||
24494 | return '0000000' + word; | ||
24495 | else | ||
24496 | return word; | ||
24497 | } | ||
24498 | exports.zero8 = zero8; | ||
24499 | |||
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) { | ||
24505 | var w; | ||
24506 | if (endian === 'big') | ||
24507 | w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; | ||
24508 | else | ||
24509 | w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; | ||
24510 | res[i] = w >>> 0; | ||
24511 | } | ||
24512 | return res; | ||
24513 | } | ||
24514 | exports.join32 = join32; | ||
24515 | |||
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) { | ||
24519 | var m = msg[i]; | ||
24520 | if (endian === 'big') { | ||
24521 | res[k] = m >>> 24; | ||
24522 | res[k + 1] = (m >>> 16) & 0xff; | ||
24523 | res[k + 2] = (m >>> 8) & 0xff; | ||
24524 | res[k + 3] = m & 0xff; | ||
24525 | } else { | ||
24526 | res[k + 3] = m >>> 24; | ||
24527 | res[k + 2] = (m >>> 16) & 0xff; | ||
24528 | res[k + 1] = (m >>> 8) & 0xff; | ||
24529 | res[k] = m & 0xff; | ||
24530 | } | ||
24531 | } | ||
24532 | return res; | ||
24533 | } | ||
24534 | exports.split32 = split32; | ||
24535 | |||
24536 | function rotr32(w, b) { | ||
24537 | return (w >>> b) | (w << (32 - b)); | ||
24538 | } | ||
24539 | exports.rotr32 = rotr32; | ||
24540 | |||
24541 | function rotl32(w, b) { | ||
24542 | return (w << b) | (w >>> (32 - b)); | ||
24543 | } | ||
24544 | exports.rotl32 = rotl32; | ||
24545 | |||
24546 | function sum32(a, b) { | ||
24547 | return (a + b) >>> 0; | ||
24548 | } | ||
24549 | exports.sum32 = sum32; | ||
24550 | |||
24551 | function sum32_3(a, b, c) { | ||
24552 | return (a + b + c) >>> 0; | ||
24553 | } | ||
24554 | exports.sum32_3 = sum32_3; | ||
24555 | |||
24556 | function sum32_4(a, b, c, d) { | ||
24557 | return (a + b + c + d) >>> 0; | ||
24558 | } | ||
24559 | exports.sum32_4 = sum32_4; | ||
24560 | |||
24561 | function sum32_5(a, b, c, d, e) { | ||
24562 | return (a + b + c + d + e) >>> 0; | ||
24563 | } | ||
24564 | exports.sum32_5 = sum32_5; | ||
24565 | |||
24566 | function sum64(buf, pos, ah, al) { | ||
24567 | var bh = buf[pos]; | ||
24568 | var bl = buf[pos + 1]; | ||
24569 | |||
24570 | var lo = (al + bl) >>> 0; | ||
24571 | var hi = (lo < al ? 1 : 0) + ah + bh; | ||
24572 | buf[pos] = hi >>> 0; | ||
24573 | buf[pos + 1] = lo; | ||
24574 | } | ||
24575 | exports.sum64 = sum64; | ||
24576 | |||
24577 | function sum64_hi(ah, al, bh, bl) { | ||
24578 | var lo = (al + bl) >>> 0; | ||
24579 | var hi = (lo < al ? 1 : 0) + ah + bh; | ||
24580 | return hi >>> 0; | ||
24581 | } | ||
24582 | exports.sum64_hi = sum64_hi; | ||
24583 | |||
24584 | function sum64_lo(ah, al, bh, bl) { | ||
24585 | var lo = al + bl; | ||
24586 | return lo >>> 0; | ||
24587 | } | ||
24588 | exports.sum64_lo = sum64_lo; | ||
24589 | |||
24590 | function sum64_4_hi(ah, al, bh, bl, ch, cl, dh, dl) { | ||
24591 | var carry = 0; | ||
24592 | var lo = al; | ||
24593 | lo = (lo + bl) >>> 0; | ||
24594 | carry += lo < al ? 1 : 0; | ||
24595 | lo = (lo + cl) >>> 0; | ||
24596 | carry += lo < cl ? 1 : 0; | ||
24597 | lo = (lo + dl) >>> 0; | ||
24598 | carry += lo < dl ? 1 : 0; | ||
24599 | |||
24600 | var hi = ah + bh + ch + dh + carry; | ||
24601 | return hi >>> 0; | ||
24602 | } | ||
24603 | exports.sum64_4_hi = sum64_4_hi; | ||
24604 | |||
24605 | function sum64_4_lo(ah, al, bh, bl, ch, cl, dh, dl) { | ||
24606 | var lo = al + bl + cl + dl; | ||
24607 | return lo >>> 0; | ||
24608 | } | ||
24609 | exports.sum64_4_lo = sum64_4_lo; | ||
24610 | |||
24611 | function sum64_5_hi(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { | ||
24612 | var carry = 0; | ||
24613 | var lo = al; | ||
24614 | lo = (lo + bl) >>> 0; | ||
24615 | carry += lo < al ? 1 : 0; | ||
24616 | lo = (lo + cl) >>> 0; | ||
24617 | carry += lo < cl ? 1 : 0; | ||
24618 | lo = (lo + dl) >>> 0; | ||
24619 | carry += lo < dl ? 1 : 0; | ||
24620 | lo = (lo + el) >>> 0; | ||
24621 | carry += lo < el ? 1 : 0; | ||
24622 | |||
24623 | var hi = ah + bh + ch + dh + eh + carry; | ||
24624 | return hi >>> 0; | ||
24625 | } | ||
24626 | exports.sum64_5_hi = sum64_5_hi; | ||
24627 | |||
24628 | function sum64_5_lo(ah, al, bh, bl, ch, cl, dh, dl, eh, el) { | ||
24629 | var lo = al + bl + cl + dl + el; | ||
24630 | |||
24631 | return lo >>> 0; | ||
24632 | } | ||
24633 | exports.sum64_5_lo = sum64_5_lo; | ||
24634 | |||
24635 | function rotr64_hi(ah, al, num) { | ||
24636 | var r = (al << (32 - num)) | (ah >>> num); | ||
24637 | return r >>> 0; | ||
24638 | } | ||
24639 | exports.rotr64_hi = rotr64_hi; | ||
24640 | |||
24641 | function rotr64_lo(ah, al, num) { | ||
24642 | var r = (ah << (32 - num)) | (al >>> num); | ||
24643 | return r >>> 0; | ||
24644 | } | ||
24645 | exports.rotr64_lo = rotr64_lo; | ||
24646 | |||
24647 | function shr64_hi(ah, al, num) { | ||
24648 | return ah >>> num; | ||
24649 | } | ||
24650 | exports.shr64_hi = shr64_hi; | ||
24651 | |||
24652 | function shr64_lo(ah, al, num) { | ||
24653 | var r = (ah << (32 - num)) | (al >>> num); | ||
24654 | return r >>> 0; | ||
24655 | } | ||
24656 | exports.shr64_lo = shr64_lo; | ||
24657 | |||
24658 | },{"inherits":163,"minimalistic-assert":176}],159:[function(require,module,exports){ | ||
24659 | 'use strict'; | ||
24660 | |||
24661 | var hash = require('hash.js'); | ||
24662 | var utils = require('minimalistic-crypto-utils'); | ||
24663 | var assert = require('minimalistic-assert'); | ||
24664 | |||
24665 | function HmacDRBG(options) { | ||
24666 | if (!(this instanceof HmacDRBG)) | ||
24667 | return new HmacDRBG(options); | ||
24668 | this.hash = options.hash; | ||
24669 | this.predResist = !!options.predResist; | ||
24670 | |||
24671 | this.outLen = this.hash.outSize; | ||
24672 | this.minEntropy = options.minEntropy || this.hash.hmacStrength; | ||
24673 | |||
24674 | this._reseed = null; | ||
24675 | this.reseedInterval = null; | ||
24676 | this.K = null; | ||
24677 | this.V = null; | ||
24678 | |||
24679 | var entropy = utils.toArray(options.entropy, options.entropyEnc || 'hex'); | ||
24680 | var nonce = utils.toArray(options.nonce, options.nonceEnc || 'hex'); | ||
24681 | var pers = utils.toArray(options.pers, options.persEnc || 'hex'); | ||
24682 | assert(entropy.length >= (this.minEntropy / 8), | ||
24683 | 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); | ||
24684 | this._init(entropy, nonce, pers); | ||
24685 | } | ||
24686 | module.exports = HmacDRBG; | ||
24687 | |||
24688 | HmacDRBG.prototype._init = function init(entropy, nonce, pers) { | ||
24689 | var seed = entropy.concat(nonce).concat(pers); | ||
24690 | |||
24691 | this.K = new Array(this.outLen / 8); | ||
24692 | this.V = new Array(this.outLen / 8); | ||
24693 | for (var i = 0; i < this.V.length; i++) { | ||
24694 | this.K[i] = 0x00; | ||
24695 | this.V[i] = 0x01; | ||
24696 | } | ||
24697 | |||
24698 | this._update(seed); | ||
24699 | this._reseed = 1; | ||
24700 | this.reseedInterval = 0x1000000000000; // 2^48 | ||
24701 | }; | ||
24702 | |||
24703 | HmacDRBG.prototype._hmac = function hmac() { | ||
24704 | return new hash.hmac(this.hash, this.K); | ||
24705 | }; | ||
24706 | |||
24707 | HmacDRBG.prototype._update = function update(seed) { | ||
24708 | var kmac = this._hmac() | ||
24709 | .update(this.V) | ||
24710 | .update([ 0x00 ]); | ||
24711 | if (seed) | ||
24712 | kmac = kmac.update(seed); | ||
24713 | this.K = kmac.digest(); | ||
24714 | this.V = this._hmac().update(this.V).digest(); | ||
24715 | if (!seed) | ||
24716 | return; | ||
24717 | |||
24718 | this.K = this._hmac() | ||
24719 | .update(this.V) | ||
24720 | .update([ 0x01 ]) | ||
24721 | .update(seed) | ||
24722 | .digest(); | ||
24723 | this.V = this._hmac().update(this.V).digest(); | ||
24724 | }; | ||
24725 | |||
24726 | HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { | ||
24727 | // Optional entropy enc | ||
24728 | if (typeof entropyEnc !== 'string') { | ||
24729 | addEnc = add; | ||
24730 | add = entropyEnc; | ||
24731 | entropyEnc = null; | ||
24732 | } | ||
24733 | |||
24734 | entropy = utils.toArray(entropy, entropyEnc); | ||
24735 | add = utils.toArray(add, addEnc); | ||
24736 | |||
24737 | assert(entropy.length >= (this.minEntropy / 8), | ||
24738 | 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); | ||
24739 | |||
24740 | this._update(entropy.concat(add || [])); | ||
24741 | this._reseed = 1; | ||
24742 | }; | ||
24743 | |||
24744 | HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { | ||
24745 | if (this._reseed > this.reseedInterval) | ||
24746 | throw new Error('Reseed is required'); | ||
24747 | |||
24748 | // Optional encoding | ||
24749 | if (typeof enc !== 'string') { | ||
24750 | addEnc = add; | ||
24751 | add = enc; | ||
24752 | enc = null; | ||
24753 | } | ||
24754 | |||
24755 | // Optional additional data | ||
24756 | if (add) { | ||
24757 | add = utils.toArray(add, addEnc || 'hex'); | ||
24758 | this._update(add); | ||
24759 | } | ||
24760 | |||
24761 | var temp = []; | ||
24762 | while (temp.length < len) { | ||
24763 | this.V = this._hmac().update(this.V).digest(); | ||
24764 | temp = temp.concat(this.V); | ||
24765 | } | ||
24766 | |||
24767 | var res = temp.slice(0, len); | ||
24768 | this._update(add); | ||
24769 | this._reseed++; | ||
24770 | return utils.encode(res, enc); | ||
24771 | }; | ||
24772 | |||
24773 | },{"hash.js":147,"minimalistic-assert":176,"minimalistic-crypto-utils":177}],160:[function(require,module,exports){ | ||
24774 | /** | ||
24775 | * Properly escape JSON for usage as an object literal inside of a `<script>` tag. | ||
24776 | * JS implementation of http://golang.org/pkg/encoding/json/#HTMLEscape | ||
24777 | * More info: http://timelessrepo.com/json-isnt-a-javascript-subset | ||
24778 | */ | ||
24779 | |||
24780 | 'use strict'; | ||
24781 | |||
24782 | var ESCAPE_LOOKUP = { | ||
24783 | '&': '\\u0026', | ||
24784 | '>': '\\u003e', | ||
24785 | '<': '\\u003c', | ||
24786 | '\u2028': '\\u2028', | ||
24787 | '\u2029': '\\u2029' | ||
24788 | }; | ||
24789 | |||
24790 | var ESCAPE_REGEX = /[&><\u2028\u2029]/g; | ||
24791 | |||
24792 | function escaper(match) { | ||
24793 | return ESCAPE_LOOKUP[match]; | ||
24794 | } | ||
24795 | |||
24796 | module.exports = function(obj) { | ||
24797 | return JSON.stringify(obj).replace(ESCAPE_REGEX, escaper); | ||
24798 | }; | ||
24799 | |||
24800 | /***/ | ||
24801 | |||
24802 | var TERMINATORS_LOOKUP = { | ||
24803 | '\u2028': '\\u2028', | ||
24804 | '\u2029': '\\u2029' | ||
24805 | }; | ||
24806 | |||
24807 | var TERMINATORS_REGEX = /[\u2028\u2029]/g; | ||
24808 | |||
24809 | function sanitizer(match) { | ||
24810 | return TERMINATORS_LOOKUP[match]; | ||
24811 | } | ||
24812 | |||
24813 | module.exports.sanitize = function(str) { | ||
24814 | return str.replace(TERMINATORS_REGEX, sanitizer); | ||
24815 | }; | ||
24816 | |||
24817 | },{}],161:[function(require,module,exports){ | ||
24818 | exports.read = function (buffer, offset, isLE, mLen, nBytes) { | ||
24819 | var e, m | ||
24820 | var eLen = nBytes * 8 - mLen - 1 | ||
24821 | var eMax = (1 << eLen) - 1 | ||
24822 | var eBias = eMax >> 1 | ||
24823 | var nBits = -7 | ||
24824 | var i = isLE ? (nBytes - 1) : 0 | ||
24825 | var d = isLE ? -1 : 1 | ||
24826 | var s = buffer[offset + i] | ||
24827 | |||
24828 | i += d | ||
24829 | |||
24830 | e = s & ((1 << (-nBits)) - 1) | ||
24831 | s >>= (-nBits) | ||
24832 | nBits += eLen | ||
24833 | for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} | ||
24834 | |||
24835 | m = e & ((1 << (-nBits)) - 1) | ||
24836 | e >>= (-nBits) | ||
24837 | nBits += mLen | ||
24838 | for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} | ||
24839 | |||
24840 | if (e === 0) { | ||
24841 | e = 1 - eBias | ||
24842 | } else if (e === eMax) { | ||
24843 | return m ? NaN : ((s ? -1 : 1) * Infinity) | ||
24844 | } else { | ||
24845 | m = m + Math.pow(2, mLen) | ||
24846 | e = e - eBias | ||
24847 | } | ||
24848 | return (s ? -1 : 1) * m * Math.pow(2, e - mLen) | ||
24849 | } | ||
24850 | |||
24851 | exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { | ||
24852 | var e, m, c | ||
24853 | var eLen = nBytes * 8 - mLen - 1 | ||
24854 | var eMax = (1 << eLen) - 1 | ||
24855 | var eBias = eMax >> 1 | ||
24856 | var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) | ||
24857 | var i = isLE ? 0 : (nBytes - 1) | ||
24858 | var d = isLE ? 1 : -1 | ||
24859 | var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 | ||
24860 | |||
24861 | value = Math.abs(value) | ||
24862 | |||
24863 | if (isNaN(value) || value === Infinity) { | ||
24864 | m = isNaN(value) ? 1 : 0 | ||
24865 | e = eMax | ||
24866 | } else { | ||
24867 | e = Math.floor(Math.log(value) / Math.LN2) | ||
24868 | if (value * (c = Math.pow(2, -e)) < 1) { | ||
24869 | e-- | ||
24870 | c *= 2 | ||
24871 | } | ||
24872 | if (e + eBias >= 1) { | ||
24873 | value += rt / c | ||
24874 | } else { | ||
24875 | value += rt * Math.pow(2, 1 - eBias) | ||
24876 | } | ||
24877 | if (value * c >= 2) { | ||
24878 | e++ | ||
24879 | c /= 2 | ||
24880 | } | ||
24881 | |||
24882 | if (e + eBias >= eMax) { | ||
24883 | m = 0 | ||
24884 | e = eMax | ||
24885 | } else if (e + eBias >= 1) { | ||
24886 | m = (value * c - 1) * Math.pow(2, mLen) | ||
24887 | e = e + eBias | ||
24888 | } else { | ||
24889 | m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) | ||
24890 | e = 0 | ||
24891 | } | ||
24892 | } | ||
24893 | |||
24894 | for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} | ||
24895 | |||
24896 | e = (e << mLen) | m | ||
24897 | eLen += mLen | ||
24898 | for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} | ||
24899 | |||
24900 | buffer[offset + i - d] |= s * 128 | ||
24901 | } | ||
24902 | |||
24903 | },{}],162:[function(require,module,exports){ | ||
24904 | |||
24905 | var indexOf = [].indexOf; | ||
24906 | |||
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; | ||
24911 | } | ||
24912 | return -1; | ||
24913 | }; | ||
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, { | ||
24920 | constructor: { | ||
24921 | value: ctor, | ||
24922 | enumerable: false, | ||
24923 | writable: true, | ||
24924 | configurable: true | ||
24925 | } | ||
24926 | }); | ||
24927 | }; | ||
24928 | } else { | ||
24929 | // old school shim for old browsers | ||
24930 | module.exports = function inherits(ctor, superCtor) { | ||
24931 | ctor.super_ = superCtor | ||
24932 | var TempCtor = function () {} | ||
24933 | TempCtor.prototype = superCtor.prototype | ||
24934 | ctor.prototype = new TempCtor() | ||
24935 | ctor.prototype.constructor = ctor | ||
24936 | } | ||
24937 | } | ||
24938 | |||
24939 | },{}],164:[function(require,module,exports){ | ||
24940 | /*! | ||
24941 | * Determine if an object is a Buffer | ||
24942 | * | ||
24943 | * @author Feross Aboukhadijeh <https://feross.org> | ||
24944 | * @license MIT | ||
24945 | */ | ||
24946 | |||
24947 | // The _isBuffer check is for Safari 5-7 support, because it's missing | ||
24948 | // Object.prototype.constructor. Remove this eventually | ||
24949 | module.exports = function (obj) { | ||
24950 | return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) | ||
24951 | } | ||
24952 | |||
24953 | function isBuffer (obj) { | ||
24954 | return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) | ||
24955 | } | ||
24956 | |||
24957 | // For Node v0.10 support. Remove this eventually. | ||
24958 | function isSlowBuffer (obj) { | ||
24959 | return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) | ||
24960 | } | ||
24961 | |||
24962 | },{}],165:[function(require,module,exports){ | ||
24963 | var toString = {}.toString; | ||
24964 | |||
24965 | module.exports = Array.isArray || function (arr) { | ||
24966 | return toString.call(arr) == '[object Array]'; | ||
24967 | }; | ||
24968 | |||
24969 | },{}],166:[function(require,module,exports){ | ||
24970 | /* | ||
24971 | A JavaScript implementation of the SHA family of hashes, as | ||
24972 | defined in FIPS PUB 180-4 and FIPS PUB 202, as well as the corresponding | ||
24973 | HMAC implementation as defined in FIPS PUB 198a | ||
24974 | |||
24975 | Copyright Brian Turek 2008-2017 | ||
24976 | Distributed under the BSD License | ||
24977 | See http://caligatio.github.com/jsSHA/ for more information | ||
24978 | |||
24979 | Several functions taken from Paul Johnston | ||
24980 | */ | ||
24981 | 'use strict';(function(Y){function C(c,a,b){var e=0,h=[],n=0,g,l,d,f,m,q,u,r,I=!1,v=[],w=[],t,y=!1,z=!1,x=-1;b=b||{};g=b.encoding||"UTF8";t=b.numRounds||1;if(t!==parseInt(t,10)||1>t)throw Error("numRounds must a integer >= 1");if("SHA-1"===c)m=512,q=K,u=Z,f=160,r=function(a){return a.slice()};else if(0===c.lastIndexOf("SHA-",0))if(q=function(a,b){return L(a,b,c)},u=function(a,b,h,e){var k,f;if("SHA-224"===c||"SHA-256"===c)k=(b+65>>>9<<4)+15,f=16;else if("SHA-384"===c||"SHA-512"===c)k=(b+129>>>10<< | ||
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); | ||
25015 | |||
25016 | },{}],167:[function(require,module,exports){ | ||
25017 | 'use strict' | ||
25018 | module.exports = require('./lib/api')(require('./lib/keccak')) | ||
25019 | |||
25020 | },{"./lib/api":168,"./lib/keccak":172}],168:[function(require,module,exports){ | ||
25021 | 'use strict' | ||
25022 | var createKeccak = require('./keccak') | ||
25023 | var createShake = require('./shake') | ||
25024 | |||
25025 | module.exports = function (KeccakState) { | ||
25026 | var Keccak = createKeccak(KeccakState) | ||
25027 | var Shake = createShake(KeccakState) | ||
25028 | |||
25029 | return function (algorithm, options) { | ||
25030 | var hash = typeof algorithm === 'string' ? algorithm.toLowerCase() : algorithm | ||
25031 | switch (hash) { | ||
25032 | case 'keccak224': return new Keccak(1152, 448, null, 224, options) | ||
25033 | case 'keccak256': return new Keccak(1088, 512, null, 256, options) | ||
25034 | case 'keccak384': return new Keccak(832, 768, null, 384, options) | ||
25035 | case 'keccak512': return new Keccak(576, 1024, null, 512, options) | ||
25036 | |||
25037 | case 'sha3-224': return new Keccak(1152, 448, 0x06, 224, options) | ||
25038 | case 'sha3-256': return new Keccak(1088, 512, 0x06, 256, options) | ||
25039 | case 'sha3-384': return new Keccak(832, 768, 0x06, 384, options) | ||
25040 | case 'sha3-512': return new Keccak(576, 1024, 0x06, 512, options) | ||
25041 | |||
25042 | case 'shake128': return new Shake(1344, 256, 0x1f, options) | ||
25043 | case 'shake256': return new Shake(1088, 512, 0x1f, options) | ||
25044 | |||
25045 | default: throw new Error('Invald algorithm: ' + algorithm) | ||
25046 | } | ||
25047 | } | ||
25048 | } | ||
25049 | |||
25050 | },{"./keccak":169,"./shake":170}],169:[function(require,module,exports){ | ||
25051 | 'use strict' | ||
25052 | var Buffer = require('safe-buffer').Buffer | ||
25053 | var Transform = require('stream').Transform | ||
25054 | var inherits = require('inherits') | ||
25055 | |||
25056 | module.exports = function (KeccakState) { | ||
25057 | function Keccak (rate, capacity, delimitedSuffix, hashBitLength, options) { | ||
25058 | Transform.call(this, options) | ||
25059 | |||
25060 | this._rate = rate | ||
25061 | this._capacity = capacity | ||
25062 | this._delimitedSuffix = delimitedSuffix | ||
25063 | this._hashBitLength = hashBitLength | ||
25064 | this._options = options | ||
25065 | |||
25066 | this._state = new KeccakState() | ||
25067 | this._state.initialize(rate, capacity) | ||
25068 | this._finalized = false | ||
25069 | } | ||
25070 | |||
25071 | inherits(Keccak, Transform) | ||
25072 | |||
25073 | Keccak.prototype._transform = function (chunk, encoding, callback) { | ||
25074 | var error = null | ||
25075 | try { | ||
25076 | this.update(chunk, encoding) | ||
25077 | } catch (err) { | ||
25078 | error = err | ||
25079 | } | ||
25080 | |||
25081 | callback(error) | ||
25082 | } | ||
25083 | |||
25084 | Keccak.prototype._flush = function (callback) { | ||
25085 | var error = null | ||
25086 | try { | ||
25087 | this.push(this.digest()) | ||
25088 | } catch (err) { | ||
25089 | error = err | ||
25090 | } | ||
25091 | |||
25092 | callback(error) | ||
25093 | } | ||
25094 | |||
25095 | Keccak.prototype.update = function (data, encoding) { | ||
25096 | if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') | ||
25097 | if (this._finalized) throw new Error('Digest already called') | ||
25098 | if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) | ||
25099 | |||
25100 | this._state.absorb(data) | ||
25101 | |||
25102 | return this | ||
25103 | } | ||
25104 | |||
25105 | Keccak.prototype.digest = function (encoding) { | ||
25106 | if (this._finalized) throw new Error('Digest already called') | ||
25107 | this._finalized = true | ||
25108 | |||
25109 | if (this._delimitedSuffix) this._state.absorbLastFewBits(this._delimitedSuffix) | ||
25110 | var digest = this._state.squeeze(this._hashBitLength / 8) | ||
25111 | if (encoding !== undefined) digest = digest.toString(encoding) | ||
25112 | |||
25113 | this._resetState() | ||
25114 | |||
25115 | return digest | ||
25116 | } | ||
25117 | |||
25118 | // remove result from memory | ||
25119 | Keccak.prototype._resetState = function () { | ||
25120 | this._state.initialize(this._rate, this._capacity) | ||
25121 | return this | ||
25122 | } | ||
25123 | |||
25124 | // because sometimes we need hash right now and little later | ||
25125 | Keccak.prototype._clone = function () { | ||
25126 | var clone = new Keccak(this._rate, this._capacity, this._delimitedSuffix, this._hashBitLength, this._options) | ||
25127 | this._state.copy(clone._state) | ||
25128 | clone._finalized = this._finalized | ||
25129 | |||
25130 | return clone | ||
25131 | } | ||
25132 | |||
25133 | return Keccak | ||
25134 | } | ||
25135 | |||
25136 | },{"inherits":163,"safe-buffer":247,"stream":263}],170:[function(require,module,exports){ | ||
25137 | 'use strict' | ||
25138 | var Buffer = require('safe-buffer').Buffer | ||
25139 | var Transform = require('stream').Transform | ||
25140 | var inherits = require('inherits') | ||
25141 | |||
25142 | module.exports = function (KeccakState) { | ||
25143 | function Shake (rate, capacity, delimitedSuffix, options) { | ||
25144 | Transform.call(this, options) | ||
25145 | |||
25146 | this._rate = rate | ||
25147 | this._capacity = capacity | ||
25148 | this._delimitedSuffix = delimitedSuffix | ||
25149 | this._options = options | ||
25150 | |||
25151 | this._state = new KeccakState() | ||
25152 | this._state.initialize(rate, capacity) | ||
25153 | this._finalized = false | ||
25154 | } | ||
25155 | |||
25156 | inherits(Shake, Transform) | ||
25157 | |||
25158 | Shake.prototype._transform = function (chunk, encoding, callback) { | ||
25159 | var error = null | ||
25160 | try { | ||
25161 | this.update(chunk, encoding) | ||
25162 | } catch (err) { | ||
25163 | error = err | ||
25164 | } | ||
25165 | |||
25166 | callback(error) | ||
25167 | } | ||
25168 | |||
25169 | Shake.prototype._flush = function () {} | ||
25170 | |||
25171 | Shake.prototype._read = function (size) { | ||
25172 | this.push(this.squeeze(size)) | ||
25173 | } | ||
25174 | |||
25175 | Shake.prototype.update = function (data, encoding) { | ||
25176 | if (!Buffer.isBuffer(data) && typeof data !== 'string') throw new TypeError('Data must be a string or a buffer') | ||
25177 | if (this._finalized) throw new Error('Squeeze already called') | ||
25178 | if (!Buffer.isBuffer(data)) data = Buffer.from(data, encoding) | ||
25179 | |||
25180 | this._state.absorb(data) | ||
25181 | |||
25182 | return this | ||
25183 | } | ||
25184 | |||
25185 | Shake.prototype.squeeze = function (dataByteLength, encoding) { | ||
25186 | if (!this._finalized) { | ||
25187 | this._finalized = true | ||
25188 | this._state.absorbLastFewBits(this._delimitedSuffix) | ||
25189 | } | ||
25190 | |||
25191 | var data = this._state.squeeze(dataByteLength) | ||
25192 | if (encoding !== undefined) data = data.toString(encoding) | ||
25193 | |||
25194 | return data | ||
25195 | } | ||
25196 | |||
25197 | Shake.prototype._resetState = function () { | ||
25198 | this._state.initialize(this._rate, this._capacity) | ||
25199 | return this | ||
25200 | } | ||
25201 | |||
25202 | Shake.prototype._clone = function () { | ||
25203 | var clone = new Shake(this._rate, this._capacity, this._delimitedSuffix, this._options) | ||
25204 | this._state.copy(clone._state) | ||
25205 | clone._finalized = this._finalized | ||
25206 | |||
25207 | return clone | ||
25208 | } | ||
25209 | |||
25210 | return Shake | ||
25211 | } | ||
25212 | |||
25213 | },{"inherits":163,"safe-buffer":247,"stream":263}],171:[function(require,module,exports){ | ||
25214 | 'use strict' | ||
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] | ||
25216 | |||
25217 | exports.p1600 = function (s) { | ||
25218 | for (var round = 0; round < 24; ++round) { | ||
25219 | // theta | ||
25220 | var lo0 = s[0] ^ s[10] ^ s[20] ^ s[30] ^ s[40] | ||
25221 | var hi0 = s[1] ^ s[11] ^ s[21] ^ s[31] ^ s[41] | ||
25222 | var lo1 = s[2] ^ s[12] ^ s[22] ^ s[32] ^ s[42] | ||
25223 | var hi1 = s[3] ^ s[13] ^ s[23] ^ s[33] ^ s[43] | ||
25224 | var lo2 = s[4] ^ s[14] ^ s[24] ^ s[34] ^ s[44] | ||
25225 | var hi2 = s[5] ^ s[15] ^ s[25] ^ s[35] ^ s[45] | ||
25226 | var lo3 = s[6] ^ s[16] ^ s[26] ^ s[36] ^ s[46] | ||
25227 | var hi3 = s[7] ^ s[17] ^ s[27] ^ s[37] ^ s[47] | ||
25228 | var lo4 = s[8] ^ s[18] ^ s[28] ^ s[38] ^ s[48] | ||
25229 | var hi4 = s[9] ^ s[19] ^ s[29] ^ s[39] ^ s[49] | ||
25230 | |||
25231 | var lo = lo4 ^ (lo1 << 1 | hi1 >>> 31) | ||
25232 | var hi = hi4 ^ (hi1 << 1 | lo1 >>> 31) | ||
25233 | var t1slo0 = s[0] ^ lo | ||
25234 | var t1shi0 = s[1] ^ hi | ||
25235 | var t1slo5 = s[10] ^ lo | ||
25236 | var t1shi5 = s[11] ^ hi | ||
25237 | var t1slo10 = s[20] ^ lo | ||
25238 | var t1shi10 = s[21] ^ hi | ||
25239 | var t1slo15 = s[30] ^ lo | ||
25240 | var t1shi15 = s[31] ^ hi | ||
25241 | var t1slo20 = s[40] ^ lo | ||
25242 | var t1shi20 = s[41] ^ hi | ||
25243 | lo = lo0 ^ (lo2 << 1 | hi2 >>> 31) | ||
25244 | hi = hi0 ^ (hi2 << 1 | lo2 >>> 31) | ||
25245 | var t1slo1 = s[2] ^ lo | ||
25246 | var t1shi1 = s[3] ^ hi | ||
25247 | var t1slo6 = s[12] ^ lo | ||
25248 | var t1shi6 = s[13] ^ hi | ||
25249 | var t1slo11 = s[22] ^ lo | ||
25250 | var t1shi11 = s[23] ^ hi | ||
25251 | var t1slo16 = s[32] ^ lo | ||
25252 | var t1shi16 = s[33] ^ hi | ||
25253 | var t1slo21 = s[42] ^ lo | ||
25254 | var t1shi21 = s[43] ^ hi | ||
25255 | lo = lo1 ^ (lo3 << 1 | hi3 >>> 31) | ||
25256 | hi = hi1 ^ (hi3 << 1 | lo3 >>> 31) | ||
25257 | var t1slo2 = s[4] ^ lo | ||
25258 | var t1shi2 = s[5] ^ hi | ||
25259 | var t1slo7 = s[14] ^ lo | ||
25260 | var t1shi7 = s[15] ^ hi | ||
25261 | var t1slo12 = s[24] ^ lo | ||
25262 | var t1shi12 = s[25] ^ hi | ||
25263 | var t1slo17 = s[34] ^ lo | ||
25264 | var t1shi17 = s[35] ^ hi | ||
25265 | var t1slo22 = s[44] ^ lo | ||
25266 | var t1shi22 = s[45] ^ hi | ||
25267 | lo = lo2 ^ (lo4 << 1 | hi4 >>> 31) | ||
25268 | hi = hi2 ^ (hi4 << 1 | lo4 >>> 31) | ||
25269 | var t1slo3 = s[6] ^ lo | ||
25270 | var t1shi3 = s[7] ^ hi | ||
25271 | var t1slo8 = s[16] ^ lo | ||
25272 | var t1shi8 = s[17] ^ hi | ||
25273 | var t1slo13 = s[26] ^ lo | ||
25274 | var t1shi13 = s[27] ^ hi | ||
25275 | var t1slo18 = s[36] ^ lo | ||
25276 | var t1shi18 = s[37] ^ hi | ||
25277 | var t1slo23 = s[46] ^ lo | ||
25278 | var t1shi23 = s[47] ^ hi | ||
25279 | lo = lo3 ^ (lo0 << 1 | hi0 >>> 31) | ||
25280 | hi = hi3 ^ (hi0 << 1 | lo0 >>> 31) | ||
25281 | var t1slo4 = s[8] ^ lo | ||
25282 | var t1shi4 = s[9] ^ hi | ||
25283 | var t1slo9 = s[18] ^ lo | ||
25284 | var t1shi9 = s[19] ^ hi | ||
25285 | var t1slo14 = s[28] ^ lo | ||
25286 | var t1shi14 = s[29] ^ hi | ||
25287 | var t1slo19 = s[38] ^ lo | ||
25288 | var t1shi19 = s[39] ^ hi | ||
25289 | var t1slo24 = s[48] ^ lo | ||
25290 | var t1shi24 = s[49] ^ hi | ||
25291 | |||
25292 | // rho & pi | ||
25293 | var t2slo0 = t1slo0 | ||
25294 | var t2shi0 = t1shi0 | ||
25295 | var t2slo16 = (t1shi5 << 4 | t1slo5 >>> 28) | ||
25296 | var t2shi16 = (t1slo5 << 4 | t1shi5 >>> 28) | ||
25297 | var t2slo7 = (t1slo10 << 3 | t1shi10 >>> 29) | ||
25298 | var t2shi7 = (t1shi10 << 3 | t1slo10 >>> 29) | ||
25299 | var t2slo23 = (t1shi15 << 9 | t1slo15 >>> 23) | ||
25300 | var t2shi23 = (t1slo15 << 9 | t1shi15 >>> 23) | ||
25301 | var t2slo14 = (t1slo20 << 18 | t1shi20 >>> 14) | ||
25302 | var t2shi14 = (t1shi20 << 18 | t1slo20 >>> 14) | ||
25303 | var t2slo10 = (t1slo1 << 1 | t1shi1 >>> 31) | ||
25304 | var t2shi10 = (t1shi1 << 1 | t1slo1 >>> 31) | ||
25305 | var t2slo1 = (t1shi6 << 12 | t1slo6 >>> 20) | ||
25306 | var t2shi1 = (t1slo6 << 12 | t1shi6 >>> 20) | ||
25307 | var t2slo17 = (t1slo11 << 10 | t1shi11 >>> 22) | ||
25308 | var t2shi17 = (t1shi11 << 10 | t1slo11 >>> 22) | ||
25309 | var t2slo8 = (t1shi16 << 13 | t1slo16 >>> 19) | ||
25310 | var t2shi8 = (t1slo16 << 13 | t1shi16 >>> 19) | ||
25311 | var t2slo24 = (t1slo21 << 2 | t1shi21 >>> 30) | ||
25312 | var t2shi24 = (t1shi21 << 2 | t1slo21 >>> 30) | ||
25313 | var t2slo20 = (t1shi2 << 30 | t1slo2 >>> 2) | ||
25314 | var t2shi20 = (t1slo2 << 30 | t1shi2 >>> 2) | ||
25315 | var t2slo11 = (t1slo7 << 6 | t1shi7 >>> 26) | ||
25316 | var t2shi11 = (t1shi7 << 6 | t1slo7 >>> 26) | ||
25317 | var t2slo2 = (t1shi12 << 11 | t1slo12 >>> 21) | ||
25318 | var t2shi2 = (t1slo12 << 11 | t1shi12 >>> 21) | ||
25319 | var t2slo18 = (t1slo17 << 15 | t1shi17 >>> 17) | ||
25320 | var t2shi18 = (t1shi17 << 15 | t1slo17 >>> 17) | ||
25321 | var t2slo9 = (t1shi22 << 29 | t1slo22 >>> 3) | ||
25322 | var t2shi9 = (t1slo22 << 29 | t1shi22 >>> 3) | ||
25323 | var t2slo5 = (t1slo3 << 28 | t1shi3 >>> 4) | ||
25324 | var t2shi5 = (t1shi3 << 28 | t1slo3 >>> 4) | ||
25325 | var t2slo21 = (t1shi8 << 23 | t1slo8 >>> 9) | ||
25326 | var t2shi21 = (t1slo8 << 23 | t1shi8 >>> 9) | ||
25327 | var t2slo12 = (t1slo13 << 25 | t1shi13 >>> 7) | ||
25328 | var t2shi12 = (t1shi13 << 25 | t1slo13 >>> 7) | ||
25329 | var t2slo3 = (t1slo18 << 21 | t1shi18 >>> 11) | ||
25330 | var t2shi3 = (t1shi18 << 21 | t1slo18 >>> 11) | ||
25331 | var t2slo19 = (t1shi23 << 24 | t1slo23 >>> 8) | ||
25332 | var t2shi19 = (t1slo23 << 24 | t1shi23 >>> 8) | ||
25333 | var t2slo15 = (t1slo4 << 27 | t1shi4 >>> 5) | ||
25334 | var t2shi15 = (t1shi4 << 27 | t1slo4 >>> 5) | ||
25335 | var t2slo6 = (t1slo9 << 20 | t1shi9 >>> 12) | ||
25336 | var t2shi6 = (t1shi9 << 20 | t1slo9 >>> 12) | ||
25337 | var t2slo22 = (t1shi14 << 7 | t1slo14 >>> 25) | ||
25338 | var t2shi22 = (t1slo14 << 7 | t1shi14 >>> 25) | ||
25339 | var t2slo13 = (t1slo19 << 8 | t1shi19 >>> 24) | ||
25340 | var t2shi13 = (t1shi19 << 8 | t1slo19 >>> 24) | ||
25341 | var t2slo4 = (t1slo24 << 14 | t1shi24 >>> 18) | ||
25342 | var t2shi4 = (t1shi24 << 14 | t1slo24 >>> 18) | ||
25343 | |||
25344 | // chi | ||
25345 | s[0] = t2slo0 ^ (~t2slo1 & t2slo2) | ||
25346 | s[1] = t2shi0 ^ (~t2shi1 & t2shi2) | ||
25347 | s[10] = t2slo5 ^ (~t2slo6 & t2slo7) | ||
25348 | s[11] = t2shi5 ^ (~t2shi6 & t2shi7) | ||
25349 | s[20] = t2slo10 ^ (~t2slo11 & t2slo12) | ||
25350 | s[21] = t2shi10 ^ (~t2shi11 & t2shi12) | ||
25351 | s[30] = t2slo15 ^ (~t2slo16 & t2slo17) | ||
25352 | s[31] = t2shi15 ^ (~t2shi16 & t2shi17) | ||
25353 | s[40] = t2slo20 ^ (~t2slo21 & t2slo22) | ||
25354 | s[41] = t2shi20 ^ (~t2shi21 & t2shi22) | ||
25355 | s[2] = t2slo1 ^ (~t2slo2 & t2slo3) | ||
25356 | s[3] = t2shi1 ^ (~t2shi2 & t2shi3) | ||
25357 | s[12] = t2slo6 ^ (~t2slo7 & t2slo8) | ||
25358 | s[13] = t2shi6 ^ (~t2shi7 & t2shi8) | ||
25359 | s[22] = t2slo11 ^ (~t2slo12 & t2slo13) | ||
25360 | s[23] = t2shi11 ^ (~t2shi12 & t2shi13) | ||
25361 | s[32] = t2slo16 ^ (~t2slo17 & t2slo18) | ||
25362 | s[33] = t2shi16 ^ (~t2shi17 & t2shi18) | ||
25363 | s[42] = t2slo21 ^ (~t2slo22 & t2slo23) | ||
25364 | s[43] = t2shi21 ^ (~t2shi22 & t2shi23) | ||
25365 | s[4] = t2slo2 ^ (~t2slo3 & t2slo4) | ||
25366 | s[5] = t2shi2 ^ (~t2shi3 & t2shi4) | ||
25367 | s[14] = t2slo7 ^ (~t2slo8 & t2slo9) | ||
25368 | s[15] = t2shi7 ^ (~t2shi8 & t2shi9) | ||
25369 | s[24] = t2slo12 ^ (~t2slo13 & t2slo14) | ||
25370 | s[25] = t2shi12 ^ (~t2shi13 & t2shi14) | ||
25371 | s[34] = t2slo17 ^ (~t2slo18 & t2slo19) | ||
25372 | s[35] = t2shi17 ^ (~t2shi18 & t2shi19) | ||
25373 | s[44] = t2slo22 ^ (~t2slo23 & t2slo24) | ||
25374 | s[45] = t2shi22 ^ (~t2shi23 & t2shi24) | ||
25375 | s[6] = t2slo3 ^ (~t2slo4 & t2slo0) | ||
25376 | s[7] = t2shi3 ^ (~t2shi4 & t2shi0) | ||
25377 | s[16] = t2slo8 ^ (~t2slo9 & t2slo5) | ||
25378 | s[17] = t2shi8 ^ (~t2shi9 & t2shi5) | ||
25379 | s[26] = t2slo13 ^ (~t2slo14 & t2slo10) | ||
25380 | s[27] = t2shi13 ^ (~t2shi14 & t2shi10) | ||
25381 | s[36] = t2slo18 ^ (~t2slo19 & t2slo15) | ||
25382 | s[37] = t2shi18 ^ (~t2shi19 & t2shi15) | ||
25383 | s[46] = t2slo23 ^ (~t2slo24 & t2slo20) | ||
25384 | s[47] = t2shi23 ^ (~t2shi24 & t2shi20) | ||
25385 | s[8] = t2slo4 ^ (~t2slo0 & t2slo1) | ||
25386 | s[9] = t2shi4 ^ (~t2shi0 & t2shi1) | ||
25387 | s[18] = t2slo9 ^ (~t2slo5 & t2slo6) | ||
25388 | s[19] = t2shi9 ^ (~t2shi5 & t2shi6) | ||
25389 | s[28] = t2slo14 ^ (~t2slo10 & t2slo11) | ||
25390 | s[29] = t2shi14 ^ (~t2shi10 & t2shi11) | ||
25391 | s[38] = t2slo19 ^ (~t2slo15 & t2slo16) | ||
25392 | s[39] = t2shi19 ^ (~t2shi15 & t2shi16) | ||
25393 | s[48] = t2slo24 ^ (~t2slo20 & t2slo21) | ||
25394 | s[49] = t2shi24 ^ (~t2shi20 & t2shi21) | ||
25395 | |||
25396 | // iota | ||
25397 | s[0] ^= P1600_ROUND_CONSTANTS[round * 2] | ||
25398 | s[1] ^= P1600_ROUND_CONSTANTS[round * 2 + 1] | ||
25399 | } | ||
25400 | } | ||
25401 | |||
25402 | },{}],172:[function(require,module,exports){ | ||
25403 | 'use strict' | ||
25404 | var Buffer = require('safe-buffer').Buffer | ||
25405 | var keccakState = require('./keccak-state-unroll') | ||
25406 | |||
25407 | function Keccak () { | ||
25408 | // much faster than `new Array(50)` | ||
25409 | this.state = [ | ||
25410 | 0, 0, 0, 0, 0, | ||
25411 | 0, 0, 0, 0, 0, | ||
25412 | 0, 0, 0, 0, 0, | ||
25413 | 0, 0, 0, 0, 0, | ||
25414 | 0, 0, 0, 0, 0 | ||
25415 | ] | ||
25416 | |||
25417 | this.blockSize = null | ||
25418 | this.count = 0 | ||
25419 | this.squeezing = false | ||
25420 | } | ||
25421 | |||
25422 | Keccak.prototype.initialize = function (rate, capacity) { | ||
25423 | for (var i = 0; i < 50; ++i) this.state[i] = 0 | ||
25424 | this.blockSize = rate / 8 | ||
25425 | this.count = 0 | ||
25426 | this.squeezing = false | ||
25427 | } | ||
25428 | |||
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)) | ||
25432 | this.count += 1 | ||
25433 | if (this.count === this.blockSize) { | ||
25434 | keccakState.p1600(this.state) | ||
25435 | this.count = 0 | ||
25436 | } | ||
25437 | } | ||
25438 | } | ||
25439 | |||
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) | ||
25445 | this.count = 0 | ||
25446 | this.squeezing = true | ||
25447 | } | ||
25448 | |||
25449 | Keccak.prototype.squeeze = function (length) { | ||
25450 | if (!this.squeezing) this.absorbLastFewBits(0x01) | ||
25451 | |||
25452 | var output = Buffer.alloc(length) | ||
25453 | for (var i = 0; i < length; ++i) { | ||
25454 | output[i] = (this.state[~~(this.count / 4)] >>> (8 * (this.count % 4))) & 0xff | ||
25455 | this.count += 1 | ||
25456 | if (this.count === this.blockSize) { | ||
25457 | keccakState.p1600(this.state) | ||
25458 | this.count = 0 | ||
25459 | } | ||
25460 | } | ||
25461 | |||
25462 | return output | ||
25463 | } | ||
25464 | |||
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 | ||
25470 | } | ||
25471 | |||
25472 | module.exports = Keccak | ||
25473 | |||
25474 | },{"./keccak-state-unroll":171,"safe-buffer":247}],173:[function(require,module,exports){ | ||
25475 | (function (Buffer){ | ||
25476 | 'use strict' | ||
25477 | var inherits = require('inherits') | ||
25478 | var HashBase = require('hash-base') | ||
25479 | |||
25480 | var ARRAY16 = new Array(16) | ||
25481 | |||
25482 | function MD5 () { | ||
25483 | HashBase.call(this, 64) | ||
25484 | |||
25485 | // state | ||
25486 | this._a = 0x67452301 | ||
25487 | this._b = 0xefcdab89 | ||
25488 | this._c = 0x98badcfe | ||
25489 | this._d = 0x10325476 | ||
25490 | } | ||
25491 | |||
25492 | inherits(MD5, HashBase) | ||
25493 | |||
25494 | MD5.prototype._update = function () { | ||
25495 | var M = ARRAY16 | ||
25496 | for (var i = 0; i < 16; ++i) M[i] = this._block.readInt32LE(i * 4) | ||
25497 | |||
25498 | var a = this._a | ||
25499 | var b = this._b | ||
25500 | var c = this._c | ||
25501 | var d = this._d | ||
25502 | |||
25503 | a = fnF(a, b, c, d, M[0], 0xd76aa478, 7) | ||
25504 | d = fnF(d, a, b, c, M[1], 0xe8c7b756, 12) | ||
25505 | c = fnF(c, d, a, b, M[2], 0x242070db, 17) | ||
25506 | b = fnF(b, c, d, a, M[3], 0xc1bdceee, 22) | ||
25507 | a = fnF(a, b, c, d, M[4], 0xf57c0faf, 7) | ||
25508 | d = fnF(d, a, b, c, M[5], 0x4787c62a, 12) | ||
25509 | c = fnF(c, d, a, b, M[6], 0xa8304613, 17) | ||
25510 | b = fnF(b, c, d, a, M[7], 0xfd469501, 22) | ||
25511 | a = fnF(a, b, c, d, M[8], 0x698098d8, 7) | ||
25512 | d = fnF(d, a, b, c, M[9], 0x8b44f7af, 12) | ||
25513 | c = fnF(c, d, a, b, M[10], 0xffff5bb1, 17) | ||
25514 | b = fnF(b, c, d, a, M[11], 0x895cd7be, 22) | ||
25515 | a = fnF(a, b, c, d, M[12], 0x6b901122, 7) | ||
25516 | d = fnF(d, a, b, c, M[13], 0xfd987193, 12) | ||
25517 | c = fnF(c, d, a, b, M[14], 0xa679438e, 17) | ||
25518 | b = fnF(b, c, d, a, M[15], 0x49b40821, 22) | ||
25519 | |||
25520 | a = fnG(a, b, c, d, M[1], 0xf61e2562, 5) | ||
25521 | d = fnG(d, a, b, c, M[6], 0xc040b340, 9) | ||
25522 | c = fnG(c, d, a, b, M[11], 0x265e5a51, 14) | ||
25523 | b = fnG(b, c, d, a, M[0], 0xe9b6c7aa, 20) | ||
25524 | a = fnG(a, b, c, d, M[5], 0xd62f105d, 5) | ||
25525 | d = fnG(d, a, b, c, M[10], 0x02441453, 9) | ||
25526 | c = fnG(c, d, a, b, M[15], 0xd8a1e681, 14) | ||
25527 | b = fnG(b, c, d, a, M[4], 0xe7d3fbc8, 20) | ||
25528 | a = fnG(a, b, c, d, M[9], 0x21e1cde6, 5) | ||
25529 | d = fnG(d, a, b, c, M[14], 0xc33707d6, 9) | ||
25530 | c = fnG(c, d, a, b, M[3], 0xf4d50d87, 14) | ||
25531 | b = fnG(b, c, d, a, M[8], 0x455a14ed, 20) | ||
25532 | a = fnG(a, b, c, d, M[13], 0xa9e3e905, 5) | ||
25533 | d = fnG(d, a, b, c, M[2], 0xfcefa3f8, 9) | ||
25534 | c = fnG(c, d, a, b, M[7], 0x676f02d9, 14) | ||
25535 | b = fnG(b, c, d, a, M[12], 0x8d2a4c8a, 20) | ||
25536 | |||
25537 | a = fnH(a, b, c, d, M[5], 0xfffa3942, 4) | ||
25538 | d = fnH(d, a, b, c, M[8], 0x8771f681, 11) | ||
25539 | c = fnH(c, d, a, b, M[11], 0x6d9d6122, 16) | ||
25540 | b = fnH(b, c, d, a, M[14], 0xfde5380c, 23) | ||
25541 | a = fnH(a, b, c, d, M[1], 0xa4beea44, 4) | ||
25542 | d = fnH(d, a, b, c, M[4], 0x4bdecfa9, 11) | ||
25543 | c = fnH(c, d, a, b, M[7], 0xf6bb4b60, 16) | ||
25544 | b = fnH(b, c, d, a, M[10], 0xbebfbc70, 23) | ||
25545 | a = fnH(a, b, c, d, M[13], 0x289b7ec6, 4) | ||
25546 | d = fnH(d, a, b, c, M[0], 0xeaa127fa, 11) | ||
25547 | c = fnH(c, d, a, b, M[3], 0xd4ef3085, 16) | ||
25548 | b = fnH(b, c, d, a, M[6], 0x04881d05, 23) | ||
25549 | a = fnH(a, b, c, d, M[9], 0xd9d4d039, 4) | ||
25550 | d = fnH(d, a, b, c, M[12], 0xe6db99e5, 11) | ||
25551 | c = fnH(c, d, a, b, M[15], 0x1fa27cf8, 16) | ||
25552 | b = fnH(b, c, d, a, M[2], 0xc4ac5665, 23) | ||
25553 | |||
25554 | a = fnI(a, b, c, d, M[0], 0xf4292244, 6) | ||
25555 | d = fnI(d, a, b, c, M[7], 0x432aff97, 10) | ||
25556 | c = fnI(c, d, a, b, M[14], 0xab9423a7, 15) | ||
25557 | b = fnI(b, c, d, a, M[5], 0xfc93a039, 21) | ||
25558 | a = fnI(a, b, c, d, M[12], 0x655b59c3, 6) | ||
25559 | d = fnI(d, a, b, c, M[3], 0x8f0ccc92, 10) | ||
25560 | c = fnI(c, d, a, b, M[10], 0xffeff47d, 15) | ||
25561 | b = fnI(b, c, d, a, M[1], 0x85845dd1, 21) | ||
25562 | a = fnI(a, b, c, d, M[8], 0x6fa87e4f, 6) | ||
25563 | d = fnI(d, a, b, c, M[15], 0xfe2ce6e0, 10) | ||
25564 | c = fnI(c, d, a, b, M[6], 0xa3014314, 15) | ||
25565 | b = fnI(b, c, d, a, M[13], 0x4e0811a1, 21) | ||
25566 | a = fnI(a, b, c, d, M[4], 0xf7537e82, 6) | ||
25567 | d = fnI(d, a, b, c, M[11], 0xbd3af235, 10) | ||
25568 | c = fnI(c, d, a, b, M[2], 0x2ad7d2bb, 15) | ||
25569 | b = fnI(b, c, d, a, M[9], 0xeb86d391, 21) | ||
25570 | |||
25571 | this._a = (this._a + a) | 0 | ||
25572 | this._b = (this._b + b) | 0 | ||
25573 | this._c = (this._c + c) | 0 | ||
25574 | this._d = (this._d + d) | 0 | ||
25575 | } | ||
25576 | |||
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) | ||
25582 | this._update() | ||
25583 | this._blockOffset = 0 | ||
25584 | } | ||
25585 | |||
25586 | this._block.fill(0, this._blockOffset, 56) | ||
25587 | this._block.writeUInt32LE(this._length[0], 56) | ||
25588 | this._block.writeUInt32LE(this._length[1], 60) | ||
25589 | this._update() | ||
25590 | |||
25591 | // produce result | ||
25592 | var buffer = new Buffer(16) | ||
25593 | buffer.writeInt32LE(this._a, 0) | ||
25594 | buffer.writeInt32LE(this._b, 4) | ||
25595 | buffer.writeInt32LE(this._c, 8) | ||
25596 | buffer.writeInt32LE(this._d, 12) | ||
25597 | return buffer | ||
25598 | } | ||
25599 | |||
25600 | function rotl (x, n) { | ||
25601 | return (x << n) | (x >>> (32 - n)) | ||
25602 | } | ||
25603 | |||
25604 | function fnF (a, b, c, d, m, k, s) { | ||
25605 | return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + b) | 0 | ||
25606 | } | ||
25607 | |||
25608 | function fnG (a, b, c, d, m, k, s) { | ||
25609 | return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + b) | 0 | ||
25610 | } | ||
25611 | |||
25612 | function fnH (a, b, c, d, m, k, s) { | ||
25613 | return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + b) | 0 | ||
25614 | } | ||
25615 | |||
25616 | function fnI (a, b, c, d, m, k, s) { | ||
25617 | return (rotl((a + ((c ^ (b | (~d)))) + m + k) | 0, s) + b) | 0 | ||
25618 | } | ||
25619 | |||
25620 | module.exports = MD5 | ||
25621 | |||
25622 | }).call(this,require("buffer").Buffer) | ||
25623 | },{"buffer":107,"hash-base":174,"inherits":163}],174:[function(require,module,exports){ | ||
25624 | 'use strict' | ||
25625 | var Buffer = require('safe-buffer').Buffer | ||
25626 | var Transform = require('stream').Transform | ||
25627 | var inherits = require('inherits') | ||
25628 | |||
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') | ||
25632 | } | ||
25633 | } | ||
25634 | |||
25635 | function HashBase (blockSize) { | ||
25636 | Transform.call(this) | ||
25637 | |||
25638 | this._block = Buffer.allocUnsafe(blockSize) | ||
25639 | this._blockSize = blockSize | ||
25640 | this._blockOffset = 0 | ||
25641 | this._length = [0, 0, 0, 0] | ||
25642 | |||
25643 | this._finalized = false | ||
25644 | } | ||
25645 | |||
25646 | inherits(HashBase, Transform) | ||
25647 | |||
25648 | HashBase.prototype._transform = function (chunk, encoding, callback) { | ||
25649 | var error = null | ||
25650 | try { | ||
25651 | this.update(chunk, encoding) | ||
25652 | } catch (err) { | ||
25653 | error = err | ||
25654 | } | ||
25655 | |||
25656 | callback(error) | ||
25657 | } | ||
25658 | |||
25659 | HashBase.prototype._flush = function (callback) { | ||
25660 | var error = null | ||
25661 | try { | ||
25662 | this.push(this.digest()) | ||
25663 | } catch (err) { | ||
25664 | error = err | ||
25665 | } | ||
25666 | |||
25667 | callback(error) | ||
25668 | } | ||
25669 | |||
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) | ||
25674 | |||
25675 | // consume data | ||
25676 | var block = this._block | ||
25677 | var offset = 0 | ||
25678 | while (this._blockOffset + data.length - offset >= this._blockSize) { | ||
25679 | for (var i = this._blockOffset; i < this._blockSize;) block[i++] = data[offset++] | ||
25680 | this._update() | ||
25681 | this._blockOffset = 0 | ||
25682 | } | ||
25683 | while (offset < data.length) block[this._blockOffset++] = data[offset++] | ||
25684 | |||
25685 | // update length | ||
25686 | for (var j = 0, carry = data.length * 8; carry > 0; ++j) { | ||
25687 | this._length[j] += carry | ||
25688 | carry = (this._length[j] / 0x0100000000) | 0 | ||
25689 | if (carry > 0) this._length[j] -= 0x0100000000 * carry | ||
25690 | } | ||
25691 | |||
25692 | return this | ||
25693 | } | ||
25694 | |||
25695 | HashBase.prototype._update = function () { | ||
25696 | throw new Error('_update is not implemented') | ||
25697 | } | ||
25698 | |||
25699 | HashBase.prototype.digest = function (encoding) { | ||
25700 | if (this._finalized) throw new Error('Digest already called') | ||
25701 | this._finalized = true | ||
25702 | |||
25703 | var digest = this._digest() | ||
25704 | if (encoding !== undefined) digest = digest.toString(encoding) | ||
25705 | |||
25706 | // reset state | ||
25707 | this._block.fill(0) | ||
25708 | this._blockOffset = 0 | ||
25709 | for (var i = 0; i < 4; ++i) this._length[i] = 0 | ||
25710 | |||
25711 | return digest | ||
25712 | } | ||
25713 | |||
25714 | HashBase.prototype._digest = function () { | ||
25715 | throw new Error('_digest is not implemented') | ||
25716 | } | ||
25717 | |||
25718 | module.exports = HashBase | ||
25719 | |||
25720 | },{"inherits":163,"safe-buffer":247,"stream":263}],175:[function(require,module,exports){ | ||
25721 | var bn = require('bn.js'); | ||
25722 | var brorand = require('brorand'); | ||
25723 | |||
25724 | function MillerRabin(rand) { | ||
25725 | this.rand = rand || new brorand.Rand(); | ||
25726 | } | ||
25727 | module.exports = MillerRabin; | ||
25728 | |||
25729 | MillerRabin.create = function create(rand) { | ||
25730 | return new MillerRabin(rand); | ||
25731 | }; | ||
25732 | |||
25733 | MillerRabin.prototype._randbelow = function _randbelow(n) { | ||
25734 | var len = n.bitLength(); | ||
25735 | var min_bytes = Math.ceil(len / 8); | ||
25736 | |||
25737 | // Generage random bytes until a number less than n is found. | ||
25738 | // This ensures that 0..n-1 have an equal probability of being selected. | ||
25739 | do | ||
25740 | var a = new bn(this.rand.generate(min_bytes)); | ||
25741 | while (a.cmp(n) >= 0); | ||
25742 | |||
25743 | return a; | ||
25744 | }; | ||
25745 | |||
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)); | ||
25750 | }; | ||
25751 | |||
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); | ||
25756 | |||
25757 | if (!k) | ||
25758 | k = Math.max(1, (len / 48) | 0); | ||
25759 | |||
25760 | // Find d and s, (n - 1) = (2 ^ s) * d; | ||
25761 | var n1 = n.subn(1); | ||
25762 | for (var s = 0; !n1.testn(s); s++) {} | ||
25763 | var d = n.shrn(s); | ||
25764 | |||
25765 | var rn1 = n1.toRed(red); | ||
25766 | |||
25767 | var prime = true; | ||
25768 | for (; k > 0; k--) { | ||
25769 | var a = this._randrange(new bn(2), n1); | ||
25770 | if (cb) | ||
25771 | cb(a); | ||
25772 | |||
25773 | var x = a.toRed(red).redPow(d); | ||
25774 | if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) | ||
25775 | continue; | ||
25776 | |||
25777 | for (var i = 1; i < s; i++) { | ||
25778 | x = x.redSqr(); | ||
25779 | |||
25780 | if (x.cmp(rone) === 0) | ||
25781 | return false; | ||
25782 | if (x.cmp(rn1) === 0) | ||
25783 | break; | ||
25784 | } | ||
25785 | |||
25786 | if (i === s) | ||
25787 | return false; | ||
25788 | } | ||
25789 | |||
25790 | return prime; | ||
25791 | }; | ||
25792 | |||
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); | ||
25797 | |||
25798 | if (!k) | ||
25799 | k = Math.max(1, (len / 48) | 0); | ||
25800 | |||
25801 | // Find d and s, (n - 1) = (2 ^ s) * d; | ||
25802 | var n1 = n.subn(1); | ||
25803 | for (var s = 0; !n1.testn(s); s++) {} | ||
25804 | var d = n.shrn(s); | ||
25805 | |||
25806 | var rn1 = n1.toRed(red); | ||
25807 | |||
25808 | for (; k > 0; k--) { | ||
25809 | var a = this._randrange(new bn(2), n1); | ||
25810 | |||
25811 | var g = n.gcd(a); | ||
25812 | if (g.cmpn(1) !== 0) | ||
25813 | return g; | ||
25814 | |||
25815 | var x = a.toRed(red).redPow(d); | ||
25816 | if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) | ||
25817 | continue; | ||
25818 | |||
25819 | for (var i = 1; i < s; i++) { | ||
25820 | x = x.redSqr(); | ||
25821 | |||
25822 | if (x.cmp(rone) === 0) | ||
25823 | return x.fromRed().subn(1).gcd(n); | ||
25824 | if (x.cmp(rn1) === 0) | ||
25825 | break; | ||
25826 | } | ||
25827 | |||
25828 | if (i === s) { | ||
25829 | x = x.redSqr(); | ||
25830 | return x.fromRed().subn(1).gcd(n); | ||
25831 | } | ||
25832 | } | ||
25833 | |||
25834 | return false; | ||
25835 | }; | ||
25836 | |||
25837 | },{"bn.js":75,"brorand":76}],176:[function(require,module,exports){ | ||
25838 | module.exports = assert; | ||
25839 | |||
25840 | function assert(val, msg) { | ||
25841 | if (!val) | ||
25842 | throw new Error(msg || 'Assertion failed'); | ||
25843 | } | ||
25844 | |||
25845 | assert.equal = function assertEqual(l, r, msg) { | ||
25846 | if (l != r) | ||
25847 | throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); | ||
25848 | }; | ||
25849 | |||
25850 | },{}],177:[function(require,module,exports){ | ||
25851 | 'use strict'; | ||
25852 | |||
25853 | var utils = exports; | ||
25854 | |||
25855 | function toArray(msg, enc) { | ||
25856 | if (Array.isArray(msg)) | ||
25857 | return msg.slice(); | ||
25858 | if (!msg) | ||
25859 | return []; | ||
25860 | var res = []; | ||
25861 | if (typeof msg !== 'string') { | ||
25862 | for (var i = 0; i < msg.length; i++) | ||
25863 | res[i] = msg[i] | 0; | ||
25864 | return res; | ||
25865 | } | ||
25866 | if (enc === 'hex') { | ||
25867 | msg = msg.replace(/[^a-z0-9]+/ig, ''); | ||
25868 | if (msg.length % 2 !== 0) | ||
25869 | msg = '0' + msg; | ||
25870 | for (var i = 0; i < msg.length; i += 2) | ||
25871 | res.push(parseInt(msg[i] + msg[i + 1], 16)); | ||
25872 | } else { | ||
25873 | for (var i = 0; i < msg.length; i++) { | ||
25874 | var c = msg.charCodeAt(i); | ||
25875 | var hi = c >> 8; | ||
25876 | var lo = c & 0xff; | ||
25877 | if (hi) | ||
25878 | res.push(hi, lo); | ||
25879 | else | ||
25880 | res.push(lo); | ||
25881 | } | ||
25882 | } | ||
25883 | return res; | ||
25884 | } | ||
25885 | utils.toArray = toArray; | ||
25886 | |||
25887 | function zero2(word) { | ||
25888 | if (word.length === 1) | ||
25889 | return '0' + word; | ||
25890 | else | ||
25891 | return word; | ||
25892 | } | ||
25893 | utils.zero2 = zero2; | ||
25894 | |||
25895 | function toHex(msg) { | ||
25896 | var res = ''; | ||
25897 | for (var i = 0; i < msg.length; i++) | ||
25898 | res += zero2(msg[i].toString(16)); | ||
25899 | return res; | ||
25900 | } | ||
25901 | utils.toHex = toHex; | ||
25902 | |||
25903 | utils.encode = function encode(arr, enc) { | ||
25904 | if (enc === 'hex') | ||
25905 | return toHex(arr); | ||
25906 | else | ||
25907 | return arr; | ||
25908 | }; | ||
25909 | |||
25910 | },{}],178:[function(require,module,exports){ | ||
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" | ||
25923 | } | ||
25924 | },{}],179:[function(require,module,exports){ | ||
25925 | // from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js | ||
25926 | // Fedor, you are amazing. | ||
25927 | 'use strict' | ||
25928 | |||
25929 | var asn1 = require('asn1.js') | ||
25930 | |||
25931 | exports.certificate = require('./certificate') | ||
25932 | |||
25933 | var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { | ||
25934 | this.seq().obj( | ||
25935 | this.key('version').int(), | ||
25936 | this.key('modulus').int(), | ||
25937 | this.key('publicExponent').int(), | ||
25938 | this.key('privateExponent').int(), | ||
25939 | this.key('prime1').int(), | ||
25940 | this.key('prime2').int(), | ||
25941 | this.key('exponent1').int(), | ||
25942 | this.key('exponent2').int(), | ||
25943 | this.key('coefficient').int() | ||
25944 | ) | ||
25945 | }) | ||
25946 | exports.RSAPrivateKey = RSAPrivateKey | ||
25947 | |||
25948 | var RSAPublicKey = asn1.define('RSAPublicKey', function () { | ||
25949 | this.seq().obj( | ||
25950 | this.key('modulus').int(), | ||
25951 | this.key('publicExponent').int() | ||
25952 | ) | ||
25953 | }) | ||
25954 | exports.RSAPublicKey = RSAPublicKey | ||
25955 | |||
25956 | var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { | ||
25957 | this.seq().obj( | ||
25958 | this.key('algorithm').use(AlgorithmIdentifier), | ||
25959 | this.key('subjectPublicKey').bitstr() | ||
25960 | ) | ||
25961 | }) | ||
25962 | exports.PublicKey = PublicKey | ||
25963 | |||
25964 | var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { | ||
25965 | this.seq().obj( | ||
25966 | this.key('algorithm').objid(), | ||
25967 | this.key('none').null_().optional(), | ||
25968 | this.key('curve').objid().optional(), | ||
25969 | this.key('params').seq().obj( | ||
25970 | this.key('p').int(), | ||
25971 | this.key('q').int(), | ||
25972 | this.key('g').int() | ||
25973 | ).optional() | ||
25974 | ) | ||
25975 | }) | ||
25976 | |||
25977 | var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { | ||
25978 | this.seq().obj( | ||
25979 | this.key('version').int(), | ||
25980 | this.key('algorithm').use(AlgorithmIdentifier), | ||
25981 | this.key('subjectPrivateKey').octstr() | ||
25982 | ) | ||
25983 | }) | ||
25984 | exports.PrivateKey = PrivateKeyInfo | ||
25985 | var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { | ||
25986 | this.seq().obj( | ||
25987 | this.key('algorithm').seq().obj( | ||
25988 | this.key('id').objid(), | ||
25989 | this.key('decrypt').seq().obj( | ||
25990 | this.key('kde').seq().obj( | ||
25991 | this.key('id').objid(), | ||
25992 | this.key('kdeparams').seq().obj( | ||
25993 | this.key('salt').octstr(), | ||
25994 | this.key('iters').int() | ||
25995 | ) | ||
25996 | ), | ||
25997 | this.key('cipher').seq().obj( | ||
25998 | this.key('algo').objid(), | ||
25999 | this.key('iv').octstr() | ||
26000 | ) | ||
26001 | ) | ||
26002 | ), | ||
26003 | this.key('subjectPrivateKey').octstr() | ||
26004 | ) | ||
26005 | }) | ||
26006 | |||
26007 | exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo | ||
26008 | |||
26009 | var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { | ||
26010 | this.seq().obj( | ||
26011 | this.key('version').int(), | ||
26012 | this.key('p').int(), | ||
26013 | this.key('q').int(), | ||
26014 | this.key('g').int(), | ||
26015 | this.key('pub_key').int(), | ||
26016 | this.key('priv_key').int() | ||
26017 | ) | ||
26018 | }) | ||
26019 | exports.DSAPrivateKey = DSAPrivateKey | ||
26020 | |||
26021 | exports.DSAparam = asn1.define('DSAparam', function () { | ||
26022 | this.int() | ||
26023 | }) | ||
26024 | |||
26025 | var ECPrivateKey = asn1.define('ECPrivateKey', function () { | ||
26026 | this.seq().obj( | ||
26027 | this.key('version').int(), | ||
26028 | this.key('privateKey').octstr(), | ||
26029 | this.key('parameters').optional().explicit(0).use(ECParameters), | ||
26030 | this.key('publicKey').optional().explicit(1).bitstr() | ||
26031 | ) | ||
26032 | }) | ||
26033 | exports.ECPrivateKey = ECPrivateKey | ||
26034 | |||
26035 | var ECParameters = asn1.define('ECParameters', function () { | ||
26036 | this.choice({ | ||
26037 | namedCurve: this.objid() | ||
26038 | }) | ||
26039 | }) | ||
26040 | |||
26041 | exports.signature = asn1.define('signature', function () { | ||
26042 | this.seq().obj( | ||
26043 | this.key('r').int(), | ||
26044 | this.key('s').int() | ||
26045 | ) | ||
26046 | }) | ||
26047 | |||
26048 | },{"./certificate":180,"asn1.js":32}],180:[function(require,module,exports){ | ||
26049 | // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js | ||
26050 | // thanks to @Rantanen | ||
26051 | |||
26052 | 'use strict' | ||
26053 | |||
26054 | var asn = require('asn1.js') | ||
26055 | |||
26056 | var Time = asn.define('Time', function () { | ||
26057 | this.choice({ | ||
26058 | utcTime: this.utctime(), | ||
26059 | generalTime: this.gentime() | ||
26060 | }) | ||
26061 | }) | ||
26062 | |||
26063 | var AttributeTypeValue = asn.define('AttributeTypeValue', function () { | ||
26064 | this.seq().obj( | ||
26065 | this.key('type').objid(), | ||
26066 | this.key('value').any() | ||
26067 | ) | ||
26068 | }) | ||
26069 | |||
26070 | var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { | ||
26071 | this.seq().obj( | ||
26072 | this.key('algorithm').objid(), | ||
26073 | this.key('parameters').optional() | ||
26074 | ) | ||
26075 | }) | ||
26076 | |||
26077 | var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { | ||
26078 | this.seq().obj( | ||
26079 | this.key('algorithm').use(AlgorithmIdentifier), | ||
26080 | this.key('subjectPublicKey').bitstr() | ||
26081 | ) | ||
26082 | }) | ||
26083 | |||
26084 | var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { | ||
26085 | this.setof(AttributeTypeValue) | ||
26086 | }) | ||
26087 | |||
26088 | var RDNSequence = asn.define('RDNSequence', function () { | ||
26089 | this.seqof(RelativeDistinguishedName) | ||
26090 | }) | ||
26091 | |||
26092 | var Name = asn.define('Name', function () { | ||
26093 | this.choice({ | ||
26094 | rdnSequence: this.use(RDNSequence) | ||
26095 | }) | ||
26096 | }) | ||
26097 | |||
26098 | var Validity = asn.define('Validity', function () { | ||
26099 | this.seq().obj( | ||
26100 | this.key('notBefore').use(Time), | ||
26101 | this.key('notAfter').use(Time) | ||
26102 | ) | ||
26103 | }) | ||
26104 | |||
26105 | var Extension = asn.define('Extension', function () { | ||
26106 | this.seq().obj( | ||
26107 | this.key('extnID').objid(), | ||
26108 | this.key('critical').bool().def(false), | ||
26109 | this.key('extnValue').octstr() | ||
26110 | ) | ||
26111 | }) | ||
26112 | |||
26113 | var TBSCertificate = asn.define('TBSCertificate', function () { | ||
26114 | this.seq().obj( | ||
26115 | this.key('version').explicit(0).int(), | ||
26116 | this.key('serialNumber').int(), | ||
26117 | this.key('signature').use(AlgorithmIdentifier), | ||
26118 | this.key('issuer').use(Name), | ||
26119 | this.key('validity').use(Validity), | ||
26120 | this.key('subject').use(Name), | ||
26121 | this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), | ||
26122 | this.key('issuerUniqueID').implicit(1).bitstr().optional(), | ||
26123 | this.key('subjectUniqueID').implicit(2).bitstr().optional(), | ||
26124 | this.key('extensions').explicit(3).seqof(Extension).optional() | ||
26125 | ) | ||
26126 | }) | ||
26127 | |||
26128 | var X509Certificate = asn.define('X509Certificate', function () { | ||
26129 | this.seq().obj( | ||
26130 | this.key('tbsCertificate').use(TBSCertificate), | ||
26131 | this.key('signatureAlgorithm').use(AlgorithmIdentifier), | ||
26132 | this.key('signatureValue').bitstr() | ||
26133 | ) | ||
26134 | }) | ||
26135 | |||
26136 | module.exports = X509Certificate | ||
26137 | |||
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) | ||
26149 | var decrypted | ||
26150 | if (!match) { | ||
26151 | var match2 = key.match(fullRegex) | ||
26152 | decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64') | ||
26153 | } else { | ||
26154 | var suite = 'aes' + match[1] | ||
26155 | var iv = new Buffer(match[2], 'hex') | ||
26156 | var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64') | ||
26157 | var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key | ||
26158 | var out = [] | ||
26159 | var cipher = ciphers.createDecipheriv(suite, cipherKey, iv) | ||
26160 | out.push(cipher.update(cipherText)) | ||
26161 | out.push(cipher.final()) | ||
26162 | decrypted = Buffer.concat(out) | ||
26163 | } | ||
26164 | var tag = key.match(startRegex)[1] | ||
26165 | return { | ||
26166 | tag: tag, | ||
26167 | data: decrypted | ||
26168 | } | ||
26169 | } | ||
26170 | |||
26171 | }).call(this,require("buffer").Buffer) | ||
26172 | },{"browserify-aes":80,"buffer":107,"evp_bytestokey":144}],182:[function(require,module,exports){ | ||
26173 | (function (Buffer){ | ||
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 | ||
26180 | |||
26181 | function parseKeys (buffer) { | ||
26182 | var password | ||
26183 | if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { | ||
26184 | password = buffer.passphrase | ||
26185 | buffer = buffer.key | ||
26186 | } | ||
26187 | if (typeof buffer === 'string') { | ||
26188 | buffer = new Buffer(buffer) | ||
26189 | } | ||
26190 | |||
26191 | var stripped = fixProc(buffer, password) | ||
26192 | |||
26193 | var type = stripped.tag | ||
26194 | var data = stripped.data | ||
26195 | var subtype, ndata | ||
26196 | switch (type) { | ||
26197 | case 'CERTIFICATE': | ||
26198 | ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo | ||
26199 | // falls through | ||
26200 | case 'PUBLIC KEY': | ||
26201 | if (!ndata) { | ||
26202 | ndata = asn1.PublicKey.decode(data, 'der') | ||
26203 | } | ||
26204 | subtype = ndata.algorithm.algorithm.join('.') | ||
26205 | switch (subtype) { | ||
26206 | case '1.2.840.113549.1.1.1': | ||
26207 | return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der') | ||
26208 | case '1.2.840.10045.2.1': | ||
26209 | ndata.subjectPrivateKey = ndata.subjectPublicKey | ||
26210 | return { | ||
26211 | type: 'ec', | ||
26212 | data: ndata | ||
26213 | } | ||
26214 | case '1.2.840.10040.4.1': | ||
26215 | ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der') | ||
26216 | return { | ||
26217 | type: 'dsa', | ||
26218 | data: ndata.algorithm.params | ||
26219 | } | ||
26220 | default: throw new Error('unknown key id ' + subtype) | ||
26221 | } | ||
26222 | throw new Error('unknown key type ' + type) | ||
26223 | case 'ENCRYPTED PRIVATE KEY': | ||
26224 | data = asn1.EncryptedPrivateKey.decode(data, 'der') | ||
26225 | data = decrypt(data, password) | ||
26226 | // falls through | ||
26227 | case 'PRIVATE KEY': | ||
26228 | ndata = asn1.PrivateKey.decode(data, 'der') | ||
26229 | subtype = ndata.algorithm.algorithm.join('.') | ||
26230 | switch (subtype) { | ||
26231 | case '1.2.840.113549.1.1.1': | ||
26232 | return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der') | ||
26233 | case '1.2.840.10045.2.1': | ||
26234 | return { | ||
26235 | curve: ndata.algorithm.curve, | ||
26236 | privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey | ||
26237 | } | ||
26238 | case '1.2.840.10040.4.1': | ||
26239 | ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der') | ||
26240 | return { | ||
26241 | type: 'dsa', | ||
26242 | params: ndata.algorithm.params | ||
26243 | } | ||
26244 | default: throw new Error('unknown key id ' + subtype) | ||
26245 | } | ||
26246 | throw new Error('unknown key type ' + type) | ||
26247 | case 'RSA PUBLIC KEY': | ||
26248 | return asn1.RSAPublicKey.decode(data, 'der') | ||
26249 | case 'RSA PRIVATE KEY': | ||
26250 | return asn1.RSAPrivateKey.decode(data, 'der') | ||
26251 | case 'DSA PRIVATE KEY': | ||
26252 | return { | ||
26253 | type: 'dsa', | ||
26254 | params: asn1.DSAPrivateKey.decode(data, 'der') | ||
26255 | } | ||
26256 | case 'EC PRIVATE KEY': | ||
26257 | data = asn1.ECPrivateKey.decode(data, 'der') | ||
26258 | return { | ||
26259 | curve: data.parameters.value, | ||
26260 | privateKey: data.privateKey | ||
26261 | } | ||
26262 | default: throw new Error('unknown key type ' + type) | ||
26263 | } | ||
26264 | } | ||
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) | ||
26275 | var out = [] | ||
26276 | out.push(cipher.update(cipherText)) | ||
26277 | out.push(cipher.final()) | ||
26278 | return Buffer.concat(out) | ||
26279 | } | ||
26280 | |||
26281 | }).call(this,require("buffer").Buffer) | ||
26282 | },{"./aesid.json":178,"./asn1":179,"./fixProc":181,"browserify-aes":80,"buffer":107,"pbkdf2":184}],183:[function(require,module,exports){ | ||
26283 | (function (process){ | ||
26284 | // Copyright Joyent, Inc. and other Node contributors. | ||
26285 | // | ||
26286 | // Permission is hereby granted, free of charge, to any person obtaining a | ||
26287 | // copy of this software and associated documentation files (the | ||
26288 | // "Software"), to deal in the Software without restriction, including | ||
26289 | // without limitation the rights to use, copy, modify, merge, publish, | ||
26290 | // distribute, sublicense, and/or sell copies of the Software, and to permit | ||
26291 | // persons to whom the Software is furnished to do so, subject to the | ||
26292 | // following conditions: | ||
26293 | // | ||
26294 | // The above copyright notice and this permission notice shall be included | ||
26295 | // in all copies or substantial portions of the Software. | ||
26296 | // | ||
26297 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
26298 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
26299 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | ||
26300 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | ||
26301 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
26302 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
26303 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
26304 | |||
26305 | // resolves . and .. elements in a path array with directory names there | ||
26306 | // must be no slashes, empty elements, or device names (c:\) in the array | ||
26307 | // (so also no leading and trailing slashes - it does not distinguish | ||
26308 | // relative and absolute paths) | ||
26309 | function normalizeArray(parts, allowAboveRoot) { | ||
26310 | // if the path tries to go above the root, `up` ends up > 0 | ||
26311 | var up = 0; | ||
26312 | for (var i = parts.length - 1; i >= 0; i--) { | ||
26313 | var last = parts[i]; | ||
26314 | if (last === '.') { | ||
26315 | parts.splice(i, 1); | ||
26316 | } else if (last === '..') { | ||
26317 | parts.splice(i, 1); | ||
26318 | up++; | ||
26319 | } else if (up) { | ||
26320 | parts.splice(i, 1); | ||
26321 | up--; | ||
26322 | } | ||
26323 | } | ||
26324 | |||
26325 | // if the path is allowed to go above the root, restore leading ..s | ||
26326 | if (allowAboveRoot) { | ||
26327 | for (; up--; up) { | ||
26328 | parts.unshift('..'); | ||
26329 | } | ||
26330 | } | ||
26331 | |||
26332 | return parts; | ||
26333 | } | ||
26334 | |||
26335 | // Split a filename into [root, dir, basename, ext], unix version | ||
26336 | // 'root' is just a slash, or nothing. | ||
26337 | var splitPathRe = | ||
26338 | /^(\/?|)([\s\S]*?)((?:\.{1,2}|[^\/]+?|)(\.[^.\/]*|))(?:[\/]*)$/; | ||
26339 | var splitPath = function(filename) { | ||
26340 | return splitPathRe.exec(filename).slice(1); | ||
26341 | }; | ||
26342 | |||
26343 | // path.resolve([from ...], to) | ||
26344 | // posix version | ||
26345 | exports.resolve = function() { | ||
26346 | var resolvedPath = '', | ||
26347 | resolvedAbsolute = false; | ||
26348 | |||
26349 | for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { | ||
26350 | var path = (i >= 0) ? arguments[i] : process.cwd(); | ||
26351 | |||
26352 | // Skip empty and invalid entries | ||
26353 | if (typeof path !== 'string') { | ||
26354 | throw new TypeError('Arguments to path.resolve must be strings'); | ||
26355 | } else if (!path) { | ||
26356 | continue; | ||
26357 | } | ||
26358 | |||
26359 | resolvedPath = path + '/' + resolvedPath; | ||
26360 | resolvedAbsolute = path.charAt(0) === '/'; | ||
26361 | } | ||
26362 | |||
26363 | // At this point the path should be resolved to a full absolute path, but | ||
26364 | // handle relative paths to be safe (might happen when process.cwd() fails) | ||
26365 | |||
26366 | // Normalize the path | ||
26367 | resolvedPath = normalizeArray(filter(resolvedPath.split('/'), function(p) { | ||
26368 | return !!p; | ||
26369 | }), !resolvedAbsolute).join('/'); | ||
26370 | |||
26371 | return ((resolvedAbsolute ? '/' : '') + resolvedPath) || '.'; | ||
26372 | }; | ||
26373 | |||
26374 | // path.normalize(path) | ||
26375 | // posix version | ||
26376 | exports.normalize = function(path) { | ||
26377 | var isAbsolute = exports.isAbsolute(path), | ||
26378 | trailingSlash = substr(path, -1) === '/'; | ||
26379 | |||
26380 | // Normalize the path | ||
26381 | path = normalizeArray(filter(path.split('/'), function(p) { | ||
26382 | return !!p; | ||
26383 | }), !isAbsolute).join('/'); | ||
26384 | |||
26385 | if (!path && !isAbsolute) { | ||
26386 | path = '.'; | ||
26387 | } | ||
26388 | if (path && trailingSlash) { | ||
26389 | path += '/'; | ||
26390 | } | ||
26391 | |||
26392 | return (isAbsolute ? '/' : '') + path; | ||
26393 | }; | ||
26394 | |||
26395 | // posix version | ||
26396 | exports.isAbsolute = function(path) { | ||
26397 | return path.charAt(0) === '/'; | ||
26398 | }; | ||
26399 | |||
26400 | // posix version | ||
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'); | ||
26406 | } | ||
26407 | return p; | ||
26408 | }).join('/')); | ||
26409 | }; | ||
26410 | |||
26411 | |||
26412 | // path.relative(from, to) | ||
26413 | // posix version | ||
26414 | exports.relative = function(from, to) { | ||
26415 | from = exports.resolve(from).substr(1); | ||
26416 | to = exports.resolve(to).substr(1); | ||
26417 | |||
26418 | function trim(arr) { | ||
26419 | var start = 0; | ||
26420 | for (; start < arr.length; start++) { | ||
26421 | if (arr[start] !== '') break; | ||
26422 | } | ||
26423 | |||
26424 | var end = arr.length - 1; | ||
26425 | for (; end >= 0; end--) { | ||
26426 | if (arr[end] !== '') break; | ||
26427 | } | ||
26428 | |||
26429 | if (start > end) return []; | ||
26430 | return arr.slice(start, end - start + 1); | ||
26431 | } | ||
26432 | |||
26433 | var fromParts = trim(from.split('/')); | ||
26434 | var toParts = trim(to.split('/')); | ||
26435 | |||
26436 | var length = Math.min(fromParts.length, toParts.length); | ||
26437 | var samePartsLength = length; | ||
26438 | for (var i = 0; i < length; i++) { | ||
26439 | if (fromParts[i] !== toParts[i]) { | ||
26440 | samePartsLength = i; | ||
26441 | break; | ||
26442 | } | ||
26443 | } | ||
26444 | |||
26445 | var outputParts = []; | ||
26446 | for (var i = samePartsLength; i < fromParts.length; i++) { | ||
26447 | outputParts.push('..'); | ||
26448 | } | ||
26449 | |||
26450 | outputParts = outputParts.concat(toParts.slice(samePartsLength)); | ||
26451 | |||
26452 | return outputParts.join('/'); | ||
26453 | }; | ||
26454 | |||
26455 | exports.sep = '/'; | ||
26456 | exports.delimiter = ':'; | ||
26457 | |||
26458 | exports.dirname = function(path) { | ||
26459 | var result = splitPath(path), | ||
26460 | root = result[0], | ||
26461 | dir = result[1]; | ||
26462 | |||
26463 | if (!root && !dir) { | ||
26464 | // No dirname whatsoever | ||
26465 | return '.'; | ||
26466 | } | ||
26467 | |||
26468 | if (dir) { | ||
26469 | // It has a dirname, strip trailing slash | ||
26470 | dir = dir.substr(0, dir.length - 1); | ||
26471 | } | ||
26472 | |||
26473 | return root + dir; | ||
26474 | }; | ||
26475 | |||
26476 | |||
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); | ||
26482 | } | ||
26483 | return f; | ||
26484 | }; | ||
26485 | |||
26486 | |||
26487 | exports.extname = function(path) { | ||
26488 | return splitPath(path)[3]; | ||
26489 | }; | ||
26490 | |||
26491 | function filter (xs, f) { | ||
26492 | if (xs.filter) return xs.filter(f); | ||
26493 | var res = []; | ||
26494 | for (var i = 0; i < xs.length; i++) { | ||
26495 | if (f(xs[i], i, xs)) res.push(xs[i]); | ||
26496 | } | ||
26497 | return res; | ||
26498 | } | ||
26499 | |||
26500 | // String.prototype.substr - negative index don't work in IE8 | ||
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); | ||
26506 | } | ||
26507 | ; | ||
26508 | |||
26509 | }).call(this,require('_process')) | ||
26510 | },{"_process":190}],184:[function(require,module,exports){ | ||
26511 | |||
26512 | exports.pbkdf2 = require('./lib/async') | ||
26513 | |||
26514 | exports.pbkdf2Sync = require('./lib/sync') | ||
26515 | |||
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 | ||
26522 | |||
26523 | var ZERO_BUF | ||
26524 | var subtle = global.crypto && global.crypto.subtle | ||
26525 | var toBrowser = { | ||
26526 | 'sha': 'SHA-1', | ||
26527 | 'sha-1': 'SHA-1', | ||
26528 | 'sha1': 'SHA-1', | ||
26529 | 'sha256': 'SHA-256', | ||
26530 | 'sha-256': 'SHA-256', | ||
26531 | 'sha384': 'SHA-384', | ||
26532 | 'sha-384': 'SHA-384', | ||
26533 | 'sha-512': 'SHA-512', | ||
26534 | 'sha512': 'SHA-512' | ||
26535 | } | ||
26536 | var checks = [] | ||
26537 | function checkNative (algo) { | ||
26538 | if (global.process && !global.process.browser) { | ||
26539 | return Promise.resolve(false) | ||
26540 | } | ||
26541 | if (!subtle || !subtle.importKey || !subtle.deriveBits) { | ||
26542 | return Promise.resolve(false) | ||
26543 | } | ||
26544 | if (checks[algo] !== undefined) { | ||
26545 | return checks[algo] | ||
26546 | } | ||
26547 | ZERO_BUF = ZERO_BUF || Buffer.alloc(8) | ||
26548 | var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) | ||
26549 | .then(function () { | ||
26550 | return true | ||
26551 | }).catch(function () { | ||
26552 | return false | ||
26553 | }) | ||
26554 | checks[algo] = prom | ||
26555 | return prom | ||
26556 | } | ||
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({ | ||
26562 | name: 'PBKDF2', | ||
26563 | salt: salt, | ||
26564 | iterations: iterations, | ||
26565 | hash: { | ||
26566 | name: algo | ||
26567 | } | ||
26568 | }, key, length << 3) | ||
26569 | }).then(function (res) { | ||
26570 | return Buffer.from(res) | ||
26571 | }) | ||
26572 | } | ||
26573 | function resolvePromise (promise, callback) { | ||
26574 | promise.then(function (out) { | ||
26575 | process.nextTick(function () { | ||
26576 | callback(null, out) | ||
26577 | }) | ||
26578 | }, function (e) { | ||
26579 | process.nextTick(function () { | ||
26580 | callback(e) | ||
26581 | }) | ||
26582 | }) | ||
26583 | } | ||
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) | ||
26587 | |||
26588 | checkParameters(iterations, keylen) | ||
26589 | if (typeof digest === 'function') { | ||
26590 | callback = digest | ||
26591 | digest = undefined | ||
26592 | } | ||
26593 | if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') | ||
26594 | |||
26595 | digest = digest || 'sha1' | ||
26596 | var algo = toBrowser[digest.toLowerCase()] | ||
26597 | if (!algo || typeof global.Promise !== 'function') { | ||
26598 | return process.nextTick(function () { | ||
26599 | var out | ||
26600 | try { | ||
26601 | out = sync(password, salt, iterations, keylen, digest) | ||
26602 | } catch (e) { | ||
26603 | return callback(e) | ||
26604 | } | ||
26605 | callback(null, out) | ||
26606 | }) | ||
26607 | } | ||
26608 | resolvePromise(checkNative(algo).then(function (resp) { | ||
26609 | if (resp) { | ||
26610 | return browserPbkdf2(password, salt, iterations, keylen, algo) | ||
26611 | } else { | ||
26612 | return sync(password, salt, iterations, keylen, digest) | ||
26613 | } | ||
26614 | }), callback) | ||
26615 | } | ||
26616 | |||
26617 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | ||
26618 | },{"./default-encoding":186,"./precondition":187,"./sync":188,"_process":190,"safe-buffer":247}],186:[function(require,module,exports){ | ||
26619 | (function (process){ | ||
26620 | var defaultEncoding | ||
26621 | /* istanbul ignore next */ | ||
26622 | if (process.browser) { | ||
26623 | defaultEncoding = 'utf-8' | ||
26624 | } else { | ||
26625 | var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) | ||
26626 | |||
26627 | defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' | ||
26628 | } | ||
26629 | module.exports = defaultEncoding | ||
26630 | |||
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') | ||
26637 | } | ||
26638 | |||
26639 | if (iterations < 0) { | ||
26640 | throw new TypeError('Bad iterations') | ||
26641 | } | ||
26642 | |||
26643 | if (typeof keylen !== 'number') { | ||
26644 | throw new TypeError('Key length not a number') | ||
26645 | } | ||
26646 | |||
26647 | if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ | ||
26648 | throw new TypeError('Bad key length') | ||
26649 | } | ||
26650 | } | ||
26651 | |||
26652 | },{}],188:[function(require,module,exports){ | ||
26653 | var md5 = require('create-hash/md5') | ||
26654 | var rmd160 = require('ripemd160') | ||
26655 | var sha = require('sha.js') | ||
26656 | |||
26657 | var checkParameters = require('./precondition') | ||
26658 | var defaultEncoding = require('./default-encoding') | ||
26659 | var Buffer = require('safe-buffer').Buffer | ||
26660 | var ZEROS = Buffer.alloc(128) | ||
26661 | var sizes = { | ||
26662 | md5: 16, | ||
26663 | sha1: 20, | ||
26664 | sha224: 28, | ||
26665 | sha256: 32, | ||
26666 | sha384: 48, | ||
26667 | sha512: 64, | ||
26668 | rmd160: 20, | ||
26669 | ripemd160: 20 | ||
26670 | } | ||
26671 | |||
26672 | function Hmac (alg, key, saltLen) { | ||
26673 | var hash = getDigest(alg) | ||
26674 | var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 | ||
26675 | |||
26676 | if (key.length > blocksize) { | ||
26677 | key = hash(key) | ||
26678 | } else if (key.length < blocksize) { | ||
26679 | key = Buffer.concat([key, ZEROS], blocksize) | ||
26680 | } | ||
26681 | |||
26682 | var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) | ||
26683 | var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) | ||
26684 | for (var i = 0; i < blocksize; i++) { | ||
26685 | ipad[i] = key[i] ^ 0x36 | ||
26686 | opad[i] = key[i] ^ 0x5C | ||
26687 | } | ||
26688 | |||
26689 | var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) | ||
26690 | ipad.copy(ipad1, 0, 0, blocksize) | ||
26691 | this.ipad1 = ipad1 | ||
26692 | this.ipad2 = ipad | ||
26693 | this.opad = opad | ||
26694 | this.alg = alg | ||
26695 | this.blocksize = blocksize | ||
26696 | this.hash = hash | ||
26697 | this.size = sizes[alg] | ||
26698 | } | ||
26699 | |||
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) | ||
26705 | } | ||
26706 | |||
26707 | function getDigest (alg) { | ||
26708 | function shaFunc (data) { | ||
26709 | return sha(alg).update(data).digest() | ||
26710 | } | ||
26711 | |||
26712 | if (alg === 'rmd160' || alg === 'ripemd160') return rmd160 | ||
26713 | if (alg === 'md5') return md5 | ||
26714 | return shaFunc | ||
26715 | } | ||
26716 | |||
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) | ||
26720 | |||
26721 | checkParameters(iterations, keylen) | ||
26722 | |||
26723 | digest = digest || 'sha1' | ||
26724 | |||
26725 | var hmac = new Hmac(digest, password, salt.length) | ||
26726 | |||
26727 | var DK = Buffer.allocUnsafe(keylen) | ||
26728 | var block1 = Buffer.allocUnsafe(salt.length + 4) | ||
26729 | salt.copy(block1, 0, 0, salt.length) | ||
26730 | |||
26731 | var destPos = 0 | ||
26732 | var hLen = sizes[digest] | ||
26733 | var l = Math.ceil(keylen / hLen) | ||
26734 | |||
26735 | for (var i = 1; i <= l; i++) { | ||
26736 | block1.writeUInt32BE(i, salt.length) | ||
26737 | |||
26738 | var T = hmac.run(block1, hmac.ipad1) | ||
26739 | var U = T | ||
26740 | |||
26741 | for (var j = 1; j < iterations; j++) { | ||
26742 | U = hmac.run(U, hmac.ipad2) | ||
26743 | for (var k = 0; k < hLen; k++) T[k] ^= U[k] | ||
26744 | } | ||
26745 | |||
26746 | T.copy(DK, destPos) | ||
26747 | destPos += hLen | ||
26748 | } | ||
26749 | |||
26750 | return DK | ||
26751 | } | ||
26752 | |||
26753 | module.exports = pbkdf2 | ||
26754 | |||
26755 | },{"./default-encoding":186,"./precondition":187,"create-hash/md5":113,"ripemd160":246,"safe-buffer":247,"sha.js":256}],189:[function(require,module,exports){ | ||
26756 | (function (process){ | ||
26757 | 'use strict'; | ||
26758 | |||
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; | ||
26763 | } else { | ||
26764 | module.exports = process.nextTick; | ||
26765 | } | ||
26766 | |||
26767 | function nextTick(fn, arg1, arg2, arg3) { | ||
26768 | if (typeof fn !== 'function') { | ||
26769 | throw new TypeError('"callback" argument must be a function'); | ||
26770 | } | ||
26771 | var len = arguments.length; | ||
26772 | var args, i; | ||
26773 | switch (len) { | ||
26774 | case 0: | ||
26775 | case 1: | ||
26776 | return process.nextTick(fn); | ||
26777 | case 2: | ||
26778 | return process.nextTick(function afterTickOne() { | ||
26779 | fn.call(null, arg1); | ||
26780 | }); | ||
26781 | case 3: | ||
26782 | return process.nextTick(function afterTickTwo() { | ||
26783 | fn.call(null, arg1, arg2); | ||
26784 | }); | ||
26785 | case 4: | ||
26786 | return process.nextTick(function afterTickThree() { | ||
26787 | fn.call(null, arg1, arg2, arg3); | ||
26788 | }); | ||
26789 | default: | ||
26790 | args = new Array(len - 1); | ||
26791 | i = 0; | ||
26792 | while (i < args.length) { | ||
26793 | args[i++] = arguments[i]; | ||
26794 | } | ||
26795 | return process.nextTick(function afterTick() { | ||
26796 | fn.apply(null, args); | ||
26797 | }); | ||
26798 | } | ||
26799 | } | ||
26800 | |||
26801 | }).call(this,require('_process')) | ||
26802 | },{"_process":190}],190:[function(require,module,exports){ | ||
26803 | // shim for using process in browser | ||
26804 | var process = module.exports = {}; | ||
26805 | |||
26806 | // cached from whatever global is present so that test runners that stub it | ||
26807 | // don't break things. But we need to wrap it in a try catch in case it is | ||
26808 | // wrapped in strict mode code which doesn't define any globals. It's inside a | ||
26809 | // function because try/catches deoptimize in certain engines. | ||
26810 | |||
26811 | var cachedSetTimeout; | ||
26812 | var cachedClearTimeout; | ||
26813 | |||
26814 | function defaultSetTimout() { | ||
26815 | throw new Error('setTimeout has not been defined'); | ||
26816 | } | ||
26817 | function defaultClearTimeout () { | ||
26818 | throw new Error('clearTimeout has not been defined'); | ||
26819 | } | ||
26820 | (function () { | ||
26821 | try { | ||
26822 | if (typeof setTimeout === 'function') { | ||
26823 | cachedSetTimeout = setTimeout; | ||
26824 | } else { | ||
26825 | cachedSetTimeout = defaultSetTimout; | ||
26826 | } | ||
26827 | } catch (e) { | ||
26828 | cachedSetTimeout = defaultSetTimout; | ||
26829 | } | ||
26830 | try { | ||
26831 | if (typeof clearTimeout === 'function') { | ||
26832 | cachedClearTimeout = clearTimeout; | ||
26833 | } else { | ||
26834 | cachedClearTimeout = defaultClearTimeout; | ||
26835 | } | ||
26836 | } catch (e) { | ||
26837 | cachedClearTimeout = defaultClearTimeout; | ||
26838 | } | ||
26839 | } ()) | ||
26840 | function runTimeout(fun) { | ||
26841 | if (cachedSetTimeout === setTimeout) { | ||
26842 | //normal enviroments in sane situations | ||
26843 | return setTimeout(fun, 0); | ||
26844 | } | ||
26845 | // if setTimeout wasn't available but was latter defined | ||
26846 | if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { | ||
26847 | cachedSetTimeout = setTimeout; | ||
26848 | return setTimeout(fun, 0); | ||
26849 | } | ||
26850 | try { | ||
26851 | // when when somebody has screwed with setTimeout but no I.E. maddness | ||
26852 | return cachedSetTimeout(fun, 0); | ||
26853 | } catch(e){ | ||
26854 | try { | ||
26855 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally | ||
26856 | return cachedSetTimeout.call(null, fun, 0); | ||
26857 | } catch(e){ | ||
26858 | // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error | ||
26859 | return cachedSetTimeout.call(this, fun, 0); | ||
26860 | } | ||
26861 | } | ||
26862 | |||
26863 | |||
26864 | } | ||
26865 | function runClearTimeout(marker) { | ||
26866 | if (cachedClearTimeout === clearTimeout) { | ||
26867 | //normal enviroments in sane situations | ||
26868 | return clearTimeout(marker); | ||
26869 | } | ||
26870 | // if clearTimeout wasn't available but was latter defined | ||
26871 | if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { | ||
26872 | cachedClearTimeout = clearTimeout; | ||
26873 | return clearTimeout(marker); | ||
26874 | } | ||
26875 | try { | ||
26876 | // when when somebody has screwed with setTimeout but no I.E. maddness | ||
26877 | return cachedClearTimeout(marker); | ||
26878 | } catch (e){ | ||
26879 | try { | ||
26880 | // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally | ||
26881 | return cachedClearTimeout.call(null, marker); | ||
26882 | } catch (e){ | ||
26883 | // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. | ||
26884 | // Some versions of I.E. have different rules for clearTimeout vs setTimeout | ||
26885 | return cachedClearTimeout.call(this, marker); | ||
26886 | } | ||
26887 | } | ||
26888 | |||
26889 | |||
26890 | |||
26891 | } | ||
26892 | var queue = []; | ||
26893 | var draining = false; | ||
26894 | var currentQueue; | ||
26895 | var queueIndex = -1; | ||
26896 | |||
26897 | function cleanUpNextTick() { | ||
26898 | if (!draining || !currentQueue) { | ||
26899 | return; | ||
26900 | } | ||
26901 | draining = false; | ||
26902 | if (currentQueue.length) { | ||
26903 | queue = currentQueue.concat(queue); | ||
26904 | } else { | ||
26905 | queueIndex = -1; | ||
26906 | } | ||
26907 | if (queue.length) { | ||
26908 | drainQueue(); | ||
26909 | } | ||
26910 | } | ||
26911 | |||
26912 | function drainQueue() { | ||
26913 | if (draining) { | ||
26914 | return; | ||
26915 | } | ||
26916 | var timeout = runTimeout(cleanUpNextTick); | ||
26917 | draining = true; | ||
26918 | |||
26919 | var len = queue.length; | ||
26920 | while(len) { | ||
26921 | currentQueue = queue; | ||
26922 | queue = []; | ||
26923 | while (++queueIndex < len) { | ||
26924 | if (currentQueue) { | ||
26925 | currentQueue[queueIndex].run(); | ||
26926 | } | ||
26927 | } | ||
26928 | queueIndex = -1; | ||
26929 | len = queue.length; | ||
26930 | } | ||
26931 | currentQueue = null; | ||
26932 | draining = false; | ||
26933 | runClearTimeout(timeout); | ||
26934 | } | ||
26935 | |||
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]; | ||
26941 | } | ||
26942 | } | ||
26943 | queue.push(new Item(fun, args)); | ||
26944 | if (queue.length === 1 && !draining) { | ||
26945 | runTimeout(drainQueue); | ||
26946 | } | ||
26947 | }; | ||
26948 | |||
26949 | // v8 likes predictible objects | ||
26950 | function Item(fun, array) { | ||
26951 | this.fun = fun; | ||
26952 | this.array = array; | ||
26953 | } | ||
26954 | Item.prototype.run = function () { | ||
26955 | this.fun.apply(null, this.array); | ||
26956 | }; | ||
26957 | process.title = 'browser'; | ||
26958 | process.browser = true; | ||
26959 | process.env = {}; | ||
26960 | process.argv = []; | ||
26961 | process.version = ''; // empty string to avoid regexp issues | ||
26962 | process.versions = {}; | ||
26963 | |||
26964 | function noop() {} | ||
26965 | |||
26966 | process.on = noop; | ||
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; | ||
26975 | |||
26976 | process.listeners = function (name) { return [] } | ||
26977 | |||
26978 | process.binding = function (name) { | ||
26979 | throw new Error('process.binding is not supported'); | ||
26980 | }; | ||
26981 | |||
26982 | process.cwd = function () { return '/' }; | ||
26983 | process.chdir = function (dir) { | ||
26984 | throw new Error('process.chdir is not supported'); | ||
26985 | }; | ||
26986 | process.umask = function() { return 0; }; | ||
26987 | |||
26988 | },{}],191:[function(require,module,exports){ | ||
26989 | // full library entry point. | ||
26990 | |||
26991 | "use strict"; | ||
26992 | module.exports = require("./src/index"); | ||
26993 | |||
26994 | },{"./src/index":200}],192:[function(require,module,exports){ | ||
26995 | "use strict"; | ||
26996 | module.exports = common; | ||
26997 | |||
26998 | var commonRe = /\/|\./; | ||
26999 | |||
27000 | /** | ||
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 | ||
27013 | * @example | ||
27014 | * // manually provides descriptor.proto (assumes google/protobuf/ namespace and .proto extension) | ||
27015 | * protobuf.common("descriptor", descriptorJson); | ||
27016 | * | ||
27017 | * // manually provides a custom definition (uses my.foo namespace) | ||
27018 | * protobuf.common("my/foo/bar.proto", myFooBarJson); | ||
27019 | */ | ||
27020 | function common(name, json) { | ||
27021 | if (!commonRe.test(name)) { | ||
27022 | name = "google/protobuf/" + name + ".proto"; | ||
27023 | json = { nested: { google: { nested: { protobuf: { nested: json } } } } }; | ||
27024 | } | ||
27025 | common[name] = json; | ||
27026 | } | ||
27027 | |||
27028 | // Not provided because of limited use (feel free to discuss or to provide yourself): | ||
27029 | // | ||
27030 | // google/protobuf/descriptor.proto | ||
27031 | // google/protobuf/source_context.proto | ||
27032 | // google/protobuf/type.proto | ||
27033 | // | ||
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. | ||
27036 | |||
27037 | common("any", { | ||
27038 | |||
27039 | /** | ||
27040 | * Properties of a google.protobuf.Any message. | ||
27041 | * @interface IAny | ||
27042 | * @type {Object} | ||
27043 | * @property {string} [typeUrl] | ||
27044 | * @property {Uint8Array} [bytes] | ||
27045 | * @memberof common | ||
27046 | */ | ||
27047 | Any: { | ||
27048 | fields: { | ||
27049 | type_url: { | ||
27050 | type: "string", | ||
27051 | id: 1 | ||
27052 | }, | ||
27053 | value: { | ||
27054 | type: "bytes", | ||
27055 | id: 2 | ||
27056 | } | ||
27057 | } | ||
27058 | } | ||
27059 | }); | ||
27060 | |||
27061 | var timeType; | ||
27062 | |||
27063 | common("duration", { | ||
27064 | |||
27065 | /** | ||
27066 | * Properties of a google.protobuf.Duration message. | ||
27067 | * @interface IDuration | ||
27068 | * @type {Object} | ||
27069 | * @property {number|Long} [seconds] | ||
27070 | * @property {number} [nanos] | ||
27071 | * @memberof common | ||
27072 | */ | ||
27073 | Duration: timeType = { | ||
27074 | fields: { | ||
27075 | seconds: { | ||
27076 | type: "int64", | ||
27077 | id: 1 | ||
27078 | }, | ||
27079 | nanos: { | ||
27080 | type: "int32", | ||
27081 | id: 2 | ||
27082 | } | ||
27083 | } | ||
27084 | } | ||
27085 | }); | ||
27086 | |||
27087 | common("timestamp", { | ||
27088 | |||
27089 | /** | ||
27090 | * Properties of a google.protobuf.Timestamp message. | ||
27091 | * @interface ITimestamp | ||
27092 | * @type {Object} | ||
27093 | * @property {number|Long} [seconds] | ||
27094 | * @property {number} [nanos] | ||
27095 | * @memberof common | ||
27096 | */ | ||
27097 | Timestamp: timeType | ||
27098 | }); | ||
27099 | |||
27100 | common("empty", { | ||
27101 | |||
27102 | /** | ||
27103 | * Properties of a google.protobuf.Empty message. | ||
27104 | * @interface IEmpty | ||
27105 | * @memberof common | ||
27106 | */ | ||
27107 | Empty: { | ||
27108 | fields: {} | ||
27109 | } | ||
27110 | }); | ||
27111 | |||
27112 | common("struct", { | ||
27113 | |||
27114 | /** | ||
27115 | * Properties of a google.protobuf.Struct message. | ||
27116 | * @interface IStruct | ||
27117 | * @type {Object} | ||
27118 | * @property {Object.<string,IValue>} [fields] | ||
27119 | * @memberof common | ||
27120 | */ | ||
27121 | Struct: { | ||
27122 | fields: { | ||
27123 | fields: { | ||
27124 | keyType: "string", | ||
27125 | type: "Value", | ||
27126 | id: 1 | ||
27127 | } | ||
27128 | } | ||
27129 | }, | ||
27130 | |||
27131 | /** | ||
27132 | * Properties of a google.protobuf.Value message. | ||
27133 | * @interface IValue | ||
27134 | * @type {Object} | ||
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] | ||
27142 | * @memberof common | ||
27143 | */ | ||
27144 | Value: { | ||
27145 | oneofs: { | ||
27146 | kind: { | ||
27147 | oneof: [ | ||
27148 | "nullValue", | ||
27149 | "numberValue", | ||
27150 | "stringValue", | ||
27151 | "boolValue", | ||
27152 | "structValue", | ||
27153 | "listValue" | ||
27154 | ] | ||
27155 | } | ||
27156 | }, | ||
27157 | fields: { | ||
27158 | nullValue: { | ||
27159 | type: "NullValue", | ||
27160 | id: 1 | ||
27161 | }, | ||
27162 | numberValue: { | ||
27163 | type: "double", | ||
27164 | id: 2 | ||
27165 | }, | ||
27166 | stringValue: { | ||
27167 | type: "string", | ||
27168 | id: 3 | ||
27169 | }, | ||
27170 | boolValue: { | ||
27171 | type: "bool", | ||
27172 | id: 4 | ||
27173 | }, | ||
27174 | structValue: { | ||
27175 | type: "Struct", | ||
27176 | id: 5 | ||
27177 | }, | ||
27178 | listValue: { | ||
27179 | type: "ListValue", | ||
27180 | id: 6 | ||
27181 | } | ||
27182 | } | ||
27183 | }, | ||
27184 | |||
27185 | NullValue: { | ||
27186 | values: { | ||
27187 | NULL_VALUE: 0 | ||
27188 | } | ||
27189 | }, | ||
27190 | |||
27191 | /** | ||
27192 | * Properties of a google.protobuf.ListValue message. | ||
27193 | * @interface IListValue | ||
27194 | * @type {Object} | ||
27195 | * @property {Array.<IValue>} [values] | ||
27196 | * @memberof common | ||
27197 | */ | ||
27198 | ListValue: { | ||
27199 | fields: { | ||
27200 | values: { | ||
27201 | rule: "repeated", | ||
27202 | type: "Value", | ||
27203 | id: 1 | ||
27204 | } | ||
27205 | } | ||
27206 | } | ||
27207 | }); | ||
27208 | |||
27209 | common("wrappers", { | ||
27210 | |||
27211 | /** | ||
27212 | * Properties of a google.protobuf.DoubleValue message. | ||
27213 | * @interface IDoubleValue | ||
27214 | * @type {Object} | ||
27215 | * @property {number} [value] | ||
27216 | * @memberof common | ||
27217 | */ | ||
27218 | DoubleValue: { | ||
27219 | fields: { | ||
27220 | value: { | ||
27221 | type: "double", | ||
27222 | id: 1 | ||
27223 | } | ||
27224 | } | ||
27225 | }, | ||
27226 | |||
27227 | /** | ||
27228 | * Properties of a google.protobuf.FloatValue message. | ||
27229 | * @interface IFloatValue | ||
27230 | * @type {Object} | ||
27231 | * @property {number} [value] | ||
27232 | * @memberof common | ||
27233 | */ | ||
27234 | FloatValue: { | ||
27235 | fields: { | ||
27236 | value: { | ||
27237 | type: "float", | ||
27238 | id: 1 | ||
27239 | } | ||
27240 | } | ||
27241 | }, | ||
27242 | |||
27243 | /** | ||
27244 | * Properties of a google.protobuf.Int64Value message. | ||
27245 | * @interface IInt64Value | ||
27246 | * @type {Object} | ||
27247 | * @property {number|Long} [value] | ||
27248 | * @memberof common | ||
27249 | */ | ||
27250 | Int64Value: { | ||
27251 | fields: { | ||
27252 | value: { | ||
27253 | type: "int64", | ||
27254 | id: 1 | ||
27255 | } | ||
27256 | } | ||
27257 | }, | ||
27258 | |||
27259 | /** | ||
27260 | * Properties of a google.protobuf.UInt64Value message. | ||
27261 | * @interface IUInt64Value | ||
27262 | * @type {Object} | ||
27263 | * @property {number|Long} [value] | ||
27264 | * @memberof common | ||
27265 | */ | ||
27266 | UInt64Value: { | ||
27267 | fields: { | ||
27268 | value: { | ||
27269 | type: "uint64", | ||
27270 | id: 1 | ||
27271 | } | ||
27272 | } | ||
27273 | }, | ||
27274 | |||
27275 | /** | ||
27276 | * Properties of a google.protobuf.Int32Value message. | ||
27277 | * @interface IInt32Value | ||
27278 | * @type {Object} | ||
27279 | * @property {number} [value] | ||
27280 | * @memberof common | ||
27281 | */ | ||
27282 | Int32Value: { | ||
27283 | fields: { | ||
27284 | value: { | ||
27285 | type: "int32", | ||
27286 | id: 1 | ||
27287 | } | ||
27288 | } | ||
27289 | }, | ||
27290 | |||
27291 | /** | ||
27292 | * Properties of a google.protobuf.UInt32Value message. | ||
27293 | * @interface IUInt32Value | ||
27294 | * @type {Object} | ||
27295 | * @property {number} [value] | ||
27296 | * @memberof common | ||
27297 | */ | ||
27298 | UInt32Value: { | ||
27299 | fields: { | ||
27300 | value: { | ||
27301 | type: "uint32", | ||
27302 | id: 1 | ||
27303 | } | ||
27304 | } | ||
27305 | }, | ||
27306 | |||
27307 | /** | ||
27308 | * Properties of a google.protobuf.BoolValue message. | ||
27309 | * @interface IBoolValue | ||
27310 | * @type {Object} | ||
27311 | * @property {boolean} [value] | ||
27312 | * @memberof common | ||
27313 | */ | ||
27314 | BoolValue: { | ||
27315 | fields: { | ||
27316 | value: { | ||
27317 | type: "bool", | ||
27318 | id: 1 | ||
27319 | } | ||
27320 | } | ||
27321 | }, | ||
27322 | |||
27323 | /** | ||
27324 | * Properties of a google.protobuf.StringValue message. | ||
27325 | * @interface IStringValue | ||
27326 | * @type {Object} | ||
27327 | * @property {string} [value] | ||
27328 | * @memberof common | ||
27329 | */ | ||
27330 | StringValue: { | ||
27331 | fields: { | ||
27332 | value: { | ||
27333 | type: "string", | ||
27334 | id: 1 | ||
27335 | } | ||
27336 | } | ||
27337 | }, | ||
27338 | |||
27339 | /** | ||
27340 | * Properties of a google.protobuf.BytesValue message. | ||
27341 | * @interface IBytesValue | ||
27342 | * @type {Object} | ||
27343 | * @property {Uint8Array} [value] | ||
27344 | * @memberof common | ||
27345 | */ | ||
27346 | BytesValue: { | ||
27347 | fields: { | ||
27348 | value: { | ||
27349 | type: "bytes", | ||
27350 | id: 1 | ||
27351 | } | ||
27352 | } | ||
27353 | } | ||
27354 | }); | ||
27355 | |||
27356 | common("field_mask", { | ||
27357 | |||
27358 | /** | ||
27359 | * Properties of a google.protobuf.FieldMask message. | ||
27360 | * @interface IDoubleValue | ||
27361 | * @type {Object} | ||
27362 | * @property {number} [value] | ||
27363 | * @memberof common | ||
27364 | */ | ||
27365 | FieldMask: { | ||
27366 | fields: { | ||
27367 | paths: { | ||
27368 | rule: "repeated", | ||
27369 | type: "string", | ||
27370 | id: 1 | ||
27371 | } | ||
27372 | } | ||
27373 | } | ||
27374 | }); | ||
27375 | |||
27376 | /** | ||
27377 | * Gets the root definition of the specified common proto file. | ||
27378 | * | ||
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 | ||
27387 | * | ||
27388 | * @param {string} file Proto file name | ||
27389 | * @returns {INamespace|null} Root definition or `null` if not defined | ||
27390 | */ | ||
27391 | common.get = function get(file) { | ||
27392 | return common[file] || null; | ||
27393 | }; | ||
27394 | |||
27395 | },{}],193:[function(require,module,exports){ | ||
27396 | "use strict"; | ||
27397 | /** | ||
27398 | * Runtime message from/to plain object converters. | ||
27399 | * @namespace | ||
27400 | */ | ||
27401 | var converter = exports; | ||
27402 | |||
27403 | var Enum = require("./enum"), | ||
27404 | util = require("./util"); | ||
27405 | |||
27406 | /** | ||
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 | ||
27413 | * @ignore | ||
27414 | */ | ||
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 | ||
27422 | ("default:"); | ||
27423 | gen | ||
27424 | ("case%j:", keys[i]) | ||
27425 | ("case %i:", values[keys[i]]) | ||
27426 | ("m%s=%j", prop, values[keys[i]]) | ||
27427 | ("break"); | ||
27428 | } gen | ||
27429 | ("}"); | ||
27430 | } else gen | ||
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); | ||
27434 | } else { | ||
27435 | var isUnsigned = false; | ||
27436 | switch (field.type) { | ||
27437 | case "double": | ||
27438 | case "float": gen | ||
27439 | ("m%s=Number(d%s)", prop, prop); // also catches "NaN", "Infinity" | ||
27440 | break; | ||
27441 | case "uint32": | ||
27442 | case "fixed32": gen | ||
27443 | ("m%s=d%s>>>0", prop, prop); | ||
27444 | break; | ||
27445 | case "int32": | ||
27446 | case "sint32": | ||
27447 | case "sfixed32": gen | ||
27448 | ("m%s=d%s|0", prop, prop); | ||
27449 | break; | ||
27450 | case "uint64": | ||
27451 | isUnsigned = true; | ||
27452 | // eslint-disable-line no-fallthrough | ||
27453 | case "int64": | ||
27454 | case "sint64": | ||
27455 | case "fixed64": | ||
27456 | case "sfixed64": gen | ||
27457 | ("if(util.Long)") | ||
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" : ""); | ||
27465 | break; | ||
27466 | case "bytes": gen | ||
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); | ||
27471 | break; | ||
27472 | case "string": gen | ||
27473 | ("m%s=String(d%s)", prop, prop); | ||
27474 | break; | ||
27475 | case "bool": gen | ||
27476 | ("m%s=Boolean(d%s)", prop, prop); | ||
27477 | break; | ||
27478 | /* default: gen | ||
27479 | ("m%s=d%s", prop, prop); | ||
27480 | break; */ | ||
27481 | } | ||
27482 | } | ||
27483 | return gen; | ||
27484 | /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ | ||
27485 | } | ||
27486 | |||
27487 | /** | ||
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 | ||
27491 | */ | ||
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)") | ||
27497 | ("return d"); | ||
27498 | if (!fields.length) return gen | ||
27499 | ("return new this.ctor"); | ||
27500 | gen | ||
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); | ||
27505 | |||
27506 | // Map fields | ||
27507 | if (field.map) { gen | ||
27508 | ("if(d%s){", prop) | ||
27509 | ("if(typeof d%s!==\"object\")", prop) | ||
27510 | ("throw TypeError(%j)", field.fullName + ": object expected") | ||
27511 | ("m%s={}", prop) | ||
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]]") | ||
27514 | ("}") | ||
27515 | ("}"); | ||
27516 | |||
27517 | // Repeated fields | ||
27518 | } else if (field.repeated) { gen | ||
27519 | ("if(d%s){", prop) | ||
27520 | ("if(!Array.isArray(d%s))", prop) | ||
27521 | ("throw TypeError(%j)", field.fullName + ": array expected") | ||
27522 | ("m%s=[]", prop) | ||
27523 | ("for(var i=0;i<d%s.length;++i){", prop); | ||
27524 | genValuePartial_fromObject(gen, field, /* not sorted */ i, prop + "[i]") | ||
27525 | ("}") | ||
27526 | ("}"); | ||
27527 | |||
27528 | // Non-repeated fields | ||
27529 | } else { | ||
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 | ||
27534 | ("}"); | ||
27535 | } | ||
27536 | } return gen | ||
27537 | ("return m"); | ||
27538 | /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ | ||
27539 | }; | ||
27540 | |||
27541 | /** | ||
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 | ||
27548 | * @ignore | ||
27549 | */ | ||
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); | ||
27555 | else gen | ||
27556 | ("d%s=types[%i].toObject(m%s,o)", prop, fieldIndex, prop); | ||
27557 | } else { | ||
27558 | var isUnsigned = false; | ||
27559 | switch (field.type) { | ||
27560 | case "double": | ||
27561 | case "float": gen | ||
27562 | ("d%s=o.json&&!isFinite(m%s)?String(m%s):m%s", prop, prop, prop, prop); | ||
27563 | break; | ||
27564 | case "uint64": | ||
27565 | isUnsigned = true; | ||
27566 | // eslint-disable-line no-fallthrough | ||
27567 | case "int64": | ||
27568 | case "sint64": | ||
27569 | case "fixed64": | ||
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); | ||
27575 | break; | ||
27576 | case "bytes": gen | ||
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); | ||
27578 | break; | ||
27579 | default: gen | ||
27580 | ("d%s=m%s", prop, prop); | ||
27581 | break; | ||
27582 | } | ||
27583 | } | ||
27584 | return gen; | ||
27585 | /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ | ||
27586 | } | ||
27587 | |||
27588 | /** | ||
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 | ||
27592 | */ | ||
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") | ||
27599 | ("if(!o)") | ||
27600 | ("o={}") | ||
27601 | ("var d={}"); | ||
27602 | |||
27603 | var repeatedFields = [], | ||
27604 | mapFields = [], | ||
27605 | normalFields = [], | ||
27606 | i = 0; | ||
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]); | ||
27612 | |||
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)); | ||
27617 | gen | ||
27618 | ("}"); | ||
27619 | } | ||
27620 | |||
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)); | ||
27625 | gen | ||
27626 | ("}"); | ||
27627 | } | ||
27628 | |||
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 | ||
27637 | ("if(util.Long){") | ||
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) | ||
27640 | ("}else") | ||
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(",") + "]"); | ||
27644 | else gen | ||
27645 | ("d%s=%j", prop, field.typeDefault); // also messages (=null) | ||
27646 | } gen | ||
27647 | ("}"); | ||
27648 | } | ||
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); | ||
27654 | if (field.map) { | ||
27655 | if (!hasKs2) { hasKs2 = true; gen | ||
27656 | ("var ks2"); | ||
27657 | } gen | ||
27658 | ("if(m%s&&(ks2=Object.keys(m%s)).length){", prop, prop) | ||
27659 | ("d%s={}", prop) | ||
27660 | ("for(var j=0;j<ks2.length;++j){"); | ||
27661 | genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[ks2[j]]") | ||
27662 | ("}"); | ||
27663 | } else if (field.repeated) { gen | ||
27664 | ("if(m%s&&m%s.length){", prop, prop) | ||
27665 | ("d%s=[]", prop) | ||
27666 | ("for(var j=0;j<m%s.length;++j){", prop); | ||
27667 | genValuePartial_toObject(gen, field, /* sorted */ index, prop + "[j]") | ||
27668 | ("}"); | ||
27669 | } else { gen | ||
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 | ||
27673 | ("if(o.oneofs)") | ||
27674 | ("d%s=%j", util.safeProp(field.partOf.name), field.name); | ||
27675 | } | ||
27676 | gen | ||
27677 | ("}"); | ||
27678 | } | ||
27679 | return gen | ||
27680 | ("return d"); | ||
27681 | /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ | ||
27682 | }; | ||
27683 | |||
27684 | },{"./enum":196,"./util":218}],194:[function(require,module,exports){ | ||
27685 | "use strict"; | ||
27686 | module.exports = decoder; | ||
27687 | |||
27688 | var Enum = require("./enum"), | ||
27689 | types = require("./types"), | ||
27690 | util = require("./util"); | ||
27691 | |||
27692 | function missing(field) { | ||
27693 | return "missing required '" + field.name + "'"; | ||
27694 | } | ||
27695 | |||
27696 | /** | ||
27697 | * Generates a decoder specific to the specified message type. | ||
27698 | * @param {Type} mtype Message type | ||
27699 | * @returns {Codegen} Codegen instance | ||
27700 | */ | ||
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 | ||
27710 | ("if((t&7)===4)") | ||
27711 | ("break"); | ||
27712 | gen | ||
27713 | ("switch(t>>>3){"); | ||
27714 | |||
27715 | var i = 0; | ||
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); | ||
27721 | |||
27722 | // Map fields | ||
27723 | if (field.map) { gen | ||
27724 | ("r.skip().pos++") // assumes id 1 + key wireType | ||
27725 | ("if(%s===util.emptyObject)", ref) | ||
27726 | ("%s={}", 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 | ||
27732 | else gen | ||
27733 | ("%s[typeof k===\"object\"?util.longToHash(k):k]=r.%s()", ref, type); | ||
27734 | } else { | ||
27735 | if (types.basic[type] === undefined) gen | ||
27736 | ("%s[k]=types[%i].decode(r,r.uint32())", ref, i); // can't be groups | ||
27737 | else gen | ||
27738 | ("%s[k]=r.%s()", ref, type); | ||
27739 | } | ||
27740 | |||
27741 | // Repeated fields | ||
27742 | } else if (field.repeated) { gen | ||
27743 | |||
27744 | ("if(!(%s&&%s.length))", ref, ref) | ||
27745 | ("%s=[]", ref); | ||
27746 | |||
27747 | // Packable (always check for forward and backward compatiblity) | ||
27748 | if (types.packed[type] !== undefined) gen | ||
27749 | ("if((t&7)===2){") | ||
27750 | ("var c2=r.uint32()+r.pos") | ||
27751 | ("while(r.pos<c2)") | ||
27752 | ("%s.push(r.%s())", ref, type) | ||
27753 | ("}else"); | ||
27754 | |||
27755 | // Non-packed | ||
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); | ||
27759 | else gen | ||
27760 | ("%s.push(r.%s())", ref, type); | ||
27761 | |||
27762 | // Non-repeated | ||
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); | ||
27766 | else gen | ||
27767 | ("%s=r.%s()", ref, type); | ||
27768 | gen | ||
27769 | ("break"); | ||
27770 | // Unknown fields | ||
27771 | } gen | ||
27772 | ("default:") | ||
27773 | ("r.skipType(t&7)") | ||
27774 | ("break") | ||
27775 | |||
27776 | ("}") | ||
27777 | ("}"); | ||
27778 | |||
27779 | // Field presence | ||
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)); | ||
27785 | } | ||
27786 | |||
27787 | return gen | ||
27788 | ("return m"); | ||
27789 | /* eslint-enable no-unexpected-multiline */ | ||
27790 | } | ||
27791 | |||
27792 | },{"./enum":196,"./types":217,"./util":218}],195:[function(require,module,exports){ | ||
27793 | "use strict"; | ||
27794 | module.exports = encoder; | ||
27795 | |||
27796 | var Enum = require("./enum"), | ||
27797 | types = require("./types"), | ||
27798 | util = require("./util"); | ||
27799 | |||
27800 | /** | ||
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 | ||
27807 | * @ignore | ||
27808 | */ | ||
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); | ||
27813 | } | ||
27814 | |||
27815 | /** | ||
27816 | * Generates an encoder specific to the specified message type. | ||
27817 | * @param {Type} mtype Message type | ||
27818 | * @returns {Codegen} Codegen instance | ||
27819 | */ | ||
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") | ||
27823 | ("if(!w)") | ||
27824 | ("w=Writer.create()"); | ||
27825 | |||
27826 | var i, ref; | ||
27827 | |||
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); | ||
27830 | |||
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); | ||
27837 | |||
27838 | // Map fields | ||
27839 | if (field.map) { | ||
27840 | gen | ||
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 | ||
27846 | else gen | ||
27847 | (".uint32(%i).%s(%s[ks[i]]).ldelim()", 16 | wireType, type, ref); | ||
27848 | gen | ||
27849 | ("}") | ||
27850 | ("}"); | ||
27851 | |||
27852 | // Repeated fields | ||
27853 | } else if (field.repeated) { gen | ||
27854 | ("if(%s!=null&&%s.length){", ref, ref); // !== undefined && !== null | ||
27855 | |||
27856 | // Packed repeated | ||
27857 | if (field.packed && types.packed[type] !== undefined) { gen | ||
27858 | |||
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) | ||
27862 | ("w.ldelim()"); | ||
27863 | |||
27864 | // Non-packed | ||
27865 | } else { gen | ||
27866 | |||
27867 | ("for(var i=0;i<%s.length;++i)", ref); | ||
27868 | if (wireType === undefined) | ||
27869 | genTypePartial(gen, field, index, ref + "[i]"); | ||
27870 | else gen | ||
27871 | ("w.uint32(%i).%s(%s[i])", (field.id << 3 | wireType) >>> 0, type, ref); | ||
27872 | |||
27873 | } gen | ||
27874 | ("}"); | ||
27875 | |||
27876 | // Non-repeated | ||
27877 | } else { | ||
27878 | if (field.optional) gen | ||
27879 | ("if(%s!=null&&m.hasOwnProperty(%j))", ref, field.name); // !== undefined && !== null | ||
27880 | |||
27881 | if (wireType === undefined) | ||
27882 | genTypePartial(gen, field, index, ref); | ||
27883 | else gen | ||
27884 | ("w.uint32(%i).%s(%s)", (field.id << 3 | wireType) >>> 0, type, ref); | ||
27885 | |||
27886 | } | ||
27887 | } | ||
27888 | |||
27889 | return gen | ||
27890 | ("return w"); | ||
27891 | /* eslint-enable no-unexpected-multiline, block-scoped-var, no-redeclare */ | ||
27892 | } | ||
27893 | },{"./enum":196,"./types":217,"./util":218}],196:[function(require,module,exports){ | ||
27894 | "use strict"; | ||
27895 | module.exports = Enum; | ||
27896 | |||
27897 | // extends ReflectionObject | ||
27898 | var ReflectionObject = require("./object"); | ||
27899 | ((Enum.prototype = Object.create(ReflectionObject.prototype)).constructor = Enum).className = "Enum"; | ||
27900 | |||
27901 | var Namespace = require("./namespace"), | ||
27902 | util = require("./util"); | ||
27903 | |||
27904 | /** | ||
27905 | * Constructs a new enum instance. | ||
27906 | * @classdesc Reflected enum. | ||
27907 | * @extends ReflectionObject | ||
27908 | * @constructor | ||
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 | ||
27914 | */ | ||
27915 | function Enum(name, values, options, comment, comments) { | ||
27916 | ReflectionObject.call(this, name, options); | ||
27917 | |||
27918 | if (values && typeof values !== "object") | ||
27919 | throw TypeError("values must be an object"); | ||
27920 | |||
27921 | /** | ||
27922 | * Enum values by id. | ||
27923 | * @type {Object.<number,string>} | ||
27924 | */ | ||
27925 | this.valuesById = {}; | ||
27926 | |||
27927 | /** | ||
27928 | * Enum values by name. | ||
27929 | * @type {Object.<string,number>} | ||
27930 | */ | ||
27931 | this.values = Object.create(this.valuesById); // toJSON, marker | ||
27932 | |||
27933 | /** | ||
27934 | * Enum comment text. | ||
27935 | * @type {string|null} | ||
27936 | */ | ||
27937 | this.comment = comment; | ||
27938 | |||
27939 | /** | ||
27940 | * Value comment texts, if any. | ||
27941 | * @type {Object.<string,string>} | ||
27942 | */ | ||
27943 | this.comments = comments || {}; | ||
27944 | |||
27945 | /** | ||
27946 | * Reserved ranges, if any. | ||
27947 | * @type {Array.<number[]|string>} | ||
27948 | */ | ||
27949 | this.reserved = undefined; // toJSON | ||
27950 | |||
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. | ||
27954 | |||
27955 | if (values) | ||
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]; | ||
27959 | } | ||
27960 | |||
27961 | /** | ||
27962 | * Enum descriptor. | ||
27963 | * @interface IEnum | ||
27964 | * @property {Object.<string,number>} values Enum values | ||
27965 | * @property {Object.<string,*>} [options] Enum options | ||
27966 | */ | ||
27967 | |||
27968 | /** | ||
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 | ||
27974 | */ | ||
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; | ||
27978 | return enm; | ||
27979 | }; | ||
27980 | |||
27981 | /** | ||
27982 | * Converts this enum to an enum descriptor. | ||
27983 | * @param {IToJSONOptions} [toJSONOptions] JSON conversion options | ||
27984 | * @returns {IEnum} Enum descriptor | ||
27985 | */ | ||
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 | ||
27994 | ]); | ||
27995 | }; | ||
27996 | |||
27997 | /** | ||
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 | ||
28005 | */ | ||
28006 | Enum.prototype.add = function add(name, id, comment) { | ||
28007 | // utilized by the parser but not by .fromJSON | ||
28008 | |||
28009 | if (!util.isString(name)) | ||
28010 | throw TypeError("name must be a string"); | ||
28011 | |||
28012 | if (!util.isInteger(id)) | ||
28013 | throw TypeError("id must be an integer"); | ||
28014 | |||
28015 | if (this.values[name] !== undefined) | ||
28016 | throw Error("duplicate name '" + name + "' in " + this); | ||
28017 | |||
28018 | if (this.isReservedId(id)) | ||
28019 | throw Error("id " + id + " is reserved in " + this); | ||
28020 | |||
28021 | if (this.isReservedName(name)) | ||
28022 | throw Error("name '" + name + "' is reserved in " + this); | ||
28023 | |||
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; | ||
28028 | } else | ||
28029 | this.valuesById[this.values[name] = id] = name; | ||
28030 | |||
28031 | this.comments[name] = comment || null; | ||
28032 | return this; | ||
28033 | }; | ||
28034 | |||
28035 | /** | ||
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 | ||
28041 | */ | ||
28042 | Enum.prototype.remove = function remove(name) { | ||
28043 | |||
28044 | if (!util.isString(name)) | ||
28045 | throw TypeError("name must be a string"); | ||
28046 | |||
28047 | var val = this.values[name]; | ||
28048 | if (val == null) | ||
28049 | throw Error("name '" + name + "' does not exist in " + this); | ||
28050 | |||
28051 | delete this.valuesById[val]; | ||
28052 | delete this.values[name]; | ||
28053 | delete this.comments[name]; | ||
28054 | |||
28055 | return this; | ||
28056 | }; | ||
28057 | |||
28058 | /** | ||
28059 | * Tests if the specified id is reserved. | ||
28060 | * @param {number} id Id to test | ||
28061 | * @returns {boolean} `true` if reserved, otherwise `false` | ||
28062 | */ | ||
28063 | Enum.prototype.isReservedId = function isReservedId(id) { | ||
28064 | return Namespace.isReservedId(this.reserved, id); | ||
28065 | }; | ||
28066 | |||
28067 | /** | ||
28068 | * Tests if the specified name is reserved. | ||
28069 | * @param {string} name Name to test | ||
28070 | * @returns {boolean} `true` if reserved, otherwise `false` | ||
28071 | */ | ||
28072 | Enum.prototype.isReservedName = function isReservedName(name) { | ||
28073 | return Namespace.isReservedName(this.reserved, name); | ||
28074 | }; | ||
28075 | |||
28076 | },{"./namespace":204,"./object":205,"./util":218}],197:[function(require,module,exports){ | ||
28077 | "use strict"; | ||
28078 | module.exports = Field; | ||
28079 | |||
28080 | // extends ReflectionObject | ||
28081 | var ReflectionObject = require("./object"); | ||
28082 | ((Field.prototype = Object.create(ReflectionObject.prototype)).constructor = Field).className = "Field"; | ||
28083 | |||
28084 | var Enum = require("./enum"), | ||
28085 | types = require("./types"), | ||
28086 | util = require("./util"); | ||
28087 | |||
28088 | var Type; // cyclic | ||
28089 | |||
28090 | var ruleRe = /^required|optional|repeated$/; | ||
28091 | |||
28092 | /** | ||
28093 | * Constructs a new message field instance. Note that {@link MapField|map fields} have their own class. | ||
28094 | * @name Field | ||
28095 | * @classdesc Reflected message field. | ||
28096 | * @extends FieldBase | ||
28097 | * @constructor | ||
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 | ||
28104 | */ | ||
28105 | |||
28106 | /** | ||
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 | ||
28112 | */ | ||
28113 | Field.fromJSON = function fromJSON(name, json) { | ||
28114 | return new Field(name, json.id, json.type, json.rule, json.extend, json.options, json.comment); | ||
28115 | }; | ||
28116 | |||
28117 | /** | ||
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 | ||
28122 | * @constructor | ||
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 | ||
28130 | */ | ||
28131 | function Field(name, id, type, rule, extend, options, comment) { | ||
28132 | |||
28133 | if (util.isObject(rule)) { | ||
28134 | comment = extend; | ||
28135 | options = rule; | ||
28136 | rule = extend = undefined; | ||
28137 | } else if (util.isObject(extend)) { | ||
28138 | comment = options; | ||
28139 | options = extend; | ||
28140 | extend = undefined; | ||
28141 | } | ||
28142 | |||
28143 | ReflectionObject.call(this, name, options); | ||
28144 | |||
28145 | if (!util.isInteger(id) || id < 0) | ||
28146 | throw TypeError("id must be a non-negative integer"); | ||
28147 | |||
28148 | if (!util.isString(type)) | ||
28149 | throw TypeError("type must be a string"); | ||
28150 | |||
28151 | if (rule !== undefined && !ruleRe.test(rule = rule.toString().toLowerCase())) | ||
28152 | throw TypeError("rule must be a string rule"); | ||
28153 | |||
28154 | if (extend !== undefined && !util.isString(extend)) | ||
28155 | throw TypeError("extend must be a string"); | ||
28156 | |||
28157 | /** | ||
28158 | * Field rule, if any. | ||
28159 | * @type {string|undefined} | ||
28160 | */ | ||
28161 | this.rule = rule && rule !== "optional" ? rule : undefined; // toJSON | ||
28162 | |||
28163 | /** | ||
28164 | * Field type. | ||
28165 | * @type {string} | ||
28166 | */ | ||
28167 | this.type = type; // toJSON | ||
28168 | |||
28169 | /** | ||
28170 | * Unique field id. | ||
28171 | * @type {number} | ||
28172 | */ | ||
28173 | this.id = id; // toJSON, marker | ||
28174 | |||
28175 | /** | ||
28176 | * Extended type if different from parent. | ||
28177 | * @type {string|undefined} | ||
28178 | */ | ||
28179 | this.extend = extend || undefined; // toJSON | ||
28180 | |||
28181 | /** | ||
28182 | * Whether this field is required. | ||
28183 | * @type {boolean} | ||
28184 | */ | ||
28185 | this.required = rule === "required"; | ||
28186 | |||
28187 | /** | ||
28188 | * Whether this field is optional. | ||
28189 | * @type {boolean} | ||
28190 | */ | ||
28191 | this.optional = !this.required; | ||
28192 | |||
28193 | /** | ||
28194 | * Whether this field is repeated. | ||
28195 | * @type {boolean} | ||
28196 | */ | ||
28197 | this.repeated = rule === "repeated"; | ||
28198 | |||
28199 | /** | ||
28200 | * Whether this field is a map or not. | ||
28201 | * @type {boolean} | ||
28202 | */ | ||
28203 | this.map = false; | ||
28204 | |||
28205 | /** | ||
28206 | * Message this field belongs to. | ||
28207 | * @type {Type|null} | ||
28208 | */ | ||
28209 | this.message = null; | ||
28210 | |||
28211 | /** | ||
28212 | * OneOf this field belongs to, if any, | ||
28213 | * @type {OneOf|null} | ||
28214 | */ | ||
28215 | this.partOf = null; | ||
28216 | |||
28217 | /** | ||
28218 | * The field type's default value. | ||
28219 | * @type {*} | ||
28220 | */ | ||
28221 | this.typeDefault = null; | ||
28222 | |||
28223 | /** | ||
28224 | * The field's default value on prototypes. | ||
28225 | * @type {*} | ||
28226 | */ | ||
28227 | this.defaultValue = null; | ||
28228 | |||
28229 | /** | ||
28230 | * Whether this field's value should be treated as a long. | ||
28231 | * @type {boolean} | ||
28232 | */ | ||
28233 | this.long = util.Long ? types.long[type] !== undefined : /* istanbul ignore next */ false; | ||
28234 | |||
28235 | /** | ||
28236 | * Whether this field's value is a buffer. | ||
28237 | * @type {boolean} | ||
28238 | */ | ||
28239 | this.bytes = type === "bytes"; | ||
28240 | |||
28241 | /** | ||
28242 | * Resolved type if not a basic type. | ||
28243 | * @type {Type|Enum|null} | ||
28244 | */ | ||
28245 | this.resolvedType = null; | ||
28246 | |||
28247 | /** | ||
28248 | * Sister-field within the extended type if a declaring extension field. | ||
28249 | * @type {Field|null} | ||
28250 | */ | ||
28251 | this.extensionField = null; | ||
28252 | |||
28253 | /** | ||
28254 | * Sister-field within the declaring namespace if an extended field. | ||
28255 | * @type {Field|null} | ||
28256 | */ | ||
28257 | this.declaringField = null; | ||
28258 | |||
28259 | /** | ||
28260 | * Internally remembers whether this field is packed. | ||
28261 | * @type {boolean|null} | ||
28262 | * @private | ||
28263 | */ | ||
28264 | this._packed = null; | ||
28265 | |||
28266 | /** | ||
28267 | * Comment for this field. | ||
28268 | * @type {string|null} | ||
28269 | */ | ||
28270 | this.comment = comment; | ||
28271 | } | ||
28272 | |||
28273 | /** | ||
28274 | * Determines whether this field is packed. Only relevant when repeated and working with proto2. | ||
28275 | * @name Field#packed | ||
28276 | * @type {boolean} | ||
28277 | * @readonly | ||
28278 | */ | ||
28279 | Object.defineProperty(Field.prototype, "packed", { | ||
28280 | get: function() { | ||
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; | ||
28285 | } | ||
28286 | }); | ||
28287 | |||
28288 | /** | ||
28289 | * @override | ||
28290 | */ | ||
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); | ||
28295 | }; | ||
28296 | |||
28297 | /** | ||
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 | ||
28304 | */ | ||
28305 | |||
28306 | /** | ||
28307 | * Extension field descriptor. | ||
28308 | * @interface IExtensionField | ||
28309 | * @extends IField | ||
28310 | * @property {string} extend Extended type | ||
28311 | */ | ||
28312 | |||
28313 | /** | ||
28314 | * Converts this field to a field descriptor. | ||
28315 | * @param {IToJSONOptions} [toJSONOptions] JSON conversion options | ||
28316 | * @returns {IField} Field descriptor | ||
28317 | */ | ||
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, | ||
28323 | "id" , this.id, | ||
28324 | "extend" , this.extend, | ||
28325 | "options" , this.options, | ||
28326 | "comment" , keepComments ? this.comment : undefined | ||
28327 | ]); | ||
28328 | }; | ||
28329 | |||
28330 | /** | ||
28331 | * Resolves this field's type references. | ||
28332 | * @returns {Field} `this` | ||
28333 | * @throws {Error} If any reference cannot be resolved | ||
28334 | */ | ||
28335 | Field.prototype.resolve = function resolve() { | ||
28336 | |||
28337 | if (this.resolved) | ||
28338 | return this; | ||
28339 | |||
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 | ||
28346 | } | ||
28347 | |||
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]; | ||
28353 | } | ||
28354 | |||
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; | ||
28361 | } | ||
28362 | |||
28363 | // convert to internal data type if necesssary | ||
28364 | if (this.long) { | ||
28365 | this.typeDefault = util.Long.fromNumber(this.typeDefault, this.type.charAt(0) === "u"); | ||
28366 | |||
28367 | /* istanbul ignore else */ | ||
28368 | if (Object.freeze) | ||
28369 | Object.freeze(this.typeDefault); // long instances are meant to be immutable anyway (i.e. use small int cache that even requires it) | ||
28370 | |||
28371 | } else if (this.bytes && typeof this.typeDefault === "string") { | ||
28372 | var buf; | ||
28373 | if (util.base64.test(this.typeDefault)) | ||
28374 | util.base64.decode(this.typeDefault, buf = util.newBuffer(util.base64.length(this.typeDefault)), 0); | ||
28375 | else | ||
28376 | util.utf8.write(this.typeDefault, buf = util.newBuffer(util.utf8.length(this.typeDefault)), 0); | ||
28377 | this.typeDefault = buf; | ||
28378 | } | ||
28379 | |||
28380 | // take special care of maps and repeated fields | ||
28381 | if (this.map) | ||
28382 | this.defaultValue = util.emptyObject; | ||
28383 | else if (this.repeated) | ||
28384 | this.defaultValue = util.emptyArray; | ||
28385 | else | ||
28386 | this.defaultValue = this.typeDefault; | ||
28387 | |||
28388 | // ensure proper value on prototype | ||
28389 | if (this.parent instanceof Type) | ||
28390 | this.parent.ctor.prototype[this.name] = this.defaultValue; | ||
28391 | |||
28392 | return ReflectionObject.prototype.resolve.call(this); | ||
28393 | }; | ||
28394 | |||
28395 | /** | ||
28396 | * Decorator function as returned by {@link Field.d} and {@link MapField.d} (TypeScript). | ||
28397 | * @typedef FieldDecorator | ||
28398 | * @type {function} | ||
28399 | * @param {Object} prototype Target prototype | ||
28400 | * @param {string} fieldName Field name | ||
28401 | * @returns {undefined} | ||
28402 | */ | ||
28403 | |||
28404 | /** | ||
28405 | * Field decorator (TypeScript). | ||
28406 | * @name Field.d | ||
28407 | * @function | ||
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[] | ||
28414 | */ | ||
28415 | Field.d = function decorateField(fieldId, fieldType, fieldRule, defaultValue) { | ||
28416 | |||
28417 | // submessage: decorate the submessage and use its name as the type | ||
28418 | if (typeof fieldType === "function") | ||
28419 | fieldType = util.decorateType(fieldType).name; | ||
28420 | |||
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; | ||
28424 | |||
28425 | return function fieldDecorator(prototype, fieldName) { | ||
28426 | util.decorateType(prototype.constructor) | ||
28427 | .add(new Field(fieldName, fieldId, fieldType, fieldRule, { "default": defaultValue })); | ||
28428 | }; | ||
28429 | }; | ||
28430 | |||
28431 | /** | ||
28432 | * Field decorator (TypeScript). | ||
28433 | * @name Field.d | ||
28434 | * @function | ||
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> | ||
28440 | * @variation 2 | ||
28441 | */ | ||
28442 | // like Field.d but without a default value | ||
28443 | |||
28444 | Field._configure = function configure(Type_) { | ||
28445 | Type = Type_; | ||
28446 | }; | ||
28447 | |||
28448 | },{"./enum":196,"./object":205,"./types":217,"./util":218}],198:[function(require,module,exports){ | ||
28449 | "use strict"; | ||
28450 | var protobuf = module.exports = require("./index-minimal"); | ||
28451 | |||
28452 | protobuf.build = "light"; | ||
28453 | |||
28454 | /** | ||
28455 | * A node-style callback as used by {@link load} and {@link Root#load}. | ||
28456 | * @typedef LoadCallback | ||
28457 | * @type {function} | ||
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} | ||
28461 | */ | ||
28462 | |||
28463 | /** | ||
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} | ||
28470 | */ | ||
28471 | function load(filename, root, callback) { | ||
28472 | if (typeof root === "function") { | ||
28473 | callback = root; | ||
28474 | root = new protobuf.Root(); | ||
28475 | } else if (!root) | ||
28476 | root = new protobuf.Root(); | ||
28477 | return root.load(filename, callback); | ||
28478 | } | ||
28479 | |||
28480 | /** | ||
28481 | * Loads one or multiple .proto or preprocessed .json files into a common root namespace and calls the callback. | ||
28482 | * @name load | ||
28483 | * @function | ||
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} | ||
28488 | * @variation 2 | ||
28489 | */ | ||
28490 | // function load(filename:string, callback:LoadCallback):undefined | ||
28491 | |||
28492 | /** | ||
28493 | * Loads one or multiple .proto or preprocessed .json files into a common root namespace and returns a promise. | ||
28494 | * @name load | ||
28495 | * @function | ||
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} | ||
28500 | * @variation 3 | ||
28501 | */ | ||
28502 | // function load(filename:string, [root:Root]):Promise<Root> | ||
28503 | |||
28504 | protobuf.load = load; | ||
28505 | |||
28506 | /** | ||
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} | ||
28513 | */ | ||
28514 | function loadSync(filename, root) { | ||
28515 | if (!root) | ||
28516 | root = new protobuf.Root(); | ||
28517 | return root.loadSync(filename); | ||
28518 | } | ||
28519 | |||
28520 | protobuf.loadSync = loadSync; | ||
28521 | |||
28522 | // Serialization | ||
28523 | protobuf.encoder = require("./encoder"); | ||
28524 | protobuf.decoder = require("./decoder"); | ||
28525 | protobuf.verifier = require("./verifier"); | ||
28526 | protobuf.converter = require("./converter"); | ||
28527 | |||
28528 | // Reflection | ||
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"); | ||
28539 | |||
28540 | // Runtime | ||
28541 | protobuf.Message = require("./message"); | ||
28542 | protobuf.wrappers = require("./wrappers"); | ||
28543 | |||
28544 | // Utility | ||
28545 | protobuf.types = require("./types"); | ||
28546 | protobuf.util = require("./util"); | ||
28547 | |||
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); | ||
28553 | |||
28554 | },{"./converter":193,"./decoder":194,"./encoder":195,"./enum":196,"./field":197,"./index-minimal":199,"./mapfield":201,"./message":202,"./method":203,"./namespace":204,"./object":205,"./oneof":206,"./root":210,"./service":214,"./type":216,"./types":217,"./util":218,"./verifier":221,"./wrappers":222}],199:[function(require,module,exports){ | ||
28555 | "use strict"; | ||
28556 | var protobuf = exports; | ||
28557 | |||
28558 | /** | ||
28559 | * Build type, one of `"full"`, `"light"` or `"minimal"`. | ||
28560 | * @name build | ||
28561 | * @type {string} | ||
28562 | * @const | ||
28563 | */ | ||
28564 | protobuf.build = "minimal"; | ||
28565 | |||
28566 | // Serialization | ||
28567 | protobuf.Writer = require("./writer"); | ||
28568 | protobuf.BufferWriter = require("./writer_buffer"); | ||
28569 | protobuf.Reader = require("./reader"); | ||
28570 | protobuf.BufferReader = require("./reader_buffer"); | ||
28571 | |||
28572 | // Utility | ||
28573 | protobuf.util = require("./util/minimal"); | ||
28574 | protobuf.rpc = require("./rpc"); | ||
28575 | protobuf.roots = require("./roots"); | ||
28576 | protobuf.configure = configure; | ||
28577 | |||
28578 | /* istanbul ignore next */ | ||
28579 | /** | ||
28580 | * Reconfigures the library according to the environment. | ||
28581 | * @returns {undefined} | ||
28582 | */ | ||
28583 | function configure() { | ||
28584 | protobuf.Reader._configure(protobuf.BufferReader); | ||
28585 | protobuf.util._configure(); | ||
28586 | } | ||
28587 | |||
28588 | // Configure serialization | ||
28589 | protobuf.Writer._configure(protobuf.BufferWriter); | ||
28590 | configure(); | ||
28591 | |||
28592 | },{"./reader":208,"./reader_buffer":209,"./roots":211,"./rpc":212,"./util/minimal":220,"./writer":223,"./writer_buffer":224}],200:[function(require,module,exports){ | ||
28593 | "use strict"; | ||
28594 | var protobuf = module.exports = require("./index-light"); | ||
28595 | |||
28596 | protobuf.build = "full"; | ||
28597 | |||
28598 | // Parser | ||
28599 | protobuf.tokenize = require("./tokenize"); | ||
28600 | protobuf.parse = require("./parse"); | ||
28601 | protobuf.common = require("./common"); | ||
28602 | |||
28603 | // Configure parser | ||
28604 | protobuf.Root._configure(protobuf.Type, protobuf.parse, protobuf.common); | ||
28605 | |||
28606 | },{"./common":192,"./index-light":198,"./parse":207,"./tokenize":215}],201:[function(require,module,exports){ | ||
28607 | "use strict"; | ||
28608 | module.exports = MapField; | ||
28609 | |||
28610 | // extends Field | ||
28611 | var Field = require("./field"); | ||
28612 | ((MapField.prototype = Object.create(Field.prototype)).constructor = MapField).className = "MapField"; | ||
28613 | |||
28614 | var types = require("./types"), | ||
28615 | util = require("./util"); | ||
28616 | |||
28617 | /** | ||
28618 | * Constructs a new map field instance. | ||
28619 | * @classdesc Reflected map field. | ||
28620 | * @extends FieldBase | ||
28621 | * @constructor | ||
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 | ||
28628 | */ | ||
28629 | function MapField(name, id, keyType, type, options, comment) { | ||
28630 | Field.call(this, name, id, type, undefined, undefined, options, comment); | ||
28631 | |||
28632 | /* istanbul ignore if */ | ||
28633 | if (!util.isString(keyType)) | ||
28634 | throw TypeError("keyType must be a string"); | ||
28635 | |||
28636 | /** | ||
28637 | * Key type. | ||
28638 | * @type {string} | ||
28639 | */ | ||
28640 | this.keyType = keyType; // toJSON, marker | ||
28641 | |||
28642 | /** | ||
28643 | * Resolved key type if not a basic type. | ||
28644 | * @type {ReflectionObject|null} | ||
28645 | */ | ||
28646 | this.resolvedKeyType = null; | ||
28647 | |||
28648 | // Overrides Field#map | ||
28649 | this.map = true; | ||
28650 | } | ||
28651 | |||
28652 | /** | ||
28653 | * Map field descriptor. | ||
28654 | * @interface IMapField | ||
28655 | * @extends {IField} | ||
28656 | * @property {string} keyType Key type | ||
28657 | */ | ||
28658 | |||
28659 | /** | ||
28660 | * Extension map field descriptor. | ||
28661 | * @interface IExtensionMapField | ||
28662 | * @extends IMapField | ||
28663 | * @property {string} extend Extended type | ||
28664 | */ | ||
28665 | |||
28666 | /** | ||
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 | ||
28672 | */ | ||
28673 | MapField.fromJSON = function fromJSON(name, json) { | ||
28674 | return new MapField(name, json.id, json.keyType, json.type, json.options, json.comment); | ||
28675 | }; | ||
28676 | |||
28677 | /** | ||
28678 | * Converts this map field to a map field descriptor. | ||
28679 | * @param {IToJSONOptions} [toJSONOptions] JSON conversion options | ||
28680 | * @returns {IMapField} Map field descriptor | ||
28681 | */ | ||
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, | ||
28687 | "id" , this.id, | ||
28688 | "extend" , this.extend, | ||
28689 | "options" , this.options, | ||
28690 | "comment" , keepComments ? this.comment : undefined | ||
28691 | ]); | ||
28692 | }; | ||
28693 | |||
28694 | /** | ||
28695 | * @override | ||
28696 | */ | ||
28697 | MapField.prototype.resolve = function resolve() { | ||
28698 | if (this.resolved) | ||
28699 | return this; | ||
28700 | |||
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); | ||
28704 | |||
28705 | return Field.prototype.resolve.call(this); | ||
28706 | }; | ||
28707 | |||
28708 | /** | ||
28709 | * Map field decorator (TypeScript). | ||
28710 | * @name MapField.d | ||
28711 | * @function | ||
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<{}> } | ||
28717 | */ | ||
28718 | MapField.d = function decorateMapField(fieldId, fieldKeyType, fieldValueType) { | ||
28719 | |||
28720 | // submessage value: decorate the submessage and use its name as the type | ||
28721 | if (typeof fieldValueType === "function") | ||
28722 | fieldValueType = util.decorateType(fieldValueType).name; | ||
28723 | |||
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; | ||
28727 | |||
28728 | return function mapFieldDecorator(prototype, fieldName) { | ||
28729 | util.decorateType(prototype.constructor) | ||
28730 | .add(new MapField(fieldName, fieldId, fieldKeyType, fieldValueType)); | ||
28731 | }; | ||
28732 | }; | ||
28733 | |||
28734 | },{"./field":197,"./types":217,"./util":218}],202:[function(require,module,exports){ | ||
28735 | "use strict"; | ||
28736 | module.exports = Message; | ||
28737 | |||
28738 | var util = require("./util/minimal"); | ||
28739 | |||
28740 | /** | ||
28741 | * Constructs a new message instance. | ||
28742 | * @classdesc Abstract runtime message. | ||
28743 | * @constructor | ||
28744 | * @param {Properties<T>} [properties] Properties to set | ||
28745 | * @template T extends object | ||
28746 | */ | ||
28747 | function Message(properties) { | ||
28748 | // not used internally | ||
28749 | if (properties) | ||
28750 | for (var keys = Object.keys(properties), i = 0; i < keys.length; ++i) | ||
28751 | this[keys[i]] = properties[keys[i]]; | ||
28752 | } | ||
28753 | |||
28754 | /** | ||
28755 | * Reference to the reflected type. | ||
28756 | * @name Message.$type | ||
28757 | * @type {Type} | ||
28758 | * @readonly | ||
28759 | */ | ||
28760 | |||
28761 | /** | ||
28762 | * Reference to the reflected type. | ||
28763 | * @name Message#$type | ||
28764 | * @type {Type} | ||
28765 | * @readonly | ||
28766 | */ | ||
28767 | |||
28768 | /*eslint-disable valid-jsdoc*/ | ||
28769 | |||
28770 | /** | ||
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> | ||
28776 | */ | ||
28777 | Message.create = function create(properties) { | ||
28778 | return this.$type.create(properties); | ||
28779 | }; | ||
28780 | |||
28781 | /** | ||
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> | ||
28788 | */ | ||
28789 | Message.encode = function encode(message, writer) { | ||
28790 | return this.$type.encode(message, writer); | ||
28791 | }; | ||
28792 | |||
28793 | /** | ||
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> | ||
28800 | */ | ||
28801 | Message.encodeDelimited = function encodeDelimited(message, writer) { | ||
28802 | return this.$type.encodeDelimited(message, writer); | ||
28803 | }; | ||
28804 | |||
28805 | /** | ||
28806 | * Decodes a message of this type. | ||
28807 | * @name Message.decode | ||
28808 | * @function | ||
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> | ||
28813 | */ | ||
28814 | Message.decode = function decode(reader) { | ||
28815 | return this.$type.decode(reader); | ||
28816 | }; | ||
28817 | |||
28818 | /** | ||
28819 | * Decodes a message of this type preceeded by its length as a varint. | ||
28820 | * @name Message.decodeDelimited | ||
28821 | * @function | ||
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> | ||
28826 | */ | ||
28827 | Message.decodeDelimited = function decodeDelimited(reader) { | ||
28828 | return this.$type.decodeDelimited(reader); | ||
28829 | }; | ||
28830 | |||
28831 | /** | ||
28832 | * Verifies a message of this type. | ||
28833 | * @name Message.verify | ||
28834 | * @function | ||
28835 | * @param {Object.<string,*>} message Plain object to verify | ||
28836 | * @returns {string|null} `null` if valid, otherwise the reason why it is not | ||
28837 | */ | ||
28838 | Message.verify = function verify(message) { | ||
28839 | return this.$type.verify(message); | ||
28840 | }; | ||
28841 | |||
28842 | /** | ||
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> | ||
28848 | */ | ||
28849 | Message.fromObject = function fromObject(object) { | ||
28850 | return this.$type.fromObject(object); | ||
28851 | }; | ||
28852 | |||
28853 | /** | ||
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> | ||
28860 | */ | ||
28861 | Message.toObject = function toObject(message, options) { | ||
28862 | return this.$type.toObject(message, options); | ||
28863 | }; | ||
28864 | |||
28865 | /** | ||
28866 | * Converts this message to JSON. | ||
28867 | * @returns {Object.<string,*>} JSON object | ||
28868 | */ | ||
28869 | Message.prototype.toJSON = function toJSON() { | ||
28870 | return this.$type.toObject(this, util.toJSONOptions); | ||
28871 | }; | ||
28872 | |||
28873 | /*eslint-enable valid-jsdoc*/ | ||
28874 | },{"./util/minimal":220}],203:[function(require,module,exports){ | ||
28875 | "use strict"; | ||
28876 | module.exports = Method; | ||
28877 | |||
28878 | // extends ReflectionObject | ||
28879 | var ReflectionObject = require("./object"); | ||
28880 | ((Method.prototype = Object.create(ReflectionObject.prototype)).constructor = Method).className = "Method"; | ||
28881 | |||
28882 | var util = require("./util"); | ||
28883 | |||
28884 | /** | ||
28885 | * Constructs a new service method instance. | ||
28886 | * @classdesc Reflected service method. | ||
28887 | * @extends ReflectionObject | ||
28888 | * @constructor | ||
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 | ||
28897 | */ | ||
28898 | function Method(name, type, requestType, responseType, requestStream, responseStream, options, comment) { | ||
28899 | |||
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; | ||
28907 | } | ||
28908 | |||
28909 | /* istanbul ignore if */ | ||
28910 | if (!(type === undefined || util.isString(type))) | ||
28911 | throw TypeError("type must be a string"); | ||
28912 | |||
28913 | /* istanbul ignore if */ | ||
28914 | if (!util.isString(requestType)) | ||
28915 | throw TypeError("requestType must be a string"); | ||
28916 | |||
28917 | /* istanbul ignore if */ | ||
28918 | if (!util.isString(responseType)) | ||
28919 | throw TypeError("responseType must be a string"); | ||
28920 | |||
28921 | ReflectionObject.call(this, name, options); | ||
28922 | |||
28923 | /** | ||
28924 | * Method type. | ||
28925 | * @type {string} | ||
28926 | */ | ||
28927 | this.type = type || "rpc"; // toJSON | ||
28928 | |||
28929 | /** | ||
28930 | * Request type. | ||
28931 | * @type {string} | ||
28932 | */ | ||
28933 | this.requestType = requestType; // toJSON, marker | ||
28934 | |||
28935 | /** | ||
28936 | * Whether requests are streamed or not. | ||
28937 | * @type {boolean|undefined} | ||
28938 | */ | ||
28939 | this.requestStream = requestStream ? true : undefined; // toJSON | ||
28940 | |||
28941 | /** | ||
28942 | * Response type. | ||
28943 | * @type {string} | ||
28944 | */ | ||
28945 | this.responseType = responseType; // toJSON | ||
28946 | |||
28947 | /** | ||
28948 | * Whether responses are streamed or not. | ||
28949 | * @type {boolean|undefined} | ||
28950 | */ | ||
28951 | this.responseStream = responseStream ? true : undefined; // toJSON | ||
28952 | |||
28953 | /** | ||
28954 | * Resolved request type. | ||
28955 | * @type {Type|null} | ||
28956 | */ | ||
28957 | this.resolvedRequestType = null; | ||
28958 | |||
28959 | /** | ||
28960 | * Resolved response type. | ||
28961 | * @type {Type|null} | ||
28962 | */ | ||
28963 | this.resolvedResponseType = null; | ||
28964 | |||
28965 | /** | ||
28966 | * Comment for this method | ||
28967 | * @type {string|null} | ||
28968 | */ | ||
28969 | this.comment = comment; | ||
28970 | } | ||
28971 | |||
28972 | /** | ||
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 | ||
28981 | */ | ||
28982 | |||
28983 | /** | ||
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 | ||
28989 | */ | ||
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); | ||
28992 | }; | ||
28993 | |||
28994 | /** | ||
28995 | * Converts this method to a method descriptor. | ||
28996 | * @param {IToJSONOptions} [toJSONOptions] JSON conversion options | ||
28997 | * @returns {IMethod} Method descriptor | ||
28998 | */ | ||
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 | ||
29009 | ]); | ||
29010 | }; | ||
29011 | |||
29012 | /** | ||
29013 | * @override | ||
29014 | */ | ||
29015 | Method.prototype.resolve = function resolve() { | ||
29016 | |||
29017 | /* istanbul ignore if */ | ||
29018 | if (this.resolved) | ||
29019 | return this; | ||
29020 | |||
29021 | this.resolvedRequestType = this.parent.lookupType(this.requestType); | ||
29022 | this.resolvedResponseType = this.parent.lookupType(this.responseType); | ||
29023 | |||
29024 | return ReflectionObject.prototype.resolve.call(this); | ||
29025 | }; | ||
29026 | |||
29027 | },{"./object":205,"./util":218}],204:[function(require,module,exports){ | ||
29028 | "use strict"; | ||
29029 | module.exports = Namespace; | ||
29030 | |||
29031 | // extends ReflectionObject | ||
29032 | var ReflectionObject = require("./object"); | ||
29033 | ((Namespace.prototype = Object.create(ReflectionObject.prototype)).constructor = Namespace).className = "Namespace"; | ||
29034 | |||
29035 | var Enum = require("./enum"), | ||
29036 | Field = require("./field"), | ||
29037 | util = require("./util"); | ||
29038 | |||
29039 | var Type, // cyclic | ||
29040 | Service; // " | ||
29041 | |||
29042 | /** | ||
29043 | * Constructs a new namespace instance. | ||
29044 | * @name Namespace | ||
29045 | * @classdesc Reflected namespace. | ||
29046 | * @extends NamespaceBase | ||
29047 | * @constructor | ||
29048 | * @param {string} name Namespace name | ||
29049 | * @param {Object.<string,*>} [options] Declared options | ||
29050 | */ | ||
29051 | |||
29052 | /** | ||
29053 | * Constructs a namespace from JSON. | ||
29054 | * @memberof Namespace | ||
29055 | * @function | ||
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 | ||
29060 | */ | ||
29061 | Namespace.fromJSON = function fromJSON(name, json) { | ||
29062 | return new Namespace(name, json.options).addJSON(json.nested); | ||
29063 | }; | ||
29064 | |||
29065 | /** | ||
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 | ||
29071 | */ | ||
29072 | function arrayToJSON(array, toJSONOptions) { | ||
29073 | if (!(array && array.length)) | ||
29074 | return undefined; | ||
29075 | var obj = {}; | ||
29076 | for (var i = 0; i < array.length; ++i) | ||
29077 | obj[array[i].name] = array[i].toJSON(toJSONOptions); | ||
29078 | return obj; | ||
29079 | } | ||
29080 | |||
29081 | Namespace.arrayToJSON = arrayToJSON; | ||
29082 | |||
29083 | /** | ||
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` | ||
29088 | */ | ||
29089 | Namespace.isReservedId = function isReservedId(reserved, id) { | ||
29090 | if (reserved) | ||
29091 | for (var i = 0; i < reserved.length; ++i) | ||
29092 | if (typeof reserved[i] !== "string" && reserved[i][0] <= id && reserved[i][1] >= id) | ||
29093 | return true; | ||
29094 | return false; | ||
29095 | }; | ||
29096 | |||
29097 | /** | ||
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` | ||
29102 | */ | ||
29103 | Namespace.isReservedName = function isReservedName(reserved, name) { | ||
29104 | if (reserved) | ||
29105 | for (var i = 0; i < reserved.length; ++i) | ||
29106 | if (reserved[i] === name) | ||
29107 | return true; | ||
29108 | return false; | ||
29109 | }; | ||
29110 | |||
29111 | /** | ||
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 | ||
29116 | * @abstract | ||
29117 | * @constructor | ||
29118 | * @param {string} name Namespace name | ||
29119 | * @param {Object.<string,*>} [options] Declared options | ||
29120 | * @see {@link Namespace} | ||
29121 | */ | ||
29122 | function Namespace(name, options) { | ||
29123 | ReflectionObject.call(this, name, options); | ||
29124 | |||
29125 | /** | ||
29126 | * Nested objects by name. | ||
29127 | * @type {Object.<string,ReflectionObject>|undefined} | ||
29128 | */ | ||
29129 | this.nested = undefined; // toJSON | ||
29130 | |||
29131 | /** | ||
29132 | * Cached nested objects as an array. | ||
29133 | * @type {ReflectionObject[]|null} | ||
29134 | * @private | ||
29135 | */ | ||
29136 | this._nestedArray = null; | ||
29137 | } | ||
29138 | |||
29139 | function clearCache(namespace) { | ||
29140 | namespace._nestedArray = null; | ||
29141 | return namespace; | ||
29142 | } | ||
29143 | |||
29144 | /** | ||
29145 | * Nested objects of this namespace as an array for iteration. | ||
29146 | * @name NamespaceBase#nestedArray | ||
29147 | * @type {ReflectionObject[]} | ||
29148 | * @readonly | ||
29149 | */ | ||
29150 | Object.defineProperty(Namespace.prototype, "nestedArray", { | ||
29151 | get: function() { | ||
29152 | return this._nestedArray || (this._nestedArray = util.toArray(this.nested)); | ||
29153 | } | ||
29154 | }); | ||
29155 | |||
29156 | /** | ||
29157 | * Namespace descriptor. | ||
29158 | * @interface INamespace | ||
29159 | * @property {Object.<string,*>} [options] Namespace options | ||
29160 | * @property {Object.<string,AnyNestedObject>} [nested] Nested object descriptors | ||
29161 | */ | ||
29162 | |||
29163 | /** | ||
29164 | * Any extension field descriptor. | ||
29165 | * @typedef AnyExtensionField | ||
29166 | * @type {IExtensionField|IExtensionMapField} | ||
29167 | */ | ||
29168 | |||
29169 | /** | ||
29170 | * Any nested object descriptor. | ||
29171 | * @typedef AnyNestedObject | ||
29172 | * @type {IEnum|IType|IService|AnyExtensionField|INamespace} | ||
29173 | */ | ||
29174 | // ^ BEWARE: VSCode hangs forever when using more than 5 types (that's why AnyExtensionField exists in the first place) | ||
29175 | |||
29176 | /** | ||
29177 | * Converts this namespace to a namespace descriptor. | ||
29178 | * @param {IToJSONOptions} [toJSONOptions] JSON conversion options | ||
29179 | * @returns {INamespace} Namespace descriptor | ||
29180 | */ | ||
29181 | Namespace.prototype.toJSON = function toJSON(toJSONOptions) { | ||
29182 | return util.toObject([ | ||
29183 | "options" , this.options, | ||
29184 | "nested" , arrayToJSON(this.nestedArray, toJSONOptions) | ||
29185 | ]); | ||
29186 | }; | ||
29187 | |||
29188 | /** | ||
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` | ||
29192 | */ | ||
29193 | Namespace.prototype.addJSON = function addJSON(nestedJson) { | ||
29194 | var ns = this; | ||
29195 | /* istanbul ignore else */ | ||
29196 | if (nestedJson) { | ||
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 | ||
29201 | ? Type.fromJSON | ||
29202 | : nested.values !== undefined | ||
29203 | ? Enum.fromJSON | ||
29204 | : nested.methods !== undefined | ||
29205 | ? Service.fromJSON | ||
29206 | : nested.id !== undefined | ||
29207 | ? Field.fromJSON | ||
29208 | : Namespace.fromJSON )(names[i], nested) | ||
29209 | ); | ||
29210 | } | ||
29211 | } | ||
29212 | return this; | ||
29213 | }; | ||
29214 | |||
29215 | /** | ||
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 | ||
29219 | */ | ||
29220 | Namespace.prototype.get = function get(name) { | ||
29221 | return this.nested && this.nested[name] | ||
29222 | || null; | ||
29223 | }; | ||
29224 | |||
29225 | /** | ||
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 | ||
29231 | */ | ||
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); | ||
29236 | }; | ||
29237 | |||
29238 | /** | ||
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 | ||
29244 | */ | ||
29245 | Namespace.prototype.add = function add(object) { | ||
29246 | |||
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"); | ||
29249 | |||
29250 | if (!this.nested) | ||
29251 | this.nested = {}; | ||
29252 | else { | ||
29253 | var prev = this.get(object.name); | ||
29254 | if (prev) { | ||
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]); | ||
29260 | this.remove(prev); | ||
29261 | if (!this.nested) | ||
29262 | this.nested = {}; | ||
29263 | object.setOptions(prev.options, true); | ||
29264 | |||
29265 | } else | ||
29266 | throw Error("duplicate name '" + object.name + "' in " + this); | ||
29267 | } | ||
29268 | } | ||
29269 | this.nested[object.name] = object; | ||
29270 | object.onAdd(this); | ||
29271 | return clearCache(this); | ||
29272 | }; | ||
29273 | |||
29274 | /** | ||
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 | ||
29280 | */ | ||
29281 | Namespace.prototype.remove = function remove(object) { | ||
29282 | |||
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); | ||
29287 | |||
29288 | delete this.nested[object.name]; | ||
29289 | if (!Object.keys(this.nested).length) | ||
29290 | this.nested = undefined; | ||
29291 | |||
29292 | object.onRemove(this); | ||
29293 | return clearCache(this); | ||
29294 | }; | ||
29295 | |||
29296 | /** | ||
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 | ||
29301 | */ | ||
29302 | Namespace.prototype.define = function define(path, json) { | ||
29303 | |||
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"); | ||
29310 | |||
29311 | var ptr = this; | ||
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"); | ||
29318 | } else | ||
29319 | ptr.add(ptr = new Namespace(part)); | ||
29320 | } | ||
29321 | if (json) | ||
29322 | ptr.addJSON(json); | ||
29323 | return ptr; | ||
29324 | }; | ||
29325 | |||
29326 | /** | ||
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` | ||
29329 | */ | ||
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(); | ||
29335 | else | ||
29336 | nested[i++].resolve(); | ||
29337 | return this.resolve(); | ||
29338 | }; | ||
29339 | |||
29340 | /** | ||
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 | ||
29346 | */ | ||
29347 | Namespace.prototype.lookup = function lookup(path, filterTypes, parentAlreadyChecked) { | ||
29348 | |||
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 ]; | ||
29355 | |||
29356 | if (util.isString(path) && path.length) { | ||
29357 | if (path === ".") | ||
29358 | return this.root; | ||
29359 | path = path.split("."); | ||
29360 | } else if (!path.length) | ||
29361 | return this; | ||
29362 | |||
29363 | // Start at root if path is absolute | ||
29364 | if (path[0] === "") | ||
29365 | return this.root.lookup(path.slice(1), filterTypes); | ||
29366 | |||
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]); | ||
29369 | if (found) { | ||
29370 | if (path.length === 1) { | ||
29371 | if (!filterTypes || filterTypes.indexOf(found.constructor) > -1) | ||
29372 | return found; | ||
29373 | } else if (found instanceof Namespace && (found = found.lookup(path.slice(1), filterTypes, true))) | ||
29374 | return found; | ||
29375 | |||
29376 | // Otherwise try each nested namespace | ||
29377 | } else | ||
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))) | ||
29380 | return found; | ||
29381 | |||
29382 | // If there hasn't been a match, try again at the parent | ||
29383 | if (this.parent === null || parentAlreadyChecked) | ||
29384 | return null; | ||
29385 | return this.parent.lookup(path, filterTypes); | ||
29386 | }; | ||
29387 | |||
29388 | /** | ||
29389 | * Looks up the reflection object at the specified path, relative to this namespace. | ||
29390 | * @name NamespaceBase#lookup | ||
29391 | * @function | ||
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 | ||
29395 | * @variation 2 | ||
29396 | */ | ||
29397 | // lookup(path: string, [parentAlreadyChecked: boolean]) | ||
29398 | |||
29399 | /** | ||
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 | ||
29405 | */ | ||
29406 | Namespace.prototype.lookupType = function lookupType(path) { | ||
29407 | var found = this.lookup(path, [ Type ]); | ||
29408 | if (!found) | ||
29409 | throw Error("no such type: " + path); | ||
29410 | return found; | ||
29411 | }; | ||
29412 | |||
29413 | /** | ||
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 | ||
29419 | */ | ||
29420 | Namespace.prototype.lookupEnum = function lookupEnum(path) { | ||
29421 | var found = this.lookup(path, [ Enum ]); | ||
29422 | if (!found) | ||
29423 | throw Error("no such Enum '" + path + "' in " + this); | ||
29424 | return found; | ||
29425 | }; | ||
29426 | |||
29427 | /** | ||
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 | ||
29433 | */ | ||
29434 | Namespace.prototype.lookupTypeOrEnum = function lookupTypeOrEnum(path) { | ||
29435 | var found = this.lookup(path, [ Type, Enum ]); | ||
29436 | if (!found) | ||
29437 | throw Error("no such Type or Enum '" + path + "' in " + this); | ||
29438 | return found; | ||
29439 | }; | ||
29440 | |||
29441 | /** | ||
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 | ||
29447 | */ | ||
29448 | Namespace.prototype.lookupService = function lookupService(path) { | ||
29449 | var found = this.lookup(path, [ Service ]); | ||
29450 | if (!found) | ||
29451 | throw Error("no such Service '" + path + "' in " + this); | ||
29452 | return found; | ||
29453 | }; | ||
29454 | |||
29455 | Namespace._configure = function(Type_, Service_) { | ||
29456 | Type = Type_; | ||
29457 | Service = Service_; | ||
29458 | }; | ||
29459 | |||
29460 | },{"./enum":196,"./field":197,"./object":205,"./util":218}],205:[function(require,module,exports){ | ||
29461 | "use strict"; | ||
29462 | module.exports = ReflectionObject; | ||
29463 | |||
29464 | ReflectionObject.className = "ReflectionObject"; | ||
29465 | |||
29466 | var util = require("./util"); | ||
29467 | |||
29468 | var Root; // cyclic | ||
29469 | |||
29470 | /** | ||
29471 | * Constructs a new reflection object instance. | ||
29472 | * @classdesc Base class of all reflection objects. | ||
29473 | * @constructor | ||
29474 | * @param {string} name Object name | ||
29475 | * @param {Object.<string,*>} [options] Declared options | ||
29476 | * @abstract | ||
29477 | */ | ||
29478 | function ReflectionObject(name, options) { | ||
29479 | |||
29480 | if (!util.isString(name)) | ||
29481 | throw TypeError("name must be a string"); | ||
29482 | |||
29483 | if (options && !util.isObject(options)) | ||
29484 | throw TypeError("options must be an object"); | ||
29485 | |||
29486 | /** | ||
29487 | * Options. | ||
29488 | * @type {Object.<string,*>|undefined} | ||
29489 | */ | ||
29490 | this.options = options; // toJSON | ||
29491 | |||
29492 | /** | ||
29493 | * Unique name within its namespace. | ||
29494 | * @type {string} | ||
29495 | */ | ||
29496 | this.name = name; | ||
29497 | |||
29498 | /** | ||
29499 | * Parent namespace. | ||
29500 | * @type {Namespace|null} | ||
29501 | */ | ||
29502 | this.parent = null; | ||
29503 | |||
29504 | /** | ||
29505 | * Whether already resolved or not. | ||
29506 | * @type {boolean} | ||
29507 | */ | ||
29508 | this.resolved = false; | ||
29509 | |||
29510 | /** | ||
29511 | * Comment text, if any. | ||
29512 | * @type {string|null} | ||
29513 | */ | ||
29514 | this.comment = null; | ||
29515 | |||
29516 | /** | ||
29517 | * Defining file name. | ||
29518 | * @type {string|null} | ||
29519 | */ | ||
29520 | this.filename = null; | ||
29521 | } | ||
29522 | |||
29523 | Object.defineProperties(ReflectionObject.prototype, { | ||
29524 | |||
29525 | /** | ||
29526 | * Reference to the root namespace. | ||
29527 | * @name ReflectionObject#root | ||
29528 | * @type {Root} | ||
29529 | * @readonly | ||
29530 | */ | ||
29531 | root: { | ||
29532 | get: function() { | ||
29533 | var ptr = this; | ||
29534 | while (ptr.parent !== null) | ||
29535 | ptr = ptr.parent; | ||
29536 | return ptr; | ||
29537 | } | ||
29538 | }, | ||
29539 | |||
29540 | /** | ||
29541 | * Full name including leading dot. | ||
29542 | * @name ReflectionObject#fullName | ||
29543 | * @type {string} | ||
29544 | * @readonly | ||
29545 | */ | ||
29546 | fullName: { | ||
29547 | get: function() { | ||
29548 | var path = [ this.name ], | ||
29549 | ptr = this.parent; | ||
29550 | while (ptr) { | ||
29551 | path.unshift(ptr.name); | ||
29552 | ptr = ptr.parent; | ||
29553 | } | ||
29554 | return path.join("."); | ||
29555 | } | ||
29556 | } | ||
29557 | }); | ||
29558 | |||
29559 | /** | ||
29560 | * Converts this reflection object to its descriptor representation. | ||
29561 | * @returns {Object.<string,*>} Descriptor | ||
29562 | * @abstract | ||
29563 | */ | ||
29564 | ReflectionObject.prototype.toJSON = /* istanbul ignore next */ function toJSON() { | ||
29565 | throw Error(); // not implemented, shouldn't happen | ||
29566 | }; | ||
29567 | |||
29568 | /** | ||
29569 | * Called when this object is added to a parent. | ||
29570 | * @param {ReflectionObject} parent Parent added to | ||
29571 | * @returns {undefined} | ||
29572 | */ | ||
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); | ||
29581 | }; | ||
29582 | |||
29583 | /** | ||
29584 | * Called when this object is removed from a parent. | ||
29585 | * @param {ReflectionObject} parent Parent removed from | ||
29586 | * @returns {undefined} | ||
29587 | */ | ||
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; | ||
29594 | }; | ||
29595 | |||
29596 | /** | ||
29597 | * Resolves this objects type references. | ||
29598 | * @returns {ReflectionObject} `this` | ||
29599 | */ | ||
29600 | ReflectionObject.prototype.resolve = function resolve() { | ||
29601 | if (this.resolved) | ||
29602 | return this; | ||
29603 | if (this.root instanceof Root) | ||
29604 | this.resolved = true; // only if part of a root | ||
29605 | return this; | ||
29606 | }; | ||
29607 | |||
29608 | /** | ||
29609 | * Gets an option value. | ||
29610 | * @param {string} name Option name | ||
29611 | * @returns {*} Option value or `undefined` if not set | ||
29612 | */ | ||
29613 | ReflectionObject.prototype.getOption = function getOption(name) { | ||
29614 | if (this.options) | ||
29615 | return this.options[name]; | ||
29616 | return undefined; | ||
29617 | }; | ||
29618 | |||
29619 | /** | ||
29620 | * Sets an option. | ||
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` | ||
29625 | */ | ||
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; | ||
29629 | return this; | ||
29630 | }; | ||
29631 | |||
29632 | /** | ||
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` | ||
29637 | */ | ||
29638 | ReflectionObject.prototype.setOptions = function setOptions(options, ifNotSet) { | ||
29639 | if (options) | ||
29640 | for (var keys = Object.keys(options), i = 0; i < keys.length; ++i) | ||
29641 | this.setOption(keys[i], options[keys[i]], ifNotSet); | ||
29642 | return this; | ||
29643 | }; | ||
29644 | |||
29645 | /** | ||
29646 | * Converts this instance to its string representation. | ||
29647 | * @returns {string} Class name[, space, full name] | ||
29648 | */ | ||
29649 | ReflectionObject.prototype.toString = function toString() { | ||
29650 | var className = this.constructor.className, | ||
29651 | fullName = this.fullName; | ||
29652 | if (fullName.length) | ||
29653 | return className + " " + fullName; | ||
29654 | return className; | ||
29655 | }; | ||
29656 | |||
29657 | ReflectionObject._configure = function(Root_) { | ||
29658 | Root = Root_; | ||
29659 | }; | ||
29660 | |||
29661 | },{"./util":218}],206:[function(require,module,exports){ | ||
29662 | "use strict"; | ||
29663 | module.exports = OneOf; | ||
29664 | |||
29665 | // extends ReflectionObject | ||
29666 | var ReflectionObject = require("./object"); | ||
29667 | ((OneOf.prototype = Object.create(ReflectionObject.prototype)).constructor = OneOf).className = "OneOf"; | ||
29668 | |||
29669 | var Field = require("./field"), | ||
29670 | util = require("./util"); | ||
29671 | |||
29672 | /** | ||
29673 | * Constructs a new oneof instance. | ||
29674 | * @classdesc Reflected oneof. | ||
29675 | * @extends ReflectionObject | ||
29676 | * @constructor | ||
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 | ||
29681 | */ | ||
29682 | function OneOf(name, fieldNames, options, comment) { | ||
29683 | if (!Array.isArray(fieldNames)) { | ||
29684 | options = fieldNames; | ||
29685 | fieldNames = undefined; | ||
29686 | } | ||
29687 | ReflectionObject.call(this, name, options); | ||
29688 | |||
29689 | /* istanbul ignore if */ | ||
29690 | if (!(fieldNames === undefined || Array.isArray(fieldNames))) | ||
29691 | throw TypeError("fieldNames must be an Array"); | ||
29692 | |||
29693 | /** | ||
29694 | * Field names that belong to this oneof. | ||
29695 | * @type {string[]} | ||
29696 | */ | ||
29697 | this.oneof = fieldNames || []; // toJSON, marker | ||
29698 | |||
29699 | /** | ||
29700 | * Fields that belong to this oneof as an array for iteration. | ||
29701 | * @type {Field[]} | ||
29702 | * @readonly | ||
29703 | */ | ||
29704 | this.fieldsArray = []; // declared readonly for conformance, possibly not yet added to parent | ||
29705 | |||
29706 | /** | ||
29707 | * Comment for this field. | ||
29708 | * @type {string|null} | ||
29709 | */ | ||
29710 | this.comment = comment; | ||
29711 | } | ||
29712 | |||
29713 | /** | ||
29714 | * Oneof descriptor. | ||
29715 | * @interface IOneOf | ||
29716 | * @property {Array.<string>} oneof Oneof field names | ||
29717 | * @property {Object.<string,*>} [options] Oneof options | ||
29718 | */ | ||
29719 | |||
29720 | /** | ||
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 | ||
29726 | */ | ||
29727 | OneOf.fromJSON = function fromJSON(name, json) { | ||
29728 | return new OneOf(name, json.oneof, json.options, json.comment); | ||
29729 | }; | ||
29730 | |||
29731 | /** | ||
29732 | * Converts this oneof to a oneof descriptor. | ||
29733 | * @param {IToJSONOptions} [toJSONOptions] JSON conversion options | ||
29734 | * @returns {IOneOf} Oneof descriptor | ||
29735 | */ | ||
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 | ||
29742 | ]); | ||
29743 | }; | ||
29744 | |||
29745 | /** | ||
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} | ||
29749 | * @inner | ||
29750 | * @ignore | ||
29751 | */ | ||
29752 | function addFieldsToParent(oneof) { | ||
29753 | if (oneof.parent) | ||
29754 | for (var i = 0; i < oneof.fieldsArray.length; ++i) | ||
29755 | if (!oneof.fieldsArray[i].parent) | ||
29756 | oneof.parent.add(oneof.fieldsArray[i]); | ||
29757 | } | ||
29758 | |||
29759 | /** | ||
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` | ||
29763 | */ | ||
29764 | OneOf.prototype.add = function add(field) { | ||
29765 | |||
29766 | /* istanbul ignore if */ | ||
29767 | if (!(field instanceof Field)) | ||
29768 | throw TypeError("field must be a Field"); | ||
29769 | |||
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); | ||
29776 | return this; | ||
29777 | }; | ||
29778 | |||
29779 | /** | ||
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` | ||
29783 | */ | ||
29784 | OneOf.prototype.remove = function remove(field) { | ||
29785 | |||
29786 | /* istanbul ignore if */ | ||
29787 | if (!(field instanceof Field)) | ||
29788 | throw TypeError("field must be a Field"); | ||
29789 | |||
29790 | var index = this.fieldsArray.indexOf(field); | ||
29791 | |||
29792 | /* istanbul ignore if */ | ||
29793 | if (index < 0) | ||
29794 | throw Error(field + " is not a member of " + this); | ||
29795 | |||
29796 | this.fieldsArray.splice(index, 1); | ||
29797 | index = this.oneof.indexOf(field.name); | ||
29798 | |||
29799 | /* istanbul ignore else */ | ||
29800 | if (index > -1) // theoretical | ||
29801 | this.oneof.splice(index, 1); | ||
29802 | |||
29803 | field.partOf = null; | ||
29804 | return this; | ||
29805 | }; | ||
29806 | |||
29807 | /** | ||
29808 | * @override | ||
29809 | */ | ||
29810 | OneOf.prototype.onAdd = function onAdd(parent) { | ||
29811 | ReflectionObject.prototype.onAdd.call(this, parent); | ||
29812 | var self = this; | ||
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); | ||
29819 | } | ||
29820 | } | ||
29821 | // Add not yet present fields | ||
29822 | addFieldsToParent(this); | ||
29823 | }; | ||
29824 | |||
29825 | /** | ||
29826 | * @override | ||
29827 | */ | ||
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); | ||
29833 | }; | ||
29834 | |||
29835 | /** | ||
29836 | * Decorator function as returned by {@link OneOf.d} (TypeScript). | ||
29837 | * @typedef OneOfDecorator | ||
29838 | * @type {function} | ||
29839 | * @param {Object} prototype Target prototype | ||
29840 | * @param {string} oneofName OneOf name | ||
29841 | * @returns {undefined} | ||
29842 | */ | ||
29843 | |||
29844 | /** | ||
29845 | * OneOf decorator (TypeScript). | ||
29846 | * @function | ||
29847 | * @param {...string} fieldNames Field names | ||
29848 | * @returns {OneOfDecorator} Decorator function | ||
29849 | * @template T extends string | ||
29850 | */ | ||
29851 | OneOf.d = function decorateOneOf() { | ||
29852 | var fieldNames = new Array(arguments.length), | ||
29853 | index = 0; | ||
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) | ||
29862 | }); | ||
29863 | }; | ||
29864 | }; | ||
29865 | |||
29866 | },{"./field":197,"./object":205,"./util":218}],207:[function(require,module,exports){ | ||
29867 | "use strict"; | ||
29868 | module.exports = parse; | ||
29869 | |||
29870 | parse.filename = null; | ||
29871 | parse.defaults = { keepCase: false }; | ||
29872 | |||
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"); | ||
29884 | |||
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]*)+$/; | ||
29895 | |||
29896 | /** | ||
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 | ||
29904 | */ | ||
29905 | |||
29906 | /** | ||
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. | ||
29911 | */ | ||
29912 | |||
29913 | /** | ||
29914 | * Options modifying the behavior of JSON serialization. | ||
29915 | * @interface IToJSONOptions | ||
29916 | * @property {boolean} [keepComments=false] Serializes comments. | ||
29917 | */ | ||
29918 | |||
29919 | /** | ||
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} | ||
29927 | */ | ||
29928 | function parse(source, root, options) { | ||
29929 | /* eslint-disable callback-return */ | ||
29930 | if (!(root instanceof Root)) { | ||
29931 | options = root; | ||
29932 | root = new Root(); | ||
29933 | } | ||
29934 | if (!options) | ||
29935 | options = parse.defaults; | ||
29936 | |||
29937 | var tn = tokenize(source, options.alternateCommentMode || false), | ||
29938 | next = tn.next, | ||
29939 | push = tn.push, | ||
29940 | peek = tn.peek, | ||
29941 | skip = tn.skip, | ||
29942 | cmnt = tn.cmnt; | ||
29943 | |||
29944 | var head = true, | ||
29945 | pkg, | ||
29946 | imports, | ||
29947 | weakImports, | ||
29948 | syntax, | ||
29949 | isProto3 = false; | ||
29950 | |||
29951 | var ptr = root; | ||
29952 | |||
29953 | var applyCase = options.keepCase ? function(name) { return name; } : util.camelCase; | ||
29954 | |||
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 + ")"); | ||
29961 | } | ||
29962 | |||
29963 | function readString() { | ||
29964 | var values = [], | ||
29965 | token; | ||
29966 | do { | ||
29967 | /* istanbul ignore if */ | ||
29968 | if ((token = next()) !== "\"" && token !== "'") | ||
29969 | throw illegal(token); | ||
29970 | |||
29971 | values.push(next()); | ||
29972 | skip(token); | ||
29973 | token = peek(); | ||
29974 | } while (token === "\"" || token === "'"); | ||
29975 | return values.join(""); | ||
29976 | } | ||
29977 | |||
29978 | function readValue(acceptTypeRef) { | ||
29979 | var token = next(); | ||
29980 | switch (token) { | ||
29981 | case "'": | ||
29982 | case "\"": | ||
29983 | push(token); | ||
29984 | return readString(); | ||
29985 | case "true": case "TRUE": | ||
29986 | return true; | ||
29987 | case "false": case "FALSE": | ||
29988 | return false; | ||
29989 | } | ||
29990 | try { | ||
29991 | return parseNumber(token, /* insideTryCatch */ true); | ||
29992 | } catch (e) { | ||
29993 | |||
29994 | /* istanbul ignore else */ | ||
29995 | if (acceptTypeRef && typeRefRe.test(token)) | ||
29996 | return token; | ||
29997 | |||
29998 | /* istanbul ignore next */ | ||
29999 | throw illegal(token, "value"); | ||
30000 | } | ||
30001 | } | ||
30002 | |||
30003 | function readRanges(target, acceptStrings) { | ||
30004 | var token, start; | ||
30005 | do { | ||
30006 | if (acceptStrings && ((token = peek()) === "\"" || token === "'")) | ||
30007 | target.push(readString()); | ||
30008 | else | ||
30009 | target.push([ start = parseId(next()), skip("to", true) ? parseId(next()) : start ]); | ||
30010 | } while (skip(",", true)); | ||
30011 | skip(";"); | ||
30012 | } | ||
30013 | |||
30014 | function parseNumber(token, insideTryCatch) { | ||
30015 | var sign = 1; | ||
30016 | if (token.charAt(0) === "-") { | ||
30017 | sign = -1; | ||
30018 | token = token.substring(1); | ||
30019 | } | ||
30020 | switch (token) { | ||
30021 | case "inf": case "INF": case "Inf": | ||
30022 | return sign * Infinity; | ||
30023 | case "nan": case "NAN": case "Nan": case "NaN": | ||
30024 | return NaN; | ||
30025 | case "0": | ||
30026 | return 0; | ||
30027 | } | ||
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); | ||
30034 | |||
30035 | /* istanbul ignore else */ | ||
30036 | if (numberRe.test(token)) | ||
30037 | return sign * parseFloat(token); | ||
30038 | |||
30039 | /* istanbul ignore next */ | ||
30040 | throw illegal(token, "number", insideTryCatch); | ||
30041 | } | ||
30042 | |||
30043 | function parseId(token, acceptNegative) { | ||
30044 | switch (token) { | ||
30045 | case "max": case "MAX": case "Max": | ||
30046 | return 536870911; | ||
30047 | case "0": | ||
30048 | return 0; | ||
30049 | } | ||
30050 | |||
30051 | /* istanbul ignore if */ | ||
30052 | if (!acceptNegative && token.charAt(0) === "-") | ||
30053 | throw illegal(token, "id"); | ||
30054 | |||
30055 | if (base10NegRe.test(token)) | ||
30056 | return parseInt(token, 10); | ||
30057 | if (base16NegRe.test(token)) | ||
30058 | return parseInt(token, 16); | ||
30059 | |||
30060 | /* istanbul ignore else */ | ||
30061 | if (base8NegRe.test(token)) | ||
30062 | return parseInt(token, 8); | ||
30063 | |||
30064 | /* istanbul ignore next */ | ||
30065 | throw illegal(token, "id"); | ||
30066 | } | ||
30067 | |||
30068 | function parsePackage() { | ||
30069 | |||
30070 | /* istanbul ignore if */ | ||
30071 | if (pkg !== undefined) | ||
30072 | throw illegal("package"); | ||
30073 | |||
30074 | pkg = next(); | ||
30075 | |||
30076 | /* istanbul ignore if */ | ||
30077 | if (!typeRefRe.test(pkg)) | ||
30078 | throw illegal(pkg, "name"); | ||
30079 | |||
30080 | ptr = ptr.define(pkg); | ||
30081 | skip(";"); | ||
30082 | } | ||
30083 | |||
30084 | function parseImport() { | ||
30085 | var token = peek(); | ||
30086 | var whichImports; | ||
30087 | switch (token) { | ||
30088 | case "weak": | ||
30089 | whichImports = weakImports || (weakImports = []); | ||
30090 | next(); | ||
30091 | break; | ||
30092 | case "public": | ||
30093 | next(); | ||
30094 | // eslint-disable-line no-fallthrough | ||
30095 | default: | ||
30096 | whichImports = imports || (imports = []); | ||
30097 | break; | ||
30098 | } | ||
30099 | token = readString(); | ||
30100 | skip(";"); | ||
30101 | whichImports.push(token); | ||
30102 | } | ||
30103 | |||
30104 | function parseSyntax() { | ||
30105 | skip("="); | ||
30106 | syntax = readString(); | ||
30107 | isProto3 = syntax === "proto3"; | ||
30108 | |||
30109 | /* istanbul ignore if */ | ||
30110 | if (!isProto3 && syntax !== "proto2") | ||
30111 | throw illegal(syntax, "syntax"); | ||
30112 | |||
30113 | skip(";"); | ||
30114 | } | ||
30115 | |||
30116 | function parseCommon(parent, token) { | ||
30117 | switch (token) { | ||
30118 | |||
30119 | case "option": | ||
30120 | parseOption(parent, token); | ||
30121 | skip(";"); | ||
30122 | return true; | ||
30123 | |||
30124 | case "message": | ||
30125 | parseType(parent, token); | ||
30126 | return true; | ||
30127 | |||
30128 | case "enum": | ||
30129 | parseEnum(parent, token); | ||
30130 | return true; | ||
30131 | |||
30132 | case "service": | ||
30133 | parseService(parent, token); | ||
30134 | return true; | ||
30135 | |||
30136 | case "extend": | ||
30137 | parseExtension(parent, token); | ||
30138 | return true; | ||
30139 | } | ||
30140 | return false; | ||
30141 | } | ||
30142 | |||
30143 | function ifBlock(obj, fnIf, fnElse) { | ||
30144 | var trailingLine = tn.line; | ||
30145 | if (obj) { | ||
30146 | obj.comment = cmnt(); // try block-type comment | ||
30147 | obj.filename = parse.filename; | ||
30148 | } | ||
30149 | if (skip("{", true)) { | ||
30150 | var token; | ||
30151 | while ((token = next()) !== "}") | ||
30152 | fnIf(token); | ||
30153 | skip(";", true); | ||
30154 | } else { | ||
30155 | if (fnElse) | ||
30156 | fnElse(); | ||
30157 | skip(";"); | ||
30158 | if (obj && typeof obj.comment !== "string") | ||
30159 | obj.comment = cmnt(trailingLine); // try line-type comment if no block | ||
30160 | } | ||
30161 | } | ||
30162 | |||
30163 | function parseType(parent, token) { | ||
30164 | |||
30165 | /* istanbul ignore if */ | ||
30166 | if (!nameRe.test(token = next())) | ||
30167 | throw illegal(token, "type name"); | ||
30168 | |||
30169 | var type = new Type(token); | ||
30170 | ifBlock(type, function parseType_block(token) { | ||
30171 | if (parseCommon(type, token)) | ||
30172 | return; | ||
30173 | |||
30174 | switch (token) { | ||
30175 | |||
30176 | case "map": | ||
30177 | parseMapField(type, token); | ||
30178 | break; | ||
30179 | |||
30180 | case "required": | ||
30181 | case "optional": | ||
30182 | case "repeated": | ||
30183 | parseField(type, token); | ||
30184 | break; | ||
30185 | |||
30186 | case "oneof": | ||
30187 | parseOneOf(type, token); | ||
30188 | break; | ||
30189 | |||
30190 | case "extensions": | ||
30191 | readRanges(type.extensions || (type.extensions = [])); | ||
30192 | break; | ||
30193 | |||
30194 | case "reserved": | ||
30195 | readRanges(type.reserved || (type.reserved = []), true); | ||
30196 | break; | ||
30197 | |||
30198 | default: | ||
30199 | /* istanbul ignore if */ | ||
30200 | if (!isProto3 || !typeRefRe.test(token)) | ||
30201 | throw illegal(token); | ||
30202 | |||
30203 | push(token); | ||
30204 | parseField(type, "optional"); | ||
30205 | break; | ||
30206 | } | ||
30207 | }); | ||
30208 | parent.add(type); | ||
30209 | } | ||
30210 | |||
30211 | function parseField(parent, rule, extend) { | ||
30212 | var type = next(); | ||
30213 | if (type === "group") { | ||
30214 | parseGroup(parent, rule); | ||
30215 | return; | ||
30216 | } | ||
30217 | |||
30218 | /* istanbul ignore if */ | ||
30219 | if (!typeRefRe.test(type)) | ||
30220 | throw illegal(type, "type"); | ||
30221 | |||
30222 | var name = next(); | ||
30223 | |||
30224 | /* istanbul ignore if */ | ||
30225 | if (!nameRe.test(name)) | ||
30226 | throw illegal(name, "name"); | ||
30227 | |||
30228 | name = applyCase(name); | ||
30229 | skip("="); | ||
30230 | |||
30231 | var field = new Field(name, parseId(next()), type, rule, extend); | ||
30232 | ifBlock(field, function parseField_block(token) { | ||
30233 | |||
30234 | /* istanbul ignore else */ | ||
30235 | if (token === "option") { | ||
30236 | parseOption(field, token); | ||
30237 | skip(";"); | ||
30238 | } else | ||
30239 | throw illegal(token); | ||
30240 | |||
30241 | }, function parseField_line() { | ||
30242 | parseInlineOptions(field); | ||
30243 | }); | ||
30244 | parent.add(field); | ||
30245 | |||
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); | ||
30251 | } | ||
30252 | |||
30253 | function parseGroup(parent, rule) { | ||
30254 | var name = next(); | ||
30255 | |||
30256 | /* istanbul ignore if */ | ||
30257 | if (!nameRe.test(name)) | ||
30258 | throw illegal(name, "name"); | ||
30259 | |||
30260 | var fieldName = util.lcFirst(name); | ||
30261 | if (name === fieldName) | ||
30262 | name = util.ucFirst(name); | ||
30263 | skip("="); | ||
30264 | var id = parseId(next()); | ||
30265 | var type = new Type(name); | ||
30266 | type.group = true; | ||
30267 | var field = new Field(fieldName, id, name, rule); | ||
30268 | field.filename = parse.filename; | ||
30269 | ifBlock(type, function parseGroup_block(token) { | ||
30270 | switch (token) { | ||
30271 | |||
30272 | case "option": | ||
30273 | parseOption(type, token); | ||
30274 | skip(";"); | ||
30275 | break; | ||
30276 | |||
30277 | case "required": | ||
30278 | case "optional": | ||
30279 | case "repeated": | ||
30280 | parseField(type, token); | ||
30281 | break; | ||
30282 | |||
30283 | /* istanbul ignore next */ | ||
30284 | default: | ||
30285 | throw illegal(token); // there are no groups with proto3 semantics | ||
30286 | } | ||
30287 | }); | ||
30288 | parent.add(type) | ||
30289 | .add(field); | ||
30290 | } | ||
30291 | |||
30292 | function parseMapField(parent) { | ||
30293 | skip("<"); | ||
30294 | var keyType = next(); | ||
30295 | |||
30296 | /* istanbul ignore if */ | ||
30297 | if (types.mapKey[keyType] === undefined) | ||
30298 | throw illegal(keyType, "type"); | ||
30299 | |||
30300 | skip(","); | ||
30301 | var valueType = next(); | ||
30302 | |||
30303 | /* istanbul ignore if */ | ||
30304 | if (!typeRefRe.test(valueType)) | ||
30305 | throw illegal(valueType, "type"); | ||
30306 | |||
30307 | skip(">"); | ||
30308 | var name = next(); | ||
30309 | |||
30310 | /* istanbul ignore if */ | ||
30311 | if (!nameRe.test(name)) | ||
30312 | throw illegal(name, "name"); | ||
30313 | |||
30314 | skip("="); | ||
30315 | var field = new MapField(applyCase(name), parseId(next()), keyType, valueType); | ||
30316 | ifBlock(field, function parseMapField_block(token) { | ||
30317 | |||
30318 | /* istanbul ignore else */ | ||
30319 | if (token === "option") { | ||
30320 | parseOption(field, token); | ||
30321 | skip(";"); | ||
30322 | } else | ||
30323 | throw illegal(token); | ||
30324 | |||
30325 | }, function parseMapField_line() { | ||
30326 | parseInlineOptions(field); | ||
30327 | }); | ||
30328 | parent.add(field); | ||
30329 | } | ||
30330 | |||
30331 | function parseOneOf(parent, token) { | ||
30332 | |||
30333 | /* istanbul ignore if */ | ||
30334 | if (!nameRe.test(token = next())) | ||
30335 | throw illegal(token, "name"); | ||
30336 | |||
30337 | var oneof = new OneOf(applyCase(token)); | ||
30338 | ifBlock(oneof, function parseOneOf_block(token) { | ||
30339 | if (token === "option") { | ||
30340 | parseOption(oneof, token); | ||
30341 | skip(";"); | ||
30342 | } else { | ||
30343 | push(token); | ||
30344 | parseField(oneof, "optional"); | ||
30345 | } | ||
30346 | }); | ||
30347 | parent.add(oneof); | ||
30348 | } | ||
30349 | |||
30350 | function parseEnum(parent, token) { | ||
30351 | |||
30352 | /* istanbul ignore if */ | ||
30353 | if (!nameRe.test(token = next())) | ||
30354 | throw illegal(token, "name"); | ||
30355 | |||
30356 | var enm = new Enum(token); | ||
30357 | ifBlock(enm, function parseEnum_block(token) { | ||
30358 | switch(token) { | ||
30359 | case "option": | ||
30360 | parseOption(enm, token); | ||
30361 | skip(";"); | ||
30362 | break; | ||
30363 | |||
30364 | case "reserved": | ||
30365 | readRanges(enm.reserved || (enm.reserved = []), true); | ||
30366 | break; | ||
30367 | |||
30368 | default: | ||
30369 | parseEnumValue(enm, token); | ||
30370 | } | ||
30371 | }); | ||
30372 | parent.add(enm); | ||
30373 | } | ||
30374 | |||
30375 | function parseEnumValue(parent, token) { | ||
30376 | |||
30377 | /* istanbul ignore if */ | ||
30378 | if (!nameRe.test(token)) | ||
30379 | throw illegal(token, "name"); | ||
30380 | |||
30381 | skip("="); | ||
30382 | var value = parseId(next(), true), | ||
30383 | dummy = {}; | ||
30384 | ifBlock(dummy, function parseEnumValue_block(token) { | ||
30385 | |||
30386 | /* istanbul ignore else */ | ||
30387 | if (token === "option") { | ||
30388 | parseOption(dummy, token); // skip | ||
30389 | skip(";"); | ||
30390 | } else | ||
30391 | throw illegal(token); | ||
30392 | |||
30393 | }, function parseEnumValue_line() { | ||
30394 | parseInlineOptions(dummy); // skip | ||
30395 | }); | ||
30396 | parent.add(token, value, dummy.comment); | ||
30397 | } | ||
30398 | |||
30399 | function parseOption(parent, token) { | ||
30400 | var isCustom = skip("(", true); | ||
30401 | |||
30402 | /* istanbul ignore if */ | ||
30403 | if (!typeRefRe.test(token = next())) | ||
30404 | throw illegal(token, "name"); | ||
30405 | |||
30406 | var name = token; | ||
30407 | if (isCustom) { | ||
30408 | skip(")"); | ||
30409 | name = "(" + name + ")"; | ||
30410 | token = peek(); | ||
30411 | if (fqTypeRefRe.test(token)) { | ||
30412 | name += token; | ||
30413 | next(); | ||
30414 | } | ||
30415 | } | ||
30416 | skip("="); | ||
30417 | parseOptionValue(parent, name); | ||
30418 | } | ||
30419 | |||
30420 | function parseOptionValue(parent, name) { | ||
30421 | if (skip("{", true)) { // { a: "foo" b { c: "bar" } } | ||
30422 | do { | ||
30423 | /* istanbul ignore if */ | ||
30424 | if (!nameRe.test(token = next())) | ||
30425 | throw illegal(token, "name"); | ||
30426 | |||
30427 | if (peek() === "{") | ||
30428 | parseOptionValue(parent, name + "." + token); | ||
30429 | else { | ||
30430 | skip(":"); | ||
30431 | if (peek() === "{") | ||
30432 | parseOptionValue(parent, name + "." + token); | ||
30433 | else | ||
30434 | setOption(parent, name + "." + token, readValue(true)); | ||
30435 | } | ||
30436 | } while (!skip("}", true)); | ||
30437 | } else | ||
30438 | setOption(parent, name, readValue(true)); | ||
30439 | // Does not enforce a delimiter to be universal | ||
30440 | } | ||
30441 | |||
30442 | function setOption(parent, name, value) { | ||
30443 | if (parent.setOption) | ||
30444 | parent.setOption(name, value); | ||
30445 | } | ||
30446 | |||
30447 | function parseInlineOptions(parent) { | ||
30448 | if (skip("[", true)) { | ||
30449 | do { | ||
30450 | parseOption(parent, "option"); | ||
30451 | } while (skip(",", true)); | ||
30452 | skip("]"); | ||
30453 | } | ||
30454 | return parent; | ||
30455 | } | ||
30456 | |||
30457 | function parseService(parent, token) { | ||
30458 | |||
30459 | /* istanbul ignore if */ | ||
30460 | if (!nameRe.test(token = next())) | ||
30461 | throw illegal(token, "service name"); | ||
30462 | |||
30463 | var service = new Service(token); | ||
30464 | ifBlock(service, function parseService_block(token) { | ||
30465 | if (parseCommon(service, token)) | ||
30466 | return; | ||
30467 | |||
30468 | /* istanbul ignore else */ | ||
30469 | if (token === "rpc") | ||
30470 | parseMethod(service, token); | ||
30471 | else | ||
30472 | throw illegal(token); | ||
30473 | }); | ||
30474 | parent.add(service); | ||
30475 | } | ||
30476 | |||
30477 | function parseMethod(parent, token) { | ||
30478 | var type = token; | ||
30479 | |||
30480 | /* istanbul ignore if */ | ||
30481 | if (!nameRe.test(token = next())) | ||
30482 | throw illegal(token, "name"); | ||
30483 | |||
30484 | var name = token, | ||
30485 | requestType, requestStream, | ||
30486 | responseType, responseStream; | ||
30487 | |||
30488 | skip("("); | ||
30489 | if (skip("stream", true)) | ||
30490 | requestStream = true; | ||
30491 | |||
30492 | /* istanbul ignore if */ | ||
30493 | if (!typeRefRe.test(token = next())) | ||
30494 | throw illegal(token); | ||
30495 | |||
30496 | requestType = token; | ||
30497 | skip(")"); skip("returns"); skip("("); | ||
30498 | if (skip("stream", true)) | ||
30499 | responseStream = true; | ||
30500 | |||
30501 | /* istanbul ignore if */ | ||
30502 | if (!typeRefRe.test(token = next())) | ||
30503 | throw illegal(token); | ||
30504 | |||
30505 | responseType = token; | ||
30506 | skip(")"); | ||
30507 | |||
30508 | var method = new Method(name, type, requestType, responseType, requestStream, responseStream); | ||
30509 | ifBlock(method, function parseMethod_block(token) { | ||
30510 | |||
30511 | /* istanbul ignore else */ | ||
30512 | if (token === "option") { | ||
30513 | parseOption(method, token); | ||
30514 | skip(";"); | ||
30515 | } else | ||
30516 | throw illegal(token); | ||
30517 | |||
30518 | }); | ||
30519 | parent.add(method); | ||
30520 | } | ||
30521 | |||
30522 | function parseExtension(parent, token) { | ||
30523 | |||
30524 | /* istanbul ignore if */ | ||
30525 | if (!typeRefRe.test(token = next())) | ||
30526 | throw illegal(token, "reference"); | ||
30527 | |||
30528 | var reference = token; | ||
30529 | ifBlock(null, function parseExtension_block(token) { | ||
30530 | switch (token) { | ||
30531 | |||
30532 | case "required": | ||
30533 | case "repeated": | ||
30534 | case "optional": | ||
30535 | parseField(parent, token, reference); | ||
30536 | break; | ||
30537 | |||
30538 | default: | ||
30539 | /* istanbul ignore if */ | ||
30540 | if (!isProto3 || !typeRefRe.test(token)) | ||
30541 | throw illegal(token); | ||
30542 | push(token); | ||
30543 | parseField(parent, "optional", reference); | ||
30544 | break; | ||
30545 | } | ||
30546 | }); | ||
30547 | } | ||
30548 | |||
30549 | var token; | ||
30550 | while ((token = next()) !== null) { | ||
30551 | switch (token) { | ||
30552 | |||
30553 | case "package": | ||
30554 | |||
30555 | /* istanbul ignore if */ | ||
30556 | if (!head) | ||
30557 | throw illegal(token); | ||
30558 | |||
30559 | parsePackage(); | ||
30560 | break; | ||
30561 | |||
30562 | case "import": | ||
30563 | |||
30564 | /* istanbul ignore if */ | ||
30565 | if (!head) | ||
30566 | throw illegal(token); | ||
30567 | |||
30568 | parseImport(); | ||
30569 | break; | ||
30570 | |||
30571 | case "syntax": | ||
30572 | |||
30573 | /* istanbul ignore if */ | ||
30574 | if (!head) | ||
30575 | throw illegal(token); | ||
30576 | |||
30577 | parseSyntax(); | ||
30578 | break; | ||
30579 | |||
30580 | case "option": | ||
30581 | |||
30582 | /* istanbul ignore if */ | ||
30583 | if (!head) | ||
30584 | throw illegal(token); | ||
30585 | |||
30586 | parseOption(ptr, token); | ||
30587 | skip(";"); | ||
30588 | break; | ||
30589 | |||
30590 | default: | ||
30591 | |||
30592 | /* istanbul ignore else */ | ||
30593 | if (parseCommon(ptr, token)) { | ||
30594 | head = false; | ||
30595 | continue; | ||
30596 | } | ||
30597 | |||
30598 | /* istanbul ignore next */ | ||
30599 | throw illegal(token); | ||
30600 | } | ||
30601 | } | ||
30602 | |||
30603 | parse.filename = null; | ||
30604 | return { | ||
30605 | "package" : pkg, | ||
30606 | "imports" : imports, | ||
30607 | weakImports : weakImports, | ||
30608 | syntax : syntax, | ||
30609 | root : root | ||
30610 | }; | ||
30611 | } | ||
30612 | |||
30613 | /** | ||
30614 | * Parses the given .proto source and returns an object with the parsed contents. | ||
30615 | * @name parse | ||
30616 | * @function | ||
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} | ||
30622 | * @variation 2 | ||
30623 | */ | ||
30624 | |||
30625 | },{"./enum":196,"./field":197,"./mapfield":201,"./method":203,"./oneof":206,"./root":210,"./service":214,"./tokenize":215,"./type":216,"./types":217,"./util":218}],208:[function(require,module,exports){ | ||
30626 | "use strict"; | ||
30627 | module.exports = Reader; | ||
30628 | |||
30629 | var util = require("./util/minimal"); | ||
30630 | |||
30631 | var BufferReader; // cyclic | ||
30632 | |||
30633 | var LongBits = util.LongBits, | ||
30634 | utf8 = util.utf8; | ||
30635 | |||
30636 | /* istanbul ignore next */ | ||
30637 | function indexOutOfRange(reader, writeLength) { | ||
30638 | return RangeError("index out of range: " + reader.pos + " + " + (writeLength || 1) + " > " + reader.len); | ||
30639 | } | ||
30640 | |||
30641 | /** | ||
30642 | * Constructs a new reader instance using the specified buffer. | ||
30643 | * @classdesc Wire format reader using `Uint8Array` if available, otherwise `Array`. | ||
30644 | * @constructor | ||
30645 | * @param {Uint8Array} buffer Buffer to read from | ||
30646 | */ | ||
30647 | function Reader(buffer) { | ||
30648 | |||
30649 | /** | ||
30650 | * Read buffer. | ||
30651 | * @type {Uint8Array} | ||
30652 | */ | ||
30653 | this.buf = buffer; | ||
30654 | |||
30655 | /** | ||
30656 | * Read buffer position. | ||
30657 | * @type {number} | ||
30658 | */ | ||
30659 | this.pos = 0; | ||
30660 | |||
30661 | /** | ||
30662 | * Read buffer length. | ||
30663 | * @type {number} | ||
30664 | */ | ||
30665 | this.len = buffer.length; | ||
30666 | } | ||
30667 | |||
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"); | ||
30673 | } | ||
30674 | /* istanbul ignore next */ | ||
30675 | : function create_array(buffer) { | ||
30676 | if (Array.isArray(buffer)) | ||
30677 | return new Reader(buffer); | ||
30678 | throw Error("illegal buffer"); | ||
30679 | }; | ||
30680 | |||
30681 | /** | ||
30682 | * Creates a new reader using the specified buffer. | ||
30683 | * @function | ||
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 | ||
30687 | */ | ||
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); | ||
30695 | })(buffer); | ||
30696 | } | ||
30697 | /* istanbul ignore next */ | ||
30698 | : create_array; | ||
30699 | |||
30700 | Reader.prototype._slice = util.Array.prototype.subarray || /* istanbul ignore next */ util.Array.prototype.slice; | ||
30701 | |||
30702 | /** | ||
30703 | * Reads a varint as an unsigned 32 bit value. | ||
30704 | * @function | ||
30705 | * @returns {number} Value read | ||
30706 | */ | ||
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; | ||
30715 | |||
30716 | /* istanbul ignore if */ | ||
30717 | if ((this.pos += 5) > this.len) { | ||
30718 | this.pos = this.len; | ||
30719 | throw indexOutOfRange(this, 10); | ||
30720 | } | ||
30721 | return value; | ||
30722 | }; | ||
30723 | })(); | ||
30724 | |||
30725 | /** | ||
30726 | * Reads a varint as a signed 32 bit value. | ||
30727 | * @returns {number} Value read | ||
30728 | */ | ||
30729 | Reader.prototype.int32 = function read_int32() { | ||
30730 | return this.uint32() | 0; | ||
30731 | }; | ||
30732 | |||
30733 | /** | ||
30734 | * Reads a zig-zag encoded varint as a signed 32 bit value. | ||
30735 | * @returns {number} Value read | ||
30736 | */ | ||
30737 | Reader.prototype.sint32 = function read_sint32() { | ||
30738 | var value = this.uint32(); | ||
30739 | return value >>> 1 ^ -(value & 1) | 0; | ||
30740 | }; | ||
30741 | |||
30742 | /* eslint-disable no-invalid-this */ | ||
30743 | |||
30744 | function readLongVarint() { | ||
30745 | // tends to deopt with local vars for octet etc. | ||
30746 | var bits = new LongBits(0, 0); | ||
30747 | var i = 0; | ||
30748 | if (this.len - this.pos > 4) { // fast route (lo) | ||
30749 | for (; i < 4; ++i) { | ||
30750 | // 1st..4th | ||
30751 | bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; | ||
30752 | if (this.buf[this.pos++] < 128) | ||
30753 | return bits; | ||
30754 | } | ||
30755 | // 5th | ||
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) | ||
30759 | return bits; | ||
30760 | i = 0; | ||
30761 | } else { | ||
30762 | for (; i < 3; ++i) { | ||
30763 | /* istanbul ignore if */ | ||
30764 | if (this.pos >= this.len) | ||
30765 | throw indexOutOfRange(this); | ||
30766 | // 1st..3th | ||
30767 | bits.lo = (bits.lo | (this.buf[this.pos] & 127) << i * 7) >>> 0; | ||
30768 | if (this.buf[this.pos++] < 128) | ||
30769 | return bits; | ||
30770 | } | ||
30771 | // 4th | ||
30772 | bits.lo = (bits.lo | (this.buf[this.pos++] & 127) << i * 7) >>> 0; | ||
30773 | return bits; | ||
30774 | } | ||
30775 | if (this.len - this.pos > 4) { // fast route (hi) | ||
30776 | for (; i < 5; ++i) { | ||
30777 | // 6th..10th | ||
30778 | bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; | ||
30779 | if (this.buf[this.pos++] < 128) | ||
30780 | return bits; | ||
30781 | } | ||
30782 | } else { | ||
30783 | for (; i < 5; ++i) { | ||
30784 | /* istanbul ignore if */ | ||
30785 | if (this.pos >= this.len) | ||
30786 | throw indexOutOfRange(this); | ||
30787 | // 6th..10th | ||
30788 | bits.hi = (bits.hi | (this.buf[this.pos] & 127) << i * 7 + 3) >>> 0; | ||
30789 | if (this.buf[this.pos++] < 128) | ||
30790 | return bits; | ||
30791 | } | ||
30792 | } | ||
30793 | /* istanbul ignore next */ | ||
30794 | throw Error("invalid varint encoding"); | ||
30795 | } | ||
30796 | |||
30797 | /* eslint-enable no-invalid-this */ | ||
30798 | |||
30799 | /** | ||
30800 | * Reads a varint as a signed 64 bit value. | ||
30801 | * @name Reader#int64 | ||
30802 | * @function | ||
30803 | * @returns {Long} Value read | ||
30804 | */ | ||
30805 | |||
30806 | /** | ||
30807 | * Reads a varint as an unsigned 64 bit value. | ||
30808 | * @name Reader#uint64 | ||
30809 | * @function | ||
30810 | * @returns {Long} Value read | ||
30811 | */ | ||
30812 | |||
30813 | /** | ||
30814 | * Reads a zig-zag encoded varint as a signed 64 bit value. | ||
30815 | * @name Reader#sint64 | ||
30816 | * @function | ||
30817 | * @returns {Long} Value read | ||
30818 | */ | ||
30819 | |||
30820 | /** | ||
30821 | * Reads a varint as a boolean. | ||
30822 | * @returns {boolean} Value read | ||
30823 | */ | ||
30824 | Reader.prototype.bool = function read_bool() { | ||
30825 | return this.uint32() !== 0; | ||
30826 | }; | ||
30827 | |||
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; | ||
30833 | } | ||
30834 | |||
30835 | /** | ||
30836 | * Reads fixed 32 bits as an unsigned 32 bit integer. | ||
30837 | * @returns {number} Value read | ||
30838 | */ | ||
30839 | Reader.prototype.fixed32 = function read_fixed32() { | ||
30840 | |||
30841 | /* istanbul ignore if */ | ||
30842 | if (this.pos + 4 > this.len) | ||
30843 | throw indexOutOfRange(this, 4); | ||
30844 | |||
30845 | return readFixed32_end(this.buf, this.pos += 4); | ||
30846 | }; | ||
30847 | |||
30848 | /** | ||
30849 | * Reads fixed 32 bits as a signed 32 bit integer. | ||
30850 | * @returns {number} Value read | ||
30851 | */ | ||
30852 | Reader.prototype.sfixed32 = function read_sfixed32() { | ||
30853 | |||
30854 | /* istanbul ignore if */ | ||
30855 | if (this.pos + 4 > this.len) | ||
30856 | throw indexOutOfRange(this, 4); | ||
30857 | |||
30858 | return readFixed32_end(this.buf, this.pos += 4) | 0; | ||
30859 | }; | ||
30860 | |||
30861 | /* eslint-disable no-invalid-this */ | ||
30862 | |||
30863 | function readFixed64(/* this: Reader */) { | ||
30864 | |||
30865 | /* istanbul ignore if */ | ||
30866 | if (this.pos + 8 > this.len) | ||
30867 | throw indexOutOfRange(this, 8); | ||
30868 | |||
30869 | return new LongBits(readFixed32_end(this.buf, this.pos += 4), readFixed32_end(this.buf, this.pos += 4)); | ||
30870 | } | ||
30871 | |||
30872 | /* eslint-enable no-invalid-this */ | ||
30873 | |||
30874 | /** | ||
30875 | * Reads fixed 64 bits. | ||
30876 | * @name Reader#fixed64 | ||
30877 | * @function | ||
30878 | * @returns {Long} Value read | ||
30879 | */ | ||
30880 | |||
30881 | /** | ||
30882 | * Reads zig-zag encoded fixed 64 bits. | ||
30883 | * @name Reader#sfixed64 | ||
30884 | * @function | ||
30885 | * @returns {Long} Value read | ||
30886 | */ | ||
30887 | |||
30888 | /** | ||
30889 | * Reads a float (32 bit) as a number. | ||
30890 | * @function | ||
30891 | * @returns {number} Value read | ||
30892 | */ | ||
30893 | Reader.prototype.float = function read_float() { | ||
30894 | |||
30895 | /* istanbul ignore if */ | ||
30896 | if (this.pos + 4 > this.len) | ||
30897 | throw indexOutOfRange(this, 4); | ||
30898 | |||
30899 | var value = util.float.readFloatLE(this.buf, this.pos); | ||
30900 | this.pos += 4; | ||
30901 | return value; | ||
30902 | }; | ||
30903 | |||
30904 | /** | ||
30905 | * Reads a double (64 bit float) as a number. | ||
30906 | * @function | ||
30907 | * @returns {number} Value read | ||
30908 | */ | ||
30909 | Reader.prototype.double = function read_double() { | ||
30910 | |||
30911 | /* istanbul ignore if */ | ||
30912 | if (this.pos + 8 > this.len) | ||
30913 | throw indexOutOfRange(this, 4); | ||
30914 | |||
30915 | var value = util.float.readDoubleLE(this.buf, this.pos); | ||
30916 | this.pos += 8; | ||
30917 | return value; | ||
30918 | }; | ||
30919 | |||
30920 | /** | ||
30921 | * Reads a sequence of bytes preceeded by its length as a varint. | ||
30922 | * @returns {Uint8Array} Value read | ||
30923 | */ | ||
30924 | Reader.prototype.bytes = function read_bytes() { | ||
30925 | var length = this.uint32(), | ||
30926 | start = this.pos, | ||
30927 | end = this.pos + length; | ||
30928 | |||
30929 | /* istanbul ignore if */ | ||
30930 | if (end > this.len) | ||
30931 | throw indexOutOfRange(this, length); | ||
30932 | |||
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); | ||
30939 | }; | ||
30940 | |||
30941 | /** | ||
30942 | * Reads a string preceeded by its byte length as a varint. | ||
30943 | * @returns {string} Value read | ||
30944 | */ | ||
30945 | Reader.prototype.string = function read_string() { | ||
30946 | var bytes = this.bytes(); | ||
30947 | return utf8.read(bytes, 0, bytes.length); | ||
30948 | }; | ||
30949 | |||
30950 | /** | ||
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` | ||
30954 | */ | ||
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; | ||
30961 | } else { | ||
30962 | do { | ||
30963 | /* istanbul ignore if */ | ||
30964 | if (this.pos >= this.len) | ||
30965 | throw indexOutOfRange(this); | ||
30966 | } while (this.buf[this.pos++] & 128); | ||
30967 | } | ||
30968 | return this; | ||
30969 | }; | ||
30970 | |||
30971 | /** | ||
30972 | * Skips the next element of the specified wire type. | ||
30973 | * @param {number} wireType Wire type received | ||
30974 | * @returns {Reader} `this` | ||
30975 | */ | ||
30976 | Reader.prototype.skipType = function(wireType) { | ||
30977 | switch (wireType) { | ||
30978 | case 0: | ||
30979 | this.skip(); | ||
30980 | break; | ||
30981 | case 1: | ||
30982 | this.skip(8); | ||
30983 | break; | ||
30984 | case 2: | ||
30985 | this.skip(this.uint32()); | ||
30986 | break; | ||
30987 | case 3: | ||
30988 | do { // eslint-disable-line no-constant-condition | ||
30989 | if ((wireType = this.uint32() & 7) === 4) | ||
30990 | break; | ||
30991 | this.skipType(wireType); | ||
30992 | } while (true); | ||
30993 | break; | ||
30994 | case 5: | ||
30995 | this.skip(4); | ||
30996 | break; | ||
30997 | |||
30998 | /* istanbul ignore next */ | ||
30999 | default: | ||
31000 | throw Error("invalid wire type " + wireType + " at offset " + this.pos); | ||
31001 | } | ||
31002 | return this; | ||
31003 | }; | ||
31004 | |||
31005 | Reader._configure = function(BufferReader_) { | ||
31006 | BufferReader = BufferReader_; | ||
31007 | |||
31008 | var fn = util.Long ? "toLong" : /* istanbul ignore next */ "toNumber"; | ||
31009 | util.merge(Reader.prototype, { | ||
31010 | |||
31011 | int64: function read_int64() { | ||
31012 | return readLongVarint.call(this)[fn](false); | ||
31013 | }, | ||
31014 | |||
31015 | uint64: function read_uint64() { | ||
31016 | return readLongVarint.call(this)[fn](true); | ||
31017 | }, | ||
31018 | |||
31019 | sint64: function read_sint64() { | ||
31020 | return readLongVarint.call(this).zzDecode()[fn](false); | ||
31021 | }, | ||
31022 | |||
31023 | fixed64: function read_fixed64() { | ||
31024 | return readFixed64.call(this)[fn](true); | ||
31025 | }, | ||
31026 | |||
31027 | sfixed64: function read_sfixed64() { | ||
31028 | return readFixed64.call(this)[fn](false); | ||
31029 | } | ||
31030 | |||
31031 | }); | ||
31032 | }; | ||
31033 | |||
31034 | },{"./util/minimal":220}],209:[function(require,module,exports){ | ||
31035 | "use strict"; | ||
31036 | module.exports = BufferReader; | ||
31037 | |||
31038 | // extends Reader | ||
31039 | var Reader = require("./reader"); | ||
31040 | (BufferReader.prototype = Object.create(Reader.prototype)).constructor = BufferReader; | ||
31041 | |||
31042 | var util = require("./util/minimal"); | ||
31043 | |||
31044 | /** | ||
31045 | * Constructs a new buffer reader instance. | ||
31046 | * @classdesc Wire format reader using node buffers. | ||
31047 | * @extends Reader | ||
31048 | * @constructor | ||
31049 | * @param {Buffer} buffer Buffer to read from | ||
31050 | */ | ||
31051 | function BufferReader(buffer) { | ||
31052 | Reader.call(this, buffer); | ||
31053 | |||
31054 | /** | ||
31055 | * Read buffer. | ||
31056 | * @name BufferReader#buf | ||
31057 | * @type {Buffer} | ||
31058 | */ | ||
31059 | } | ||
31060 | |||
31061 | /* istanbul ignore else */ | ||
31062 | if (util.Buffer) | ||
31063 | BufferReader.prototype._slice = util.Buffer.prototype.slice; | ||
31064 | |||
31065 | /** | ||
31066 | * @override | ||
31067 | */ | ||
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)); | ||
31071 | }; | ||
31072 | |||
31073 | /** | ||
31074 | * Reads a sequence of bytes preceeded by its length as a varint. | ||
31075 | * @name BufferReader#bytes | ||
31076 | * @function | ||
31077 | * @returns {Buffer} Value read | ||
31078 | */ | ||
31079 | |||
31080 | },{"./reader":208,"./util/minimal":220}],210:[function(require,module,exports){ | ||
31081 | "use strict"; | ||
31082 | module.exports = Root; | ||
31083 | |||
31084 | // extends Namespace | ||
31085 | var Namespace = require("./namespace"); | ||
31086 | ((Root.prototype = Object.create(Namespace.prototype)).constructor = Root).className = "Root"; | ||
31087 | |||
31088 | var Field = require("./field"), | ||
31089 | Enum = require("./enum"), | ||
31090 | OneOf = require("./oneof"), | ||
31091 | util = require("./util"); | ||
31092 | |||
31093 | var Type, // cyclic | ||
31094 | parse, // might be excluded | ||
31095 | common; // " | ||
31096 | |||
31097 | /** | ||
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 | ||
31101 | * @constructor | ||
31102 | * @param {Object.<string,*>} [options] Top level options | ||
31103 | */ | ||
31104 | function Root(options) { | ||
31105 | Namespace.call(this, "", options); | ||
31106 | |||
31107 | /** | ||
31108 | * Deferred extension fields. | ||
31109 | * @type {Field[]} | ||
31110 | */ | ||
31111 | this.deferred = []; | ||
31112 | |||
31113 | /** | ||
31114 | * Resolved file names of loaded files. | ||
31115 | * @type {string[]} | ||
31116 | */ | ||
31117 | this.files = []; | ||
31118 | } | ||
31119 | |||
31120 | /** | ||
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 | ||
31125 | */ | ||
31126 | Root.fromJSON = function fromJSON(json, root) { | ||
31127 | if (!root) | ||
31128 | root = new Root(); | ||
31129 | if (json.options) | ||
31130 | root.setOptions(json.options); | ||
31131 | return root.addJSON(json.nested); | ||
31132 | }; | ||
31133 | |||
31134 | /** | ||
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. | ||
31137 | * @function | ||
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 | ||
31141 | */ | ||
31142 | Root.prototype.resolvePath = util.path.resolve; | ||
31143 | |||
31144 | // A symbol-like function to safely signal synchronous loading | ||
31145 | /* istanbul ignore next */ | ||
31146 | function SYNC() {} // eslint-disable-line no-empty-function | ||
31147 | |||
31148 | /** | ||
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} | ||
31154 | */ | ||
31155 | Root.prototype.load = function load(filename, options, callback) { | ||
31156 | if (typeof options === "function") { | ||
31157 | callback = options; | ||
31158 | options = undefined; | ||
31159 | } | ||
31160 | var self = this; | ||
31161 | if (!callback) | ||
31162 | return util.asPromise(load, self, filename, options); | ||
31163 | |||
31164 | var sync = callback === SYNC; // undocumented | ||
31165 | |||
31166 | // Finishes loading by calling the callback (exactly once) | ||
31167 | function finish(err, root) { | ||
31168 | /* istanbul ignore if */ | ||
31169 | if (!callback) | ||
31170 | return; | ||
31171 | var cb = callback; | ||
31172 | callback = null; | ||
31173 | if (sync) | ||
31174 | throw err; | ||
31175 | cb(err, root); | ||
31176 | } | ||
31177 | |||
31178 | // Processes a single file | ||
31179 | function process(filename, source) { | ||
31180 | try { | ||
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); | ||
31185 | else { | ||
31186 | parse.filename = filename; | ||
31187 | var parsed = parse(source, self, options), | ||
31188 | resolved, | ||
31189 | i = 0; | ||
31190 | if (parsed.imports) | ||
31191 | for (; i < parsed.imports.length; ++i) | ||
31192 | if (resolved = self.resolvePath(filename, parsed.imports[i])) | ||
31193 | fetch(resolved); | ||
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); | ||
31198 | } | ||
31199 | } catch (err) { | ||
31200 | finish(err); | ||
31201 | } | ||
31202 | if (!sync && !queued) | ||
31203 | finish(null, self); // only once anyway | ||
31204 | } | ||
31205 | |||
31206 | // Fetches a single file | ||
31207 | function fetch(filename, weak) { | ||
31208 | |||
31209 | // Strip path if this file references a bundled definition | ||
31210 | var idx = filename.lastIndexOf("google/protobuf/"); | ||
31211 | if (idx > -1) { | ||
31212 | var altname = filename.substring(idx); | ||
31213 | if (altname in common) | ||
31214 | filename = altname; | ||
31215 | } | ||
31216 | |||
31217 | // Skip if already loaded / attempted | ||
31218 | if (self.files.indexOf(filename) > -1) | ||
31219 | return; | ||
31220 | self.files.push(filename); | ||
31221 | |||
31222 | // Shortcut bundled definitions | ||
31223 | if (filename in common) { | ||
31224 | if (sync) | ||
31225 | process(filename, common[filename]); | ||
31226 | else { | ||
31227 | ++queued; | ||
31228 | setTimeout(function() { | ||
31229 | --queued; | ||
31230 | process(filename, common[filename]); | ||
31231 | }); | ||
31232 | } | ||
31233 | return; | ||
31234 | } | ||
31235 | |||
31236 | // Otherwise fetch from disk or network | ||
31237 | if (sync) { | ||
31238 | var source; | ||
31239 | try { | ||
31240 | source = util.fs.readFileSync(filename).toString("utf8"); | ||
31241 | } catch (err) { | ||
31242 | if (!weak) | ||
31243 | finish(err); | ||
31244 | return; | ||
31245 | } | ||
31246 | process(filename, source); | ||
31247 | } else { | ||
31248 | ++queued; | ||
31249 | util.fetch(filename, function(err, source) { | ||
31250 | --queued; | ||
31251 | /* istanbul ignore if */ | ||
31252 | if (!callback) | ||
31253 | return; // terminated meanwhile | ||
31254 | if (err) { | ||
31255 | /* istanbul ignore else */ | ||
31256 | if (!weak) | ||
31257 | finish(err); | ||
31258 | else if (!queued) // can't be covered reliably | ||
31259 | finish(null, self); | ||
31260 | return; | ||
31261 | } | ||
31262 | process(filename, source); | ||
31263 | }); | ||
31264 | } | ||
31265 | } | ||
31266 | var queued = 0; | ||
31267 | |||
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])) | ||
31274 | fetch(resolved); | ||
31275 | |||
31276 | if (sync) | ||
31277 | return self; | ||
31278 | if (!queued) | ||
31279 | finish(null, self); | ||
31280 | return undefined; | ||
31281 | }; | ||
31282 | // function load(filename:string, options:IParseOptions, callback:LoadCallback):undefined | ||
31283 | |||
31284 | /** | ||
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} | ||
31290 | * @variation 2 | ||
31291 | */ | ||
31292 | // function load(filename:string, callback:LoadCallback):undefined | ||
31293 | |||
31294 | /** | ||
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 | ||
31300 | * @variation 3 | ||
31301 | */ | ||
31302 | // function load(filename:string, [options:IParseOptions]):Promise<Root> | ||
31303 | |||
31304 | /** | ||
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 | ||
31311 | */ | ||
31312 | Root.prototype.loadSync = function loadSync(filename, options) { | ||
31313 | if (!util.isNode) | ||
31314 | throw Error("not supported"); | ||
31315 | return this.load(filename, options, SYNC); | ||
31316 | }; | ||
31317 | |||
31318 | /** | ||
31319 | * @override | ||
31320 | */ | ||
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; | ||
31325 | }).join(", ")); | ||
31326 | return Namespace.prototype.resolveAll.call(this); | ||
31327 | }; | ||
31328 | |||
31329 | // only uppercased (and thus conflict-free) children are exposed, see below | ||
31330 | var exposeRe = /^[A-Z]/; | ||
31331 | |||
31332 | /** | ||
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 | ||
31337 | * @inner | ||
31338 | * @ignore | ||
31339 | */ | ||
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); | ||
31347 | return true; | ||
31348 | } | ||
31349 | return false; | ||
31350 | } | ||
31351 | |||
31352 | /** | ||
31353 | * Called when any object is added to this root or its sub-namespaces. | ||
31354 | * @param {ReflectionObject} object Object added | ||
31355 | * @returns {undefined} | ||
31356 | * @private | ||
31357 | */ | ||
31358 | Root.prototype._handleAdd = function _handleAdd(object) { | ||
31359 | if (object instanceof Field) { | ||
31360 | |||
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); | ||
31364 | |||
31365 | } else if (object instanceof Enum) { | ||
31366 | |||
31367 | if (exposeRe.test(object.name)) | ||
31368 | object.parent[object.name] = object.values; // expose enum values as property of its parent | ||
31369 | |||
31370 | } else if (!(object instanceof OneOf)) /* everything else is a namespace */ { | ||
31371 | |||
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); | ||
31376 | else | ||
31377 | ++i; | ||
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 | ||
31382 | } | ||
31383 | |||
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. | ||
31387 | }; | ||
31388 | |||
31389 | /** | ||
31390 | * Called when any object is removed from this root or its sub-namespaces. | ||
31391 | * @param {ReflectionObject} object Object removed | ||
31392 | * @returns {undefined} | ||
31393 | * @private | ||
31394 | */ | ||
31395 | Root.prototype._handleRemove = function _handleRemove(object) { | ||
31396 | if (object instanceof Field) { | ||
31397 | |||
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 */ | ||
31405 | if (index > -1) | ||
31406 | this.deferred.splice(index, 1); | ||
31407 | } | ||
31408 | } | ||
31409 | |||
31410 | } else if (object instanceof Enum) { | ||
31411 | |||
31412 | if (exposeRe.test(object.name)) | ||
31413 | delete object.parent[object.name]; // unexpose enum values | ||
31414 | |||
31415 | } else if (object instanceof Namespace) { | ||
31416 | |||
31417 | for (var i = 0; i < /* initializes */ object.nestedArray.length; ++i) // recurse into the namespace | ||
31418 | this._handleRemove(object._nestedArray[i]); | ||
31419 | |||
31420 | if (exposeRe.test(object.name)) | ||
31421 | delete object.parent[object.name]; // unexpose namespaces | ||
31422 | |||
31423 | } | ||
31424 | }; | ||
31425 | |||
31426 | Root._configure = function(Type_, parse_, common_) { | ||
31427 | Type = Type_; | ||
31428 | parse = parse_; | ||
31429 | common = common_; | ||
31430 | }; | ||
31431 | |||
31432 | },{"./enum":196,"./field":197,"./namespace":204,"./oneof":206,"./util":218}],211:[function(require,module,exports){ | ||
31433 | "use strict"; | ||
31434 | module.exports = {}; | ||
31435 | |||
31436 | /** | ||
31437 | * Named roots. | ||
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. | ||
31440 | * @name roots | ||
31441 | * @type {Object.<string,Root>} | ||
31442 | * @example | ||
31443 | * // pbjs -r myroot -o compiled.js ... | ||
31444 | * | ||
31445 | * // in another module: | ||
31446 | * require("./compiled.js"); | ||
31447 | * | ||
31448 | * // in any subsequent module: | ||
31449 | * var root = protobuf.roots["myroot"]; | ||
31450 | */ | ||
31451 | |||
31452 | },{}],212:[function(require,module,exports){ | ||
31453 | "use strict"; | ||
31454 | |||
31455 | /** | ||
31456 | * Streaming RPC helpers. | ||
31457 | * @namespace | ||
31458 | */ | ||
31459 | var rpc = exports; | ||
31460 | |||
31461 | /** | ||
31462 | * RPC implementation passed to {@link Service#create} performing a service request on network level, i.e. by utilizing http requests or websockets. | ||
31463 | * @typedef RPCImpl | ||
31464 | * @type {function} | ||
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} | ||
31469 | * @example | ||
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); | ||
31475 | * }); | ||
31476 | * } | ||
31477 | */ | ||
31478 | |||
31479 | /** | ||
31480 | * Node-style callback as used by {@link RPCImpl}. | ||
31481 | * @typedef RPCImplCallback | ||
31482 | * @type {function} | ||
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} | ||
31486 | */ | ||
31487 | |||
31488 | rpc.Service = require("./rpc/service"); | ||
31489 | |||
31490 | },{"./rpc/service":213}],213:[function(require,module,exports){ | ||
31491 | "use strict"; | ||
31492 | module.exports = Service; | ||
31493 | |||
31494 | var util = require("../util/minimal"); | ||
31495 | |||
31496 | // Extends EventEmitter | ||
31497 | (Service.prototype = Object.create(util.EventEmitter.prototype)).constructor = Service; | ||
31498 | |||
31499 | /** | ||
31500 | * A service method callback as used by {@link rpc.ServiceMethod|ServiceMethod}. | ||
31501 | * | ||
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> | ||
31505 | * @type {function} | ||
31506 | * @param {Error|null} error Error, if any | ||
31507 | * @param {TRes} [response] Response message | ||
31508 | * @returns {undefined} | ||
31509 | */ | ||
31510 | |||
31511 | /** | ||
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> | ||
31516 | * @type {function} | ||
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` | ||
31520 | */ | ||
31521 | |||
31522 | /** | ||
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 | ||
31527 | * @constructor | ||
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 | ||
31531 | */ | ||
31532 | function Service(rpcImpl, requestDelimited, responseDelimited) { | ||
31533 | |||
31534 | if (typeof rpcImpl !== "function") | ||
31535 | throw TypeError("rpcImpl must be a function"); | ||
31536 | |||
31537 | util.EventEmitter.call(this); | ||
31538 | |||
31539 | /** | ||
31540 | * RPC implementation. Becomes `null` once the service is ended. | ||
31541 | * @type {RPCImpl|null} | ||
31542 | */ | ||
31543 | this.rpcImpl = rpcImpl; | ||
31544 | |||
31545 | /** | ||
31546 | * Whether requests are length-delimited. | ||
31547 | * @type {boolean} | ||
31548 | */ | ||
31549 | this.requestDelimited = Boolean(requestDelimited); | ||
31550 | |||
31551 | /** | ||
31552 | * Whether responses are length-delimited. | ||
31553 | * @type {boolean} | ||
31554 | */ | ||
31555 | this.responseDelimited = Boolean(responseDelimited); | ||
31556 | } | ||
31557 | |||
31558 | /** | ||
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> | ||
31568 | */ | ||
31569 | Service.prototype.rpcCall = function rpcCall(method, requestCtor, responseCtor, request, callback) { | ||
31570 | |||
31571 | if (!request) | ||
31572 | throw TypeError("request must be specified"); | ||
31573 | |||
31574 | var self = this; | ||
31575 | if (!callback) | ||
31576 | return util.asPromise(rpcCall, self, method, requestCtor, responseCtor, request); | ||
31577 | |||
31578 | if (!self.rpcImpl) { | ||
31579 | setTimeout(function() { callback(Error("already ended")); }, 0); | ||
31580 | return undefined; | ||
31581 | } | ||
31582 | |||
31583 | try { | ||
31584 | return self.rpcImpl( | ||
31585 | method, | ||
31586 | requestCtor[self.requestDelimited ? "encodeDelimited" : "encode"](request).finish(), | ||
31587 | function rpcCallback(err, response) { | ||
31588 | |||
31589 | if (err) { | ||
31590 | self.emit("error", err, method); | ||
31591 | return callback(err); | ||
31592 | } | ||
31593 | |||
31594 | if (response === null) { | ||
31595 | self.end(/* endedByRPC */ true); | ||
31596 | return undefined; | ||
31597 | } | ||
31598 | |||
31599 | if (!(response instanceof responseCtor)) { | ||
31600 | try { | ||
31601 | response = responseCtor[self.responseDelimited ? "decodeDelimited" : "decode"](response); | ||
31602 | } catch (err) { | ||
31603 | self.emit("error", err, method); | ||
31604 | return callback(err); | ||
31605 | } | ||
31606 | } | ||
31607 | |||
31608 | self.emit("data", response, method); | ||
31609 | return callback(null, response); | ||
31610 | } | ||
31611 | ); | ||
31612 | } catch (err) { | ||
31613 | self.emit("error", err, method); | ||
31614 | setTimeout(function() { callback(err); }, 0); | ||
31615 | return undefined; | ||
31616 | } | ||
31617 | }; | ||
31618 | |||
31619 | /** | ||
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` | ||
31623 | */ | ||
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(); | ||
31630 | } | ||
31631 | return this; | ||
31632 | }; | ||
31633 | |||
31634 | },{"../util/minimal":220}],214:[function(require,module,exports){ | ||
31635 | "use strict"; | ||
31636 | module.exports = Service; | ||
31637 | |||
31638 | // extends Namespace | ||
31639 | var Namespace = require("./namespace"); | ||
31640 | ((Service.prototype = Object.create(Namespace.prototype)).constructor = Service).className = "Service"; | ||
31641 | |||
31642 | var Method = require("./method"), | ||
31643 | util = require("./util"), | ||
31644 | rpc = require("./rpc"); | ||
31645 | |||
31646 | /** | ||
31647 | * Constructs a new service instance. | ||
31648 | * @classdesc Reflected service. | ||
31649 | * @extends NamespaceBase | ||
31650 | * @constructor | ||
31651 | * @param {string} name Service name | ||
31652 | * @param {Object.<string,*>} [options] Service options | ||
31653 | * @throws {TypeError} If arguments are invalid | ||
31654 | */ | ||
31655 | function Service(name, options) { | ||
31656 | Namespace.call(this, name, options); | ||
31657 | |||
31658 | /** | ||
31659 | * Service methods. | ||
31660 | * @type {Object.<string,Method>} | ||
31661 | */ | ||
31662 | this.methods = {}; // toJSON, marker | ||
31663 | |||
31664 | /** | ||
31665 | * Cached methods as an array. | ||
31666 | * @type {Method[]|null} | ||
31667 | * @private | ||
31668 | */ | ||
31669 | this._methodsArray = null; | ||
31670 | } | ||
31671 | |||
31672 | /** | ||
31673 | * Service descriptor. | ||
31674 | * @interface IService | ||
31675 | * @extends INamespace | ||
31676 | * @property {Object.<string,IMethod>} methods Method descriptors | ||
31677 | */ | ||
31678 | |||
31679 | /** | ||
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 | ||
31685 | */ | ||
31686 | Service.fromJSON = function fromJSON(name, json) { | ||
31687 | var service = new Service(name, json.options); | ||
31688 | /* istanbul ignore else */ | ||
31689 | if (json.methods) | ||
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]])); | ||
31692 | if (json.nested) | ||
31693 | service.addJSON(json.nested); | ||
31694 | service.comment = json.comment; | ||
31695 | return service; | ||
31696 | }; | ||
31697 | |||
31698 | /** | ||
31699 | * Converts this service to a service descriptor. | ||
31700 | * @param {IToJSONOptions} [toJSONOptions] JSON conversion options | ||
31701 | * @returns {IService} Service descriptor | ||
31702 | */ | ||
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 | ||
31711 | ]); | ||
31712 | }; | ||
31713 | |||
31714 | /** | ||
31715 | * Methods of this service as an array for iteration. | ||
31716 | * @name Service#methodsArray | ||
31717 | * @type {Method[]} | ||
31718 | * @readonly | ||
31719 | */ | ||
31720 | Object.defineProperty(Service.prototype, "methodsArray", { | ||
31721 | get: function() { | ||
31722 | return this._methodsArray || (this._methodsArray = util.toArray(this.methods)); | ||
31723 | } | ||
31724 | }); | ||
31725 | |||
31726 | function clearCache(service) { | ||
31727 | service._methodsArray = null; | ||
31728 | return service; | ||
31729 | } | ||
31730 | |||
31731 | /** | ||
31732 | * @override | ||
31733 | */ | ||
31734 | Service.prototype.get = function get(name) { | ||
31735 | return this.methods[name] | ||
31736 | || Namespace.prototype.get.call(this, name); | ||
31737 | }; | ||
31738 | |||
31739 | /** | ||
31740 | * @override | ||
31741 | */ | ||
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); | ||
31747 | }; | ||
31748 | |||
31749 | /** | ||
31750 | * @override | ||
31751 | */ | ||
31752 | Service.prototype.add = function add(object) { | ||
31753 | |||
31754 | /* istanbul ignore if */ | ||
31755 | if (this.get(object.name)) | ||
31756 | throw Error("duplicate name '" + object.name + "' in " + this); | ||
31757 | |||
31758 | if (object instanceof Method) { | ||
31759 | this.methods[object.name] = object; | ||
31760 | object.parent = this; | ||
31761 | return clearCache(this); | ||
31762 | } | ||
31763 | return Namespace.prototype.add.call(this, object); | ||
31764 | }; | ||
31765 | |||
31766 | /** | ||
31767 | * @override | ||
31768 | */ | ||
31769 | Service.prototype.remove = function remove(object) { | ||
31770 | if (object instanceof Method) { | ||
31771 | |||
31772 | /* istanbul ignore if */ | ||
31773 | if (this.methods[object.name] !== object) | ||
31774 | throw Error(object + " is not a member of " + this); | ||
31775 | |||
31776 | delete this.methods[object.name]; | ||
31777 | object.parent = null; | ||
31778 | return clearCache(this); | ||
31779 | } | ||
31780 | return Namespace.prototype.remove.call(this, object); | ||
31781 | }; | ||
31782 | |||
31783 | /** | ||
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. | ||
31789 | */ | ||
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)")({ | ||
31795 | m: method, | ||
31796 | q: method.resolvedRequestType.ctor, | ||
31797 | s: method.resolvedResponseType.ctor | ||
31798 | }); | ||
31799 | } | ||
31800 | return rpcService; | ||
31801 | }; | ||
31802 | |||
31803 | },{"./method":203,"./namespace":204,"./rpc":212,"./util":218}],215:[function(require,module,exports){ | ||
31804 | "use strict"; | ||
31805 | module.exports = tokenize; | ||
31806 | |||
31807 | var delimRe = /[\s{}=;:[\],'"()<>]/g, | ||
31808 | stringDoubleRe = /(?:"([^"\\]*(?:\\.[^"\\]*)*)")/g, | ||
31809 | stringSingleRe = /(?:'([^'\\]*(?:\\.[^'\\]*)*)')/g; | ||
31810 | |||
31811 | var setCommentRe = /^ *[*/]+ */, | ||
31812 | setCommentAltRe = /^\s*\*?\/*/, | ||
31813 | setCommentSplitRe = /\n/g, | ||
31814 | whitespaceRe = /\s/, | ||
31815 | unescapeRe = /\\(.?)/g; | ||
31816 | |||
31817 | var unescapeMap = { | ||
31818 | "0": "\0", | ||
31819 | "r": "\r", | ||
31820 | "n": "\n", | ||
31821 | "t": "\t" | ||
31822 | }; | ||
31823 | |||
31824 | /** | ||
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 | ||
31830 | */ | ||
31831 | function unescape(str) { | ||
31832 | return str.replace(unescapeRe, function($0, $1) { | ||
31833 | switch ($1) { | ||
31834 | case "\\": | ||
31835 | case "": | ||
31836 | return $1; | ||
31837 | default: | ||
31838 | return unescapeMap[$1] || ""; | ||
31839 | } | ||
31840 | }); | ||
31841 | } | ||
31842 | |||
31843 | tokenize.unescape = unescape; | ||
31844 | |||
31845 | /** | ||
31846 | * Gets the next token and advances. | ||
31847 | * @typedef TokenizerHandleNext | ||
31848 | * @type {function} | ||
31849 | * @returns {string|null} Next token or `null` on eof | ||
31850 | */ | ||
31851 | |||
31852 | /** | ||
31853 | * Peeks for the next token. | ||
31854 | * @typedef TokenizerHandlePeek | ||
31855 | * @type {function} | ||
31856 | * @returns {string|null} Next token or `null` on eof | ||
31857 | */ | ||
31858 | |||
31859 | /** | ||
31860 | * Pushes a token back to the stack. | ||
31861 | * @typedef TokenizerHandlePush | ||
31862 | * @type {function} | ||
31863 | * @param {string} token Token | ||
31864 | * @returns {undefined} | ||
31865 | */ | ||
31866 | |||
31867 | /** | ||
31868 | * Skips the next token. | ||
31869 | * @typedef TokenizerHandleSkip | ||
31870 | * @type {function} | ||
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 | ||
31875 | */ | ||
31876 | |||
31877 | /** | ||
31878 | * Gets the comment on the previous line or, alternatively, the line comment on the specified line. | ||
31879 | * @typedef TokenizerHandleCmnt | ||
31880 | * @type {function} | ||
31881 | * @param {number} [line] Line number | ||
31882 | * @returns {string|null} Comment text or `null` if none | ||
31883 | */ | ||
31884 | |||
31885 | /** | ||
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 | ||
31894 | */ | ||
31895 | |||
31896 | /** | ||
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 | ||
31901 | */ | ||
31902 | function tokenize(source, alternateCommentMode) { | ||
31903 | /* eslint-disable callback-return */ | ||
31904 | source = source.toString(); | ||
31905 | |||
31906 | var offset = 0, | ||
31907 | length = source.length, | ||
31908 | line = 1, | ||
31909 | commentType = null, | ||
31910 | commentText = null, | ||
31911 | commentLine = 0, | ||
31912 | commentLineEmpty = false; | ||
31913 | |||
31914 | var stack = []; | ||
31915 | |||
31916 | var stringDelim = null; | ||
31917 | |||
31918 | /* istanbul ignore next */ | ||
31919 | /** | ||
31920 | * Creates an error for illegal syntax. | ||
31921 | * @param {string} subject Subject | ||
31922 | * @returns {Error} Error created | ||
31923 | * @inner | ||
31924 | */ | ||
31925 | function illegal(subject) { | ||
31926 | return Error("illegal " + subject + " (line " + line + ")"); | ||
31927 | } | ||
31928 | |||
31929 | /** | ||
31930 | * Reads a string till its end. | ||
31931 | * @returns {string} String read | ||
31932 | * @inner | ||
31933 | */ | ||
31934 | function readString() { | ||
31935 | var re = stringDelim === "'" ? stringSingleRe : stringDoubleRe; | ||
31936 | re.lastIndex = offset - 1; | ||
31937 | var match = re.exec(source); | ||
31938 | if (!match) | ||
31939 | throw illegal("string"); | ||
31940 | offset = re.lastIndex; | ||
31941 | push(stringDelim); | ||
31942 | stringDelim = null; | ||
31943 | return unescape(match[1]); | ||
31944 | } | ||
31945 | |||
31946 | /** | ||
31947 | * Gets the character at `pos` within the source. | ||
31948 | * @param {number} pos Position | ||
31949 | * @returns {string} Character | ||
31950 | * @inner | ||
31951 | */ | ||
31952 | function charAt(pos) { | ||
31953 | return source.charAt(pos); | ||
31954 | } | ||
31955 | |||
31956 | /** | ||
31957 | * Sets the current comment text. | ||
31958 | * @param {number} start Start offset | ||
31959 | * @param {number} end End offset | ||
31960 | * @returns {undefined} | ||
31961 | * @inner | ||
31962 | */ | ||
31963 | function setComment(start, end) { | ||
31964 | commentType = source.charAt(start++); | ||
31965 | commentLine = line; | ||
31966 | commentLineEmpty = false; | ||
31967 | var lookback; | ||
31968 | if (alternateCommentMode) { | ||
31969 | lookback = 2; // alternate comment parsing: "//" or "/*" | ||
31970 | } else { | ||
31971 | lookback = 3; // "///" or "/**" | ||
31972 | } | ||
31973 | var commentOffset = start - lookback, | ||
31974 | c; | ||
31975 | do { | ||
31976 | if (--commentOffset < 0 || | ||
31977 | (c = source.charAt(commentOffset)) === "\n") { | ||
31978 | commentLineEmpty = true; | ||
31979 | break; | ||
31980 | } | ||
31981 | } while (c === " " || c === "\t"); | ||
31982 | var lines = source | ||
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, "") | ||
31988 | .trim(); | ||
31989 | commentText = lines | ||
31990 | .join("\n") | ||
31991 | .trim(); | ||
31992 | } | ||
31993 | |||
31994 | function isDoubleSlashCommentLine(startOffset) { | ||
31995 | var endOffset = findEndOfLine(startOffset); | ||
31996 | |||
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); | ||
32002 | return isComment; | ||
32003 | } | ||
32004 | |||
32005 | function findEndOfLine(cursor) { | ||
32006 | // find end of cursor's line | ||
32007 | var endOffset = cursor; | ||
32008 | while (endOffset < length && charAt(endOffset) !== "\n") { | ||
32009 | endOffset++; | ||
32010 | } | ||
32011 | return endOffset; | ||
32012 | } | ||
32013 | |||
32014 | /** | ||
32015 | * Obtains the next token. | ||
32016 | * @returns {string|null} Next token or `null` on eof | ||
32017 | * @inner | ||
32018 | */ | ||
32019 | function next() { | ||
32020 | if (stack.length > 0) | ||
32021 | return stack.shift(); | ||
32022 | if (stringDelim) | ||
32023 | return readString(); | ||
32024 | var repeat, | ||
32025 | prev, | ||
32026 | curr, | ||
32027 | start, | ||
32028 | isDoc; | ||
32029 | do { | ||
32030 | if (offset === length) | ||
32031 | return null; | ||
32032 | repeat = false; | ||
32033 | while (whitespaceRe.test(curr = charAt(offset))) { | ||
32034 | if (curr === "\n") | ||
32035 | ++line; | ||
32036 | if (++offset === length) | ||
32037 | return null; | ||
32038 | } | ||
32039 | |||
32040 | if (charAt(offset) === "/") { | ||
32041 | if (++offset === length) { | ||
32042 | throw illegal("comment"); | ||
32043 | } | ||
32044 | if (charAt(offset) === "/") { // Line | ||
32045 | if (!alternateCommentMode) { | ||
32046 | // check for triple-slash comment | ||
32047 | isDoc = charAt(start = offset + 1) === "/"; | ||
32048 | |||
32049 | while (charAt(++offset) !== "\n") { | ||
32050 | if (offset === length) { | ||
32051 | return null; | ||
32052 | } | ||
32053 | } | ||
32054 | ++offset; | ||
32055 | if (isDoc) { | ||
32056 | setComment(start, offset - 1); | ||
32057 | } | ||
32058 | ++line; | ||
32059 | repeat = true; | ||
32060 | } else { | ||
32061 | // check for double-slash comments, consolidating consecutive lines | ||
32062 | start = offset; | ||
32063 | isDoc = false; | ||
32064 | if (isDoubleSlashCommentLine(offset)) { | ||
32065 | isDoc = true; | ||
32066 | do { | ||
32067 | offset = findEndOfLine(offset); | ||
32068 | if (offset === length) { | ||
32069 | break; | ||
32070 | } | ||
32071 | offset++; | ||
32072 | } while (isDoubleSlashCommentLine(offset)); | ||
32073 | } else { | ||
32074 | offset = Math.min(length, findEndOfLine(offset) + 1); | ||
32075 | } | ||
32076 | if (isDoc) { | ||
32077 | setComment(start, offset); | ||
32078 | } | ||
32079 | line++; | ||
32080 | repeat = true; | ||
32081 | } | ||
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) === "*"; | ||
32086 | do { | ||
32087 | if (curr === "\n") { | ||
32088 | ++line; | ||
32089 | } | ||
32090 | if (++offset === length) { | ||
32091 | throw illegal("comment"); | ||
32092 | } | ||
32093 | prev = curr; | ||
32094 | curr = charAt(offset); | ||
32095 | } while (prev !== "*" || curr !== "/"); | ||
32096 | ++offset; | ||
32097 | if (isDoc) { | ||
32098 | setComment(start, offset - 2); | ||
32099 | } | ||
32100 | repeat = true; | ||
32101 | } else { | ||
32102 | return "/"; | ||
32103 | } | ||
32104 | } | ||
32105 | } while (repeat); | ||
32106 | |||
32107 | // offset !== length if we got here | ||
32108 | |||
32109 | var end = offset; | ||
32110 | delimRe.lastIndex = 0; | ||
32111 | var delim = delimRe.test(charAt(end++)); | ||
32112 | if (!delim) | ||
32113 | while (end < length && !delimRe.test(charAt(end))) | ||
32114 | ++end; | ||
32115 | var token = source.substring(offset, offset = end); | ||
32116 | if (token === "\"" || token === "'") | ||
32117 | stringDelim = token; | ||
32118 | return token; | ||
32119 | } | ||
32120 | |||
32121 | /** | ||
32122 | * Pushes a token back to the stack. | ||
32123 | * @param {string} token Token | ||
32124 | * @returns {undefined} | ||
32125 | * @inner | ||
32126 | */ | ||
32127 | function push(token) { | ||
32128 | stack.push(token); | ||
32129 | } | ||
32130 | |||
32131 | /** | ||
32132 | * Peeks for the next token. | ||
32133 | * @returns {string|null} Token or `null` on eof | ||
32134 | * @inner | ||
32135 | */ | ||
32136 | function peek() { | ||
32137 | if (!stack.length) { | ||
32138 | var token = next(); | ||
32139 | if (token === null) | ||
32140 | return null; | ||
32141 | push(token); | ||
32142 | } | ||
32143 | return stack[0]; | ||
32144 | } | ||
32145 | |||
32146 | /** | ||
32147 | * Skips a token. | ||
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 | ||
32152 | * @inner | ||
32153 | */ | ||
32154 | function skip(expected, optional) { | ||
32155 | var actual = peek(), | ||
32156 | equals = actual === expected; | ||
32157 | if (equals) { | ||
32158 | next(); | ||
32159 | return true; | ||
32160 | } | ||
32161 | if (!optional) | ||
32162 | throw illegal("token '" + actual + "', '" + expected + "' expected"); | ||
32163 | return false; | ||
32164 | } | ||
32165 | |||
32166 | /** | ||
32167 | * Gets a comment. | ||
32168 | * @param {number} [trailingLine] Line number if looking for a trailing comment | ||
32169 | * @returns {string|null} Comment text | ||
32170 | * @inner | ||
32171 | */ | ||
32172 | function cmnt(trailingLine) { | ||
32173 | var ret = null; | ||
32174 | if (trailingLine === undefined) { | ||
32175 | if (commentLine === line - 1 && (alternateCommentMode || commentType === "*" || commentLineEmpty)) { | ||
32176 | ret = commentText; | ||
32177 | } | ||
32178 | } else { | ||
32179 | /* istanbul ignore else */ | ||
32180 | if (commentLine < trailingLine) { | ||
32181 | peek(); | ||
32182 | } | ||
32183 | if (commentLine === trailingLine && !commentLineEmpty && (alternateCommentMode || commentType === "/")) { | ||
32184 | ret = commentText; | ||
32185 | } | ||
32186 | } | ||
32187 | return ret; | ||
32188 | } | ||
32189 | |||
32190 | return Object.defineProperty({ | ||
32191 | next: next, | ||
32192 | peek: peek, | ||
32193 | push: push, | ||
32194 | skip: skip, | ||
32195 | cmnt: cmnt | ||
32196 | }, "line", { | ||
32197 | get: function() { return line; } | ||
32198 | }); | ||
32199 | /* eslint-enable callback-return */ | ||
32200 | } | ||
32201 | |||
32202 | },{}],216:[function(require,module,exports){ | ||
32203 | "use strict"; | ||
32204 | module.exports = Type; | ||
32205 | |||
32206 | // extends Namespace | ||
32207 | var Namespace = require("./namespace"); | ||
32208 | ((Type.prototype = Object.create(Namespace.prototype)).constructor = Type).className = "Type"; | ||
32209 | |||
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"); | ||
32224 | |||
32225 | /** | ||
32226 | * Constructs a new reflected message type instance. | ||
32227 | * @classdesc Reflected message type. | ||
32228 | * @extends NamespaceBase | ||
32229 | * @constructor | ||
32230 | * @param {string} name Message name | ||
32231 | * @param {Object.<string,*>} [options] Declared options | ||
32232 | */ | ||
32233 | function Type(name, options) { | ||
32234 | Namespace.call(this, name, options); | ||
32235 | |||
32236 | /** | ||
32237 | * Message fields. | ||
32238 | * @type {Object.<string,Field>} | ||
32239 | */ | ||
32240 | this.fields = {}; // toJSON, marker | ||
32241 | |||
32242 | /** | ||
32243 | * Oneofs declared within this namespace, if any. | ||
32244 | * @type {Object.<string,OneOf>} | ||
32245 | */ | ||
32246 | this.oneofs = undefined; // toJSON | ||
32247 | |||
32248 | /** | ||
32249 | * Extension ranges, if any. | ||
32250 | * @type {number[][]} | ||
32251 | */ | ||
32252 | this.extensions = undefined; // toJSON | ||
32253 | |||
32254 | /** | ||
32255 | * Reserved ranges, if any. | ||
32256 | * @type {Array.<number[]|string>} | ||
32257 | */ | ||
32258 | this.reserved = undefined; // toJSON | ||
32259 | |||
32260 | /*? | ||
32261 | * Whether this type is a legacy group. | ||
32262 | * @type {boolean|undefined} | ||
32263 | */ | ||
32264 | this.group = undefined; // toJSON | ||
32265 | |||
32266 | /** | ||
32267 | * Cached fields by id. | ||
32268 | * @type {Object.<number,Field>|null} | ||
32269 | * @private | ||
32270 | */ | ||
32271 | this._fieldsById = null; | ||
32272 | |||
32273 | /** | ||
32274 | * Cached fields as an array. | ||
32275 | * @type {Field[]|null} | ||
32276 | * @private | ||
32277 | */ | ||
32278 | this._fieldsArray = null; | ||
32279 | |||
32280 | /** | ||
32281 | * Cached oneofs as an array. | ||
32282 | * @type {OneOf[]|null} | ||
32283 | * @private | ||
32284 | */ | ||
32285 | this._oneofsArray = null; | ||
32286 | |||
32287 | /** | ||
32288 | * Cached constructor. | ||
32289 | * @type {Constructor<{}>} | ||
32290 | * @private | ||
32291 | */ | ||
32292 | this._ctor = null; | ||
32293 | } | ||
32294 | |||
32295 | Object.defineProperties(Type.prototype, { | ||
32296 | |||
32297 | /** | ||
32298 | * Message fields by id. | ||
32299 | * @name Type#fieldsById | ||
32300 | * @type {Object.<number,Field>} | ||
32301 | * @readonly | ||
32302 | */ | ||
32303 | fieldsById: { | ||
32304 | get: function() { | ||
32305 | |||
32306 | /* istanbul ignore if */ | ||
32307 | if (this._fieldsById) | ||
32308 | return this._fieldsById; | ||
32309 | |||
32310 | this._fieldsById = {}; | ||
32311 | for (var names = Object.keys(this.fields), i = 0; i < names.length; ++i) { | ||
32312 | var field = this.fields[names[i]], | ||
32313 | id = field.id; | ||
32314 | |||
32315 | /* istanbul ignore if */ | ||
32316 | if (this._fieldsById[id]) | ||
32317 | throw Error("duplicate id " + id + " in " + this); | ||
32318 | |||
32319 | this._fieldsById[id] = field; | ||
32320 | } | ||
32321 | return this._fieldsById; | ||
32322 | } | ||
32323 | }, | ||
32324 | |||
32325 | /** | ||
32326 | * Fields of this message as an array for iteration. | ||
32327 | * @name Type#fieldsArray | ||
32328 | * @type {Field[]} | ||
32329 | * @readonly | ||
32330 | */ | ||
32331 | fieldsArray: { | ||
32332 | get: function() { | ||
32333 | return this._fieldsArray || (this._fieldsArray = util.toArray(this.fields)); | ||
32334 | } | ||
32335 | }, | ||
32336 | |||
32337 | /** | ||
32338 | * Oneofs of this message as an array for iteration. | ||
32339 | * @name Type#oneofsArray | ||
32340 | * @type {OneOf[]} | ||
32341 | * @readonly | ||
32342 | */ | ||
32343 | oneofsArray: { | ||
32344 | get: function() { | ||
32345 | return this._oneofsArray || (this._oneofsArray = util.toArray(this.oneofs)); | ||
32346 | } | ||
32347 | }, | ||
32348 | |||
32349 | /** | ||
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. | ||
32352 | * @name Type#ctor | ||
32353 | * @type {Constructor<{}>} | ||
32354 | */ | ||
32355 | ctor: { | ||
32356 | get: function() { | ||
32357 | return this._ctor || (this.ctor = Type.generateConstructor(this)()); | ||
32358 | }, | ||
32359 | set: function(ctor) { | ||
32360 | |||
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); | ||
32366 | } | ||
32367 | |||
32368 | // Classes and messages reference their reflected type | ||
32369 | ctor.$type = ctor.prototype.$type = this; | ||
32370 | |||
32371 | // Mix in static methods | ||
32372 | util.merge(ctor, Message, true); | ||
32373 | |||
32374 | this._ctor = ctor; | ||
32375 | |||
32376 | // Messages have non-enumerable default values on their prototype | ||
32377 | var i = 0; | ||
32378 | for (; i < /* initializes */ this.fieldsArray.length; ++i) | ||
32379 | this._fieldsArray[i].resolve(); // ensures a proper value | ||
32380 | |||
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) | ||
32387 | }; | ||
32388 | if (i) | ||
32389 | Object.defineProperties(ctor.prototype, ctorProperties); | ||
32390 | } | ||
32391 | } | ||
32392 | }); | ||
32393 | |||
32394 | /** | ||
32395 | * Generates a constructor function for the specified type. | ||
32396 | * @param {Type} mtype Message type | ||
32397 | * @returns {Codegen} Codegen instance | ||
32398 | */ | ||
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)); | ||
32408 | return gen | ||
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 */ | ||
32412 | }; | ||
32413 | |||
32414 | function clearCache(type) { | ||
32415 | type._fieldsById = type._fieldsArray = type._oneofsArray = null; | ||
32416 | delete type.encode; | ||
32417 | delete type.decode; | ||
32418 | delete type.verify; | ||
32419 | return type; | ||
32420 | } | ||
32421 | |||
32422 | /** | ||
32423 | * Message type descriptor. | ||
32424 | * @interface IType | ||
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 | ||
32431 | */ | ||
32432 | |||
32433 | /** | ||
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 | ||
32438 | */ | ||
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), | ||
32444 | i = 0; | ||
32445 | for (; i < names.length; ++i) | ||
32446 | type.add( | ||
32447 | ( typeof json.fields[names[i]].keyType !== "undefined" | ||
32448 | ? MapField.fromJSON | ||
32449 | : Field.fromJSON )(names[i], json.fields[names[i]]) | ||
32450 | ); | ||
32451 | if (json.oneofs) | ||
32452 | for (names = Object.keys(json.oneofs), i = 0; i < names.length; ++i) | ||
32453 | type.add(OneOf.fromJSON(names[i], json.oneofs[names[i]])); | ||
32454 | if (json.nested) | ||
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 | ||
32459 | ? Field.fromJSON | ||
32460 | : nested.fields !== undefined | ||
32461 | ? Type.fromJSON | ||
32462 | : nested.values !== undefined | ||
32463 | ? Enum.fromJSON | ||
32464 | : nested.methods !== undefined | ||
32465 | ? Service.fromJSON | ||
32466 | : Namespace.fromJSON )(names[i], nested) | ||
32467 | ); | ||
32468 | } | ||
32469 | if (json.extensions && json.extensions.length) | ||
32470 | type.extensions = json.extensions; | ||
32471 | if (json.reserved && json.reserved.length) | ||
32472 | type.reserved = json.reserved; | ||
32473 | if (json.group) | ||
32474 | type.group = true; | ||
32475 | if (json.comment) | ||
32476 | type.comment = json.comment; | ||
32477 | return type; | ||
32478 | }; | ||
32479 | |||
32480 | /** | ||
32481 | * Converts this message type to a message type descriptor. | ||
32482 | * @param {IToJSONOptions} [toJSONOptions] JSON conversion options | ||
32483 | * @returns {IType} Message type descriptor | ||
32484 | */ | ||
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 | ||
32497 | ]); | ||
32498 | }; | ||
32499 | |||
32500 | /** | ||
32501 | * @override | ||
32502 | */ | ||
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); | ||
32511 | }; | ||
32512 | |||
32513 | /** | ||
32514 | * @override | ||
32515 | */ | ||
32516 | Type.prototype.get = function get(name) { | ||
32517 | return this.fields[name] | ||
32518 | || this.oneofs && this.oneofs[name] | ||
32519 | || this.nested && this.nested[name] | ||
32520 | || null; | ||
32521 | }; | ||
32522 | |||
32523 | /** | ||
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 | ||
32529 | */ | ||
32530 | Type.prototype.add = function add(object) { | ||
32531 | |||
32532 | if (this.get(object.name)) | ||
32533 | throw Error("duplicate name '" + object.name + "' in " + this); | ||
32534 | |||
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 | ||
32538 | // type instead. | ||
32539 | |||
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); | ||
32547 | |||
32548 | if (object.parent) | ||
32549 | object.parent.remove(object); | ||
32550 | this.fields[object.name] = object; | ||
32551 | object.message = this; | ||
32552 | object.onAdd(this); | ||
32553 | return clearCache(this); | ||
32554 | } | ||
32555 | if (object instanceof OneOf) { | ||
32556 | if (!this.oneofs) | ||
32557 | this.oneofs = {}; | ||
32558 | this.oneofs[object.name] = object; | ||
32559 | object.onAdd(this); | ||
32560 | return clearCache(this); | ||
32561 | } | ||
32562 | return Namespace.prototype.add.call(this, object); | ||
32563 | }; | ||
32564 | |||
32565 | /** | ||
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 | ||
32571 | */ | ||
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. | ||
32575 | |||
32576 | /* istanbul ignore if */ | ||
32577 | if (!this.fields || this.fields[object.name] !== object) | ||
32578 | throw Error(object + " is not a member of " + this); | ||
32579 | |||
32580 | delete this.fields[object.name]; | ||
32581 | object.parent = null; | ||
32582 | object.onRemove(this); | ||
32583 | return clearCache(this); | ||
32584 | } | ||
32585 | if (object instanceof OneOf) { | ||
32586 | |||
32587 | /* istanbul ignore if */ | ||
32588 | if (!this.oneofs || this.oneofs[object.name] !== object) | ||
32589 | throw Error(object + " is not a member of " + this); | ||
32590 | |||
32591 | delete this.oneofs[object.name]; | ||
32592 | object.parent = null; | ||
32593 | object.onRemove(this); | ||
32594 | return clearCache(this); | ||
32595 | } | ||
32596 | return Namespace.prototype.remove.call(this, object); | ||
32597 | }; | ||
32598 | |||
32599 | /** | ||
32600 | * Tests if the specified id is reserved. | ||
32601 | * @param {number} id Id to test | ||
32602 | * @returns {boolean} `true` if reserved, otherwise `false` | ||
32603 | */ | ||
32604 | Type.prototype.isReservedId = function isReservedId(id) { | ||
32605 | return Namespace.isReservedId(this.reserved, id); | ||
32606 | }; | ||
32607 | |||
32608 | /** | ||
32609 | * Tests if the specified name is reserved. | ||
32610 | * @param {string} name Name to test | ||
32611 | * @returns {boolean} `true` if reserved, otherwise `false` | ||
32612 | */ | ||
32613 | Type.prototype.isReservedName = function isReservedName(name) { | ||
32614 | return Namespace.isReservedName(this.reserved, name); | ||
32615 | }; | ||
32616 | |||
32617 | /** | ||
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 | ||
32621 | */ | ||
32622 | Type.prototype.create = function create(properties) { | ||
32623 | return new this.ctor(properties); | ||
32624 | }; | ||
32625 | |||
32626 | /** | ||
32627 | * Sets up {@link Type#encode|encode}, {@link Type#decode|decode} and {@link Type#verify|verify}. | ||
32628 | * @returns {Type} `this` | ||
32629 | */ | ||
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). | ||
32633 | |||
32634 | var fullName = this.fullName, | ||
32635 | types = []; | ||
32636 | for (var i = 0; i < /* initializes */ this.fieldsArray.length; ++i) | ||
32637 | types.push(this._fieldsArray[i].resolve().resolvedType); | ||
32638 | |||
32639 | // Replace setup methods with type-specific generated functions | ||
32640 | this.encode = encoder(this)({ | ||
32641 | Writer : Writer, | ||
32642 | types : types, | ||
32643 | util : util | ||
32644 | }); | ||
32645 | this.decode = decoder(this)({ | ||
32646 | Reader : Reader, | ||
32647 | types : types, | ||
32648 | util : util | ||
32649 | }); | ||
32650 | this.verify = verifier(this)({ | ||
32651 | types : types, | ||
32652 | util : util | ||
32653 | }); | ||
32654 | this.fromObject = converter.fromObject(this)({ | ||
32655 | types : types, | ||
32656 | util : util | ||
32657 | }); | ||
32658 | this.toObject = converter.toObject(this)({ | ||
32659 | types : types, | ||
32660 | util : util | ||
32661 | }); | ||
32662 | |||
32663 | // Inject custom wrappers for common types | ||
32664 | var wrapper = wrappers[fullName]; | ||
32665 | if (wrapper) { | ||
32666 | var originalThis = Object.create(this); | ||
32667 | // if (wrapper.fromObject) { | ||
32668 | originalThis.fromObject = this.fromObject; | ||
32669 | this.fromObject = wrapper.fromObject.bind(originalThis); | ||
32670 | // } | ||
32671 | // if (wrapper.toObject) { | ||
32672 | originalThis.toObject = this.toObject; | ||
32673 | this.toObject = wrapper.toObject.bind(originalThis); | ||
32674 | // } | ||
32675 | } | ||
32676 | |||
32677 | return this; | ||
32678 | }; | ||
32679 | |||
32680 | /** | ||
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 | ||
32685 | */ | ||
32686 | Type.prototype.encode = function encode_setup(message, writer) { | ||
32687 | return this.setup().encode(message, writer); // overrides this method | ||
32688 | }; | ||
32689 | |||
32690 | /** | ||
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 | ||
32695 | */ | ||
32696 | Type.prototype.encodeDelimited = function encodeDelimited(message, writer) { | ||
32697 | return this.encode(message, writer && writer.len ? writer.fork() : writer).ldelim(); | ||
32698 | }; | ||
32699 | |||
32700 | /** | ||
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 | ||
32707 | */ | ||
32708 | Type.prototype.decode = function decode_setup(reader, length) { | ||
32709 | return this.setup().decode(reader, length); // overrides this method | ||
32710 | }; | ||
32711 | |||
32712 | /** | ||
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 | ||
32718 | */ | ||
32719 | Type.prototype.decodeDelimited = function decodeDelimited(reader) { | ||
32720 | if (!(reader instanceof Reader)) | ||
32721 | reader = Reader.create(reader); | ||
32722 | return this.decode(reader, reader.uint32()); | ||
32723 | }; | ||
32724 | |||
32725 | /** | ||
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 | ||
32729 | */ | ||
32730 | Type.prototype.verify = function verify_setup(message) { | ||
32731 | return this.setup().verify(message); // overrides this method | ||
32732 | }; | ||
32733 | |||
32734 | /** | ||
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 | ||
32738 | */ | ||
32739 | Type.prototype.fromObject = function fromObject(object) { | ||
32740 | return this.setup().fromObject(object); | ||
32741 | }; | ||
32742 | |||
32743 | /** | ||
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 | ||
32760 | */ | ||
32761 | |||
32762 | /** | ||
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 | ||
32767 | */ | ||
32768 | Type.prototype.toObject = function toObject(message, options) { | ||
32769 | return this.setup().toObject(message, options); | ||
32770 | }; | ||
32771 | |||
32772 | /** | ||
32773 | * Decorator function as returned by {@link Type.d} (TypeScript). | ||
32774 | * @typedef TypeDecorator | ||
32775 | * @type {function} | ||
32776 | * @param {Constructor<T>} target Target constructor | ||
32777 | * @returns {undefined} | ||
32778 | * @template T extends Message<T> | ||
32779 | */ | ||
32780 | |||
32781 | /** | ||
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> | ||
32786 | */ | ||
32787 | Type.d = function decorateType(typeName) { | ||
32788 | return function typeDecorator(target) { | ||
32789 | util.decorateType(target, typeName); | ||
32790 | }; | ||
32791 | }; | ||
32792 | |||
32793 | },{"./converter":193,"./decoder":194,"./encoder":195,"./enum":196,"./field":197,"./mapfield":201,"./message":202,"./namespace":204,"./oneof":206,"./reader":208,"./service":214,"./util":218,"./verifier":221,"./wrappers":222,"./writer":223}],217:[function(require,module,exports){ | ||
32794 | "use strict"; | ||
32795 | |||
32796 | /** | ||
32797 | * Common type constants. | ||
32798 | * @namespace | ||
32799 | */ | ||
32800 | var types = exports; | ||
32801 | |||
32802 | var util = require("./util"); | ||
32803 | |||
32804 | var s = [ | ||
32805 | "double", // 0 | ||
32806 | "float", // 1 | ||
32807 | "int32", // 2 | ||
32808 | "uint32", // 3 | ||
32809 | "sint32", // 4 | ||
32810 | "fixed32", // 5 | ||
32811 | "sfixed32", // 6 | ||
32812 | "int64", // 7 | ||
32813 | "uint64", // 8 | ||
32814 | "sint64", // 9 | ||
32815 | "fixed64", // 10 | ||
32816 | "sfixed64", // 11 | ||
32817 | "bool", // 12 | ||
32818 | "string", // 13 | ||
32819 | "bytes" // 14 | ||
32820 | ]; | ||
32821 | |||
32822 | function bake(values, offset) { | ||
32823 | var i = 0, o = {}; | ||
32824 | offset |= 0; | ||
32825 | while (i < values.length) o[s[i + offset]] = values[i++]; | ||
32826 | return o; | ||
32827 | } | ||
32828 | |||
32829 | /** | ||
32830 | * Basic type wire types. | ||
32831 | * @type {Object.<string,number>} | ||
32832 | * @const | ||
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 | ||
32848 | */ | ||
32849 | types.basic = bake([ | ||
32850 | /* double */ 1, | ||
32851 | /* float */ 5, | ||
32852 | /* int32 */ 0, | ||
32853 | /* uint32 */ 0, | ||
32854 | /* sint32 */ 0, | ||
32855 | /* fixed32 */ 5, | ||
32856 | /* sfixed32 */ 5, | ||
32857 | /* int64 */ 0, | ||
32858 | /* uint64 */ 0, | ||
32859 | /* sint64 */ 0, | ||
32860 | /* fixed64 */ 1, | ||
32861 | /* sfixed64 */ 1, | ||
32862 | /* bool */ 0, | ||
32863 | /* string */ 2, | ||
32864 | /* bytes */ 2 | ||
32865 | ]); | ||
32866 | |||
32867 | /** | ||
32868 | * Basic type defaults. | ||
32869 | * @type {Object.<string,*>} | ||
32870 | * @const | ||
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 | ||
32887 | */ | ||
32888 | types.defaults = bake([ | ||
32889 | /* double */ 0, | ||
32890 | /* float */ 0, | ||
32891 | /* int32 */ 0, | ||
32892 | /* uint32 */ 0, | ||
32893 | /* sint32 */ 0, | ||
32894 | /* fixed32 */ 0, | ||
32895 | /* sfixed32 */ 0, | ||
32896 | /* int64 */ 0, | ||
32897 | /* uint64 */ 0, | ||
32898 | /* sint64 */ 0, | ||
32899 | /* fixed64 */ 0, | ||
32900 | /* sfixed64 */ 0, | ||
32901 | /* bool */ false, | ||
32902 | /* string */ "", | ||
32903 | /* bytes */ util.emptyArray, | ||
32904 | /* message */ null | ||
32905 | ]); | ||
32906 | |||
32907 | /** | ||
32908 | * Basic long type wire types. | ||
32909 | * @type {Object.<string,number>} | ||
32910 | * @const | ||
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 | ||
32916 | */ | ||
32917 | types.long = bake([ | ||
32918 | /* int64 */ 0, | ||
32919 | /* uint64 */ 0, | ||
32920 | /* sint64 */ 0, | ||
32921 | /* fixed64 */ 1, | ||
32922 | /* sfixed64 */ 1 | ||
32923 | ], 7); | ||
32924 | |||
32925 | /** | ||
32926 | * Allowed types for map keys with their associated wire type. | ||
32927 | * @type {Object.<string,number>} | ||
32928 | * @const | ||
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 | ||
32941 | */ | ||
32942 | types.mapKey = bake([ | ||
32943 | /* int32 */ 0, | ||
32944 | /* uint32 */ 0, | ||
32945 | /* sint32 */ 0, | ||
32946 | /* fixed32 */ 5, | ||
32947 | /* sfixed32 */ 5, | ||
32948 | /* int64 */ 0, | ||
32949 | /* uint64 */ 0, | ||
32950 | /* sint64 */ 0, | ||
32951 | /* fixed64 */ 1, | ||
32952 | /* sfixed64 */ 1, | ||
32953 | /* bool */ 0, | ||
32954 | /* string */ 2 | ||
32955 | ], 2); | ||
32956 | |||
32957 | /** | ||
32958 | * Allowed types for packed repeated fields with their associated wire type. | ||
32959 | * @type {Object.<string,number>} | ||
32960 | * @const | ||
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 | ||
32974 | */ | ||
32975 | types.packed = bake([ | ||
32976 | /* double */ 1, | ||
32977 | /* float */ 5, | ||
32978 | /* int32 */ 0, | ||
32979 | /* uint32 */ 0, | ||
32980 | /* sint32 */ 0, | ||
32981 | /* fixed32 */ 5, | ||
32982 | /* sfixed32 */ 5, | ||
32983 | /* int64 */ 0, | ||
32984 | /* uint64 */ 0, | ||
32985 | /* sint64 */ 0, | ||
32986 | /* fixed64 */ 1, | ||
32987 | /* sfixed64 */ 1, | ||
32988 | /* bool */ 0 | ||
32989 | ]); | ||
32990 | |||
32991 | },{"./util":218}],218:[function(require,module,exports){ | ||
32992 | "use strict"; | ||
32993 | |||
32994 | /** | ||
32995 | * Various utility functions. | ||
32996 | * @namespace | ||
32997 | */ | ||
32998 | var util = module.exports = require("./util/minimal"); | ||
32999 | |||
33000 | var roots = require("./roots"); | ||
33001 | |||
33002 | var Type, // cyclic | ||
33003 | Enum; | ||
33004 | |||
33005 | util.codegen = require("@protobufjs/codegen"); | ||
33006 | util.fetch = require("@protobufjs/fetch"); | ||
33007 | util.path = require("@protobufjs/path"); | ||
33008 | |||
33009 | /** | ||
33010 | * Node's fs module if available. | ||
33011 | * @type {Object.<string,*>} | ||
33012 | */ | ||
33013 | util.fs = util.inquire("fs"); | ||
33014 | |||
33015 | /** | ||
33016 | * Converts an object's values to an array. | ||
33017 | * @param {Object.<string,*>} object Object to convert | ||
33018 | * @returns {Array.<*>} Converted array | ||
33019 | */ | ||
33020 | util.toArray = function toArray(object) { | ||
33021 | if (object) { | ||
33022 | var keys = Object.keys(object), | ||
33023 | array = new Array(keys.length), | ||
33024 | index = 0; | ||
33025 | while (index < keys.length) | ||
33026 | array[index] = object[keys[index++]]; | ||
33027 | return array; | ||
33028 | } | ||
33029 | return []; | ||
33030 | }; | ||
33031 | |||
33032 | /** | ||
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 | ||
33036 | */ | ||
33037 | util.toObject = function toObject(array) { | ||
33038 | var object = {}, | ||
33039 | index = 0; | ||
33040 | while (index < array.length) { | ||
33041 | var key = array[index++], | ||
33042 | val = array[index++]; | ||
33043 | if (val !== undefined) | ||
33044 | object[key] = val; | ||
33045 | } | ||
33046 | return object; | ||
33047 | }; | ||
33048 | |||
33049 | var safePropBackslashRe = /\\/g, | ||
33050 | safePropQuoteRe = /"/g; | ||
33051 | |||
33052 | /** | ||
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` | ||
33056 | */ | ||
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); | ||
33059 | }; | ||
33060 | |||
33061 | /** | ||
33062 | * Returns a safe property accessor for the specified property name. | ||
33063 | * @param {string} prop Property name | ||
33064 | * @returns {string} Safe accessor | ||
33065 | */ | ||
33066 | util.safeProp = function safeProp(prop) { | ||
33067 | if (!/^[$\w_]+$/.test(prop) || util.isReserved(prop)) | ||
33068 | return "[\"" + prop.replace(safePropBackslashRe, "\\\\").replace(safePropQuoteRe, "\\\"") + "\"]"; | ||
33069 | return "." + prop; | ||
33070 | }; | ||
33071 | |||
33072 | /** | ||
33073 | * Converts the first character of a string to upper case. | ||
33074 | * @param {string} str String to convert | ||
33075 | * @returns {string} Converted string | ||
33076 | */ | ||
33077 | util.ucFirst = function ucFirst(str) { | ||
33078 | return str.charAt(0).toUpperCase() + str.substring(1); | ||
33079 | }; | ||
33080 | |||
33081 | var camelCaseRe = /_([a-z])/g; | ||
33082 | |||
33083 | /** | ||
33084 | * Converts a string to camel case. | ||
33085 | * @param {string} str String to convert | ||
33086 | * @returns {string} Converted string | ||
33087 | */ | ||
33088 | util.camelCase = function camelCase(str) { | ||
33089 | return str.substring(0, 1) | ||
33090 | + str.substring(1) | ||
33091 | .replace(camelCaseRe, function($0, $1) { return $1.toUpperCase(); }); | ||
33092 | }; | ||
33093 | |||
33094 | /** | ||
33095 | * Compares reflected fields by id. | ||
33096 | * @param {Field} a First field | ||
33097 | * @param {Field} b Second field | ||
33098 | * @returns {number} Comparison value | ||
33099 | */ | ||
33100 | util.compareFieldsById = function compareFieldsById(a, b) { | ||
33101 | return a.id - b.id; | ||
33102 | }; | ||
33103 | |||
33104 | /** | ||
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 | ||
33111 | */ | ||
33112 | util.decorateType = function decorateType(ctor, typeName) { | ||
33113 | |||
33114 | /* istanbul ignore if */ | ||
33115 | if (ctor.$type) { | ||
33116 | if (typeName && ctor.$type.name !== typeName) { | ||
33117 | util.decorateRoot.remove(ctor.$type); | ||
33118 | ctor.$type.name = typeName; | ||
33119 | util.decorateRoot.add(ctor.$type); | ||
33120 | } | ||
33121 | return ctor.$type; | ||
33122 | } | ||
33123 | |||
33124 | /* istanbul ignore next */ | ||
33125 | if (!Type) | ||
33126 | Type = require("./type"); | ||
33127 | |||
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 }); | ||
33133 | return type; | ||
33134 | }; | ||
33135 | |||
33136 | var decorateEnumIndex = 0; | ||
33137 | |||
33138 | /** | ||
33139 | * Decorator helper for enums (TypeScript). | ||
33140 | * @param {Object} object Enum object | ||
33141 | * @returns {Enum} Reflected enum | ||
33142 | */ | ||
33143 | util.decorateEnum = function decorateEnum(object) { | ||
33144 | |||
33145 | /* istanbul ignore if */ | ||
33146 | if (object.$type) | ||
33147 | return object.$type; | ||
33148 | |||
33149 | /* istanbul ignore next */ | ||
33150 | if (!Enum) | ||
33151 | Enum = require("./enum"); | ||
33152 | |||
33153 | var enm = new Enum("Enum" + decorateEnumIndex++, object); | ||
33154 | util.decorateRoot.add(enm); | ||
33155 | Object.defineProperty(object, "$type", { value: enm, enumerable: false }); | ||
33156 | return enm; | ||
33157 | }; | ||
33158 | |||
33159 | /** | ||
33160 | * Decorator root (TypeScript). | ||
33161 | * @name util.decorateRoot | ||
33162 | * @type {Root} | ||
33163 | * @readonly | ||
33164 | */ | ||
33165 | Object.defineProperty(util, "decorateRoot", { | ||
33166 | get: function() { | ||
33167 | return roots["decorated"] || (roots["decorated"] = new (require("./root"))()); | ||
33168 | } | ||
33169 | }); | ||
33170 | |||
33171 | },{"./enum":196,"./root":210,"./roots":211,"./type":216,"./util/minimal":220,"@protobufjs/codegen":24,"@protobufjs/fetch":26,"@protobufjs/path":29}],219:[function(require,module,exports){ | ||
33172 | "use strict"; | ||
33173 | module.exports = LongBits; | ||
33174 | |||
33175 | var util = require("../util/minimal"); | ||
33176 | |||
33177 | /** | ||
33178 | * Constructs new long bits. | ||
33179 | * @classdesc Helper class for working with the low and high bits of a 64 bit value. | ||
33180 | * @memberof util | ||
33181 | * @constructor | ||
33182 | * @param {number} lo Low 32 bits, unsigned | ||
33183 | * @param {number} hi High 32 bits, unsigned | ||
33184 | */ | ||
33185 | function LongBits(lo, hi) { | ||
33186 | |||
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. | ||
33189 | |||
33190 | /** | ||
33191 | * Low bits. | ||
33192 | * @type {number} | ||
33193 | */ | ||
33194 | this.lo = lo >>> 0; | ||
33195 | |||
33196 | /** | ||
33197 | * High bits. | ||
33198 | * @type {number} | ||
33199 | */ | ||
33200 | this.hi = hi >>> 0; | ||
33201 | } | ||
33202 | |||
33203 | /** | ||
33204 | * Zero bits. | ||
33205 | * @memberof util.LongBits | ||
33206 | * @type {util.LongBits} | ||
33207 | */ | ||
33208 | var zero = LongBits.zero = new LongBits(0, 0); | ||
33209 | |||
33210 | zero.toNumber = function() { return 0; }; | ||
33211 | zero.zzEncode = zero.zzDecode = function() { return this; }; | ||
33212 | zero.length = function() { return 1; }; | ||
33213 | |||
33214 | /** | ||
33215 | * Zero hash. | ||
33216 | * @memberof util.LongBits | ||
33217 | * @type {string} | ||
33218 | */ | ||
33219 | var zeroHash = LongBits.zeroHash = "\0\0\0\0\0\0\0\0"; | ||
33220 | |||
33221 | /** | ||
33222 | * Constructs new long bits from the specified number. | ||
33223 | * @param {number} value Value | ||
33224 | * @returns {util.LongBits} Instance | ||
33225 | */ | ||
33226 | LongBits.fromNumber = function fromNumber(value) { | ||
33227 | if (value === 0) | ||
33228 | return zero; | ||
33229 | var sign = value < 0; | ||
33230 | if (sign) | ||
33231 | value = -value; | ||
33232 | var lo = value >>> 0, | ||
33233 | hi = (value - lo) / 4294967296 >>> 0; | ||
33234 | if (sign) { | ||
33235 | hi = ~hi >>> 0; | ||
33236 | lo = ~lo >>> 0; | ||
33237 | if (++lo > 4294967295) { | ||
33238 | lo = 0; | ||
33239 | if (++hi > 4294967295) | ||
33240 | hi = 0; | ||
33241 | } | ||
33242 | } | ||
33243 | return new LongBits(lo, hi); | ||
33244 | }; | ||
33245 | |||
33246 | /** | ||
33247 | * Constructs new long bits from a number, long or string. | ||
33248 | * @param {Long|number|string} value Value | ||
33249 | * @returns {util.LongBits} Instance | ||
33250 | */ | ||
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 */ | ||
33256 | if (util.Long) | ||
33257 | value = util.Long.fromString(value); | ||
33258 | else | ||
33259 | return LongBits.fromNumber(parseInt(value, 10)); | ||
33260 | } | ||
33261 | return value.low || value.high ? new LongBits(value.low >>> 0, value.high >>> 0) : zero; | ||
33262 | }; | ||
33263 | |||
33264 | /** | ||
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 | ||
33268 | */ | ||
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; | ||
33273 | if (!lo) | ||
33274 | hi = hi + 1 >>> 0; | ||
33275 | return -(lo + hi * 4294967296); | ||
33276 | } | ||
33277 | return this.lo + this.hi * 4294967296; | ||
33278 | }; | ||
33279 | |||
33280 | /** | ||
33281 | * Converts this long bits to a long. | ||
33282 | * @param {boolean} [unsigned=false] Whether unsigned or not | ||
33283 | * @returns {Long} Long | ||
33284 | */ | ||
33285 | LongBits.prototype.toLong = function toLong(unsigned) { | ||
33286 | return util.Long | ||
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) }; | ||
33290 | }; | ||
33291 | |||
33292 | var charCodeAt = String.prototype.charCodeAt; | ||
33293 | |||
33294 | /** | ||
33295 | * Constructs new long bits from the specified 8 characters long hash. | ||
33296 | * @param {string} hash Hash | ||
33297 | * @returns {util.LongBits} Bits | ||
33298 | */ | ||
33299 | LongBits.fromHash = function fromHash(hash) { | ||
33300 | if (hash === zeroHash) | ||
33301 | return zero; | ||
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 | ||
33307 | , | ||
33308 | ( charCodeAt.call(hash, 4) | ||
33309 | | charCodeAt.call(hash, 5) << 8 | ||
33310 | | charCodeAt.call(hash, 6) << 16 | ||
33311 | | charCodeAt.call(hash, 7) << 24) >>> 0 | ||
33312 | ); | ||
33313 | }; | ||
33314 | |||
33315 | /** | ||
33316 | * Converts this long bits to a 8 characters long hash. | ||
33317 | * @returns {string} Hash | ||
33318 | */ | ||
33319 | LongBits.prototype.toHash = function toHash() { | ||
33320 | return String.fromCharCode( | ||
33321 | this.lo & 255, | ||
33322 | this.lo >>> 8 & 255, | ||
33323 | this.lo >>> 16 & 255, | ||
33324 | this.lo >>> 24 , | ||
33325 | this.hi & 255, | ||
33326 | this.hi >>> 8 & 255, | ||
33327 | this.hi >>> 16 & 255, | ||
33328 | this.hi >>> 24 | ||
33329 | ); | ||
33330 | }; | ||
33331 | |||
33332 | /** | ||
33333 | * Zig-zag encodes this long bits. | ||
33334 | * @returns {util.LongBits} `this` | ||
33335 | */ | ||
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; | ||
33340 | return this; | ||
33341 | }; | ||
33342 | |||
33343 | /** | ||
33344 | * Zig-zag decodes this long bits. | ||
33345 | * @returns {util.LongBits} `this` | ||
33346 | */ | ||
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; | ||
33351 | return this; | ||
33352 | }; | ||
33353 | |||
33354 | /** | ||
33355 | * Calculates the length of this longbits when encoded as a varint. | ||
33356 | * @returns {number} Length | ||
33357 | */ | ||
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; | ||
33362 | return part2 === 0 | ||
33363 | ? part1 === 0 | ||
33364 | ? part0 < 16384 | ||
33365 | ? part0 < 128 ? 1 : 2 | ||
33366 | : part0 < 2097152 ? 3 : 4 | ||
33367 | : part1 < 16384 | ||
33368 | ? part1 < 128 ? 5 : 6 | ||
33369 | : part1 < 2097152 ? 7 : 8 | ||
33370 | : part2 < 128 ? 9 : 10; | ||
33371 | }; | ||
33372 | |||
33373 | },{"../util/minimal":220}],220:[function(require,module,exports){ | ||
33374 | (function (global){ | ||
33375 | "use strict"; | ||
33376 | var util = exports; | ||
33377 | |||
33378 | // used to return a Promise where callback is omitted | ||
33379 | util.asPromise = require("@protobufjs/aspromise"); | ||
33380 | |||
33381 | // converts to / from base64 encoded strings | ||
33382 | util.base64 = require("@protobufjs/base64"); | ||
33383 | |||
33384 | // base class of rpc.Service | ||
33385 | util.EventEmitter = require("@protobufjs/eventemitter"); | ||
33386 | |||
33387 | // float handling accross browsers | ||
33388 | util.float = require("@protobufjs/float"); | ||
33389 | |||
33390 | // requires modules optionally and hides the call from bundlers | ||
33391 | util.inquire = require("@protobufjs/inquire"); | ||
33392 | |||
33393 | // converts to / from utf8 encoded strings | ||
33394 | util.utf8 = require("@protobufjs/utf8"); | ||
33395 | |||
33396 | // provides a node-like buffer pool in the browser | ||
33397 | util.pool = require("@protobufjs/pool"); | ||
33398 | |||
33399 | // utility to work with the low and high bits of a 64 bit value | ||
33400 | util.LongBits = require("./longbits"); | ||
33401 | |||
33402 | /** | ||
33403 | * An immuable empty array. | ||
33404 | * @memberof util | ||
33405 | * @type {Array.<*>} | ||
33406 | * @const | ||
33407 | */ | ||
33408 | util.emptyArray = Object.freeze ? Object.freeze([]) : /* istanbul ignore next */ []; // used on prototypes | ||
33409 | |||
33410 | /** | ||
33411 | * An immutable empty object. | ||
33412 | * @type {Object} | ||
33413 | * @const | ||
33414 | */ | ||
33415 | util.emptyObject = Object.freeze ? Object.freeze({}) : /* istanbul ignore next */ {}; // used on prototypes | ||
33416 | |||
33417 | /** | ||
33418 | * Whether running within node or not. | ||
33419 | * @memberof util | ||
33420 | * @type {boolean} | ||
33421 | * @const | ||
33422 | */ | ||
33423 | util.isNode = Boolean(global.process && global.process.versions && global.process.versions.node); | ||
33424 | |||
33425 | /** | ||
33426 | * Tests if the specified value is an integer. | ||
33427 | * @function | ||
33428 | * @param {*} value Value to test | ||
33429 | * @returns {boolean} `true` if the value is an integer | ||
33430 | */ | ||
33431 | util.isInteger = Number.isInteger || /* istanbul ignore next */ function isInteger(value) { | ||
33432 | return typeof value === "number" && isFinite(value) && Math.floor(value) === value; | ||
33433 | }; | ||
33434 | |||
33435 | /** | ||
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 | ||
33439 | */ | ||
33440 | util.isString = function isString(value) { | ||
33441 | return typeof value === "string" || value instanceof String; | ||
33442 | }; | ||
33443 | |||
33444 | /** | ||
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 | ||
33448 | */ | ||
33449 | util.isObject = function isObject(value) { | ||
33450 | return value && typeof value === "object"; | ||
33451 | }; | ||
33452 | |||
33453 | /** | ||
33454 | * Checks if a property on a message is considered to be present. | ||
33455 | * This is an alias of {@link util.isSet}. | ||
33456 | * @function | ||
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` | ||
33460 | */ | ||
33461 | util.isset = | ||
33462 | |||
33463 | /** | ||
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` | ||
33468 | */ | ||
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; | ||
33473 | return false; | ||
33474 | }; | ||
33475 | |||
33476 | /** | ||
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 | ||
33481 | */ | ||
33482 | |||
33483 | /** | ||
33484 | * Node's Buffer class if available. | ||
33485 | * @type {Constructor<Buffer>} | ||
33486 | */ | ||
33487 | util.Buffer = (function() { | ||
33488 | try { | ||
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; | ||
33492 | } catch (e) { | ||
33493 | /* istanbul ignore next */ | ||
33494 | return null; | ||
33495 | } | ||
33496 | })(); | ||
33497 | |||
33498 | // Internal alias of or polyfull for Buffer.from. | ||
33499 | util._Buffer_from = null; | ||
33500 | |||
33501 | // Internal alias of or polyfill for Buffer.allocUnsafe. | ||
33502 | util._Buffer_allocUnsafe = null; | ||
33503 | |||
33504 | /** | ||
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 | ||
33508 | */ | ||
33509 | util.newBuffer = function newBuffer(sizeOrArray) { | ||
33510 | /* istanbul ignore next */ | ||
33511 | return typeof sizeOrArray === "number" | ||
33512 | ? util.Buffer | ||
33513 | ? util._Buffer_allocUnsafe(sizeOrArray) | ||
33514 | : new util.Array(sizeOrArray) | ||
33515 | : util.Buffer | ||
33516 | ? util._Buffer_from(sizeOrArray) | ||
33517 | : typeof Uint8Array === "undefined" | ||
33518 | ? sizeOrArray | ||
33519 | : new Uint8Array(sizeOrArray); | ||
33520 | }; | ||
33521 | |||
33522 | /** | ||
33523 | * Array implementation used in the browser. `Uint8Array` if supported, otherwise `Array`. | ||
33524 | * @type {Constructor<Uint8Array>} | ||
33525 | */ | ||
33526 | util.Array = typeof Uint8Array !== "undefined" ? Uint8Array /* istanbul ignore next */ : Array; | ||
33527 | |||
33528 | /** | ||
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. | ||
33531 | * @interface Long | ||
33532 | * @property {number} low Low bits | ||
33533 | * @property {number} high High bits | ||
33534 | * @property {boolean} unsigned Whether unsigned or not | ||
33535 | */ | ||
33536 | |||
33537 | /** | ||
33538 | * Long.js's Long class if available. | ||
33539 | * @type {Constructor<Long>} | ||
33540 | */ | ||
33541 | util.Long = /* istanbul ignore next */ global.dcodeIO && /* istanbul ignore next */ global.dcodeIO.Long || util.inquire("long"); | ||
33542 | |||
33543 | /** | ||
33544 | * Regular expression used to verify 2 bit (`bool`) map keys. | ||
33545 | * @type {RegExp} | ||
33546 | * @const | ||
33547 | */ | ||
33548 | util.key2Re = /^true|false|0|1$/; | ||
33549 | |||
33550 | /** | ||
33551 | * Regular expression used to verify 32 bit (`int32` etc.) map keys. | ||
33552 | * @type {RegExp} | ||
33553 | * @const | ||
33554 | */ | ||
33555 | util.key32Re = /^-?(?:0|[1-9][0-9]*)$/; | ||
33556 | |||
33557 | /** | ||
33558 | * Regular expression used to verify 64 bit (`int64` etc.) map keys. | ||
33559 | * @type {RegExp} | ||
33560 | * @const | ||
33561 | */ | ||
33562 | util.key64Re = /^(?:[\\x00-\\xff]{8}|-?(?:0|[1-9][0-9]*))$/; | ||
33563 | |||
33564 | /** | ||
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 | ||
33568 | */ | ||
33569 | util.longToHash = function longToHash(value) { | ||
33570 | return value | ||
33571 | ? util.LongBits.from(value).toHash() | ||
33572 | : util.LongBits.zeroHash; | ||
33573 | }; | ||
33574 | |||
33575 | /** | ||
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 | ||
33580 | */ | ||
33581 | util.longFromHash = function longFromHash(hash, unsigned) { | ||
33582 | var bits = util.LongBits.fromHash(hash); | ||
33583 | if (util.Long) | ||
33584 | return util.Long.fromBits(bits.lo, bits.hi, unsigned); | ||
33585 | return bits.toNumber(Boolean(unsigned)); | ||
33586 | }; | ||
33587 | |||
33588 | /** | ||
33589 | * Merges the properties of the source object into the destination object. | ||
33590 | * @memberof util | ||
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 | ||
33595 | */ | ||
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]]; | ||
33600 | return dst; | ||
33601 | } | ||
33602 | |||
33603 | util.merge = merge; | ||
33604 | |||
33605 | /** | ||
33606 | * Converts the first character of a string to lower case. | ||
33607 | * @param {string} str String to convert | ||
33608 | * @returns {string} Converted string | ||
33609 | */ | ||
33610 | util.lcFirst = function lcFirst(str) { | ||
33611 | return str.charAt(0).toLowerCase() + str.substring(1); | ||
33612 | }; | ||
33613 | |||
33614 | /** | ||
33615 | * Creates a custom error constructor. | ||
33616 | * @memberof util | ||
33617 | * @param {string} name Error name | ||
33618 | * @returns {Constructor<Error>} Custom error constructor | ||
33619 | */ | ||
33620 | function newError(name) { | ||
33621 | |||
33622 | function CustomError(message, properties) { | ||
33623 | |||
33624 | if (!(this instanceof CustomError)) | ||
33625 | return new CustomError(message, properties); | ||
33626 | |||
33627 | // Error.call(this, message); | ||
33628 | // ^ just returns a new error instance because the ctor can be called as a function | ||
33629 | |||
33630 | Object.defineProperty(this, "message", { get: function() { return message; } }); | ||
33631 | |||
33632 | /* istanbul ignore next */ | ||
33633 | if (Error.captureStackTrace) // node | ||
33634 | Error.captureStackTrace(this, CustomError); | ||
33635 | else | ||
33636 | Object.defineProperty(this, "stack", { value: (new Error()).stack || "" }); | ||
33637 | |||
33638 | if (properties) | ||
33639 | merge(this, properties); | ||
33640 | } | ||
33641 | |||
33642 | (CustomError.prototype = Object.create(Error.prototype)).constructor = CustomError; | ||
33643 | |||
33644 | Object.defineProperty(CustomError.prototype, "name", { get: function() { return name; } }); | ||
33645 | |||
33646 | CustomError.prototype.toString = function toString() { | ||
33647 | return this.name + ": " + this.message; | ||
33648 | }; | ||
33649 | |||
33650 | return CustomError; | ||
33651 | } | ||
33652 | |||
33653 | util.newError = newError; | ||
33654 | |||
33655 | /** | ||
33656 | * Constructs a new protocol error. | ||
33657 | * @classdesc Error subclass indicating a protocol specifc error. | ||
33658 | * @memberof util | ||
33659 | * @extends Error | ||
33660 | * @template T extends Message<T> | ||
33661 | * @constructor | ||
33662 | * @param {string} message Error message | ||
33663 | * @param {Object.<string,*>} [properties] Additional properties | ||
33664 | * @example | ||
33665 | * try { | ||
33666 | * MyMessage.decode(someBuffer); // throws if required fields are missing | ||
33667 | * } catch (e) { | ||
33668 | * if (e instanceof ProtocolError && e.instance) | ||
33669 | * console.log("decoded so far: " + JSON.stringify(e.instance)); | ||
33670 | * } | ||
33671 | */ | ||
33672 | util.ProtocolError = newError("ProtocolError"); | ||
33673 | |||
33674 | /** | ||
33675 | * So far decoded message instance. | ||
33676 | * @name util.ProtocolError#instance | ||
33677 | * @type {Message<T>} | ||
33678 | */ | ||
33679 | |||
33680 | /** | ||
33681 | * A OneOf getter as returned by {@link util.oneOfGetter}. | ||
33682 | * @typedef OneOfGetter | ||
33683 | * @type {function} | ||
33684 | * @returns {string|undefined} Set field name, if any | ||
33685 | */ | ||
33686 | |||
33687 | /** | ||
33688 | * Builds a getter for a oneof's present field name. | ||
33689 | * @param {string[]} fieldNames Field names | ||
33690 | * @returns {OneOfGetter} Unbound getter | ||
33691 | */ | ||
33692 | util.oneOfGetter = function getOneOf(fieldNames) { | ||
33693 | var fieldMap = {}; | ||
33694 | for (var i = 0; i < fieldNames.length; ++i) | ||
33695 | fieldMap[fieldNames[i]] = 1; | ||
33696 | |||
33697 | /** | ||
33698 | * @returns {string|undefined} Set field name, if any | ||
33699 | * @this Object | ||
33700 | * @ignore | ||
33701 | */ | ||
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) | ||
33705 | return keys[i]; | ||
33706 | }; | ||
33707 | }; | ||
33708 | |||
33709 | /** | ||
33710 | * A OneOf setter as returned by {@link util.oneOfSetter}. | ||
33711 | * @typedef OneOfSetter | ||
33712 | * @type {function} | ||
33713 | * @param {string|undefined} value Field name | ||
33714 | * @returns {undefined} | ||
33715 | */ | ||
33716 | |||
33717 | /** | ||
33718 | * Builds a setter for a oneof's present field name. | ||
33719 | * @param {string[]} fieldNames Field names | ||
33720 | * @returns {OneOfSetter} Unbound setter | ||
33721 | */ | ||
33722 | util.oneOfSetter = function setOneOf(fieldNames) { | ||
33723 | |||
33724 | /** | ||
33725 | * @param {string} name Field name | ||
33726 | * @returns {undefined} | ||
33727 | * @this Object | ||
33728 | * @ignore | ||
33729 | */ | ||
33730 | return function(name) { | ||
33731 | for (var i = 0; i < fieldNames.length; ++i) | ||
33732 | if (fieldNames[i] !== name) | ||
33733 | delete this[fieldNames[i]]; | ||
33734 | }; | ||
33735 | }; | ||
33736 | |||
33737 | /** | ||
33738 | * Default conversion options used for {@link Message#toJSON} implementations. | ||
33739 | * | ||
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: | ||
33741 | * | ||
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 | ||
33749 | * | ||
33750 | * @type {IConversionOptions} | ||
33751 | * @see https://developers.google.com/protocol-buffers/docs/proto3?hl=en#json | ||
33752 | */ | ||
33753 | util.toJSONOptions = { | ||
33754 | longs: String, | ||
33755 | enums: String, | ||
33756 | bytes: String, | ||
33757 | json: true | ||
33758 | }; | ||
33759 | |||
33760 | util._configure = function() { | ||
33761 | var Buffer = util.Buffer; | ||
33762 | /* istanbul ignore if */ | ||
33763 | if (!Buffer) { | ||
33764 | util._Buffer_from = util._Buffer_allocUnsafe = null; | ||
33765 | return; | ||
33766 | } | ||
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); | ||
33773 | }; | ||
33774 | util._Buffer_allocUnsafe = Buffer.allocUnsafe || | ||
33775 | /* istanbul ignore next */ | ||
33776 | function Buffer_allocUnsafe(size) { | ||
33777 | return new Buffer(size); | ||
33778 | }; | ||
33779 | }; | ||
33780 | |||
33781 | }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | ||
33782 | },{"./longbits":219,"@protobufjs/aspromise":22,"@protobufjs/base64":23,"@protobufjs/eventemitter":25,"@protobufjs/float":27,"@protobufjs/inquire":28,"@protobufjs/pool":30,"@protobufjs/utf8":31}],221:[function(require,module,exports){ | ||
33783 | "use strict"; | ||
33784 | module.exports = verifier; | ||
33785 | |||
33786 | var Enum = require("./enum"), | ||
33787 | util = require("./util"); | ||
33788 | |||
33789 | function invalid(field, expected) { | ||
33790 | return field.name + ": " + expected + (field.repeated && expected !== "array" ? "[]" : field.map && expected !== "object" ? "{k:"+field.keyType+"}" : "") + " expected"; | ||
33791 | } | ||
33792 | |||
33793 | /** | ||
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 | ||
33800 | * @ignore | ||
33801 | */ | ||
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) | ||
33807 | ("default:") | ||
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]]); | ||
33811 | gen | ||
33812 | ("break") | ||
33813 | ("}"); | ||
33814 | } else { | ||
33815 | gen | ||
33816 | ("{") | ||
33817 | ("var e=types[%i].verify(%s);", fieldIndex, ref) | ||
33818 | ("if(e)") | ||
33819 | ("return%j+e", field.name + ".") | ||
33820 | ("}"); | ||
33821 | } | ||
33822 | } else { | ||
33823 | switch (field.type) { | ||
33824 | case "int32": | ||
33825 | case "uint32": | ||
33826 | case "sint32": | ||
33827 | case "fixed32": | ||
33828 | case "sfixed32": gen | ||
33829 | ("if(!util.isInteger(%s))", ref) | ||
33830 | ("return%j", invalid(field, "integer")); | ||
33831 | break; | ||
33832 | case "int64": | ||
33833 | case "uint64": | ||
33834 | case "sint64": | ||
33835 | case "fixed64": | ||
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")); | ||
33839 | break; | ||
33840 | case "float": | ||
33841 | case "double": gen | ||
33842 | ("if(typeof %s!==\"number\")", ref) | ||
33843 | ("return%j", invalid(field, "number")); | ||
33844 | break; | ||
33845 | case "bool": gen | ||
33846 | ("if(typeof %s!==\"boolean\")", ref) | ||
33847 | ("return%j", invalid(field, "boolean")); | ||
33848 | break; | ||
33849 | case "string": gen | ||
33850 | ("if(!util.isString(%s))", ref) | ||
33851 | ("return%j", invalid(field, "string")); | ||
33852 | break; | ||
33853 | case "bytes": gen | ||
33854 | ("if(!(%s&&typeof %s.length===\"number\"||util.isString(%s)))", ref, ref, ref) | ||
33855 | ("return%j", invalid(field, "buffer")); | ||
33856 | break; | ||
33857 | } | ||
33858 | } | ||
33859 | return gen; | ||
33860 | /* eslint-enable no-unexpected-multiline */ | ||
33861 | } | ||
33862 | |||
33863 | /** | ||
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 | ||
33869 | * @ignore | ||
33870 | */ | ||
33871 | function genVerifyKey(gen, field, ref) { | ||
33872 | /* eslint-disable no-unexpected-multiline */ | ||
33873 | switch (field.keyType) { | ||
33874 | case "int32": | ||
33875 | case "uint32": | ||
33876 | case "sint32": | ||
33877 | case "fixed32": | ||
33878 | case "sfixed32": gen | ||
33879 | ("if(!util.key32Re.test(%s))", ref) | ||
33880 | ("return%j", invalid(field, "integer key")); | ||
33881 | break; | ||
33882 | case "int64": | ||
33883 | case "uint64": | ||
33884 | case "sint64": | ||
33885 | case "fixed64": | ||
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")); | ||
33889 | break; | ||
33890 | case "bool": gen | ||
33891 | ("if(!util.key2Re.test(%s))", ref) | ||
33892 | ("return%j", invalid(field, "boolean key")); | ||
33893 | break; | ||
33894 | } | ||
33895 | return gen; | ||
33896 | /* eslint-enable no-unexpected-multiline */ | ||
33897 | } | ||
33898 | |||
33899 | /** | ||
33900 | * Generates a verifier specific to the specified message type. | ||
33901 | * @param {Type} mtype Message type | ||
33902 | * @returns {Codegen} Codegen instance | ||
33903 | */ | ||
33904 | function verifier(mtype) { | ||
33905 | /* eslint-disable no-unexpected-multiline */ | ||
33906 | |||
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 | ||
33913 | ("var p={}"); | ||
33914 | |||
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); | ||
33918 | |||
33919 | if (field.optional) gen | ||
33920 | ("if(%s!=null&&m.hasOwnProperty(%j)){", ref, field.name); // !== undefined && !== null | ||
33921 | |||
33922 | // map fields | ||
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]]") | ||
33930 | ("}"); | ||
33931 | |||
33932 | // repeated fields | ||
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]") | ||
33938 | ("}"); | ||
33939 | |||
33940 | // required or present fields | ||
33941 | } else { | ||
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; | ||
33948 | gen | ||
33949 | ("p%s=1", oneofProp); | ||
33950 | } | ||
33951 | genVerifyValue(gen, field, i, ref); | ||
33952 | } | ||
33953 | if (field.optional) gen | ||
33954 | ("}"); | ||
33955 | } | ||
33956 | return gen | ||
33957 | ("return null"); | ||
33958 | /* eslint-enable no-unexpected-multiline */ | ||
33959 | } | ||
33960 | },{"./enum":196,"./util":218}],222:[function(require,module,exports){ | ||
33961 | "use strict"; | ||
33962 | |||
33963 | /** | ||
33964 | * Wrappers for common types. | ||
33965 | * @type {Object.<string,IWrapper>} | ||
33966 | * @const | ||
33967 | */ | ||
33968 | var wrappers = exports; | ||
33969 | |||
33970 | var Message = require("./message"); | ||
33971 | |||
33972 | /** | ||
33973 | * From object converter part of an {@link IWrapper}. | ||
33974 | * @typedef WrapperFromObjectConverter | ||
33975 | * @type {function} | ||
33976 | * @param {Object.<string,*>} object Plain object | ||
33977 | * @returns {Message<{}>} Message instance | ||
33978 | * @this Type | ||
33979 | */ | ||
33980 | |||
33981 | /** | ||
33982 | * To object converter part of an {@link IWrapper}. | ||
33983 | * @typedef WrapperToObjectConverter | ||
33984 | * @type {function} | ||
33985 | * @param {Message<{}>} message Message instance | ||
33986 | * @param {IConversionOptions} [options] Conversion options | ||
33987 | * @returns {Object.<string,*>} Plain object | ||
33988 | * @this Type | ||
33989 | */ | ||
33990 | |||
33991 | /** | ||
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 | ||
33996 | */ | ||
33997 | |||
33998 | // Custom wrapper for Any | ||
33999 | wrappers[".google.protobuf.Any"] = { | ||
34000 | |||
34001 | fromObject: function(object) { | ||
34002 | |||
34003 | // unwrap value type if mapped | ||
34004 | if (object && object["@type"]) { | ||
34005 | var type = this.lookup(object["@type"]); | ||
34006 | /* istanbul ignore else */ | ||
34007 | if (type) { | ||
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() | ||
34015 | }); | ||
34016 | } | ||
34017 | } | ||
34018 | |||
34019 | return this.fromObject(object); | ||
34020 | }, | ||
34021 | |||
34022 | toObject: function(message, options) { | ||
34023 | |||
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 */ | ||
34030 | if (type) | ||
34031 | message = type.decode(message.value); | ||
34032 | } | ||
34033 | |||
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; | ||
34038 | return object; | ||
34039 | } | ||
34040 | |||
34041 | return this.toObject(message, options); | ||
34042 | } | ||
34043 | }; | ||
34044 | |||
34045 | },{"./message":202}],223:[function(require,module,exports){ | ||
34046 | "use strict"; | ||
34047 | module.exports = Writer; | ||
34048 | |||
34049 | var util = require("./util/minimal"); | ||
34050 | |||
34051 | var BufferWriter; // cyclic | ||
34052 | |||
34053 | var LongBits = util.LongBits, | ||
34054 | base64 = util.base64, | ||
34055 | utf8 = util.utf8; | ||
34056 | |||
34057 | /** | ||
34058 | * Constructs a new writer operation instance. | ||
34059 | * @classdesc Scheduled writer operation. | ||
34060 | * @constructor | ||
34061 | * @param {function(*, Uint8Array, number)} fn Function to call | ||
34062 | * @param {number} len Value byte length | ||
34063 | * @param {*} val Value to write | ||
34064 | * @ignore | ||
34065 | */ | ||
34066 | function Op(fn, len, val) { | ||
34067 | |||
34068 | /** | ||
34069 | * Function to call. | ||
34070 | * @type {function(Uint8Array, number, *)} | ||
34071 | */ | ||
34072 | this.fn = fn; | ||
34073 | |||
34074 | /** | ||
34075 | * Value byte length. | ||
34076 | * @type {number} | ||
34077 | */ | ||
34078 | this.len = len; | ||
34079 | |||
34080 | /** | ||
34081 | * Next operation. | ||
34082 | * @type {Writer.Op|undefined} | ||
34083 | */ | ||
34084 | this.next = undefined; | ||
34085 | |||
34086 | /** | ||
34087 | * Value to write. | ||
34088 | * @type {*} | ||
34089 | */ | ||
34090 | this.val = val; // type varies | ||
34091 | } | ||
34092 | |||
34093 | /* istanbul ignore next */ | ||
34094 | function noop() {} // eslint-disable-line no-empty-function | ||
34095 | |||
34096 | /** | ||
34097 | * Constructs a new writer state instance. | ||
34098 | * @classdesc Copied writer state. | ||
34099 | * @memberof Writer | ||
34100 | * @constructor | ||
34101 | * @param {Writer} writer Writer to copy state from | ||
34102 | * @ignore | ||
34103 | */ | ||
34104 | function State(writer) { | ||
34105 | |||
34106 | /** | ||
34107 | * Current head. | ||
34108 | * @type {Writer.Op} | ||
34109 | */ | ||
34110 | this.head = writer.head; | ||
34111 | |||
34112 | /** | ||
34113 | * Current tail. | ||
34114 | * @type {Writer.Op} | ||
34115 | */ | ||
34116 | this.tail = writer.tail; | ||
34117 | |||
34118 | /** | ||
34119 | * Current buffer length. | ||
34120 | * @type {number} | ||
34121 | */ | ||
34122 | this.len = writer.len; | ||
34123 | |||
34124 | /** | ||
34125 | * Next state. | ||
34126 | * @type {State|null} | ||
34127 | */ | ||
34128 | this.next = writer.states; | ||
34129 | } | ||
34130 | |||
34131 | /** | ||
34132 | * Constructs a new writer instance. | ||
34133 | * @classdesc Wire format writer using `Uint8Array` if available, otherwise `Array`. | ||
34134 | * @constructor | ||
34135 | */ | ||
34136 | function Writer() { | ||
34137 | |||
34138 | /** | ||
34139 | * Current length. | ||
34140 | * @type {number} | ||
34141 | */ | ||
34142 | this.len = 0; | ||
34143 | |||
34144 | /** | ||
34145 | * Operations head. | ||
34146 | * @type {Object} | ||
34147 | */ | ||
34148 | this.head = new Op(noop, 0, 0); | ||
34149 | |||
34150 | /** | ||
34151 | * Operations tail | ||
34152 | * @type {Object} | ||
34153 | */ | ||
34154 | this.tail = this.head; | ||
34155 | |||
34156 | /** | ||
34157 | * Linked forked states. | ||
34158 | * @type {Object|null} | ||
34159 | */ | ||
34160 | this.states = null; | ||
34161 | |||
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. | ||
34167 | } | ||
34168 | |||
34169 | /** | ||
34170 | * Creates a new writer. | ||
34171 | * @function | ||
34172 | * @returns {BufferWriter|Writer} A {@link BufferWriter} when Buffers are supported, otherwise a {@link Writer} | ||
34173 | */ | ||
34174 | Writer.create = util.Buffer | ||
34175 | ? function create_buffer_setup() { | ||
34176 | return (Writer.create = function create_buffer() { | ||
34177 | return new BufferWriter(); | ||
34178 | })(); | ||
34179 | } | ||
34180 | /* istanbul ignore next */ | ||
34181 | : function create_array() { | ||
34182 | return new Writer(); | ||
34183 | }; | ||
34184 | |||
34185 | /** | ||
34186 | * Allocates a buffer of the specified size. | ||
34187 | * @param {number} size Buffer size | ||
34188 | * @returns {Uint8Array} Buffer | ||
34189 | */ | ||
34190 | Writer.alloc = function alloc(size) { | ||
34191 | return new util.Array(size); | ||
34192 | }; | ||
34193 | |||
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); | ||
34198 | |||
34199 | /** | ||
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` | ||
34205 | * @private | ||
34206 | */ | ||
34207 | Writer.prototype._push = function push(fn, len, val) { | ||
34208 | this.tail = this.tail.next = new Op(fn, len, val); | ||
34209 | this.len += len; | ||
34210 | return this; | ||
34211 | }; | ||
34212 | |||
34213 | function writeByte(val, buf, pos) { | ||
34214 | buf[pos] = val & 255; | ||
34215 | } | ||
34216 | |||
34217 | function writeVarint32(val, buf, pos) { | ||
34218 | while (val > 127) { | ||
34219 | buf[pos++] = val & 127 | 128; | ||
34220 | val >>>= 7; | ||
34221 | } | ||
34222 | buf[pos] = val; | ||
34223 | } | ||
34224 | |||
34225 | /** | ||
34226 | * Constructs a new varint writer operation instance. | ||
34227 | * @classdesc Scheduled varint writer operation. | ||
34228 | * @extends Op | ||
34229 | * @constructor | ||
34230 | * @param {number} len Value byte length | ||
34231 | * @param {number} val Value to write | ||
34232 | * @ignore | ||
34233 | */ | ||
34234 | function VarintOp(len, val) { | ||
34235 | this.len = len; | ||
34236 | this.next = undefined; | ||
34237 | this.val = val; | ||
34238 | } | ||
34239 | |||
34240 | VarintOp.prototype = Object.create(Op.prototype); | ||
34241 | VarintOp.prototype.fn = writeVarint32; | ||
34242 | |||
34243 | /** | ||
34244 | * Writes an unsigned 32 bit value as a varint. | ||
34245 | * @param {number} value Value to write | ||
34246 | * @returns {Writer} `this` | ||
34247 | */ | ||
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) | ||
34253 | < 128 ? 1 | ||
34254 | : value < 16384 ? 2 | ||
34255 | : value < 2097152 ? 3 | ||
34256 | : value < 268435456 ? 4 | ||
34257 | : 5, | ||
34258 | value)).len; | ||
34259 | return this; | ||
34260 | }; | ||
34261 | |||
34262 | /** | ||
34263 | * Writes a signed 32 bit value as a varint. | ||
34264 | * @function | ||
34265 | * @param {number} value Value to write | ||
34266 | * @returns {Writer} `this` | ||
34267 | */ | ||
34268 | Writer.prototype.int32 = function write_int32(value) { | ||
34269 | return value < 0 | ||
34270 | ? this._push(writeVarint64, 10, LongBits.fromNumber(value)) // 10 bytes per spec | ||
34271 | : this.uint32(value); | ||
34272 | }; | ||
34273 | |||
34274 | /** | ||
34275 | * Writes a 32 bit value as a varint, zig-zag encoded. | ||
34276 | * @param {number} value Value to write | ||
34277 | * @returns {Writer} `this` | ||
34278 | */ | ||
34279 | Writer.prototype.sint32 = function write_sint32(value) { | ||
34280 | return this.uint32((value << 1 ^ value >> 31) >>> 0); | ||
34281 | }; | ||
34282 | |||
34283 | function writeVarint64(val, buf, pos) { | ||
34284 | while (val.hi) { | ||
34285 | buf[pos++] = val.lo & 127 | 128; | ||
34286 | val.lo = (val.lo >>> 7 | val.hi << 25) >>> 0; | ||
34287 | val.hi >>>= 7; | ||
34288 | } | ||
34289 | while (val.lo > 127) { | ||
34290 | buf[pos++] = val.lo & 127 | 128; | ||
34291 | val.lo = val.lo >>> 7; | ||
34292 | } | ||
34293 | buf[pos++] = val.lo; | ||
34294 | } | ||
34295 | |||
34296 | /** | ||
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. | ||
34301 | */ | ||
34302 | Writer.prototype.uint64 = function write_uint64(value) { | ||
34303 | var bits = LongBits.from(value); | ||
34304 | return this._push(writeVarint64, bits.length(), bits); | ||
34305 | }; | ||
34306 | |||
34307 | /** | ||
34308 | * Writes a signed 64 bit value as a varint. | ||
34309 | * @function | ||
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. | ||
34313 | */ | ||
34314 | Writer.prototype.int64 = Writer.prototype.uint64; | ||
34315 | |||
34316 | /** | ||
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. | ||
34321 | */ | ||
34322 | Writer.prototype.sint64 = function write_sint64(value) { | ||
34323 | var bits = LongBits.from(value).zzEncode(); | ||
34324 | return this._push(writeVarint64, bits.length(), bits); | ||
34325 | }; | ||
34326 | |||
34327 | /** | ||
34328 | * Writes a boolish value as a varint. | ||
34329 | * @param {boolean} value Value to write | ||
34330 | * @returns {Writer} `this` | ||
34331 | */ | ||
34332 | Writer.prototype.bool = function write_bool(value) { | ||
34333 | return this._push(writeByte, 1, value ? 1 : 0); | ||
34334 | }; | ||
34335 | |||
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; | ||
34341 | } | ||
34342 | |||
34343 | /** | ||
34344 | * Writes an unsigned 32 bit value as fixed 32 bits. | ||
34345 | * @param {number} value Value to write | ||
34346 | * @returns {Writer} `this` | ||
34347 | */ | ||
34348 | Writer.prototype.fixed32 = function write_fixed32(value) { | ||
34349 | return this._push(writeFixed32, 4, value >>> 0); | ||
34350 | }; | ||
34351 | |||
34352 | /** | ||
34353 | * Writes a signed 32 bit value as fixed 32 bits. | ||
34354 | * @function | ||
34355 | * @param {number} value Value to write | ||
34356 | * @returns {Writer} `this` | ||
34357 | */ | ||
34358 | Writer.prototype.sfixed32 = Writer.prototype.fixed32; | ||
34359 | |||
34360 | /** | ||
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. | ||
34365 | */ | ||
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); | ||
34369 | }; | ||
34370 | |||
34371 | /** | ||
34372 | * Writes a signed 64 bit value as fixed 64 bits. | ||
34373 | * @function | ||
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. | ||
34377 | */ | ||
34378 | Writer.prototype.sfixed64 = Writer.prototype.fixed64; | ||
34379 | |||
34380 | /** | ||
34381 | * Writes a float (32 bit). | ||
34382 | * @function | ||
34383 | * @param {number} value Value to write | ||
34384 | * @returns {Writer} `this` | ||
34385 | */ | ||
34386 | Writer.prototype.float = function write_float(value) { | ||
34387 | return this._push(util.float.writeFloatLE, 4, value); | ||
34388 | }; | ||
34389 | |||
34390 | /** | ||
34391 | * Writes a double (64 bit float). | ||
34392 | * @function | ||
34393 | * @param {number} value Value to write | ||
34394 | * @returns {Writer} `this` | ||
34395 | */ | ||
34396 | Writer.prototype.double = function write_double(value) { | ||
34397 | return this._push(util.float.writeDoubleLE, 8, value); | ||
34398 | }; | ||
34399 | |||
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 | ||
34403 | } | ||
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]; | ||
34408 | }; | ||
34409 | |||
34410 | /** | ||
34411 | * Writes a sequence of bytes. | ||
34412 | * @param {Uint8Array|string} value Buffer or base64 encoded string to write | ||
34413 | * @returns {Writer} `this` | ||
34414 | */ | ||
34415 | Writer.prototype.bytes = function write_bytes(value) { | ||
34416 | var len = value.length >>> 0; | ||
34417 | if (!len) | ||
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); | ||
34422 | value = buf; | ||
34423 | } | ||
34424 | return this.uint32(len)._push(writeBytes, len, value); | ||
34425 | }; | ||
34426 | |||
34427 | /** | ||
34428 | * Writes a string. | ||
34429 | * @param {string} value Value to write | ||
34430 | * @returns {Writer} `this` | ||
34431 | */ | ||
34432 | Writer.prototype.string = function write_string(value) { | ||
34433 | var len = utf8.length(value); | ||
34434 | return len | ||
34435 | ? this.uint32(len)._push(utf8.write, len, value) | ||
34436 | : this._push(writeByte, 1, 0); | ||
34437 | }; | ||
34438 | |||
34439 | /** | ||
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` | ||
34443 | */ | ||
34444 | Writer.prototype.fork = function fork() { | ||
34445 | this.states = new State(this); | ||
34446 | this.head = this.tail = new Op(noop, 0, 0); | ||
34447 | this.len = 0; | ||
34448 | return this; | ||
34449 | }; | ||
34450 | |||
34451 | /** | ||
34452 | * Resets this instance to the last state. | ||
34453 | * @returns {Writer} `this` | ||
34454 | */ | ||
34455 | Writer.prototype.reset = function reset() { | ||
34456 | if (this.states) { | ||
34457 | this.head = this.states.head; | ||
34458 | this.tail = this.states.tail; | ||
34459 | this.len = this.states.len; | ||
34460 | this.states = this.states.next; | ||
34461 | } else { | ||
34462 | this.head = this.tail = new Op(noop, 0, 0); | ||
34463 | this.len = 0; | ||
34464 | } | ||
34465 | return this; | ||
34466 | }; | ||
34467 | |||
34468 | /** | ||
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` | ||
34471 | */ | ||
34472 | Writer.prototype.ldelim = function ldelim() { | ||
34473 | var head = this.head, | ||
34474 | tail = this.tail, | ||
34475 | len = this.len; | ||
34476 | this.reset().uint32(len); | ||
34477 | if (len) { | ||
34478 | this.tail.next = head.next; // skip noop | ||
34479 | this.tail = tail; | ||
34480 | this.len += len; | ||
34481 | } | ||
34482 | return this; | ||
34483 | }; | ||
34484 | |||
34485 | /** | ||
34486 | * Finishes the write operation. | ||
34487 | * @returns {Uint8Array} Finished buffer | ||
34488 | */ | ||
34489 | Writer.prototype.finish = function finish() { | ||
34490 | var head = this.head.next, // skip noop | ||
34491 | buf = this.constructor.alloc(this.len), | ||
34492 | pos = 0; | ||
34493 | while (head) { | ||
34494 | head.fn(head.val, buf, pos); | ||
34495 | pos += head.len; | ||
34496 | head = head.next; | ||
34497 | } | ||
34498 | // this.head = this.tail = null; | ||
34499 | return buf; | ||
34500 | }; | ||
34501 | |||
34502 | Writer._configure = function(BufferWriter_) { | ||
34503 | BufferWriter = BufferWriter_; | ||
34504 | }; | ||
34505 | |||
34506 | },{"./util/minimal":220}],224:[function(require,module,exports){ | ||
34507 | "use strict"; | ||
34508 | module.exports = BufferWriter; | ||
34509 | |||
34510 | // extends Writer | ||
34511 | var Writer = require("./writer"); | ||
34512 | (BufferWriter.prototype = Object.create(Writer.prototype)).constructor = BufferWriter; | ||
34513 | |||
34514 | var util = require("./util/minimal"); | ||
34515 | |||
34516 | var Buffer = util.Buffer; | ||
34517 | |||
34518 | /** | ||
34519 | * Constructs a new buffer writer instance. | ||
34520 | * @classdesc Wire format writer using node buffers. | ||
34521 | * @extends Writer | ||
34522 | * @constructor | ||
34523 | */ | ||
34524 | function BufferWriter() { | ||
34525 | Writer.call(this); | ||
34526 | } | ||
34527 | |||
34528 | /** | ||
34529 | * Allocates a buffer of the specified size. | ||
34530 | * @param {number} size Buffer size | ||
34531 | * @returns {Buffer} Buffer | ||
34532 | */ | ||
34533 | BufferWriter.alloc = function alloc_buffer(size) { | ||
34534 | return (BufferWriter.alloc = util._Buffer_allocUnsafe)(size); | ||
34535 | }; | ||
34536 | |||
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 | ||
34541 | } | ||
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++]; | ||
34548 | }; | ||
34549 | |||
34550 | /** | ||
34551 | * @override | ||
34552 | */ | ||
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; | ||
34557 | this.uint32(len); | ||
34558 | if (len) | ||
34559 | this._push(writeBytesBuffer, len, value); | ||
34560 | return this; | ||
34561 | }; | ||
34562 | |||
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); | ||
34566 | else | ||
34567 | buf.utf8Write(val, pos); | ||
34568 | } | ||
34569 | |||
34570 | /** | ||
34571 | * @override | ||
34572 | */ | ||
34573 | BufferWriter.prototype.string = function write_string_buffer(value) { | ||
34574 | var len = Buffer.byteLength(value); | ||
34575 | this.uint32(len); | ||
34576 | if (len) | ||
34577 | this._push(writeStringBuffer, len, value); | ||
34578 | return this; | ||
34579 | }; | ||
34580 | |||
34581 | |||
34582 | /** | ||
34583 | * Finishes the write operation. | ||
34584 | * @name BufferWriter#finish | ||
34585 | * @function | ||
34586 | * @returns {Buffer} Finished buffer | ||
34587 | */ | ||
34588 | |||
34589 | },{"./util/minimal":220,"./writer":223}],225:[function(require,module,exports){ | ||
34590 | exports.publicEncrypt = require('./publicEncrypt'); | ||
34591 | exports.privateDecrypt = require('./privateDecrypt'); | ||
34592 | |||
34593 | exports.privateEncrypt = function privateEncrypt(key, buf) { | ||
34594 | return exports.publicEncrypt(key, buf, true); | ||
34595 | }; | ||
34596 | |||
34597 | exports.publicDecrypt = function publicDecrypt(key, buf) { | ||
34598 | return exports.privateDecrypt(key, buf, true); | ||
34599 | }; | ||
34600 | },{"./privateDecrypt":227,"./publicEncrypt":228}],226:[function(require,module,exports){ | ||
34601 | (function (Buffer){ | ||
34602 | var createHash = require('create-hash'); | ||
34603 | module.exports = function (seed, len) { | ||
34604 | var t = new Buffer(''); | ||
34605 | var i = 0, c; | ||
34606 | while (t.length < len) { | ||
34607 | c = i2ops(i++); | ||
34608 | t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]); | ||
34609 | } | ||
34610 | return t.slice(0, len); | ||
34611 | }; | ||
34612 | |||
34613 | function i2ops(c) { | ||
34614 | var out = new Buffer(4); | ||
34615 | out.writeUInt32BE(c,0); | ||
34616 | return out; | ||
34617 | } | ||
34618 | }).call(this,require("buffer").Buffer) | ||
34619 | },{"buffer":107,"create-hash":111}],227:[function(require,module,exports){ | ||
34620 | (function (Buffer){ | ||
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) { | ||
34629 | var padding; | ||
34630 | if (private_key.padding) { | ||
34631 | padding = private_key.padding; | ||
34632 | } else if (reverse) { | ||
34633 | padding = 1; | ||
34634 | } else { | ||
34635 | padding = 4; | ||
34636 | } | ||
34637 | |||
34638 | var key = parseKeys(private_key); | ||
34639 | var k = key.modulus.byteLength(); | ||
34640 | if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) { | ||
34641 | throw new Error('decryption error'); | ||
34642 | } | ||
34643 | var msg; | ||
34644 | if (reverse) { | ||
34645 | msg = withPublic(new bn(enc), key); | ||
34646 | } else { | ||
34647 | msg = crt(enc, key); | ||
34648 | } | ||
34649 | var zBuffer = new Buffer(k - msg.length); | ||
34650 | zBuffer.fill(0); | ||
34651 | msg = Buffer.concat([zBuffer, msg], k); | ||
34652 | if (padding === 4) { | ||
34653 | return oaep(key, msg); | ||
34654 | } else if (padding === 1) { | ||
34655 | return pkcs1(key, msg, reverse); | ||
34656 | } else if (padding === 3) { | ||
34657 | return msg; | ||
34658 | } else { | ||
34659 | throw new Error('unknown padding'); | ||
34660 | } | ||
34661 | }; | ||
34662 | |||
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'); | ||
34672 | } | ||
34673 | var maskedSeed = msg.slice(1, hLen + 1); | ||
34674 | var maskedDb = msg.slice(hLen + 1); | ||
34675 | var seed = xor(maskedSeed, mgf(maskedDb, hLen)); | ||
34676 | var db = xor(maskedDb, mgf(seed, k - hLen - 1)); | ||
34677 | if (compare(iHash, db.slice(0, hLen))) { | ||
34678 | throw new Error('decryption error'); | ||
34679 | } | ||
34680 | var i = hLen; | ||
34681 | while (db[i] === 0) { | ||
34682 | i++; | ||
34683 | } | ||
34684 | if (db[i++] !== 1) { | ||
34685 | throw new Error('decryption error'); | ||
34686 | } | ||
34687 | return db.slice(i); | ||
34688 | } | ||
34689 | |||
34690 | function pkcs1(key, msg, reverse){ | ||
34691 | var p1 = msg.slice(0, 2); | ||
34692 | var i = 2; | ||
34693 | var status = 0; | ||
34694 | while (msg[i++] !== 0) { | ||
34695 | if (i >= msg.length) { | ||
34696 | status++; | ||
34697 | break; | ||
34698 | } | ||
34699 | } | ||
34700 | var ps = msg.slice(2, i - 1); | ||
34701 | var p2 = msg.slice(i - 1, i); | ||
34702 | |||
34703 | if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){ | ||
34704 | status++; | ||
34705 | } | ||
34706 | if (ps.length < 8) { | ||
34707 | status++; | ||
34708 | } | ||
34709 | if (status) { | ||
34710 | throw new Error('decryption error'); | ||
34711 | } | ||
34712 | return msg.slice(i); | ||
34713 | } | ||
34714 | function compare(a, b){ | ||
34715 | a = new Buffer(a); | ||
34716 | b = new Buffer(b); | ||
34717 | var dif = 0; | ||
34718 | var len = a.length; | ||
34719 | if (a.length !== b.length) { | ||
34720 | dif++; | ||
34721 | len = Math.min(a.length, b.length); | ||
34722 | } | ||
34723 | var i = -1; | ||
34724 | while (++i < len) { | ||
34725 | dif += (a[i] ^ b[i]); | ||
34726 | } | ||
34727 | return dif; | ||
34728 | } | ||
34729 | }).call(this,require("buffer").Buffer) | ||
34730 | },{"./mgf":226,"./withPublic":229,"./xor":230,"bn.js":75,"browserify-rsa":98,"buffer":107,"create-hash":111,"parse-asn1":182}],228:[function(require,module,exports){ | ||
34731 | (function (Buffer){ | ||
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'); | ||
34740 | |||
34741 | var constants = { | ||
34742 | RSA_PKCS1_OAEP_PADDING: 4, | ||
34743 | RSA_PKCS1_PADDIN: 1, | ||
34744 | RSA_NO_PADDING: 3 | ||
34745 | }; | ||
34746 | |||
34747 | module.exports = function publicEncrypt(public_key, msg, reverse) { | ||
34748 | var padding; | ||
34749 | if (public_key.padding) { | ||
34750 | padding = public_key.padding; | ||
34751 | } else if (reverse) { | ||
34752 | padding = 1; | ||
34753 | } else { | ||
34754 | padding = 4; | ||
34755 | } | ||
34756 | var key = parseKeys(public_key); | ||
34757 | var paddedMsg; | ||
34758 | if (padding === 4) { | ||
34759 | paddedMsg = oaep(key, msg); | ||
34760 | } else if (padding === 1) { | ||
34761 | paddedMsg = pkcs1(key, msg, reverse); | ||
34762 | } else if (padding === 3) { | ||
34763 | paddedMsg = new bn(msg); | ||
34764 | if (paddedMsg.cmp(key.modulus) >= 0) { | ||
34765 | throw new Error('data too long for modulus'); | ||
34766 | } | ||
34767 | } else { | ||
34768 | throw new Error('unknown padding'); | ||
34769 | } | ||
34770 | if (reverse) { | ||
34771 | return crt(paddedMsg, key); | ||
34772 | } else { | ||
34773 | return withPublic(paddedMsg, key); | ||
34774 | } | ||
34775 | }; | ||
34776 | |||
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'); | ||
34785 | } | ||
34786 | var ps = new Buffer(k - mLen - hLen2 - 2); | ||
34787 | ps.fill(0); | ||
34788 | var dblen = k - hLen - 1; | ||
34789 | var seed = randomBytes(hLen); | ||
34790 | var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen)); | ||
34791 | var maskedSeed = xor(seed, mgf(maskedDb, hLen)); | ||
34792 | return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k)); | ||
34793 | } | ||
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'); | ||
34799 | } | ||
34800 | var ps; | ||
34801 | if (reverse) { | ||
34802 | ps = new Buffer(k - mLen - 3); | ||
34803 | ps.fill(0xff); | ||
34804 | } else { | ||
34805 | ps = nonZero(k - mLen - 3); | ||
34806 | } | ||
34807 | return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k)); | ||
34808 | } | ||
34809 | function nonZero(len, crypto) { | ||
34810 | var out = new Buffer(len); | ||
34811 | var i = 0; | ||
34812 | var cache = randomBytes(len*2); | ||
34813 | var cur = 0; | ||
34814 | var num; | ||
34815 | while (i < len) { | ||
34816 | if (cur === cache.length) { | ||
34817 | cache = randomBytes(len*2); | ||
34818 | cur = 0; | ||
34819 | } | ||
34820 | num = cache[cur++]; | ||
34821 | if (num) { | ||
34822 | out[i++] = num; | ||
34823 | } | ||
34824 | } | ||
34825 | return out; | ||
34826 | } | ||
34827 | }).call(this,require("buffer").Buffer) | ||
34828 | },{"./mgf":226,"./withPublic":229,"./xor":230,"bn.js":75,"browserify-rsa":98,"buffer":107,"create-hash":111,"parse-asn1":182,"randombytes":231}],229:[function(require,module,exports){ | ||
34829 | (function (Buffer){ | ||
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)) | ||
34835 | .fromRed() | ||
34836 | .toArray()); | ||
34837 | } | ||
34838 | |||
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; | ||
34844 | var i = -1; | ||
34845 | while (++i < len) { | ||
34846 | a[i] ^= b[i]; | ||
34847 | } | ||
34848 | return a | ||
34849 | }; | ||
34850 | },{}],231:[function(require,module,exports){ | ||
34851 | (function (process,global){ | ||
34852 | 'use strict' | ||
34853 | |||
34854 | function oldBrowser () { | ||
34855 | throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') | ||
34856 | } | ||
34857 | |||
34858 | var Buffer = require('safe-buffer').Buffer | ||
34859 | var crypto = global.crypto || global.msCrypto | ||
34860 | |||
34861 | if (crypto && crypto.getRandomValues) { | ||
34862 | module.exports = randomBytes | ||
34863 | } else { | ||
34864 | module.exports = oldBrowser | ||
34865 | } | ||
34866 | |||
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) | ||
34872 | |||
34873 | // This will not work in older browsers. | ||
34874 | // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues | ||
34875 | if (size > 0) { // getRandomValues fails on IE if size == 0 | ||
34876 | crypto.getRandomValues(rawBytes) | ||
34877 | } | ||
34878 | |||
34879 | // XXX: phantomjs doesn't like a buffer being passed here | ||
34880 | var bytes = Buffer.from(rawBytes.buffer) | ||
34881 | |||
34882 | if (typeof cb === 'function') { | ||
34883 | return process.nextTick(function () { | ||
34884 | cb(null, bytes) | ||
34885 | }) | ||
34886 | } | ||
34887 | |||
34888 | return bytes | ||
34889 | } | ||
34890 | |||
34891 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | ||
34892 | },{"_process":190,"safe-buffer":247}],232:[function(require,module,exports){ | ||
34893 | (function (process,global){ | ||
34894 | 'use strict' | ||
34895 | |||
34896 | function oldBrowser () { | ||
34897 | throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') | ||
34898 | } | ||
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') | ||
34908 | } | ||
34909 | |||
34910 | if (offset > kMaxUint32 || offset < 0) { | ||
34911 | throw new TypeError('offset must be a uint32') | ||
34912 | } | ||
34913 | |||
34914 | if (offset > kBufferMaxLength || offset > length) { | ||
34915 | throw new RangeError('offset out of range') | ||
34916 | } | ||
34917 | } | ||
34918 | |||
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') | ||
34922 | } | ||
34923 | |||
34924 | if (size > kMaxUint32 || size < 0) { | ||
34925 | throw new TypeError('size must be a uint32') | ||
34926 | } | ||
34927 | |||
34928 | if (size + offset > length || size > kBufferMaxLength) { | ||
34929 | throw new RangeError('buffer too small') | ||
34930 | } | ||
34931 | } | ||
34932 | if ((crypto && crypto.getRandomValues) || !process.browser) { | ||
34933 | exports.randomFill = randomFill | ||
34934 | exports.randomFillSync = randomFillSync | ||
34935 | } else { | ||
34936 | exports.randomFill = oldBrowser | ||
34937 | exports.randomFillSync = oldBrowser | ||
34938 | } | ||
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') | ||
34942 | } | ||
34943 | |||
34944 | if (typeof offset === 'function') { | ||
34945 | cb = offset | ||
34946 | offset = 0 | ||
34947 | size = buf.length | ||
34948 | } else if (typeof size === 'function') { | ||
34949 | cb = size | ||
34950 | size = buf.length - offset | ||
34951 | } else if (typeof cb !== 'function') { | ||
34952 | throw new TypeError('"cb" argument must be a function') | ||
34953 | } | ||
34954 | assertOffset(offset, buf.length) | ||
34955 | assertSize(size, offset, buf.length) | ||
34956 | return actualFill(buf, offset, size, cb) | ||
34957 | } | ||
34958 | |||
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) | ||
34964 | if (cb) { | ||
34965 | process.nextTick(function () { | ||
34966 | cb(null, buf) | ||
34967 | }) | ||
34968 | return | ||
34969 | } | ||
34970 | return buf | ||
34971 | } | ||
34972 | if (cb) { | ||
34973 | randombytes(size, function (err, bytes) { | ||
34974 | if (err) { | ||
34975 | return cb(err) | ||
34976 | } | ||
34977 | bytes.copy(buf, offset) | ||
34978 | cb(null, buf) | ||
34979 | }) | ||
34980 | return | ||
34981 | } | ||
34982 | var bytes = randombytes(size) | ||
34983 | bytes.copy(buf, offset) | ||
34984 | return buf | ||
34985 | } | ||
34986 | function randomFillSync (buf, offset, size) { | ||
34987 | if (typeof offset === 'undefined') { | ||
34988 | offset = 0 | ||
34989 | } | ||
34990 | if (!Buffer.isBuffer(buf) && !(buf instanceof global.Uint8Array)) { | ||
34991 | throw new TypeError('"buf" argument must be a Buffer or Uint8Array') | ||
34992 | } | ||
34993 | |||
34994 | assertOffset(offset, buf.length) | ||
34995 | |||
34996 | if (size === undefined) size = buf.length - offset | ||
34997 | |||
34998 | assertSize(size, offset, buf.length) | ||
34999 | |||
35000 | return actualFill(buf, offset, size) | ||
35001 | } | ||
35002 | |||
35003 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | ||
35004 | },{"_process":190,"randombytes":231,"safe-buffer":247}],233:[function(require,module,exports){ | ||
35005 | module.exports = require('./lib/_stream_duplex.js'); | ||
35006 | |||
35007 | },{"./lib/_stream_duplex.js":234}],234:[function(require,module,exports){ | ||
35008 | // Copyright Joyent, Inc. and other Node contributors. | ||
35009 | // | ||
35010 | // Permission is hereby granted, free of charge, to any person obtaining a | ||
35011 | // copy of this software and associated documentation files (the | ||
35012 | // "Software"), to deal in the Software without restriction, including | ||
35013 | // without limitation the rights to use, copy, modify, merge, publish, | ||
35014 | // distribute, sublicense, and/or sell copies of the Software, and to permit | ||
35015 | // persons to whom the Software is furnished to do so, subject to the | ||
35016 | // following conditions: | ||
35017 | // | ||
35018 | // The above copyright notice and this permission notice shall be included | ||
35019 | // in all copies or substantial portions of the Software. | ||
35020 | // | ||
35021 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
35022 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
35023 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | ||
35024 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | ||
35025 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
35026 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
35027 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
35028 | |||
35029 | // a duplex stream is just a stream that is both readable and writable. | ||
35030 | // Since JS doesn't have multiple prototypal inheritance, this class | ||
35031 | // prototypally inherits from Readable, and then parasitically from | ||
35032 | // Writable. | ||
35033 | |||
35034 | 'use strict'; | ||
35035 | |||
35036 | /*<replacement>*/ | ||
35037 | |||
35038 | var processNextTick = require('process-nextick-args'); | ||
35039 | /*</replacement>*/ | ||
35040 | |||
35041 | /*<replacement>*/ | ||
35042 | var objectKeys = Object.keys || function (obj) { | ||
35043 | var keys = []; | ||
35044 | for (var key in obj) { | ||
35045 | keys.push(key); | ||
35046 | }return keys; | ||
35047 | }; | ||
35048 | /*</replacement>*/ | ||
35049 | |||
35050 | module.exports = Duplex; | ||
35051 | |||
35052 | /*<replacement>*/ | ||
35053 | var util = require('core-util-is'); | ||
35054 | util.inherits = require('inherits'); | ||
35055 | /*</replacement>*/ | ||
35056 | |||
35057 | var Readable = require('./_stream_readable'); | ||
35058 | var Writable = require('./_stream_writable'); | ||
35059 | |||
35060 | util.inherits(Duplex, Readable); | ||
35061 | |||
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]; | ||
35066 | } | ||
35067 | |||
35068 | function Duplex(options) { | ||
35069 | if (!(this instanceof Duplex)) return new Duplex(options); | ||
35070 | |||
35071 | Readable.call(this, options); | ||
35072 | Writable.call(this, options); | ||
35073 | |||
35074 | if (options && options.readable === false) this.readable = false; | ||
35075 | |||
35076 | if (options && options.writable === false) this.writable = false; | ||
35077 | |||
35078 | this.allowHalfOpen = true; | ||
35079 | if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; | ||
35080 | |||
35081 | this.once('end', onend); | ||
35082 | } | ||
35083 | |||
35084 | // the no-half-open enforcer | ||
35085 | function onend() { | ||
35086 | // if we allow half-open state, or if the writable side ended, | ||
35087 | // then we're ok. | ||
35088 | if (this.allowHalfOpen || this._writableState.ended) return; | ||
35089 | |||
35090 | // no more data can be written. | ||
35091 | // But allow more writes to happen in this tick. | ||
35092 | processNextTick(onEndNT, this); | ||
35093 | } | ||
35094 | |||
35095 | function onEndNT(self) { | ||
35096 | self.end(); | ||
35097 | } | ||
35098 | |||
35099 | Object.defineProperty(Duplex.prototype, 'destroyed', { | ||
35100 | get: function () { | ||
35101 | if (this._readableState === undefined || this._writableState === undefined) { | ||
35102 | return false; | ||
35103 | } | ||
35104 | return this._readableState.destroyed && this._writableState.destroyed; | ||
35105 | }, | ||
35106 | set: function (value) { | ||
35107 | // we ignore the value if the stream | ||
35108 | // has not been initialized yet | ||
35109 | if (this._readableState === undefined || this._writableState === undefined) { | ||
35110 | return; | ||
35111 | } | ||
35112 | |||
35113 | // backward compatibility, the user is explicitly | ||
35114 | // managing destroyed | ||
35115 | this._readableState.destroyed = value; | ||
35116 | this._writableState.destroyed = value; | ||
35117 | } | ||
35118 | }); | ||
35119 | |||
35120 | Duplex.prototype._destroy = function (err, cb) { | ||
35121 | this.push(null); | ||
35122 | this.end(); | ||
35123 | |||
35124 | processNextTick(cb, err); | ||
35125 | }; | ||
35126 | |||
35127 | function forEach(xs, f) { | ||
35128 | for (var i = 0, l = xs.length; i < l; i++) { | ||
35129 | f(xs[i], i); | ||
35130 | } | ||
35131 | } | ||
35132 | },{"./_stream_readable":236,"./_stream_writable":238,"core-util-is":109,"inherits":163,"process-nextick-args":189}],235:[function(require,module,exports){ | ||
35133 | // Copyright Joyent, Inc. and other Node contributors. | ||
35134 | // | ||
35135 | // Permission is hereby granted, free of charge, to any person obtaining a | ||
35136 | // copy of this software and associated documentation files (the | ||
35137 | // "Software"), to deal in the Software without restriction, including | ||
35138 | // without limitation the rights to use, copy, modify, merge, publish, | ||
35139 | // distribute, sublicense, and/or sell copies of the Software, and to permit | ||
35140 | // persons to whom the Software is furnished to do so, subject to the | ||
35141 | // following conditions: | ||
35142 | // | ||
35143 | // The above copyright notice and this permission notice shall be included | ||
35144 | // in all copies or substantial portions of the Software. | ||
35145 | // | ||
35146 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
35147 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
35148 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | ||
35149 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | ||
35150 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
35151 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
35152 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
35153 | |||
35154 | // a passthrough stream. | ||
35155 | // basically just the most minimal sort of Transform stream. | ||
35156 | // Every written chunk gets output as-is. | ||
35157 | |||
35158 | 'use strict'; | ||
35159 | |||
35160 | module.exports = PassThrough; | ||
35161 | |||
35162 | var Transform = require('./_stream_transform'); | ||
35163 | |||
35164 | /*<replacement>*/ | ||
35165 | var util = require('core-util-is'); | ||
35166 | util.inherits = require('inherits'); | ||
35167 | /*</replacement>*/ | ||
35168 | |||
35169 | util.inherits(PassThrough, Transform); | ||
35170 | |||
35171 | function PassThrough(options) { | ||
35172 | if (!(this instanceof PassThrough)) return new PassThrough(options); | ||
35173 | |||
35174 | Transform.call(this, options); | ||
35175 | } | ||
35176 | |||
35177 | PassThrough.prototype._transform = function (chunk, encoding, cb) { | ||
35178 | cb(null, chunk); | ||
35179 | }; | ||
35180 | },{"./_stream_transform":237,"core-util-is":109,"inherits":163}],236:[function(require,module,exports){ | ||
35181 | (function (process,global){ | ||
35182 | // Copyright Joyent, Inc. and other Node contributors. | ||
35183 | // | ||
35184 | // Permission is hereby granted, free of charge, to any person obtaining a | ||
35185 | // copy of this software and associated documentation files (the | ||
35186 | // "Software"), to deal in the Software without restriction, including | ||
35187 | // without limitation the rights to use, copy, modify, merge, publish, | ||
35188 | // distribute, sublicense, and/or sell copies of the Software, and to permit | ||
35189 | // persons to whom the Software is furnished to do so, subject to the | ||
35190 | // following conditions: | ||
35191 | // | ||
35192 | // The above copyright notice and this permission notice shall be included | ||
35193 | // in all copies or substantial portions of the Software. | ||
35194 | // | ||
35195 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
35196 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
35197 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | ||
35198 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | ||
35199 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
35200 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
35201 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
35202 | |||
35203 | 'use strict'; | ||
35204 | |||
35205 | /*<replacement>*/ | ||
35206 | |||
35207 | var processNextTick = require('process-nextick-args'); | ||
35208 | /*</replacement>*/ | ||
35209 | |||
35210 | module.exports = Readable; | ||
35211 | |||
35212 | /*<replacement>*/ | ||
35213 | var isArray = require('isarray'); | ||
35214 | /*</replacement>*/ | ||
35215 | |||
35216 | /*<replacement>*/ | ||
35217 | var Duplex; | ||
35218 | /*</replacement>*/ | ||
35219 | |||
35220 | Readable.ReadableState = ReadableState; | ||
35221 | |||
35222 | /*<replacement>*/ | ||
35223 | var EE = require('events').EventEmitter; | ||
35224 | |||
35225 | var EElistenerCount = function (emitter, type) { | ||
35226 | return emitter.listeners(type).length; | ||
35227 | }; | ||
35228 | /*</replacement>*/ | ||
35229 | |||
35230 | /*<replacement>*/ | ||
35231 | var Stream = require('./internal/streams/stream'); | ||
35232 | /*</replacement>*/ | ||
35233 | |||
35234 | // TODO(bmeurer): Change this back to const once hole checks are | ||
35235 | // properly optimized away early in Ignition+TurboFan. | ||
35236 | /*<replacement>*/ | ||
35237 | var Buffer = require('safe-buffer').Buffer; | ||
35238 | var OurUint8Array = global.Uint8Array || function () {}; | ||
35239 | function _uint8ArrayToBuffer(chunk) { | ||
35240 | return Buffer.from(chunk); | ||
35241 | } | ||
35242 | function _isUint8Array(obj) { | ||
35243 | return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; | ||
35244 | } | ||
35245 | /*</replacement>*/ | ||
35246 | |||
35247 | /*<replacement>*/ | ||
35248 | var util = require('core-util-is'); | ||
35249 | util.inherits = require('inherits'); | ||
35250 | /*</replacement>*/ | ||
35251 | |||
35252 | /*<replacement>*/ | ||
35253 | var debugUtil = require('util'); | ||
35254 | var debug = void 0; | ||
35255 | if (debugUtil && debugUtil.debuglog) { | ||
35256 | debug = debugUtil.debuglog('stream'); | ||
35257 | } else { | ||
35258 | debug = function () {}; | ||
35259 | } | ||
35260 | /*</replacement>*/ | ||
35261 | |||
35262 | var BufferList = require('./internal/streams/BufferList'); | ||
35263 | var destroyImpl = require('./internal/streams/destroy'); | ||
35264 | var StringDecoder; | ||
35265 | |||
35266 | util.inherits(Readable, Stream); | ||
35267 | |||
35268 | var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; | ||
35269 | |||
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); | ||
35275 | } else { | ||
35276 | // This is a hack to make sure that our error handler is attached before any | ||
35277 | // userland ones. NEVER DO THIS. This is here only because this code needs | ||
35278 | // to continue to work with older versions of Node.js that do not include | ||
35279 | // the prependListener() method. The goal is to eventually remove this hack. | ||
35280 | if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; | ||
35281 | } | ||
35282 | } | ||
35283 | |||
35284 | function ReadableState(options, stream) { | ||
35285 | Duplex = Duplex || require('./_stream_duplex'); | ||
35286 | |||
35287 | options = options || {}; | ||
35288 | |||
35289 | // object stream flag. Used to make read(n) ignore n and to | ||
35290 | // make all the buffer merging and length checks go away | ||
35291 | this.objectMode = !!options.objectMode; | ||
35292 | |||
35293 | if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; | ||
35294 | |||
35295 | // the point at which it stops calling _read() to fill the buffer | ||
35296 | // Note: 0 is a valid value, means "don't call _read preemptively ever" | ||
35297 | var hwm = options.highWaterMark; | ||
35298 | var defaultHwm = this.objectMode ? 16 : 16 * 1024; | ||
35299 | this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; | ||
35300 | |||
35301 | // cast to ints. | ||
35302 | this.highWaterMark = Math.floor(this.highWaterMark); | ||
35303 | |||
35304 | // A linked list is used to store data chunks instead of an array because the | ||
35305 | // linked list can remove elements from the beginning faster than | ||
35306 | // array.shift() | ||
35307 | this.buffer = new BufferList(); | ||
35308 | this.length = 0; | ||
35309 | this.pipes = null; | ||
35310 | this.pipesCount = 0; | ||
35311 | this.flowing = null; | ||
35312 | this.ended = false; | ||
35313 | this.endEmitted = false; | ||
35314 | this.reading = false; | ||
35315 | |||
35316 | // a flag to be able to tell if the event 'readable'/'data' is emitted | ||
35317 | // immediately, or on a later tick. We set this to true at first, because | ||
35318 | // any actions that shouldn't happen until "later" should generally also | ||
35319 | // not happen before the first read call. | ||
35320 | this.sync = true; | ||
35321 | |||
35322 | // whenever we return null, then we set a flag to say | ||
35323 | // that we're awaiting a 'readable' event emission. | ||
35324 | this.needReadable = false; | ||
35325 | this.emittedReadable = false; | ||
35326 | this.readableListening = false; | ||
35327 | this.resumeScheduled = false; | ||
35328 | |||
35329 | // has it been destroyed | ||
35330 | this.destroyed = false; | ||
35331 | |||
35332 | // Crypto is kind of old and crusty. Historically, its default string | ||
35333 | // encoding is 'binary' so we have to make this configurable. | ||
35334 | // Everything else in the universe uses 'utf8', though. | ||
35335 | this.defaultEncoding = options.defaultEncoding || 'utf8'; | ||
35336 | |||
35337 | // the number of writers that are awaiting a drain event in .pipe()s | ||
35338 | this.awaitDrain = 0; | ||
35339 | |||
35340 | // if true, a maybeReadMore has been scheduled | ||
35341 | this.readingMore = false; | ||
35342 | |||
35343 | this.decoder = null; | ||
35344 | this.encoding = null; | ||
35345 | if (options.encoding) { | ||
35346 | if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; | ||
35347 | this.decoder = new StringDecoder(options.encoding); | ||
35348 | this.encoding = options.encoding; | ||
35349 | } | ||
35350 | } | ||
35351 | |||
35352 | function Readable(options) { | ||
35353 | Duplex = Duplex || require('./_stream_duplex'); | ||
35354 | |||
35355 | if (!(this instanceof Readable)) return new Readable(options); | ||
35356 | |||
35357 | this._readableState = new ReadableState(options, this); | ||
35358 | |||
35359 | // legacy | ||
35360 | this.readable = true; | ||
35361 | |||
35362 | if (options) { | ||
35363 | if (typeof options.read === 'function') this._read = options.read; | ||
35364 | |||
35365 | if (typeof options.destroy === 'function') this._destroy = options.destroy; | ||
35366 | } | ||
35367 | |||
35368 | Stream.call(this); | ||
35369 | } | ||
35370 | |||
35371 | Object.defineProperty(Readable.prototype, 'destroyed', { | ||
35372 | get: function () { | ||
35373 | if (this._readableState === undefined) { | ||
35374 | return false; | ||
35375 | } | ||
35376 | return this._readableState.destroyed; | ||
35377 | }, | ||
35378 | set: function (value) { | ||
35379 | // we ignore the value if the stream | ||
35380 | // has not been initialized yet | ||
35381 | if (!this._readableState) { | ||
35382 | return; | ||
35383 | } | ||
35384 | |||
35385 | // backward compatibility, the user is explicitly | ||
35386 | // managing destroyed | ||
35387 | this._readableState.destroyed = value; | ||
35388 | } | ||
35389 | }); | ||
35390 | |||
35391 | Readable.prototype.destroy = destroyImpl.destroy; | ||
35392 | Readable.prototype._undestroy = destroyImpl.undestroy; | ||
35393 | Readable.prototype._destroy = function (err, cb) { | ||
35394 | this.push(null); | ||
35395 | cb(err); | ||
35396 | }; | ||
35397 | |||
35398 | // Manually shove something into the read() buffer. | ||
35399 | // This returns true if the highWaterMark has not been hit yet, | ||
35400 | // similar to how Writable.write() returns true if you should | ||
35401 | // write() some more. | ||
35402 | Readable.prototype.push = function (chunk, encoding) { | ||
35403 | var state = this._readableState; | ||
35404 | var skipChunkCheck; | ||
35405 | |||
35406 | if (!state.objectMode) { | ||
35407 | if (typeof chunk === 'string') { | ||
35408 | encoding = encoding || state.defaultEncoding; | ||
35409 | if (encoding !== state.encoding) { | ||
35410 | chunk = Buffer.from(chunk, encoding); | ||
35411 | encoding = ''; | ||
35412 | } | ||
35413 | skipChunkCheck = true; | ||
35414 | } | ||
35415 | } else { | ||
35416 | skipChunkCheck = true; | ||
35417 | } | ||
35418 | |||
35419 | return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); | ||
35420 | }; | ||
35421 | |||
35422 | // Unshift should *always* be something directly out of read() | ||
35423 | Readable.prototype.unshift = function (chunk) { | ||
35424 | return readableAddChunk(this, chunk, null, true, false); | ||
35425 | }; | ||
35426 | |||
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); | ||
35432 | } else { | ||
35433 | var er; | ||
35434 | if (!skipChunkCheck) er = chunkInvalid(state, chunk); | ||
35435 | if (er) { | ||
35436 | stream.emit('error', er); | ||
35437 | } else if (state.objectMode || chunk && chunk.length > 0) { | ||
35438 | if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { | ||
35439 | chunk = _uint8ArrayToBuffer(chunk); | ||
35440 | } | ||
35441 | |||
35442 | if (addToFront) { | ||
35443 | if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); | ||
35444 | } else if (state.ended) { | ||
35445 | stream.emit('error', new Error('stream.push() after EOF')); | ||
35446 | } else { | ||
35447 | state.reading = false; | ||
35448 | if (state.decoder && !encoding) { | ||
35449 | chunk = state.decoder.write(chunk); | ||
35450 | if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); | ||
35451 | } else { | ||
35452 | addChunk(stream, state, chunk, false); | ||
35453 | } | ||
35454 | } | ||
35455 | } else if (!addToFront) { | ||
35456 | state.reading = false; | ||
35457 | } | ||
35458 | } | ||
35459 | |||
35460 | return needMoreData(state); | ||
35461 | } | ||
35462 | |||
35463 | function addChunk(stream, state, chunk, addToFront) { | ||
35464 | if (state.flowing && state.length === 0 && !state.sync) { | ||
35465 | stream.emit('data', chunk); | ||
35466 | stream.read(0); | ||
35467 | } else { | ||
35468 | // update the buffer info. | ||
35469 | state.length += state.objectMode ? 1 : chunk.length; | ||
35470 | if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); | ||
35471 | |||
35472 | if (state.needReadable) emitReadable(stream); | ||
35473 | } | ||
35474 | maybeReadMore(stream, state); | ||
35475 | } | ||
35476 | |||
35477 | function chunkInvalid(state, chunk) { | ||
35478 | var er; | ||
35479 | if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { | ||
35480 | er = new TypeError('Invalid non-string/buffer chunk'); | ||
35481 | } | ||
35482 | return er; | ||
35483 | } | ||
35484 | |||
35485 | // if it's past the high water mark, we can push in some more. | ||
35486 | // Also, if we have no data yet, we can stand some | ||
35487 | // more bytes. This is to work around cases where hwm=0, | ||
35488 | // such as the repl. Also, if the push() triggered a | ||
35489 | // readable event, and the user called read(largeNumber) such that | ||
35490 | // needReadable was set, then we ought to push more, so that another | ||
35491 | // 'readable' event will be triggered. | ||
35492 | function needMoreData(state) { | ||
35493 | return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); | ||
35494 | } | ||
35495 | |||
35496 | Readable.prototype.isPaused = function () { | ||
35497 | return this._readableState.flowing === false; | ||
35498 | }; | ||
35499 | |||
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; | ||
35505 | return this; | ||
35506 | }; | ||
35507 | |||
35508 | // Don't raise the hwm > 8MB | ||
35509 | var MAX_HWM = 0x800000; | ||
35510 | function computeNewHighWaterMark(n) { | ||
35511 | if (n >= MAX_HWM) { | ||
35512 | n = MAX_HWM; | ||
35513 | } else { | ||
35514 | // Get the next highest power of 2 to prevent increasing hwm excessively in | ||
35515 | // tiny amounts | ||
35516 | n--; | ||
35517 | n |= n >>> 1; | ||
35518 | n |= n >>> 2; | ||
35519 | n |= n >>> 4; | ||
35520 | n |= n >>> 8; | ||
35521 | n |= n >>> 16; | ||
35522 | n++; | ||
35523 | } | ||
35524 | return n; | ||
35525 | } | ||
35526 | |||
35527 | // This function is designed to be inlinable, so please take care when making | ||
35528 | // changes to the function body. | ||
35529 | function howMuchToRead(n, state) { | ||
35530 | if (n <= 0 || state.length === 0 && state.ended) return 0; | ||
35531 | if (state.objectMode) return 1; | ||
35532 | if (n !== n) { | ||
35533 | // Only flow one buffer at a time | ||
35534 | if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; | ||
35535 | } | ||
35536 | // If we're asking for more than the current hwm, then raise the hwm. | ||
35537 | if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); | ||
35538 | if (n <= state.length) return n; | ||
35539 | // Don't have enough | ||
35540 | if (!state.ended) { | ||
35541 | state.needReadable = true; | ||
35542 | return 0; | ||
35543 | } | ||
35544 | return state.length; | ||
35545 | } | ||
35546 | |||
35547 | // you can override either this method, or the async _read(n) below. | ||
35548 | Readable.prototype.read = function (n) { | ||
35549 | debug('read', n); | ||
35550 | n = parseInt(n, 10); | ||
35551 | var state = this._readableState; | ||
35552 | var nOrig = n; | ||
35553 | |||
35554 | if (n !== 0) state.emittedReadable = false; | ||
35555 | |||
35556 | // if we're doing read(0) to trigger a readable event, but we | ||
35557 | // already have a bunch of data in the buffer, then just trigger | ||
35558 | // the 'readable' event and move on. | ||
35559 | if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { | ||
35560 | debug('read: emitReadable', state.length, state.ended); | ||
35561 | if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); | ||
35562 | return null; | ||
35563 | } | ||
35564 | |||
35565 | n = howMuchToRead(n, state); | ||
35566 | |||
35567 | // if we've ended, and we're now clear, then finish it up. | ||
35568 | if (n === 0 && state.ended) { | ||
35569 | if (state.length === 0) endReadable(this); | ||
35570 | return null; | ||
35571 | } | ||
35572 | |||
35573 | // All the actual chunk generation logic needs to be | ||
35574 | // *below* the call to _read. The reason is that in certain | ||
35575 | // synthetic stream cases, such as passthrough streams, _read | ||
35576 | // may be a completely synchronous operation which may change | ||
35577 | // the state of the read buffer, providing enough data when | ||
35578 | // before there was *not* enough. | ||
35579 | // | ||
35580 | // So, the steps are: | ||
35581 | // 1. Figure out what the state of things will be after we do | ||
35582 | // a read from the buffer. | ||
35583 | // | ||
35584 | // 2. If that resulting state will trigger a _read, then call _read. | ||
35585 | // Note that this may be asynchronous, or synchronous. Yes, it is | ||
35586 | // deeply ugly to write APIs this way, but that still doesn't mean | ||
35587 | // that the Readable class should behave improperly, as streams are | ||
35588 | // designed to be sync/async agnostic. | ||
35589 | // Take note if the _read call is sync or async (ie, if the read call | ||
35590 | // has returned yet), so that we know whether or not it's safe to emit | ||
35591 | // 'readable' etc. | ||
35592 | // | ||
35593 | // 3. Actually pull the requested chunks out of the buffer and return. | ||
35594 | |||
35595 | // if we need a readable event, then we need to do some reading. | ||
35596 | var doRead = state.needReadable; | ||
35597 | debug('need readable', doRead); | ||
35598 | |||
35599 | // if we currently have less than the highWaterMark, then also read some | ||
35600 | if (state.length === 0 || state.length - n < state.highWaterMark) { | ||
35601 | doRead = true; | ||
35602 | debug('length less than watermark', doRead); | ||
35603 | } | ||
35604 | |||
35605 | // however, if we've ended, then there's no point, and if we're already | ||
35606 | // reading, then it's unnecessary. | ||
35607 | if (state.ended || state.reading) { | ||
35608 | doRead = false; | ||
35609 | debug('reading or ended', doRead); | ||
35610 | } else if (doRead) { | ||
35611 | debug('do read'); | ||
35612 | state.reading = true; | ||
35613 | state.sync = true; | ||
35614 | // if the length is currently zero, then we *need* a readable event. | ||
35615 | if (state.length === 0) state.needReadable = true; | ||
35616 | // call internal read method | ||
35617 | this._read(state.highWaterMark); | ||
35618 | state.sync = false; | ||
35619 | // If _read pushed data synchronously, then `reading` will be false, | ||
35620 | // and we need to re-evaluate how much data we can return to the user. | ||
35621 | if (!state.reading) n = howMuchToRead(nOrig, state); | ||
35622 | } | ||
35623 | |||
35624 | var ret; | ||
35625 | if (n > 0) ret = fromList(n, state);else ret = null; | ||
35626 | |||
35627 | if (ret === null) { | ||
35628 | state.needReadable = true; | ||
35629 | n = 0; | ||
35630 | } else { | ||
35631 | state.length -= n; | ||
35632 | } | ||
35633 | |||
35634 | if (state.length === 0) { | ||
35635 | // If we have nothing in the buffer, then we want to know | ||
35636 | // as soon as we *do* get something into the buffer. | ||
35637 | if (!state.ended) state.needReadable = true; | ||
35638 | |||
35639 | // If we tried to read() past the EOF, then emit end on the next tick. | ||
35640 | if (nOrig !== n && state.ended) endReadable(this); | ||
35641 | } | ||
35642 | |||
35643 | if (ret !== null) this.emit('data', ret); | ||
35644 | |||
35645 | return ret; | ||
35646 | }; | ||
35647 | |||
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; | ||
35655 | } | ||
35656 | } | ||
35657 | state.ended = true; | ||
35658 | |||
35659 | // emit 'readable' now to make sure it gets picked up. | ||
35660 | emitReadable(stream); | ||
35661 | } | ||
35662 | |||
35663 | // Don't emit readable right away in sync mode, because this can trigger | ||
35664 | // another read() call => stack overflow. This way, it might trigger | ||
35665 | // a nextTick recursion warning, but that's not so bad. | ||
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); | ||
35673 | } | ||
35674 | } | ||
35675 | |||
35676 | function emitReadable_(stream) { | ||
35677 | debug('emit readable'); | ||
35678 | stream.emit('readable'); | ||
35679 | flow(stream); | ||
35680 | } | ||
35681 | |||
35682 | // at this point, the user has presumably seen the 'readable' event, | ||
35683 | // and called read() to consume some data. that may have triggered | ||
35684 | // in turn another _read(n) call, in which case reading = true if | ||
35685 | // it's in progress. | ||
35686 | // However, if we're not ended, or reading, and the length < hwm, | ||
35687 | // then go ahead and try to read some more preemptively. | ||
35688 | function maybeReadMore(stream, state) { | ||
35689 | if (!state.readingMore) { | ||
35690 | state.readingMore = true; | ||
35691 | processNextTick(maybeReadMore_, stream, state); | ||
35692 | } | ||
35693 | } | ||
35694 | |||
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'); | ||
35699 | stream.read(0); | ||
35700 | if (len === state.length) | ||
35701 | // didn't get any data, stop spinning. | ||
35702 | break;else len = state.length; | ||
35703 | } | ||
35704 | state.readingMore = false; | ||
35705 | } | ||
35706 | |||
35707 | // abstract method. to be overridden in specific implementation classes. | ||
35708 | // call cb(er, data) where data is <= n in length. | ||
35709 | // for virtual (non-string, non-buffer) streams, "length" is somewhat | ||
35710 | // arbitrary, and perhaps not very meaningful. | ||
35711 | Readable.prototype._read = function (n) { | ||
35712 | this.emit('error', new Error('_read() is not implemented')); | ||
35713 | }; | ||
35714 | |||
35715 | Readable.prototype.pipe = function (dest, pipeOpts) { | ||
35716 | var src = this; | ||
35717 | var state = this._readableState; | ||
35718 | |||
35719 | switch (state.pipesCount) { | ||
35720 | case 0: | ||
35721 | state.pipes = dest; | ||
35722 | break; | ||
35723 | case 1: | ||
35724 | state.pipes = [state.pipes, dest]; | ||
35725 | break; | ||
35726 | default: | ||
35727 | state.pipes.push(dest); | ||
35728 | break; | ||
35729 | } | ||
35730 | state.pipesCount += 1; | ||
35731 | debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); | ||
35732 | |||
35733 | var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; | ||
35734 | |||
35735 | var endFn = doEnd ? onend : unpipe; | ||
35736 | if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); | ||
35737 | |||
35738 | dest.on('unpipe', onunpipe); | ||
35739 | function onunpipe(readable, unpipeInfo) { | ||
35740 | debug('onunpipe'); | ||
35741 | if (readable === src) { | ||
35742 | if (unpipeInfo && unpipeInfo.hasUnpiped === false) { | ||
35743 | unpipeInfo.hasUnpiped = true; | ||
35744 | cleanup(); | ||
35745 | } | ||
35746 | } | ||
35747 | } | ||
35748 | |||
35749 | function onend() { | ||
35750 | debug('onend'); | ||
35751 | dest.end(); | ||
35752 | } | ||
35753 | |||
35754 | // when the dest drains, it reduces the awaitDrain counter | ||
35755 | // on the source. This would be more elegant with a .once() | ||
35756 | // handler in flow(), but adding and removing repeatedly is | ||
35757 | // too slow. | ||
35758 | var ondrain = pipeOnDrain(src); | ||
35759 | dest.on('drain', ondrain); | ||
35760 | |||
35761 | var cleanedUp = false; | ||
35762 | function cleanup() { | ||
35763 | debug('cleanup'); | ||
35764 | // cleanup event handlers once the pipe is broken | ||
35765 | dest.removeListener('close', onclose); | ||
35766 | dest.removeListener('finish', onfinish); | ||
35767 | dest.removeListener('drain', ondrain); | ||
35768 | dest.removeListener('error', onerror); | ||
35769 | dest.removeListener('unpipe', onunpipe); | ||
35770 | src.removeListener('end', onend); | ||
35771 | src.removeListener('end', unpipe); | ||
35772 | src.removeListener('data', ondata); | ||
35773 | |||
35774 | cleanedUp = true; | ||
35775 | |||
35776 | // if the reader is waiting for a drain event from this | ||
35777 | // specific writer, then it would cause it to never start | ||
35778 | // flowing again. | ||
35779 | // So, if this is awaiting a drain, then we just call it now. | ||
35780 | // If we don't know, then assume that we are waiting for one. | ||
35781 | if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); | ||
35782 | } | ||
35783 | |||
35784 | // If the user pushes more data while we're writing to dest then we'll end up | ||
35785 | // in ondata again. However, we only want to increase awaitDrain once because | ||
35786 | // dest will only emit one 'drain' event for the multiple writes. | ||
35787 | // => Introduce a guard on increasing awaitDrain. | ||
35788 | var increasedAwaitDrain = false; | ||
35789 | src.on('data', ondata); | ||
35790 | function ondata(chunk) { | ||
35791 | debug('ondata'); | ||
35792 | increasedAwaitDrain = false; | ||
35793 | var ret = dest.write(chunk); | ||
35794 | if (false === ret && !increasedAwaitDrain) { | ||
35795 | // If the user unpiped during `dest.write()`, it is possible | ||
35796 | // to get stuck in a permanently paused state if that write | ||
35797 | // also returned false. | ||
35798 | // => Check whether `dest` is still a piping destination. | ||
35799 | if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { | ||
35800 | debug('false write response, pause', src._readableState.awaitDrain); | ||
35801 | src._readableState.awaitDrain++; | ||
35802 | increasedAwaitDrain = true; | ||
35803 | } | ||
35804 | src.pause(); | ||
35805 | } | ||
35806 | } | ||
35807 | |||
35808 | // if the dest has an error, then stop piping into it. | ||
35809 | // however, don't suppress the throwing behavior for this. | ||
35810 | function onerror(er) { | ||
35811 | debug('onerror', er); | ||
35812 | unpipe(); | ||
35813 | dest.removeListener('error', onerror); | ||
35814 | if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); | ||
35815 | } | ||
35816 | |||
35817 | // Make sure our error handler is attached before userland ones. | ||
35818 | prependListener(dest, 'error', onerror); | ||
35819 | |||
35820 | // Both close and finish should trigger unpipe, but only once. | ||
35821 | function onclose() { | ||
35822 | dest.removeListener('finish', onfinish); | ||
35823 | unpipe(); | ||
35824 | } | ||
35825 | dest.once('close', onclose); | ||
35826 | function onfinish() { | ||
35827 | debug('onfinish'); | ||
35828 | dest.removeListener('close', onclose); | ||
35829 | unpipe(); | ||
35830 | } | ||
35831 | dest.once('finish', onfinish); | ||
35832 | |||
35833 | function unpipe() { | ||
35834 | debug('unpipe'); | ||
35835 | src.unpipe(dest); | ||
35836 | } | ||
35837 | |||
35838 | // tell the dest that it's being piped to | ||
35839 | dest.emit('pipe', src); | ||
35840 | |||
35841 | // start the flow if it hasn't been started already. | ||
35842 | if (!state.flowing) { | ||
35843 | debug('pipe resume'); | ||
35844 | src.resume(); | ||
35845 | } | ||
35846 | |||
35847 | return dest; | ||
35848 | }; | ||
35849 | |||
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; | ||
35857 | flow(src); | ||
35858 | } | ||
35859 | }; | ||
35860 | } | ||
35861 | |||
35862 | Readable.prototype.unpipe = function (dest) { | ||
35863 | var state = this._readableState; | ||
35864 | var unpipeInfo = { hasUnpiped: false }; | ||
35865 | |||
35866 | // if we're not piping anywhere, then do nothing. | ||
35867 | if (state.pipesCount === 0) return this; | ||
35868 | |||
35869 | // just one destination. most common case. | ||
35870 | if (state.pipesCount === 1) { | ||
35871 | // passed in one, but it's not the right one. | ||
35872 | if (dest && dest !== state.pipes) return this; | ||
35873 | |||
35874 | if (!dest) dest = state.pipes; | ||
35875 | |||
35876 | // got a match. | ||
35877 | state.pipes = null; | ||
35878 | state.pipesCount = 0; | ||
35879 | state.flowing = false; | ||
35880 | if (dest) dest.emit('unpipe', this, unpipeInfo); | ||
35881 | return this; | ||
35882 | } | ||
35883 | |||
35884 | // slow case. multiple pipe destinations. | ||
35885 | |||
35886 | if (!dest) { | ||
35887 | // remove all. | ||
35888 | var dests = state.pipes; | ||
35889 | var len = state.pipesCount; | ||
35890 | state.pipes = null; | ||
35891 | state.pipesCount = 0; | ||
35892 | state.flowing = false; | ||
35893 | |||
35894 | for (var i = 0; i < len; i++) { | ||
35895 | dests[i].emit('unpipe', this, unpipeInfo); | ||
35896 | }return this; | ||
35897 | } | ||
35898 | |||
35899 | // try to find the right one. | ||
35900 | var index = indexOf(state.pipes, dest); | ||
35901 | if (index === -1) return this; | ||
35902 | |||
35903 | state.pipes.splice(index, 1); | ||
35904 | state.pipesCount -= 1; | ||
35905 | if (state.pipesCount === 1) state.pipes = state.pipes[0]; | ||
35906 | |||
35907 | dest.emit('unpipe', this, unpipeInfo); | ||
35908 | |||
35909 | return this; | ||
35910 | }; | ||
35911 | |||
35912 | // set up data events if they are asked for | ||
35913 | // Ensure readable listeners eventually get something | ||
35914 | Readable.prototype.on = function (ev, fn) { | ||
35915 | var res = Stream.prototype.on.call(this, ev, fn); | ||
35916 | |||
35917 | if (ev === 'data') { | ||
35918 | // Start flowing on next tick if stream isn't explicitly paused | ||
35919 | if (this._readableState.flowing !== false) this.resume(); | ||
35920 | } else if (ev === 'readable') { | ||
35921 | var state = this._readableState; | ||
35922 | if (!state.endEmitted && !state.readableListening) { | ||
35923 | state.readableListening = state.needReadable = true; | ||
35924 | state.emittedReadable = false; | ||
35925 | if (!state.reading) { | ||
35926 | processNextTick(nReadingNextTick, this); | ||
35927 | } else if (state.length) { | ||
35928 | emitReadable(this); | ||
35929 | } | ||
35930 | } | ||
35931 | } | ||
35932 | |||
35933 | return res; | ||
35934 | }; | ||
35935 | Readable.prototype.addListener = Readable.prototype.on; | ||
35936 | |||
35937 | function nReadingNextTick(self) { | ||
35938 | debug('readable nexttick read 0'); | ||
35939 | self.read(0); | ||
35940 | } | ||
35941 | |||
35942 | // pause() and resume() are remnants of the legacy readable stream API | ||
35943 | // If the user uses them, then switch into old mode. | ||
35944 | Readable.prototype.resume = function () { | ||
35945 | var state = this._readableState; | ||
35946 | if (!state.flowing) { | ||
35947 | debug('resume'); | ||
35948 | state.flowing = true; | ||
35949 | resume(this, state); | ||
35950 | } | ||
35951 | return this; | ||
35952 | }; | ||
35953 | |||
35954 | function resume(stream, state) { | ||
35955 | if (!state.resumeScheduled) { | ||
35956 | state.resumeScheduled = true; | ||
35957 | processNextTick(resume_, stream, state); | ||
35958 | } | ||
35959 | } | ||
35960 | |||
35961 | function resume_(stream, state) { | ||
35962 | if (!state.reading) { | ||
35963 | debug('resume read 0'); | ||
35964 | stream.read(0); | ||
35965 | } | ||
35966 | |||
35967 | state.resumeScheduled = false; | ||
35968 | state.awaitDrain = 0; | ||
35969 | stream.emit('resume'); | ||
35970 | flow(stream); | ||
35971 | if (state.flowing && !state.reading) stream.read(0); | ||
35972 | } | ||
35973 | |||
35974 | Readable.prototype.pause = function () { | ||
35975 | debug('call pause flowing=%j', this._readableState.flowing); | ||
35976 | if (false !== this._readableState.flowing) { | ||
35977 | debug('pause'); | ||
35978 | this._readableState.flowing = false; | ||
35979 | this.emit('pause'); | ||
35980 | } | ||
35981 | return this; | ||
35982 | }; | ||
35983 | |||
35984 | function flow(stream) { | ||
35985 | var state = stream._readableState; | ||
35986 | debug('flow', state.flowing); | ||
35987 | while (state.flowing && stream.read() !== null) {} | ||
35988 | } | ||
35989 | |||
35990 | // wrap an old-style stream as the async data source. | ||
35991 | // This is *not* part of the readable stream interface. | ||
35992 | // It is an ugly unfortunate mess of history. | ||
35993 | Readable.prototype.wrap = function (stream) { | ||
35994 | var state = this._readableState; | ||
35995 | var paused = false; | ||
35996 | |||
35997 | var self = this; | ||
35998 | stream.on('end', function () { | ||
35999 | debug('wrapped end'); | ||
36000 | if (state.decoder && !state.ended) { | ||
36001 | var chunk = state.decoder.end(); | ||
36002 | if (chunk && chunk.length) self.push(chunk); | ||
36003 | } | ||
36004 | |||
36005 | self.push(null); | ||
36006 | }); | ||
36007 | |||
36008 | stream.on('data', function (chunk) { | ||
36009 | debug('wrapped data'); | ||
36010 | if (state.decoder) chunk = state.decoder.write(chunk); | ||
36011 | |||
36012 | // don't skip over falsy values in objectMode | ||
36013 | if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; | ||
36014 | |||
36015 | var ret = self.push(chunk); | ||
36016 | if (!ret) { | ||
36017 | paused = true; | ||
36018 | stream.pause(); | ||
36019 | } | ||
36020 | }); | ||
36021 | |||
36022 | // proxy all the other methods. | ||
36023 | // important when wrapping filters and duplexes. | ||
36024 | for (var i in stream) { | ||
36025 | if (this[i] === undefined && typeof stream[i] === 'function') { | ||
36026 | this[i] = function (method) { | ||
36027 | return function () { | ||
36028 | return stream[method].apply(stream, arguments); | ||
36029 | }; | ||
36030 | }(i); | ||
36031 | } | ||
36032 | } | ||
36033 | |||
36034 | // proxy certain important events. | ||
36035 | for (var n = 0; n < kProxyEvents.length; n++) { | ||
36036 | stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); | ||
36037 | } | ||
36038 | |||
36039 | // when we try to consume some more bytes, simply unpause the | ||
36040 | // underlying stream. | ||
36041 | self._read = function (n) { | ||
36042 | debug('wrapped _read', n); | ||
36043 | if (paused) { | ||
36044 | paused = false; | ||
36045 | stream.resume(); | ||
36046 | } | ||
36047 | }; | ||
36048 | |||
36049 | return self; | ||
36050 | }; | ||
36051 | |||
36052 | // exposed for testing purposes only. | ||
36053 | Readable._fromList = fromList; | ||
36054 | |||
36055 | // Pluck off n bytes from an array of buffers. | ||
36056 | // Length is the combined lengths of all the buffers in the list. | ||
36057 | // This function is designed to be inlinable, so please take care when making | ||
36058 | // changes to the function body. | ||
36059 | function fromList(n, state) { | ||
36060 | // nothing buffered | ||
36061 | if (state.length === 0) return null; | ||
36062 | |||
36063 | var ret; | ||
36064 | if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { | ||
36065 | // read it all, truncate the list | ||
36066 | if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); | ||
36067 | state.buffer.clear(); | ||
36068 | } else { | ||
36069 | // read part of list | ||
36070 | ret = fromListPartial(n, state.buffer, state.decoder); | ||
36071 | } | ||
36072 | |||
36073 | return ret; | ||
36074 | } | ||
36075 | |||
36076 | // Extracts only enough buffered data to satisfy the amount requested. | ||
36077 | // This function is designed to be inlinable, so please take care when making | ||
36078 | // changes to the function body. | ||
36079 | function fromListPartial(n, list, hasStrings) { | ||
36080 | var ret; | ||
36081 | if (n < list.head.data.length) { | ||
36082 | // slice is the same for buffers and strings | ||
36083 | ret = list.head.data.slice(0, n); | ||
36084 | list.head.data = list.head.data.slice(n); | ||
36085 | } else if (n === list.head.data.length) { | ||
36086 | // first chunk is a perfect match | ||
36087 | ret = list.shift(); | ||
36088 | } else { | ||
36089 | // result spans more than one buffer | ||
36090 | ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); | ||
36091 | } | ||
36092 | return ret; | ||
36093 | } | ||
36094 | |||
36095 | // Copies a specified amount of characters from the list of buffered data | ||
36096 | // chunks. | ||
36097 | // This function is designed to be inlinable, so please take care when making | ||
36098 | // changes to the function body. | ||
36099 | function copyFromBufferString(n, list) { | ||
36100 | var p = list.head; | ||
36101 | var c = 1; | ||
36102 | var ret = p.data; | ||
36103 | n -= ret.length; | ||
36104 | while (p = p.next) { | ||
36105 | var str = p.data; | ||
36106 | var nb = n > str.length ? str.length : n; | ||
36107 | if (nb === str.length) ret += str;else ret += str.slice(0, n); | ||
36108 | n -= nb; | ||
36109 | if (n === 0) { | ||
36110 | if (nb === str.length) { | ||
36111 | ++c; | ||
36112 | if (p.next) list.head = p.next;else list.head = list.tail = null; | ||
36113 | } else { | ||
36114 | list.head = p; | ||
36115 | p.data = str.slice(nb); | ||
36116 | } | ||
36117 | break; | ||
36118 | } | ||
36119 | ++c; | ||
36120 | } | ||
36121 | list.length -= c; | ||
36122 | return ret; | ||
36123 | } | ||
36124 | |||
36125 | // Copies a specified amount of bytes from the list of buffered data chunks. | ||
36126 | // This function is designed to be inlinable, so please take care when making | ||
36127 | // changes to the function body. | ||
36128 | function copyFromBuffer(n, list) { | ||
36129 | var ret = Buffer.allocUnsafe(n); | ||
36130 | var p = list.head; | ||
36131 | var c = 1; | ||
36132 | p.data.copy(ret); | ||
36133 | n -= p.data.length; | ||
36134 | while (p = p.next) { | ||
36135 | var buf = p.data; | ||
36136 | var nb = n > buf.length ? buf.length : n; | ||
36137 | buf.copy(ret, ret.length - n, 0, nb); | ||
36138 | n -= nb; | ||
36139 | if (n === 0) { | ||
36140 | if (nb === buf.length) { | ||
36141 | ++c; | ||
36142 | if (p.next) list.head = p.next;else list.head = list.tail = null; | ||
36143 | } else { | ||
36144 | list.head = p; | ||
36145 | p.data = buf.slice(nb); | ||
36146 | } | ||
36147 | break; | ||
36148 | } | ||
36149 | ++c; | ||
36150 | } | ||
36151 | list.length -= c; | ||
36152 | return ret; | ||
36153 | } | ||
36154 | |||
36155 | function endReadable(stream) { | ||
36156 | var state = stream._readableState; | ||
36157 | |||
36158 | // If we get here before consuming all the bytes, then that is a | ||
36159 | // bug in node. Should never happen. | ||
36160 | if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); | ||
36161 | |||
36162 | if (!state.endEmitted) { | ||
36163 | state.ended = true; | ||
36164 | processNextTick(endReadableNT, state, stream); | ||
36165 | } | ||
36166 | } | ||
36167 | |||
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'); | ||
36174 | } | ||
36175 | } | ||
36176 | |||
36177 | function forEach(xs, f) { | ||
36178 | for (var i = 0, l = xs.length; i < l; i++) { | ||
36179 | f(xs[i], i); | ||
36180 | } | ||
36181 | } | ||
36182 | |||
36183 | function indexOf(xs, x) { | ||
36184 | for (var i = 0, l = xs.length; i < l; i++) { | ||
36185 | if (xs[i] === x) return i; | ||
36186 | } | ||
36187 | return -1; | ||
36188 | } | ||
36189 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | ||
36190 | },{"./_stream_duplex":234,"./internal/streams/BufferList":239,"./internal/streams/destroy":240,"./internal/streams/stream":241,"_process":190,"core-util-is":109,"events":143,"inherits":163,"isarray":165,"process-nextick-args":189,"safe-buffer":247,"string_decoder/":264,"util":77}],237:[function(require,module,exports){ | ||
36191 | // Copyright Joyent, Inc. and other Node contributors. | ||
36192 | // | ||
36193 | // Permission is hereby granted, free of charge, to any person obtaining a | ||
36194 | // copy of this software and associated documentation files (the | ||
36195 | // "Software"), to deal in the Software without restriction, including | ||
36196 | // without limitation the rights to use, copy, modify, merge, publish, | ||
36197 | // distribute, sublicense, and/or sell copies of the Software, and to permit | ||
36198 | // persons to whom the Software is furnished to do so, subject to the | ||
36199 | // following conditions: | ||
36200 | // | ||
36201 | // The above copyright notice and this permission notice shall be included | ||
36202 | // in all copies or substantial portions of the Software. | ||
36203 | // | ||
36204 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
36205 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
36206 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | ||
36207 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | ||
36208 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
36209 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
36210 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
36211 | |||
36212 | // a transform stream is a readable/writable stream where you do | ||
36213 | // something with the data. Sometimes it's called a "filter", | ||
36214 | // but that's not a great name for it, since that implies a thing where | ||
36215 | // some bits pass through, and others are simply ignored. (That would | ||
36216 | // be a valid example of a transform, of course.) | ||
36217 | // | ||
36218 | // While the output is causally related to the input, it's not a | ||
36219 | // necessarily symmetric or synchronous transformation. For example, | ||
36220 | // a zlib stream might take multiple plain-text writes(), and then | ||
36221 | // emit a single compressed chunk some time in the future. | ||
36222 | // | ||
36223 | // Here's how this works: | ||
36224 | // | ||
36225 | // The Transform stream has all the aspects of the readable and writable | ||
36226 | // stream classes. When you write(chunk), that calls _write(chunk,cb) | ||
36227 | // internally, and returns false if there's a lot of pending writes | ||
36228 | // buffered up. When you call read(), that calls _read(n) until | ||
36229 | // there's enough pending readable data buffered up. | ||
36230 | // | ||
36231 | // In a transform stream, the written data is placed in a buffer. When | ||
36232 | // _read(n) is called, it transforms the queued up data, calling the | ||
36233 | // buffered _write cb's as it consumes chunks. If consuming a single | ||
36234 | // written chunk would result in multiple output chunks, then the first | ||
36235 | // outputted bit calls the readcb, and subsequent chunks just go into | ||
36236 | // the read buffer, and will cause it to emit 'readable' if necessary. | ||
36237 | // | ||
36238 | // This way, back-pressure is actually determined by the reading side, | ||
36239 | // since _read has to be called to start processing a new chunk. However, | ||
36240 | // a pathological inflate type of transform can cause excessive buffering | ||
36241 | // here. For example, imagine a stream where every byte of input is | ||
36242 | // interpreted as an integer from 0-255, and then results in that many | ||
36243 | // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in | ||
36244 | // 1kb of data being output. In this case, you could write a very small | ||
36245 | // amount of input, and end up with a very large amount of output. In | ||
36246 | // such a pathological inflating mechanism, there'd be no way to tell | ||
36247 | // the system to stop doing the transform. A single 4MB write could | ||
36248 | // cause the system to run out of memory. | ||
36249 | // | ||
36250 | // However, even in such a pathological case, only a single written chunk | ||
36251 | // would be consumed, and then the rest would wait (un-transformed) until | ||
36252 | // the results of the previous transformed chunk were consumed. | ||
36253 | |||
36254 | 'use strict'; | ||
36255 | |||
36256 | module.exports = Transform; | ||
36257 | |||
36258 | var Duplex = require('./_stream_duplex'); | ||
36259 | |||
36260 | /*<replacement>*/ | ||
36261 | var util = require('core-util-is'); | ||
36262 | util.inherits = require('inherits'); | ||
36263 | /*</replacement>*/ | ||
36264 | |||
36265 | util.inherits(Transform, Duplex); | ||
36266 | |||
36267 | function TransformState(stream) { | ||
36268 | this.afterTransform = function (er, data) { | ||
36269 | return afterTransform(stream, er, data); | ||
36270 | }; | ||
36271 | |||
36272 | this.needTransform = false; | ||
36273 | this.transforming = false; | ||
36274 | this.writecb = null; | ||
36275 | this.writechunk = null; | ||
36276 | this.writeencoding = null; | ||
36277 | } | ||
36278 | |||
36279 | function afterTransform(stream, er, data) { | ||
36280 | var ts = stream._transformState; | ||
36281 | ts.transforming = false; | ||
36282 | |||
36283 | var cb = ts.writecb; | ||
36284 | |||
36285 | if (!cb) { | ||
36286 | return stream.emit('error', new Error('write callback called multiple times')); | ||
36287 | } | ||
36288 | |||
36289 | ts.writechunk = null; | ||
36290 | ts.writecb = null; | ||
36291 | |||
36292 | if (data !== null && data !== undefined) stream.push(data); | ||
36293 | |||
36294 | cb(er); | ||
36295 | |||
36296 | var rs = stream._readableState; | ||
36297 | rs.reading = false; | ||
36298 | if (rs.needReadable || rs.length < rs.highWaterMark) { | ||
36299 | stream._read(rs.highWaterMark); | ||
36300 | } | ||
36301 | } | ||
36302 | |||
36303 | function Transform(options) { | ||
36304 | if (!(this instanceof Transform)) return new Transform(options); | ||
36305 | |||
36306 | Duplex.call(this, options); | ||
36307 | |||
36308 | this._transformState = new TransformState(this); | ||
36309 | |||
36310 | var stream = this; | ||
36311 | |||
36312 | // start out asking for a readable event once data is transformed. | ||
36313 | this._readableState.needReadable = true; | ||
36314 | |||
36315 | // we have implemented the _read method, and done the other things | ||
36316 | // that Readable wants before the first _read call, so unset the | ||
36317 | // sync guard flag. | ||
36318 | this._readableState.sync = false; | ||
36319 | |||
36320 | if (options) { | ||
36321 | if (typeof options.transform === 'function') this._transform = options.transform; | ||
36322 | |||
36323 | if (typeof options.flush === 'function') this._flush = options.flush; | ||
36324 | } | ||
36325 | |||
36326 | // When the writable side finishes, then flush out anything remaining. | ||
36327 | this.once('prefinish', function () { | ||
36328 | if (typeof this._flush === 'function') this._flush(function (er, data) { | ||
36329 | done(stream, er, data); | ||
36330 | });else done(stream); | ||
36331 | }); | ||
36332 | } | ||
36333 | |||
36334 | Transform.prototype.push = function (chunk, encoding) { | ||
36335 | this._transformState.needTransform = false; | ||
36336 | return Duplex.prototype.push.call(this, chunk, encoding); | ||
36337 | }; | ||
36338 | |||
36339 | // This is the part where you do stuff! | ||
36340 | // override this function in implementation classes. | ||
36341 | // 'chunk' is an input chunk. | ||
36342 | // | ||
36343 | // Call `push(newChunk)` to pass along transformed output | ||
36344 | // to the readable side. You may call 'push' zero or more times. | ||
36345 | // | ||
36346 | // Call `cb(err)` when you are done with this chunk. If you pass | ||
36347 | // an error, then that'll put the hurt on the whole operation. If you | ||
36348 | // never call cb(), then you'll never get another chunk. | ||
36349 | Transform.prototype._transform = function (chunk, encoding, cb) { | ||
36350 | throw new Error('_transform() is not implemented'); | ||
36351 | }; | ||
36352 | |||
36353 | Transform.prototype._write = function (chunk, encoding, cb) { | ||
36354 | var ts = this._transformState; | ||
36355 | ts.writecb = cb; | ||
36356 | ts.writechunk = chunk; | ||
36357 | ts.writeencoding = encoding; | ||
36358 | if (!ts.transforming) { | ||
36359 | var rs = this._readableState; | ||
36360 | if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); | ||
36361 | } | ||
36362 | }; | ||
36363 | |||
36364 | // Doesn't matter what the args are here. | ||
36365 | // _transform does all the work. | ||
36366 | // That we got here means that the readable side wants more data. | ||
36367 | Transform.prototype._read = function (n) { | ||
36368 | var ts = this._transformState; | ||
36369 | |||
36370 | if (ts.writechunk !== null && ts.writecb && !ts.transforming) { | ||
36371 | ts.transforming = true; | ||
36372 | this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); | ||
36373 | } else { | ||
36374 | // mark that we need a transform, so that any data that comes in | ||
36375 | // will get processed, now that we've asked for it. | ||
36376 | ts.needTransform = true; | ||
36377 | } | ||
36378 | }; | ||
36379 | |||
36380 | Transform.prototype._destroy = function (err, cb) { | ||
36381 | var _this = this; | ||
36382 | |||
36383 | Duplex.prototype._destroy.call(this, err, function (err2) { | ||
36384 | cb(err2); | ||
36385 | _this.emit('close'); | ||
36386 | }); | ||
36387 | }; | ||
36388 | |||
36389 | function done(stream, er, data) { | ||
36390 | if (er) return stream.emit('error', er); | ||
36391 | |||
36392 | if (data !== null && data !== undefined) stream.push(data); | ||
36393 | |||
36394 | // if there's nothing in the write buffer, then that means | ||
36395 | // that nothing more will ever be provided | ||
36396 | var ws = stream._writableState; | ||
36397 | var ts = stream._transformState; | ||
36398 | |||
36399 | if (ws.length) throw new Error('Calling transform done when ws.length != 0'); | ||
36400 | |||
36401 | if (ts.transforming) throw new Error('Calling transform done when still transforming'); | ||
36402 | |||
36403 | return stream.push(null); | ||
36404 | } | ||
36405 | },{"./_stream_duplex":234,"core-util-is":109,"inherits":163}],238:[function(require,module,exports){ | ||
36406 | (function (process,global){ | ||
36407 | // Copyright Joyent, Inc. and other Node contributors. | ||
36408 | // | ||
36409 | // Permission is hereby granted, free of charge, to any person obtaining a | ||
36410 | // copy of this software and associated documentation files (the | ||
36411 | // "Software"), to deal in the Software without restriction, including | ||
36412 | // without limitation the rights to use, copy, modify, merge, publish, | ||
36413 | // distribute, sublicense, and/or sell copies of the Software, and to permit | ||
36414 | // persons to whom the Software is furnished to do so, subject to the | ||
36415 | // following conditions: | ||
36416 | // | ||
36417 | // The above copyright notice and this permission notice shall be included | ||
36418 | // in all copies or substantial portions of the Software. | ||
36419 | // | ||
36420 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
36421 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
36422 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | ||
36423 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | ||
36424 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
36425 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
36426 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
36427 | |||
36428 | // A bit simpler than readable streams. | ||
36429 | // Implement an async ._write(chunk, encoding, cb), and it'll handle all | ||
36430 | // the drain event emission and buffering. | ||
36431 | |||
36432 | 'use strict'; | ||
36433 | |||
36434 | /*<replacement>*/ | ||
36435 | |||
36436 | var processNextTick = require('process-nextick-args'); | ||
36437 | /*</replacement>*/ | ||
36438 | |||
36439 | module.exports = Writable; | ||
36440 | |||
36441 | /* <replacement> */ | ||
36442 | function WriteReq(chunk, encoding, cb) { | ||
36443 | this.chunk = chunk; | ||
36444 | this.encoding = encoding; | ||
36445 | this.callback = cb; | ||
36446 | this.next = null; | ||
36447 | } | ||
36448 | |||
36449 | // It seems a linked list but it is not | ||
36450 | // there will be only 2 of these for each stream | ||
36451 | function CorkedRequest(state) { | ||
36452 | var _this = this; | ||
36453 | |||
36454 | this.next = null; | ||
36455 | this.entry = null; | ||
36456 | this.finish = function () { | ||
36457 | onCorkedFinish(_this, state); | ||
36458 | }; | ||
36459 | } | ||
36460 | /* </replacement> */ | ||
36461 | |||
36462 | /*<replacement>*/ | ||
36463 | var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; | ||
36464 | /*</replacement>*/ | ||
36465 | |||
36466 | /*<replacement>*/ | ||
36467 | var Duplex; | ||
36468 | /*</replacement>*/ | ||
36469 | |||
36470 | Writable.WritableState = WritableState; | ||
36471 | |||
36472 | /*<replacement>*/ | ||
36473 | var util = require('core-util-is'); | ||
36474 | util.inherits = require('inherits'); | ||
36475 | /*</replacement>*/ | ||
36476 | |||
36477 | /*<replacement>*/ | ||
36478 | var internalUtil = { | ||
36479 | deprecate: require('util-deprecate') | ||
36480 | }; | ||
36481 | /*</replacement>*/ | ||
36482 | |||
36483 | /*<replacement>*/ | ||
36484 | var Stream = require('./internal/streams/stream'); | ||
36485 | /*</replacement>*/ | ||
36486 | |||
36487 | /*<replacement>*/ | ||
36488 | var Buffer = require('safe-buffer').Buffer; | ||
36489 | var OurUint8Array = global.Uint8Array || function () {}; | ||
36490 | function _uint8ArrayToBuffer(chunk) { | ||
36491 | return Buffer.from(chunk); | ||
36492 | } | ||
36493 | function _isUint8Array(obj) { | ||
36494 | return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; | ||
36495 | } | ||
36496 | /*</replacement>*/ | ||
36497 | |||
36498 | var destroyImpl = require('./internal/streams/destroy'); | ||
36499 | |||
36500 | util.inherits(Writable, Stream); | ||
36501 | |||
36502 | function nop() {} | ||
36503 | |||
36504 | function WritableState(options, stream) { | ||
36505 | Duplex = Duplex || require('./_stream_duplex'); | ||
36506 | |||
36507 | options = options || {}; | ||
36508 | |||
36509 | // object stream flag to indicate whether or not this stream | ||
36510 | // contains buffers or objects. | ||
36511 | this.objectMode = !!options.objectMode; | ||
36512 | |||
36513 | if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; | ||
36514 | |||
36515 | // the point at which write() starts returning false | ||
36516 | // Note: 0 is a valid value, means that we always return false if | ||
36517 | // the entire buffer is not flushed immediately on write() | ||
36518 | var hwm = options.highWaterMark; | ||
36519 | var defaultHwm = this.objectMode ? 16 : 16 * 1024; | ||
36520 | this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; | ||
36521 | |||
36522 | // cast to ints. | ||
36523 | this.highWaterMark = Math.floor(this.highWaterMark); | ||
36524 | |||
36525 | // if _final has been called | ||
36526 | this.finalCalled = false; | ||
36527 | |||
36528 | // drain event flag. | ||
36529 | this.needDrain = false; | ||
36530 | // at the start of calling end() | ||
36531 | this.ending = false; | ||
36532 | // when end() has been called, and returned | ||
36533 | this.ended = false; | ||
36534 | // when 'finish' is emitted | ||
36535 | this.finished = false; | ||
36536 | |||
36537 | // has it been destroyed | ||
36538 | this.destroyed = false; | ||
36539 | |||
36540 | // should we decode strings into buffers before passing to _write? | ||
36541 | // this is here so that some node-core streams can optimize string | ||
36542 | // handling at a lower level. | ||
36543 | var noDecode = options.decodeStrings === false; | ||
36544 | this.decodeStrings = !noDecode; | ||
36545 | |||
36546 | // Crypto is kind of old and crusty. Historically, its default string | ||
36547 | // encoding is 'binary' so we have to make this configurable. | ||
36548 | // Everything else in the universe uses 'utf8', though. | ||
36549 | this.defaultEncoding = options.defaultEncoding || 'utf8'; | ||
36550 | |||
36551 | // not an actual buffer we keep track of, but a measurement | ||
36552 | // of how much we're waiting to get pushed to some underlying | ||
36553 | // socket or file. | ||
36554 | this.length = 0; | ||
36555 | |||
36556 | // a flag to see when we're in the middle of a write. | ||
36557 | this.writing = false; | ||
36558 | |||
36559 | // when true all writes will be buffered until .uncork() call | ||
36560 | this.corked = 0; | ||
36561 | |||
36562 | // a flag to be able to tell if the onwrite cb is called immediately, | ||
36563 | // or on a later tick. We set this to true at first, because any | ||
36564 | // actions that shouldn't happen until "later" should generally also | ||
36565 | // not happen before the first write call. | ||
36566 | this.sync = true; | ||
36567 | |||
36568 | // a flag to know if we're processing previously buffered items, which | ||
36569 | // may call the _write() callback in the same tick, so that we don't | ||
36570 | // end up in an overlapped onwrite situation. | ||
36571 | this.bufferProcessing = false; | ||
36572 | |||
36573 | // the callback that's passed to _write(chunk,cb) | ||
36574 | this.onwrite = function (er) { | ||
36575 | onwrite(stream, er); | ||
36576 | }; | ||
36577 | |||
36578 | // the callback that the user supplies to write(chunk,encoding,cb) | ||
36579 | this.writecb = null; | ||
36580 | |||
36581 | // the amount that is being written when _write is called. | ||
36582 | this.writelen = 0; | ||
36583 | |||
36584 | this.bufferedRequest = null; | ||
36585 | this.lastBufferedRequest = null; | ||
36586 | |||
36587 | // number of pending user-supplied write callbacks | ||
36588 | // this must be 0 before 'finish' can be emitted | ||
36589 | this.pendingcb = 0; | ||
36590 | |||
36591 | // emit prefinish if the only thing we're waiting for is _write cbs | ||
36592 | // This is relevant for synchronous Transform streams | ||
36593 | this.prefinished = false; | ||
36594 | |||
36595 | // True if the error was already emitted and should not be thrown again | ||
36596 | this.errorEmitted = false; | ||
36597 | |||
36598 | // count buffered requests | ||
36599 | this.bufferedRequestCount = 0; | ||
36600 | |||
36601 | // allocate the first CorkedRequest, there is always | ||
36602 | // one allocated and free to use, and we maintain at most two | ||
36603 | this.corkedRequestsFree = new CorkedRequest(this); | ||
36604 | } | ||
36605 | |||
36606 | WritableState.prototype.getBuffer = function getBuffer() { | ||
36607 | var current = this.bufferedRequest; | ||
36608 | var out = []; | ||
36609 | while (current) { | ||
36610 | out.push(current); | ||
36611 | current = current.next; | ||
36612 | } | ||
36613 | return out; | ||
36614 | }; | ||
36615 | |||
36616 | (function () { | ||
36617 | try { | ||
36618 | Object.defineProperty(WritableState.prototype, 'buffer', { | ||
36619 | get: internalUtil.deprecate(function () { | ||
36620 | return this.getBuffer(); | ||
36621 | }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') | ||
36622 | }); | ||
36623 | } catch (_) {} | ||
36624 | })(); | ||
36625 | |||
36626 | // Test _writableState for inheritance to account for Duplex streams, | ||
36627 | // whose prototype chain only points to Readable. | ||
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; | ||
36634 | |||
36635 | return object && object._writableState instanceof WritableState; | ||
36636 | } | ||
36637 | }); | ||
36638 | } else { | ||
36639 | realHasInstance = function (object) { | ||
36640 | return object instanceof this; | ||
36641 | }; | ||
36642 | } | ||
36643 | |||
36644 | function Writable(options) { | ||
36645 | Duplex = Duplex || require('./_stream_duplex'); | ||
36646 | |||
36647 | // Writable ctor is applied to Duplexes, too. | ||
36648 | // `realHasInstance` is necessary because using plain `instanceof` | ||
36649 | // would return false, as no `_writableState` property is attached. | ||
36650 | |||
36651 | // Trying to use the custom `instanceof` for Writable here will also break the | ||
36652 | // Node.js LazyTransform implementation, which has a non-trivial getter for | ||
36653 | // `_writableState` that would lead to infinite recursion. | ||
36654 | if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { | ||
36655 | return new Writable(options); | ||
36656 | } | ||
36657 | |||
36658 | this._writableState = new WritableState(options, this); | ||
36659 | |||
36660 | // legacy. | ||
36661 | this.writable = true; | ||
36662 | |||
36663 | if (options) { | ||
36664 | if (typeof options.write === 'function') this._write = options.write; | ||
36665 | |||
36666 | if (typeof options.writev === 'function') this._writev = options.writev; | ||
36667 | |||
36668 | if (typeof options.destroy === 'function') this._destroy = options.destroy; | ||
36669 | |||
36670 | if (typeof options.final === 'function') this._final = options.final; | ||
36671 | } | ||
36672 | |||
36673 | Stream.call(this); | ||
36674 | } | ||
36675 | |||
36676 | // Otherwise people can pipe Writable streams, which is just wrong. | ||
36677 | Writable.prototype.pipe = function () { | ||
36678 | this.emit('error', new Error('Cannot pipe, not readable')); | ||
36679 | }; | ||
36680 | |||
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); | ||
36686 | } | ||
36687 | |||
36688 | // Checks that a user-supplied chunk is valid, especially for the particular | ||
36689 | // mode the stream is in. Currently this means that `null` is never accepted | ||
36690 | // and undefined/non-string values are only allowed in object mode. | ||
36691 | function validChunk(stream, state, chunk, cb) { | ||
36692 | var valid = true; | ||
36693 | var er = false; | ||
36694 | |||
36695 | if (chunk === null) { | ||
36696 | er = new TypeError('May not write null values to stream'); | ||
36697 | } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { | ||
36698 | er = new TypeError('Invalid non-string/buffer chunk'); | ||
36699 | } | ||
36700 | if (er) { | ||
36701 | stream.emit('error', er); | ||
36702 | processNextTick(cb, er); | ||
36703 | valid = false; | ||
36704 | } | ||
36705 | return valid; | ||
36706 | } | ||
36707 | |||
36708 | Writable.prototype.write = function (chunk, encoding, cb) { | ||
36709 | var state = this._writableState; | ||
36710 | var ret = false; | ||
36711 | var isBuf = _isUint8Array(chunk) && !state.objectMode; | ||
36712 | |||
36713 | if (isBuf && !Buffer.isBuffer(chunk)) { | ||
36714 | chunk = _uint8ArrayToBuffer(chunk); | ||
36715 | } | ||
36716 | |||
36717 | if (typeof encoding === 'function') { | ||
36718 | cb = encoding; | ||
36719 | encoding = null; | ||
36720 | } | ||
36721 | |||
36722 | if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; | ||
36723 | |||
36724 | if (typeof cb !== 'function') cb = nop; | ||
36725 | |||
36726 | if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { | ||
36727 | state.pendingcb++; | ||
36728 | ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); | ||
36729 | } | ||
36730 | |||
36731 | return ret; | ||
36732 | }; | ||
36733 | |||
36734 | Writable.prototype.cork = function () { | ||
36735 | var state = this._writableState; | ||
36736 | |||
36737 | state.corked++; | ||
36738 | }; | ||
36739 | |||
36740 | Writable.prototype.uncork = function () { | ||
36741 | var state = this._writableState; | ||
36742 | |||
36743 | if (state.corked) { | ||
36744 | state.corked--; | ||
36745 | |||
36746 | if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); | ||
36747 | } | ||
36748 | }; | ||
36749 | |||
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; | ||
36755 | return this; | ||
36756 | }; | ||
36757 | |||
36758 | function decodeChunk(state, chunk, encoding) { | ||
36759 | if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { | ||
36760 | chunk = Buffer.from(chunk, encoding); | ||
36761 | } | ||
36762 | return chunk; | ||
36763 | } | ||
36764 | |||
36765 | // if we're already writing something, then just put this | ||
36766 | // in the queue, and wait our turn. Otherwise, call _write | ||
36767 | // If we return false, then we need a drain event, so set that flag. | ||
36768 | function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { | ||
36769 | if (!isBuf) { | ||
36770 | var newChunk = decodeChunk(state, chunk, encoding); | ||
36771 | if (chunk !== newChunk) { | ||
36772 | isBuf = true; | ||
36773 | encoding = 'buffer'; | ||
36774 | chunk = newChunk; | ||
36775 | } | ||
36776 | } | ||
36777 | var len = state.objectMode ? 1 : chunk.length; | ||
36778 | |||
36779 | state.length += len; | ||
36780 | |||
36781 | var ret = state.length < state.highWaterMark; | ||
36782 | // we must ensure that previous needDrain will not be reset to false. | ||
36783 | if (!ret) state.needDrain = true; | ||
36784 | |||
36785 | if (state.writing || state.corked) { | ||
36786 | var last = state.lastBufferedRequest; | ||
36787 | state.lastBufferedRequest = { | ||
36788 | chunk: chunk, | ||
36789 | encoding: encoding, | ||
36790 | isBuf: isBuf, | ||
36791 | callback: cb, | ||
36792 | next: null | ||
36793 | }; | ||
36794 | if (last) { | ||
36795 | last.next = state.lastBufferedRequest; | ||
36796 | } else { | ||
36797 | state.bufferedRequest = state.lastBufferedRequest; | ||
36798 | } | ||
36799 | state.bufferedRequestCount += 1; | ||
36800 | } else { | ||
36801 | doWrite(stream, state, false, len, chunk, encoding, cb); | ||
36802 | } | ||
36803 | |||
36804 | return ret; | ||
36805 | } | ||
36806 | |||
36807 | function doWrite(stream, state, writev, len, chunk, encoding, cb) { | ||
36808 | state.writelen = len; | ||
36809 | state.writecb = cb; | ||
36810 | state.writing = true; | ||
36811 | state.sync = true; | ||
36812 | if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); | ||
36813 | state.sync = false; | ||
36814 | } | ||
36815 | |||
36816 | function onwriteError(stream, state, sync, er, cb) { | ||
36817 | --state.pendingcb; | ||
36818 | |||
36819 | if (sync) { | ||
36820 | // defer the callback if we are being called synchronously | ||
36821 | // to avoid piling up things on the stack | ||
36822 | processNextTick(cb, er); | ||
36823 | // this can emit finish, and it will always happen | ||
36824 | // after error | ||
36825 | processNextTick(finishMaybe, stream, state); | ||
36826 | stream._writableState.errorEmitted = true; | ||
36827 | stream.emit('error', er); | ||
36828 | } else { | ||
36829 | // the caller expect this to happen before if | ||
36830 | // it is async | ||
36831 | cb(er); | ||
36832 | stream._writableState.errorEmitted = true; | ||
36833 | stream.emit('error', er); | ||
36834 | // this can emit finish, but finish must | ||
36835 | // always follow error | ||
36836 | finishMaybe(stream, state); | ||
36837 | } | ||
36838 | } | ||
36839 | |||
36840 | function onwriteStateUpdate(state) { | ||
36841 | state.writing = false; | ||
36842 | state.writecb = null; | ||
36843 | state.length -= state.writelen; | ||
36844 | state.writelen = 0; | ||
36845 | } | ||
36846 | |||
36847 | function onwrite(stream, er) { | ||
36848 | var state = stream._writableState; | ||
36849 | var sync = state.sync; | ||
36850 | var cb = state.writecb; | ||
36851 | |||
36852 | onwriteStateUpdate(state); | ||
36853 | |||
36854 | if (er) onwriteError(stream, state, sync, er, cb);else { | ||
36855 | // Check if we're actually ready to finish, but don't emit yet | ||
36856 | var finished = needFinish(state); | ||
36857 | |||
36858 | if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { | ||
36859 | clearBuffer(stream, state); | ||
36860 | } | ||
36861 | |||
36862 | if (sync) { | ||
36863 | /*<replacement>*/ | ||
36864 | asyncWrite(afterWrite, stream, state, finished, cb); | ||
36865 | /*</replacement>*/ | ||
36866 | } else { | ||
36867 | afterWrite(stream, state, finished, cb); | ||
36868 | } | ||
36869 | } | ||
36870 | } | ||
36871 | |||
36872 | function afterWrite(stream, state, finished, cb) { | ||
36873 | if (!finished) onwriteDrain(stream, state); | ||
36874 | state.pendingcb--; | ||
36875 | cb(); | ||
36876 | finishMaybe(stream, state); | ||
36877 | } | ||
36878 | |||
36879 | // Must force callback to be called on nextTick, so that we don't | ||
36880 | // emit 'drain' before the write() consumer gets the 'false' return | ||
36881 | // value, and has a chance to attach a 'drain' listener. | ||
36882 | function onwriteDrain(stream, state) { | ||
36883 | if (state.length === 0 && state.needDrain) { | ||
36884 | state.needDrain = false; | ||
36885 | stream.emit('drain'); | ||
36886 | } | ||
36887 | } | ||
36888 | |||
36889 | // if there's something in the buffer waiting, then process it | ||
36890 | function clearBuffer(stream, state) { | ||
36891 | state.bufferProcessing = true; | ||
36892 | var entry = state.bufferedRequest; | ||
36893 | |||
36894 | if (stream._writev && entry && entry.next) { | ||
36895 | // Fast case, write everything using _writev() | ||
36896 | var l = state.bufferedRequestCount; | ||
36897 | var buffer = new Array(l); | ||
36898 | var holder = state.corkedRequestsFree; | ||
36899 | holder.entry = entry; | ||
36900 | |||
36901 | var count = 0; | ||
36902 | var allBuffers = true; | ||
36903 | while (entry) { | ||
36904 | buffer[count] = entry; | ||
36905 | if (!entry.isBuf) allBuffers = false; | ||
36906 | entry = entry.next; | ||
36907 | count += 1; | ||
36908 | } | ||
36909 | buffer.allBuffers = allBuffers; | ||
36910 | |||
36911 | doWrite(stream, state, true, state.length, buffer, '', holder.finish); | ||
36912 | |||
36913 | // doWrite is almost always async, defer these to save a bit of time | ||
36914 | // as the hot path ends with doWrite | ||
36915 | state.pendingcb++; | ||
36916 | state.lastBufferedRequest = null; | ||
36917 | if (holder.next) { | ||
36918 | state.corkedRequestsFree = holder.next; | ||
36919 | holder.next = null; | ||
36920 | } else { | ||
36921 | state.corkedRequestsFree = new CorkedRequest(state); | ||
36922 | } | ||
36923 | } else { | ||
36924 | // Slow case, write chunks one-by-one | ||
36925 | while (entry) { | ||
36926 | var chunk = entry.chunk; | ||
36927 | var encoding = entry.encoding; | ||
36928 | var cb = entry.callback; | ||
36929 | var len = state.objectMode ? 1 : chunk.length; | ||
36930 | |||
36931 | doWrite(stream, state, false, len, chunk, encoding, cb); | ||
36932 | entry = entry.next; | ||
36933 | // if we didn't call the onwrite immediately, then | ||
36934 | // it means that we need to wait until it does. | ||
36935 | // also, that means that the chunk and cb are currently | ||
36936 | // being processed, so move the buffer counter past them. | ||
36937 | if (state.writing) { | ||
36938 | break; | ||
36939 | } | ||
36940 | } | ||
36941 | |||
36942 | if (entry === null) state.lastBufferedRequest = null; | ||
36943 | } | ||
36944 | |||
36945 | state.bufferedRequestCount = 0; | ||
36946 | state.bufferedRequest = entry; | ||
36947 | state.bufferProcessing = false; | ||
36948 | } | ||
36949 | |||
36950 | Writable.prototype._write = function (chunk, encoding, cb) { | ||
36951 | cb(new Error('_write() is not implemented')); | ||
36952 | }; | ||
36953 | |||
36954 | Writable.prototype._writev = null; | ||
36955 | |||
36956 | Writable.prototype.end = function (chunk, encoding, cb) { | ||
36957 | var state = this._writableState; | ||
36958 | |||
36959 | if (typeof chunk === 'function') { | ||
36960 | cb = chunk; | ||
36961 | chunk = null; | ||
36962 | encoding = null; | ||
36963 | } else if (typeof encoding === 'function') { | ||
36964 | cb = encoding; | ||
36965 | encoding = null; | ||
36966 | } | ||
36967 | |||
36968 | if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); | ||
36969 | |||
36970 | // .end() fully uncorks | ||
36971 | if (state.corked) { | ||
36972 | state.corked = 1; | ||
36973 | this.uncork(); | ||
36974 | } | ||
36975 | |||
36976 | // ignore unnecessary end() calls. | ||
36977 | if (!state.ending && !state.finished) endWritable(this, state, cb); | ||
36978 | }; | ||
36979 | |||
36980 | function needFinish(state) { | ||
36981 | return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; | ||
36982 | } | ||
36983 | function callFinal(stream, state) { | ||
36984 | stream._final(function (err) { | ||
36985 | state.pendingcb--; | ||
36986 | if (err) { | ||
36987 | stream.emit('error', err); | ||
36988 | } | ||
36989 | state.prefinished = true; | ||
36990 | stream.emit('prefinish'); | ||
36991 | finishMaybe(stream, state); | ||
36992 | }); | ||
36993 | } | ||
36994 | function prefinish(stream, state) { | ||
36995 | if (!state.prefinished && !state.finalCalled) { | ||
36996 | if (typeof stream._final === 'function') { | ||
36997 | state.pendingcb++; | ||
36998 | state.finalCalled = true; | ||
36999 | processNextTick(callFinal, stream, state); | ||
37000 | } else { | ||
37001 | state.prefinished = true; | ||
37002 | stream.emit('prefinish'); | ||
37003 | } | ||
37004 | } | ||
37005 | } | ||
37006 | |||
37007 | function finishMaybe(stream, state) { | ||
37008 | var need = needFinish(state); | ||
37009 | if (need) { | ||
37010 | prefinish(stream, state); | ||
37011 | if (state.pendingcb === 0) { | ||
37012 | state.finished = true; | ||
37013 | stream.emit('finish'); | ||
37014 | } | ||
37015 | } | ||
37016 | return need; | ||
37017 | } | ||
37018 | |||
37019 | function endWritable(stream, state, cb) { | ||
37020 | state.ending = true; | ||
37021 | finishMaybe(stream, state); | ||
37022 | if (cb) { | ||
37023 | if (state.finished) processNextTick(cb);else stream.once('finish', cb); | ||
37024 | } | ||
37025 | state.ended = true; | ||
37026 | stream.writable = false; | ||
37027 | } | ||
37028 | |||
37029 | function onCorkedFinish(corkReq, state, err) { | ||
37030 | var entry = corkReq.entry; | ||
37031 | corkReq.entry = null; | ||
37032 | while (entry) { | ||
37033 | var cb = entry.callback; | ||
37034 | state.pendingcb--; | ||
37035 | cb(err); | ||
37036 | entry = entry.next; | ||
37037 | } | ||
37038 | if (state.corkedRequestsFree) { | ||
37039 | state.corkedRequestsFree.next = corkReq; | ||
37040 | } else { | ||
37041 | state.corkedRequestsFree = corkReq; | ||
37042 | } | ||
37043 | } | ||
37044 | |||
37045 | Object.defineProperty(Writable.prototype, 'destroyed', { | ||
37046 | get: function () { | ||
37047 | if (this._writableState === undefined) { | ||
37048 | return false; | ||
37049 | } | ||
37050 | return this._writableState.destroyed; | ||
37051 | }, | ||
37052 | set: function (value) { | ||
37053 | // we ignore the value if the stream | ||
37054 | // has not been initialized yet | ||
37055 | if (!this._writableState) { | ||
37056 | return; | ||
37057 | } | ||
37058 | |||
37059 | // backward compatibility, the user is explicitly | ||
37060 | // managing destroyed | ||
37061 | this._writableState.destroyed = value; | ||
37062 | } | ||
37063 | }); | ||
37064 | |||
37065 | Writable.prototype.destroy = destroyImpl.destroy; | ||
37066 | Writable.prototype._undestroy = destroyImpl.undestroy; | ||
37067 | Writable.prototype._destroy = function (err, cb) { | ||
37068 | this.end(); | ||
37069 | cb(err); | ||
37070 | }; | ||
37071 | }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | ||
37072 | },{"./_stream_duplex":234,"./internal/streams/destroy":240,"./internal/streams/stream":241,"_process":190,"core-util-is":109,"inherits":163,"process-nextick-args":189,"safe-buffer":247,"util-deprecate":265}],239:[function(require,module,exports){ | ||
37073 | 'use strict'; | ||
37074 | |||
37075 | /*<replacement>*/ | ||
37076 | |||
37077 | function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } | ||
37078 | |||
37079 | var Buffer = require('safe-buffer').Buffer; | ||
37080 | /*</replacement>*/ | ||
37081 | |||
37082 | function copyBuffer(src, target, offset) { | ||
37083 | src.copy(target, offset); | ||
37084 | } | ||
37085 | |||
37086 | module.exports = function () { | ||
37087 | function BufferList() { | ||
37088 | _classCallCheck(this, BufferList); | ||
37089 | |||
37090 | this.head = null; | ||
37091 | this.tail = null; | ||
37092 | this.length = 0; | ||
37093 | } | ||
37094 | |||
37095 | BufferList.prototype.push = function push(v) { | ||
37096 | var entry = { data: v, next: null }; | ||
37097 | if (this.length > 0) this.tail.next = entry;else this.head = entry; | ||
37098 | this.tail = entry; | ||
37099 | ++this.length; | ||
37100 | }; | ||
37101 | |||
37102 | BufferList.prototype.unshift = function unshift(v) { | ||
37103 | var entry = { data: v, next: this.head }; | ||
37104 | if (this.length === 0) this.tail = entry; | ||
37105 | this.head = entry; | ||
37106 | ++this.length; | ||
37107 | }; | ||
37108 | |||
37109 | BufferList.prototype.shift = function shift() { | ||
37110 | if (this.length === 0) return; | ||
37111 | var ret = this.head.data; | ||
37112 | if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; | ||
37113 | --this.length; | ||
37114 | return ret; | ||
37115 | }; | ||
37116 | |||
37117 | BufferList.prototype.clear = function clear() { | ||
37118 | this.head = this.tail = null; | ||
37119 | this.length = 0; | ||
37120 | }; | ||
37121 | |||
37122 | BufferList.prototype.join = function join(s) { | ||
37123 | if (this.length === 0) return ''; | ||
37124 | var p = this.head; | ||
37125 | var ret = '' + p.data; | ||
37126 | while (p = p.next) { | ||
37127 | ret += s + p.data; | ||
37128 | }return ret; | ||
37129 | }; | ||
37130 | |||
37131 | BufferList.prototype.concat = function concat(n) { | ||
37132 | if (this.length === 0) return Buffer.alloc(0); | ||
37133 | if (this.length === 1) return this.head.data; | ||
37134 | var ret = Buffer.allocUnsafe(n >>> 0); | ||
37135 | var p = this.head; | ||
37136 | var i = 0; | ||
37137 | while (p) { | ||
37138 | copyBuffer(p.data, ret, i); | ||
37139 | i += p.data.length; | ||
37140 | p = p.next; | ||
37141 | } | ||
37142 | return ret; | ||
37143 | }; | ||
37144 | |||
37145 | return BufferList; | ||
37146 | }(); | ||
37147 | },{"safe-buffer":247}],240:[function(require,module,exports){ | ||
37148 | 'use strict'; | ||
37149 | |||
37150 | /*<replacement>*/ | ||
37151 | |||
37152 | var processNextTick = require('process-nextick-args'); | ||
37153 | /*</replacement>*/ | ||
37154 | |||
37155 | // undocumented cb() API, needed for core, not for public API | ||
37156 | function destroy(err, cb) { | ||
37157 | var _this = this; | ||
37158 | |||
37159 | var readableDestroyed = this._readableState && this._readableState.destroyed; | ||
37160 | var writableDestroyed = this._writableState && this._writableState.destroyed; | ||
37161 | |||
37162 | if (readableDestroyed || writableDestroyed) { | ||
37163 | if (cb) { | ||
37164 | cb(err); | ||
37165 | } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { | ||
37166 | processNextTick(emitErrorNT, this, err); | ||
37167 | } | ||
37168 | return; | ||
37169 | } | ||
37170 | |||
37171 | // we set destroyed to true before firing error callbacks in order | ||
37172 | // to make it re-entrance safe in case destroy() is called within callbacks | ||
37173 | |||
37174 | if (this._readableState) { | ||
37175 | this._readableState.destroyed = true; | ||
37176 | } | ||
37177 | |||
37178 | // if this is a duplex stream mark the writable part as destroyed as well | ||
37179 | if (this._writableState) { | ||
37180 | this._writableState.destroyed = true; | ||
37181 | } | ||
37182 | |||
37183 | this._destroy(err || null, function (err) { | ||
37184 | if (!cb && err) { | ||
37185 | processNextTick(emitErrorNT, _this, err); | ||
37186 | if (_this._writableState) { | ||
37187 | _this._writableState.errorEmitted = true; | ||
37188 | } | ||
37189 | } else if (cb) { | ||
37190 | cb(err); | ||
37191 | } | ||
37192 | }); | ||
37193 | } | ||
37194 | |||
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; | ||
37201 | } | ||
37202 | |||
37203 | if (this._writableState) { | ||
37204 | this._writableState.destroyed = false; | ||
37205 | this._writableState.ended = false; | ||
37206 | this._writableState.ending = false; | ||
37207 | this._writableState.finished = false; | ||
37208 | this._writableState.errorEmitted = false; | ||
37209 | } | ||
37210 | } | ||
37211 | |||
37212 | function emitErrorNT(self, err) { | ||
37213 | self.emit('error', err); | ||
37214 | } | ||
37215 | |||
37216 | module.exports = { | ||
37217 | destroy: destroy, | ||
37218 | undestroy: undestroy | ||
37219 | }; | ||
37220 | },{"process-nextick-args":189}],241:[function(require,module,exports){ | ||
37221 | module.exports = require('events').EventEmitter; | ||
37222 | |||
37223 | },{"events":143}],242:[function(require,module,exports){ | ||
37224 | module.exports = require('./readable').PassThrough | ||
37225 | |||
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'); | ||
37234 | |||
37235 | },{"./lib/_stream_duplex.js":234,"./lib/_stream_passthrough.js":235,"./lib/_stream_readable.js":236,"./lib/_stream_transform.js":237,"./lib/_stream_writable.js":238}],244:[function(require,module,exports){ | ||
37236 | module.exports = require('./readable').Transform | ||
37237 | |||
37238 | },{"./readable":243}],245:[function(require,module,exports){ | ||
37239 | module.exports = require('./lib/_stream_writable.js'); | ||
37240 | |||
37241 | },{"./lib/_stream_writable.js":238}],246:[function(require,module,exports){ | ||
37242 | (function (Buffer){ | ||
37243 | 'use strict' | ||
37244 | var inherits = require('inherits') | ||
37245 | var HashBase = require('hash-base') | ||
37246 | |||
37247 | function RIPEMD160 () { | ||
37248 | HashBase.call(this, 64) | ||
37249 | |||
37250 | // state | ||
37251 | this._a = 0x67452301 | ||
37252 | this._b = 0xefcdab89 | ||
37253 | this._c = 0x98badcfe | ||
37254 | this._d = 0x10325476 | ||
37255 | this._e = 0xc3d2e1f0 | ||
37256 | } | ||
37257 | |||
37258 | inherits(RIPEMD160, HashBase) | ||
37259 | |||
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) | ||
37263 | |||
37264 | var al = this._a | ||
37265 | var bl = this._b | ||
37266 | var cl = this._c | ||
37267 | var dl = this._d | ||
37268 | var el = this._e | ||
37269 | |||
37270 | // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 | ||
37271 | // K = 0x00000000 | ||
37272 | // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8 | ||
37273 | al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10) | ||
37274 | el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10) | ||
37275 | dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10) | ||
37276 | cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10) | ||
37277 | bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10) | ||
37278 | al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10) | ||
37279 | el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10) | ||
37280 | dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10) | ||
37281 | cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10) | ||
37282 | bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10) | ||
37283 | al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10) | ||
37284 | el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10) | ||
37285 | dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10) | ||
37286 | cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10) | ||
37287 | bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10) | ||
37288 | al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10) | ||
37289 | |||
37290 | // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8 | ||
37291 | // K = 0x5a827999 | ||
37292 | // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12 | ||
37293 | el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10) | ||
37294 | dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10) | ||
37295 | cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10) | ||
37296 | bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10) | ||
37297 | al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10) | ||
37298 | el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10) | ||
37299 | dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10) | ||
37300 | cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10) | ||
37301 | bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10) | ||
37302 | al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10) | ||
37303 | el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10) | ||
37304 | dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10) | ||
37305 | cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10) | ||
37306 | bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10) | ||
37307 | al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10) | ||
37308 | el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10) | ||
37309 | |||
37310 | // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12 | ||
37311 | // K = 0x6ed9eba1 | ||
37312 | // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5 | ||
37313 | dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10) | ||
37314 | cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10) | ||
37315 | bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10) | ||
37316 | al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10) | ||
37317 | el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10) | ||
37318 | dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10) | ||
37319 | cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10) | ||
37320 | bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10) | ||
37321 | al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10) | ||
37322 | el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10) | ||
37323 | dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10) | ||
37324 | cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10) | ||
37325 | bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10) | ||
37326 | al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10) | ||
37327 | el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10) | ||
37328 | dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10) | ||
37329 | |||
37330 | // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2 | ||
37331 | // K = 0x8f1bbcdc | ||
37332 | // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12 | ||
37333 | cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10) | ||
37334 | bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10) | ||
37335 | al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10) | ||
37336 | el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10) | ||
37337 | dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10) | ||
37338 | cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10) | ||
37339 | bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10) | ||
37340 | al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10) | ||
37341 | el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10) | ||
37342 | dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10) | ||
37343 | cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10) | ||
37344 | bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10) | ||
37345 | al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10) | ||
37346 | el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10) | ||
37347 | dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10) | ||
37348 | cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10) | ||
37349 | |||
37350 | // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 | ||
37351 | // K = 0xa953fd4e | ||
37352 | // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 | ||
37353 | bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10) | ||
37354 | al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10) | ||
37355 | el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10) | ||
37356 | dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10) | ||
37357 | cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10) | ||
37358 | bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10) | ||
37359 | al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10) | ||
37360 | el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10) | ||
37361 | dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10) | ||
37362 | cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10) | ||
37363 | bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10) | ||
37364 | al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10) | ||
37365 | el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10) | ||
37366 | dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10) | ||
37367 | cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10) | ||
37368 | bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10) | ||
37369 | |||
37370 | var ar = this._a | ||
37371 | var br = this._b | ||
37372 | var cr = this._c | ||
37373 | var dr = this._d | ||
37374 | var er = this._e | ||
37375 | |||
37376 | // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12 | ||
37377 | // K' = 0x50a28be6 | ||
37378 | // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6 | ||
37379 | ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10) | ||
37380 | er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10) | ||
37381 | dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10) | ||
37382 | cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10) | ||
37383 | br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10) | ||
37384 | ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10) | ||
37385 | er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10) | ||
37386 | dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10) | ||
37387 | cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10) | ||
37388 | br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10) | ||
37389 | ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10) | ||
37390 | er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10) | ||
37391 | dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10) | ||
37392 | cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10) | ||
37393 | br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10) | ||
37394 | ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10) | ||
37395 | |||
37396 | // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2 | ||
37397 | // K' = 0x5c4dd124 | ||
37398 | // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11 | ||
37399 | er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10) | ||
37400 | dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10) | ||
37401 | cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10) | ||
37402 | br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10) | ||
37403 | ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10) | ||
37404 | er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10) | ||
37405 | dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10) | ||
37406 | cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10) | ||
37407 | br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10) | ||
37408 | ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10) | ||
37409 | er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10) | ||
37410 | dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10) | ||
37411 | cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10) | ||
37412 | br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10) | ||
37413 | ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10) | ||
37414 | er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10) | ||
37415 | |||
37416 | // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13 | ||
37417 | // K' = 0x6d703ef3 | ||
37418 | // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5 | ||
37419 | dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10) | ||
37420 | cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10) | ||
37421 | br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10) | ||
37422 | ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10) | ||
37423 | er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10) | ||
37424 | dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10) | ||
37425 | cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10) | ||
37426 | br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10) | ||
37427 | ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10) | ||
37428 | er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10) | ||
37429 | dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10) | ||
37430 | cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10) | ||
37431 | br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10) | ||
37432 | ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10) | ||
37433 | er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10) | ||
37434 | dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10) | ||
37435 | |||
37436 | // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14 | ||
37437 | // K' = 0x7a6d76e9 | ||
37438 | // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8 | ||
37439 | cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10) | ||
37440 | br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10) | ||
37441 | ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10) | ||
37442 | er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10) | ||
37443 | dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10) | ||
37444 | cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10) | ||
37445 | br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10) | ||
37446 | ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10) | ||
37447 | er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10) | ||
37448 | dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10) | ||
37449 | cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10) | ||
37450 | br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10) | ||
37451 | ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10) | ||
37452 | er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10) | ||
37453 | dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10) | ||
37454 | cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10) | ||
37455 | |||
37456 | // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 | ||
37457 | // K' = 0x00000000 | ||
37458 | // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 | ||
37459 | br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10) | ||
37460 | ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10) | ||
37461 | er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10) | ||
37462 | dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10) | ||
37463 | cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10) | ||
37464 | br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10) | ||
37465 | ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10) | ||
37466 | er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10) | ||
37467 | dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10) | ||
37468 | cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10) | ||
37469 | br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10) | ||
37470 | ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10) | ||
37471 | er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10) | ||
37472 | dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10) | ||
37473 | cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10) | ||
37474 | br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10) | ||
37475 | |||
37476 | // change state | ||
37477 | var t = (this._b + cl + dr) | 0 | ||
37478 | this._b = (this._c + dl + er) | 0 | ||
37479 | this._c = (this._d + el + ar) | 0 | ||
37480 | this._d = (this._e + al + br) | 0 | ||
37481 | this._e = (this._a + bl + cr) | 0 | ||
37482 | this._a = t | ||
37483 | } | ||
37484 | |||
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) | ||
37490 | this._update() | ||
37491 | this._blockOffset = 0 | ||
37492 | } | ||
37493 | |||
37494 | this._block.fill(0, this._blockOffset, 56) | ||
37495 | this._block.writeUInt32LE(this._length[0], 56) | ||
37496 | this._block.writeUInt32LE(this._length[1], 60) | ||
37497 | this._update() | ||
37498 | |||
37499 | // produce result | ||
37500 | var buffer = new Buffer(20) | ||
37501 | buffer.writeInt32LE(this._a, 0) | ||
37502 | buffer.writeInt32LE(this._b, 4) | ||
37503 | buffer.writeInt32LE(this._c, 8) | ||
37504 | buffer.writeInt32LE(this._d, 12) | ||
37505 | buffer.writeInt32LE(this._e, 16) | ||
37506 | return buffer | ||
37507 | } | ||
37508 | |||
37509 | function rotl (x, n) { | ||
37510 | return (x << n) | (x >>> (32 - n)) | ||
37511 | } | ||
37512 | |||
37513 | function fn1 (a, b, c, d, e, m, k, s) { | ||
37514 | return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 | ||
37515 | } | ||
37516 | |||
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 | ||
37519 | } | ||
37520 | |||
37521 | function fn3 (a, b, c, d, e, m, k, s) { | ||
37522 | return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 | ||
37523 | } | ||
37524 | |||
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 | ||
37527 | } | ||
37528 | |||
37529 | function fn5 (a, b, c, d, e, m, k, s) { | ||
37530 | return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 | ||
37531 | } | ||
37532 | |||
37533 | module.exports = RIPEMD160 | ||
37534 | |||
37535 | }).call(this,require("buffer").Buffer) | ||
37536 | },{"buffer":107,"hash-base":146,"inherits":163}],247:[function(require,module,exports){ | ||
37537 | /* eslint-disable node/no-deprecated-api */ | ||
37538 | var buffer = require('buffer') | ||
37539 | var Buffer = buffer.Buffer | ||
37540 | |||
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] | ||
37545 | } | ||
37546 | } | ||
37547 | if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { | ||
37548 | module.exports = buffer | ||
37549 | } else { | ||
37550 | // Copy properties from require('buffer') | ||
37551 | copyProps(buffer, exports) | ||
37552 | exports.Buffer = SafeBuffer | ||
37553 | } | ||
37554 | |||
37555 | function SafeBuffer (arg, encodingOrOffset, length) { | ||
37556 | return Buffer(arg, encodingOrOffset, length) | ||
37557 | } | ||
37558 | |||
37559 | // Copy static methods from Buffer | ||
37560 | copyProps(Buffer, SafeBuffer) | ||
37561 | |||
37562 | SafeBuffer.from = function (arg, encodingOrOffset, length) { | ||
37563 | if (typeof arg === 'number') { | ||
37564 | throw new TypeError('Argument must not be a number') | ||
37565 | } | ||
37566 | return Buffer(arg, encodingOrOffset, length) | ||
37567 | } | ||
37568 | |||
37569 | SafeBuffer.alloc = function (size, fill, encoding) { | ||
37570 | if (typeof size !== 'number') { | ||
37571 | throw new TypeError('Argument must be a number') | ||
37572 | } | ||
37573 | var buf = Buffer(size) | ||
37574 | if (fill !== undefined) { | ||
37575 | if (typeof encoding === 'string') { | ||
37576 | buf.fill(fill, encoding) | ||
37577 | } else { | ||
37578 | buf.fill(fill) | ||
37579 | } | ||
37580 | } else { | ||
37581 | buf.fill(0) | ||
37582 | } | ||
37583 | return buf | ||
37584 | } | ||
37585 | |||
37586 | SafeBuffer.allocUnsafe = function (size) { | ||
37587 | if (typeof size !== 'number') { | ||
37588 | throw new TypeError('Argument must be a number') | ||
37589 | } | ||
37590 | return Buffer(size) | ||
37591 | } | ||
37592 | |||
37593 | SafeBuffer.allocUnsafeSlow = function (size) { | ||
37594 | if (typeof size !== 'number') { | ||
37595 | throw new TypeError('Argument must be a number') | ||
37596 | } | ||
37597 | return buffer.SlowBuffer(size) | ||
37598 | } | ||
37599 | |||
37600 | },{"buffer":107}],248:[function(require,module,exports){ | ||
37601 | (function (Buffer){ | ||
37602 | var crypto = require('crypto') | ||
37603 | /* eslint-disable camelcase */ | ||
37604 | |||
37605 | var MAX_VALUE = 0x7fffffff | ||
37606 | |||
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') | ||
37610 | |||
37611 | if (N > MAX_VALUE / 128 / r) throw Error('Parameter N is too large') | ||
37612 | if (r > MAX_VALUE / 128 / p) throw Error('Parameter r is too large') | ||
37613 | |||
37614 | var XY = new Buffer(256 * r) | ||
37615 | var V = new Buffer(128 * r * N) | ||
37616 | |||
37617 | // pseudo global | ||
37618 | var B32 = new Int32Array(16) // salsa20_8 | ||
37619 | var x = new Int32Array(16) // salsa20_8 | ||
37620 | var _X = new Buffer(64) // blockmix_salsa8 | ||
37621 | |||
37622 | // pseudo global | ||
37623 | var B = crypto.pbkdf2Sync(key, salt, 1, p * 128 * r, 'sha256') | ||
37624 | |||
37625 | var tickCallback | ||
37626 | if (progressCallback) { | ||
37627 | var totalOps = p * N * 2 | ||
37628 | var currentOp = 0 | ||
37629 | |||
37630 | tickCallback = function () { | ||
37631 | ++currentOp | ||
37632 | |||
37633 | // send progress notifications once every 1,000 ops | ||
37634 | if (currentOp % 1000 === 0) { | ||
37635 | progressCallback({ | ||
37636 | current: currentOp, | ||
37637 | total: totalOps, | ||
37638 | percent: (currentOp / totalOps) * 100.0 | ||
37639 | }) | ||
37640 | } | ||
37641 | } | ||
37642 | } | ||
37643 | |||
37644 | for (var i = 0; i < p; i++) { | ||
37645 | smix(B, i * 128 * r, r, N, V, XY) | ||
37646 | } | ||
37647 | |||
37648 | return crypto.pbkdf2Sync(key, B, 1, dkLen, 'sha256') | ||
37649 | |||
37650 | // all of these functions are actually moved to the top | ||
37651 | // due to function hoisting | ||
37652 | |||
37653 | function smix (B, Bi, r, N, V, XY) { | ||
37654 | var Xi = 0 | ||
37655 | var Yi = 128 * r | ||
37656 | var i | ||
37657 | |||
37658 | B.copy(XY, Xi, Bi, Bi + Yi) | ||
37659 | |||
37660 | for (i = 0; i < N; i++) { | ||
37661 | XY.copy(V, i * Yi, Xi, Xi + Yi) | ||
37662 | blockmix_salsa8(XY, Xi, Yi, r) | ||
37663 | |||
37664 | if (tickCallback) tickCallback() | ||
37665 | } | ||
37666 | |||
37667 | for (i = 0; i < N; i++) { | ||
37668 | var offset = Xi + (2 * r - 1) * 64 | ||
37669 | var j = XY.readUInt32LE(offset) & (N - 1) | ||
37670 | blockxor(V, j * Yi, XY, Xi, Yi) | ||
37671 | blockmix_salsa8(XY, Xi, Yi, r) | ||
37672 | |||
37673 | if (tickCallback) tickCallback() | ||
37674 | } | ||
37675 | |||
37676 | XY.copy(B, Bi, Xi, Xi + Yi) | ||
37677 | } | ||
37678 | |||
37679 | function blockmix_salsa8 (BY, Bi, Yi, r) { | ||
37680 | var i | ||
37681 | |||
37682 | arraycopy(BY, Bi + (2 * r - 1) * 64, _X, 0, 64) | ||
37683 | |||
37684 | for (i = 0; i < 2 * r; i++) { | ||
37685 | blockxor(BY, i * 64, _X, 0, 64) | ||
37686 | salsa20_8(_X) | ||
37687 | arraycopy(_X, 0, BY, Yi + (i * 64), 64) | ||
37688 | } | ||
37689 | |||
37690 | for (i = 0; i < r; i++) { | ||
37691 | arraycopy(BY, Yi + (i * 2) * 64, BY, Bi + (i * 64), 64) | ||
37692 | } | ||
37693 | |||
37694 | for (i = 0; i < r; i++) { | ||
37695 | arraycopy(BY, Yi + (i * 2 + 1) * 64, BY, Bi + (i + r) * 64, 64) | ||
37696 | } | ||
37697 | } | ||
37698 | |||
37699 | function R (a, b) { | ||
37700 | return (a << b) | (a >>> (32 - b)) | ||
37701 | } | ||
37702 | |||
37703 | function salsa20_8 (B) { | ||
37704 | var i | ||
37705 | |||
37706 | for (i = 0; i < 16; i++) { | ||
37707 | B32[i] = (B[i * 4 + 0] & 0xff) << 0 | ||
37708 | B32[i] |= (B[i * 4 + 1] & 0xff) << 8 | ||
37709 | B32[i] |= (B[i * 4 + 2] & 0xff) << 16 | ||
37710 | B32[i] |= (B[i * 4 + 3] & 0xff) << 24 | ||
37711 | // B32[i] = B.readUInt32LE(i*4) <--- this is signficantly slower even in Node.js | ||
37712 | } | ||
37713 | |||
37714 | arraycopy(B32, 0, x, 0, 16) | ||
37715 | |||
37716 | for (i = 8; i > 0; i -= 2) { | ||
37717 | x[4] ^= R(x[0] + x[12], 7) | ||
37718 | x[8] ^= R(x[4] + x[0], 9) | ||
37719 | x[12] ^= R(x[8] + x[4], 13) | ||
37720 | x[0] ^= R(x[12] + x[8], 18) | ||
37721 | x[9] ^= R(x[5] + x[1], 7) | ||
37722 | x[13] ^= R(x[9] + x[5], 9) | ||
37723 | x[1] ^= R(x[13] + x[9], 13) | ||
37724 | x[5] ^= R(x[1] + x[13], 18) | ||
37725 | x[14] ^= R(x[10] + x[6], 7) | ||
37726 | x[2] ^= R(x[14] + x[10], 9) | ||
37727 | x[6] ^= R(x[2] + x[14], 13) | ||
37728 | x[10] ^= R(x[6] + x[2], 18) | ||
37729 | x[3] ^= R(x[15] + x[11], 7) | ||
37730 | x[7] ^= R(x[3] + x[15], 9) | ||
37731 | x[11] ^= R(x[7] + x[3], 13) | ||
37732 | x[15] ^= R(x[11] + x[7], 18) | ||
37733 | x[1] ^= R(x[0] + x[3], 7) | ||
37734 | x[2] ^= R(x[1] + x[0], 9) | ||
37735 | x[3] ^= R(x[2] + x[1], 13) | ||
37736 | x[0] ^= R(x[3] + x[2], 18) | ||
37737 | x[6] ^= R(x[5] + x[4], 7) | ||
37738 | x[7] ^= R(x[6] + x[5], 9) | ||
37739 | x[4] ^= R(x[7] + x[6], 13) | ||
37740 | x[5] ^= R(x[4] + x[7], 18) | ||
37741 | x[11] ^= R(x[10] + x[9], 7) | ||
37742 | x[8] ^= R(x[11] + x[10], 9) | ||
37743 | x[9] ^= R(x[8] + x[11], 13) | ||
37744 | x[10] ^= R(x[9] + x[8], 18) | ||
37745 | x[12] ^= R(x[15] + x[14], 7) | ||
37746 | x[13] ^= R(x[12] + x[15], 9) | ||
37747 | x[14] ^= R(x[13] + x[12], 13) | ||
37748 | x[15] ^= R(x[14] + x[13], 18) | ||
37749 | } | ||
37750 | |||
37751 | for (i = 0; i < 16; ++i) B32[i] = x[i] + B32[i] | ||
37752 | |||
37753 | for (i = 0; i < 16; i++) { | ||
37754 | var bi = i * 4 | ||
37755 | B[bi + 0] = (B32[i] >> 0 & 0xff) | ||
37756 | B[bi + 1] = (B32[i] >> 8 & 0xff) | ||
37757 | B[bi + 2] = (B32[i] >> 16 & 0xff) | ||
37758 | B[bi + 3] = (B32[i] >> 24 & 0xff) | ||
37759 | // B.writeInt32LE(B32[i], i*4) //<--- this is signficantly slower even in Node.js | ||
37760 | } | ||
37761 | } | ||
37762 | |||
37763 | // naive approach... going back to loop unrolling may yield additional performance | ||
37764 | function blockxor (S, Si, D, Di, len) { | ||
37765 | for (var i = 0; i < len; i++) { | ||
37766 | D[Di + i] ^= S[Si + i] | ||
37767 | } | ||
37768 | } | ||
37769 | } | ||
37770 | |||
37771 | function arraycopy (src, srcPos, dest, destPos, length) { | ||
37772 | if (Buffer.isBuffer(src) && Buffer.isBuffer(dest)) { | ||
37773 | src.copy(dest, destPos, srcPos, srcPos + length) | ||
37774 | } else { | ||
37775 | while (length--) { | ||
37776 | dest[destPos++] = src[srcPos++] | ||
37777 | } | ||
37778 | } | ||
37779 | } | ||
37780 | |||
37781 | module.exports = scrypt | ||
37782 | |||
37783 | }).call(this,require("buffer").Buffer) | ||
37784 | },{"buffer":107,"crypto":116}],249:[function(require,module,exports){ | ||
37785 | 'use strict' | ||
37786 | module.exports = require('./lib')(require('./lib/elliptic')) | ||
37787 | |||
37788 | },{"./lib":253,"./lib/elliptic":252}],250:[function(require,module,exports){ | ||
37789 | (function (Buffer){ | ||
37790 | 'use strict' | ||
37791 | var toString = Object.prototype.toString | ||
37792 | |||
37793 | // TypeError | ||
37794 | exports.isArray = function (value, message) { | ||
37795 | if (!Array.isArray(value)) throw TypeError(message) | ||
37796 | } | ||
37797 | |||
37798 | exports.isBoolean = function (value, message) { | ||
37799 | if (toString.call(value) !== '[object Boolean]') throw TypeError(message) | ||
37800 | } | ||
37801 | |||
37802 | exports.isBuffer = function (value, message) { | ||
37803 | if (!Buffer.isBuffer(value)) throw TypeError(message) | ||
37804 | } | ||
37805 | |||
37806 | exports.isFunction = function (value, message) { | ||
37807 | if (toString.call(value) !== '[object Function]') throw TypeError(message) | ||
37808 | } | ||
37809 | |||
37810 | exports.isNumber = function (value, message) { | ||
37811 | if (toString.call(value) !== '[object Number]') throw TypeError(message) | ||
37812 | } | ||
37813 | |||
37814 | exports.isObject = function (value, message) { | ||
37815 | if (toString.call(value) !== '[object Object]') throw TypeError(message) | ||
37816 | } | ||
37817 | |||
37818 | // RangeError | ||
37819 | exports.isBufferLength = function (buffer, length, message) { | ||
37820 | if (buffer.length !== length) throw RangeError(message) | ||
37821 | } | ||
37822 | |||
37823 | exports.isBufferLength2 = function (buffer, length1, length2, message) { | ||
37824 | if (buffer.length !== length1 && buffer.length !== length2) throw RangeError(message) | ||
37825 | } | ||
37826 | |||
37827 | exports.isLengthGTZero = function (value, message) { | ||
37828 | if (value.length === 0) throw RangeError(message) | ||
37829 | } | ||
37830 | |||
37831 | exports.isNumberInInterval = function (number, x, y, message) { | ||
37832 | if (number <= x || number >= y) throw RangeError(message) | ||
37833 | } | ||
37834 | |||
37835 | }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) | ||
37836 | },{"../../is-buffer/index.js":164}],251:[function(require,module,exports){ | ||
37837 | 'use strict' | ||
37838 | var Buffer = require('safe-buffer').Buffer | ||
37839 | var bip66 = require('bip66') | ||
37840 | |||
37841 | var EC_PRIVKEY_EXPORT_DER_COMPRESSED = Buffer.from([ | ||
37842 | // begin | ||
37843 | 0x30, 0x81, 0xd3, 0x02, 0x01, 0x01, 0x04, 0x20, | ||
37844 | // private key | ||
37845 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37846 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37847 | // middle | ||
37848 | 0xa0, 0x81, 0x85, 0x30, 0x81, 0x82, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, | ||
37849 | 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, | ||
37850 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, | ||
37851 | 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, | ||
37852 | 0x21, 0x02, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, | ||
37853 | 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, | ||
37854 | 0x17, 0x98, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, | ||
37855 | 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, | ||
37856 | 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x24, 0x03, 0x22, 0x00, | ||
37857 | // public key | ||
37858 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37859 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37860 | 0x00 | ||
37861 | ]) | ||
37862 | |||
37863 | var EC_PRIVKEY_EXPORT_DER_UNCOMPRESSED = Buffer.from([ | ||
37864 | // begin | ||
37865 | 0x30, 0x82, 0x01, 0x13, 0x02, 0x01, 0x01, 0x04, 0x20, | ||
37866 | // private key | ||
37867 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37868 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37869 | // middle | ||
37870 | 0xa0, 0x81, 0xa5, 0x30, 0x81, 0xa2, 0x02, 0x01, 0x01, 0x30, 0x2c, 0x06, 0x07, 0x2a, 0x86, 0x48, | ||
37871 | 0xcE, 0x3d, 0x01, 0x01, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, | ||
37872 | 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, | ||
37873 | 0xff, 0xff, 0xfE, 0xff, 0xff, 0xfc, 0x2f, 0x30, 0x06, 0x04, 0x01, 0x00, 0x04, 0x01, 0x07, 0x04, | ||
37874 | 0x41, 0x04, 0x79, 0xbE, 0x66, 0x7E, 0xf9, 0xdc, 0xbb, 0xac, 0x55, 0xa0, 0x62, 0x95, 0xcE, 0x87, | ||
37875 | 0x0b, 0x07, 0x02, 0x9b, 0xfc, 0xdb, 0x2d, 0xcE, 0x28, 0xd9, 0x59, 0xf2, 0x81, 0x5b, 0x16, 0xf8, | ||
37876 | 0x17, 0x98, 0x48, 0x3a, 0xda, 0x77, 0x26, 0xa3, 0xc4, 0x65, 0x5d, 0xa4, 0xfb, 0xfc, 0x0E, 0x11, | ||
37877 | 0x08, 0xa8, 0xfd, 0x17, 0xb4, 0x48, 0xa6, 0x85, 0x54, 0x19, 0x9c, 0x47, 0xd0, 0x8f, 0xfb, 0x10, | ||
37878 | 0xd4, 0xb8, 0x02, 0x21, 0x00, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, | ||
37879 | 0xff, 0xff, 0xff, 0xff, 0xfE, 0xba, 0xaE, 0xdc, 0xE6, 0xaf, 0x48, 0xa0, 0x3b, 0xbf, 0xd2, 0x5E, | ||
37880 | 0x8c, 0xd0, 0x36, 0x41, 0x41, 0x02, 0x01, 0x01, 0xa1, 0x44, 0x03, 0x42, 0x00, | ||
37881 | // public key | ||
37882 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37883 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37884 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37885 | 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, | ||
37886 | 0x00 | ||
37887 | ]) | ||
37888 | |||
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) | ||
37893 | return result | ||
37894 | } | ||
37895 | |||
37896 | exports.privateKeyImport = function (privateKey) { | ||
37897 | var length = privateKey.length | ||
37898 | |||
37899 | // sequence header | ||
37900 | var index = 0 | ||
37901 | if (length < index + 1 || privateKey[index] !== 0x30) return | ||
37902 | index += 1 | ||
37903 | |||
37904 | // sequence length constructor | ||
37905 | if (length < index + 1 || !(privateKey[index] & 0x80)) return | ||
37906 | |||
37907 | var lenb = privateKey[index] & 0x7f | ||
37908 | index += 1 | ||
37909 | if (lenb < 1 || lenb > 2) return | ||
37910 | if (length < index + lenb) return | ||
37911 | |||
37912 | // sequence length | ||
37913 | var len = privateKey[index + lenb - 1] | (lenb > 1 ? privateKey[index + lenb - 2] << 8 : 0) | ||
37914 | index += lenb | ||
37915 | if (length < index + len) return | ||
37916 | |||
37917 | // sequence element 0: version number (=1) | ||
37918 | if (length < index + 3 || | ||
37919 | privateKey[index] !== 0x02 || | ||
37920 | privateKey[index + 1] !== 0x01 || | ||
37921 | privateKey[index + 2] !== 0x01) { | ||
37922 | return | ||
37923 | } | ||
37924 | index += 3 | ||
37925 | |||
37926 | // sequence element 1: octet string, up to 32 bytes | ||
37927 | if (length < index + 2 || | ||
37928 | privateKey[index] !== 0x04 || | ||
37929 | privateKey[index + 1] > 0x20 || | ||
37930 | length < index + 2 + privateKey[index + 1]) { | ||
37931 | return | ||
37932 | } | ||
37933 | |||
37934 | return privateKey.slice(index + 2, index + 2 + privateKey[index + 1]) | ||
37935 | } | ||
37936 | |||
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); | ||
37940 | |||
37941 | var s = Buffer.concat([Buffer.from([0]), sigObj.s]) | ||
37942 | for (var lenS = 33, posS = 0; lenS > 1 && s[posS] === 0x00 && !(s[posS + 1] & 0x80); --lenS, ++posS); | ||
37943 | |||
37944 | return bip66.encode(r.slice(posR), s.slice(posS)) | ||
37945 | } | ||
37946 | |||
37947 | exports.signatureImport = function (sig) { | ||
37948 | var r = Buffer.alloc(32, 0) | ||
37949 | var s = Buffer.alloc(32, 0) | ||
37950 | |||
37951 | try { | ||
37952 | var sigObj = bip66.decode(sig) | ||
37953 | if (sigObj.r.length === 33 && sigObj.r[0] === 0x00) sigObj.r = sigObj.r.slice(1) | ||
37954 | if (sigObj.r.length > 32) throw new Error('R length is too long') | ||
37955 | if (sigObj.s.length === 33 && sigObj.s[0] === 0x00) sigObj.s = sigObj.s.slice(1) | ||
37956 | if (sigObj.s.length > 32) throw new Error('S length is too long') | ||
37957 | } catch (err) { | ||
37958 | return | ||
37959 | } | ||
37960 | |||
37961 | sigObj.r.copy(r, 32 - sigObj.r.length) | ||
37962 | sigObj.s.copy(s, 32 - sigObj.s.length) | ||
37963 | |||
37964 | return { r: r, s: s } | ||
37965 | } | ||
37966 | |||
37967 | exports.signatureImportLax = function (sig) { | ||
37968 | var r = Buffer.alloc(32, 0) | ||
37969 | var s = Buffer.alloc(32, 0) | ||
37970 | |||
37971 | var length = sig.length | ||
37972 | var index = 0 | ||
37973 | |||
37974 | // sequence tag byte | ||
37975 | if (sig[index++] !== 0x30) return | ||
37976 | |||
37977 | // sequence length byte | ||
37978 | var lenbyte = sig[index++] | ||
37979 | if (lenbyte & 0x80) { | ||
37980 | index += lenbyte - 0x80 | ||
37981 | if (index > length) return | ||
37982 | } | ||
37983 | |||
37984 | // sequence tag byte for r | ||
37985 | if (sig[index++] !== 0x02) return | ||
37986 | |||
37987 | // length for r | ||
37988 | var rlen = sig[index++] | ||
37989 | if (rlen & 0x80) { | ||
37990 | lenbyte = rlen - 0x80 | ||
37991 | if (index + lenbyte > length) return | ||
37992 | for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); | ||
37993 | for (rlen = 0; lenbyte > 0; index += 1, lenbyte -= 1) rlen = (rlen << 8) + sig[index] | ||
37994 | } | ||
37995 | if (rlen > length - index) return | ||
37996 | var rindex = index | ||
37997 | index += rlen | ||
37998 | |||
37999 | // sequence tag byte for s | ||
38000 | if (sig[index++] !== 0x02) return | ||
38001 | |||
38002 | // length for s | ||
38003 | var slen = sig[index++] | ||
38004 | if (slen & 0x80) { | ||
38005 | lenbyte = slen - 0x80 | ||
38006 | if (index + lenbyte > length) return | ||
38007 | for (; lenbyte > 0 && sig[index] === 0x00; index += 1, lenbyte -= 1); | ||
38008 | for (slen = 0; lenbyte > 0; index += 1, lenbyte -= 1) slen = (slen << 8) + sig[index] | ||
38009 | } | ||
38010 | if (slen > length - index) return | ||
38011 | var sindex = index | ||
38012 | index += slen | ||
38013 | |||
38014 | // ignore leading zeros in r | ||
38015 | for (; rlen > 0 && sig[rindex] === 0x00; rlen -= 1, rindex += 1); | ||
38016 | // copy r value | ||
38017 | if (rlen > 32) return | ||
38018 | var rvalue = sig.slice(rindex, rindex + rlen) | ||
38019 | rvalue.copy(r, 32 - rvalue.length) | ||
38020 | |||
38021 | // ignore leading zeros in s | ||
38022 | for (; slen > 0 && sig[sindex] === 0x00; slen -= 1, sindex += 1); | ||
38023 | // copy s value | ||
38024 | if (slen > 32) return | ||
38025 | var svalue = sig.slice(sindex, sindex + slen) | ||
38026 | svalue.copy(s, 32 - svalue.length) | ||
38027 | |||
38028 | return { r: r, s: s } | ||
38029 | } | ||
38030 | |||
38031 | },{"bip66":74,"safe-buffer":247}],252:[function(require,module,exports){ | ||
38032 | 'use strict' | ||
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 | ||
38037 | |||
38038 | var messages = require('../messages.json') | ||
38039 | |||
38040 | var ec = new EC('secp256k1') | ||
38041 | var ecparams = ec.curve | ||
38042 | |||
38043 | function loadCompressedPublicKey (first, xBuffer) { | ||
38044 | var x = new BN(xBuffer) | ||
38045 | |||
38046 | // overflow | ||
38047 | if (x.cmp(ecparams.p) >= 0) return null | ||
38048 | x = x.toRed(ecparams.red) | ||
38049 | |||
38050 | // compute corresponding Y | ||
38051 | var y = x.redSqr().redIMul(x).redIAdd(ecparams.b).redSqrt() | ||
38052 | if ((first === 0x03) !== y.isOdd()) y = y.redNeg() | ||
38053 | |||
38054 | return ec.keyPair({ pub: { x: x, y: y } }) | ||
38055 | } | ||
38056 | |||
38057 | function loadUncompressedPublicKey (first, xBuffer, yBuffer) { | ||
38058 | var x = new BN(xBuffer) | ||
38059 | var y = new BN(yBuffer) | ||
38060 | |||
38061 | // overflow | ||
38062 | if (x.cmp(ecparams.p) >= 0 || y.cmp(ecparams.p) >= 0) return null | ||
38063 | |||
38064 | x = x.toRed(ecparams.red) | ||
38065 | y = y.toRed(ecparams.red) | ||
38066 | |||
38067 | // is odd flag | ||
38068 | if ((first === 0x06 || first === 0x07) && y.isOdd() !== (first === 0x07)) return null | ||
38069 | |||
38070 | // x*x*x + b = y*y | ||
38071 | var x3 = x.redSqr().redIMul(x) | ||
38072 | if (!y.redSqr().redISub(x3.redIAdd(ecparams.b)).isZero()) return null | ||
38073 | |||
38074 | return ec.keyPair({ pub: { x: x, y: y } }) | ||
38075 | } | ||
38076 | |||
38077 | function loadPublicKey (publicKey) { | ||
38078 | var first = publicKey[0] | ||
38079 | switch (first) { | ||
38080 | case 0x02: | ||
38081 | case 0x03: | ||
38082 | if (publicKey.length !== 33) return null | ||
38083 | return loadCompressedPublicKey(first, publicKey.slice(1, 33)) | ||
38084 | case 0x04: | ||
38085 | case 0x06: | ||
38086 | case 0x07: | ||
38087 | if (publicKey.length !== 65) return null | ||
38088 | return loadUncompressedPublicKey(first, publicKey.slice(1, 33), publicKey.slice(33, 65)) | ||
38089 | default: | ||
38090 | return null | ||
38091 | } | ||
38092 | } | ||
38093 | |||
38094 | exports.privateKeyVerify = function (privateKey) { | ||
38095 | var bn = new BN(privateKey) | ||
38096 | return bn.cmp(ecparams.n) < 0 && !bn.isZero() | ||
38097 | } | ||
38098 | |||
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) | ||
38102 | |||
38103 | return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) | ||
38104 | } | ||
38105 | |||
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) | ||
38109 | } | ||
38110 | |||
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) | ||
38114 | |||
38115 | return bn.invm(ecparams.n).toArrayLike(Buffer, 'be', 32) | ||
38116 | } | ||
38117 | |||
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) | ||
38121 | |||
38122 | bn.iadd(new BN(privateKey)) | ||
38123 | if (bn.cmp(ecparams.n) >= 0) bn.isub(ecparams.n) | ||
38124 | if (bn.isZero()) throw new Error(messages.EC_PRIVATE_KEY_TWEAK_ADD_FAIL) | ||
38125 | |||
38126 | return bn.toArrayLike(Buffer, 'be', 32) | ||
38127 | } | ||
38128 | |||
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) | ||
38132 | |||
38133 | bn.imul(new BN(privateKey)) | ||
38134 | if (bn.cmp(ecparams.n)) bn = bn.umod(ecparams.n) | ||
38135 | |||
38136 | return bn.toArrayLike(Buffer, 'be', 32) | ||
38137 | } | ||
38138 | |||
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) | ||
38142 | |||
38143 | return Buffer.from(ec.keyFromPrivate(privateKey).getPublic(compressed, true)) | ||
38144 | } | ||
38145 | |||
38146 | exports.publicKeyConvert = function (publicKey, compressed) { | ||
38147 | var pair = loadPublicKey(publicKey) | ||
38148 | if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) | ||
38149 | |||
38150 | return Buffer.from(pair.getPublic(compressed, true)) | ||
38151 | } | ||
38152 | |||
38153 | exports.publicKeyVerify = function (publicKey) { | ||
38154 | return loadPublicKey(publicKey) !== null | ||
38155 | } | ||
38156 | |||
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) | ||
38160 | |||
38161 | tweak = new BN(tweak) | ||
38162 | if (tweak.cmp(ecparams.n) >= 0) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_ADD_FAIL) | ||
38163 | |||
38164 | return Buffer.from(ecparams.g.mul(tweak).add(pair.pub).encode(true, compressed)) | ||
38165 | } | ||
38166 | |||
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) | ||
38170 | |||
38171 | tweak = new BN(tweak) | ||
38172 | if (tweak.cmp(ecparams.n) >= 0 || tweak.isZero()) throw new Error(messages.EC_PUBLIC_KEY_TWEAK_MUL_FAIL) | ||
38173 | |||
38174 | return Buffer.from(pair.pub.mul(tweak).encode(true, compressed)) | ||
38175 | } | ||
38176 | |||
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) | ||
38182 | } | ||
38183 | |||
38184 | var point = pairs[0].pub | ||
38185 | for (var j = 1; j < pairs.length; ++j) point = point.add(pairs[j].pub) | ||
38186 | if (point.isInfinity()) throw new Error(messages.EC_PUBLIC_KEY_COMBINE_FAIL) | ||
38187 | |||
38188 | return Buffer.from(point.encode(true, compressed)) | ||
38189 | } | ||
38190 | |||
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) | ||
38195 | |||
38196 | var result = Buffer.from(signature) | ||
38197 | if (s.cmp(ec.nh) === 1) ecparams.n.sub(s).toArrayLike(Buffer, 'be', 32).copy(result, 32) | ||
38198 | |||
38199 | return result | ||
38200 | } | ||
38201 | |||
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) | ||
38206 | |||
38207 | return { r: r, s: s } | ||
38208 | } | ||
38209 | |||
38210 | exports.signatureImport = function (sigObj) { | ||
38211 | var r = new BN(sigObj.r) | ||
38212 | if (r.cmp(ecparams.n) >= 0) r = new BN(0) | ||
38213 | |||
38214 | var s = new BN(sigObj.s) | ||
38215 | if (s.cmp(ecparams.n) >= 0) s = new BN(0) | ||
38216 | |||
38217 | return Buffer.concat([ | ||
38218 | r.toArrayLike(Buffer, 'be', 32), | ||
38219 | s.toArrayLike(Buffer, 'be', 32) | ||
38220 | ]) | ||
38221 | } | ||
38222 | |||
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) | ||
38229 | |||
38230 | return new BN(nonce) | ||
38231 | } | ||
38232 | } | ||
38233 | |||
38234 | var d = new BN(privateKey) | ||
38235 | if (d.cmp(ecparams.n) >= 0 || d.isZero()) throw new Error(messages.ECDSA_SIGN_FAIL) | ||
38236 | |||
38237 | var result = ec.sign(message, privateKey, { canonical: true, k: noncefn, pers: data }) | ||
38238 | return { | ||
38239 | signature: Buffer.concat([ | ||
38240 | result.r.toArrayLike(Buffer, 'be', 32), | ||
38241 | result.s.toArrayLike(Buffer, 'be', 32) | ||
38242 | ]), | ||
38243 | recovery: result.recoveryParam | ||
38244 | } | ||
38245 | } | ||
38246 | |||
38247 | exports.verify = function (message, signature, publicKey) { | ||
38248 | var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)} | ||
38249 | |||
38250 | var sigr = new BN(sigObj.r) | ||
38251 | var sigs = new BN(sigObj.s) | ||
38252 | if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) | ||
38253 | if (sigs.cmp(ec.nh) === 1 || sigr.isZero() || sigs.isZero()) return false | ||
38254 | |||
38255 | var pair = loadPublicKey(publicKey) | ||
38256 | if (pair === null) throw new Error(messages.EC_PUBLIC_KEY_PARSE_FAIL) | ||
38257 | |||
38258 | return ec.verify(message, sigObj, {x: pair.pub.x, y: pair.pub.y}) | ||
38259 | } | ||
38260 | |||
38261 | exports.recover = function (message, signature, recovery, compressed) { | ||
38262 | var sigObj = {r: signature.slice(0, 32), s: signature.slice(32, 64)} | ||
38263 | |||
38264 | var sigr = new BN(sigObj.r) | ||
38265 | var sigs = new BN(sigObj.s) | ||
38266 | if (sigr.cmp(ecparams.n) >= 0 || sigs.cmp(ecparams.n) >= 0) throw new Error(messages.ECDSA_SIGNATURE_PARSE_FAIL) | ||
38267 | |||
38268 | try { | ||
38269 | if (sigr.isZero() || sigs.isZero()) throw new Error() | ||
38270 | |||
38271 | var point = ec.recoverPubKey(message, sigObj, recovery) | ||
38272 | return Buffer.from(point.encode(true, compressed)) | ||
38273 | } catch (err) { | ||
38274 | throw new Error(messages.ECDSA_RECOVER_FAIL) | ||
38275 | } | ||
38276 | } | ||
38277 | |||
38278 | exports.ecdh = function (publicKey, privateKey) { | ||
38279 | var shared = exports.ecdhUnsafe(publicKey, privateKey, true) | ||
38280 | return createHash('sha256').update(shared).digest() | ||
38281 | } | ||
38282 | |||
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) | ||
38286 | |||
38287 | var scalar = new BN(privateKey) | ||
38288 | if (scalar.cmp(ecparams.n) >= 0 || scalar.isZero()) throw new Error(messages.ECDH_FAIL) | ||
38289 | |||
38290 | return Buffer.from(pair.pub.mul(scalar).encode(true, compressed)) | ||
38291 | } | ||
38292 | |||
38293 | },{"../messages.json":254,"bn.js":75,"create-hash":111,"elliptic":127,"safe-buffer":247}],253:[function(require,module,exports){ | ||
38294 | 'use strict' | ||
38295 | var assert = require('./assert') | ||
38296 | var der = require('./der') | ||
38297 | var messages = require('./messages.json') | ||
38298 | |||
38299 | function initCompressedValue (value, defaultValue) { | ||
38300 | if (value === undefined) return defaultValue | ||
38301 | |||
38302 | assert.isBoolean(value, messages.COMPRESSED_TYPE_INVALID) | ||
38303 | return value | ||
38304 | } | ||
38305 | |||
38306 | module.exports = function (secp256k1) { | ||
38307 | return { | ||
38308 | privateKeyVerify: function (privateKey) { | ||
38309 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38310 | return privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey) | ||
38311 | }, | ||
38312 | |||
38313 | privateKeyExport: function (privateKey, compressed) { | ||
38314 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38315 | assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) | ||
38316 | |||
38317 | compressed = initCompressedValue(compressed, true) | ||
38318 | var publicKey = secp256k1.privateKeyExport(privateKey, compressed) | ||
38319 | |||
38320 | return der.privateKeyExport(privateKey, publicKey, compressed) | ||
38321 | }, | ||
38322 | |||
38323 | privateKeyImport: function (privateKey) { | ||
38324 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38325 | |||
38326 | privateKey = der.privateKeyImport(privateKey) | ||
38327 | if (privateKey && privateKey.length === 32 && secp256k1.privateKeyVerify(privateKey)) return privateKey | ||
38328 | |||
38329 | throw new Error(messages.EC_PRIVATE_KEY_IMPORT_DER_FAIL) | ||
38330 | }, | ||
38331 | |||
38332 | privateKeyNegate: function (privateKey) { | ||
38333 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38334 | assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) | ||
38335 | |||
38336 | return secp256k1.privateKeyNegate(privateKey) | ||
38337 | }, | ||
38338 | |||
38339 | privateKeyModInverse: function (privateKey) { | ||
38340 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38341 | assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) | ||
38342 | |||
38343 | return secp256k1.privateKeyModInverse(privateKey) | ||
38344 | }, | ||
38345 | |||
38346 | privateKeyTweakAdd: function (privateKey, tweak) { | ||
38347 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38348 | assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) | ||
38349 | |||
38350 | assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) | ||
38351 | assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) | ||
38352 | |||
38353 | return secp256k1.privateKeyTweakAdd(privateKey, tweak) | ||
38354 | }, | ||
38355 | |||
38356 | privateKeyTweakMul: function (privateKey, tweak) { | ||
38357 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38358 | assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) | ||
38359 | |||
38360 | assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) | ||
38361 | assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) | ||
38362 | |||
38363 | return secp256k1.privateKeyTweakMul(privateKey, tweak) | ||
38364 | }, | ||
38365 | |||
38366 | publicKeyCreate: function (privateKey, compressed) { | ||
38367 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38368 | assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) | ||
38369 | |||
38370 | compressed = initCompressedValue(compressed, true) | ||
38371 | |||
38372 | return secp256k1.publicKeyCreate(privateKey, compressed) | ||
38373 | }, | ||
38374 | |||
38375 | publicKeyConvert: function (publicKey, compressed) { | ||
38376 | assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) | ||
38377 | assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) | ||
38378 | |||
38379 | compressed = initCompressedValue(compressed, true) | ||
38380 | |||
38381 | return secp256k1.publicKeyConvert(publicKey, compressed) | ||
38382 | }, | ||
38383 | |||
38384 | publicKeyVerify: function (publicKey) { | ||
38385 | assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) | ||
38386 | return secp256k1.publicKeyVerify(publicKey) | ||
38387 | }, | ||
38388 | |||
38389 | publicKeyTweakAdd: function (publicKey, tweak, compressed) { | ||
38390 | assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) | ||
38391 | assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) | ||
38392 | |||
38393 | assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) | ||
38394 | assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) | ||
38395 | |||
38396 | compressed = initCompressedValue(compressed, true) | ||
38397 | |||
38398 | return secp256k1.publicKeyTweakAdd(publicKey, tweak, compressed) | ||
38399 | }, | ||
38400 | |||
38401 | publicKeyTweakMul: function (publicKey, tweak, compressed) { | ||
38402 | assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) | ||
38403 | assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) | ||
38404 | |||
38405 | assert.isBuffer(tweak, messages.TWEAK_TYPE_INVALID) | ||
38406 | assert.isBufferLength(tweak, 32, messages.TWEAK_LENGTH_INVALID) | ||
38407 | |||
38408 | compressed = initCompressedValue(compressed, true) | ||
38409 | |||
38410 | return secp256k1.publicKeyTweakMul(publicKey, tweak, compressed) | ||
38411 | }, | ||
38412 | |||
38413 | publicKeyCombine: function (publicKeys, compressed) { | ||
38414 | assert.isArray(publicKeys, messages.EC_PUBLIC_KEYS_TYPE_INVALID) | ||
38415 | assert.isLengthGTZero(publicKeys, messages.EC_PUBLIC_KEYS_LENGTH_INVALID) | ||
38416 | for (var i = 0; i < publicKeys.length; ++i) { | ||
38417 | assert.isBuffer(publicKeys[i], messages.EC_PUBLIC_KEY_TYPE_INVALID) | ||
38418 | assert.isBufferLength2(publicKeys[i], 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) | ||
38419 | } | ||
38420 | |||
38421 | compressed = initCompressedValue(compressed, true) | ||
38422 | |||
38423 | return secp256k1.publicKeyCombine(publicKeys, compressed) | ||
38424 | }, | ||
38425 | |||
38426 | signatureNormalize: function (signature) { | ||
38427 | assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) | ||
38428 | assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) | ||
38429 | |||
38430 | return secp256k1.signatureNormalize(signature) | ||
38431 | }, | ||
38432 | |||
38433 | signatureExport: function (signature) { | ||
38434 | assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) | ||
38435 | assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) | ||
38436 | |||
38437 | var sigObj = secp256k1.signatureExport(signature) | ||
38438 | return der.signatureExport(sigObj) | ||
38439 | }, | ||
38440 | |||
38441 | signatureImport: function (sig) { | ||
38442 | assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) | ||
38443 | assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) | ||
38444 | |||
38445 | var sigObj = der.signatureImport(sig) | ||
38446 | if (sigObj) return secp256k1.signatureImport(sigObj) | ||
38447 | |||
38448 | throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) | ||
38449 | }, | ||
38450 | |||
38451 | signatureImportLax: function (sig) { | ||
38452 | assert.isBuffer(sig, messages.ECDSA_SIGNATURE_TYPE_INVALID) | ||
38453 | assert.isLengthGTZero(sig, messages.ECDSA_SIGNATURE_LENGTH_INVALID) | ||
38454 | |||
38455 | var sigObj = der.signatureImportLax(sig) | ||
38456 | if (sigObj) return secp256k1.signatureImport(sigObj) | ||
38457 | |||
38458 | throw new Error(messages.ECDSA_SIGNATURE_PARSE_DER_FAIL) | ||
38459 | }, | ||
38460 | |||
38461 | sign: function (message, privateKey, options) { | ||
38462 | assert.isBuffer(message, messages.MSG32_TYPE_INVALID) | ||
38463 | assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) | ||
38464 | |||
38465 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38466 | assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) | ||
38467 | |||
38468 | var data = null | ||
38469 | var noncefn = null | ||
38470 | if (options !== undefined) { | ||
38471 | assert.isObject(options, messages.OPTIONS_TYPE_INVALID) | ||
38472 | |||
38473 | if (options.data !== undefined) { | ||
38474 | assert.isBuffer(options.data, messages.OPTIONS_DATA_TYPE_INVALID) | ||
38475 | assert.isBufferLength(options.data, 32, messages.OPTIONS_DATA_LENGTH_INVALID) | ||
38476 | data = options.data | ||
38477 | } | ||
38478 | |||
38479 | if (options.noncefn !== undefined) { | ||
38480 | assert.isFunction(options.noncefn, messages.OPTIONS_NONCEFN_TYPE_INVALID) | ||
38481 | noncefn = options.noncefn | ||
38482 | } | ||
38483 | } | ||
38484 | |||
38485 | return secp256k1.sign(message, privateKey, noncefn, data) | ||
38486 | }, | ||
38487 | |||
38488 | verify: function (message, signature, publicKey) { | ||
38489 | assert.isBuffer(message, messages.MSG32_TYPE_INVALID) | ||
38490 | assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) | ||
38491 | |||
38492 | assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) | ||
38493 | assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) | ||
38494 | |||
38495 | assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) | ||
38496 | assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) | ||
38497 | |||
38498 | return secp256k1.verify(message, signature, publicKey) | ||
38499 | }, | ||
38500 | |||
38501 | recover: function (message, signature, recovery, compressed) { | ||
38502 | assert.isBuffer(message, messages.MSG32_TYPE_INVALID) | ||
38503 | assert.isBufferLength(message, 32, messages.MSG32_LENGTH_INVALID) | ||
38504 | |||
38505 | assert.isBuffer(signature, messages.ECDSA_SIGNATURE_TYPE_INVALID) | ||
38506 | assert.isBufferLength(signature, 64, messages.ECDSA_SIGNATURE_LENGTH_INVALID) | ||
38507 | |||
38508 | assert.isNumber(recovery, messages.RECOVERY_ID_TYPE_INVALID) | ||
38509 | assert.isNumberInInterval(recovery, -1, 4, messages.RECOVERY_ID_VALUE_INVALID) | ||
38510 | |||
38511 | compressed = initCompressedValue(compressed, true) | ||
38512 | |||
38513 | return secp256k1.recover(message, signature, recovery, compressed) | ||
38514 | }, | ||
38515 | |||
38516 | ecdh: function (publicKey, privateKey) { | ||
38517 | assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) | ||
38518 | assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) | ||
38519 | |||
38520 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38521 | assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) | ||
38522 | |||
38523 | return secp256k1.ecdh(publicKey, privateKey) | ||
38524 | }, | ||
38525 | |||
38526 | ecdhUnsafe: function (publicKey, privateKey, compressed) { | ||
38527 | assert.isBuffer(publicKey, messages.EC_PUBLIC_KEY_TYPE_INVALID) | ||
38528 | assert.isBufferLength2(publicKey, 33, 65, messages.EC_PUBLIC_KEY_LENGTH_INVALID) | ||
38529 | |||
38530 | assert.isBuffer(privateKey, messages.EC_PRIVATE_KEY_TYPE_INVALID) | ||
38531 | assert.isBufferLength(privateKey, 32, messages.EC_PRIVATE_KEY_LENGTH_INVALID) | ||
38532 | |||
38533 | compressed = initCompressedValue(compressed, true) | ||
38534 | |||
38535 | return secp256k1.ecdhUnsafe(publicKey, privateKey, compressed) | ||
38536 | } | ||
38537 | } | ||
38538 | } | ||
38539 | |||
38540 | },{"./assert":250,"./der":251,"./messages.json":254}],254:[function(require,module,exports){ | ||
38541 | 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" | ||
38577 | } | ||
38578 | |||
38579 | },{}],255:[function(require,module,exports){ | ||
38580 | var Buffer = require('safe-buffer').Buffer | ||
38581 | |||
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 | ||
38587 | this._len = 0 | ||
38588 | } | ||
38589 | |||
38590 | Hash.prototype.update = function (data, enc) { | ||
38591 | if (typeof data === 'string') { | ||
38592 | enc = enc || 'utf8' | ||
38593 | data = Buffer.from(data, enc) | ||
38594 | } | ||
38595 | |||
38596 | var block = this._block | ||
38597 | var blockSize = this._blockSize | ||
38598 | var length = data.length | ||
38599 | var accum = this._len | ||
38600 | |||
38601 | for (var offset = 0; offset < length;) { | ||
38602 | var assigned = accum % blockSize | ||
38603 | var remainder = Math.min(length - offset, blockSize - assigned) | ||
38604 | |||
38605 | for (var i = 0; i < remainder; i++) { | ||
38606 | block[assigned + i] = data[offset + i] | ||
38607 | } | ||
38608 | |||
38609 | accum += remainder | ||
38610 | offset += remainder | ||
38611 | |||
38612 | if ((accum % blockSize) === 0) { | ||
38613 | this._update(block) | ||
38614 | } | ||
38615 | } | ||
38616 | |||
38617 | this._len += length | ||
38618 | return this | ||
38619 | } | ||
38620 | |||
38621 | Hash.prototype.digest = function (enc) { | ||
38622 | var rem = this._len % this._blockSize | ||
38623 | |||
38624 | this._block[rem] = 0x80 | ||
38625 | |||
38626 | // zero (rem + 1) trailing bits, where (rem + 1) is the smallest | ||
38627 | // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize | ||
38628 | this._block.fill(0, rem + 1) | ||
38629 | |||
38630 | if (rem >= this._finalSize) { | ||
38631 | this._update(this._block) | ||
38632 | this._block.fill(0) | ||
38633 | } | ||
38634 | |||
38635 | var bits = this._len * 8 | ||
38636 | |||
38637 | // uint32 | ||
38638 | if (bits <= 0xffffffff) { | ||
38639 | this._block.writeUInt32BE(bits, this._blockSize - 4) | ||
38640 | |||
38641 | // uint64 | ||
38642 | } else { | ||
38643 | var lowBits = bits & 0xffffffff | ||
38644 | var highBits = (bits - lowBits) / 0x100000000 | ||
38645 | |||
38646 | this._block.writeUInt32BE(highBits, this._blockSize - 8) | ||
38647 | this._block.writeUInt32BE(lowBits, this._blockSize - 4) | ||
38648 | } | ||
38649 | |||
38650 | this._update(this._block) | ||
38651 | var hash = this._hash() | ||
38652 | |||
38653 | return enc ? hash.toString(enc) : hash | ||
38654 | } | ||
38655 | |||
38656 | Hash.prototype._update = function () { | ||
38657 | throw new Error('_update must be implemented by subclass') | ||
38658 | } | ||
38659 | |||
38660 | module.exports = Hash | ||
38661 | |||
38662 | },{"safe-buffer":247}],256:[function(require,module,exports){ | ||
38663 | var exports = module.exports = function SHA (algorithm) { | ||
38664 | algorithm = algorithm.toLowerCase() | ||
38665 | |||
38666 | var Algorithm = exports[algorithm] | ||
38667 | if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') | ||
38668 | |||
38669 | return new Algorithm() | ||
38670 | } | ||
38671 | |||
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') | ||
38678 | |||
38679 | },{"./sha":257,"./sha1":258,"./sha224":259,"./sha256":260,"./sha384":261,"./sha512":262}],257:[function(require,module,exports){ | ||
38680 | /* | ||
38681 | * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined | ||
38682 | * in FIPS PUB 180-1 | ||
38683 | * This source code is derived from sha1.js of the same repository. | ||
38684 | * The difference between SHA-0 and SHA-1 is just a bitwise rotate left | ||
38685 | * operation was added. | ||
38686 | */ | ||
38687 | |||
38688 | var inherits = require('inherits') | ||
38689 | var Hash = require('./hash') | ||
38690 | var Buffer = require('safe-buffer').Buffer | ||
38691 | |||
38692 | var K = [ | ||
38693 | 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 | ||
38694 | ] | ||
38695 | |||
38696 | var W = new Array(80) | ||
38697 | |||
38698 | function Sha () { | ||
38699 | this.init() | ||
38700 | this._w = W | ||
38701 | |||
38702 | Hash.call(this, 64, 56) | ||
38703 | } | ||
38704 | |||
38705 | inherits(Sha, Hash) | ||
38706 | |||
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 | ||
38713 | |||
38714 | return this | ||
38715 | } | ||
38716 | |||
38717 | function rotl5 (num) { | ||
38718 | return (num << 5) | (num >>> 27) | ||
38719 | } | ||
38720 | |||
38721 | function rotl30 (num) { | ||
38722 | return (num << 30) | (num >>> 2) | ||
38723 | } | ||
38724 | |||
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) | ||
38728 | return b ^ c ^ d | ||
38729 | } | ||
38730 | |||
38731 | Sha.prototype._update = function (M) { | ||
38732 | var W = this._w | ||
38733 | |||
38734 | var a = this._a | 0 | ||
38735 | var b = this._b | 0 | ||
38736 | var c = this._c | 0 | ||
38737 | var d = this._d | 0 | ||
38738 | var e = this._e | 0 | ||
38739 | |||
38740 | for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) | ||
38741 | for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] | ||
38742 | |||
38743 | for (var j = 0; j < 80; ++j) { | ||
38744 | var s = ~~(j / 20) | ||
38745 | var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 | ||
38746 | |||
38747 | e = d | ||
38748 | d = c | ||
38749 | c = rotl30(b) | ||
38750 | b = a | ||
38751 | a = t | ||
38752 | } | ||
38753 | |||
38754 | this._a = (a + this._a) | 0 | ||
38755 | this._b = (b + this._b) | 0 | ||
38756 | this._c = (c + this._c) | 0 | ||
38757 | this._d = (d + this._d) | 0 | ||
38758 | this._e = (e + this._e) | 0 | ||
38759 | } | ||
38760 | |||
38761 | Sha.prototype._hash = function () { | ||
38762 | var H = Buffer.allocUnsafe(20) | ||
38763 | |||
38764 | H.writeInt32BE(this._a | 0, 0) | ||
38765 | H.writeInt32BE(this._b | 0, 4) | ||
38766 | H.writeInt32BE(this._c | 0, 8) | ||
38767 | H.writeInt32BE(this._d | 0, 12) | ||
38768 | H.writeInt32BE(this._e | 0, 16) | ||
38769 | |||
38770 | return H | ||
38771 | } | ||
38772 | |||
38773 | module.exports = Sha | ||
38774 | |||
38775 | },{"./hash":255,"inherits":163,"safe-buffer":247}],258:[function(require,module,exports){ | ||
38776 | /* | ||
38777 | * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined | ||
38778 | * in FIPS PUB 180-1 | ||
38779 | * Version 2.1a Copyright Paul Johnston 2000 - 2002. | ||
38780 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet | ||
38781 | * Distributed under the BSD License | ||
38782 | * See http://pajhome.org.uk/crypt/md5 for details. | ||
38783 | */ | ||
38784 | |||
38785 | var inherits = require('inherits') | ||
38786 | var Hash = require('./hash') | ||
38787 | var Buffer = require('safe-buffer').Buffer | ||
38788 | |||
38789 | var K = [ | ||
38790 | 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 | ||
38791 | ] | ||
38792 | |||
38793 | var W = new Array(80) | ||
38794 | |||
38795 | function Sha1 () { | ||
38796 | this.init() | ||
38797 | this._w = W | ||
38798 | |||
38799 | Hash.call(this, 64, 56) | ||
38800 | } | ||
38801 | |||
38802 | inherits(Sha1, Hash) | ||
38803 | |||
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 | ||
38810 | |||
38811 | return this | ||
38812 | } | ||
38813 | |||
38814 | function rotl1 (num) { | ||
38815 | return (num << 1) | (num >>> 31) | ||
38816 | } | ||
38817 | |||
38818 | function rotl5 (num) { | ||
38819 | return (num << 5) | (num >>> 27) | ||
38820 | } | ||
38821 | |||
38822 | function rotl30 (num) { | ||
38823 | return (num << 30) | (num >>> 2) | ||
38824 | } | ||
38825 | |||
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) | ||
38829 | return b ^ c ^ d | ||
38830 | } | ||
38831 | |||
38832 | Sha1.prototype._update = function (M) { | ||
38833 | var W = this._w | ||
38834 | |||
38835 | var a = this._a | 0 | ||
38836 | var b = this._b | 0 | ||
38837 | var c = this._c | 0 | ||
38838 | var d = this._d | 0 | ||
38839 | var e = this._e | 0 | ||
38840 | |||
38841 | for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) | ||
38842 | for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) | ||
38843 | |||
38844 | for (var j = 0; j < 80; ++j) { | ||
38845 | var s = ~~(j / 20) | ||
38846 | var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 | ||
38847 | |||
38848 | e = d | ||
38849 | d = c | ||
38850 | c = rotl30(b) | ||
38851 | b = a | ||
38852 | a = t | ||
38853 | } | ||
38854 | |||
38855 | this._a = (a + this._a) | 0 | ||
38856 | this._b = (b + this._b) | 0 | ||
38857 | this._c = (c + this._c) | 0 | ||
38858 | this._d = (d + this._d) | 0 | ||
38859 | this._e = (e + this._e) | 0 | ||
38860 | } | ||
38861 | |||
38862 | Sha1.prototype._hash = function () { | ||
38863 | var H = Buffer.allocUnsafe(20) | ||
38864 | |||
38865 | H.writeInt32BE(this._a | 0, 0) | ||
38866 | H.writeInt32BE(this._b | 0, 4) | ||
38867 | H.writeInt32BE(this._c | 0, 8) | ||
38868 | H.writeInt32BE(this._d | 0, 12) | ||
38869 | H.writeInt32BE(this._e | 0, 16) | ||
38870 | |||
38871 | return H | ||
38872 | } | ||
38873 | |||
38874 | module.exports = Sha1 | ||
38875 | |||
38876 | },{"./hash":255,"inherits":163,"safe-buffer":247}],259:[function(require,module,exports){ | ||
38877 | /** | ||
38878 | * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined | ||
38879 | * in FIPS 180-2 | ||
38880 | * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. | ||
38881 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet | ||
38882 | * | ||
38883 | */ | ||
38884 | |||
38885 | var inherits = require('inherits') | ||
38886 | var Sha256 = require('./sha256') | ||
38887 | var Hash = require('./hash') | ||
38888 | var Buffer = require('safe-buffer').Buffer | ||
38889 | |||
38890 | var W = new Array(64) | ||
38891 | |||
38892 | function Sha224 () { | ||
38893 | this.init() | ||
38894 | |||
38895 | this._w = W // new Array(64) | ||
38896 | |||
38897 | Hash.call(this, 64, 56) | ||
38898 | } | ||
38899 | |||
38900 | inherits(Sha224, Sha256) | ||
38901 | |||
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 | ||
38911 | |||
38912 | return this | ||
38913 | } | ||
38914 | |||
38915 | Sha224.prototype._hash = function () { | ||
38916 | var H = Buffer.allocUnsafe(28) | ||
38917 | |||
38918 | H.writeInt32BE(this._a, 0) | ||
38919 | H.writeInt32BE(this._b, 4) | ||
38920 | H.writeInt32BE(this._c, 8) | ||
38921 | H.writeInt32BE(this._d, 12) | ||
38922 | H.writeInt32BE(this._e, 16) | ||
38923 | H.writeInt32BE(this._f, 20) | ||
38924 | H.writeInt32BE(this._g, 24) | ||
38925 | |||
38926 | return H | ||
38927 | } | ||
38928 | |||
38929 | module.exports = Sha224 | ||
38930 | |||
38931 | },{"./hash":255,"./sha256":260,"inherits":163,"safe-buffer":247}],260:[function(require,module,exports){ | ||
38932 | /** | ||
38933 | * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined | ||
38934 | * in FIPS 180-2 | ||
38935 | * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. | ||
38936 | * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet | ||
38937 | * | ||
38938 | */ | ||
38939 | |||
38940 | var inherits = require('inherits') | ||
38941 | var Hash = require('./hash') | ||
38942 | var Buffer = require('safe-buffer').Buffer | ||
38943 | |||
38944 | var K = [ | ||
38945 | 0x428A2F98, 0x71374491, 0xB5C0FBCF, 0xE9B5DBA5, | ||
38946 | 0x3956C25B, 0x59F111F1, 0x923F82A4, 0xAB1C5ED5, | ||
38947 | 0xD807AA98, 0x12835B01, 0x243185BE, 0x550C7DC3, | ||
38948 | 0x72BE5D74, 0x80DEB1FE, 0x9BDC06A7, 0xC19BF174, | ||
38949 | 0xE49B69C1, 0xEFBE4786, 0x0FC19DC6, 0x240CA1CC, | ||
38950 | 0x2DE92C6F, 0x4A7484AA, 0x5CB0A9DC, 0x76F988DA, | ||
38951 | 0x983E5152, 0xA831C66D, 0xB00327C8, 0xBF597FC7, | ||
38952 | 0xC6E00BF3, 0xD5A79147, 0x06CA6351, 0x14292967, | ||
38953 | 0x27B70A85, 0x2E1B2138, 0x4D2C6DFC, 0x53380D13, | ||
38954 | 0x650A7354, 0x766A0ABB, 0x81C2C92E, 0x92722C85, | ||
38955 | 0xA2BFE8A1, 0xA81A664B, 0xC24B8B70, 0xC76C51A3, | ||
38956 | 0xD192E819, 0xD6990624, 0xF40E3585, 0x106AA070, | ||
38957 | 0x19A4C116, 0x1E376C08, 0x2748774C, 0x34B0BCB5, | ||
38958 | 0x391C0CB3, 0x4ED8AA4A, 0x5B9CCA4F, 0x682E6FF3, | ||
38959 | 0x748F82EE, 0x78A5636F, 0x84C87814, 0x8CC70208, | ||
38960 | 0x90BEFFFA, 0xA4506CEB, 0xBEF9A3F7, 0xC67178F2 | ||
38961 | ] | ||
38962 | |||
38963 | var W = new Array(64) | ||
38964 | |||
38965 | function Sha256 () { | ||
38966 | this.init() | ||
38967 | |||
38968 | this._w = W // new Array(64) | ||
38969 | |||
38970 | Hash.call(this, 64, 56) | ||
38971 | } | ||
38972 | |||
38973 | inherits(Sha256, Hash) | ||
38974 | |||
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 | ||
38984 | |||
38985 | return this | ||
38986 | } | ||
38987 | |||
38988 | function ch (x, y, z) { | ||
38989 | return z ^ (x & (y ^ z)) | ||
38990 | } | ||
38991 | |||
38992 | function maj (x, y, z) { | ||
38993 | return (x & y) | (z & (x | y)) | ||
38994 | } | ||
38995 | |||
38996 | function sigma0 (x) { | ||
38997 | return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) | ||
38998 | } | ||
38999 | |||
39000 | function sigma1 (x) { | ||
39001 | return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) | ||
39002 | } | ||
39003 | |||
39004 | function gamma0 (x) { | ||
39005 | return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) | ||
39006 | } | ||
39007 | |||
39008 | function gamma1 (x) { | ||
39009 | return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) | ||
39010 | } | ||
39011 | |||
39012 | Sha256.prototype._update = function (M) { | ||
39013 | var W = this._w | ||
39014 | |||
39015 | var a = this._a | 0 | ||
39016 | var b = this._b | 0 | ||
39017 | var c = this._c | 0 | ||
39018 | var d = this._d | 0 | ||
39019 | var e = this._e | 0 | ||
39020 | var f = this._f | 0 | ||
39021 | var g = this._g | 0 | ||
39022 | var h = this._h | 0 | ||
39023 | |||
39024 | for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) | ||
39025 | for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 | ||
39026 | |||
39027 | for (var j = 0; j < 64; ++j) { | ||
39028 | var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 | ||
39029 | var T2 = (sigma0(a) + maj(a, b, c)) | 0 | ||
39030 | |||
39031 | h = g | ||
39032 | g = f | ||
39033 | f = e | ||
39034 | e = (d + T1) | 0 | ||
39035 | d = c | ||
39036 | c = b | ||
39037 | b = a | ||
39038 | a = (T1 + T2) | 0 | ||
39039 | } | ||
39040 | |||
39041 | this._a = (a + this._a) | 0 | ||
39042 | this._b = (b + this._b) | 0 | ||
39043 | this._c = (c + this._c) | 0 | ||
39044 | this._d = (d + this._d) | 0 | ||
39045 | this._e = (e + this._e) | 0 | ||
39046 | this._f = (f + this._f) | 0 | ||
39047 | this._g = (g + this._g) | 0 | ||
39048 | this._h = (h + this._h) | 0 | ||
39049 | } | ||
39050 | |||
39051 | Sha256.prototype._hash = function () { | ||
39052 | var H = Buffer.allocUnsafe(32) | ||
39053 | |||
39054 | H.writeInt32BE(this._a, 0) | ||
39055 | H.writeInt32BE(this._b, 4) | ||
39056 | H.writeInt32BE(this._c, 8) | ||
39057 | H.writeInt32BE(this._d, 12) | ||
39058 | H.writeInt32BE(this._e, 16) | ||
39059 | H.writeInt32BE(this._f, 20) | ||
39060 | H.writeInt32BE(this._g, 24) | ||
39061 | H.writeInt32BE(this._h, 28) | ||
39062 | |||
39063 | return H | ||
39064 | } | ||
39065 | |||
39066 | module.exports = Sha256 | ||
39067 | |||
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 | ||
39073 | |||
39074 | var W = new Array(160) | ||
39075 | |||
39076 | function Sha384 () { | ||
39077 | this.init() | ||
39078 | this._w = W | ||
39079 | |||
39080 | Hash.call(this, 128, 112) | ||
39081 | } | ||
39082 | |||
39083 | inherits(Sha384, SHA512) | ||
39084 | |||
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 | ||
39094 | |||
39095 | this._al = 0xc1059ed8 | ||
39096 | this._bl = 0x367cd507 | ||
39097 | this._cl = 0x3070dd17 | ||
39098 | this._dl = 0xf70e5939 | ||
39099 | this._el = 0xffc00b31 | ||
39100 | this._fl = 0x68581511 | ||
39101 | this._gl = 0x64f98fa7 | ||
39102 | this._hl = 0xbefa4fa4 | ||
39103 | |||
39104 | return this | ||
39105 | } | ||
39106 | |||
39107 | Sha384.prototype._hash = function () { | ||
39108 | var H = Buffer.allocUnsafe(48) | ||
39109 | |||
39110 | function writeInt64BE (h, l, offset) { | ||
39111 | H.writeInt32BE(h, offset) | ||
39112 | H.writeInt32BE(l, offset + 4) | ||
39113 | } | ||
39114 | |||
39115 | writeInt64BE(this._ah, this._al, 0) | ||
39116 | writeInt64BE(this._bh, this._bl, 8) | ||
39117 | writeInt64BE(this._ch, this._cl, 16) | ||
39118 | writeInt64BE(this._dh, this._dl, 24) | ||
39119 | writeInt64BE(this._eh, this._el, 32) | ||
39120 | writeInt64BE(this._fh, this._fl, 40) | ||
39121 | |||
39122 | return H | ||
39123 | } | ||
39124 | |||
39125 | module.exports = Sha384 | ||
39126 | |||
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 | ||
39131 | |||
39132 | var K = [ | ||
39133 | 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, | ||
39134 | 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, | ||
39135 | 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, | ||
39136 | 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, | ||
39137 | 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, | ||
39138 | 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, | ||
39139 | 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, | ||
39140 | 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, | ||
39141 | 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, | ||
39142 | 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, | ||
39143 | 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, | ||
39144 | 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, | ||
39145 | 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, | ||
39146 | 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, | ||
39147 | 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, | ||
39148 | 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, | ||
39149 | 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, | ||
39150 | 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, | ||
39151 | 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, | ||
39152 | 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, | ||
39153 | 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, | ||
39154 | 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, | ||
39155 | 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, | ||
39156 | 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, | ||
39157 | 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, | ||
39158 | 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, | ||
39159 | 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, | ||
39160 | 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, | ||
39161 | 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, | ||
39162 | 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, | ||
39163 | 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, | ||
39164 | 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, | ||
39165 | 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, | ||
39166 | 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, | ||
39167 | 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, | ||
39168 | 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, | ||
39169 | 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, | ||
39170 | 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, | ||
39171 | 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, | ||
39172 | 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 | ||
39173 | ] | ||
39174 | |||
39175 | var W = new Array(160) | ||
39176 | |||
39177 | function Sha512 () { | ||
39178 | this.init() | ||
39179 | this._w = W | ||
39180 | |||
39181 | Hash.call(this, 128, 112) | ||
39182 | } | ||
39183 | |||
39184 | inherits(Sha512, Hash) | ||
39185 | |||
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 | ||
39195 | |||
39196 | this._al = 0xf3bcc908 | ||
39197 | this._bl = 0x84caa73b | ||
39198 | this._cl = 0xfe94f82b | ||
39199 | this._dl = 0x5f1d36f1 | ||
39200 | this._el = 0xade682d1 | ||
39201 | this._fl = 0x2b3e6c1f | ||
39202 | this._gl = 0xfb41bd6b | ||
39203 | this._hl = 0x137e2179 | ||
39204 | |||
39205 | return this | ||
39206 | } | ||
39207 | |||
39208 | function Ch (x, y, z) { | ||
39209 | return z ^ (x & (y ^ z)) | ||
39210 | } | ||
39211 | |||
39212 | function maj (x, y, z) { | ||
39213 | return (x & y) | (z & (x | y)) | ||
39214 | } | ||
39215 | |||
39216 | function sigma0 (x, xl) { | ||
39217 | return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) | ||
39218 | } | ||
39219 | |||
39220 | function sigma1 (x, xl) { | ||
39221 | return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) | ||
39222 | } | ||
39223 | |||
39224 | function Gamma0 (x, xl) { | ||
39225 | return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) | ||
39226 | } | ||
39227 | |||
39228 | function Gamma0l (x, xl) { | ||
39229 | return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) | ||
39230 | } | ||
39231 | |||
39232 | function Gamma1 (x, xl) { | ||
39233 | return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) | ||
39234 | } | ||
39235 | |||
39236 | function Gamma1l (x, xl) { | ||
39237 | return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) | ||
39238 | } | ||
39239 | |||
39240 | function getCarry (a, b) { | ||
39241 | return (a >>> 0) < (b >>> 0) ? 1 : 0 | ||
39242 | } | ||
39243 | |||
39244 | Sha512.prototype._update = function (M) { | ||
39245 | var W = this._w | ||
39246 | |||
39247 | var ah = this._ah | 0 | ||
39248 | var bh = this._bh | 0 | ||
39249 | var ch = this._ch | 0 | ||
39250 | var dh = this._dh | 0 | ||
39251 | var eh = this._eh | 0 | ||
39252 | var fh = this._fh | 0 | ||
39253 | var gh = this._gh | 0 | ||
39254 | var hh = this._hh | 0 | ||
39255 | |||
39256 | var al = this._al | 0 | ||
39257 | var bl = this._bl | 0 | ||
39258 | var cl = this._cl | 0 | ||
39259 | var dl = this._dl | 0 | ||
39260 | var el = this._el | 0 | ||
39261 | var fl = this._fl | 0 | ||
39262 | var gl = this._gl | 0 | ||
39263 | var hl = this._hl | 0 | ||
39264 | |||
39265 | for (var i = 0; i < 32; i += 2) { | ||
39266 | W[i] = M.readInt32BE(i * 4) | ||
39267 | W[i + 1] = M.readInt32BE(i * 4 + 4) | ||
39268 | } | ||
39269 | for (; i < 160; i += 2) { | ||
39270 | var xh = W[i - 15 * 2] | ||
39271 | var xl = W[i - 15 * 2 + 1] | ||
39272 | var gamma0 = Gamma0(xh, xl) | ||
39273 | var gamma0l = Gamma0l(xl, xh) | ||
39274 | |||
39275 | xh = W[i - 2 * 2] | ||
39276 | xl = W[i - 2 * 2 + 1] | ||
39277 | var gamma1 = Gamma1(xh, xl) | ||
39278 | var gamma1l = Gamma1l(xl, xh) | ||
39279 | |||
39280 | // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] | ||
39281 | var Wi7h = W[i - 7 * 2] | ||
39282 | var Wi7l = W[i - 7 * 2 + 1] | ||
39283 | |||
39284 | var Wi16h = W[i - 16 * 2] | ||
39285 | var Wi16l = W[i - 16 * 2 + 1] | ||
39286 | |||
39287 | var Wil = (gamma0l + Wi7l) | 0 | ||
39288 | var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 | ||
39289 | Wil = (Wil + gamma1l) | 0 | ||
39290 | Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 | ||
39291 | Wil = (Wil + Wi16l) | 0 | ||
39292 | Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 | ||
39293 | |||
39294 | W[i] = Wih | ||
39295 | W[i + 1] = Wil | ||
39296 | } | ||
39297 | |||
39298 | for (var j = 0; j < 160; j += 2) { | ||
39299 | Wih = W[j] | ||
39300 | Wil = W[j + 1] | ||
39301 | |||
39302 | var majh = maj(ah, bh, ch) | ||
39303 | var majl = maj(al, bl, cl) | ||
39304 | |||
39305 | var sigma0h = sigma0(ah, al) | ||
39306 | var sigma0l = sigma0(al, ah) | ||
39307 | var sigma1h = sigma1(eh, el) | ||
39308 | var sigma1l = sigma1(el, eh) | ||
39309 | |||
39310 | // t1 = h + sigma1 + ch + K[j] + W[j] | ||
39311 | var Kih = K[j] | ||
39312 | var Kil = K[j + 1] | ||
39313 | |||
39314 | var chh = Ch(eh, fh, gh) | ||
39315 | var chl = Ch(el, fl, gl) | ||
39316 | |||
39317 | var t1l = (hl + sigma1l) | 0 | ||
39318 | var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 | ||
39319 | t1l = (t1l + chl) | 0 | ||
39320 | t1h = (t1h + chh + getCarry(t1l, chl)) | 0 | ||
39321 | t1l = (t1l + Kil) | 0 | ||
39322 | t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 | ||
39323 | t1l = (t1l + Wil) | 0 | ||
39324 | t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 | ||
39325 | |||
39326 | // t2 = sigma0 + maj | ||
39327 | var t2l = (sigma0l + majl) | 0 | ||
39328 | var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 | ||
39329 | |||
39330 | hh = gh | ||
39331 | hl = gl | ||
39332 | gh = fh | ||
39333 | gl = fl | ||
39334 | fh = eh | ||
39335 | fl = el | ||
39336 | el = (dl + t1l) | 0 | ||
39337 | eh = (dh + t1h + getCarry(el, dl)) | 0 | ||
39338 | dh = ch | ||
39339 | dl = cl | ||
39340 | ch = bh | ||
39341 | cl = bl | ||
39342 | bh = ah | ||
39343 | bl = al | ||
39344 | al = (t1l + t2l) | 0 | ||
39345 | ah = (t1h + t2h + getCarry(al, t1l)) | 0 | ||
39346 | } | ||
39347 | |||
39348 | this._al = (this._al + al) | 0 | ||
39349 | this._bl = (this._bl + bl) | 0 | ||
39350 | this._cl = (this._cl + cl) | 0 | ||
39351 | this._dl = (this._dl + dl) | 0 | ||
39352 | this._el = (this._el + el) | 0 | ||
39353 | this._fl = (this._fl + fl) | 0 | ||
39354 | this._gl = (this._gl + gl) | 0 | ||
39355 | this._hl = (this._hl + hl) | 0 | ||
39356 | |||
39357 | this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 | ||
39358 | this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 | ||
39359 | this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 | ||
39360 | this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 | ||
39361 | this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 | ||
39362 | this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 | ||
39363 | this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 | ||
39364 | this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 | ||
39365 | } | ||
39366 | |||
39367 | Sha512.prototype._hash = function () { | ||
39368 | var H = Buffer.allocUnsafe(64) | ||
39369 | |||
39370 | function writeInt64BE (h, l, offset) { | ||
39371 | H.writeInt32BE(h, offset) | ||
39372 | H.writeInt32BE(l, offset + 4) | ||
39373 | } | ||
39374 | |||
39375 | writeInt64BE(this._ah, this._al, 0) | ||
39376 | writeInt64BE(this._bh, this._bl, 8) | ||
39377 | writeInt64BE(this._ch, this._cl, 16) | ||
39378 | writeInt64BE(this._dh, this._dl, 24) | ||
39379 | writeInt64BE(this._eh, this._el, 32) | ||
39380 | writeInt64BE(this._fh, this._fl, 40) | ||
39381 | writeInt64BE(this._gh, this._gl, 48) | ||
39382 | writeInt64BE(this._hh, this._hl, 56) | ||
39383 | |||
39384 | return H | ||
39385 | } | ||
39386 | |||
39387 | module.exports = Sha512 | ||
39388 | |||
39389 | },{"./hash":255,"inherits":163,"safe-buffer":247}],263:[function(require,module,exports){ | ||
39390 | // Copyright Joyent, Inc. and other Node contributors. | ||
39391 | // | ||
39392 | // Permission is hereby granted, free of charge, to any person obtaining a | ||
39393 | // copy of this software and associated documentation files (the | ||
39394 | // "Software"), to deal in the Software without restriction, including | ||
39395 | // without limitation the rights to use, copy, modify, merge, publish, | ||
39396 | // distribute, sublicense, and/or sell copies of the Software, and to permit | ||
39397 | // persons to whom the Software is furnished to do so, subject to the | ||
39398 | // following conditions: | ||
39399 | // | ||
39400 | // The above copyright notice and this permission notice shall be included | ||
39401 | // in all copies or substantial portions of the Software. | ||
39402 | // | ||
39403 | // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS | ||
39404 | // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF | ||
39405 | // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN | ||
39406 | // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, | ||
39407 | // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR | ||
39408 | // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE | ||
39409 | // USE OR OTHER DEALINGS IN THE SOFTWARE. | ||
39410 | |||
39411 | module.exports = Stream; | ||
39412 | |||
39413 | var EE = require('events').EventEmitter; | ||
39414 | var inherits = require('inherits'); | ||
39415 | |||
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'); | ||
39422 | |||
39423 | // Backwards-compat with node 0.4.x | ||
39424 | Stream.Stream = Stream; | ||
39425 | |||
39426 | |||
39427 | |||
39428 | // old-style streams. Note that the pipe method (the only relevant | ||
39429 | // part of this class) is overridden in the Readable class. | ||
39430 | |||
39431 | function Stream() { | ||
39432 | EE.call(this); | ||
39433 | } | ||
39434 | |||
39435 | Stream.prototype.pipe = function(dest, options) { | ||
39436 | var source = this; | ||
39437 | |||
39438 | function ondata(chunk) { | ||
39439 | if (dest.writable) { | ||
39440 | if (false === dest.write(chunk) && source.pause) { | ||
39441 | source.pause(); | ||
39442 | } | ||
39443 | } | ||
39444 | } | ||
39445 | |||
39446 | source.on('data', ondata); | ||
39447 | |||
39448 | function ondrain() { | ||
39449 | if (source.readable && source.resume) { | ||
39450 | source.resume(); | ||
39451 | } | ||
39452 | } | ||
39453 | |||
39454 | dest.on('drain', ondrain); | ||
39455 | |||
39456 | // If the 'end' option is not supplied, dest.end() will be called when | ||
39457 | // source gets the 'end' or 'close' events. Only dest.end() once. | ||
39458 | if (!dest._isStdio && (!options || options.end !== false)) { | ||
39459 | source.on('end', onend); | ||
39460 | source.on('close', onclose); | ||
39461 | } | ||
39462 | |||
39463 | var didOnEnd = false; | ||
39464 | function onend() { | ||
39465 | if (didOnEnd) return; | ||
39466 | didOnEnd = true; | ||
39467 | |||
39468 | dest.end(); | ||
39469 | } | ||
39470 | |||
39471 | |||
39472 | function onclose() { | ||
39473 | if (didOnEnd) return; | ||
39474 | didOnEnd = true; | ||
39475 | |||
39476 | if (typeof dest.destroy === 'function') dest.destroy(); | ||
39477 | } | ||
39478 | |||
39479 | // don't leave dangling pipes when there are errors. | ||
39480 | function onerror(er) { | ||
39481 | cleanup(); | ||
39482 | if (EE.listenerCount(this, 'error') === 0) { | ||
39483 | throw er; // Unhandled stream error in pipe. | ||
39484 | } | ||
39485 | } | ||
39486 | |||
39487 | source.on('error', onerror); | ||
39488 | dest.on('error', onerror); | ||
39489 | |||
39490 | // remove all the event listeners that were added. | ||
39491 | function cleanup() { | ||
39492 | source.removeListener('data', ondata); | ||
39493 | dest.removeListener('drain', ondrain); | ||
39494 | |||
39495 | source.removeListener('end', onend); | ||
39496 | source.removeListener('close', onclose); | ||
39497 | |||
39498 | source.removeListener('error', onerror); | ||
39499 | dest.removeListener('error', onerror); | ||
39500 | |||
39501 | source.removeListener('end', cleanup); | ||
39502 | source.removeListener('close', cleanup); | ||
39503 | |||
39504 | dest.removeListener('close', cleanup); | ||
39505 | } | ||
39506 | |||
39507 | source.on('end', cleanup); | ||
39508 | source.on('close', cleanup); | ||
39509 | |||
39510 | dest.on('close', cleanup); | ||
39511 | |||
39512 | dest.emit('pipe', source); | ||
39513 | |||
39514 | // Allow for unix-like usage: A.pipe(B).pipe(C) | ||
39515 | return dest; | ||
39516 | }; | ||
39517 | |||
39518 | },{"events":143,"inherits":163,"readable-stream/duplex.js":233,"readable-stream/passthrough.js":242,"readable-stream/readable.js":243,"readable-stream/transform.js":244,"readable-stream/writable.js":245}],264:[function(require,module,exports){ | ||
39519 | 'use strict'; | ||
39520 | |||
39521 | var Buffer = require('safe-buffer').Buffer; | ||
39522 | |||
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': | ||
39527 | return true; | ||
39528 | default: | ||
39529 | return false; | ||
39530 | } | ||
39531 | }; | ||
39532 | |||
39533 | function _normalizeEncoding(enc) { | ||
39534 | if (!enc) return 'utf8'; | ||
39535 | var retried; | ||
39536 | while (true) { | ||
39537 | switch (enc) { | ||
39538 | case 'utf8': | ||
39539 | case 'utf-8': | ||
39540 | return 'utf8'; | ||
39541 | case 'ucs2': | ||
39542 | case 'ucs-2': | ||
39543 | case 'utf16le': | ||
39544 | case 'utf-16le': | ||
39545 | return 'utf16le'; | ||
39546 | case 'latin1': | ||
39547 | case 'binary': | ||
39548 | return 'latin1'; | ||
39549 | case 'base64': | ||
39550 | case 'ascii': | ||
39551 | case 'hex': | ||
39552 | return enc; | ||
39553 | default: | ||
39554 | if (retried) return; // undefined | ||
39555 | enc = ('' + enc).toLowerCase(); | ||
39556 | retried = true; | ||
39557 | } | ||
39558 | } | ||
39559 | }; | ||
39560 | |||
39561 | // Do not cache `Buffer.isEncoding` when checking encoding names as some | ||
39562 | // modules monkey-patch it to support additional encodings | ||
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; | ||
39567 | } | ||
39568 | |||
39569 | // StringDecoder provides an interface for efficiently splitting a series of | ||
39570 | // buffers into a series of JS strings without breaking apart multi-byte | ||
39571 | // characters. | ||
39572 | exports.StringDecoder = StringDecoder; | ||
39573 | function StringDecoder(encoding) { | ||
39574 | this.encoding = normalizeEncoding(encoding); | ||
39575 | var nb; | ||
39576 | switch (this.encoding) { | ||
39577 | case 'utf16le': | ||
39578 | this.text = utf16Text; | ||
39579 | this.end = utf16End; | ||
39580 | nb = 4; | ||
39581 | break; | ||
39582 | case 'utf8': | ||
39583 | this.fillLast = utf8FillLast; | ||
39584 | nb = 4; | ||
39585 | break; | ||
39586 | case 'base64': | ||
39587 | this.text = base64Text; | ||
39588 | this.end = base64End; | ||
39589 | nb = 3; | ||
39590 | break; | ||
39591 | default: | ||
39592 | this.write = simpleWrite; | ||
39593 | this.end = simpleEnd; | ||
39594 | return; | ||
39595 | } | ||
39596 | this.lastNeed = 0; | ||
39597 | this.lastTotal = 0; | ||
39598 | this.lastChar = Buffer.allocUnsafe(nb); | ||
39599 | } | ||
39600 | |||
39601 | StringDecoder.prototype.write = function (buf) { | ||
39602 | if (buf.length === 0) return ''; | ||
39603 | var r; | ||
39604 | var i; | ||
39605 | if (this.lastNeed) { | ||
39606 | r = this.fillLast(buf); | ||
39607 | if (r === undefined) return ''; | ||
39608 | i = this.lastNeed; | ||
39609 | this.lastNeed = 0; | ||
39610 | } else { | ||
39611 | i = 0; | ||
39612 | } | ||
39613 | if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); | ||
39614 | return r || ''; | ||
39615 | }; | ||
39616 | |||
39617 | StringDecoder.prototype.end = utf8End; | ||
39618 | |||
39619 | // Returns only complete characters in a Buffer | ||
39620 | StringDecoder.prototype.text = utf8Text; | ||
39621 | |||
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); | ||
39627 | } | ||
39628 | buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); | ||
39629 | this.lastNeed -= buf.length; | ||
39630 | }; | ||
39631 | |||
39632 | // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a | ||
39633 | // continuation byte. | ||
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; | ||
39636 | return -1; | ||
39637 | } | ||
39638 | |||
39639 | // Checks at most 3 bytes at the end of a Buffer in order to detect an | ||
39640 | // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) | ||
39641 | // needed to complete the UTF-8 character (if applicable) are returned. | ||
39642 | function utf8CheckIncomplete(self, buf, i) { | ||
39643 | var j = buf.length - 1; | ||
39644 | if (j < i) return 0; | ||
39645 | var nb = utf8CheckByte(buf[j]); | ||
39646 | if (nb >= 0) { | ||
39647 | if (nb > 0) self.lastNeed = nb - 1; | ||
39648 | return nb; | ||
39649 | } | ||
39650 | if (--j < i) return 0; | ||
39651 | nb = utf8CheckByte(buf[j]); | ||
39652 | if (nb >= 0) { | ||
39653 | if (nb > 0) self.lastNeed = nb - 2; | ||
39654 | return nb; | ||
39655 | } | ||
39656 | if (--j < i) return 0; | ||
39657 | nb = utf8CheckByte(buf[j]); | ||
39658 | if (nb >= 0) { | ||
39659 | if (nb > 0) { | ||
39660 | if (nb === 2) nb = 0;else self.lastNeed = nb - 3; | ||
39661 | } | ||
39662 | return nb; | ||
39663 | } | ||
39664 | return 0; | ||
39665 | } | ||
39666 | |||
39667 | // Validates as many continuation bytes for a multi-byte UTF-8 character as | ||
39668 | // needed or are available. If we see a non-continuation byte where we expect | ||
39669 | // one, we "replace" the validated continuation bytes we've seen so far with | ||
39670 | // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding | ||
39671 | // behavior. The continuation byte check is included three times in the case | ||
39672 | // where all of the continuation bytes for a character exist in the same buffer. | ||
39673 | // It is also done this way as a slight performance increase instead of using a | ||
39674 | // loop. | ||
39675 | function utf8CheckExtraBytes(self, buf, p) { | ||
39676 | if ((buf[0] & 0xC0) !== 0x80) { | ||
39677 | self.lastNeed = 0; | ||
39678 | return '\ufffd'.repeat(p); | ||
39679 | } | ||
39680 | if (self.lastNeed > 1 && buf.length > 1) { | ||
39681 | if ((buf[1] & 0xC0) !== 0x80) { | ||
39682 | self.lastNeed = 1; | ||
39683 | return '\ufffd'.repeat(p + 1); | ||
39684 | } | ||
39685 | if (self.lastNeed > 2 && buf.length > 2) { | ||
39686 | if ((buf[2] & 0xC0) !== 0x80) { | ||
39687 | self.lastNeed = 2; | ||
39688 | return '\ufffd'.repeat(p + 2); | ||
39689 | } | ||
39690 | } | ||
39691 | } | ||
39692 | } | ||
39693 | |||
39694 | // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. | ||
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); | ||
39702 | } | ||
39703 | buf.copy(this.lastChar, p, 0, buf.length); | ||
39704 | this.lastNeed -= buf.length; | ||
39705 | } | ||
39706 | |||
39707 | // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a | ||
39708 | // partial character, the character's bytes are buffered until the required | ||
39709 | // number of bytes are available. | ||
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); | ||
39717 | } | ||
39718 | |||
39719 | // For UTF-8, a replacement character for each buffered byte of a (partial) | ||
39720 | // character needs to be added to the output. | ||
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); | ||
39724 | return r; | ||
39725 | } | ||
39726 | |||
39727 | // UTF-16LE typically needs two bytes per character, but even if we have an even | ||
39728 | // number of bytes available, we need to check if we end on a leading/high | ||
39729 | // surrogate. In that case, we need to wait for the next two bytes in order to | ||
39730 | // decode the last character properly. | ||
39731 | function utf16Text(buf, i) { | ||
39732 | if ((buf.length - i) % 2 === 0) { | ||
39733 | var r = buf.toString('utf16le', i); | ||
39734 | if (r) { | ||
39735 | var c = r.charCodeAt(r.length - 1); | ||
39736 | if (c >= 0xD800 && c <= 0xDBFF) { | ||
39737 | this.lastNeed = 2; | ||
39738 | this.lastTotal = 4; | ||
39739 | this.lastChar[0] = buf[buf.length - 2]; | ||
39740 | this.lastChar[1] = buf[buf.length - 1]; | ||
39741 | return r.slice(0, -1); | ||
39742 | } | ||
39743 | } | ||
39744 | return r; | ||
39745 | } | ||
39746 | this.lastNeed = 1; | ||
39747 | this.lastTotal = 2; | ||
39748 | this.lastChar[0] = buf[buf.length - 1]; | ||
39749 | return buf.toString('utf16le', i, buf.length - 1); | ||
39750 | } | ||
39751 | |||
39752 | // For UTF-16LE we do not explicitly append special replacement characters if we | ||
39753 | // end on a partial character, we simply let v8 handle that. | ||
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); | ||
39759 | } | ||
39760 | return r; | ||
39761 | } | ||
39762 | |||
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; | ||
39768 | if (n === 1) { | ||
39769 | this.lastChar[0] = buf[buf.length - 1]; | ||
39770 | } else { | ||
39771 | this.lastChar[0] = buf[buf.length - 2]; | ||
39772 | this.lastChar[1] = buf[buf.length - 1]; | ||
39773 | } | ||
39774 | return buf.toString('base64', i, buf.length - n); | ||
39775 | } | ||
39776 | |||
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); | ||
39780 | return r; | ||
39781 | } | ||
39782 | |||
39783 | // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) | ||
39784 | function simpleWrite(buf) { | ||
39785 | return buf.toString(this.encoding); | ||
39786 | } | ||
39787 | |||
39788 | function simpleEnd(buf) { | ||
39789 | return buf && buf.length ? this.write(buf) : ''; | ||
39790 | } | ||
39791 | },{"safe-buffer":247}],265:[function(require,module,exports){ | ||
39792 | (function (global){ | ||
39793 | |||
39794 | /** | ||
39795 | * Module exports. | ||
39796 | */ | ||
39797 | |||
39798 | module.exports = deprecate; | ||
39799 | |||
39800 | /** | ||
39801 | * Mark that a method should not be used. | ||
39802 | * Returns a modified function which warns once by default. | ||
39803 | * | ||
39804 | * If `localStorage.noDeprecation = true` is set, then it is a no-op. | ||
39805 | * | ||
39806 | * If `localStorage.throwDeprecation = true` is set, then deprecated functions | ||
39807 | * will throw an Error when invoked. | ||
39808 | * | ||
39809 | * If `localStorage.traceDeprecation = true` is set, then deprecated functions | ||
39810 | * will invoke `console.trace()` instead of `console.error()`. | ||
39811 | * | ||
39812 | * @param {Function} fn - the function to deprecate | ||
39813 | * @param {String} msg - the string to print to the console when `fn` is invoked | ||
39814 | * @returns {Function} a new "deprecated" version of `fn` | ||
39815 | * @api public | ||
39816 | */ | ||
39817 | |||
39818 | function deprecate (fn, msg) { | ||
39819 | if (config('noDeprecation')) { | ||
39820 | return fn; | ||
39821 | } | ||
39822 | |||
39823 | var warned = false; | ||
39824 | function deprecated() { | ||
39825 | if (!warned) { | ||
39826 | if (config('throwDeprecation')) { | ||
39827 | throw new Error(msg); | ||
39828 | } else if (config('traceDeprecation')) { | ||
39829 | console.trace(msg); | ||
39830 | } else { | ||
39831 | console.warn(msg); | ||
39832 | } | ||
39833 | warned = true; | ||
39834 | } | ||
39835 | return fn.apply(this, arguments); | ||
39836 | } | ||
39837 | |||
39838 | return deprecated; | ||
39839 | } | ||
39840 | |||
39841 | /** | ||
39842 | * Checks `localStorage` for boolean values for the given `name`. | ||
39843 | * | ||
39844 | * @param {String} name | ||
39845 | * @returns {Boolean} | ||
39846 | * @api private | ||
39847 | */ | ||
39848 | |||
39849 | function config (name) { | ||
39850 | // accessing global.localStorage can trigger a DOMException in sandboxed iframes | ||
39851 | try { | ||
39852 | if (!global.localStorage) return false; | ||
39853 | } catch (_) { | ||
39854 | return false; | ||
39855 | } | ||
39856 | var val = global.localStorage[name]; | ||
39857 | if (null == val) return false; | ||
39858 | return String(val).toLowerCase() === 'true'; | ||
39859 | } | ||
39860 | |||
39861 | }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) | ||
39862 | },{}],266:[function(require,module,exports){ | ||
39863 | var v1 = require('./v1'); | ||
39864 | var v4 = require('./v4'); | ||
39865 | |||
39866 | var uuid = v4; | ||
39867 | uuid.v1 = v1; | ||
39868 | uuid.v4 = v4; | ||
39869 | |||
39870 | module.exports = uuid; | ||
39871 | |||
39872 | },{"./v1":269,"./v4":270}],267:[function(require,module,exports){ | ||
39873 | /** | ||
39874 | * Convert array of 16 byte values to UUID string format of the form: | ||
39875 | * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX | ||
39876 | */ | ||
39877 | var byteToHex = []; | ||
39878 | for (var i = 0; i < 256; ++i) { | ||
39879 | byteToHex[i] = (i + 0x100).toString(16).substr(1); | ||
39880 | } | ||
39881 | |||
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++]]; | ||
39893 | } | ||
39894 | |||
39895 | module.exports = bytesToUuid; | ||
39896 | |||
39897 | },{}],268:[function(require,module,exports){ | ||
39898 | (function (global){ | ||
39899 | // Unique ID creation requires a high quality random # generator. In the | ||
39900 | // browser this is a little complicated due to unknown quality of Math.random() | ||
39901 | // and inconsistent support for the `crypto` API. We do the best we can via | ||
39902 | // feature-detection | ||
39903 | var rng; | ||
39904 | |||
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); | ||
39911 | return rnds8; | ||
39912 | }; | ||
39913 | } | ||
39914 | |||
39915 | if (!rng) { | ||
39916 | // Math.random()-based (RNG) | ||
39917 | // | ||
39918 | // If all else fails, use Math.random(). It's fast, but is of unspecified | ||
39919 | // quality. | ||
39920 | var rnds = new Array(16); | ||
39921 | rng = function() { | ||
39922 | for (var i = 0, r; i < 16; i++) { | ||
39923 | if ((i & 0x03) === 0) r = Math.random() * 0x100000000; | ||
39924 | rnds[i] = r >>> ((i & 0x03) << 3) & 0xff; | ||
39925 | } | ||
39926 | |||
39927 | return rnds; | ||
39928 | }; | ||
39929 | } | ||
39930 | |||
39931 | module.exports = rng; | ||
39932 | |||
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'); | ||
39937 | |||
39938 | // **`v1()` - Generate time-based UUID** | ||
39939 | // | ||
39940 | // Inspired by https://github.com/LiosK/UUID.js | ||
39941 | // and http://docs.python.org/library/uuid.html | ||
39942 | |||
39943 | // random #'s we need to init node and clockseq | ||
39944 | var _seedBytes = rng(); | ||
39945 | |||
39946 | // Per 4.5, create and 48-bit node id, (47 random bits + multicast bit = 1) | ||
39947 | var _nodeId = [ | ||
39948 | _seedBytes[0] | 0x01, | ||
39949 | _seedBytes[1], _seedBytes[2], _seedBytes[3], _seedBytes[4], _seedBytes[5] | ||
39950 | ]; | ||
39951 | |||
39952 | // Per 4.2.2, randomize (14 bit) clockseq | ||
39953 | var _clockseq = (_seedBytes[6] << 8 | _seedBytes[7]) & 0x3fff; | ||
39954 | |||
39955 | // Previous uuid creation time | ||
39956 | var _lastMSecs = 0, _lastNSecs = 0; | ||
39957 | |||
39958 | // See https://github.com/broofa/node-uuid for API details | ||
39959 | function v1(options, buf, offset) { | ||
39960 | var i = buf && offset || 0; | ||
39961 | var b = buf || []; | ||
39962 | |||
39963 | options = options || {}; | ||
39964 | |||
39965 | var clockseq = options.clockseq !== undefined ? options.clockseq : _clockseq; | ||
39966 | |||
39967 | // UUID timestamps are 100 nano-second units since the Gregorian epoch, | ||
39968 | // (1582-10-15 00:00). JSNumbers aren't precise enough for this, so | ||
39969 | // time is handled internally as 'msecs' (integer milliseconds) and 'nsecs' | ||
39970 | // (100-nanoseconds offset from msecs) since unix epoch, 1970-01-01 00:00. | ||
39971 | var msecs = options.msecs !== undefined ? options.msecs : new Date().getTime(); | ||
39972 | |||
39973 | // Per 4.2.1.2, use count of uuid's generated during the current clock | ||
39974 | // cycle to simulate higher resolution clock | ||
39975 | var nsecs = options.nsecs !== undefined ? options.nsecs : _lastNSecs + 1; | ||
39976 | |||
39977 | // Time since last uuid creation (in msecs) | ||
39978 | var dt = (msecs - _lastMSecs) + (nsecs - _lastNSecs)/10000; | ||
39979 | |||
39980 | // Per 4.2.1.2, Bump clockseq on clock regression | ||
39981 | if (dt < 0 && options.clockseq === undefined) { | ||
39982 | clockseq = clockseq + 1 & 0x3fff; | ||
39983 | } | ||
39984 | |||
39985 | // Reset nsecs if clock regresses (new clockseq) or we've moved onto a new | ||
39986 | // time interval | ||
39987 | if ((dt < 0 || msecs > _lastMSecs) && options.nsecs === undefined) { | ||
39988 | nsecs = 0; | ||
39989 | } | ||
39990 | |||
39991 | // Per 4.2.1.2 Throw error if too many uuids are requested | ||
39992 | if (nsecs >= 10000) { | ||
39993 | throw new Error('uuid.v1(): Can\'t create more than 10M uuids/sec'); | ||
39994 | } | ||
39995 | |||
39996 | _lastMSecs = msecs; | ||
39997 | _lastNSecs = nsecs; | ||
39998 | _clockseq = clockseq; | ||
39999 | |||
40000 | // Per 4.1.4 - Convert from unix epoch to Gregorian epoch | ||
40001 | msecs += 12219292800000; | ||
40002 | |||
40003 | // `time_low` | ||
40004 | var tl = ((msecs & 0xfffffff) * 10000 + nsecs) % 0x100000000; | ||
40005 | b[i++] = tl >>> 24 & 0xff; | ||
40006 | b[i++] = tl >>> 16 & 0xff; | ||
40007 | b[i++] = tl >>> 8 & 0xff; | ||
40008 | b[i++] = tl & 0xff; | ||
40009 | |||
40010 | // `time_mid` | ||
40011 | var tmh = (msecs / 0x100000000 * 10000) & 0xfffffff; | ||
40012 | b[i++] = tmh >>> 8 & 0xff; | ||
40013 | b[i++] = tmh & 0xff; | ||
40014 | |||
40015 | // `time_high_and_version` | ||
40016 | b[i++] = tmh >>> 24 & 0xf | 0x10; // include version | ||
40017 | b[i++] = tmh >>> 16 & 0xff; | ||
40018 | |||
40019 | // `clock_seq_hi_and_reserved` (Per 4.2.2 - include variant) | ||
40020 | b[i++] = clockseq >>> 8 | 0x80; | ||
40021 | |||
40022 | // `clock_seq_low` | ||
40023 | b[i++] = clockseq & 0xff; | ||
40024 | |||
40025 | // `node` | ||
40026 | var node = options.node || _nodeId; | ||
40027 | for (var n = 0; n < 6; ++n) { | ||
40028 | b[i + n] = node[n]; | ||
40029 | } | ||
40030 | |||
40031 | return buf ? buf : bytesToUuid(b); | ||
40032 | } | ||
40033 | |||
40034 | module.exports = v1; | ||
40035 | |||
40036 | },{"./lib/bytesToUuid":267,"./lib/rng":268}],270:[function(require,module,exports){ | ||
40037 | var rng = require('./lib/rng'); | ||
40038 | var bytesToUuid = require('./lib/bytesToUuid'); | ||
40039 | |||
40040 | function v4(options, buf, offset) { | ||
40041 | var i = buf && offset || 0; | ||
40042 | |||
40043 | if (typeof(options) == 'string') { | ||
40044 | buf = options == 'binary' ? new Array(16) : null; | ||
40045 | options = null; | ||
40046 | } | ||
40047 | options = options || {}; | ||
40048 | |||
40049 | var rnds = options.random || (options.rng || rng)(); | ||
40050 | |||
40051 | // Per 4.4, set bits for version and `clock_seq_hi_and_reserved` | ||
40052 | rnds[6] = (rnds[6] & 0x0f) | 0x40; | ||
40053 | rnds[8] = (rnds[8] & 0x3f) | 0x80; | ||
40054 | |||
40055 | // Copy bytes to buffer, if provided | ||
40056 | if (buf) { | ||
40057 | for (var ii = 0; ii < 16; ++ii) { | ||
40058 | buf[i + ii] = rnds[ii]; | ||
40059 | } | ||
40060 | } | ||
40061 | |||
40062 | return buf || bytesToUuid(rnds); | ||
40063 | } | ||
40064 | |||
40065 | module.exports = v4; | ||
40066 | |||
40067 | },{"./lib/bytesToUuid":267,"./lib/rng":268}],271:[function(require,module,exports){ | ||
40068 | var indexOf = require('indexof'); | ||
40069 | |||
40070 | var Object_keys = function (obj) { | ||
40071 | if (Object.keys) return Object.keys(obj) | ||
40072 | else { | ||
40073 | var res = []; | ||
40074 | for (var key in obj) res.push(key) | ||
40075 | return res; | ||
40076 | } | ||
40077 | }; | ||
40078 | |||
40079 | var forEach = function (xs, fn) { | ||
40080 | if (xs.forEach) return xs.forEach(fn) | ||
40081 | else for (var i = 0; i < xs.length; i++) { | ||
40082 | fn(xs[i], i, xs); | ||
40083 | } | ||
40084 | }; | ||
40085 | |||
40086 | var defineProp = (function() { | ||
40087 | try { | ||
40088 | Object.defineProperty({}, '_', {}); | ||
40089 | return function(obj, name, value) { | ||
40090 | Object.defineProperty(obj, name, { | ||
40091 | writable: true, | ||
40092 | enumerable: false, | ||
40093 | configurable: true, | ||
40094 | value: value | ||
40095 | }) | ||
40096 | }; | ||
40097 | } catch(e) { | ||
40098 | return function(obj, name, value) { | ||
40099 | obj[name] = value; | ||
40100 | }; | ||
40101 | } | ||
40102 | }()); | ||
40103 | |||
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']; | ||
40109 | |||
40110 | function Context() {} | ||
40111 | Context.prototype = {}; | ||
40112 | |||
40113 | var Script = exports.Script = function NodeScript (code) { | ||
40114 | if (!(this instanceof Script)) return new Script(code); | ||
40115 | this.code = code; | ||
40116 | }; | ||
40117 | |||
40118 | Script.prototype.runInContext = function (context) { | ||
40119 | if (!(context instanceof Context)) { | ||
40120 | throw new TypeError("needs a 'context' argument."); | ||
40121 | } | ||
40122 | |||
40123 | var iframe = document.createElement('iframe'); | ||
40124 | if (!iframe.style) iframe.style = {}; | ||
40125 | iframe.style.display = 'none'; | ||
40126 | |||
40127 | document.body.appendChild(iframe); | ||
40128 | |||
40129 | var win = iframe.contentWindow; | ||
40130 | var wEval = win.eval, wExecScript = win.execScript; | ||
40131 | |||
40132 | if (!wEval && wExecScript) { | ||
40133 | // win.eval() magically appears when this is called in IE: | ||
40134 | wExecScript.call(win, 'null'); | ||
40135 | wEval = win.eval; | ||
40136 | } | ||
40137 | |||
40138 | forEach(Object_keys(context), function (key) { | ||
40139 | win[key] = context[key]; | ||
40140 | }); | ||
40141 | forEach(globals, function (key) { | ||
40142 | if (context[key]) { | ||
40143 | win[key] = context[key]; | ||
40144 | } | ||
40145 | }); | ||
40146 | |||
40147 | var winKeys = Object_keys(win); | ||
40148 | |||
40149 | var res = wEval.call(win, this.code); | ||
40150 | |||
40151 | forEach(Object_keys(win), function (key) { | ||
40152 | // Avoid copying circular objects like `top` and `window` by only | ||
40153 | // updating existing context properties or new properties in the `win` | ||
40154 | // that was only introduced after the eval. | ||
40155 | if (key in context || indexOf(winKeys, key) === -1) { | ||
40156 | context[key] = win[key]; | ||
40157 | } | ||
40158 | }); | ||
40159 | |||
40160 | forEach(globals, function (key) { | ||
40161 | if (!(key in context)) { | ||
40162 | defineProp(context, key, win[key]); | ||
40163 | } | ||
40164 | }); | ||
40165 | |||
40166 | document.body.removeChild(iframe); | ||
40167 | |||
40168 | return res; | ||
40169 | }; | ||
40170 | |||
40171 | Script.prototype.runInThisContext = function () { | ||
40172 | return eval(this.code); // maybe... | ||
40173 | }; | ||
40174 | |||
40175 | Script.prototype.runInNewContext = function (context) { | ||
40176 | var ctx = Script.createContext(context); | ||
40177 | var res = this.runInContext(ctx); | ||
40178 | |||
40179 | forEach(Object_keys(ctx), function (key) { | ||
40180 | context[key] = ctx[key]; | ||
40181 | }); | ||
40182 | |||
40183 | return res; | ||
40184 | }; | ||
40185 | |||
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)); | ||
40190 | }; | ||
40191 | }); | ||
40192 | |||
40193 | exports.createScript = function (code) { | ||
40194 | return exports.Script(code); | ||
40195 | }; | ||
40196 | |||
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]; | ||
40202 | }); | ||
40203 | } | ||
40204 | return copy; | ||
40205 | }; | ||
40206 | |||
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'); | ||
40216 | |||
40217 | // dont override global variable | ||
40218 | if (typeof window !== 'undefined' && typeof window.Neb === 'undefined') { | ||
40219 | window.Neb = Neb; | ||
40220 | } | ||
40221 | |||
40222 | module.exports = { | ||
40223 | HttpRequest: HttpRequest, | ||
40224 | Neb: Neb, | ||
40225 | Account: Account, | ||
40226 | Transaction: Transaction, | ||
40227 | Utils: Utils, | ||
40228 | CryptoUtils: CryptoUtils, | ||
40229 | Unit: Unit, | ||
40230 | NVM: NVM | ||
40231 | }; | ||
40232 | |||
40233 | },{"./lib/account":1,"./lib/httprequest":4,"./lib/neb":5,"./lib/nvm/nvm":16,"./lib/transaction":18,"./lib/utils/crypto-utils":19,"./lib/utils/unit":20,"./lib/utils/utils":21}],"node-localstorage.js":[function(require,module,exports){ | ||
40234 | 'use strict'; | ||
40235 | |||
40236 | // go env doesn't have and need localStorage | ||
40237 | |||
40238 | if (typeof localStorage === 'undefined') { | ||
40239 | exports.localStorage = {}; | ||
40240 | } else { | ||
40241 | exports.localStorage = localStorage; // jshint ignore:line | ||
40242 | } | ||
40243 | |||
40244 | },{}]},{},[]); | ||