From 789a116a05c040bef38e37d523a838ee93ba4557 Mon Sep 17 00:00:00 2001 From: Matias Alejo Garcia Date: Sat, 4 Apr 2015 11:33:23 -0300 Subject: [PATCH] use copayerName also on walletCreate --- bitcore-wallet-client.js | 71034 +++++++++++++-------------------- bitcore-wallet-client.min.js | 119 +- lib/api.js | 16 +- 3 files changed, 27383 insertions(+), 43786 deletions(-) diff --git a/bitcore-wallet-client.js b/bitcore-wallet-client.js index e3c2c48b..17e271da 100644 --- a/bitcore-wallet-client.js +++ b/bitcore-wallet-client.js @@ -3,7 +3,7 @@ var Client = require('./lib'); module.exports = Client; },{"./lib":5}],2:[function(require,module,exports){ -(function (process){ +(function (process,Buffer){ /** @namespace Client.API */ 'use strict'; @@ -69,6 +69,10 @@ API.prototype.initNotifications = function(cb) { var self = this; var socket = io.connect(self.baseHost, { 'force new connection': true, + 'reconnection': true, + 'reconnectionDelay': 1000, + 'secure': true, + 'transports': ['polling', 'websocket'], }); socket.on('unauthorized', function() { @@ -210,6 +214,7 @@ API.prototype.seedFromExtendedPrivateKey = function(xPrivKey) { this.credentials = Credentials.fromExtendedPrivateKey(xPrivKey); }; + /** * Export wallet * @@ -278,9 +283,8 @@ API.prototype._doRequest = function(method, url, args, cb) { var reqSignature; if (this.credentials.requestPrivKey) { - reqSignature = API._signRequest(method, url, args, this.credentials.requestPrivKey); + reqSignature = API._signRequest(method, url, args, args._requestPrivKey || this.credentials.requestPrivKey); } - var absUrl = this.baseUrl + url; var args = { // relUrl: only for testing with `supertest` @@ -299,6 +303,7 @@ API.prototype._doRequest = function(method, url, args, cb) { log.debug('Request Args', util.inspect(args, { depth: 10 })); + this.request(args, function(err, res, body) { log.debug(util.inspect(body, { depth: 10 @@ -309,6 +314,9 @@ API.prototype._doRequest = function(method, url, args, cb) { return cb(API._parseError(body)); } + if (body === '{"error":"read ECONNRESET"}') + return cb(JSON.parse(body)); + return cb(null, body, res.header); }); }; @@ -325,6 +333,10 @@ API.prototype._doPostRequest = function(url, args, cb) { return this._doRequest('post', url, args, cb); }; +API.prototype._doPutRequest = function(url, args, cb) { + return this._doRequest('put', url, args, cb); +}; + /** * Do a GET request * @private @@ -333,6 +345,8 @@ API.prototype._doPostRequest = function(url, args, cb) { * @param {Callback} cb */ API.prototype._doGetRequest = function(url, cb) { + url += url.indexOf('?') > 0 ? '&' : '?'; + url += 'r=' + _.random(10000, 99999); return this._doRequest('get', url, {}, cb); }; @@ -356,14 +370,20 @@ API.prototype._doDeleteRequest = function(url, cb) { * @param {String} xPubKey * @param {String} requestPubKey * @param {String} copayerName + * @param {Object} Optional args + * @param {Object} .isTemporaryRequestKey * @param {Callback} cb */ -API.prototype._doJoinWallet = function(walletId, walletPrivKey, xPubKey, requestPubKey, copayerName, cb) { +API.prototype._doJoinWallet = function(walletId, walletPrivKey, xPubKey, requestPubKey, copayerName, opts, cb) { + opts = opts || {}; + $.shouldBeFunction(cb); + var args = { walletId: walletId, name: copayerName, xPubKey: xPubKey, - requestPubKey: requestPubKey + requestPubKey: requestPubKey, + isTemporaryRequestKey: !!opts.isTemporaryRequestKey, }; var hash = WalletUtils.getCopayerHash(args.name, args.xPubKey, args.requestPubKey); args.copayerSignature = WalletUtils.signMessage(hash, walletPrivKey); @@ -398,54 +418,79 @@ API.prototype.openWallet = function(cb) { var self = this; - if (self.credentials.isComplete()) return cb(null, true); + var wasComplete = self.credentials.isComplete(); + + if (wasComplete && !self.credentials.hasTemporaryRequestKeys()) + return cb(null, true); self._doGetRequest('/v1/wallets/', function(err, ret) { if (err) return cb(err); var wallet = ret.wallet; - if (wallet.status != 'complete') return cb(null, false); + if (wallet.status != 'complete') + return cb(null, false); if (self.credentials.walletPrivKey) { + if (!Verifier.checkCopayers(self.credentials, wallet.copayers)) { return cb(new ServerCompromisedError( 'Copayers in the wallet could not be verified to have known the wallet secret')); } } else { - log.warn('Could not perform verification of other copayers in the wallet'); + log.warn('Could not verify copayers key (missing wallet Private Key)'); } - self.credentials.addPublicKeyRing(_.map(wallet.copayers, function(copayer) { - return _.pick(copayer, ['xPubKey', 'requestPubKey']); - })); - if (!self.credentials.hasWalletInfo()) { - var me = _.find(wallet.copayers, { - id: self.credentials.copayerId - }); - self.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, null, me.name); - } + if (wasComplete) { - self.emit('walletCompleted', wallet); + // Wallet was completed. We are just updating temporary request keys + + self.credentials.updatePublicKeyRing(_.map(wallet.copayers, function(copayer) { + return _.pick(copayer, ['xPubKey', 'requestPubKey', 'isTemporaryRequestKey']); + })); + if (!self.credentials.hasTemporaryRequestKeys()) + self.emit('walletCompleted', wallet); + } else { + + + // Wallet was not complete. We are completing it. + + self.credentials.addPublicKeyRing(_.map(wallet.copayers, function(copayer) { + return _.pick(copayer, ['xPubKey', 'requestPubKey', 'isTemporaryRequestKey']); + })); + + if (!self.credentials.hasWalletInfo()) { + var me = _.find(wallet.copayers, { + id: self.credentials.copayerId + }); + self.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, null, me.name); + } + self.emit('walletCompleted', wallet); + } return cb(null, true); }); }; /** - * Create a wallet. * + * Create a wallet. * @param {String} walletName * @param {String} copayerName * @param {Number} m * @param {Number} n - * @param {String} network - 'livenet' or 'testnet' - * @param {Callback} cb - * @returns {Callback} cb - Returns the wallet - */ -API.prototype.createWallet = function(walletName, copayerName, m, n, network, cb) { + * @param {Object} opts (Optional: advanced options) + * @param {String} opts.network - 'livenet' or 'testnet' + * @param {String} opts.walletPrivKey - set a walletPrivKey (instead of random) + * @param {String} opts.id - set a id for wallet (instead of server given) + * @param cb + * @return {undefined} + */ +API.prototype.createWallet = function(walletName, copayerName, m, n, opts, cb) { var self = this; + if (opts) $.shouldBeObject(opts); + opts = opts || {}; - network = network || 'livenet'; + var network = opts.network || 'livenet'; if (!_.contains(['testnet', 'livenet'], network)) return cb(new Error('Invalid network')); if (!self.credentials) { @@ -459,15 +504,15 @@ API.prototype.createWallet = function(walletName, copayerName, m, n, network, cb return cb(new Error('Existing keys were created for a different network')); } - var walletPrivKey = new Bitcore.PrivateKey(); + var walletPrivKey = opts.walletPrivKey || new Bitcore.PrivateKey(); var args = { name: walletName, m: m, n: n, - pubKey: walletPrivKey.toPublicKey().toString(), + pubKey: (new Bitcore.PrivateKey(walletPrivKey)).toPublicKey().toString(), network: network, + id: opts.id, }; - self._doPostRequest('/v1/wallets/', args, function(err, body) { if (err) return cb(err); @@ -476,7 +521,7 @@ API.prototype.createWallet = function(walletName, copayerName, m, n, network, cb var secret = WalletUtils.toSecret(walletId, walletPrivKey, network); self.credentials.addWalletInfo(walletId, walletName, m, n, walletPrivKey.toString(), copayerName); - self._doJoinWallet(walletId, walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, + self._doJoinWallet(walletId, walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, {}, function(err, wallet) { if (err) return cb(err); return cb(null, n > 1 ? secret : null); @@ -505,7 +550,7 @@ API.prototype.joinWallet = function(secret, copayerName, cb) { self.seedFromRandom(secretData.network); } - self._doJoinWallet(secretData.walletId, secretData.walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, + self._doJoinWallet(secretData.walletId, secretData.walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, {}, function(err, wallet) { if (err) return cb(err); self.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, secretData.walletPrivKey.toString(), copayerName); @@ -544,7 +589,7 @@ API.prototype.recreateWallet = function(cb) { } else { copayerName = 'recovered copayer #' + (i++); } - self._doJoinWallet(walletId, walletPrivKey, item.xPubKey, item.requestPubKey, copayerName, next); + self._doJoinWallet(walletId, walletPrivKey, item.xPubKey, item.requestPubKey, copayerName, {}, next); }, cb); }); }; @@ -634,6 +679,7 @@ API.prototype.createAddress = function(cb) { self._doPostRequest('/v1/addresses/', {}, function(err, address) { if (err) return cb(err); + if (!Verifier.checkAddress(self.credentials, address)) { return cb(new ServerCompromisedError('Server sent fake address')); } @@ -676,9 +722,7 @@ API.prototype.getMainAddresses = function(opts, cb) { */ API.prototype.getBalance = function(cb) { $.checkState(this.credentials && this.credentials.isComplete()); - var self = this; - - self._doGetRequest('/v1/balance/', cb); + this._doGetRequest('/v1/balance/', cb); }; /** @@ -869,8 +913,7 @@ API.prototype.removeTxProposal = function(txp, cb) { var url = '/v1/txproposals/' + txp.id; self._doDeleteRequest(url, function(err) { - if (err) return cb(err); - return cb(); + return cb(err); }); }; @@ -900,17 +943,190 @@ API.prototype.getTxHistory = function(opts, cb) { var url = '/v1/txhistory/' + qs; self._doGetRequest(url, function(err, txs) { if (err) return cb(err); - API._processTxps(txs, self.credentials.sharedEncryptingKey); - return cb(null, txs); }); }; +/** + * Start an address scanning process. + * When finished, the scanning process will send a notification 'ScanFinished' to all copayers. + * + * @param {Object} opts + * @param {Boolean} opts.includeCopayerBranches (defaults to false) + * @param {Callback} cb + */ +API.prototype.startScan = function(opts, cb) { + $.checkState(this.credentials && this.credentials.isComplete()); + + var self = this; + + var args = { + includeCopayerBranches: opts.includeCopayerBranches, + }; + + self._doPostRequest('/v1/addresses/scan', args, function(err) { + return cb(err); + }); +}; + +/* + * + * Compatibility Functions + * + */ + +API.prototype._oldCopayDecrypt = function(username, password, blob) { + var SEP1 = '@#$'; + var SEP2 = '%^#@'; + + var decrypted; + try { + var passphrase = username + SEP1 + password; + decrypted = sjcl.decrypt(passphrase, blob); + } catch (e) { + passphrase = username + SEP2 + password; + try { + decrypted = sjcl.decrypt(passphrase, blob); + } catch (e) { + log.debug(e); + }; + } + + if (!decrypted) + return null; + + var ret; + try { + ret = JSON.parse(decrypted); + } catch (e) {}; + return ret; +}; + + +API.prototype.getWalletIdsFromOldCopay = function(username, password, blob) { + var p = this._oldCopayDecrypt(username, password, blob); + if (!p) return null; + var ids = p.walletIds.concat(_.keys(p.focusedTimestamps)); + return _.uniq(ids); +}; + +API.prototype._walletPrivKeyFromOldCopayWallet = function(w) { + // IN BWS, the master Pub Keys are not sent to the server, + // so it is safe to use them as seed for wallet's shared secret. + var seed = w.publicKeyRing.copayersExtPubKeys.sort().join(''); + var seedBuf = new Buffer(seed); + var privKey = new Bitcore.PrivateKey.fromBuffer(Bitcore.crypto.Hash.sha256(seedBuf)); + return privKey.toString(); +}; + +/** + * createWalletFromOldCopay + * + * @param username + * @param password + * @param blob + * @param cb + * @return {undefined} + */ +API.prototype.createWalletFromOldCopay = function(username, password, blob, cb) { + var self = this; + var w = this._oldCopayDecrypt(username, password, blob); + if (!w) return cb('Could not decrypt'); + + if ( w.publicKeyRing.copayersExtPubKeys.length != w.opts.totalCopayers) + return cb('Wallet is incomplete, cannot be imported'); + + var m = w.opts.requiredCopayers; + var n = w.opts.totalCopayers; + var walletId = w.opts.id; + var walletName = w.opts.name; + var network = w.opts.networkName; + this.credentials = Credentials.fromOldCopayWallet(w); + + var walletPrivKey = this._walletPrivKeyFromOldCopayWallet(w); + + + // Grab My Copayer Name + var hd = new Bitcore.HDPublicKey(self.credentials.xPubKey).derive('m/2147483646/0/0'); + var pubKey = hd.publicKey.toString('hex'); + var copayerName = w.publicKeyRing.nicknameFor[pubKey] || username; + + + this.createWallet(walletName, copayerName, m, n, { + network: network, + id: walletId, + walletPrivKey: walletPrivKey, + }, function(err, secret) { + + if (err && err.code == 'WEXISTS') { + + self.credentials.addWalletInfo(walletId, walletName, m, n, + walletPrivKey, copayerName); + + return self._replaceTemporaryRequestKey(function(err) { + if (err) return cb(err); + self.openWallet(function(err) { + return cb(err, true); + }); + }); + } + if (err) return cb(err); + + var i = 1; + async.eachSeries(self.credentials.publicKeyRing, function(item, next) { + if (item.xPubKey == self.credentials.xPubKey) + return next(); + + var copayerName; + // Grab Copayer Name + var hd = new Bitcore.HDPublicKey(item.xPubKey).derive('m/2147483646/0/0'); + var pubKey = hd.publicKey.toString('hex'); + copayerName = w.publicKeyRing.nicknameFor[pubKey] || 'recovered copayer #' + i++; + self._doJoinWallet(walletId, walletPrivKey, item.xPubKey, item.requestPubKey, copayerName, { + isTemporaryRequestKey: true + }, next); + }, cb); + }); +}; + +/* +Replace temporary request key + */ +API.prototype._replaceTemporaryRequestKey = function(cb) { + $.checkState(this.credentials && this.credentials.isComplete()); + + var args = { + name: this.credentials.copayerName, + xPubKey: this.credentials.xPubKey, + requestPubKey: this.credentials.requestPubKey, + isTemporaryRequestKey: false, + }; + + var hash = WalletUtils.getCopayerHash(args.name, args.xPubKey, args.requestPubKey); + args.copayerSignature = WalletUtils.signMessage(hash, this.credentials.walletPrivKey); + + // Use tmp request key to create the request. + var path0 = WalletUtils.PATHS.BASE_ADDRESS_DERIVATION; + var requestDerivationBase = (new Bitcore.HDPrivateKey(this.credentials.xPrivKey)) + .derive(path0); + + var path1 = WalletUtils.PATHS.TMP_REQUEST_KEY; + var requestDerivation = requestDerivationBase.derive(path1); + args._requestPrivKey = requestDerivation.privateKey.toString(); + + + this._doPutRequest('/v1/copayers/', args, function(err, wallet) { + if (err) return cb(err); + return cb(null, wallet); + }); +}; + + module.exports = API; -}).call(this,require('_process')) -},{"./clienterror":3,"./credentials":4,"./log":6,"./payprorequest":7,"./servercompromisederror":8,"./verifier":10,"_process":357,"async":11,"bitcore-payment-protocol":12,"bitcore-wallet-utils":108,"browser-request":192,"events":348,"lodash":380,"preconditions":381,"request":386,"sjcl":443,"socket.io-client":444,"url":375,"util":377}],3:[function(require,module,exports){ +}).call(this,require('_process'),require("buffer").Buffer) +},{"./clienterror":3,"./credentials":4,"./log":6,"./payprorequest":7,"./servercompromisederror":8,"./verifier":10,"_process":279,"async":11,"bitcore-payment-protocol":12,"bitcore-wallet-utils":35,"browser-request":112,"buffer":129,"events":270,"lodash":302,"preconditions":303,"request":308,"sjcl":393,"socket.io-client":394,"url":297,"util":299}],3:[function(require,module,exports){ function ClientError(code, message) { this.code = code; this.message = message; @@ -1038,7 +1254,9 @@ Credentials.prototype.addWalletInfo = function(walletId, walletName, m, n, walle this.m = m; this.n = n; this.walletPrivKey = walletPrivKey; - this.sharedEncryptingKey = WalletUtils.privateKeyToAESKey(walletPrivKey); + if (walletPrivKey) + this.sharedEncryptingKey = WalletUtils.privateKeyToAESKey(walletPrivKey); + this.copayerName = copayerName; if (n == 1) { this.addPublicKeyRing([{ @@ -1056,6 +1274,20 @@ Credentials.prototype.addPublicKeyRing = function(publicKeyRing) { this.publicKeyRing = _.clone(publicKeyRing); }; +Credentials.prototype.updatePublicKeyRing = function(publicKeyRing) { + _.each(this.publicKeyRing, function(x) { + if (x.isTemporaryRequestKey) { + var y = _.find(publicKeyRing, { + xPubKey: x.xPubKey + }); + if (y && !y.isTemporaryRequestKey) { + x.requestPubKey = y.requestPubKey; + x.isTemporaryRequestKey = y.isTemporaryRequestKey; + } + } + }); +}; + Credentials.prototype.canSign = function() { return !!this.xPrivKey; }; @@ -1066,6 +1298,13 @@ Credentials.prototype.isComplete = function() { return true; }; +Credentials.prototype.hasTemporaryRequestKeys = function() { + if (!this.isComplete()) return null; + return _.any(this.publicKeyRing, function(item) { + return item.isTemporaryRequestKey; + }); +}; + Credentials.prototype.exportCompressed = function() { var self = this; var values = _.map(EXPORTABLE_FIELDS, function(field) { @@ -1112,9 +1351,36 @@ Credentials.importCompressed = function(compressed) { return x; }; +Credentials.fromOldCopayWallet = function(w){ + var credentials = Credentials.fromExtendedPrivateKey(w.privateKey.extendedPrivateKeyString); + + var pkr = _.map(w.publicKeyRing.copayersExtPubKeys, function(xPubStr) { + + var isMe = xPubStr === credentials.xPubKey; + var requestDerivation; + + if (isMe) { + var path = WalletUtils.PATHS.REQUEST_KEY; + requestDerivation = (new Bitcore.HDPrivateKey(credentials.xPrivKey)) + .derive(path).hdPublicKey; + } else { + var path = WalletUtils.PATHS.TMP_REQUEST_KEY; + requestDerivation = (new Bitcore.HDPublicKey(xPubStr)).derive(path); + } + return { + xPubKey: xPubStr, + requestPubKey: requestDerivation.publicKey.toString(), + isTemporaryRequestKey: !isMe, + }; + }); + credentials.addPublicKeyRing(pkr); + + return credentials; +}; + module.exports = Credentials; -},{"bitcore-wallet-utils":108,"lodash":380,"preconditions":381}],5:[function(require,module,exports){ +},{"bitcore-wallet-utils":35,"lodash":302,"preconditions":303}],5:[function(require,module,exports){ /** * The official client library for bitcore-wallet-service. * @module Client @@ -1131,13 +1397,13 @@ var client = module.exports = require('./api'); * @alias module:Client.Verifier */ client.Verifier = require('./verifier'); - client.Utils = require('./utils'); +client.sjcl = require('sjcl'); // Expose bitcore client.Bitcore = require('bitcore-wallet-utils').Bitcore; -},{"./api":2,"./utils":9,"./verifier":10,"bitcore-wallet-utils":108}],6:[function(require,module,exports){ +},{"./api":2,"./utils":9,"./verifier":10,"bitcore-wallet-utils":35,"sjcl":393}],6:[function(require,module,exports){ var _ = require('lodash'); /** * @desc @@ -1265,7 +1531,7 @@ var error = new Error(); logger.setLevel('info'); module.exports = logger; -},{"lodash":380}],7:[function(require,module,exports){ +},{"lodash":302}],7:[function(require,module,exports){ (function (process,Buffer){ var $ = require('preconditions').singleton(); @@ -1360,8 +1626,13 @@ PayProRequest.get = function(opts, cb) { getter(opts, function(err, dataBuffer) { if (err) return cb(err); - var body = PayPro.PaymentRequest.decode(dataBuffer); - var request = (new PayPro()).makePaymentRequest(body); + var request; + try { + var body = PayPro.PaymentRequest.decode(dataBuffer); + request = (new PayPro()).makePaymentRequest(body); + } catch (e) { + return cb('Could not parse payment protocol:' + e) + } var signature = request.get('signature'); var serializedDetails = request.get('serialized_payment_details'); @@ -1417,7 +1688,7 @@ PayProRequest.get = function(opts, cb) { module.exports = PayProRequest; }).call(this,require('_process'),require("buffer").Buffer) -},{"_process":357,"bitcore-payment-protocol":12,"bitcore-wallet-utils":108,"buffer":209,"http":349,"https":353,"preconditions":381}],8:[function(require,module,exports){ +},{"_process":279,"bitcore-payment-protocol":12,"bitcore-wallet-utils":35,"buffer":129,"http":271,"https":275,"preconditions":303}],8:[function(require,module,exports){ function ServerCompromisedError(message) { this.code = 'SERVERCOMPROMISED'; this.message = message; @@ -1466,7 +1737,7 @@ Utils.formatAmount = function(satoshis, unit, opts) { module.exports = Utils; -},{"lodash":380,"preconditions":381}],10:[function(require,module,exports){ +},{"lodash":302,"preconditions":303}],10:[function(require,module,exports){ /** @namespace Verifier */ var $ = require('preconditions').singleton(); @@ -1495,7 +1766,8 @@ function Verifier(opts) {}; Verifier.checkAddress = function(credentials, address) { $.checkState(credentials.isComplete()); var local = WalletUtils.deriveAddress(credentials.publicKeyRing, address.path, credentials.m, credentials.network); - return (local.address == address.address && JSON.stringify(local.publicKeys) == JSON.stringify(address.publicKeys)); + return (local.address == address.address && + _.difference(local.publicKeys, address.publicKeys).length === 0); }; /** @@ -1518,6 +1790,8 @@ Verifier.checkCopayers = function(credentials, copayers) { var uniq = []; var error; _.each(copayers, function(copayer) { + if (error) return; + if (uniq[copayers.xPubKey]++) { log.error('Repeated public keys in server response'); error = true; @@ -1604,7 +1878,7 @@ Verifier.checkTxProposal = function(credentials, txp, opts, cb) { module.exports = Verifier; -},{"./log":6,"./payprorequest":7,"bitcore-wallet-utils":108,"lodash":380,"preconditions":381}],11:[function(require,module,exports){ +},{"./log":6,"./payprorequest":7,"bitcore-wallet-utils":35,"lodash":302,"preconditions":303}],11:[function(require,module,exports){ (function (process){ /*! * async @@ -2731,7 +3005,7 @@ module.exports = Verifier; }()); }).call(this,require('_process')) -},{"_process":357}],12:[function(require,module,exports){ +},{"_process":279}],12:[function(require,module,exports){ (function (Buffer){ 'use strict'; @@ -2952,7 +3226,7 @@ PaymentProtocol.verifyCertChain = function(chain, sigHashAlg) { module.exports = PaymentProtocol; }).call(this,require("buffer").Buffer) -},{"./common":13,"./rootcerts":15,"asn1.js/rfc/3280":29,"buffer":209,"jsrsasign":103}],13:[function(require,module,exports){ +},{"./common":13,"./rootcerts":15,"asn1.js/rfc/3280":29,"buffer":129,"jsrsasign":30}],13:[function(require,module,exports){ (function (Buffer){ 'use strict'; @@ -3414,7 +3688,7 @@ PaymentProtocol.trusted = RootCerts.trusted; module.exports = PaymentProtocol; }).call(this,require("buffer").Buffer) -},{"./rootcerts":15,"bitcore":30,"buffer":209,"protobufjs/dist/ProtoBuf":104}],14:[function(require,module,exports){ +},{"./rootcerts":15,"bitcore":37,"buffer":129,"protobufjs/dist/ProtoBuf":31}],14:[function(require,module,exports){ module.exports={ "GTE CyberTrust Global Root": "-----BEGIN CERTIFICATE-----\nMIICWjCCAcMCAgGlMA0GCSqGSIb3DQEBBAUAMHUxCzAJBgNVBAYTAlVTMRgwFgYDVQQKEw9H\nVEUgQ29ycG9yYXRpb24xJzAlBgNVBAsTHkdURSBDeWJlclRydXN0IFNvbHV0aW9ucywgSW5j\nLjEjMCEGA1UEAxMaR1RFIEN5YmVyVHJ1c3QgR2xvYmFsIFJvb3QwHhcNOTgwODEzMDAyOTAw\nWhcNMTgwODEzMjM1OTAwWjB1MQswCQYDVQQGEwJVUzEYMBYGA1UEChMPR1RFIENvcnBvcmF0\naW9uMScwJQYDVQQLEx5HVEUgQ3liZXJUcnVzdCBTb2x1dGlvbnMsIEluYy4xIzAhBgNVBAMT\nGkdURSBDeWJlclRydXN0IEdsb2JhbCBSb290MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKB\ngQCVD6C28FCc6HrHiM3dFw4usJTQGz0O9pTAipTHBsiQl8i4ZBp6fmw8U+E3KHNgf7KXUwef\nU/ltWJTSr41tiGeA5u2ylc9yMcqlHHK6XALnZELn+aks1joNrI1CqiQBOeacPwGFVw1Yh0X4\n04Wqk2kmhXBIgD8SFcd5tB8FLztimQIDAQABMA0GCSqGSIb3DQEBBAUAA4GBAG3rGwnpXtlR\n22ciYaQqPEh346B8pt5zohQDhT37qw4wxYMWM4ETCJ57NE7fQMh017l93PR2VX2bY1QY6fDq\n81yx2YtCHrnAlU66+tXifPVoYb+O7AWXX1uw16OFNMQkpw0PlZPvy5TYnh+dXIVtx6quTx8i\ntc2VrbqnzPmrC3p/\n-----END CERTIFICATE-----\n", "Thawte Server CA": "-----BEGIN CERTIFICATE-----\nMIIDEzCCAnygAwIBAgIBATANBgkqhkiG9w0BAQQFADCBxDELMAkGA1UEBhMCWkExFTATBgNV\nBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0wGwYDVQQKExRUaGF3dGUg\nQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBTZXJ2aWNlcyBEaXZpc2lv\nbjEZMBcGA1UEAxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3DQEJARYXc2VydmVyLWNl\ncnRzQHRoYXd0ZS5jb20wHhcNOTYwODAxMDAwMDAwWhcNMjAxMjMxMjM1OTU5WjCBxDELMAkG\nA1UEBhMCWkExFTATBgNVBAgTDFdlc3Rlcm4gQ2FwZTESMBAGA1UEBxMJQ2FwZSBUb3duMR0w\nGwYDVQQKExRUaGF3dGUgQ29uc3VsdGluZyBjYzEoMCYGA1UECxMfQ2VydGlmaWNhdGlvbiBT\nZXJ2aWNlcyBEaXZpc2lvbjEZMBcGA1UEAxMQVGhhd3RlIFNlcnZlciBDQTEmMCQGCSqGSIb3\nDQEJARYXc2VydmVyLWNlcnRzQHRoYXd0ZS5jb20wgZ8wDQYJKoZIhvcNAQEBBQADgY0AMIGJ\nAoGBANOkUG7I/1Zr5s9dtuoMaHVHoqrC2oQl/Kj0R1HahbUgdJSGHg91yekIYfUGbTBuFRkC\n6VLAYttNmZ7iagxEOM3+vuNkCXDF/rFrKbYvScg71CcEJRCXL+eQbcAoQpnXTEPew/UhbVSf\nXcNY4cDk2VuwuNy0e982OsK1ZiIS1ocNAgMBAAGjEzARMA8GA1UdEwEB/wQFMAMBAf8wDQYJ\nKoZIhvcNAQEEBQADgYEAB/pMaVz7lcxG7oWDTSEwjsrZqG9JGubaUeNgcGyEYRGhGshIPllD\nfU+VPaGLtwtimHp1it2ITk6eQNuozDJ0uW8NxuOzRAvZim+aKZuZGCg70eNAKJpaPNW15yAb\ni8qkq43pUdniTCxZqdq5snUb9kLy78fyGPmJvKP/iiMucEc=\n-----END CERTIFICATE-----\n", @@ -3638,7 +3912,7 @@ RootCerts.certs = certs; RootCerts.trusted = trusted; }).call(this,require("buffer").Buffer) -},{"./rootcerts.json":14,"buffer":209}],16:[function(require,module,exports){ +},{"./rootcerts.json":14,"buffer":129}],16:[function(require,module,exports){ var asn1 = exports; asn1.bignum = require('bn.js'); @@ -3702,7 +3976,7 @@ Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; -},{"../asn1":16,"util":377,"vm":378}],18:[function(require,module,exports){ +},{"../asn1":16,"util":299,"vm":300}],18:[function(require,module,exports){ var assert = require('assert'); var util = require('util'); var Reporter = require('../base').Reporter; @@ -3820,7 +4094,7 @@ EncoderBuffer.prototype.join = function join(out, offset) { return out; }; -},{"../base":19,"assert":194,"buffer":209,"util":377}],19:[function(require,module,exports){ +},{"../base":19,"assert":114,"buffer":129,"util":299}],19:[function(require,module,exports){ var base = exports; base.Reporter = require('./reporter').Reporter; @@ -4378,7 +4652,7 @@ Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { throw new Error('Unsupported tag: ' + tag); }; -},{"../base":19,"assert":194}],21:[function(require,module,exports){ +},{"../base":19,"assert":114}],21:[function(require,module,exports){ var util = require('util'); function Reporter(options) { @@ -4469,7 +4743,7 @@ ReporterError.prototype.rethrow = function rethrow(msg) { return this; }; -},{"util":377}],22:[function(require,module,exports){ +},{"util":299}],22:[function(require,module,exports){ var constants = require('../constants'); exports.tagClass = { @@ -4832,7 +5106,7 @@ function derDecodeLen(buf, primitive, fail) { return len; } -},{"../../asn1":16,"util":377}],25:[function(require,module,exports){ +},{"../../asn1":16,"util":299}],25:[function(require,module,exports){ var decoders = exports; decoders.der = require('./der'); @@ -5072,7 +5346,7 @@ function encodeTag(tag, primitive, cls, reporter) { return res; } -},{"../../asn1":16,"buffer":209,"util":377}],27:[function(require,module,exports){ +},{"../../asn1":16,"buffer":129,"util":299}],27:[function(require,module,exports){ var encoders = exports; encoders.der = require('./der'); @@ -7026,24496 +7300,674 @@ exports.AttributeValue = AttributeValue; },{"../..":16,"asn1.js":16}],30:[function(require,module,exports){ (function (Buffer){ -var bitcore = module.exports; - + +var navigator = {}; +navigator.uesrAgent = false; + +var window = {}; +/* + * jsrsasign 4.2.1 (c) 2010-2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +/* +yahoo-min.js +Copyright (c) 2011, Yahoo! Inc. All rights reserved. +Code licensed under the BSD License: +http://developer.yahoo.com/yui/license.html +version: 2.9.0 +*/ +if(typeof YAHOO=="undefined"||!YAHOO){var YAHOO={};}YAHOO.namespace=function(){var b=arguments,g=null,e,c,f;for(e=0;e":">",'"':""","'":"'","/":"/","`":"`"},d=["toString","valueOf"],e={isArray:function(j){return a.toString.apply(j)===c;},isBoolean:function(j){return typeof j==="boolean";},isFunction:function(j){return(typeof j==="function")||a.toString.apply(j)===h;},isNull:function(j){return j===null;},isNumber:function(j){return typeof j==="number"&&isFinite(j);},isObject:function(j){return(j&&(typeof j==="object"||f.isFunction(j)))||false;},isString:function(j){return typeof j==="string";},isUndefined:function(j){return typeof j==="undefined";},_IEEnumFix:(YAHOO.env.ua.ie)?function(l,k){var j,n,m;for(j=0;j"'\/`]/g,function(k){return g[k];});},extend:function(m,n,l){if(!n||!m){throw new Error("extend failed, please check that "+"all dependencies are included.");}var k=function(){},j;k.prototype=n.prototype;m.prototype=new k();m.prototype.constructor=m;m.superclass=n.prototype;if(n.prototype.constructor==a.constructor){n.prototype.constructor=n;}if(l){for(j in l){if(f.hasOwnProperty(l,j)){m.prototype[j]=l[j];}}f._IEEnumFix(m.prototype,l);}},augmentObject:function(n,m){if(!m||!n){throw new Error("Absorb failed, verify dependencies.");}var j=arguments,l,o,k=j[2];if(k&&k!==true){for(l=2;l0)?f.dump(j[l],p-1):t);}else{r.push(j[l]);}r.push(q);}if(r.length>1){r.pop();}r.push("]");}else{r.push("{");for(l in j){if(f.hasOwnProperty(j,l)){r.push(l+m);if(f.isObject(j[l])){r.push((p>0)?f.dump(j[l],p-1):t);}else{r.push(j[l]);}r.push(q);}}if(r.length>1){r.pop();}r.push("}");}return r.join("");},substitute:function(x,y,E,l){var D,C,B,G,t,u,F=[],p,z=x.length,A="dump",r=" ",q="{",m="}",n,w;for(;;){D=x.lastIndexOf(q,z);if(D<0){break;}C=x.indexOf(m,D);if(D+1>C){break;}p=x.substring(D+1,C);G=p;u=null;B=G.indexOf(r);if(B>-1){u=G.substring(B+1);G=G.substring(0,B);}t=y[G];if(E){t=E(G,t,u);}if(f.isObject(t)){if(f.isArray(t)){t=f.dump(t,parseInt(u,10));}else{u=u||"";n=u.indexOf(A);if(n>-1){u=u.substring(4);}w=t.toString();if(w===i||n>-1){t=f.dump(t,parseInt(u,10));}else{t=w;}}}else{if(!f.isString(t)&&!f.isNumber(t)){t="~-"+F.length+"-~";F[F.length]=p;}}x=x.substring(0,D)+t+x.substring(C+1);if(l===false){z=D-1;}}for(D=F.length-1;D>=0;D=D-1){x=x.replace(new RegExp("~-"+D+"-~"),"{"+F[D]+"}","g");}return x;},trim:function(j){try{return j.replace(/^\s+|\s+$/g,"");}catch(k){return j; +}},merge:function(){var n={},k=arguments,j=k.length,m;for(m=0;m>>2]>>>(24-(r%4)*8))&255;q[(n+r)>>>2]|=o<<(24-((n+r)%4)*8)}}else{for(var r=0;r>>2]=p[r>>>2]}}this.sigBytes+=s;return this},clamp:function(){var o=this.words;var n=this.sigBytes;o[n>>>2]&=4294967295<<(32-(n%4)*8);o.length=e.ceil(n/4)},clone:function(){var n=j.clone.call(this);n.words=this.words.slice(0);return n},random:function(p){var o=[];for(var n=0;n>>2]>>>(24-(n%4)*8))&255;q.push((s>>>4).toString(16));q.push((s&15).toString(16))}return q.join("")},parse:function(p){var n=p.length;var q=[];for(var o=0;o>>3]|=parseInt(p.substr(o,2),16)<<(24-(o%8)*4)}return new l.init(q,n/2)}};var d=m.Latin1={stringify:function(q){var r=q.words;var p=q.sigBytes;var n=[];for(var o=0;o>>2]>>>(24-(o%4)*8))&255;n.push(String.fromCharCode(s))}return n.join("")},parse:function(p){var n=p.length;var q=[];for(var o=0;o>>2]|=(p.charCodeAt(o)&255)<<(24-(o%4)*8)}return new l.init(q,n)}};var c=m.Utf8={stringify:function(n){try{return decodeURIComponent(escape(d.stringify(n)))}catch(o){throw new Error("Malformed UTF-8 data")}},parse:function(n){return d.parse(unescape(encodeURIComponent(n)))}};var i=b.BufferedBlockAlgorithm=j.extend({reset:function(){this._data=new l.init();this._nDataBytes=0},_append:function(n){if(typeof n=="string"){n=c.parse(n)}this._data.concat(n);this._nDataBytes+=n.sigBytes},_process:function(w){var q=this._data;var x=q.words;var n=q.sigBytes;var t=this.blockSize;var v=t*4;var u=n/v;if(w){u=e.ceil(u)}else{u=e.max((u|0)-this._minBufferSize,0)}var s=u*t;var r=e.min(s*4,n);if(s){for(var p=0;pe&&(b=a.finalize(b));b.clamp();for(var f=this._oKey=b.clone(),g=this._iKey=b.clone(),h=f.words,j=g.words,d=0;db;){var d;a:{d=l;for(var w=k.sqrt(d),r=2;r<=w;r++)if(!(d%r)){d=!1;break a}d=!0}d&&(8>b&&(s[b]=u(k.pow(l,0.5))),t[b]=u(k.pow(l,1/3)),b++);l++}var n=[],h=h.SHA256=j.extend({_doReset:function(){this._hash=new v.init(s.slice(0))},_doProcessBlock:function(q,h){for(var a=this._hash.words,c=a[0],d=a[1],b=a[2],k=a[3],f=a[4],g=a[5],j=a[6],l=a[7],e=0;64>e;e++){if(16>e)n[e]= +q[h+e]|0;else{var m=n[e-15],p=n[e-2];n[e]=((m<<25|m>>>7)^(m<<14|m>>>18)^m>>>3)+n[e-7]+((p<<15|p>>>17)^(p<<13|p>>>19)^p>>>10)+n[e-16]}m=l+((f<<26|f>>>6)^(f<<21|f>>>11)^(f<<7|f>>>25))+(f&g^~f&j)+t[e]+n[e];p=((c<<30|c>>>2)^(c<<19|c>>>13)^(c<<10|c>>>22))+(c&d^c&b^d&b);l=j;j=g;g=f;f=k+m|0;k=b;b=d;d=c;c=m+p|0}a[0]=a[0]+c|0;a[1]=a[1]+d|0;a[2]=a[2]+b|0;a[3]=a[3]+k|0;a[4]=a[4]+f|0;a[5]=a[5]+g|0;a[6]=a[6]+j|0;a[7]=a[7]+l|0},_doFinalize:function(){var d=this._data,b=d.words,a=8*this._nDataBytes,c=8*d.sigBytes; +b[c>>>5]|=128<<24-c%32;b[(c+64>>>9<<4)+14]=k.floor(a/4294967296);b[(c+64>>>9<<4)+15]=a;d.sigBytes=4*b.length;this._process();return this._hash},clone:function(){var b=j.clone.call(this);b._hash=this._hash.clone();return b}});g.SHA256=j._createHelper(h);g.HmacSHA256=j._createHmacHelper(h)})(Math); +/* +CryptoJS v3.1.2 sha224-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var b=CryptoJS,d=b.lib.WordArray,a=b.algo,c=a.SHA256,a=a.SHA224=c.extend({_doReset:function(){this._hash=new d.init([3238371032,914150663,812702999,4144912697,4290775857,1750603025,1694076839,3204075428])},_doFinalize:function(){var a=c._doFinalize.call(this);a.sigBytes-=4;return a}});b.SHA224=c._createHelper(a);b.HmacSHA224=c._createHmacHelper(a)})(); +/* +CryptoJS v3.1.2 sha512-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){function a(){return d.create.apply(d,arguments)}for(var n=CryptoJS,r=n.lib.Hasher,e=n.x64,d=e.Word,T=e.WordArray,e=n.algo,ea=[a(1116352408,3609767458),a(1899447441,602891725),a(3049323471,3964484399),a(3921009573,2173295548),a(961987163,4081628472),a(1508970993,3053834265),a(2453635748,2937671579),a(2870763221,3664609560),a(3624381080,2734883394),a(310598401,1164996542),a(607225278,1323610764),a(1426881987,3590304994),a(1925078388,4068182383),a(2162078206,991336113),a(2614888103,633803317), +a(3248222580,3479774868),a(3835390401,2666613458),a(4022224774,944711139),a(264347078,2341262773),a(604807628,2007800933),a(770255983,1495990901),a(1249150122,1856431235),a(1555081692,3175218132),a(1996064986,2198950837),a(2554220882,3999719339),a(2821834349,766784016),a(2952996808,2566594879),a(3210313671,3203337956),a(3336571891,1034457026),a(3584528711,2466948901),a(113926993,3758326383),a(338241895,168717936),a(666307205,1188179964),a(773529912,1546045734),a(1294757372,1522805485),a(1396182291, +2643833823),a(1695183700,2343527390),a(1986661051,1014477480),a(2177026350,1206759142),a(2456956037,344077627),a(2730485921,1290863460),a(2820302411,3158454273),a(3259730800,3505952657),a(3345764771,106217008),a(3516065817,3606008344),a(3600352804,1432725776),a(4094571909,1467031594),a(275423344,851169720),a(430227734,3100823752),a(506948616,1363258195),a(659060556,3750685593),a(883997877,3785050280),a(958139571,3318307427),a(1322822218,3812723403),a(1537002063,2003034995),a(1747873779,3602036899), +a(1955562222,1575990012),a(2024104815,1125592928),a(2227730452,2716904306),a(2361852424,442776044),a(2428436474,593698344),a(2756734187,3733110249),a(3204031479,2999351573),a(3329325298,3815920427),a(3391569614,3928383900),a(3515267271,566280711),a(3940187606,3454069534),a(4118630271,4000239992),a(116418474,1914138554),a(174292421,2731055270),a(289380356,3203993006),a(460393269,320620315),a(685471733,587496836),a(852142971,1086792851),a(1017036298,365543100),a(1126000580,2618297676),a(1288033470, +3409855158),a(1501505948,4234509866),a(1607167915,987167468),a(1816402316,1246189591)],v=[],w=0;80>w;w++)v[w]=a();e=e.SHA512=r.extend({_doReset:function(){this._hash=new T.init([new d.init(1779033703,4089235720),new d.init(3144134277,2227873595),new d.init(1013904242,4271175723),new d.init(2773480762,1595750129),new d.init(1359893119,2917565137),new d.init(2600822924,725511199),new d.init(528734635,4215389547),new d.init(1541459225,327033209)])},_doProcessBlock:function(a,d){for(var f=this._hash.words, +F=f[0],e=f[1],n=f[2],r=f[3],G=f[4],H=f[5],I=f[6],f=f[7],w=F.high,J=F.low,X=e.high,K=e.low,Y=n.high,L=n.low,Z=r.high,M=r.low,$=G.high,N=G.low,aa=H.high,O=H.low,ba=I.high,P=I.low,ca=f.high,Q=f.low,k=w,g=J,z=X,x=K,A=Y,y=L,U=Z,B=M,l=$,h=N,R=aa,C=O,S=ba,D=P,V=ca,E=Q,m=0;80>m;m++){var s=v[m];if(16>m)var j=s.high=a[d+2*m]|0,b=s.low=a[d+2*m+1]|0;else{var j=v[m-15],b=j.high,p=j.low,j=(b>>>1|p<<31)^(b>>>8|p<<24)^b>>>7,p=(p>>>1|b<<31)^(p>>>8|b<<24)^(p>>>7|b<<25),u=v[m-2],b=u.high,c=u.low,u=(b>>>19|c<<13)^(b<< +3|c>>>29)^b>>>6,c=(c>>>19|b<<13)^(c<<3|b>>>29)^(c>>>6|b<<26),b=v[m-7],W=b.high,t=v[m-16],q=t.high,t=t.low,b=p+b.low,j=j+W+(b>>>0

>>0?1:0),b=b+c,j=j+u+(b>>>0>>0?1:0),b=b+t,j=j+q+(b>>>0>>0?1:0);s.high=j;s.low=b}var W=l&R^~l&S,t=h&C^~h&D,s=k&z^k&A^z&A,T=g&x^g&y^x&y,p=(k>>>28|g<<4)^(k<<30|g>>>2)^(k<<25|g>>>7),u=(g>>>28|k<<4)^(g<<30|k>>>2)^(g<<25|k>>>7),c=ea[m],fa=c.high,da=c.low,c=E+((h>>>14|l<<18)^(h>>>18|l<<14)^(h<<23|l>>>9)),q=V+((l>>>14|h<<18)^(l>>>18|h<<14)^(l<<23|h>>>9))+(c>>>0>>0?1: +0),c=c+t,q=q+W+(c>>>0>>0?1:0),c=c+da,q=q+fa+(c>>>0>>0?1:0),c=c+b,q=q+j+(c>>>0>>0?1:0),b=u+T,s=p+s+(b>>>0>>0?1:0),V=S,E=D,S=R,D=C,R=l,C=h,h=B+c|0,l=U+q+(h>>>0>>0?1:0)|0,U=A,B=y,A=z,y=x,z=k,x=g,g=c+b|0,k=q+s+(g>>>0>>0?1:0)|0}J=F.low=J+g;F.high=w+k+(J>>>0>>0?1:0);K=e.low=K+x;e.high=X+z+(K>>>0>>0?1:0);L=n.low=L+y;n.high=Y+A+(L>>>0>>0?1:0);M=r.low=M+B;r.high=Z+U+(M>>>0>>0?1:0);N=G.low=N+h;G.high=$+l+(N>>>0>>0?1:0);O=H.low=O+C;H.high=aa+R+(O>>>0>>0?1:0);P=I.low=P+D; +I.high=ba+S+(P>>>0>>0?1:0);Q=f.low=Q+E;f.high=ca+V+(Q>>>0>>0?1:0)},_doFinalize:function(){var a=this._data,d=a.words,f=8*this._nDataBytes,e=8*a.sigBytes;d[e>>>5]|=128<<24-e%32;d[(e+128>>>10<<5)+30]=Math.floor(f/4294967296);d[(e+128>>>10<<5)+31]=f;a.sigBytes=4*d.length;this._process();return this._hash.toX32()},clone:function(){var a=r.clone.call(this);a._hash=this._hash.clone();return a},blockSize:32});n.SHA512=r._createHelper(e);n.HmacSHA512=r._createHmacHelper(e)})(); +/* +CryptoJS v3.1.2 sha384-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var c=CryptoJS,a=c.x64,b=a.Word,e=a.WordArray,a=c.algo,d=a.SHA512,a=a.SHA384=d.extend({_doReset:function(){this._hash=new e.init([new b.init(3418070365,3238371032),new b.init(1654270250,914150663),new b.init(2438529370,812702999),new b.init(355462360,4144912697),new b.init(1731405415,4290775857),new b.init(2394180231,1750603025),new b.init(3675008525,1694076839),new b.init(1203062813,3204075428)])},_doFinalize:function(){var a=d._doFinalize.call(this);a.sigBytes-=16;return a}});c.SHA384= +d._createHelper(a);c.HmacSHA384=d._createHmacHelper(a)})(); +/* +CryptoJS v3.1.2 md5-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(E){function h(a,f,g,j,p,h,k){a=a+(f&g|~f&j)+p+k;return(a<>>32-h)+f}function k(a,f,g,j,p,h,k){a=a+(f&j|g&~j)+p+k;return(a<>>32-h)+f}function l(a,f,g,j,h,k,l){a=a+(f^g^j)+h+l;return(a<>>32-k)+f}function n(a,f,g,j,h,k,l){a=a+(g^(f|~j))+h+l;return(a<>>32-k)+f}for(var r=CryptoJS,q=r.lib,F=q.WordArray,s=q.Hasher,q=r.algo,a=[],t=0;64>t;t++)a[t]=4294967296*E.abs(E.sin(t+1))|0;q=q.MD5=s.extend({_doReset:function(){this._hash=new F.init([1732584193,4023233417,2562383102,271733878])}, +_doProcessBlock:function(m,f){for(var g=0;16>g;g++){var j=f+g,p=m[j];m[j]=(p<<8|p>>>24)&16711935|(p<<24|p>>>8)&4278255360}var g=this._hash.words,j=m[f+0],p=m[f+1],q=m[f+2],r=m[f+3],s=m[f+4],t=m[f+5],u=m[f+6],v=m[f+7],w=m[f+8],x=m[f+9],y=m[f+10],z=m[f+11],A=m[f+12],B=m[f+13],C=m[f+14],D=m[f+15],b=g[0],c=g[1],d=g[2],e=g[3],b=h(b,c,d,e,j,7,a[0]),e=h(e,b,c,d,p,12,a[1]),d=h(d,e,b,c,q,17,a[2]),c=h(c,d,e,b,r,22,a[3]),b=h(b,c,d,e,s,7,a[4]),e=h(e,b,c,d,t,12,a[5]),d=h(d,e,b,c,u,17,a[6]),c=h(c,d,e,b,v,22,a[7]), +b=h(b,c,d,e,w,7,a[8]),e=h(e,b,c,d,x,12,a[9]),d=h(d,e,b,c,y,17,a[10]),c=h(c,d,e,b,z,22,a[11]),b=h(b,c,d,e,A,7,a[12]),e=h(e,b,c,d,B,12,a[13]),d=h(d,e,b,c,C,17,a[14]),c=h(c,d,e,b,D,22,a[15]),b=k(b,c,d,e,p,5,a[16]),e=k(e,b,c,d,u,9,a[17]),d=k(d,e,b,c,z,14,a[18]),c=k(c,d,e,b,j,20,a[19]),b=k(b,c,d,e,t,5,a[20]),e=k(e,b,c,d,y,9,a[21]),d=k(d,e,b,c,D,14,a[22]),c=k(c,d,e,b,s,20,a[23]),b=k(b,c,d,e,x,5,a[24]),e=k(e,b,c,d,C,9,a[25]),d=k(d,e,b,c,r,14,a[26]),c=k(c,d,e,b,w,20,a[27]),b=k(b,c,d,e,B,5,a[28]),e=k(e,b, +c,d,q,9,a[29]),d=k(d,e,b,c,v,14,a[30]),c=k(c,d,e,b,A,20,a[31]),b=l(b,c,d,e,t,4,a[32]),e=l(e,b,c,d,w,11,a[33]),d=l(d,e,b,c,z,16,a[34]),c=l(c,d,e,b,C,23,a[35]),b=l(b,c,d,e,p,4,a[36]),e=l(e,b,c,d,s,11,a[37]),d=l(d,e,b,c,v,16,a[38]),c=l(c,d,e,b,y,23,a[39]),b=l(b,c,d,e,B,4,a[40]),e=l(e,b,c,d,j,11,a[41]),d=l(d,e,b,c,r,16,a[42]),c=l(c,d,e,b,u,23,a[43]),b=l(b,c,d,e,x,4,a[44]),e=l(e,b,c,d,A,11,a[45]),d=l(d,e,b,c,D,16,a[46]),c=l(c,d,e,b,q,23,a[47]),b=n(b,c,d,e,j,6,a[48]),e=n(e,b,c,d,v,10,a[49]),d=n(d,e,b,c, +C,15,a[50]),c=n(c,d,e,b,t,21,a[51]),b=n(b,c,d,e,A,6,a[52]),e=n(e,b,c,d,r,10,a[53]),d=n(d,e,b,c,y,15,a[54]),c=n(c,d,e,b,p,21,a[55]),b=n(b,c,d,e,w,6,a[56]),e=n(e,b,c,d,D,10,a[57]),d=n(d,e,b,c,u,15,a[58]),c=n(c,d,e,b,B,21,a[59]),b=n(b,c,d,e,s,6,a[60]),e=n(e,b,c,d,z,10,a[61]),d=n(d,e,b,c,q,15,a[62]),c=n(c,d,e,b,x,21,a[63]);g[0]=g[0]+b|0;g[1]=g[1]+c|0;g[2]=g[2]+d|0;g[3]=g[3]+e|0},_doFinalize:function(){var a=this._data,f=a.words,g=8*this._nDataBytes,j=8*a.sigBytes;f[j>>>5]|=128<<24-j%32;var h=E.floor(g/ +4294967296);f[(j+64>>>9<<4)+15]=(h<<8|h>>>24)&16711935|(h<<24|h>>>8)&4278255360;f[(j+64>>>9<<4)+14]=(g<<8|g>>>24)&16711935|(g<<24|g>>>8)&4278255360;a.sigBytes=4*(f.length+1);this._process();a=this._hash;f=a.words;for(g=0;4>g;g++)j=f[g],f[g]=(j<<8|j>>>24)&16711935|(j<<24|j>>>8)&4278255360;return a},clone:function(){var a=s.clone.call(this);a._hash=this._hash.clone();return a}});r.MD5=s._createHelper(q);r.HmacMD5=s._createHmacHelper(q)})(Math); +/* +CryptoJS v3.1.2 enc-base64-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var h=CryptoJS,j=h.lib.WordArray;h.enc.Base64={stringify:function(b){var e=b.words,f=b.sigBytes,c=this._map;b.clamp();b=[];for(var a=0;a>>2]>>>24-8*(a%4)&255)<<16|(e[a+1>>>2]>>>24-8*((a+1)%4)&255)<<8|e[a+2>>>2]>>>24-8*((a+2)%4)&255,g=0;4>g&&a+0.75*g>>6*(3-g)&63));if(e=c.charAt(64))for(;b.length%4;)b.push(e);return b.join("")},parse:function(b){var e=b.length,f=this._map,c=f.charAt(64);c&&(c=b.indexOf(c),-1!=c&&(e=c));for(var c=[],a=0,d=0;d< +e;d++)if(d%4){var g=f.indexOf(b.charAt(d-1))<<2*(d%4),h=f.indexOf(b.charAt(d))>>>6-2*(d%4);c[a>>>2]|=(g|h)<<24-8*(a%4);a++}return j.create(c,a)},_map:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/="}})(); +/* +CryptoJS v3.1.2 cipher-core-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +CryptoJS.lib.Cipher||function(u){var g=CryptoJS,f=g.lib,k=f.Base,l=f.WordArray,q=f.BufferedBlockAlgorithm,r=g.enc.Base64,v=g.algo.EvpKDF,n=f.Cipher=q.extend({cfg:k.extend(),createEncryptor:function(a,b){return this.create(this._ENC_XFORM_MODE,a,b)},createDecryptor:function(a,b){return this.create(this._DEC_XFORM_MODE,a,b)},init:function(a,b,c){this.cfg=this.cfg.extend(c);this._xformMode=a;this._key=b;this.reset()},reset:function(){q.reset.call(this);this._doReset()},process:function(a){this._append(a); +return this._process()},finalize:function(a){a&&this._append(a);return this._doFinalize()},keySize:4,ivSize:4,_ENC_XFORM_MODE:1,_DEC_XFORM_MODE:2,_createHelper:function(a){return{encrypt:function(b,c,d){return("string"==typeof c?s:j).encrypt(a,b,c,d)},decrypt:function(b,c,d){return("string"==typeof c?s:j).decrypt(a,b,c,d)}}}});f.StreamCipher=n.extend({_doFinalize:function(){return this._process(!0)},blockSize:1});var m=g.mode={},t=function(a,b,c){var d=this._iv;d?this._iv=u:d=this._prevBlock;for(var e= +0;e>>2]&255}};f.BlockCipher=n.extend({cfg:n.cfg.extend({mode:m,padding:h}),reset:function(){n.reset.call(this);var a=this.cfg,b=a.iv,a=a.mode;if(this._xformMode==this._ENC_XFORM_MODE)var c=a.createEncryptor;else c=a.createDecryptor,this._minBufferSize=1; +this._mode=c.call(a,this,b&&b.words)},_doProcessBlock:function(a,b){this._mode.processBlock(a,b)},_doFinalize:function(){var a=this.cfg.padding;if(this._xformMode==this._ENC_XFORM_MODE){a.pad(this._data,this.blockSize);var b=this._process(!0)}else b=this._process(!0),a.unpad(b);return b},blockSize:4});var p=f.CipherParams=k.extend({init:function(a){this.mixIn(a)},toString:function(a){return(a||this.formatter).stringify(this)}}),m=(g.format={}).OpenSSL={stringify:function(a){var b=a.ciphertext;a=a.salt; +return(a?l.create([1398893684,1701076831]).concat(a).concat(b):b).toString(r)},parse:function(a){a=r.parse(a);var b=a.words;if(1398893684==b[0]&&1701076831==b[1]){var c=l.create(b.slice(2,4));b.splice(0,4);a.sigBytes-=16}return p.create({ciphertext:a,salt:c})}},j=f.SerializableCipher=k.extend({cfg:k.extend({format:m}),encrypt:function(a,b,c,d){d=this.cfg.extend(d);var e=a.createEncryptor(c,d);b=e.finalize(b);e=e.cfg;return p.create({ciphertext:b,key:c,iv:e.iv,algorithm:a,mode:e.mode,padding:e.padding, +blockSize:a.blockSize,formatter:d.format})},decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);return a.createDecryptor(c,d).finalize(b.ciphertext)},_parse:function(a,b){return"string"==typeof a?b.parse(a,this):a}}),g=(g.kdf={}).OpenSSL={execute:function(a,b,c,d){d||(d=l.random(8));a=v.create({keySize:b+c}).compute(a,d);c=l.create(a.words.slice(b),4*c);a.sigBytes=4*b;return p.create({key:a,iv:c,salt:d})}},s=f.PasswordBasedCipher=j.extend({cfg:j.cfg.extend({kdf:g}),encrypt:function(a, +b,c,d){d=this.cfg.extend(d);c=d.kdf.execute(c,a.keySize,a.ivSize);d.iv=c.iv;a=j.encrypt.call(this,a,b,c.key,d);a.mixIn(c);return a},decrypt:function(a,b,c,d){d=this.cfg.extend(d);b=this._parse(b,d.format);c=d.kdf.execute(c,a.keySize,a.ivSize,b.salt);d.iv=c.iv;return j.decrypt.call(this,a,b,c.key,d)}})}(); +/* +CryptoJS v3.1.2 aes-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){for(var q=CryptoJS,x=q.lib.BlockCipher,r=q.algo,j=[],y=[],z=[],A=[],B=[],C=[],s=[],u=[],v=[],w=[],g=[],k=0;256>k;k++)g[k]=128>k?k<<1:k<<1^283;for(var n=0,l=0,k=0;256>k;k++){var f=l^l<<1^l<<2^l<<3^l<<4,f=f>>>8^f&255^99;j[n]=f;y[f]=n;var t=g[n],D=g[t],E=g[D],b=257*g[f]^16843008*f;z[n]=b<<24|b>>>8;A[n]=b<<16|b>>>16;B[n]=b<<8|b>>>24;C[n]=b;b=16843009*E^65537*D^257*t^16843008*n;s[f]=b<<24|b>>>8;u[f]=b<<16|b>>>16;v[f]=b<<8|b>>>24;w[f]=b;n?(n=t^g[g[g[E^t]]],l^=g[g[l]]):n=l=1}var F=[0,1,2,4,8, +16,32,64,128,27,54],r=r.AES=x.extend({_doReset:function(){for(var c=this._key,e=c.words,a=c.sigBytes/4,c=4*((this._nRounds=a+6)+1),b=this._keySchedule=[],h=0;h>>24]<<24|j[d>>>16&255]<<16|j[d>>>8&255]<<8|j[d&255]):(d=d<<8|d>>>24,d=j[d>>>24]<<24|j[d>>>16&255]<<16|j[d>>>8&255]<<8|j[d&255],d^=F[h/a|0]<<24);b[h]=b[h-a]^d}e=this._invKeySchedule=[];for(a=0;aa||4>=h?d:s[j[d>>>24]]^u[j[d>>>16&255]]^v[j[d>>> +8&255]]^w[j[d&255]]},encryptBlock:function(c,e){this._doCryptBlock(c,e,this._keySchedule,z,A,B,C,j)},decryptBlock:function(c,e){var a=c[e+1];c[e+1]=c[e+3];c[e+3]=a;this._doCryptBlock(c,e,this._invKeySchedule,s,u,v,w,y);a=c[e+1];c[e+1]=c[e+3];c[e+3]=a},_doCryptBlock:function(c,e,a,b,h,d,j,m){for(var n=this._nRounds,f=c[e]^a[0],g=c[e+1]^a[1],k=c[e+2]^a[2],p=c[e+3]^a[3],l=4,t=1;t>>24]^h[g>>>16&255]^d[k>>>8&255]^j[p&255]^a[l++],r=b[g>>>24]^h[k>>>16&255]^d[p>>>8&255]^j[f&255]^a[l++],s= +b[k>>>24]^h[p>>>16&255]^d[f>>>8&255]^j[g&255]^a[l++],p=b[p>>>24]^h[f>>>16&255]^d[g>>>8&255]^j[k&255]^a[l++],f=q,g=r,k=s;q=(m[f>>>24]<<24|m[g>>>16&255]<<16|m[k>>>8&255]<<8|m[p&255])^a[l++];r=(m[g>>>24]<<24|m[k>>>16&255]<<16|m[p>>>8&255]<<8|m[f&255])^a[l++];s=(m[k>>>24]<<24|m[p>>>16&255]<<16|m[f>>>8&255]<<8|m[g&255])^a[l++];p=(m[p>>>24]<<24|m[f>>>16&255]<<16|m[g>>>8&255]<<8|m[k&255])^a[l++];c[e]=q;c[e+1]=r;c[e+2]=s;c[e+3]=p},keySize:8});q.AES=x._createHelper(r)})(); +/* +CryptoJS v3.1.2 tripledes-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){function j(b,c){var a=(this._lBlock>>>b^this._rBlock)&c;this._rBlock^=a;this._lBlock^=a<>>b^this._lBlock)&c;this._lBlock^=a;this._rBlock^=a<a;a++){var f=q[a]-1;c[a]=b[f>>>5]>>>31-f%32&1}b=this._subKeys=[];for(f=0;16>f;f++){for(var d=b[f]=[],e=r[f],a=0;24>a;a++)d[a/6|0]|=c[(p[a]-1+e)%28]<<31-a%6,d[4+(a/6|0)]|=c[28+(p[a+24]-1+e)%28]<<31-a%6;d[0]=d[0]<<1|d[0]>>>31;for(a=1;7>a;a++)d[a]>>>= +4*(a-1)+3;d[7]=d[7]<<5|d[7]>>>27}c=this._invSubKeys=[];for(a=0;16>a;a++)c[a]=b[15-a]},encryptBlock:function(b,c){this._doCryptBlock(b,c,this._subKeys)},decryptBlock:function(b,c){this._doCryptBlock(b,c,this._invSubKeys)},_doCryptBlock:function(b,c,a){this._lBlock=b[c];this._rBlock=b[c+1];j.call(this,4,252645135);j.call(this,16,65535);l.call(this,2,858993459);l.call(this,8,16711935);j.call(this,1,1431655765);for(var f=0;16>f;f++){for(var d=a[f],e=this._lBlock,h=this._rBlock,g=0,k=0;8>k;k++)g|=s[k][((h^ +d[k])&t[k])>>>0];this._lBlock=h;this._rBlock=e^g}a=this._lBlock;this._lBlock=this._rBlock;this._rBlock=a;j.call(this,1,1431655765);l.call(this,8,16711935);l.call(this,2,858993459);j.call(this,16,65535);j.call(this,4,252645135);b[c]=this._lBlock;b[c+1]=this._rBlock},keySize:2,ivSize:2,blockSize:2});h.DES=e._createHelper(m);g=g.TripleDES=e.extend({_doReset:function(){var b=this._key.words;this._des1=m.createEncryptor(n.create(b.slice(0,2)));this._des2=m.createEncryptor(n.create(b.slice(2,4)));this._des3= +m.createEncryptor(n.create(b.slice(4,6)))},encryptBlock:function(b,c){this._des1.encryptBlock(b,c);this._des2.decryptBlock(b,c);this._des3.encryptBlock(b,c)},decryptBlock:function(b,c){this._des3.decryptBlock(b,c);this._des2.encryptBlock(b,c);this._des1.decryptBlock(b,c)},keySize:6,ivSize:2,blockSize:2});h.TripleDES=e._createHelper(g)})(); +/* +CryptoJS v3.1.2 sha1-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var k=CryptoJS,b=k.lib,m=b.WordArray,l=b.Hasher,d=[],b=k.algo.SHA1=l.extend({_doReset:function(){this._hash=new m.init([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(n,p){for(var a=this._hash.words,e=a[0],f=a[1],h=a[2],j=a[3],b=a[4],c=0;80>c;c++){if(16>c)d[c]=n[p+c]|0;else{var g=d[c-3]^d[c-8]^d[c-14]^d[c-16];d[c]=g<<1|g>>>31}g=(e<<5|e>>>27)+b+d[c];g=20>c?g+((f&h|~f&j)+1518500249):40>c?g+((f^h^j)+1859775393):60>c?g+((f&h|f&j|h&j)-1894007588):g+((f^h^ +j)-899497514);b=j;j=h;h=f<<30|f>>>2;f=e;e=g}a[0]=a[0]+e|0;a[1]=a[1]+f|0;a[2]=a[2]+h|0;a[3]=a[3]+j|0;a[4]=a[4]+b|0},_doFinalize:function(){var b=this._data,d=b.words,a=8*this._nDataBytes,e=8*b.sigBytes;d[e>>>5]|=128<<24-e%32;d[(e+64>>>9<<4)+14]=Math.floor(a/4294967296);d[(e+64>>>9<<4)+15]=a;b.sigBytes=4*d.length;this._process();return this._hash},clone:function(){var b=l.clone.call(this);b._hash=this._hash.clone();return b}});k.SHA1=l._createHelper(b);k.HmacSHA1=l._createHmacHelper(b)})(); +/* +CryptoJS v3.1.2 ripemd160-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +/* -// crypto -bitcore.crypto = {}; -bitcore.crypto.BN = require('./lib/crypto/bn'); -bitcore.crypto.ECDSA = require('./lib/crypto/ecdsa'); -bitcore.crypto.Hash = require('./lib/crypto/hash'); -bitcore.crypto.Random = require('./lib/crypto/random'); -bitcore.crypto.Point = require('./lib/crypto/point'); -bitcore.crypto.Signature = require('./lib/crypto/signature'); +(c) 2012 by Cedric Mesnil. All rights reserved. -// encoding -bitcore.encoding = {}; -bitcore.encoding.Base58 = require('./lib/encoding/base58'); -bitcore.encoding.Base58Check = require('./lib/encoding/base58check'); -bitcore.encoding.BufferReader = require('./lib/encoding/bufferreader'); -bitcore.encoding.BufferWriter = require('./lib/encoding/bufferwriter'); -bitcore.encoding.Varint = require('./lib/encoding/varint'); +Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: -// utilities -bitcore.util = {}; -bitcore.util.buffer = require('./lib/util/buffer'); -bitcore.util.js = require('./lib/util/js'); -bitcore.util.preconditions = require('./lib/util/preconditions'); + - Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. + - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. -// errors thrown by the library -bitcore.errors = require('./lib/errors'); +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ +(function(){var q=CryptoJS,d=q.lib,n=d.WordArray,p=d.Hasher,d=q.algo,x=n.create([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,7,4,13,1,10,6,15,3,12,0,9,5,2,14,11,8,3,10,14,4,9,15,8,1,2,7,0,6,13,11,5,12,1,9,11,10,0,8,12,4,13,3,7,15,14,5,6,2,4,0,5,9,7,12,2,10,14,1,3,8,11,6,15,13]),y=n.create([5,14,7,0,9,2,11,4,13,6,15,8,1,10,3,12,6,11,3,7,0,13,5,10,14,15,8,12,4,9,1,2,15,5,1,3,7,14,6,9,11,8,12,2,10,0,4,13,8,6,4,1,3,11,15,0,5,12,2,13,9,7,10,14,12,15,10,4,1,5,8,7,6,2,13,14,0,3,9,11]),z=n.create([11,14,15,12, +5,8,7,9,11,13,14,15,6,7,9,8,7,6,8,13,11,9,7,15,7,12,15,9,11,7,13,12,11,13,6,7,14,9,13,15,14,8,13,6,5,12,7,5,11,12,14,15,14,15,9,8,9,14,5,6,8,6,5,12,9,15,5,11,6,8,13,12,5,12,13,14,11,8,5,6]),A=n.create([8,9,9,11,13,15,15,5,7,7,8,11,14,14,12,6,9,13,15,7,12,8,9,11,7,7,12,7,6,15,13,11,9,7,15,11,8,6,6,14,12,13,5,14,13,13,7,5,15,5,8,11,14,14,6,14,6,9,12,9,12,5,15,8,8,5,12,9,12,5,14,6,8,13,6,5,15,13,11,11]),B=n.create([0,1518500249,1859775393,2400959708,2840853838]),C=n.create([1352829926,1548603684,1836072691, +2053994217,0]),d=d.RIPEMD160=p.extend({_doReset:function(){this._hash=n.create([1732584193,4023233417,2562383102,271733878,3285377520])},_doProcessBlock:function(e,v){for(var b=0;16>b;b++){var c=v+b,f=e[c];e[c]=(f<<8|f>>>24)&16711935|(f<<24|f>>>8)&4278255360}var c=this._hash.words,f=B.words,d=C.words,n=x.words,q=y.words,p=z.words,w=A.words,t,g,h,j,r,u,k,l,m,s;u=t=c[0];k=g=c[1];l=h=c[2];m=j=c[3];s=r=c[4];for(var a,b=0;80>b;b+=1)a=t+e[v+n[b]]|0,a=16>b?a+((g^h^j)+f[0]):32>b?a+((g&h|~g&j)+f[1]):48>b? +a+(((g|~h)^j)+f[2]):64>b?a+((g&j|h&~j)+f[3]):a+((g^(h|~j))+f[4]),a|=0,a=a<>>32-p[b],a=a+r|0,t=r,r=j,j=h<<10|h>>>22,h=g,g=a,a=u+e[v+q[b]]|0,a=16>b?a+((k^(l|~m))+d[0]):32>b?a+((k&m|l&~m)+d[1]):48>b?a+(((k|~l)^m)+d[2]):64>b?a+((k&l|~k&m)+d[3]):a+((k^l^m)+d[4]),a|=0,a=a<>>32-w[b],a=a+s|0,u=s,s=m,m=l<<10|l>>>22,l=k,k=a;a=c[1]+h+m|0;c[1]=c[2]+j+s|0;c[2]=c[3]+r+u|0;c[3]=c[4]+t+k|0;c[4]=c[0]+g+l|0;c[0]=a},_doFinalize:function(){var e=this._data,d=e.words,b=8*this._nDataBytes,c=8*e.sigBytes; +d[c>>>5]|=128<<24-c%32;d[(c+64>>>9<<4)+14]=(b<<8|b>>>24)&16711935|(b<<24|b>>>8)&4278255360;e.sigBytes=4*(d.length+1);this._process();e=this._hash;d=e.words;for(b=0;5>b;b++)c=d[b],d[b]=(c<<8|c>>>24)&16711935|(c<<24|c>>>8)&4278255360;return e},clone:function(){var d=p.clone.call(this);d._hash=this._hash.clone();return d}});q.RIPEMD160=p._createHelper(d);q.HmacRIPEMD160=p._createHmacHelper(d)})(Math); +/* +CryptoJS v3.1.2 pbkdf2-min.js +code.google.com/p/crypto-js +(c) 2009-2013 by Jeff Mott. All rights reserved. +code.google.com/p/crypto-js/wiki/License +*/ +(function(){var b=CryptoJS,a=b.lib,d=a.Base,m=a.WordArray,a=b.algo,q=a.HMAC,l=a.PBKDF2=d.extend({cfg:d.extend({keySize:4,hasher:a.SHA1,iterations:1}),init:function(a){this.cfg=this.cfg.extend(a)},compute:function(a,b){for(var c=this.cfg,f=q.create(c.hasher,a),g=m.create(),d=m.create([1]),l=g.words,r=d.words,n=c.keySize,c=c.iterations;l.length>6)+b64map.charAt(e&63)}if(b+1==d.length){e=parseInt(d.substring(b,b+1),16);a+=b64map.charAt(e<<2)}else{if(b+2==d.length){e=parseInt(d.substring(b,b+2),16);a+=b64map.charAt(e>>2)+b64map.charAt((e&3)<<4)}}if(b64pad){while((a.length&3)>0){a+=b64pad}}return a}function b64tohex(f){var d="";var e;var b=0;var c;var a;for(e=0;e>2);c=a&3;b=1}else{if(b==1){d+=int2char((c<<2)|(a>>4));c=a&15;b=2}else{if(b==2){d+=int2char(c);d+=int2char(a>>2);c=a&3;b=3}else{d+=int2char((c<<2)|(a>>4));d+=int2char(a&15);b=0}}}}if(b==1){d+=int2char(c<<2)}return d}function b64toBA(e){var d=b64tohex(e);var c;var b=new Array();for(c=0;2*c=0){var d=a*this[f++]+b[e]+h;h=Math.floor(d/67108864);b[e++]=d&67108863}return h}function am2(f,q,r,e,o,a){var k=q&32767,p=q>>15;while(--a>=0){var d=this[f]&32767;var g=this[f++]>>15;var b=p*d+g*k;d=k*d+((b&32767)<<15)+r[e]+(o&1073741823);o=(d>>>30)+(b>>>15)+p*g+(o>>>30);r[e++]=d&1073741823}return o}function am3(f,q,r,e,o,a){var k=q&16383,p=q>>14;while(--a>=0){var d=this[f]&16383;var g=this[f++]>>14;var b=p*d+g*k;d=k*d+((b&16383)<<14)+r[e]+o;o=(d>>28)+(b>>14)+p*g;r[e++]=d&268435455}return o}if(j_lm&&(navigator.appName=="Microsoft Internet Explorer")){BigInteger.prototype.am=am2;dbits=30}else{if(j_lm&&(navigator.appName!="Netscape")){BigInteger.prototype.am=am1;dbits=26}else{BigInteger.prototype.am=am3;dbits=28}}BigInteger.prototype.DB=dbits;BigInteger.prototype.DM=((1<=0;--a){b[a]=this[a]}b.t=this.t;b.s=this.s}function bnpFromInt(a){this.t=1;this.s=(a<0)?-1:0;if(a>0){this[0]=a}else{if(a<-1){this[0]=a+this.DV}else{this.t=0}}}function nbv(a){var b=nbi();b.fromInt(a);return b}function bnpFromString(h,c){var e;if(c==16){e=4}else{if(c==8){e=3}else{if(c==256){e=8}else{if(c==2){e=1}else{if(c==32){e=5}else{if(c==4){e=2}else{this.fromRadix(h,c);return}}}}}}this.t=0;this.s=0;var g=h.length,d=false,f=0;while(--g>=0){var a=(e==8)?h[g]&255:intAt(h,g);if(a<0){if(h.charAt(g)=="-"){d=true}continue}d=false;if(f==0){this[this.t++]=a}else{if(f+e>this.DB){this[this.t-1]|=(a&((1<<(this.DB-f))-1))<>(this.DB-f))}else{this[this.t-1]|=a<=this.DB){f-=this.DB}}if(e==8&&(h[0]&128)!=0){this.s=-1;if(f>0){this[this.t-1]|=((1<<(this.DB-f))-1)<0&&this[this.t-1]==a){--this.t}}function bnToString(c){if(this.s<0){return"-"+this.negate().toString(c)}var e;if(c==16){e=4}else{if(c==8){e=3}else{if(c==2){e=1}else{if(c==32){e=5}else{if(c==4){e=2}else{return this.toRadix(c)}}}}}var g=(1<0){if(j>j)>0){a=true;h=int2char(l)}while(f>=0){if(j>(j+=this.DB-e)}else{l=(this[f]>>(j-=e))&g;if(j<=0){j+=this.DB;--f}}if(l>0){a=true}if(a){h+=int2char(l)}}}return a?h:"0"}function bnNegate(){var a=nbi();BigInteger.ZERO.subTo(this,a);return a}function bnAbs(){return(this.s<0)?this.negate():this}function bnCompareTo(b){var d=this.s-b.s;if(d!=0){return d}var c=this.t;d=c-b.t;if(d!=0){return(this.s<0)?-d:d}while(--c>=0){if((d=this[c]-b[c])!=0){return d}}return 0}function nbits(a){var c=1,b;if((b=a>>>16)!=0){a=b;c+=16}if((b=a>>8)!=0){a=b;c+=8}if((b=a>>4)!=0){a=b;c+=4}if((b=a>>2)!=0){a=b;c+=2}if((b=a>>1)!=0){a=b;c+=1}return c}function bnBitLength(){if(this.t<=0){return 0}return this.DB*(this.t-1)+nbits(this[this.t-1]^(this.s&this.DM))}function bnpDLShiftTo(c,b){var a;for(a=this.t-1;a>=0;--a){b[a+c]=this[a]}for(a=c-1;a>=0;--a){b[a]=0}b.t=this.t+c;b.s=this.s}function bnpDRShiftTo(c,b){for(var a=c;a=0;--d){e[d+f+1]=(this[d]>>a)|h;h=(this[d]&g)<=0;--d){e[d]=0}e[f]=h;e.t=this.t+f+1;e.s=this.s;e.clamp()}function bnpRShiftTo(g,d){d.s=this.s;var e=Math.floor(g/this.DB);if(e>=this.t){d.t=0;return}var b=g%this.DB;var a=this.DB-b;var f=(1<>b;for(var c=e+1;c>b}if(b>0){d[this.t-e-1]|=(this.s&f)<>=this.DB}if(d.t>=this.DB}g+=this.s}else{g+=this.s;while(e>=this.DB}g-=d.s}f.s=(g<0)?-1:0;if(g<-1){f[e++]=this.DV+g}else{if(g>0){f[e++]=g}}f.t=e;f.clamp()}function bnpMultiplyTo(c,e){var b=this.abs(),f=c.abs();var d=b.t;e.t=d+f.t;while(--d>=0){e[d]=0}for(d=0;d=0){d[b]=0}for(b=0;b=a.DV){d[b+a.t]-=a.DV;d[b+a.t+1]=1}}if(d.t>0){d[d.t-1]+=a.am(b,a[b],d,2*b,0,1)}d.s=0;d.clamp()}function bnpDivRemTo(n,h,g){var w=n.abs();if(w.t<=0){return}var k=this.abs();if(k.t0){w.lShiftTo(v,d);k.lShiftTo(v,g)}else{w.copyTo(d);k.copyTo(g)}var p=d.t;var b=d[p-1];if(b==0){return}var o=b*(1<1)?d[p-2]>>this.F2:0);var A=this.FV/o,z=(1<=0){g[g.t++]=1;g.subTo(f,g)}BigInteger.ONE.dlShiftTo(p,f);f.subTo(d,d);while(d.t=0){var c=(g[--u]==b)?this.DM:Math.floor(g[u]*A+(g[u-1]+x)*z);if((g[u]+=d.am(0,c,g,s,0,p))0){g.rShiftTo(v,g)}if(a<0){BigInteger.ZERO.subTo(g,g)}}function bnMod(b){var c=nbi();this.abs().divRemTo(b,null,c);if(this.s<0&&c.compareTo(BigInteger.ZERO)>0){b.subTo(c,c)}return c}function Classic(a){this.m=a}function cConvert(a){if(a.s<0||a.compareTo(this.m)>=0){return a.mod(this.m)}else{return a}}function cRevert(a){return a}function cReduce(a){a.divRemTo(this.m,null,a)}function cMulTo(a,c,b){a.multiplyTo(c,b);this.reduce(b)}function cSqrTo(a,b){a.squareTo(b);this.reduce(b)}Classic.prototype.convert=cConvert;Classic.prototype.revert=cRevert;Classic.prototype.reduce=cReduce;Classic.prototype.mulTo=cMulTo;Classic.prototype.sqrTo=cSqrTo;function bnpInvDigit(){if(this.t<1){return 0}var a=this[0];if((a&1)==0){return 0}var b=a&3;b=(b*(2-(a&15)*b))&15;b=(b*(2-(a&255)*b))&255;b=(b*(2-(((a&65535)*b)&65535)))&65535;b=(b*(2-a*b%this.DV))%this.DV;return(b>0)?this.DV-b:-b}function Montgomery(a){this.m=a;this.mp=a.invDigit();this.mpl=this.mp&32767;this.mph=this.mp>>15;this.um=(1<<(a.DB-15))-1;this.mt2=2*a.t}function montConvert(a){var b=nbi();a.abs().dlShiftTo(this.m.t,b);b.divRemTo(this.m,null,b);if(a.s<0&&b.compareTo(BigInteger.ZERO)>0){this.m.subTo(b,b)}return b}function montRevert(a){var b=nbi();a.copyTo(b);this.reduce(b);return b}function montReduce(a){while(a.t<=this.mt2){a[a.t++]=0}for(var c=0;c>15)*this.mpl)&this.um)<<15))&a.DM;b=c+this.m.t;a[b]+=this.m.am(0,d,a,c,0,this.m.t);while(a[b]>=a.DV){a[b]-=a.DV;a[++b]++}}a.clamp();a.drShiftTo(this.m.t,a);if(a.compareTo(this.m)>=0){a.subTo(this.m,a)}}function montSqrTo(a,b){a.squareTo(b);this.reduce(b)}function montMulTo(a,c,b){a.multiplyTo(c,b);this.reduce(b)}Montgomery.prototype.convert=montConvert;Montgomery.prototype.revert=montRevert;Montgomery.prototype.reduce=montReduce;Montgomery.prototype.mulTo=montMulTo;Montgomery.prototype.sqrTo=montSqrTo;function bnpIsEven(){return((this.t>0)?(this[0]&1):this.s)==0}function bnpExp(h,j){if(h>4294967295||h<1){return BigInteger.ONE}var f=nbi(),a=nbi(),d=j.convert(this),c=nbits(h)-1;d.copyTo(f);while(--c>=0){j.sqrTo(f,a);if((h&(1<0){j.mulTo(a,d,f)}else{var b=f;f=a;a=b}}return j.revert(f)}function bnModPowInt(b,a){var c;if(b<256||a.isEven()){c=new Classic(a)}else{c=new Montgomery(a)}return this.exp(b,c)}BigInteger.prototype.copyTo=bnpCopyTo;BigInteger.prototype.fromInt=bnpFromInt;BigInteger.prototype.fromString=bnpFromString;BigInteger.prototype.clamp=bnpClamp;BigInteger.prototype.dlShiftTo=bnpDLShiftTo;BigInteger.prototype.drShiftTo=bnpDRShiftTo;BigInteger.prototype.lShiftTo=bnpLShiftTo;BigInteger.prototype.rShiftTo=bnpRShiftTo;BigInteger.prototype.subTo=bnpSubTo;BigInteger.prototype.multiplyTo=bnpMultiplyTo;BigInteger.prototype.squareTo=bnpSquareTo;BigInteger.prototype.divRemTo=bnpDivRemTo;BigInteger.prototype.invDigit=bnpInvDigit;BigInteger.prototype.isEven=bnpIsEven;BigInteger.prototype.exp=bnpExp;BigInteger.prototype.toString=bnToString;BigInteger.prototype.negate=bnNegate;BigInteger.prototype.abs=bnAbs;BigInteger.prototype.compareTo=bnCompareTo;BigInteger.prototype.bitLength=bnBitLength;BigInteger.prototype.mod=bnMod;BigInteger.prototype.modPowInt=bnModPowInt;BigInteger.ZERO=nbv(0);BigInteger.ONE=nbv(1); +/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ + */ +function bnClone(){var a=nbi();this.copyTo(a);return a}function bnIntValue(){if(this.s<0){if(this.t==1){return this[0]-this.DV}else{if(this.t==0){return -1}}}else{if(this.t==1){return this[0]}else{if(this.t==0){return 0}}}return((this[1]&((1<<(32-this.DB))-1))<>24}function bnShortValue(){return(this.t==0)?this.s:(this[0]<<16)>>16}function bnpChunkSize(a){return Math.floor(Math.LN2*this.DB/Math.log(a))}function bnSigNum(){if(this.s<0){return -1}else{if(this.t<=0||(this.t==1&&this[0]<=0)){return 0}else{return 1}}}function bnpToRadix(c){if(c==null){c=10}if(this.signum()==0||c<2||c>36){return"0"}var f=this.chunkSize(c);var e=Math.pow(c,f);var i=nbv(e),j=nbi(),h=nbi(),g="";this.divRemTo(i,j,h);while(j.signum()>0){g=(e+h.intValue()).toString(c).substr(1)+g;j.divRemTo(i,j,h)}return h.intValue().toString(c)+g}function bnpFromRadix(m,h){this.fromInt(0);if(h==null){h=10}var f=this.chunkSize(h);var g=Math.pow(h,f),e=false,a=0,l=0;for(var c=0;c=f){this.dMultiply(g);this.dAddOffset(l,0);a=0;l=0}}if(a>0){this.dMultiply(Math.pow(h,a));this.dAddOffset(l,0)}if(e){BigInteger.ZERO.subTo(this,this)}}function bnpFromNumber(f,e,h){if("number"==typeof e){if(f<2){this.fromInt(1)}else{this.fromNumber(f,h);if(!this.testBit(f-1)){this.bitwiseTo(BigInteger.ONE.shiftLeft(f-1),op_or,this)}if(this.isEven()){this.dAddOffset(1,0)}while(!this.isProbablePrime(e)){this.dAddOffset(2,0);if(this.bitLength()>f){this.subTo(BigInteger.ONE.shiftLeft(f-1),this)}}}}else{var d=new Array(),g=f&7;d.length=(f>>3)+1;e.nextBytes(d);if(g>0){d[0]&=((1<0){if(e>e)!=(this.s&this.DM)>>e){c[a++]=f|(this.s<<(this.DB-e))}while(b>=0){if(e<8){f=(this[b]&((1<>(e+=this.DB-8)}else{f=(this[b]>>(e-=8))&255;if(e<=0){e+=this.DB;--b}}if((f&128)!=0){f|=-256}if(a==0&&(this.s&128)!=(f&128)){++a}if(a>0||f!=this.s){c[a++]=f}}}return c}function bnEquals(b){return(this.compareTo(b)==0)}function bnMin(b){return(this.compareTo(b)<0)?this:b}function bnMax(b){return(this.compareTo(b)>0)?this:b}function bnpBitwiseTo(c,h,e){var d,g,b=Math.min(c.t,this.t);for(d=0;d>=16;b+=16}if((a&255)==0){a>>=8;b+=8}if((a&15)==0){a>>=4;b+=4}if((a&3)==0){a>>=2;b+=2}if((a&1)==0){++b}return b}function bnGetLowestSetBit(){for(var a=0;a=this.t){return(this.s!=0)}return((this[a]&(1<<(b%this.DB)))!=0)}function bnpChangeBit(c,b){var a=BigInteger.ONE.shiftLeft(c);this.bitwiseTo(a,b,a);return a}function bnSetBit(a){return this.changeBit(a,op_or)}function bnClearBit(a){return this.changeBit(a,op_andnot)}function bnFlipBit(a){return this.changeBit(a,op_xor)}function bnpAddTo(d,f){var e=0,g=0,b=Math.min(d.t,this.t);while(e>=this.DB}if(d.t>=this.DB}g+=this.s}else{g+=this.s;while(e>=this.DB}g+=d.s}f.s=(g<0)?-1:0;if(g>0){f[e++]=g}else{if(g<-1){f[e++]=this.DV+g}}f.t=e;f.clamp()}function bnAdd(b){var c=nbi();this.addTo(b,c);return c}function bnSubtract(b){var c=nbi();this.subTo(b,c);return c}function bnMultiply(b){var c=nbi();this.multiplyTo(b,c);return c}function bnSquare(){var a=nbi();this.squareTo(a);return a}function bnDivide(b){var c=nbi();this.divRemTo(b,c,null);return c}function bnRemainder(b){var c=nbi();this.divRemTo(b,null,c);return c}function bnDivideAndRemainder(b){var d=nbi(),c=nbi();this.divRemTo(b,d,c);return new Array(d,c)}function bnpDMultiply(a){this[this.t]=this.am(0,a-1,this,0,0,this.t);++this.t;this.clamp()}function bnpDAddOffset(b,a){if(b==0){return}while(this.t<=a){this[this.t++]=0}this[a]+=b;while(this[a]>=this.DV){this[a]-=this.DV;if(++a>=this.t){this[this.t++]=0}++this[a]}}function NullExp(){}function nNop(a){return a}function nMulTo(a,c,b){a.multiplyTo(c,b)}function nSqrTo(a,b){a.squareTo(b)}NullExp.prototype.convert=nNop;NullExp.prototype.revert=nNop;NullExp.prototype.mulTo=nMulTo;NullExp.prototype.sqrTo=nSqrTo;function bnPow(a){return this.exp(a,new NullExp())}function bnpMultiplyLowerTo(b,f,e){var d=Math.min(this.t+b.t,f);e.s=0;e.t=d;while(d>0){e[--d]=0}var c;for(c=e.t-this.t;d=0){d[c]=0}for(c=Math.max(e-this.t,0);c2*this.m.t){return a.mod(this.m)}else{if(a.compareTo(this.m)<0){return a}else{var b=nbi();a.copyTo(b);this.reduce(b);return b}}}function barrettRevert(a){return a}function barrettReduce(a){a.drShiftTo(this.m.t-1,this.r2);if(a.t>this.m.t+1){a.t=this.m.t+1;a.clamp()}this.mu.multiplyUpperTo(this.r2,this.m.t+1,this.q3);this.m.multiplyLowerTo(this.q3,this.m.t+1,this.r2);while(a.compareTo(this.r2)<0){a.dAddOffset(1,this.m.t+1)}a.subTo(this.r2,a);while(a.compareTo(this.m)>=0){a.subTo(this.m,a)}}function barrettSqrTo(a,b){a.squareTo(b);this.reduce(b)}function barrettMulTo(a,c,b){a.multiplyTo(c,b);this.reduce(b)}Barrett.prototype.convert=barrettConvert;Barrett.prototype.revert=barrettRevert;Barrett.prototype.reduce=barrettReduce;Barrett.prototype.mulTo=barrettMulTo;Barrett.prototype.sqrTo=barrettSqrTo;function bnModPow(q,f){var o=q.bitLength(),h,b=nbv(1),v;if(o<=0){return b}else{if(o<18){h=1}else{if(o<48){h=3}else{if(o<144){h=4}else{if(o<768){h=5}else{h=6}}}}}if(o<8){v=new Classic(f)}else{if(f.isEven()){v=new Barrett(f)}else{v=new Montgomery(f)}}var p=new Array(),d=3,s=h-1,a=(1<1){var A=nbi();v.sqrTo(p[1],A);while(d<=a){p[d]=nbi();v.mulTo(A,p[d-2],p[d]);d+=2}}var l=q.t-1,x,u=true,c=nbi(),y;o=nbits(q[l])-1;while(l>=0){if(o>=s){x=(q[l]>>(o-s))&a}else{x=(q[l]&((1<<(o+1))-1))<<(s-o);if(l>0){x|=q[l-1]>>(this.DB+o-s)}}d=h;while((x&1)==0){x>>=1;--d}if((o-=d)<0){o+=this.DB;--l}if(u){p[x].copyTo(b);u=false}else{while(d>1){v.sqrTo(b,c);v.sqrTo(c,b);d-=2}if(d>0){v.sqrTo(b,c)}else{y=b;b=c;c=y}v.mulTo(c,p[x],b)}while(l>=0&&(q[l]&(1<0){b.rShiftTo(f,b);h.rShiftTo(f,h)}while(b.signum()>0){if((d=b.getLowestSetBit())>0){b.rShiftTo(d,b)}if((d=h.getLowestSetBit())>0){h.rShiftTo(d,h)}if(b.compareTo(h)>=0){b.subTo(h,b);b.rShiftTo(1,b)}else{h.subTo(b,h);h.rShiftTo(1,h)}}if(f>0){h.lShiftTo(f,h)}return h}function bnpModInt(e){if(e<=0){return 0}var c=this.DV%e,b=(this.s<0)?e-1:0;if(this.t>0){if(c==0){b=this[0]%e}else{for(var a=this.t-1;a>=0;--a){b=(c*b+this[a])%e}}}return b}function bnModInverse(f){var j=f.isEven();if((this.isEven()&&j)||f.signum()==0){return BigInteger.ZERO}var i=f.clone(),h=this.clone();var g=nbv(1),e=nbv(0),l=nbv(0),k=nbv(1);while(i.signum()!=0){while(i.isEven()){i.rShiftTo(1,i);if(j){if(!g.isEven()||!e.isEven()){g.addTo(this,g);e.subTo(f,e)}g.rShiftTo(1,g)}else{if(!e.isEven()){e.subTo(f,e)}}e.rShiftTo(1,e)}while(h.isEven()){h.rShiftTo(1,h);if(j){if(!l.isEven()||!k.isEven()){l.addTo(this,l);k.subTo(f,k)}l.rShiftTo(1,l)}else{if(!k.isEven()){k.subTo(f,k)}}k.rShiftTo(1,k)}if(i.compareTo(h)>=0){i.subTo(h,i);if(j){g.subTo(l,g)}e.subTo(k,e)}else{h.subTo(i,h);if(j){l.subTo(g,l)}k.subTo(e,k)}}if(h.compareTo(BigInteger.ONE)!=0){return BigInteger.ZERO}if(k.compareTo(f)>=0){return k.subtract(f)}if(k.signum()<0){k.addTo(f,k)}else{return k}if(k.signum()<0){return k.add(f)}else{return k}}var lowprimes=[2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53,59,61,67,71,73,79,83,89,97,101,103,107,109,113,127,131,137,139,149,151,157,163,167,173,179,181,191,193,197,199,211,223,227,229,233,239,241,251,257,263,269,271,277,281,283,293,307,311,313,317,331,337,347,349,353,359,367,373,379,383,389,397,401,409,419,421,431,433,439,443,449,457,461,463,467,479,487,491,499,503,509,521,523,541,547,557,563,569,571,577,587,593,599,601,607,613,617,619,631,641,643,647,653,659,661,673,677,683,691,701,709,719,727,733,739,743,751,757,761,769,773,787,797,809,811,821,823,827,829,839,853,857,859,863,877,881,883,887,907,911,919,929,937,941,947,953,967,971,977,983,991,997];var lplim=(1<<26)/lowprimes[lowprimes.length-1];function bnIsProbablePrime(e){var d,b=this.abs();if(b.t==1&&b[0]<=lowprimes[lowprimes.length-1]){for(d=0;d>1;if(f>lowprimes.length){f=lowprimes.length}var b=nbi();for(var e=0;e>8)&255;rng_pool[rng_pptr++]^=(a>>16)&255;rng_pool[rng_pptr++]^=(a>>24)&255;if(rng_pptr>=rng_psize){rng_pptr-=rng_psize}}function rng_seed_time(){rng_seed_int(new Date().getTime())}if(rng_pool==null){rng_pool=new Array();rng_pptr=0;var t;if(navigator.appName=="Netscape"&&navigator.appVersion<"5"&&window.crypto){var z=window.crypto.random(32);for(t=0;t>>8;rng_pool[rng_pptr++]=t&255}rng_pptr=0;rng_seed_time()}function rng_get_byte(){if(rng_state==null){rng_seed_time();rng_state=prng_newstate();rng_state.init(rng_pool);for(rng_pptr=0;rng_pptr=0&&h>0){var f=e.charCodeAt(d--);if(f<128){g[--h]=f}else{if((f>127)&&(f<2048)){g[--h]=(f&63)|128;g[--h]=(f>>6)|192}else{g[--h]=(f&63)|128;g[--h]=((f>>6)&63)|128;g[--h]=(f>>12)|224}}}g[--h]=0;var b=new SecureRandom();var a=new Array();while(h>2){a[0]=0;while(a[0]==0){b.nextBytes(a)}g[--h]=a[0]}g[--h]=2;g[--h]=0;return new BigInteger(g)}function oaep_mgf1_arr(c,a,e){var b="",d=0;while(b.length>24,(d&16711680)>>16,(d&65280)>>8,d&255])));d+=1}return b}var SHA1_SIZE=20;function oaep_pad(l,a,c){if(l.length+2*SHA1_SIZE+2>a){throw"Message too long for RSA"}var h="",d;for(d=0;d0&&a.length>0){this.n=parseBigInt(b,16);this.e=parseInt(a,16)}else{alert("Invalid RSA public key")}}}function RSADoPublic(a){return a.modPowInt(this.e,this.n)}function RSAEncrypt(d){var a=pkcs1pad2(d,(this.n.bitLength()+7)>>3);if(a==null){return null}var e=this.doPublic(a);if(e==null){return null}var b=e.toString(16);if((b.length&1)==0){return b}else{return"0"+b}}function RSAEncryptOAEP(e,d){var a=oaep_pad(e,(this.n.bitLength()+7)>>3,d);if(a==null){return null}var f=this.doPublic(a);if(f==null){return null}var b=f.toString(16);if((b.length&1)==0){return b}else{return"0"+b}}RSAKey.prototype.doPublic=RSADoPublic;RSAKey.prototype.setPublic=RSASetPublic;RSAKey.prototype.encrypt=RSAEncrypt;RSAKey.prototype.encryptOAEP=RSAEncryptOAEP;RSAKey.prototype.type="RSA"; +/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ + */ +function pkcs1unpad2(g,j){var a=g.toByteArray();var f=0;while(f=a.length){return null}}var e="";while(++f191)&&(h<224)){e+=String.fromCharCode(((h&31)<<6)|(a[f+1]&63));++f}else{e+=String.fromCharCode(((h&15)<<12)|((a[f+1]&63)<<6)|(a[f+2]&63));f+=2}}}return e}function oaep_mgf1_str(c,a,e){var b="",d=0;while(b.length>24,(d&16711680)>>16,(d&65280)>>8,d&255]));d+=1}return b}var SHA1_SIZE=20;function oaep_unpad(l,b,e){l=l.toByteArray();var f;for(f=0;f0&&a.length>0){this.n=parseBigInt(c,16);this.e=parseInt(a,16);this.d=parseBigInt(b,16)}else{alert("Invalid RSA private key")}}}function RSASetPrivateEx(g,d,e,c,b,a,h,f){this.isPrivate=true;if(g==null){throw"RSASetPrivateEx N == null"}if(d==null){throw"RSASetPrivateEx E == null"}if(g.length==0){throw"RSASetPrivateEx N.length == 0"}if(d.length==0){throw"RSASetPrivateEx E.length == 0"}if(g!=null&&d!=null&&g.length>0&&d.length>0){this.n=parseBigInt(g,16);this.e=parseInt(d,16);this.d=parseBigInt(e,16);this.p=parseBigInt(c,16);this.q=parseBigInt(b,16);this.dmp1=parseBigInt(a,16);this.dmq1=parseBigInt(h,16);this.coeff=parseBigInt(f,16)}else{alert("Invalid RSA private key in RSASetPrivateEx")}}function RSAGenerate(b,i){var a=new SecureRandom();var f=b>>1;this.e=parseInt(i,16);var c=new BigInteger(i,16);for(;;){for(;;){this.p=new BigInteger(b-f,1,a);if(this.p.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE)==0&&this.p.isProbablePrime(10)){break}}for(;;){this.q=new BigInteger(f,1,a);if(this.q.subtract(BigInteger.ONE).gcd(c).compareTo(BigInteger.ONE)==0&&this.q.isProbablePrime(10)){break}}if(this.p.compareTo(this.q)<=0){var h=this.p;this.p=this.q;this.q=h}var g=this.p.subtract(BigInteger.ONE);var d=this.q.subtract(BigInteger.ONE);var e=g.multiply(d);if(e.gcd(c).compareTo(BigInteger.ONE)==0){this.n=this.p.multiply(this.q);this.d=c.modInverse(e);this.dmp1=this.d.mod(g);this.dmq1=this.d.mod(d);this.coeff=this.q.modInverse(this.p);break}}}function RSADoPrivate(a){if(this.p==null||this.q==null){return a.modPow(this.d,this.n)}var c=a.mod(this.p).modPow(this.dmp1,this.p);var b=a.mod(this.q).modPow(this.dmq1,this.q);while(c.compareTo(b)<0){c=c.add(this.p)}return c.subtract(b).multiply(this.coeff).mod(this.p).multiply(this.q).add(b)}function RSADecrypt(b){var d=parseBigInt(b,16);var a=this.doPrivate(d);if(a==null){return null}return pkcs1unpad2(a,(this.n.bitLength()+7)>>3)}function RSADecryptOAEP(d,b){var e=parseBigInt(d,16);var a=this.doPrivate(e);if(a==null){return null}return oaep_unpad(a,(this.n.bitLength()+7)>>3,b)}RSAKey.prototype.doPrivate=RSADoPrivate;RSAKey.prototype.setPrivate=RSASetPrivate;RSAKey.prototype.setPrivateEx=RSASetPrivateEx;RSAKey.prototype.generate=RSAGenerate;RSAKey.prototype.decrypt=RSADecrypt;RSAKey.prototype.decryptOAEP=RSADecryptOAEP; +/*! (c) Tom Wu | http://www-cs-students.stanford.edu/~tjw/jsbn/ + */ +function ECFieldElementFp(b,a){this.x=a;this.q=b}function feFpEquals(a){if(a==this){return true}return(this.q.equals(a.q)&&this.x.equals(a.x))}function feFpToBigInteger(){return this.x}function feFpNegate(){return new ECFieldElementFp(this.q,this.x.negate().mod(this.q))}function feFpAdd(a){return new ECFieldElementFp(this.q,this.x.add(a.toBigInteger()).mod(this.q))}function feFpSubtract(a){return new ECFieldElementFp(this.q,this.x.subtract(a.toBigInteger()).mod(this.q))}function feFpMultiply(a){return new ECFieldElementFp(this.q,this.x.multiply(a.toBigInteger()).mod(this.q))}function feFpSquare(){return new ECFieldElementFp(this.q,this.x.square().mod(this.q))}function feFpDivide(a){return new ECFieldElementFp(this.q,this.x.multiply(a.toBigInteger().modInverse(this.q)).mod(this.q))}ECFieldElementFp.prototype.equals=feFpEquals;ECFieldElementFp.prototype.toBigInteger=feFpToBigInteger;ECFieldElementFp.prototype.negate=feFpNegate;ECFieldElementFp.prototype.add=feFpAdd;ECFieldElementFp.prototype.subtract=feFpSubtract;ECFieldElementFp.prototype.multiply=feFpMultiply;ECFieldElementFp.prototype.square=feFpSquare;ECFieldElementFp.prototype.divide=feFpDivide;function ECPointFp(c,a,d,b){this.curve=c;this.x=a;this.y=d;if(b==null){this.z=BigInteger.ONE}else{this.z=b}this.zinv=null}function pointFpGetX(){if(this.zinv==null){this.zinv=this.z.modInverse(this.curve.q)}return this.curve.fromBigInteger(this.x.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpGetY(){if(this.zinv==null){this.zinv=this.z.modInverse(this.curve.q)}return this.curve.fromBigInteger(this.y.toBigInteger().multiply(this.zinv).mod(this.curve.q))}function pointFpEquals(a){if(a==this){return true}if(this.isInfinity()){return a.isInfinity()}if(a.isInfinity()){return this.isInfinity()}var c,b;c=a.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(a.z)).mod(this.curve.q);if(!c.equals(BigInteger.ZERO)){return false}b=a.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(a.z)).mod(this.curve.q);return b.equals(BigInteger.ZERO)}function pointFpIsInfinity(){if((this.x==null)&&(this.y==null)){return true}return this.z.equals(BigInteger.ZERO)&&!this.y.toBigInteger().equals(BigInteger.ZERO)}function pointFpNegate(){return new ECPointFp(this.curve,this.x,this.y.negate(),this.z)}function pointFpAdd(l){if(this.isInfinity()){return l}if(l.isInfinity()){return this}var p=l.y.toBigInteger().multiply(this.z).subtract(this.y.toBigInteger().multiply(l.z)).mod(this.curve.q);var o=l.x.toBigInteger().multiply(this.z).subtract(this.x.toBigInteger().multiply(l.z)).mod(this.curve.q);if(BigInteger.ZERO.equals(o)){if(BigInteger.ZERO.equals(p)){return this.twice()}return this.curve.getInfinity()}var j=new BigInteger("3");var e=this.x.toBigInteger();var n=this.y.toBigInteger();var c=l.x.toBigInteger();var k=l.y.toBigInteger();var m=o.square();var i=m.multiply(o);var d=e.multiply(m);var g=p.square().multiply(this.z);var a=g.subtract(d.shiftLeft(1)).multiply(l.z).subtract(i).multiply(o).mod(this.curve.q);var h=d.multiply(j).multiply(p).subtract(n.multiply(i)).subtract(g.multiply(p)).multiply(l.z).add(p.multiply(i)).mod(this.curve.q);var f=i.multiply(this.z).multiply(l.z).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(a),this.curve.fromBigInteger(h),f)}function pointFpTwice(){if(this.isInfinity()){return this}if(this.y.toBigInteger().signum()==0){return this.curve.getInfinity()}var g=new BigInteger("3");var c=this.x.toBigInteger();var h=this.y.toBigInteger();var e=h.multiply(this.z);var j=e.multiply(h).mod(this.curve.q);var i=this.curve.a.toBigInteger();var k=c.square().multiply(g);if(!BigInteger.ZERO.equals(i)){k=k.add(this.z.square().multiply(i))}k=k.mod(this.curve.q);var b=k.square().subtract(c.shiftLeft(3).multiply(j)).shiftLeft(1).multiply(e).mod(this.curve.q);var f=k.multiply(g).multiply(c).subtract(j.shiftLeft(1)).shiftLeft(2).multiply(j).subtract(k.square().multiply(k)).mod(this.curve.q);var d=e.square().multiply(e).shiftLeft(3).mod(this.curve.q);return new ECPointFp(this.curve,this.curve.fromBigInteger(b),this.curve.fromBigInteger(f),d)}function pointFpMultiply(b){if(this.isInfinity()){return this}if(b.signum()==0){return this.curve.getInfinity()}var g=b;var f=g.multiply(new BigInteger("3"));var l=this.negate();var d=this;var c;for(c=f.bitLength()-2;c>0;--c){d=d.twice();var a=f.testBit(c);var j=g.testBit(c);if(a!=j){d=d.add(a?this:l)}}return d}function pointFpMultiplyTwo(c,a,b){var d;if(c.bitLength()>b.bitLength()){d=c.bitLength()-1}else{d=b.bitLength()-1}var f=this.curve.getInfinity();var e=this.add(a);while(d>=0){f=f.twice();if(c.testBit(d)){if(b.testBit(d)){f=f.add(e)}else{f=f.add(this)}}else{if(b.testBit(d)){f=f.add(a)}}--d}return f}ECPointFp.prototype.getX=pointFpGetX;ECPointFp.prototype.getY=pointFpGetY;ECPointFp.prototype.equals=pointFpEquals;ECPointFp.prototype.isInfinity=pointFpIsInfinity;ECPointFp.prototype.negate=pointFpNegate;ECPointFp.prototype.add=pointFpAdd;ECPointFp.prototype.twice=pointFpTwice;ECPointFp.prototype.multiply=pointFpMultiply;ECPointFp.prototype.multiplyTwo=pointFpMultiplyTwo;function ECCurveFp(e,d,c){this.q=e;this.a=this.fromBigInteger(d);this.b=this.fromBigInteger(c);this.infinity=new ECPointFp(this,null,null)}function curveFpGetQ(){return this.q}function curveFpGetA(){return this.a}function curveFpGetB(){return this.b}function curveFpEquals(a){if(a==this){return true}return(this.q.equals(a.q)&&this.a.equals(a.a)&&this.b.equals(a.b))}function curveFpGetInfinity(){return this.infinity}function curveFpFromBigInteger(a){return new ECFieldElementFp(this.q,a)}function curveFpDecodePointHex(d){switch(parseInt(d.substr(0,2),16)){case 0:return this.infinity;case 2:case 3:return null;case 4:case 6:case 7:var a=(d.length-2)/2;var c=d.substr(2,a);var b=d.substr(a+2,a);return new ECPointFp(this,this.fromBigInteger(new BigInteger(c,16)),this.fromBigInteger(new BigInteger(b,16)));default:return null}}ECCurveFp.prototype.getQ=curveFpGetQ;ECCurveFp.prototype.getA=curveFpGetA;ECCurveFp.prototype.getB=curveFpGetB;ECCurveFp.prototype.equals=curveFpEquals;ECCurveFp.prototype.getInfinity=curveFpGetInfinity;ECCurveFp.prototype.fromBigInteger=curveFpFromBigInteger;ECCurveFp.prototype.decodePointHex=curveFpDecodePointHex; +/*! (c) Stefan Thomas | https://github.com/bitcoinjs/bitcoinjs-lib + */ +ECFieldElementFp.prototype.getByteLength=function(){return Math.floor((this.toBigInteger().bitLength()+7)/8)};ECPointFp.prototype.getEncoded=function(c){var d=function(h,f){var g=h.toByteArrayUnsigned();if(fg.length){g.unshift(0)}}return g};var a=this.getX().toBigInteger();var e=this.getY().toBigInteger();var b=d(a,32);if(c){if(e.isEven()){b.unshift(2)}else{b.unshift(3)}}else{b.unshift(4);b=b.concat(d(e,32))}return b};ECPointFp.decodeFrom=function(g,c){var f=c[0];var e=c.length-1;var d=c.slice(1,1+e/2);var b=c.slice(1+e/2,1+e);d.unshift(0);b.unshift(0);var a=new BigInteger(d);var h=new BigInteger(b);return new ECPointFp(g,g.fromBigInteger(a),g.fromBigInteger(h))};ECPointFp.decodeFromHex=function(g,c){var f=c.substr(0,2);var e=c.length-2;var d=c.substr(2,e/2);var b=c.substr(2+e/2,e/2);var a=new BigInteger(d,16);var h=new BigInteger(b,16);return new ECPointFp(g,g.fromBigInteger(a),g.fromBigInteger(h))};ECPointFp.prototype.add2D=function(c){if(this.isInfinity()){return c}if(c.isInfinity()){return this}if(this.x.equals(c.x)){if(this.y.equals(c.y)){return this.twice()}return this.curve.getInfinity()}var g=c.x.subtract(this.x);var e=c.y.subtract(this.y);var a=e.divide(g);var d=a.square().subtract(this.x).subtract(c.x);var f=a.multiply(this.x.subtract(d)).subtract(this.y);return new ECPointFp(this.curve,d,f)};ECPointFp.prototype.twice2D=function(){if(this.isInfinity()){return this}if(this.y.toBigInteger().signum()==0){return this.curve.getInfinity()}var b=this.curve.fromBigInteger(BigInteger.valueOf(2));var e=this.curve.fromBigInteger(BigInteger.valueOf(3));var a=this.x.square().multiply(e).add(this.curve.a).divide(this.y.multiply(b));var c=a.square().subtract(this.x.multiply(b));var d=a.multiply(this.x.subtract(c)).subtract(this.y);return new ECPointFp(this.curve,c,d)};ECPointFp.prototype.multiply2D=function(b){if(this.isInfinity()){return this}if(b.signum()==0){return this.curve.getInfinity()}var g=b;var f=g.multiply(new BigInteger("3"));var l=this.negate();var d=this;var c;for(c=f.bitLength()-2;c>0;--c){d=d.twice();var a=f.testBit(c);var j=g.testBit(c);if(a!=j){d=d.add2D(a?this:l)}}return d};ECPointFp.prototype.isOnCurve=function(){var d=this.getX().toBigInteger();var i=this.getY().toBigInteger();var f=this.curve.getA().toBigInteger();var c=this.curve.getB().toBigInteger();var h=this.curve.getQ();var e=i.multiply(i).mod(h);var g=d.multiply(d).multiply(d).add(f.multiply(d)).add(c).mod(h);return e.equals(g)};ECPointFp.prototype.toString=function(){return"("+this.getX().toBigInteger().toString()+","+this.getY().toBigInteger().toString()+")"};ECPointFp.prototype.validate=function(){var c=this.curve.getQ();if(this.isInfinity()){throw new Error("Point is at infinity.")}var a=this.getX().toBigInteger();var b=this.getY().toBigInteger();if(a.compareTo(BigInteger.ONE)<0||a.compareTo(c.subtract(BigInteger.ONE))>0){throw new Error("x coordinate out of bounds")}if(b.compareTo(BigInteger.ONE)<0||b.compareTo(c.subtract(BigInteger.ONE))>0){throw new Error("y coordinate out of bounds")}if(!this.isOnCurve()){throw new Error("Point is not on the curve.")}if(this.multiply(c).isInfinity()){throw new Error("Point is not a scalar multiple of G.")}return true}; +/*! asn1-1.0.4.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}KJUR.asn1.ASN1Util=new function(){this.integerToByteHex=function(a){var b=a.toString(16);if((b.length%2)==1){b="0"+b}return b};this.bigIntToMinTwosComplementsHex=function(j){var f=j.toString(16);if(f.substr(0,1)!="-"){if(f.length%2==1){f="0"+f}else{if(!f.match(/^[0-7]/)){f="00"+f}}}else{var a=f.substr(1);var e=a.length;if(e%2==1){e+=1}else{if(!f.match(/^[0-7]/)){e+=2}}var g="";for(var d=0;d15){throw"ASN.1 length too long to represent by 8x: n = "+i.toString(16)}var f=128+g;return f.toString(16)+h}};this.getEncodedHex=function(){if(this.hTLV==null||this.isModified){this.hV=this.getFreshValueHex();this.hL=this.getLengthHexFromValue();this.hTLV=this.hT+this.hL+this.hV;this.isModified=false}return this.hTLV};this.getValueHex=function(){this.getEncodedHex();return this.hV};this.getFreshValueHex=function(){return""}};KJUR.asn1.DERAbstractString=function(c){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);var b=null;var a=null;this.getString=function(){return this.s};this.setString=function(d){this.hTLV=null;this.isModified=true;this.s=d;this.hV=stohex(this.s)};this.setStringHex=function(d){this.hTLV=null;this.isModified=true;this.s=null;this.hV=d};this.getFreshValueHex=function(){return this.hV};if(typeof c!="undefined"){if(typeof c=="string"){this.setString(c)}else{if(typeof c.str!="undefined"){this.setString(c.str)}else{if(typeof c.hex!="undefined"){this.setStringHex(c.hex)}}}}};YAHOO.lang.extend(KJUR.asn1.DERAbstractString,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractTime=function(c){KJUR.asn1.DERAbstractTime.superclass.constructor.call(this);var b=null;var a=null;this.localDateToUTC=function(f){utc=f.getTime()+(f.getTimezoneOffset()*60000);var e=new Date(utc);return e};this.formatDate=function(j,l){var e=this.zeroPadding;var k=this.localDateToUTC(j);var m=String(k.getFullYear());if(l=="utc"){m=m.substr(2,2)}var i=e(String(k.getMonth()+1),2);var n=e(String(k.getDate()),2);var f=e(String(k.getHours()),2);var g=e(String(k.getMinutes()),2);var h=e(String(k.getSeconds()),2);return m+i+n+f+g+h+"Z"};this.zeroPadding=function(e,d){if(e.length>=d){return e}return new Array(d-e.length+1).join("0")+e};this.getString=function(){return this.s};this.setString=function(d){this.hTLV=null;this.isModified=true;this.s=d;this.hV=stohex(d)};this.setByDateValue=function(h,j,e,d,f,g){var i=new Date(Date.UTC(h,j-1,e,d,f,g,0));this.setByDate(i)};this.getFreshValueHex=function(){return this.hV}};YAHOO.lang.extend(KJUR.asn1.DERAbstractTime,KJUR.asn1.ASN1Object);KJUR.asn1.DERAbstractStructured=function(b){KJUR.asn1.DERAbstractString.superclass.constructor.call(this);var a=null;this.setByASN1ObjectArray=function(c){this.hTLV=null;this.isModified=true;this.asn1Array=c};this.appendASN1Object=function(c){this.hTLV=null;this.isModified=true;this.asn1Array.push(c)};this.asn1Array=new Array();if(typeof b!="undefined"){if(typeof b.array!="undefined"){this.asn1Array=b.array}}};YAHOO.lang.extend(KJUR.asn1.DERAbstractStructured,KJUR.asn1.ASN1Object);KJUR.asn1.DERBoolean=function(){KJUR.asn1.DERBoolean.superclass.constructor.call(this);this.hT="01";this.hTLV="0101ff"};YAHOO.lang.extend(KJUR.asn1.DERBoolean,KJUR.asn1.ASN1Object);KJUR.asn1.DERInteger=function(a){KJUR.asn1.DERInteger.superclass.constructor.call(this);this.hT="02";this.setByBigInteger=function(b){this.hTLV=null;this.isModified=true;this.hV=KJUR.asn1.ASN1Util.bigIntToMinTwosComplementsHex(b)};this.setByInteger=function(c){var b=new BigInteger(String(c),10);this.setByBigInteger(b)};this.setValueHex=function(b){this.hV=b};this.getFreshValueHex=function(){return this.hV};if(typeof a!="undefined"){if(typeof a.bigint!="undefined"){this.setByBigInteger(a.bigint)}else{if(typeof a["int"]!="undefined"){this.setByInteger(a["int"])}else{if(typeof a=="number"){this.setByInteger(a)}else{if(typeof a.hex!="undefined"){this.setValueHex(a.hex)}}}}}};YAHOO.lang.extend(KJUR.asn1.DERInteger,KJUR.asn1.ASN1Object);KJUR.asn1.DERBitString=function(a){KJUR.asn1.DERBitString.superclass.constructor.call(this);this.hT="03";this.setHexValueIncludingUnusedBits=function(b){this.hTLV=null;this.isModified=true;this.hV=b};this.setUnusedBitsAndHexValue=function(b,d){if(b<0||7=(b*2))){break}if(d>=200){break}c.push(e);g=e;d++}return c};this.getNthChildIndex_AtObj=function(d,b,e){var c=this.getPosArrayOfChildren_AtObj(d,b);return c[e]};this.getDecendantIndexByNthList=function(e,d,c){if(c.length==0){return d}var f=c.shift();var b=this.getPosArrayOfChildren_AtObj(e,d);return this.getDecendantIndexByNthList(e,b[f],c)};this.getDecendantHexTLVByNthList=function(d,c,b){var a=this.getDecendantIndexByNthList(d,c,b);return this.getHexOfTLV_AtObj(d,a)};this.getDecendantHexVByNthList=function(d,c,b){var a=this.getDecendantIndexByNthList(d,c,b);return this.getHexOfV_AtObj(d,a)}};ASN1HEX.getVbyList=function(d,c,b,e){var a=this.getDecendantIndexByNthList(d,c,b);if(a===undefined){throw"can't find nthList object"}if(e!==undefined){if(d.substr(a,2)!=e){throw"checking tag doesn't match: "+d.substr(a,2)+"!="+e}}return this.getHexOfV_AtObj(d,a)}; +/*! asn1x509-1.0.7.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.asn1=="undefined"||!KJUR.asn1){KJUR.asn1={}}if(typeof KJUR.asn1.x509=="undefined"||!KJUR.asn1.x509){KJUR.asn1.x509={}}KJUR.asn1.x509.Certificate=function(g){KJUR.asn1.x509.Certificate.superclass.constructor.call(this);var b=null;var d=null;var f=null;var c=null;var a=null;var e=null;this.setRsaPrvKeyByPEMandPass=function(i,k){var h=PKCS5PKEY.getDecryptedKeyHex(i,k);var j=new RSAKey();j.readPrivateKeyFromASN1HexString(h);this.prvKey=j};this.sign=function(){this.asn1SignatureAlg=this.asn1TBSCert.asn1SignatureAlg;sig=new KJUR.crypto.Signature({alg:"SHA1withRSA"});sig.init(this.prvKey);sig.updateHex(this.asn1TBSCert.getEncodedHex());this.hexSig=sig.sign();this.asn1Sig=new KJUR.asn1.DERBitString({hex:"00"+this.hexSig});var h=new KJUR.asn1.DERSequence({array:[this.asn1TBSCert,this.asn1SignatureAlg,this.asn1Sig]});this.hTLV=h.getEncodedHex();this.isModified=false};this.getEncodedHex=function(){if(this.isModified==false&&this.hTLV!=null){return this.hTLV}throw"not signed yet"};this.getPEMString=function(){var j=this.getEncodedHex();var h=CryptoJS.enc.Hex.parse(j);var i=CryptoJS.enc.Base64.stringify(h);var k=i.replace(/(.{64})/g,"$1\r\n");return"-----BEGIN CERTIFICATE-----\r\n"+k+"\r\n-----END CERTIFICATE-----\r\n"};if(typeof g!="undefined"){if(typeof g.tbscertobj!="undefined"){this.asn1TBSCert=g.tbscertobj}if(typeof g.prvkeyobj!="undefined"){this.prvKey=g.prvkeyobj}else{if(typeof g.rsaprvkey!="undefined"){this.prvKey=g.rsaprvkey}else{if((typeof g.rsaprvpem!="undefined")&&(typeof g.rsaprvpas!="undefined")){this.setRsaPrvKeyByPEMandPass(g.rsaprvpem,g.rsaprvpas)}}}}};YAHOO.lang.extend(KJUR.asn1.x509.Certificate,KJUR.asn1.ASN1Object);KJUR.asn1.x509.TBSCertificate=function(a){KJUR.asn1.x509.TBSCertificate.superclass.constructor.call(this);this._initialize=function(){this.asn1Array=new Array();this.asn1Version=new KJUR.asn1.DERTaggedObject({obj:new KJUR.asn1.DERInteger({"int":2})});this.asn1SerialNumber=null;this.asn1SignatureAlg=null;this.asn1Issuer=null;this.asn1NotBefore=null;this.asn1NotAfter=null;this.asn1Subject=null;this.asn1SubjPKey=null;this.extensionsArray=new Array()};this.setSerialNumberByParam=function(b){this.asn1SerialNumber=new KJUR.asn1.DERInteger(b)};this.setSignatureAlgByParam=function(b){this.asn1SignatureAlg=new KJUR.asn1.x509.AlgorithmIdentifier(b)};this.setIssuerByParam=function(b){this.asn1Issuer=new KJUR.asn1.x509.X500Name(b)};this.setNotBeforeByParam=function(b){this.asn1NotBefore=new KJUR.asn1.x509.Time(b)};this.setNotAfterByParam=function(b){this.asn1NotAfter=new KJUR.asn1.x509.Time(b)};this.setSubjectByParam=function(b){this.asn1Subject=new KJUR.asn1.x509.X500Name(b)};this.setSubjectPublicKeyByParam=function(b){this.asn1SubjPKey=new KJUR.asn1.x509.SubjectPublicKeyInfo(b)};this.setSubjectPublicKeyByGetKey=function(c){var b=KEYUTIL.getKey(c);this.asn1SubjPKey=new KJUR.asn1.x509.SubjectPublicKeyInfo(b)};this.appendExtension=function(b){this.extensionsArray.push(b)};this.appendExtensionByName=function(d,b){if(d.toLowerCase()=="basicconstraints"){var c=new KJUR.asn1.x509.BasicConstraints(b);this.appendExtension(c)}else{if(d.toLowerCase()=="keyusage"){var c=new KJUR.asn1.x509.KeyUsage(b);this.appendExtension(c)}else{if(d.toLowerCase()=="crldistributionpoints"){var c=new KJUR.asn1.x509.CRLDistributionPoints(b);this.appendExtension(c)}else{if(d.toLowerCase()=="extkeyusage"){var c=new KJUR.asn1.x509.ExtKeyUsage(b);this.appendExtension(c)}else{throw"unsupported extension name: "+d}}}}};this.getEncodedHex=function(){if(this.asn1NotBefore==null||this.asn1NotAfter==null){throw"notBefore and/or notAfter not set"}var c=new KJUR.asn1.DERSequence({array:[this.asn1NotBefore,this.asn1NotAfter]});this.asn1Array=new Array();this.asn1Array.push(this.asn1Version);this.asn1Array.push(this.asn1SerialNumber);this.asn1Array.push(this.asn1SignatureAlg);this.asn1Array.push(this.asn1Issuer);this.asn1Array.push(c);this.asn1Array.push(this.asn1Subject);this.asn1Array.push(this.asn1SubjPKey);if(this.extensionsArray.length>0){var d=new KJUR.asn1.DERSequence({array:this.extensionsArray});var b=new KJUR.asn1.DERTaggedObject({explicit:true,tag:"a3",obj:d});this.asn1Array.push(b)}var e=new KJUR.asn1.DERSequence({array:this.asn1Array});this.hTLV=e.getEncodedHex();this.isModified=false;return this.hTLV};this._initialize()};YAHOO.lang.extend(KJUR.asn1.x509.TBSCertificate,KJUR.asn1.ASN1Object);KJUR.asn1.x509.Extension=function(b){KJUR.asn1.x509.Extension.superclass.constructor.call(this);var a=null;this.getEncodedHex=function(){var f=new KJUR.asn1.DERObjectIdentifier({oid:this.oid});var e=new KJUR.asn1.DEROctetString({hex:this.getExtnValueHex()});var d=new Array();d.push(f);if(this.critical){d.push(new KJUR.asn1.DERBoolean())}d.push(e);var c=new KJUR.asn1.DERSequence({array:d});return c.getEncodedHex()};this.critical=false;if(typeof b!="undefined"){if(typeof b.critical!="undefined"){this.critical=b.critical}}};YAHOO.lang.extend(KJUR.asn1.x509.Extension,KJUR.asn1.ASN1Object);KJUR.asn1.x509.KeyUsage=function(a){KJUR.asn1.x509.KeyUsage.superclass.constructor.call(this,a);this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.oid="2.5.29.15";if(typeof a!="undefined"){if(typeof a.bin!="undefined"){this.asn1ExtnValue=new KJUR.asn1.DERBitString(a)}}};YAHOO.lang.extend(KJUR.asn1.x509.KeyUsage,KJUR.asn1.x509.Extension);KJUR.asn1.x509.BasicConstraints=function(c){KJUR.asn1.x509.BasicConstraints.superclass.constructor.call(this,c);var a=false;var b=-1;this.getExtnValueHex=function(){var e=new Array();if(this.cA){e.push(new KJUR.asn1.DERBoolean())}if(this.pathLen>-1){e.push(new KJUR.asn1.DERInteger({"int":this.pathLen}))}var d=new KJUR.asn1.DERSequence({array:e});this.asn1ExtnValue=d;return this.asn1ExtnValue.getEncodedHex()};this.oid="2.5.29.19";this.cA=false;this.pathLen=-1;if(typeof c!="undefined"){if(typeof c.cA!="undefined"){this.cA=c.cA}if(typeof c.pathLen!="undefined"){this.pathLen=c.pathLen}}};YAHOO.lang.extend(KJUR.asn1.x509.BasicConstraints,KJUR.asn1.x509.Extension);KJUR.asn1.x509.CRLDistributionPoints=function(a){KJUR.asn1.x509.CRLDistributionPoints.superclass.constructor.call(this,a);this.getExtnValueHex=function(){return this.asn1ExtnValue.getEncodedHex()};this.setByDPArray=function(b){this.asn1ExtnValue=new KJUR.asn1.DERSequence({array:b})};this.setByOneURI=function(e){var b=new KJUR.asn1.x509.GeneralNames([{uri:e}]);var d=new KJUR.asn1.x509.DistributionPointName(b);var c=new KJUR.asn1.x509.DistributionPoint({dpobj:d});this.setByDPArray([c])};this.oid="2.5.29.31";if(typeof a!="undefined"){if(typeof a.array!="undefined"){this.setByDPArray(a.array)}else{if(typeof a.uri!="undefined"){this.setByOneURI(a.uri)}}}};YAHOO.lang.extend(KJUR.asn1.x509.CRLDistributionPoints,KJUR.asn1.x509.Extension);KJUR.asn1.x509.ExtKeyUsage=function(a){KJUR.asn1.x509.ExtKeyUsage.superclass.constructor.call(this,a);this.setPurposeArray=function(b){this.asn1ExtnValue=new KJUR.asn1.DERSequence();for(var c=0;c0){var c=new KJUR.asn1.DERSequence({array:this.aRevokedCert});this.asn1Array.push(c)}var d=new KJUR.asn1.DERSequence({array:this.asn1Array});this.hTLV=d.getEncodedHex();this.isModified=false;return this.hTLV};this._initialize=function(){this.asn1Version=null;this.asn1SignatureAlg=null;this.asn1Issuer=null;this.asn1ThisUpdate=null;this.asn1NextUpdate=null;this.aRevokedCert=new Array()};this._initialize()};YAHOO.lang.extend(KJUR.asn1.x509.TBSCertList,KJUR.asn1.ASN1Object);KJUR.asn1.x509.CRLEntry=function(c){KJUR.asn1.x509.CRLEntry.superclass.constructor.call(this);var b=null;var a=null;this.setCertSerial=function(d){this.sn=new KJUR.asn1.DERInteger(d)};this.setRevocationDate=function(d){this.time=new KJUR.asn1.x509.Time(d)};this.getEncodedHex=function(){var d=new KJUR.asn1.DERSequence({array:[this.sn,this.time]});this.TLV=d.getEncodedHex();return this.TLV};if(typeof c!="undefined"){if(typeof c.time!="undefined"){this.setRevocationDate(c.time)}if(typeof c.sn!="undefined"){this.setCertSerial(c.sn)}}};YAHOO.lang.extend(KJUR.asn1.x509.CRLEntry,KJUR.asn1.ASN1Object);KJUR.asn1.x509.X500Name=function(a){KJUR.asn1.x509.X500Name.superclass.constructor.call(this);this.asn1Array=new Array();this.setByString=function(b){var c=b.split("/");c.shift();for(var d=0;dd){throw"key is too short for SigAlg: keylen="+j+","+a}var b="0001";var k="00"+c;var g="";var l=d-b.length-k.length;for(var f=0;f=0;--p){q=q.twice2D();q.z=BigInteger.ONE;if(o.testBit(p)){if(n.testBit(p)){q=q.add2D(t)}else{q=q.add2D(s)}}else{if(n.testBit(p)){q=q.add2D(r)}}}return q}this.getBigRandom=function(i){return new BigInteger(i.bitLength(),a).mod(i.subtract(BigInteger.ONE)).add(BigInteger.ONE)};this.setNamedCurve=function(i){this.ecparams=KJUR.crypto.ECParameterDB.getByName(i);this.prvKeyHex=null;this.pubKeyHex=null;this.curveName=i};this.setPrivateKeyHex=function(i){this.isPrivate=true;this.prvKeyHex=i};this.setPublicKeyHex=function(i){this.isPublic=true;this.pubKeyHex=i};this.generateKeyPairHex=function(){var k=this.ecparams.n;var n=this.getBigRandom(k);var l=this.ecparams.G.multiply(n);var q=l.getX().toBigInteger();var o=l.getY().toBigInteger();var i=this.ecparams.keylen/4;var m=("0000000000"+n.toString(16)).slice(-i);var r=("0000000000"+q.toString(16)).slice(-i);var p=("0000000000"+o.toString(16)).slice(-i);var j="04"+r+p;this.setPrivateKeyHex(m);this.setPublicKeyHex(j);return{ecprvhex:m,ecpubhex:j}};this.signWithMessageHash=function(i){return this.signHex(i,this.prvKeyHex)};this.signHex=function(o,j){var t=new BigInteger(j,16);var l=this.ecparams.n;var q=new BigInteger(o,16);do{var m=this.getBigRandom(l);var u=this.ecparams.G;var p=u.multiply(m);var i=p.getX().toBigInteger().mod(l)}while(i.compareTo(BigInteger.ZERO)<=0);var v=m.modInverse(l).multiply(q.add(t.multiply(i))).mod(l);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(i,v)};this.sign=function(m,u){var q=u;var j=this.ecparams.n;var p=BigInteger.fromByteArrayUnsigned(m);do{var l=this.getBigRandom(j);var t=this.ecparams.G;var o=t.multiply(l);var i=o.getX().toBigInteger().mod(j)}while(i.compareTo(BigInteger.ZERO)<=0);var v=l.modInverse(j).multiply(p.add(q.multiply(i))).mod(j);return this.serializeSig(i,v)};this.verifyWithMessageHash=function(j,i){return this.verifyHex(j,i,this.pubKeyHex)};this.verifyHex=function(m,i,p){var l,j;var o=KJUR.crypto.ECDSA.parseSigHex(i);l=o.r;j=o.s;var k;k=ECPointFp.decodeFromHex(this.ecparams.curve,p);var n=new BigInteger(m,16);return this.verifyRaw(n,l,j,k)};this.verify=function(o,p,j){var l,i;if(Bitcoin.Util.isArray(p)){var n=this.parseSig(p);l=n.r;i=n.s}else{if("object"===typeof p&&p.r&&p.s){l=p.r;i=p.s}else{throw"Invalid value for signature"}}var k;if(j instanceof ECPointFp){k=j}else{if(Bitcoin.Util.isArray(j)){k=ECPointFp.decodeFrom(this.ecparams.curve,j)}else{throw"Invalid format for pubkey value, must be byte array or ECPointFp"}}var m=BigInteger.fromByteArrayUnsigned(o);return this.verifyRaw(m,l,i,k)};this.verifyRaw=function(o,i,w,m){var l=this.ecparams.n;var u=this.ecparams.G;if(i.compareTo(BigInteger.ONE)<0||i.compareTo(l)>=0){return false}if(w.compareTo(BigInteger.ONE)<0||w.compareTo(l)>=0){return false}var p=w.modInverse(l);var k=o.multiply(p).mod(l);var j=i.multiply(p).mod(l);var q=u.multiply(k).add(m.multiply(j));var t=q.getX().toBigInteger().mod(l);return t.equals(i)};this.serializeSig=function(k,j){var l=k.toByteArraySigned();var i=j.toByteArraySigned();var m=[];m.push(2);m.push(l.length);m=m.concat(l);m.push(2);m.push(i.length);m=m.concat(i);m.unshift(m.length);m.unshift(48);return m};this.parseSig=function(n){var m;if(n[0]!=48){throw new Error("Signature not a valid DERSequence")}m=2;if(n[m]!=2){throw new Error("First element in signature must be a DERInteger")}var l=n.slice(m+2,m+2+n[m+1]);m+=2+n[m+1];if(n[m]!=2){throw new Error("Second element in signature must be a DERInteger")}var i=n.slice(m+2,m+2+n[m+1]);m+=2+n[m+1];var k=BigInteger.fromByteArrayUnsigned(l);var j=BigInteger.fromByteArrayUnsigned(i);return{r:k,s:j}};this.parseSigCompact=function(m){if(m.length!==65){throw"Signature has the wrong length"}var j=m[0]-27;if(j<0||j>7){throw"Invalid signature type"}var o=this.ecparams.n;var l=BigInteger.fromByteArrayUnsigned(m.slice(1,33)).mod(o);var k=BigInteger.fromByteArrayUnsigned(m.slice(33,65)).mod(o);return{r:l,s:k,i:j}};if(h!==undefined){if(h.curve!==undefined){this.curveName=h.curve}}if(this.curveName===undefined){this.curveName=e}this.setNamedCurve(this.curveName);if(h!==undefined){if(h.prv!==undefined){this.setPrivateKeyHex(h.prv)}if(h.pub!==undefined){this.setPublicKeyHex(h.pub)}}};KJUR.crypto.ECDSA.parseSigHex=function(a){var b=KJUR.crypto.ECDSA.parseSigHexInHexRS(a);var d=new BigInteger(b.r,16);var c=new BigInteger(b.s,16);return{r:d,s:c}};KJUR.crypto.ECDSA.parseSigHexInHexRS=function(c){if(c.substr(0,2)!="30"){throw"signature is not a ASN.1 sequence"}var b=ASN1HEX.getPosArrayOfChildren_AtObj(c,0);if(b.length!=2){throw"number of signature ASN.1 sequence elements seem wrong"}var g=b[0];var f=b[1];if(c.substr(g,2)!="02"){throw"1st item of sequene of signature is not ASN.1 integer"}if(c.substr(f,2)!="02"){throw"2nd item of sequene of signature is not ASN.1 integer"}var e=ASN1HEX.getHexOfV_AtObj(c,g);var d=ASN1HEX.getHexOfV_AtObj(c,f);return{r:e,s:d}};KJUR.crypto.ECDSA.asn1SigToConcatSig=function(c){var d=KJUR.crypto.ECDSA.parseSigHexInHexRS(c);var b=d.r;var a=d.s;if(b.substr(0,2)=="00"&&(((b.length/2)*8)%(16*8))==8){b=b.substr(2)}if(a.substr(0,2)=="00"&&(((a.length/2)*8)%(16*8))==8){a=a.substr(2)}if((((b.length/2)*8)%(16*8))!=0){throw"unknown ECDSA sig r length error"}if((((a.length/2)*8)%(16*8))!=0){throw"unknown ECDSA sig s length error"}return b+a};KJUR.crypto.ECDSA.concatSigToASN1Sig=function(a){if((((a.length/2)*8)%(16*8))!=0){throw"unknown ECDSA concatinated r-s sig length error"}var c=a.substr(0,a.length/2);var b=a.substr(a.length/2);return KJUR.crypto.ECDSA.hexRSSigToASN1Sig(c,b)};KJUR.crypto.ECDSA.hexRSSigToASN1Sig=function(b,a){var d=new BigInteger(b,16);var c=new BigInteger(a,16);return KJUR.crypto.ECDSA.biRSSigToASN1Sig(d,c)};KJUR.crypto.ECDSA.biRSSigToASN1Sig=function(e,c){var b=new KJUR.asn1.DERInteger({bigint:e});var a=new KJUR.asn1.DERInteger({bigint:c});var d=new KJUR.asn1.DERSequence({array:[b,a]});return d.getEncodedHex()}; +/*! ecparam-1.0.0.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.crypto=="undefined"||!KJUR.crypto){KJUR.crypto={}}KJUR.crypto.ECParameterDB=new function(){var b={};var c={};function a(d){return new BigInteger(d,16)}this.getByName=function(e){var d=e;if(typeof c[d]!="undefined"){d=c[e]}if(typeof b[d]!="undefined"){return b[d]}throw"unregistered EC curve name: "+d};this.regist=function(A,l,o,g,m,e,j,f,k,u,d,x){b[A]={};var s=a(o);var z=a(g);var y=a(m);var t=a(e);var w=a(j);var r=new ECCurveFp(s,z,y);var q=r.decodePointHex("04"+f+k);b[A]["name"]=A;b[A]["keylen"]=l;b[A]["curve"]=r;b[A]["G"]=q;b[A]["n"]=t;b[A]["h"]=w;b[A]["oid"]=d;b[A]["info"]=x;for(var v=0;v0||K.compareTo(u)>0||BigInteger.ZERO.compareTo(J)>0||J.compareTo(u)>0){throw"invalid DSA signature"}var I=J.modInverse(u);var A=D.multiply(I).mod(u);var v=K.multiply(I).mod(u);var F=G.modPow(A,z).multiply(H.modPow(v,z)).mod(z).mod(u);return F.compareTo(K)==0};this.parseASN1Signature=function(u){try{var y=new BigInteger(ASN1HEX.getVbyList(u,0,[0],"02"),16);var v=new BigInteger(ASN1HEX.getVbyList(u,0,[1],"02"),16);return[y,v]}catch(w){throw"malformed DSA signature"}};function d(E,w,B,v,u,C){var z=KJUR.crypto.Util.hashString(w,E.toLowerCase());var z=z.substr(0,u.bitLength()/4);var A=new BigInteger(z,16);var y=n(BigInteger.ONE.add(BigInteger.ONE),u.subtract(BigInteger.ONE));var F=(B.modPow(y,v)).mod(u);var D=(y.modInverse(u).multiply(A.add(C.multiply(F)))).mod(u);var G=new Array();G[0]=F;G[1]=D;return G}function r(v){var u=openpgp.config.config.prefer_hash_algorithm;switch(Math.round(v.bitLength()/8)){case 20:if(u!=2&&u>11&&u!=10&&u<8){return 2}return u;case 28:if(u>11&&u<8){return 11}return u;case 32:if(u>10&&u<8){return 8}return u;default:util.print_debug("DSA select hash algorithm: returning null for an unknown length of q");return null}}this.select_hash_algorithm=r;function m(I,K,J,B,z,u,F,G){var C=KJUR.crypto.Util.hashString(B,I.toLowerCase());var C=C.substr(0,u.bitLength()/4);var D=new BigInteger(C,16);if(BigInteger.ZERO.compareTo(K)>0||K.compareTo(u)>0||BigInteger.ZERO.compareTo(J)>0||J.compareTo(u)>0){util.print_error("invalid DSA Signature");return null}var H=J.modInverse(u);var A=D.multiply(H).mod(u);var v=K.multiply(H).mod(u);var E=F.modPow(A,z).multiply(G.modPow(v,z)).mod(z).mod(u);return E.compareTo(K)==0}function a(z){var A=new BigInteger(z,primeCenterie);var y=j(q,512);var u=t(p,q,z);var v;do{v=new BigInteger(q.bitCount(),rand)}while(x.compareTo(BigInteger.ZERO)!=1&&x.compareTo(q)!=-1);var w=g.modPow(x,p);return{x:v,q:A,p:y,g:u,y:w}}function j(y,z,w){if(z%64!=0){return false}var u;var v;do{u=w(bitcount,true);v=u.subtract(BigInteger.ONE);u=u.subtract(v.remainder(y))}while(!u.isProbablePrime(primeCenterie)||u.bitLength()!=l);return u}function t(B,z,A,w){var u=B.subtract(BigInteger.ONE);var y=u.divide(z);var v;do{v=w(A)}while(v.compareTo(u)!=-1&&v.compareTo(BigInteger.ONE)!=1);return v.modPow(y,B)}function o(w,y,u){var v;do{v=u(y,false)}while(v.compareTo(w)!=-1&&v.compareTo(BigInteger.ZERO)!=1);return v}function i(v,w){k=o(v);var u=g.modPow(k,w).mod(v);return u}function h(B,w,y,v,z,u){var A=B(v);s=(w.modInverse(z).multiply(A.add(u.multiply(y)))).mod(z);return s}this.sign=d;this.verify=m;function n(w,u){if(u.compareTo(w)<=0){return}var v=u.subtract(w);var y=e(v.bitLength());while(y>v){y=e(v.bitLength())}return w.add(y)}function e(w){if(w<0){return null}var u=Math.floor((w+7)/8);var v=c(u);if(w%8>0){v=String.fromCharCode((Math.pow(2,w%8)-1)&v.charCodeAt(0))+v.substring(1)}return new BigInteger(f(v),16)}function c(w){var u="";for(var v=0;v=s*2){break}}var x={};x.keyhex=v.substr(0,g[o]["keylen"]*2);x.ivhex=v.substr(g[o]["keylen"]*2,g[o]["ivlen"]*2);return x};var a=function(n,t,p,u){var q=CryptoJS.enc.Base64.parse(n);var o=CryptoJS.enc.Hex.stringify(q);var s=g[t]["proc"];var r=s(o,p,u);return r};var f=function(n,q,o,s){var p=g[q]["eproc"];var r=p(n,o,s);return r};return{version:"1.0.5",getHexFromPEM:function(o,r){var p=o;if(p.indexOf("BEGIN "+r)==-1){throw"can't find PEM header: "+r}p=p.replace("-----BEGIN "+r+"-----","");p=p.replace("-----END "+r+"-----","");var q=p.replace(/\s+/g,"");var n=b64tohex(q);return n},getDecryptedKeyHexByKeyIV:function(o,r,q,p){var n=b(r);return n(o,q,p)},parsePKCS5PEM:function(n){return l(n)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(o,n,p){return h(o,n,p)},decryptKeyB64:function(n,p,o,q){return a(n,p,o,q)},getDecryptedKeyHex:function(w,v){var o=l(w);var r=o.type;var p=o.cipher;var n=o.ivsalt;var q=o.data;var u=h(p,v,n);var t=u.keyhex;var s=a(q,p,t,n);return s},getRSAKeyFromEncryptedPKCS5PEM:function(p,o){var q=this.getDecryptedKeyHex(p,o);var n=new RSAKey();n.readPrivateKeyFromASN1HexString(q);return n},getEryptedPKCS5PEMFromPrvKeyHex:function(q,x,r,p){var n="";if(typeof r=="undefined"||r==null){r="AES-256-CBC"}if(typeof g[r]=="undefined"){throw"PKCS5PKEY unsupported algorithm: "+r}if(typeof p=="undefined"||p==null){var t=g[r]["ivlen"];var s=k(t);p=s.toUpperCase()}var w=h(r,x,p);var v=w.keyhex;var u=f(q,r,v,p);var o=u.replace(/(.{64})/g,"$1\r\n");var n="-----BEGIN RSA PRIVATE KEY-----\r\n";n+="Proc-Type: 4,ENCRYPTED\r\n";n+="DEK-Info: "+r+","+p+"\r\n";n+="\r\n";n+=o;n+="\r\n-----END RSA PRIVATE KEY-----\r\n";return n},getEryptedPKCS5PEMFromRSAKey:function(C,D,o,s){var A=new KJUR.asn1.DERInteger({"int":0});var v=new KJUR.asn1.DERInteger({bigint:C.n});var z=new KJUR.asn1.DERInteger({"int":C.e});var B=new KJUR.asn1.DERInteger({bigint:C.d});var t=new KJUR.asn1.DERInteger({bigint:C.p});var r=new KJUR.asn1.DERInteger({bigint:C.q});var y=new KJUR.asn1.DERInteger({bigint:C.dmp1});var u=new KJUR.asn1.DERInteger({bigint:C.dmq1});var x=new KJUR.asn1.DERInteger({bigint:C.coeff});var E=new KJUR.asn1.DERSequence({array:[A,v,z,B,t,r,y,u,x]});var w=E.getEncodedHex();return this.getEryptedPKCS5PEMFromPrvKeyHex(w,D,o,s)},newEncryptedPKCS5PEM:function(n,o,r,s){if(typeof o=="undefined"||o==null){o=1024}if(typeof r=="undefined"||r==null){r="10001"}var p=new RSAKey();p.generate(o,r);var q=null;if(typeof s=="undefined"||s==null){q=this.getEncryptedPKCS5PEMFromRSAKey(pkey,n)}else{q=this.getEncryptedPKCS5PEMFromRSAKey(pkey,n,s)}return q},getRSAKeyFromPlainPKCS8PEM:function(p){if(p.match(/ENCRYPTED/)){throw"pem shall be not ENCRYPTED"}var o=this.getHexFromPEM(p,"PRIVATE KEY");var n=this.getRSAKeyFromPlainPKCS8Hex(o);return n},getRSAKeyFromPlainPKCS8Hex:function(q){var p=ASN1HEX.getPosArrayOfChildren_AtObj(q,0);if(p.length!=3){throw"outer DERSequence shall have 3 elements: "+p.length}var o=ASN1HEX.getHexOfTLV_AtObj(q,p[1]);if(o!="300d06092a864886f70d0101010500"){throw"PKCS8 AlgorithmIdentifier is not rsaEnc: "+o}var o=ASN1HEX.getHexOfTLV_AtObj(q,p[1]);var r=ASN1HEX.getHexOfTLV_AtObj(q,p[2]);var s=ASN1HEX.getHexOfV_AtObj(r,0);var n=new RSAKey();n.readPrivateKeyFromASN1HexString(s);return n},parseHexOfEncryptedPKCS8:function(u){var q={};var p=ASN1HEX.getPosArrayOfChildren_AtObj(u,0);if(p.length!=2){throw"malformed format: SEQUENCE(0).items != 2: "+p.length}q.ciphertext=ASN1HEX.getHexOfV_AtObj(u,p[1]);var w=ASN1HEX.getPosArrayOfChildren_AtObj(u,p[0]);if(w.length!=2){throw"malformed format: SEQUENCE(0.0).items != 2: "+w.length}if(ASN1HEX.getHexOfV_AtObj(u,w[0])!="2a864886f70d01050d"){throw"this only supports pkcs5PBES2"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(u,w[1]);if(w.length!=2){throw"malformed format: SEQUENCE(0.0.1).items != 2: "+n.length}var o=ASN1HEX.getPosArrayOfChildren_AtObj(u,n[1]);if(o.length!=2){throw"malformed format: SEQUENCE(0.0.1.1).items != 2: "+o.length}if(ASN1HEX.getHexOfV_AtObj(u,o[0])!="2a864886f70d0307"){throw"this only supports TripleDES"}q.encryptionSchemeAlg="TripleDES";q.encryptionSchemeIV=ASN1HEX.getHexOfV_AtObj(u,o[1]);var r=ASN1HEX.getPosArrayOfChildren_AtObj(u,n[0]);if(r.length!=2){throw"malformed format: SEQUENCE(0.0.1.0).items != 2: "+r.length}if(ASN1HEX.getHexOfV_AtObj(u,r[0])!="2a864886f70d01050c"){throw"this only supports pkcs5PBKDF2"}var v=ASN1HEX.getPosArrayOfChildren_AtObj(u,r[1]);if(v.length<2){throw"malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+v.length}q.pbkdf2Salt=ASN1HEX.getHexOfV_AtObj(u,v[0]);var s=ASN1HEX.getHexOfV_AtObj(u,v[1]);try{q.pbkdf2Iter=parseInt(s,16)}catch(t){throw"malformed format pbkdf2Iter: "+s}return q},getPBKDF2KeyHexFromParam:function(s,n){var r=CryptoJS.enc.Hex.parse(s.pbkdf2Salt);var o=s.pbkdf2Iter;var q=CryptoJS.PBKDF2(n,r,{keySize:192/32,iterations:o});var p=CryptoJS.enc.Hex.stringify(q);return p},getPlainPKCS8HexFromEncryptedPKCS8PEM:function(v,w){var p=this.getHexFromPEM(v,"ENCRYPTED PRIVATE KEY");var n=this.parseHexOfEncryptedPKCS8(p);var s=PKCS5PKEY.getPBKDF2KeyHexFromParam(n,w);var t={};t.ciphertext=CryptoJS.enc.Hex.parse(n.ciphertext);var r=CryptoJS.enc.Hex.parse(s);var q=CryptoJS.enc.Hex.parse(n.encryptionSchemeIV);var u=CryptoJS.TripleDES.decrypt(t,r,{iv:q});var o=CryptoJS.enc.Hex.stringify(u);return o},getRSAKeyFromEncryptedPKCS8PEM:function(q,p){var o=this.getPlainPKCS8HexFromEncryptedPKCS8PEM(q,p);var n=this.getRSAKeyFromPlainPKCS8Hex(o);return n},getKeyFromEncryptedPKCS8PEM:function(q,o){var n=this.getPlainPKCS8HexFromEncryptedPKCS8PEM(q,o);var p=this.getKeyFromPlainPrivatePKCS8Hex(n);return p},parsePlainPrivatePKCS8Hex:function(q){var o={};o.algparam=null;if(q.substr(0,2)!="30"){throw"malformed plain PKCS8 private key(code:001)"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(q,0);if(p.length!=3){throw"malformed plain PKCS8 private key(code:002)"}if(q.substr(p[1],2)!="30"){throw"malformed PKCS8 private key(code:003)"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(q,p[1]);if(n.length!=2){throw"malformed PKCS8 private key(code:004)"}if(q.substr(n[0],2)!="06"){throw"malformed PKCS8 private key(code:005)"}o.algoid=ASN1HEX.getHexOfV_AtObj(q,n[0]);if(q.substr(n[1],2)=="06"){o.algparam=ASN1HEX.getHexOfV_AtObj(q,n[1])}if(q.substr(p[2],2)!="04"){throw"malformed PKCS8 private key(code:006)"}o.keyidx=ASN1HEX.getStartPosOfV_AtObj(q,p[2]);return o},getKeyFromPlainPrivatePKCS8PEM:function(o){var n=this.getHexFromPEM(o,"PRIVATE KEY");var p=this.getKeyFromPlainPrivatePKCS8Hex(n);return p},getKeyFromPlainPrivatePKCS8Hex:function(n){var p=this.parsePlainPrivatePKCS8Hex(n);if(p.algoid=="2a864886f70d010101"){this.parsePrivateRawRSAKeyHexAtObj(n,p);var o=p.key;var q=new RSAKey();q.setPrivateEx(o.n,o.e,o.d,o.p,o.q,o.dp,o.dq,o.co);return q}else{if(p.algoid=="2a8648ce3d0201"){this.parsePrivateRawECKeyHexAtObj(n,p);if(KJUR.crypto.OID.oidhex2name[p.algparam]===undefined){throw"KJUR.crypto.OID.oidhex2name undefined: "+p.algparam}var r=KJUR.crypto.OID.oidhex2name[p.algparam];var q=new KJUR.crypto.ECDSA({curve:r,prv:p.key});return q}else{throw"unsupported private key algorithm"}}},getRSAKeyFromPublicPKCS8PEM:function(o){var p=this.getHexFromPEM(o,"PUBLIC KEY");var n=this.getRSAKeyFromPublicPKCS8Hex(p);return n},getKeyFromPublicPKCS8PEM:function(o){var p=this.getHexFromPEM(o,"PUBLIC KEY");var n=this.getKeyFromPublicPKCS8Hex(p);return n},getKeyFromPublicPKCS8Hex:function(o){var n=this.parsePublicPKCS8Hex(o);if(n.algoid=="2a864886f70d010101"){var r=this.parsePublicRawRSAKeyHex(n.key);var p=new RSAKey();p.setPublic(r.n,r.e);return p}else{if(n.algoid=="2a8648ce3d0201"){if(KJUR.crypto.OID.oidhex2name[n.algparam]===undefined){throw"KJUR.crypto.OID.oidhex2name undefined: "+n.algparam}var q=KJUR.crypto.OID.oidhex2name[n.algparam];var p=new KJUR.crypto.ECDSA({curve:q,pub:n.key});return p}else{throw"unsupported public key algorithm"}}},parsePublicRawRSAKeyHex:function(p){var n={};if(p.substr(0,2)!="30"){throw"malformed RSA key(code:001)"}var o=ASN1HEX.getPosArrayOfChildren_AtObj(p,0);if(o.length!=2){throw"malformed RSA key(code:002)"}if(p.substr(o[0],2)!="02"){throw"malformed RSA key(code:003)"}n.n=ASN1HEX.getHexOfV_AtObj(p,o[0]);if(p.substr(o[1],2)!="02"){throw"malformed RSA key(code:004)"}n.e=ASN1HEX.getHexOfV_AtObj(p,o[1]);return n},parsePrivateRawRSAKeyHexAtObj:function(o,q){var p=q.keyidx;if(o.substr(p,2)!="30"){throw"malformed RSA private key(code:001)"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(o,p);if(n.length!=9){throw"malformed RSA private key(code:002)"}q.key={};q.key.n=ASN1HEX.getHexOfV_AtObj(o,n[1]);q.key.e=ASN1HEX.getHexOfV_AtObj(o,n[2]);q.key.d=ASN1HEX.getHexOfV_AtObj(o,n[3]);q.key.p=ASN1HEX.getHexOfV_AtObj(o,n[4]);q.key.q=ASN1HEX.getHexOfV_AtObj(o,n[5]);q.key.dp=ASN1HEX.getHexOfV_AtObj(o,n[6]);q.key.dq=ASN1HEX.getHexOfV_AtObj(o,n[7]);q.key.co=ASN1HEX.getHexOfV_AtObj(o,n[8])},parsePrivateRawECKeyHexAtObj:function(o,q){var p=q.keyidx;if(o.substr(p,2)!="30"){throw"malformed ECC private key(code:001)"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(o,p);if(n.length!=3){throw"malformed ECC private key(code:002)"}if(o.substr(n[1],2)!="04"){throw"malformed ECC private key(code:003)"}q.key=ASN1HEX.getHexOfV_AtObj(o,n[1])},parsePublicPKCS8Hex:function(q){var o={};o.algparam=null;var p=ASN1HEX.getPosArrayOfChildren_AtObj(q,0);if(p.length!=2){throw"outer DERSequence shall have 2 elements: "+p.length}var r=p[0];if(q.substr(r,2)!="30"){throw"malformed PKCS8 public key(code:001)"}var n=ASN1HEX.getPosArrayOfChildren_AtObj(q,r);if(n.length!=2){throw"malformed PKCS8 public key(code:002)"}if(q.substr(n[0],2)!="06"){throw"malformed PKCS8 public key(code:003)"}o.algoid=ASN1HEX.getHexOfV_AtObj(q,n[0]);if(q.substr(n[1],2)=="06"){o.algparam=ASN1HEX.getHexOfV_AtObj(q,n[1])}if(q.substr(p[1],2)!="03"){throw"malformed PKCS8 public key(code:004)"}o.key=ASN1HEX.getHexOfV_AtObj(q,p[1]).substr(2);return o},getRSAKeyFromPublicPKCS8Hex:function(r){var q=ASN1HEX.getPosArrayOfChildren_AtObj(r,0);if(q.length!=2){throw"outer DERSequence shall have 2 elements: "+q.length}var p=ASN1HEX.getHexOfTLV_AtObj(r,q[0]);if(p!="300d06092a864886f70d0101010500"){throw"PKCS8 AlgorithmId is not rsaEncryption"}if(r.substr(q[1],2)!="03"){throw"PKCS8 Public Key is not BITSTRING encapslated."}var t=ASN1HEX.getStartPosOfV_AtObj(r,q[1])+2;if(r.substr(t,2)!="30"){throw"PKCS8 Public Key is not SEQUENCE."}var n=ASN1HEX.getPosArrayOfChildren_AtObj(r,t);if(n.length!=2){throw"inner DERSequence shall have 2 elements: "+n.length}if(r.substr(n[0],2)!="02"){throw"N is not ASN.1 INTEGER"}if(r.substr(n[1],2)!="02"){throw"E is not ASN.1 INTEGER"}var u=ASN1HEX.getHexOfV_AtObj(r,n[0]);var s=ASN1HEX.getHexOfV_AtObj(r,n[1]);var o=new RSAKey();o.setPublic(u,s);return o},}}(); +/*! keyutil-1.0.4.js (c) 2013 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +var KEYUTIL=function(){var d=function(p,r,q){return k(CryptoJS.AES,p,r,q)};var e=function(p,r,q){return k(CryptoJS.TripleDES,p,r,q)};var a=function(p,r,q){return k(CryptoJS.DES,p,r,q)};var k=function(s,x,u,q){var r=CryptoJS.enc.Hex.parse(x);var w=CryptoJS.enc.Hex.parse(u);var p=CryptoJS.enc.Hex.parse(q);var t={};t.key=w;t.iv=p;t.ciphertext=r;var v=s.decrypt(t,w,{iv:p});return CryptoJS.enc.Hex.stringify(v)};var l=function(p,r,q){return g(CryptoJS.AES,p,r,q)};var o=function(p,r,q){return g(CryptoJS.TripleDES,p,r,q)};var f=function(p,r,q){return g(CryptoJS.DES,p,r,q)};var g=function(t,y,v,q){var s=CryptoJS.enc.Hex.parse(y);var x=CryptoJS.enc.Hex.parse(v);var p=CryptoJS.enc.Hex.parse(q);var w=t.encrypt(s,x,{iv:p});var r=CryptoJS.enc.Hex.parse(w.toString());var u=CryptoJS.enc.Base64.stringify(r);return u};var i={"AES-256-CBC":{proc:d,eproc:l,keylen:32,ivlen:16},"AES-192-CBC":{proc:d,eproc:l,keylen:24,ivlen:16},"AES-128-CBC":{proc:d,eproc:l,keylen:16,ivlen:16},"DES-EDE3-CBC":{proc:e,eproc:o,keylen:24,ivlen:8},"DES-CBC":{proc:a,eproc:f,keylen:8,ivlen:8}};var c=function(p){return i[p]["proc"]};var m=function(p){var r=CryptoJS.lib.WordArray.random(p);var q=CryptoJS.enc.Hex.stringify(r);return q};var n=function(t){var u={};if(t.match(new RegExp("DEK-Info: ([^,]+),([0-9A-Fa-f]+)","m"))){u.cipher=RegExp.$1;u.ivsalt=RegExp.$2}if(t.match(new RegExp("-----BEGIN ([A-Z]+) PRIVATE KEY-----"))){u.type=RegExp.$1}var r=-1;var v=0;if(t.indexOf("\r\n\r\n")!=-1){r=t.indexOf("\r\n\r\n");v=2}if(t.indexOf("\n\n")!=-1){r=t.indexOf("\n\n");v=1}var q=t.indexOf("-----END");if(r!=-1&&q!=-1){var p=t.substring(r+v*2,q-v);p=p.replace(/\s+/g,"");u.data=p}return u};var j=function(q,y,p){var v=p.substring(0,16);var t=CryptoJS.enc.Hex.parse(v);var r=CryptoJS.enc.Utf8.parse(y);var u=i[q]["keylen"]+i[q]["ivlen"];var x="";var w=null;for(;;){var s=CryptoJS.algo.MD5.create();if(w!=null){s.update(w)}s.update(r);s.update(t);w=s.finalize();x=x+CryptoJS.enc.Hex.stringify(w);if(x.length>=u*2){break}}var z={};z.keyhex=x.substr(0,i[q]["keylen"]*2);z.ivhex=x.substr(i[q]["keylen"]*2,i[q]["ivlen"]*2);return z};var b=function(p,v,r,w){var s=CryptoJS.enc.Base64.parse(p);var q=CryptoJS.enc.Hex.stringify(s);var u=i[v]["proc"];var t=u(q,r,w);return t};var h=function(p,s,q,u){var r=i[s]["eproc"];var t=r(p,q,u);return t};return{version:"1.0.0",getHexFromPEM:function(q,u){var r=q;if(r.indexOf("BEGIN "+u)==-1){throw"can't find PEM header: "+u}r=r.replace("-----BEGIN "+u+"-----","");r=r.replace("-----END "+u+"-----","");var t=r.replace(/\s+/g,"");var p=b64tohex(t);return p},getDecryptedKeyHexByKeyIV:function(q,t,s,r){var p=c(t);return p(q,s,r)},parsePKCS5PEM:function(p){return n(p)},getKeyAndUnusedIvByPasscodeAndIvsalt:function(q,p,r){return j(q,p,r)},decryptKeyB64:function(p,r,q,s){return b(p,r,q,s)},getDecryptedKeyHex:function(y,x){var q=n(y);var t=q.type;var r=q.cipher;var p=q.ivsalt;var s=q.data;var w=j(r,x,p);var v=w.keyhex;var u=b(s,r,v,p);return u},getRSAKeyFromEncryptedPKCS5PEM:function(r,q){var s=this.getDecryptedKeyHex(r,q);var p=new RSAKey();p.readPrivateKeyFromASN1HexString(s);return p},getEncryptedPKCS5PEMFromPrvKeyHex:function(x,s,A,t,r){var p="";if(typeof t=="undefined"||t==null){t="AES-256-CBC"}if(typeof i[t]=="undefined"){throw"KEYUTIL unsupported algorithm: "+t}if(typeof r=="undefined"||r==null){var v=i[t]["ivlen"];var u=m(v);r=u.toUpperCase()}var z=j(t,A,r);var y=z.keyhex;var w=h(s,t,y,r);var q=w.replace(/(.{64})/g,"$1\r\n");var p="-----BEGIN "+x+" PRIVATE KEY-----\r\n";p+="Proc-Type: 4,ENCRYPTED\r\n";p+="DEK-Info: "+t+","+r+"\r\n";p+="\r\n";p+=q;p+="\r\n-----END "+x+" PRIVATE KEY-----\r\n";return p},getEncryptedPKCS5PEMFromRSAKey:function(D,E,r,t){var B=new KJUR.asn1.DERInteger({"int":0});var w=new KJUR.asn1.DERInteger({bigint:D.n});var A=new KJUR.asn1.DERInteger({"int":D.e});var C=new KJUR.asn1.DERInteger({bigint:D.d});var u=new KJUR.asn1.DERInteger({bigint:D.p});var s=new KJUR.asn1.DERInteger({bigint:D.q});var z=new KJUR.asn1.DERInteger({bigint:D.dmp1});var v=new KJUR.asn1.DERInteger({bigint:D.dmq1});var y=new KJUR.asn1.DERInteger({bigint:D.coeff});var F=new KJUR.asn1.DERSequence({array:[B,w,A,C,u,s,z,v,y]});var x=F.getEncodedHex();return this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",x,E,r,t)},newEncryptedPKCS5PEM:function(p,q,t,u){if(typeof q=="undefined"||q==null){q=1024}if(typeof t=="undefined"||t==null){t="10001"}var r=new RSAKey();r.generate(q,t);var s=null;if(typeof u=="undefined"||u==null){s=this.getEncryptedPKCS5PEMFromRSAKey(r,p)}else{s=this.getEncryptedPKCS5PEMFromRSAKey(r,p,u)}return s},getRSAKeyFromPlainPKCS8PEM:function(r){if(r.match(/ENCRYPTED/)){throw"pem shall be not ENCRYPTED"}var q=this.getHexFromPEM(r,"PRIVATE KEY");var p=this.getRSAKeyFromPlainPKCS8Hex(q);return p},getRSAKeyFromPlainPKCS8Hex:function(s){var r=ASN1HEX.getPosArrayOfChildren_AtObj(s,0);if(r.length!=3){throw"outer DERSequence shall have 3 elements: "+r.length}var q=ASN1HEX.getHexOfTLV_AtObj(s,r[1]);if(q!="300d06092a864886f70d0101010500"){throw"PKCS8 AlgorithmIdentifier is not rsaEnc: "+q}var q=ASN1HEX.getHexOfTLV_AtObj(s,r[1]);var t=ASN1HEX.getHexOfTLV_AtObj(s,r[2]);var u=ASN1HEX.getHexOfV_AtObj(t,0);var p=new RSAKey();p.readPrivateKeyFromASN1HexString(u);return p},parseHexOfEncryptedPKCS8:function(w){var s={};var r=ASN1HEX.getPosArrayOfChildren_AtObj(w,0);if(r.length!=2){throw"malformed format: SEQUENCE(0).items != 2: "+r.length}s.ciphertext=ASN1HEX.getHexOfV_AtObj(w,r[1]);var y=ASN1HEX.getPosArrayOfChildren_AtObj(w,r[0]);if(y.length!=2){throw"malformed format: SEQUENCE(0.0).items != 2: "+y.length}if(ASN1HEX.getHexOfV_AtObj(w,y[0])!="2a864886f70d01050d"){throw"this only supports pkcs5PBES2"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(w,y[1]);if(y.length!=2){throw"malformed format: SEQUENCE(0.0.1).items != 2: "+p.length}var q=ASN1HEX.getPosArrayOfChildren_AtObj(w,p[1]);if(q.length!=2){throw"malformed format: SEQUENCE(0.0.1.1).items != 2: "+q.length}if(ASN1HEX.getHexOfV_AtObj(w,q[0])!="2a864886f70d0307"){throw"this only supports TripleDES"}s.encryptionSchemeAlg="TripleDES";s.encryptionSchemeIV=ASN1HEX.getHexOfV_AtObj(w,q[1]);var t=ASN1HEX.getPosArrayOfChildren_AtObj(w,p[0]);if(t.length!=2){throw"malformed format: SEQUENCE(0.0.1.0).items != 2: "+t.length}if(ASN1HEX.getHexOfV_AtObj(w,t[0])!="2a864886f70d01050c"){throw"this only supports pkcs5PBKDF2"}var x=ASN1HEX.getPosArrayOfChildren_AtObj(w,t[1]);if(x.length<2){throw"malformed format: SEQUENCE(0.0.1.0.1).items < 2: "+x.length}s.pbkdf2Salt=ASN1HEX.getHexOfV_AtObj(w,x[0]);var u=ASN1HEX.getHexOfV_AtObj(w,x[1]);try{s.pbkdf2Iter=parseInt(u,16)}catch(v){throw"malformed format pbkdf2Iter: "+u}return s},getPBKDF2KeyHexFromParam:function(u,p){var t=CryptoJS.enc.Hex.parse(u.pbkdf2Salt);var q=u.pbkdf2Iter;var s=CryptoJS.PBKDF2(p,t,{keySize:192/32,iterations:q});var r=CryptoJS.enc.Hex.stringify(s);return r},getPlainPKCS8HexFromEncryptedPKCS8PEM:function(x,y){var r=this.getHexFromPEM(x,"ENCRYPTED PRIVATE KEY");var p=this.parseHexOfEncryptedPKCS8(r);var u=KEYUTIL.getPBKDF2KeyHexFromParam(p,y);var v={};v.ciphertext=CryptoJS.enc.Hex.parse(p.ciphertext);var t=CryptoJS.enc.Hex.parse(u);var s=CryptoJS.enc.Hex.parse(p.encryptionSchemeIV);var w=CryptoJS.TripleDES.decrypt(v,t,{iv:s});var q=CryptoJS.enc.Hex.stringify(w);return q},getRSAKeyFromEncryptedPKCS8PEM:function(s,r){var q=this.getPlainPKCS8HexFromEncryptedPKCS8PEM(s,r);var p=this.getRSAKeyFromPlainPKCS8Hex(q);return p},getKeyFromEncryptedPKCS8PEM:function(s,q){var p=this.getPlainPKCS8HexFromEncryptedPKCS8PEM(s,q);var r=this.getKeyFromPlainPrivatePKCS8Hex(p);return r},parsePlainPrivatePKCS8Hex:function(s){var q={};q.algparam=null;if(s.substr(0,2)!="30"){throw"malformed plain PKCS8 private key(code:001)"}var r=ASN1HEX.getPosArrayOfChildren_AtObj(s,0);if(r.length!=3){throw"malformed plain PKCS8 private key(code:002)"}if(s.substr(r[1],2)!="30"){throw"malformed PKCS8 private key(code:003)"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(s,r[1]);if(p.length!=2){throw"malformed PKCS8 private key(code:004)"}if(s.substr(p[0],2)!="06"){throw"malformed PKCS8 private key(code:005)"}q.algoid=ASN1HEX.getHexOfV_AtObj(s,p[0]);if(s.substr(p[1],2)=="06"){q.algparam=ASN1HEX.getHexOfV_AtObj(s,p[1])}if(s.substr(r[2],2)!="04"){throw"malformed PKCS8 private key(code:006)"}q.keyidx=ASN1HEX.getStartPosOfV_AtObj(s,r[2]);return q},getKeyFromPlainPrivatePKCS8PEM:function(q){var p=this.getHexFromPEM(q,"PRIVATE KEY");var r=this.getKeyFromPlainPrivatePKCS8Hex(p);return r},getKeyFromPlainPrivatePKCS8Hex:function(p){var w=this.parsePlainPrivatePKCS8Hex(p);if(w.algoid=="2a864886f70d010101"){this.parsePrivateRawRSAKeyHexAtObj(p,w);var u=w.key;var z=new RSAKey();z.setPrivateEx(u.n,u.e,u.d,u.p,u.q,u.dp,u.dq,u.co);return z}else{if(w.algoid=="2a8648ce3d0201"){this.parsePrivateRawECKeyHexAtObj(p,w);if(KJUR.crypto.OID.oidhex2name[w.algparam]===undefined){throw"KJUR.crypto.OID.oidhex2name undefined: "+w.algparam}var v=KJUR.crypto.OID.oidhex2name[w.algparam];var z=new KJUR.crypto.ECDSA({curve:v});z.setPublicKeyHex(w.pubkey);z.setPrivateKeyHex(w.key);z.isPublic=false;return z}else{if(w.algoid=="2a8648ce380401"){var t=ASN1HEX.getVbyList(p,0,[1,1,0],"02");var s=ASN1HEX.getVbyList(p,0,[1,1,1],"02");var y=ASN1HEX.getVbyList(p,0,[1,1,2],"02");var B=ASN1HEX.getVbyList(p,0,[2,0],"02");var r=new BigInteger(t,16);var q=new BigInteger(s,16);var x=new BigInteger(y,16);var A=new BigInteger(B,16);var z=new KJUR.crypto.DSA();z.setPrivate(r,q,x,null,A);return z}else{throw"unsupported private key algorithm"}}}},getRSAKeyFromPublicPKCS8PEM:function(q){var r=this.getHexFromPEM(q,"PUBLIC KEY");var p=this.getRSAKeyFromPublicPKCS8Hex(r);return p},getKeyFromPublicPKCS8PEM:function(q){var r=this.getHexFromPEM(q,"PUBLIC KEY");var p=this.getKeyFromPublicPKCS8Hex(r);return p},getKeyFromPublicPKCS8Hex:function(q){var p=this.parsePublicPKCS8Hex(q);if(p.algoid=="2a864886f70d010101"){var u=this.parsePublicRawRSAKeyHex(p.key);var r=new RSAKey();r.setPublic(u.n,u.e);return r}else{if(p.algoid=="2a8648ce3d0201"){if(KJUR.crypto.OID.oidhex2name[p.algparam]===undefined){throw"KJUR.crypto.OID.oidhex2name undefined: "+p.algparam}var s=KJUR.crypto.OID.oidhex2name[p.algparam];var r=new KJUR.crypto.ECDSA({curve:s,pub:p.key});return r}else{if(p.algoid=="2a8648ce380401"){var t=p.algparam;var v=ASN1HEX.getHexOfV_AtObj(p.key,0);var r=new KJUR.crypto.DSA();r.setPublic(new BigInteger(t.p,16),new BigInteger(t.q,16),new BigInteger(t.g,16),new BigInteger(v,16));return r}else{throw"unsupported public key algorithm"}}}},parsePublicRawRSAKeyHex:function(r){var p={};if(r.substr(0,2)!="30"){throw"malformed RSA key(code:001)"}var q=ASN1HEX.getPosArrayOfChildren_AtObj(r,0);if(q.length!=2){throw"malformed RSA key(code:002)"}if(r.substr(q[0],2)!="02"){throw"malformed RSA key(code:003)"}p.n=ASN1HEX.getHexOfV_AtObj(r,q[0]);if(r.substr(q[1],2)!="02"){throw"malformed RSA key(code:004)"}p.e=ASN1HEX.getHexOfV_AtObj(r,q[1]);return p},parsePrivateRawRSAKeyHexAtObj:function(q,s){var r=s.keyidx;if(q.substr(r,2)!="30"){throw"malformed RSA private key(code:001)"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(q,r);if(p.length!=9){throw"malformed RSA private key(code:002)"}s.key={};s.key.n=ASN1HEX.getHexOfV_AtObj(q,p[1]);s.key.e=ASN1HEX.getHexOfV_AtObj(q,p[2]);s.key.d=ASN1HEX.getHexOfV_AtObj(q,p[3]);s.key.p=ASN1HEX.getHexOfV_AtObj(q,p[4]);s.key.q=ASN1HEX.getHexOfV_AtObj(q,p[5]);s.key.dp=ASN1HEX.getHexOfV_AtObj(q,p[6]);s.key.dq=ASN1HEX.getHexOfV_AtObj(q,p[7]);s.key.co=ASN1HEX.getHexOfV_AtObj(q,p[8])},parsePrivateRawECKeyHexAtObj:function(p,t){var q=t.keyidx;var r=ASN1HEX.getVbyList(p,q,[1],"04");var s=ASN1HEX.getVbyList(p,q,[2,0],"03").substr(2);t.key=r;t.pubkey=s},parsePublicPKCS8Hex:function(s){var q={};q.algparam=null;var r=ASN1HEX.getPosArrayOfChildren_AtObj(s,0);if(r.length!=2){throw"outer DERSequence shall have 2 elements: "+r.length}var t=r[0];if(s.substr(t,2)!="30"){throw"malformed PKCS8 public key(code:001)"}var p=ASN1HEX.getPosArrayOfChildren_AtObj(s,t);if(p.length!=2){throw"malformed PKCS8 public key(code:002)"}if(s.substr(p[0],2)!="06"){throw"malformed PKCS8 public key(code:003)"}q.algoid=ASN1HEX.getHexOfV_AtObj(s,p[0]);if(s.substr(p[1],2)=="06"){q.algparam=ASN1HEX.getHexOfV_AtObj(s,p[1])}else{if(s.substr(p[1],2)=="30"){q.algparam={};q.algparam.p=ASN1HEX.getVbyList(s,p[1],[0],"02");q.algparam.q=ASN1HEX.getVbyList(s,p[1],[1],"02");q.algparam.g=ASN1HEX.getVbyList(s,p[1],[2],"02")}}if(s.substr(r[1],2)!="03"){throw"malformed PKCS8 public key(code:004)"}q.key=ASN1HEX.getHexOfV_AtObj(s,r[1]).substr(2);return q},getRSAKeyFromPublicPKCS8Hex:function(t){var s=ASN1HEX.getPosArrayOfChildren_AtObj(t,0);if(s.length!=2){throw"outer DERSequence shall have 2 elements: "+s.length}var r=ASN1HEX.getHexOfTLV_AtObj(t,s[0]);if(r!="300d06092a864886f70d0101010500"){throw"PKCS8 AlgorithmId is not rsaEncryption"}if(t.substr(s[1],2)!="03"){throw"PKCS8 Public Key is not BITSTRING encapslated."}var v=ASN1HEX.getStartPosOfV_AtObj(t,s[1])+2;if(t.substr(v,2)!="30"){throw"PKCS8 Public Key is not SEQUENCE."}var p=ASN1HEX.getPosArrayOfChildren_AtObj(t,v);if(p.length!=2){throw"inner DERSequence shall have 2 elements: "+p.length}if(t.substr(p[0],2)!="02"){throw"N is not ASN.1 INTEGER"}if(t.substr(p[1],2)!="02"){throw"E is not ASN.1 INTEGER"}var w=ASN1HEX.getHexOfV_AtObj(t,p[0]);var u=ASN1HEX.getHexOfV_AtObj(t,p[1]);var q=new RSAKey();q.setPublic(w,u);return q},}}();KEYUTIL.getKey=function(c,o,i){if(typeof RSAKey!="undefined"&&c instanceof RSAKey){return c}if(typeof KJUR.crypto.ECDSA!="undefined"&&c instanceof KJUR.crypto.ECDSA){return c}if(typeof KJUR.crypto.DSA!="undefined"&&c instanceof KJUR.crypto.DSA){return c}if(c.xy!==undefined&&c.curve!==undefined){return new KJUR.crypto.ECDSA({prv:c.xy,curve:c.curve})}if(c.n!==undefined&&c.e!==undefined&&c.d!==undefined&&c.p!==undefined&&c.q!==undefined&&c.dp!==undefined&&c.dq!==undefined&&c.co!==undefined){var n=new RSAKey();n.setPrivateEx(c.n,c.e,c.d,c.p,c.q,c.dp,c.dq,c.co);return n}if(c.p!==undefined&&c.q!==undefined&&c.g!==undefined&&c.y!==undefined&&c.x!==undefined){var n=new KJUR.crypto.DSA();n.setPrivate(c.p,c.q,c.g,c.y,c.x);return n}if(c.d!==undefined&&c.curve!==undefined){return new KJUR.crypto.ECDSA({pub:c.d,curve:c.curve})}if(c.n!==undefined&&c.e){var n=new RSAKey();n.setPublic(c.n,c.e);return n}if(c.p!==undefined&&c.q!==undefined&&c.g!==undefined&&c.y!==undefined&&c.x===undefined){var n=new KJUR.crypto.DSA();n.setPublic(c.p,c.q,c.g,c.y);return n}if(c.indexOf("-END CERTIFICATE-",0)!=-1||c.indexOf("-END X509 CERTIFICATE-",0)!=-1||c.indexOf("-END TRUSTED CERTIFICATE-",0)!=-1){return X509.getPublicKeyFromCertPEM(c)}if(i==="pkcs8pub"){return KEYUTIL.getKeyFromPublicPKCS8Hex(c)}if(c.indexOf("-END PUBLIC KEY-")!=-1){return KEYUTIL.getKeyFromPublicPKCS8PEM(c)}if(i==="pkcs5prv"){var n=new RSAKey();n.readPrivateKeyFromASN1HexString(c);return n}if(i==="pkcs5prv"){var n=new RSAKey();n.readPrivateKeyFromASN1HexString(c);return n}if(c.indexOf("-END RSA PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")==-1){var n=new RSAKey();n.readPrivateKeyFromPEMString(c);return n}if(c.indexOf("-END DSA PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")==-1){var m=this.getHexFromPEM(c,"DSA PRIVATE KEY");var b=ASN1HEX.getVbyList(m,0,[1],"02");var a=ASN1HEX.getVbyList(m,0,[2],"02");var e=ASN1HEX.getVbyList(m,0,[3],"02");var k=ASN1HEX.getVbyList(m,0,[4],"02");var l=ASN1HEX.getVbyList(m,0,[5],"02");var n=new KJUR.crypto.DSA();n.setPrivate(new BigInteger(b,16),new BigInteger(a,16),new BigInteger(e,16),new BigInteger(k,16),new BigInteger(l,16));return n}if(c.indexOf("-END PRIVATE KEY-")!=-1){return KEYUTIL.getKeyFromPlainPrivatePKCS8PEM(c)}if(c.indexOf("-END RSA PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")!=-1){return KEYUTIL.getRSAKeyFromEncryptedPKCS5PEM(c,o)}if(c.indexOf("-END EC PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")!=-1){var m=KEYUTIL.getDecryptedKeyHex(c,o);var n=ASN1HEX.getVbyList(m,0,[1],"04");var j=ASN1HEX.getVbyList(m,0,[2,0],"06");var d=ASN1HEX.getVbyList(m,0,[3,0],"03").substr(2);var h="";if(KJUR.crypto.OID.oidhex2name[j]!==undefined){h=KJUR.crypto.OID.oidhex2name[j]}else{throw"undefined OID(hex) in KJUR.crypto.OID: "+j}var f=new KJUR.crypto.ECDSA({name:h});f.setPublicKeyHex(d);f.setPrivateKeyHex(n);f.isPublic=false;return f}if(c.indexOf("-END DSA PRIVATE KEY-")!=-1&&c.indexOf("4,ENCRYPTED")!=-1){var m=KEYUTIL.getDecryptedKeyHex(c,o);var b=ASN1HEX.getVbyList(m,0,[1],"02");var a=ASN1HEX.getVbyList(m,0,[2],"02");var e=ASN1HEX.getVbyList(m,0,[3],"02");var k=ASN1HEX.getVbyList(m,0,[4],"02");var l=ASN1HEX.getVbyList(m,0,[5],"02");var n=new KJUR.crypto.DSA();n.setPrivate(new BigInteger(b,16),new BigInteger(a,16),new BigInteger(e,16),new BigInteger(k,16),new BigInteger(l,16));return n}if(c.indexOf("-END ENCRYPTED PRIVATE KEY-")!=-1){return KEYUTIL.getKeyFromEncryptedPKCS8PEM(c,o)}throw"not supported argument"};KEYUTIL.generateKeypair=function(a,c){if(a=="RSA"){var b=c;var h=new RSAKey();h.generate(b,"10001");var f=new RSAKey();var e=h.n.toString(16);var i=h.e.toString(16);f.setPublic(e,i);var k={};k.prvKeyObj=h;k.pubKeyObj=f;return k}else{if(a=="EC"){var d=c;var g=new KJUR.crypto.ECDSA({curve:d});var j=g.generateKeyPairHex();var h=new KJUR.crypto.ECDSA({curve:d});h.setPrivateKeyHex(j.ecprvhex);var f=new KJUR.crypto.ECDSA({curve:d});f.setPublicKeyHex(j.ecpubhex);var k={};k.prvKeyObj=h;k.pubKeyObj=f;return k}else{throw"unknown algorithm: "+a}}};KEYUTIL.getPEM=function(a,r,o,g,j){var v=KJUR.asn1;var u=KJUR.crypto;function p(s){var w=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{"int":{bigint:s.n}},{"int":s.e},{"int":{bigint:s.d}},{"int":{bigint:s.p}},{"int":{bigint:s.q}},{"int":{bigint:s.dmp1}},{"int":{bigint:s.dmq1}},{"int":{bigint:s.coeff}}]});return w}function q(w){var s=KJUR.asn1.ASN1Util.newObject({seq:[{"int":1},{octstr:{hex:w.prvKeyHex}},{tag:["a0",true,{oid:{name:w.curveName}}]},{tag:["a1",true,{bitstr:{hex:"00"+w.pubKeyHex}}]}]});return s}function n(s){var w=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{"int":{bigint:s.p}},{"int":{bigint:s.q}},{"int":{bigint:s.g}},{"int":{bigint:s.y}},{"int":{bigint:s.x}}]});return w}if(((typeof RSAKey!="undefined"&&a instanceof RSAKey)||(typeof u.DSA!="undefined"&&a instanceof u.DSA)||(typeof u.ECDSA!="undefined"&&a instanceof u.ECDSA))&&a.isPublic==true&&(r===undefined||r=="PKCS8PUB")){var t=new KJUR.asn1.x509.SubjectPublicKeyInfo(a);var m=t.getEncodedHex();return v.ASN1Util.getPEMStringFromHex(m,"PUBLIC KEY")}if(r=="PKCS1PRV"&&typeof RSAKey!="undefined"&&a instanceof RSAKey&&(o===undefined||o==null)&&a.isPrivate==true){var t=p(a);var m=t.getEncodedHex();return v.ASN1Util.getPEMStringFromHex(m,"RSA PRIVATE KEY")}if(r=="PKCS1PRV"&&typeof RSAKey!="undefined"&&a instanceof KJUR.crypto.ECDSA&&(o===undefined||o==null)&&a.isPrivate==true){var f=new KJUR.asn1.DERObjectIdentifier({name:a.curveName});var l=f.getEncodedHex();var e=q(a);var k=e.getEncodedHex();var i="";i+=v.ASN1Util.getPEMStringFromHex(l,"EC PARAMETERS");i+=v.ASN1Util.getPEMStringFromHex(k,"EC PRIVATE KEY");return i}if(r=="PKCS1PRV"&&typeof KJUR.crypto.DSA!="undefined"&&a instanceof KJUR.crypto.DSA&&(o===undefined||o==null)&&a.isPrivate==true){var t=n(a);var m=t.getEncodedHex();return v.ASN1Util.getPEMStringFromHex(m,"DSA PRIVATE KEY")}if(r=="PKCS5PRV"&&typeof RSAKey!="undefined"&&a instanceof RSAKey&&(o!==undefined&&o!=null)&&a.isPrivate==true){var t=p(a);var m=t.getEncodedHex();if(g===undefined){g="DES-EDE3-CBC"}return this.getEncryptedPKCS5PEMFromPrvKeyHex("RSA",m,o,g)}if(r=="PKCS5PRV"&&typeof KJUR.crypto.ECDSA!="undefined"&&a instanceof KJUR.crypto.ECDSA&&(o!==undefined&&o!=null)&&a.isPrivate==true){var t=q(a);var m=t.getEncodedHex();if(g===undefined){g="DES-EDE3-CBC"}return this.getEncryptedPKCS5PEMFromPrvKeyHex("EC",m,o,g)}if(r=="PKCS5PRV"&&typeof KJUR.crypto.DSA!="undefined"&&a instanceof KJUR.crypto.DSA&&(o!==undefined&&o!=null)&&a.isPrivate==true){var t=n(a);var m=t.getEncodedHex();if(g===undefined){g="DES-EDE3-CBC"}return this.getEncryptedPKCS5PEMFromPrvKeyHex("DSA",m,o,g)}var h=function(w,s){var y=b(w,s);var x=new KJUR.asn1.ASN1Util.newObject({seq:[{seq:[{oid:{name:"pkcs5PBES2"}},{seq:[{seq:[{oid:{name:"pkcs5PBKDF2"}},{seq:[{octstr:{hex:y.pbkdf2Salt}},{"int":y.pbkdf2Iter}]}]},{seq:[{oid:{name:"des-EDE3-CBC"}},{octstr:{hex:y.encryptionSchemeIV}}]}]}]},{octstr:{hex:y.ciphertext}}]});return x.getEncodedHex()};var b=function(D,E){var x=100;var C=CryptoJS.lib.WordArray.random(8);var B="DES-EDE3-CBC";var s=CryptoJS.lib.WordArray.random(8);var y=CryptoJS.PBKDF2(E,C,{keySize:192/32,iterations:x});var z=CryptoJS.enc.Hex.parse(D);var A=CryptoJS.TripleDES.encrypt(z,y,{iv:s})+"";var w={};w.ciphertext=A;w.pbkdf2Salt=CryptoJS.enc.Hex.stringify(C);w.pbkdf2Iter=x;w.encryptionSchemeAlg=B;w.encryptionSchemeIV=CryptoJS.enc.Hex.stringify(s);return w};if(r=="PKCS8PRV"&&typeof RSAKey!="undefined"&&a instanceof RSAKey&&a.isPrivate==true){var d=p(a);var c=d.getEncodedHex();var t=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{seq:[{oid:{name:"rsaEncryption"}},{"null":true}]},{octstr:{hex:c}}]});var m=t.getEncodedHex();if(o===undefined||o==null){return v.ASN1Util.getPEMStringFromHex(m,"PRIVATE KEY")}else{var k=h(m,o);return v.ASN1Util.getPEMStringFromHex(k,"ENCRYPTED PRIVATE KEY")}}if(r=="PKCS8PRV"&&typeof KJUR.crypto.ECDSA!="undefined"&&a instanceof KJUR.crypto.ECDSA&&a.isPrivate==true){var d=new KJUR.asn1.ASN1Util.newObject({seq:[{"int":1},{octstr:{hex:a.prvKeyHex}},{tag:["a1",true,{bitstr:{hex:"00"+a.pubKeyHex}}]}]});var c=d.getEncodedHex();var t=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{seq:[{oid:{name:"ecPublicKey"}},{oid:{name:a.curveName}}]},{octstr:{hex:c}}]});var m=t.getEncodedHex();if(o===undefined||o==null){return v.ASN1Util.getPEMStringFromHex(m,"PRIVATE KEY")}else{var k=h(m,o);return v.ASN1Util.getPEMStringFromHex(k,"ENCRYPTED PRIVATE KEY")}}if(r=="PKCS8PRV"&&typeof KJUR.crypto.DSA!="undefined"&&a instanceof KJUR.crypto.DSA&&a.isPrivate==true){var d=new KJUR.asn1.DERInteger({bigint:a.x});var c=d.getEncodedHex();var t=KJUR.asn1.ASN1Util.newObject({seq:[{"int":0},{seq:[{oid:{name:"dsa"}},{seq:[{"int":{bigint:a.p}},{"int":{bigint:a.q}},{"int":{bigint:a.g}}]}]},{octstr:{hex:c}}]});var m=t.getEncodedHex();if(o===undefined||o==null){return v.ASN1Util.getPEMStringFromHex(m,"PRIVATE KEY")}else{var k=h(m,o);return v.ASN1Util.getPEMStringFromHex(k,"ENCRYPTED PRIVATE KEY")}}throw"unsupported object nor format"}; +/*! rsapem-1.1.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +function _rsapem_pemToBase64(b){var a=b;a=a.replace("-----BEGIN RSA PRIVATE KEY-----","");a=a.replace("-----END RSA PRIVATE KEY-----","");a=a.replace(/[ \n]+/g,"");return a}function _rsapem_getPosArrayOfChildrenFromHex(d){var j=new Array();var k=ASN1HEX.getStartPosOfV_AtObj(d,0);var f=ASN1HEX.getPosOfNextSibling_AtObj(d,k);var h=ASN1HEX.getPosOfNextSibling_AtObj(d,f);var b=ASN1HEX.getPosOfNextSibling_AtObj(d,h);var l=ASN1HEX.getPosOfNextSibling_AtObj(d,b);var e=ASN1HEX.getPosOfNextSibling_AtObj(d,l);var g=ASN1HEX.getPosOfNextSibling_AtObj(d,e);var c=ASN1HEX.getPosOfNextSibling_AtObj(d,g);var i=ASN1HEX.getPosOfNextSibling_AtObj(d,c);j.push(k,f,h,b,l,e,g,c,i);return j}function _rsapem_getHexValueArrayOfChildrenFromHex(i){var o=_rsapem_getPosArrayOfChildrenFromHex(i);var r=ASN1HEX.getHexOfV_AtObj(i,o[0]);var f=ASN1HEX.getHexOfV_AtObj(i,o[1]);var j=ASN1HEX.getHexOfV_AtObj(i,o[2]);var k=ASN1HEX.getHexOfV_AtObj(i,o[3]);var c=ASN1HEX.getHexOfV_AtObj(i,o[4]);var b=ASN1HEX.getHexOfV_AtObj(i,o[5]);var h=ASN1HEX.getHexOfV_AtObj(i,o[6]);var g=ASN1HEX.getHexOfV_AtObj(i,o[7]);var l=ASN1HEX.getHexOfV_AtObj(i,o[8]);var m=new Array();m.push(r,f,j,k,c,b,h,g,l);return m}function _rsapem_readPrivateKeyFromASN1HexString(c){var b=_rsapem_getHexValueArrayOfChildrenFromHex(c);this.setPrivateEx(b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8])}function _rsapem_readPrivateKeyFromPEMString(e){var c=_rsapem_pemToBase64(e);var d=b64tohex(c);var b=_rsapem_getHexValueArrayOfChildrenFromHex(d);this.setPrivateEx(b[1],b[2],b[3],b[4],b[5],b[6],b[7],b[8])}RSAKey.prototype.readPrivateKeyFromPEMString=_rsapem_readPrivateKeyFromPEMString;RSAKey.prototype.readPrivateKeyFromASN1HexString=_rsapem_readPrivateKeyFromASN1HexString; +/*! rsasign-1.2.7.js (c) 2012 Kenji Urushima | kjur.github.com/jsrsasign/license + */ +var _RE_HEXDECONLY=new RegExp("");_RE_HEXDECONLY.compile("[^0-9a-f]","gi");function _rsasign_getHexPaddedDigestInfoForString(d,e,a){var b=function(f){return KJUR.crypto.Util.hashString(f,a)};var c=b(d);return KJUR.crypto.Util.getPaddedDigestInfoHex(c,a,e)}function _zeroPaddingOfSignature(e,d){var c="";var a=d/4-e.length;for(var b=0;b>24,(d&16711680)>>16,(d&65280)>>8,d&255]))));d+=1}return b}function _rsasign_signStringPSS(e,a,d){var c=function(f){return KJUR.crypto.Util.hashHex(f,a)};var b=c(rstrtohex(e));if(d===undefined){d=-1}return this.signWithMessageHashPSS(b,a,d)}function _rsasign_signWithMessageHashPSS(l,a,k){var b=hextorstr(l);var g=b.length;var m=this.n.bitLength()-1;var c=Math.ceil(m/8);var d;var o=function(i){return KJUR.crypto.Util.hashHex(i,a)};if(k===-1||k===undefined){k=g}else{if(k===-2){k=c-g-2}else{if(k<-2){throw"invalid salt length"}}}if(c<(g+k+2)){throw"data too long"}var f="";if(k>0){f=new Array(k);new SecureRandom().nextBytes(f);f=String.fromCharCode.apply(String,f)}var n=hextorstr(o(rstrtohex("\x00\x00\x00\x00\x00\x00\x00\x00"+b+f)));var j=[];for(d=0;d>(8*c-m))&255;q[0]&=~p;for(d=0;dthis.n.bitLength()){return 0}var i=this.doPublic(b);var e=i.toString(16).replace(/^1f+00/,"");var g=_rsasign_getAlgNameAndHashFromHexDisgestInfo(e);if(g.length==0){return false}var d=g[0];var h=g[1];var a=function(k){return KJUR.crypto.Util.hashString(k,d)};var c=a(f);return(h==c)}function _rsasign_verifyWithMessageHash(e,a){a=a.replace(_RE_HEXDECONLY,"");a=a.replace(/[ \n]+/g,"");var b=parseBigInt(a,16);if(b.bitLength()>this.n.bitLength()){return 0}var h=this.doPublic(b);var g=h.toString(16).replace(/^1f+00/,"");var c=_rsasign_getAlgNameAndHashFromHexDisgestInfo(g);if(c.length==0){return false}var d=c[0];var f=c[1];return(f==e)}function _rsasign_verifyStringPSS(c,b,a,f){var e=function(g){return KJUR.crypto.Util.hashHex(g,a)};var d=e(rstrtohex(c));if(f===undefined){f=-1}return this.verifyWithMessageHashPSS(d,b,a,f)}function _rsasign_verifyWithMessageHashPSS(f,s,l,c){var k=new BigInteger(s,16);if(k.bitLength()>this.n.bitLength()){return false}var r=function(i){return KJUR.crypto.Util.hashHex(i,l)};var j=hextorstr(f);var h=j.length;var g=this.n.bitLength()-1;var m=Math.ceil(g/8);var q;if(c===-1||c===undefined){c=h}else{if(c===-2){c=m-h-2}else{if(c<-2){throw"invalid salt length"}}}if(m<(h+c+2)){throw"data too long"}var a=this.doPublic(k).toByteArray();for(q=0;q>(8*m-g))&255;if((d.charCodeAt(0)&p)!==0){throw"bits beyond keysize not zero"}var n=pss_mgf1_str(e,d.length,r);var o=[];for(q=0;q=0;){delete D[n[A]]}}}return q.call(C,B,D)};x=s({"":x},"")}return x}})();/*! jws-3.0.2 (c) 2013 Kenji Urushima | kjur.github.com/jsjws/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.jws=="undefined"||!KJUR.jws){KJUR.jws={}}KJUR.jws.JWS=function(){this.parseJWS=function(n,p){if((this.parsedJWS!==undefined)&&(p||(this.parsedJWS.sigvalH!==undefined))){return}if(n.match(/^([^.]+)\.([^.]+)\.([^.]+)$/)==null){throw"JWS signature is not a form of 'Head.Payload.SigValue'."}var q=RegExp.$1;var l=RegExp.$2;var r=RegExp.$3;var t=q+"."+l;this.parsedJWS={};this.parsedJWS.headB64U=q;this.parsedJWS.payloadB64U=l;this.parsedJWS.sigvalB64U=r;this.parsedJWS.si=t;if(!p){var o=b64utohex(r);var m=parseBigInt(o,16);this.parsedJWS.sigvalH=o;this.parsedJWS.sigvalBI=m}var k=b64utoutf8(q);var s=b64utoutf8(l);this.parsedJWS.headS=k;this.parsedJWS.payloadS=s;if(!this.isSafeJSONString(k,this.parsedJWS,"headP")){throw"malformed JSON string for JWS Head: "+k}};function b(l,k){return utf8tob64u(l)+"."+utf8tob64u(k)}function f(m,l){var k=function(n){return KJUR.crypto.Util.hashString(n,l)};if(k==null){throw"hash function not defined in jsrsasign: "+l}return k(m)}function h(q,n,k,o,m){var p=b(q,n);var l=parseBigInt(k,16);return _rsasign_verifySignatureWithArgs(p,l,o,m)}this.verifyJWSByNE=function(m,l,k){this.parseJWS(m);return _rsasign_verifySignatureWithArgs(this.parsedJWS.si,this.parsedJWS.sigvalBI,l,k)};this.verifyJWSByKey=function(n,m){this.parseJWS(n);var k=c(this.parsedJWS.headP);var l=this.parsedJWS.headP.alg.substr(0,2)=="PS";if(m.hashAndVerify){return m.hashAndVerify(k,new Buffer(this.parsedJWS.si,"utf8").toString("base64"),b64utob64(this.parsedJWS.sigvalB64U),"base64",l)}else{if(l){return m.verifyStringPSS(this.parsedJWS.si,this.parsedJWS.sigvalH,k)}else{return m.verifyString(this.parsedJWS.si,this.parsedJWS.sigvalH)}}};this.verifyJWSByPemX509Cert=function(m,k){this.parseJWS(m);var l=new X509();l.readCertPEM(k);return l.subjectPublicKeyRSA.verifyString(this.parsedJWS.si,this.parsedJWS.sigvalH)};function c(l){var m=l.alg;var k="";if(m!="RS256"&&m!="RS512"&&m!="PS256"&&m!="PS512"){throw"JWS signature algorithm not supported: "+m}if(m.substr(2)=="256"){k="sha256"}if(m.substr(2)=="512"){k="sha512"}return k}function e(k){return c(jsonParse(k))}function j(k,p,s,m,q,r){var n=new RSAKey();n.setPrivate(m,q,r);var l=e(k);var o=n.signString(s,l);return o}function i(q,p,o,n,m){var k=null;if(typeof m=="undefined"){k=e(q)}else{k=c(m)}var l=m.alg.substr(0,2)=="PS";if(n.hashAndSign){return b64tob64u(n.hashAndSign(k,o,"binary","base64",l))}else{if(l){return hextob64u(n.signStringPSS(o,k))}else{return hextob64u(n.signString(o,k))}}}function g(p,m,o,l,n){var k=b(p,m);return j(p,m,k,o,l,n)}this.generateJWSByNED=function(r,n,q,m,p){if(!this.isSafeJSONString(r)){throw"JWS Head is not safe JSON string: "+r}var l=b(r,n);var o=j(r,n,l,q,m,p);var k=hextob64u(o);this.parsedJWS={};this.parsedJWS.headB64U=l.split(".")[0];this.parsedJWS.payloadB64U=l.split(".")[1];this.parsedJWS.sigvalB64U=k;return l+"."+k};this.generateJWSByKey=function(p,n,k){var o={};if(!this.isSafeJSONString(p,o,"headP")){throw"JWS Head is not safe JSON string: "+p}var m=b(p,n);var l=i(p,n,m,k,o.headP);this.parsedJWS={};this.parsedJWS.headB64U=m.split(".")[0];this.parsedJWS.payloadB64U=m.split(".")[1];this.parsedJWS.sigvalB64U=l;return m+"."+l};function d(q,p,o,l){var n=new RSAKey();n.readPrivateKeyFromPEMString(l);var k=e(q);var m=n.signString(o,k);return m}this.generateJWSByP1PrvKey=function(p,n,k){if(!this.isSafeJSONString(p)){throw"JWS Head is not safe JSON string: "+p}var m=b(p,n);var o=d(p,n,m,k);var l=hextob64u(o);this.parsedJWS={};this.parsedJWS.headB64U=m.split(".")[0];this.parsedJWS.payloadB64U=m.split(".")[1];this.parsedJWS.sigvalB64U=l;return m+"."+l}};KJUR.jws.JWS.sign=function(b,p,i,l,k){var j=KJUR.jws.JWS;if(!j.isSafeJSONString(p)){throw"JWS Head is not safe JSON string: "+sHead}var e=j.readSafeJSONString(p);if((b==""||b==null)&&e.alg!==undefined){b=e.alg}if((b!=""&&b!=null)&&e.alg===undefined){e.alg=b;p=JSON.stringify(e)}var d=null;if(j.jwsalg2sigalg[b]===undefined){throw"unsupported alg name: "+b}else{d=j.jwsalg2sigalg[b]}var c=utf8tob64u(p);var g=utf8tob64u(i);var n=c+"."+g;var m="";if(d.substr(0,4)=="Hmac"){if(l===undefined){throw"hexadecimal key shall be specified for HMAC"}var h=new KJUR.crypto.Mac({alg:d,pass:hextorstr(l)});h.updateString(n);m=h.doFinal()}else{if(d.indexOf("withECDSA")!=-1){var o=new KJUR.crypto.Signature({alg:d});o.init(l,k);o.updateString(n);hASN1Sig=o.sign();m=KJUR.crypto.ECDSA.asn1SigToConcatSig(hASN1Sig)}else{if(d!="none"){var o=new KJUR.crypto.Signature({alg:d});o.init(l,k);o.updateString(n);m=o.sign()}}}var f=hextob64u(m);return n+"."+f};KJUR.jws.JWS.verify=function(d,m){var k=KJUR.jws.JWS;var l=d.split(".");var c=l[0];var h=l[1];var o=c+"."+h;var n=b64utohex(l[2]);var f=k.readSafeJSONString(b64utoutf8(l[0]));var b=null;if(f.alg===undefined){throw"algorithm not specified in header"}else{b=f.alg}var e=null;if(k.jwsalg2sigalg[f.alg]===undefined){throw"unsupported alg name: "+b}else{e=k.jwsalg2sigalg[b]}if(e=="none"){return true}else{if(e.substr(0,4)=="Hmac"){if(m===undefined){throw"hexadecimal key shall be specified for HMAC"}var j=new KJUR.crypto.Mac({alg:e,pass:hextorstr(m)});j.updateString(o);hSig2=j.doFinal();return n==hSig2}else{if(e.indexOf("withECDSA")!=-1){var g=null;try{g=KJUR.crypto.ECDSA.concatSigToASN1Sig(n)}catch(i){return false}var p=new KJUR.crypto.Signature({alg:e});p.init(m);p.updateString(o);return p.verify(g)}else{var p=new KJUR.crypto.Signature({alg:e});p.init(m);p.updateString(o);return p.verify(n)}}}};KJUR.jws.JWS.jwsalg2sigalg={HS256:"HmacSHA256",HS512:"HmacSHA512",RS256:"SHA256withRSA",RS384:"SHA384withRSA",RS512:"SHA512withRSA",ES256:"SHA256withECDSA",ES384:"SHA384withECDSA",PS256:"SHA256withRSAandMGF1",PS384:"SHA384withRSAandMGF1",PS512:"SHA512withRSAandMGF1",none:"none",};KJUR.jws.JWS.isSafeJSONString=function(d,c,e){var f=null;try{f=jsonParse(d);if(typeof f!="object"){return 0}if(f.constructor===Array){return 0}if(c){c[e]=f}return 1}catch(b){return 0}};KJUR.jws.JWS.readSafeJSONString=function(c){var d=null;try{d=jsonParse(c);if(typeof d!="object"){return null}if(d.constructor===Array){return null}return d}catch(b){return null}};KJUR.jws.JWS.getEncodedSignatureValueFromJWS=function(b){if(b.match(/^[^.]+\.[^.]+\.([^.]+)$/)==null){throw"JWS signature is not a form of 'Head.Payload.SigValue'."}return RegExp.$1};KJUR.jws.IntDate=function(){};KJUR.jws.IntDate.get=function(b){if(b=="now"){return KJUR.jws.IntDate.getNow()}else{if(b=="now + 1hour"){return KJUR.jws.IntDate.getNow()+60*60}else{if(b=="now + 1day"){return KJUR.jws.IntDate.getNow()+60*60*24}else{if(b=="now + 1month"){return KJUR.jws.IntDate.getNow()+60*60*24*30}else{if(b=="now + 1year"){return KJUR.jws.IntDate.getNow()+60*60*24*365}else{if(b.match(/Z$/)){return KJUR.jws.IntDate.getZulu(b)}else{if(b.match(/^[0-9]+$/)){return parseInt(b)}}}}}}}throw"unsupported format: "+b};KJUR.jws.IntDate.getZulu=function(h){if(a=h.match(/(\d{4})(\d\d)(\d\d)(\d\d)(\d\d)(\d\d)Z/)){var g=parseInt(RegExp.$1);var i=parseInt(RegExp.$2)-1;var c=parseInt(RegExp.$3);var b=parseInt(RegExp.$4);var e=parseInt(RegExp.$5);var f=parseInt(RegExp.$6);var j=new Date(Date.UTC(g,i,c,b,e,f));return ~~(j/1000)}throw"unsupported format: "+h};KJUR.jws.IntDate.getNow=function(){var b=~~(new Date()/1000);return b};KJUR.jws.IntDate.intDate2UTCString=function(b){var c=new Date(b*1000);return c.toUTCString()};KJUR.jws.IntDate.intDate2Zulu=function(f){var j=new Date(f*1000);var i=("0000"+j.getUTCFullYear()).slice(-4);var h=("00"+(j.getUTCMonth()+1)).slice(-2);var c=("00"+j.getUTCDate()).slice(-2);var b=("00"+j.getUTCHours()).slice(-2);var e=("00"+j.getUTCMinutes()).slice(-2);var g=("00"+j.getUTCSeconds()).slice(-2);return i+h+c+b+e+g+"Z"};/*! jwsjs-2.0.0 (c) 2013 Kenji Urushima | kjur.github.com/jsjws/license + */ +if(typeof KJUR=="undefined"||!KJUR){KJUR={}}if(typeof KJUR.jws=="undefined"||!KJUR.jws){KJUR.jws={}}KJUR.jws.JWSJS=function(){this.aHeader=[];this.sPayload="";this.aSignature=[];this.init=function(){this.aHeader=[];this.sPayload="";this.aSignature=[]};this.initWithJWS=function(b){this.init();var a=new KJUR.jws.JWS();a.parseJWS(b);this.aHeader.push(a.parsedJWS.headB64U);this.sPayload=a.parsedJWS.payloadB64U;this.aSignature.push(a.parsedJWS.sigvalB64U)};this.addSignatureByHeaderKey=function(d,a){var c=b64utoutf8(this.sPayload);var b=new KJUR.jws.JWS();var e=b.generateJWSByP1PrvKey(d,c,a);this.aHeader.push(b.parsedJWS.headB64U);this.aSignature.push(b.parsedJWS.sigvalB64U)};this.addSignatureByHeaderPayloadKey=function(d,c,a){var b=new KJUR.jws.JWS();var e=b.generateJWSByP1PrvKey(d,c,a);this.aHeader.push(b.parsedJWS.headB64U);this.sPayload=b.parsedJWS.payloadB64U;this.aSignature.push(b.parsedJWS.sigvalB64U)};this.verifyWithCerts=function(b){if(this.aHeader.length!=b.length){throw"num headers does not match with num certs"}if(this.aSignature.length!=b.length){throw"num signatures does not match with num certs"}var j=this.sPayload;var f="";for(var c=0;c + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. + */ + +/** + * @license ProtoBuf.js (c) 2013 Daniel Wirtz + * Released under the Apache License, Version 2.0 + * see: https://github.com/dcodeIO/ProtoBuf.js for details + */ +(function(global) { + "use strict"; + + function loadProtoBuf(ByteBuffer) { + + if (!ByteBuffer || !ByteBuffer.VERSION || ByteBuffer.VERSION.split(".")[0] < 3) + throw Error("ProtoBuf.js requires ByteBuffer.js >=3"); + + /** + * The ProtoBuf namespace. + * @exports ProtoBuf + * @namespace + * @expose + */ + var ProtoBuf = {}; + + /** + * ProtoBuf.js version. + * @type {string} + * @const + * @expose + */ + ProtoBuf.VERSION = "3.0.0"; + + /** + * Wire types. + * @type {Object.} + * @const + * @expose + */ + ProtoBuf.WIRE_TYPES = {}; + + /** + * Varint wire type. + * @type {number} + * @expose + */ + ProtoBuf.WIRE_TYPES.VARINT = 0; + + /** + * Fixed 64 bits wire type. + * @type {number} + * @const + * @expose + */ + ProtoBuf.WIRE_TYPES.BITS64 = 1; + + /** + * Length delimited wire type. + * @type {number} + * @const + * @expose + */ + ProtoBuf.WIRE_TYPES.LDELIM = 2; + + /** + * Start group wire type. + * @type {number} + * @const + * @expose + */ + ProtoBuf.WIRE_TYPES.STARTGROUP = 3; + + /** + * End group wire type. + * @type {number} + * @const + * @expose + */ + ProtoBuf.WIRE_TYPES.ENDGROUP = 4; + + /** + * Fixed 32 bits wire type. + * @type {number} + * @const + * @expose + */ + ProtoBuf.WIRE_TYPES.BITS32 = 5; + + /** + * Packable wire types. + * @type {!Array.} + * @const + * @expose + */ + ProtoBuf.PACKABLE_WIRE_TYPES = [ + ProtoBuf.WIRE_TYPES.VARINT, + ProtoBuf.WIRE_TYPES.BITS64, + ProtoBuf.WIRE_TYPES.BITS32 + ]; + + /** + * Types. + * @dict + * @type {Object.} + * @const + * @expose + */ + ProtoBuf.TYPES = { + // According to the protobuf spec. + "int32": { + name: "int32", + wireType: ProtoBuf.WIRE_TYPES.VARINT + }, + "uint32": { + name: "uint32", + wireType: ProtoBuf.WIRE_TYPES.VARINT + }, + "sint32": { + name: "sint32", + wireType: ProtoBuf.WIRE_TYPES.VARINT + }, + "int64": { + name: "int64", + wireType: ProtoBuf.WIRE_TYPES.VARINT + }, + "uint64": { + name: "uint64", + wireType: ProtoBuf.WIRE_TYPES.VARINT + }, + "sint64": { + name: "sint64", + wireType: ProtoBuf.WIRE_TYPES.VARINT + }, + "bool": { + name: "bool", + wireType: ProtoBuf.WIRE_TYPES.VARINT + }, + "double": { + name: "double", + wireType: ProtoBuf.WIRE_TYPES.BITS64 + }, + "string": { + name: "string", + wireType: ProtoBuf.WIRE_TYPES.LDELIM + }, + "bytes": { + name: "bytes", + wireType: ProtoBuf.WIRE_TYPES.LDELIM + }, + "fixed32": { + name: "fixed32", + wireType: ProtoBuf.WIRE_TYPES.BITS32 + }, + "sfixed32": { + name: "sfixed32", + wireType: ProtoBuf.WIRE_TYPES.BITS32 + }, + "fixed64": { + name: "fixed64", + wireType: ProtoBuf.WIRE_TYPES.BITS64 + }, + "sfixed64": { + name: "sfixed64", + wireType: ProtoBuf.WIRE_TYPES.BITS64 + }, + "float": { + name: "float", + wireType: ProtoBuf.WIRE_TYPES.BITS32 + }, + "enum": { + name: "enum", + wireType: ProtoBuf.WIRE_TYPES.VARINT + }, + "message": { + name: "message", + wireType: ProtoBuf.WIRE_TYPES.LDELIM + }, + "group": { + name: "group", + wireType: ProtoBuf.WIRE_TYPES.STARTGROUP + } + }; + + /** + * Minimum field id. + * @type {number} + * @const + * @expose + */ + ProtoBuf.ID_MIN = 1; + + /** + * Maximum field id. + * @type {number} + * @const + * @expose + */ + ProtoBuf.ID_MAX = 0x1FFFFFFF; + + /** + * @type {!function(new: ByteBuffer, ...[*])} + * @expose + */ + ProtoBuf.ByteBuffer = ByteBuffer; + + /** + * @type {?function(new: Long, ...[*])} + * @expose + */ + ProtoBuf.Long = ByteBuffer.Long || null; + + /** + * If set to `true`, field names will be converted from underscore notation to camel case. Defaults to `false`. + * Must be set prior to parsing. + * @type {boolean} + * @expose + */ + ProtoBuf.convertFieldsToCamelCase = false; + + /** + * @alias ProtoBuf.Util + * @expose + */ + ProtoBuf.Util = (function() { + "use strict"; -/** - * @param {Buffer} hash - An instance of a hash Buffer - * @returns {Object} An object with keys: hashBuffer - * @private - */ -Address._transformHash = function(hash){ - var info = {}; - if (!(hash instanceof Buffer) && !(hash instanceof Uint8Array)) { - throw new TypeError('Address supplied is not a buffer.'); - } - if (hash.length !== 20) { - throw new TypeError('Address hashbuffers must be exactly 20 bytes.'); - } - info.hashBuffer = hash; - return info; -}; + // Object.create polyfill + // ref: https://developer.mozilla.org/de/docs/JavaScript/Reference/Global_Objects/Object/create + if (!Object.create) { + /** @expose */ + Object.create = function (o) { + if (arguments.length > 1) { + throw new Error('Object.create implementation only accepts the first parameter.'); + } + function F() {} + F.prototype = o; + return new F(); + }; + } -/** - * Deserializes an address serialized through `Address#toObject()` - * @param {Object} data - * @param {string} data.hash - the hash that this address encodes - * @param {string} data.type - either 'pubkeyhash' or 'scripthash' - * @param {Network=} data.network - the name of the network associated - * @return {Address} - */ -Address._transformObject = function(data) { - $.checkArgument(data.hash || data.hashBuffer, 'Must provide a `hash` or `hashBuffer` property'); - $.checkArgument(data.type, 'Must provide a `type` property'); - return { - hashBuffer: data.hash ? new Buffer(data.hash, 'hex') : data.hashBuffer, - network: Networks.get(data.network) || Networks.defaultNetwork, - type: data.type - }; -}; + /** + * ProtoBuf utilities. + * @exports ProtoBuf.Util + * @namespace + */ + var Util = {}; -/** - * Internal function to discover the network and type based on the first data byte - * - * @param {Buffer} buffer - An instance of a hex encoded address Buffer - * @returns {Object} An object with keys: network and type - * @private - */ -Address._classifyFromVersion = function(buffer){ - var version = {}; - version.network = Networks.get(buffer[0]); - switch (buffer[0]) { // the version byte - case Networks.livenet.pubkeyhash: - version.type = Address.PayToPublicKeyHash; - break; + /** + * Flag if running in node (fs is available) or not. + * @type {boolean} + * @const + * @expose + */ + Util.IS_NODE = false; + try { + // There is no reliable way to detect node.js as an environment, so our + // best bet is to feature-detect what we actually need. + Util.IS_NODE = + typeof require === 'function' && + typeof require("fs").readFileSync === 'function' && + typeof require("path").resolve === 'function'; + } catch (e) {} - case Networks.livenet.scripthash: - version.type = Address.PayToScriptHash; - break; + /** + * Constructs a XMLHttpRequest object. + * @return {XMLHttpRequest} + * @throws {Error} If XMLHttpRequest is not supported + * @expose + */ + Util.XHR = function() { + // No dependencies please, ref: http://www.quirksmode.org/js/xmlhttp.html + var XMLHttpFactories = [ + function () {return new XMLHttpRequest()}, + function () {return new ActiveXObject("Msxml2.XMLHTTP")}, + function () {return new ActiveXObject("Msxml3.XMLHTTP")}, + function () {return new ActiveXObject("Microsoft.XMLHTTP")} + ]; + /** @type {?XMLHttpRequest} */ + var xhr = null; + for (var i=0;i'; -}; - -module.exports = Address; - -}).call(this,require("buffer").Buffer) -},{"./crypto/hash":36,"./encoding/base58check":41,"./networks":50,"./publickey":53,"./script":54,"./util/js":70,"./util/preconditions":71,"buffer":209,"lodash":95}],32:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); -var BlockHeader = require('./blockheader'); -var BN = require('./crypto/bn'); -var BufferUtil = require('./util/buffer'); -var BufferReader = require('./encoding/bufferreader'); -var BufferWriter = require('./encoding/bufferwriter'); -var Hash = require('./crypto/hash'); -var JSUtil = require('./util/js'); -var Transaction = require('./transaction'); -var $ = require('./util/preconditions'); - -/** - * Instantiate a Block from a Buffer, JSON object, or Object with - * the properties of the Block - * - * @param {*} - A Buffer, JSON string, or Object - * @returns {Block} - * @constructor - */ -function Block(arg) { - if (!(this instanceof Block)) { - return new Block(arg); - } - _.extend(this, Block._from(arg)); - return this; -} - -// https://github.com/bitcoin/bitcoin/blob/b5fa132329f0377d787a4a21c1686609c2bfaece/src/primitives/block.h#L14 -Block.MAX_BLOCK_SIZE = 1000000; - -/** - * @param {*} - A Buffer, JSON string or Object - * @returns {Object} - An object representing block data - * @throws {TypeError} - If the argument was not recognized - * @private - */ -Block._from = function _from(arg) { - var info = {}; - if (BufferUtil.isBuffer(arg)) { - info = Block._fromBufferReader(BufferReader(arg)); - } else if (JSUtil.isValidJSON(arg)) { - info = Block._fromJSON(arg); - } else if (_.isObject(arg)) { - info = { - /** - * @name Block#header - * @type {BlockHeader} - */ - header: arg.header, - /** - * @name Block#transactions - * @type {Transaction[]} - */ - transactions: arg.transactions - }; - } else { - throw new TypeError('Unrecognized argument for Block'); - } - return info; -}; - -/** - * @param {String|Object} - A JSON string or object - * @returns {Object} - An object representing block data - * @private - */ -Block._fromJSON = function _fromJSON(data) { - if (JSUtil.isValidJSON(data)) { - data = JSON.parse(data); - } - var transactions = []; - data.transactions.forEach(function(data) { - transactions.push(Transaction().fromJSON(data)); - }); - var info = { - header: BlockHeader.fromJSON(data.header), - transactions: transactions - }; - return info; -}; - -/** - * @param {String|Object} - A JSON string or object - * @returns {Block} - An instance of block - */ -Block.fromJSON = function fromJSON(json) { - var info = Block._fromJSON(json); - return new Block(info); -}; - -/** - * @param {BufferReader} - Block data - * @returns {Object} - An object representing the block data - * @private - */ -Block._fromBufferReader = function _fromBufferReader(br) { - var info = {}; - $.checkState(!br.finished(), 'No block data received'); - info.header = BlockHeader.fromBufferReader(br); - var transactions = br.readVarintNum(); - info.transactions = []; - for (var i = 0; i < transactions; i++) { - info.transactions.push(Transaction().fromBufferReader(br)); - } - return info; -}; - -/** - * @param {BufferReader} - A buffer reader of the block - * @returns {Block} - An instance of block - */ -Block.fromBufferReader = function fromBufferReader(br) { - var info = Block._fromBufferReader(br); - return new Block(info); -}; - -/** - * @param {Buffer} - A buffer of the block - * @returns {Block} - An instance of block - */ -Block.fromBuffer = function fromBuffer(buf) { - return Block.fromBufferReader(BufferReader(buf)); -}; - -/** - * @param {String} - str - A hex encoded string of the block - * @returns {Block} - A hex encoded string of the block - */ -Block.fromString = function fromString(str) { - var buf = new Buffer(str, 'hex'); - return Block.fromBuffer(buf); -}; - -/** - * @param {Binary} - Raw block binary data or buffer - * @returns {Block} - An instance of block - */ -Block.fromRawBlock = function fromRawBlock(data) { - if (!BufferUtil.isBuffer(data)) { - data = new Buffer(data, 'binary'); - } - var br = BufferReader(data); - br.pos = Block.Values.START_OF_BLOCK; - var info = Block._fromBufferReader(br); - return new Block(info); -}; - -/** - * @returns {Object} - A plain object with the block properties - */ -Block.prototype.toObject = function toObject() { - var transactions = []; - this.transactions.forEach(function(tx) { - transactions.push(tx.toObject()); - }); - return { - header: this.header.toObject(), - transactions: transactions - }; -}; - -/** - * @returns {String} - A JSON string - */ -Block.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -/** - * @returns {Buffer} - A buffer of the block - */ -Block.prototype.toBuffer = function toBuffer() { - return this.toBufferWriter().concat(); -}; - -/** - * @returns {String} - A hex encoded string of the block - */ -Block.prototype.toString = function toString() { - return this.toBuffer().toString('hex'); -}; - -/** - * @param {BufferWriter} - An existing instance of BufferWriter - * @returns {BufferWriter} - An instance of BufferWriter representation of the Block - */ -Block.prototype.toBufferWriter = function toBufferWriter(bw) { - if (!bw) { - bw = new BufferWriter(); - } - bw.write(this.header.toBuffer()); - bw.writeVarintNum(this.transactions.length); - for (var i = 0; i < this.transactions.length; i++) { - this.transactions[i].toBufferWriter(bw); - } - return bw; -}; - -/** - * Will iterate through each transaction and return an array of hashes - * @returns {Array} - An array with transaction hashes - */ -Block.prototype.getTransactionHashes = function getTransactionHashes() { - var hashes = []; - if (this.transactions.length === 0) { - return [Block.Values.NULL_HASH]; - } - for (var t = 0; t < this.transactions.length; t++) { - hashes.push(this.transactions[t]._getHash()); - } - return hashes; -}; - -/** - * Will build a merkle tree of all the transactions, ultimately arriving at - * a single point, the merkle root. - * @link https://en.bitcoin.it/wiki/Protocol_specification#Merkle_Trees - * @returns {Array} - An array with each level of the tree after the other. - */ -Block.prototype.getMerkleTree = function getMerkleTree() { - - var tree = this.getTransactionHashes(); - - var j = 0; - for (var size = this.transactions.length; size > 1; size = Math.floor((size + 1) / 2)) { - for (var i = 0; i < size; i += 2) { - var i2 = Math.min(i + 1, size - 1); - var buf = Buffer.concat([tree[j + i], tree[j + i2]]); - tree.push(Hash.sha256sha256(buf)); - } - j += size; - } - - return tree; -}; - -/** - * Calculates the merkleRoot from the transactions. - * @returns {Buffer} - A buffer of the merkle root hash - */ -Block.prototype.getMerkleRoot = function getMerkleRoot() { - var tree = this.getMerkleTree(); - return tree[tree.length - 1]; -}; - -/** - * Verifies that the transactions in the block match the header merkle root - * @returns {Boolean} - If the merkle roots match - */ -Block.prototype.validMerkleRoot = function validMerkleRoot() { - - var h = new BN(this.header.merkleRoot.toString('hex'), 'hex'); - var c = new BN(this.getMerkleRoot().toString('hex'), 'hex'); - - if (h.cmp(c) !== 0) { - return false; - } - - return true; -}; - -/** - * @returns {Buffer} - The little endian hash buffer of the header - */ -Block.prototype._getHash = function() { - return this.header._getHash(); -}; - -var idProperty = { - configurable: false, - writeable: false, - /** - * @returns {string} - The big endian hash buffer of the header - */ - get: function() { - if (!this._id) { - this._id = this.header.id; - } - return this._id; - }, - set: _.noop -}; -Object.defineProperty(Block.prototype, 'id', idProperty); -Object.defineProperty(Block.prototype, 'hash', idProperty); - -/** - * @returns {String} - A string formated for the console - */ -Block.prototype.inspect = function inspect() { - return ''; -}; - -Block.Values = { - START_OF_BLOCK: 8, // Start of block in raw block data - NULL_HASH: new Buffer('0000000000000000000000000000000000000000000000000000000000000000', 'hex') -}; - -module.exports = Block; - -}).call(this,require("buffer").Buffer) -},{"./blockheader":33,"./crypto/bn":34,"./crypto/hash":36,"./encoding/bufferreader":42,"./encoding/bufferwriter":43,"./transaction":57,"./util/buffer":69,"./util/js":70,"./util/preconditions":71,"buffer":209,"lodash":95}],33:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); -var BN = require('./crypto/bn'); -var BufferUtil = require('./util/buffer'); -var BufferReader = require('./encoding/bufferreader'); -var BufferWriter = require('./encoding/bufferwriter'); -var Hash = require('./crypto/hash'); -var JSUtil = require('./util/js'); - -/** - * Instantiate a BlockHeader from a Buffer, JSON object, or Object with - * the properties of the BlockHeader - * - * @param {*} - A Buffer, JSON string, or Object - * @returns {BlockHeader} - An instance of block header - * @constructor - */ -var BlockHeader = function BlockHeader(arg) { - if (!(this instanceof BlockHeader)) { - return new BlockHeader(arg); - } - _.extend(this, BlockHeader._from(arg)); - return this; -}; - -/** - * @param {*} - A Buffer, JSON string or Object - * @returns {Object} - An object representing block header data - * @throws {TypeError} - If the argument was not recognized - * @private - */ -BlockHeader._from = function _from(arg) { - var info = {}; - if (BufferUtil.isBuffer(arg)) { - info = BlockHeader._fromBufferReader(BufferReader(arg)); - } else if (JSUtil.isValidJSON(arg)) { - info = BlockHeader._fromJSON(arg); - } else if (_.isObject(arg)) { - info = { - version: arg.version, - prevHash: arg.prevHash, - merkleRoot: arg.merkleRoot, - time: arg.time, - bits: arg.bits, - nonce: arg.nonce - }; - } else { - throw new TypeError('Unrecognized argument for BlockHeader'); - } - return info; -}; - -/** - * @param {String|Object} - A JSON string or object - * @returns {Object} - An object representing block header data - * @private - */ -BlockHeader._fromJSON = function _fromJSON(data) { - if (JSUtil.isValidJSON(data)) { - data = JSON.parse(data); - } - var info = { - version: data.version, - prevHash: new Buffer(data.prevHash, 'hex'), - merkleRoot: new Buffer(data.merkleRoot, 'hex'), - time: data.time, - timestamp: data.time, - bits: data.bits, - nonce: data.nonce - }; - return info; -}; - -/** - * @param {String|Object} - A JSON string or object - * @returns {BlockHeader} - An instance of block header - */ -BlockHeader.fromJSON = function fromJSON(json) { - var info = BlockHeader._fromJSON(json); - return new BlockHeader(info); -}; - -/** - * @param {Binary} - Raw block binary data or buffer - * @returns {BlockHeader} - An instance of block header - */ -BlockHeader.fromRawBlock = function fromRawBlock(data) { - if (!BufferUtil.isBuffer(data)) { - data = new Buffer(data, 'binary'); - } - var br = BufferReader(data); - br.pos = BlockHeader.Constants.START_OF_HEADER; - var info = BlockHeader._fromBufferReader(br); - return new BlockHeader(info); -}; - -/** - * @param {Buffer} - A buffer of the block header - * @returns {BlockHeader} - An instance of block header - */ -BlockHeader.fromBuffer = function fromBuffer(buf) { - var info = BlockHeader._fromBufferReader(BufferReader(buf)); - return new BlockHeader(info); -}; - -/** - * @param {String} - A hex encoded buffer of the block header - * @returns {BlockHeader} - An instance of block header - */ -BlockHeader.fromString = function fromString(str) { - var buf = new Buffer(str, 'hex'); - return BlockHeader.fromBuffer(buf); -}; - -/** - * @param {BufferReader} - A BufferReader of the block header - * @returns {Object} - An object representing block header data - * @private - */ -BlockHeader._fromBufferReader = function _fromBufferReader(br) { - var info = {}; - info.version = br.readUInt32LE(); - info.prevHash = br.read(32); - info.merkleRoot = br.read(32); - info.time = br.readUInt32LE(); - info.bits = br.readUInt32LE(); - info.nonce = br.readUInt32LE(); - return info; -}; - -/** - * @param {BufferReader} - A BufferReader of the block header - * @returns {BlockHeader} - An instance of block header - */ -BlockHeader.fromBufferReader = function fromBufferReader(br) { - var info = BlockHeader._fromBufferReader(br); - return new BlockHeader(info); -}; - -/** - * @returns {Object} - A plain object of the BlockHeader - */ -BlockHeader.prototype.toObject = function toObject() { - return { - version: this.version, - prevHash: this.prevHash.toString('hex'), - merkleRoot: this.merkleRoot.toString('hex'), - time: this.time, - bits: this.bits, - nonce: this.nonce - }; -}; - -/** - * @returns {String} - A JSON string - */ -BlockHeader.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -/** - * @returns {Buffer} - A Buffer of the BlockHeader - */ -BlockHeader.prototype.toBuffer = function toBuffer() { - return this.toBufferWriter().concat(); -}; - -/** - * @returns {String} - A hex encoded string of the BlockHeader - */ -BlockHeader.prototype.toString = function toString() { - return this.toBuffer().toString('hex'); -}; - -/** - * @param {BufferWriter} - An existing instance BufferWriter - * @returns {BufferWriter} - An instance of BufferWriter representation of the BlockHeader - */ -BlockHeader.prototype.toBufferWriter = function toBufferWriter(bw) { - if (!bw) { - bw = new BufferWriter(); - } - bw.writeUInt32LE(this.version); - bw.write(this.prevHash); - bw.write(this.merkleRoot); - bw.writeUInt32LE(this.time); - bw.writeUInt32LE(this.bits); - bw.writeUInt32LE(this.nonce); - return bw; -}; - -/** - * @link https://en.bitcoin.it/wiki/Difficulty - * @returns {BN} - An instance of BN with the decoded difficulty bits - */ -BlockHeader.prototype.getTargetDifficulty = function getTargetDifficulty(info) { - var target = new BN(this.bits & 0xffffff); - var mov = 8 * ((this.bits >>> 24) - 3); - while (mov-- > 0) { - target = target.mul(new BN(2)); - } - return target; -}; - -/** - * @returns {Buffer} - The little endian hash buffer of the header - */ -BlockHeader.prototype._getHash = function hash() { - var buf = this.toBuffer(); - return Hash.sha256sha256(buf); -}; - -var idProperty = { - configurable: false, - writeable: false, - enumerable: true, - /** - * @returns {string} - The big endian hash buffer of the header - */ - get: function() { - if (!this._id) { - this._id = BufferReader(this._getHash()).readReverse().toString('hex'); - } - return this._id; - }, - set: _.noop -}; -Object.defineProperty(BlockHeader.prototype, 'id', idProperty); -Object.defineProperty(BlockHeader.prototype, 'hash', idProperty); - -/** - * @returns {Boolean} - If timestamp is not too far in the future - */ -BlockHeader.prototype.validTimestamp = function validTimestamp() { - var currentTime = Math.round(new Date().getTime() / 1000); - if (this.time > currentTime + BlockHeader.Constants.MAX_TIME_OFFSET) { - return false; - } - return true; -}; - -/** - * @returns {Boolean} - If the proof-of-work hash satisfies the target difficulty - */ -BlockHeader.prototype.validProofOfWork = function validProofOfWork() { - var pow = new BN(this.id, 'hex'); - var target = this.getTargetDifficulty(); - - if (pow.cmp(target) > 0) { - return false; - } - return true; -}; - -/** - * @returns {String} - A string formated for the console - */ -BlockHeader.prototype.inspect = function inspect() { - return ''; -}; - -BlockHeader.Constants = { - START_OF_HEADER: 8, // Start buffer position in raw block data - MAX_TIME_OFFSET: 2 * 60 * 60, // The max a timestamp can be in the future - LARGEST_HASH: new BN('10000000000000000000000000000000000000000000000000000000000000000', 'hex') -}; - -module.exports = BlockHeader; - -}).call(this,require("buffer").Buffer) -},{"./crypto/bn":34,"./crypto/hash":36,"./encoding/bufferreader":42,"./encoding/bufferwriter":43,"./util/buffer":69,"./util/js":70,"buffer":209,"lodash":95}],34:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var BN = require('bn.js'); -var $ = require('../util/preconditions'); -var _ = require('lodash'); - -var reversebuf = function(buf) { - var buf2 = new Buffer(buf.length); - for (var i = 0; i < buf.length; i++) { - buf2[i] = buf[buf.length - 1 - i]; - } - return buf2; -}; - -BN.Zero = new BN(0); -BN.One = new BN(1); -BN.Minus1 = new BN(-1); - -BN.fromNumber = function(n) { - $.checkArgument(_.isNumber(n)); - return new BN(n); -}; - -BN.fromString = function(str) { - $.checkArgument(_.isString(str)); - return new BN(str); -}; - -BN.fromBuffer = function(buf, opts) { - if (typeof opts !== 'undefined' && opts.endian === 'little') { - buf = reversebuf(buf); - } - var hex = buf.toString('hex'); - var bn = new BN(hex, 16); - return bn; -}; - -/** - * Instantiate a BigNumber from a "signed magnitude buffer" - * (a buffer where the most significant bit represents the sign (0 = positive, -1 = negative)) - */ -BN.fromSM = function(buf, opts) { - var ret; - if (buf.length === 0) { - return BN.fromBuffer(new Buffer([0])); - } - - var endian = 'big'; - if (opts) { - endian = opts.endian; - } - if (endian === 'little') { - buf = reversebuf(buf); - } - - if (buf[0] & 0x80) { - buf[0] = buf[0] & 0x7f; - ret = BN.fromBuffer(buf); - ret.neg().copy(ret); - } else { - ret = BN.fromBuffer(buf); - } - return ret; -}; - - -BN.prototype.toNumber = function() { - return parseInt(this.toString(10), 10); -}; - -BN.prototype.toBuffer = function(opts) { - var buf, hex; - if (opts && opts.size) { - hex = this.toString(16, 2); - var natlen = hex.length / 2; - buf = new Buffer(hex, 'hex'); - - if (natlen === opts.size) { - buf = buf; - } else if (natlen > opts.size) { - buf = BN.trim(buf, natlen); - } else if (natlen < opts.size) { - buf = BN.pad(buf, natlen, opts.size); - } - } else { - hex = this.toString(16, 2); - buf = new Buffer(hex, 'hex'); - } - - if (typeof opts !== 'undefined' && opts.endian === 'little') { - buf = reversebuf(buf); - } - - return buf; -}; - -BN.prototype.toSMBigEndian = function() { - var buf; - if (this.cmp(BN.Zero) === -1) { - buf = this.neg().toBuffer(); - if (buf[0] & 0x80) { - buf = Buffer.concat([new Buffer([0x80]), buf]); - } else { - buf[0] = buf[0] | 0x80; - } - } else { - buf = this.toBuffer(); - if (buf[0] & 0x80) { - buf = Buffer.concat([new Buffer([0x00]), buf]); - } - } - - if (buf.length === 1 & buf[0] === 0) { - buf = new Buffer([]); - } - return buf; -}; - -BN.prototype.toSM = function(opts) { - var endian = opts ? opts.endian : 'big'; - var buf = this.toSMBigEndian(); - - if (endian === 'little') { - buf = reversebuf(buf); - } - return buf; -}; - -/** - * Create a BN from a "ScriptNum": - * This is analogous to the constructor for CScriptNum in bitcoind. Many ops in - * bitcoind's script interpreter use CScriptNum, which is not really a proper - * bignum. Instead, an error is thrown if trying to input a number bigger than - * 4 bytes. We copy that behavior here. - */ -BN.fromScriptNumBuffer = function(buf, fRequireMinimal) { - var nMaxNumSize = 4; - $.checkArgument(buf.length <= nMaxNumSize, new Error('script number overflow')); - if (fRequireMinimal && buf.length > 0) { - // Check that the number is encoded with the minimum possible - // number of bytes. - // - // If the most-significant-byte - excluding the sign bit - is zero - // then we're not minimal. Note how this test also rejects the - // negative-zero encoding, 0x80. - if ((buf[buf.length - 1] & 0x7f) === 0) { - // One exception: if there's more than one byte and the most - // significant bit of the second-most-significant-byte is set - // it would conflict with the sign bit. An example of this case - // is +-255, which encode to 0xff00 and 0xff80 respectively. - // (big-endian). - if (buf.length <= 1 || (buf[buf.length - 2] & 0x80) === 0) { - throw new Error('non-minimally encoded script number'); - } - } - } - return BN.fromSM(buf, { - endian: 'little' - }); -}; - -/** - * The corollary to the above, with the notable exception that we do not throw - * an error if the output is larger than four bytes. (Which can happen if - * performing a numerical operation that results in an overflow to more than 4 - * bytes). - */ -BN.prototype.toScriptNumBuffer = function() { - return this.toSM({ - endian: 'little' - }); -}; - -BN.prototype.gt = function(b) { - return this.cmp(b) > 0; -}; - -BN.prototype.lt = function(b) { - return this.cmp(b) < 0; -}; - -BN.trim = function(buf, natlen) { - return buf.slice(natlen - buf.length, buf.length); -}; - -BN.pad = function(buf, natlen, size) { - var rbuf = new Buffer(size); - for (var i = 0; i < buf.length; i++) { - rbuf[rbuf.length - 1 - i] = buf[buf.length - 1 - i]; - } - for (i = 0; i < size - natlen; i++) { - rbuf[i] = 0; - } - return rbuf; -}; - -module.exports = BN; - -}).call(this,require("buffer").Buffer) -},{"../util/preconditions":71,"bn.js":72,"buffer":209,"lodash":95}],35:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var BN = require('./bn'); -var Point = require('./point'); -var Signature = require('./signature'); -var PublicKey = require('../publickey'); -var Random = require('./random'); -var Hash = require('./hash'); -var BufferUtil = require('../util/buffer'); -var _ = require('lodash'); -var $ = require('../util/preconditions'); - -var ECDSA = function ECDSA(obj) { - if (!(this instanceof ECDSA)) { - return new ECDSA(obj); - } - if (obj) { - this.set(obj); - } -}; - -/* jshint maxcomplexity: 9 */ -ECDSA.prototype.set = function(obj) { - this.hashbuf = obj.hashbuf || this.hashbuf; - this.endian = obj.endian || this.endian; //the endianness of hashbuf - this.privkey = obj.privkey || this.privkey; - this.pubkey = obj.pubkey || (this.privkey ? this.privkey.publicKey : this.pubkey); - this.sig = obj.sig || this.sig; - this.k = obj.k || this.k; - this.verified = obj.verified || this.verified; - return this; -}; - -ECDSA.prototype.privkey2pubkey = function() { - this.pubkey = this.privkey.toPublicKey(); -}; - -ECDSA.prototype.calci = function() { - for (var i = 0; i < 4; i++) { - this.sig.i = i; - var Qprime; - try { - Qprime = this.toPublicKey(); - } catch (e) { - console.error(e); - continue; - } - - if (Qprime.point.eq(this.pubkey.point)) { - this.sig.compressed = this.pubkey.compressed; - return this; - } - } - - this.sig.i = undefined; - throw new Error('Unable to find valid recovery factor'); -}; - -ECDSA.fromString = function(str) { - var obj = JSON.parse(str); - return new ECDSA(obj); -}; - -ECDSA.prototype.randomK = function() { - var N = Point.getN(); - var k; - do { - k = BN.fromBuffer(Random.getRandomBuffer(32)); - } while (!(k.lt(N) && k.gt(BN.Zero))); - this.k = k; - return this; -}; - - -// https://tools.ietf.org/html/rfc6979#section-3.2 -ECDSA.prototype.deterministicK = function(badrs) { - /* jshint maxstatements: 25 */ - // if r or s were invalid when this function was used in signing, - // we do not want to actually compute r, s here for efficiency, so, - // we can increment badrs. explained at end of RFC 6979 section 3.2 - if (_.isUndefined(badrs)) { - badrs = 0; - } - var v = new Buffer(32); - v.fill(0x01); - var k = new Buffer(32); - k.fill(0x00); - var x = this.privkey.bn.toBuffer({ - size: 32 - }); - k = Hash.sha256hmac(Buffer.concat([v, new Buffer([0x00]), x, this.hashbuf]), k); - v = Hash.sha256hmac(v, k); - k = Hash.sha256hmac(Buffer.concat([v, new Buffer([0x01]), x, this.hashbuf]), k); - v = Hash.sha256hmac(v, k); - v = Hash.sha256hmac(v, k); - var T = BN.fromBuffer(v); - var N = Point.getN(); - - // also explained in 3.2, we must ensure T is in the proper range (0, N) - for (var i = 0; i < badrs || !(T.lt(N) && T.gt(BN.Zero)); i++) { - k = Hash.sha256hmac(Buffer.concat([v, new Buffer([0x00])]), k); - v = Hash.sha256hmac(v, k); - v = Hash.sha256hmac(v, k); - T = BN.fromBuffer(v); - } - - this.k = T; - return this; -}; - -// Information about public key recovery: -// https://bitcointalk.org/index.php?topic=6430.0 -// http://stackoverflow.com/questions/19665491/how-do-i-get-an-ecdsa-public-key-from-just-a-bitcoin-signature-sec1-4-1-6-k -ECDSA.prototype.toPublicKey = function() { - /* jshint maxstatements: 25 */ - var i = this.sig.i; - $.checkArgument(i === 0 || i === 1 || i === 2 || i === 3, new Error('i must be equal to 0, 1, 2, or 3')); - - var e = BN.fromBuffer(this.hashbuf); - var r = this.sig.r; - var s = this.sig.s; - - // A set LSB signifies that the y-coordinate is odd - var isYOdd = i & 1; - - // The more significant bit specifies whether we should use the - // first or second candidate key. - var isSecondKey = i >> 1; - - var n = Point.getN(); - var G = Point.getG(); - - // 1.1 Let x = r + jn - var x = isSecondKey ? r.add(n) : r; - var R = Point.fromX(isYOdd, x); - - // 1.4 Check that nR is at infinity - var nR = R.mul(n); - - if (!nR.isInfinity()) { - throw new Error('nR is not a valid curve point'); - } - - // Compute -e from e - var eNeg = e.neg().mod(n); - - // 1.6.1 Compute Q = r^-1 (sR - eG) - // Q = r^-1 (sR + -eG) - var rInv = r.invm(n); - - //var Q = R.multiplyTwo(s, G, eNeg).mul(rInv); - var Q = R.mul(s).add(G.mul(eNeg)).mul(rInv); - - var pubkey = PublicKey.fromPoint(Q, this.sig.compressed); - - return pubkey; -}; - -ECDSA.prototype.sigError = function() { - /* jshint maxstatements: 25 */ - if (!BufferUtil.isBuffer(this.hashbuf) || this.hashbuf.length !== 32) { - return 'hashbuf must be a 32 byte buffer'; - } - - var r = this.sig.r; - var s = this.sig.s; - if (!(r.gt(BN.Zero) && r.lt(Point.getN())) || !(s.gt(BN.Zero) && s.lt(Point.getN()))) { - return 'r and s not in range'; - } - - var e = BN.fromBuffer(this.hashbuf, this.endian ? { - endian: this.endian - } : undefined); - var n = Point.getN(); - var sinv = s.invm(n); - var u1 = sinv.mul(e).mod(n); - var u2 = sinv.mul(r).mod(n); - - var p = Point.getG().mulAdd(u1, this.pubkey.point, u2); - if (p.isInfinity()) { - return 'p is infinity'; - } - - if (p.getX().mod(n).cmp(r) !== 0) { - return 'Invalid signature'; - } else { - return false; - } -}; - -ECDSA.toLowS = function(s) { - //enforce low s - //see BIP 62, "low S values in signatures" - if (s.gt(BN.fromBuffer(new Buffer('7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0', 'hex')))) { - s = Point.getN().sub(s); - } - return s; -}; - -ECDSA.prototype._findSignature = function(d, e) { - var N = Point.getN(); - var G = Point.getG(); - // try different values of k until r, s are valid - var badrs = 0; - var k, Q, r, s; - do { - if (!this.k || badrs > 0) { - this.deterministicK(badrs); - } - badrs++; - k = this.k; - Q = G.mul(k); - r = Q.x.mod(N); - s = k.invm(N).mul(e.add(d.mul(r))).mod(N); - } while (r.cmp(BN.Zero) <= 0 || s.cmp(BN.Zero) <= 0); - - s = ECDSA.toLowS(s); - return { - s: s, - r: r - }; - -}; - -ECDSA.prototype.sign = function() { - var hashbuf = this.hashbuf; - var privkey = this.privkey; - var d = privkey.bn; - - $.checkState(hashbuf && privkey && d, new Error('invalid parameters')); - $.checkState(BufferUtil.isBuffer(hashbuf) && hashbuf.length === 32, new Error('hashbuf must be a 32 byte buffer')); - - var e = BN.fromBuffer(hashbuf, this.endian ? { - endian: this.endian - } : undefined); - - var obj = this._findSignature(d, e); - obj.compressed = this.pubkey.compressed; - - this.sig = new Signature(obj); - return this; -}; - -ECDSA.prototype.signRandomK = function() { - this.randomK(); - return this.sign(); -}; - -ECDSA.prototype.toString = function() { - var obj = {}; - if (this.hashbuf) { - obj.hashbuf = this.hashbuf.toString('hex'); - } - if (this.privkey) { - obj.privkey = this.privkey.toString(); - } - if (this.pubkey) { - obj.pubkey = this.pubkey.toString(); - } - if (this.sig) { - obj.sig = this.sig.toString(); - } - if (this.k) { - obj.k = this.k.toString(); - } - return JSON.stringify(obj); -}; - -ECDSA.prototype.verify = function() { - if (!this.sigError()) { - this.verified = true; - } else { - this.verified = false; - } - return this; -}; - -ECDSA.sign = function(hashbuf, privkey, endian) { - return ECDSA().set({ - hashbuf: hashbuf, - endian: endian, - privkey: privkey - }).sign().sig; -}; - -ECDSA.verify = function(hashbuf, sig, pubkey, endian) { - return ECDSA().set({ - hashbuf: hashbuf, - endian: endian, - sig: sig, - pubkey: pubkey - }).verify().verified; -}; - -module.exports = ECDSA; - -}).call(this,require("buffer").Buffer) -},{"../publickey":53,"../util/buffer":69,"../util/preconditions":71,"./bn":34,"./hash":36,"./point":37,"./random":38,"./signature":39,"buffer":209,"lodash":95}],36:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var hashjs = require('hash.js'); -var sha512 = require('sha512'); -var crypto = require('crypto'); -var BufferUtil = require('../util/buffer'); -var $ = require('../util/preconditions'); - -var Hash = module.exports; - -Hash.sha1 = function(buf) { - $.checkArgument(BufferUtil.isBuffer(buf)); - return crypto.createHash('sha1').update(buf).digest(); -}; - -Hash.sha1.blocksize = 512; - -Hash.sha256 = function(buf) { - $.checkArgument(BufferUtil.isBuffer(buf)); - return crypto.createHash('sha256').update(buf).digest(); -}; - -Hash.sha256.blocksize = 512; - -Hash.sha256sha256 = function(buf) { - $.checkArgument(BufferUtil.isBuffer(buf)); - return Hash.sha256(Hash.sha256(buf)); -}; - -Hash.ripemd160 = function(buf) { - $.checkArgument(BufferUtil.isBuffer(buf)); - var hash = (new hashjs.ripemd160()).update(buf).digest(); - return new Buffer(hash); -}; - -Hash.sha256ripemd160 = function(buf) { - $.checkArgument(BufferUtil.isBuffer(buf)); - return Hash.ripemd160(Hash.sha256(buf)); -}; - -Hash.sha512 = function(buf) { - $.checkArgument(BufferUtil.isBuffer(buf)); - var hash = sha512(buf); - return new Buffer(hash); -}; - -Hash.sha512.blocksize = 1024; - -Hash.hmac = function(hashf, data, key) { - //http://en.wikipedia.org/wiki/Hash-based_message_authentication_code - //http://tools.ietf.org/html/rfc4868#section-2 - $.checkArgument(BufferUtil.isBuffer(data)); - $.checkArgument(BufferUtil.isBuffer(key)); - $.checkArgument(hashf.blocksize); - - var blocksize = hashf.blocksize / 8; - - if (key.length > blocksize) { - key = hashf(key); - } else if (key < blocksize) { - var fill = new Buffer(blocksize); - fill.fill(0); - key.copy(fill); - key = fill; - } - - var o_key = new Buffer(blocksize); - o_key.fill(0x5c); - - var i_key = new Buffer(blocksize); - i_key.fill(0x36); - - var o_key_pad = new Buffer(blocksize); - var i_key_pad = new Buffer(blocksize); - for (var i = 0; i < blocksize; i++) { - o_key_pad[i] = o_key[i] ^ key[i]; - i_key_pad[i] = i_key[i] ^ key[i]; - } - - return hashf(Buffer.concat([o_key_pad, hashf(Buffer.concat([i_key_pad, data]))])); -}; - -Hash.sha256hmac = function(data, key) { - return Hash.hmac(Hash.sha256, data, key); -}; - -Hash.sha512hmac = function(data, key) { - return Hash.hmac(Hash.sha512, data, key); -}; - -}).call(this,require("buffer").Buffer) -},{"../util/buffer":69,"../util/preconditions":71,"buffer":209,"crypto":213,"hash.js":88,"sha512":98}],37:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var BN = require('./bn'); -var BufferUtil = require('../util/buffer'); -var ec = require('elliptic').curves.secp256k1; -var ecPoint = ec.curve.point.bind(ec.curve); -var ecPointFromX = ec.curve.pointFromX.bind(ec.curve); - -/** - * - * Instantiate a valid secp256k1 Point from the X and Y coordinates. - * - * @param {BN|String} x - The X coordinate - * @param {BN|String} y - The Y coordinate - * @link https://github.com/indutny/elliptic - * @augments elliptic.curve.point - * @throws {Error} A validation error if exists - * @returns {Point} An instance of Point - * @constructor - */ -var Point = function Point(x, y, isRed) { - var point = ecPoint(x, y, isRed); - point.validate(); - return point; -}; - -Point.prototype = Object.getPrototypeOf(ec.curve.point()); - -/** - * - * Instantiate a valid secp256k1 Point from only the X coordinate - * - * @param {boolean} odd - If the Y coordinate is odd - * @param {BN|String} x - The X coordinate - * @throws {Error} A validation error if exists - * @returns {Point} An instance of Point - */ -Point.fromX = function fromX(odd, x){ - var point = ecPointFromX(odd, x); - point.validate(); - return point; -}; - -/** - * - * Will return a secp256k1 ECDSA base point. - * - * @link https://en.bitcoin.it/wiki/Secp256k1 - * @returns {Point} An instance of the base point. - */ -Point.getG = function getG() { - return ec.curve.g; -}; - -/** - * - * Will return the max of range of valid private keys as governed by the secp256k1 ECDSA standard. - * - * @link https://en.bitcoin.it/wiki/Private_key#Range_of_valid_ECDSA_private_keys - * @returns {BN} A BN instance of the number of points on the curve - */ -Point.getN = function getN() { - return new BN(ec.curve.n.toArray()); -}; - -Point.prototype._getX = Point.prototype.getX; - -/** - * - * Will return the X coordinate of the Point - * - * @returns {BN} A BN instance of the X coordinate - */ -Point.prototype.getX = function getX() { - return new BN(this._getX().toArray()); -}; - -Point.prototype._getY = Point.prototype.getY; - -/** - * - * Will return the Y coordinate of the Point - * - * @returns {BN} A BN instance of the Y coordinate - */ -Point.prototype.getY = function getY() { - return new BN(this._getY().toArray()); -}; - -/** - * - * Will determine if the point is valid - * - * @link https://www.iacr.org/archive/pkc2003/25670211/25670211.pdf - * @param {Point} An instance of Point - * @throws {Error} A validation error if exists - * @returns {Point} An instance of the same Point - */ -Point.prototype.validate = function validate() { - - if (this.isInfinity()){ - throw new Error('Point cannot be equal to Infinity'); - } - - if (this.getX().cmp(BN.Zero) === 0 || this.getY().cmp(BN.Zero) === 0){ - throw new Error('Invalid x,y value for curve, cannot equal 0.'); - } - - var p2 = ecPointFromX(this.getY().isOdd(), this.getX()); - - if (p2.y.cmp(this.y) !== 0) { - throw new Error('Invalid y value for curve.'); - } - - var xValidRange = (this.getX().gt(BN.Minus1) && this.getX().lt(Point.getN())); - var yValidRange = (this.getY().gt(BN.Minus1) && this.getY().lt(Point.getN())); - - if ( !xValidRange || !yValidRange ) { - throw new Error('Point does not lie on the curve'); - } - - //todo: needs test case - if (!(this.mul(Point.getN()).isInfinity())) { - throw new Error('Point times N must be infinity'); - } - - return this; - -}; - -Point.pointToCompressed = function pointToCompressed(point) { - var xbuf = point.getX().toBuffer({size: 32}); - var ybuf = point.getY().toBuffer({size: 32}); - - var prefix; - var odd = ybuf[ybuf.length - 1] % 2; - if (odd) { - prefix = new Buffer([0x03]); - } else { - prefix = new Buffer([0x02]); - } - return BufferUtil.concat([prefix, xbuf]); -}; - -module.exports = Point; - -}).call(this,require("buffer").Buffer) -},{"../util/buffer":69,"./bn":34,"buffer":209,"elliptic":74}],38:[function(require,module,exports){ -(function (process,Buffer){ -'use strict'; - -function Random() { -} - -/* secure random bytes that sometimes throws an error due to lack of entropy */ -Random.getRandomBuffer = function(size) { - if (process.browser) - return Random.getRandomBufferBrowser(size); - else - return Random.getRandomBufferNode(size); -}; - -Random.getRandomBufferNode = function(size) { - var crypto = require('crypto'); - return crypto.randomBytes(size); -}; - -Random.getRandomBufferBrowser = function(size) { - if (!window.crypto && !window.msCrypto) - throw new Error('window.crypto not available'); - - if (window.crypto && window.crypto.getRandomValues) - var crypto = window.crypto; - else if (window.msCrypto && window.msCrypto.getRandomValues) //internet explorer - var crypto = window.msCrypto; - else - throw new Error('window.crypto.getRandomValues not available'); - - var bbuf = new Uint8Array(size); - crypto.getRandomValues(bbuf); - var buf = new Buffer(bbuf); - - return buf; -}; - -/* insecure random bytes, but it never fails */ -Random.getPseudoRandomBuffer = function(size) { - var b32 = 0x100000000; - var b = new Buffer(size); - var r; - - for (var i = 0; i <= size; i++) { - var j = Math.floor(i / 4); - var k = i - j * 4; - if (k === 0) { - r = Math.random() * b32; - b[i] = r & 0xff; - } else { - b[i] = (r = r >>> 8) & 0xff; - } - } - - return b; -}; - -module.exports = Random; - -}).call(this,require('_process'),require("buffer").Buffer) -},{"_process":357,"buffer":209,"crypto":213}],39:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var BN = require('./bn'); -var _ = require('lodash'); -var $ = require('../util/preconditions'); -var BufferUtil = require('../util/buffer'); - -var Signature = function Signature(r, s) { - if (!(this instanceof Signature)) { - return new Signature(r, s); - } - if (r instanceof BN) { - this.set({ - r: r, - s: s - }); - } else if (r) { - var obj = r; - this.set(obj); - } -}; - -/* jshint maxcomplexity: 7 */ -Signature.prototype.set = function(obj) { - this.r = obj.r || this.r || undefined; - this.s = obj.s || this.s || undefined; - this.i = typeof obj.i !== 'undefined' ? obj.i : this.i; //public key recovery parameter in range [0, 3] - this.compressed = typeof obj.compressed !== 'undefined' ? - obj.compressed : this.compressed; //whether the recovered pubkey is compressed - return this; -}; - -Signature.fromCompact = function(buf) { - var sig = new Signature(); - //TODO: handle uncompressed pubkeys - var compressed = true; - var i = buf.slice(0, 1)[0] - 27 - 4; - var b2 = buf.slice(1, 33); - var b3 = buf.slice(33, 65); - - $.checkArgument(i === 0 || i === 1 || i === 2 || i === 3, new Error('i must be 0, 1, 2, or 3')); - $.checkArgument(b2.length === 32, new Error('r must be 32 bytes')); - $.checkArgument(b3.length === 32, new Error('s must be 32 bytes')); - - sig.compressed = compressed; - sig.i = i; - sig.r = BN.fromBuffer(b2); - sig.s = BN.fromBuffer(b3); - - return sig; -}; - -Signature.fromDER = Signature.fromBuffer = function(buf, strict) { - var obj = Signature.parseDER(buf, strict); - var sig = new Signature(); - - sig.r = obj.r; - sig.s = obj.s; - - return sig; -}; - -// The format used in a tx -Signature.fromTxFormat = function(buf) { - var nhashtype = buf.readUInt8(buf.length - 1); - var derbuf = buf.slice(0, buf.length - 1); - var sig = new Signature.fromDER(derbuf, false); - sig.nhashtype = nhashtype; - return sig; -}; - -Signature.fromString = function(str) { - var buf = new Buffer(str, 'hex'); - return Signature.fromDER(buf); -}; - - -/** - * In order to mimic the non-strict DER encoding of OpenSSL, set strict = false. - */ -Signature.parseDER = function(buf, strict) { - $.checkArgument(BufferUtil.isBuffer(buf), new Error('DER formatted signature should be a buffer')); - if (_.isUndefined(strict)) { - strict = true; - } - - var header = buf[0]; - $.checkArgument(header === 0x30, new Error('Header byte should be 0x30')); - - var length = buf[1]; - var buflength = buf.slice(2).length; - $.checkArgument(!strict || length === buflength, new Error('Length byte should length of what follows')); - - length = length < buflength ? length : buflength; - - var rheader = buf[2 + 0]; - $.checkArgument(rheader === 0x02, new Error('Integer byte for r should be 0x02')); - - var rlength = buf[2 + 1]; - var rbuf = buf.slice(2 + 2, 2 + 2 + rlength); - var r = BN.fromBuffer(rbuf); - var rneg = buf[2 + 1 + 1] === 0x00 ? true : false; - $.checkArgument(rlength === rbuf.length, new Error('Length of r incorrect')); - - var sheader = buf[2 + 2 + rlength + 0]; - $.checkArgument(sheader === 0x02, new Error('Integer byte for s should be 0x02')); - - var slength = buf[2 + 2 + rlength + 1]; - var sbuf = buf.slice(2 + 2 + rlength + 2, 2 + 2 + rlength + 2 + slength); - var s = BN.fromBuffer(sbuf); - var sneg = buf[2 + 2 + rlength + 2 + 2] === 0x00 ? true : false; - $.checkArgument(slength === sbuf.length, new Error('Length of s incorrect')); - - var sumlength = 2 + 2 + rlength + 2 + slength; - $.checkArgument(length === sumlength - 2, new Error('Length of signature incorrect')); - - var obj = { - header: header, - length: length, - rheader: rheader, - rlength: rlength, - rneg: rneg, - rbuf: rbuf, - r: r, - sheader: sheader, - slength: slength, - sneg: sneg, - sbuf: sbuf, - s: s - }; - - return obj; -}; - - -Signature.prototype.toCompact = function(i, compressed) { - i = typeof i === 'number' ? i : this.i; - compressed = typeof compressed === 'boolean' ? compressed : this.compressed; - - if (!(i === 0 || i === 1 || i === 2 || i === 3)) { - throw new Error('i must be equal to 0, 1, 2, or 3'); - } - - var val = i + 27 + 4; - if (compressed === false) - val = val - 4; - var b1 = new Buffer([val]); - var b2 = this.r.toBuffer({ - size: 32 - }); - var b3 = this.s.toBuffer({ - size: 32 - }); - return Buffer.concat([b1, b2, b3]); -}; - -Signature.prototype.toBuffer = Signature.prototype.toDER = function() { - var rnbuf = this.r.toBuffer(); - var snbuf = this.s.toBuffer(); - - var rneg = rnbuf[0] & 0x80 ? true : false; - var sneg = snbuf[0] & 0x80 ? true : false; - - var rbuf = rneg ? Buffer.concat([new Buffer([0x00]), rnbuf]) : rnbuf; - var sbuf = sneg ? Buffer.concat([new Buffer([0x00]), snbuf]) : snbuf; - - var rlength = rbuf.length; - var slength = sbuf.length; - var length = 2 + rlength + 2 + slength; - var rheader = 0x02; - var sheader = 0x02; - var header = 0x30; - - var der = Buffer.concat([new Buffer([header, length, rheader, rlength]), rbuf, new Buffer([sheader, slength]), sbuf]); - return der; -}; - -Signature.prototype.toString = function() { - var buf = this.toDER(); - return buf.toString('hex'); -}; - -/** - * This function is translated from bitcoind's IsDERSignature and is used in - * the script interpreter. This "DER" format actually includes an extra byte, - * the nhashtype, at the end. It is really the tx format, not DER format. - * - * A canonical signature exists of: [30] [total len] [02] [len R] [R] [02] [len S] [S] [hashtype] - * Where R and S are not negative (their first byte has its highest bit not set), and not - * excessively padded (do not start with a 0 byte, unless an otherwise negative number follows, - * in which case a single 0 byte is necessary and even required). - * - * See https://bitcointalk.org/index.php?topic=8392.msg127623#msg127623 - */ -Signature.isTxDER = function(buf) { - if (buf.length < 9) { - // Non-canonical signature: too short - return false; - } - if (buf.length > 73) { - // Non-canonical signature: too long - return false; - } - if (buf[0] !== 0x30) { - // Non-canonical signature: wrong type - return false; - } - if (buf[1] !== buf.length - 3) { - // Non-canonical signature: wrong length marker - return false; - } - var nLenR = buf[3]; - if (5 + nLenR >= buf.length) { - // Non-canonical signature: S length misplaced - return false; - } - var nLenS = buf[5 + nLenR]; - if ((nLenR + nLenS + 7) !== buf.length) { - // Non-canonical signature: R+S length mismatch - return false; - } - - var R = buf.slice(4); - if (buf[4 - 2] !== 0x02) { - // Non-canonical signature: R value type mismatch - return false; - } - if (nLenR === 0) { - // Non-canonical signature: R length is zero - return false; - } - if (R[0] & 0x80) { - // Non-canonical signature: R value negative - return false; - } - if (nLenR > 1 && (R[0] === 0x00) && !(R[1] & 0x80)) { - // Non-canonical signature: R value excessively padded - return false; - } - - var S = buf.slice(6 + nLenR); - if (buf[6 + nLenR - 2] !== 0x02) { - // Non-canonical signature: S value type mismatch - return false; - } - if (nLenS === 0) { - // Non-canonical signature: S length is zero - return false; - } - if (S[0] & 0x80) { - // Non-canonical signature: S value negative - return false; - } - if (nLenS > 1 && (S[0] === 0x00) && !(S[1] & 0x80)) { - // Non-canonical signature: S value excessively padded - return false; - } - return true; -}; - -/** - * Compares to bitcoind's IsLowDERSignature - * See also ECDSA signature algorithm which enforces this. - * See also BIP 62, "low S values in signatures" - */ -Signature.prototype.hasLowS = function() { - if (this.s.lt(new BN(1)) || - this.s.gt(new BN('7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0'))) { - return false; - } - return true; -}; - -/** - * @returns true if the nhashtype is exactly equal to one of the standard options or combinations thereof. - * Translated from bitcoind's IsDefinedHashtypeSignature - */ -Signature.prototype.hasDefinedHashtype = function() { - if (this.nhashtype < Signature.SIGHASH_ALL || this.nhashtype > Signature.SIGHASH_SINGLE) { - return false; - } - return true; -}; - -Signature.prototype.toTxFormat = function() { - var derbuf = this.toDER(); - var buf = new Buffer(1); - buf.writeUInt8(this.nhashtype, 0); - return Buffer.concat([derbuf, buf]); -}; - -Signature.SIGHASH_ALL = 0x01; -Signature.SIGHASH_NONE = 0x02; -Signature.SIGHASH_SINGLE = 0x03; -Signature.SIGHASH_ANYONECANPAY = 0x80; - -module.exports = Signature; - -}).call(this,require("buffer").Buffer) -},{"../util/buffer":69,"../util/preconditions":71,"./bn":34,"buffer":209,"lodash":95}],40:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); -var bs58 = require('bs58'); -var buffer = require('buffer'); - -var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'.split(''); - -var Base58 = function Base58(obj) { - /* jshint maxcomplexity: 8 */ - if (!(this instanceof Base58)) { - return new Base58(obj); - } - if (Buffer.isBuffer(obj)) { - var buf = obj; - this.fromBuffer(buf); - } else if (typeof obj === 'string') { - var str = obj; - this.fromString(str); - } else if (obj) { - this.set(obj); - } -}; - -Base58.validCharacters = function validCharacters(chars) { - if (buffer.Buffer.isBuffer(chars)) { - chars = chars.toString(); - } - return _.all(_.map(chars, function(char) { return _.contains(ALPHABET, char); })); -}; - -Base58.prototype.set = function(obj) { - this.buf = obj.buf || this.buf || undefined; - return this; -}; - -Base58.encode = function(buf) { - if (!buffer.Buffer.isBuffer(buf)) { - throw new Error('Input should be a buffer'); - } - return bs58.encode(buf); -}; - -Base58.decode = function(str) { - if (typeof str !== 'string') { - throw new Error('Input should be a string'); - } - return new Buffer(bs58.decode(str)); -}; - -Base58.prototype.fromBuffer = function(buf) { - this.buf = buf; - return this; -}; - -Base58.prototype.fromString = function(str) { - var buf = Base58.decode(str); - this.buf = buf; - return this; -}; - -Base58.prototype.toBuffer = function() { - return this.buf; -}; - -Base58.prototype.toString = function() { - return Base58.encode(this.buf); -}; - -module.exports = Base58; - -}).call(this,require("buffer").Buffer) -},{"bs58":73,"buffer":209,"lodash":95}],41:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); -var Base58 = require('./base58'); -var buffer = require('buffer'); -var sha256sha256 = require('../crypto/hash').sha256sha256; - -var Base58Check = function Base58Check(obj) { - if (!(this instanceof Base58Check)) - return new Base58Check(obj); - if (Buffer.isBuffer(obj)) { - var buf = obj; - this.fromBuffer(buf); - } else if (typeof obj === 'string') { - var str = obj; - this.fromString(str); - } else if (obj) { - this.set(obj); - } -}; - -Base58Check.prototype.set = function(obj) { - this.buf = obj.buf || this.buf || undefined; - return this; -}; - -Base58Check.validChecksum = function validChecksum(data, checksum) { - if (_.isString(data)) { - data = new buffer.Buffer(Base58.decode(data)); - } - if (_.isString(checksum)) { - checksum = new buffer.Buffer(Base58.decode(checksum)); - } - if (!checksum) { - checksum = data.slice(-4); - data = data.slice(0, -4); - } - return Base58Check.checksum(data).toString('hex') === checksum.toString('hex'); -}; - -Base58Check.decode = function(s) { - if (typeof s !== 'string') - throw new Error('Input must be a string'); - - var buf = new Buffer(Base58.decode(s)); - - if (buf.length < 4) - throw new Error("Input string too short"); - - var data = buf.slice(0, -4); - var csum = buf.slice(-4); - - var hash = sha256sha256(data); - var hash4 = hash.slice(0, 4); - - if (csum.toString('hex') !== hash4.toString('hex')) - throw new Error("Checksum mismatch"); - - return data; -}; - -Base58Check.checksum = function(buffer) { - return sha256sha256(buffer).slice(0, 4); -}; - -Base58Check.encode = function(buf) { - if (!Buffer.isBuffer(buf)) - throw new Error('Input must be a buffer'); - var checkedBuf = new Buffer(buf.length + 4); - var hash = Base58Check.checksum(buf); - buf.copy(checkedBuf); - hash.copy(checkedBuf, buf.length); - return Base58.encode(checkedBuf); -}; - -Base58Check.prototype.fromBuffer = function(buf) { - this.buf = buf; - return this; -}; - -Base58Check.prototype.fromString = function(str) { - var buf = Base58Check.decode(str); - this.buf = buf; - return this; -}; - -Base58Check.prototype.toBuffer = function() { - return this.buf; -}; - -Base58Check.prototype.toString = function() { - return Base58Check.encode(this.buf); -}; - -module.exports = Base58Check; - -}).call(this,require("buffer").Buffer) -},{"../crypto/hash":36,"./base58":40,"buffer":209,"lodash":95}],42:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); -var $ = require('../util/preconditions'); -var BufferUtil = require('../util/buffer'); -var BN = require('../crypto/bn'); - -var BufferReader = function BufferReader(buf) { - if (!(this instanceof BufferReader)) { - return new BufferReader(buf); - } - if (Buffer.isBuffer(buf)) { - this.set({ - buf: buf - }); - } else if (buf) { - var obj = buf; - this.set(obj); - } -}; - -BufferReader.prototype.set = function(obj) { - this.buf = obj.buf || this.buf || undefined; - this.pos = obj.pos || this.pos || 0; - return this; -}; - -BufferReader.prototype.eof = function() { - return this.pos >= this.buf.length; -}; - -BufferReader.prototype.finished = BufferReader.prototype.eof; - -BufferReader.prototype.read = function(len) { - $.checkArgument(!_.isUndefined(len), 'Must specify a length'); - var buf = this.buf.slice(this.pos, this.pos + len); - this.pos = this.pos + len; - return buf; -}; - -BufferReader.prototype.readAll = function() { - var buf = this.buf.slice(this.pos, this.buf.length); - this.pos = this.buf.length; - return buf; -}; - -BufferReader.prototype.readUInt8 = function() { - var val = this.buf.readUInt8(this.pos); - this.pos = this.pos + 1; - return val; -}; - -BufferReader.prototype.readUInt16BE = function() { - var val = this.buf.readUInt16BE(this.pos); - this.pos = this.pos + 2; - return val; -}; - -BufferReader.prototype.readUInt16LE = function() { - var val = this.buf.readUInt16LE(this.pos); - this.pos = this.pos + 2; - return val; -}; - -BufferReader.prototype.readUInt32BE = function() { - var val = this.buf.readUInt32BE(this.pos); - this.pos = this.pos + 4; - return val; -}; - -BufferReader.prototype.readUInt32LE = function() { - var val = this.buf.readUInt32LE(this.pos); - this.pos = this.pos + 4; - return val; -}; - -BufferReader.prototype.readUInt64BEBN = function() { - var buf = this.buf.slice(this.pos, this.pos + 8); - var bn = BN.fromBuffer(buf); - this.pos = this.pos + 8; - return bn; -}; - -BufferReader.prototype.readUInt64LEBN = function() { - var buf = this.buf.slice(this.pos, this.pos + 8); - var reversebuf = BufferReader({ - buf: buf - }).readReverse(); - var bn = BN.fromBuffer(reversebuf); - this.pos = this.pos + 8; - return bn; -}; - -BufferReader.prototype.readVarintNum = function() { - var first = this.readUInt8(); - switch (first) { - case 0xFD: - return this.readUInt16LE(); - case 0xFE: - return this.readUInt32LE(); - case 0xFF: - var bn = this.readUInt64LEBN(); - var n = bn.toNumber(); - if (n <= Math.pow(2, 53)) { - return n; - } else { - throw new Error('number too large to retain precision - use readVarintBN'); - } - break; - default: - return first; - } -}; - -/** - * reads a length prepended buffer - */ -BufferReader.prototype.readVarLengthBuffer = function() { - var len = this.readVarintNum(); - var buf = this.read(len); - $.checkState(buf.length === len, 'Invalid length while reading varlength buffer. ' + - 'Expected to read: ' + len + ' and read ' + buf.length); - return buf; -}; - -BufferReader.prototype.readVarintBuf = function() { - var first = this.buf.readUInt8(this.pos); - switch (first) { - case 0xFD: - return this.read(1 + 2); - case 0xFE: - return this.read(1 + 4); - case 0xFF: - return this.read(1 + 8); - default: - return this.read(1); - } -}; - -BufferReader.prototype.readVarintBN = function() { - var first = this.readUInt8(); - switch (first) { - case 0xFD: - return new BN(this.readUInt16LE()); - case 0xFE: - return new BN(this.readUInt32LE()); - case 0xFF: - return this.readUInt64LEBN(); - default: - return new BN(first); - } -}; - -BufferReader.prototype.reverse = function() { - var buf = new Buffer(this.buf.length); - for (var i = 0; i < buf.length; i++) { - buf[i] = this.buf[this.buf.length - 1 - i]; - } - this.buf = buf; - return this; -}; - -BufferReader.prototype.readReverse = function(len) { - if (_.isUndefined(len)) { - len = this.buf.length; - } - var buf = this.buf.slice(this.pos, this.pos + len); - this.pos = this.pos + len; - return BufferUtil.reverse(buf); -}; - -module.exports = BufferReader; - -}).call(this,require("buffer").Buffer) -},{"../crypto/bn":34,"../util/buffer":69,"../util/preconditions":71,"buffer":209,"lodash":95}],43:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var bufferUtil = require('../util/buffer'); -var assert = require('assert'); - -var BufferWriter = function BufferWriter(obj) { - if (!(this instanceof BufferWriter)) - return new BufferWriter(obj); - if (obj) - this.set(obj); - else - this.bufs = []; -}; - -BufferWriter.prototype.set = function(obj) { - this.bufs = obj.bufs || this.bufs || []; - return this; -}; - -BufferWriter.prototype.toBuffer = function() { - return this.concat(); -}; - -BufferWriter.prototype.concat = function() { - return Buffer.concat(this.bufs); -}; - -BufferWriter.prototype.write = function(buf) { - assert(bufferUtil.isBuffer(buf)); - this.bufs.push(buf); - return this; -}; - -BufferWriter.prototype.writeReverse = function(buf) { - assert(bufferUtil.isBuffer(buf)); - this.bufs.push(bufferUtil.reverse(buf)); - return this; -}; - -BufferWriter.prototype.writeUInt8 = function(n) { - var buf = new Buffer(1); - buf.writeUInt8(n, 0); - this.write(buf); - return this; -}; - -BufferWriter.prototype.writeUInt16BE = function(n) { - var buf = new Buffer(2); - buf.writeUInt16BE(n, 0); - this.write(buf); - return this; -}; - -BufferWriter.prototype.writeUInt16LE = function(n) { - var buf = new Buffer(2); - buf.writeUInt16LE(n, 0); - this.write(buf); - return this; -}; - -BufferWriter.prototype.writeUInt32BE = function(n) { - var buf = new Buffer(4); - buf.writeUInt32BE(n, 0); - this.write(buf); - return this; -}; - -BufferWriter.prototype.writeInt32LE = function(n) { - var buf = new Buffer(4); - buf.writeInt32LE(n, 0); - this.write(buf); - return this; -}; - -BufferWriter.prototype.writeUInt32LE = function(n) { - var buf = new Buffer(4); - buf.writeUInt32LE(n, 0); - this.write(buf); - return this; -}; - -BufferWriter.prototype.writeUInt64BEBN = function(bn) { - var buf = bn.toBuffer({size: 8}); - this.write(buf); - return this; -}; - -BufferWriter.prototype.writeUInt64LEBN = function(bn) { - var buf = bn.toBuffer({size: 8}); - var reversebuf = new Buffer(Array.apply(new Array(), buf).reverse()); - this.write(reversebuf); - return this; -}; - -BufferWriter.prototype.writeVarintNum = function(n) { - var buf = BufferWriter.varintBufNum(n); - this.write(buf); - return this; -}; - -BufferWriter.prototype.writeVarintBN = function(bn) { - var buf = BufferWriter.varintBufBN(bn); - this.write(buf); - return this; -}; - -BufferWriter.varintBufNum = function(n) { - var buf = undefined; - if (n < 253) { - buf = new Buffer(1); - buf.writeUInt8(n, 0); - } else if (n < 0x10000) { - buf = new Buffer(1 + 2); - buf.writeUInt8(253, 0); - buf.writeUInt16LE(n, 1); - } else if (n < 0x100000000) { - buf = new Buffer(1 + 4); - buf.writeUInt8(254, 0); - buf.writeUInt32LE(n, 1); - } else { - buf = new Buffer(1 + 8); - buf.writeUInt8(255, 0); - buf.writeInt32LE(n & -1, 1); - buf.writeUInt32LE(Math.floor(n / 0x100000000), 5); - } - return buf; -}; - -BufferWriter.varintBufBN = function(bn) { - var buf = undefined; - var n = bn.toNumber(); - if (n < 253) { - buf = new Buffer(1); - buf.writeUInt8(n, 0); - } else if (n < 0x10000) { - buf = new Buffer(1 + 2); - buf.writeUInt8(253, 0); - buf.writeUInt16LE(n, 1); - } else if (n < 0x100000000) { - buf = new Buffer(1 + 4); - buf.writeUInt8(254, 0); - buf.writeUInt32LE(n, 1); - } else { - var bw = new BufferWriter(); - bw.writeUInt8(255); - bw.writeUInt64LEBN(bn); - var buf = bw.concat(); - } - return buf; -}; - -module.exports = BufferWriter; - -}).call(this,require("buffer").Buffer) -},{"../util/buffer":69,"assert":194,"buffer":209}],44:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var BufferWriter = require('./bufferwriter'); -var BufferReader = require('./bufferreader'); -var BN = require('../crypto/bn'); - -var Varint = function Varint(buf) { - if (!(this instanceof Varint)) - return new Varint(buf); - if (Buffer.isBuffer(buf)) { - this.buf = buf; - } else if (typeof buf === 'number') { - var num = buf; - this.fromNumber(num); - } else if (buf instanceof BN) { - var bn = buf; - this.fromBN(bn); - } else if (buf) { - var obj = buf; - this.set(obj); - } -}; - -Varint.prototype.set = function(obj) { - this.buf = obj.buf || this.buf; - return this; -}; - -Varint.prototype.fromString = function(str) { - this.set({ - buf: new Buffer(str, 'hex') - }); - return this; -}; - -Varint.prototype.toString = function() { - return this.buf.toString('hex'); -}; - -Varint.prototype.fromBuffer = function(buf) { - this.buf = buf; - return this; -}; - -Varint.prototype.fromBufferReader = function(br) { - this.buf = br.readVarintBuf(); - return this; -}; - -Varint.prototype.fromBN = function(bn) { - this.buf = BufferWriter().writeVarintBN(bn).concat(); - return this; -}; - -Varint.prototype.fromNumber = function(num) { - this.buf = BufferWriter().writeVarintNum(num).concat(); - return this; -}; - -Varint.prototype.toBuffer = function() { - return this.buf; -}; - -Varint.prototype.toBN = function() { - return BufferReader(this.buf).readVarintBN(); -}; - -Varint.prototype.toNumber = function() { - return BufferReader(this.buf).readVarintNum(); -}; - -module.exports = Varint; - -}).call(this,require("buffer").Buffer) -},{"../crypto/bn":34,"./bufferreader":42,"./bufferwriter":43,"buffer":209}],45:[function(require,module,exports){ -'use strict'; - -var _ = require('lodash'); - -function format(message, args) { - return message - .replace('{0}', args[0]) - .replace('{1}', args[1]) - .replace('{2}', args[2]); -} -var traverseNode = function(parent, errorDefinition) { - var NodeError = function() { - if (_.isString(errorDefinition.message)) { - this.message = format(errorDefinition.message, arguments); - } else if (_.isFunction(errorDefinition.message)) { - this.message = errorDefinition.message.apply(null, arguments); - } else { - throw new Error('Invalid error definition for ' + errorDefinition.name); - } - this.stack = this.message + '\n' + (new Error()).stack; - }; - NodeError.prototype = Object.create(parent.prototype); - NodeError.prototype.name = parent.prototype.name + errorDefinition.name; - parent[errorDefinition.name] = NodeError; - if (errorDefinition.errors) { - childDefinitions(NodeError, errorDefinition.errors); - } - return NodeError; -}; - -/* jshint latedef: false */ -var childDefinitions = function(parent, childDefinitions) { - _.each(childDefinitions, function(childDefinition) { - traverseNode(parent, childDefinition); - }); -}; -/* jshint latedef: true */ - -var traverseRoot = function(parent, errorsDefinition) { - childDefinitions(parent, errorsDefinition); - return parent; -}; - - -var bitcore = {}; -bitcore.Error = function() { - this.message = 'Internal error'; - this.stack = this.message + '\n' + (new Error()).stack; -}; -bitcore.Error.prototype = Object.create(Error.prototype); -bitcore.Error.prototype.name = 'bitcore.Error'; - - -var data = require('./spec'); -traverseRoot(bitcore.Error, data); - -module.exports = bitcore.Error; - -module.exports.extend = function(spec) { - return traverseNode(bitcore.Error, spec); -}; - -},{"./spec":46,"lodash":95}],46:[function(require,module,exports){ -'use strict'; - -var docsURL = 'http://bitcore.io/'; - -module.exports = [{ - name: 'InvalidB58Char', - message: 'Invalid Base58 character: {0} in {1}' -}, { - name: 'InvalidB58Checksum', - message: 'Invalid Base58 checksum for {0}' -}, { - name: 'InvalidNetwork', - message: 'Invalid version for network: got {0}' -}, { - name: 'InvalidState', - message: 'Invalid state: {0}' -}, { - name: 'NotImplemented', - message: 'Function {0} was not implemented yet' -}, { - name: 'InvalidNetworkArgument', - message: 'Invalid network: must be "livenet" or "testnet", got {0}' -}, { - name: 'InvalidArgument', - message: function() { - return 'Invalid Argument' + (arguments[0] ? (': ' + arguments[0]) : '') + - (arguments[1] ? (' Documentation: ' + docsURL + arguments[1]) : ''); - } -}, { - name: 'AbstractMethodInvoked', - message: 'Abstract Method Invokation: {0}' -}, { - name: 'InvalidArgumentType', - message: function() { - return 'Invalid Argument for ' + arguments[2] + ', expected ' + arguments[1] + ' but got ' + typeof arguments[0]; - } -}, { - name: 'Unit', - message: 'Internal Error on Unit {0}', - errors: [{ - 'name': 'UnknownCode', - 'message': 'Unrecognized unit code: {0}' - }, { - 'name': 'InvalidRate', - 'message': 'Invalid exchange rate: {0}' - }] -}, { - name: 'Transaction', - message: 'Internal Error on Transaction {0}', - errors: [{ - name: 'Input', - message: 'Internal Error on Input {0}', - errors: [{ - name: 'MissingScript', - message: 'Need a script to create an input' - }, { - name: 'UnsupportedScript', - message: 'Unsupported input script type: {0}' - }] - }, { - name: 'NeedMoreInfo', - message: '{0}' - }, { - name: 'InvalidIndex', - message: 'Invalid index: {0} is not between 0, {1}' - }, { - name: 'UnableToVerifySignature', - message: 'Unable to verify signature: {0}' - }, { - name: 'DustOutputs', - message: 'Dust amount detected in one output' - }, { - name: 'FeeError', - message: 'Fees are not correctly set {0}', - }, { - name: 'ChangeAddressMissing', - message: 'Change address is missing' - }, { - name: 'BlockHeightTooHigh', - message: 'Block Height can be at most 2^32 -1' - }, { - name: 'NLockTimeOutOfRange', - message: 'Block Height can only be between 0 and 499 999 999' - }, { - name: 'LockTimeTooEarly', - message: 'Lock Time can\'t be earlier than UNIX date 500 000 000' - }] -}, { - name: 'Script', - message: 'Internal Error on Script {0}', - errors: [{ - name: 'UnrecognizedAddress', - message: 'Expected argument {0} to be an address' - }] -}, { - name: 'HDPrivateKey', - message: 'Internal Error on HDPrivateKey {0}', - errors: [{ - name: 'InvalidDerivationArgument', - message: 'Invalid derivation argument {0}, expected string, or number and boolean' - }, { - name: 'InvalidEntropyArgument', - message: 'Invalid entropy: must be an hexa string or binary buffer, got {0}', - errors: [{ - name: 'TooMuchEntropy', - message: 'Invalid entropy: more than 512 bits is non standard, got "{0}"' - }, { - name: 'NotEnoughEntropy', - message: 'Invalid entropy: at least 128 bits needed, got "{0}"' - }] - }, { - name: 'InvalidLength', - message: 'Invalid length for xprivkey string in {0}' - }, { - name: 'InvalidPath', - message: 'Invalid derivation path: {0}' - }, { - name: 'UnrecognizedArgument', - message: 'Invalid argument: creating a HDPrivateKey requires a string, buffer, json or object, got "{0}"' - }] -}, { - name: 'HDPublicKey', - message: 'Internal Error on HDPublicKey {0}', - errors: [{ - name: 'ArgumentIsPrivateExtended', - message: 'Argument is an extended private key: {0}' - }, { - name: 'InvalidDerivationArgument', - message: 'Invalid derivation argument: got {0}' - }, { - name: 'InvalidLength', - message: 'Invalid length for xpubkey: got "{0}"' - }, { - name: 'InvalidPath', - message: 'Invalid derivation path, it should look like: "m/1/100", got "{0}"' - }, { - name: 'MustSupplyArgument', - message: 'Must supply an argument to create a HDPublicKey' - }, { - name: 'UnrecognizedArgument', - message: 'Invalid argument for creation, must be string, json, buffer, or object' - }] -}]; - -},{}],47:[function(require,module,exports){ -'use strict'; - -module.exports = { - _cache: {}, - _count: 0, - _eraseIndex: 0, - _usedList: {}, - _usedIndex: {}, - _CACHE_SIZE: 5000, - - get: function(xkey, number, hardened) { - hardened = !!hardened; - var key = xkey + '/' + number + '/' + hardened; - if (this._cache[key]) { - this._cacheHit(key); - return this._cache[key]; - } - }, - set: function(xkey, number, hardened, derived) { - hardened = !!hardened; - var key = xkey + '/' + number + '/' + hardened; - this._cache[key] = derived; - this._cacheHit(key); - }, - _cacheHit: function(key) { - if (this._usedIndex[key]) { - delete this._usedList[this._usedIndex[key]]; - } - this._usedList[this._count] = key; - this._usedIndex[key] = this._count; - this._count++; - this._cacheRemove(); - }, - _cacheRemove: function() { - while (this._eraseIndex < this._count - this._CACHE_SIZE) { - if (this._usedList[this._eraseIndex]) { - var removeKey = this._usedList[this._eraseIndex]; - delete this._usedIndex[removeKey]; - delete this._cache[removeKey]; - } - delete this._usedList[this._eraseIndex]; - this._eraseIndex++; - } - } -}; - -},{}],48:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - - -var assert = require('assert'); -var buffer = require('buffer'); -var _ = require('lodash'); -var $ = require('./util/preconditions'); - -var BN = require('./crypto/bn'); -var Base58 = require('./encoding/base58'); -var Base58Check = require('./encoding/base58check'); -var Hash = require('./crypto/hash'); -var Network = require('./networks'); -var HDKeyCache = require('./hdkeycache'); -var Point = require('./crypto/point'); -var PrivateKey = require('./privatekey'); -var Random = require('./crypto/random'); - -var errors = require('./errors'); -var hdErrors = errors.HDPrivateKey; -var BufferUtil = require('./util/buffer'); -var JSUtil = require('./util/js'); - -var MINIMUM_ENTROPY_BITS = 128; -var BITS_TO_BYTES = 1 / 8; -var MAXIMUM_ENTROPY_BITS = 512; - - -/** - * Represents an instance of an hierarchically derived private key. - * - * More info on https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki - * - * @constructor - * @param {string|Buffer|Object} arg - */ -function HDPrivateKey(arg) { - /* jshint maxcomplexity: 10 */ - if (arg instanceof HDPrivateKey) { - return arg; - } - if (!(this instanceof HDPrivateKey)) { - return new HDPrivateKey(arg); - } - if (!arg) { - return this._generateRandomly(); - } - - if (Network.get(arg)) { - return this._generateRandomly(arg); - } else if (_.isString(arg) || BufferUtil.isBuffer(arg)) { - if (HDPrivateKey.isValidSerialized(arg)) { - this._buildFromSerialized(arg); - } else if (JSUtil.isValidJSON(arg)) { - this._buildFromJSON(arg); - } else if (BufferUtil.isBuffer(arg) && HDPrivateKey.isValidSerialized(arg.toString())) { - this._buildFromSerialized(arg.toString()); - } else { - throw HDPrivateKey.getSerializedError(arg); - } - } else if (_.isObject(arg)) { - this._buildFromObject(arg); - } else { - throw new hdErrors.UnrecognizedArgument(arg); - } -} - -/** - * Verifies that a given path is valid. - * - * @param {string|number} arg - * @param {boolean?} hardened - * @return {boolean} - */ -HDPrivateKey.isValidPath = function(arg, hardened) { - if (_.isString(arg)) { - var indexes = HDPrivateKey._getDerivationIndexes(arg); - return indexes !== null && _.all(indexes, HDPrivateKey.isValidPath); - } - - if (_.isNumber(arg)) { - if (arg < HDPrivateKey.Hardened && hardened === true) { - arg += HDPrivateKey.Hardened; - } - return arg >= 0 && arg < HDPrivateKey.MaxIndex; - } - - return false; -}; - -/** - * Internal function that splits a string path into a derivation index array. - * It will return null if the string path is malformed. - * It does not validate if indexes are in bounds. - * - * @param {string} path - * @return {Array} - */ -HDPrivateKey._getDerivationIndexes = function(path) { - var steps = path.split('/'); - - // Special cases: - if (_.contains(HDPrivateKey.RootElementAlias, path)) { - return []; - } - - if (!_.contains(HDPrivateKey.RootElementAlias, steps[0])) { - return null; - } - - var indexes = steps.slice(1).map(function(step) { - var isHardened = step.slice(-1) === '\''; - if (isHardened) { - step = step.slice(0, -1); - } - if (!step || step[0] === '-') { - return NaN; - } - var index = +step; // cast to number - if (isHardened) { - index += HDPrivateKey.Hardened; - } - - return index; - }); - - return _.any(indexes, isNaN) ? null : indexes; -}; - -/** - * Get a derivated child based on a string or number. - * - * If the first argument is a string, it's parsed as the full path of - * derivation. Valid values for this argument include "m" (which returns the - * same private key), "m/0/1/40/2'/1000", where the ' quote means a hardened - * derivation. - * - * If the first argument is a number, the child with that index will be - * derived. If the second argument is truthy, the hardened version will be - * derived. See the example usage for clarification. - * - * @example - * ```javascript - * var parent = new HDPrivateKey('xprv...'); - * var child_0_1_2h = parent.derive(0).derive(1).derive(2, true); - * var copy_of_child_0_1_2h = parent.derive("m/0/1/2'"); - * assert(child_0_1_2h.xprivkey === copy_of_child_0_1_2h); - * ``` - * - * @param {string|number} arg - * @param {boolean?} hardened - */ -HDPrivateKey.prototype.derive = function(arg, hardened) { - if (_.isNumber(arg)) { - return this._deriveWithNumber(arg, hardened); - } else if (_.isString(arg)) { - return this._deriveFromString(arg); - } else { - throw new hdErrors.InvalidDerivationArgument(arg); - } -}; - -HDPrivateKey.prototype._deriveWithNumber = function(index, hardened) { - /* jshint maxstatements: 20 */ - /* jshint maxcomplexity: 10 */ - if (!HDPrivateKey.isValidPath(index, hardened)) { - throw new hdErrors.InvalidPath(index); - } - - hardened = index >= HDPrivateKey.Hardened ? true : hardened; - if (index < HDPrivateKey.Hardened && hardened === true) { - index += HDPrivateKey.Hardened; - } - - var cached = HDKeyCache.get(this.xprivkey, index, hardened); - if (cached) { - return cached; - } - - var indexBuffer = BufferUtil.integerAsBuffer(index); - var data; - if (hardened) { - data = BufferUtil.concat([new buffer.Buffer([0]), this.privateKey.toBuffer(), indexBuffer]); - } else { - data = BufferUtil.concat([this.publicKey.toBuffer(), indexBuffer]); - } - var hash = Hash.sha512hmac(data, this._buffers.chainCode); - var leftPart = BN.fromBuffer(hash.slice(0, 32), { - size: 32 - }); - var chainCode = hash.slice(32, 64); - - var privateKey = leftPart.add(this.privateKey.toBigNumber()).mod(Point.getN()).toBuffer({ - size: 32 - }); - - var derived = new HDPrivateKey({ - network: this.network, - depth: this.depth + 1, - parentFingerPrint: this.fingerPrint, - childIndex: index, - chainCode: chainCode, - privateKey: privateKey - }); - HDKeyCache.set(this.xprivkey, index, hardened, derived); - return derived; -}; - -HDPrivateKey.prototype._deriveFromString = function(path) { - if (!HDPrivateKey.isValidPath(path)) { - throw new hdErrors.InvalidPath(path); - } - - var indexes = HDPrivateKey._getDerivationIndexes(path); - var derived = indexes.reduce(function(prev, index) { - return prev._deriveWithNumber(index); - }, this); - - return derived; -}; - -/** - * Verifies that a given serialized private key in base58 with checksum format - * is valid. - * - * @param {string|Buffer} data - the serialized private key - * @param {string|Network=} network - optional, if present, checks that the - * network provided matches the network serialized. - * @return {boolean} - */ -HDPrivateKey.isValidSerialized = function(data, network) { - return !HDPrivateKey.getSerializedError(data, network); -}; - -/** - * Checks what's the error that causes the validation of a serialized private key - * in base58 with checksum to fail. - * - * @param {string|Buffer} data - the serialized private key - * @param {string|Network=} network - optional, if present, checks that the - * network provided matches the network serialized. - * @return {errors.InvalidArgument|null} - */ -HDPrivateKey.getSerializedError = function(data, network) { - /* jshint maxcomplexity: 10 */ - if (!(_.isString(data) || BufferUtil.isBuffer(data))) { - return new hdErrors.UnrecognizedArgument('Expected string or buffer'); - } - if (!Base58.validCharacters(data)) { - return new errors.InvalidB58Char('(unknown)', data); - } - try { - data = Base58Check.decode(data); - } catch (e) { - return new errors.InvalidB58Checksum(data); - } - if (data.length !== HDPrivateKey.DataLength) { - return new hdErrors.InvalidLength(data); - } - if (!_.isUndefined(network)) { - var error = HDPrivateKey._validateNetwork(data, network); - if (error) { - return error; - } - } - return null; -}; - -HDPrivateKey._validateNetwork = function(data, networkArg) { - var network = Network.get(networkArg); - if (!network) { - return new errors.InvalidNetworkArgument(networkArg); - } - var version = data.slice(0, 4); - if (BufferUtil.integerFromBuffer(version) !== network.xprivkey) { - return new errors.InvalidNetwork(version); - } - return null; -}; - -HDPrivateKey.fromJSON = function(arg) { - $.checkArgument(JSUtil.isValidJSON(arg), 'No valid JSON string was provided'); - return new HDPrivateKey(arg); -}; - -HDPrivateKey.fromString = function(arg) { - $.checkArgument(_.isString(arg), 'No valid string was provided'); - return new HDPrivateKey(arg); -}; - -HDPrivateKey.fromObject = function(arg) { - $.checkArgument(_.isObject(arg), 'No valid argument was provided'); - return new HDPrivateKey(arg); -}; - -HDPrivateKey.prototype._buildFromJSON = function(arg) { - return this._buildFromObject(JSON.parse(arg)); -}; - -HDPrivateKey.prototype._buildFromObject = function(arg) { - /* jshint maxcomplexity: 12 */ - // TODO: Type validation - var buffers = { - version: arg.network ? BufferUtil.integerAsBuffer(Network.get(arg.network).xprivkey) : arg.version, - depth: _.isNumber(arg.depth) ? BufferUtil.integerAsSingleByteBuffer(arg.depth) : arg.depth, - parentFingerPrint: _.isNumber(arg.parentFingerPrint) ? BufferUtil.integerAsBuffer(arg.parentFingerPrint) : arg.parentFingerPrint, - childIndex: _.isNumber(arg.childIndex) ? BufferUtil.integerAsBuffer(arg.childIndex) : arg.childIndex, - chainCode: _.isString(arg.chainCode) ? BufferUtil.hexToBuffer(arg.chainCode) : arg.chainCode, - privateKey: (_.isString(arg.privateKey) && JSUtil.isHexa(arg.privateKey)) ? BufferUtil.hexToBuffer(arg.privateKey) : arg.privateKey, - checksum: arg.checksum ? (arg.checksum.length ? arg.checksum : BufferUtil.integerAsBuffer(arg.checksum)) : undefined - }; - return this._buildFromBuffers(buffers); -}; - -HDPrivateKey.prototype._buildFromSerialized = function(arg) { - var decoded = Base58Check.decode(arg); - var buffers = { - version: decoded.slice(HDPrivateKey.VersionStart, HDPrivateKey.VersionEnd), - depth: decoded.slice(HDPrivateKey.DepthStart, HDPrivateKey.DepthEnd), - parentFingerPrint: decoded.slice(HDPrivateKey.ParentFingerPrintStart, - HDPrivateKey.ParentFingerPrintEnd), - childIndex: decoded.slice(HDPrivateKey.ChildIndexStart, HDPrivateKey.ChildIndexEnd), - chainCode: decoded.slice(HDPrivateKey.ChainCodeStart, HDPrivateKey.ChainCodeEnd), - privateKey: decoded.slice(HDPrivateKey.PrivateKeyStart, HDPrivateKey.PrivateKeyEnd), - checksum: decoded.slice(HDPrivateKey.ChecksumStart, HDPrivateKey.ChecksumEnd), - xprivkey: arg - }; - return this._buildFromBuffers(buffers); -}; - -HDPrivateKey.prototype._generateRandomly = function(network) { - return HDPrivateKey.fromSeed(Random.getRandomBuffer(64), network); -}; - -/** - * Generate a private key from a seed, as described in BIP32 - * - * @param {string|Buffer} hexa - * @param {*} network - * @return HDPrivateKey - */ -HDPrivateKey.fromSeed = function(hexa, network) { - /* jshint maxcomplexity: 8 */ - if (JSUtil.isHexaString(hexa)) { - hexa = BufferUtil.hexToBuffer(hexa); - } - if (!Buffer.isBuffer(hexa)) { - throw new hdErrors.InvalidEntropyArgument(hexa); - } - if (hexa.length < MINIMUM_ENTROPY_BITS * BITS_TO_BYTES) { - throw new hdErrors.InvalidEntropyArgument.NotEnoughEntropy(hexa); - } - if (hexa.length > MAXIMUM_ENTROPY_BITS * BITS_TO_BYTES) { - throw new hdErrors.InvalidEntropyArgument.TooMuchEntropy(hexa); - } - var hash = Hash.sha512hmac(hexa, new buffer.Buffer('Bitcoin seed')); - - return new HDPrivateKey({ - network: Network.get(network) || Network.defaultNetwork, - depth: 0, - parentFingerPrint: 0, - childIndex: 0, - privateKey: hash.slice(0, 32), - chainCode: hash.slice(32, 64) - }); -}; - -/** - * Receives a object with buffers in all the properties and populates the - * internal structure - * - * @param {Object} arg - * @param {buffer.Buffer} arg.version - * @param {buffer.Buffer} arg.depth - * @param {buffer.Buffer} arg.parentFingerPrint - * @param {buffer.Buffer} arg.childIndex - * @param {buffer.Buffer} arg.chainCode - * @param {buffer.Buffer} arg.privateKey - * @param {buffer.Buffer} arg.checksum - * @param {string=} arg.xprivkey - if set, don't recalculate the base58 - * representation - * @return {HDPrivateKey} this - */ -HDPrivateKey.prototype._buildFromBuffers = function(arg) { - /* jshint maxcomplexity: 8 */ - /* jshint maxstatements: 20 */ - - HDPrivateKey._validateBufferArguments(arg); - - JSUtil.defineImmutable(this, { - _buffers: arg - }); - - var sequence = [ - arg.version, arg.depth, arg.parentFingerPrint, arg.childIndex, arg.chainCode, - BufferUtil.emptyBuffer(1), arg.privateKey - ]; - var concat = buffer.Buffer.concat(sequence); - if (!arg.checksum || !arg.checksum.length) { - arg.checksum = Base58Check.checksum(concat); - } else { - if (arg.checksum.toString() !== Base58Check.checksum(concat).toString()) { - throw new errors.InvalidB58Checksum(concat); - } - } - - var xprivkey; - xprivkey = Base58Check.encode(buffer.Buffer.concat(sequence)); - arg.xprivkey = new Buffer(xprivkey); - - var privateKey = new PrivateKey(BN.fromBuffer(arg.privateKey)); - var publicKey = privateKey.toPublicKey(); - var size = HDPrivateKey.ParentFingerPrintSize; - var fingerPrint = Hash.sha256ripemd160(publicKey.toBuffer()).slice(0, size); - - JSUtil.defineImmutable(this, { - xprivkey: xprivkey, - network: Network.get(BufferUtil.integerFromBuffer(arg.version)), - depth: BufferUtil.integerFromSingleByteBuffer(arg.depth), - privateKey: privateKey, - publicKey: publicKey, - fingerPrint: fingerPrint - }); - - var HDPublicKey = require('./hdpublickey'); - var hdPublicKey = new HDPublicKey(this); - - JSUtil.defineImmutable(this, { - hdPublicKey: hdPublicKey, - xpubkey: hdPublicKey.xpubkey - }); - - return this; -}; - -HDPrivateKey._validateBufferArguments = function(arg) { - var checkBuffer = function(name, size) { - var buff = arg[name]; - assert(BufferUtil.isBuffer(buff), name + ' argument is not a buffer'); - assert( - buff.length === size, - name + ' has not the expected size: found ' + buff.length + ', expected ' + size - ); - }; - checkBuffer('version', HDPrivateKey.VersionSize); - checkBuffer('depth', HDPrivateKey.DepthSize); - checkBuffer('parentFingerPrint', HDPrivateKey.ParentFingerPrintSize); - checkBuffer('childIndex', HDPrivateKey.ChildIndexSize); - checkBuffer('chainCode', HDPrivateKey.ChainCodeSize); - checkBuffer('privateKey', HDPrivateKey.PrivateKeySize); - if (arg.checksum && arg.checksum.length) { - checkBuffer('checksum', HDPrivateKey.CheckSumSize); - } -}; - -/** - * Returns the string representation of this private key (a string starting - * with "xprv..." - * - * @return string - */ -HDPrivateKey.prototype.toString = function() { - return this.xprivkey; -}; - -/** - * Returns the console representation of this extended private key. - * @return string - */ -HDPrivateKey.prototype.inspect = function() { - return ''; -}; - -/** - * Returns a plain object with a representation of this private key. - * - * Fields include:

    - *
  • network: either 'livenet' or 'testnet' - *
  • depth: a number ranging from 0 to 255 - *
  • fingerPrint: a number ranging from 0 to 2^32-1, taken from the hash of the - *
  • associated public key - *
  • parentFingerPrint: a number ranging from 0 to 2^32-1, taken from the hash - *
  • of this parent's associated public key or zero. - *
  • childIndex: the index from which this child was derived (or zero) - *
  • chainCode: an hexa string representing a number used in the derivation - *
  • privateKey: the private key associated, in hexa representation - *
  • xprivkey: the representation of this extended private key in checksum - *
  • base58 format - *
  • checksum: the base58 checksum of xprivkey - *
- * @return {Object} - */ -HDPrivateKey.prototype.toObject = function toObject() { - return { - network: Network.get(BufferUtil.integerFromBuffer(this._buffers.version)).name, - depth: BufferUtil.integerFromSingleByteBuffer(this._buffers.depth), - fingerPrint: BufferUtil.integerFromBuffer(this.fingerPrint), - parentFingerPrint: BufferUtil.integerFromBuffer(this._buffers.parentFingerPrint), - childIndex: BufferUtil.integerFromBuffer(this._buffers.childIndex), - chainCode: BufferUtil.bufferToHex(this._buffers.chainCode), - privateKey: this.privateKey.toBuffer().toString('hex'), - checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), - xprivkey: this.xprivkey - }; -}; - -/** - * Returns a JSON representation of the HDPrivateKey - * - * @return {string} - */ -HDPrivateKey.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -/** - * Build a HDPrivateKey from a buffer - * - * @param {Buffer} arg - * @return {HDPrivateKey} - */ -HDPrivateKey.fromBuffer = function(arg) { - return new HDPrivateKey(arg.toString()); -}; - -/** - * Returns a buffer representation of the HDPrivateKey - * - * @return {string} - */ -HDPrivateKey.prototype.toBuffer = function() { - return BufferUtil.copy(this._buffers.xprivkey); -}; - -HDPrivateKey.DefaultDepth = 0; -HDPrivateKey.DefaultFingerprint = 0; -HDPrivateKey.DefaultChildIndex = 0; -HDPrivateKey.Hardened = 0x80000000; -HDPrivateKey.MaxIndex = 2 * HDPrivateKey.Hardened; - -HDPrivateKey.RootElementAlias = ['m', 'M', 'm\'', 'M\'']; - -HDPrivateKey.VersionSize = 4; -HDPrivateKey.DepthSize = 1; -HDPrivateKey.ParentFingerPrintSize = 4; -HDPrivateKey.ChildIndexSize = 4; -HDPrivateKey.ChainCodeSize = 32; -HDPrivateKey.PrivateKeySize = 32; -HDPrivateKey.CheckSumSize = 4; - -HDPrivateKey.DataLength = 78; -HDPrivateKey.SerializedByteSize = 82; - -HDPrivateKey.VersionStart = 0; -HDPrivateKey.VersionEnd = HDPrivateKey.VersionStart + HDPrivateKey.VersionSize; -HDPrivateKey.DepthStart = HDPrivateKey.VersionEnd; -HDPrivateKey.DepthEnd = HDPrivateKey.DepthStart + HDPrivateKey.DepthSize; -HDPrivateKey.ParentFingerPrintStart = HDPrivateKey.DepthEnd; -HDPrivateKey.ParentFingerPrintEnd = HDPrivateKey.ParentFingerPrintStart + HDPrivateKey.ParentFingerPrintSize; -HDPrivateKey.ChildIndexStart = HDPrivateKey.ParentFingerPrintEnd; -HDPrivateKey.ChildIndexEnd = HDPrivateKey.ChildIndexStart + HDPrivateKey.ChildIndexSize; -HDPrivateKey.ChainCodeStart = HDPrivateKey.ChildIndexEnd; -HDPrivateKey.ChainCodeEnd = HDPrivateKey.ChainCodeStart + HDPrivateKey.ChainCodeSize; -HDPrivateKey.PrivateKeyStart = HDPrivateKey.ChainCodeEnd + 1; -HDPrivateKey.PrivateKeyEnd = HDPrivateKey.PrivateKeyStart + HDPrivateKey.PrivateKeySize; -HDPrivateKey.ChecksumStart = HDPrivateKey.PrivateKeyEnd; -HDPrivateKey.ChecksumEnd = HDPrivateKey.ChecksumStart + HDPrivateKey.CheckSumSize; - -assert(HDPrivateKey.ChecksumEnd === HDPrivateKey.SerializedByteSize); - -module.exports = HDPrivateKey; - -}).call(this,require("buffer").Buffer) -},{"./crypto/bn":34,"./crypto/hash":36,"./crypto/point":37,"./crypto/random":38,"./encoding/base58":40,"./encoding/base58check":41,"./errors":45,"./hdkeycache":47,"./hdpublickey":49,"./networks":50,"./privatekey":52,"./util/buffer":69,"./util/js":70,"./util/preconditions":71,"assert":194,"buffer":209,"lodash":95}],49:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); -var $ = require('./util/preconditions'); - -var BN = require('./crypto/bn'); -var Base58 = require('./encoding/base58'); -var Base58Check = require('./encoding/base58check'); -var Hash = require('./crypto/hash'); -var HDPrivateKey = require('./hdprivatekey'); -var HDKeyCache = require('./hdkeycache'); -var Network = require('./networks'); -var Point = require('./crypto/point'); -var PublicKey = require('./publickey'); - -var bitcoreErrors = require('./errors'); -var errors = bitcoreErrors; -var hdErrors = bitcoreErrors.HDPublicKey; -var assert = require('assert'); - -var JSUtil = require('./util/js'); -var BufferUtil = require('./util/buffer'); - -/** - * The representation of an hierarchically derived public key. - * - * See https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki - * - * @constructor - * @param {Object|string|Buffer} arg - */ -function HDPublicKey(arg) { - /* jshint maxcomplexity: 12 */ - /* jshint maxstatements: 20 */ - if (arg instanceof HDPublicKey) { - return arg; - } - if (!(this instanceof HDPublicKey)) { - return new HDPublicKey(arg); - } - if (arg) { - if (_.isString(arg) || BufferUtil.isBuffer(arg)) { - var error = HDPublicKey.getSerializedError(arg); - if (!error) { - return this._buildFromSerialized(arg); - } else if (JSUtil.isValidJSON(arg)) { - return this._buildFromJSON(arg); - } else if (BufferUtil.isBuffer(arg) && !HDPublicKey.getSerializedError(arg.toString())) { - return this._buildFromSerialized(arg.toString()); - } else { - if (error instanceof hdErrors.ArgumentIsPrivateExtended) { - return new HDPrivateKey(arg).hdPublicKey; - } - throw error; - } - } else { - if (_.isObject(arg)) { - if (arg instanceof HDPrivateKey) { - return this._buildFromPrivate(arg); - } else { - return this._buildFromObject(arg); - } - } else { - throw new hdErrors.UnrecognizedArgument(arg); - } - } - } else { - throw new hdErrors.MustSupplyArgument(); - } -} - -/** - * Verifies that a given path is valid. - * - * @param {string|number} arg - * @return {boolean} - */ -HDPublicKey.isValidPath = function(arg) { - if (_.isString(arg)) { - var indexes = HDPrivateKey._getDerivationIndexes(arg); - return indexes !== null && _.all(indexes, HDPublicKey.isValidPath); - } - - if (_.isNumber(arg)) { - return arg >= 0 && arg < HDPublicKey.Hardened; - } - - return false; -}; - -/** - * Get a derivated child based on a string or number. - * - * If the first argument is a string, it's parsed as the full path of - * derivation. Valid values for this argument include "m" (which returns the - * same public key), "m/0/1/40/2/1000". - * - * Note that hardened keys can't be derived from a public extended key. - * - * If the first argument is a number, the child with that index will be - * derived. See the example usage for clarification. - * - * @example - * ```javascript - * var parent = new HDPublicKey('xpub...'); - * var child_0_1_2 = parent.derive(0).derive(1).derive(2); - * var copy_of_child_0_1_2 = parent.derive("m/0/1/2"); - * assert(child_0_1_2.xprivkey === copy_of_child_0_1_2); - * ``` - * - * @param {string|number} arg - */ -HDPublicKey.prototype.derive = function (arg) { - if (_.isNumber(arg)) { - return this._deriveWithNumber(arg); - } else if (_.isString(arg)) { - return this._deriveFromString(arg); - } else { - throw new hdErrors.InvalidDerivationArgument(arg); - } -}; - -HDPublicKey.prototype._deriveWithNumber = function (index) { - if (index >= HDPublicKey.Hardened) { - throw new hdErrors.InvalidIndexCantDeriveHardened(); - } - if (index < 0) { - throw new hdErrors.InvalidPath(index); - } - var cached = HDKeyCache.get(this.xpubkey, index, false); - if (cached) { - return cached; - } - - var indexBuffer = BufferUtil.integerAsBuffer(index); - var data = BufferUtil.concat([this.publicKey.toBuffer(), indexBuffer]); - var hash = Hash.sha512hmac(data, this._buffers.chainCode); - var leftPart = BN.fromBuffer(hash.slice(0, 32), {size: 32}); - var chainCode = hash.slice(32, 64); - - var publicKey = PublicKey.fromPoint(Point.getG().mul(leftPart).add(this.publicKey.point)); - - var derived = new HDPublicKey({ - network: this.network, - depth: this.depth + 1, - parentFingerPrint: this.fingerPrint, - childIndex: index, - chainCode: chainCode, - publicKey: publicKey - }); - HDKeyCache.set(this.xpubkey, index, false, derived); - return derived; -}; - -HDPublicKey.prototype._deriveFromString = function (path) { - /* jshint maxcomplexity: 8 */ - if (_.contains(path, "'")) { - throw new hdErrors.InvalidIndexCantDeriveHardened(); - } else if (!HDPublicKey.isValidPath(path)) { - throw new hdErrors.InvalidPath(path); - } - - var indexes = HDPrivateKey._getDerivationIndexes(path); - var derived = indexes.reduce(function(prev, index) { - return prev._deriveWithNumber(index); - }, this); - - return derived; -}; - -/** - * Verifies that a given serialized public key in base58 with checksum format - * is valid. - * - * @param {string|Buffer} data - the serialized public key - * @param {string|Network=} network - optional, if present, checks that the - * network provided matches the network serialized. - * @return {boolean} - */ -HDPublicKey.isValidSerialized = function (data, network) { - return _.isNull(HDPublicKey.getSerializedError(data, network)); -}; - -/** - * Checks what's the error that causes the validation of a serialized public key - * in base58 with checksum to fail. - * - * @param {string|Buffer} data - the serialized public key - * @param {string|Network=} network - optional, if present, checks that the - * network provided matches the network serialized. - * @return {errors|null} - */ -HDPublicKey.getSerializedError = function (data, network) { - /* jshint maxcomplexity: 10 */ - /* jshint maxstatements: 20 */ - if (!(_.isString(data) || BufferUtil.isBuffer(data))) { - return new hdErrors.UnrecognizedArgument('expected buffer or string'); - } - if (!Base58.validCharacters(data)) { - return new errors.InvalidB58Char('(unknown)', data); - } - try { - data = Base58Check.decode(data); - } catch (e) { - return new errors.InvalidB58Checksum(data); - } - if (data.length !== HDPublicKey.DataSize) { - return new errors.InvalidLength(data); - } - if (!_.isUndefined(network)) { - var error = HDPublicKey._validateNetwork(data, network); - if (error) { - return error; - } - } - var version = BufferUtil.integerFromBuffer(data.slice(0, 4)); - if (version === Network.livenet.xprivkey || version === Network.testnet.xprivkey ) { - return new hdErrors.ArgumentIsPrivateExtended(); - } - return null; -}; - -HDPublicKey._validateNetwork = function (data, networkArg) { - var network = Network.get(networkArg); - if (!network) { - return new errors.InvalidNetworkArgument(networkArg); - } - var version = data.slice(HDPublicKey.VersionStart, HDPublicKey.VersionEnd); - if (BufferUtil.integerFromBuffer(version) !== network.xpubkey) { - return new errors.InvalidNetwork(version); - } - return null; -}; - -HDPublicKey.prototype._buildFromJSON = function (arg) { - return this._buildFromObject(JSON.parse(arg)); -}; - -HDPublicKey.prototype._buildFromPrivate = function (arg) { - var args = _.clone(arg._buffers); - var point = Point.getG().mul(BN.fromBuffer(args.privateKey)); - args.publicKey = Point.pointToCompressed(point); - args.version = BufferUtil.integerAsBuffer(Network.get(BufferUtil.integerFromBuffer(args.version)).xpubkey); - args.privateKey = undefined; - args.checksum = undefined; - args.xprivkey = undefined; - return this._buildFromBuffers(args); -}; - -HDPublicKey.prototype._buildFromObject = function (arg) { - /* jshint maxcomplexity: 10 */ - // TODO: Type validation - var buffers = { - version: arg.network ? BufferUtil.integerAsBuffer(Network.get(arg.network).xpubkey) : arg.version, - depth: _.isNumber(arg.depth) ? BufferUtil.integerAsSingleByteBuffer(arg.depth) : arg.depth, - parentFingerPrint: _.isNumber(arg.parentFingerPrint) ? BufferUtil.integerAsBuffer(arg.parentFingerPrint) : arg.parentFingerPrint, - childIndex: _.isNumber(arg.childIndex) ? BufferUtil.integerAsBuffer(arg.childIndex) : arg.childIndex, - chainCode: _.isString(arg.chainCode) ? BufferUtil.hexToBuffer(arg.chainCode) : arg.chainCode, - publicKey: _.isString(arg.publicKey) ? BufferUtil.hexToBuffer(arg.publicKey) : - BufferUtil.isBuffer(arg.publicKey) ? arg.publicKey : arg.publicKey.toBuffer(), - checksum: _.isNumber(arg.checksum) ? BufferUtil.integerAsBuffer(arg.checksum) : arg.checksum - }; - return this._buildFromBuffers(buffers); -}; - -HDPublicKey.prototype._buildFromSerialized = function (arg) { - var decoded = Base58Check.decode(arg); - var buffers = { - version: decoded.slice(HDPublicKey.VersionStart, HDPublicKey.VersionEnd), - depth: decoded.slice(HDPublicKey.DepthStart, HDPublicKey.DepthEnd), - parentFingerPrint: decoded.slice(HDPublicKey.ParentFingerPrintStart, - HDPublicKey.ParentFingerPrintEnd), - childIndex: decoded.slice(HDPublicKey.ChildIndexStart, HDPublicKey.ChildIndexEnd), - chainCode: decoded.slice(HDPublicKey.ChainCodeStart, HDPublicKey.ChainCodeEnd), - publicKey: decoded.slice(HDPublicKey.PublicKeyStart, HDPublicKey.PublicKeyEnd), - checksum: decoded.slice(HDPublicKey.ChecksumStart, HDPublicKey.ChecksumEnd), - xpubkey: arg - }; - return this._buildFromBuffers(buffers); -}; - -/** - * Receives a object with buffers in all the properties and populates the - * internal structure - * - * @param {Object} arg - * @param {buffer.Buffer} arg.version - * @param {buffer.Buffer} arg.depth - * @param {buffer.Buffer} arg.parentFingerPrint - * @param {buffer.Buffer} arg.childIndex - * @param {buffer.Buffer} arg.chainCode - * @param {buffer.Buffer} arg.publicKey - * @param {buffer.Buffer} arg.checksum - * @param {string=} arg.xpubkey - if set, don't recalculate the base58 - * representation - * @return {HDPublicKey} this - */ -HDPublicKey.prototype._buildFromBuffers = function (arg) { - /* jshint maxcomplexity: 8 */ - /* jshint maxstatements: 20 */ - - HDPublicKey._validateBufferArguments(arg); - - JSUtil.defineImmutable(this, { - _buffers: arg - }); - - var sequence = [ - arg.version, arg.depth, arg.parentFingerPrint, arg.childIndex, arg.chainCode, - arg.publicKey - ]; - var concat = BufferUtil.concat(sequence); - var checksum = Base58Check.checksum(concat); - if (!arg.checksum || !arg.checksum.length) { - arg.checksum = checksum; - } else { - if (arg.checksum.toString('hex') !== checksum.toString('hex')) { - throw new errors.InvalidB58Checksum(concat, checksum); - } - } - - var xpubkey; - xpubkey = Base58Check.encode(BufferUtil.concat(sequence)); - arg.xpubkey = new Buffer(xpubkey); - - var publicKey = PublicKey.fromString(arg.publicKey); - var size = HDPublicKey.ParentFingerPrintSize; - var fingerPrint = Hash.sha256ripemd160(publicKey.toBuffer()).slice(0, size); - - JSUtil.defineImmutable(this, { - xpubkey: xpubkey, - network: Network.get(BufferUtil.integerFromBuffer(arg.version)), - depth: BufferUtil.integerFromSingleByteBuffer(arg.depth), - publicKey: publicKey, - fingerPrint: fingerPrint - }); - - return this; -}; - -HDPublicKey._validateBufferArguments = function (arg) { - var checkBuffer = function(name, size) { - var buff = arg[name]; - assert(BufferUtil.isBuffer(buff), name + ' argument is not a buffer, it\'s ' + typeof buff); - assert( - buff.length === size, - name + ' has not the expected size: found ' + buff.length + ', expected ' + size - ); - }; - checkBuffer('version', HDPublicKey.VersionSize); - checkBuffer('depth', HDPublicKey.DepthSize); - checkBuffer('parentFingerPrint', HDPublicKey.ParentFingerPrintSize); - checkBuffer('childIndex', HDPublicKey.ChildIndexSize); - checkBuffer('chainCode', HDPublicKey.ChainCodeSize); - checkBuffer('publicKey', HDPublicKey.PublicKeySize); - if (arg.checksum && arg.checksum.length) { - checkBuffer('checksum', HDPublicKey.CheckSumSize); - } -}; - -HDPublicKey.fromJSON = function(arg) { - $.checkArgument(JSUtil.isValidJSON(arg), 'No valid JSON string was provided'); - return new HDPublicKey(arg); -}; - -HDPublicKey.fromObject = function(arg) { - $.checkArgument(_.isObject(arg), 'No valid argument was provided'); - return new HDPublicKey(arg); -}; - -HDPublicKey.fromString = function(arg) { - $.checkArgument(_.isString(arg), 'No valid string was provided'); - return new HDPublicKey(arg); -}; - -/** - * Returns the base58 checked representation of the public key - * @return {string} a string starting with "xpub..." in livenet - */ -HDPublicKey.prototype.toString = function () { - return this.xpubkey; -}; - -/** - * Returns the console representation of this extended public key. - * @return string - */ -HDPublicKey.prototype.inspect = function() { - return ''; -}; - -/** - * Returns a plain javascript object with information to reconstruct a key. - * - * Fields are:
    - *
  • network: 'livenet' or 'testnet' - *
  • depth: a number from 0 to 255, the depth to the master extended key - *
  • fingerPrint: a number of 32 bits taken from the hash of the public key - *
  • fingerPrint: a number of 32 bits taken from the hash of this key's - *
  • parent's public key - *
  • childIndex: index with which this key was derived - *
  • chainCode: string in hexa encoding used for derivation - *
  • publicKey: string, hexa encoded, in compressed key format - *
  • checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), - *
  • xpubkey: the string with the base58 representation of this extended key - *
  • checksum: the base58 checksum of xpubkey - *
- */ -HDPublicKey.prototype.toObject = function toObject() { - return { - network: Network.get(BufferUtil.integerFromBuffer(this._buffers.version)).name, - depth: BufferUtil.integerFromSingleByteBuffer(this._buffers.depth), - fingerPrint: BufferUtil.integerFromBuffer(this.fingerPrint), - parentFingerPrint: BufferUtil.integerFromBuffer(this._buffers.parentFingerPrint), - childIndex: BufferUtil.integerFromBuffer(this._buffers.childIndex), - chainCode: BufferUtil.bufferToHex(this._buffers.chainCode), - publicKey: this.publicKey.toString(), - checksum: BufferUtil.integerFromBuffer(this._buffers.checksum), - xpubkey: this.xpubkey - }; -}; - -/** - * Serializes this object into a JSON string - * @return {string} - */ -HDPublicKey.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -/** - * Create a HDPublicKey from a buffer argument - * - * @param {Buffer} arg - * @return {HDPublicKey} - */ -HDPublicKey.fromBuffer = function(arg) { - return new HDPublicKey(arg); -}; - -/** - * Return a buffer representation of the xpubkey - * - * @return {Buffer} - */ -HDPublicKey.prototype.toBuffer = function() { - return BufferUtil.copy(this._buffers.xpubkey); -}; - -HDPublicKey.Hardened = 0x80000000; -HDPublicKey.RootElementAlias = ['m', 'M']; - -HDPublicKey.VersionSize = 4; -HDPublicKey.DepthSize = 1; -HDPublicKey.ParentFingerPrintSize = 4; -HDPublicKey.ChildIndexSize = 4; -HDPublicKey.ChainCodeSize = 32; -HDPublicKey.PublicKeySize = 33; -HDPublicKey.CheckSumSize = 4; - -HDPublicKey.DataSize = 78; -HDPublicKey.SerializedByteSize = 82; - -HDPublicKey.VersionStart = 0; -HDPublicKey.VersionEnd = HDPublicKey.VersionStart + HDPublicKey.VersionSize; -HDPublicKey.DepthStart = HDPublicKey.VersionEnd; -HDPublicKey.DepthEnd = HDPublicKey.DepthStart + HDPublicKey.DepthSize; -HDPublicKey.ParentFingerPrintStart = HDPublicKey.DepthEnd; -HDPublicKey.ParentFingerPrintEnd = HDPublicKey.ParentFingerPrintStart + HDPublicKey.ParentFingerPrintSize; -HDPublicKey.ChildIndexStart = HDPublicKey.ParentFingerPrintEnd; -HDPublicKey.ChildIndexEnd = HDPublicKey.ChildIndexStart + HDPublicKey.ChildIndexSize; -HDPublicKey.ChainCodeStart = HDPublicKey.ChildIndexEnd; -HDPublicKey.ChainCodeEnd = HDPublicKey.ChainCodeStart + HDPublicKey.ChainCodeSize; -HDPublicKey.PublicKeyStart = HDPublicKey.ChainCodeEnd; -HDPublicKey.PublicKeyEnd = HDPublicKey.PublicKeyStart + HDPublicKey.PublicKeySize; -HDPublicKey.ChecksumStart = HDPublicKey.PublicKeyEnd; -HDPublicKey.ChecksumEnd = HDPublicKey.ChecksumStart + HDPublicKey.CheckSumSize; - -assert(HDPublicKey.PublicKeyEnd === HDPublicKey.DataSize); -assert(HDPublicKey.ChecksumEnd === HDPublicKey.SerializedByteSize); - -module.exports = HDPublicKey; - -}).call(this,require("buffer").Buffer) -},{"./crypto/bn":34,"./crypto/hash":36,"./crypto/point":37,"./encoding/base58":40,"./encoding/base58check":41,"./errors":45,"./hdkeycache":47,"./hdprivatekey":48,"./networks":50,"./publickey":53,"./util/buffer":69,"./util/js":70,"./util/preconditions":71,"assert":194,"buffer":209,"lodash":95}],50:[function(require,module,exports){ -'use strict'; -var _ = require('lodash'); - -var BufferUtil = require('./util/buffer'); -var networks = []; -var networkMaps = {}; - -/** - * A network is merely a map containing values that correspond to version - * numbers for each bitcoin network. Currently only supporting "livenet" - * (a.k.a. "mainnet") and "testnet". - * @constructor - */ -function Network() {} - -Network.prototype.toString = function toString() { - return this.name; -}; - -/** - * @function - * @member Networks#get - * Retrieves the network associated with a magic number or string. - * @param {string|number|Network} arg - * @param {string} key - if set, only check if the magic number associated with this name matches - * @return Network - */ -function getNetwork(arg, key) { - if (~networks.indexOf(arg)) { - return arg; - } - if (key) { - for (var index in networks) { - if (networks[index][key] === arg) { - return networks[index]; - } - } - return undefined; - } - return networkMaps[arg]; -} - -/** - * @function - * @member Networks#add - * Will add a custom Network - * @param {Object} data - * @param {String} data.name - The name of the network - * @param {String} data.alias - The aliased name of the network - * @param {Number} data.pubkeyhash - The publickey hash prefix - * @param {Number} data.privatekey - The privatekey prefix - * @param {Number} data.scripthash - The scripthash prefix - * @param {Number} data.xpubkey - The extended public key magic - * @param {Number} data.xprivkey - The extended private key magic - * @param {Number} data.networkMagic - The network magic number - * @param {Number} data.port - The network port - * @param {Array} data.dnsSeeds - An array of dns seeds - * @return Network - */ -function addNetwork(data) { - - var network = new Network(); - - _.extend(network, { - name: data.name, - alias: data.alias, - pubkeyhash: data.pubkeyhash, - privatekey: data.privatekey, - scripthash: data.scripthash, - xpubkey: data.xpubkey, - xprivkey: data.xprivkey, - networkMagic: BufferUtil.integerAsBuffer(data.networkMagic), - port: data.port, - dnsSeeds: data.dnsSeeds - }); - - _.each(_.values(network), function(value) { - if (!_.isObject(value)) { - networkMaps[value] = network; - } - }); - - networks.push(network); - - return network; - -} - -addNetwork({ - name: 'livenet', - alias: 'mainnet', - pubkeyhash: 0x00, - privatekey: 0x80, - scripthash: 0x05, - xpubkey: 0x0488b21e, - xprivkey: 0x0488ade4, - networkMagic: 0xf9beb4d9, - port: 8333, - dnsSeeds: [ - 'seed.bitcoin.sipa.be', - 'dnsseed.bluematt.me', - 'dnsseed.bitcoin.dashjr.org', - 'seed.bitcoinstats.com', - 'seed.bitnodes.io', - 'bitseed.xf2.org' - ] -}); - -addNetwork({ - name: 'testnet', - alias: 'testnet', - pubkeyhash: 0x6f, - privatekey: 0xef, - scripthash: 0xc4, - xpubkey: 0x043587cf, - xprivkey: 0x04358394, - networkMagic: 0x0b110907, - port: 18333, - dnsSeeds: [ - 'testnet-seed.bitcoin.petertodd.org', - 'testnet-seed.bluematt.me', - 'testnet-seed.alexykot.me', - 'testnet-seed.bitcoin.schildbach.de' - ], -}); - -/** -* @instance -* @member Networks#livenet -*/ -var livenet = getNetwork('livenet'); - -/** -* @instance -* @member Networks#testnet -*/ -var testnet = getNetwork('testnet'); - -/** - * @namespace Networks - */ -module.exports = { - add: addNetwork, - defaultNetwork: livenet, - livenet: livenet, - mainnet: livenet, - testnet: testnet, - get: getNetwork -}; - -},{"./util/buffer":69,"lodash":95}],51:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); -var $ = require('./util/preconditions'); -var BufferUtil = require('./util/buffer'); -var JSUtil = require('./util/js'); - -function Opcode(num) { - if (!(this instanceof Opcode)) { - return new Opcode(num); - } - - var value; - - if (_.isNumber(num)) { - value = num; - } else if (_.isString(num)) { - value = Opcode.map[num]; - } else { - throw new TypeError('Unrecognized num type: "' + typeof(num) + '" for Opcode'); - } - - JSUtil.defineImmutable(this, { - num: value - }); - - return this; -} - -Opcode.fromBuffer = function(buf) { - $.checkArgument(BufferUtil.isBuffer(buf)); - return new Opcode(Number('0x' + buf.toString('hex'))); -}; - -Opcode.fromNumber = function(num) { - $.checkArgument(_.isNumber(num)); - return new Opcode(num); -}; - -Opcode.fromString = function(str) { - $.checkArgument(_.isString(str)); - var value = Opcode.map[str]; - if (typeof value === 'undefined') { - throw new TypeError('Invalid opcodestr'); - } - return new Opcode(value); -}; - -Opcode.prototype.toHex = function() { - return this.num.toString(16); -}; - -Opcode.prototype.toBuffer = function() { - return new Buffer(this.toHex(), 'hex'); -}; - -Opcode.prototype.toNumber = function() { - return this.num; -}; - -Opcode.prototype.toString = function() { - var str = Opcode.reverseMap[this.num]; - if (typeof str === 'undefined') { - throw new Error('Opcode does not have a string representation'); - } - return str; -}; - -Opcode.smallInt = function(n) { - $.checkArgument(n >= 0 && n <= 16, 'Invalid Argument: n must be between 0 and 16'); - if (n === 0) { - return Opcode('OP_0'); - } - return new Opcode(Opcode.map.OP_1 + n - 1); -}; - -Opcode.map = { - // push value - OP_FALSE: 0, - OP_0: 0, - OP_PUSHDATA1: 76, - OP_PUSHDATA2: 77, - OP_PUSHDATA4: 78, - OP_1NEGATE: 79, - OP_RESERVED: 80, - OP_TRUE: 81, - OP_1: 81, - OP_2: 82, - OP_3: 83, - OP_4: 84, - OP_5: 85, - OP_6: 86, - OP_7: 87, - OP_8: 88, - OP_9: 89, - OP_10: 90, - OP_11: 91, - OP_12: 92, - OP_13: 93, - OP_14: 94, - OP_15: 95, - OP_16: 96, - - // control - OP_NOP: 97, - OP_VER: 98, - OP_IF: 99, - OP_NOTIF: 100, - OP_VERIF: 101, - OP_VERNOTIF: 102, - OP_ELSE: 103, - OP_ENDIF: 104, - OP_VERIFY: 105, - OP_RETURN: 106, - - // stack ops - OP_TOALTSTACK: 107, - OP_FROMALTSTACK: 108, - OP_2DROP: 109, - OP_2DUP: 110, - OP_3DUP: 111, - OP_2OVER: 112, - OP_2ROT: 113, - OP_2SWAP: 114, - OP_IFDUP: 115, - OP_DEPTH: 116, - OP_DROP: 117, - OP_DUP: 118, - OP_NIP: 119, - OP_OVER: 120, - OP_PICK: 121, - OP_ROLL: 122, - OP_ROT: 123, - OP_SWAP: 124, - OP_TUCK: 125, - - // splice ops - OP_CAT: 126, - OP_SUBSTR: 127, - OP_LEFT: 128, - OP_RIGHT: 129, - OP_SIZE: 130, - - // bit logic - OP_INVERT: 131, - OP_AND: 132, - OP_OR: 133, - OP_XOR: 134, - OP_EQUAL: 135, - OP_EQUALVERIFY: 136, - OP_RESERVED1: 137, - OP_RESERVED2: 138, - - // numeric - OP_1ADD: 139, - OP_1SUB: 140, - OP_2MUL: 141, - OP_2DIV: 142, - OP_NEGATE: 143, - OP_ABS: 144, - OP_NOT: 145, - OP_0NOTEQUAL: 146, - - OP_ADD: 147, - OP_SUB: 148, - OP_MUL: 149, - OP_DIV: 150, - OP_MOD: 151, - OP_LSHIFT: 152, - OP_RSHIFT: 153, - - OP_BOOLAND: 154, - OP_BOOLOR: 155, - OP_NUMEQUAL: 156, - OP_NUMEQUALVERIFY: 157, - OP_NUMNOTEQUAL: 158, - OP_LESSTHAN: 159, - OP_GREATERTHAN: 160, - OP_LESSTHANOREQUAL: 161, - OP_GREATERTHANOREQUAL: 162, - OP_MIN: 163, - OP_MAX: 164, - - OP_WITHIN: 165, - - // crypto - OP_RIPEMD160: 166, - OP_SHA1: 167, - OP_SHA256: 168, - OP_HASH160: 169, - OP_HASH256: 170, - OP_CODESEPARATOR: 171, - OP_CHECKSIG: 172, - OP_CHECKSIGVERIFY: 173, - OP_CHECKMULTISIG: 174, - OP_CHECKMULTISIGVERIFY: 175, - - // expansion - OP_NOP1: 176, - OP_NOP2: 177, - OP_NOP3: 178, - OP_NOP4: 179, - OP_NOP5: 180, - OP_NOP6: 181, - OP_NOP7: 182, - OP_NOP8: 183, - OP_NOP9: 184, - OP_NOP10: 185, - - // template matching params - OP_PUBKEYHASH: 253, - OP_PUBKEY: 254, - OP_INVALIDOPCODE: 255 -}; - -Opcode.reverseMap = []; - -for (var k in Opcode.map) { - Opcode.reverseMap[Opcode.map[k]] = k; -} - -// Easier access to opcodes -_.extend(Opcode, Opcode.map); - -/** - * @returns true if opcode is one of OP_0, OP_1, ..., OP_16 - */ -Opcode.isSmallIntOp = function(opcode) { - if (opcode instanceof Opcode) { - opcode = opcode.toNumber(); - } - return ((opcode === Opcode.map.OP_0) || - ((opcode >= Opcode.map.OP_1) && (opcode <= Opcode.map.OP_16))); -}; - -/** - * Will return a string formatted for the console - * - * @returns {String} Script opcode - */ -Opcode.prototype.inspect = function() { - return ''; -}; - -module.exports = Opcode; - -}).call(this,require("buffer").Buffer) -},{"./util/buffer":69,"./util/js":70,"./util/preconditions":71,"buffer":209,"lodash":95}],52:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); -var Address = require('./address'); -var Base58Check = require('./encoding/base58check'); -var BN = require('./crypto/bn'); -var JSUtil = require('./util/js'); -var Networks = require('./networks'); -var Point = require('./crypto/point'); -var PublicKey = require('./publickey'); -var Random = require('./crypto/random'); - -/** - * Instantiate a PrivateKey from a BN, Buffer and WIF. - * - * @example - * ```javascript - * // generate a new random key - * var key = PrivateKey(); - * - * // get the associated address - * var address = key.toAddress(); - * - * // encode into wallet export format - * var exported = key.toWIF(); - * - * // instantiate from the exported (and saved) private key - * var imported = PrivateKey.fromWIF(exported); - * ``` - * - * @param {string} data - The encoded data in various formats - * @param {Network|string} [network] - a {@link Network} object, or a string with the network name - * @returns {PrivateKey} A new valid instance of an PrivateKey - * @constructor - */ -var PrivateKey = function PrivateKey(data, network) { - /* jshint maxstatements: 20 */ - /* jshint maxcomplexity: 8 */ - - if (!(this instanceof PrivateKey)) { - return new PrivateKey(data, network); - } - if (data instanceof PrivateKey) { - return data; - } - - var info = this._classifyArguments(data, network); - - // validation - if (!info.bn || info.bn.cmp(new BN(0)) === 0){ - throw new TypeError('Number can not be equal to zero, undefined, null or false'); - } - if (!info.bn.lt(Point.getN())) { - throw new TypeError('Number must be less than N'); - } - if (typeof(info.network) === 'undefined') { - throw new TypeError('Must specify the network ("livenet" or "testnet")'); - } - - JSUtil.defineImmutable(this, { - bn: info.bn, - compressed: info.compressed, - network: info.network - }); - - Object.defineProperty(this, 'publicKey', { - configurable: false, - enumerable: true, - get: this.toPublicKey.bind(this) - }); - - return this; - -}; - -/** - * Internal helper to instantiate PrivateKey internal `info` object from - * different kinds of arguments passed to the constructor. - * - * @param {*} data - * @param {Network|string} [network] - a {@link Network} object, or a string with the network name - * @return {Object} - */ -PrivateKey.prototype._classifyArguments = function(data, network) { - /* jshint maxcomplexity: 10 */ - var info = { - compressed: true, - network: network ? Networks.get(network) : Networks.defaultNetwork - }; - - // detect type of data - if (_.isUndefined(data) || _.isNull(data)){ - info.bn = PrivateKey._getRandomBN(); - } else if (data instanceof BN) { - info.bn = data; - } else if (data instanceof Buffer || data instanceof Uint8Array) { - info = PrivateKey._transformBuffer(data, network); - } else if (PrivateKey._isJSON(data)){ - info = PrivateKey._transformJSON(data); - } else if (!network && Networks.get(data)) { - info.bn = PrivateKey._getRandomBN(); - info.network = Networks.get(data); - } else if (typeof(data) === 'string'){ - if (JSUtil.isHexa(data)) { - info.bn = new BN(new Buffer(data, 'hex')); - } else { - info = PrivateKey._transformWIF(data, network); - } - } else { - throw new TypeError('First argument is an unrecognized data type.'); - } - return info; -}; - -/** - * Internal function to get a random Big Number (BN) - * - * @returns {BN} A new randomly generated BN - * @private - */ -PrivateKey._getRandomBN = function(){ - var condition; - var bn; - do { - var privbuf = Random.getRandomBuffer(32); - bn = BN.fromBuffer(privbuf); - condition = bn.lt(Point.getN()); - } while (!condition); - return bn; -}; - -/** - * Internal function to detect if a param is a JSON string or plain object - * - * @param {*} param - value to test - * @returns {boolean} - * @private - */ -PrivateKey._isJSON = function(json) { - return JSUtil.isValidJSON(json) || (json.bn && json.network); -}; - -/** - * Internal function to transform a WIF Buffer into a private key - * - * @param {Buffer} buf - An WIF string - * @param {Network|string} [network] - a {@link Network} object, or a string with the network name - * @returns {Object} An object with keys: bn, network and compressed - * @private - */ -PrivateKey._transformBuffer = function(buf, network) { - - var info = {}; - - if (buf.length === 32) { - return PrivateKey._transformBNBuffer(buf, network); - } - - info.network = Networks.get(buf[0], 'privatekey'); - if (buf[0] === Networks.livenet.privatekey) { - info.network = Networks.livenet; - } else if (buf[0] === Networks.testnet.privatekey) { - info.network = Networks.testnet; - } else { - throw new Error('Invalid network'); - } - - if (network && info.network !== Networks.get(network)) { - throw new TypeError('Private key network mismatch'); - } - - if (buf.length === 1 + 32 + 1 && buf[1 + 32 + 1 - 1] === 1) { - info.compressed = true; - } else if (buf.length === 1 + 32) { - info.compressed = false; - } else { - throw new Error('Length of buffer must be 33 (uncompressed) or 34 (compressed)'); - } - - info.bn = BN.fromBuffer(buf.slice(1, 32 + 1)); - - return info; -}; - -/** - * Internal function to transform a BN buffer into a private key - * - * @param {Buffer} buf - * @param {Network|string} [network] - a {@link Network} object, or a string with the network name - * @returns {object} an Object with keys: bn, network, and compressed - * @private - */ -PrivateKey._transformBNBuffer = function(buf, network) { - var info = {}; - info.network = Networks.get(network) || Networks.defaultNetwork; - info.bn = BN.fromBuffer(buf); - info.compressed = false; - return info; -}; - -/** - * Internal function to transform a WIF string into a private key - * - * @param {String} buf - An WIF string - * @returns {Object} An object with keys: bn, network and compressed - * @private - */ -PrivateKey._transformWIF = function(str, network) { - return PrivateKey._transformBuffer(Base58Check.decode(str), network); -}; - -/** - * Instantiate a PrivateKey from a JSON string - * - * @param {String} json - The JSON encoded private key string - * @returns {PrivateKey} A new valid instance of PrivateKey - */ -PrivateKey.fromJSON = function(json) { - if (!PrivateKey._isJSON(json)) { - throw new TypeError('Must be a valid JSON string or plain object'); - } - - return new PrivateKey(json); -}; - -/** - * Instantiate a PrivateKey from a Buffer with the DER or WIF representation - * - * @param {Buffer} arg - * @param {Network} network - * @return {PrivateKey} - */ -PrivateKey.fromBuffer = function(arg, network) { - return new PrivateKey(arg, network); -}; - -/** - * Internal function to transform a JSON string on plain object into a private key - * return this. - * - * @param {String} json - A JSON string or plain object - * @returns {Object} An object with keys: bn, network and compressed - * @private - */ -PrivateKey._transformJSON = function(json) { - if (JSUtil.isValidJSON(json)) { - json = JSON.parse(json); - } - var bn = new BN(json.bn, 'hex'); - return { - bn: bn, - network: json.network, - compressed: json.compressed - }; -}; - -/** - * Instantiate a PrivateKey from a WIF string - * - * @param {String} str - The WIF encoded private key string - * @returns {PrivateKey} A new valid instance of PrivateKey - */ -PrivateKey.fromString = PrivateKey.fromWIF = function(str) { - return new PrivateKey(str); -}; - -/** - * Instantiate a PrivateKey from random bytes - * - * @param {String} [network] - Either "livenet" or "testnet" - * @returns {PrivateKey} A new valid instance of PrivateKey - */ -PrivateKey.fromRandom = function(network) { - var bn = PrivateKey._getRandomBN(); - return new PrivateKey(bn, network); -}; - -/** - * Check if there would be any errors when initializing a PrivateKey - * - * @param {String} data - The encoded data in various formats - * @param {String} [network] - Either "livenet" or "testnet" - * @returns {null|Error} An error if exists - */ - -PrivateKey.getValidationError = function(data, network) { - var error; - try { - /* jshint nonew: false */ - new PrivateKey(data, network); - } catch (e) { - error = e; - } - return error; -}; - -/** - * Check if the parameters are valid - * - * @param {String} data - The encoded data in various formats - * @param {String} [network] - Either "livenet" or "testnet" - * @returns {Boolean} If the private key is would be valid - */ -PrivateKey.isValid = function(data, network){ - return !PrivateKey.getValidationError(data, network); -}; - -/** - * Will output the PrivateKey encoded as hex string - * - * @returns {String} - */ -PrivateKey.prototype.toString = function() { - return this.toBuffer().toString('hex'); -}; - -/** - * Will output the PrivateKey to a WIF string - * - * @returns {String} A WIP representation of the private key - */ -PrivateKey.prototype.toWIF = function() { - var network = this.network; - var compressed = this.compressed; - - var buf; - if (compressed) { - buf = Buffer.concat([new Buffer([network.privatekey]), - this.bn.toBuffer({size: 32}), - new Buffer([0x01])]); - } else { - buf = Buffer.concat([new Buffer([network.privatekey]), - this.bn.toBuffer({size: 32})]); - } - - return Base58Check.encode(buf); -}; - -/** - * Will return the private key as a BN instance - * - * @returns {BN} A BN instance of the private key - */ -PrivateKey.prototype.toBigNumber = function(){ - return this.bn; -}; - -/** - * Will return the private key as a BN buffer - * - * @returns {Buffer} A buffer of the private key - */ -PrivateKey.prototype.toBuffer = function(){ - return this.bn.toBuffer(); -}; - -/** - * Will return the corresponding public key - * - * @returns {PublicKey} A public key generated from the private key - */ -PrivateKey.prototype.toPublicKey = function(){ - if (!this._pubkey) { - this._pubkey = PublicKey.fromPrivateKey(this); - } - return this._pubkey; -}; - -/** - * Will return an address for the private key - * - * @returns {Address} An address generated from the private key - */ -PrivateKey.prototype.toAddress = function() { - var pubkey = this.toPublicKey(); - return Address.fromPublicKey(pubkey, this.network); -}; - -/** - * @returns {Object} A plain object representation - */ -PrivateKey.prototype.toObject = function toObject() { - return { - bn: this.bn.toString('hex'), - compressed: this.compressed, - network: this.network.toString() - }; -}; - -PrivateKey.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -/** - * Will return a string formatted for the console - * - * @returns {String} Private key - */ -PrivateKey.prototype.inspect = function() { - var uncompressed = !this.compressed ? ', uncompressed' : ''; - return ''; -}; - -module.exports = PrivateKey; - -}).call(this,require("buffer").Buffer) -},{"./address":31,"./crypto/bn":34,"./crypto/point":37,"./crypto/random":38,"./encoding/base58check":41,"./networks":50,"./publickey":53,"./util/js":70,"buffer":209,"lodash":95}],53:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var Address = require('./address'); -var BN = require('./crypto/bn'); -var Point = require('./crypto/point'); -var Hash = require('./crypto/hash'); -var JSUtil = require('./util/js'); -var Network = require('./networks'); -var _ = require('lodash'); -var $ = require('./util/preconditions'); - -/** - * Instantiate a PublicKey from a {@link PrivateKey}, {@link Point}, `string`, or `Buffer`. - * - * There are two internal properties, `network` and `compressed`, that deal with importing - * a PublicKey from a PrivateKey in WIF format. More details described on {@link PrivateKey} - * - * @example - * ```javascript - * // instantiate from a private key - * var key = PublicKey(privateKey, true); - * - * // export to as a DER hex encoded string - * var exported = key.toString(); - * - * // import the public key - * var imported = PublicKey.fromString(exported); - * ``` - * - * @param {String} data - The encoded data in various formats - * @param {Object} extra - additional options - * @param {Network=} extra.network - Which network should the address for this public key be for - * @param {String=} extra.compressed - If the public key is compressed - * @returns {PublicKey} A new valid instance of an PublicKey - * @constructor - */ -var PublicKey = function PublicKey(data, extra) { - - if (!(this instanceof PublicKey)) { - return new PublicKey(data, extra); - } - - $.checkArgument(data, new TypeError('First argument is required, please include public key data.')); - - if (data instanceof PublicKey) { - // Return copy, but as it's an immutable object, return same argument - return data; - } - extra = extra || {}; - - var info = this._classifyArgs(data, extra); - - // validation - info.point.validate(); - - JSUtil.defineImmutable(this, { - point: info.point, - compressed: info.compressed, - network: info.network || Network.defaultNetwork - }); - - return this; -}; - -/** - * Internal function to differentiate between arguments passed to the constructor - * @param {*} data - * @param {Object} extra - */ -PublicKey.prototype._classifyArgs = function(data, extra) { - /* jshint maxcomplexity: 10 */ - var info = { - compressed: _.isUndefined(extra.compressed) || extra.compressed, - network: _.isUndefined(extra.network) ? undefined : Network.get(extra.network) - }; - - // detect type of data - if (data instanceof Point) { - info.point = data; - } else if (PublicKey._isJSON(data)) { - info = PublicKey._transformJSON(data); - } else if (typeof(data) === 'string') { - info = PublicKey._transformDER(new Buffer(data, 'hex')); - } else if (PublicKey._isBuffer(data)) { - info = PublicKey._transformDER(data); - } else if (PublicKey._isPrivateKey(data)) { - info = PublicKey._transformPrivateKey(data); - } else { - throw new TypeError('First argument is an unrecognized data format.'); - } - return info; -}; - -/** - * Internal function to detect if an object is a {@link PrivateKey} - * - * @param {*} param - object to test - * @returns {boolean} - * @private - */ -PublicKey._isPrivateKey = function(param) { - var PrivateKey = require('./privatekey'); - return param instanceof PrivateKey; -}; - -/** - * Internal function to detect if an object is a Buffer - * - * @param {*} param - object to test - * @returns {boolean} - * @private - */ -PublicKey._isBuffer = function(param) { - return (param instanceof Buffer) || (param instanceof Uint8Array); -}; - -/** - * Internal function to detect if a param is a JSON string or plain object - * - * @param {*} param - value to test - * @returns {boolean} - * @private - */ -PublicKey._isJSON = function(json) { - return !!(JSUtil.isValidJSON(json) || (json.x && json.y)); -}; - -/** - * Internal function to transform a private key into a public key point - * - * @param {PrivateKey} privkey - An instance of PrivateKey - * @returns {Object} An object with keys: point and compressed - * @private - */ -PublicKey._transformPrivateKey = function(privkey) { - $.checkArgument(PublicKey._isPrivateKey(privkey), - new TypeError('Must be an instance of PrivateKey')); - var info = {}; - info.point = Point.getG().mul(privkey.bn); - info.compressed = privkey.compressed; - info.network = privkey.network; - return info; -}; - -/** - * Internal function to transform DER into a public key point - * - * @param {Buffer} buf - An hex encoded buffer - * @param {bool} [strict] - if set to false, will loosen some conditions - * @returns {Object} An object with keys: point and compressed - * @private - */ -PublicKey._transformDER = function(buf, strict) { - /* jshint maxstatements: 30 */ - /* jshint maxcomplexity: 12 */ - $.checkArgument(PublicKey._isBuffer(buf), new TypeError('Must be a hex buffer of DER encoded public key')); - var info = {}; - - strict = _.isUndefined(strict) ? true : strict; - - var x; - var y; - var xbuf; - var ybuf; - - if (buf[0] === 0x04 || (!strict && (buf[0] === 0x06 || buf[0] === 0x07))) { - xbuf = buf.slice(1, 33); - ybuf = buf.slice(33, 65); - if (xbuf.length !== 32 || ybuf.length !== 32 || buf.length !== 65) { - throw new TypeError('Length of x and y must be 32 bytes'); - } - x = new BN(xbuf); - y = new BN(ybuf); - info.point = new Point(x, y); - info.compressed = false; - } else if (buf[0] === 0x03) { - xbuf = buf.slice(1); - x = new BN(xbuf); - info = PublicKey._transformX(true, x); - info.compressed = true; - } else if (buf[0] === 0x02) { - xbuf = buf.slice(1); - x = new BN(xbuf); - info = PublicKey._transformX(false, x); - info.compressed = true; - } else { - throw new TypeError('Invalid DER format public key'); - } - return info; -}; - -/** - * Internal function to transform X into a public key point - * - * @param {Boolean} odd - If the point is above or below the x axis - * @param {Point} x - The x point - * @returns {Object} An object with keys: point and compressed - * @private - */ -PublicKey._transformX = function(odd, x) { - $.checkArgument(typeof odd === 'boolean', - new TypeError('Must specify whether y is odd or not (true or false)')); - var info = {}; - info.point = Point.fromX(odd, x); - return info; -}; - -/** - * Instantiate a PublicKey from JSON - * - * @param {String} json - A JSON string - * @returns {PublicKey} A new valid instance of PublicKey - */ -PublicKey.fromJSON = function(json) { - $.checkArgument(PublicKey._isJSON(json), - new TypeError('Must be a valid JSON string or plain object')); - return new PublicKey(json); -}; - -/** - * Internal function to transform a JSON into a public key point - * - * @param {Buffer} buf - a JSON string or plain object - * @returns {Object} An object with keys: point and compressed - * @private - */ -PublicKey._transformJSON = function(json) { - if (JSUtil.isValidJSON(json)) { - json = JSON.parse(json); - } - var x = new BN(json.x, 'hex'); - var y = new BN(json.y, 'hex'); - var point = new Point(x, y); - return new PublicKey(point, { - compressed: json.compressed - }); -}; - -/** - * Instantiate a PublicKey from a PrivateKey - * - * @param {PrivateKey} privkey - An instance of PrivateKey - * @returns {PublicKey} A new valid instance of PublicKey - */ -PublicKey.fromPrivateKey = function(privkey) { - $.checkArgument(PublicKey._isPrivateKey(privkey), new TypeError('Must be an instance of PrivateKey')); - var info = PublicKey._transformPrivateKey(privkey); - return new PublicKey(info.point, { - compressed: info.compressed, - network: info.network - }); -}; - -/** - * Instantiate a PublicKey from a Buffer - * @param {Buffer} buf - A DER hex buffer - * @param {bool} [strict] - if set to false, will loosen some conditions - * @returns {PublicKey} A new valid instance of PublicKey - */ -PublicKey.fromDER = PublicKey.fromBuffer = function(buf, strict) { - $.checkArgument(PublicKey._isBuffer(buf), - new TypeError('Must be a hex buffer of DER encoded public key')); - var info = PublicKey._transformDER(buf, strict); - return new PublicKey(info.point, { - compressed: info.compressed - }); -}; - -/** - * Instantiate a PublicKey from a Point - * - * @param {Point} point - A Point instance - * @param {boolean=} compressed - whether to store this public key as compressed format - * @returns {PublicKey} A new valid instance of PublicKey - */ -PublicKey.fromPoint = function(point, compressed) { - $.checkArgument(point instanceof Point, - new TypeError('First argument must be an instance of Point.')); - return new PublicKey(point, { - compressed: compressed - }); -}; - -/** - * Instantiate a PublicKey from a DER hex encoded string - * - * @param {String} str - A DER hex string - * @param {String} [encoding] - The type of string encoding - * @returns {PublicKey} A new valid instance of PublicKey - */ -PublicKey.fromString = function(str, encoding) { - var buf = new Buffer(str, encoding || 'hex'); - var info = PublicKey._transformDER(buf); - return new PublicKey(info.point, { - compressed: info.compressed - }); -}; - -/** - * Instantiate a PublicKey from an X Point - * - * @param {Boolean} odd - If the point is above or below the x axis - * @param {Point} x - The x point - * @returns {PublicKey} A new valid instance of PublicKey - */ -PublicKey.fromX = function(odd, x) { - var info = PublicKey._transformX(odd, x); - return new PublicKey(info.point, { - compressed: info.compressed - }); -}; - -/** - * Check if there would be any errors when initializing a PublicKey - * - * @param {String} data - The encoded data in various formats - * @param {String} [compressed] - If the public key is compressed - * @returns {null|Error} An error if exists - */ -PublicKey.getValidationError = function(data) { - var error; - try { - /* jshint nonew: false */ - new PublicKey(data); - } catch (e) { - error = e; - } - return error; -}; - -/** - * Check if the parameters are valid - * - * @param {String} data - The encoded data in various formats - * @param {String} [compressed] - If the public key is compressed - * @returns {Boolean} If the public key would be valid - */ -PublicKey.isValid = function(data) { - return !PublicKey.getValidationError(data); -}; - -/** - * @returns {Object} A plain object of the PublicKey - */ -PublicKey.prototype.toObject = function toObject() { - return { - x: this.point.getX().toString('hex'), - y: this.point.getY().toString('hex'), - compressed: this.compressed - }; -}; - -PublicKey.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -/** - * Will output the PublicKey to a DER Buffer - * - * @returns {Buffer} A DER hex encoded buffer - */ -PublicKey.prototype.toBuffer = PublicKey.prototype.toDER = function() { - var x = this.point.getX(); - var y = this.point.getY(); - - var xbuf = x.toBuffer({ - size: 32 - }); - var ybuf = y.toBuffer({ - size: 32 - }); - - var prefix; - if (!this.compressed) { - prefix = new Buffer([0x04]); - return Buffer.concat([prefix, xbuf, ybuf]); - } else { - var odd = ybuf[ybuf.length - 1] % 2; - if (odd) { - prefix = new Buffer([0x03]); - } else { - prefix = new Buffer([0x02]); - } - return Buffer.concat([prefix, xbuf]); - } -}; - -/** - * Will return a sha256 + ripemd160 hash of the serialized public key - * @see https://github.com/bitcoin/bitcoin/blob/master/src/pubkey.h#L141 - * @returns {Buffer} - */ -PublicKey.prototype._getID = function _getID() { - return Hash.sha256ripemd160(this.toBuffer()); -}; - -/** - * Will return an address for the public key - * - * @returns {Address} An address generated from the public key - */ -PublicKey.prototype.toAddress = function(network) { - return Address.fromPublicKey(this, network || this.network); -}; - -/** - * Will output the PublicKey to a DER encoded hex string - * - * @returns {String} A DER hex encoded string - */ -PublicKey.prototype.toString = function() { - return this.toDER().toString('hex'); -}; - -/** - * Will return a string formatted for the console - * - * @returns {String} Public key - */ -PublicKey.prototype.inspect = function() { - return ''; -}; - - -module.exports = PublicKey; - -}).call(this,require("buffer").Buffer) -},{"./address":31,"./crypto/bn":34,"./crypto/hash":36,"./crypto/point":37,"./networks":50,"./privatekey":52,"./util/js":70,"./util/preconditions":71,"buffer":209,"lodash":95}],54:[function(require,module,exports){ -module.exports = require('./script'); - -module.exports.Interpreter = require('./interpreter'); - -},{"./interpreter":55,"./script":56}],55:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); - -var Script = require('./script'); -var Opcode = require('../opcode'); -var BN = require('../crypto/bn'); -var Hash = require('../crypto/hash'); -var Signature = require('../crypto/signature'); -var PublicKey = require('../publickey'); - -/** - * Bitcoin transactions contain scripts. Each input has a script called the - * scriptSig, and each output has a script called the scriptPubkey. To validate - * an input, the input's script is concatenated with the referenced output script, - * and the result is executed. If at the end of execution the stack contains a - * "true" value, then the transaction is valid. - * - * The primary way to use this class is via the verify function. - * e.g., Interpreter().verify( ... ); - */ -var Interpreter = function Interpreter(obj) { - if (!(this instanceof Interpreter)) { - return new Interpreter(obj); - } - if (obj) { - this.initialize(); - this.set(obj); - } else { - this.initialize(); - } -}; - -/** - * Verifies a Script by executing it and returns true if it is valid. - * This function needs to be provided with the scriptSig and the scriptPubkey - * separately. - * @param {Script} scriptSig - the script's first part (corresponding to the tx input) - * @param {Script} scriptPubkey - the script's last part (corresponding to the tx output) - * @param {Transaction} [tx] - the Transaction containing the scriptSig in one input (used - * to check signature validity for some opcodes like OP_CHECKSIG) - * @param {number} nin - index of the transaction input containing the scriptSig verified. - * @param {number} flags - evaluation flags. See Interpreter.SCRIPT_* constants - * - * Translated from bitcoind's VerifyScript - */ -Interpreter.prototype.verify = function(scriptSig, scriptPubkey, tx, nin, flags) { - var Transaction = require('../transaction'); - if (_.isUndefined(tx)) { - tx = new Transaction(); - } - if (_.isUndefined(nin)) { - nin = 0; - } - if (_.isUndefined(flags)) { - flags = 0; - } - this.set({ - script: scriptSig, - tx: tx, - nin: nin, - flags: flags - }); - var stackCopy; - - if ((flags & Interpreter.SCRIPT_VERIFY_SIGPUSHONLY) !== 0 && !scriptSig.isPushOnly()) { - this.errstr = 'SCRIPT_ERR_SIG_PUSHONLY'; - return false; - } - - // evaluate scriptSig - if (!this.evaluate()) { - return false; - } - - if (flags & Interpreter.SCRIPT_VERIFY_P2SH) { - stackCopy = this.stack.slice(); - } - - var stack = this.stack; - this.initialize(); - this.set({ - script: scriptPubkey, - stack: stack, - tx: tx, - nin: nin, - flags: flags - }); - - // evaluate scriptPubkey - if (!this.evaluate()) { - return false; - } - - if (this.stack.length === 0) { - this.errstr = 'SCRIPT_ERR_EVAL_FALSE_NO_RESULT'; - return false; - } - - var buf = this.stack[this.stack.length - 1]; - if (!Interpreter.castToBool(buf)) { - this.errstr = 'SCRIPT_ERR_EVAL_FALSE_IN_STACK'; - return false; - } - - // Additional validation for spend-to-script-hash transactions: - if ((flags & Interpreter.SCRIPT_VERIFY_P2SH) && scriptPubkey.isScriptHashOut()) { - // scriptSig must be literals-only or validation fails - if (!scriptSig.isPushOnly()) { - this.errstr = 'SCRIPT_ERR_SIG_PUSHONLY'; - return false; - } - - // stackCopy cannot be empty here, because if it was the - // P2SH HASH <> EQUAL scriptPubKey would be evaluated with - // an empty stack and the EvalScript above would return false. - if (stackCopy.length === 0) { - throw new Error('internal error - stack copy empty'); - } - - var redeemScriptSerialized = stackCopy[stackCopy.length - 1]; - var redeemScript = Script.fromBuffer(redeemScriptSerialized); - stackCopy.pop(); - - this.initialize(); - this.set({ - script: redeemScript, - stack: stackCopy, - tx: tx, - nin: nin, - flags: flags - }); - - // evaluate redeemScript - if (!this.evaluate()) { - return false; - } - - if (stackCopy.length === 0) { - this.errstr = 'SCRIPT_ERR_EVAL_FALSE_NO_P2SH_STACK'; - return false; - } - - if (!Interpreter.castToBool(stackCopy[stackCopy.length - 1])) { - this.errstr = 'SCRIPT_ERR_EVAL_FALSE_IN_P2SH_STACK'; - return false; - } else { - return true; - } - } - - return true; -}; - -module.exports = Interpreter; - -Interpreter.prototype.initialize = function(obj) { - this.stack = []; - this.altstack = []; - this.pc = 0; - this.pbegincodehash = 0; - this.nOpCount = 0; - this.vfExec = []; - this.errstr = ''; - this.flags = 0; -}; - -Interpreter.prototype.set = function(obj) { - this.script = obj.script || this.script; - this.tx = obj.tx || this.tx; - this.nin = typeof obj.nin !== 'undefined' ? obj.nin : this.nin; - this.stack = obj.stack || this.stack; - this.altstack = obj.altack || this.altstack; - this.pc = typeof obj.pc !== 'undefined' ? obj.pc : this.pc; - this.pbegincodehash = typeof obj.pbegincodehash !== 'undefined' ? obj.pbegincodehash : this.pbegincodehash; - this.nOpCount = typeof obj.nOpCount !== 'undefined' ? obj.nOpCount : this.nOpCount; - this.vfExec = obj.vfExec || this.vfExec; - this.errstr = obj.errstr || this.errstr; - this.flags = typeof obj.flags !== 'undefined' ? obj.flags : this.flags; -}; - -Interpreter.true = new Buffer([1]); -Interpreter.false = new Buffer([]); - -Interpreter.MAX_SCRIPT_ELEMENT_SIZE = 520; - -// flags taken from bitcoind -// bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104 -Interpreter.SCRIPT_VERIFY_NONE = 0; - -// Evaluate P2SH subscripts (softfork safe, BIP16). -Interpreter.SCRIPT_VERIFY_P2SH = (1 << 0); - -// Passing a non-strict-DER signature or one with undefined hashtype to a checksig operation causes script failure. -// Passing a pubkey that is not (0x04 + 64 bytes) or (0x02 or 0x03 + 32 bytes) to checksig causes that pubkey to be -// skipped (not softfork safe: this flag can widen the validity of OP_CHECKSIG OP_NOT). -Interpreter.SCRIPT_VERIFY_STRICTENC = (1 << 1); - -// Passing a non-strict-DER signature to a checksig operation causes script failure (softfork safe, BIP62 rule 1) -Interpreter.SCRIPT_VERIFY_DERSIG = (1 << 2); - -// Passing a non-strict-DER signature or one with S > order/2 to a checksig operation causes script failure -// (softfork safe, BIP62 rule 5). -Interpreter.SCRIPT_VERIFY_LOW_S = (1 << 3); - -// verify dummy stack item consumed by CHECKMULTISIG is of zero-length (softfork safe, BIP62 rule 7). -Interpreter.SCRIPT_VERIFY_NULLDUMMY = (1 << 4); - -// Using a non-push operator in the scriptSig causes script failure (softfork safe, BIP62 rule 2). -Interpreter.SCRIPT_VERIFY_SIGPUSHONLY = (1 << 5); - -// Require minimal encodings for all push operations (OP_0... OP_16, OP_1NEGATE where possible, direct -// pushes up to 75 bytes, OP_PUSHDATA up to 255 bytes, OP_PUSHDATA2 for anything larger). Evaluating -// any other push causes the script to fail (BIP62 rule 3). -// In addition, whenever a stack element is interpreted as a number, it must be of minimal length (BIP62 rule 4). -// (softfork safe) -Interpreter.SCRIPT_VERIFY_MINIMALDATA = (1 << 6); - -// Discourage use of NOPs reserved for upgrades (NOP1-10) -// -// Provided so that nodes can avoid accepting or mining transactions -// containing executed NOP's whose meaning may change after a soft-fork, -// thus rendering the script invalid; with this flag set executing -// discouraged NOPs fails the script. This verification flag will never be -// a mandatory flag applied to scripts in a block. NOPs that are not -// executed, e.g. within an unexecuted IF ENDIF block, are *not* rejected. -Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS = (1 << 7); - -Interpreter.castToBool = function(buf) { - for (var i = 0; i < buf.length; i++) { - if (buf[i] !== 0) { - // can be negative zero - if (i === buf.length - 1 && buf[i] === 0x80) { - return false; - } - return true; - } - } - return false; -}; - -/** - * Translated from bitcoind's CheckSignatureEncoding - */ -Interpreter.prototype.checkSignatureEncoding = function(buf) { - var sig; - if ((this.flags & (Interpreter.SCRIPT_VERIFY_DERSIG | Interpreter.SCRIPT_VERIFY_LOW_S | Interpreter.SCRIPT_VERIFY_STRICTENC)) !== 0 && !Signature.isTxDER(buf)) { - this.errstr = 'SCRIPT_ERR_SIG_DER_INVALID_FORMAT'; - return false; - } else if ((this.flags & Interpreter.SCRIPT_VERIFY_LOW_S) !== 0) { - sig = Signature.fromTxFormat(buf); - if (!sig.hasLowS()) { - this.errstr = 'SCRIPT_ERR_SIG_DER_HIGH_S'; - return false; - } - } else if ((this.flags & Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0) { - sig = Signature.fromTxFormat(buf); - if (!sig.hasDefinedHashtype()) { - this.errstr = 'SCRIPT_ERR_SIG_HASHTYPE'; - return false; - } - } - return true; -}; - -/** - * Translated from bitcoind's CheckPubKeyEncoding - */ -Interpreter.prototype.checkPubkeyEncoding = function(buf) { - if ((this.flags & Interpreter.SCRIPT_VERIFY_STRICTENC) !== 0 && !PublicKey.isValid(buf)) { - this.errstr = 'SCRIPT_ERR_PUBKEYTYPE'; - return false; - } - return true; -}; - -/** - * Based on bitcoind's EvalScript function, with the inner loop moved to - * Interpreter.prototype.step() - * bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104 - */ -Interpreter.prototype.evaluate = function() { - if (this.script.toBuffer().length > 10000) { - this.errstr = 'SCRIPT_ERR_SCRIPT_SIZE'; - return false; - } - - try { - while (this.pc < this.script.chunks.length) { - var fSuccess = this.step(); - if (!fSuccess) { - return false; - } - } - - // Size limits - if (this.stack.length + this.altstack.length > 1000) { - this.errstr = 'SCRIPT_ERR_STACK_SIZE'; - return false; - } - } catch (e) { - this.errstr = 'SCRIPT_ERR_UNKNOWN_ERROR: ' + e; - return false; - } - - if (this.vfExec.length > 0) { - this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'; - return false; - } - - return true; -}; - -/** - * Based on the inner loop of bitcoind's EvalScript function - * bitcoind commit: b5d1b1092998bc95313856d535c632ea5a8f9104 - */ -Interpreter.prototype.step = function() { - - var fRequireMinimal = (this.flags & Interpreter.SCRIPT_VERIFY_MINIMALDATA) !== 0; - - //bool fExec = !count(vfExec.begin(), vfExec.end(), false); - var fExec = (this.vfExec.indexOf(false) === -1); - var buf, buf1, buf2, spliced, n, x1, x2, bn, bn1, bn2, bufSig, bufPubkey, subscript; - var sig, pubkey; - var fValue, fSuccess; - - // Read instruction - var chunk = this.script.chunks[this.pc]; - this.pc++; - var opcodenum = chunk.opcodenum; - if (_.isUndefined(opcodenum)) { - this.errstr = 'SCRIPT_ERR_UNDEFINED_OPCODE'; - return false; - } - if (chunk.buf && chunk.buf.length > Interpreter.MAX_SCRIPT_ELEMENT_SIZE) { - this.errstr = 'SCRIPT_ERR_PUSH_SIZE'; - return false; - } - - // Note how Opcode.OP_RESERVED does not count towards the opcode limit. - if (opcodenum > Opcode.OP_16 && ++(this.nOpCount) > 201) { - this.errstr = 'SCRIPT_ERR_OP_COUNT'; - return false; - } - - - if (opcodenum === Opcode.OP_CAT || - opcodenum === Opcode.OP_SUBSTR || - opcodenum === Opcode.OP_LEFT || - opcodenum === Opcode.OP_RIGHT || - opcodenum === Opcode.OP_INVERT || - opcodenum === Opcode.OP_AND || - opcodenum === Opcode.OP_OR || - opcodenum === Opcode.OP_XOR || - opcodenum === Opcode.OP_2MUL || - opcodenum === Opcode.OP_2DIV || - opcodenum === Opcode.OP_MUL || - opcodenum === Opcode.OP_DIV || - opcodenum === Opcode.OP_MOD || - opcodenum === Opcode.OP_LSHIFT || - opcodenum === Opcode.OP_RSHIFT) { - this.errstr = 'SCRIPT_ERR_DISABLED_OPCODE'; - return false; - } - - if (fExec && 0 <= opcodenum && opcodenum <= Opcode.OP_PUSHDATA4) { - if (fRequireMinimal && !this.script.checkMinimalPush(this.pc - 1)) { - this.errstr = 'SCRIPT_ERR_MINIMALDATA'; - return false; - } - if (!chunk.buf) { - this.stack.push(Interpreter.false); - } else if (chunk.len !== chunk.buf.length) { - throw new Error('Length of push value not equal to length of data'); - } else { - this.stack.push(chunk.buf); - } - } else if (fExec || (Opcode.OP_IF <= opcodenum && opcodenum <= Opcode.OP_ENDIF)) { - switch (opcodenum) { - // Push value - case Opcode.OP_1NEGATE: - case Opcode.OP_1: - case Opcode.OP_2: - case Opcode.OP_3: - case Opcode.OP_4: - case Opcode.OP_5: - case Opcode.OP_6: - case Opcode.OP_7: - case Opcode.OP_8: - case Opcode.OP_9: - case Opcode.OP_10: - case Opcode.OP_11: - case Opcode.OP_12: - case Opcode.OP_13: - case Opcode.OP_14: - case Opcode.OP_15: - case Opcode.OP_16: - { - // ( -- value) - // ScriptNum bn((int)opcode - (int)(Opcode.OP_1 - 1)); - n = opcodenum - (Opcode.OP_1 - 1); - buf = new BN(n).toScriptNumBuffer(); - this.stack.push(buf); - // The result of these opcodes should always be the minimal way to push the data - // they push, so no need for a CheckMinimalPush here. - } - break; - - - // - // Control - // - case Opcode.OP_NOP: - break; - - case Opcode.OP_NOP1: - case Opcode.OP_NOP2: - case Opcode.OP_NOP3: - case Opcode.OP_NOP4: - case Opcode.OP_NOP5: - case Opcode.OP_NOP6: - case Opcode.OP_NOP7: - case Opcode.OP_NOP8: - case Opcode.OP_NOP9: - case Opcode.OP_NOP10: - { - if (this.flags & Interpreter.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS) { - this.errstr = 'SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS'; - return false; - } - } - break; - - case Opcode.OP_IF: - case Opcode.OP_NOTIF: - { - // if [statements] [else [statements]] endif - // bool fValue = false; - fValue = false; - if (fExec) { - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'; - return false; - } - buf = this.stack.pop(); - fValue = Interpreter.castToBool(buf); - if (opcodenum === Opcode.OP_NOTIF) { - fValue = !fValue; - } - } - this.vfExec.push(fValue); - } - break; - - case Opcode.OP_ELSE: - { - if (this.vfExec.length === 0) { - this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'; - return false; - } - this.vfExec[this.vfExec.length - 1] = !this.vfExec[this.vfExec.length - 1]; - } - break; - - case Opcode.OP_ENDIF: - { - if (this.vfExec.length === 0) { - this.errstr = 'SCRIPT_ERR_UNBALANCED_CONDITIONAL'; - return false; - } - this.vfExec.pop(); - } - break; - - case Opcode.OP_VERIFY: - { - // (true -- ) or - // (false -- false) and return - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf = this.stack[this.stack.length - 1]; - fValue = Interpreter.castToBool(buf); - if (fValue) { - this.stack.pop(); - } else { - this.errstr = 'SCRIPT_ERR_VERIFY'; - return false; - } - } - break; - - case Opcode.OP_RETURN: - { - this.errstr = 'SCRIPT_ERR_OP_RETURN'; - return false; - } - break; - - - // - // Stack ops - // - case Opcode.OP_TOALTSTACK: - { - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - this.altstack.push(this.stack.pop()); - } - break; - - case Opcode.OP_FROMALTSTACK: - { - if (this.altstack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_ALTSTACK_OPERATION'; - return false; - } - this.stack.push(this.altstack.pop()); - } - break; - - case Opcode.OP_2DROP: - { - // (x1 x2 -- ) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - this.stack.pop(); - this.stack.pop(); - } - break; - - case Opcode.OP_2DUP: - { - // (x1 x2 -- x1 x2 x1 x2) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf1 = this.stack[this.stack.length - 2]; - buf2 = this.stack[this.stack.length - 1]; - this.stack.push(buf1); - this.stack.push(buf2); - } - break; - - case Opcode.OP_3DUP: - { - // (x1 x2 x3 -- x1 x2 x3 x1 x2 x3) - if (this.stack.length < 3) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf1 = this.stack[this.stack.length - 3]; - buf2 = this.stack[this.stack.length - 2]; - var buf3 = this.stack[this.stack.length - 1]; - this.stack.push(buf1); - this.stack.push(buf2); - this.stack.push(buf3); - } - break; - - case Opcode.OP_2OVER: - { - // (x1 x2 x3 x4 -- x1 x2 x3 x4 x1 x2) - if (this.stack.length < 4) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf1 = this.stack[this.stack.length - 4]; - buf2 = this.stack[this.stack.length - 3]; - this.stack.push(buf1); - this.stack.push(buf2); - } - break; - - case Opcode.OP_2ROT: - { - // (x1 x2 x3 x4 x5 x6 -- x3 x4 x5 x6 x1 x2) - if (this.stack.length < 6) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - spliced = this.stack.splice(this.stack.length - 6, 2); - this.stack.push(spliced[0]); - this.stack.push(spliced[1]); - } - break; - - case Opcode.OP_2SWAP: - { - // (x1 x2 x3 x4 -- x3 x4 x1 x2) - if (this.stack.length < 4) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - spliced = this.stack.splice(this.stack.length - 4, 2); - this.stack.push(spliced[0]); - this.stack.push(spliced[1]); - } - break; - - case Opcode.OP_IFDUP: - { - // (x - 0 | x x) - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf = this.stack[this.stack.length - 1]; - fValue = Interpreter.castToBool(buf); - if (fValue) { - this.stack.push(buf); - } - } - break; - - case Opcode.OP_DEPTH: - { - // -- stacksize - buf = new BN(this.stack.length).toScriptNumBuffer(); - this.stack.push(buf); - } - break; - - case Opcode.OP_DROP: - { - // (x -- ) - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - this.stack.pop(); - } - break; - - case Opcode.OP_DUP: - { - // (x -- x x) - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - this.stack.push(this.stack[this.stack.length - 1]); - } - break; - - case Opcode.OP_NIP: - { - // (x1 x2 -- x2) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - this.stack.splice(this.stack.length - 2, 1); - } - break; - - case Opcode.OP_OVER: - { - // (x1 x2 -- x1 x2 x1) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - this.stack.push(this.stack[this.stack.length - 2]); - } - break; - - case Opcode.OP_PICK: - case Opcode.OP_ROLL: - { - // (xn ... x2 x1 x0 n - xn ... x2 x1 x0 xn) - // (xn ... x2 x1 x0 n - ... x2 x1 x0 xn) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf = this.stack[this.stack.length - 1]; - bn = BN.fromScriptNumBuffer(buf, fRequireMinimal); - n = bn.toNumber(); - this.stack.pop(); - if (n < 0 || n >= this.stack.length) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf = this.stack[this.stack.length - n - 1]; - if (opcodenum === Opcode.OP_ROLL) { - this.stack.splice(this.stack.length - n - 1, 1); - } - this.stack.push(buf); - } - break; - - case Opcode.OP_ROT: - { - // (x1 x2 x3 -- x2 x3 x1) - // x2 x1 x3 after first swap - // x2 x3 x1 after second swap - if (this.stack.length < 3) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - x1 = this.stack[this.stack.length - 3]; - x2 = this.stack[this.stack.length - 2]; - var x3 = this.stack[this.stack.length - 1]; - this.stack[this.stack.length - 3] = x2; - this.stack[this.stack.length - 2] = x3; - this.stack[this.stack.length - 1] = x1; - } - break; - - case Opcode.OP_SWAP: - { - // (x1 x2 -- x2 x1) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - x1 = this.stack[this.stack.length - 2]; - x2 = this.stack[this.stack.length - 1]; - this.stack[this.stack.length - 2] = x2; - this.stack[this.stack.length - 1] = x1; - } - break; - - case Opcode.OP_TUCK: - { - // (x1 x2 -- x2 x1 x2) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - this.stack.splice(this.stack.length - 2, 0, this.stack[this.stack.length - 1]); - } - break; - - - case Opcode.OP_SIZE: - { - // (in -- in size) - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - bn = new BN(this.stack[this.stack.length - 1].length); - this.stack.push(bn.toScriptNumBuffer()); - } - break; - - - // - // Bitwise logic - // - case Opcode.OP_EQUAL: - case Opcode.OP_EQUALVERIFY: - //case Opcode.OP_NOTEQUAL: // use Opcode.OP_NUMNOTEQUAL - { - // (x1 x2 - bool) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf1 = this.stack[this.stack.length - 2]; - buf2 = this.stack[this.stack.length - 1]; - var fEqual = buf1.toString('hex') === buf2.toString('hex'); - this.stack.pop(); - this.stack.pop(); - this.stack.push(fEqual ? Interpreter.true : Interpreter.false); - if (opcodenum === Opcode.OP_EQUALVERIFY) { - if (fEqual) { - this.stack.pop(); - } else { - this.errstr = 'SCRIPT_ERR_EQUALVERIFY'; - return false; - } - } - } - break; - - - // - // Numeric - // - case Opcode.OP_1ADD: - case Opcode.OP_1SUB: - case Opcode.OP_NEGATE: - case Opcode.OP_ABS: - case Opcode.OP_NOT: - case Opcode.OP_0NOTEQUAL: - { - // (in -- out) - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf = this.stack[this.stack.length - 1]; - bn = BN.fromScriptNumBuffer(buf, fRequireMinimal); - switch (opcodenum) { - case Opcode.OP_1ADD: - bn = bn.add(BN.One); - break; - case Opcode.OP_1SUB: - bn = bn.sub(BN.One); - break; - case Opcode.OP_NEGATE: - bn = bn.neg(); - break; - case Opcode.OP_ABS: - if (bn.cmp(BN.Zero) < 0) { - bn = bn.neg(); - } - break; - case Opcode.OP_NOT: - bn = new BN((bn.cmp(BN.Zero) === 0) + 0); - break; - case Opcode.OP_0NOTEQUAL: - bn = new BN((bn.cmp(BN.Zero) !== 0) + 0); - break; - //default: assert(!'invalid opcode'); break; // TODO: does this ever occur? - } - this.stack.pop(); - this.stack.push(bn.toScriptNumBuffer()); - } - break; - - case Opcode.OP_ADD: - case Opcode.OP_SUB: - case Opcode.OP_BOOLAND: - case Opcode.OP_BOOLOR: - case Opcode.OP_NUMEQUAL: - case Opcode.OP_NUMEQUALVERIFY: - case Opcode.OP_NUMNOTEQUAL: - case Opcode.OP_LESSTHAN: - case Opcode.OP_GREATERTHAN: - case Opcode.OP_LESSTHANOREQUAL: - case Opcode.OP_GREATERTHANOREQUAL: - case Opcode.OP_MIN: - case Opcode.OP_MAX: - { - // (x1 x2 -- out) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - bn1 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 2], fRequireMinimal); - bn2 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 1], fRequireMinimal); - bn = new BN(0); - - switch (opcodenum) { - case Opcode.OP_ADD: - bn = bn1.add(bn2); - break; - - case Opcode.OP_SUB: - bn = bn1.sub(bn2); - break; - - // case Opcode.OP_BOOLAND: bn = (bn1 != bnZero && bn2 != bnZero); break; - case Opcode.OP_BOOLAND: - bn = new BN(((bn1.cmp(BN.Zero) !== 0) && (bn2.cmp(BN.Zero) !== 0)) + 0); - break; - // case Opcode.OP_BOOLOR: bn = (bn1 != bnZero || bn2 != bnZero); break; - case Opcode.OP_BOOLOR: - bn = new BN(((bn1.cmp(BN.Zero) !== 0) || (bn2.cmp(BN.Zero) !== 0)) + 0); - break; - // case Opcode.OP_NUMEQUAL: bn = (bn1 == bn2); break; - case Opcode.OP_NUMEQUAL: - bn = new BN((bn1.cmp(bn2) === 0) + 0); - break; - // case Opcode.OP_NUMEQUALVERIFY: bn = (bn1 == bn2); break; - case Opcode.OP_NUMEQUALVERIFY: - bn = new BN((bn1.cmp(bn2) === 0) + 0); - break; - // case Opcode.OP_NUMNOTEQUAL: bn = (bn1 != bn2); break; - case Opcode.OP_NUMNOTEQUAL: - bn = new BN((bn1.cmp(bn2) !== 0) + 0); - break; - // case Opcode.OP_LESSTHAN: bn = (bn1 < bn2); break; - case Opcode.OP_LESSTHAN: - bn = new BN((bn1.cmp(bn2) < 0) + 0); - break; - // case Opcode.OP_GREATERTHAN: bn = (bn1 > bn2); break; - case Opcode.OP_GREATERTHAN: - bn = new BN((bn1.cmp(bn2) > 0) + 0); - break; - // case Opcode.OP_LESSTHANOREQUAL: bn = (bn1 <= bn2); break; - case Opcode.OP_LESSTHANOREQUAL: - bn = new BN((bn1.cmp(bn2) <= 0) + 0); - break; - // case Opcode.OP_GREATERTHANOREQUAL: bn = (bn1 >= bn2); break; - case Opcode.OP_GREATERTHANOREQUAL: - bn = new BN((bn1.cmp(bn2) >= 0) + 0); - break; - case Opcode.OP_MIN: - bn = (bn1.cmp(bn2) < 0 ? bn1 : bn2); - break; - case Opcode.OP_MAX: - bn = (bn1.cmp(bn2) > 0 ? bn1 : bn2); - break; - // default: assert(!'invalid opcode'); break; //TODO: does this ever occur? - } - this.stack.pop(); - this.stack.pop(); - this.stack.push(bn.toScriptNumBuffer()); - - if (opcodenum === Opcode.OP_NUMEQUALVERIFY) { - // if (CastToBool(stacktop(-1))) - if (Interpreter.castToBool(this.stack[this.stack.length - 1])) { - this.stack.pop(); - } else { - this.errstr = 'SCRIPT_ERR_NUMEQUALVERIFY'; - return false; - } - } - } - break; - - case Opcode.OP_WITHIN: - { - // (x min max -- out) - if (this.stack.length < 3) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - bn1 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 3], fRequireMinimal); - bn2 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 2], fRequireMinimal); - var bn3 = BN.fromScriptNumBuffer(this.stack[this.stack.length - 1], fRequireMinimal); - //bool fValue = (bn2 <= bn1 && bn1 < bn3); - fValue = (bn2.cmp(bn1) <= 0) && (bn1.cmp(bn3) < 0); - this.stack.pop(); - this.stack.pop(); - this.stack.pop(); - this.stack.push(fValue ? Interpreter.true : Interpreter.false); - } - break; - - - // - // Crypto - // - case Opcode.OP_RIPEMD160: - case Opcode.OP_SHA1: - case Opcode.OP_SHA256: - case Opcode.OP_HASH160: - case Opcode.OP_HASH256: - { - // (in -- hash) - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - buf = this.stack[this.stack.length - 1]; - //valtype vchHash((opcode == Opcode.OP_RIPEMD160 || - // opcode == Opcode.OP_SHA1 || opcode == Opcode.OP_HASH160) ? 20 : 32); - var bufHash; - if (opcodenum === Opcode.OP_RIPEMD160) { - bufHash = Hash.ripemd160(buf); - } else if (opcodenum === Opcode.OP_SHA1) { - bufHash = Hash.sha1(buf); - } else if (opcodenum === Opcode.OP_SHA256) { - bufHash = Hash.sha256(buf); - } else if (opcodenum === Opcode.OP_HASH160) { - bufHash = Hash.sha256ripemd160(buf); - } else if (opcodenum === Opcode.OP_HASH256) { - bufHash = Hash.sha256sha256(buf); - } - this.stack.pop(); - this.stack.push(bufHash); - } - break; - - case Opcode.OP_CODESEPARATOR: - { - // Hash starts after the code separator - this.pbegincodehash = this.pc; - } - break; - - case Opcode.OP_CHECKSIG: - case Opcode.OP_CHECKSIGVERIFY: - { - // (sig pubkey -- bool) - if (this.stack.length < 2) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - - bufSig = this.stack[this.stack.length - 2]; - bufPubkey = this.stack[this.stack.length - 1]; - - // Subset of script starting at the most recent codeseparator - // CScript scriptCode(pbegincodehash, pend); - subscript = new Script().set({ - chunks: this.script.chunks.slice(this.pbegincodehash) - }); - - // Drop the signature, since there's no way for a signature to sign itself - var tmpScript = new Script().add(bufSig); - subscript.findAndDelete(tmpScript); - - if (!this.checkSignatureEncoding(bufSig) || !this.checkPubkeyEncoding(bufPubkey)) { - return false; - } - - try { - sig = Signature.fromTxFormat(bufSig); - pubkey = PublicKey.fromBuffer(bufPubkey, false); - fSuccess = this.tx.verifySignature(sig, pubkey, this.nin, subscript); - } catch (e) { - //invalid sig or pubkey - fSuccess = false; - } - - this.stack.pop(); - this.stack.pop(); - // stack.push_back(fSuccess ? vchTrue : vchFalse); - this.stack.push(fSuccess ? Interpreter.true : Interpreter.false); - if (opcodenum === Opcode.OP_CHECKSIGVERIFY) { - if (fSuccess) { - this.stack.pop(); - } else { - this.errstr = 'SCRIPT_ERR_CHECKSIGVERIFY'; - return false; - } - } - } - break; - - case Opcode.OP_CHECKMULTISIG: - case Opcode.OP_CHECKMULTISIGVERIFY: - { - // ([sig ...] num_of_signatures [pubkey ...] num_of_pubkeys -- bool) - - var i = 1; - if (this.stack.length < i) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - - var nKeysCount = BN.fromScriptNumBuffer(this.stack[this.stack.length - i], fRequireMinimal).toNumber(); - if (nKeysCount < 0 || nKeysCount > 20) { - this.errstr = 'SCRIPT_ERR_PUBKEY_COUNT'; - return false; - } - this.nOpCount += nKeysCount; - if (this.nOpCount > 201) { - this.errstr = 'SCRIPT_ERR_OP_COUNT'; - return false; - } - // int ikey = ++i; - var ikey = ++i; - i += nKeysCount; - if (this.stack.length < i) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - - var nSigsCount = BN.fromScriptNumBuffer(this.stack[this.stack.length - i], fRequireMinimal).toNumber(); - if (nSigsCount < 0 || nSigsCount > nKeysCount) { - this.errstr = 'SCRIPT_ERR_SIG_COUNT'; - return false; - } - // int isig = ++i; - var isig = ++i; - i += nSigsCount; - if (this.stack.length < i) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - - // Subset of script starting at the most recent codeseparator - subscript = new Script().set({ - chunks: this.script.chunks.slice(this.pbegincodehash) - }); - - // Drop the signatures, since there's no way for a signature to sign itself - for (var k = 0; k < nSigsCount; k++) { - bufSig = this.stack[this.stack.length - isig - k]; - subscript.findAndDelete(new Script().add(bufSig)); - } - - fSuccess = true; - while (fSuccess && nSigsCount > 0) { - // valtype& vchSig = stacktop(-isig); - bufSig = this.stack[this.stack.length - isig]; - // valtype& vchPubKey = stacktop(-ikey); - bufPubkey = this.stack[this.stack.length - ikey]; - - if (!this.checkSignatureEncoding(bufSig) || !this.checkPubkeyEncoding(bufPubkey)) { - return false; - } - - var fOk; - try { - sig = Signature.fromTxFormat(bufSig); - pubkey = PublicKey.fromBuffer(bufPubkey, false); - fOk = this.tx.verifySignature(sig, pubkey, this.nin, subscript); - } catch (e) { - //invalid sig or pubkey - fOk = false; - } - - if (fOk) { - isig++; - nSigsCount--; - } - ikey++; - nKeysCount--; - - // If there are more signatures left than keys left, - // then too many signatures have failed - if (nSigsCount > nKeysCount) { - fSuccess = false; - } - } - - // Clean up stack of actual arguments - while (i-- > 1) { - this.stack.pop(); - } - - // A bug causes CHECKMULTISIG to consume one extra argument - // whose contents were not checked in any way. - // - // Unfortunately this is a potential source of mutability, - // so optionally verify it is exactly equal to zero prior - // to removing it from the stack. - if (this.stack.length < 1) { - this.errstr = 'SCRIPT_ERR_INVALID_STACK_OPERATION'; - return false; - } - if ((this.flags & Interpreter.SCRIPT_VERIFY_NULLDUMMY) && this.stack[this.stack.length - 1].length) { - this.errstr = 'SCRIPT_ERR_SIG_NULLDUMMY'; - return false; - } - this.stack.pop(); - - this.stack.push(fSuccess ? Interpreter.true : Interpreter.false); - - if (opcodenum === Opcode.OP_CHECKMULTISIGVERIFY) { - if (fSuccess) { - this.stack.pop(); - } else { - this.errstr = 'SCRIPT_ERR_CHECKMULTISIGVERIFY'; - return false; - } - } - } - break; - - default: - this.errstr = 'SCRIPT_ERR_BAD_OPCODE'; - return false; - } - } - - return true; -}; - - -}).call(this,require("buffer").Buffer) -},{"../crypto/bn":34,"../crypto/hash":36,"../crypto/signature":39,"../opcode":51,"../publickey":53,"../transaction":57,"./script":56,"buffer":209,"lodash":95}],56:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - - -var Address = require('../address'); -var BufferReader = require('../encoding/bufferreader'); -var BufferWriter = require('../encoding/bufferwriter'); -var Hash = require('../crypto/hash'); -var Opcode = require('../opcode'); -var PublicKey = require('../publickey'); -var Signature = require('../crypto/signature'); -var Networks = require('../networks'); - -var $ = require('../util/preconditions'); -var _ = require('lodash'); -var errors = require('../errors'); -var buffer = require('buffer'); -var BufferUtil = require('../util/buffer'); -var JSUtil = require('../util/js'); - -/** - * A bitcoin transaction script. Each transaction's inputs and outputs - * has a script that is evaluated to validate it's spending. - * - * See https://en.bitcoin.it/wiki/Script - * - * @constructor - * @param {Object|string|Buffer} [from] optional data to populate script - */ -var Script = function Script(from) { - if (!(this instanceof Script)) { - return new Script(from); - } - - this.chunks = []; - - if (BufferUtil.isBuffer(from)) { - return Script.fromBuffer(from); - } else if (from instanceof Address) { - return Script.fromAddress(from); - } else if (from instanceof Script) { - return Script.fromBuffer(from.toBuffer()); - } else if (typeof from === 'string') { - return Script.fromString(from); - } else if (typeof from !== 'undefined') { - this.set(from); - } -}; - -Script.prototype.set = function(obj) { - this.chunks = obj.chunks || this.chunks; - return this; -}; - -Script.fromBuffer = function(buffer) { - var script = new Script(); - script.chunks = []; - - var br = new BufferReader(buffer); - while (!br.finished()) { - var opcodenum = br.readUInt8(); - - var len, buf; - if (opcodenum > 0 && opcodenum < Opcode.OP_PUSHDATA1) { - len = opcodenum; - script.chunks.push({ - buf: br.read(len), - len: len, - opcodenum: opcodenum - }); - } else if (opcodenum === Opcode.OP_PUSHDATA1) { - len = br.readUInt8(); - buf = br.read(len); - script.chunks.push({ - buf: buf, - len: len, - opcodenum: opcodenum - }); - } else if (opcodenum === Opcode.OP_PUSHDATA2) { - len = br.readUInt16LE(); - buf = br.read(len); - script.chunks.push({ - buf: buf, - len: len, - opcodenum: opcodenum - }); - } else if (opcodenum === Opcode.OP_PUSHDATA4) { - len = br.readUInt32LE(); - buf = br.read(len); - script.chunks.push({ - buf: buf, - len: len, - opcodenum: opcodenum - }); - } else { - script.chunks.push({ - opcodenum: opcodenum - }); - } - } - - return script; -}; - -Script.prototype.toBuffer = function() { - var bw = new BufferWriter(); - - for (var i = 0; i < this.chunks.length; i++) { - var chunk = this.chunks[i]; - var opcodenum = chunk.opcodenum; - bw.writeUInt8(chunk.opcodenum); - if (chunk.buf) { - if (opcodenum < Opcode.OP_PUSHDATA1) { - bw.write(chunk.buf); - } else if (opcodenum === Opcode.OP_PUSHDATA1) { - bw.writeUInt8(chunk.len); - bw.write(chunk.buf); - } else if (opcodenum === Opcode.OP_PUSHDATA2) { - bw.writeUInt16LE(chunk.len); - bw.write(chunk.buf); - } else if (opcodenum === Opcode.OP_PUSHDATA4) { - bw.writeUInt32LE(chunk.len); - bw.write(chunk.buf); - } - } - } - - return bw.concat(); -}; - -Script.fromString = function(str) { - if (JSUtil.isHexa(str) || str.length === 0) { - return new Script(new buffer.Buffer(str, 'hex')); - } - var script = new Script(); - script.chunks = []; - - var tokens = str.split(' '); - var i = 0; - while (i < tokens.length) { - var token = tokens[i]; - var opcode = Opcode(token); - var opcodenum = opcode.toNumber(); - - if (_.isUndefined(opcodenum)) { - opcodenum = parseInt(token); - if (opcodenum > 0 && opcodenum < Opcode.OP_PUSHDATA1) { - script.chunks.push({ - buf: new Buffer(tokens[i + 1].slice(2), 'hex'), - len: opcodenum, - opcodenum: opcodenum - }); - i = i + 2; - } else { - throw new Error('Invalid script: ' + JSON.stringify(str)); - } - } else if (opcodenum === Opcode.OP_PUSHDATA1 || - opcodenum === Opcode.OP_PUSHDATA2 || - opcodenum === Opcode.OP_PUSHDATA4) { - if (tokens[i + 2].slice(0, 2) !== '0x') { - throw new Error('Pushdata data must start with 0x'); - } - script.chunks.push({ - buf: new Buffer(tokens[i + 2].slice(2), 'hex'), - len: parseInt(tokens[i + 1]), - opcodenum: opcodenum - }); - i = i + 3; - } else { - script.chunks.push({ - opcodenum: opcodenum - }); - i = i + 1; - } - } - return script; -}; - -Script.prototype.toString = function() { - var str = ''; - for (var i = 0; i < this.chunks.length; i++) { - var chunk = this.chunks[i]; - var opcodenum = chunk.opcodenum; - if (!chunk.buf) { - if (typeof Opcode.reverseMap[opcodenum] !== 'undefined') { - str = str + ' ' + Opcode(opcodenum).toString(); - } else { - var numstr = opcodenum.toString(16); - if (numstr.length % 2 !== 0) { - numstr = '0' + numstr; - } - str = str + ' ' + '0x' + numstr; - } - } else { - if (opcodenum === Opcode.OP_PUSHDATA1 || - opcodenum === Opcode.OP_PUSHDATA2 || - opcodenum === Opcode.OP_PUSHDATA4) { - str = str + ' ' + Opcode(opcodenum).toString(); - } - str = str + ' ' + chunk.len; - if (chunk.len > 0) { - str = str + ' ' + '0x' + chunk.buf.toString('hex'); - } - } - } - - return str.substr(1); -}; - -Script.prototype.toHex = function() { - return this.toBuffer().toString('hex'); -}; - -Script.prototype.inspect = function() { - return ''; -}; - -// script classification methods - -/** - * @returns {boolean} if this is a pay to pubkey hash output script - */ -Script.prototype.isPublicKeyHashOut = function() { - return !!(this.chunks.length === 5 && - this.chunks[0].opcodenum === Opcode.OP_DUP && - this.chunks[1].opcodenum === Opcode.OP_HASH160 && - this.chunks[2].buf && - this.chunks[3].opcodenum === Opcode.OP_EQUALVERIFY && - this.chunks[4].opcodenum === Opcode.OP_CHECKSIG); -}; - -/** - * @returns {boolean} if this is a pay to public key hash input script - */ -Script.prototype.isPublicKeyHashIn = function() { - return this.chunks.length === 2 && - this.chunks[0].buf && - this.chunks[0].buf.length >= 0x47 && - this.chunks[0].buf.length <= 0x49 && - PublicKey.isValid(this.chunks[1].buf); -}; - -Script.prototype.getPublicKeyHash = function() { - $.checkState(this.isPublicKeyHashOut(), 'Can\'t retrieve PublicKeyHash from a non-PKH output'); - return this.chunks[2].buf; -}; - -/** - * @returns {boolean} if this is a public key output script - */ -Script.prototype.isPublicKeyOut = function() { - return this.chunks.length === 2 && - BufferUtil.isBuffer(this.chunks[0].buf) && - PublicKey.isValid(this.chunks[0].buf) && - this.chunks[1].opcodenum === Opcode.OP_CHECKSIG; -}; - -/** - * @returns {boolean} if this is a pay to public key input script - */ -Script.prototype.isPublicKeyIn = function() { - return this.chunks.length === 1 && - BufferUtil.isBuffer(this.chunks[0].buf) && - this.chunks[0].buf.length === 0x47; -}; - - -/** - * @returns {boolean} if this is a p2sh output script - */ -Script.prototype.isScriptHashOut = function() { - var buf = this.toBuffer(); - return (buf.length === 23 && - buf[0] === Opcode.OP_HASH160 && - buf[1] === 0x14 && - buf[buf.length - 1] === Opcode.OP_EQUAL); -}; - -/** - * @returns {boolean} if this is a p2sh input script - * Note that these are frequently indistinguishable from pubkeyhashin - */ -Script.prototype.isScriptHashIn = function() { - if (this.chunks.length === 0) { - return false; - } - var chunk = this.chunks[this.chunks.length - 1]; - if (!chunk) { - return false; - } - var scriptBuf = chunk.buf; - if (!scriptBuf) { - return false; - } - var redeemScript = new Script(scriptBuf); - var type = redeemScript.classify(); - return type !== Script.types.UNKNOWN; -}; - -/** - * @returns {boolean} if this is a mutlsig output script - */ -Script.prototype.isMultisigOut = function() { - return (this.chunks.length > 3 && - Opcode.isSmallIntOp(this.chunks[0].opcodenum) && - this.chunks.slice(1, this.chunks.length - 2).every(function(obj) { - return obj.buf && BufferUtil.isBuffer(obj.buf); - }) && - Opcode.isSmallIntOp(this.chunks[this.chunks.length - 2].opcodenum) && - this.chunks[this.chunks.length - 1].opcodenum === Opcode.OP_CHECKMULTISIG); -}; - - -/** - * @returns {boolean} if this is a multisig input script - */ -Script.prototype.isMultisigIn = function() { - return this.chunks.length >= 2 && - this.chunks[0].opcodenum === 0 && - this.chunks.slice(1, this.chunks.length).every(function(obj) { - return obj.buf && - BufferUtil.isBuffer(obj.buf) && - obj.buf.length === 0x47; - }); -}; - -/** - * @returns {boolean} true if this is a valid standard OP_RETURN output - */ -Script.prototype.isDataOut = function() { - return this.chunks.length >= 1 && - this.chunks[0].opcodenum === Opcode.OP_RETURN && - (this.chunks.length === 1 || - (this.chunks.length === 2 && - this.chunks[1].buf && - this.chunks[1].buf.length <= Script.OP_RETURN_STANDARD_SIZE && - this.chunks[1].length === this.chunks.len)); -}; - -/** - * Retrieve the associated data for this script. - * In the case of a pay to public key hash or P2SH, return the hash. - * In the case of a standard OP_RETURN, return the data - * @returns {Buffer} - */ -Script.prototype.getData = function() { - if (this.isDataOut() || this.isScriptHashOut()) { - return new Buffer(this.chunks[1].buf); - } - if (this.isPublicKeyHashOut()) { - return new Buffer(this.chunks[2].buf); - } - throw new Error('Unrecognized script type to get data from'); -}; - -/** - * @returns {boolean} if the script is only composed of data pushing - * opcodes or small int opcodes (OP_0, OP_1, ..., OP_16) - */ -Script.prototype.isPushOnly = function() { - return _.every(this.chunks, function(chunk) { - return chunk.opcodenum <= Opcode.OP_16; - }); -}; - - -Script.types = {}; -Script.types.UNKNOWN = 'Unknown'; -Script.types.PUBKEY_OUT = 'Pay to public key'; -Script.types.PUBKEY_IN = 'Spend from public key'; -Script.types.PUBKEYHASH_OUT = 'Pay to public key hash'; -Script.types.PUBKEYHASH_IN = 'Spend from public key hash'; -Script.types.SCRIPTHASH_OUT = 'Pay to script hash'; -Script.types.SCRIPTHASH_IN = 'Spend from script hash'; -Script.types.MULTISIG_OUT = 'Pay to multisig'; -Script.types.MULTISIG_IN = 'Spend from multisig'; -Script.types.DATA_OUT = 'Data push'; - -Script.OP_RETURN_STANDARD_SIZE = 80; - -Script.identifiers = {}; -Script.identifiers.PUBKEY_OUT = Script.prototype.isPublicKeyOut; -Script.identifiers.PUBKEY_IN = Script.prototype.isPublicKeyIn; -Script.identifiers.PUBKEYHASH_OUT = Script.prototype.isPublicKeyHashOut; -Script.identifiers.PUBKEYHASH_IN = Script.prototype.isPublicKeyHashIn; -Script.identifiers.MULTISIG_OUT = Script.prototype.isMultisigOut; -Script.identifiers.MULTISIG_IN = Script.prototype.isMultisigIn; -Script.identifiers.SCRIPTHASH_OUT = Script.prototype.isScriptHashOut; -Script.identifiers.SCRIPTHASH_IN = Script.prototype.isScriptHashIn; -Script.identifiers.DATA_OUT = Script.prototype.isDataOut; - -/** - * @returns {object} The Script type if it is a known form, - * or Script.UNKNOWN if it isn't - */ -Script.prototype.classify = function() { - for (var type in Script.identifiers) { - if (Script.identifiers[type].bind(this)()) { - return Script.types[type]; - } - } - return Script.types.UNKNOWN; -}; - - -/** - * @returns {boolean} if script is one of the known types - */ -Script.prototype.isStandard = function() { - // TODO: Add BIP62 compliance - return this.classify() !== Script.types.UNKNOWN; -}; - - -// Script construction methods - -/** - * Adds a script element at the start of the script. - * @param {*} obj a string, number, Opcode, Bufer, or object to add - * @returns {Script} this script instance - */ -Script.prototype.prepend = function(obj) { - this._addByType(obj, true); - return this; -}; - -/** - * Compares a script with another script - */ -Script.prototype.equals = function(script) { - $.checkState(script instanceof Script, 'Must provide another script'); - if (this.chunks.length !== script.chunks.length) { - return false; - } - var i; - for (i = 0; i < this.chunks.length; i++) { - if (BufferUtil.isBuffer(this.chunks[i]) && !BufferUtil.isBuffer(script.chunks[i])) { - return false; - } else if (this.chunks[i] instanceof Opcode && !(script.chunks[i] instanceof Opcode)) { - return false; - } - if (BufferUtil.isBuffer(this.chunks[i]) && !BufferUtil.equals(this.chunks[i], script.chunks[i])) { - return false; - } else if (this.chunks[i].num !== script.chunks[i].num) { - return false; - } - } - return true; -}; - -/** - * Adds a script element to the end of the script. - * - * @param {*} obj a string, number, Opcode, Bufer, or object to add - * @returns {Script} this script instance - * - */ -Script.prototype.add = function(obj) { - this._addByType(obj, false); - return this; -}; - -Script.prototype._addByType = function(obj, prepend) { - if (typeof obj === 'string') { - this._addOpcode(obj, prepend); - } else if (typeof obj === 'number') { - this._addOpcode(obj, prepend); - } else if (obj instanceof Opcode) { - this._addOpcode(obj, prepend); - } else if (BufferUtil.isBuffer(obj)) { - this._addBuffer(obj, prepend); - } else if (typeof obj === 'object') { - this._insertAtPosition(obj, prepend); - } else if (obj instanceof Script) { - this.chunks = this.chunks.concat(obj.chunks); - } else { - throw new Error('Invalid script chunk'); - } -}; - -Script.prototype._insertAtPosition = function(op, prepend) { - if (prepend) { - this.chunks.unshift(op); - } else { - this.chunks.push(op); - } -}; - -Script.prototype._addOpcode = function(opcode, prepend) { - var op; - if (typeof opcode === 'number') { - op = opcode; - } else if (opcode instanceof Opcode) { - op = opcode.toNumber(); - } else { - op = Opcode(opcode).toNumber(); - } - this._insertAtPosition({ - opcodenum: op - }, prepend); - return this; -}; - -Script.prototype._addBuffer = function(buf, prepend) { - var opcodenum; - var len = buf.length; - if (len >= 0 && len < Opcode.OP_PUSHDATA1) { - opcodenum = len; - } else if (len < Math.pow(2, 8)) { - opcodenum = Opcode.OP_PUSHDATA1; - } else if (len < Math.pow(2, 16)) { - opcodenum = Opcode.OP_PUSHDATA2; - } else if (len < Math.pow(2, 32)) { - opcodenum = Opcode.OP_PUSHDATA4; - } else { - throw new Error('You can\'t push that much data'); - } - this._insertAtPosition({ - buf: buf, - len: len, - opcodenum: opcodenum - }, prepend); - return this; -}; - -Script.prototype.removeCodeseparators = function() { - var chunks = []; - for (var i = 0; i < this.chunks.length; i++) { - if (this.chunks[i].opcodenum !== Opcode.OP_CODESEPARATOR) { - chunks.push(this.chunks[i]); - } - } - this.chunks = chunks; - return this; -}; - -// high level script builder methods - -/** - * @returns {Script} a new Multisig output script for given public keys, - * requiring m of those public keys to spend - * @param {PublicKey[]} publicKeys - list of all public keys controlling the output - * @param {number} threshold - amount of required signatures to spend the output - * @param {Object} [opts] - Several options: - * - noSorting: defaults to false, if true, don't sort the given - * public keys before creating the script - */ -Script.buildMultisigOut = function(publicKeys, threshold, opts) { - $.checkArgument(threshold <= publicKeys.length, - 'Number of required signatures must be less than or equal to the number of public keys'); - opts = opts || {}; - var script = new Script(); - script.add(Opcode.smallInt(threshold)); - publicKeys = _.map(publicKeys, PublicKey); - var sorted = publicKeys; - if (!opts.noSorting) { - sorted = _.sortBy(publicKeys, function(publicKey) { - return publicKey.toString('hex'); - }); - } - for (var i = 0; i < sorted.length; i++) { - var publicKey = sorted[i]; - script.add(publicKey.toBuffer()); - } - script.add(Opcode.smallInt(publicKeys.length)); - script.add(Opcode.OP_CHECKMULTISIG); - return script; -}; - -/** - * A new P2SH Multisig input script for the given public keys, requiring m of those public keys to spend - * - * @param {PublicKey[]} pubkeys list of all public keys controlling the output - * @param {number} threshold amount of required signatures to spend the output - * @param {Array} signatures signatures to append to the script - * @param {Object=} opts - * @param {boolean=} opts.noSorting don't sort the given public keys before creating the script (false by default) - * @param {Script=} opts.cachedMultisig don't recalculate the redeemScript - * - * @returns {Script} - */ -Script.buildP2SHMultisigIn = function(pubkeys, threshold, signatures, opts) { - $.checkArgument(_.isArray(pubkeys)); - $.checkArgument(_.isNumber(threshold)); - $.checkArgument(_.isArray(signatures)); - opts = opts || {}; - var s = new Script(); - s.add(Opcode.OP_0); - _.each(signatures, function(signature) { - s.add(signature); - }); - s.add((opts.cachedMultisig || Script.buildMultisigOut(pubkeys, threshold, opts)).toBuffer()); - return s; -}; - -/** - * @returns {Script} a new pay to public key hash output for the given - * address or public key - * @param {(Address|PublicKey)} to - destination address or public key - */ -Script.buildPublicKeyHashOut = function(to) { - $.checkArgument(!_.isUndefined(to)); - $.checkArgument(to instanceof PublicKey || to instanceof Address || _.isString(to)); - if (to instanceof PublicKey) { - to = to.toAddress(); - } else if (_.isString(to)) { - to = new Address(to); - } - var s = new Script(); - s.add(Opcode.OP_DUP) - .add(Opcode.OP_HASH160) - .add(to.hashBuffer) - .add(Opcode.OP_EQUALVERIFY) - .add(Opcode.OP_CHECKSIG); - s._network = to.network; - return s; -}; - -/** - * @returns {Script} a new pay to public key output for the given - * public key - */ -Script.buildPublicKeyOut = function(pubkey) { - $.checkArgument(pubkey instanceof PublicKey); - var s = new Script(); - s.add(pubkey.toBuffer()) - .add(Opcode.OP_CHECKSIG); - return s; -}; - -/** - * @returns {Script} a new OP_RETURN script with data - * @param {(string|Buffer)} to - the data to embed in the output - */ -Script.buildDataOut = function(data) { - $.checkArgument(_.isUndefined(data) || _.isString(data) || BufferUtil.isBuffer(data)); - if (typeof data === 'string') { - data = new Buffer(data); - } - var s = new Script(); - s.add(Opcode.OP_RETURN); - if (!_.isUndefined(data)) { - s.add(data); - } - return s; -}; - -/** - * @param {Script|Address} script - the redeemScript for the new p2sh output. - * It can also be a p2sh address - * @returns {Script} new pay to script hash script for given script - */ -Script.buildScriptHashOut = function(script) { - $.checkArgument(script instanceof Script || - (script instanceof Address && script.isPayToScriptHash())); - var s = new Script(); - s.add(Opcode.OP_HASH160) - .add(script instanceof Address ? script.hashBuffer : Hash.sha256ripemd160(script.toBuffer())) - .add(Opcode.OP_EQUAL); - - s._network = script._network || script.network; - return s; -}; - -/** - * Builds a scriptSig (a script for an input) that signs a public key hash - * output script. - * - * @param {Buffer|string|PublicKey} publicKey - * @param {Signature|Buffer} signature - a Signature object, or the signature in DER cannonical encoding - * @param {number=} sigtype - the type of the signature (defaults to SIGHASH_ALL) - */ -Script.buildPublicKeyHashIn = function(publicKey, signature, sigtype) { - $.checkArgument(signature instanceof Signature || BufferUtil.isBuffer(signature)); - $.checkArgument(_.isUndefined(sigtype) || _.isNumber(sigtype)); - if (signature instanceof Signature) { - signature = signature.toBuffer(); - } - var script = new Script() - .add(BufferUtil.concat([ - signature, - BufferUtil.integerAsSingleByteBuffer(sigtype || Signature.SIGHASH_ALL) - ])) - .add(new PublicKey(publicKey).toBuffer()); - return script; -}; - -/** - * @returns {Script} an empty script - */ -Script.empty = function() { - return new Script(); -}; - -/** - * @returns {Script} a new pay to script hash script that pays to this script - */ -Script.prototype.toScriptHashOut = function() { - return Script.buildScriptHashOut(this); -}; - -/** - * @return {Script} a script built from the address - */ -Script.fromAddress = function(address) { - address = Address(address); - if (address.isPayToScriptHash()) { - return Script.buildScriptHashOut(address); - } else if (address.isPayToPublicKeyHash()) { - return Script.buildPublicKeyHashOut(address); - } - throw new errors.Script.UnrecognizedAddress(address); -}; - -/** - * @param {Network} [network] - * @return {Address} the associated address for this script - */ -Script.prototype.toAddress = function(network) { - network = Networks.get(network) || this._network || Networks.defaultNetwork; - if (this.isPublicKeyHashOut() || this.isScriptHashOut()) { - return new Address(this, network); - } - throw new Error('The script type needs to be PayToPublicKeyHash or PayToScriptHash'); -}; - -/** - * @return {Script} - */ -Script.prototype.toScriptHashOut = function() { - return Script.buildScriptHashOut(this); -}; - -/** - * Analagous to bitcoind's FindAndDelete. Find and delete equivalent chunks, - * typically used with push data chunks. Note that this will find and delete - * not just the same data, but the same data with the same push data op as - * produced by default. i.e., if a pushdata in a tx does not use the minimal - * pushdata op, then when you try to remove the data it is pushing, it will not - * be removed, because they do not use the same pushdata op. - */ -Script.prototype.findAndDelete = function(script) { - var buf = script.toBuffer(); - var hex = buf.toString('hex'); - for (var i = 0; i < this.chunks.length; i++) { - var script2 = Script({ - chunks: [this.chunks[i]] - }); - var buf2 = script2.toBuffer(); - var hex2 = buf2.toString('hex'); - if (hex === hex2) { - this.chunks.splice(i, 1); - } - } - return this; -}; - -/** - * Comes from bitcoind's script interpreter CheckMinimalPush function - * @returns {boolean} if the chunk {i} is the smallest way to push that particular data. - */ -Script.prototype.checkMinimalPush = function(i) { - var chunk = this.chunks[i]; - var buf = chunk.buf; - var opcodenum = chunk.opcodenum; - if (!buf) { - return true; - } - if (buf.length === 0) { - // Could have used OP_0. - return opcodenum === Opcode.OP_0; - } else if (buf.length === 1 && buf[0] >= 1 && buf[0] <= 16) { - // Could have used OP_1 .. OP_16. - return opcodenum === Opcode.OP_1 + (buf[0] - 1); - } else if (buf.length === 1 && buf[0] === 0x81) { - // Could have used OP_1NEGATE - return opcodenum === Opcode.OP_1NEGATE; - } else if (buf.length <= 75) { - // Could have used a direct push (opcode indicating number of bytes pushed + those bytes). - return opcodenum === buf.length; - } else if (buf.length <= 255) { - // Could have used OP_PUSHDATA. - return opcodenum === Opcode.OP_PUSHDATA1; - } else if (buf.length <= 65535) { - // Could have used OP_PUSHDATA2. - return opcodenum === Opcode.OP_PUSHDATA2; - } - return true; -}; - -module.exports = Script; - -}).call(this,require("buffer").Buffer) -},{"../address":31,"../crypto/hash":36,"../crypto/signature":39,"../encoding/bufferreader":42,"../encoding/bufferwriter":43,"../errors":45,"../networks":50,"../opcode":51,"../publickey":53,"../util/buffer":69,"../util/js":70,"../util/preconditions":71,"buffer":209,"lodash":95}],57:[function(require,module,exports){ -module.exports = require('./transaction'); - -module.exports.Input = require('./input'); -module.exports.Output = require('./output'); -module.exports.UnspentOutput = require('./unspentoutput'); -module.exports.Signature = require('./signature'); - -},{"./input":58,"./output":62,"./signature":64,"./transaction":65,"./unspentoutput":66}],58:[function(require,module,exports){ -module.exports = require('./input'); - -module.exports.PublicKeyHash = require('./publickeyhash'); -module.exports.MultiSigScriptHash = require('./multisigscripthash.js'); - -},{"./input":59,"./multisigscripthash.js":60,"./publickeyhash":61}],59:[function(require,module,exports){ -'use strict'; - -var _ = require('lodash'); -var errors = require('../../errors'); -var BufferWriter = require('../../encoding/bufferwriter'); -var buffer = require('buffer'); -var BufferUtil = require('../../util/buffer'); -var JSUtil = require('../../util/js'); -var Script = require('../../script'); -var Sighash = require('../sighash'); -var Output = require('../output'); - -function Input(params) { - if (!(this instanceof Input)) { - return new Input(params); - } - if (params) { - return this._fromObject(params); - } -} - -Object.defineProperty(Input.prototype, 'script', { - configurable: false, - writeable: false, - enumerable: true, - get: function() { - if (!this._script) { - this._script = new Script(this._scriptBuffer); - } - return this._script; - } -}); - -Input.prototype._fromObject = function(params) { - if (_.isString(params.prevTxId) && JSUtil.isHexa(params.prevTxId)) { - params.prevTxId = new buffer.Buffer(params.prevTxId, 'hex'); - } - this.output = params.output ? - (params.output instanceof Output ? params.output : new Output(params.output)) : undefined; - this.prevTxId = params.prevTxId; - this.outputIndex = params.outputIndex; - this.sequenceNumber = params.sequenceNumber; - if (_.isUndefined(params.script) && _.isUndefined(params.scriptBuffer)) { - throw new errors.Transaction.Input.MissingScript(); - } - this.setScript(params.scriptBuffer || params.script); - return this; -}; - -Input.prototype.toObject = function toObject() { - return { - prevTxId: this.prevTxId.toString('hex'), - outputIndex: this.outputIndex, - sequenceNumber: this.sequenceNumber, - script: this.script.toString(), - output: this.output ? this.output.toObject() : undefined - }; -}; - -Input.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -Input.fromJSON = function(json) { - if (JSUtil.isValidJSON(json)) { - json = JSON.parse(json); - } - return new Input({ - output: json.output ? new Output(json.output) : undefined, - prevTxId: json.prevTxId || json.txidbuf, - outputIndex: _.isUndefined(json.outputIndex) ? json.txoutnum : json.outputIndex, - sequenceNumber: json.sequenceNumber || json.seqnum, - scriptBuffer: new Script(json.script, 'hex') - }); -}; - -Input.fromBufferReader = function(br) { - var input = new Input(); - input.prevTxId = br.readReverse(32); - input.outputIndex = br.readUInt32LE(); - input._scriptBuffer = br.readVarLengthBuffer(); - input.sequenceNumber = br.readUInt32LE(); - return input; -}; - -Input.prototype.toBufferWriter = function(writer) { - if (!writer) { - writer = new BufferWriter(); - } - writer.writeReverse(this.prevTxId); - writer.writeUInt32LE(this.outputIndex); - var script = this._scriptBuffer; - writer.writeVarintNum(script.length); - writer.write(script); - writer.writeUInt32LE(this.sequenceNumber); - return writer; -}; - -Input.prototype.setScript = function(script) { - if (script instanceof Script) { - this._script = script; - this._scriptBuffer = script.toBuffer(); - } else if (_.isString(script)) { - this._script = new Script(script); - this._scriptBuffer = this._script.toBuffer(); - } else if (BufferUtil.isBuffer(script)) { - this._script = null; - this._scriptBuffer = new buffer.Buffer(script); - } else { - throw new TypeError('Invalid Argument'); - } - return this; -}; - -/** - * Retrieve signatures for the provided PrivateKey. - * - * @param {Transaction} transaction - the transaction to be signed - * @param {PrivateKey} privateKey - the private key to use when signing - * @param {number} inputIndex - the index of this input in the provided transaction - * @param {number} sigType - defaults to Signature.SIGHASH_ALL - * @param {Buffer} addressHash - if provided, don't calculate the hash of the - * public key associated with the private key provided - * @abstract - */ -Input.prototype.getSignatures = function() { - throw new errors.AbstractMethodInvoked( - 'Trying to sign unsupported output type (only P2PKH and P2SH multisig inputs are supported)' + - ' for input: ' + this.toJSON() - ); -}; - -Input.prototype.isFullySigned = function() { - throw new errors.AbstractMethodInvoked('Input#isFullySigned'); -}; - -Input.prototype.addSignature = function() { - throw new errors.AbstractMethodInvoked('Input#addSignature'); -}; - -Input.prototype.clearSignatures = function() { - throw new errors.AbstractMethodInvoked('Input#clearSignatures'); -}; - -Input.prototype.isValidSignature = function(transaction, signature) { - // FIXME: Refactor signature so this is not necessary - signature.signature.nhashtype = signature.sigtype; - return Sighash.verify( - transaction, - signature.signature, - signature.publicKey, - signature.inputIndex, - this.output.script - ); -}; - -/** - * @returns true if this is a coinbase input (represents no input) - */ -Input.prototype.isNull = function() { - return this.prevTxId.toString('hex') === '0000000000000000000000000000000000000000000000000000000000000000' && - this.outputIndex === 0xffffffff; -}; - -Input.prototype._estimateSize = function() { - var bufferWriter = new BufferWriter(); - this.toBufferWriter(bufferWriter); - return bufferWriter.toBuffer().length; -}; - -module.exports = Input; - -},{"../../encoding/bufferwriter":43,"../../errors":45,"../../script":54,"../../util/buffer":69,"../../util/js":70,"../output":62,"../sighash":63,"buffer":209,"lodash":95}],60:[function(require,module,exports){ -'use strict'; - -var _ = require('lodash'); -var inherits = require('inherits'); -var Input = require('./input'); -var Output = require('../output'); -var $ = require('../../util/preconditions'); - -var Script = require('../../script'); -var Signature = require('../../crypto/signature'); -var Sighash = require('../sighash'); -var PublicKey = require('../../publickey'); -var BufferUtil = require('../../util/buffer'); -var TransactionSignature = require('../signature'); - -/** - * @constructor - */ -function MultiSigScriptHashInput(input, pubkeys, threshold, signatures) { - Input.apply(this, arguments); - var self = this; - pubkeys = pubkeys || input.publicKeys; - threshold = threshold || input.threshold; - signatures = signatures || input.signatures; - this.publicKeys = _.sortBy(pubkeys, function(publicKey) { return publicKey.toString('hex'); }); - this.redeemScript = Script.buildMultisigOut(this.publicKeys, threshold); - $.checkState(Script.buildScriptHashOut(this.redeemScript).equals(this.output.script), - 'Provided public keys don\'t hash to the provided output'); - this.publicKeyIndex = {}; - _.each(this.publicKeys, function(publicKey, index) { - self.publicKeyIndex[publicKey.toString()] = index; - }); - this.threshold = threshold; - // Empty array of signatures - this.signatures = signatures ? this._deserializeSignatures(signatures) : new Array(this.publicKeys.length); -} -inherits(MultiSigScriptHashInput, Input); - -MultiSigScriptHashInput.prototype.toObject = function() { - var obj = Input.prototype.toObject.apply(this, arguments); - obj.threshold = this.threshold; - obj.publicKeys = _.map(this.publicKeys, function(publicKey) { return publicKey.toString(); }); - obj.signatures = this._serializeSignatures(); - return obj; -}; - -MultiSigScriptHashInput.prototype._deserializeSignatures = function(signatures) { - return _.map(signatures, function(signature) { - if (!signature) { - return undefined; - } - return new TransactionSignature(signature); - }); -}; - -MultiSigScriptHashInput.prototype._serializeSignatures = function() { - return _.map(this.signatures, function(signature) { - if (!signature) { - return undefined; - } - return signature.toObject(); - }); -}; - -MultiSigScriptHashInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype) { - $.checkState(this.output instanceof Output); - sigtype = sigtype || Signature.SIGHASH_ALL; - - var self = this; - var results = []; - _.each(this.publicKeys, function(publicKey) { - if (publicKey.toString() === privateKey.publicKey.toString()) { - results.push(new TransactionSignature({ - publicKey: privateKey.publicKey, - prevTxId: self.prevTxId, - outputIndex: self.outputIndex, - inputIndex: index, - signature: Sighash.sign(transaction, privateKey, sigtype, index, self.redeemScript), - sigtype: sigtype - })); - } - }); - return results; -}; - -MultiSigScriptHashInput.prototype.addSignature = function(transaction, signature) { - $.checkState(!this.isFullySigned(), 'All needed signatures have already been added'); - $.checkArgument(!_.isUndefined(this.publicKeyIndex[signature.publicKey.toString()]), - 'Signature has no matching public key'); - $.checkState(this.isValidSignature(transaction, signature)); - this.signatures[this.publicKeyIndex[signature.publicKey.toString()]] = signature; - this._updateScript(); - return this; -}; - -MultiSigScriptHashInput.prototype._updateScript = function() { - this.setScript(Script.buildP2SHMultisigIn( - this.publicKeys, - this.threshold, - this._createSignatures(), - { cachedMultisig: this.redeemScript } - )); - return this; -}; - -MultiSigScriptHashInput.prototype._createSignatures = function() { - return _.map( - _.filter(this.signatures, function(signature) { return !_.isUndefined(signature); }), - function(signature) { - return BufferUtil.concat([ - signature.signature.toDER(), - BufferUtil.integerAsSingleByteBuffer(signature.sigtype) - ]); - } - ); -}; - -MultiSigScriptHashInput.prototype.clearSignatures = function() { - this.signatures = new Array(this.publicKeys.length); - this._updateScript(); -}; - -MultiSigScriptHashInput.prototype.isFullySigned = function() { - return this.countSignatures() === this.threshold; -}; - -MultiSigScriptHashInput.prototype.countMissingSignatures = function() { - return this.threshold - this.countSignatures(); -}; - -MultiSigScriptHashInput.prototype.countSignatures = function() { - return _.reduce(this.signatures, function(sum, signature) { - return sum + (!!signature); - }, 0); -}; - -MultiSigScriptHashInput.prototype.publicKeysWithoutSignature = function() { - var self = this; - return _.filter(this.publicKeys, function(publicKey) { - return !(self.signatures[self.publicKeyIndex[publicKey.toString()]]); - }); -}; - -MultiSigScriptHashInput.prototype.isValidSignature = function(transaction, signature) { - // FIXME: Refactor signature so this is not necessary - signature.signature.nhashtype = signature.sigtype; - return Sighash.verify( - transaction, - signature.signature, - signature.publicKey, - signature.inputIndex, - this.redeemScript - ); -}; - -MultiSigScriptHashInput.OPCODES_SIZE = 7; // serialized size (<=3) + 0 .. N .. M OP_CHECKMULTISIG -MultiSigScriptHashInput.SIGNATURE_SIZE = 74; // size (1) + DER (<=72) + sighash (1) -MultiSigScriptHashInput.PUBKEY_SIZE = 34; // size (1) + DER (<=33) - -MultiSigScriptHashInput.prototype._estimateSize = function() { - return MultiSigScriptHashInput.OPCODES_SIZE + - this.threshold * MultiSigScriptHashInput.SIGNATURE_SIZE + - this.publicKeys.length * MultiSigScriptHashInput.PUBKEY_SIZE; -}; - -module.exports = MultiSigScriptHashInput; - -},{"../../crypto/signature":39,"../../publickey":53,"../../script":54,"../../util/buffer":69,"../../util/preconditions":71,"../output":62,"../sighash":63,"../signature":64,"./input":59,"inherits":94,"lodash":95}],61:[function(require,module,exports){ -'use strict'; - -var inherits = require('inherits'); - -var $ = require('../../util/preconditions'); -var BufferUtil = require('../../util/buffer'); - -var Hash = require('../../crypto/hash'); -var Input = require('./input'); -var Output = require('../output'); -var Sighash = require('../sighash'); -var Script = require('../../script'); -var Signature = require('../../crypto/signature'); -var TransactionSignature = require('../signature'); - -/** - * Represents a special kind of input of PayToPublicKeyHash kind. - * @constructor - */ -function PublicKeyHashInput() { - Input.apply(this, arguments); -} -inherits(PublicKeyHashInput, Input); - -/* jshint maxparams: 5 */ -/** - * @param {Transaction} transaction - the transaction to be signed - * @param {PrivateKey} privateKey - the private key with which to sign the transaction - * @param {number} index - the index of the input in the transaction input vector - * @param {number=} sigtype - the type of signature, defaults to Signature.SIGHASH_ALL - * @param {Buffer=} hashData - the precalculated hash of the public key associated with the privateKey provided - * @return {Array} of objects that can be - */ -PublicKeyHashInput.prototype.getSignatures = function(transaction, privateKey, index, sigtype, hashData) { - $.checkState(this.output instanceof Output); - hashData = hashData || Hash.sha256ripemd160(privateKey.publicKey.toBuffer()); - sigtype = sigtype || Signature.SIGHASH_ALL; - - if (BufferUtil.equals(hashData, this.output.script.getPublicKeyHash())) { - return [new TransactionSignature({ - publicKey: privateKey.publicKey, - prevTxId: this.prevTxId, - outputIndex: this.outputIndex, - inputIndex: index, - signature: Sighash.sign(transaction, privateKey, sigtype, index, this.output.script), - sigtype: sigtype - })]; - } - return []; -}; -/* jshint maxparams: 3 */ - -/** - * Add the provided signature - * - * @param {Object} signature - * @param {PublicKey} signature.publicKey - * @param {Signature} signature.signature - * @param {number=} signature.sigtype - * @return {PublicKeyHashInput} this, for chaining - */ -PublicKeyHashInput.prototype.addSignature = function(transaction, signature) { - $.checkState(this.isValidSignature(transaction, signature), 'Signature is invalid'); - this.setScript(Script.buildPublicKeyHashIn( - signature.publicKey, - signature.signature.toDER(), - signature.sigtype - )); - return this; -}; - -/** - * Clear the input's signature - * @return {PublicKeyHashInput} this, for chaining - */ -PublicKeyHashInput.prototype.clearSignatures = function() { - this.setScript(Script.empty()); - return this; -}; - -/** - * Query whether the input is signed - * @return {boolean} - */ -PublicKeyHashInput.prototype.isFullySigned = function() { - return this.script.isPublicKeyHashIn(); -}; - -PublicKeyHashInput.SCRIPT_MAX_SIZE = 73 + 34; // sigsize (1 + 72) + pubkey (1 + 33) - -PublicKeyHashInput.prototype._estimateSize = function() { - return PublicKeyHashInput.SCRIPT_MAX_SIZE; -}; - -module.exports = PublicKeyHashInput; - -},{"../../crypto/hash":36,"../../crypto/signature":39,"../../script":54,"../../util/buffer":69,"../../util/preconditions":71,"../output":62,"../sighash":63,"../signature":64,"./input":59,"inherits":94}],62:[function(require,module,exports){ -'use strict'; - -var _ = require('lodash'); -var BN = require('../crypto/bn'); -var buffer = require('buffer'); -var bufferUtil = require('../util/buffer'); -var JSUtil = require('../util/js'); -var BufferWriter = require('../encoding/bufferwriter'); -var Script = require('../script'); - -function Output(params) { - if (!(this instanceof Output)) { - return new Output(params); - } - if (params) { - if (JSUtil.isValidJSON(params)) { - return Output.fromJSON(params); - } - return this._fromObject(params); - } -} - -Object.defineProperty(Output.prototype, 'script', { - configurable: false, - writeable: false, - enumerable: true, - get: function() { - if (!this._script) { - this._script = new Script(this._scriptBuffer); - } - return this._script; - } -}); - -Object.defineProperty(Output.prototype, 'satoshis', { - configurable: false, - writeable: true, - enumerable: true, - get: function() { - return this._satoshis; - }, - set: function(num) { - if (num instanceof BN) { - this._satoshisBN = num; - this._satoshis = num.toNumber(); - } else if (_.isString(num)) { - this._satoshis = parseInt(num); - this._satoshisBN = BN.fromNumber(this._satoshis); - } else { - this._satoshisBN = BN.fromNumber(num); - this._satoshis = num; - } - } -}); - -Output.prototype._fromObject = function(param) { - this.satoshis = param.satoshis; - if (param.script || param.scriptBuffer) { - this.setScript(param.script || param.scriptBuffer); - } - return this; -}; - -Output.prototype.toObject = function toObject() { - return { - satoshis: this.satoshis, - script: this.script.toString() - }; -}; - -Output.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -Output.fromJSON = function(json) { - if (JSUtil.isValidJSON(json)) { - json = JSON.parse(json); - } - return new Output({ - satoshis: json.satoshis || -(-json.valuebn), - script: new Script(json.script) - }); -}; - -Output.prototype.setScript = function(script) { - if (script instanceof Script) { - this._scriptBuffer = script.toBuffer(); - this._script = script; - } else if (_.isString(script)) { - this._script = new Script(script); - this._scriptBuffer = this._script.toBuffer(); - } else if (bufferUtil.isBuffer(script)) { - this._scriptBuffer = script; - this._script = null; - } else { - throw new TypeError('Unrecognized Argument'); - } - return this; -}; - -Output.prototype.inspect = function() { - return ''; -}; - -Output.fromBufferReader = function(br) { - var output = new Output(); - output.satoshis = br.readUInt64LEBN(); - var size = br.readVarintNum(); - if (size !== 0) { - output._scriptBuffer = br.read(size); - } else { - output._scriptBuffer = new buffer.Buffer([]); - } - return output; -}; - -Output.prototype.toBufferWriter = function(writer) { - if (!writer) { - writer = new BufferWriter(); - } - writer.writeUInt64LEBN(this._satoshisBN); - var script = this._scriptBuffer; - writer.writeVarintNum(script.length); - writer.write(script); - return writer; -}; - -module.exports = Output; - -},{"../crypto/bn":34,"../encoding/bufferwriter":43,"../script":54,"../util/buffer":69,"../util/js":70,"buffer":209,"lodash":95}],63:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var buffer = require('buffer'); - -var Signature = require('../crypto/signature'); -var Script = require('../script'); -var Output = require('./output'); -var BufferReader = require('../encoding/bufferreader'); -var BufferWriter = require('../encoding/bufferwriter'); -var BN = require('../crypto/bn'); -var Hash = require('../crypto/hash'); -var ECDSA = require('../crypto/ecdsa'); -var $ = require('../util/preconditions'); -var _ = require('lodash'); - -var SIGHASH_SINGLE_BUG = '0000000000000000000000000000000000000000000000000000000000000001'; -var BITS_64_ON = 'ffffffffffffffff'; - -/** - * Returns a buffer of length 32 bytes with the hash that needs to be signed - * for OP_CHECKSIG. - * - * @name Signing.sighash - * @param {Transaction} transaction the transaction to sign - * @param {number} sighashType the type of the hash - * @param {number} inputNumber the input index for the signature - * @param {Script} subscript the script that will be signed - */ -var sighash = function sighash(transaction, sighashType, inputNumber, subscript) { - var Transaction = require('./transaction'); - var Input = require('./input'); - - var i; - // Copy transaction - var txcopy = Transaction.shallowCopy(transaction); - - // Copy script - subscript = new Script(subscript); - subscript.removeCodeseparators(); - - for (i = 0; i < txcopy.inputs.length; i++) { - // Blank signatures for other inputs - txcopy.inputs[i] = new Input(txcopy.inputs[i]).setScript(Script.empty()); - } - - txcopy.inputs[inputNumber] = new Input(txcopy.inputs[inputNumber]).setScript(subscript); - - if ((sighashType & 31) === Signature.SIGHASH_NONE || - (sighashType & 31) === Signature.SIGHASH_SINGLE) { - - // clear all sequenceNumbers - for (i = 0; i < txcopy.inputs.length; i++) { - if (i !== inputNumber) { - txcopy.inputs[i].sequenceNumber = 0; - } - } - } - - if ((sighashType & 31) === Signature.SIGHASH_NONE) { - txcopy.outputs = []; - - } else if ((sighashType & 31) === Signature.SIGHASH_SINGLE) { - // The SIGHASH_SINGLE bug. - // https://bitcointalk.org/index.php?topic=260595.0 - if (inputNumber > txcopy.outputs.length - 1) { - return new Buffer(SIGHASH_SINGLE_BUG, 'hex'); - } - if (txcopy.outputs.length <= inputNumber) { - throw new Error('Missing output to sign'); - } - - txcopy.outputs.length = inputNumber + 1; - - for (i = 0; i < inputNumber; i++) { - txcopy.outputs[i] = new Output({ - satoshis: BN.fromBuffer(new buffer.Buffer(BITS_64_ON, 'hex')), - script: Script.empty() - }); - } - } - - if (sighashType & Signature.SIGHASH_ANYONECANPAY) { - txcopy.inputs = [txcopy.inputs[inputNumber]]; - } - - var buf = new BufferWriter() - .write(txcopy.toBuffer()) - .writeInt32LE(sighashType) - .toBuffer(); - var ret = Hash.sha256sha256(buf); - ret = new BufferReader(ret).readReverse(); - return ret; -}; - -/** - * Create a signature - * - * @name Signing.sign - * @param {Transaction} transaction - * @param {PrivateKey} privateKey - * @param {number} sighash - * @param {number} inputIndex - * @param {Script} subscript - * @return {Signature} - */ -function sign(transaction, privateKey, sighashType, inputIndex, subscript) { - var hashbuf = sighash(transaction, sighashType, inputIndex, subscript); - var sig = ECDSA.sign(hashbuf, privateKey, 'little').set({ - nhashtype: sighashType - }); - return sig; -} - -/** - * Verify a signature - * - * @name Signing.verify - * @param {Transaction} transaction - * @param {Signature} signature - * @param {PublicKey} publicKey - * @param {number} inputIndex - * @param {Script} subscript - * @return {boolean} - */ -function verify(transaction, signature, publicKey, inputIndex, subscript) { - $.checkArgument(!_.isUndefined(transaction)); - $.checkArgument(!_.isUndefined(signature) && !_.isUndefined(signature.nhashtype)); - var hashbuf = sighash(transaction, signature.nhashtype, inputIndex, subscript); - return ECDSA.verify(hashbuf, signature, publicKey, 'little'); -} - -/** - * @namespace Signing - */ -module.exports = { - sighash: sighash, - sign: sign, - verify: verify -}; - -}).call(this,require("buffer").Buffer) -},{"../crypto/bn":34,"../crypto/ecdsa":35,"../crypto/hash":36,"../crypto/signature":39,"../encoding/bufferreader":42,"../encoding/bufferwriter":43,"../script":54,"../util/preconditions":71,"./input":58,"./output":62,"./transaction":65,"buffer":209,"lodash":95}],64:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var _ = require('lodash'); -var $ = require('../util/preconditions'); -var inherits = require('inherits'); -var BufferUtil = require('../util/buffer'); -var JSUtil = require('../util/js'); - -var PublicKey = require('../publickey'); -var errors = require('../errors'); -var Signature = require('../crypto/signature'); - -/** - * @desc - * Wrapper around Signature with fields related to signing a transaction specifically - * - * @param {Object|string|TransactionSignature} arg - * @constructor - */ -function TransactionSignature(arg) { - if (!(this instanceof TransactionSignature)) { - return new TransactionSignature(arg); - } - if (arg instanceof TransactionSignature) { - return arg; - } - if (_.isString(arg)) { - if (JSUtil.isValidJSON(arg)) { - return TransactionSignature.fromJSON(arg); - } - } - if (_.isObject(arg)) { - return this._fromObject(arg); - } - throw new errors.InvalidArgument('TransactionSignatures must be instantiated from an object'); -} -inherits(TransactionSignature, Signature); - -TransactionSignature.prototype._fromObject = function(arg) { - this._checkObjectArgs(arg); - this.publicKey = new PublicKey(arg.publicKey); - this.prevTxId = BufferUtil.isBuffer(arg.prevTxId) ? arg.prevTxId : new Buffer(arg.prevTxId, 'hex'); - this.outputIndex = arg.outputIndex; - this.inputIndex = arg.inputIndex; - this.signature = (arg.signature instanceof Signature) ? arg.signature : - BufferUtil.isBuffer(arg.signature) ? Signature.fromBuffer(arg.signature) : - Signature.fromString(arg.signature); - this.sigtype = arg.sigtype; - return this; -}; - -TransactionSignature.prototype._checkObjectArgs = function(arg) { - $.checkArgument(PublicKey(arg.publicKey), 'publicKey'); - $.checkArgument(!_.isUndefined(arg.inputIndex), 'inputIndex'); - $.checkArgument(!_.isUndefined(arg.outputIndex), 'outputIndex'); - $.checkState(_.isNumber(arg.inputIndex), 'inputIndex must be a number'); - $.checkState(_.isNumber(arg.outputIndex), 'outputIndex must be a number'); - $.checkArgument(arg.signature, 'signature'); - $.checkArgument(arg.prevTxId, 'prevTxId'); - $.checkState(arg.signature instanceof Signature || - BufferUtil.isBuffer(arg.signature) || - JSUtil.isHexa(arg.signature), 'signature must be a buffer or hexa value'); - $.checkState(BufferUtil.isBuffer(arg.prevTxId) || - JSUtil.isHexa(arg.prevTxId), 'prevTxId must be a buffer or hexa value'); - $.checkArgument(arg.sigtype, 'sigtype'); - $.checkState(_.isNumber(arg.sigtype), 'sigtype must be a number'); -}; - -/** - * Serializes a transaction to a plain JS object - * @return {Object} - */ -TransactionSignature.prototype.toObject = function() { - return { - publicKey: this.publicKey.toString(), - prevTxId: this.prevTxId.toString('hex'), - outputIndex: this.outputIndex, - inputIndex: this.inputIndex, - signature: this.signature.toString(), - sigtype: this.sigtype - }; -}; - -/** - * Serializes a transaction to a JSON string - * @return {string} - */ -TransactionSignature.prototype.toJSON = function() { - return JSON.stringify(this.toObject()); -}; - -/** - * Builds a TransactionSignature from a JSON string - * @param {string} json - * @return {TransactionSignature} - */ -TransactionSignature.fromJSON = function(json) { - return new TransactionSignature(JSON.parse(json)); -}; - -/** - * Builds a TransactionSignature from an object - * @param {Object} object - * @return {TransactionSignature} - */ -TransactionSignature.fromObject = function(object) { - $.checkArgument(object); - return new TransactionSignature(object); -}; - -module.exports = TransactionSignature; - -}).call(this,require("buffer").Buffer) -},{"../crypto/signature":39,"../errors":45,"../publickey":53,"../util/buffer":69,"../util/js":70,"../util/preconditions":71,"buffer":209,"inherits":94,"lodash":95}],65:[function(require,module,exports){ -'use strict'; - -var _ = require('lodash'); -var $ = require('../util/preconditions'); -var buffer = require('buffer'); - -var errors = require('../errors'); -var BufferUtil = require('../util/buffer'); -var JSUtil = require('../util/js'); -var BufferReader = require('../encoding/bufferreader'); -var BufferWriter = require('../encoding/bufferwriter'); -var Hash = require('../crypto/hash'); -var Signature = require('../crypto/signature'); -var Sighash = require('./sighash'); - -var Address = require('../address'); -var UnspentOutput = require('./unspentoutput'); -var Input = require('./input'); -var PublicKeyHashInput = Input.PublicKeyHash; -var MultiSigScriptHashInput = Input.MultiSigScriptHash; -var Output = require('./output'); -var Script = require('../script'); -var PrivateKey = require('../privatekey'); -var Block = require('../block'); -var BN = require('../crypto/bn'); - -var CURRENT_VERSION = 1; -var DEFAULT_NLOCKTIME = 0; -var DEFAULT_SEQNUMBER = 0xFFFFFFFF; - -/** - * Represents a transaction, a set of inputs and outputs to change ownership of tokens - * - * @param {*} serialized - * @constructor - */ -function Transaction(serialized) { - if (!(this instanceof Transaction)) { - return new Transaction(serialized); - } - this.inputs = []; - this.outputs = []; - this._inputAmount = 0; - this._outputAmount = 0; - - if (serialized) { - if (serialized instanceof Transaction) { - return Transaction.shallowCopy(serialized); - } else if (JSUtil.isHexa(serialized)) { - this.fromString(serialized); - } else if (JSUtil.isValidJSON(serialized)) { - this.fromJSON(serialized); - } else if (BufferUtil.isBuffer(serialized)) { - this.fromBuffer(serialized); - } else if (_.isObject(serialized)) { - this.fromObject(serialized); - } else { - throw new errors.InvalidArgument('Must provide an object or string to deserialize a transaction'); - } - } else { - this._newTransaction(); - } -} - -// max amount of satoshis in circulation -Transaction.MAX_MONEY = 21000000 * 1e8; - -// nlocktime limit to be considered block height rather than a timestamp -Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT = 5e8; - -// Max value for an unsigned 32 bit value -Transaction.NLOCKTIME_MAX_VALUE = 4294967295; - -/* Constructors and Serialization */ - -/** - * Create a 'shallow' copy of the transaction, by serializing and deserializing - * it dropping any additional information that inputs and outputs may have hold - * - * @param {Transaction} transaction - * @return {Transaction} - */ -Transaction.shallowCopy = function(transaction) { - var copy = new Transaction(transaction.toBuffer()); - return copy; -}; - -var hashProperty = { - configurable: false, - writeable: false, - enumerable: true, - get: function() { - return new BufferReader(this._getHash()).readReverse().toString('hex'); - } -}; -Object.defineProperty(Transaction.prototype, 'hash', hashProperty); -Object.defineProperty(Transaction.prototype, 'id', hashProperty); - -/** - * Retrieve the little endian hash of the transaction (used for serialization) - * @return {Buffer} - */ -Transaction.prototype._getHash = function() { - return Hash.sha256sha256(this.toBuffer()); -}; - -/** - * Retrieve a hexa string that can be used with bitcoind's CLI interface - * (decoderawtransaction, sendrawtransaction) - * - * @param {boolean=} unsafe if true, skip testing for fees that are too high - * @return {string} - */ -Transaction.prototype.serialize = function(unsafe) { - if (unsafe) { - return this.uncheckedSerialize(); - } else { - return this.checkedSerialize(); - } -}; - -Transaction.prototype.uncheckedSerialize = Transaction.prototype.toString = function() { - return this.toBuffer().toString('hex'); -}; - -Transaction.prototype.checkedSerialize = function() { - var feeError = this._validateFees(); - var missingChange = this._missingChange(); - if (feeError && missingChange) { - throw new errors.Transaction.ChangeAddressMissing(); - } - if (feeError && !missingChange) { - throw new errors.Transaction.FeeError(feeError); - } - if (this._hasDustOutputs()) { - throw new errors.Transaction.DustOutputs(); - } - return this.uncheckedSerialize(); -}; - -Transaction.FEE_SECURITY_MARGIN = 15; - -Transaction.prototype._validateFees = function() { - if (this._getUnspentValue() > Transaction.FEE_SECURITY_MARGIN * this._estimateFee()) { - return 'Fee is more than ' + Transaction.FEE_SECURITY_MARGIN + ' times the suggested amount'; - } - if (this._getUnspentValue() < this._estimateFee() / Transaction.FEE_SECURITY_MARGIN) { - return 'Fee is less than ' + Transaction.FEE_SECURITY_MARGIN + ' times the suggested amount'; - } -}; - -Transaction.prototype._missingChange = function() { - return !this._changeScript; -}; - -Transaction.DUST_AMOUNT = 5460; - -Transaction.prototype._hasDustOutputs = function() { - var index, output; - for (index in this.outputs) { - output = this.outputs[index]; - if (output.satoshis < Transaction.DUST_AMOUNT && !output.script.isDataOut()) { - return true; - } - } - return false; -}; - -Transaction.prototype.inspect = function() { - return ''; -}; - -Transaction.prototype.toBuffer = function() { - var writer = new BufferWriter(); - return this.toBufferWriter(writer).toBuffer(); -}; - -Transaction.prototype.toBufferWriter = function(writer) { - writer.writeUInt32LE(this.version); - writer.writeVarintNum(this.inputs.length); - _.each(this.inputs, function(input) { - input.toBufferWriter(writer); - }); - writer.writeVarintNum(this.outputs.length); - _.each(this.outputs, function(output) { - output.toBufferWriter(writer); - }); - writer.writeUInt32LE(this.nLockTime); - return writer; -}; - -Transaction.prototype.fromBuffer = function(buffer) { - var reader = new BufferReader(buffer); - return this.fromBufferReader(reader); -}; - -Transaction.prototype.fromBufferReader = function(reader) { - $.checkArgument(!reader.finished(), 'No transaction data received'); - var i, sizeTxIns, sizeTxOuts; - - this.version = reader.readUInt32LE(); - sizeTxIns = reader.readVarintNum(); - for (i = 0; i < sizeTxIns; i++) { - var input = Input.fromBufferReader(reader); - this.inputs.push(input); - } - sizeTxOuts = reader.readVarintNum(); - for (i = 0; i < sizeTxOuts; i++) { - this.outputs.push(Output.fromBufferReader(reader)); - } - this.nLockTime = reader.readUInt32LE(); - return this; -}; - -Transaction.prototype.fromJSON = function(json) { - if (JSUtil.isValidJSON(json)) { - json = JSON.parse(json); - } - return this.fromObject(json); -}; - -Transaction.prototype.toObject = function toObject() { - var inputs = []; - this.inputs.forEach(function(input) { - inputs.push(input.toObject()); - }); - var outputs = []; - this.outputs.forEach(function(output) { - outputs.push(output.toObject()); - }); - var obj = { - version: this.version, - inputs: inputs, - outputs: outputs, - nLockTime: this.nLockTime - }; - if (this._changeScript) { - obj.changeScript = this._changeScript.toString(); - } - if (!_.isUndefined(this._changeIndex)) { - obj.changeIndex = this._changeIndex; - } - if (!_.isUndefined(this._fee)) { - obj.fee = this._fee; - } - return obj; -}; - -Transaction.prototype.fromObject = function(transaction) { - var self = this; - _.each(transaction.inputs, function(input) { - if (!input.output || !input.output.script) { - self.uncheckedAddInput(new Input(input)); - return; - } - input.output.script = new Script(input.output.script); - var txin; - if (input.output.script.isPublicKeyHashOut()) { - txin = new Input.PublicKeyHash(input); - } else if (input.output.script.isScriptHashOut() && input.publicKeys && input.threshold) { - txin = new Input.MultiSigScriptHash( - input, input.publicKeys, input.threshold, input.signatures - ); - } else { - throw new errors.Transaction.Input.UnsupportedScript(input.output.script); - } - self.addInput(txin); - }); - _.each(transaction.outputs, function(output) { - self.addOutput(new Output(output)); - }); - if (transaction.changeIndex) { - this._changeIndex = transaction.changeIndex; - } - if (transaction.changeScript) { - this._changeScript = new Script(transaction.changeScript); - } - if (transaction.fee) { - this.fee(transaction.fee); - } - this.nLockTime = transaction.nLockTime; - this.version = transaction.version; - this._checkConsistency(); - return this; -}; - -Transaction.prototype._checkConsistency = function() { - if (!_.isUndefined(this._changeIndex)) { - $.checkState(this._changeScript); - $.checkState(this.outputs[this._changeIndex]); - $.checkState(this.outputs[this._changeIndex].script.toString() === - this._changeScript.toString()); - } - // TODO: add other checks -}; - -/** - * Sets nLockTime so that transaction is not valid until the desired date(a - * timestamp in seconds since UNIX epoch is also accepted) - * - * @param {Date | Number} time - * @return {Transaction} this - */ -Transaction.prototype.lockUntilDate = function(time) { - $.checkArgument(time); - if (_.isNumber(time) && time < Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) { - throw new errors.Transaction.LockTimeTooEarly(); - } - if (_.isDate(time)) { - time = time.getTime() / 1000; - } - this.nLockTime = time; - return this; -}; - -/** - * Sets nLockTime so that transaction is not valid until the desired block - * height. - * - * @param {Number} height - * @return {Transaction} this - */ -Transaction.prototype.lockUntilBlockHeight = function(height) { - $.checkArgument(_.isNumber(height)); - if (height >= Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) { - throw new errors.Transaction.BlockHeightTooHigh(); - } - if (height < 0) { - throw new errors.Transaction.NLockTimeOutOfRange(); - } - this.nLockTime = height; - return this; -}; - -/** - * Returns a semantic version of the transaction's nLockTime. - * @return {Number|Date} - * If nLockTime is 0, it returns null, - * if it is < 500000000, it returns a block height (number) - * else it returns a Date object. - */ -Transaction.prototype.getLockTime = function() { - if (!this.nLockTime) { - return null; - } - if (this.nLockTime < Transaction.NLOCKTIME_BLOCKHEIGHT_LIMIT) { - return this.nLockTime; - } - return new Date(1000 * this.nLockTime); -}; - -Transaction.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -Transaction.prototype.fromString = function(string) { - this.fromBuffer(new buffer.Buffer(string, 'hex')); -}; - -Transaction.prototype._newTransaction = function() { - this.version = CURRENT_VERSION; - this.nLockTime = DEFAULT_NLOCKTIME; -}; - -/* Transaction creation interface */ - -/** - * Add an input to this transaction. This is a high level interface - * to add an input, for more control, use @{link Transaction#addInput}. - * - * Can receive, as output information, the output of bitcoind's `listunspent` command, - * and a slightly fancier format recognized by bitcore: - * - * ``` - * { - * address: 'mszYqVnqKoQx4jcTdJXxwKAissE3Jbrrc1', - * txId: 'a477af6b2667c29670467e4e0728b685ee07b240235771862318e29ddbe58458', - * outputIndex: 0, - * script: Script.empty(), - * satoshis: 1020000 - * } - * ``` - * Where `address` can be either a string or a bitcore Address object. The - * same is true for `script`, which can be a string or a bitcore Script. - * - * Beware that this resets all the signatures for inputs (in further versions, - * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset). - * - * @example - * ```javascript - * var transaction = new Transaction(); - * - * // From a pay to public key hash output from bitcoind's listunspent - * transaction.from({'txid': '0000...', vout: 0, amount: 0.1, scriptPubKey: 'OP_DUP ...'}); - * - * // From a pay to public key hash output - * transaction.from({'txId': '0000...', outputIndex: 0, satoshis: 1000, script: 'OP_DUP ...'}); - * - * // From a multisig P2SH output - * transaction.from({'txId': '0000...', inputIndex: 0, satoshis: 1000, script: '... OP_HASH'}, - * ['03000...', '02000...'], 2); - * ``` - * - * @param {Object} utxo - * @param {Array=} pubkeys - * @param {number=} threshold - */ -Transaction.prototype.from = function(utxo, pubkeys, threshold) { - if (_.isArray(utxo)) { - var self = this; - _.each(utxo, function(utxo) { - self.from(utxo, pubkeys, threshold); - }); - return this; - } - var exists = _.any(this.inputs, function(input) { - // TODO: Maybe prevTxId should be a string? Or defined as read only property? - return input.prevTxId.toString('hex') === utxo.txId && input.outputIndex === utxo.outputIndex; - }); - if (exists) { - return; - } - if (pubkeys && threshold) { - this._fromMultisigUtxo(utxo, pubkeys, threshold); - } else { - this._fromNonP2SH(utxo); - } - return this; -}; - -Transaction.prototype._fromNonP2SH = function(utxo) { - var clazz; - utxo = new UnspentOutput(utxo); - if (utxo.script.isPublicKeyHashOut()) { - clazz = PublicKeyHashInput; - } else { - clazz = Input; - } - this.addInput(new clazz({ - output: new Output({ - script: utxo.script, - satoshis: utxo.satoshis - }), - prevTxId: utxo.txId, - outputIndex: utxo.outputIndex, - sequenceNumber: DEFAULT_SEQNUMBER, - script: Script.empty() - })); -}; - -Transaction.prototype._fromMultisigUtxo = function(utxo, pubkeys, threshold) { - $.checkArgument(threshold <= pubkeys.length, - 'Number of required signatures must be greater than the number of public keys'); - utxo = new UnspentOutput(utxo); - this.addInput(new MultiSigScriptHashInput({ - output: new Output({ - script: utxo.script, - satoshis: utxo.satoshis - }), - prevTxId: utxo.txId, - outputIndex: utxo.outputIndex, - sequenceNumber: DEFAULT_SEQNUMBER, - script: Script.empty() - }, pubkeys, threshold)); -}; - -/** - * Add an input to this transaction. The input must be an instance of the `Input` class. - * It should have information about the Output that it's spending, but if it's not already - * set, two additional parameters, `outputScript` and `satoshis` can be provided. - * - * @param {Input} input - * @param {String|Script} outputScript - * @param {number} satoshis - * @return Transaction this, for chaining - */ -Transaction.prototype.addInput = function(input, outputScript, satoshis) { - $.checkArgumentType(input, Input, 'input'); - if (!input.output && (_.isUndefined(outputScript) || _.isUndefined(satoshis))) { - throw new errors.Transaction.NeedMoreInfo('Need information about the UTXO script and satoshis'); - } - if (!input.output && outputScript && !_.isUndefined(satoshis)) { - outputScript = outputScript instanceof Script ? outputScript : new Script(outputScript); - $.checkArgumentType(satoshis, 'number', 'satoshis'); - input.output = new Output({ - script: outputScript, - satoshis: satoshis - }); - } - return this.uncheckedAddInput(input); -}; - -/** - * Add an input to this transaction, without checking that the input has information about - * the output that it's spending. - * - * @param {Input} input - * @return Transaction this, for chaining - */ -Transaction.prototype.uncheckedAddInput = function(input) { - $.checkArgumentType(input, Input, 'input'); - this.inputs.push(input); - if (input.output) { - this._inputAmount += input.output.satoshis; - } - this._updateChangeOutput(); - return this; -}; - -/** - * Returns true if the transaction has enough info on all inputs to be correctly validated - * - * @return {boolean} - */ -Transaction.prototype.hasAllUtxoInfo = function() { - return _.all(this.inputs.map(function(input) { - return !!input.output; - })); -}; - -/** - * Manually set the fee for this transaction. Beware that this resets all the signatures - * for inputs (in further versions, SIGHASH_SINGLE or SIGHASH_NONE signatures will not - * be reset). - * - * @param {number} amount satoshis to be sent - * @return {Transaction} this, for chaining - */ -Transaction.prototype.fee = function(amount) { - this._fee = amount; - this._updateChangeOutput(); - return this; -}; - -/* Output management */ - -/** - * Set the change address for this transaction - * - * Beware that this resets all the signatures for inputs (in further versions, - * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset). - * - * @param {address} An address for change to be sent to. - * @return {Transaction} this, for chaining - */ -Transaction.prototype.change = function(address) { - this._changeScript = Script.fromAddress(address); - this._updateChangeOutput(); - return this; -}; - - -/** - * @return {Output} change output, if it exists - */ -Transaction.prototype.getChangeOutput = function() { - if (!_.isUndefined(this._changeIndex)) { - return this.outputs[this._changeIndex]; - } - return null; -}; - -/** - * Add an output to the transaction. - * - * Beware that this resets all the signatures for inputs (in further versions, - * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset). - * - * @param {string|Address} address - * @param {number} amount in satoshis - * @return {Transaction} this, for chaining - */ -Transaction.prototype.to = function(address, amount) { - this.addOutput(new Output({ - script: Script(new Address(address)), - satoshis: amount - })); - return this; -}; - -/** - * Add an OP_RETURN output to the transaction. - * - * Beware that this resets all the signatures for inputs (in further versions, - * SIGHASH_SINGLE or SIGHASH_NONE signatures will not be reset). - * - * @param {Buffer|string} value the data to be stored in the OP_RETURN output. - * In case of a string, the UTF-8 representation will be stored - * @return {Transaction} this, for chaining - */ -Transaction.prototype.addData = function(value) { - this.addOutput(new Output({ - script: Script.buildDataOut(value), - satoshis: 0 - })); - return this; -}; - -Transaction.prototype.addOutput = function(output) { - $.checkArgumentType(output, Output, 'output'); - this._addOutput(output); - this._updateChangeOutput(); -}; - -Transaction.prototype._addOutput = function(output) { - this.outputs.push(output); - this._outputAmount += output.satoshis; -}; - -Transaction.prototype._updateChangeOutput = function() { - if (!this._changeScript) { - return; - } - this._clearSignatures(); - if (!_.isUndefined(this._changeIndex)) { - this._removeOutput(this._changeIndex); - } - var available = this._getUnspentValue(); - var fee = this.getFee(); - var changeAmount = available - fee; - if (changeAmount > 0) { - this._changeIndex = this.outputs.length; - this._addOutput(new Output({ - script: this._changeScript, - satoshis: changeAmount - })); - } else { - this._changeIndex = undefined; - } -}; -/** - * Calculates the fees for the transaction. - * - * If there is no change output set, the fee will be the - * output amount minus the input amount. - * If there's a fixed fee set, return that - * If there's no fee set, estimate it based on size - * @return {Number} miner fee for this transaction in satoshis - */ -Transaction.prototype.getFee = function() { - // if no change output is set, fees should equal all the unspent amount - if (!this._changeScript) { - return this._getUnspentValue(); - } - return _.isUndefined(this._fee) ? this._estimateFee() : this._fee; -}; - -/** - * Estimates fee from serialized transaction size in bytes. - */ -Transaction.prototype._estimateFee = function() { - var estimatedSize = this._estimateSize(); - var available = this._getUnspentValue(); - return Transaction._estimateFee(estimatedSize, available); -}; - -Transaction.prototype._getUnspentValue = function() { - return this._inputAmount - this._outputAmount; -}; - -Transaction.prototype._clearSignatures = function() { - _.each(this.inputs, function(input) { - input.clearSignatures(); - }); -}; - -Transaction.FEE_PER_KB = 10000; -// Safe upper bound for change address script -Transaction.CHANGE_OUTPUT_MAX_SIZE = 20 + 4 + 34 + 4; - -Transaction._estimateFee = function(size, amountAvailable) { - var fee = Math.ceil(size / Transaction.FEE_PER_KB); - if (amountAvailable > fee) { - size += Transaction.CHANGE_OUTPUT_MAX_SIZE; - } - return Math.ceil(size / 1000) * Transaction.FEE_PER_KB; -}; - -Transaction.MAXIMUM_EXTRA_SIZE = 4 + 9 + 9 + 4; - -Transaction.prototype._estimateSize = function() { - var result = Transaction.MAXIMUM_EXTRA_SIZE; - _.each(this.inputs, function(input) { - result += input._estimateSize(); - }); - _.each(this.outputs, function(output) { - result += output.script.toBuffer().length + 9; - }); - return result; -}; - -Transaction.prototype._removeOutput = function(index) { - var output = this.outputs[index]; - this._outputAmount -= output.satoshis; - this.outputs = _.without(this.outputs, output); -}; - -Transaction.prototype.removeOutput = function(index) { - this._removeOutput(index); - this._updateChangeOutput(); -}; - -Transaction.prototype.removeInput = function(txId, outputIndex) { - var index; - if (!outputIndex && _.isNumber(txId)) { - index = txId; - } else { - index = _.findIndex(this.inputs, function(input) { - return input.prevTxId.toString('hex') === txId && input.outputIndex === outputIndex; - }); - } - if (index < 0 || index >= this.inputs.length) { - throw new errors.Transaction.InvalidIndex(index, this.inputs.length); - } - var input = this.inputs[index]; - this._inputAmount -= input.output.satoshis; - this.inputs = _.without(this.inputs, input); - this._updateChangeOutput(); -}; - -/* Signature handling */ - -/** - * Sign the transaction using one or more private keys. - * - * It tries to sign each input, verifying that the signature will be valid - * (matches a public key). - * - * @param {Array|String|PrivateKey} privateKey - * @param {number} sigtype - * @return {Transaction} this, for chaining - */ -Transaction.prototype.sign = function(privateKey, sigtype) { - $.checkState(this.hasAllUtxoInfo()); - var self = this; - if (_.isArray(privateKey)) { - _.each(privateKey, function(privateKey) { - self.sign(privateKey, sigtype); - }); - return this; - } - _.each(this.getSignatures(privateKey, sigtype), function(signature) { - self.applySignature(signature); - }); - return this; -}; - -Transaction.prototype.getSignatures = function(privKey, sigtype) { - privKey = new PrivateKey(privKey); - sigtype = sigtype || Signature.SIGHASH_ALL; - var transaction = this; - var results = []; - var hashData = Hash.sha256ripemd160(privKey.publicKey.toBuffer()); - _.each(this.inputs, function forEachInput(input, index) { - _.each(input.getSignatures(transaction, privKey, index, sigtype, hashData), function(signature) { - results.push(signature); - }); - }); - return results; -}; - -/** - * Add a signature to the transaction - * - * @param {Object} signature - * @param {number} signature.inputIndex - * @param {number} signature.sigtype - * @param {PublicKey} signature.publicKey - * @param {Signature} signature.signature - * @return {Transaction} this, for chaining - */ -Transaction.prototype.applySignature = function(signature) { - this.inputs[signature.inputIndex].addSignature(this, signature); - return this; -}; - -Transaction.prototype.isFullySigned = function() { - _.each(this.inputs, function(input) { - if (input.isFullySigned === Input.prototype.isFullySigned) { - throw new errors.Transaction.UnableToVerifySignature( - 'Unrecognized script kind, or not enough information to execute script.' + - 'This usually happens when creating a transaction from a serialized transaction' - ); - } - }); - return _.all(_.map(this.inputs, function(input) { - return input.isFullySigned(); - })); -}; - -Transaction.prototype.isValidSignature = function(signature) { - var self = this; - if (this.inputs[signature.inputIndex].isValidSignature === Input.prototype.isValidSignature) { - throw new errors.Transaction.UnableToVerifySignature( - 'Unrecognized script kind, or not enough information to execute script.' + - 'This usually happens when creating a transaction from a serialized transaction' - ); - } - return this.inputs[signature.inputIndex].isValidSignature(self, signature); -}; - -/** - * @returns {bool} whether the signature is valid for this transaction input - */ -Transaction.prototype.verifySignature = function(sig, pubkey, nin, subscript) { - return Sighash.verify(this, sig, pubkey, nin, subscript); -}; - -/** - * Check that a transaction passes basic sanity tests. If not, return a string - * describing the error. This function contains the same logic as - * CheckTransaction in bitcoin core. - */ -Transaction.prototype.verify = function() { - // Basic checks that don't depend on any context - if (this.inputs.length === 0) { - return 'transaction txins empty'; - } - - if (this.outputs.length === 0) { - return 'transaction txouts empty'; - } - - // Size limits - if (this.toBuffer().length > Block.MAX_BLOCK_SIZE) { - return 'transaction over the maximum block size'; - } - - // Check for negative or overflow output values - var valueoutbn = new BN(0); - for (var i = 0; i < this.outputs.length; i++) { - var txout = this.outputs[i]; - var valuebn = txout._satoshisBN; - if (valuebn.lt(BN.Zero)) { - return 'transaction txout ' + i + ' negative'; - } - if (valuebn.gt(new BN(Transaction.MAX_MONEY, 10))) { - return 'transaction txout ' + i + ' greater than MAX_MONEY'; - } - valueoutbn = valueoutbn.add(valuebn); - if (valueoutbn.gt(new BN(Transaction.MAX_MONEY))) { - return 'transaction txout ' + i + ' total output greater than MAX_MONEY'; - } - } - - // Check for duplicate inputs - var txinmap = {}; - for (i = 0; i < this.inputs.length; i++) { - var txin = this.inputs[i]; - - var inputid = txin.prevTxId + ':' + txin.outputIndex; - if (!_.isUndefined(txinmap[inputid])) { - return 'transaction input ' + i + ' duplicate input'; - } - txinmap[inputid] = true; - } - - var isCoinbase = this.isCoinbase(); - if (isCoinbase) { - var buf = this.inputs[0]._script.toBuffer(); - if (buf.length < 2 || buf.length > 100) { - return 'coinbase trasaction script size invalid'; - } - } else { - for (i = 0; i < this.inputs.length; i++) { - if (this.inputs[i].isNull()) { - return 'tranasction input ' + i + ' has null input'; - } - } - } - return true; -}; - -/** - * Analagous to bitcoind's IsCoinBase function in transaction.h - */ -Transaction.prototype.isCoinbase = function() { - return (this.inputs.length === 1 && this.inputs[0].isNull()); -}; - - -module.exports = Transaction; - -},{"../address":31,"../block":32,"../crypto/bn":34,"../crypto/hash":36,"../crypto/signature":39,"../encoding/bufferreader":42,"../encoding/bufferwriter":43,"../errors":45,"../privatekey":52,"../script":54,"../util/buffer":69,"../util/js":70,"../util/preconditions":71,"./input":58,"./output":62,"./sighash":63,"./unspentoutput":66,"buffer":209,"lodash":95}],66:[function(require,module,exports){ -'use strict'; - -var _ = require('lodash'); -var $ = require('../util/preconditions'); -var JSUtil = require('../util/js'); - -var Script = require('../script'); -var Address = require('../address'); -var Unit = require('../unit'); - -/** - * Represents an unspent output information: its script, associated amount and address, - * transaction id and output index. - * - * @constructor - * @param {object} data - * @param {string} data.txid the previous transaction id - * @param {string=} data.txId alias for `txid` - * @param {number} data.vout the index in the transaction - * @param {number=} data.outputIndex alias for `vout` - * @param {string|Script} data.scriptPubKey the script that must be resolved to release the funds - * @param {string|Script=} data.script alias for `scriptPubKey` - * @param {number} data.amount amount of bitcoins associated - * @param {number=} data.satoshis alias for `amount`, but expressed in satoshis (1 BTC = 1e8 satoshis) - * @param {string|Address=} data.address the associated address to the script, if provided - */ -function UnspentOutput(data) { - /* jshint maxcomplexity: 20 */ - /* jshint maxstatements: 20 */ - if (!(this instanceof UnspentOutput)) { - return new UnspentOutput(data); - } - $.checkArgument(_.isObject(data), 'Must provide an object from where to extract data'); - var address = data.address ? new Address(data.address) : undefined; - var txId = data.txid ? data.txid : data.txId; - if (!txId || !JSUtil.isHexaString(txId) || txId.length > 64) { - // TODO: Use the errors library - throw new Error('Invalid TXID in object', data); - } - var outputIndex = _.isUndefined(data.vout) ? data.outputIndex : data.vout; - if (!_.isNumber(outputIndex)) { - throw new Error('Invalid outputIndex, received ' + outputIndex); - } - $.checkArgument(!_.isUndefined(data.scriptPubKey) || !_.isUndefined(data.script), - 'Must provide the scriptPubKey for that output!'); - var script = new Script(data.scriptPubKey || data.script); - $.checkArgument(!_.isUndefined(data.amount) || !_.isUndefined(data.satoshis), - 'Must provide an amount for the output'); - var amount = !_.isUndefined(data.amount) ? new Unit.fromBTC(data.amount).toSatoshis() : data.satoshis; - $.checkArgument(_.isNumber(amount), 'Amount must be a number'); - JSUtil.defineImmutable(this, { - address: address, - txId: txId, - outputIndex: outputIndex, - script: script, - satoshis: amount - }); -} - -/** - * Provide an informative output when displaying this object in the console - * @returns string - */ -UnspentOutput.prototype.inspect = function() { - return ''; -}; - -/** - * String representation: just "txid:index" - * @returns string - */ -UnspentOutput.prototype.toString = function() { - return this.txId + ':' + this.outputIndex; -}; - -/** - * Deserialize an UnspentOutput from an object or JSON string - * @param {object|string} data - * @return UnspentOutput - */ -UnspentOutput.fromJSON = UnspentOutput.fromObject = function(data) { - if (JSUtil.isValidJSON(data)) { - data = JSON.parse(data); - } - return new UnspentOutput(data); -}; - -/** - * Retrieve a string representation of this object - * @return {string} - */ -UnspentOutput.prototype.toJSON = function() { - return JSON.stringify(this.toObject()); -}; - -/** - * Returns a plain object (no prototype or methods) with the associated infor for this output - * @return {object} - */ -UnspentOutput.prototype.toObject = function() { - return { - address: this.address ? this.address.toString() : undefined, - txid: this.txId, - vout: this.outputIndex, - scriptPubKey: this.script.toBuffer().toString('hex'), - amount: Unit.fromSatoshis(this.satoshis).toBTC() - }; -}; - -module.exports = UnspentOutput; - -},{"../address":31,"../script":54,"../unit":67,"../util/js":70,"../util/preconditions":71,"lodash":95}],67:[function(require,module,exports){ -'use strict'; - -var _ = require('lodash'); - -var errors = require('./errors'); -var JSUtil = require('./util/js'); - -var UNITS = { - 'BTC' : [1e8, 8], - 'mBTC' : [1e5, 5], - 'uBTC' : [1e2, 2], - 'bits' : [1e2, 2], - 'satoshis' : [1, 0] -}; - -/** - * Utility for handling and converting bitcoins units. The supported units are - * BTC, mBTC, bits (also named uBTC) and satoshis. A unit instance can be created with an - * amount and a unit code, or alternatively using static methods like {fromBTC}. - * It also allows to be created from a fiat amount and the exchange rate, or - * alternatively using the {fromFiat} static method. - * You can consult for different representation of a unit instance using it's - * {to} method, the fixed unit methods like {toSatoshis} or alternatively using - * the unit accessors. It also can be converted to a fiat amount by providing the - * corresponding BTC/fiat exchange rate. - * - * @example - * ```javascript - * var sats = Unit.fromBTC(1.3).toSatoshis(); - * var mili = Unit.fromBits(1.3).to(Unit.mBTC); - * var bits = Unit.fromFiat(1.3, 350).bits; - * var btc = new Unit(1.3, Unit.bits).BTC; - * ``` - * - * @param {Number} amount - The amount to be represented - * @param {String|Number} code - The unit of the amount or the exchange rate - * @returns {Unit} A new instance of an Unit - * @constructor - */ -function Unit(amount, code) { - if (!(this instanceof Unit)) { - return new Unit(amount, code); - } - - // convert fiat to BTC - if (_.isNumber(code)) { - if (code <= 0) { - throw new errors.Unit.InvalidRate(code); - } - amount = amount / code; - code = Unit.BTC; - } - - this._value = this._from(amount, code); - - var self = this; - var defineAccesor = function(key) { - Object.defineProperty(self, key, { - get: function() { return self.to(key); }, - enumerable: true, - }); - }; - - Object.keys(UNITS).forEach(defineAccesor); -} - -Object.keys(UNITS).forEach(function(key) { - Unit[key] = key; -}); - -/** - * Returns a Unit instance created from JSON string or object - * - * @param {String|Object} json - JSON with keys: amount and code - * @returns {Unit} A Unit instance - */ -Unit.fromJSON = function fromJSON(json){ - if (JSUtil.isValidJSON(json)) { - json = JSON.parse(json); - } - return new Unit(json.amount, json.code); -}; - -/** - * Returns a Unit instance created from an amount in BTC - * - * @param {Number} amount - The amount in BTC - * @returns {Unit} A Unit instance - */ -Unit.fromBTC = function(amount) { - return new Unit(amount, Unit.BTC); -}; - -/** - * Returns a Unit instance created from an amount in mBTC - * - * @param {Number} amount - The amount in mBTC - * @returns {Unit} A Unit instance - */ -Unit.fromMilis = function(amount) { - return new Unit(amount, Unit.mBTC); -}; - -/** - * Returns a Unit instance created from an amount in bits - * - * @param {Number} amount - The amount in bits - * @returns {Unit} A Unit instance - */ -Unit.fromMicros = Unit.fromBits = function(amount) { - return new Unit(amount, Unit.bits); -}; - -/** - * Returns a Unit instance created from an amount in satoshis - * - * @param {Number} amount - The amount in satoshis - * @returns {Unit} A Unit instance - */ -Unit.fromSatoshis = function(amount) { - return new Unit(amount, Unit.satoshis); -}; - -/** - * Returns a Unit instance created from a fiat amount and exchange rate. - * - * @param {Number} amount - The amount in fiat - * @param {Number} rate - The exchange rate BTC/fiat - * @returns {Unit} A Unit instance - */ -Unit.fromFiat = function(amount, rate) { - return new Unit(amount, rate); -}; - -Unit.prototype._from = function(amount, code) { - if (!UNITS[code]) { - throw new errors.Unit.UnknownCode(code); - } - return parseInt((amount * UNITS[code][0]).toFixed()); -}; - -/** - * Returns the value represented in the specified unit - * - * @param {String|Number} code - The unit code or exchange rate - * @returns {Number} The converted value - */ -Unit.prototype.to = function(code) { - if (_.isNumber(code)) { - if (code <= 0) { - throw new errors.Unit.InvalidRate(code); - } - return parseFloat((this.BTC * code).toFixed(2)); - } - - if (!UNITS[code]) { - throw new errors.Unit.UnknownCode(code); - } - - var value = this._value / UNITS[code][0]; - return parseFloat(value.toFixed(UNITS[code][1])); -}; - -/** - * Returns the value represented in BTC - * - * @returns {Number} The value converted to BTC - */ -Unit.prototype.toBTC = function() { - return this.to(Unit.BTC); -}; - -/** - * Returns the value represented in mBTC - * - * @returns {Number} The value converted to mBTC - */ -Unit.prototype.toMilis = function() { - return this.to(Unit.mBTC); -}; - -/** - * Returns the value represented in bits - * - * @returns {Number} The value converted to bits - */ -Unit.prototype.toMicros = Unit.prototype.toBits = function() { - return this.to(Unit.bits); -}; - -/** - * Returns the value represented in satoshis - * - * @returns {Number} The value converted to satoshis - */ -Unit.prototype.toSatoshis = function() { - return this.to(Unit.satoshis); -}; - -/** - * Returns the value represented in fiat - * - * @param {string} rate - The exchange rate between BTC/currency - * @returns {Number} The value converted to satoshis - */ -Unit.prototype.atRate = function(rate) { - return this.to(rate); -}; - -/** - * Returns a the string representation of the value in satoshis - * - * @returns {String} the value in satoshis - */ -Unit.prototype.toString = function() { - return this.satoshis + ' satoshis'; -}; - -/** - * Returns a plain object representation of the Unit - * - * @returns {Object} An object with the keys: amount and code - */ -Unit.prototype.toObject = function toObject() { - return { - amount: this.BTC, - code: Unit.BTC - }; -}; - -Unit.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -/** - * Returns a string formatted for the console - * - * @returns {String} the value in satoshis - */ -Unit.prototype.inspect = function() { - return ''; -}; - -module.exports = Unit; - -},{"./errors":45,"./util/js":70,"lodash":95}],68:[function(require,module,exports){ -'use strict'; - -var _ = require('lodash'); -var URL = require('url'); - -var Address = require('./address'); -var Unit = require('./unit'); -var JSUtil = require('./util/js'); - -/** - * Bitcore URI - * - * Instantiate an URI from a bitcoin URI String or an Object. An URI instance - * can be created with a bitcoin uri string or an object. All instances of - * URI are valid, the static method isValid allows checking before instanciation. - * - * All standard parameters can be found as members of the class, the address - * is represented using an {Address} instance and the amount is represented in - * satoshis. Any other non-standard parameters can be found under the extra member. - * - * @example - * ```javascript - * - * var uri = new URI('bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu?amount=1.2'); - * console.log(uri.address, uri.amount); - * ``` - * - * @param {string|Object} data - A bitcoin URI string or an Object - * @param {Array.} [knownParams] - Required non-standard params - * @throws {TypeError} Invalid bitcoin address - * @throws {TypeError} Invalid amount - * @throws {Error} Unknown required argument - * @returns {URI} A new valid and frozen instance of URI - * @constructor - */ -var URI = function(data, knownParams) { - if (!(this instanceof URI)) { - return new URI(data, knownParams); - } - - this.extras = {}; - this.knownParams = knownParams || []; - this.address = this.network = this.amount = this.message = null; - - if (typeof(data) === 'string') { - var params = URI.parse(data); - if (params.amount) { - params.amount = this._parseAmount(params.amount); - } - this._fromObject(params); - } else if (typeof(data) === 'object') { - this._fromObject(data); - } else { - throw new TypeError('Unrecognized data format.'); - } -}; - -/** - * Instantiate a URI from a String - * - * @param {String} str - JSON string or object of the URI - * @returns {URI} A new instance of a URI - */ -URI.fromString = function fromString(str) { - if (typeof(str) !== 'string') { - throw new TypeError('Expected a string'); - } - return new URI(str); -}; - -/** - * Instantiate a URI from JSON - * - * @param {String|Object} json - JSON string or object of the URI - * @returns {URI} A new instance of a URI - */ -URI.fromJSON = function fromJSON(json) { - if (JSUtil.isValidJSON(json)) { - json = JSON.parse(json); - } - return new URI(json); -}; - -/** - * Check if an bitcoin URI string is valid - * - * @example - * ```javascript - * - * var valid = URI.isValid('bitcoin:12A1MyfXbW6RhdRAZEqofac5jCQQjwEPBu'); - * // true - * ``` - * - * @param {string|Object} data - A bitcoin URI string or an Object - * @param {Array.} [knownParams] - Required non-standard params - * @returns {boolean} Result of uri validation - */ -URI.isValid = function(arg, knownParams) { - try { - new URI(arg, knownParams); - } catch (err) { - return false; - } - return true; -}; - -/** - * Convert a bitcoin URI string into a simple object. - * - * @param {string} uri - A bitcoin URI string - * @throws {TypeError} Invalid bitcoin URI - * @returns {Object} An object with the parsed params - */ -URI.parse = function(uri) { - var info = URL.parse(uri, true); - - if (info.protocol !== 'bitcoin:') { - throw new TypeError('Invalid bitcoin URI'); - } - - // workaround to host insensitiveness - var group = /[^:]*:\/?\/?([^?]*)/.exec(uri); - info.query.address = group && group[1] || undefined; - - return info.query; -}; - -URI.Members = ['address', 'amount', 'message', 'label', 'r']; - -/** - * Internal function to load the URI instance with an object. - * - * @param {Object} obj - Object with the information - * @throws {TypeError} Invalid bitcoin address - * @throws {TypeError} Invalid amount - * @throws {Error} Unknown required argument - */ -URI.prototype._fromObject = function(obj) { - /* jshint maxcomplexity: 10 */ - - if (!Address.isValid(obj.address)) { - throw new TypeError('Invalid bitcoin address'); - } - - this.address = new Address(obj.address); - this.network = this.address.network; - this.amount = obj.amount; - - for (var key in obj) { - if (key === 'address' || key === 'amount') { - continue; - } - - if (/^req-/.exec(key) && this.knownParams.indexOf(key) === -1) { - throw Error('Unknown required argument ' + key); - } - - var destination = URI.Members.indexOf(key) > -1 ? this : this.extras; - destination[key] = obj[key]; - } -}; - -/** - * Internal function to transform a BTC string amount into satoshis - * - * @param {String} amount - Amount BTC string - * @throws {TypeError} Invalid amount - * @returns {Object} Amount represented in satoshis - */ -URI.prototype._parseAmount = function(amount) { - amount = Number(amount); - if (isNaN(amount)) { - throw new TypeError('Invalid amount'); - } - return Unit.fromBTC(amount).toSatoshis(); -}; - -URI.prototype.toObject = function toObject() { - var json = {}; - for (var i = 0; i < URI.Members.length; i++) { - var m = URI.Members[i]; - if (this.hasOwnProperty(m) && typeof(this[m]) !== 'undefined') { - json[m] = this[m].toString(); - } - } - _.extend(json, this.extras); - return json; -}; - -URI.prototype.toJSON = function toJSON() { - return JSON.stringify(this.toObject()); -}; - -/** - * Will return a the string representation of the URI - * - * @returns {String} Bitcoin URI string - */ -URI.prototype.toString = function() { - var query = {}; - if (this.amount) { - query.amount = Unit.fromSatoshis(this.amount).toBTC(); - } - if (this.message) { - query.message = this.message; - } - if (this.label) { - query.label = this.label; - } - if (this.r) { - query.r = this.r; - } - _.extend(query, this.extras); - - return URL.format({ - protocol: 'bitcoin:', - host: this.address, - query: query - }); -}; - -/** - * Will return a string formatted for the console - * - * @returns {String} Bitcoin URI - */ -URI.prototype.inspect = function() { - return ''; -}; - -module.exports = URI; - -},{"./address":31,"./unit":67,"./util/js":70,"lodash":95,"url":375}],69:[function(require,module,exports){ -(function (Buffer){ -'use strict'; - -var buffer = require('buffer'); -var assert = require('assert'); - -var js = require('./js'); -var $ = require('./preconditions'); - -function equals(a, b) { - if (a.length !== b.length) { - return false; - } - var length = a.length; - for (var i = 0; i < length; i++) { - if (a[i] !== b[i]) { - return false; - } - } - return true; -} - -module.exports = { - /** - * Fill a buffer with a value. - * - * @param {Buffer} buffer - * @param {number} value - * @return {Buffer} - */ - fill: function fill(buffer, value) { - $.checkArgumentType(buffer, 'Buffer', 'buffer'); - $.checkArgumentType(value, 'number', 'value'); - var length = buffer.length; - for (var i = 0; i < length; i++) { - buffer[i] = value; - } - return buffer; - }, - - /** - * Return a copy of a buffer - * - * @param {Buffer} original - * @return {Buffer} - */ - copy: function(original) { - var buffer = new Buffer(original.length); - original.copy(buffer); - return buffer; - }, - - /** - * Returns true if the given argument is an instance of a buffer. Tests for - * both node's Buffer and Uint8Array - * - * @param {*} arg - * @return {boolean} - */ - isBuffer: function isBuffer(arg) { - return buffer.Buffer.isBuffer(arg) || arg instanceof Uint8Array; - }, - - /** - * Returns a zero-filled byte array - * - * @param {number} bytes - * @return {Buffer} - */ - emptyBuffer: function emptyBuffer(bytes) { - $.checkArgumentType(bytes, 'number', 'bytes'); - var result = new buffer.Buffer(bytes); - for (var i = 0; i < bytes; i++) { - result.write('\0', i); - } - return result; - }, - - /** - * Concatenates a buffer - * - * Shortcut for buffer.Buffer.concat - */ - concat: buffer.Buffer.concat, - - equals: equals, - equal: equals, - - /** - * Transforms a number from 0 to 255 into a Buffer of size 1 with that value - * - * @param {number} integer - * @return {Buffer} - */ - integerAsSingleByteBuffer: function integerAsSingleByteBuffer(integer) { - $.checkArgumentType(integer, 'number', 'integer'); - return new buffer.Buffer([integer & 0xff]); - }, - - /** - * Transform a 4-byte integer into a Buffer of length 4. - * - * @param {number} integer - * @return {Buffer} - */ - integerAsBuffer: function integerAsBuffer(integer) { - $.checkArgumentType(integer, 'number', 'integer'); - var bytes = []; - bytes.push((integer >> 24) & 0xff); - bytes.push((integer >> 16) & 0xff); - bytes.push((integer >> 8) & 0xff); - bytes.push(integer & 0xff); - return new Buffer(bytes); - }, - - /** - * Transform the first 4 values of a Buffer into a number, in little endian encoding - * - * @param {Buffer} buffer - * @return {number} - */ - integerFromBuffer: function integerFromBuffer(buffer) { - $.checkArgumentType(buffer, 'Buffer', 'buffer'); - return buffer[0] << 24 | buffer[1] << 16 | buffer[2] << 8 | buffer[3]; - }, - - /** - * Transforms the first byte of an array into a number ranging from -128 to 127 - * @param {Buffer} buffer - * @return {number} - */ - integerFromSingleByteBuffer: function integerFromBuffer(buffer) { - $.checkArgumentType(buffer, 'Buffer', 'buffer'); - return buffer[0]; - }, - - /** - * Transforms a buffer into a string with a number in hexa representation - * - * Shorthand for buffer.toString('hex') - * - * @param {Buffer} buffer - * @return {string} - */ - bufferToHex: function bufferToHex(buffer) { - $.checkArgumentType(buffer, 'Buffer', 'buffer'); - return buffer.toString('hex'); - }, - - /** - * Reverse a buffer - * @param {Buffer} param - * @return {Buffer} - */ - reverse: function reverse(param) { - $.checkArgumentType(param, 'Buffer', 'param'); - var ret = new buffer.Buffer(param.length); - for (var i = 0; i < param.length; i++) { - ret[i] = param[param.length - i - 1]; - } - return ret; - }, - - /** - * Transforms an hexa encoded string into a Buffer with binary values - * - * Shorthand for Buffer(string, 'hex') - * - * @param {string} string - * @return {Buffer} - */ - hexToBuffer: function hexToBuffer(string) { - assert(js.isHexa(string)); - return new buffer.Buffer(string, 'hex'); - } -}; - -module.exports.NULL_HASH = module.exports.fill(new Buffer(32), 0); -module.exports.EMPTY_BUFFER = new Buffer(0); - -}).call(this,require("buffer").Buffer) -},{"./js":70,"./preconditions":71,"assert":194,"buffer":209}],70:[function(require,module,exports){ -'use strict'; - -var _ = require('lodash'); - -/** - * Determines whether a string contains only hexadecimal values - * - * @name JSUtil.isHexa - * @param {string} value - * @return {boolean} true if the string is the hexa representation of a number - */ -var isHexa = function isHexa(value) { - if (!_.isString(value)) { - return false; - } - return /^[0-9a-fA-F]+$/.test(value); -}; - -/** - * @namespace JSUtil - */ -module.exports = { - /** - * Test if an argument is a valid JSON object. If it is, returns a truthy - * value (the json object decoded), so no double JSON.parse call is necessary - * - * @param {string} arg - * @return {Object|boolean} false if the argument is not a JSON string. - */ - isValidJSON: function isValidJSON(arg) { - var parsed; - if (!_.isString(arg)) { - return false; - } - try { - parsed = JSON.parse(arg); - } catch (e) { - return false; - } - if (typeof(parsed) === 'object') { - return true; - } - return false; - }, - isHexa: isHexa, - isHexaString: isHexa, - - /** - * Clone an array - */ - cloneArray: function(array) { - return [].concat(array); - }, - - /** - * Define immutable properties on a target object - * - * @param {Object} target - An object to be extended - * @param {Object} values - An object of properties - * @return {Object} The target object - */ - defineImmutable: function defineImmutable(target, values){ - Object.keys(values).forEach(function(key){ - Object.defineProperty(target, key, { - configurable: false, - enumerable: true, - value: values[key] - }); - }); - return target; - } -}; - -},{"lodash":95}],71:[function(require,module,exports){ -'use strict'; - -var errors = require('../errors'); -var _ = require('lodash'); - -module.exports = { - checkState: function(condition, message) { - if (!condition) { - throw new errors.InvalidState(message); - } - }, - checkArgument: function(condition, argumentName, message, docsPath) { - if (!condition) { - throw new errors.InvalidArgument(argumentName, message, docsPath); - } - }, - checkArgumentType: function(argument, type, argumentName) { - argumentName = argumentName || '(unknown name)'; - if (_.isString(type)) { - if (type === 'Buffer') { - var BufferUtil = require('./buffer'); - if (!BufferUtil.isBuffer(argument)) { - throw new errors.InvalidArgumentType(argument, type, argumentName); - } - } else if (typeof argument !== type) { - throw new errors.InvalidArgumentType(argument, type, argumentName); - } - } else { - if (!(argument instanceof type)) { - throw new errors.InvalidArgumentType(argument, type.name, argumentName); - } - } - } -}; - -},{"../errors":45,"./buffer":69,"lodash":95}],72:[function(require,module,exports){ -// Utils - -function assert(val, msg) { - if (!val) - throw new Error(msg || 'Assertion failed'); -} - -function assertEqual(l, r, msg) { - if (l != r) - throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); -} - -// Could use `inherits` module, but don't want to move from single file -// architecture yet. -function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor -} - -// BN - -function BN(number, base, endian) { - // May be `new BN(bn)` ? - if (number !== null && - typeof number === 'object' && - Array.isArray(number.words)) { - return number; - } - - this.sign = false; - this.words = null; - this.length = 0; - - // Reduction context - this.red = null; - - if (base === 'le' || base === 'be') { - endian = base; - base = 10; - } - - if (number !== null) - this._init(number || 0, base || 10, endian || 'be'); -} -if (typeof module === 'object') - module.exports = BN; - -BN.BN = BN; -BN.wordSize = 26; - -BN.prototype._init = function init(number, base, endian) { - if (typeof number === 'number') { - if (number < 0) { - this.sign = true; - number = -number; - } - if (number < 0x4000000) { - this.words = [ number & 0x3ffffff ]; - this.length = 1; - } else { - this.words = [ - number & 0x3ffffff, - (number / 0x4000000) & 0x3ffffff - ]; - this.length = 2; - } - return; - } else if (typeof number === 'object') { - return this._initArray(number, base, endian); - } - if (base === 'hex') - base = 16; - assert(base === (base | 0) && base >= 2 && base <= 36); - - number = number.toString().replace(/\s+/g, ''); - var start = 0; - if (number[0] === '-') - start++; - - if (base === 16) - this._parseHex(number, start); - else - this._parseBase(number, base, start); - - if (number[0] === '-') - this.sign = true; - - this.strip(); -}; - -BN.prototype._initArray = function _initArray(number, base, endian) { - // Perhaps a Uint8Array - assert(typeof number.length === 'number'); - this.length = Math.ceil(number.length / 3); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - this.words[i] = 0; - - var off = 0; - if (endian === 'be') { - for (var i = number.length - 1, j = 0; i >= 0; i -= 3) { - var w = number[i] | (number[i - 1] << 8) | (number[i - 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } else if (endian === 'le') { - for (var i = 0, j = 0; i < number.length; i += 3) { - var w = number[i] | (number[i + 1] << 8) | (number[i + 2] << 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] = (w >>> (26 - off)) & 0x3ffffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - } - return this.strip(); -}; - -BN.prototype._parseHex = function parseHex(number, start) { - // Create possibly bigger array to ensure that it fits the number - this.length = Math.ceil((number.length - start) / 6); - this.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - this.words[i] = 0; - - // Scan 24-bit chunks and add them to the number - var off = 0; - for (var i = number.length - 6, j = 0; i >= start; i -= 6) { - var w = parseInt(number.slice(i, i + 6), 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - off += 24; - if (off >= 26) { - off -= 26; - j++; - } - } - if (i + 6 !== start) { - var w = parseInt(number.slice(start, i + 6), 16); - this.words[j] |= (w << off) & 0x3ffffff; - this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; - } - this.strip(); -}; - -BN.prototype._parseBase = function parseBase(number, base, start) { - // Initialize as zero - this.words = [ 0 ]; - this.length = 1; - - var word = 0; - var q = 1; - var p = 0; - var bigQ = null; - for (var i = start; i < number.length; i++) { - var digit; - var ch = number[i]; - if (base === 10 || ch <= '9') - digit = ch | 0; - else if (ch >= 'a') - digit = ch.charCodeAt(0) - 97 + 10; - else - digit = ch.charCodeAt(0) - 65 + 10; - word *= base; - word += digit; - q *= base; - p++; - - if (q > 0xfffff) { - assert(q <= 0x3ffffff); - if (!bigQ) - bigQ = new BN(q); - this.mul(bigQ).copy(this); - this.iadd(new BN(word)); - word = 0; - q = 1; - p = 0; - } - } - if (p !== 0) { - this.mul(new BN(q)).copy(this); - this.iadd(new BN(word)); - } -}; - -BN.prototype.copy = function copy(dest) { - dest.words = new Array(this.length); - for (var i = 0; i < this.length; i++) - dest.words[i] = this.words[i]; - dest.length = this.length; - dest.sign = this.sign; - dest.red = this.red; -}; - -BN.prototype.clone = function clone() { - var r = new BN(null); - this.copy(r); - return r; -}; - -// Remove leading `0` from `this` -BN.prototype.strip = function strip() { - while (this.length > 1 && this.words[this.length - 1] === 0) - this.length--; - return this._normSign(); -}; - -BN.prototype._normSign = function _normSign() { - // -0 = 0 - if (this.length === 1 && this.words[0] === 0) - this.sign = false; - return this; -}; - -BN.prototype.inspect = function inspect() { - return (this.red ? ''; -}; - -/* - -var zeros = []; -var groupSizes = []; -var groupBases = []; - -var s = ''; -var i = -1; -while (++i < BN.wordSize) { - zeros[i] = s; - s += '0'; -} -groupSizes[0] = 0; -groupSizes[1] = 0; -groupBases[0] = 0; -groupBases[1] = 0; -var base = 2 - 1; -while (++base < 36 + 1) { - var groupSize = 0; - var groupBase = 1; - // TODO: <= - while (groupBase < (1 << BN.wordSize) / base) { - groupBase *= base; - groupSize += 1; - } - groupSizes[base] = groupSize; - groupBases[base] = groupBase; -} - -*/ - -var zeros = [ - '', - '0', - '00', - '000', - '0000', - '00000', - '000000', - '0000000', - '00000000', - '000000000', - '0000000000', - '00000000000', - '000000000000', - '0000000000000', - '00000000000000', - '000000000000000', - '0000000000000000', - '00000000000000000', - '000000000000000000', - '0000000000000000000', - '00000000000000000000', - '000000000000000000000', - '0000000000000000000000', - '00000000000000000000000', - '000000000000000000000000', - '0000000000000000000000000' -]; - -var groupSizes = [ - 0, 0, - 25, 16, 12, 11, 10, 9, 8, - 8, 7, 7, 7, 7, 6, 6, - 6, 6, 6, 6, 6, 5, 5, - 5, 5, 5, 5, 5, 5, 5, - 5, 5, 5, 5, 5, 5, 5 -]; - -var groupBases = [ - 0, 0, - 33554432, 43046721, 16777216, 48828125, 60466176, 40353607, 16777216, - 43046721, 10000000, 19487171, 35831808, 62748517, 7529536, 11390625, - 16777216, 24137569, 34012224, 47045881, 64000000, 4084101, 5153632, - 6436343, 7962624, 9765625, 11881376, 14348907, 17210368, 20511149, - 24300000, 28629151, 33554432, 39135393, 45435424, 52521875, 60466176 -]; - -BN.prototype.toString = function toString(base, padding) { - base = base || 10; - if (base === 16 || base === 'hex') { - var out = ''; - var off = 0; - var padding = padding | 0 || 1; - var carry = 0; - for (var i = 0; i < this.length; i++) { - var w = this.words[i]; - var word = (((w << off) | carry) & 0xffffff).toString(16); - carry = (w >>> (24 - off)) & 0xffffff; - if (carry !== 0 || i !== this.length - 1) - out = zeros[6 - word.length] + word + out; - else - out = word + out; - off += 2; - if (off >= 26) { - off -= 26; - i--; - } - } - if (carry !== 0) - out = carry.toString(16) + out; - while (out.length % padding !== 0) - out = '0' + out; - if (this.sign) - out = '-' + out; - return out; - } else if (base === (base | 0) && base >= 2 && base <= 36) { - // var groupSize = Math.floor(BN.wordSize * Math.LN2 / Math.log(base)); - var groupSize = groupSizes[base]; - // var groupBase = Math.pow(base, groupSize); - var groupBase = groupBases[base]; - var out = ''; - var c = this.clone(); - c.sign = false; - while (c.cmpn(0) !== 0) { - var r = c.modn(groupBase).toString(base); - c = c.idivn(groupBase); - - if (c.cmpn(0) !== 0) - out = zeros[groupSize - r.length] + r + out; - else - out = r + out; - } - if (this.cmpn(0) === 0) - out = '0' + out; - if (this.sign) - out = '-' + out; - return out; - } else { - assert(false, 'Base should be between 2 and 36'); - } -}; - -BN.prototype.toJSON = function toJSON() { - return this.toString(16); -}; - -BN.prototype.toArray = function toArray() { - this.strip(); - var res = new Array(this.byteLength()); - res[0] = 0; - - var q = this.clone(); - for (var i = 0; q.cmpn(0) !== 0; i++) { - var b = q.andln(0xff); - q.ishrn(8); - - // Assume big-endian - res[res.length - i - 1] = b; - } - - return res; -}; - -/* -function genCountBits(bits) { - var arr = []; - - for (var i = bits - 1; i >= 0; i--) { - var bit = '0x' + (1 << i).toString(16); - arr.push('w >= ' + bit + ' ? ' + (i + 1)); - } - - return new Function('w', 'return ' + arr.join(' :\n') + ' :\n0;'); -}; - -BN.prototype._countBits = genCountBits(26); -*/ - -// Sadly chrome apps could not contain `new Function()` calls -BN.prototype._countBits = function _countBits(w) { - return w >= 0x2000000 ? 26 : - w >= 0x1000000 ? 25 : - w >= 0x800000 ? 24 : - w >= 0x400000 ? 23 : - w >= 0x200000 ? 22 : - w >= 0x100000 ? 21 : - w >= 0x80000 ? 20 : - w >= 0x40000 ? 19 : - w >= 0x20000 ? 18 : - w >= 0x10000 ? 17 : - w >= 0x8000 ? 16 : - w >= 0x4000 ? 15 : - w >= 0x2000 ? 14 : - w >= 0x1000 ? 13 : - w >= 0x800 ? 12 : - w >= 0x400 ? 11 : - w >= 0x200 ? 10 : - w >= 0x100 ? 9 : - w >= 0x80 ? 8 : - w >= 0x40 ? 7 : - w >= 0x20 ? 6 : - w >= 0x10 ? 5 : - w >= 0x8 ? 4 : - w >= 0x4 ? 3 : - w >= 0x2 ? 2 : - w >= 0x1 ? 1 : - 0; -}; - -// Return number of used bits in a BN -BN.prototype.bitLength = function bitLength() { - var hi = 0; - var w = this.words[this.length - 1]; - var hi = this._countBits(w); - return (this.length - 1) * 26 + hi; -}; - -BN.prototype.byteLength = function byteLength() { - var hi = 0; - var w = this.words[this.length - 1]; - return Math.ceil(this.bitLength() / 8); -}; - -// Return negative clone of `this` -BN.prototype.neg = function neg() { - if (this.cmpn(0) === 0) - return this.clone(); - - var r = this.clone(); - r.sign = !this.sign; - return r; -}; - -// Add `num` to `this` in-place -BN.prototype.iadd = function iadd(num) { - // negative + positive - if (this.sign && !num.sign) { - this.sign = false; - var r = this.isub(num); - this.sign = !this.sign; - return this._normSign(); - - // positive + negative - } else if (!this.sign && num.sign) { - num.sign = false; - var r = this.isub(num); - num.sign = true; - return r._normSign(); - } - - // a.length > b.length - var a; - var b; - if (this.length > num.length) { - a = this; - b = num; - } else { - a = num; - b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - var r = a.words[i] + b.words[i] + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - for (; carry !== 0 && i < a.length; i++) { - var r = a.words[i] + carry; - this.words[i] = r & 0x3ffffff; - carry = r >>> 26; - } - - this.length = a.length; - if (carry !== 0) { - this.words[this.length] = carry; - this.length++; - // Copy the rest of the words - } else if (a !== this) { - for (; i < a.length; i++) - this.words[i] = a.words[i]; - } - - return this; -}; - -// Add `num` to `this` -BN.prototype.add = function add(num) { - if (num.sign && !this.sign) { - num.sign = false; - var res = this.sub(num); - num.sign = true; - return res; - } else if (!num.sign && this.sign) { - this.sign = false; - var res = num.sub(this); - this.sign = true; - return res; - } - - if (this.length > num.length) - return this.clone().iadd(num); - else - return num.clone().iadd(this); -}; - -// Subtract `num` from `this` in-place -BN.prototype.isub = function isub(num) { - // this - (-num) = this + num - if (num.sign) { - num.sign = false; - var r = this.iadd(num); - num.sign = true; - return r._normSign(); - - // -this - num = -(this + num) - } else if (this.sign) { - this.sign = false; - this.iadd(num); - this.sign = true; - return this._normSign(); - } - - // At this point both numbers are positive - var cmp = this.cmp(num); - - // Optimization - zeroify - if (cmp === 0) { - this.sign = false; - this.length = 1; - this.words[0] = 0; - return this; - } - - // a > b - if (cmp > 0) { - var a = this; - var b = num; - } else { - var a = num; - var b = this; - } - - var carry = 0; - for (var i = 0; i < b.length; i++) { - var r = a.words[i] - b.words[i] - carry; - if (r < 0) { - r += 0x4000000; - carry = 1; - } else { - carry = 0; - } - this.words[i] = r; - } - for (; carry !== 0 && i < a.length; i++) { - var r = a.words[i] - carry; - if (r < 0) { - r += 0x4000000; - carry = 1; - } else { - carry = 0; - } - this.words[i] = r; - } - - // Copy rest of the words - if (carry === 0 && i < a.length && a !== this) - for (; i < a.length; i++) - this.words[i] = a.words[i]; - this.length = Math.max(this.length, i); - - if (a !== this) - this.sign = true; - - return this.strip(); -}; - -// Subtract `num` from `this` -BN.prototype.sub = function sub(num) { - return this.clone().isub(num); -}; - -/* -// NOTE: This could be potentionally used to generate loop-less multiplications -function _genCombMulTo(alen, blen) { - var len = alen + blen - 1; - var src = [ - 'var a = this.words, b = num.words, o = out.words, c = 0, w, ' + - 'mask = 0x3ffffff, shift = 0x4000000;', - 'out.length = ' + len + ';' - ]; - for (var k = 0; k < len; k++) { - var minJ = Math.max(0, k - alen + 1); - var maxJ = Math.min(k, blen - 1); - - for (var j = minJ; j <= maxJ; j++) { - var i = k - j; - var mul = 'a[' + i + '] * b[' + j + ']'; - - if (j === minJ) { - src.push('w = ' + mul + ' + c;'); - src.push('c = (w / shift) | 0;'); - } else { - src.push('w += ' + mul + ';'); - src.push('c += (w / shift) | 0;'); - } - src.push('w &= mask;'); - } - src.push('o[' + k + '] = w;'); - } - src.push('if (c !== 0) {', - ' o[' + k + '] = c;', - ' out.length++;', - '}', - 'return out;'); - - return src.join('\n'); -} -*/ - -BN.prototype._smallMulTo = function _smallMulTo(num, out) { - out.sign = num.sign !== this.sign; - out.length = this.length + num.length; - - var carry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = carry >>> 26; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - } - out.words[k] = rword; - carry = ncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); -}; - -BN.prototype._bigMulTo = function _bigMulTo(num, out) { - out.sign = num.sign !== this.sign; - out.length = this.length + num.length; - - var carry = 0; - var hncarry = 0; - for (var k = 0; k < out.length - 1; k++) { - // Sum all words with the same `i + j = k` and accumulate `ncarry`, - // note that ncarry could be >= 0x3ffffff - var ncarry = hncarry; - hncarry = 0; - var rword = carry & 0x3ffffff; - var maxJ = Math.min(k, num.length - 1); - for (var j = Math.max(0, k - this.length + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i] | 0; - var b = num.words[j] | 0; - var r = a * b; - - var lo = r & 0x3ffffff; - ncarry = (ncarry + ((r / 0x4000000) | 0)) | 0; - lo = (lo + rword) | 0; - rword = lo & 0x3ffffff; - ncarry = (ncarry + (lo >>> 26)) | 0; - - hncarry += ncarry >>> 26; - ncarry &= 0x3ffffff; - } - out.words[k] = rword; - carry = ncarry; - ncarry = hncarry; - } - if (carry !== 0) { - out.words[k] = carry; - } else { - out.length--; - } - - return out.strip(); -}; - -BN.prototype.mulTo = function mulTo(num, out) { - var res; - if (this.length + num.length < 63) - res = this._smallMulTo(num, out); - else - res = this._bigMulTo(num, out); - return res; -}; - -// Multiply `this` by `num` -BN.prototype.mul = function mul(num) { - var out = new BN(null); - out.words = new Array(this.length + num.length); - return this.mulTo(num, out); -}; - -// In-place Multiplication -BN.prototype.imul = function imul(num) { - if (this.cmpn(0) === 0 || num.cmpn(0) === 0) { - this.words[0] = 0; - this.length = 1; - return this; - } - - var tlen = this.length; - var nlen = num.length; - - this.sign = num.sign !== this.sign; - this.length = this.length + num.length; - this.words[this.length - 1] = 0; - - var lastCarry = 0; - for (var k = this.length - 2; k >= 0; k--) { - // Sum all words with the same `i + j = k` and accumulate `carry`, - // note that carry could be >= 0x3ffffff - var carry = 0; - var rword = 0; - var maxJ = Math.min(k, nlen - 1); - for (var j = Math.max(0, k - tlen + 1); j <= maxJ; j++) { - var i = k - j; - var a = this.words[i]; - var b = num.words[j]; - var r = a * b; - - var lo = r & 0x3ffffff; - carry += (r / 0x4000000) | 0; - lo += rword; - rword = lo & 0x3ffffff; - carry += lo >>> 26; - } - this.words[k] = rword; - this.words[k + 1] += carry; - carry = 0; - } - - // Propagate overflows - var carry = 0; - for (var i = 1; i < this.length; i++) { - var w = this.words[i] + carry; - this.words[i] = w & 0x3ffffff; - carry = w >>> 26; - } - - return this.strip(); -}; - -// `this` * `this` -BN.prototype.sqr = function sqr() { - return this.mul(this); -}; - -// `this` * `this` in-place -BN.prototype.isqr = function isqr() { - return this.mul(this); -}; - -// Shift-left in-place -BN.prototype.ishln = function ishln(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); - - var o = this.clone(); - if (r !== 0) { - var carry = 0; - for (var i = 0; i < this.length; i++) { - var newCarry = this.words[i] & carryMask; - var c = (this.words[i] - newCarry) << r; - this.words[i] = c | carry; - carry = newCarry >>> (26 - r); - } - if (carry) { - this.words[i] = carry; - this.length++; - } - } - - if (s !== 0) { - for (var i = this.length - 1; i >= 0; i--) - this.words[i + s] = this.words[i]; - for (var i = 0; i < s; i++) - this.words[i] = 0; - this.length += s; - } - - return this.strip(); -}; - -// Shift-right in-place -// NOTE: `hint` is a lowest bit before trailing zeroes -// NOTE: if `extended` is true - { lo: ..., hi: } object will be returned -BN.prototype.ishrn = function ishrn(bits, hint, extended) { - assert(typeof bits === 'number' && bits >= 0); - if (hint) - hint = (hint - (hint % 26)) / 26; - else - hint = 0; - - var r = bits % 26; - var s = Math.min((bits - r) / 26, this.length); - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - var maskedWords = extended; - - hint -= s; - hint = Math.max(0, hint); - - // Extended mode, copy masked part - if (maskedWords) { - for (var i = 0; i < s; i++) - maskedWords.words[i] = this.words[i]; - maskedWords.length = s; - } - - if (s === 0) { - // No-op, we should not move anything at all - } else if (this.length > s) { - this.length -= s; - for (var i = 0; i < this.length; i++) - this.words[i] = this.words[i + s]; - } else { - this.words[0] = 0; - this.length = 1; - } - - var carry = 0; - for (var i = this.length - 1; i >= 0 && (carry !== 0 || i >= hint); i--) { - var word = this.words[i]; - this.words[i] = (carry << (26 - r)) | (word >>> r); - carry = word & mask; - } - - // Push carried bits as a mask - if (maskedWords && carry !== 0) - maskedWords.words[maskedWords.length++] = carry; - - if (this.length === 0) { - this.words[0] = 0; - this.length = 1; - } - - this.strip(); - if (extended) - return { hi: this, lo: maskedWords }; - - return this; -}; - -// Shift-left -BN.prototype.shln = function shln(bits) { - return this.clone().ishln(bits); -}; - -// Shift-right -BN.prototype.shrn = function shrn(bits) { - return this.clone().ishrn(bits); -}; - -// Test if n bit is set -BN.prototype.testn = function testn(bit) { - assert(typeof bit === 'number' && bit >= 0); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - return false; - } - - // Check bit and return - var w = this.words[s]; - - return !!(w & q); -}; - -// Return only lowers bits of number (in-place) -BN.prototype.imaskn = function imaskn(bits) { - assert(typeof bits === 'number' && bits >= 0); - var r = bits % 26; - var s = (bits - r) / 26; - - assert(!this.sign, 'imaskn works only with positive numbers'); - - if (r !== 0) - s++; - this.length = Math.min(s, this.length); - - if (r !== 0) { - var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); - this.words[this.length - 1] &= mask; - } - - return this.strip(); -}; - -// Return only lowers bits of number -BN.prototype.maskn = function maskn(bits) { - return this.clone().imaskn(bits); -}; - -// Add plain number `num` to `this` -BN.prototype.iaddn = function iaddn(num) { - assert(typeof num === 'number'); - if (num < 0) - return this.isubn(-num); - - // Possible sign change - if (this.sign) { - if (this.length === 1 && this.words[0] < num) { - this.words[0] = num - this.words[0]; - this.sign = false; - return this; - } - - this.sign = false; - this.isubn(num); - this.sign = true; - return this; - } - this.words[0] += num; - - // Carry - for (var i = 0; i < this.length && this.words[i] >= 0x4000000; i++) { - this.words[i] -= 0x4000000; - if (i === this.length - 1) - this.words[i + 1] = 1; - else - this.words[i + 1]++; - } - this.length = Math.max(this.length, i + 1); - - return this; -}; - -// Subtract plain number `num` from `this` -BN.prototype.isubn = function isubn(num) { - assert(typeof num === 'number'); - if (num < 0) - return this.iaddn(-num); - - if (this.sign) { - this.sign = false; - this.iaddn(num); - this.sign = true; - return this; - } - - this.words[0] -= num; - - // Carry - for (var i = 0; i < this.length && this.words[i] < 0; i++) { - this.words[i] += 0x4000000; - this.words[i + 1] -= 1; - } - - return this.strip(); -}; - -BN.prototype.addn = function addn(num) { - return this.clone().iaddn(num); -}; - -BN.prototype.subn = function subn(num) { - return this.clone().isubn(num); -}; - -BN.prototype.iabs = function iabs() { - this.sign = false; - - return this -}; - -BN.prototype.abs = function abs() { - return this.clone().iabs(); -}; - -BN.prototype._wordDiv = function _wordDiv(num, mode) { - var shift = this.length - num.length; - - var a = this.clone(); - var b = num; - - var q = mode !== 'mod' && new BN(0); - var sign = false; - - // Approximate quotient at each step - while (a.length > b.length) { - // NOTE: a.length is always >= 2, because of the condition .div() - var hi = a.words[a.length - 1] * 0x4000000 + a.words[a.length - 2]; - var sq = (hi / b.words[b.length - 1]); - var sqhi = (sq / 0x4000000) | 0; - var sqlo = sq & 0x3ffffff; - sq = new BN(null); - sq.words = [ sqlo, sqhi ]; - sq.length = 2; - - // Collect quotient - var shift = (a.length - b.length - 1) * 26; - if (q) { - var t = sq.shln(shift); - if (a.sign) - q.isub(t); - else - q.iadd(t); - } - - sq = sq.mul(b).ishln(shift); - if (a.sign) - a.iadd(sq) - else - a.isub(sq); - } - // At this point a.length <= b.length - while (a.ucmp(b) >= 0) { - // NOTE: a.length is always >= 2, because of the condition above - var hi = a.words[a.length - 1]; - var sq = new BN((hi / b.words[b.length - 1]) | 0); - var shift = (a.length - b.length) * 26; - - if (q) { - var t = sq.shln(shift); - if (a.sign) - q.isub(t); - else - q.iadd(t); - } - - sq = sq.mul(b).ishln(shift); - - if (a.sign) - a.iadd(sq); - else - a.isub(sq); - } - - if (a.sign) { - if (q) - q.isubn(1); - a.iadd(b); - } - return { div: q ? q : null, mod: a }; -}; - -BN.prototype.divmod = function divmod(num, mode) { - assert(num.cmpn(0) !== 0); - - if (this.sign && !num.sign) { - var res = this.neg().divmod(num, mode); - var div; - var mod; - if (mode !== 'mod') - div = res.div.neg(); - if (mode !== 'div') - mod = res.mod.cmpn(0) === 0 ? res.mod : num.sub(res.mod); - return { - div: div, - mod: mod - }; - } else if (!this.sign && num.sign) { - var res = this.divmod(num.neg(), mode); - var div; - if (mode !== 'mod') - div = res.div.neg(); - return { div: div, mod: res.mod }; - } else if (this.sign && num.sign) { - return this.neg().divmod(num.neg(), mode); - } - - // Both numbers are positive at this point - - // Strip both numbers to approximate shift value - if (num.length > this.length || this.cmp(num) < 0) - return { div: new BN(0), mod: this }; - - // Very short reduction - if (num.length === 1) { - if (mode === 'div') - return { div: this.divn(num.words[0]), mod: null }; - else if (mode === 'mod') - return { div: null, mod: new BN(this.modn(num.words[0])) }; - return { - div: this.divn(num.words[0]), - mod: new BN(this.modn(num.words[0])) - }; - } - - return this._wordDiv(num, mode); -}; - -// Find `this` / `num` -BN.prototype.div = function div(num) { - return this.divmod(num, 'div').div; -}; - -// Find `this` % `num` -BN.prototype.mod = function mod(num) { - return this.divmod(num, 'mod').mod; -}; - -// Find Round(`this` / `num`) -BN.prototype.divRound = function divRound(num) { - var dm = this.divmod(num); - - // Fast case - exact division - if (dm.mod.cmpn(0) === 0) - return dm.div; - - var mod = dm.div.sign ? dm.mod.isub(num) : dm.mod; - - var half = num.shrn(1); - var r2 = num.andln(1); - var cmp = mod.cmp(half); - - // Round down - if (cmp < 0 || r2 === 1 && cmp === 0) - return dm.div; - - // Round up - return dm.div.sign ? dm.div.isubn(1) : dm.div.iaddn(1); -}; - -BN.prototype.modn = function modn(num) { - assert(num <= 0x3ffffff); - var p = (1 << 26) % num; - - var acc = 0; - for (var i = this.length - 1; i >= 0; i--) - acc = (p * acc + this.words[i]) % num; - - return acc; -}; - -// In-place division by number -BN.prototype.idivn = function idivn(num) { - assert(num <= 0x3ffffff); - - var carry = 0; - for (var i = this.length - 1; i >= 0; i--) { - var w = this.words[i] + carry * 0x4000000; - this.words[i] = (w / num) | 0; - carry = w % num; - } - - return this.strip(); -}; - -BN.prototype.divn = function divn(num) { - return this.clone().idivn(num); -}; - -BN.prototype._egcd = function _egcd(x1, p) { - assert(!p.sign); - assert(p.cmpn(0) !== 0); - - var a = this; - var b = p.clone(); - - if (a.sign) - a = a.mod(p); - else - a = a.clone(); - - var x2 = new BN(0); - while (b.isEven()) - b.ishrn(1); - var delta = b.clone(); - while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { - while (a.isEven()) { - a.ishrn(1); - if (x1.isEven()) - x1.ishrn(1); - else - x1.iadd(delta).ishrn(1); - } - while (b.isEven()) { - b.ishrn(1); - if (x2.isEven()) - x2.ishrn(1); - else - x2.iadd(delta).ishrn(1); - } - if (a.cmp(b) >= 0) { - a.isub(b); - x1.isub(x2); - } else { - b.isub(a); - x2.isub(x1); - } - } - if (a.cmpn(1) === 0) - return x1; - else - return x2; -}; - -BN.prototype.gcd = function gcd(num) { - if (this.cmpn(0) === 0) - return num.clone(); - if (num.cmpn(0) === 0) - return this.clone(); - - var a = this.clone(); - var b = num.clone(); - a.sign = false; - b.sign = false; - - // Remove common factor of two - for (var shift = 0; a.isEven() && b.isEven(); shift++) { - a.ishrn(1); - b.ishrn(1); - } - - while (a.isEven()) - a.ishrn(1); - - do { - while (b.isEven()) - b.ishrn(1); - - // Swap `a` and `b` to make `a` always bigger than `b` - if (a.cmp(b) < 0) { - var t = a; - a = b; - b = t; - } - a.isub(a.div(b).mul(b)); - } while (a.cmpn(0) !== 0 && b.cmpn(0) !== 0); - if (a.cmpn(0) === 0) - return b.ishln(shift); - else - return a.ishln(shift); -}; - -// Invert number in the field F(num) -BN.prototype.invm = function invm(num) { - return this._egcd(new BN(1), num).mod(num); -}; - -BN.prototype.isEven = function isEven(num) { - return (this.words[0] & 1) === 0; -}; - -BN.prototype.isOdd = function isOdd(num) { - return (this.words[0] & 1) === 1; -}; - -// And first word and num -BN.prototype.andln = function andln(num) { - return this.words[0] & num; -}; - -// Increment at the bit position in-line -BN.prototype.bincn = function bincn(bit) { - assert(typeof bit === 'number'); - var r = bit % 26; - var s = (bit - r) / 26; - var q = 1 << r; - - // Fast case: bit is much higher than all existing words - if (this.length <= s) { - for (var i = this.length; i < s + 1; i++) - this.words[i] = 0; - this.words[s] |= q; - this.length = s + 1; - return this; - } - - // Add bit and propagate, if needed - var carry = q; - for (var i = s; carry !== 0 && i < this.length; i++) { - var w = this.words[i]; - w += carry; - carry = w >>> 26; - w &= 0x3ffffff; - this.words[i] = w; - } - if (carry !== 0) { - this.words[i] = carry; - this.length++; - } - return this; -}; - -BN.prototype.cmpn = function cmpn(num) { - var sign = num < 0; - if (sign) - num = -num; - - if (this.sign && !sign) - return -1; - else if (!this.sign && sign) - return 1; - - num &= 0x3ffffff; - this.strip(); - - var res; - if (this.length > 1) { - res = 1; - } else { - var w = this.words[0]; - res = w === num ? 0 : w < num ? -1 : 1; - } - if (this.sign) - res = -res; - return res; -}; - -// Compare two numbers and return: -// 1 - if `this` > `num` -// 0 - if `this` == `num` -// -1 - if `this` < `num` -BN.prototype.cmp = function cmp(num) { - if (this.sign && !num.sign) - return -1; - else if (!this.sign && num.sign) - return 1; - - var res = this.ucmp(num); - if (this.sign) - return -res; - else - return res; -}; - -// Unsigned comparison -BN.prototype.ucmp = function ucmp(num) { - // At this point both numbers have the same sign - if (this.length > num.length) - return 1; - else if (this.length < num.length) - return -1; - - var res = 0; - for (var i = this.length - 1; i >= 0; i--) { - var a = this.words[i]; - var b = num.words[i]; - - if (a === b) - continue; - if (a < b) - res = -1; - else if (a > b) - res = 1; - break; - } - return res; -}; - -// -// A reduce context, could be using montgomery or something better, depending -// on the `m` itself. -// -BN.red = function red(num) { - return new Red(num); -}; - -BN.prototype.toRed = function toRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - assert(!this.sign, 'red works only with positives'); - return ctx.convertTo(this)._forceRed(ctx); -}; - -BN.prototype.fromRed = function fromRed() { - assert(this.red, 'fromRed works only with numbers in reduction context'); - return this.red.convertFrom(this); -}; - -BN.prototype._forceRed = function _forceRed(ctx) { - this.red = ctx; - return this; -}; - -BN.prototype.forceRed = function forceRed(ctx) { - assert(!this.red, 'Already a number in reduction context'); - return this._forceRed(ctx); -}; - -BN.prototype.redAdd = function redAdd(num) { - assert(this.red, 'redAdd works only with red numbers'); - return this.red.add(this, num); -}; - -BN.prototype.redIAdd = function redIAdd(num) { - assert(this.red, 'redIAdd works only with red numbers'); - return this.red.iadd(this, num); -}; - -BN.prototype.redSub = function redSub(num) { - assert(this.red, 'redSub works only with red numbers'); - return this.red.sub(this, num); -}; - -BN.prototype.redISub = function redISub(num) { - assert(this.red, 'redISub works only with red numbers'); - return this.red.isub(this, num); -}; - -BN.prototype.redShl = function redShl(num) { - assert(this.red, 'redShl works only with red numbers'); - return this.red.shl(this, num); -}; - -BN.prototype.redMul = function redMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.mul(this, num); -}; - -BN.prototype.redIMul = function redIMul(num) { - assert(this.red, 'redMul works only with red numbers'); - this.red._verify2(this, num); - return this.red.imul(this, num); -}; - -BN.prototype.redSqr = function redSqr() { - assert(this.red, 'redSqr works only with red numbers'); - this.red._verify1(this); - return this.red.sqr(this); -}; - -BN.prototype.redISqr = function redISqr() { - assert(this.red, 'redISqr works only with red numbers'); - this.red._verify1(this); - return this.red.isqr(this); -}; - -// Square root over p -BN.prototype.redSqrt = function redSqrt() { - assert(this.red, 'redSqrt works only with red numbers'); - this.red._verify1(this); - return this.red.sqrt(this); -}; - -BN.prototype.redInvm = function redInvm() { - assert(this.red, 'redInvm works only with red numbers'); - this.red._verify1(this); - return this.red.invm(this); -}; - -// Return negative clone of `this` % `red modulo` -BN.prototype.redNeg = function redNeg() { - assert(this.red, 'redNeg works only with red numbers'); - this.red._verify1(this); - return this.red.neg(this); -}; - -BN.prototype.redPow = function redPow(num) { - assert(this.red && !num.red, 'redPow(normalNum)'); - this.red._verify1(this); - return this.red.pow(this, num); -}; - -// Prime numbers with efficient reduction -var primes = { - k256: null, - p224: null, - p192: null, - p25519: null -}; - -// Pseudo-Mersenne prime -function MPrime(name, p) { - // P = 2 ^ N - K - this.name = name; - this.p = new BN(p, 16); - this.n = this.p.bitLength(); - this.k = new BN(1).ishln(this.n).isub(this.p); - - this.tmp = this._tmp(); -} - -MPrime.prototype._tmp = function _tmp() { - var tmp = new BN(null); - tmp.words = new Array(Math.ceil(this.n / 13)); - return tmp; -}; - -MPrime.prototype.ireduce = function ireduce(num) { - // Assumes that `num` is less than `P^2` - // num = HI * (2 ^ N - K) + HI * K + LO = HI * K + LO (mod P) - var r = num; - var rlen; - - do { - var pair = r.ishrn(this.n, 0, this.tmp); - r = this.imulK(pair.hi); - r = r.iadd(pair.lo); - rlen = r.bitLength(); - } while (rlen > this.n); - - var cmp = rlen < this.n ? -1 : r.cmp(this.p); - if (cmp === 0) { - r.words[0] = 0; - r.length = 1; - } else if (cmp > 0) { - r.isub(this.p); - } else { - r.strip(); - } - - return r; -}; - -MPrime.prototype.imulK = function imulK(num) { - return num.imul(this.k); -}; - -function K256() { - MPrime.call( - this, - 'k256', - 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f'); -} -inherits(K256, MPrime); - -K256.prototype.imulK = function imulK(num) { - // K = 0x1000003d1 = [ 0x40, 0x3d1 ] - num.words[num.length] = 0; - num.words[num.length + 1] = 0; - num.length += 2; - - var uhi = 0; - var hi = 0; - var lo = 0; - for (var i = 0; i < num.length; i++) { - var w = num.words[i]; - hi += w * 0x40; - lo += w * 0x3d1; - hi += (lo / 0x4000000) | 0; - uhi += (hi / 0x4000000) | 0; - hi &= 0x3ffffff; - lo &= 0x3ffffff; - - num.words[i] = lo; - - lo = hi; - hi = uhi; - uhi = 0; - } - - // Fast length reduction - if (num.words[num.length - 1] === 0) - num.length--; - if (num.words[num.length - 1] === 0) - num.length--; - return num; -}; - -function P224() { - MPrime.call( - this, - 'p224', - 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001'); -} -inherits(P224, MPrime); - -function P192() { - MPrime.call( - this, - 'p192', - 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff'); -} -inherits(P192, MPrime); - -function P25519() { - // 2 ^ 255 - 19 - MPrime.call( - this, - '25519', - '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed'); -} -inherits(P25519, MPrime); - -P25519.prototype.imulK = function imulK(num) { - // K = 0x13 - var carry = 0; - for (var i = 0; i < num.length; i++) { - var hi = num.words[i] * 0x13 + carry; - var lo = hi & 0x3ffffff; - hi >>>= 26; - - num.words[i] = lo; - carry = hi; - } - if (carry !== 0) - num.words[num.length++] = carry; - return num; -}; - -// Exported mostly for testing purposes, use plain name instead -BN._prime = function prime(name) { - // Cached version of prime - if (primes[name]) - return primes[name]; - - var prime; - if (name === 'k256') - prime = new K256(); - else if (name === 'p224') - prime = new P224(); - else if (name === 'p192') - prime = new P192(); - else if (name === 'p25519') - prime = new P25519(); - else - throw new Error('Unknown prime ' + name); - primes[name] = prime; - - return prime; -} - -// -// Base reduction engine -// -function Red(m) { - if (typeof m === 'string') { - var prime = BN._prime(m); - this.m = prime.p; - this.prime = prime; - } else { - this.m = m; - this.prime = null; - } -} - -Red.prototype._verify1 = function _verify1(a) { - assert(!a.sign, 'red works only with positives'); - assert(a.red, 'red works only with red numbers'); -}; - -Red.prototype._verify2 = function _verify2(a, b) { - assert(!a.sign && !b.sign, 'red works only with positives'); - assert(a.red && a.red === b.red, - 'red works only with red numbers'); -}; - -Red.prototype.imod = function imod(a) { - if (this.prime) - return this.prime.ireduce(a)._forceRed(this); - return a.mod(this.m)._forceRed(this); -}; - -Red.prototype.neg = function neg(a) { - var r = a.clone(); - r.sign = !r.sign; - return r.iadd(this.m)._forceRed(this); -}; - -Red.prototype.add = function add(a, b) { - this._verify2(a, b); - - var res = a.add(b); - if (res.cmp(this.m) >= 0) - res.isub(this.m); - return res._forceRed(this); -}; - -Red.prototype.iadd = function iadd(a, b) { - this._verify2(a, b); - - var res = a.iadd(b); - if (res.cmp(this.m) >= 0) - res.isub(this.m); - return res; -}; - -Red.prototype.sub = function sub(a, b) { - this._verify2(a, b); - - var res = a.sub(b); - if (res.cmpn(0) < 0) - res.iadd(this.m); - return res._forceRed(this); -}; - -Red.prototype.isub = function isub(a, b) { - this._verify2(a, b); - - var res = a.isub(b); - if (res.cmpn(0) < 0) - res.iadd(this.m); - return res; -}; - -Red.prototype.shl = function shl(a, num) { - this._verify1(a); - return this.imod(a.shln(num)); -}; - -Red.prototype.imul = function imul(a, b) { - this._verify2(a, b); - return this.imod(a.imul(b)); -}; - -Red.prototype.mul = function mul(a, b) { - this._verify2(a, b); - return this.imod(a.mul(b)); -}; - -Red.prototype.isqr = function isqr(a) { - return this.imul(a, a); -}; - -Red.prototype.sqr = function sqr(a) { - return this.mul(a, a); -}; - -Red.prototype.sqrt = function sqrt(a) { - if (a.cmpn(0) === 0) - return a.clone(); - - var mod3 = this.m.andln(3); - assert(mod3 % 2 === 1); - - // Fast case - if (mod3 === 3) { - var pow = this.m.add(new BN(1)).ishrn(2); - var r = this.pow(a, pow); - return r; - } - - // Tonelli-Shanks algorithm (Totally unoptimized and slow) - // - // Find Q and S, that Q * 2 ^ S = (P - 1) - var q = this.m.subn(1); - var s = 0; - while (q.cmpn(0) !== 0 && q.andln(1) === 0) { - s++; - q.ishrn(1); - } - assert(q.cmpn(0) !== 0); - - var one = new BN(1).toRed(this); - var nOne = one.redNeg(); - - // Find quadratic non-residue - // NOTE: Max is such because of generalized Riemann hypothesis. - var lpow = this.m.subn(1).ishrn(1); - var z = this.m.bitLength(); - z = new BN(2 * z * z).toRed(this); - while (this.pow(z, lpow).cmp(nOne) !== 0) - z.redIAdd(nOne); - - var c = this.pow(z, q); - var r = this.pow(a, q.addn(1).ishrn(1)); - var t = this.pow(a, q); - var m = s; - while (t.cmp(one) !== 0) { - var tmp = t; - for (var i = 0; tmp.cmp(one) !== 0; i++) - tmp = tmp.redSqr(); - assert(i < m); - var b = this.pow(c, new BN(1).ishln(m - i - 1)); - - r = r.redMul(b); - c = b.redSqr(); - t = t.redMul(c); - m = i; - } - - return r; -}; - -Red.prototype.invm = function invm(a) { - var inv = a._egcd(new BN(1), this.m); - if (inv.sign) { - inv.sign = false; - return this.imod(inv).redNeg(); - } else { - return this.imod(inv); - } -}; - -Red.prototype.pow = function pow(a, num) { - var w = []; - var q = num.clone(); - while (q.cmpn(0) !== 0) { - w.push(q.andln(1)); - q.ishrn(1); - } - - // Skip leading zeroes - var res = a; - for (var i = 0; i < w.length; i++, res = this.sqr(res)) - if (w[i] !== 0) - break; - - if (++i < w.length) { - for (var q = this.sqr(res); i < w.length; i++, q = this.sqr(q)) { - if (w[i] === 0) - continue; - res = this.mul(res, q); - } - } - - return res; -}; - -Red.prototype.convertTo = function convertTo(num) { - return num.clone(); -}; - -Red.prototype.convertFrom = function convertFrom(num) { - var res = num.clone(); - res.red = null; - return res; -}; - -// -// Montgomery method engine -// - -BN.mont = function mont(num) { - return new Mont(num); -}; - -function Mont(m) { - Red.call(this, m); - - this.shift = this.m.bitLength(); - if (this.shift % 26 !== 0) - this.shift += 26 - (this.shift % 26); - this.r = new BN(1).ishln(this.shift); - this.r2 = this.imod(this.r.sqr()); - this.rinv = this.r.invm(this.m); - - // TODO(indutny): simplify it - this.minv = this.rinv.mul(this.r) - .sub(new BN(1)) - .div(this.m) - .neg() - .mod(this.r); -} -inherits(Mont, Red); - -Mont.prototype.convertTo = function convertTo(num) { - return this.imod(num.shln(this.shift)); -}; - -Mont.prototype.convertFrom = function convertFrom(num) { - var r = this.imod(num.mul(this.rinv)); - r.red = null; - return r; -}; - -Mont.prototype.imul = function imul(a, b) { - if (a.cmpn(0) === 0 || b.cmpn(0) === 0) { - a.words[0] = 0; - a.length = 1; - return a; - } - - var t = a.imul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).ishrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) - res = u.isub(this.m); - else if (u.cmpn(0) < 0) - res = u.iadd(this.m); - - return res._forceRed(this); -}; - -Mont.prototype.mul = function mul(a, b) { - if (a.cmpn(0) === 0 || b.cmpn(0) === 0) - return new BN(0)._forceRed(this); - - var t = a.mul(b); - var c = t.maskn(this.shift).mul(this.minv).imaskn(this.shift).mul(this.m); - var u = t.isub(c).ishrn(this.shift); - var res = u; - if (u.cmp(this.m) >= 0) - res = u.isub(this.m); - else if (u.cmpn(0) < 0) - res = u.iadd(this.m); - - return res._forceRed(this); -}; - -Mont.prototype.invm = function invm(a) { - // (AR)^-1 * R^2 = (A^-1 * R^-1) * R^2 = A^-1 * R - var res = this.imod(a.invm(this.m).mul(this.r2)); - return res._forceRed(this); -}; - -},{}],73:[function(require,module,exports){ -// Base58 encoding/decoding -// Originally written by Mike Hearn for BitcoinJ -// Copyright (c) 2011 Google Inc -// Ported to JavaScript by Stefan Thomas -// Merged Buffer refactorings from base58-native by Stephen Pair -// Copyright (c) 2013 BitPay Inc - -var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' -var ALPHABET_MAP = {} -for(var i = 0; i < ALPHABET.length; i++) { - ALPHABET_MAP[ALPHABET.charAt(i)] = i -} -var BASE = 58 - -function encode(buffer) { - if (buffer.length === 0) return '' - - var i, j, digits = [0] - for (i = 0; i < buffer.length; i++) { - for (j = 0; j < digits.length; j++) digits[j] <<= 8 - - digits[0] += buffer[i] - - var carry = 0 - for (j = 0; j < digits.length; ++j) { - digits[j] += carry - - carry = (digits[j] / BASE) | 0 - digits[j] %= BASE - } - - while (carry) { - digits.push(carry % BASE) - - carry = (carry / BASE) | 0 - } - } - - // deal with leading zeros - for (i = 0; buffer[i] === 0 && i < buffer.length - 1; i++) digits.push(0) - - return digits.reverse().map(function(digit) { return ALPHABET[digit] }).join('') -} - -function decode(string) { - if (string.length === 0) return [] - - var i, j, bytes = [0] - for (i = 0; i < string.length; i++) { - var c = string[i] - if (!(c in ALPHABET_MAP)) throw new Error('Non-base58 character') - - for (j = 0; j < bytes.length; j++) bytes[j] *= BASE - bytes[0] += ALPHABET_MAP[c] - - var carry = 0 - for (j = 0; j < bytes.length; ++j) { - bytes[j] += carry - - carry = bytes[j] >> 8 - bytes[j] &= 0xff - } - - while (carry) { - bytes.push(carry & 0xff) - - carry >>= 8 - } - } - - // deal with leading zeros - for (i = 0; string[i] === '1' && i < string.length - 1; i++) bytes.push(0) - - return bytes.reverse() -} - -module.exports = { - encode: encode, - decode: decode -} - -},{}],74:[function(require,module,exports){ -var elliptic = exports; - -elliptic.version = require('../package.json').version; -elliptic.utils = require('./elliptic/utils'); -elliptic.rand = require('brorand'); -elliptic.hmacDRBG = require('./elliptic/hmac-drbg'); -elliptic.curve = require('./elliptic/curve'); -elliptic.curves = require('./elliptic/curves'); - -// Protocols -elliptic.ec = require('./elliptic/ec'); - -},{"../package.json":87,"./elliptic/curve":77,"./elliptic/curves":80,"./elliptic/ec":81,"./elliptic/hmac-drbg":84,"./elliptic/utils":85,"brorand":86}],75:[function(require,module,exports){ -var assert = require('assert'); -var bn = require('bn.js'); -var elliptic = require('../../elliptic'); - -var getNAF = elliptic.utils.getNAF; -var getJSF = elliptic.utils.getJSF; - -function BaseCurve(type, conf) { - this.type = type; - this.p = new bn(conf.p, 16); - - // Use Montgomery, when there is no fast reduction for the prime - this.red = conf.prime ? bn.red(conf.prime) : bn.mont(this.p); - - // Useful for many curves - this.zero = new bn(0).toRed(this.red); - this.one = new bn(1).toRed(this.red); - this.two = new bn(2).toRed(this.red); - - // Curve configuration, optional - this.n = conf.n && new bn(conf.n, 16); - this.g = conf.g && this.pointFromJSON(conf.g, conf.gRed); - - // Temporary arrays - this._wnafT1 = new Array(4); - this._wnafT2 = new Array(4); - this._wnafT3 = new Array(4); - this._wnafT4 = new Array(4); -} -module.exports = BaseCurve; - -BaseCurve.prototype.point = function point() { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype.validate = function validate(point) { - throw new Error('Not implemented'); -}; - -BaseCurve.prototype._fixedNafMul = function _fixedNafMul(p, k) { - var doubles = p._getDoubles(); - - var naf = getNAF(k, 1); - var I = (1 << (doubles.step + 1)) - (doubles.step % 2 === 0 ? 2 : 1); - I /= 3; - - // Translate into more windowed form - var repr = []; - for (var j = 0; j < naf.length; j += doubles.step) { - var nafW = 0; - for (var k = j + doubles.step - 1; k >= j; k--) - nafW = (nafW << 1) + naf[k]; - repr.push(nafW); - } - - var a = this.jpoint(null, null, null); - var b = this.jpoint(null, null, null); - for (var i = I; i > 0; i--) { - for (var j = 0; j < repr.length; j++) { - var nafW = repr[j]; - if (nafW === i) - b = b.mixedAdd(doubles.points[j]); - else if (nafW === -i) - b = b.mixedAdd(doubles.points[j].neg()); - } - a = a.add(b); - } - return a.toP(); -}; - -BaseCurve.prototype._wnafMul = function _wnafMul(p, k) { - var w = 4; - - // Precompute window - var nafPoints = p._getNAFPoints(w); - w = nafPoints.wnd; - var wnd = nafPoints.points; - - // Get NAF form - var naf = getNAF(k, w); - - // Add `this`*(N+1) for every w-NAF index - var acc = this.jpoint(null, null, null); - for (var i = naf.length - 1; i >= 0; i--) { - // Count zeroes - for (var k = 0; i >= 0 && naf[i] === 0; i--) - k++; - if (i >= 0) - k++; - acc = acc.dblp(k); - - if (i < 0) - break; - var z = naf[i]; - assert(z !== 0); - if (p.type === 'affine') { - // J +- P - if (z > 0) - acc = acc.mixedAdd(wnd[(z - 1) >> 1]); - else - acc = acc.mixedAdd(wnd[(-z - 1) >> 1].neg()); - } else { - // J +- J - if (z > 0) - acc = acc.add(wnd[(z - 1) >> 1]); - else - acc = acc.add(wnd[(-z - 1) >> 1].neg()); - } - } - return p.type === 'affine' ? acc.toP() : acc; -}; - -BaseCurve.prototype._wnafMulAdd = function _wnafMulAdd(defW, - points, - coeffs, - len) { - var wndWidth = this._wnafT1; - var wnd = this._wnafT2; - var naf = this._wnafT3; - - // Fill all arrays - var max = 0; - for (var i = 0; i < len; i++) { - var p = points[i]; - var nafPoints = p._getNAFPoints(defW); - wndWidth[i] = nafPoints.wnd; - wnd[i] = nafPoints.points; - } - - // Comb small window NAFs - for (var i = len - 1; i >= 1; i -= 2) { - var a = i - 1; - var b = i; - if (wndWidth[a] !== 1 || wndWidth[b] !== 1) { - naf[a] = getNAF(coeffs[a], wndWidth[a]); - naf[b] = getNAF(coeffs[b], wndWidth[b]); - max = Math.max(naf[a].length, max); - max = Math.max(naf[b].length, max); - continue; - } - - var comb = [ - points[a], /* 1 */ - null, /* 3 */ - null, /* 5 */ - points[b] /* 7 */ - ]; - - // Try to avoid Projective points, if possible - if (points[a].y.cmp(points[b].y) === 0) { - comb[1] = points[a].add(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } else if (points[a].y.cmp(points[b].y.redNeg()) === 0) { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].add(points[b].neg()); - } else { - comb[1] = points[a].toJ().mixedAdd(points[b]); - comb[2] = points[a].toJ().mixedAdd(points[b].neg()); - } - - var index = [ - -3, /* -1 -1 */ - -1, /* -1 0 */ - -5, /* -1 1 */ - -7, /* 0 -1 */ - 0, /* 0 0 */ - 7, /* 0 1 */ - 5, /* 1 -1 */ - 1, /* 1 0 */ - 3 /* 1 1 */ - ]; - - var jsf = getJSF(coeffs[a], coeffs[b]); - max = Math.max(jsf[0].length, max); - naf[a] = new Array(max); - naf[b] = new Array(max); - for (var j = 0; j < max; j++) { - var ja = jsf[0][j] | 0; - var jb = jsf[1][j] | 0; - - naf[a][j] = index[(ja + 1) * 3 + (jb + 1)]; - naf[b][j] = 0; - wnd[a] = comb; - } - } - - var acc = this.jpoint(null, null, null); - var tmp = this._wnafT4; - for (var i = max; i >= 0; i--) { - var k = 0; - - while (i >= 0) { - var zero = true; - for (var j = 0; j < len; j++) { - tmp[j] = naf[j][i] | 0; - if (tmp[j] !== 0) - zero = false; - } - if (!zero) - break; - k++; - i--; - } - if (i >= 0) - k++; - acc = acc.dblp(k); - if (i < 0) - break; - - for (var j = 0; j < len; j++) { - var z = tmp[j]; - var p; - if (z === 0) - continue; - else if (z > 0) - p = wnd[j][(z - 1) >> 1]; - else if (z < 0) - p = wnd[j][(-z - 1) >> 1].neg(); - - if (p.type === 'affine') - acc = acc.mixedAdd(p); - else - acc = acc.add(p); - } - } - // Zeroify references - for (var i = 0; i < len; i++) - wnd[i] = null; - return acc.toP(); -}; - -BaseCurve.BasePoint = BasePoint; - -function BasePoint(curve, type) { - this.curve = curve; - this.type = type; - this.precomputed = null; -} - -BasePoint.prototype.validate = function validate() { - return this.curve.validate(this); -}; - -BasePoint.prototype.precompute = function precompute(power, _beta) { - if (this.precomputed) - return this; - - var precomputed = { - doubles: null, - naf: null, - beta: null - }; - precomputed.naf = this._getNAFPoints(8); - precomputed.doubles = this._getDoubles(4, power); - precomputed.beta = this._getBeta(); - this.precomputed = precomputed; - - return this; -}; - -BasePoint.prototype._getDoubles = function _getDoubles(step, power) { - if (this.precomputed && this.precomputed.doubles) - return this.precomputed.doubles; - - var doubles = [ this ]; - var acc = this; - for (var i = 0; i < power; i += step) { - for (var j = 0; j < step; j++) - acc = acc.dbl(); - doubles.push(acc); - } - return { - step: step, - points: doubles - }; -}; - -BasePoint.prototype._getNAFPoints = function _getNAFPoints(wnd) { - if (this.precomputed && this.precomputed.naf) - return this.precomputed.naf; - - var res = [ this ]; - var max = (1 << wnd) - 1; - var dbl = max === 1 ? null : this.dbl(); - for (var i = 1; i < max; i++) - res[i] = res[i - 1].add(dbl); - return { - wnd: wnd, - points: res - }; -}; - -BasePoint.prototype._getBeta = function _getBeta() { - return null; -}; - -BasePoint.prototype.dblp = function dblp(k) { - var r = this; - for (var i = 0; i < k; i++) - r = r.dbl(); - return r; -}; - -},{"../../elliptic":74,"assert":194,"bn.js":72}],76:[function(require,module,exports){ -var assert = require('assert'); -var curve = require('../curve'); -var elliptic = require('../../elliptic'); -var bn = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var getNAF = elliptic.utils.getNAF; - -function EdwardsCurve(conf) { - // NOTE: Important as we are creating point in Base.call() - this.twisted = conf.a != 1; - this.mOneA = this.twisted && conf.a == -1; - this.extended = this.mOneA; - - Base.call(this, 'mont', conf); - - this.a = new bn(conf.a, 16).mod(this.red.m).toRed(this.red); - this.c = new bn(conf.c, 16).toRed(this.red); - this.c2 = this.c.redSqr(); - this.d = new bn(conf.d, 16).toRed(this.red); - this.dd = this.d.redAdd(this.d); - - assert(!this.twisted || this.c.fromRed().cmpn(1) === 0); - this.oneC = conf.c == 1; -} -inherits(EdwardsCurve, Base); -module.exports = EdwardsCurve; - -EdwardsCurve.prototype._mulA = function _mulA(num) { - if (this.mOneA) - return num.redNeg(); - else - return this.a.redMul(num); -}; - -EdwardsCurve.prototype._mulC = function _mulC(num) { - if (this.oneC) - return num; - else - return this.c.redMul(num); -}; - -EdwardsCurve.prototype.point = function point(x, y, z, t) { - return new Point(this, x, y, z, t); -}; - -// Just for compatibility with Short curve -EdwardsCurve.prototype.jpoint = function jpoint(x, y, z, t) { - return this.point(x, y, z, t); -}; - -EdwardsCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -}; - -EdwardsCurve.prototype.pointFromX = function pointFromX(odd, x) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var x2 = x.redSqr(); - var rhs = this.c2.redSub(this.a.redMul(x2)); - var lhs = this.one.redSub(this.c2.redMul(this.d).redMul(x2)); - - var y = rhs.redMul(lhs.redInvm()).redSqrt(); - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y, curve.one); -}; - -EdwardsCurve.prototype.validate = function validate(point) { - if (point.isInfinity()) - return true; - - // Curve: A * X^2 + Y^2 = C^2 * (1 + D * X^2 * Y^2) - point.normalize(); - - var x2 = point.x.redSqr(); - var y2 = point.y.redSqr(); - var lhs = x2.redMul(this.a).redAdd(y2); - var rhs = this.c2.redMul(this.one.redAdd(this.d.redMul(x2).redMul(y2))); - - return lhs.cmp(rhs) === 0; -}; - -function Point(curve, x, y, z, t) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && y === null && z === null) { - this.x = this.curve.zero; - this.y = this.curve.one; - this.z = this.curve.one; - this.t = this.curve.zero; - this.zOne = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = z ? new bn(z, 16) : this.curve.one; - this.t = t && new bn(t, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - if (this.t && !this.t.red) - this.t = this.t.toRed(this.curve.red); - this.zOne = this.z === this.curve.one; - - // Use extended coordinates - if (this.curve.extended && !this.t) { - this.t = this.x.redMul(this.y); - if (!this.zOne) - this.t = this.t.redMul(this.z.redInvm()); - } - } -} -inherits(Point, Base.BasePoint); - -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1], obj[2]); -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.x.cmpn(0) === 0 && - this.y.cmp(this.z) === 0; -}; - -Point.prototype._extDbl = function _extDbl() { - // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#doubling-dbl-2008-hwcd - // 4M + 4S - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = 2 * Z1^2 - var c = this.z.redSqr(); - c = c.redIAdd(c); - // D = a * A - var d = this.curve._mulA(a); - // E = (X1 + Y1)^2 - A - B - var e = this.x.redAdd(this.y).redSqr().redISub(a).redISub(b); - // G = D + B - var g = d.redAdd(b); - // F = G - C - var f = g.redSub(c); - // H = D - B - var h = d.redSub(b); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point.prototype._projDbl = function _projDbl() { - // http://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#doubling-dbl-2008-bbjlp - // http://hyperelliptic.org/EFD/g1p/auto-edwards-projective.html#doubling-dbl-2007-bl - // and others - // Generally 3M + 4S or 2M + 4S - - // B = (X1 + Y1)^2 - var b = this.x.redAdd(this.y).redSqr(); - // C = X1^2 - var c = this.x.redSqr(); - // D = Y1^2 - var d = this.y.redSqr(); - - if (this.curve.twisted) { - // E = a * C - var e = this.curve._mulA(c); - // F = E + D - var f = e.redAdd(d); - if (this.zOne) { - // X3 = (B - C - D) * (F - 2) - var nx = b.redSub(c).redSub(d).redMul(f.redSub(this.curve.two)); - // Y3 = F * (E - D) - var ny = f.redMul(e.redSub(d)); - // Z3 = F^2 - 2 * F - var nz = f.redSqr().redSub(f).redSub(f); - } else { - // H = Z1^2 - var h = this.z.redSqr(); - // J = F - 2 * H - var j = f.redSub(h).redISub(h); - // X3 = (B-C-D)*J - var nx = b.redSub(c).redISub(d).redMul(j); - // Y3 = F * (E - D) - var ny = f.redMul(e.redSub(d)); - // Z3 = F * J - var nz = f.redMul(j); - } - } else { - // E = C + D - var e = c.redAdd(d); - // H = (c * Z1)^2 - var h = this.curve._mulC(redMul(this.z)).redSqr(); - // J = E - 2 * H - var j = e.redSub(h).redSub(h); - // X3 = c * (B - E) * J - var nx = this.curve._mulC(b.redISub(e)).redMul(j); - // Y3 = c * E * (C - D) - var ny = this.curve._mulC(e).redMul(c.redISub(d)); - // Z3 = E * J - var nz = e.redMul(j); - } - return this.curve.point(nx, ny, nz); -}; - -Point.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - // Double in extended coordinates - if (this.curve.extended) - return this._extDbl(); - else - return this._projDbl(); -}; - -Point.prototype._extAdd = function _extAdd(p) { - // http://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3 - // 8M - - // A = (Y1 - X1) * (Y2 - X2) - var a = this.y.redSub(this.x).redMul(p.y.redSub(p.x)); - // B = (Y1 + X1) * (Y2 + X2) - var b = this.y.redAdd(this.x).redMul(p.y.redAdd(p.x)); - // C = T1 * k * T2 - var c = this.t.redMul(this.curve.dd).redMul(p.t); - // D = Z1 * 2 * Z2 - var d = this.z.redMul(p.z.redAdd(p.z)); - // E = B - A - var e = b.redSub(a); - // F = D - C - var f = d.redSub(c); - // G = D + C - var g = d.redAdd(c); - // H = B + A - var h = b.redAdd(a); - // X3 = E * F - var nx = e.redMul(f); - // Y3 = G * H - var ny = g.redMul(h); - // T3 = E * H - var nt = e.redMul(h); - // Z3 = F * G - var nz = f.redMul(g); - return this.curve.point(nx, ny, nz, nt); -}; - -Point.prototype._projAdd = function _projAdd(p) { - // http://hyperelliptic.org/EFD/g1p/auto-twisted-projective.html#addition-add-2008-bbjlp - // http://hyperelliptic.org/EFD/g1p/auto-edwards-projective.html#addition-add-2007-bl - // 10M + 1S - - // A = Z1 * Z2 - var a = this.z.redMul(p.z); - // B = A^2 - var b = a.redSqr(); - // C = X1 * X2 - var c = this.x.redMul(p.x); - // D = Y1 * Y2 - var d = this.y.redMul(p.y); - // E = d * C * D - var e = this.curve.d.redMul(c).redMul(d); - // F = B - E - var f = b.redSub(e); - // G = B + E - var g = b.redAdd(e); - // X3 = A * F * ((X1 + Y1) * (X2 + Y2) - C - D) - var tmp = this.x.redAdd(this.y).redMul(p.x.redAdd(p.y)).redISub(c).redISub(d); - var nx = a.redMul(f).redMul(tmp); - if (this.curve.twisted) { - // Y3 = A * G * (D - a * C) - var ny = a.redMul(g).redMul(d.redSub(this.curve._mulA(c))); - // Z3 = F * G - var nz = f.redMul(g); - } else { - // Y3 = A * G * (D - C) - var ny = a.redMul(g).redMul(d.redSub(c)); - // Z3 = c * F * G - var nz = this.curve._mulC(f).redMul(g); - } - return this.curve.point(nx, ny, nz); -}; - -Point.prototype.add = function add(p) { - if (this.isInfinity()) - return p; - if (p.isInfinity()) - return this; - - if (this.curve.extended) - return this._extAdd(p); - else - return this._projAdd(p); -}; - -Point.prototype.mul = function mul(k) { - if (this.precomputed && this.precomputed.doubles) - return this.curve._fixedNafMul(this, k); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p, k2) { - return this.curve._wnafMulAdd(1, [ this, p ], [ k1, k2 ], 2); -}; - -Point.prototype.normalize = function normalize() { - if (this.zOne) - return this; - - // Normalize coordinates - var zi = this.z.redInvm(); - this.x = this.x.redMul(zi); - this.y = this.y.redMul(zi); - if (this.t) - this.t = this.t.redMul(zi); - this.z = this.curve.one; - this.zOne = true; - return this; -}; - -Point.prototype.neg = function neg() { - return this.curve.point(this.x.redNeg(), - this.y, - this.z, - this.t && this.t.redNeg()); -}; - -Point.prototype.getX = function getX() { - this.normalize(); - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - this.normalize(); - return this.y.fromRed(); -}; - -// Compatibility with BaseCurve -Point.prototype.toP = Point.prototype.normalize; -Point.prototype.mixedAdd = Point.prototype.add; - -},{"../../elliptic":74,"../curve":77,"assert":194,"bn.js":72,"inherits":94}],77:[function(require,module,exports){ -var curve = exports; - -curve.base = require('./base'); -curve.short = require('./short'); -curve.mont = require('./mont'); -curve.edwards = require('./edwards'); - -},{"./base":75,"./edwards":76,"./mont":78,"./short":79}],78:[function(require,module,exports){ -var assert = require('assert'); -var curve = require('../curve'); -var elliptic = require('../../elliptic'); -var bn = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var getNAF = elliptic.utils.getNAF; - -function MontCurve(conf) { - Base.call(this, 'mont', conf); - - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.i4 = new bn(4).toRed(this.red).redInvm(); - this.two = new bn(2).toRed(this.red); - this.a24 = this.i4.redMul(this.a.redAdd(this.two)); -} -inherits(MontCurve, Base); -module.exports = MontCurve; - -MontCurve.prototype.point = function point(x, z) { - return new Point(this, x, z); -}; - -MontCurve.prototype.pointFromJSON = function pointFromJSON(obj) { - return Point.fromJSON(this, obj); -} - -MontCurve.prototype.validate = function validate(point) { - var x = point.normalize().x; - var x2 = x.redSqr(); - var rhs = x2.redMul(x).redAdd(x2.redMul(this.a)).redAdd(x); - var y = rhs.redSqrt(); - - return y.redSqr().cmp(rhs) === 0; -}; - -function Point(curve, x, z) { - Base.BasePoint.call(this, curve, 'projective'); - if (x === null && z === null) { - this.x = this.curve.one; - this.z = this.curve.zero; - } else { - this.x = new bn(x, 16); - this.z = new bn(z, 16); - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - } -} -inherits(Point, Base.BasePoint); - -Point.prototype.precompute = function precompute() { - // No-op -}; - -Point.fromJSON = function fromJSON(curve, obj) { - return new Point(curve, obj[0], obj[1] || curve.one); -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -Point.prototype.dbl = function dbl() { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#doubling-dbl-1987-m-3 - // 2M + 2S + 4A - - // A = X1 + Z1 - var a = this.x.redAdd(this.z); - // AA = A^2 - var aa = a.redSqr(); - // B = X1 - Z1 - var b = this.x.redSub(this.z); - // BB = B^2 - var bb = b.redSqr(); - // C = AA - BB - var c = aa.redSub(bb); - // X3 = AA * BB - var nx = aa.redMul(bb); - // Z3 = C * (BB + A24 * C) - var nz = c.redMul(bb.redAdd(this.curve.a24.redMul(c))); - return this.curve.point(nx, nz); -}; - -Point.prototype.add = function add(p) { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.diffAdd = function diffAdd(p, diff) { - // http://hyperelliptic.org/EFD/g1p/auto-montgom-xz.html#diffadd-dadd-1987-m-3 - // 4M + 2S + 6A - - // A = X2 + Z2 - var a = this.x.redAdd(this.z); - // B = X2 - Z2 - var b = this.x.redSub(this.z); - // C = X3 + Z3 - var c = p.x.redAdd(p.z); - // D = X3 - Z3 - var d = p.x.redSub(p.z); - // DA = D * A - var da = d.redMul(a); - // CB = C * B - var cb = c.redMul(b); - // X5 = Z1 * (DA + CB)^2 - var nx = diff.z.redMul(da.redAdd(cb).redSqr()); - // Z5 = X1 * (DA - CB)^2 - var nz = diff.x.redMul(da.redISub(cb).redSqr()); - return this.curve.point(nx, nz); -}; - -Point.prototype.mul = function mul(k) { - var t = k.clone(); - var a = this; // (N / 2) * Q + Q - var b = this.curve.point(null, null); // (N / 2) * Q - var c = this; // Q - - for (var bits = []; t.cmpn(0) !== 0; t.ishrn(1)) - bits.push(t.andln(1)); - - for (var i = bits.length - 1; i >= 0; i--) { - if (bits[i] === 0) { - // N * Q + Q = ((N / 2) * Q + Q)) + (N / 2) * Q - a = a.diffAdd(b, c); - // N * Q = 2 * ((N / 2) * Q + Q)) - b = b.dbl(); - } else { - // N * Q = ((N / 2) * Q + Q) + ((N / 2) * Q) - b = a.diffAdd(b, c); - // N * Q + Q = 2 * ((N / 2) * Q + Q) - a = a.dbl(); - } - } - return b; -}; - -Point.prototype.mulAdd = function mulAdd() { - throw new Error('Not supported on Montgomery curve'); -}; - -Point.prototype.normalize = function normalize() { - this.x = this.x.redMul(this.z.redInvm()); - this.z = this.curve.one; - return this; -}; - -Point.prototype.getX = function getX() { - // Normalize coordinates - this.normalize(); - - return this.x.fromRed(); -}; - -},{"../../elliptic":74,"../curve":77,"assert":194,"bn.js":72,"inherits":94}],79:[function(require,module,exports){ -var assert = require('assert'); -var curve = require('../curve'); -var elliptic = require('../../elliptic'); -var bn = require('bn.js'); -var inherits = require('inherits'); -var Base = curve.base; - -var getNAF = elliptic.utils.getNAF; - -function ShortCurve(conf) { - Base.call(this, 'short', conf); - - this.a = new bn(conf.a, 16).toRed(this.red); - this.b = new bn(conf.b, 16).toRed(this.red); - this.tinv = this.two.redInvm(); - - this.zeroA = this.a.fromRed().cmpn(0) === 0; - this.threeA = this.a.fromRed().sub(this.p).cmpn(-3) === 0; - - // If the curve is endomorphic, precalculate beta and lambda - this.endo = this._getEndomorphism(conf); - this._endoWnafT1 = new Array(4); - this._endoWnafT2 = new Array(4); -} -inherits(ShortCurve, Base); -module.exports = ShortCurve; - -ShortCurve.prototype._getEndomorphism = function _getEndomorphism(conf) { - // No efficient endomorphism - if (!this.zeroA || !this.g || !this.n || this.p.modn(3) !== 1) - return; - - // Compute beta and lambda, that lambda * P = (beta * Px; Py) - var beta; - var lambda; - if (conf.beta) { - beta = new bn(conf.beta, 16).toRed(this.red); - } else { - var betas = this._getEndoRoots(this.p); - // Choose the smallest beta - beta = betas[0].cmp(betas[1]) < 0 ? betas[0] : betas[1]; - beta = beta.toRed(this.red); - } - if (conf.lambda) { - lambda = new bn(conf.lambda, 16); - } else { - // Choose the lambda that is matching selected beta - var lambdas = this._getEndoRoots(this.n); - if (this.g.mul(lambdas[0]).x.cmp(this.g.x.redMul(beta)) === 0) { - lambda = lambdas[0]; - } else { - lambda = lambdas[1]; - assert(this.g.mul(lambda).x.cmp(this.g.x.redMul(beta)) === 0); - } - } - - // Get basis vectors, used for balanced length-two representation - var basis; - if (conf.basis) { - basis = conf.basis.map(function(vec) { - return { - a: new bn(vec.a, 16), - b: new bn(vec.b, 16), - }; - }); - } else { - basis = this._getEndoBasis(lambda); - } - - return { - beta: beta, - lambda: lambda, - basis: basis - }; -}; - -ShortCurve.prototype._getEndoRoots = function _getEndoRoots(num) { - // Find roots of for x^2 + x + 1 in F - // Root = (-1 +- Sqrt(-3)) / 2 - // - var red = num === this.p ? this.red : bn.mont(num); - var tinv = new bn(2).toRed(red).redInvm(); - var ntinv = tinv.redNeg(); - var one = new bn(1).toRed(red); - - var s = new bn(3).toRed(red).redNeg().redSqrt().redMul(tinv); - - var l1 = ntinv.redAdd(s).fromRed(); - var l2 = ntinv.redSub(s).fromRed(); - return [ l1, l2 ]; -}; - -ShortCurve.prototype._getEndoBasis = function _getEndoBasis(lambda) { - // aprxSqrt >= sqrt(this.n) - var aprxSqrt = this.n.shrn(Math.floor(this.n.bitLength() / 2)); - - // 3.74 - // Run EGCD, until r(L + 1) < aprxSqrt - var u = lambda; - var v = this.n.clone(); - var x1 = new bn(1); - var y1 = new bn(0); - var x2 = new bn(0); - var y2 = new bn(1); - - // NOTE: all vectors are roots of: a + b * lambda = 0 (mod n) - var a0; - var b0; - // First vector - var a1; - var b1; - // Second vector - var a2; - var b2; - - var prevR; - var i = 0; - while (u.cmpn(0) !== 0) { - var q = v.div(u); - var r = v.sub(q.mul(u)); - var x = x2.sub(q.mul(x1)); - var y = y2.sub(q.mul(y1)); - - if (!a1 && r.cmp(aprxSqrt) < 0) { - a0 = prevR.neg(); - b0 = x1; - a1 = r.neg(); - b1 = x; - } else if (a1 && ++i === 2) { - break; - } - prevR = r; - - v = u; - u = r; - x2 = x1; - x1 = x; - y2 = y1; - y1 = y; - } - a2 = r.neg(); - b2 = x; - - var len1 = a1.sqr().add(b1.sqr()); - var len2 = a2.sqr().add(b2.sqr()); - if (len2.cmp(len1) >= 0) { - a2 = a0; - b2 = b0; - } - - // Normalize signs - if (a1.sign) { - a1 = a1.neg(); - b1 = b1.neg(); - } - if (a2.sign) { - a2 = a2.neg(); - b2 = b2.neg(); - } - - return [ - { a: a1, b: b1 }, - { a: a2, b: b2 } - ]; -}; - -ShortCurve.prototype._endoSplit = function _endoSplit(k) { - var basis = this.endo.basis; - var v1 = basis[0]; - var v2 = basis[1]; - - var c1 = v2.b.mul(k).divRound(this.n); - var c2 = v1.b.neg().mul(k).divRound(this.n); - - var p1 = c1.mul(v1.a); - var p2 = c2.mul(v2.a); - var q1 = c1.mul(v1.b); - var q2 = c2.mul(v2.b); - - // Calculate answer - var k1 = k.sub(p1).sub(p2); - var k2 = q1.add(q2).neg(); - return { k1: k1, k2: k2 }; -}; - -ShortCurve.prototype.point = function point(x, y, isRed) { - return new Point(this, x, y, isRed); -}; - -ShortCurve.prototype.pointFromX = function pointFromX(odd, x) { - x = new bn(x, 16); - if (!x.red) - x = x.toRed(this.red); - - var y2 = x.redSqr().redMul(x).redIAdd(x.redMul(this.a)).redIAdd(this.b); - var y = y2.redSqrt(); - - // XXX Is there any way to tell if the number is odd without converting it - // to non-red form? - var isOdd = y.fromRed().isOdd(); - if (odd && !isOdd || !odd && isOdd) - y = y.redNeg(); - - return this.point(x, y); -}; - -ShortCurve.prototype.jpoint = function jpoint(x, y, z) { - return new JPoint(this, x, y, z); -}; - -ShortCurve.prototype.pointFromJSON = function pointFromJSON(obj, red) { - return Point.fromJSON(this, obj, red); -}; - -ShortCurve.prototype.validate = function validate(point) { - if (point.inf) - return true; - - var x = point.x; - var y = point.y; - - var ax = this.a.redMul(x); - var rhs = x.redSqr().redMul(x).redIAdd(ax).redIAdd(this.b); - return y.redSqr().redISub(rhs).cmpn(0) === 0; -}; - -ShortCurve.prototype._endoWnafMulAdd = function _endoWnafMulAdd(points, coeffs) { - var npoints = this._endoWnafT1; - var ncoeffs = this._endoWnafT2; - for (var i = 0; i < points.length; i++) { - var split = this._endoSplit(coeffs[i]); - var p = points[i]; - var beta = p._getBeta(); - - if (split.k1.sign) { - split.k1.sign = !split.k1.sign; - p = p.neg(true); - } - if (split.k2.sign) { - split.k2.sign = !split.k2.sign; - beta = beta.neg(true); - } - - npoints[i * 2] = p; - npoints[i * 2 + 1] = beta; - ncoeffs[i * 2] = split.k1; - ncoeffs[i * 2 + 1] = split.k2; - } - var res = this._wnafMulAdd(1, npoints, ncoeffs, i * 2); - - // Clean-up references to points and coefficients - for (var j = 0; j < i * 2; j++) { - npoints[j] = null; - ncoeffs[j] = null; - } - return res; -}; - -function Point(curve, x, y, isRed) { - Base.BasePoint.call(this, curve, 'affine'); - if (x === null && y === null) { - this.x = null; - this.y = null; - this.inf = true; - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - // Force redgomery representation when loading from JSON - if (isRed) { - this.x.forceRed(this.curve.red); - this.y.forceRed(this.curve.red); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - this.inf = false; - } -} -inherits(Point, Base.BasePoint); - -Point.prototype._getBeta = function _getBeta() { - if (!this.curve.endo) - return; - - var pre = this.precomputed; - if (pre && pre.beta) - return pre.beta; - - var beta = this.curve.point(this.x.redMul(this.curve.endo.beta), this.y); - if (pre) { - var curve = this.curve; - function endoMul(p) { - return curve.point(p.x.redMul(curve.endo.beta), p.y); - } - pre.beta = beta; - beta.precomputed = { - beta: null, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(endoMul) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(endoMul) - } - }; - } - return beta; -}; - -Point.prototype.toJSON = function toJSON() { - if (!this.precomputed) - return [ this.x, this.y ]; - - return [ this.x, this.y, this.precomputed && { - doubles: this.precomputed.doubles && { - step: this.precomputed.doubles.step, - points: this.precomputed.doubles.points.slice(1) - }, - naf: this.precomputed.naf && { - wnd: this.precomputed.naf.wnd, - points: this.precomputed.naf.points.slice(1) - } - }]; -}; - -Point.fromJSON = function fromJSON(curve, obj, red) { - if (typeof obj === 'string') - obj = JSON.parse(obj); - var res = curve.point(obj[0], obj[1], red); - if (!obj[2]) - return res; - - function obj2point(obj) { - return curve.point(obj[0], obj[1], red); - } - - var pre = obj[2]; - res.precomputed = { - beta: null, - doubles: pre.doubles && { - step: pre.doubles.step, - points: [ res ].concat(pre.doubles.points.map(obj2point)) - }, - naf: pre.naf && { - wnd: pre.naf.wnd, - points: [ res ].concat(pre.naf.points.map(obj2point)) - } - }; - return res; -}; - -Point.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -Point.prototype.isInfinity = function isInfinity() { - return this.inf; -}; - -Point.prototype.add = function add(p) { - // O + P = P - if (this.inf) - return p; - - // P + O = P - if (p.inf) - return this; - - // P + P = 2P - if (this.eq(p)) - return this.dbl(); - - // P + (-P) = O - if (this.neg().eq(p)) - return this.curve.point(null, null); - - // P + Q = O - if (this.x.cmp(p.x) === 0) - return this.curve.point(null, null); - - var c = this.y.redSub(p.y); - if (c.cmpn(0) !== 0) - c = c.redMul(this.x.redSub(p.x).redInvm()); - var nx = c.redSqr().redISub(this.x).redISub(p.x); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.dbl = function dbl() { - if (this.inf) - return this; - - // 2P = O - var ys1 = this.y.redAdd(this.y); - if (ys1.cmpn(0) === 0) - return this.curve.point(null, null); - - var a = this.curve.a; - - var x2 = this.x.redSqr(); - var dyinv = ys1.redInvm(); - var c = x2.redAdd(x2).redIAdd(x2).redIAdd(a).redMul(dyinv); - - var nx = c.redSqr().redISub(this.x.redAdd(this.x)); - var ny = c.redMul(this.x.redSub(nx)).redISub(this.y); - return this.curve.point(nx, ny); -}; - -Point.prototype.getX = function getX() { - return this.x.fromRed(); -}; - -Point.prototype.getY = function getY() { - return this.y.fromRed(); -}; - -Point.prototype.mul = function mul(k) { - k = new bn(k, 16); - - if (this.precomputed && this.precomputed.doubles) - return this.curve._fixedNafMul(this, k); - else if (this.curve.endo) - return this.curve._endoWnafMulAdd([ this ], [ k ]); - else - return this.curve._wnafMul(this, k); -}; - -Point.prototype.mulAdd = function mulAdd(k1, p2, k2) { - var points = [ this, p2 ]; - var coeffs = [ k1, k2 ]; - if (this.curve.endo) - return this.curve._endoWnafMulAdd(points, coeffs); - else - return this.curve._wnafMulAdd(1, points, coeffs, 2); -}; - -Point.prototype.eq = function eq(p) { - return this === p || - this.inf === p.inf && - (this.inf || this.x.cmp(p.x) === 0 && this.y.cmp(p.y) === 0); -}; - -Point.prototype.neg = function neg(_precompute) { - if (this.inf) - return this; - - var res = this.curve.point(this.x, this.y.redNeg()); - if (_precompute && this.precomputed) { - var pre = this.precomputed; - function negate(p) { - return p.neg(); - } - res.precomputed = { - naf: pre.naf && { - wnd: pre.naf.wnd, - points: pre.naf.points.map(negate) - }, - doubles: pre.doubles && { - step: pre.doubles.step, - points: pre.doubles.points.map(negate) - } - }; - } - return res; -}; - -Point.prototype.toJ = function toJ() { - if (this.inf) - return this.curve.jpoint(null, null, null); - - var res = this.curve.jpoint(this.x, this.y, this.curve.one); - return res; -}; - -function JPoint(curve, x, y, z) { - Base.BasePoint.call(this, curve, 'jacobian'); - if (x === null && y === null && z === null) { - this.x = this.curve.one; - this.y = this.curve.one; - this.z = new bn(0); - } else { - this.x = new bn(x, 16); - this.y = new bn(y, 16); - this.z = new bn(z, 16); - } - if (!this.x.red) - this.x = this.x.toRed(this.curve.red); - if (!this.y.red) - this.y = this.y.toRed(this.curve.red); - if (!this.z.red) - this.z = this.z.toRed(this.curve.red); - - this.zOne = this.z === this.curve.one; -} -inherits(JPoint, Base.BasePoint); - -JPoint.prototype.toP = function toP() { - if (this.isInfinity()) - return this.curve.point(null, null); - - var zinv = this.z.redInvm(); - var zinv2 = zinv.redSqr(); - var ax = this.x.redMul(zinv2); - var ay = this.y.redMul(zinv2).redMul(zinv); - - return this.curve.point(ax, ay); -}; - -JPoint.prototype.neg = function neg() { - return this.curve.jpoint(this.x, this.y.redNeg(), this.z); -}; - -JPoint.prototype.add = function add(p) { - // O + P = P - if (this.isInfinity()) - return p; - - // P + O = P - if (p.isInfinity()) - return this; - - // 12M + 4S + 7A - var pz2 = p.z.redSqr(); - var z2 = this.z.redSqr(); - var u1 = this.x.redMul(pz2); - var u2 = p.x.redMul(z2); - var s1 = this.y.redMul(pz2.redMul(p.z)); - var s2 = p.y.redMul(z2.redMul(this.z)); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(p.z).redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mixedAdd = function mixedAdd(p) { - // O + P = P - if (this.isInfinity()) - return p.toJ(); - - // P + O = P - if (p.isInfinity()) - return this; - - // 8M + 3S + 7A - var z2 = this.z.redSqr(); - var u1 = this.x; - var u2 = p.x.redMul(z2); - var s1 = this.y; - var s2 = p.y.redMul(z2).redMul(this.z); - - var h = u1.redSub(u2); - var r = s1.redSub(s2); - if (h.cmpn(0) === 0) { - if (r.cmpn(0) !== 0) - return this.curve.jpoint(null, null, null); - else - return this.dbl(); - } - - var h2 = h.redSqr(); - var h3 = h2.redMul(h); - var v = u1.redMul(h2); - - var nx = r.redSqr().redIAdd(h3).redISub(v).redISub(v); - var ny = r.redMul(v.redISub(nx)).redISub(s1.redMul(h3)); - var nz = this.z.redMul(h); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.dblp = function dblp(pow) { - if (pow === 0) - return this; - if (this.isInfinity()) - return this; - if (!pow) - return this.dbl(); - - if (this.curve.zeroA || this.curve.threeA) { - var r = this; - for (var i = 0; i < pow; i++) - r = r.dbl(); - return r; - } - - // 1M + 2S + 1A + N * (4S + 5M + 8A) - // N = 1 => 6M + 6S + 9A - var a = this.curve.a; - var tinv = this.curve.tinv; - - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - // Reuse results - var jyd = jy.redAdd(jy); - for (var i = 0; i < pow; i++) { - var jx2 = jx.redSqr(); - var jyd2 = jyd.redSqr(); - var jyd4 = jyd2.redSqr(); - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var t1 = jx.redMul(jyd2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - var dny = c.redMul(t2); - dny = dny.redIAdd(dny).redISub(jyd4); - var nz = jyd.redMul(jz); - if (i + 1 < pow) - jz4 = jz4.redMul(jyd4); - - jx = nx; - jz = nz; - jyd = dny; - } - - return this.curve.jpoint(jx, jyd.redMul(tinv), jz); -}; - -JPoint.prototype.dbl = function dbl() { - if (this.isInfinity()) - return this; - - if (this.curve.zeroA) - return this._zeroDbl(); - else if (this.curve.threeA) - return this._threeDbl(); - else - return this._dbl(); -}; - -JPoint.prototype._zeroDbl = function _zeroDbl() { - // Z = 1 - if (this.zOne) { - // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-mdbl-2007-bl - // 1M + 5S + 14A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // T = M ^ 2 - 2*S - var t = m.redSqr().redISub(s).redISub(s); - - // 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - - // X3 = T - var nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2*Y1 - var nz = this.y.redAdd(this.y); - } else { - // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#doubling-dbl-2009-l - // 2M + 5S + 13A - - // A = X1^2 - var a = this.x.redSqr(); - // B = Y1^2 - var b = this.y.redSqr(); - // C = B^2 - var c = b.redSqr(); - // D = 2 * ((X1 + B)^2 - A - C) - var d = this.x.redAdd(b).redSqr().redISub(a).redISub(c); - d = d.redIAdd(d); - // E = 3 * A - var e = a.redAdd(a).redIAdd(a); - // F = E^2 - var f = e.redSqr(); - - // 8 * C - var c8 = c.redIAdd(c); - c8 = c8.redIAdd(c8); - c8 = c8.redIAdd(c8); - - // X3 = F - 2 * D - var nx = f.redISub(d).redISub(d); - // Y3 = E * (D - X3) - 8 * C - var ny = e.redMul(d.redISub(nx)).redISub(c8); - // Z3 = 2 * Y1 * Z1 - var nz = this.y.redMul(this.z); - nz = nz.redIAdd(nz); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._threeDbl = function _threeDbl() { - // Z = 1 - if (this.zOne) { - // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-mdbl-2007-bl - // 1M + 5S + 15A - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // S = 2 * ((X1 + YY)^2 - XX - YYYY) - var s = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - s = s.redIAdd(s); - // M = 3 * XX + a - var m = xx.redAdd(xx).redIAdd(xx).redIAdd(this.curve.a); - // T = M^2 - 2 * S - var t = m.redSqr().redISub(s).redISub(s); - // X3 = T - var nx = t; - // Y3 = M * (S - T) - 8 * YYYY - var yyyy8 = yyyy.redIAdd(yyyy); - yyyy8 = yyyy8.redIAdd(yyyy8); - yyyy8 = yyyy8.redIAdd(yyyy8); - var ny = m.redMul(s.redISub(t)).redISub(yyyy8); - // Z3 = 2 * Y1 - var nz = this.y.redAdd(this.y); - } else { - // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-3.html#doubling-dbl-2001-b - // 3M + 5S - - // delta = Z1^2 - var delta = this.z.redSqr(); - // gamma = Y1^2 - var gamma = this.y.redSqr(); - // beta = X1 * gamma - var beta = this.x.redMul(gamma); - // alpha = 3 * (X1 - delta) * (X1 + delta) - var alpha = this.x.redSub(delta).redMul(this.x.redAdd(delta)); - alpha = alpha.redAdd(alpha).redIAdd(alpha); - // X3 = alpha^2 - 8 * beta - var beta4 = beta.redIAdd(beta); - beta4 = beta4.redIAdd(beta4); - var beta8 = beta4.redAdd(beta4); - var nx = alpha.redSqr().redISub(beta8); - // Z3 = (Y1 + Z1)^2 - gamma - delta - var nz = this.y.redAdd(this.z).redSqr().redISub(gamma).redISub(delta); - // Y3 = alpha * (4 * beta - X3) - 8 * gamma^2 - var ggamma8 = gamma.redSqr(); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - ggamma8 = ggamma8.redIAdd(ggamma8); - var ny = alpha.redMul(beta4.redISub(nx)).redISub(ggamma8); - } - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype._dbl = function _dbl() { - var a = this.curve.a; - var tinv = this.curve.tinv; - - // 4M + 6S + 10A - var jx = this.x; - var jy = this.y; - var jz = this.z; - var jz4 = jz.redSqr().redSqr(); - - var jx2 = jx.redSqr(); - var jy2 = jy.redSqr(); - - var c = jx2.redAdd(jx2).redIAdd(jx2).redIAdd(a.redMul(jz4)); - - var jxd4 = jx.redAdd(jx); - jxd4 = jxd4.redIAdd(jxd4); - var t1 = jxd4.redMul(jy2); - var nx = c.redSqr().redISub(t1.redAdd(t1)); - var t2 = t1.redISub(nx); - - var jyd8 = jy2.redSqr(); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - jyd8 = jyd8.redIAdd(jyd8); - var ny = c.redMul(t2).redISub(jyd8); - var nz = jy.redAdd(jy).redMul(jz); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.trpl = function trpl() { - if (!this.curve.zeroA) - return this.dbl().add(this); - - // http://hyperelliptic.org/EFD/g1p/auto-shortw-jacobian-0.html#tripling-tpl-2007-bl - // 5M + 10S + ... - - // XX = X1^2 - var xx = this.x.redSqr(); - // YY = Y1^2 - var yy = this.y.redSqr(); - // ZZ = Z1^2 - var zz = this.z.redSqr(); - // YYYY = YY^2 - var yyyy = yy.redSqr(); - // M = 3 * XX + a * ZZ2; a = 0 - var m = xx.redAdd(xx).redIAdd(xx); - // MM = M^2 - var mm = m.redSqr(); - // E = 6 * ((X1 + YY)^2 - XX - YYYY) - MM - var e = this.x.redAdd(yy).redSqr().redISub(xx).redISub(yyyy); - e = e.redIAdd(e); - e = e.redAdd(e).redIAdd(e); - e = e.redISub(mm); - // EE = E^2 - var ee = e.redSqr(); - // T = 16*YYYY - var t = yyyy.redIAdd(yyyy); - t = t.redIAdd(t); - t = t.redIAdd(t); - t = t.redIAdd(t); - // U = (M + E)^2 - MM - EE - T - var u = m.redIAdd(e).redSqr().redISub(mm).redISub(ee).redISub(t); - // X3 = 4 * (X1 * EE - 4 * YY * U) - var yyu4 = yy.redMul(u); - yyu4 = yyu4.redIAdd(yyu4); - yyu4 = yyu4.redIAdd(yyu4); - var nx = this.x.redMul(ee).redISub(yyu4); - nx = nx.redIAdd(nx); - nx = nx.redIAdd(nx); - // Y3 = 8 * Y1 * (U * (T - U) - E * EE) - var ny = this.y.redMul(u.redMul(t.redISub(u)).redISub(e.redMul(ee))); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - ny = ny.redIAdd(ny); - // Z3 = (Z1 + E)^2 - ZZ - EE - var nz = this.z.redAdd(e).redSqr().redISub(zz).redISub(ee); - - return this.curve.jpoint(nx, ny, nz); -}; - -JPoint.prototype.mul = function mul(k, kbase) { - k = new bn(k, kbase); - - return this.curve._wnafMul(this, k); -}; - -JPoint.prototype.eq = function eq(p) { - if (p.type === 'affine') - return this.eq(p.toJ()); - - if (this === p) - return true; - - // x1 * z2^2 == x2 * z1^2 - var z2 = this.z.redSqr(); - var pz2 = p.z.redSqr(); - if (this.x.redMul(pz2).redISub(p.x.redMul(z2)).cmpn(0) !== 0) - return false; - - // y1 * z2^3 == y2 * z1^3 - var z3 = z2.redMul(this.z); - var pz3 = pz2.redMul(p.z); - return this.y.redMul(pz3).redISub(p.y.redMul(z3)).cmpn(0) === 0; -}; - -JPoint.prototype.inspect = function inspect() { - if (this.isInfinity()) - return ''; - return ''; -}; - -JPoint.prototype.isInfinity = function isInfinity() { - // XXX This code assumes that zero is always zero in red - return this.z.cmpn(0) === 0; -}; - -},{"../../elliptic":74,"../curve":77,"assert":194,"bn.js":72,"inherits":94}],80:[function(require,module,exports){ -var curves = exports; - -var assert = require('assert'); -var hash = require('hash.js'); -var bn = require('bn.js'); -var elliptic = require('../elliptic'); - -function PresetCurve(options) { - if (options.type === 'short') - this.curve = new elliptic.curve.short(options); - else if (options.type === 'edwards') - this.curve = new elliptic.curve.edwards(options); - else - this.curve = new elliptic.curve.mont(options); - this.g = this.curve.g; - this.n = this.curve.n; - this.hash = options.hash; - - assert(this.g.validate(), 'Invalid curve'); - assert(this.g.mul(this.n).isInfinity(), 'Invalid curve, G*N != O'); -} -curves.PresetCurve = PresetCurve; - -function defineCurve(name, options) { - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - get: function() { - var curve = new PresetCurve(options); - Object.defineProperty(curves, name, { - configurable: true, - enumerable: true, - value: curve - }); - return curve; - } - }); -} - -defineCurve('p192', { - type: 'short', - prime: 'p192', - p: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff fffffffc', - b: '64210519 e59c80e7 0fa7e9ab 72243049 feb8deec c146b9b1', - n: 'ffffffff ffffffff ffffffff 99def836 146bc9b1 b4d22831', - hash: hash.sha256, - gRed: false, - g: [ - '188da80e b03090f6 7cbf20eb 43a18800 f4ff0afd 82ff1012', - '07192b95 ffc8da78 631011ed 6b24cdd5 73f977a1 1e794811' - ], -}); - -defineCurve('p224', { - type: 'short', - prime: 'p224', - p: 'ffffffff ffffffff ffffffff ffffffff 00000000 00000000 00000001', - a: 'ffffffff ffffffff ffffffff fffffffe ffffffff ffffffff fffffffe', - b: 'b4050a85 0c04b3ab f5413256 5044b0b7 d7bfd8ba 270b3943 2355ffb4', - n: 'ffffffff ffffffff ffffffff ffff16a2 e0b8f03e 13dd2945 5c5c2a3d', - hash: hash.sha256, - gRed: false, - g: [ - 'b70e0cbd 6bb4bf7f 321390b9 4a03c1d3 56c21122 343280d6 115c1d21', - 'bd376388 b5f723fb 4c22dfe6 cd4375a0 5a074764 44d58199 85007e34' - ], -}); - -defineCurve('p256', { - type: 'short', - prime: null, - p: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff ffffffff', - a: 'ffffffff 00000001 00000000 00000000 00000000 ffffffff ffffffff fffffffc', - b: '5ac635d8 aa3a93e7 b3ebbd55 769886bc 651d06b0 cc53b0f6 3bce3c3e 27d2604b', - n: 'ffffffff 00000000 ffffffff ffffffff bce6faad a7179e84 f3b9cac2 fc632551', - hash: hash.sha256, - gRed: false, - g: [ - '6b17d1f2 e12c4247 f8bce6e5 63a440f2 77037d81 2deb33a0 f4a13945 d898c296', - '4fe342e2 fe1a7f9b 8ee7eb4a 7c0f9e16 2bce3357 6b315ece cbb64068 37bf51f5' - ], -}); - -defineCurve('curve25519', { - type: 'mont', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '76d06', - b: '0', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '9' - ] -}); - -defineCurve('ed25519', { - type: 'edwards', - prime: 'p25519', - p: '7fffffffffffffff ffffffffffffffff ffffffffffffffff ffffffffffffffed', - a: '-1', - c: '1', - // -121665 * (121666^(-1)) (mod P) - d: '52036cee2b6ffe73 8cc740797779e898 00700a4d4141d8ab 75eb4dca135978a3', - n: '1000000000000000 0000000000000000 14def9dea2f79cd6 5812631a5cf5d3ed', - hash: hash.sha256, - gRed: false, - g: [ - '216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51a', - - // 4/5 - '6666666666666666666666666666666666666666666666666666666666666658' - ] -}); - -defineCurve('secp256k1', { - type: 'short', - prime: 'k256', - p: 'ffffffff ffffffff ffffffff ffffffff ffffffff ffffffff fffffffe fffffc2f', - a: '0', - b: '7', - n: 'ffffffff ffffffff ffffffff fffffffe baaedce6 af48a03b bfd25e8c d0364141', - h: '1', - hash: hash.sha256, - - // Precomputed endomorphism - beta: '7ae96a2b657c07106e64479eac3434e99cf0497512f58995c1396c28719501ee', - lambda: '5363ad4cc05c30e0a5261c028812645a122e22ea20816678df02967c1b23bd72', - basis: [ - { - a: '3086d221a7d46bcde86c90e49284eb15', - b: '-e4437ed6010e88286f547fa90abfe4c3' - }, - { - a: '114ca50f7a8e2f3f657c1108d9d44cfd8', - b: '3086d221a7d46bcde86c90e49284eb15' - } - ], - - gRed: false, - g: [ - '79be667ef9dcbbac55a06295ce870b07029bfcdb2dce28d959f2815b16f81798', - '483ada7726a3c4655da4fbfc0e1108a8fd17b448a68554199c47d08ffb10d4b8', - { - 'doubles': { - 'step': 4, - 'points': [ - [ - 'e60fce93b59e9ec53011aabc21c23e97b2a31369b87a5ae9c44ee89e2a6dec0a', - 'f7e3507399e595929db99f34f57937101296891e44d23f0be1f32cce69616821' - ], - [ - '8282263212c609d9ea2a6e3e172de238d8c39cabd5ac1ca10646e23fd5f51508', - '11f8a8098557dfe45e8256e830b60ace62d613ac2f7b17bed31b6eaff6e26caf' - ], - [ - '175e159f728b865a72f99cc6c6fc846de0b93833fd2222ed73fce5b551e5b739', - 'd3506e0d9e3c79eba4ef97a51ff71f5eacb5955add24345c6efa6ffee9fed695' - ], - [ - '363d90d447b00c9c99ceac05b6262ee053441c7e55552ffe526bad8f83ff4640', - '4e273adfc732221953b445397f3363145b9a89008199ecb62003c7f3bee9de9' - ], - [ - '8b4b5f165df3c2be8c6244b5b745638843e4a781a15bcd1b69f79a55dffdf80c', - '4aad0a6f68d308b4b3fbd7813ab0da04f9e336546162ee56b3eff0c65fd4fd36' - ], - [ - '723cbaa6e5db996d6bf771c00bd548c7b700dbffa6c0e77bcb6115925232fcda', - '96e867b5595cc498a921137488824d6e2660a0653779494801dc069d9eb39f5f' - ], - [ - 'eebfa4d493bebf98ba5feec812c2d3b50947961237a919839a533eca0e7dd7fa', - '5d9a8ca3970ef0f269ee7edaf178089d9ae4cdc3a711f712ddfd4fdae1de8999' - ], - [ - '100f44da696e71672791d0a09b7bde459f1215a29b3c03bfefd7835b39a48db0', - 'cdd9e13192a00b772ec8f3300c090666b7ff4a18ff5195ac0fbd5cd62bc65a09' - ], - [ - 'e1031be262c7ed1b1dc9227a4a04c017a77f8d4464f3b3852c8acde6e534fd2d', - '9d7061928940405e6bb6a4176597535af292dd419e1ced79a44f18f29456a00d' - ], - [ - 'feea6cae46d55b530ac2839f143bd7ec5cf8b266a41d6af52d5e688d9094696d', - 'e57c6b6c97dce1bab06e4e12bf3ecd5c981c8957cc41442d3155debf18090088' - ], - [ - 'da67a91d91049cdcb367be4be6ffca3cfeed657d808583de33fa978bc1ec6cb1', - '9bacaa35481642bc41f463f7ec9780e5dec7adc508f740a17e9ea8e27a68be1d' - ], - [ - '53904faa0b334cdda6e000935ef22151ec08d0f7bb11069f57545ccc1a37b7c0', - '5bc087d0bc80106d88c9eccac20d3c1c13999981e14434699dcb096b022771c8' - ], - [ - '8e7bcd0bd35983a7719cca7764ca906779b53a043a9b8bcaeff959f43ad86047', - '10b7770b2a3da4b3940310420ca9514579e88e2e47fd68b3ea10047e8460372a' - ], - [ - '385eed34c1cdff21e6d0818689b81bde71a7f4f18397e6690a841e1599c43862', - '283bebc3e8ea23f56701de19e9ebf4576b304eec2086dc8cc0458fe5542e5453' - ], - [ - '6f9d9b803ecf191637c73a4413dfa180fddf84a5947fbc9c606ed86c3fac3a7', - '7c80c68e603059ba69b8e2a30e45c4d47ea4dd2f5c281002d86890603a842160' - ], - [ - '3322d401243c4e2582a2147c104d6ecbf774d163db0f5e5313b7e0e742d0e6bd', - '56e70797e9664ef5bfb019bc4ddaf9b72805f63ea2873af624f3a2e96c28b2a0' - ], - [ - '85672c7d2de0b7da2bd1770d89665868741b3f9af7643397721d74d28134ab83', - '7c481b9b5b43b2eb6374049bfa62c2e5e77f17fcc5298f44c8e3094f790313a6' - ], - [ - '948bf809b1988a46b06c9f1919413b10f9226c60f668832ffd959af60c82a0a', - '53a562856dcb6646dc6b74c5d1c3418c6d4dff08c97cd2bed4cb7f88d8c8e589' - ], - [ - '6260ce7f461801c34f067ce0f02873a8f1b0e44dfc69752accecd819f38fd8e8', - 'bc2da82b6fa5b571a7f09049776a1ef7ecd292238051c198c1a84e95b2b4ae17' - ], - [ - 'e5037de0afc1d8d43d8348414bbf4103043ec8f575bfdc432953cc8d2037fa2d', - '4571534baa94d3b5f9f98d09fb990bddbd5f5b03ec481f10e0e5dc841d755bda' - ], - [ - 'e06372b0f4a207adf5ea905e8f1771b4e7e8dbd1c6a6c5b725866a0ae4fce725', - '7a908974bce18cfe12a27bb2ad5a488cd7484a7787104870b27034f94eee31dd' - ], - [ - '213c7a715cd5d45358d0bbf9dc0ce02204b10bdde2a3f58540ad6908d0559754', - '4b6dad0b5ae462507013ad06245ba190bb4850f5f36a7eeddff2c27534b458f2' - ], - [ - '4e7c272a7af4b34e8dbb9352a5419a87e2838c70adc62cddf0cc3a3b08fbd53c', - '17749c766c9d0b18e16fd09f6def681b530b9614bff7dd33e0b3941817dcaae6' - ], - [ - 'fea74e3dbe778b1b10f238ad61686aa5c76e3db2be43057632427e2840fb27b6', - '6e0568db9b0b13297cf674deccb6af93126b596b973f7b77701d3db7f23cb96f' - ], - [ - '76e64113f677cf0e10a2570d599968d31544e179b760432952c02a4417bdde39', - 'c90ddf8dee4e95cf577066d70681f0d35e2a33d2b56d2032b4b1752d1901ac01' - ], - [ - 'c738c56b03b2abe1e8281baa743f8f9a8f7cc643df26cbee3ab150242bcbb891', - '893fb578951ad2537f718f2eacbfbbbb82314eef7880cfe917e735d9699a84c3' - ], - [ - 'd895626548b65b81e264c7637c972877d1d72e5f3a925014372e9f6588f6c14b', - 'febfaa38f2bc7eae728ec60818c340eb03428d632bb067e179363ed75d7d991f' - ], - [ - 'b8da94032a957518eb0f6433571e8761ceffc73693e84edd49150a564f676e03', - '2804dfa44805a1e4d7c99cc9762808b092cc584d95ff3b511488e4e74efdf6e7' - ], - [ - 'e80fea14441fb33a7d8adab9475d7fab2019effb5156a792f1a11778e3c0df5d', - 'eed1de7f638e00771e89768ca3ca94472d155e80af322ea9fcb4291b6ac9ec78' - ], - [ - 'a301697bdfcd704313ba48e51d567543f2a182031efd6915ddc07bbcc4e16070', - '7370f91cfb67e4f5081809fa25d40f9b1735dbf7c0a11a130c0d1a041e177ea1' - ], - [ - '90ad85b389d6b936463f9d0512678de208cc330b11307fffab7ac63e3fb04ed4', - 'e507a3620a38261affdcbd9427222b839aefabe1582894d991d4d48cb6ef150' - ], - [ - '8f68b9d2f63b5f339239c1ad981f162ee88c5678723ea3351b7b444c9ec4c0da', - '662a9f2dba063986de1d90c2b6be215dbbea2cfe95510bfdf23cbf79501fff82' - ], - [ - 'e4f3fb0176af85d65ff99ff9198c36091f48e86503681e3e6686fd5053231e11', - '1e63633ad0ef4f1c1661a6d0ea02b7286cc7e74ec951d1c9822c38576feb73bc' - ], - [ - '8c00fa9b18ebf331eb961537a45a4266c7034f2f0d4e1d0716fb6eae20eae29e', - 'efa47267fea521a1a9dc343a3736c974c2fadafa81e36c54e7d2a4c66702414b' - ], - [ - 'e7a26ce69dd4829f3e10cec0a9e98ed3143d084f308b92c0997fddfc60cb3e41', - '2a758e300fa7984b471b006a1aafbb18d0a6b2c0420e83e20e8a9421cf2cfd51' - ], - [ - 'b6459e0ee3662ec8d23540c223bcbdc571cbcb967d79424f3cf29eb3de6b80ef', - '67c876d06f3e06de1dadf16e5661db3c4b3ae6d48e35b2ff30bf0b61a71ba45' - ], - [ - 'd68a80c8280bb840793234aa118f06231d6f1fc67e73c5a5deda0f5b496943e8', - 'db8ba9fff4b586d00c4b1f9177b0e28b5b0e7b8f7845295a294c84266b133120' - ], - [ - '324aed7df65c804252dc0270907a30b09612aeb973449cea4095980fc28d3d5d', - '648a365774b61f2ff130c0c35aec1f4f19213b0c7e332843967224af96ab7c84' - ], - [ - '4df9c14919cde61f6d51dfdbe5fee5dceec4143ba8d1ca888e8bd373fd054c96', - '35ec51092d8728050974c23a1d85d4b5d506cdc288490192ebac06cad10d5d' - ], - [ - '9c3919a84a474870faed8a9c1cc66021523489054d7f0308cbfc99c8ac1f98cd', - 'ddb84f0f4a4ddd57584f044bf260e641905326f76c64c8e6be7e5e03d4fc599d' - ], - [ - '6057170b1dd12fdf8de05f281d8e06bb91e1493a8b91d4cc5a21382120a959e5', - '9a1af0b26a6a4807add9a2daf71df262465152bc3ee24c65e899be932385a2a8' - ], - [ - 'a576df8e23a08411421439a4518da31880cef0fba7d4df12b1a6973eecb94266', - '40a6bf20e76640b2c92b97afe58cd82c432e10a7f514d9f3ee8be11ae1b28ec8' - ], - [ - '7778a78c28dec3e30a05fe9629de8c38bb30d1f5cf9a3a208f763889be58ad71', - '34626d9ab5a5b22ff7098e12f2ff580087b38411ff24ac563b513fc1fd9f43ac' - ], - [ - '928955ee637a84463729fd30e7afd2ed5f96274e5ad7e5cb09eda9c06d903ac', - 'c25621003d3f42a827b78a13093a95eeac3d26efa8a8d83fc5180e935bcd091f' - ], - [ - '85d0fef3ec6db109399064f3a0e3b2855645b4a907ad354527aae75163d82751', - '1f03648413a38c0be29d496e582cf5663e8751e96877331582c237a24eb1f962' - ], - [ - 'ff2b0dce97eece97c1c9b6041798b85dfdfb6d8882da20308f5404824526087e', - '493d13fef524ba188af4c4dc54d07936c7b7ed6fb90e2ceb2c951e01f0c29907' - ], - [ - '827fbbe4b1e880ea9ed2b2e6301b212b57f1ee148cd6dd28780e5e2cf856e241', - 'c60f9c923c727b0b71bef2c67d1d12687ff7a63186903166d605b68baec293ec' - ], - [ - 'eaa649f21f51bdbae7be4ae34ce6e5217a58fdce7f47f9aa7f3b58fa2120e2b3', - 'be3279ed5bbbb03ac69a80f89879aa5a01a6b965f13f7e59d47a5305ba5ad93d' - ], - [ - 'e4a42d43c5cf169d9391df6decf42ee541b6d8f0c9a137401e23632dda34d24f', - '4d9f92e716d1c73526fc99ccfb8ad34ce886eedfa8d8e4f13a7f7131deba9414' - ], - [ - '1ec80fef360cbdd954160fadab352b6b92b53576a88fea4947173b9d4300bf19', - 'aeefe93756b5340d2f3a4958a7abbf5e0146e77f6295a07b671cdc1cc107cefd' - ], - [ - '146a778c04670c2f91b00af4680dfa8bce3490717d58ba889ddb5928366642be', - 'b318e0ec3354028add669827f9d4b2870aaa971d2f7e5ed1d0b297483d83efd0' - ], - [ - 'fa50c0f61d22e5f07e3acebb1aa07b128d0012209a28b9776d76a8793180eef9', - '6b84c6922397eba9b72cd2872281a68a5e683293a57a213b38cd8d7d3f4f2811' - ], - [ - 'da1d61d0ca721a11b1a5bf6b7d88e8421a288ab5d5bba5220e53d32b5f067ec2', - '8157f55a7c99306c79c0766161c91e2966a73899d279b48a655fba0f1ad836f1' - ], - [ - 'a8e282ff0c9706907215ff98e8fd416615311de0446f1e062a73b0610d064e13', - '7f97355b8db81c09abfb7f3c5b2515888b679a3e50dd6bd6cef7c73111f4cc0c' - ], - [ - '174a53b9c9a285872d39e56e6913cab15d59b1fa512508c022f382de8319497c', - 'ccc9dc37abfc9c1657b4155f2c47f9e6646b3a1d8cb9854383da13ac079afa73' - ], - [ - '959396981943785c3d3e57edf5018cdbe039e730e4918b3d884fdff09475b7ba', - '2e7e552888c331dd8ba0386a4b9cd6849c653f64c8709385e9b8abf87524f2fd' - ], - [ - 'd2a63a50ae401e56d645a1153b109a8fcca0a43d561fba2dbb51340c9d82b151', - 'e82d86fb6443fcb7565aee58b2948220a70f750af484ca52d4142174dcf89405' - ], - [ - '64587e2335471eb890ee7896d7cfdc866bacbdbd3839317b3436f9b45617e073', - 'd99fcdd5bf6902e2ae96dd6447c299a185b90a39133aeab358299e5e9faf6589' - ], - [ - '8481bde0e4e4d885b3a546d3e549de042f0aa6cea250e7fd358d6c86dd45e458', - '38ee7b8cba5404dd84a25bf39cecb2ca900a79c42b262e556d64b1b59779057e' - ], - [ - '13464a57a78102aa62b6979ae817f4637ffcfed3c4b1ce30bcd6303f6caf666b', - '69be159004614580ef7e433453ccb0ca48f300a81d0942e13f495a907f6ecc27' - ], - [ - 'bc4a9df5b713fe2e9aef430bcc1dc97a0cd9ccede2f28588cada3a0d2d83f366', - 'd3a81ca6e785c06383937adf4b798caa6e8a9fbfa547b16d758d666581f33c1' - ], - [ - '8c28a97bf8298bc0d23d8c749452a32e694b65e30a9472a3954ab30fe5324caa', - '40a30463a3305193378fedf31f7cc0eb7ae784f0451cb9459e71dc73cbef9482' - ], - [ - '8ea9666139527a8c1dd94ce4f071fd23c8b350c5a4bb33748c4ba111faccae0', - '620efabbc8ee2782e24e7c0cfb95c5d735b783be9cf0f8e955af34a30e62b945' - ], - [ - 'dd3625faef5ba06074669716bbd3788d89bdde815959968092f76cc4eb9a9787', - '7a188fa3520e30d461da2501045731ca941461982883395937f68d00c644a573' - ], - [ - 'f710d79d9eb962297e4f6232b40e8f7feb2bc63814614d692c12de752408221e', - 'ea98e67232d3b3295d3b535532115ccac8612c721851617526ae47a9c77bfc82' - ] - ] - }, - 'naf': { - 'wnd': 7, - 'points': [ - [ - 'f9308a019258c31049344f85f89d5229b531c845836f99b08601f113bce036f9', - '388f7b0f632de8140fe337e62a37f3566500a99934c2231b6cb9fd7584b8e672' - ], - [ - '2f8bde4d1a07209355b4a7250a5c5128e88b84bddc619ab7cba8d569b240efe4', - 'd8ac222636e5e3d6d4dba9dda6c9c426f788271bab0d6840dca87d3aa6ac62d6' - ], - [ - '5cbdf0646e5db4eaa398f365f2ea7a0e3d419b7e0330e39ce92bddedcac4f9bc', - '6aebca40ba255960a3178d6d861a54dba813d0b813fde7b5a5082628087264da' - ], - [ - 'acd484e2f0c7f65309ad178a9f559abde09796974c57e714c35f110dfc27ccbe', - 'cc338921b0a7d9fd64380971763b61e9add888a4375f8e0f05cc262ac64f9c37' - ], - [ - '774ae7f858a9411e5ef4246b70c65aac5649980be5c17891bbec17895da008cb', - 'd984a032eb6b5e190243dd56d7b7b365372db1e2dff9d6a8301d74c9c953c61b' - ], - [ - 'f28773c2d975288bc7d1d205c3748651b075fbc6610e58cddeeddf8f19405aa8', - 'ab0902e8d880a89758212eb65cdaf473a1a06da521fa91f29b5cb52db03ed81' - ], - [ - 'd7924d4f7d43ea965a465ae3095ff41131e5946f3c85f79e44adbcf8e27e080e', - '581e2872a86c72a683842ec228cc6defea40af2bd896d3a5c504dc9ff6a26b58' - ], - [ - 'defdea4cdb677750a420fee807eacf21eb9898ae79b9768766e4faa04a2d4a34', - '4211ab0694635168e997b0ead2a93daeced1f4a04a95c0f6cfb199f69e56eb77' - ], - [ - '2b4ea0a797a443d293ef5cff444f4979f06acfebd7e86d277475656138385b6c', - '85e89bc037945d93b343083b5a1c86131a01f60c50269763b570c854e5c09b7a' - ], - [ - '352bbf4a4cdd12564f93fa332ce333301d9ad40271f8107181340aef25be59d5', - '321eb4075348f534d59c18259dda3e1f4a1b3b2e71b1039c67bd3d8bcf81998c' - ], - [ - '2fa2104d6b38d11b0230010559879124e42ab8dfeff5ff29dc9cdadd4ecacc3f', - '2de1068295dd865b64569335bd5dd80181d70ecfc882648423ba76b532b7d67' - ], - [ - '9248279b09b4d68dab21a9b066edda83263c3d84e09572e269ca0cd7f5453714', - '73016f7bf234aade5d1aa71bdea2b1ff3fc0de2a887912ffe54a32ce97cb3402' - ], - [ - 'daed4f2be3a8bf278e70132fb0beb7522f570e144bf615c07e996d443dee8729', - 'a69dce4a7d6c98e8d4a1aca87ef8d7003f83c230f3afa726ab40e52290be1c55' - ], - [ - 'c44d12c7065d812e8acf28d7cbb19f9011ecd9e9fdf281b0e6a3b5e87d22e7db', - '2119a460ce326cdc76c45926c982fdac0e106e861edf61c5a039063f0e0e6482' - ], - [ - '6a245bf6dc698504c89a20cfded60853152b695336c28063b61c65cbd269e6b4', - 'e022cf42c2bd4a708b3f5126f16a24ad8b33ba48d0423b6efd5e6348100d8a82' - ], - [ - '1697ffa6fd9de627c077e3d2fe541084ce13300b0bec1146f95ae57f0d0bd6a5', - 'b9c398f186806f5d27561506e4557433a2cf15009e498ae7adee9d63d01b2396' - ], - [ - '605bdb019981718b986d0f07e834cb0d9deb8360ffb7f61df982345ef27a7479', - '2972d2de4f8d20681a78d93ec96fe23c26bfae84fb14db43b01e1e9056b8c49' - ], - [ - '62d14dab4150bf497402fdc45a215e10dcb01c354959b10cfe31c7e9d87ff33d', - '80fc06bd8cc5b01098088a1950eed0db01aa132967ab472235f5642483b25eaf' - ], - [ - '80c60ad0040f27dade5b4b06c408e56b2c50e9f56b9b8b425e555c2f86308b6f', - '1c38303f1cc5c30f26e66bad7fe72f70a65eed4cbe7024eb1aa01f56430bd57a' - ], - [ - '7a9375ad6167ad54aa74c6348cc54d344cc5dc9487d847049d5eabb0fa03c8fb', - 'd0e3fa9eca8726909559e0d79269046bdc59ea10c70ce2b02d499ec224dc7f7' - ], - [ - 'd528ecd9b696b54c907a9ed045447a79bb408ec39b68df504bb51f459bc3ffc9', - 'eecf41253136e5f99966f21881fd656ebc4345405c520dbc063465b521409933' - ], - [ - '49370a4b5f43412ea25f514e8ecdad05266115e4a7ecb1387231808f8b45963', - '758f3f41afd6ed428b3081b0512fd62a54c3f3afbb5b6764b653052a12949c9a' - ], - [ - '77f230936ee88cbbd73df930d64702ef881d811e0e1498e2f1c13eb1fc345d74', - '958ef42a7886b6400a08266e9ba1b37896c95330d97077cbbe8eb3c7671c60d6' - ], - [ - 'f2dac991cc4ce4b9ea44887e5c7c0bce58c80074ab9d4dbaeb28531b7739f530', - 'e0dedc9b3b2f8dad4da1f32dec2531df9eb5fbeb0598e4fd1a117dba703a3c37' - ], - [ - '463b3d9f662621fb1b4be8fbbe2520125a216cdfc9dae3debcba4850c690d45b', - '5ed430d78c296c3543114306dd8622d7c622e27c970a1de31cb377b01af7307e' - ], - [ - 'f16f804244e46e2a09232d4aff3b59976b98fac14328a2d1a32496b49998f247', - 'cedabd9b82203f7e13d206fcdf4e33d92a6c53c26e5cce26d6579962c4e31df6' - ], - [ - 'caf754272dc84563b0352b7a14311af55d245315ace27c65369e15f7151d41d1', - 'cb474660ef35f5f2a41b643fa5e460575f4fa9b7962232a5c32f908318a04476' - ], - [ - '2600ca4b282cb986f85d0f1709979d8b44a09c07cb86d7c124497bc86f082120', - '4119b88753c15bd6a693b03fcddbb45d5ac6be74ab5f0ef44b0be9475a7e4b40' - ], - [ - '7635ca72d7e8432c338ec53cd12220bc01c48685e24f7dc8c602a7746998e435', - '91b649609489d613d1d5e590f78e6d74ecfc061d57048bad9e76f302c5b9c61' - ], - [ - '754e3239f325570cdbbf4a87deee8a66b7f2b33479d468fbc1a50743bf56cc18', - '673fb86e5bda30fb3cd0ed304ea49a023ee33d0197a695d0c5d98093c536683' - ], - [ - 'e3e6bd1071a1e96aff57859c82d570f0330800661d1c952f9fe2694691d9b9e8', - '59c9e0bba394e76f40c0aa58379a3cb6a5a2283993e90c4167002af4920e37f5' - ], - [ - '186b483d056a033826ae73d88f732985c4ccb1f32ba35f4b4cc47fdcf04aa6eb', - '3b952d32c67cf77e2e17446e204180ab21fb8090895138b4a4a797f86e80888b' - ], - [ - 'df9d70a6b9876ce544c98561f4be4f725442e6d2b737d9c91a8321724ce0963f', - '55eb2dafd84d6ccd5f862b785dc39d4ab157222720ef9da217b8c45cf2ba2417' - ], - [ - '5edd5cc23c51e87a497ca815d5dce0f8ab52554f849ed8995de64c5f34ce7143', - 'efae9c8dbc14130661e8cec030c89ad0c13c66c0d17a2905cdc706ab7399a868' - ], - [ - '290798c2b6476830da12fe02287e9e777aa3fba1c355b17a722d362f84614fba', - 'e38da76dcd440621988d00bcf79af25d5b29c094db2a23146d003afd41943e7a' - ], - [ - 'af3c423a95d9f5b3054754efa150ac39cd29552fe360257362dfdecef4053b45', - 'f98a3fd831eb2b749a93b0e6f35cfb40c8cd5aa667a15581bc2feded498fd9c6' - ], - [ - '766dbb24d134e745cccaa28c99bf274906bb66b26dcf98df8d2fed50d884249a', - '744b1152eacbe5e38dcc887980da38b897584a65fa06cedd2c924f97cbac5996' - ], - [ - '59dbf46f8c94759ba21277c33784f41645f7b44f6c596a58ce92e666191abe3e', - 'c534ad44175fbc300f4ea6ce648309a042ce739a7919798cd85e216c4a307f6e' - ], - [ - 'f13ada95103c4537305e691e74e9a4a8dd647e711a95e73cb62dc6018cfd87b8', - 'e13817b44ee14de663bf4bc808341f326949e21a6a75c2570778419bdaf5733d' - ], - [ - '7754b4fa0e8aced06d4167a2c59cca4cda1869c06ebadfb6488550015a88522c', - '30e93e864e669d82224b967c3020b8fa8d1e4e350b6cbcc537a48b57841163a2' - ], - [ - '948dcadf5990e048aa3874d46abef9d701858f95de8041d2a6828c99e2262519', - 'e491a42537f6e597d5d28a3224b1bc25df9154efbd2ef1d2cbba2cae5347d57e' - ], - [ - '7962414450c76c1689c7b48f8202ec37fb224cf5ac0bfa1570328a8a3d7c77ab', - '100b610ec4ffb4760d5c1fc133ef6f6b12507a051f04ac5760afa5b29db83437' - ], - [ - '3514087834964b54b15b160644d915485a16977225b8847bb0dd085137ec47ca', - 'ef0afbb2056205448e1652c48e8127fc6039e77c15c2378b7e7d15a0de293311' - ], - [ - 'd3cc30ad6b483e4bc79ce2c9dd8bc54993e947eb8df787b442943d3f7b527eaf', - '8b378a22d827278d89c5e9be8f9508ae3c2ad46290358630afb34db04eede0a4' - ], - [ - '1624d84780732860ce1c78fcbfefe08b2b29823db913f6493975ba0ff4847610', - '68651cf9b6da903e0914448c6cd9d4ca896878f5282be4c8cc06e2a404078575' - ], - [ - '733ce80da955a8a26902c95633e62a985192474b5af207da6df7b4fd5fc61cd4', - 'f5435a2bd2badf7d485a4d8b8db9fcce3e1ef8e0201e4578c54673bc1dc5ea1d' - ], - [ - '15d9441254945064cf1a1c33bbd3b49f8966c5092171e699ef258dfab81c045c', - 'd56eb30b69463e7234f5137b73b84177434800bacebfc685fc37bbe9efe4070d' - ], - [ - 'a1d0fcf2ec9de675b612136e5ce70d271c21417c9d2b8aaaac138599d0717940', - 'edd77f50bcb5a3cab2e90737309667f2641462a54070f3d519212d39c197a629' - ], - [ - 'e22fbe15c0af8ccc5780c0735f84dbe9a790badee8245c06c7ca37331cb36980', - 'a855babad5cd60c88b430a69f53a1a7a38289154964799be43d06d77d31da06' - ], - [ - '311091dd9860e8e20ee13473c1155f5f69635e394704eaa74009452246cfa9b3', - '66db656f87d1f04fffd1f04788c06830871ec5a64feee685bd80f0b1286d8374' - ], - [ - '34c1fd04d301be89b31c0442d3e6ac24883928b45a9340781867d4232ec2dbdf', - '9414685e97b1b5954bd46f730174136d57f1ceeb487443dc5321857ba73abee' - ], - [ - 'f219ea5d6b54701c1c14de5b557eb42a8d13f3abbcd08affcc2a5e6b049b8d63', - '4cb95957e83d40b0f73af4544cccf6b1f4b08d3c07b27fb8d8c2962a400766d1' - ], - [ - 'd7b8740f74a8fbaab1f683db8f45de26543a5490bca627087236912469a0b448', - 'fa77968128d9c92ee1010f337ad4717eff15db5ed3c049b3411e0315eaa4593b' - ], - [ - '32d31c222f8f6f0ef86f7c98d3a3335ead5bcd32abdd94289fe4d3091aa824bf', - '5f3032f5892156e39ccd3d7915b9e1da2e6dac9e6f26e961118d14b8462e1661' - ], - [ - '7461f371914ab32671045a155d9831ea8793d77cd59592c4340f86cbc18347b5', - '8ec0ba238b96bec0cbdddcae0aa442542eee1ff50c986ea6b39847b3cc092ff6' - ], - [ - 'ee079adb1df1860074356a25aa38206a6d716b2c3e67453d287698bad7b2b2d6', - '8dc2412aafe3be5c4c5f37e0ecc5f9f6a446989af04c4e25ebaac479ec1c8c1e' - ], - [ - '16ec93e447ec83f0467b18302ee620f7e65de331874c9dc72bfd8616ba9da6b5', - '5e4631150e62fb40d0e8c2a7ca5804a39d58186a50e497139626778e25b0674d' - ], - [ - 'eaa5f980c245f6f038978290afa70b6bd8855897f98b6aa485b96065d537bd99', - 'f65f5d3e292c2e0819a528391c994624d784869d7e6ea67fb18041024edc07dc' - ], - [ - '78c9407544ac132692ee1910a02439958ae04877151342ea96c4b6b35a49f51', - 'f3e0319169eb9b85d5404795539a5e68fa1fbd583c064d2462b675f194a3ddb4' - ], - [ - '494f4be219a1a77016dcd838431aea0001cdc8ae7a6fc688726578d9702857a5', - '42242a969283a5f339ba7f075e36ba2af925ce30d767ed6e55f4b031880d562c' - ], - [ - 'a598a8030da6d86c6bc7f2f5144ea549d28211ea58faa70ebf4c1e665c1fe9b5', - '204b5d6f84822c307e4b4a7140737aec23fc63b65b35f86a10026dbd2d864e6b' - ], - [ - 'c41916365abb2b5d09192f5f2dbeafec208f020f12570a184dbadc3e58595997', - '4f14351d0087efa49d245b328984989d5caf9450f34bfc0ed16e96b58fa9913' - ], - [ - '841d6063a586fa475a724604da03bc5b92a2e0d2e0a36acfe4c73a5514742881', - '73867f59c0659e81904f9a1c7543698e62562d6744c169ce7a36de01a8d6154' - ], - [ - '5e95bb399a6971d376026947f89bde2f282b33810928be4ded112ac4d70e20d5', - '39f23f366809085beebfc71181313775a99c9aed7d8ba38b161384c746012865' - ], - [ - '36e4641a53948fd476c39f8a99fd974e5ec07564b5315d8bf99471bca0ef2f66', - 'd2424b1b1abe4eb8164227b085c9aa9456ea13493fd563e06fd51cf5694c78fc' - ], - [ - '336581ea7bfbbb290c191a2f507a41cf5643842170e914faeab27c2c579f726', - 'ead12168595fe1be99252129b6e56b3391f7ab1410cd1e0ef3dcdcabd2fda224' - ], - [ - '8ab89816dadfd6b6a1f2634fcf00ec8403781025ed6890c4849742706bd43ede', - '6fdcef09f2f6d0a044e654aef624136f503d459c3e89845858a47a9129cdd24e' - ], - [ - '1e33f1a746c9c5778133344d9299fcaa20b0938e8acff2544bb40284b8c5fb94', - '60660257dd11b3aa9c8ed618d24edff2306d320f1d03010e33a7d2057f3b3b6' - ], - [ - '85b7c1dcb3cec1b7ee7f30ded79dd20a0ed1f4cc18cbcfcfa410361fd8f08f31', - '3d98a9cdd026dd43f39048f25a8847f4fcafad1895d7a633c6fed3c35e999511' - ], - [ - '29df9fbd8d9e46509275f4b125d6d45d7fbe9a3b878a7af872a2800661ac5f51', - 'b4c4fe99c775a606e2d8862179139ffda61dc861c019e55cd2876eb2a27d84b' - ], - [ - 'a0b1cae06b0a847a3fea6e671aaf8adfdfe58ca2f768105c8082b2e449fce252', - 'ae434102edde0958ec4b19d917a6a28e6b72da1834aff0e650f049503a296cf2' - ], - [ - '4e8ceafb9b3e9a136dc7ff67e840295b499dfb3b2133e4ba113f2e4c0e121e5', - 'cf2174118c8b6d7a4b48f6d534ce5c79422c086a63460502b827ce62a326683c' - ], - [ - 'd24a44e047e19b6f5afb81c7ca2f69080a5076689a010919f42725c2b789a33b', - '6fb8d5591b466f8fc63db50f1c0f1c69013f996887b8244d2cdec417afea8fa3' - ], - [ - 'ea01606a7a6c9cdd249fdfcfacb99584001edd28abbab77b5104e98e8e3b35d4', - '322af4908c7312b0cfbfe369f7a7b3cdb7d4494bc2823700cfd652188a3ea98d' - ], - [ - 'af8addbf2b661c8a6c6328655eb96651252007d8c5ea31be4ad196de8ce2131f', - '6749e67c029b85f52a034eafd096836b2520818680e26ac8f3dfbcdb71749700' - ], - [ - 'e3ae1974566ca06cc516d47e0fb165a674a3dabcfca15e722f0e3450f45889', - '2aeabe7e4531510116217f07bf4d07300de97e4874f81f533420a72eeb0bd6a4' - ], - [ - '591ee355313d99721cf6993ffed1e3e301993ff3ed258802075ea8ced397e246', - 'b0ea558a113c30bea60fc4775460c7901ff0b053d25ca2bdeee98f1a4be5d196' - ], - [ - '11396d55fda54c49f19aa97318d8da61fa8584e47b084945077cf03255b52984', - '998c74a8cd45ac01289d5833a7beb4744ff536b01b257be4c5767bea93ea57a4' - ], - [ - '3c5d2a1ba39c5a1790000738c9e0c40b8dcdfd5468754b6405540157e017aa7a', - 'b2284279995a34e2f9d4de7396fc18b80f9b8b9fdd270f6661f79ca4c81bd257' - ], - [ - 'cc8704b8a60a0defa3a99a7299f2e9c3fbc395afb04ac078425ef8a1793cc030', - 'bdd46039feed17881d1e0862db347f8cf395b74fc4bcdc4e940b74e3ac1f1b13' - ], - [ - 'c533e4f7ea8555aacd9777ac5cad29b97dd4defccc53ee7ea204119b2889b197', - '6f0a256bc5efdf429a2fb6242f1a43a2d9b925bb4a4b3a26bb8e0f45eb596096' - ], - [ - 'c14f8f2ccb27d6f109f6d08d03cc96a69ba8c34eec07bbcf566d48e33da6593', - 'c359d6923bb398f7fd4473e16fe1c28475b740dd098075e6c0e8649113dc3a38' - ], - [ - 'a6cbc3046bc6a450bac24789fa17115a4c9739ed75f8f21ce441f72e0b90e6ef', - '21ae7f4680e889bb130619e2c0f95a360ceb573c70603139862afd617fa9b9f' - ], - [ - '347d6d9a02c48927ebfb86c1359b1caf130a3c0267d11ce6344b39f99d43cc38', - '60ea7f61a353524d1c987f6ecec92f086d565ab687870cb12689ff1e31c74448' - ], - [ - 'da6545d2181db8d983f7dcb375ef5866d47c67b1bf31c8cf855ef7437b72656a', - '49b96715ab6878a79e78f07ce5680c5d6673051b4935bd897fea824b77dc208a' - ], - [ - 'c40747cc9d012cb1a13b8148309c6de7ec25d6945d657146b9d5994b8feb1111', - '5ca560753be2a12fc6de6caf2cb489565db936156b9514e1bb5e83037e0fa2d4' - ], - [ - '4e42c8ec82c99798ccf3a610be870e78338c7f713348bd34c8203ef4037f3502', - '7571d74ee5e0fb92a7a8b33a07783341a5492144cc54bcc40a94473693606437' - ], - [ - '3775ab7089bc6af823aba2e1af70b236d251cadb0c86743287522a1b3b0dedea', - 'be52d107bcfa09d8bcb9736a828cfa7fac8db17bf7a76a2c42ad961409018cf7' - ], - [ - 'cee31cbf7e34ec379d94fb814d3d775ad954595d1314ba8846959e3e82f74e26', - '8fd64a14c06b589c26b947ae2bcf6bfa0149ef0be14ed4d80f448a01c43b1c6d' - ], - [ - 'b4f9eaea09b6917619f6ea6a4eb5464efddb58fd45b1ebefcdc1a01d08b47986', - '39e5c9925b5a54b07433a4f18c61726f8bb131c012ca542eb24a8ac07200682a' - ], - [ - 'd4263dfc3d2df923a0179a48966d30ce84e2515afc3dccc1b77907792ebcc60e', - '62dfaf07a0f78feb30e30d6295853ce189e127760ad6cf7fae164e122a208d54' - ], - [ - '48457524820fa65a4f8d35eb6930857c0032acc0a4a2de422233eeda897612c4', - '25a748ab367979d98733c38a1fa1c2e7dc6cc07db2d60a9ae7a76aaa49bd0f77' - ], - [ - 'dfeeef1881101f2cb11644f3a2afdfc2045e19919152923f367a1767c11cceda', - 'ecfb7056cf1de042f9420bab396793c0c390bde74b4bbdff16a83ae09a9a7517' - ], - [ - '6d7ef6b17543f8373c573f44e1f389835d89bcbc6062ced36c82df83b8fae859', - 'cd450ec335438986dfefa10c57fea9bcc521a0959b2d80bbf74b190dca712d10' - ], - [ - 'e75605d59102a5a2684500d3b991f2e3f3c88b93225547035af25af66e04541f', - 'f5c54754a8f71ee540b9b48728473e314f729ac5308b06938360990e2bfad125' - ], - [ - 'eb98660f4c4dfaa06a2be453d5020bc99a0c2e60abe388457dd43fefb1ed620c', - '6cb9a8876d9cb8520609af3add26cd20a0a7cd8a9411131ce85f44100099223e' - ], - [ - '13e87b027d8514d35939f2e6892b19922154596941888336dc3563e3b8dba942', - 'fef5a3c68059a6dec5d624114bf1e91aac2b9da568d6abeb2570d55646b8adf1' - ], - [ - 'ee163026e9fd6fe017c38f06a5be6fc125424b371ce2708e7bf4491691e5764a', - '1acb250f255dd61c43d94ccc670d0f58f49ae3fa15b96623e5430da0ad6c62b2' - ], - [ - 'b268f5ef9ad51e4d78de3a750c2dc89b1e626d43505867999932e5db33af3d80', - '5f310d4b3c99b9ebb19f77d41c1dee018cf0d34fd4191614003e945a1216e423' - ], - [ - 'ff07f3118a9df035e9fad85eb6c7bfe42b02f01ca99ceea3bf7ffdba93c4750d', - '438136d603e858a3a5c440c38eccbaddc1d2942114e2eddd4740d098ced1f0d8' - ], - [ - '8d8b9855c7c052a34146fd20ffb658bea4b9f69e0d825ebec16e8c3ce2b526a1', - 'cdb559eedc2d79f926baf44fb84ea4d44bcf50fee51d7ceb30e2e7f463036758' - ], - [ - '52db0b5384dfbf05bfa9d472d7ae26dfe4b851ceca91b1eba54263180da32b63', - 'c3b997d050ee5d423ebaf66a6db9f57b3180c902875679de924b69d84a7b375' - ], - [ - 'e62f9490d3d51da6395efd24e80919cc7d0f29c3f3fa48c6fff543becbd43352', - '6d89ad7ba4876b0b22c2ca280c682862f342c8591f1daf5170e07bfd9ccafa7d' - ], - [ - '7f30ea2476b399b4957509c88f77d0191afa2ff5cb7b14fd6d8e7d65aaab1193', - 'ca5ef7d4b231c94c3b15389a5f6311e9daff7bb67b103e9880ef4bff637acaec' - ], - [ - '5098ff1e1d9f14fb46a210fada6c903fef0fb7b4a1dd1d9ac60a0361800b7a00', - '9731141d81fc8f8084d37c6e7542006b3ee1b40d60dfe5362a5b132fd17ddc0' - ], - [ - '32b78c7de9ee512a72895be6b9cbefa6e2f3c4ccce445c96b9f2c81e2778ad58', - 'ee1849f513df71e32efc3896ee28260c73bb80547ae2275ba497237794c8753c' - ], - [ - 'e2cb74fddc8e9fbcd076eef2a7c72b0ce37d50f08269dfc074b581550547a4f7', - 'd3aa2ed71c9dd2247a62df062736eb0baddea9e36122d2be8641abcb005cc4a4' - ], - [ - '8438447566d4d7bedadc299496ab357426009a35f235cb141be0d99cd10ae3a8', - 'c4e1020916980a4da5d01ac5e6ad330734ef0d7906631c4f2390426b2edd791f' - ], - [ - '4162d488b89402039b584c6fc6c308870587d9c46f660b878ab65c82c711d67e', - '67163e903236289f776f22c25fb8a3afc1732f2b84b4e95dbda47ae5a0852649' - ], - [ - '3fad3fa84caf0f34f0f89bfd2dcf54fc175d767aec3e50684f3ba4a4bf5f683d', - 'cd1bc7cb6cc407bb2f0ca647c718a730cf71872e7d0d2a53fa20efcdfe61826' - ], - [ - '674f2600a3007a00568c1a7ce05d0816c1fb84bf1370798f1c69532faeb1a86b', - '299d21f9413f33b3edf43b257004580b70db57da0b182259e09eecc69e0d38a5' - ], - [ - 'd32f4da54ade74abb81b815ad1fb3b263d82d6c692714bcff87d29bd5ee9f08f', - 'f9429e738b8e53b968e99016c059707782e14f4535359d582fc416910b3eea87' - ], - [ - '30e4e670435385556e593657135845d36fbb6931f72b08cb1ed954f1e3ce3ff6', - '462f9bce619898638499350113bbc9b10a878d35da70740dc695a559eb88db7b' - ], - [ - 'be2062003c51cc3004682904330e4dee7f3dcd10b01e580bf1971b04d4cad297', - '62188bc49d61e5428573d48a74e1c655b1c61090905682a0d5558ed72dccb9bc' - ], - [ - '93144423ace3451ed29e0fb9ac2af211cb6e84a601df5993c419859fff5df04a', - '7c10dfb164c3425f5c71a3f9d7992038f1065224f72bb9d1d902a6d13037b47c' - ], - [ - 'b015f8044f5fcbdcf21ca26d6c34fb8197829205c7b7d2a7cb66418c157b112c', - 'ab8c1e086d04e813744a655b2df8d5f83b3cdc6faa3088c1d3aea1454e3a1d5f' - ], - [ - 'd5e9e1da649d97d89e4868117a465a3a4f8a18de57a140d36b3f2af341a21b52', - '4cb04437f391ed73111a13cc1d4dd0db1693465c2240480d8955e8592f27447a' - ], - [ - 'd3ae41047dd7ca065dbf8ed77b992439983005cd72e16d6f996a5316d36966bb', - 'bd1aeb21ad22ebb22a10f0303417c6d964f8cdd7df0aca614b10dc14d125ac46' - ], - [ - '463e2763d885f958fc66cdd22800f0a487197d0a82e377b49f80af87c897b065', - 'bfefacdb0e5d0fd7df3a311a94de062b26b80c61fbc97508b79992671ef7ca7f' - ], - [ - '7985fdfd127c0567c6f53ec1bb63ec3158e597c40bfe747c83cddfc910641917', - '603c12daf3d9862ef2b25fe1de289aed24ed291e0ec6708703a5bd567f32ed03' - ], - [ - '74a1ad6b5f76e39db2dd249410eac7f99e74c59cb83d2d0ed5ff1543da7703e9', - 'cc6157ef18c9c63cd6193d83631bbea0093e0968942e8c33d5737fd790e0db08' - ], - [ - '30682a50703375f602d416664ba19b7fc9bab42c72747463a71d0896b22f6da3', - '553e04f6b018b4fa6c8f39e7f311d3176290d0e0f19ca73f17714d9977a22ff8' - ], - [ - '9e2158f0d7c0d5f26c3791efefa79597654e7a2b2464f52b1ee6c1347769ef57', - '712fcdd1b9053f09003a3481fa7762e9ffd7c8ef35a38509e2fbf2629008373' - ], - [ - '176e26989a43c9cfeba4029c202538c28172e566e3c4fce7322857f3be327d66', - 'ed8cc9d04b29eb877d270b4878dc43c19aefd31f4eee09ee7b47834c1fa4b1c3' - ], - [ - '75d46efea3771e6e68abb89a13ad747ecf1892393dfc4f1b7004788c50374da8', - '9852390a99507679fd0b86fd2b39a868d7efc22151346e1a3ca4726586a6bed8' - ], - [ - '809a20c67d64900ffb698c4c825f6d5f2310fb0451c869345b7319f645605721', - '9e994980d9917e22b76b061927fa04143d096ccc54963e6a5ebfa5f3f8e286c1' - ], - [ - '1b38903a43f7f114ed4500b4eac7083fdefece1cf29c63528d563446f972c180', - '4036edc931a60ae889353f77fd53de4a2708b26b6f5da72ad3394119daf408f9' - ] - ] - } - } - ] -}); - -},{"../elliptic":74,"assert":194,"bn.js":72,"hash.js":88}],81:[function(require,module,exports){ -var assert = require('assert'); -var bn = require('bn.js'); -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; - -var KeyPair = require('./key'); -var Signature = require('./signature'); - -function EC(options) { - if (!(this instanceof EC)) - return new EC(options); - - // Shortcut `elliptic.ec(curve-name)` - if (typeof options === 'string') { - assert(elliptic.curves.hasOwnProperty(options), 'Unknown curve ' + options); - - options = elliptic.curves[options]; - } - - // Shortcut for `elliptic.ec(elliptic.curves.curveName)` - if (options instanceof elliptic.curves.PresetCurve) - options = { curve: options }; - - this.curve = options.curve.curve; - this.n = this.curve.n; - this.nh = this.n.shrn(1); - this.g = this.curve.g; - - // Point on curve - this.g = options.curve.g; - this.g.precompute(options.curve.n.bitLength() + 1); - - // Hash for function for DRBG - this.hash = options.hash || options.curve.hash; -} -module.exports = EC; - -EC.prototype.keyPair = function keyPair(priv, pub) { - return new KeyPair(this, priv, pub); -}; - -EC.prototype.genKeyPair = function genKeyPair(options) { - if (!options) - options = {}; - - // Instantiate Hmac_DRBG - var drbg = new elliptic.hmacDRBG({ - hash: this.hash, - pers: options.pers, - entropy: options.entropy || elliptic.rand(this.hash.hmacStrength), - nonce: this.n.toArray() - }); - - var bytes = this.n.byteLength(); - var ns2 = this.n.sub(new bn(2)); - do { - var priv = new bn(drbg.generate(bytes)); - if (priv.cmp(ns2) > 0) - continue; - - priv.iaddn(1); - return this.keyPair(priv); - } while (true); -}; - -EC.prototype._truncateToN = function truncateToN(msg, truncOnly) { - var delta = msg.byteLength() * 8 - this.n.bitLength(); - if (delta > 0) - msg = msg.shrn(delta); - if (!truncOnly && msg.cmp(this.n) >= 0) - return msg.sub(this.n); - else - return msg; -}; - -EC.prototype.sign = function sign(msg, key, options) { - key = this.keyPair(key, 'hex'); - msg = this._truncateToN(new bn(msg, 16)); - if (!options) - options = {}; - - // Zero-extend key to provide enough entropy - var bytes = this.n.byteLength(); - var bkey = key.getPrivate().toArray(); - for (var i = bkey.length; i < 21; i++) - bkey.unshift(0); - - // Zero-extend nonce to have the same byte size as N - var nonce = msg.toArray(); - for (var i = nonce.length; i < bytes; i++) - nonce.unshift(0); - - // Instantiate Hmac_DRBG - var drbg = new elliptic.hmacDRBG({ - hash: this.hash, - entropy: bkey, - nonce: nonce - }); - - // Number of bytes to generate - var ns1 = this.n.sub(new bn(1)); - do { - var k = new bn(drbg.generate(this.n.byteLength())); - k = this._truncateToN(k, true); - if (k.cmpn(1) <= 0 || k.cmp(ns1) >= 0) - continue; - - var kp = this.g.mul(k); - if (kp.isInfinity()) - continue; - - var r = kp.getX().mod(this.n); - if (r.cmpn(0) === 0) - continue; - - var s = k.invm(this.n).mul(r.mul(key.getPrivate()).iadd(msg)).mod(this.n); - if (s.cmpn(0) === 0) - continue; - - // Use complement of `s`, if it is > `n / 2` - if (options.canonical && s.cmp(this.nh) > 0) - s = this.n.sub(s); - - return new Signature(r, s); - } while (true); -}; - -EC.prototype.verify = function verify(msg, signature, key) { - msg = this._truncateToN(new bn(msg, 16)); - key = this.keyPair(key, 'hex'); - signature = new Signature(signature, 'hex'); - - // Perform primitive values validation - var r = signature.r; - var s = signature.s; - if (r.cmpn(1) < 0 || r.cmp(this.n) >= 0) - return false; - if (s.cmpn(1) < 0 || s.cmp(this.n) >= 0) - return false; - - // Validate signature - var sinv = s.invm(this.n); - var u1 = sinv.mul(msg).mod(this.n); - var u2 = sinv.mul(r).mod(this.n); - - var p = this.g.mulAdd(u1, key.getPublic(), u2); - if (p.isInfinity()) - return false; - - return p.getX().mod(this.n).cmp(r) === 0; -}; - -},{"../../elliptic":74,"./key":82,"./signature":83,"assert":194,"bn.js":72}],82:[function(require,module,exports){ -var assert = require('assert'); -var bn = require('bn.js'); - -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; - -function KeyPair(ec, priv, pub) { - if (priv instanceof KeyPair) - return priv; - if (pub instanceof KeyPair) - return pub; - - if (!priv) { - priv = pub; - pub = null; - } - if (priv !== null && typeof priv === 'object') { - if (priv.x) { - // KeyPair(public) - pub = priv; - priv = null; - } else if (priv.priv || priv.pub) { - // KeyPair({ priv: ..., pub: ... }) - pub = priv.pub; - priv = priv.priv; - } - } - - this.ec = ec; - this.priv = null; - this.pub = null; - - // KeyPair(public, 'hex') - if (this._importPublicHex(priv, pub)) - return; - - if (pub === 'hex') - pub = null; - - // KeyPair(priv, pub) - if (priv) - this._importPrivate(priv); - if (pub) - this._importPublic(pub); -} -module.exports = KeyPair; - -KeyPair.prototype.validate = function validate() { - var pub = this.getPublic(); - - if (pub.isInfinity()) - return { result: false, reason: 'Invalid public key' }; - if (!pub.validate()) - return { result: false, reason: 'Public key is not a point' }; - if (!pub.mul(this.ec.curve.n).isInfinity()) - return { result: false, reason: 'Public key * N != O' }; - - return { result: true, reason: null }; -}; - -KeyPair.prototype.getPublic = function getPublic(compact, enc) { - if (!this.pub) - this.pub = this.ec.g.mul(this.priv); - - // compact is optional argument - if (typeof compact === 'string') { - enc = compact; - compact = null; - } - - if (!enc) - return this.pub; - - var len = this.ec.curve.p.byteLength(); - var x = this.pub.getX().toArray(); - - for (var i = x.length; i < len; i++) - x.unshift(0); - - if (compact) { - var res = [ this.pub.getY().isEven() ? 0x02 : 0x03 ].concat(x); - } else { - var y = this.pub.getY().toArray(); - for (var i = y.length; i < len; i++) - y.unshift(0); - var res = [ 0x04 ].concat(x, y); - } - return utils.encode(res, enc); -}; - -KeyPair.prototype.getPrivate = function getPrivate(enc) { - if (enc === 'hex') - return this.priv.toString(16, 2); - else - return this.priv; -}; - -KeyPair.prototype._importPrivate = function _importPrivate(key) { - this.priv = new bn(key, 16); - - // Ensure that the priv won't be bigger than n, otherwise we may fail - // in fixed multiplication method - this.priv = this.priv.mod(this.ec.curve.n); -}; - -KeyPair.prototype._importPublic = function _importPublic(key) { - this.pub = this.ec.curve.point(key.x, key.y); -}; - -KeyPair.prototype._importPublicHex = function _importPublic(key, enc) { - key = utils.toArray(key, enc); - var len = this.ec.curve.p.byteLength(); - if (key[0] === 0x04 && key.length - 1 === 2 * len) { - this.pub = this.ec.curve.point( - key.slice(1, 1 + len), - key.slice(1 + len, 1 + 2 * len)); - } else if ((key[0] === 0x02 || key[0] === 0x03) && key.length - 1 === len) { - this.pub = this.ec.curve.pointFromX(key[0] === 0x03, - key.slice(1, 1 +len)); - } else { - return false; - } - - return true; -}; - -// ECDH -KeyPair.prototype.derive = function derive(pub) { - return pub.mul(this.priv).getX(); -}; - -// ECDSA -KeyPair.prototype.sign = function sign(msg) { - return this.ec.sign(msg, this); -}; - -KeyPair.prototype.verify = function verify(msg, signature) { - return this.ec.verify(msg, signature, this); -}; - -KeyPair.prototype.inspect = function inspect() { - return ''; -}; - -},{"../../elliptic":74,"assert":194,"bn.js":72}],83:[function(require,module,exports){ -var assert = require('assert'); -var bn = require('bn.js'); - -var elliptic = require('../../elliptic'); -var utils = elliptic.utils; - -function Signature(r, s) { - if (r instanceof Signature) - return r; - - if (this._importDER(r, s)) - return; - - assert(r && s, 'Signature without r or s'); - this.r = new bn(r, 16); - this.s = new bn(s, 16); -} -module.exports = Signature; - -Signature.prototype._importDER = function _importDER(data, enc) { - data = utils.toArray(data, enc); - if (data.length < 6 || data[0] !== 0x30 || data[2] !== 0x02) - return false; - var total = data[1]; - if (1 + total > data.length) - return false; - var rlen = data[3]; - // Short length notation - if (rlen >= 0x80) - return false; - if (4 + rlen + 2 >= data.length) - return false; - if (data[4 + rlen] !== 0x02) - return false; - var slen = data[5 + rlen]; - // Short length notation - if (slen >= 0x80) - return false; - if (4 + rlen + 2 + slen > data.length) - return false; - - this.r = new bn(data.slice(4, 4 + rlen)); - this.s = new bn(data.slice(4 + rlen + 2, 4 + rlen + 2 + slen)); - - return true; -}; - -Signature.prototype.toDER = function toDER(enc) { - var r = this.r.toArray(); - var s = this.s.toArray(); - - // Pad values - if (r[0] & 0x80) - r = [ 0 ].concat(r); - // Pad values - if (s[0] & 0x80) - s = [ 0 ].concat(s); - - var total = r.length + s.length + 4; - var res = [ 0x30, total, 0x02, r.length ]; - res = res.concat(r, [ 0x02, s.length ], s); - return utils.encode(res, enc); -}; - -},{"../../elliptic":74,"assert":194,"bn.js":72}],84:[function(require,module,exports){ -var assert = require('assert'); - -var hash = require('hash.js'); -var elliptic = require('../elliptic'); -var utils = elliptic.utils; - -function HmacDRBG(options) { - if (!(this instanceof HmacDRBG)) - return new HmacDRBG(options); - this.hash = options.hash; - this.predResist = !!options.predResist; - - this.outLen = this.hash.outSize; - this.minEntropy = options.minEntropy || this.hash.hmacStrength; - - this.reseed = null; - this.reseedInterval = null; - this.K = null; - this.V = null; - - var entropy = utils.toArray(options.entropy, options.entropyEnc); - var nonce = utils.toArray(options.nonce, options.nonceEnc); - var pers = utils.toArray(options.pers, options.persEnc); - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - this._init(entropy, nonce, pers); -} -module.exports = HmacDRBG; - -HmacDRBG.prototype._init = function init(entropy, nonce, pers) { - var seed = entropy.concat(nonce).concat(pers); - - this.K = new Array(this.outLen / 8); - this.V = new Array(this.outLen / 8); - for (var i = 0; i < this.V.length; i++) { - this.K[i] = 0x00; - this.V[i] = 0x01; - } - - this._update(seed); - this.reseed = 1; - this.reseedInterval = 0x1000000000000; // 2^48 -}; - -HmacDRBG.prototype._hmac = function hmac() { - return new hash.hmac(this.hash, this.K); -}; - -HmacDRBG.prototype._update = function update(seed) { - var kmac = this._hmac() - .update(this.V) - .update([ 0x00 ]); - if (seed) - kmac = kmac.update(seed); - this.K = kmac.digest(); - this.V = this._hmac().update(this.V).digest(); - if (!seed) - return; - - this.K = this._hmac() - .update(this.V) - .update([ 0x01 ]) - .update(seed) - .digest(); - this.V = this._hmac().update(this.V).digest(); -}; - -HmacDRBG.prototype.reseed = function reseed(entropy, entropyEnc, add, addEnc) { - // Optional entropy enc - if (typeof entropyEnc !== 'string') { - addEnc = add; - add = entropyEnc; - entropyEnc = null; - } - - entropy = utils.toBuffer(entropy, entropyEnc); - add = utils.toBuffer(add, addEnc); - - assert(entropy.length >= (this.minEntropy / 8), - 'Not enough entropy. Minimum is: ' + this.minEntropy + ' bits'); - - this._update(entropy.concat(add || [])); - this.reseed = 1; -}; - -HmacDRBG.prototype.generate = function generate(len, enc, add, addEnc) { - if (this.reseed > this.reseedInterval) - throw new Error('Reseed is required'); - - // Optional encoding - if (typeof enc !== 'string') { - addEnc = add; - add = enc; - enc = null; - } - - // Optional additional data - if (add) { - add = utils.toArray(add, addEnc); - this._update(add); - } - - var temp = []; - while (temp.length < len) { - this.V = this._hmac().update(this.V).digest(); - temp = temp.concat(this.V); - } - - var res = temp.slice(0, len); - this._update(add); - this.reseed++; - return utils.encode(res, enc); -}; - -},{"../elliptic":74,"assert":194,"hash.js":88}],85:[function(require,module,exports){ -var assert = require('assert'); -var bn = require('bn.js'); - -var utils = exports; - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 !== 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -utils.toArray = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -utils.toHex = toHex; - -utils.encode = function encode(arr, enc) { - if (enc === 'hex') - return toHex(arr); - else - return arr; -}; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -utils.zero2 = zero2; - -// Represent num in a w-NAF form -function getNAF(num, w) { - var naf = []; - var ws = 1 << (w + 1); - var k = num.clone(); - while (k.cmpn(1) >= 0) { - var z; - if (k.isOdd()) { - var mod = k.andln(ws - 1); - if (mod > (ws >> 1) - 1) - z = (ws >> 1) - mod; - else - z = mod; - k.isubn(z); - } else { - z = 0; - } - naf.push(z); - - // Optimization, shift by word if possible - var shift = (k.cmpn(0) !== 0 && k.andln(ws - 1) === 0) ? (w + 1) : 1; - for (var i = 1; i < shift; i++) - naf.push(0); - k.ishrn(shift); - } - - return naf; -} -utils.getNAF = getNAF; - -// Represent k1, k2 in a Joint Sparse Form -function getJSF(k1, k2) { - var jsf = [ - [], - [] - ]; - - k1 = k1.clone(); - k2 = k2.clone(); - var d1 = 0; - var d2 = 0; - while (k1.cmpn(-d1) > 0 || k2.cmpn(-d2) > 0) { - - // First phase - var m14 = (k1.andln(3) + d1) & 3; - var m24 = (k2.andln(3) + d2) & 3; - if (m14 === 3) - m14 = -1; - if (m24 === 3) - m24 = -1; - var u1; - if ((m14 & 1) === 0) { - u1 = 0; - } else { - var m8 = (k1.andln(7) + d1) & 7; - if ((m8 === 3 || m8 === 5) && m24 === 2) - u1 = -m14; - else - u1 = m14; - } - jsf[0].push(u1); - - var u2; - if ((m24 & 1) === 0) { - u2 = 0; - } else { - var m8 = (k2.andln(7) + d2) & 7; - if ((m8 === 3 || m8 === 5) && m14 === 2) - u2 = -m24; - else - u2 = m24; - } - jsf[1].push(u2); - - // Second phase - if (2 * d1 === u1 + 1) - d1 = 1 - d1; - if (2 * d2 === u2 + 1) - d2 = 1 - d2; - k1.ishrn(1); - k2.ishrn(1); - } - - return jsf; -} -utils.getJSF = getJSF; - -},{"assert":194,"bn.js":72}],86:[function(require,module,exports){ -var r; - -module.exports = function rand(len) { - if (!r) - r = new Rand(); - - return r.generate(len); -}; - -function Rand() { -} - -Rand.prototype.generate = function generate(len) { - return this._rand(len); -}; - -if (typeof window === 'object') { - if (window.crypto && window.crypto.getRandomValues) { - // Modern browsers - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - window.crypto.getRandomValues(arr); - return arr; - }; - } else if (window.msCrypto && window.msCrypto.getRandomValues) { - // IE - Rand.prototype._rand = function _rand(n) { - var arr = new Uint8Array(n); - window.msCrypto.getRandomValues(arr); - return arr; - }; - } else { - // Old junk - Rand.prototype._rand = function() { - throw new Error('Not implemented yet'); - }; - } -} else { - // Node.js - var crypto; - Rand.prototype._rand = function _rand(n) { - if (!crypto) - crypto = require('cry' + 'pto'); - return crypto.randomBytes(n); - }; -} - -},{}],87:[function(require,module,exports){ -module.exports={ - "name": "elliptic", - "version": "0.16.0", - "description": "EC cryptography", - "main": "lib/elliptic.js", - "scripts": { - "test": "mocha --reporter=spec test/*-test.js" - }, - "repository": { - "type": "git", - "url": "git@github.com:indutny/elliptic" - }, - "keywords": [ - "EC", - "Elliptic", - "curve", - "Cryptography" - ], - "author": { - "name": "Fedor Indutny", - "email": "fedor@indutny.com" - }, - "license": "MIT", - "bugs": { - "url": "https://github.com/indutny/elliptic/issues" - }, - "homepage": "https://github.com/indutny/elliptic", - "devDependencies": { - "browserify": "^3.44.2", - "mocha": "^1.18.2", - "uglify-js": "^2.4.13" - }, - "dependencies": { - "bn.js": "^0.16.0", - "brorand": "^1.0.1", - "hash.js": "^0.3.2", - "inherits": "^2.0.1" - }, - "readme": "# Elliptic [![Build Status](https://secure.travis-ci.org/indutny/elliptic.png)](http://travis-ci.org/indutny/elliptic)\n\nFast elliptic-curve cryptography in a plain javascript implementation.\n\nNOTE: Please take a look at http://safecurves.cr.yp.to/ before choosing a curve\nfor your cryptography operations.\n\n## Incentive\n\nECC is much slower than regular RSA cryptography, the JS implementations are\neven more slower.\n\n## Benchmarks\n\n```bash\n$ node benchmarks/index.js\nBenchmarking: sign\nelliptic#sign x 262 ops/sec ±0.51% (177 runs sampled)\neccjs#sign x 55.91 ops/sec ±0.90% (144 runs sampled)\n------------------------\nFastest is elliptic#sign\n========================\nBenchmarking: verify\nelliptic#verify x 113 ops/sec ±0.50% (166 runs sampled)\neccjs#verify x 48.56 ops/sec ±0.36% (125 runs sampled)\n------------------------\nFastest is elliptic#verify\n========================\nBenchmarking: gen\nelliptic#gen x 294 ops/sec ±0.43% (176 runs sampled)\neccjs#gen x 62.25 ops/sec ±0.63% (129 runs sampled)\n------------------------\nFastest is elliptic#gen\n========================\nBenchmarking: ecdh\nelliptic#ecdh x 136 ops/sec ±0.85% (156 runs sampled)\n------------------------\nFastest is elliptic#ecdh\n========================\n```\n\n## API\n\n### ECDSA\n\n```javascript\nvar EC = require('elliptic').ec;\n\n// Create and initialize EC context\n// (better do it once and reuse it)\nvar ec = new EC('secp256k1');\n\n// Generate keys\nvar key = ec.genKeyPair();\n\n// Sign message (must be an array, or it'll be treated as a hex sequence)\nvar msg = [ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ];\nvar signature = key.sign(msg);\n\n// Export DER encoded signature in Array\nvar derSign = signature.toDER();\n\n// Verify signature\nconsole.log(key.verify(msg, derSign));\n```\n\n### ECDH\n\n```javascript\n// Generate keys\nvar key1 = ec.genKeyPair();\nvar key2 = ec.genKeyPair();\n\nvar shared1 = key1.derive(key2.getPublic());\nvar shared2 = key2.derive(key1.getPublic());\n\nconsole.log('Both shared secrets are BN instances');\nconsole.log(shared1.toString(16));\nconsole.log(shared2.toString(16));\n```\n\nNOTE: `.derive()` returns a [BN][1] instance.\n\n## Supported curves\n\nElliptic.js support following curve types:\n\n* Short Weierstrass\n* Montgomery\n* Edwards\n* Twisted Edwards\n\nFollowing curve 'presets' are embedded into the library:\n\n* `secp256k1`\n* `p192`\n* `p224`\n* `p256`\n* `curve25519`\n* `ed25519`\n\nNOTE: That `curve25519` could not be used for ECDSA, use `ed25519` instead.\n\n### Implementation details\n\nECDSA is using deterministic `k` value generation as per [RFC6979][0]. Most of\nthe curve operations are performed on non-affine coordinates (either projective\nor extended), various windowing techniques are used for different cases.\n\nAll operations are performed in reduction context using [bn.js][1], hashing is\nprovided by [hash.js][2]\n\n#### LICENSE\n\nThis software is licensed under the MIT License.\n\nCopyright Fedor Indutny, 2014.\n\nPermission is hereby granted, free of charge, to any person obtaining a\ncopy of this software and associated documentation files (the\n\"Software\"), to deal in the Software without restriction, including\nwithout limitation the rights to use, copy, modify, merge, publish,\ndistribute, sublicense, and/or sell copies of the Software, and to permit\npersons to whom the Software is furnished to do so, subject to the\nfollowing conditions:\n\nThe above copyright notice and this permission notice shall be included\nin all copies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS\nOR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF\nMERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN\nNO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,\nDAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR\nOTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE\nUSE OR OTHER DEALINGS IN THE SOFTWARE.\n\n[0]: http://tools.ietf.org/html/rfc6979\n[1]: https://github.com/indutny/bn.js\n[2]: https://github.com/indutny/hash.js\n", - "readmeFilename": "README.md", - "_id": "elliptic@0.16.0", - "_shasum": "9bc84e75ccd97e3e452c97371726c535314d1a57", - "_from": "https://registry.npmjs.org/elliptic/-/elliptic-0.16.0.tgz", - "_resolved": "https://registry.npmjs.org/elliptic/-/elliptic-0.16.0.tgz" -} - -},{}],88:[function(require,module,exports){ -var hash = exports; - -hash.utils = require('./hash/utils'); -hash.common = require('./hash/common'); -hash.sha = require('./hash/sha'); -hash.ripemd = require('./hash/ripemd'); -hash.hmac = require('./hash/hmac'); - -// Proxy hash functions to the main object -hash.sha1 = hash.sha.sha1; -hash.sha256 = hash.sha.sha256; -hash.sha224 = hash.sha.sha224; -hash.ripemd160 = hash.ripemd.ripemd160; - -},{"./hash/common":89,"./hash/hmac":90,"./hash/ripemd":91,"./hash/sha":92,"./hash/utils":93}],89:[function(require,module,exports){ -var hash = require('../hash'); -var utils = hash.utils; -var assert = utils.assert; - -function BlockHash() { - this.pending = null; - this.pendingTotal = 0; - this.blockSize = this.constructor.blockSize; - this.outSize = this.constructor.outSize; - this.hmacStrength = this.constructor.hmacStrength; - this.endian = 'big'; - - this._delta8 = this.blockSize / 8; - this._delta32 = this.blockSize / 32; -} -exports.BlockHash = BlockHash; - -BlockHash.prototype.update = function update(msg, enc) { - // Convert message to array, pad it, and join into 32bit blocks - msg = utils.toArray(msg, enc); - if (!this.pending) - this.pending = msg; - else - this.pending = this.pending.concat(msg); - this.pendingTotal += msg.length; - - // Enough data, try updating - if (this.pending.length >= this._delta8) { - msg = this.pending; - - // Process pending data in blocks - var r = msg.length % this._delta8; - this.pending = msg.slice(msg.length - r, msg.length); - if (this.pending.length === 0) - this.pending = null; - - msg = utils.join32(msg, 0, msg.length - r, this.endian); - for (var i = 0; i < msg.length; i += this._delta32) - this._update(msg, i, i + this._delta32); - } - - return this; -}; - -BlockHash.prototype.digest = function digest(enc) { - this.update(this._pad()); - assert(this.pending === null); - - return this._digest(enc); -}; - -BlockHash.prototype._pad = function pad() { - var len = this.pendingTotal; - var bytes = this._delta8; - var k = bytes - ((len + 8) % bytes); - var res = new Array(k + 8); - res[0] = 0x80; - for (var i = 1; i < k; i++) - res[i] = 0; - - // Append length - len <<= 3; - if (this.endian === 'big') { - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = (len >>> 24) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = len & 0xff; - } else { - res[i++] = len & 0xff; - res[i++] = (len >>> 8) & 0xff; - res[i++] = (len >>> 16) & 0xff; - res[i++] = (len >>> 24) & 0xff; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - res[i++] = 0; - } - - return res; -} - -},{"../hash":88}],90:[function(require,module,exports){ -var hmac = exports; - -var hash = require('../hash'); -var utils = hash.utils; -var assert = utils.assert; - -function Hmac(hash, key, enc) { - if (!(this instanceof Hmac)) - return new Hmac(hash, key, enc); - this.Hash = hash; - this.blockSize = hash.blockSize / 8; - this.outSize = hash.outSize / 8; - this.inner = null; - this.outer = null; - - this._init(utils.toArray(key, enc)); -} -module.exports = Hmac; - -Hmac.prototype._init = function init(key) { - // Shorten key, if needed - if (key.length > this.blockSize) - key = new this.Hash().update(key).digest(); - assert(key.length <= this.blockSize); - - // Add padding to key - for (var i = key.length; i < this.blockSize; i++) - key.push(0); - - for (var i = 0; i < key.length; i++) - key[i] ^= 0x36; - this.inner = new this.Hash().update(key); - - // 0x36 ^ 0x5c = 0x6a - for (var i = 0; i < key.length; i++) - key[i] ^= 0x6a; - this.outer = new this.Hash().update(key); -}; - -Hmac.prototype.update = function update(msg, enc) { - this.inner.update(msg, enc); - return this; -}; - -Hmac.prototype.digest = function digest(enc) { - this.outer.update(this.inner.digest()); - return this.outer.digest(enc); -}; - -},{"../hash":88}],91:[function(require,module,exports){ -var hash = require('../hash'); -var utils = hash.utils; - -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_3 = utils.sum32_3; -var sum32_4 = utils.sum32_4; -var BlockHash = hash.common.BlockHash; - -function RIPEMD160() { - if (!(this instanceof RIPEMD160)) - return new RIPEMD160(); - - BlockHash.call(this); - - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0 ]; - this.endian = 'little'; -} -utils.inherits(RIPEMD160, BlockHash); -exports.ripemd160 = RIPEMD160; - -RIPEMD160.blockSize = 512; -RIPEMD160.outSize = 160; -RIPEMD160.hmacStrength = 192; - -RIPEMD160.prototype._update = function update(msg, start) { - var A = this.h[0]; - var B = this.h[1]; - var C = this.h[2]; - var D = this.h[3]; - var E = this.h[4]; - var Ah = A; - var Bh = B; - var Ch = C; - var Dh = D; - var Eh = E; - for (var j = 0; j < 80; j++) { - var T = sum32( - rotl32( - sum32_4(A, f(j, B, C, D), msg[r[j] + start], K(j)), - s[j]), - E); - A = E; - E = D; - D = rotl32(C, 10); - C = B; - B = T; - T = sum32( - rotl32( - sum32_4(Ah, f(79 - j, Bh, Ch, Dh), msg[rh[j] + start], Kh(j)), - sh[j]), - Eh); - Ah = Eh; - Eh = Dh; - Dh = rotl32(Ch, 10); - Ch = Bh; - Bh = T; - } - T = sum32_3(this.h[1], C, Dh); - this.h[1] = sum32_3(this.h[2], D, Eh); - this.h[2] = sum32_3(this.h[3], E, Ah); - this.h[3] = sum32_3(this.h[4], A, Bh); - this.h[4] = sum32_3(this.h[0], B, Ch); - this.h[0] = T; -}; - -RIPEMD160.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'little'); - else - return utils.split32(this.h, 'little'); -}; - -function f(j, x, y, z) { - if (j <= 15) - return x ^ y ^ z; - else if (j <= 31) - return (x & y) | ((~x) & z); - else if (j <= 47) - return (x | (~y)) ^ z; - else if (j <= 63) - return (x & z) | (y & (~z)); - else - return x ^ (y | (~z)); -} - -function K(j) { - if (j <= 15) - return 0x00000000; - else if (j <= 31) - return 0x5a827999; - else if (j <= 47) - return 0x6ed9eba1; - else if (j <= 63) - return 0x8f1bbcdc; - else - return 0xa953fd4e; -} - -function Kh(j) { - if (j <= 15) - return 0x50a28be6; - else if (j <= 31) - return 0x5c4dd124; - else if (j <= 47) - return 0x6d703ef3; - else if (j <= 63) - return 0x7a6d76e9; - else - return 0x00000000; -} - -var r = [ - 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, - 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8, - 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12, - 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2, - 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13, -]; - -var rh = [ - 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12, - 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2, - 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13, - 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14, - 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 -]; - -var s = [ - 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8, - 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12, - 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5, - 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12, - 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6, -]; - -var sh = [ - 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6, - 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11, - 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5, - 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8, - 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 -]; - -},{"../hash":88}],92:[function(require,module,exports){ -var hash = require('../hash'); -var utils = hash.utils; -var assert = utils.assert; - -var rotr32 = utils.rotr32; -var rotl32 = utils.rotl32; -var sum32 = utils.sum32; -var sum32_4 = utils.sum32_4; -var sum32_5 = utils.sum32_5; -var BlockHash = hash.common.BlockHash; - -var sha256_K = [ - 0x428a2f98, 0x71374491, 0xb5c0fbcf, 0xe9b5dba5, - 0x3956c25b, 0x59f111f1, 0x923f82a4, 0xab1c5ed5, - 0xd807aa98, 0x12835b01, 0x243185be, 0x550c7dc3, - 0x72be5d74, 0x80deb1fe, 0x9bdc06a7, 0xc19bf174, - 0xe49b69c1, 0xefbe4786, 0x0fc19dc6, 0x240ca1cc, - 0x2de92c6f, 0x4a7484aa, 0x5cb0a9dc, 0x76f988da, - 0x983e5152, 0xa831c66d, 0xb00327c8, 0xbf597fc7, - 0xc6e00bf3, 0xd5a79147, 0x06ca6351, 0x14292967, - 0x27b70a85, 0x2e1b2138, 0x4d2c6dfc, 0x53380d13, - 0x650a7354, 0x766a0abb, 0x81c2c92e, 0x92722c85, - 0xa2bfe8a1, 0xa81a664b, 0xc24b8b70, 0xc76c51a3, - 0xd192e819, 0xd6990624, 0xf40e3585, 0x106aa070, - 0x19a4c116, 0x1e376c08, 0x2748774c, 0x34b0bcb5, - 0x391c0cb3, 0x4ed8aa4a, 0x5b9cca4f, 0x682e6ff3, - 0x748f82ee, 0x78a5636f, 0x84c87814, 0x8cc70208, - 0x90befffa, 0xa4506ceb, 0xbef9a3f7, 0xc67178f2 -]; - -var sha1_K = [ - 0x5A827999, 0x6ED9EBA1, - 0x8F1BBCDC, 0xCA62C1D6 -]; - -function SHA256() { - if (!(this instanceof SHA256)) - return new SHA256(); - - BlockHash.call(this); - this.h = [ 0x6a09e667, 0xbb67ae85, 0x3c6ef372, 0xa54ff53a, - 0x510e527f, 0x9b05688c, 0x1f83d9ab, 0x5be0cd19 ]; - this.k = sha256_K; - this.W = new Array(64); -} -utils.inherits(SHA256, BlockHash); -exports.sha256 = SHA256; - -SHA256.blockSize = 512; -SHA256.outSize = 256; -SHA256.hmacStrength = 192; - -SHA256.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - for (; i < W.length; i++) - W[i] = sum32_4(g1_256(W[i - 2]), W[i - 7], g0_256(W[i - 15]), W[i - 16]); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - var f = this.h[5]; - var g = this.h[6]; - var h = this.h[7]; - - assert(this.k.length === W.length); - for (var i = 0; i < W.length; i++) { - var T1 = sum32_5(h, s1_256(e), ch32(e, f, g), this.k[i], W[i]); - var T2 = sum32(s0_256(a), maj32(a, b, c)); - h = g; - g = f; - f = e; - e = sum32(d, T1); - d = c; - c = b; - b = a; - a = sum32(T1, T2); - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); - this.h[5] = sum32(this.h[5], f); - this.h[6] = sum32(this.h[6], g); - this.h[7] = sum32(this.h[7], h); -}; - -SHA256.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function SHA224() { - if (!(this instanceof SHA224)) - return new SHA224(); - - SHA256.call(this); - this.h = [ 0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939, - 0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4 ]; -} -utils.inherits(SHA224, SHA256); -exports.sha224 = SHA224; - -SHA224.blockSize = 512; -SHA224.outSize = 224; -SHA224.hmacStrength = 192; - -SHA224.prototype._digest = function digest(enc) { - // Just truncate output - if (enc === 'hex') - return utils.toHex32(this.h.slice(0, 7), 'big'); - else - return utils.split32(this.h.slice(0, 7), 'big'); -}; - -function SHA1() { - if (!(this instanceof SHA1)) - return new SHA1(); - - BlockHash.call(this); - this.h = [ 0x67452301, 0xefcdab89, 0x98badcfe, - 0x10325476, 0xc3d2e1f0 ]; - this.W = new Array(80); -} - -utils.inherits(SHA1, BlockHash); -exports.sha1 = SHA1; - -SHA1.blockSize = 512; -SHA1.outSize = 160; -SHA1.hmacStrength = 80; - -SHA1.prototype._update = function _update(msg, start) { - var W = this.W; - - for (var i = 0; i < 16; i++) - W[i] = msg[start + i]; - - for(; i < W.length; i++) - W[i] = rotl32(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16], 1); - - var a = this.h[0]; - var b = this.h[1]; - var c = this.h[2]; - var d = this.h[3]; - var e = this.h[4]; - - for (var i = 0; i < W.length; i++) { - var s = ~~(i / 20); - var t = sum32_5(rotl32(a, 5), ft_1(s, b, c, d), e, W[i], sha1_K[s]); - e = d; - d = c; - c = rotl32(b, 30); - b = a; - a = t; - } - - this.h[0] = sum32(this.h[0], a); - this.h[1] = sum32(this.h[1], b); - this.h[2] = sum32(this.h[2], c); - this.h[3] = sum32(this.h[3], d); - this.h[4] = sum32(this.h[4], e); -}; - -SHA1.prototype._digest = function digest(enc) { - if (enc === 'hex') - return utils.toHex32(this.h, 'big'); - else - return utils.split32(this.h, 'big'); -}; - -function ch32(x, y, z) { - return (x & y) ^ ((~x) & z); -} - -function maj32(x, y, z) { - return (x & y) ^ (x & z) ^ (y & z); -} - -function p32(x, y, z) { - return x ^ y ^ z; -} - -function s0_256(x) { - return rotr32(x, 2) ^ rotr32(x, 13) ^ rotr32(x, 22); -} - -function s1_256(x) { - return rotr32(x, 6) ^ rotr32(x, 11) ^ rotr32(x, 25); -} - -function g0_256(x) { - return rotr32(x, 7) ^ rotr32(x, 18) ^ (x >>> 3); -} - -function g1_256(x) { - return rotr32(x, 17) ^ rotr32(x, 19) ^ (x >>> 10); -} - -function ft_1(s, x, y, z) { - if (s === 0) - return ch32(x, y, z); - if (s === 1 || s === 3) - return p32(x, y, z) - if (s === 2) - return maj32(x, y, z) -} - -},{"../hash":88}],93:[function(require,module,exports){ -var utils = exports; -var inherits = require('inherits'); - -function toArray(msg, enc) { - if (Array.isArray(msg)) - return msg.slice(); - if (!msg) - return []; - var res = []; - if (typeof msg === 'string') { - if (!enc) { - for (var i = 0; i < msg.length; i++) { - var c = msg.charCodeAt(i); - var hi = c >> 8; - var lo = c & 0xff; - if (hi) - res.push(hi, lo); - else - res.push(lo); - } - } else if (enc === 'hex') { - msg = msg.replace(/[^a-z0-9]+/ig, ''); - if (msg.length % 2 != 0) - msg = '0' + msg; - for (var i = 0; i < msg.length; i += 2) - res.push(parseInt(msg[i] + msg[i + 1], 16)); - } - } else { - for (var i = 0; i < msg.length; i++) - res[i] = msg[i] | 0; - } - return res; -} -utils.toArray = toArray; - -function toHex(msg) { - var res = ''; - for (var i = 0; i < msg.length; i++) - res += zero2(msg[i].toString(16)); - return res; -} -utils.toHex = toHex; - -function toHex32(msg, endian) { - var res = ''; - for (var i = 0; i < msg.length; i++) { - var w = msg[i]; - if (endian === 'little') { - w = (w >>> 24) | - ((w >>> 8) & 0xff00) | - ((w << 8) & 0xff0000) | - ((w & 0xff) << 24); - if (w < 0) - w += 0x100000000; - } - res += zero8(w.toString(16)); - } - return res; -} -utils.toHex32 = toHex32; - -function zero2(word) { - if (word.length === 1) - return '0' + word; - else - return word; -} -utils.zero2 = zero2; - -function zero8(word) { - if (word.length === 7) - return '0' + word; - else if (word.length === 6) - return '00' + word; - else if (word.length === 5) - return '000' + word; - else if (word.length === 4) - return '0000' + word; - else if (word.length === 3) - return '00000' + word; - else if (word.length === 2) - return '000000' + word; - else if (word.length === 1) - return '0000000' + word; - else - return word; -} -utils.zero8 = zero8; - -function join32(msg, start, end, endian) { - var len = end - start; - assert(len % 4 === 0); - var res = new Array(len / 4); - for (var i = 0, k = start; i < res.length; i++, k += 4) { - var w; - if (endian === 'big') - w = (msg[k] << 24) | (msg[k + 1] << 16) | (msg[k + 2] << 8) | msg[k + 3]; - else - w = (msg[k + 3] << 24) | (msg[k + 2] << 16) | (msg[k + 1] << 8) | msg[k]; - if (w < 0) - w += 0x100000000; - res[i] = w; - } - return res; -} -utils.join32 = join32; - -function split32(msg, endian) { - var res = new Array(msg.length * 4); - for (var i = 0, k = 0; i < msg.length; i++, k += 4) { - var m = msg[i]; - if (endian === 'big') { - res[k] = m >>> 24; - res[k + 1] = (m >>> 16) & 0xff; - res[k + 2] = (m >>> 8) & 0xff; - res[k + 3] = m & 0xff; - } else { - res[k + 3] = m >>> 24; - res[k + 2] = (m >>> 16) & 0xff; - res[k + 1] = (m >>> 8) & 0xff; - res[k] = m & 0xff; - } - } - return res; -} -utils.split32 = split32; - -function rotr32(w, b) { - return (w >>> b) | (w << (32 - b)); -} -utils.rotr32 = rotr32; - -function rotl32(w, b) { - return (w << b) | (w >>> (32 - b)); -} -utils.rotl32 = rotl32; - -function sum32(a, b) { - var r = (a + b) & 0xffffffff; - if (r < 0) - r += 0x100000000; - return r; -} -utils.sum32 = sum32; - -function sum32_3(a, b, c) { - var r = (a + b + c) & 0xffffffff; - if (r < 0) - r += 0x100000000; - return r; -} -utils.sum32_3 = sum32_3; - -function sum32_4(a, b, c, d) { - var r = (a + b + c + d) & 0xffffffff; - if (r < 0) - r += 0x100000000; - return r; -} -utils.sum32_4 = sum32_4; - -function sum32_5(a, b, c, d, e) { - var r = (a + b + c + d + e) & 0xffffffff; - if (r < 0) - r += 0x100000000; - return r; -} -utils.sum32_5 = sum32_5; - -function assert(cond, msg) { - if (!cond) - throw new Error(msg || 'Assertion failed'); -} -utils.assert = assert; - -utils.inherits = inherits; - -},{"inherits":94}],94:[function(require,module,exports){ -if (typeof Object.create === 'function') { - // implementation from standard node.js 'util' module - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - ctor.prototype = Object.create(superCtor.prototype, { - constructor: { - value: ctor, - enumerable: false, - writable: true, - configurable: true - } - }); - }; -} else { - // old school shim for old browsers - module.exports = function inherits(ctor, superCtor) { - ctor.super_ = superCtor - var TempCtor = function () {} - TempCtor.prototype = superCtor.prototype - ctor.prototype = new TempCtor() - ctor.prototype.constructor = ctor - } -} - -},{}],95:[function(require,module,exports){ -(function (global){ -/** - * @license - * Lo-Dash 2.4.1 (Custom Build) - * Build: `lodash modern -o ./dist/lodash.js` - * Copyright 2012-2013 The Dojo Foundation - * Based on Underscore.js 1.5.2 - * Copyright 2009-2013 Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors - * Available under MIT license - */ -;(function() { - - /** Used as a safe reference for `undefined` in pre ES5 environments */ - var undefined; - - /** Used to pool arrays and objects used internally */ - var arrayPool = [], - objectPool = []; - - /** Used to generate unique IDs */ - var idCounter = 0; - - /** Used to prefix keys to avoid issues with `__proto__` and properties on `Object.prototype` */ - var keyPrefix = +new Date + ''; - - /** Used as the size when optimizations are enabled for large arrays */ - var largeArraySize = 75; - - /** Used as the max size of the `arrayPool` and `objectPool` */ - var maxPoolSize = 40; - - /** Used to detect and test whitespace */ - var whitespace = ( - // whitespace - ' \t\x0B\f\xA0\ufeff' + - - // line terminators - '\n\r\u2028\u2029' + - - // unicode category "Zs" space separators - '\u1680\u180e\u2000\u2001\u2002\u2003\u2004\u2005\u2006\u2007\u2008\u2009\u200a\u202f\u205f\u3000' - ); - - /** Used to match empty string literals in compiled template source */ - var reEmptyStringLeading = /\b__p \+= '';/g, - reEmptyStringMiddle = /\b(__p \+=) '' \+/g, - reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; - - /** - * Used to match ES6 template delimiters - * http://people.mozilla.org/~jorendorff/es6-draft.html#sec-literals-string-literals - */ - var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; - - /** Used to match regexp flags from their coerced string values */ - var reFlags = /\w*$/; - - /** Used to detected named functions */ - var reFuncName = /^\s*function[ \n\r\t]+\w/; - - /** Used to match "interpolate" template delimiters */ - var reInterpolate = /<%=([\s\S]+?)%>/g; - - /** Used to match leading whitespace and zeros to be removed */ - var reLeadingSpacesAndZeros = RegExp('^[' + whitespace + ']*0+(?=.$)'); - - /** Used to ensure capturing order of template delimiters */ - var reNoMatch = /($^)/; - - /** Used to detect functions containing a `this` reference */ - var reThis = /\bthis\b/; - - /** Used to match unescaped characters in compiled string literals */ - var reUnescapedString = /['\n\r\t\u2028\u2029\\]/g; - - /** Used to assign default `context` object properties */ - var contextProps = [ - 'Array', 'Boolean', 'Date', 'Function', 'Math', 'Number', 'Object', - 'RegExp', 'String', '_', 'attachEvent', 'clearTimeout', 'isFinite', 'isNaN', - 'parseInt', 'setTimeout' - ]; - - /** Used to make template sourceURLs easier to identify */ - var templateCounter = 0; - - /** `Object#toString` result shortcuts */ - var argsClass = '[object Arguments]', - arrayClass = '[object Array]', - boolClass = '[object Boolean]', - dateClass = '[object Date]', - funcClass = '[object Function]', - numberClass = '[object Number]', - objectClass = '[object Object]', - regexpClass = '[object RegExp]', - stringClass = '[object String]'; - - /** Used to identify object classifications that `_.clone` supports */ - var cloneableClasses = {}; - cloneableClasses[funcClass] = false; - cloneableClasses[argsClass] = cloneableClasses[arrayClass] = - cloneableClasses[boolClass] = cloneableClasses[dateClass] = - cloneableClasses[numberClass] = cloneableClasses[objectClass] = - cloneableClasses[regexpClass] = cloneableClasses[stringClass] = true; - - /** Used as an internal `_.debounce` options object */ - var debounceOptions = { - 'leading': false, - 'maxWait': 0, - 'trailing': false - }; - - /** Used as the property descriptor for `__bindData__` */ - var descriptor = { - 'configurable': false, - 'enumerable': false, - 'value': null, - 'writable': false - }; - - /** Used to determine if values are of the language type Object */ - var objectTypes = { - 'boolean': false, - 'function': true, - 'object': true, - 'number': false, - 'string': false, - 'undefined': false - }; - - /** Used to escape characters for inclusion in compiled string literals */ - var stringEscapes = { - '\\': '\\', - "'": "'", - '\n': 'n', - '\r': 'r', - '\t': 't', - '\u2028': 'u2028', - '\u2029': 'u2029' - }; - - /** Used as a reference to the global object */ - var root = (objectTypes[typeof window] && window) || this; - - /** Detect free variable `exports` */ - var freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports; - - /** Detect free variable `module` */ - var freeModule = objectTypes[typeof module] && module && !module.nodeType && module; - - /** Detect the popular CommonJS extension `module.exports` */ - var moduleExports = freeModule && freeModule.exports === freeExports && freeExports; - - /** Detect free variable `global` from Node.js or Browserified code and use it as `root` */ - var freeGlobal = objectTypes[typeof global] && global; - if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) { - root = freeGlobal; - } - - /*--------------------------------------------------------------------------*/ - - /** - * The base implementation of `_.indexOf` without support for binary searches - * or `fromIndex` constraints. - * - * @private - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {number} Returns the index of the matched value or `-1`. - */ - function baseIndexOf(array, value, fromIndex) { - var index = (fromIndex || 0) - 1, - length = array ? array.length : 0; - - while (++index < length) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * An implementation of `_.contains` for cache objects that mimics the return - * signature of `_.indexOf` by returning `0` if the value is found, else `-1`. - * - * @private - * @param {Object} cache The cache object to inspect. - * @param {*} value The value to search for. - * @returns {number} Returns `0` if `value` is found, else `-1`. - */ - function cacheIndexOf(cache, value) { - var type = typeof value; - cache = cache.cache; - - if (type == 'boolean' || value == null) { - return cache[value] ? 0 : -1; - } - if (type != 'number' && type != 'string') { - type = 'object'; - } - var key = type == 'number' ? value : keyPrefix + value; - cache = (cache = cache[type]) && cache[key]; - - return type == 'object' - ? (cache && baseIndexOf(cache, value) > -1 ? 0 : -1) - : (cache ? 0 : -1); - } - - /** - * Adds a given value to the corresponding cache object. - * - * @private - * @param {*} value The value to add to the cache. - */ - function cachePush(value) { - var cache = this.cache, - type = typeof value; - - if (type == 'boolean' || value == null) { - cache[value] = true; - } else { - if (type != 'number' && type != 'string') { - type = 'object'; - } - var key = type == 'number' ? value : keyPrefix + value, - typeCache = cache[type] || (cache[type] = {}); - - if (type == 'object') { - (typeCache[key] || (typeCache[key] = [])).push(value); - } else { - typeCache[key] = true; - } - } - } - - /** - * Used by `_.max` and `_.min` as the default callback when a given - * collection is a string value. - * - * @private - * @param {string} value The character to inspect. - * @returns {number} Returns the code unit of given character. - */ - function charAtCallback(value) { - return value.charCodeAt(0); - } - - /** - * Used by `sortBy` to compare transformed `collection` elements, stable sorting - * them in ascending order. - * - * @private - * @param {Object} a The object to compare to `b`. - * @param {Object} b The object to compare to `a`. - * @returns {number} Returns the sort order indicator of `1` or `-1`. - */ - function compareAscending(a, b) { - var ac = a.criteria, - bc = b.criteria, - index = -1, - length = ac.length; - - while (++index < length) { - var value = ac[index], - other = bc[index]; - - if (value !== other) { - if (value > other || typeof value == 'undefined') { - return 1; - } - if (value < other || typeof other == 'undefined') { - return -1; - } - } - } - // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications - // that causes it, under certain circumstances, to return the same value for - // `a` and `b`. See https://github.com/jashkenas/underscore/pull/1247 - // - // This also ensures a stable sort in V8 and other engines. - // See http://code.google.com/p/v8/issues/detail?id=90 - return a.index - b.index; - } - - /** - * Creates a cache object to optimize linear searches of large arrays. - * - * @private - * @param {Array} [array=[]] The array to search. - * @returns {null|Object} Returns the cache object or `null` if caching should not be used. - */ - function createCache(array) { - var index = -1, - length = array.length, - first = array[0], - mid = array[(length / 2) | 0], - last = array[length - 1]; - - if (first && typeof first == 'object' && - mid && typeof mid == 'object' && last && typeof last == 'object') { - return false; - } - var cache = getObject(); - cache['false'] = cache['null'] = cache['true'] = cache['undefined'] = false; - - var result = getObject(); - result.array = array; - result.cache = cache; - result.push = cachePush; - - while (++index < length) { - result.push(array[index]); - } - return result; - } - - /** - * Used by `template` to escape characters for inclusion in compiled - * string literals. - * - * @private - * @param {string} match The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeStringChar(match) { - return '\\' + stringEscapes[match]; - } - - /** - * Gets an array from the array pool or creates a new one if the pool is empty. - * - * @private - * @returns {Array} The array from the pool. - */ - function getArray() { - return arrayPool.pop() || []; - } - - /** - * Gets an object from the object pool or creates a new one if the pool is empty. - * - * @private - * @returns {Object} The object from the pool. - */ - function getObject() { - return objectPool.pop() || { - 'array': null, - 'cache': null, - 'criteria': null, - 'false': false, - 'index': 0, - 'null': false, - 'number': null, - 'object': null, - 'push': null, - 'string': null, - 'true': false, - 'undefined': false, - 'value': null - }; - } - - /** - * Releases the given array back to the array pool. - * - * @private - * @param {Array} [array] The array to release. - */ - function releaseArray(array) { - array.length = 0; - if (arrayPool.length < maxPoolSize) { - arrayPool.push(array); - } - } - - /** - * Releases the given object back to the object pool. - * - * @private - * @param {Object} [object] The object to release. - */ - function releaseObject(object) { - var cache = object.cache; - if (cache) { - releaseObject(cache); - } - object.array = object.cache = object.criteria = object.object = object.number = object.string = object.value = null; - if (objectPool.length < maxPoolSize) { - objectPool.push(object); - } - } - - /** - * Slices the `collection` from the `start` index up to, but not including, - * the `end` index. - * - * Note: This function is used instead of `Array#slice` to support node lists - * in IE < 9 and to ensure dense arrays are returned. - * - * @private - * @param {Array|Object|string} collection The collection to slice. - * @param {number} start The start index. - * @param {number} end The end index. - * @returns {Array} Returns the new array. - */ - function slice(array, start, end) { - start || (start = 0); - if (typeof end == 'undefined') { - end = array ? array.length : 0; - } - var index = -1, - length = end - start || 0, - result = Array(length < 0 ? 0 : length); - - while (++index < length) { - result[index] = array[start + index]; - } - return result; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Create a new `lodash` function using the given context object. - * - * @static - * @memberOf _ - * @category Utilities - * @param {Object} [context=root] The context object. - * @returns {Function} Returns the `lodash` function. - */ - function runInContext(context) { - // Avoid issues with some ES3 environments that attempt to use values, named - // after built-in constructors like `Object`, for the creation of literals. - // ES5 clears this up by stating that literals must use built-in constructors. - // See http://es5.github.io/#x11.1.5. - context = context ? _.defaults(root.Object(), context, _.pick(root, contextProps)) : root; - - /** Native constructor references */ - var Array = context.Array, - Boolean = context.Boolean, - Date = context.Date, - Function = context.Function, - Math = context.Math, - Number = context.Number, - Object = context.Object, - RegExp = context.RegExp, - String = context.String, - TypeError = context.TypeError; - - /** - * Used for `Array` method references. - * - * Normally `Array.prototype` would suffice, however, using an array literal - * avoids issues in Narwhal. - */ - var arrayRef = []; - - /** Used for native method references */ - var objectProto = Object.prototype; - - /** Used to restore the original `_` reference in `noConflict` */ - var oldDash = context._; - - /** Used to resolve the internal [[Class]] of values */ - var toString = objectProto.toString; - - /** Used to detect if a method is native */ - var reNative = RegExp('^' + - String(toString) - .replace(/[.*+?^${}()|[\]\\]/g, '\\$&') - .replace(/toString| for [^\]]+/g, '.*?') + '$' - ); - - /** Native method shortcuts */ - var ceil = Math.ceil, - clearTimeout = context.clearTimeout, - floor = Math.floor, - fnToString = Function.prototype.toString, - getPrototypeOf = isNative(getPrototypeOf = Object.getPrototypeOf) && getPrototypeOf, - hasOwnProperty = objectProto.hasOwnProperty, - push = arrayRef.push, - setTimeout = context.setTimeout, - splice = arrayRef.splice, - unshift = arrayRef.unshift; - - /** Used to set meta data on functions */ - var defineProperty = (function() { - // IE 8 only accepts DOM elements - try { - var o = {}, - func = isNative(func = Object.defineProperty) && func, - result = func(o, o, o) && func; - } catch(e) { } - return result; - }()); - - /* Native method shortcuts for methods with the same name as other `lodash` methods */ - var nativeCreate = isNative(nativeCreate = Object.create) && nativeCreate, - nativeIsArray = isNative(nativeIsArray = Array.isArray) && nativeIsArray, - nativeIsFinite = context.isFinite, - nativeIsNaN = context.isNaN, - nativeKeys = isNative(nativeKeys = Object.keys) && nativeKeys, - nativeMax = Math.max, - nativeMin = Math.min, - nativeParseInt = context.parseInt, - nativeRandom = Math.random; - - /** Used to lookup a built-in constructor by [[Class]] */ - var ctorByClass = {}; - ctorByClass[arrayClass] = Array; - ctorByClass[boolClass] = Boolean; - ctorByClass[dateClass] = Date; - ctorByClass[funcClass] = Function; - ctorByClass[objectClass] = Object; - ctorByClass[numberClass] = Number; - ctorByClass[regexpClass] = RegExp; - ctorByClass[stringClass] = String; - - /*--------------------------------------------------------------------------*/ - - /** - * Creates a `lodash` object which wraps the given value to enable intuitive - * method chaining. - * - * In addition to Lo-Dash methods, wrappers also have the following `Array` methods: - * `concat`, `join`, `pop`, `push`, `reverse`, `shift`, `slice`, `sort`, `splice`, - * and `unshift` - * - * Chaining is supported in custom builds as long as the `value` method is - * implicitly or explicitly included in the build. - * - * The chainable wrapper functions are: - * `after`, `assign`, `bind`, `bindAll`, `bindKey`, `chain`, `compact`, - * `compose`, `concat`, `countBy`, `create`, `createCallback`, `curry`, - * `debounce`, `defaults`, `defer`, `delay`, `difference`, `filter`, `flatten`, - * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, - * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, - * `invoke`, `keys`, `map`, `max`, `memoize`, `merge`, `min`, `object`, `omit`, - * `once`, `pairs`, `partial`, `partialRight`, `pick`, `pluck`, `pull`, `push`, - * `range`, `reject`, `remove`, `rest`, `reverse`, `shuffle`, `slice`, `sort`, - * `sortBy`, `splice`, `tap`, `throttle`, `times`, `toArray`, `transform`, - * `union`, `uniq`, `unshift`, `unzip`, `values`, `where`, `without`, `wrap`, - * and `zip` - * - * The non-chainable wrapper functions are: - * `clone`, `cloneDeep`, `contains`, `escape`, `every`, `find`, `findIndex`, - * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `has`, `identity`, - * `indexOf`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, - * `isEmpty`, `isEqual`, `isFinite`, `isFunction`, `isNaN`, `isNull`, `isNumber`, - * `isObject`, `isPlainObject`, `isRegExp`, `isString`, `isUndefined`, `join`, - * `lastIndexOf`, `mixin`, `noConflict`, `parseInt`, `pop`, `random`, `reduce`, - * `reduceRight`, `result`, `shift`, `size`, `some`, `sortedIndex`, `runInContext`, - * `template`, `unescape`, `uniqueId`, and `value` - * - * The wrapper functions `first` and `last` return wrapped values when `n` is - * provided, otherwise they return unwrapped values. - * - * Explicit chaining can be enabled by using the `_.chain` method. - * - * @name _ - * @constructor - * @category Chaining - * @param {*} value The value to wrap in a `lodash` instance. - * @returns {Object} Returns a `lodash` instance. - * @example - * - * var wrapped = _([1, 2, 3]); - * - * // returns an unwrapped value - * wrapped.reduce(function(sum, num) { - * return sum + num; - * }); - * // => 6 - * - * // returns a wrapped value - * var squares = wrapped.map(function(num) { - * return num * num; - * }); - * - * _.isArray(squares); - * // => false - * - * _.isArray(squares.value()); - * // => true - */ - function lodash(value) { - // don't wrap if already wrapped, even if wrapped by a different `lodash` constructor - return (value && typeof value == 'object' && !isArray(value) && hasOwnProperty.call(value, '__wrapped__')) - ? value - : new lodashWrapper(value); - } - - /** - * A fast path for creating `lodash` wrapper objects. - * - * @private - * @param {*} value The value to wrap in a `lodash` instance. - * @param {boolean} chainAll A flag to enable chaining for all methods - * @returns {Object} Returns a `lodash` instance. - */ - function lodashWrapper(value, chainAll) { - this.__chain__ = !!chainAll; - this.__wrapped__ = value; - } - // ensure `new lodashWrapper` is an instance of `lodash` - lodashWrapper.prototype = lodash.prototype; - - /** - * An object used to flag environments features. - * - * @static - * @memberOf _ - * @type Object - */ - var support = lodash.support = {}; - - /** - * Detect if functions can be decompiled by `Function#toString` - * (all but PS3 and older Opera mobile browsers & avoided in Windows 8 apps). - * - * @memberOf _.support - * @type boolean - */ - support.funcDecomp = !isNative(context.WinRTError) && reThis.test(runInContext); - - /** - * Detect if `Function#name` is supported (all but IE). - * - * @memberOf _.support - * @type boolean - */ - support.funcNames = typeof Function.name == 'string'; - - /** - * By default, the template delimiters used by Lo-Dash are similar to those in - * embedded Ruby (ERB). Change the following template settings to use alternative - * delimiters. - * - * @static - * @memberOf _ - * @type Object - */ - lodash.templateSettings = { - - /** - * Used to detect `data` property values to be HTML-escaped. - * - * @memberOf _.templateSettings - * @type RegExp - */ - 'escape': /<%-([\s\S]+?)%>/g, - - /** - * Used to detect code to be evaluated. - * - * @memberOf _.templateSettings - * @type RegExp - */ - 'evaluate': /<%([\s\S]+?)%>/g, - - /** - * Used to detect `data` property values to inject. - * - * @memberOf _.templateSettings - * @type RegExp - */ - 'interpolate': reInterpolate, - - /** - * Used to reference the data object in the template text. - * - * @memberOf _.templateSettings - * @type string - */ - 'variable': '', - - /** - * Used to import variables into the compiled template. - * - * @memberOf _.templateSettings - * @type Object - */ - 'imports': { - - /** - * A reference to the `lodash` function. - * - * @memberOf _.templateSettings.imports - * @type Function - */ - '_': lodash - } - }; - - /*--------------------------------------------------------------------------*/ - - /** - * The base implementation of `_.bind` that creates the bound function and - * sets its meta data. - * - * @private - * @param {Array} bindData The bind data array. - * @returns {Function} Returns the new bound function. - */ - function baseBind(bindData) { - var func = bindData[0], - partialArgs = bindData[2], - thisArg = bindData[4]; - - function bound() { - // `Function#bind` spec - // http://es5.github.io/#x15.3.4.5 - if (partialArgs) { - // avoid `arguments` object deoptimizations by using `slice` instead - // of `Array.prototype.slice.call` and not assigning `arguments` to a - // variable as a ternary expression - var args = slice(partialArgs); - push.apply(args, arguments); - } - // mimic the constructor's `return` behavior - // http://es5.github.io/#x13.2.2 - if (this instanceof bound) { - // ensure `new bound` is an instance of `func` - var thisBinding = baseCreate(func.prototype), - result = func.apply(thisBinding, args || arguments); - return isObject(result) ? result : thisBinding; - } - return func.apply(thisArg, args || arguments); - } - setBindData(bound, bindData); - return bound; - } - - /** - * The base implementation of `_.clone` without argument juggling or support - * for `thisArg` binding. - * - * @private - * @param {*} value The value to clone. - * @param {boolean} [isDeep=false] Specify a deep clone. - * @param {Function} [callback] The function to customize cloning values. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates clones with source counterparts. - * @returns {*} Returns the cloned value. - */ - function baseClone(value, isDeep, callback, stackA, stackB) { - if (callback) { - var result = callback(value); - if (typeof result != 'undefined') { - return result; - } - } - // inspect [[Class]] - var isObj = isObject(value); - if (isObj) { - var className = toString.call(value); - if (!cloneableClasses[className]) { - return value; - } - var ctor = ctorByClass[className]; - switch (className) { - case boolClass: - case dateClass: - return new ctor(+value); - - case numberClass: - case stringClass: - return new ctor(value); - - case regexpClass: - result = ctor(value.source, reFlags.exec(value)); - result.lastIndex = value.lastIndex; - return result; - } - } else { - return value; - } - var isArr = isArray(value); - if (isDeep) { - // check for circular references and return corresponding clone - var initedStack = !stackA; - stackA || (stackA = getArray()); - stackB || (stackB = getArray()); - - var length = stackA.length; - while (length--) { - if (stackA[length] == value) { - return stackB[length]; - } - } - result = isArr ? ctor(value.length) : {}; - } - else { - result = isArr ? slice(value) : assign({}, value); - } - // add array properties assigned by `RegExp#exec` - if (isArr) { - if (hasOwnProperty.call(value, 'index')) { - result.index = value.index; - } - if (hasOwnProperty.call(value, 'input')) { - result.input = value.input; - } - } - // exit for shallow clone - if (!isDeep) { - return result; - } - // add the source value to the stack of traversed objects - // and associate it with its clone - stackA.push(value); - stackB.push(result); - - // recursively populate clone (susceptible to call stack limits) - (isArr ? forEach : forOwn)(value, function(objValue, key) { - result[key] = baseClone(objValue, isDeep, callback, stackA, stackB); - }); - - if (initedStack) { - releaseArray(stackA); - releaseArray(stackB); - } - return result; - } - - /** - * The base implementation of `_.create` without support for assigning - * properties to the created object. - * - * @private - * @param {Object} prototype The object to inherit from. - * @returns {Object} Returns the new object. - */ - function baseCreate(prototype, properties) { - return isObject(prototype) ? nativeCreate(prototype) : {}; - } - // fallback for browsers without `Object.create` - if (!nativeCreate) { - baseCreate = (function() { - function Object() {} - return function(prototype) { - if (isObject(prototype)) { - Object.prototype = prototype; - var result = new Object; - Object.prototype = null; - } - return result || context.Object(); - }; - }()); - } - - /** - * The base implementation of `_.createCallback` without support for creating - * "_.pluck" or "_.where" style callbacks. - * - * @private - * @param {*} [func=identity] The value to convert to a callback. - * @param {*} [thisArg] The `this` binding of the created callback. - * @param {number} [argCount] The number of arguments the callback accepts. - * @returns {Function} Returns a callback function. - */ - function baseCreateCallback(func, thisArg, argCount) { - if (typeof func != 'function') { - return identity; - } - // exit early for no `thisArg` or already bound by `Function#bind` - if (typeof thisArg == 'undefined' || !('prototype' in func)) { - return func; - } - var bindData = func.__bindData__; - if (typeof bindData == 'undefined') { - if (support.funcNames) { - bindData = !func.name; - } - bindData = bindData || !support.funcDecomp; - if (!bindData) { - var source = fnToString.call(func); - if (!support.funcNames) { - bindData = !reFuncName.test(source); - } - if (!bindData) { - // checks if `func` references the `this` keyword and stores the result - bindData = reThis.test(source); - setBindData(func, bindData); - } - } - } - // exit early if there are no `this` references or `func` is bound - if (bindData === false || (bindData !== true && bindData[1] & 1)) { - return func; - } - switch (argCount) { - case 1: return function(value) { - return func.call(thisArg, value); - }; - case 2: return function(a, b) { - return func.call(thisArg, a, b); - }; - case 3: return function(value, index, collection) { - return func.call(thisArg, value, index, collection); - }; - case 4: return function(accumulator, value, index, collection) { - return func.call(thisArg, accumulator, value, index, collection); - }; - } - return bind(func, thisArg); - } - - /** - * The base implementation of `createWrapper` that creates the wrapper and - * sets its meta data. - * - * @private - * @param {Array} bindData The bind data array. - * @returns {Function} Returns the new function. - */ - function baseCreateWrapper(bindData) { - var func = bindData[0], - bitmask = bindData[1], - partialArgs = bindData[2], - partialRightArgs = bindData[3], - thisArg = bindData[4], - arity = bindData[5]; - - var isBind = bitmask & 1, - isBindKey = bitmask & 2, - isCurry = bitmask & 4, - isCurryBound = bitmask & 8, - key = func; - - function bound() { - var thisBinding = isBind ? thisArg : this; - if (partialArgs) { - var args = slice(partialArgs); - push.apply(args, arguments); - } - if (partialRightArgs || isCurry) { - args || (args = slice(arguments)); - if (partialRightArgs) { - push.apply(args, partialRightArgs); - } - if (isCurry && args.length < arity) { - bitmask |= 16 & ~32; - return baseCreateWrapper([func, (isCurryBound ? bitmask : bitmask & ~3), args, null, thisArg, arity]); - } - } - args || (args = arguments); - if (isBindKey) { - func = thisBinding[key]; - } - if (this instanceof bound) { - thisBinding = baseCreate(func.prototype); - var result = func.apply(thisBinding, args); - return isObject(result) ? result : thisBinding; - } - return func.apply(thisBinding, args); - } - setBindData(bound, bindData); - return bound; - } - - /** - * The base implementation of `_.difference` that accepts a single array - * of values to exclude. - * - * @private - * @param {Array} array The array to process. - * @param {Array} [values] The array of values to exclude. - * @returns {Array} Returns a new array of filtered values. - */ - function baseDifference(array, values) { - var index = -1, - indexOf = getIndexOf(), - length = array ? array.length : 0, - isLarge = length >= largeArraySize && indexOf === baseIndexOf, - result = []; - - if (isLarge) { - var cache = createCache(values); - if (cache) { - indexOf = cacheIndexOf; - values = cache; - } else { - isLarge = false; - } - } - while (++index < length) { - var value = array[index]; - if (indexOf(values, value) < 0) { - result.push(value); - } - } - if (isLarge) { - releaseObject(values); - } - return result; - } - - /** - * The base implementation of `_.flatten` without support for callback - * shorthands or `thisArg` binding. - * - * @private - * @param {Array} array The array to flatten. - * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. - * @param {boolean} [isStrict=false] A flag to restrict flattening to arrays and `arguments` objects. - * @param {number} [fromIndex=0] The index to start from. - * @returns {Array} Returns a new flattened array. - */ - function baseFlatten(array, isShallow, isStrict, fromIndex) { - var index = (fromIndex || 0) - 1, - length = array ? array.length : 0, - result = []; - - while (++index < length) { - var value = array[index]; - - if (value && typeof value == 'object' && typeof value.length == 'number' - && (isArray(value) || isArguments(value))) { - // recursively flatten arrays (susceptible to call stack limits) - if (!isShallow) { - value = baseFlatten(value, isShallow, isStrict); - } - var valIndex = -1, - valLength = value.length, - resIndex = result.length; - - result.length += valLength; - while (++valIndex < valLength) { - result[resIndex++] = value[valIndex]; - } - } else if (!isStrict) { - result.push(value); - } - } - return result; - } - - /** - * The base implementation of `_.isEqual`, without support for `thisArg` binding, - * that allows partial "_.where" style comparisons. - * - * @private - * @param {*} a The value to compare. - * @param {*} b The other value to compare. - * @param {Function} [callback] The function to customize comparing values. - * @param {Function} [isWhere=false] A flag to indicate performing partial comparisons. - * @param {Array} [stackA=[]] Tracks traversed `a` objects. - * @param {Array} [stackB=[]] Tracks traversed `b` objects. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - */ - function baseIsEqual(a, b, callback, isWhere, stackA, stackB) { - // used to indicate that when comparing objects, `a` has at least the properties of `b` - if (callback) { - var result = callback(a, b); - if (typeof result != 'undefined') { - return !!result; - } - } - // exit early for identical values - if (a === b) { - // treat `+0` vs. `-0` as not equal - return a !== 0 || (1 / a == 1 / b); - } - var type = typeof a, - otherType = typeof b; - - // exit early for unlike primitive values - if (a === a && - !(a && objectTypes[type]) && - !(b && objectTypes[otherType])) { - return false; - } - // exit early for `null` and `undefined` avoiding ES3's Function#call behavior - // http://es5.github.io/#x15.3.4.4 - if (a == null || b == null) { - return a === b; - } - // compare [[Class]] names - var className = toString.call(a), - otherClass = toString.call(b); - - if (className == argsClass) { - className = objectClass; - } - if (otherClass == argsClass) { - otherClass = objectClass; - } - if (className != otherClass) { - return false; - } - switch (className) { - case boolClass: - case dateClass: - // coerce dates and booleans to numbers, dates to milliseconds and booleans - // to `1` or `0` treating invalid dates coerced to `NaN` as not equal - return +a == +b; - - case numberClass: - // treat `NaN` vs. `NaN` as equal - return (a != +a) - ? b != +b - // but treat `+0` vs. `-0` as not equal - : (a == 0 ? (1 / a == 1 / b) : a == +b); - - case regexpClass: - case stringClass: - // coerce regexes to strings (http://es5.github.io/#x15.10.6.4) - // treat string primitives and their corresponding object instances as equal - return a == String(b); - } - var isArr = className == arrayClass; - if (!isArr) { - // unwrap any `lodash` wrapped values - var aWrapped = hasOwnProperty.call(a, '__wrapped__'), - bWrapped = hasOwnProperty.call(b, '__wrapped__'); - - if (aWrapped || bWrapped) { - return baseIsEqual(aWrapped ? a.__wrapped__ : a, bWrapped ? b.__wrapped__ : b, callback, isWhere, stackA, stackB); - } - // exit for functions and DOM nodes - if (className != objectClass) { - return false; - } - // in older versions of Opera, `arguments` objects have `Array` constructors - var ctorA = a.constructor, - ctorB = b.constructor; - - // non `Object` object instances with different constructors are not equal - if (ctorA != ctorB && - !(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) && - ('constructor' in a && 'constructor' in b) - ) { - return false; - } - } - // assume cyclic structures are equal - // the algorithm for detecting cyclic structures is adapted from ES 5.1 - // section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3) - var initedStack = !stackA; - stackA || (stackA = getArray()); - stackB || (stackB = getArray()); - - var length = stackA.length; - while (length--) { - if (stackA[length] == a) { - return stackB[length] == b; - } - } - var size = 0; - result = true; - - // add `a` and `b` to the stack of traversed objects - stackA.push(a); - stackB.push(b); - - // recursively compare objects and arrays (susceptible to call stack limits) - if (isArr) { - // compare lengths to determine if a deep comparison is necessary - length = a.length; - size = b.length; - result = size == length; - - if (result || isWhere) { - // deep compare the contents, ignoring non-numeric properties - while (size--) { - var index = length, - value = b[size]; - - if (isWhere) { - while (index--) { - if ((result = baseIsEqual(a[index], value, callback, isWhere, stackA, stackB))) { - break; - } - } - } else if (!(result = baseIsEqual(a[size], value, callback, isWhere, stackA, stackB))) { - break; - } - } - } - } - else { - // deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys` - // which, in this case, is more costly - forIn(b, function(value, key, b) { - if (hasOwnProperty.call(b, key)) { - // count the number of properties. - size++; - // deep compare each property value. - return (result = hasOwnProperty.call(a, key) && baseIsEqual(a[key], value, callback, isWhere, stackA, stackB)); - } - }); - - if (result && !isWhere) { - // ensure both objects have the same number of properties - forIn(a, function(value, key, a) { - if (hasOwnProperty.call(a, key)) { - // `size` will be `-1` if `a` has more properties than `b` - return (result = --size > -1); - } - }); - } - } - stackA.pop(); - stackB.pop(); - - if (initedStack) { - releaseArray(stackA); - releaseArray(stackB); - } - return result; - } - - /** - * The base implementation of `_.merge` without argument juggling or support - * for `thisArg` binding. - * - * @private - * @param {Object} object The destination object. - * @param {Object} source The source object. - * @param {Function} [callback] The function to customize merging properties. - * @param {Array} [stackA=[]] Tracks traversed source objects. - * @param {Array} [stackB=[]] Associates values with source counterparts. - */ - function baseMerge(object, source, callback, stackA, stackB) { - (isArray(source) ? forEach : forOwn)(source, function(source, key) { - var found, - isArr, - result = source, - value = object[key]; - - if (source && ((isArr = isArray(source)) || isPlainObject(source))) { - // avoid merging previously merged cyclic sources - var stackLength = stackA.length; - while (stackLength--) { - if ((found = stackA[stackLength] == source)) { - value = stackB[stackLength]; - break; - } - } - if (!found) { - var isShallow; - if (callback) { - result = callback(value, source); - if ((isShallow = typeof result != 'undefined')) { - value = result; - } - } - if (!isShallow) { - value = isArr - ? (isArray(value) ? value : []) - : (isPlainObject(value) ? value : {}); - } - // add `source` and associated `value` to the stack of traversed objects - stackA.push(source); - stackB.push(value); - - // recursively merge objects and arrays (susceptible to call stack limits) - if (!isShallow) { - baseMerge(value, source, callback, stackA, stackB); - } - } - } - else { - if (callback) { - result = callback(value, source); - if (typeof result == 'undefined') { - result = source; - } - } - if (typeof result != 'undefined') { - value = result; - } - } - object[key] = value; - }); - } - - /** - * The base implementation of `_.random` without argument juggling or support - * for returning floating-point numbers. - * - * @private - * @param {number} min The minimum possible value. - * @param {number} max The maximum possible value. - * @returns {number} Returns a random number. - */ - function baseRandom(min, max) { - return min + floor(nativeRandom() * (max - min + 1)); - } - - /** - * The base implementation of `_.uniq` without support for callback shorthands - * or `thisArg` binding. - * - * @private - * @param {Array} array The array to process. - * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. - * @param {Function} [callback] The function called per iteration. - * @returns {Array} Returns a duplicate-value-free array. - */ - function baseUniq(array, isSorted, callback) { - var index = -1, - indexOf = getIndexOf(), - length = array ? array.length : 0, - result = []; - - var isLarge = !isSorted && length >= largeArraySize && indexOf === baseIndexOf, - seen = (callback || isLarge) ? getArray() : result; - - if (isLarge) { - var cache = createCache(seen); - indexOf = cacheIndexOf; - seen = cache; - } - while (++index < length) { - var value = array[index], - computed = callback ? callback(value, index, array) : value; - - if (isSorted - ? !index || seen[seen.length - 1] !== computed - : indexOf(seen, computed) < 0 - ) { - if (callback || isLarge) { - seen.push(computed); - } - result.push(value); - } - } - if (isLarge) { - releaseArray(seen.array); - releaseObject(seen); - } else if (callback) { - releaseArray(seen); - } - return result; - } - - /** - * Creates a function that aggregates a collection, creating an object composed - * of keys generated from the results of running each element of the collection - * through a callback. The given `setter` function sets the keys and values - * of the composed object. - * - * @private - * @param {Function} setter The setter function. - * @returns {Function} Returns the new aggregator function. - */ - function createAggregator(setter) { - return function(collection, callback, thisArg) { - var result = {}; - callback = lodash.createCallback(callback, thisArg, 3); - - var index = -1, - length = collection ? collection.length : 0; - - if (typeof length == 'number') { - while (++index < length) { - var value = collection[index]; - setter(result, value, callback(value, index, collection), collection); - } - } else { - forOwn(collection, function(value, key, collection) { - setter(result, value, callback(value, key, collection), collection); - }); - } - return result; - }; - } - - /** - * Creates a function that, when called, either curries or invokes `func` - * with an optional `this` binding and partially applied arguments. - * - * @private - * @param {Function|string} func The function or method name to reference. - * @param {number} bitmask The bitmask of method flags to compose. - * The bitmask may be composed of the following flags: - * 1 - `_.bind` - * 2 - `_.bindKey` - * 4 - `_.curry` - * 8 - `_.curry` (bound) - * 16 - `_.partial` - * 32 - `_.partialRight` - * @param {Array} [partialArgs] An array of arguments to prepend to those - * provided to the new function. - * @param {Array} [partialRightArgs] An array of arguments to append to those - * provided to the new function. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {number} [arity] The arity of `func`. - * @returns {Function} Returns the new function. - */ - function createWrapper(func, bitmask, partialArgs, partialRightArgs, thisArg, arity) { - var isBind = bitmask & 1, - isBindKey = bitmask & 2, - isCurry = bitmask & 4, - isCurryBound = bitmask & 8, - isPartial = bitmask & 16, - isPartialRight = bitmask & 32; - - if (!isBindKey && !isFunction(func)) { - throw new TypeError; - } - if (isPartial && !partialArgs.length) { - bitmask &= ~16; - isPartial = partialArgs = false; - } - if (isPartialRight && !partialRightArgs.length) { - bitmask &= ~32; - isPartialRight = partialRightArgs = false; - } - var bindData = func && func.__bindData__; - if (bindData && bindData !== true) { - // clone `bindData` - bindData = slice(bindData); - if (bindData[2]) { - bindData[2] = slice(bindData[2]); - } - if (bindData[3]) { - bindData[3] = slice(bindData[3]); - } - // set `thisBinding` is not previously bound - if (isBind && !(bindData[1] & 1)) { - bindData[4] = thisArg; - } - // set if previously bound but not currently (subsequent curried functions) - if (!isBind && bindData[1] & 1) { - bitmask |= 8; - } - // set curried arity if not yet set - if (isCurry && !(bindData[1] & 4)) { - bindData[5] = arity; - } - // append partial left arguments - if (isPartial) { - push.apply(bindData[2] || (bindData[2] = []), partialArgs); - } - // append partial right arguments - if (isPartialRight) { - unshift.apply(bindData[3] || (bindData[3] = []), partialRightArgs); - } - // merge flags - bindData[1] |= bitmask; - return createWrapper.apply(null, bindData); - } - // fast path for `_.bind` - var creater = (bitmask == 1 || bitmask === 17) ? baseBind : baseCreateWrapper; - return creater([func, bitmask, partialArgs, partialRightArgs, thisArg, arity]); - } - - /** - * Used by `escape` to convert characters to HTML entities. - * - * @private - * @param {string} match The matched character to escape. - * @returns {string} Returns the escaped character. - */ - function escapeHtmlChar(match) { - return htmlEscapes[match]; - } - - /** - * Gets the appropriate "indexOf" function. If the `_.indexOf` method is - * customized, this method returns the custom method, otherwise it returns - * the `baseIndexOf` function. - * - * @private - * @returns {Function} Returns the "indexOf" function. - */ - function getIndexOf() { - var result = (result = lodash.indexOf) === indexOf ? baseIndexOf : result; - return result; - } - - /** - * Checks if `value` is a native function. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a native function, else `false`. - */ - function isNative(value) { - return typeof value == 'function' && reNative.test(value); - } - - /** - * Sets `this` binding data on a given function. - * - * @private - * @param {Function} func The function to set data on. - * @param {Array} value The data array to set. - */ - var setBindData = !defineProperty ? noop : function(func, value) { - descriptor.value = value; - defineProperty(func, '__bindData__', descriptor); - }; - - /** - * A fallback implementation of `isPlainObject` which checks if a given value - * is an object created by the `Object` constructor, assuming objects created - * by the `Object` constructor have no inherited enumerable properties and that - * there are no `Object.prototype` extensions. - * - * @private - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - */ - function shimIsPlainObject(value) { - var ctor, - result; - - // avoid non Object objects, `arguments` objects, and DOM elements - if (!(value && toString.call(value) == objectClass) || - (ctor = value.constructor, isFunction(ctor) && !(ctor instanceof ctor))) { - return false; - } - // In most environments an object's own properties are iterated before - // its inherited properties. If the last iterated property is an object's - // own property then there are no inherited enumerable properties. - forIn(value, function(value, key) { - result = key; - }); - return typeof result == 'undefined' || hasOwnProperty.call(value, result); - } - - /** - * Used by `unescape` to convert HTML entities to characters. - * - * @private - * @param {string} match The matched character to unescape. - * @returns {string} Returns the unescaped character. - */ - function unescapeHtmlChar(match) { - return htmlUnescapes[match]; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Checks if `value` is an `arguments` object. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is an `arguments` object, else `false`. - * @example - * - * (function() { return _.isArguments(arguments); })(1, 2, 3); - * // => true - * - * _.isArguments([1, 2, 3]); - * // => false - */ - function isArguments(value) { - return value && typeof value == 'object' && typeof value.length == 'number' && - toString.call(value) == argsClass || false; - } - - /** - * Checks if `value` is an array. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is an array, else `false`. - * @example - * - * (function() { return _.isArray(arguments); })(); - * // => false - * - * _.isArray([1, 2, 3]); - * // => true - */ - var isArray = nativeIsArray || function(value) { - return value && typeof value == 'object' && typeof value.length == 'number' && - toString.call(value) == arrayClass || false; - }; - - /** - * A fallback implementation of `Object.keys` which produces an array of the - * given object's own enumerable property names. - * - * @private - * @type Function - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property names. - */ - var shimKeys = function(object) { - var index, iterable = object, result = []; - if (!iterable) return result; - if (!(objectTypes[typeof object])) return result; - for (index in iterable) { - if (hasOwnProperty.call(iterable, index)) { - result.push(index); - } - } - return result - }; - - /** - * Creates an array composed of the own enumerable property names of an object. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property names. - * @example - * - * _.keys({ 'one': 1, 'two': 2, 'three': 3 }); - * // => ['one', 'two', 'three'] (property order is not guaranteed across environments) - */ - var keys = !nativeKeys ? shimKeys : function(object) { - if (!isObject(object)) { - return []; - } - return nativeKeys(object); - }; - - /** - * Used to convert characters to HTML entities: - * - * Though the `>` character is escaped for symmetry, characters like `>` and `/` - * don't require escaping in HTML and have no special meaning unless they're part - * of a tag or an unquoted attribute value. - * http://mathiasbynens.be/notes/ambiguous-ampersands (under "semi-related fun fact") - */ - var htmlEscapes = { - '&': '&', - '<': '<', - '>': '>', - '"': '"', - "'": ''' - }; - - /** Used to convert HTML entities to characters */ - var htmlUnescapes = invert(htmlEscapes); - - /** Used to match HTML entities and HTML characters */ - var reEscapedHtml = RegExp('(' + keys(htmlUnescapes).join('|') + ')', 'g'), - reUnescapedHtml = RegExp('[' + keys(htmlEscapes).join('') + ']', 'g'); - - /*--------------------------------------------------------------------------*/ - - /** - * Assigns own enumerable properties of source object(s) to the destination - * object. Subsequent sources will overwrite property assignments of previous - * sources. If a callback is provided it will be executed to produce the - * assigned values. The callback is bound to `thisArg` and invoked with two - * arguments; (objectValue, sourceValue). - * - * @static - * @memberOf _ - * @type Function - * @alias extend - * @category Objects - * @param {Object} object The destination object. - * @param {...Object} [source] The source objects. - * @param {Function} [callback] The function to customize assigning values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the destination object. - * @example - * - * _.assign({ 'name': 'fred' }, { 'employer': 'slate' }); - * // => { 'name': 'fred', 'employer': 'slate' } - * - * var defaults = _.partialRight(_.assign, function(a, b) { - * return typeof a == 'undefined' ? b : a; - * }); - * - * var object = { 'name': 'barney' }; - * defaults(object, { 'name': 'fred', 'employer': 'slate' }); - * // => { 'name': 'barney', 'employer': 'slate' } - */ - var assign = function(object, source, guard) { - var index, iterable = object, result = iterable; - if (!iterable) return result; - var args = arguments, - argsIndex = 0, - argsLength = typeof guard == 'number' ? 2 : args.length; - if (argsLength > 3 && typeof args[argsLength - 2] == 'function') { - var callback = baseCreateCallback(args[--argsLength - 1], args[argsLength--], 2); - } else if (argsLength > 2 && typeof args[argsLength - 1] == 'function') { - callback = args[--argsLength]; - } - while (++argsIndex < argsLength) { - iterable = args[argsIndex]; - if (iterable && objectTypes[typeof iterable]) { - var ownIndex = -1, - ownProps = objectTypes[typeof iterable] && keys(iterable), - length = ownProps ? ownProps.length : 0; - - while (++ownIndex < length) { - index = ownProps[ownIndex]; - result[index] = callback ? callback(result[index], iterable[index]) : iterable[index]; - } - } - } - return result - }; - - /** - * Creates a clone of `value`. If `isDeep` is `true` nested objects will also - * be cloned, otherwise they will be assigned by reference. If a callback - * is provided it will be executed to produce the cloned values. If the - * callback returns `undefined` cloning will be handled by the method instead. - * The callback is bound to `thisArg` and invoked with one argument; (value). - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to clone. - * @param {boolean} [isDeep=false] Specify a deep clone. - * @param {Function} [callback] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the cloned value. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * var shallow = _.clone(characters); - * shallow[0] === characters[0]; - * // => true - * - * var deep = _.clone(characters, true); - * deep[0] === characters[0]; - * // => false - * - * _.mixin({ - * 'clone': _.partialRight(_.clone, function(value) { - * return _.isElement(value) ? value.cloneNode(false) : undefined; - * }) - * }); - * - * var clone = _.clone(document.body); - * clone.childNodes.length; - * // => 0 - */ - function clone(value, isDeep, callback, thisArg) { - // allows working with "Collections" methods without using their `index` - // and `collection` arguments for `isDeep` and `callback` - if (typeof isDeep != 'boolean' && isDeep != null) { - thisArg = callback; - callback = isDeep; - isDeep = false; - } - return baseClone(value, isDeep, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); - } - - /** - * Creates a deep clone of `value`. If a callback is provided it will be - * executed to produce the cloned values. If the callback returns `undefined` - * cloning will be handled by the method instead. The callback is bound to - * `thisArg` and invoked with one argument; (value). - * - * Note: This method is loosely based on the structured clone algorithm. Functions - * and DOM nodes are **not** cloned. The enumerable properties of `arguments` objects and - * objects created by constructors other than `Object` are cloned to plain `Object` objects. - * See http://www.w3.org/TR/html5/infrastructure.html#internal-structured-cloning-algorithm. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to deep clone. - * @param {Function} [callback] The function to customize cloning values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the deep cloned value. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * var deep = _.cloneDeep(characters); - * deep[0] === characters[0]; - * // => false - * - * var view = { - * 'label': 'docs', - * 'node': element - * }; - * - * var clone = _.cloneDeep(view, function(value) { - * return _.isElement(value) ? value.cloneNode(true) : undefined; - * }); - * - * clone.node == view.node; - * // => false - */ - function cloneDeep(value, callback, thisArg) { - return baseClone(value, true, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 1)); - } - - /** - * Creates an object that inherits from the given `prototype` object. If a - * `properties` object is provided its own enumerable properties are assigned - * to the created object. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} prototype The object to inherit from. - * @param {Object} [properties] The properties to assign to the object. - * @returns {Object} Returns the new object. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * function Circle() { - * Shape.call(this); - * } - * - * Circle.prototype = _.create(Shape.prototype, { 'constructor': Circle }); - * - * var circle = new Circle; - * circle instanceof Circle; - * // => true - * - * circle instanceof Shape; - * // => true - */ - function create(prototype, properties) { - var result = baseCreate(prototype); - return properties ? assign(result, properties) : result; - } - - /** - * Assigns own enumerable properties of source object(s) to the destination - * object for all destination properties that resolve to `undefined`. Once a - * property is set, additional defaults of the same property will be ignored. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {Object} object The destination object. - * @param {...Object} [source] The source objects. - * @param- {Object} [guard] Allows working with `_.reduce` without using its - * `key` and `object` arguments as sources. - * @returns {Object} Returns the destination object. - * @example - * - * var object = { 'name': 'barney' }; - * _.defaults(object, { 'name': 'fred', 'employer': 'slate' }); - * // => { 'name': 'barney', 'employer': 'slate' } - */ - var defaults = function(object, source, guard) { - var index, iterable = object, result = iterable; - if (!iterable) return result; - var args = arguments, - argsIndex = 0, - argsLength = typeof guard == 'number' ? 2 : args.length; - while (++argsIndex < argsLength) { - iterable = args[argsIndex]; - if (iterable && objectTypes[typeof iterable]) { - var ownIndex = -1, - ownProps = objectTypes[typeof iterable] && keys(iterable), - length = ownProps ? ownProps.length : 0; - - while (++ownIndex < length) { - index = ownProps[ownIndex]; - if (typeof result[index] == 'undefined') result[index] = iterable[index]; - } - } - } - return result - }; - - /** - * This method is like `_.findIndex` except that it returns the key of the - * first element that passes the callback check, instead of the element itself. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to search. - * @param {Function|Object|string} [callback=identity] The function called per - * iteration. If a property name or object is provided it will be used to - * create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {string|undefined} Returns the key of the found element, else `undefined`. - * @example - * - * var characters = { - * 'barney': { 'age': 36, 'blocked': false }, - * 'fred': { 'age': 40, 'blocked': true }, - * 'pebbles': { 'age': 1, 'blocked': false } - * }; - * - * _.findKey(characters, function(chr) { - * return chr.age < 40; - * }); - * // => 'barney' (property order is not guaranteed across environments) - * - * // using "_.where" callback shorthand - * _.findKey(characters, { 'age': 1 }); - * // => 'pebbles' - * - * // using "_.pluck" callback shorthand - * _.findKey(characters, 'blocked'); - * // => 'fred' - */ - function findKey(object, callback, thisArg) { - var result; - callback = lodash.createCallback(callback, thisArg, 3); - forOwn(object, function(value, key, object) { - if (callback(value, key, object)) { - result = key; - return false; - } - }); - return result; - } - - /** - * This method is like `_.findKey` except that it iterates over elements - * of a `collection` in the opposite order. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to search. - * @param {Function|Object|string} [callback=identity] The function called per - * iteration. If a property name or object is provided it will be used to - * create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {string|undefined} Returns the key of the found element, else `undefined`. - * @example - * - * var characters = { - * 'barney': { 'age': 36, 'blocked': true }, - * 'fred': { 'age': 40, 'blocked': false }, - * 'pebbles': { 'age': 1, 'blocked': true } - * }; - * - * _.findLastKey(characters, function(chr) { - * return chr.age < 40; - * }); - * // => returns `pebbles`, assuming `_.findKey` returns `barney` - * - * // using "_.where" callback shorthand - * _.findLastKey(characters, { 'age': 40 }); - * // => 'fred' - * - * // using "_.pluck" callback shorthand - * _.findLastKey(characters, 'blocked'); - * // => 'pebbles' - */ - function findLastKey(object, callback, thisArg) { - var result; - callback = lodash.createCallback(callback, thisArg, 3); - forOwnRight(object, function(value, key, object) { - if (callback(value, key, object)) { - result = key; - return false; - } - }); - return result; - } - - /** - * Iterates over own and inherited enumerable properties of an object, - * executing the callback for each property. The callback is bound to `thisArg` - * and invoked with three arguments; (value, key, object). Callbacks may exit - * iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * Shape.prototype.move = function(x, y) { - * this.x += x; - * this.y += y; - * }; - * - * _.forIn(new Shape, function(value, key) { - * console.log(key); - * }); - * // => logs 'x', 'y', and 'move' (property order is not guaranteed across environments) - */ - var forIn = function(collection, callback, thisArg) { - var index, iterable = collection, result = iterable; - if (!iterable) return result; - if (!objectTypes[typeof iterable]) return result; - callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); - for (index in iterable) { - if (callback(iterable[index], index, collection) === false) return result; - } - return result - }; - - /** - * This method is like `_.forIn` except that it iterates over elements - * of a `collection` in the opposite order. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * Shape.prototype.move = function(x, y) { - * this.x += x; - * this.y += y; - * }; - * - * _.forInRight(new Shape, function(value, key) { - * console.log(key); - * }); - * // => logs 'move', 'y', and 'x' assuming `_.forIn ` logs 'x', 'y', and 'move' - */ - function forInRight(object, callback, thisArg) { - var pairs = []; - - forIn(object, function(value, key) { - pairs.push(key, value); - }); - - var length = pairs.length; - callback = baseCreateCallback(callback, thisArg, 3); - while (length--) { - if (callback(pairs[length--], pairs[length], object) === false) { - break; - } - } - return object; - } - - /** - * Iterates over own enumerable properties of an object, executing the callback - * for each property. The callback is bound to `thisArg` and invoked with three - * arguments; (value, key, object). Callbacks may exit iteration early by - * explicitly returning `false`. - * - * @static - * @memberOf _ - * @type Function - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * _.forOwn({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { - * console.log(key); - * }); - * // => logs '0', '1', and 'length' (property order is not guaranteed across environments) - */ - var forOwn = function(collection, callback, thisArg) { - var index, iterable = collection, result = iterable; - if (!iterable) return result; - if (!objectTypes[typeof iterable]) return result; - callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); - var ownIndex = -1, - ownProps = objectTypes[typeof iterable] && keys(iterable), - length = ownProps ? ownProps.length : 0; - - while (++ownIndex < length) { - index = ownProps[ownIndex]; - if (callback(iterable[index], index, collection) === false) return result; - } - return result - }; - - /** - * This method is like `_.forOwn` except that it iterates over elements - * of a `collection` in the opposite order. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns `object`. - * @example - * - * _.forOwnRight({ '0': 'zero', '1': 'one', 'length': 2 }, function(num, key) { - * console.log(key); - * }); - * // => logs 'length', '1', and '0' assuming `_.forOwn` logs '0', '1', and 'length' - */ - function forOwnRight(object, callback, thisArg) { - var props = keys(object), - length = props.length; - - callback = baseCreateCallback(callback, thisArg, 3); - while (length--) { - var key = props[length]; - if (callback(object[key], key, object) === false) { - break; - } - } - return object; - } - - /** - * Creates a sorted array of property names of all enumerable properties, - * own and inherited, of `object` that have function values. - * - * @static - * @memberOf _ - * @alias methods - * @category Objects - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property names that have function values. - * @example - * - * _.functions(_); - * // => ['all', 'any', 'bind', 'bindAll', 'clone', 'compact', 'compose', ...] - */ - function functions(object) { - var result = []; - forIn(object, function(value, key) { - if (isFunction(value)) { - result.push(key); - } - }); - return result.sort(); - } - - /** - * Checks if the specified property name exists as a direct property of `object`, - * instead of an inherited property. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to inspect. - * @param {string} key The name of the property to check. - * @returns {boolean} Returns `true` if key is a direct property, else `false`. - * @example - * - * _.has({ 'a': 1, 'b': 2, 'c': 3 }, 'b'); - * // => true - */ - function has(object, key) { - return object ? hasOwnProperty.call(object, key) : false; - } - - /** - * Creates an object composed of the inverted keys and values of the given object. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to invert. - * @returns {Object} Returns the created inverted object. - * @example - * - * _.invert({ 'first': 'fred', 'second': 'barney' }); - * // => { 'fred': 'first', 'barney': 'second' } - */ - function invert(object) { - var index = -1, - props = keys(object), - length = props.length, - result = {}; - - while (++index < length) { - var key = props[index]; - result[object[key]] = key; - } - return result; - } - - /** - * Checks if `value` is a boolean value. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a boolean value, else `false`. - * @example - * - * _.isBoolean(null); - * // => false - */ - function isBoolean(value) { - return value === true || value === false || - value && typeof value == 'object' && toString.call(value) == boolClass || false; - } - - /** - * Checks if `value` is a date. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a date, else `false`. - * @example - * - * _.isDate(new Date); - * // => true - */ - function isDate(value) { - return value && typeof value == 'object' && toString.call(value) == dateClass || false; - } - - /** - * Checks if `value` is a DOM element. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a DOM element, else `false`. - * @example - * - * _.isElement(document.body); - * // => true - */ - function isElement(value) { - return value && value.nodeType === 1 || false; - } - - /** - * Checks if `value` is empty. Arrays, strings, or `arguments` objects with a - * length of `0` and objects with no own enumerable properties are considered - * "empty". - * - * @static - * @memberOf _ - * @category Objects - * @param {Array|Object|string} value The value to inspect. - * @returns {boolean} Returns `true` if the `value` is empty, else `false`. - * @example - * - * _.isEmpty([1, 2, 3]); - * // => false - * - * _.isEmpty({}); - * // => true - * - * _.isEmpty(''); - * // => true - */ - function isEmpty(value) { - var result = true; - if (!value) { - return result; - } - var className = toString.call(value), - length = value.length; - - if ((className == arrayClass || className == stringClass || className == argsClass ) || - (className == objectClass && typeof length == 'number' && isFunction(value.splice))) { - return !length; - } - forOwn(value, function() { - return (result = false); - }); - return result; - } - - /** - * Performs a deep comparison between two values to determine if they are - * equivalent to each other. If a callback is provided it will be executed - * to compare values. If the callback returns `undefined` comparisons will - * be handled by the method instead. The callback is bound to `thisArg` and - * invoked with two arguments; (a, b). - * - * @static - * @memberOf _ - * @category Objects - * @param {*} a The value to compare. - * @param {*} b The other value to compare. - * @param {Function} [callback] The function to customize comparing values. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {boolean} Returns `true` if the values are equivalent, else `false`. - * @example - * - * var object = { 'name': 'fred' }; - * var copy = { 'name': 'fred' }; - * - * object == copy; - * // => false - * - * _.isEqual(object, copy); - * // => true - * - * var words = ['hello', 'goodbye']; - * var otherWords = ['hi', 'goodbye']; - * - * _.isEqual(words, otherWords, function(a, b) { - * var reGreet = /^(?:hello|hi)$/i, - * aGreet = _.isString(a) && reGreet.test(a), - * bGreet = _.isString(b) && reGreet.test(b); - * - * return (aGreet || bGreet) ? (aGreet == bGreet) : undefined; - * }); - * // => true - */ - function isEqual(a, b, callback, thisArg) { - return baseIsEqual(a, b, typeof callback == 'function' && baseCreateCallback(callback, thisArg, 2)); - } - - /** - * Checks if `value` is, or can be coerced to, a finite number. - * - * Note: This is not the same as native `isFinite` which will return true for - * booleans and empty strings. See http://es5.github.io/#x15.1.2.5. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is finite, else `false`. - * @example - * - * _.isFinite(-101); - * // => true - * - * _.isFinite('10'); - * // => true - * - * _.isFinite(true); - * // => false - * - * _.isFinite(''); - * // => false - * - * _.isFinite(Infinity); - * // => false - */ - function isFinite(value) { - return nativeIsFinite(value) && !nativeIsNaN(parseFloat(value)); - } - - /** - * Checks if `value` is a function. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a function, else `false`. - * @example - * - * _.isFunction(_); - * // => true - */ - function isFunction(value) { - return typeof value == 'function'; - } - - /** - * Checks if `value` is the language type of Object. - * (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is an object, else `false`. - * @example - * - * _.isObject({}); - * // => true - * - * _.isObject([1, 2, 3]); - * // => true - * - * _.isObject(1); - * // => false - */ - function isObject(value) { - // check if the value is the ECMAScript language type of Object - // http://es5.github.io/#x8 - // and avoid a V8 bug - // http://code.google.com/p/v8/issues/detail?id=2291 - return !!(value && objectTypes[typeof value]); - } - - /** - * Checks if `value` is `NaN`. - * - * Note: This is not the same as native `isNaN` which will return `true` for - * `undefined` and other non-numeric values. See http://es5.github.io/#x15.1.2.4. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is `NaN`, else `false`. - * @example - * - * _.isNaN(NaN); - * // => true - * - * _.isNaN(new Number(NaN)); - * // => true - * - * isNaN(undefined); - * // => true - * - * _.isNaN(undefined); - * // => false - */ - function isNaN(value) { - // `NaN` as a primitive is the only value that is not equal to itself - // (perform the [[Class]] check first to avoid errors with some host objects in IE) - return isNumber(value) && value != +value; - } - - /** - * Checks if `value` is `null`. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is `null`, else `false`. - * @example - * - * _.isNull(null); - * // => true - * - * _.isNull(undefined); - * // => false - */ - function isNull(value) { - return value === null; - } - - /** - * Checks if `value` is a number. - * - * Note: `NaN` is considered a number. See http://es5.github.io/#x8.5. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a number, else `false`. - * @example - * - * _.isNumber(8.4 * 5); - * // => true - */ - function isNumber(value) { - return typeof value == 'number' || - value && typeof value == 'object' && toString.call(value) == numberClass || false; - } - - /** - * Checks if `value` is an object created by the `Object` constructor. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. - * @example - * - * function Shape() { - * this.x = 0; - * this.y = 0; - * } - * - * _.isPlainObject(new Shape); - * // => false - * - * _.isPlainObject([1, 2, 3]); - * // => false - * - * _.isPlainObject({ 'x': 0, 'y': 0 }); - * // => true - */ - var isPlainObject = !getPrototypeOf ? shimIsPlainObject : function(value) { - if (!(value && toString.call(value) == objectClass)) { - return false; - } - var valueOf = value.valueOf, - objProto = isNative(valueOf) && (objProto = getPrototypeOf(valueOf)) && getPrototypeOf(objProto); - - return objProto - ? (value == objProto || getPrototypeOf(value) == objProto) - : shimIsPlainObject(value); - }; - - /** - * Checks if `value` is a regular expression. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a regular expression, else `false`. - * @example - * - * _.isRegExp(/fred/); - * // => true - */ - function isRegExp(value) { - return value && typeof value == 'object' && toString.call(value) == regexpClass || false; - } - - /** - * Checks if `value` is a string. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is a string, else `false`. - * @example - * - * _.isString('fred'); - * // => true - */ - function isString(value) { - return typeof value == 'string' || - value && typeof value == 'object' && toString.call(value) == stringClass || false; - } - - /** - * Checks if `value` is `undefined`. - * - * @static - * @memberOf _ - * @category Objects - * @param {*} value The value to check. - * @returns {boolean} Returns `true` if the `value` is `undefined`, else `false`. - * @example - * - * _.isUndefined(void 0); - * // => true - */ - function isUndefined(value) { - return typeof value == 'undefined'; - } - - /** - * Creates an object with the same keys as `object` and values generated by - * running each own enumerable property of `object` through the callback. - * The callback is bound to `thisArg` and invoked with three arguments; - * (value, key, object). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new object with values of the results of each `callback` execution. - * @example - * - * _.mapValues({ 'a': 1, 'b': 2, 'c': 3} , function(num) { return num * 3; }); - * // => { 'a': 3, 'b': 6, 'c': 9 } - * - * var characters = { - * 'fred': { 'name': 'fred', 'age': 40 }, - * 'pebbles': { 'name': 'pebbles', 'age': 1 } - * }; - * - * // using "_.pluck" callback shorthand - * _.mapValues(characters, 'age'); - * // => { 'fred': 40, 'pebbles': 1 } - */ - function mapValues(object, callback, thisArg) { - var result = {}; - callback = lodash.createCallback(callback, thisArg, 3); - - forOwn(object, function(value, key, object) { - result[key] = callback(value, key, object); - }); - return result; - } - - /** - * Recursively merges own enumerable properties of the source object(s), that - * don't resolve to `undefined` into the destination object. Subsequent sources - * will overwrite property assignments of previous sources. If a callback is - * provided it will be executed to produce the merged values of the destination - * and source properties. If the callback returns `undefined` merging will - * be handled by the method instead. The callback is bound to `thisArg` and - * invoked with two arguments; (objectValue, sourceValue). - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The destination object. - * @param {...Object} [source] The source objects. - * @param {Function} [callback] The function to customize merging properties. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the destination object. - * @example - * - * var names = { - * 'characters': [ - * { 'name': 'barney' }, - * { 'name': 'fred' } - * ] - * }; - * - * var ages = { - * 'characters': [ - * { 'age': 36 }, - * { 'age': 40 } - * ] - * }; - * - * _.merge(names, ages); - * // => { 'characters': [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] } - * - * var food = { - * 'fruits': ['apple'], - * 'vegetables': ['beet'] - * }; - * - * var otherFood = { - * 'fruits': ['banana'], - * 'vegetables': ['carrot'] - * }; - * - * _.merge(food, otherFood, function(a, b) { - * return _.isArray(a) ? a.concat(b) : undefined; - * }); - * // => { 'fruits': ['apple', 'banana'], 'vegetables': ['beet', 'carrot] } - */ - function merge(object) { - var args = arguments, - length = 2; - - if (!isObject(object)) { - return object; - } - // allows working with `_.reduce` and `_.reduceRight` without using - // their `index` and `collection` arguments - if (typeof args[2] != 'number') { - length = args.length; - } - if (length > 3 && typeof args[length - 2] == 'function') { - var callback = baseCreateCallback(args[--length - 1], args[length--], 2); - } else if (length > 2 && typeof args[length - 1] == 'function') { - callback = args[--length]; - } - var sources = slice(arguments, 1, length), - index = -1, - stackA = getArray(), - stackB = getArray(); - - while (++index < length) { - baseMerge(object, sources[index], callback, stackA, stackB); - } - releaseArray(stackA); - releaseArray(stackB); - return object; - } - - /** - * Creates a shallow clone of `object` excluding the specified properties. - * Property names may be specified as individual arguments or as arrays of - * property names. If a callback is provided it will be executed for each - * property of `object` omitting the properties the callback returns truey - * for. The callback is bound to `thisArg` and invoked with three arguments; - * (value, key, object). - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The source object. - * @param {Function|...string|string[]} [callback] The properties to omit or the - * function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns an object without the omitted properties. - * @example - * - * _.omit({ 'name': 'fred', 'age': 40 }, 'age'); - * // => { 'name': 'fred' } - * - * _.omit({ 'name': 'fred', 'age': 40 }, function(value) { - * return typeof value == 'number'; - * }); - * // => { 'name': 'fred' } - */ - function omit(object, callback, thisArg) { - var result = {}; - if (typeof callback != 'function') { - var props = []; - forIn(object, function(value, key) { - props.push(key); - }); - props = baseDifference(props, baseFlatten(arguments, true, false, 1)); - - var index = -1, - length = props.length; - - while (++index < length) { - var key = props[index]; - result[key] = object[key]; - } - } else { - callback = lodash.createCallback(callback, thisArg, 3); - forIn(object, function(value, key, object) { - if (!callback(value, key, object)) { - result[key] = value; - } - }); - } - return result; - } - - /** - * Creates a two dimensional array of an object's key-value pairs, - * i.e. `[[key1, value1], [key2, value2]]`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to inspect. - * @returns {Array} Returns new array of key-value pairs. - * @example - * - * _.pairs({ 'barney': 36, 'fred': 40 }); - * // => [['barney', 36], ['fred', 40]] (property order is not guaranteed across environments) - */ - function pairs(object) { - var index = -1, - props = keys(object), - length = props.length, - result = Array(length); - - while (++index < length) { - var key = props[index]; - result[index] = [key, object[key]]; - } - return result; - } - - /** - * Creates a shallow clone of `object` composed of the specified properties. - * Property names may be specified as individual arguments or as arrays of - * property names. If a callback is provided it will be executed for each - * property of `object` picking the properties the callback returns truey - * for. The callback is bound to `thisArg` and invoked with three arguments; - * (value, key, object). - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The source object. - * @param {Function|...string|string[]} [callback] The function called per - * iteration or property names to pick, specified as individual property - * names or arrays of property names. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns an object composed of the picked properties. - * @example - * - * _.pick({ 'name': 'fred', '_userid': 'fred1' }, 'name'); - * // => { 'name': 'fred' } - * - * _.pick({ 'name': 'fred', '_userid': 'fred1' }, function(value, key) { - * return key.charAt(0) != '_'; - * }); - * // => { 'name': 'fred' } - */ - function pick(object, callback, thisArg) { - var result = {}; - if (typeof callback != 'function') { - var index = -1, - props = baseFlatten(arguments, true, false, 1), - length = isObject(object) ? props.length : 0; - - while (++index < length) { - var key = props[index]; - if (key in object) { - result[key] = object[key]; - } - } - } else { - callback = lodash.createCallback(callback, thisArg, 3); - forIn(object, function(value, key, object) { - if (callback(value, key, object)) { - result[key] = value; - } - }); - } - return result; - } - - /** - * An alternative to `_.reduce` this method transforms `object` to a new - * `accumulator` object which is the result of running each of its own - * enumerable properties through a callback, with each callback execution - * potentially mutating the `accumulator` object. The callback is bound to - * `thisArg` and invoked with four arguments; (accumulator, value, key, object). - * Callbacks may exit iteration early by explicitly returning `false`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Array|Object} object The object to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [accumulator] The custom accumulator value. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the accumulated value. - * @example - * - * var squares = _.transform([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], function(result, num) { - * num *= num; - * if (num % 2) { - * return result.push(num) < 3; - * } - * }); - * // => [1, 9, 25] - * - * var mapped = _.transform({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { - * result[key] = num * 3; - * }); - * // => { 'a': 3, 'b': 6, 'c': 9 } - */ - function transform(object, callback, accumulator, thisArg) { - var isArr = isArray(object); - if (accumulator == null) { - if (isArr) { - accumulator = []; - } else { - var ctor = object && object.constructor, - proto = ctor && ctor.prototype; - - accumulator = baseCreate(proto); - } - } - if (callback) { - callback = lodash.createCallback(callback, thisArg, 4); - (isArr ? forEach : forOwn)(object, function(value, index, object) { - return callback(accumulator, value, index, object); - }); - } - return accumulator; - } - - /** - * Creates an array composed of the own enumerable property values of `object`. - * - * @static - * @memberOf _ - * @category Objects - * @param {Object} object The object to inspect. - * @returns {Array} Returns an array of property values. - * @example - * - * _.values({ 'one': 1, 'two': 2, 'three': 3 }); - * // => [1, 2, 3] (property order is not guaranteed across environments) - */ - function values(object) { - var index = -1, - props = keys(object), - length = props.length, - result = Array(length); - - while (++index < length) { - result[index] = object[props[index]]; - } - return result; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Creates an array of elements from the specified indexes, or keys, of the - * `collection`. Indexes may be specified as individual arguments or as arrays - * of indexes. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {...(number|number[]|string|string[])} [index] The indexes of `collection` - * to retrieve, specified as individual indexes or arrays of indexes. - * @returns {Array} Returns a new array of elements corresponding to the - * provided indexes. - * @example - * - * _.at(['a', 'b', 'c', 'd', 'e'], [0, 2, 4]); - * // => ['a', 'c', 'e'] - * - * _.at(['fred', 'barney', 'pebbles'], 0, 2); - * // => ['fred', 'pebbles'] - */ - function at(collection) { - var args = arguments, - index = -1, - props = baseFlatten(args, true, false, 1), - length = (args[2] && args[2][args[1]] === collection) ? 1 : props.length, - result = Array(length); - - while(++index < length) { - result[index] = collection[props[index]]; - } - return result; - } - - /** - * Checks if a given value is present in a collection using strict equality - * for comparisons, i.e. `===`. If `fromIndex` is negative, it is used as the - * offset from the end of the collection. - * - * @static - * @memberOf _ - * @alias include - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {*} target The value to check for. - * @param {number} [fromIndex=0] The index to search from. - * @returns {boolean} Returns `true` if the `target` element is found, else `false`. - * @example - * - * _.contains([1, 2, 3], 1); - * // => true - * - * _.contains([1, 2, 3], 1, 2); - * // => false - * - * _.contains({ 'name': 'fred', 'age': 40 }, 'fred'); - * // => true - * - * _.contains('pebbles', 'eb'); - * // => true - */ - function contains(collection, target, fromIndex) { - var index = -1, - indexOf = getIndexOf(), - length = collection ? collection.length : 0, - result = false; - - fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex) || 0; - if (isArray(collection)) { - result = indexOf(collection, target, fromIndex) > -1; - } else if (typeof length == 'number') { - result = (isString(collection) ? collection.indexOf(target, fromIndex) : indexOf(collection, target, fromIndex)) > -1; - } else { - forOwn(collection, function(value) { - if (++index >= fromIndex) { - return !(result = value === target); - } - }); - } - return result; - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of `collection` through the callback. The corresponding value - * of each key is the number of times the key was returned by the callback. - * The callback is bound to `thisArg` and invoked with three arguments; - * (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.countBy([4.3, 6.1, 6.4], function(num) { return Math.floor(num); }); - * // => { '4': 1, '6': 2 } - * - * _.countBy([4.3, 6.1, 6.4], function(num) { return this.floor(num); }, Math); - * // => { '4': 1, '6': 2 } - * - * _.countBy(['one', 'two', 'three'], 'length'); - * // => { '3': 2, '5': 1 } - */ - var countBy = createAggregator(function(result, value, key) { - (hasOwnProperty.call(result, key) ? result[key]++ : result[key] = 1); - }); - - /** - * Checks if the given callback returns truey value for **all** elements of - * a collection. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias all - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {boolean} Returns `true` if all elements passed the callback check, - * else `false`. - * @example - * - * _.every([true, 1, null, 'yes']); - * // => false - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * // using "_.pluck" callback shorthand - * _.every(characters, 'age'); - * // => true - * - * // using "_.where" callback shorthand - * _.every(characters, { 'age': 36 }); - * // => false - */ - function every(collection, callback, thisArg) { - var result = true; - callback = lodash.createCallback(callback, thisArg, 3); - - var index = -1, - length = collection ? collection.length : 0; - - if (typeof length == 'number') { - while (++index < length) { - if (!(result = !!callback(collection[index], index, collection))) { - break; - } - } - } else { - forOwn(collection, function(value, index, collection) { - return (result = !!callback(value, index, collection)); - }); - } - return result; - } - - /** - * Iterates over elements of a collection, returning an array of all elements - * the callback returns truey for. The callback is bound to `thisArg` and - * invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias select - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of elements that passed the callback check. - * @example - * - * var evens = _.filter([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); - * // => [2, 4, 6] - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true } - * ]; - * - * // using "_.pluck" callback shorthand - * _.filter(characters, 'blocked'); - * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] - * - * // using "_.where" callback shorthand - * _.filter(characters, { 'age': 36 }); - * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] - */ - function filter(collection, callback, thisArg) { - var result = []; - callback = lodash.createCallback(callback, thisArg, 3); - - var index = -1, - length = collection ? collection.length : 0; - - if (typeof length == 'number') { - while (++index < length) { - var value = collection[index]; - if (callback(value, index, collection)) { - result.push(value); - } - } - } else { - forOwn(collection, function(value, index, collection) { - if (callback(value, index, collection)) { - result.push(value); - } - }); - } - return result; - } - - /** - * Iterates over elements of a collection, returning the first element that - * the callback returns truey for. The callback is bound to `thisArg` and - * invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias detect, findWhere - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the found element, else `undefined`. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true }, - * { 'name': 'pebbles', 'age': 1, 'blocked': false } - * ]; - * - * _.find(characters, function(chr) { - * return chr.age < 40; - * }); - * // => { 'name': 'barney', 'age': 36, 'blocked': false } - * - * // using "_.where" callback shorthand - * _.find(characters, { 'age': 1 }); - * // => { 'name': 'pebbles', 'age': 1, 'blocked': false } - * - * // using "_.pluck" callback shorthand - * _.find(characters, 'blocked'); - * // => { 'name': 'fred', 'age': 40, 'blocked': true } - */ - function find(collection, callback, thisArg) { - callback = lodash.createCallback(callback, thisArg, 3); - - var index = -1, - length = collection ? collection.length : 0; - - if (typeof length == 'number') { - while (++index < length) { - var value = collection[index]; - if (callback(value, index, collection)) { - return value; - } - } - } else { - var result; - forOwn(collection, function(value, index, collection) { - if (callback(value, index, collection)) { - result = value; - return false; - } - }); - return result; - } - } - - /** - * This method is like `_.find` except that it iterates over elements - * of a `collection` from right to left. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the found element, else `undefined`. - * @example - * - * _.findLast([1, 2, 3, 4], function(num) { - * return num % 2 == 1; - * }); - * // => 3 - */ - function findLast(collection, callback, thisArg) { - var result; - callback = lodash.createCallback(callback, thisArg, 3); - forEachRight(collection, function(value, index, collection) { - if (callback(value, index, collection)) { - result = value; - return false; - } - }); - return result; - } - - /** - * Iterates over elements of a collection, executing the callback for each - * element. The callback is bound to `thisArg` and invoked with three arguments; - * (value, index|key, collection). Callbacks may exit iteration early by - * explicitly returning `false`. - * - * Note: As with other "Collections" methods, objects with a `length` property - * are iterated like arrays. To avoid this behavior `_.forIn` or `_.forOwn` - * may be used for object iteration. - * - * @static - * @memberOf _ - * @alias each - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array|Object|string} Returns `collection`. - * @example - * - * _([1, 2, 3]).forEach(function(num) { console.log(num); }).join(','); - * // => logs each number and returns '1,2,3' - * - * _.forEach({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { console.log(num); }); - * // => logs each number and returns the object (property order is not guaranteed across environments) - */ - function forEach(collection, callback, thisArg) { - var index = -1, - length = collection ? collection.length : 0; - - callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); - if (typeof length == 'number') { - while (++index < length) { - if (callback(collection[index], index, collection) === false) { - break; - } - } - } else { - forOwn(collection, callback); - } - return collection; - } - - /** - * This method is like `_.forEach` except that it iterates over elements - * of a `collection` from right to left. - * - * @static - * @memberOf _ - * @alias eachRight - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array|Object|string} Returns `collection`. - * @example - * - * _([1, 2, 3]).forEachRight(function(num) { console.log(num); }).join(','); - * // => logs each number from right to left and returns '3,2,1' - */ - function forEachRight(collection, callback, thisArg) { - var length = collection ? collection.length : 0; - callback = callback && typeof thisArg == 'undefined' ? callback : baseCreateCallback(callback, thisArg, 3); - if (typeof length == 'number') { - while (length--) { - if (callback(collection[length], length, collection) === false) { - break; - } - } - } else { - var props = keys(collection); - length = props.length; - forOwn(collection, function(value, key, collection) { - key = props ? props[--length] : --length; - return callback(collection[key], key, collection); - }); - } - return collection; - } - - /** - * Creates an object composed of keys generated from the results of running - * each element of a collection through the callback. The corresponding value - * of each key is an array of the elements responsible for generating the key. - * The callback is bound to `thisArg` and invoked with three arguments; - * (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false` - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * _.groupBy([4.2, 6.1, 6.4], function(num) { return Math.floor(num); }); - * // => { '4': [4.2], '6': [6.1, 6.4] } - * - * _.groupBy([4.2, 6.1, 6.4], function(num) { return this.floor(num); }, Math); - * // => { '4': [4.2], '6': [6.1, 6.4] } - * - * // using "_.pluck" callback shorthand - * _.groupBy(['one', 'two', 'three'], 'length'); - * // => { '3': ['one', 'two'], '5': ['three'] } - */ - var groupBy = createAggregator(function(result, value, key) { - (hasOwnProperty.call(result, key) ? result[key] : result[key] = []).push(value); - }); - - /** - * Creates an object composed of keys generated from the results of running - * each element of the collection through the given callback. The corresponding - * value of each key is the last element responsible for generating the key. - * The callback is bound to `thisArg` and invoked with three arguments; - * (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Object} Returns the composed aggregate object. - * @example - * - * var keys = [ - * { 'dir': 'left', 'code': 97 }, - * { 'dir': 'right', 'code': 100 } - * ]; - * - * _.indexBy(keys, 'dir'); - * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } - * - * _.indexBy(keys, function(key) { return String.fromCharCode(key.code); }); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - * - * _.indexBy(characters, function(key) { this.fromCharCode(key.code); }, String); - * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } - */ - var indexBy = createAggregator(function(result, value, key) { - result[key] = value; - }); - - /** - * Invokes the method named by `methodName` on each element in the `collection` - * returning an array of the results of each invoked method. Additional arguments - * will be provided to each invoked method. If `methodName` is a function it - * will be invoked for, and `this` bound to, each element in the `collection`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|string} methodName The name of the method to invoke or - * the function invoked per iteration. - * @param {...*} [arg] Arguments to invoke the method with. - * @returns {Array} Returns a new array of the results of each invoked method. - * @example - * - * _.invoke([[5, 1, 7], [3, 2, 1]], 'sort'); - * // => [[1, 5, 7], [1, 2, 3]] - * - * _.invoke([123, 456], String.prototype.split, ''); - * // => [['1', '2', '3'], ['4', '5', '6']] - */ - function invoke(collection, methodName) { - var args = slice(arguments, 2), - index = -1, - isFunc = typeof methodName == 'function', - length = collection ? collection.length : 0, - result = Array(typeof length == 'number' ? length : 0); - - forEach(collection, function(value) { - result[++index] = (isFunc ? methodName : value[methodName]).apply(value, args); - }); - return result; - } - - /** - * Creates an array of values by running each element in the collection - * through the callback. The callback is bound to `thisArg` and invoked with - * three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias collect - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of the results of each `callback` execution. - * @example - * - * _.map([1, 2, 3], function(num) { return num * 3; }); - * // => [3, 6, 9] - * - * _.map({ 'one': 1, 'two': 2, 'three': 3 }, function(num) { return num * 3; }); - * // => [3, 6, 9] (property order is not guaranteed across environments) - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * // using "_.pluck" callback shorthand - * _.map(characters, 'name'); - * // => ['barney', 'fred'] - */ - function map(collection, callback, thisArg) { - var index = -1, - length = collection ? collection.length : 0; - - callback = lodash.createCallback(callback, thisArg, 3); - if (typeof length == 'number') { - var result = Array(length); - while (++index < length) { - result[index] = callback(collection[index], index, collection); - } - } else { - result = []; - forOwn(collection, function(value, key, collection) { - result[++index] = callback(value, key, collection); - }); - } - return result; - } - - /** - * Retrieves the maximum value of a collection. If the collection is empty or - * falsey `-Infinity` is returned. If a callback is provided it will be executed - * for each value in the collection to generate the criterion by which the value - * is ranked. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the maximum value. - * @example - * - * _.max([4, 2, 8, 6]); - * // => 8 - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * _.max(characters, function(chr) { return chr.age; }); - * // => { 'name': 'fred', 'age': 40 }; - * - * // using "_.pluck" callback shorthand - * _.max(characters, 'age'); - * // => { 'name': 'fred', 'age': 40 }; - */ - function max(collection, callback, thisArg) { - var computed = -Infinity, - result = computed; - - // allows working with functions like `_.map` without using - // their `index` argument as a callback - if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { - callback = null; - } - if (callback == null && isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - var value = collection[index]; - if (value > result) { - result = value; - } - } - } else { - callback = (callback == null && isString(collection)) - ? charAtCallback - : lodash.createCallback(callback, thisArg, 3); - - forEach(collection, function(value, index, collection) { - var current = callback(value, index, collection); - if (current > computed) { - computed = current; - result = value; - } - }); - } - return result; - } - - /** - * Retrieves the minimum value of a collection. If the collection is empty or - * falsey `Infinity` is returned. If a callback is provided it will be executed - * for each value in the collection to generate the criterion by which the value - * is ranked. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the minimum value. - * @example - * - * _.min([4, 2, 8, 6]); - * // => 2 - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * _.min(characters, function(chr) { return chr.age; }); - * // => { 'name': 'barney', 'age': 36 }; - * - * // using "_.pluck" callback shorthand - * _.min(characters, 'age'); - * // => { 'name': 'barney', 'age': 36 }; - */ - function min(collection, callback, thisArg) { - var computed = Infinity, - result = computed; - - // allows working with functions like `_.map` without using - // their `index` argument as a callback - if (typeof callback != 'function' && thisArg && thisArg[callback] === collection) { - callback = null; - } - if (callback == null && isArray(collection)) { - var index = -1, - length = collection.length; - - while (++index < length) { - var value = collection[index]; - if (value < result) { - result = value; - } - } - } else { - callback = (callback == null && isString(collection)) - ? charAtCallback - : lodash.createCallback(callback, thisArg, 3); - - forEach(collection, function(value, index, collection) { - var current = callback(value, index, collection); - if (current < computed) { - computed = current; - result = value; - } - }); - } - return result; - } - - /** - * Retrieves the value of a specified property from all elements in the collection. - * - * @static - * @memberOf _ - * @type Function - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {string} property The name of the property to pluck. - * @returns {Array} Returns a new array of property values. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * _.pluck(characters, 'name'); - * // => ['barney', 'fred'] - */ - var pluck = map; - - /** - * Reduces a collection to a value which is the accumulated result of running - * each element in the collection through the callback, where each successive - * callback execution consumes the return value of the previous execution. If - * `accumulator` is not provided the first element of the collection will be - * used as the initial `accumulator` value. The callback is bound to `thisArg` - * and invoked with four arguments; (accumulator, value, index|key, collection). - * - * @static - * @memberOf _ - * @alias foldl, inject - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [accumulator] Initial value of the accumulator. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the accumulated value. - * @example - * - * var sum = _.reduce([1, 2, 3], function(sum, num) { - * return sum + num; - * }); - * // => 6 - * - * var mapped = _.reduce({ 'a': 1, 'b': 2, 'c': 3 }, function(result, num, key) { - * result[key] = num * 3; - * return result; - * }, {}); - * // => { 'a': 3, 'b': 6, 'c': 9 } - */ - function reduce(collection, callback, accumulator, thisArg) { - if (!collection) return accumulator; - var noaccum = arguments.length < 3; - callback = lodash.createCallback(callback, thisArg, 4); - - var index = -1, - length = collection.length; - - if (typeof length == 'number') { - if (noaccum) { - accumulator = collection[++index]; - } - while (++index < length) { - accumulator = callback(accumulator, collection[index], index, collection); - } - } else { - forOwn(collection, function(value, index, collection) { - accumulator = noaccum - ? (noaccum = false, value) - : callback(accumulator, value, index, collection) - }); - } - return accumulator; - } - - /** - * This method is like `_.reduce` except that it iterates over elements - * of a `collection` from right to left. - * - * @static - * @memberOf _ - * @alias foldr - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function} [callback=identity] The function called per iteration. - * @param {*} [accumulator] Initial value of the accumulator. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the accumulated value. - * @example - * - * var list = [[0, 1], [2, 3], [4, 5]]; - * var flat = _.reduceRight(list, function(a, b) { return a.concat(b); }, []); - * // => [4, 5, 2, 3, 0, 1] - */ - function reduceRight(collection, callback, accumulator, thisArg) { - var noaccum = arguments.length < 3; - callback = lodash.createCallback(callback, thisArg, 4); - forEachRight(collection, function(value, index, collection) { - accumulator = noaccum - ? (noaccum = false, value) - : callback(accumulator, value, index, collection); - }); - return accumulator; - } - - /** - * The opposite of `_.filter` this method returns the elements of a - * collection that the callback does **not** return truey for. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of elements that failed the callback check. - * @example - * - * var odds = _.reject([1, 2, 3, 4, 5, 6], function(num) { return num % 2 == 0; }); - * // => [1, 3, 5] - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true } - * ]; - * - * // using "_.pluck" callback shorthand - * _.reject(characters, 'blocked'); - * // => [{ 'name': 'barney', 'age': 36, 'blocked': false }] - * - * // using "_.where" callback shorthand - * _.reject(characters, { 'age': 36 }); - * // => [{ 'name': 'fred', 'age': 40, 'blocked': true }] - */ - function reject(collection, callback, thisArg) { - callback = lodash.createCallback(callback, thisArg, 3); - return filter(collection, function(value, index, collection) { - return !callback(value, index, collection); - }); - } - - /** - * Retrieves a random element or `n` random elements from a collection. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to sample. - * @param {number} [n] The number of elements to sample. - * @param- {Object} [guard] Allows working with functions like `_.map` - * without using their `index` arguments as `n`. - * @returns {Array} Returns the random sample(s) of `collection`. - * @example - * - * _.sample([1, 2, 3, 4]); - * // => 2 - * - * _.sample([1, 2, 3, 4], 2); - * // => [3, 1] - */ - function sample(collection, n, guard) { - if (collection && typeof collection.length != 'number') { - collection = values(collection); - } - if (n == null || guard) { - return collection ? collection[baseRandom(0, collection.length - 1)] : undefined; - } - var result = shuffle(collection); - result.length = nativeMin(nativeMax(0, n), result.length); - return result; - } - - /** - * Creates an array of shuffled values, using a version of the Fisher-Yates - * shuffle. See http://en.wikipedia.org/wiki/Fisher-Yates_shuffle. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to shuffle. - * @returns {Array} Returns a new shuffled collection. - * @example - * - * _.shuffle([1, 2, 3, 4, 5, 6]); - * // => [4, 1, 6, 3, 5, 2] - */ - function shuffle(collection) { - var index = -1, - length = collection ? collection.length : 0, - result = Array(typeof length == 'number' ? length : 0); - - forEach(collection, function(value) { - var rand = baseRandom(0, ++index); - result[index] = result[rand]; - result[rand] = value; - }); - return result; - } - - /** - * Gets the size of the `collection` by returning `collection.length` for arrays - * and array-like objects or the number of own enumerable properties for objects. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to inspect. - * @returns {number} Returns `collection.length` or number of own enumerable properties. - * @example - * - * _.size([1, 2]); - * // => 2 - * - * _.size({ 'one': 1, 'two': 2, 'three': 3 }); - * // => 3 - * - * _.size('pebbles'); - * // => 7 - */ - function size(collection) { - var length = collection ? collection.length : 0; - return typeof length == 'number' ? length : keys(collection).length; - } - - /** - * Checks if the callback returns a truey value for **any** element of a - * collection. The function returns as soon as it finds a passing value and - * does not iterate over the entire collection. The callback is bound to - * `thisArg` and invoked with three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias any - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {boolean} Returns `true` if any element passed the callback check, - * else `false`. - * @example - * - * _.some([null, 0, 'yes', false], Boolean); - * // => true - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true } - * ]; - * - * // using "_.pluck" callback shorthand - * _.some(characters, 'blocked'); - * // => true - * - * // using "_.where" callback shorthand - * _.some(characters, { 'age': 1 }); - * // => false - */ - function some(collection, callback, thisArg) { - var result; - callback = lodash.createCallback(callback, thisArg, 3); - - var index = -1, - length = collection ? collection.length : 0; - - if (typeof length == 'number') { - while (++index < length) { - if ((result = callback(collection[index], index, collection))) { - break; - } - } - } else { - forOwn(collection, function(value, index, collection) { - return !(result = callback(value, index, collection)); - }); - } - return !!result; - } - - /** - * Creates an array of elements, sorted in ascending order by the results of - * running each element in a collection through the callback. This method - * performs a stable sort, that is, it will preserve the original sort order - * of equal elements. The callback is bound to `thisArg` and invoked with - * three arguments; (value, index|key, collection). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an array of property names is provided for `callback` the collection - * will be sorted by each property value. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Array|Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of sorted elements. - * @example - * - * _.sortBy([1, 2, 3], function(num) { return Math.sin(num); }); - * // => [3, 1, 2] - * - * _.sortBy([1, 2, 3], function(num) { return this.sin(num); }, Math); - * // => [3, 1, 2] - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 }, - * { 'name': 'barney', 'age': 26 }, - * { 'name': 'fred', 'age': 30 } - * ]; - * - * // using "_.pluck" callback shorthand - * _.map(_.sortBy(characters, 'age'), _.values); - * // => [['barney', 26], ['fred', 30], ['barney', 36], ['fred', 40]] - * - * // sorting by multiple properties - * _.map(_.sortBy(characters, ['name', 'age']), _.values); - * // = > [['barney', 26], ['barney', 36], ['fred', 30], ['fred', 40]] - */ - function sortBy(collection, callback, thisArg) { - var index = -1, - isArr = isArray(callback), - length = collection ? collection.length : 0, - result = Array(typeof length == 'number' ? length : 0); - - if (!isArr) { - callback = lodash.createCallback(callback, thisArg, 3); - } - forEach(collection, function(value, key, collection) { - var object = result[++index] = getObject(); - if (isArr) { - object.criteria = map(callback, function(key) { return value[key]; }); - } else { - (object.criteria = getArray())[0] = callback(value, key, collection); - } - object.index = index; - object.value = value; - }); - - length = result.length; - result.sort(compareAscending); - while (length--) { - var object = result[length]; - result[length] = object.value; - if (!isArr) { - releaseArray(object.criteria); - } - releaseObject(object); - } - return result; - } - - /** - * Converts the `collection` to an array. - * - * @static - * @memberOf _ - * @category Collections - * @param {Array|Object|string} collection The collection to convert. - * @returns {Array} Returns the new converted array. - * @example - * - * (function() { return _.toArray(arguments).slice(1); })(1, 2, 3, 4); - * // => [2, 3, 4] - */ - function toArray(collection) { - if (collection && typeof collection.length == 'number') { - return slice(collection); - } - return values(collection); - } - - /** - * Performs a deep comparison of each element in a `collection` to the given - * `properties` object, returning an array of all elements that have equivalent - * property values. - * - * @static - * @memberOf _ - * @type Function - * @category Collections - * @param {Array|Object|string} collection The collection to iterate over. - * @param {Object} props The object of property values to filter by. - * @returns {Array} Returns a new array of elements that have the given properties. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }, - * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } - * ]; - * - * _.where(characters, { 'age': 36 }); - * // => [{ 'name': 'barney', 'age': 36, 'pets': ['hoppy'] }] - * - * _.where(characters, { 'pets': ['dino'] }); - * // => [{ 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] }] - */ - var where = filter; - - /*--------------------------------------------------------------------------*/ - - /** - * Creates an array with all falsey values removed. The values `false`, `null`, - * `0`, `""`, `undefined`, and `NaN` are all falsey. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to compact. - * @returns {Array} Returns a new array of filtered values. - * @example - * - * _.compact([0, 1, false, 2, '', 3]); - * // => [1, 2, 3] - */ - function compact(array) { - var index = -1, - length = array ? array.length : 0, - result = []; - - while (++index < length) { - var value = array[index]; - if (value) { - result.push(value); - } - } - return result; - } - - /** - * Creates an array excluding all values of the provided arrays using strict - * equality for comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to process. - * @param {...Array} [values] The arrays of values to exclude. - * @returns {Array} Returns a new array of filtered values. - * @example - * - * _.difference([1, 2, 3, 4, 5], [5, 2, 10]); - * // => [1, 3, 4] - */ - function difference(array) { - return baseDifference(array, baseFlatten(arguments, true, true, 1)); - } - - /** - * This method is like `_.find` except that it returns the index of the first - * element that passes the callback check, instead of the element itself. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to search. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': false }, - * { 'name': 'fred', 'age': 40, 'blocked': true }, - * { 'name': 'pebbles', 'age': 1, 'blocked': false } - * ]; - * - * _.findIndex(characters, function(chr) { - * return chr.age < 20; - * }); - * // => 2 - * - * // using "_.where" callback shorthand - * _.findIndex(characters, { 'age': 36 }); - * // => 0 - * - * // using "_.pluck" callback shorthand - * _.findIndex(characters, 'blocked'); - * // => 1 - */ - function findIndex(array, callback, thisArg) { - var index = -1, - length = array ? array.length : 0; - - callback = lodash.createCallback(callback, thisArg, 3); - while (++index < length) { - if (callback(array[index], index, array)) { - return index; - } - } - return -1; - } - - /** - * This method is like `_.findIndex` except that it iterates over elements - * of a `collection` from right to left. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to search. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {number} Returns the index of the found element, else `-1`. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36, 'blocked': true }, - * { 'name': 'fred', 'age': 40, 'blocked': false }, - * { 'name': 'pebbles', 'age': 1, 'blocked': true } - * ]; - * - * _.findLastIndex(characters, function(chr) { - * return chr.age > 30; - * }); - * // => 1 - * - * // using "_.where" callback shorthand - * _.findLastIndex(characters, { 'age': 36 }); - * // => 0 - * - * // using "_.pluck" callback shorthand - * _.findLastIndex(characters, 'blocked'); - * // => 2 - */ - function findLastIndex(array, callback, thisArg) { - var length = array ? array.length : 0; - callback = lodash.createCallback(callback, thisArg, 3); - while (length--) { - if (callback(array[length], length, array)) { - return length; - } - } - return -1; - } - - /** - * Gets the first element or first `n` elements of an array. If a callback - * is provided elements at the beginning of the array are returned as long - * as the callback returns truey. The callback is bound to `thisArg` and - * invoked with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias head, take - * @category Arrays - * @param {Array} array The array to query. - * @param {Function|Object|number|string} [callback] The function called - * per element or the number of elements to return. If a property name or - * object is provided it will be used to create a "_.pluck" or "_.where" - * style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the first element(s) of `array`. - * @example - * - * _.first([1, 2, 3]); - * // => 1 - * - * _.first([1, 2, 3], 2); - * // => [1, 2] - * - * _.first([1, 2, 3], function(num) { - * return num < 3; - * }); - * // => [1, 2] - * - * var characters = [ - * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, - * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, - * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } - * ]; - * - * // using "_.pluck" callback shorthand - * _.first(characters, 'blocked'); - * // => [{ 'name': 'barney', 'blocked': true, 'employer': 'slate' }] - * - * // using "_.where" callback shorthand - * _.pluck(_.first(characters, { 'employer': 'slate' }), 'name'); - * // => ['barney', 'fred'] - */ - function first(array, callback, thisArg) { - var n = 0, - length = array ? array.length : 0; - - if (typeof callback != 'number' && callback != null) { - var index = -1; - callback = lodash.createCallback(callback, thisArg, 3); - while (++index < length && callback(array[index], index, array)) { - n++; - } - } else { - n = callback; - if (n == null || thisArg) { - return array ? array[0] : undefined; - } - } - return slice(array, 0, nativeMin(nativeMax(0, n), length)); - } - - /** - * Flattens a nested array (the nesting can be to any depth). If `isShallow` - * is truey, the array will only be flattened a single level. If a callback - * is provided each element of the array is passed through the callback before - * flattening. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to flatten. - * @param {boolean} [isShallow=false] A flag to restrict flattening to a single level. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new flattened array. - * @example - * - * _.flatten([1, [2], [3, [[4]]]]); - * // => [1, 2, 3, 4]; - * - * _.flatten([1, [2], [3, [[4]]]], true); - * // => [1, 2, 3, [[4]]]; - * - * var characters = [ - * { 'name': 'barney', 'age': 30, 'pets': ['hoppy'] }, - * { 'name': 'fred', 'age': 40, 'pets': ['baby puss', 'dino'] } - * ]; - * - * // using "_.pluck" callback shorthand - * _.flatten(characters, 'pets'); - * // => ['hoppy', 'baby puss', 'dino'] - */ - function flatten(array, isShallow, callback, thisArg) { - // juggle arguments - if (typeof isShallow != 'boolean' && isShallow != null) { - thisArg = callback; - callback = (typeof isShallow != 'function' && thisArg && thisArg[isShallow] === array) ? null : isShallow; - isShallow = false; - } - if (callback != null) { - array = map(array, callback, thisArg); - } - return baseFlatten(array, isShallow); - } - - /** - * Gets the index at which the first occurrence of `value` is found using - * strict equality for comparisons, i.e. `===`. If the array is already sorted - * providing `true` for `fromIndex` will run a faster binary search. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {boolean|number} [fromIndex=0] The index to search from or `true` - * to perform a binary search on a sorted array. - * @returns {number} Returns the index of the matched value or `-1`. - * @example - * - * _.indexOf([1, 2, 3, 1, 2, 3], 2); - * // => 1 - * - * _.indexOf([1, 2, 3, 1, 2, 3], 2, 3); - * // => 4 - * - * _.indexOf([1, 1, 2, 2, 3, 3], 2, true); - * // => 2 - */ - function indexOf(array, value, fromIndex) { - if (typeof fromIndex == 'number') { - var length = array ? array.length : 0; - fromIndex = (fromIndex < 0 ? nativeMax(0, length + fromIndex) : fromIndex || 0); - } else if (fromIndex) { - var index = sortedIndex(array, value); - return array[index] === value ? index : -1; - } - return baseIndexOf(array, value, fromIndex); - } - - /** - * Gets all but the last element or last `n` elements of an array. If a - * callback is provided elements at the end of the array are excluded from - * the result as long as the callback returns truey. The callback is bound - * to `thisArg` and invoked with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to query. - * @param {Function|Object|number|string} [callback=1] The function called - * per element or the number of elements to exclude. If a property name or - * object is provided it will be used to create a "_.pluck" or "_.where" - * style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a slice of `array`. - * @example - * - * _.initial([1, 2, 3]); - * // => [1, 2] - * - * _.initial([1, 2, 3], 2); - * // => [1] - * - * _.initial([1, 2, 3], function(num) { - * return num > 1; - * }); - * // => [1] - * - * var characters = [ - * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, - * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, - * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } - * ]; - * - * // using "_.pluck" callback shorthand - * _.initial(characters, 'blocked'); - * // => [{ 'name': 'barney', 'blocked': false, 'employer': 'slate' }] - * - * // using "_.where" callback shorthand - * _.pluck(_.initial(characters, { 'employer': 'na' }), 'name'); - * // => ['barney', 'fred'] - */ - function initial(array, callback, thisArg) { - var n = 0, - length = array ? array.length : 0; - - if (typeof callback != 'number' && callback != null) { - var index = length; - callback = lodash.createCallback(callback, thisArg, 3); - while (index-- && callback(array[index], index, array)) { - n++; - } - } else { - n = (callback == null || thisArg) ? 1 : callback || n; - } - return slice(array, 0, nativeMin(nativeMax(0, length - n), length)); - } - - /** - * Creates an array of unique values present in all provided arrays using - * strict equality for comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {...Array} [array] The arrays to inspect. - * @returns {Array} Returns an array of shared values. - * @example - * - * _.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1]); - * // => [1, 2] - */ - function intersection() { - var args = [], - argsIndex = -1, - argsLength = arguments.length, - caches = getArray(), - indexOf = getIndexOf(), - trustIndexOf = indexOf === baseIndexOf, - seen = getArray(); - - while (++argsIndex < argsLength) { - var value = arguments[argsIndex]; - if (isArray(value) || isArguments(value)) { - args.push(value); - caches.push(trustIndexOf && value.length >= largeArraySize && - createCache(argsIndex ? args[argsIndex] : seen)); - } - } - var array = args[0], - index = -1, - length = array ? array.length : 0, - result = []; - - outer: - while (++index < length) { - var cache = caches[0]; - value = array[index]; - - if ((cache ? cacheIndexOf(cache, value) : indexOf(seen, value)) < 0) { - argsIndex = argsLength; - (cache || seen).push(value); - while (--argsIndex) { - cache = caches[argsIndex]; - if ((cache ? cacheIndexOf(cache, value) : indexOf(args[argsIndex], value)) < 0) { - continue outer; - } - } - result.push(value); - } - } - while (argsLength--) { - cache = caches[argsLength]; - if (cache) { - releaseObject(cache); - } - } - releaseArray(caches); - releaseArray(seen); - return result; - } - - /** - * Gets the last element or last `n` elements of an array. If a callback is - * provided elements at the end of the array are returned as long as the - * callback returns truey. The callback is bound to `thisArg` and invoked - * with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to query. - * @param {Function|Object|number|string} [callback] The function called - * per element or the number of elements to return. If a property name or - * object is provided it will be used to create a "_.pluck" or "_.where" - * style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {*} Returns the last element(s) of `array`. - * @example - * - * _.last([1, 2, 3]); - * // => 3 - * - * _.last([1, 2, 3], 2); - * // => [2, 3] - * - * _.last([1, 2, 3], function(num) { - * return num > 1; - * }); - * // => [2, 3] - * - * var characters = [ - * { 'name': 'barney', 'blocked': false, 'employer': 'slate' }, - * { 'name': 'fred', 'blocked': true, 'employer': 'slate' }, - * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } - * ]; - * - * // using "_.pluck" callback shorthand - * _.pluck(_.last(characters, 'blocked'), 'name'); - * // => ['fred', 'pebbles'] - * - * // using "_.where" callback shorthand - * _.last(characters, { 'employer': 'na' }); - * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] - */ - function last(array, callback, thisArg) { - var n = 0, - length = array ? array.length : 0; - - if (typeof callback != 'number' && callback != null) { - var index = length; - callback = lodash.createCallback(callback, thisArg, 3); - while (index-- && callback(array[index], index, array)) { - n++; - } - } else { - n = callback; - if (n == null || thisArg) { - return array ? array[length - 1] : undefined; - } - } - return slice(array, nativeMax(0, length - n)); - } - - /** - * Gets the index at which the last occurrence of `value` is found using strict - * equality for comparisons, i.e. `===`. If `fromIndex` is negative, it is used - * as the offset from the end of the collection. - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to search. - * @param {*} value The value to search for. - * @param {number} [fromIndex=array.length-1] The index to search from. - * @returns {number} Returns the index of the matched value or `-1`. - * @example - * - * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2); - * // => 4 - * - * _.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3); - * // => 1 - */ - function lastIndexOf(array, value, fromIndex) { - var index = array ? array.length : 0; - if (typeof fromIndex == 'number') { - index = (fromIndex < 0 ? nativeMax(0, index + fromIndex) : nativeMin(fromIndex, index - 1)) + 1; - } - while (index--) { - if (array[index] === value) { - return index; - } - } - return -1; - } - - /** - * Removes all provided values from the given array using strict equality for - * comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to modify. - * @param {...*} [value] The values to remove. - * @returns {Array} Returns `array`. - * @example - * - * var array = [1, 2, 3, 1, 2, 3]; - * _.pull(array, 2, 3); - * console.log(array); - * // => [1, 1] - */ - function pull(array) { - var args = arguments, - argsIndex = 0, - argsLength = args.length, - length = array ? array.length : 0; - - while (++argsIndex < argsLength) { - var index = -1, - value = args[argsIndex]; - while (++index < length) { - if (array[index] === value) { - splice.call(array, index--, 1); - length--; - } - } - } - return array; - } - - /** - * Creates an array of numbers (positive and/or negative) progressing from - * `start` up to but not including `end`. If `start` is less than `stop` a - * zero-length range is created unless a negative `step` is specified. - * - * @static - * @memberOf _ - * @category Arrays - * @param {number} [start=0] The start of the range. - * @param {number} end The end of the range. - * @param {number} [step=1] The value to increment or decrement by. - * @returns {Array} Returns a new range array. - * @example - * - * _.range(4); - * // => [0, 1, 2, 3] - * - * _.range(1, 5); - * // => [1, 2, 3, 4] - * - * _.range(0, 20, 5); - * // => [0, 5, 10, 15] - * - * _.range(0, -4, -1); - * // => [0, -1, -2, -3] - * - * _.range(1, 4, 0); - * // => [1, 1, 1] - * - * _.range(0); - * // => [] - */ - function range(start, end, step) { - start = +start || 0; - step = typeof step == 'number' ? step : (+step || 1); - - if (end == null) { - end = start; - start = 0; - } - // use `Array(length)` so engines like Chakra and V8 avoid slower modes - // http://youtu.be/XAqIpGU8ZZk#t=17m25s - var index = -1, - length = nativeMax(0, ceil((end - start) / (step || 1))), - result = Array(length); - - while (++index < length) { - result[index] = start; - start += step; - } - return result; - } - - /** - * Removes all elements from an array that the callback returns truey for - * and returns an array of removed elements. The callback is bound to `thisArg` - * and invoked with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to modify. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a new array of removed elements. - * @example - * - * var array = [1, 2, 3, 4, 5, 6]; - * var evens = _.remove(array, function(num) { return num % 2 == 0; }); - * - * console.log(array); - * // => [1, 3, 5] - * - * console.log(evens); - * // => [2, 4, 6] - */ - function remove(array, callback, thisArg) { - var index = -1, - length = array ? array.length : 0, - result = []; - - callback = lodash.createCallback(callback, thisArg, 3); - while (++index < length) { - var value = array[index]; - if (callback(value, index, array)) { - result.push(value); - splice.call(array, index--, 1); - length--; - } - } - return result; - } - - /** - * The opposite of `_.initial` this method gets all but the first element or - * first `n` elements of an array. If a callback function is provided elements - * at the beginning of the array are excluded from the result as long as the - * callback returns truey. The callback is bound to `thisArg` and invoked - * with three arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias drop, tail - * @category Arrays - * @param {Array} array The array to query. - * @param {Function|Object|number|string} [callback=1] The function called - * per element or the number of elements to exclude. If a property name or - * object is provided it will be used to create a "_.pluck" or "_.where" - * style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a slice of `array`. - * @example - * - * _.rest([1, 2, 3]); - * // => [2, 3] - * - * _.rest([1, 2, 3], 2); - * // => [3] - * - * _.rest([1, 2, 3], function(num) { - * return num < 3; - * }); - * // => [3] - * - * var characters = [ - * { 'name': 'barney', 'blocked': true, 'employer': 'slate' }, - * { 'name': 'fred', 'blocked': false, 'employer': 'slate' }, - * { 'name': 'pebbles', 'blocked': true, 'employer': 'na' } - * ]; - * - * // using "_.pluck" callback shorthand - * _.pluck(_.rest(characters, 'blocked'), 'name'); - * // => ['fred', 'pebbles'] - * - * // using "_.where" callback shorthand - * _.rest(characters, { 'employer': 'slate' }); - * // => [{ 'name': 'pebbles', 'blocked': true, 'employer': 'na' }] - */ - function rest(array, callback, thisArg) { - if (typeof callback != 'number' && callback != null) { - var n = 0, - index = -1, - length = array ? array.length : 0; - - callback = lodash.createCallback(callback, thisArg, 3); - while (++index < length && callback(array[index], index, array)) { - n++; - } - } else { - n = (callback == null || thisArg) ? 1 : nativeMax(0, callback); - } - return slice(array, n); - } - - /** - * Uses a binary search to determine the smallest index at which a value - * should be inserted into a given sorted array in order to maintain the sort - * order of the array. If a callback is provided it will be executed for - * `value` and each element of `array` to compute their sort ranking. The - * callback is bound to `thisArg` and invoked with one argument; (value). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to inspect. - * @param {*} value The value to evaluate. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {number} Returns the index at which `value` should be inserted - * into `array`. - * @example - * - * _.sortedIndex([20, 30, 50], 40); - * // => 2 - * - * // using "_.pluck" callback shorthand - * _.sortedIndex([{ 'x': 20 }, { 'x': 30 }, { 'x': 50 }], { 'x': 40 }, 'x'); - * // => 2 - * - * var dict = { - * 'wordToNumber': { 'twenty': 20, 'thirty': 30, 'fourty': 40, 'fifty': 50 } - * }; - * - * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { - * return dict.wordToNumber[word]; - * }); - * // => 2 - * - * _.sortedIndex(['twenty', 'thirty', 'fifty'], 'fourty', function(word) { - * return this.wordToNumber[word]; - * }, dict); - * // => 2 - */ - function sortedIndex(array, value, callback, thisArg) { - var low = 0, - high = array ? array.length : low; - - // explicitly reference `identity` for better inlining in Firefox - callback = callback ? lodash.createCallback(callback, thisArg, 1) : identity; - value = callback(value); - - while (low < high) { - var mid = (low + high) >>> 1; - (callback(array[mid]) < value) - ? low = mid + 1 - : high = mid; - } - return low; - } - - /** - * Creates an array of unique values, in order, of the provided arrays using - * strict equality for comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {...Array} [array] The arrays to inspect. - * @returns {Array} Returns an array of combined values. - * @example - * - * _.union([1, 2, 3], [5, 2, 1, 4], [2, 1]); - * // => [1, 2, 3, 5, 4] - */ - function union() { - return baseUniq(baseFlatten(arguments, true, true)); - } - - /** - * Creates a duplicate-value-free version of an array using strict equality - * for comparisons, i.e. `===`. If the array is sorted, providing - * `true` for `isSorted` will use a faster algorithm. If a callback is provided - * each element of `array` is passed through the callback before uniqueness - * is computed. The callback is bound to `thisArg` and invoked with three - * arguments; (value, index, array). - * - * If a property name is provided for `callback` the created "_.pluck" style - * callback will return the property value of the given element. - * - * If an object is provided for `callback` the created "_.where" style callback - * will return `true` for elements that have the properties of the given object, - * else `false`. - * - * @static - * @memberOf _ - * @alias unique - * @category Arrays - * @param {Array} array The array to process. - * @param {boolean} [isSorted=false] A flag to indicate that `array` is sorted. - * @param {Function|Object|string} [callback=identity] The function called - * per iteration. If a property name or object is provided it will be used - * to create a "_.pluck" or "_.where" style callback, respectively. - * @param {*} [thisArg] The `this` binding of `callback`. - * @returns {Array} Returns a duplicate-value-free array. - * @example - * - * _.uniq([1, 2, 1, 3, 1]); - * // => [1, 2, 3] - * - * _.uniq([1, 1, 2, 2, 3], true); - * // => [1, 2, 3] - * - * _.uniq(['A', 'b', 'C', 'a', 'B', 'c'], function(letter) { return letter.toLowerCase(); }); - * // => ['A', 'b', 'C'] - * - * _.uniq([1, 2.5, 3, 1.5, 2, 3.5], function(num) { return this.floor(num); }, Math); - * // => [1, 2.5, 3] - * - * // using "_.pluck" callback shorthand - * _.uniq([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x'); - * // => [{ 'x': 1 }, { 'x': 2 }] - */ - function uniq(array, isSorted, callback, thisArg) { - // juggle arguments - if (typeof isSorted != 'boolean' && isSorted != null) { - thisArg = callback; - callback = (typeof isSorted != 'function' && thisArg && thisArg[isSorted] === array) ? null : isSorted; - isSorted = false; - } - if (callback != null) { - callback = lodash.createCallback(callback, thisArg, 3); - } - return baseUniq(array, isSorted, callback); - } - - /** - * Creates an array excluding all provided values using strict equality for - * comparisons, i.e. `===`. - * - * @static - * @memberOf _ - * @category Arrays - * @param {Array} array The array to filter. - * @param {...*} [value] The values to exclude. - * @returns {Array} Returns a new array of filtered values. - * @example - * - * _.without([1, 2, 1, 0, 3, 1, 4], 0, 1); - * // => [2, 3, 4] - */ - function without(array) { - return baseDifference(array, slice(arguments, 1)); - } - - /** - * Creates an array that is the symmetric difference of the provided arrays. - * See http://en.wikipedia.org/wiki/Symmetric_difference. - * - * @static - * @memberOf _ - * @category Arrays - * @param {...Array} [array] The arrays to inspect. - * @returns {Array} Returns an array of values. - * @example - * - * _.xor([1, 2, 3], [5, 2, 1, 4]); - * // => [3, 5, 4] - * - * _.xor([1, 2, 5], [2, 3, 5], [3, 4, 5]); - * // => [1, 4, 5] - */ - function xor() { - var index = -1, - length = arguments.length; - - while (++index < length) { - var array = arguments[index]; - if (isArray(array) || isArguments(array)) { - var result = result - ? baseUniq(baseDifference(result, array).concat(baseDifference(array, result))) - : array; - } - } - return result || []; - } - - /** - * Creates an array of grouped elements, the first of which contains the first - * elements of the given arrays, the second of which contains the second - * elements of the given arrays, and so on. - * - * @static - * @memberOf _ - * @alias unzip - * @category Arrays - * @param {...Array} [array] Arrays to process. - * @returns {Array} Returns a new array of grouped elements. - * @example - * - * _.zip(['fred', 'barney'], [30, 40], [true, false]); - * // => [['fred', 30, true], ['barney', 40, false]] - */ - function zip() { - var array = arguments.length > 1 ? arguments : arguments[0], - index = -1, - length = array ? max(pluck(array, 'length')) : 0, - result = Array(length < 0 ? 0 : length); - - while (++index < length) { - result[index] = pluck(array, index); - } - return result; - } - - /** - * Creates an object composed from arrays of `keys` and `values`. Provide - * either a single two dimensional array, i.e. `[[key1, value1], [key2, value2]]` - * or two arrays, one of `keys` and one of corresponding `values`. - * - * @static - * @memberOf _ - * @alias object - * @category Arrays - * @param {Array} keys The array of keys. - * @param {Array} [values=[]] The array of values. - * @returns {Object} Returns an object composed of the given keys and - * corresponding values. - * @example - * - * _.zipObject(['fred', 'barney'], [30, 40]); - * // => { 'fred': 30, 'barney': 40 } - */ - function zipObject(keys, values) { - var index = -1, - length = keys ? keys.length : 0, - result = {}; - - if (!values && length && !isArray(keys[0])) { - values = []; - } - while (++index < length) { - var key = keys[index]; - if (values) { - result[key] = values[index]; - } else if (key) { - result[key[0]] = key[1]; - } - } - return result; - } - - /*--------------------------------------------------------------------------*/ - - /** - * Creates a function that executes `func`, with the `this` binding and - * arguments of the created function, only after being called `n` times. - * - * @static - * @memberOf _ - * @category Functions - * @param {number} n The number of times the function must be called before - * `func` is executed. - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var saves = ['profile', 'settings']; - * - * var done = _.after(saves.length, function() { - * console.log('Done saving!'); - * }); - * - * _.forEach(saves, function(type) { - * asyncSave({ 'type': type, 'complete': done }); - * }); - * // => logs 'Done saving!', after all saves have completed - */ - function after(n, func) { - if (!isFunction(func)) { - throw new TypeError; - } - return function() { - if (--n < 1) { - return func.apply(this, arguments); - } - }; - } - - /** - * Creates a function that, when called, invokes `func` with the `this` - * binding of `thisArg` and prepends any additional `bind` arguments to those - * provided to the bound function. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to bind. - * @param {*} [thisArg] The `this` binding of `func`. - * @param {...*} [arg] Arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var func = function(greeting) { - * return greeting + ' ' + this.name; - * }; - * - * func = _.bind(func, { 'name': 'fred' }, 'hi'); - * func(); - * // => 'hi fred' - */ - function bind(func, thisArg) { - return arguments.length > 2 - ? createWrapper(func, 17, slice(arguments, 2), null, thisArg) - : createWrapper(func, 1, null, null, thisArg); - } - - /** - * Binds methods of an object to the object itself, overwriting the existing - * method. Method names may be specified as individual arguments or as arrays - * of method names. If no method names are provided all the function properties - * of `object` will be bound. - * - * @static - * @memberOf _ - * @category Functions - * @param {Object} object The object to bind and assign the bound methods to. - * @param {...string} [methodName] The object method names to - * bind, specified as individual method names or arrays of method names. - * @returns {Object} Returns `object`. - * @example - * - * var view = { - * 'label': 'docs', - * 'onClick': function() { console.log('clicked ' + this.label); } - * }; - * - * _.bindAll(view); - * jQuery('#docs').on('click', view.onClick); - * // => logs 'clicked docs', when the button is clicked - */ - function bindAll(object) { - var funcs = arguments.length > 1 ? baseFlatten(arguments, true, false, 1) : functions(object), - index = -1, - length = funcs.length; - - while (++index < length) { - var key = funcs[index]; - object[key] = createWrapper(object[key], 1, null, null, object); - } - return object; - } - - /** - * Creates a function that, when called, invokes the method at `object[key]` - * and prepends any additional `bindKey` arguments to those provided to the bound - * function. This method differs from `_.bind` by allowing bound functions to - * reference methods that will be redefined or don't yet exist. - * See http://michaux.ca/articles/lazy-function-definition-pattern. - * - * @static - * @memberOf _ - * @category Functions - * @param {Object} object The object the method belongs to. - * @param {string} key The key of the method. - * @param {...*} [arg] Arguments to be partially applied. - * @returns {Function} Returns the new bound function. - * @example - * - * var object = { - * 'name': 'fred', - * 'greet': function(greeting) { - * return greeting + ' ' + this.name; - * } - * }; - * - * var func = _.bindKey(object, 'greet', 'hi'); - * func(); - * // => 'hi fred' - * - * object.greet = function(greeting) { - * return greeting + 'ya ' + this.name + '!'; - * }; - * - * func(); - * // => 'hiya fred!' - */ - function bindKey(object, key) { - return arguments.length > 2 - ? createWrapper(key, 19, slice(arguments, 2), null, object) - : createWrapper(key, 3, null, null, object); - } - - /** - * Creates a function that is the composition of the provided functions, - * where each function consumes the return value of the function that follows. - * For example, composing the functions `f()`, `g()`, and `h()` produces `f(g(h()))`. - * Each function is executed with the `this` binding of the composed function. - * - * @static - * @memberOf _ - * @category Functions - * @param {...Function} [func] Functions to compose. - * @returns {Function} Returns the new composed function. - * @example - * - * var realNameMap = { - * 'pebbles': 'penelope' - * }; - * - * var format = function(name) { - * name = realNameMap[name.toLowerCase()] || name; - * return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase(); - * }; - * - * var greet = function(formatted) { - * return 'Hiya ' + formatted + '!'; - * }; - * - * var welcome = _.compose(greet, format); - * welcome('pebbles'); - * // => 'Hiya Penelope!' - */ - function compose() { - var funcs = arguments, - length = funcs.length; - - while (length--) { - if (!isFunction(funcs[length])) { - throw new TypeError; - } - } - return function() { - var args = arguments, - length = funcs.length; - - while (length--) { - args = [funcs[length].apply(this, args)]; - } - return args[0]; - }; - } - - /** - * Creates a function which accepts one or more arguments of `func` that when - * invoked either executes `func` returning its result, if all `func` arguments - * have been provided, or returns a function that accepts one or more of the - * remaining `func` arguments, and so on. The arity of `func` can be specified - * if `func.length` is not sufficient. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to curry. - * @param {number} [arity=func.length] The arity of `func`. - * @returns {Function} Returns the new curried function. - * @example - * - * var curried = _.curry(function(a, b, c) { - * console.log(a + b + c); - * }); - * - * curried(1)(2)(3); - * // => 6 - * - * curried(1, 2)(3); - * // => 6 - * - * curried(1, 2, 3); - * // => 6 - */ - function curry(func, arity) { - arity = typeof arity == 'number' ? arity : (+arity || func.length); - return createWrapper(func, 4, null, null, null, arity); - } - - /** - * Creates a function that will delay the execution of `func` until after - * `wait` milliseconds have elapsed since the last time it was invoked. - * Provide an options object to indicate that `func` should be invoked on - * the leading and/or trailing edge of the `wait` timeout. Subsequent calls - * to the debounced function will return the result of the last `func` call. - * - * Note: If `leading` and `trailing` options are `true` `func` will be called - * on the trailing edge of the timeout only if the the debounced function is - * invoked more than once during the `wait` timeout. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to debounce. - * @param {number} wait The number of milliseconds to delay. - * @param {Object} [options] The options object. - * @param {boolean} [options.leading=false] Specify execution on the leading edge of the timeout. - * @param {number} [options.maxWait] The maximum time `func` is allowed to be delayed before it's called. - * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. - * @returns {Function} Returns the new debounced function. - * @example - * - * // avoid costly calculations while the window size is in flux - * var lazyLayout = _.debounce(calculateLayout, 150); - * jQuery(window).on('resize', lazyLayout); - * - * // execute `sendMail` when the click event is fired, debouncing subsequent calls - * jQuery('#postbox').on('click', _.debounce(sendMail, 300, { - * 'leading': true, - * 'trailing': false - * }); - * - * // ensure `batchLog` is executed once after 1 second of debounced calls - * var source = new EventSource('/stream'); - * source.addEventListener('message', _.debounce(batchLog, 250, { - * 'maxWait': 1000 - * }, false); - */ - function debounce(func, wait, options) { - var args, - maxTimeoutId, - result, - stamp, - thisArg, - timeoutId, - trailingCall, - lastCalled = 0, - maxWait = false, - trailing = true; - - if (!isFunction(func)) { - throw new TypeError; - } - wait = nativeMax(0, wait) || 0; - if (options === true) { - var leading = true; - trailing = false; - } else if (isObject(options)) { - leading = options.leading; - maxWait = 'maxWait' in options && (nativeMax(wait, options.maxWait) || 0); - trailing = 'trailing' in options ? options.trailing : trailing; - } - var delayed = function() { - var remaining = wait - (now() - stamp); - if (remaining <= 0) { - if (maxTimeoutId) { - clearTimeout(maxTimeoutId); - } - var isCalled = trailingCall; - maxTimeoutId = timeoutId = trailingCall = undefined; - if (isCalled) { - lastCalled = now(); - result = func.apply(thisArg, args); - if (!timeoutId && !maxTimeoutId) { - args = thisArg = null; - } - } - } else { - timeoutId = setTimeout(delayed, remaining); - } - }; - - var maxDelayed = function() { - if (timeoutId) { - clearTimeout(timeoutId); - } - maxTimeoutId = timeoutId = trailingCall = undefined; - if (trailing || (maxWait !== wait)) { - lastCalled = now(); - result = func.apply(thisArg, args); - if (!timeoutId && !maxTimeoutId) { - args = thisArg = null; - } - } - }; - - return function() { - args = arguments; - stamp = now(); - thisArg = this; - trailingCall = trailing && (timeoutId || !leading); - - if (maxWait === false) { - var leadingCall = leading && !timeoutId; - } else { - if (!maxTimeoutId && !leading) { - lastCalled = stamp; - } - var remaining = maxWait - (stamp - lastCalled), - isCalled = remaining <= 0; - - if (isCalled) { - if (maxTimeoutId) { - maxTimeoutId = clearTimeout(maxTimeoutId); - } - lastCalled = stamp; - result = func.apply(thisArg, args); - } - else if (!maxTimeoutId) { - maxTimeoutId = setTimeout(maxDelayed, remaining); - } - } - if (isCalled && timeoutId) { - timeoutId = clearTimeout(timeoutId); - } - else if (!timeoutId && wait !== maxWait) { - timeoutId = setTimeout(delayed, wait); - } - if (leadingCall) { - isCalled = true; - result = func.apply(thisArg, args); - } - if (isCalled && !timeoutId && !maxTimeoutId) { - args = thisArg = null; - } - return result; - }; - } - - /** - * Defers executing the `func` function until the current call stack has cleared. - * Additional arguments will be provided to `func` when it is invoked. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to defer. - * @param {...*} [arg] Arguments to invoke the function with. - * @returns {number} Returns the timer id. - * @example - * - * _.defer(function(text) { console.log(text); }, 'deferred'); - * // logs 'deferred' after one or more milliseconds - */ - function defer(func) { - if (!isFunction(func)) { - throw new TypeError; - } - var args = slice(arguments, 1); - return setTimeout(function() { func.apply(undefined, args); }, 1); - } - - /** - * Executes the `func` function after `wait` milliseconds. Additional arguments - * will be provided to `func` when it is invoked. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to delay. - * @param {number} wait The number of milliseconds to delay execution. - * @param {...*} [arg] Arguments to invoke the function with. - * @returns {number} Returns the timer id. - * @example - * - * _.delay(function(text) { console.log(text); }, 1000, 'later'); - * // => logs 'later' after one second - */ - function delay(func, wait) { - if (!isFunction(func)) { - throw new TypeError; - } - var args = slice(arguments, 2); - return setTimeout(function() { func.apply(undefined, args); }, wait); - } - - /** - * Creates a function that memoizes the result of `func`. If `resolver` is - * provided it will be used to determine the cache key for storing the result - * based on the arguments provided to the memoized function. By default, the - * first argument provided to the memoized function is used as the cache key. - * The `func` is executed with the `this` binding of the memoized function. - * The result cache is exposed as the `cache` property on the memoized function. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to have its output memoized. - * @param {Function} [resolver] A function used to resolve the cache key. - * @returns {Function} Returns the new memoizing function. - * @example - * - * var fibonacci = _.memoize(function(n) { - * return n < 2 ? n : fibonacci(n - 1) + fibonacci(n - 2); - * }); - * - * fibonacci(9) - * // => 34 - * - * var data = { - * 'fred': { 'name': 'fred', 'age': 40 }, - * 'pebbles': { 'name': 'pebbles', 'age': 1 } - * }; - * - * // modifying the result cache - * var get = _.memoize(function(name) { return data[name]; }, _.identity); - * get('pebbles'); - * // => { 'name': 'pebbles', 'age': 1 } - * - * get.cache.pebbles.name = 'penelope'; - * get('pebbles'); - * // => { 'name': 'penelope', 'age': 1 } - */ - function memoize(func, resolver) { - if (!isFunction(func)) { - throw new TypeError; - } - var memoized = function() { - var cache = memoized.cache, - key = resolver ? resolver.apply(this, arguments) : keyPrefix + arguments[0]; - - return hasOwnProperty.call(cache, key) - ? cache[key] - : (cache[key] = func.apply(this, arguments)); - } - memoized.cache = {}; - return memoized; - } - - /** - * Creates a function that is restricted to execute `func` once. Repeat calls to - * the function will return the value of the first call. The `func` is executed - * with the `this` binding of the created function. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to restrict. - * @returns {Function} Returns the new restricted function. - * @example - * - * var initialize = _.once(createApplication); - * initialize(); - * initialize(); - * // `initialize` executes `createApplication` once - */ - function once(func) { - var ran, - result; - - if (!isFunction(func)) { - throw new TypeError; - } - return function() { - if (ran) { - return result; - } - ran = true; - result = func.apply(this, arguments); - - // clear the `func` variable so the function may be garbage collected - func = null; - return result; - }; - } - - /** - * Creates a function that, when called, invokes `func` with any additional - * `partial` arguments prepended to those provided to the new function. This - * method is similar to `_.bind` except it does **not** alter the `this` binding. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [arg] Arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * var greet = function(greeting, name) { return greeting + ' ' + name; }; - * var hi = _.partial(greet, 'hi'); - * hi('fred'); - * // => 'hi fred' - */ - function partial(func) { - return createWrapper(func, 16, slice(arguments, 1)); - } - - /** - * This method is like `_.partial` except that `partial` arguments are - * appended to those provided to the new function. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to partially apply arguments to. - * @param {...*} [arg] Arguments to be partially applied. - * @returns {Function} Returns the new partially applied function. - * @example - * - * var defaultsDeep = _.partialRight(_.merge, _.defaults); - * - * var options = { - * 'variable': 'data', - * 'imports': { 'jq': $ } - * }; - * - * defaultsDeep(options, _.templateSettings); - * - * options.variable - * // => 'data' - * - * options.imports - * // => { '_': _, 'jq': $ } - */ - function partialRight(func) { - return createWrapper(func, 32, null, slice(arguments, 1)); - } - - /** - * Creates a function that, when executed, will only call the `func` function - * at most once per every `wait` milliseconds. Provide an options object to - * indicate that `func` should be invoked on the leading and/or trailing edge - * of the `wait` timeout. Subsequent calls to the throttled function will - * return the result of the last `func` call. - * - * Note: If `leading` and `trailing` options are `true` `func` will be called - * on the trailing edge of the timeout only if the the throttled function is - * invoked more than once during the `wait` timeout. - * - * @static - * @memberOf _ - * @category Functions - * @param {Function} func The function to throttle. - * @param {number} wait The number of milliseconds to throttle executions to. - * @param {Object} [options] The options object. - * @param {boolean} [options.leading=true] Specify execution on the leading edge of the timeout. - * @param {boolean} [options.trailing=true] Specify execution on the trailing edge of the timeout. - * @returns {Function} Returns the new throttled function. - * @example - * - * // avoid excessively updating the position while scrolling - * var throttled = _.throttle(updatePosition, 100); - * jQuery(window).on('scroll', throttled); - * - * // execute `renewToken` when the click event is fired, but not more than once every 5 minutes - * jQuery('.interactive').on('click', _.throttle(renewToken, 300000, { - * 'trailing': false - * })); - */ - function throttle(func, wait, options) { - var leading = true, - trailing = true; - - if (!isFunction(func)) { - throw new TypeError; - } - if (options === false) { - leading = false; - } else if (isObject(options)) { - leading = 'leading' in options ? options.leading : leading; - trailing = 'trailing' in options ? options.trailing : trailing; - } - debounceOptions.leading = leading; - debounceOptions.maxWait = wait; - debounceOptions.trailing = trailing; - - return debounce(func, wait, debounceOptions); - } - - /** - * Creates a function that provides `value` to the wrapper function as its - * first argument. Additional arguments provided to the function are appended - * to those provided to the wrapper function. The wrapper is executed with - * the `this` binding of the created function. - * - * @static - * @memberOf _ - * @category Functions - * @param {*} value The value to wrap. - * @param {Function} wrapper The wrapper function. - * @returns {Function} Returns the new function. - * @example - * - * var p = _.wrap(_.escape, function(func, text) { - * return '

' + func(text) + '

'; - * }); - * - * p('Fred, Wilma, & Pebbles'); - * // => '

Fred, Wilma, & Pebbles

' - */ - function wrap(value, wrapper) { - return createWrapper(wrapper, 16, [value]); - } - - /*--------------------------------------------------------------------------*/ - - /** - * Creates a function that returns `value`. - * - * @static - * @memberOf _ - * @category Utilities - * @param {*} value The value to return from the new function. - * @returns {Function} Returns the new function. - * @example - * - * var object = { 'name': 'fred' }; - * var getter = _.constant(object); - * getter() === object; - * // => true - */ - function constant(value) { - return function() { - return value; - }; - } - - /** - * Produces a callback bound to an optional `thisArg`. If `func` is a property - * name the created callback will return the property value for a given element. - * If `func` is an object the created callback will return `true` for elements - * that contain the equivalent object properties, otherwise it will return `false`. - * - * @static - * @memberOf _ - * @category Utilities - * @param {*} [func=identity] The value to convert to a callback. - * @param {*} [thisArg] The `this` binding of the created callback. - * @param {number} [argCount] The number of arguments the callback accepts. - * @returns {Function} Returns a callback function. - * @example - * - * var characters = [ - * { 'name': 'barney', 'age': 36 }, - * { 'name': 'fred', 'age': 40 } - * ]; - * - * // wrap to create custom callback shorthands - * _.createCallback = _.wrap(_.createCallback, function(func, callback, thisArg) { - * var match = /^(.+?)__([gl]t)(.+)$/.exec(callback); - * return !match ? func(callback, thisArg) : function(object) { - * return match[2] == 'gt' ? object[match[1]] > match[3] : object[match[1]] < match[3]; - * }; - * }); - * - * _.filter(characters, 'age__gt38'); - * // => [{ 'name': 'fred', 'age': 40 }] - */ - function createCallback(func, thisArg, argCount) { - var type = typeof func; - if (func == null || type == 'function') { - return baseCreateCallback(func, thisArg, argCount); - } - // handle "_.pluck" style callback shorthands - if (type != 'object') { - return property(func); - } - var props = keys(func), - key = props[0], - a = func[key]; - - // handle "_.where" style callback shorthands - if (props.length == 1 && a === a && !isObject(a)) { - // fast path the common case of providing an object with a single - // property containing a primitive value - return function(object) { - var b = object[key]; - return a === b && (a !== 0 || (1 / a == 1 / b)); - }; - } - return function(object) { - var length = props.length, - result = false; - - while (length--) { - if (!(result = baseIsEqual(object[props[length]], func[props[length]], null, true))) { - break; - } - } - return result; - }; - } - - /** - * Converts the characters `&`, `<`, `>`, `"`, and `'` in `string` to their - * corresponding HTML entities. - * - * @static - * @memberOf _ - * @category Utilities - * @param {string} string The string to escape. - * @returns {string} Returns the escaped string. - * @example - * - * _.escape('Fred, Wilma, & Pebbles'); - * // => 'Fred, Wilma, & Pebbles' - */ - function escape(string) { - return string == null ? '' : String(string).replace(reUnescapedHtml, escapeHtmlChar); - } - - /** - * This method returns the first argument provided to it. - * - * @static - * @memberOf _ - * @category Utilities - * @param {*} value Any value. - * @returns {*} Returns `value`. - * @example - * - * var object = { 'name': 'fred' }; - * _.identity(object) === object; - * // => true - */ - function identity(value) { - return value; - } - - /** - * Adds function properties of a source object to the destination object. - * If `object` is a function methods will be added to its prototype as well. - * - * @static - * @memberOf _ - * @category Utilities - * @param {Function|Object} [object=lodash] object The destination object. - * @param {Object} source The object of functions to add. - * @param {Object} [options] The options object. - * @param {boolean} [options.chain=true] Specify whether the functions added are chainable. - * @example - * - * function capitalize(string) { - * return string.charAt(0).toUpperCase() + string.slice(1).toLowerCase(); - * } - * - * _.mixin({ 'capitalize': capitalize }); - * _.capitalize('fred'); - * // => 'Fred' - * - * _('fred').capitalize().value(); - * // => 'Fred' - * - * _.mixin({ 'capitalize': capitalize }, { 'chain': false }); - * _('fred').capitalize(); - * // => 'Fred' - */ - function mixin(object, source, options) { - var chain = true, - methodNames = source && functions(source); - - if (!source || (!options && !methodNames.length)) { - if (options == null) { - options = source; - } - ctor = lodashWrapper; - source = object; - object = lodash; - methodNames = functions(source); - } - if (options === false) { - chain = false; - } else if (isObject(options) && 'chain' in options) { - chain = options.chain; - } - var ctor = object, - isFunc = isFunction(ctor); - - forEach(methodNames, function(methodName) { - var func = object[methodName] = source[methodName]; - if (isFunc) { - ctor.prototype[methodName] = function() { - var chainAll = this.__chain__, - value = this.__wrapped__, - args = [value]; - - push.apply(args, arguments); - var result = func.apply(object, args); - if (chain || chainAll) { - if (value === result && isObject(result)) { - return this; - } - result = new ctor(result); - result.__chain__ = chainAll; - } - return result; - }; - } - }); - } - - /** - * Reverts the '_' variable to its previous value and returns a reference to - * the `lodash` function. - * - * @static - * @memberOf _ - * @category Utilities - * @returns {Function} Returns the `lodash` function. - * @example - * - * var lodash = _.noConflict(); - */ - function noConflict() { - context._ = oldDash; - return this; - } - - /** - * A no-operation function. - * - * @static - * @memberOf _ - * @category Utilities - * @example - * - * var object = { 'name': 'fred' }; - * _.noop(object) === undefined; - * // => true - */ - function noop() { - // no operation performed - } - - /** - * Gets the number of milliseconds that have elapsed since the Unix epoch - * (1 January 1970 00:00:00 UTC). - * - * @static - * @memberOf _ - * @category Utilities - * @example - * - * var stamp = _.now(); - * _.defer(function() { console.log(_.now() - stamp); }); - * // => logs the number of milliseconds it took for the deferred function to be called - */ - var now = isNative(now = Date.now) && now || function() { - return new Date().getTime(); - }; - - /** - * Converts the given value into an integer of the specified radix. - * If `radix` is `undefined` or `0` a `radix` of `10` is used unless the - * `value` is a hexadecimal, in which case a `radix` of `16` is used. - * - * Note: This method avoids differences in native ES3 and ES5 `parseInt` - * implementations. See http://es5.github.io/#E. - * - * @static - * @memberOf _ - * @category Utilities - * @param {string} value The value to parse. - * @param {number} [radix] The radix used to interpret the value to parse. - * @returns {number} Returns the new integer value. - * @example - * - * _.parseInt('08'); - * // => 8 - */ - var parseInt = nativeParseInt(whitespace + '08') == 8 ? nativeParseInt : function(value, radix) { - // Firefox < 21 and Opera < 15 follow the ES3 specified implementation of `parseInt` - return nativeParseInt(isString(value) ? value.replace(reLeadingSpacesAndZeros, '') : value, radix || 0); - }; - - /** - * Creates a "_.pluck" style function, which returns the `key` value of a - * given object. - * - * @static - * @memberOf _ - * @category Utilities - * @param {string} key The name of the property to retrieve. - * @returns {Function} Returns the new function. - * @example - * - * var characters = [ - * { 'name': 'fred', 'age': 40 }, - * { 'name': 'barney', 'age': 36 } - * ]; - * - * var getName = _.property('name'); - * - * _.map(characters, getName); - * // => ['barney', 'fred'] - * - * _.sortBy(characters, getName); - * // => [{ 'name': 'barney', 'age': 36 }, { 'name': 'fred', 'age': 40 }] - */ - function property(key) { - return function(object) { - return object[key]; - }; - } - - /** - * Produces a random number between `min` and `max` (inclusive). If only one - * argument is provided a number between `0` and the given number will be - * returned. If `floating` is truey or either `min` or `max` are floats a - * floating-point number will be returned instead of an integer. - * - * @static - * @memberOf _ - * @category Utilities - * @param {number} [min=0] The minimum possible value. - * @param {number} [max=1] The maximum possible value. - * @param {boolean} [floating=false] Specify returning a floating-point number. - * @returns {number} Returns a random number. - * @example - * - * _.random(0, 5); - * // => an integer between 0 and 5 - * - * _.random(5); - * // => also an integer between 0 and 5 - * - * _.random(5, true); - * // => a floating-point number between 0 and 5 - * - * _.random(1.2, 5.2); - * // => a floating-point number between 1.2 and 5.2 - */ - function random(min, max, floating) { - var noMin = min == null, - noMax = max == null; - - if (floating == null) { - if (typeof min == 'boolean' && noMax) { - floating = min; - min = 1; - } - else if (!noMax && typeof max == 'boolean') { - floating = max; - noMax = true; - } - } - if (noMin && noMax) { - max = 1; - } - min = +min || 0; - if (noMax) { - max = min; - min = 0; - } else { - max = +max || 0; - } - if (floating || min % 1 || max % 1) { - var rand = nativeRandom(); - return nativeMin(min + (rand * (max - min + parseFloat('1e-' + ((rand +'').length - 1)))), max); - } - return baseRandom(min, max); - } - - /** - * Resolves the value of property `key` on `object`. If `key` is a function - * it will be invoked with the `this` binding of `object` and its result returned, - * else the property value is returned. If `object` is falsey then `undefined` - * is returned. - * - * @static - * @memberOf _ - * @category Utilities - * @param {Object} object The object to inspect. - * @param {string} key The name of the property to resolve. - * @returns {*} Returns the resolved value. - * @example - * - * var object = { - * 'cheese': 'crumpets', - * 'stuff': function() { - * return 'nonsense'; - * } - * }; - * - * _.result(object, 'cheese'); - * // => 'crumpets' - * - * _.result(object, 'stuff'); - * // => 'nonsense' - */ - function result(object, key) { - if (object) { - var value = object[key]; - return isFunction(value) ? object[key]() : value; - } - } - - /** - * A micro-templating method that handles arbitrary delimiters, preserves - * whitespace, and correctly escapes quotes within interpolated code. - * - * Note: In the development build, `_.template` utilizes sourceURLs for easier - * debugging. See http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl - * - * For more information on precompiling templates see: - * http://lodash.com/custom-builds - * - * For more information on Chrome extension sandboxes see: - * http://developer.chrome.com/stable/extensions/sandboxingEval.html - * - * @static - * @memberOf _ - * @category Utilities - * @param {string} text The template text. - * @param {Object} data The data object used to populate the text. - * @param {Object} [options] The options object. - * @param {RegExp} [options.escape] The "escape" delimiter. - * @param {RegExp} [options.evaluate] The "evaluate" delimiter. - * @param {Object} [options.imports] An object to import into the template as local variables. - * @param {RegExp} [options.interpolate] The "interpolate" delimiter. - * @param {string} [sourceURL] The sourceURL of the template's compiled source. - * @param {string} [variable] The data object variable name. - * @returns {Function|string} Returns a compiled function when no `data` object - * is given, else it returns the interpolated text. - * @example - * - * // using the "interpolate" delimiter to create a compiled template - * var compiled = _.template('hello <%= name %>'); - * compiled({ 'name': 'fred' }); - * // => 'hello fred' - * - * // using the "escape" delimiter to escape HTML in data property values - * _.template('<%- value %>', { 'value': '