(function(f){if(typeof exports==="object"&&typeof module!=="undefined"){module.exports=f()}else if(typeof define==="function"&&define.amd){define([],f)}else{var g;if(typeof window!=="undefined"){g=window}else if(typeof global!=="undefined"){g=global}else if(typeof self!=="undefined"){g=self}else{g=this}g.blockstack = f()}})(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o 0 && arguments[0] !== undefined ? arguments[0] : (0, _index.makeAuthRequest)(); var blockstackIDHost = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : _authConstants.DEFAULT_BLOCKSTACK_HOST; var protocolURI = _utils.BLOCKSTACK_HANDLER + ':' + authRequest; var httpsURI = blockstackIDHost + '?authRequest=' + authRequest; // If they're on a mobile OS, always redirect them to HTTPS site if (/Android|webOS|iPhone|iPad|iPod|Opera Mini/i.test(navigator.userAgent)) { _logger.Logger.info('detected mobile OS, sending to https'); window.location = httpsURI; return; } function successCallback() { _logger.Logger.info('protocol handler detected'); // protocolCheck should open the link for us } function failCallback() { _logger.Logger.warn('protocol handler not detected'); window.location = httpsURI; } function unsupportedBrowserCallback() { // Safari is unsupported by protocolCheck _logger.Logger.warn('can not detect custom protocols on this browser'); window.location = protocolURI; } (0, _customProtocolDetectionBlockstack2.default)(protocolURI, failCallback, successCallback, unsupportedBrowserCallback); } /** * Generates an authentication request and redirects the user to the Blockstack * browser to approve the sign in request. * * Please note that this requires that the web browser properly handles the * `blockstack:` URL protocol handler. * * Most applications should use this * method for sign in unless they require more fine grained control over how the * authentication request is generated. If your app falls into this category, * use `makeAuthRequest` and `redirectToSignInWithAuthRequest` to build your own sign in process. * * @param {String} [redirectURI=`${window.location.origin}/`] * The location to which the identity provider will redirect the user after * the user approves sign in. * @param {String} [manifestURI=`${window.location.origin}/manifest.json`] * Location of the manifest file. * @param {Array} [scopes=DEFAULT_SCOPE] Defaults to requesting write access to * this app's data store. * An array of strings indicating which permissions this app is requesting. * @return {void} */ function redirectToSignIn() { var redirectURI = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : window.location.origin + '/'; var manifestURI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location.origin + '/manifest.json'; var scopes = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : _authConstants.DEFAULT_SCOPE; var authRequest = (0, _index.makeAuthRequest)(generateAndStoreTransitKey(), redirectURI, manifestURI, scopes); redirectToSignInWithAuthRequest(authRequest); } /** * Retrieve the authentication token from the URL query * @return {String} the authentication token if it exists otherwise `null` */ function getAuthResponseToken() { var queryDict = _queryString2.default.parse(location.search); return queryDict.authResponse ? queryDict.authResponse : ''; } /** * Check if there is a authentication request that hasn't been handled. * @return {Boolean} `true` if there is a pending sign in, otherwise `false` */ function isSignInPending() { return !!getAuthResponseToken(); } /** * Try to process any pending sign in request by returning a `Promise` that resolves * to the user data object if the sign in succeeds. * * @param {String} nameLookupURL - the endpoint against which to verify public * keys match claimed username * @param {String} authResponseToken - the signed authentication response token * @param {String} transitKey - the transit private key that corresponds to the transit public key * that was provided in the authentication request * @return {Promise} that resolves to the user data object if successful and rejects * if handling the sign in request fails or there was no pending sign in request. */ function handlePendingSignIn() { var nameLookupURL = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var authResponseToken = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : getAuthResponseToken(); var transitKey = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : getTransitKey(); if (!nameLookupURL) { var tokenPayload = (0, _jsontokens.decodeToken)(authResponseToken).payload; if ((0, _utils.isLaterVersion)(tokenPayload.version, '1.3.0') && tokenPayload.blockstackAPIUrl !== null && tokenPayload.blockstackAPIUrl !== undefined) { // override globally _logger.Logger.info('Overriding ' + _config.config.network.blockstackAPIUrl + ' ' + ('with ' + tokenPayload.blockstackAPIUrl)); _config.config.network.blockstackAPIUrl = tokenPayload.blockstackAPIUrl; nameLookupURL = tokenPayload.blockstackAPIUrl + '/v1/names'; } nameLookupURL = _config.config.network.blockstackAPIUrl + '/v1/names/'; } return (0, _index.verifyAuthResponse)(authResponseToken, nameLookupURL).then(function (isValid) { if (!isValid) { throw new _errors.LoginFailedError('Invalid authentication response.'); } var tokenPayload = (0, _jsontokens.decodeToken)(authResponseToken).payload; // TODO: real version handling var appPrivateKey = tokenPayload.private_key; var coreSessionToken = tokenPayload.core_token; if ((0, _utils.isLaterVersion)(tokenPayload.version, '1.1.0')) { if (transitKey !== undefined && transitKey != null) { if (tokenPayload.private_key !== undefined && tokenPayload.private_key !== null) { try { appPrivateKey = (0, _authMessages.decryptPrivateKey)(transitKey, tokenPayload.private_key); } catch (e) { _logger.Logger.warn('Failed decryption of appPrivateKey, will try to use as given'); try { (0, _utils.hexStringToECPair)(tokenPayload.private_key); } catch (ecPairError) { throw new _errors.LoginFailedError('Failed decrypting appPrivateKey. Usually means' + ' that the transit key has changed during login.'); } } } if (coreSessionToken !== undefined && coreSessionToken !== null) { try { coreSessionToken = (0, _authMessages.decryptPrivateKey)(transitKey, coreSessionToken); } catch (e) { _logger.Logger.info('Failed decryption of coreSessionToken, will try to use as given'); } } } else { throw new _errors.LoginFailedError('Authenticating with protocol > 1.1.0 requires transit' + ' key, and none found.'); } } var hubUrl = _authConstants.BLOCKSTACK_DEFAULT_GAIA_HUB_URL; var gaiaAssociationToken = void 0; if ((0, _utils.isLaterVersion)(tokenPayload.version, '1.2.0') && tokenPayload.hubUrl !== null && tokenPayload.hubUrl !== undefined) { hubUrl = tokenPayload.hubUrl; } if ((0, _utils.isLaterVersion)(tokenPayload.version, '1.3.0') && tokenPayload.associationToken !== null && tokenPayload.associationToken !== undefined) { gaiaAssociationToken = tokenPayload.associationToken; } var userData = { username: tokenPayload.username, profile: tokenPayload.profile, decentralizedID: tokenPayload.iss, identityAddress: (0, _index2.getAddressFromDID)(tokenPayload.iss), appPrivateKey: appPrivateKey, coreSessionToken: coreSessionToken, authResponseToken: authResponseToken, hubUrl: hubUrl, gaiaAssociationToken: gaiaAssociationToken }; var profileURL = tokenPayload.profile_url; if ((userData.profile === null || userData.profile === undefined) && profileURL !== undefined && profileURL !== null) { return fetch(profileURL).then(function (response) { if (!response.ok) { // return blank profile if we fail to fetch userData.profile = Object.assign({}, DEFAULT_PROFILE); window.localStorage.setItem(_authConstants.BLOCKSTACK_STORAGE_LABEL, JSON.stringify(userData)); return userData; } else { return response.text().then(function (responseText) { return JSON.parse(responseText); }).then(function (wrappedProfile) { return (0, _profiles.extractProfile)(wrappedProfile[0].token); }).then(function (profile) { userData.profile = profile; window.localStorage.setItem(_authConstants.BLOCKSTACK_STORAGE_LABEL, JSON.stringify(userData)); return userData; }); } }); } else { userData.profile = tokenPayload.profile; window.localStorage.setItem(_authConstants.BLOCKSTACK_STORAGE_LABEL, JSON.stringify(userData)); return userData; } }); } /** * Retrieves the user data object. The user's profile is stored in the key `profile`. * @return {Object} User data object. */ function loadUserData() { return JSON.parse(window.localStorage.getItem(_authConstants.BLOCKSTACK_STORAGE_LABEL)); } /** * Sign the user out and optionally redirect to given location. * @param {String} [redirectURL=null] Location to redirect user to after sign out. * @return {void} */ function signUserOut() { var redirectURL = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : null; window.localStorage.removeItem(_authConstants.BLOCKSTACK_STORAGE_LABEL); window.localStorage.removeItem(_storage.BLOCKSTACK_GAIA_HUB_LABEL); if (redirectURL !== null) { window.location = redirectURL; } } },{"../config":8,"../errors":11,"../index":12,"../logger":14,"../profiles":22,"../storage":45,"../utils":46,"./authConstants":2,"./authMessages":3,"./index":7,"custom-protocol-detection-blockstack":292,"jsontokens":384,"query-string":450}],2:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var BLOCKSTACK_HANDLER = exports.BLOCKSTACK_HANDLER = 'blockstack'; var BLOCKSTACK_STORAGE_LABEL = exports.BLOCKSTACK_STORAGE_LABEL = 'blockstack'; var DEFAULT_BLOCKSTACK_HOST = exports.DEFAULT_BLOCKSTACK_HOST = 'https://browser.blockstack.org/auth'; var DEFAULT_SCOPE = exports.DEFAULT_SCOPE = ['store_write']; var BLOCKSTACK_APP_PRIVATE_KEY_LABEL = exports.BLOCKSTACK_APP_PRIVATE_KEY_LABEL = 'blockstack-transit-private-key'; var BLOCKSTACK_DEFAULT_GAIA_HUB_URL = exports.BLOCKSTACK_DEFAULT_GAIA_HUB_URL = 'https://hub.blockstack.org'; },{}],3:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeAuthRequest = makeAuthRequest; exports.encryptPrivateKey = encryptPrivateKey; exports.decryptPrivateKey = decryptPrivateKey; exports.makeAuthResponse = makeAuthResponse; require('cross-fetch/polyfill'); var _jsontokens = require('jsontokens'); var _index = require('../index'); var _authConstants = require('./authConstants'); var _encryption = require('../encryption'); var _logger = require('../logger'); var VERSION = '1.3.1'; /** * Generates an authentication request that can be sent to the Blockstack * browser for the user to approve sign in. This authentication request can * then be used for sign in by passing it to the `redirectToSignInWithAuthRequest` * method. * * *Note: This method should only be used if you want to roll your own authentication * flow. Typically you'd use `redirectToSignIn` which takes care of this * under the hood.* * * @param {String} [transitPrivateKey=generateAndStoreTransitKey()] - hex encoded transit * private key * @param {String} redirectURI - location to redirect user to after sign in approval * @param {String} manifestURI - location of this app's manifest file * @param {Array} scopes - the permissions this app is requesting * @param {String} appDomain - the origin of this app * @param {Number} expiresAt - the time at which this request is no longer valid * @param {Object} extraParams - Any extra parameters you'd like to pass to the authenticator. * Use this to pass options that aren't part of the Blockstack auth spec, but might be supported * by special authenticators. * @return {String} the authentication request */ function makeAuthRequest() { var transitPrivateKey = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : (0, _index.generateAndStoreTransitKey)(); var redirectURI = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : window.location.origin + '/'; var manifestURI = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : window.location.origin + '/manifest.json'; var scopes = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _authConstants.DEFAULT_SCOPE; var appDomain = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : window.location.origin; var expiresAt = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : (0, _index.nextHour)().getTime(); var extraParams = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : {}; /* Create the payload */ var payload = Object.assign({}, extraParams, { jti: (0, _index.makeUUID4)(), iat: Math.floor(new Date().getTime() / 1000), // JWT times are in seconds exp: Math.floor(expiresAt / 1000), // JWT times are in seconds iss: null, public_keys: [], domain_name: appDomain, manifest_uri: manifestURI, redirect_uri: redirectURI, version: VERSION, do_not_include_profile: true, supports_hub_url: true, scopes: scopes }); _logger.Logger.info('blockstack.js: generating v' + VERSION + ' auth request'); /* Convert the private key to a public key to an issuer */ var publicKey = _jsontokens.SECP256K1Client.derivePublicKey(transitPrivateKey); payload.public_keys = [publicKey]; var address = (0, _index.publicKeyToAddress)(publicKey); payload.iss = (0, _index.makeDIDFromAddress)(address); /* Sign and return the token */ var tokenSigner = new _jsontokens.TokenSigner('ES256k', transitPrivateKey); var token = tokenSigner.sign(payload); return token; } /** * Encrypts the private key for decryption by the given * public key. * @param {String} publicKey [description] * @param {String} privateKey [description] * @return {String} hex encoded ciphertext * @private */ function encryptPrivateKey(publicKey, privateKey) { var encryptedObj = (0, _encryption.encryptECIES)(publicKey, privateKey); var encryptedJSON = JSON.stringify(encryptedObj); return new Buffer(encryptedJSON).toString('hex'); } /** * Decrypts the hex encrypted private key * @param {String} privateKey the private key corresponding to the public * key for which the ciphertext was encrypted * @param {String} hexedEncrypted the ciphertext * @return {String} the decrypted private key * @throws {Error} if unable to decrypt * * @private */ function decryptPrivateKey(privateKey, hexedEncrypted) { var unhexedString = new Buffer(hexedEncrypted, 'hex').toString(); var encryptedObj = JSON.parse(unhexedString); var decrypted = (0, _encryption.decryptECIES)(privateKey, encryptedObj); if (typeof decrypted !== 'string') { throw new Error('Unable to correctly decrypt private key'); } else { return decrypted; } } /** * Generates a signed authentication response token for an app. This * token is sent back to apps which use contents to access the * resources and data requested by the app. * * @param {String} privateKey the identity key of the Blockstack ID generating * the authentication response * @param {Object} profile the profile object for the Blockstack ID * @param {String} username the username of the Blockstack ID if any, otherwise `null` * @param {AuthMetadata} metadata an object containing metadata sent as part of the authentication * response including `email` if requested and available and a URL to the profile * @param {String} coreToken core session token when responding to a legacy auth request * or `null` for current direct to gaia authentication requests * @param {String} appPrivateKey the application private key. This private key is * unique and specific for every Blockstack ID and application combination. * @param {Number} expiresAt an integer in the same format as * `new Date().getTime()`, milliseconds since the Unix epoch * @param {String} transitPublicKey the public key provide by the app * in its authentication request with which secrets will be encrypted * @param {String} hubUrl URL to the write path of the user's Gaia hub * @param {String} blockstackAPIUrl URL to the API endpoint to use * @param {String} associationToken JWT that binds the app key to the identity key * @return {String} signed and encoded authentication response token * @private */ function makeAuthResponse(privateKey) { var profile = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {}; var username = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var metadata = arguments[3]; var coreToken = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; var appPrivateKey = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; var expiresAt = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : (0, _index.nextMonth)().getTime(); var transitPublicKey = arguments.length > 7 && arguments[7] !== undefined ? arguments[7] : null; var hubUrl = arguments.length > 8 && arguments[8] !== undefined ? arguments[8] : null; var blockstackAPIUrl = arguments.length > 9 && arguments[9] !== undefined ? arguments[9] : null; var associationToken = arguments.length > 10 && arguments[10] !== undefined ? arguments[10] : null; /* Convert the private key to a public key to an issuer */ var publicKey = _jsontokens.SECP256K1Client.derivePublicKey(privateKey); var address = (0, _index.publicKeyToAddress)(publicKey); /* See if we should encrypt with the transit key */ var privateKeyPayload = appPrivateKey; var coreTokenPayload = coreToken; var additionalProperties = {}; if (appPrivateKey !== undefined && appPrivateKey !== null) { _logger.Logger.info('blockstack.js: generating v' + VERSION + ' auth response'); if (transitPublicKey !== undefined && transitPublicKey !== null) { privateKeyPayload = encryptPrivateKey(transitPublicKey, appPrivateKey); if (coreToken !== undefined && coreToken !== null) { coreTokenPayload = encryptPrivateKey(transitPublicKey, coreToken); } } additionalProperties = { email: metadata.email ? metadata.email : null, profile_url: metadata.profileUrl ? metadata.profileUrl : null, hubUrl: hubUrl, blockstackAPIUrl: blockstackAPIUrl, associationToken: associationToken, version: VERSION }; } else { _logger.Logger.info('blockstack.js: generating legacy auth response'); } /* Create the payload */ var payload = Object.assign({}, { jti: (0, _index.makeUUID4)(), iat: Math.floor(new Date().getTime() / 1000), // JWT times are in seconds exp: Math.floor(expiresAt / 1000), // JWT times are in seconds iss: (0, _index.makeDIDFromAddress)(address), private_key: privateKeyPayload, public_keys: [publicKey], profile: profile, username: username, core_token: coreTokenPayload }, additionalProperties); /* Sign and return the token */ var tokenSigner = new _jsontokens.TokenSigner('ES256k', privateKey); return tokenSigner.sign(payload); } }).call(this,require("buffer").Buffer) },{"../encryption":10,"../index":12,"../logger":14,"./authConstants":2,"buffer":179,"cross-fetch/polyfill":283,"jsontokens":384}],4:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getAuthRequestFromURL = getAuthRequestFromURL; exports.fetchAppManifest = fetchAppManifest; exports.redirectUserToApp = redirectUserToApp; var _queryString = require('query-string'); var _queryString2 = _interopRequireDefault(_queryString); var _jsontokens = require('jsontokens'); var _index = require('../index'); var _utils = require('../utils'); var _logger = require('../logger'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * Retrieves the authentication request from the query string * @return {String|null} the authentication request or `null` if * the query string parameter `authRequest` is not found * @private */ function getAuthRequestFromURL() { var queryDict = _queryString2.default.parse(location.search); if (queryDict.authRequest !== null && queryDict.authRequest !== undefined) { return queryDict.authRequest.split(_utils.BLOCKSTACK_HANDLER + ':').join(''); } else { return null; } } /** * Fetches the contents of the manifest file specified in the authentication request * * @param {String} authRequest encoded and signed authentication request * @return {Promise} Returns a `Promise` that resolves to the JSON * object manifest file unless there's an error in which case rejects with an error * message. * @private */ function fetchAppManifest(authRequest) { return new Promise(function (resolve, reject) { if (!authRequest) { reject('Invalid auth request'); } else { var payload = (0, _jsontokens.decodeToken)(authRequest).payload; var manifestURI = payload.manifest_uri; try { _logger.Logger.debug('Fetching manifest from ' + manifestURI); fetch(manifestURI).then(function (response) { return response.text(); }).then(function (responseText) { return JSON.parse(responseText); }).then(function (responseJSON) { resolve(responseJSON); }).catch(function (e) { _logger.Logger.debug(e.stack); reject('Could not fetch manifest.json'); }); } catch (e) { _logger.Logger.debug(e.stack); reject('Could not fetch manifest.json'); } } }); } /** * Redirect the user's browser to the app using the `redirect_uri` * specified in the authentication request, passing the authentication * response token as a query parameter. * * @param {String} authRequest encoded and signed authentication request token * @param {String} authResponse encoded and signed authentication response token * @return {void} * @throws {Error} if there is no redirect uri * @private */ function redirectUserToApp(authRequest, authResponse) { var payload = (0, _jsontokens.decodeToken)(authRequest).payload; var redirectURI = payload.redirect_uri; _logger.Logger.debug(redirectURI); if (redirectURI) { redirectURI = (0, _index.updateQueryStringParameter)(redirectURI, 'authResponse', authResponse); } else { throw new Error('Invalid redirect URI'); } window.location = redirectURI; } },{"../index":12,"../logger":14,"../utils":46,"jsontokens":384,"query-string":450}],5:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeCoreSessionRequest = makeCoreSessionRequest; exports.sendCoreSessionRequest = sendCoreSessionRequest; exports.getCoreSession = getCoreSession; var _jsontokens = require('jsontokens'); require('cross-fetch/polyfill'); /** * Create an authentication token to be sent to the Core API server * in order to generate a Core session JWT. * * @param {String} appDomain The unique application identifier (e.g. foo.app, www.foo.com, etc). * @param {Array} appMethods The list of API methods this application will need. * @param {String} appPrivateKey The application-specific private key * @param {String|null} blockchainID This is the blockchain ID of the requester * @param {String} thisDevice Identifier of the current device * * @return {String} a JWT signed by the app's private key * @deprecated * @private */ function makeCoreSessionRequest(appDomain, appMethods, appPrivateKey) { var blockchainID = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var thisDevice = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; if (thisDevice === null) { thisDevice = '.default'; } var appPublicKey = _jsontokens.SECP256K1Client.derivePublicKey(appPrivateKey); var appPublicKeys = [{ public_key: appPublicKey, device_id: thisDevice }]; var authBody = { version: 1, blockchain_id: blockchainID, app_private_key: appPrivateKey, app_domain: appDomain, methods: appMethods, app_public_keys: appPublicKeys, device_id: thisDevice // make token };var tokenSigner = new _jsontokens.TokenSigner('ES256k', appPrivateKey); var token = tokenSigner.sign(authBody); return token; } /** * Send Core a request for a session token. * * @param {String} coreHost host name of the core node * @param {Number} corePort port number of the core node * @param {String} coreAuthRequest a signed JWT encoding the authentication request * @param {String} apiPassword the API password for Core * * @return {Promise} the resolves to a JWT signed with the Core API server's private key * that authorizes the bearer to carry out the requested operations and rejects * with an error message otherwise * @deprecated * @private */ function sendCoreSessionRequest(coreHost, corePort, coreAuthRequest, apiPassword) { return new Promise(function (resolve, reject) { if (!apiPassword) { reject('Missing API password'); return null; } var options = { headers: { Authorization: 'bearer ' + apiPassword } }; var url = 'http://' + coreHost + ':' + corePort + '/v1/auth?authRequest=' + coreAuthRequest; return fetch(url, options).then(function (response) { if (!response.ok) { reject('HTTP status not OK'); throw new Error('HTTP status not OK'); } return response.text(); }).then(function (responseText) { return JSON.parse(responseText); }).then(function (responseJson) { var token = responseJson.token; if (!token) { reject('Failed to get Core session token'); return null; } resolve(token); return token; }).catch(function (error) { console.error(error); reject('Invalid Core response: not JSON'); }); }); } /** * Get a core session token. Generate an auth request, sign it, send it to Core, * and get back a session token. * * @param {String} coreHost Core API server's hostname * @param {Number} corePort Core API server's port number * @param {String} apiPassword core api password * @param {String} appPrivateKey Application's private key * @param {String} blockchainId blockchain ID of the user signing in. * `null` if user has no blockchain ID * @param {String} authRequest authentication request token * @param {String} deviceId identifier for the current device * * @return {Promise} a Promise that resolves to a Core session token or rejects * with an error message. * @deprecated * @private */ function getCoreSession(coreHost, corePort, apiPassword, appPrivateKey) { var blockchainId = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; var authRequest = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; var deviceId = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : '0'; if (!authRequest) { return Promise.reject('No authRequest provided'); } var payload = null; var authRequestObject = null; try { authRequestObject = (0, _jsontokens.decodeToken)(authRequest); if (!authRequestObject) { return Promise.reject('Invalid authRequest in URL query string'); } if (!authRequestObject.payload) { return Promise.reject('Invalid authRequest in URL query string'); } payload = authRequestObject.payload; } catch (e) { console.error(e.stack); return Promise.reject('Failed to parse authRequest in URL'); } var appDomain = payload.domain_name; if (!appDomain) { return Promise.reject('No domain_name in authRequest'); } var appMethods = payload.scopes; var coreAuthRequest = makeCoreSessionRequest(appDomain, appMethods, appPrivateKey, blockchainId, deviceId); return sendCoreSessionRequest(coreHost, corePort, coreAuthRequest, apiPassword); } },{"cross-fetch/polyfill":283,"jsontokens":384}],6:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.doSignaturesMatchPublicKeys = doSignaturesMatchPublicKeys; exports.doPublicKeysMatchIssuer = doPublicKeysMatchIssuer; exports.doPublicKeysMatchUsername = doPublicKeysMatchUsername; exports.isIssuanceDateValid = isIssuanceDateValid; exports.isExpirationDateValid = isExpirationDateValid; exports.isManifestUriValid = isManifestUriValid; exports.isRedirectUriValid = isRedirectUriValid; exports.verifyAuthRequest = verifyAuthRequest; exports.verifyAuthRequestAndLoadManifest = verifyAuthRequestAndLoadManifest; exports.verifyAuthResponse = verifyAuthResponse; var _jsontokens = require('jsontokens'); var _index = require('../index'); /** * Checks if the ES256k signature on passed `token` match the claimed public key * in the payload key `public_keys`. * * @param {String} token encoded and signed authentication token * @return {Boolean} Returns `true` if the signature matches the claimed public key * @throws {Error} if `token` contains multiple public keys * @private */ function doSignaturesMatchPublicKeys(token) { var payload = (0, _jsontokens.decodeToken)(token).payload; var publicKeys = payload.public_keys; if (publicKeys.length === 1) { var publicKey = publicKeys[0]; try { var tokenVerifier = new _jsontokens.TokenVerifier('ES256k', publicKey); var signatureVerified = tokenVerifier.verify(token); if (signatureVerified) { return true; } else { return false; } } catch (e) { return false; } } else { throw new Error('Multiple public keys are not supported'); } } /** * Makes sure that the identity address portion of * the decentralized identifier passed in the issuer `iss` * key of the token matches the public key * * @param {String} token encoded and signed authentication token * @return {Boolean} if the identity address and public keys match * @throws {Error} if ` token` has multiple public keys * @private */ function doPublicKeysMatchIssuer(token) { var payload = (0, _jsontokens.decodeToken)(token).payload; var publicKeys = payload.public_keys; var addressFromIssuer = (0, _index.getAddressFromDID)(payload.iss); if (publicKeys.length === 1) { var addressFromPublicKeys = (0, _index.publicKeyToAddress)(publicKeys[0]); if (addressFromPublicKeys === addressFromIssuer) { return true; } } else { throw new Error('Multiple public keys are not supported'); } return false; } /** * Looks up the identity address that owns the claimed username * in `token` using the lookup endpoint provided in `nameLookupURL` * to determine if the username is owned by the identity address * that matches the claimed public key * * @param {String} token encoded and signed authentication token * @param {String} nameLookupURL a URL to the name lookup endpoint of the Blockstack Core API * @return {Promise} returns a `Promise` that resolves to * `true` if the username is owned by the public key, otherwise the * `Promise` resolves to `false` * @private */ function doPublicKeysMatchUsername(token, nameLookupURL) { return new Promise(function (resolve) { var payload = (0, _jsontokens.decodeToken)(token).payload; if (!payload.username) { resolve(true); return; } if (payload.username === null) { resolve(true); return; } if (nameLookupURL === null) { resolve(false); return; } var username = payload.username; var url = nameLookupURL.replace(/\/$/, '') + '/' + username; try { fetch(url).then(function (response) { return response.text(); }).then(function (responseText) { return JSON.parse(responseText); }).then(function (responseJSON) { if (responseJSON.hasOwnProperty('address')) { var nameOwningAddress = responseJSON.address; var addressFromIssuer = (0, _index.getAddressFromDID)(payload.iss); if (nameOwningAddress === addressFromIssuer) { resolve(true); } else { resolve(false); } } else { resolve(false); } }).catch(function () { resolve(false); }); } catch (e) { resolve(false); } }); } /** * Checks if the if the token issuance time and date is after the * current time and date. * * @param {String} token encoded and signed authentication token * @return {Boolean} `true` if the token was issued after the current time, * otherwise returns `false` * @private */ function isIssuanceDateValid(token) { var payload = (0, _jsontokens.decodeToken)(token).payload; if (payload.iat) { if (typeof payload.iat !== 'number') { return false; } var issuedAt = new Date(payload.iat * 1000); // JWT times are in seconds if (new Date().getTime() < issuedAt.getTime()) { return false; } else { return true; } } else { return true; } } /** * Checks if the expiration date of the `token` is before the current time * @param {String} token encoded and signed authentication token * @return {Boolean} `true` if the `token` has not yet expired, `false` * if the `token` has expired * * @private */ function isExpirationDateValid(token) { var payload = (0, _jsontokens.decodeToken)(token).payload; if (payload.exp) { if (typeof payload.exp !== 'number') { return false; } var expiresAt = new Date(payload.exp * 1000); // JWT times are in seconds if (new Date().getTime() > expiresAt.getTime()) { return false; } else { return true; } } else { return true; } } /** * Makes sure the `manifest_uri` is a same origin absolute URL. * @param {String} token encoded and signed authentication token * @return {Boolean} `true` if valid, otherwise `false` * @private */ function isManifestUriValid(token) { var payload = (0, _jsontokens.decodeToken)(token).payload; return (0, _index.isSameOriginAbsoluteUrl)(payload.domain_name, payload.manifest_uri); } /** * Makes sure the `redirect_uri` is a same origin absolute URL. * @param {String} token encoded and signed authentication token * @return {Boolean} `true` if valid, otherwise `false` * @private */ function isRedirectUriValid(token) { var payload = (0, _jsontokens.decodeToken)(token).payload; return (0, _index.isSameOriginAbsoluteUrl)(payload.domain_name, payload.redirect_uri); } /** * Verify authentication request is valid. This function performs a number * of checks on the authentication request token: * * Checks that `token` has a valid issuance date & is not expired * * Checks that `token` has a valid signature that matches the public key it claims * * Checks that both the manifest and redirect URLs are absolute and conform to * the same origin policy * * @param {String} token encoded and signed authentication request token * @return {Promise} that resolves to true if the auth request * is valid and false if it does not. It rejects with a String if the * token is not signed * @private */ function verifyAuthRequest(token) { return new Promise(function (resolve, reject) { if ((0, _jsontokens.decodeToken)(token).header.alg === 'none') { reject('Token must be signed in order to be verified'); } Promise.all([isExpirationDateValid(token), isIssuanceDateValid(token), doSignaturesMatchPublicKeys(token), doPublicKeysMatchIssuer(token), isManifestUriValid(token), isRedirectUriValid(token)]).then(function (values) { if (values.every(Boolean)) { resolve(true); } else { resolve(false); } }); }); } /** * Verify the authentication request is valid and * fetch the app manifest file if valid. Otherwise, reject the promise. * @param {String} token encoded and signed authentication request token * @return {Promise} that resolves to the app manifest file in JSON format * or rejects if the auth request or app manifest file is invalid * @private */ function verifyAuthRequestAndLoadManifest(token) { return new Promise(function (resolve, reject) { return verifyAuthRequest(token).then(function (valid) { if (valid) { return (0, _index.fetchAppManifest)(token).then(function (appManifest) { resolve(appManifest); }).catch(function (err) { reject(err); }); } else { reject(); return Promise.reject(); } }); }); } /** * Verify the authentication response is valid * @param {String} token the authentication response token * @param {String} nameLookupURL the url use to verify owner of a username * @return {Promise} that resolves to true if auth response * is valid and false if it does not * @private */ function verifyAuthResponse(token, nameLookupURL) { return new Promise(function (resolve) { Promise.all([isExpirationDateValid(token), isIssuanceDateValid(token), doSignaturesMatchPublicKeys(token), doPublicKeysMatchIssuer(token), doPublicKeysMatchUsername(token, nameLookupURL)]).then(function (values) { if (values.every(Boolean)) { resolve(true); } else { resolve(false); } }); }); } },{"../index":12,"jsontokens":384}],7:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _authApp = require('./authApp'); Object.defineProperty(exports, 'isUserSignedIn', { enumerable: true, get: function get() { return _authApp.isUserSignedIn; } }); Object.defineProperty(exports, 'redirectToSignIn', { enumerable: true, get: function get() { return _authApp.redirectToSignIn; } }); Object.defineProperty(exports, 'redirectToSignInWithAuthRequest', { enumerable: true, get: function get() { return _authApp.redirectToSignInWithAuthRequest; } }); Object.defineProperty(exports, 'getAuthResponseToken', { enumerable: true, get: function get() { return _authApp.getAuthResponseToken; } }); Object.defineProperty(exports, 'isSignInPending', { enumerable: true, get: function get() { return _authApp.isSignInPending; } }); Object.defineProperty(exports, 'handlePendingSignIn', { enumerable: true, get: function get() { return _authApp.handlePendingSignIn; } }); Object.defineProperty(exports, 'loadUserData', { enumerable: true, get: function get() { return _authApp.loadUserData; } }); Object.defineProperty(exports, 'signUserOut', { enumerable: true, get: function get() { return _authApp.signUserOut; } }); Object.defineProperty(exports, 'generateAndStoreTransitKey', { enumerable: true, get: function get() { return _authApp.generateAndStoreTransitKey; } }); Object.defineProperty(exports, 'getTransitKey', { enumerable: true, get: function get() { return _authApp.getTransitKey; } }); var _authMessages = require('./authMessages'); Object.defineProperty(exports, 'makeAuthRequest', { enumerable: true, get: function get() { return _authMessages.makeAuthRequest; } }); Object.defineProperty(exports, 'makeAuthResponse', { enumerable: true, get: function get() { return _authMessages.makeAuthResponse; } }); var _authProvider = require('./authProvider'); Object.defineProperty(exports, 'getAuthRequestFromURL', { enumerable: true, get: function get() { return _authProvider.getAuthRequestFromURL; } }); Object.defineProperty(exports, 'fetchAppManifest', { enumerable: true, get: function get() { return _authProvider.fetchAppManifest; } }); Object.defineProperty(exports, 'redirectUserToApp', { enumerable: true, get: function get() { return _authProvider.redirectUserToApp; } }); var _authSession = require('./authSession'); Object.defineProperty(exports, 'makeCoreSessionRequest', { enumerable: true, get: function get() { return _authSession.makeCoreSessionRequest; } }); Object.defineProperty(exports, 'sendCoreSessionRequest', { enumerable: true, get: function get() { return _authSession.sendCoreSessionRequest; } }); Object.defineProperty(exports, 'getCoreSession', { enumerable: true, get: function get() { return _authSession.getCoreSession; } }); var _authVerification = require('./authVerification'); Object.defineProperty(exports, 'verifyAuthRequest', { enumerable: true, get: function get() { return _authVerification.verifyAuthRequest; } }); Object.defineProperty(exports, 'verifyAuthResponse', { enumerable: true, get: function get() { return _authVerification.verifyAuthResponse; } }); Object.defineProperty(exports, 'isExpirationDateValid', { enumerable: true, get: function get() { return _authVerification.isExpirationDateValid; } }); Object.defineProperty(exports, 'isIssuanceDateValid', { enumerable: true, get: function get() { return _authVerification.isIssuanceDateValid; } }); Object.defineProperty(exports, 'doPublicKeysMatchUsername', { enumerable: true, get: function get() { return _authVerification.doPublicKeysMatchUsername; } }); Object.defineProperty(exports, 'doPublicKeysMatchIssuer', { enumerable: true, get: function get() { return _authVerification.doPublicKeysMatchIssuer; } }); Object.defineProperty(exports, 'doSignaturesMatchPublicKeys', { enumerable: true, get: function get() { return _authVerification.doSignaturesMatchPublicKeys; } }); Object.defineProperty(exports, 'isManifestUriValid', { enumerable: true, get: function get() { return _authVerification.isManifestUriValid; } }); Object.defineProperty(exports, 'isRedirectUriValid', { enumerable: true, get: function get() { return _authVerification.isRedirectUriValid; } }); Object.defineProperty(exports, 'verifyAuthRequestAndLoadManifest', { enumerable: true, get: function get() { return _authVerification.verifyAuthRequestAndLoadManifest; } }); },{"./authApp":1,"./authMessages":3,"./authProvider":4,"./authSession":5,"./authVerification":6}],8:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.config = undefined; var _network = require('./network'); var _logger = require('./logger'); var config = { network: _network.network.defaults.MAINNET_DEFAULT, logLevel: _logger.levels[0] }; exports.config = config; },{"./logger":14,"./network":15}],9:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeDIDFromAddress = makeDIDFromAddress; exports.makeDIDFromPublicKey = makeDIDFromPublicKey; exports.getDIDType = getDIDType; exports.getAddressFromDID = getAddressFromDID; var _errors = require('./errors'); function makeDIDFromAddress(address) { return 'did:btc-addr:' + address; } function makeDIDFromPublicKey(publicKey) { return 'did:ecdsa-pub:' + publicKey; } function getDIDType(decentralizedID) { var didParts = decentralizedID.split(':'); if (didParts.length !== 3) { throw new _errors.InvalidDIDError('Decentralized IDs must have 3 parts'); } if (didParts[0].toLowerCase() !== 'did') { throw new _errors.InvalidDIDError('Decentralized IDs must start with "did"'); } return didParts[1].toLowerCase(); } function getAddressFromDID(decentralizedID) { var didType = getDIDType(decentralizedID); if (didType === 'btc-addr') { return decentralizedID.split(':')[2]; } else { return null; } } /* export function getPublicKeyOrAddressFromDID(decentralizedID) { const didParts = decentralizedID.split(':') if (didParts.length !== 3) { throw new InvalidDIDError('Decentralized IDs must have 3 parts') } if (didParts[0].toLowerCase() !== 'did') { throw new InvalidDIDError('Decentralized IDs must start with "did"') } if (didParts[1].toLowerCase() === 'ecdsa-pub') { return didParts[2] } else if (didParts[1].toLowerCase() === 'btc-addr') { return didParts[2] } else { throw new InvalidDIDError('Decentralized ID format not supported') } } */ },{"./errors":11}],10:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getHexFromBN = getHexFromBN; exports.encryptECIES = encryptECIES; exports.decryptECIES = decryptECIES; exports.signECDSA = signECDSA; exports.verifyECDSA = verifyECDSA; exports.encryptMnemonic = encryptMnemonic; exports.decryptMnemonic = decryptMnemonic; var _elliptic = require('elliptic'); var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto); var _bip = require('bip39'); var _bip2 = _interopRequireDefault(_bip); var _triplesec = require('triplesec'); var _triplesec2 = _interopRequireDefault(_triplesec); var _keys = require('./keys'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ecurve = new _elliptic.ec('secp256k1'); function aes256CbcEncrypt(iv, key, plaintext) { var cipher = _crypto2.default.createCipheriv('aes-256-cbc', key, iv); return Buffer.concat([cipher.update(plaintext), cipher.final()]); } function aes256CbcDecrypt(iv, key, ciphertext) { var cipher = _crypto2.default.createDecipheriv('aes-256-cbc', key, iv); return Buffer.concat([cipher.update(ciphertext), cipher.final()]); } function hmacSha256(key, content) { return _crypto2.default.createHmac('sha256', key).update(content).digest(); } function equalConstTime(b1, b2) { if (b1.length !== b2.length) { return false; } var res = 0; for (var i = 0; i < b1.length; i++) { res |= b1[i] ^ b2[i]; // jshint ignore:line } return res === 0; } function sharedSecretToKeys(sharedSecret) { // generate mac and encryption key from shared secret var hashedSecret = _crypto2.default.createHash('sha512').update(sharedSecret).digest(); return { encryptionKey: hashedSecret.slice(0, 32), hmacKey: hashedSecret.slice(32) }; } function getHexFromBN(bnInput) { var hexOut = bnInput.toString('hex'); if (hexOut.length === 64) { return hexOut; } else if (hexOut.length < 64) { // pad with leading zeros // the padStart function would require node 9 var padding = '0'.repeat(64 - hexOut.length); return '' + padding + hexOut; } else { throw new Error('Generated a > 32-byte BN for encryption. Failing.'); } } /** * Encrypt content to elliptic curve publicKey using ECIES * @param {String} publicKey - secp256k1 public key hex string * @param {String | Buffer} content - content to encrypt * @return {Object} Object containing (hex encoded): * iv (initialization vector), cipherText (cipher text), * mac (message authentication code), ephemeral public key * wasString (boolean indicating with or not to return a buffer or string on decrypt) * @private */ function encryptECIES(publicKey, content) { var isString = typeof content === 'string'; var plainText = Buffer.from(content); // always copy to buffer var ecPK = ecurve.keyFromPublic(publicKey, 'hex').getPublic(); var ephemeralSK = ecurve.genKeyPair(); var ephemeralPK = ephemeralSK.getPublic(); var sharedSecret = ephemeralSK.derive(ecPK); var sharedSecretHex = getHexFromBN(sharedSecret); var sharedKeys = sharedSecretToKeys(new Buffer(sharedSecretHex, 'hex')); var initializationVector = _crypto2.default.randomBytes(16); var cipherText = aes256CbcEncrypt(initializationVector, sharedKeys.encryptionKey, plainText); var macData = Buffer.concat([initializationVector, new Buffer(ephemeralPK.encodeCompressed()), cipherText]); var mac = hmacSha256(sharedKeys.hmacKey, macData); return { iv: initializationVector.toString('hex'), ephemeralPK: ephemeralPK.encodeCompressed('hex'), cipherText: cipherText.toString('hex'), mac: mac.toString('hex'), wasString: isString }; } /** * Decrypt content encrypted using ECIES * @param {String} privateKey - secp256k1 private key hex string * @param {Object} cipherObject - object to decrypt, should contain: * iv (initialization vector), cipherText (cipher text), * mac (message authentication code), ephemeralPublicKey * wasString (boolean indicating with or not to return a buffer or string on decrypt) * @return {Buffer} plaintext * @throws {Error} if unable to decrypt * @private */ function decryptECIES(privateKey, cipherObject) { var ecSK = ecurve.keyFromPrivate(privateKey, 'hex'); var ephemeralPK = ecurve.keyFromPublic(cipherObject.ephemeralPK, 'hex').getPublic(); var sharedSecret = ecSK.derive(ephemeralPK); var sharedSecretBuffer = new Buffer(getHexFromBN(sharedSecret), 'hex'); var sharedKeys = sharedSecretToKeys(sharedSecretBuffer); var ivBuffer = new Buffer(cipherObject.iv, 'hex'); var cipherTextBuffer = new Buffer(cipherObject.cipherText, 'hex'); var macData = Buffer.concat([ivBuffer, new Buffer(ephemeralPK.encodeCompressed()), cipherTextBuffer]); var actualMac = hmacSha256(sharedKeys.hmacKey, macData); var expectedMac = new Buffer(cipherObject.mac, 'hex'); if (!equalConstTime(expectedMac, actualMac)) { throw new Error('Decryption failed: failure in MAC check'); } var plainText = aes256CbcDecrypt(ivBuffer, sharedKeys.encryptionKey, cipherTextBuffer); if (cipherObject.wasString) { return plainText.toString(); } else { return plainText; } } /** * Sign content using ECDSA * @private * @param {String} privateKey - secp256k1 private key hex string * @param {Object} content - content to sign * @return {Object} contains: * signature - Hex encoded DER signature * public key - Hex encoded private string taken from privateKey * @private */ function signECDSA(privateKey, content) { var contentBuffer = Buffer.from(content); var ecPrivate = ecurve.keyFromPrivate(privateKey, 'hex'); var publicKey = (0, _keys.getPublicKeyFromPrivate)(privateKey); var contentHash = _crypto2.default.createHash('sha256').update(contentBuffer).digest(); var signature = ecPrivate.sign(contentHash); var signatureString = signature.toDER('hex'); return { signature: signatureString, publicKey: publicKey }; } /** * Verify content using ECDSA * @param {String | Buffer} content - Content to verify was signed * @param {String} publicKey - secp256k1 private key hex string * @param {String} signature - Hex encoded DER signature * @return {Boolean} returns true when signature matches publickey + content, false if not * @private */ function verifyECDSA(content, publicKey, signature) { var contentBuffer = Buffer.from(content); var ecPublic = ecurve.keyFromPublic(publicKey, 'hex'); var contentHash = _crypto2.default.createHash('sha256').update(contentBuffer).digest(); return ecPublic.verify(contentHash, signature); } /** * Encrypt a raw mnemonic phrase to be password protected * @param {string} phrase - Raw mnemonic phrase * @param {string} password - Password to encrypt mnemonic with * @return {Promise} The encrypted phrase * @private */ function encryptMnemonic(phrase, password) { return Promise.resolve().then(function () { // must be bip39 mnemonic if (!_bip2.default.validateMnemonic(phrase)) { throw new Error('Not a valid bip39 nmemonic'); } // normalize plaintext to fixed length byte string var plaintextNormalized = Buffer.from(_bip2.default.mnemonicToEntropy(phrase).toString('hex'), 'hex'); // AES-128-CBC with SHA256 HMAC var salt = _crypto2.default.randomBytes(16); var keysAndIV = _crypto2.default.pbkdf2Sync(password, salt, 100000, 48, 'sha512'); var encKey = keysAndIV.slice(0, 16); var macKey = keysAndIV.slice(16, 32); var iv = keysAndIV.slice(32, 48); var cipher = _crypto2.default.createCipheriv('aes-128-cbc', encKey, iv); var cipherText = cipher.update(plaintextNormalized).toString('hex'); cipherText += cipher.final().toString('hex'); var hmacPayload = Buffer.concat([salt, Buffer.from(cipherText, 'hex')]); var hmac = _crypto2.default.createHmac('sha256', macKey); hmac.write(hmacPayload); var hmacDigest = hmac.digest(); var payload = Buffer.concat([salt, hmacDigest, Buffer.from(cipherText, 'hex')]); return payload; }); } // Used to distinguish bad password during decrypt vs invalid format var PasswordError = function (_Error) { _inherits(PasswordError, _Error); function PasswordError() { _classCallCheck(this, PasswordError); return _possibleConstructorReturn(this, (PasswordError.__proto__ || Object.getPrototypeOf(PasswordError)).apply(this, arguments)); } return PasswordError; }(Error); function decryptMnemonicBuffer(dataBuffer, password) { return Promise.resolve().then(function () { var salt = dataBuffer.slice(0, 16); var hmacSig = dataBuffer.slice(16, 48); // 32 bytes var cipherText = dataBuffer.slice(48); var hmacPayload = Buffer.concat([salt, cipherText]); var keysAndIV = _crypto2.default.pbkdf2Sync(password, salt, 100000, 48, 'sha512'); var encKey = keysAndIV.slice(0, 16); var macKey = keysAndIV.slice(16, 32); var iv = keysAndIV.slice(32, 48); var decipher = _crypto2.default.createDecipheriv('aes-128-cbc', encKey, iv); var plaintext = decipher.update(cipherText).toString('hex'); plaintext += decipher.final().toString('hex'); var hmac = _crypto2.default.createHmac('sha256', macKey); hmac.write(hmacPayload); var hmacDigest = hmac.digest(); // hash both hmacSig and hmacDigest so string comparison time // is uncorrelated to the ciphertext var hmacSigHash = _crypto2.default.createHash('sha256').update(hmacSig).digest().toString('hex'); var hmacDigestHash = _crypto2.default.createHash('sha256').update(hmacDigest).digest().toString('hex'); if (hmacSigHash !== hmacDigestHash) { // not authentic throw new PasswordError('Wrong password (HMAC mismatch)'); } var mnemonic = _bip2.default.entropyToMnemonic(plaintext); if (!_bip2.default.validateMnemonic(mnemonic)) { throw new PasswordError('Wrong password (invalid plaintext)'); } return mnemonic; }); } /** * Decrypt legacy triplesec keys * @param {Buffer} dataBuffer - The encrypted key * @param {String} password - Password for data * @return {Promise} Decrypted seed * @private */ function decryptLegacy(dataBuffer, password) { return new Promise(function (resolve, reject) { _triplesec2.default.decrypt({ key: Buffer.from(password), data: dataBuffer }, function (err, plaintextBuffer) { if (!err) { resolve(plaintextBuffer); } else { reject(err); } }); }); } /** * Encrypt a raw mnemonic phrase with a password * @param {string | Buffer} data - Buffer or hex-encoded string of the encrypted mnemonic * @param {string} password - Password for data * @return {Promise} the raw mnemonic phrase * @private */ function decryptMnemonic(data, password) { var dataBuffer = Buffer.isBuffer(data) ? data : Buffer.from(data, 'hex'); return decryptMnemonicBuffer(dataBuffer, password).catch(function (err) { // If it was a password error, don't even bother with legacy if (err instanceof PasswordError) { throw err; } return decryptLegacy(dataBuffer, password); }); } }).call(this,require("buffer").Buffer) },{"./keys":13,"bip39":74,"buffer":179,"crypto":188,"elliptic":306,"triplesec":478}],11:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var ERROR_CODES = exports.ERROR_CODES = { MISSING_PARAMETER: 'missing_parameter', REMOTE_SERVICE_ERROR: 'remote_service_error', UNKNOWN: 'unknown' }; Object.freeze(ERROR_CODES); var BlockstackError = exports.BlockstackError = function (_Error) { _inherits(BlockstackError, _Error); function BlockstackError(error) { _classCallCheck(this, BlockstackError); var _this = _possibleConstructorReturn(this, (BlockstackError.__proto__ || Object.getPrototypeOf(BlockstackError)).call(this, error.message)); _this.code = error.code; _this.parameter = error.parameter ? error.parameter : null; return _this; } _createClass(BlockstackError, [{ key: 'toString', value: function toString() { return _get(BlockstackError.prototype.__proto__ || Object.getPrototypeOf(BlockstackError.prototype), 'toString', this).call(this) + '\n code: ' + this.code + ' param: ' + (this.parameter ? this.parameter : 'n/a'); } }]); return BlockstackError; }(Error); var InvalidParameterError = exports.InvalidParameterError = function (_BlockstackError) { _inherits(InvalidParameterError, _BlockstackError); function InvalidParameterError(parameter) { var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; _classCallCheck(this, InvalidParameterError); var _this2 = _possibleConstructorReturn(this, (InvalidParameterError.__proto__ || Object.getPrototypeOf(InvalidParameterError)).call(this, { code: 'missing_parameter', message: message, parameter: '' })); _this2.name = 'MissingParametersError'; return _this2; } return InvalidParameterError; }(BlockstackError); var MissingParameterError = exports.MissingParameterError = function (_BlockstackError2) { _inherits(MissingParameterError, _BlockstackError2); function MissingParameterError(parameter) { var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; _classCallCheck(this, MissingParameterError); var _this3 = _possibleConstructorReturn(this, (MissingParameterError.__proto__ || Object.getPrototypeOf(MissingParameterError)).call(this, { code: ERROR_CODES.MISSING_PARAMETER, message: message, parameter: parameter })); _this3.name = 'MissingParametersError'; return _this3; } return MissingParameterError; }(BlockstackError); var RemoteServiceError = exports.RemoteServiceError = function (_BlockstackError3) { _inherits(RemoteServiceError, _BlockstackError3); function RemoteServiceError(response) { var message = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : ''; _classCallCheck(this, RemoteServiceError); var _this4 = _possibleConstructorReturn(this, (RemoteServiceError.__proto__ || Object.getPrototypeOf(RemoteServiceError)).call(this, { code: ERROR_CODES.REMOTE_SERVICE_ERROR, message: message })); _this4.response = response; return _this4; } return RemoteServiceError; }(BlockstackError); var InvalidDIDError = exports.InvalidDIDError = function (_BlockstackError4) { _inherits(InvalidDIDError, _BlockstackError4); function InvalidDIDError() { var message = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; _classCallCheck(this, InvalidDIDError); var _this5 = _possibleConstructorReturn(this, (InvalidDIDError.__proto__ || Object.getPrototypeOf(InvalidDIDError)).call(this, { code: 'invalid_did_error', message: message })); _this5.name = 'InvalidDIDError'; return _this5; } return InvalidDIDError; }(BlockstackError); var NotEnoughFundsError = exports.NotEnoughFundsError = function (_BlockstackError5) { _inherits(NotEnoughFundsError, _BlockstackError5); function NotEnoughFundsError(leftToFund) { _classCallCheck(this, NotEnoughFundsError); var message = 'Not enough UTXOs to fund. Left to fund: ' + leftToFund; var _this6 = _possibleConstructorReturn(this, (NotEnoughFundsError.__proto__ || Object.getPrototypeOf(NotEnoughFundsError)).call(this, { code: 'not_enough_error', message: message })); _this6.leftToFund = leftToFund; _this6.name = 'NotEnoughFundsError'; _this6.message = message; return _this6; } return NotEnoughFundsError; }(BlockstackError); var InvalidAmountError = exports.InvalidAmountError = function (_BlockstackError6) { _inherits(InvalidAmountError, _BlockstackError6); function InvalidAmountError(fees, specifiedAmount) { _classCallCheck(this, InvalidAmountError); var message = 'Not enough coin to fund fees transaction fees. Fees would be ' + fees + ',' + (' specified spend is ' + specifiedAmount); var _this7 = _possibleConstructorReturn(this, (InvalidAmountError.__proto__ || Object.getPrototypeOf(InvalidAmountError)).call(this, { code: 'invalid_amount_error', message: message })); _this7.specifiedAmount = specifiedAmount; _this7.fees = fees; _this7.name = 'InvalidAmountError'; _this7.message = message; return _this7; } return InvalidAmountError; }(BlockstackError); var LoginFailedError = exports.LoginFailedError = function (_BlockstackError7) { _inherits(LoginFailedError, _BlockstackError7); function LoginFailedError(reason) { _classCallCheck(this, LoginFailedError); var message = 'Failed to login: ' + reason; var _this8 = _possibleConstructorReturn(this, (LoginFailedError.__proto__ || Object.getPrototypeOf(LoginFailedError)).call(this, { code: 'login_failed', message: message })); _this8.message = message; _this8.name = 'LoginFailedError'; return _this8; } return LoginFailedError; }(BlockstackError); var SignatureVerificationError = exports.SignatureVerificationError = function (_BlockstackError8) { _inherits(SignatureVerificationError, _BlockstackError8); function SignatureVerificationError(reason) { _classCallCheck(this, SignatureVerificationError); var message = 'Failed to verify signature: ' + reason; var _this9 = _possibleConstructorReturn(this, (SignatureVerificationError.__proto__ || Object.getPrototypeOf(SignatureVerificationError)).call(this, { code: 'signature_verification_failure', message: message })); _this9.message = message; _this9.name = 'SignatureVerificationError'; return _this9; } return SignatureVerificationError; }(BlockstackError); },{}],12:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _auth = require('./auth'); Object.keys(_auth).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _auth[key]; } }); }); var _profiles = require('./profiles'); Object.keys(_profiles).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _profiles[key]; } }); }); var _storage = require('./storage'); Object.keys(_storage).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _storage[key]; } }); }); var _dids = require('./dids'); Object.defineProperty(exports, 'makeDIDFromAddress', { enumerable: true, get: function get() { return _dids.makeDIDFromAddress; } }); Object.defineProperty(exports, 'makeDIDFromPublicKey', { enumerable: true, get: function get() { return _dids.makeDIDFromPublicKey; } }); Object.defineProperty(exports, 'getDIDType', { enumerable: true, get: function get() { return _dids.getDIDType; } }); Object.defineProperty(exports, 'getAddressFromDID', { enumerable: true, get: function get() { return _dids.getAddressFromDID; } }); var _keys = require('./keys'); Object.defineProperty(exports, 'getEntropy', { enumerable: true, get: function get() { return _keys.getEntropy; } }); Object.defineProperty(exports, 'makeECPrivateKey', { enumerable: true, get: function get() { return _keys.makeECPrivateKey; } }); Object.defineProperty(exports, 'publicKeyToAddress', { enumerable: true, get: function get() { return _keys.publicKeyToAddress; } }); Object.defineProperty(exports, 'getPublicKeyFromPrivate', { enumerable: true, get: function get() { return _keys.getPublicKeyFromPrivate; } }); var _utils = require('./utils'); Object.defineProperty(exports, 'nextYear', { enumerable: true, get: function get() { return _utils.nextYear; } }); Object.defineProperty(exports, 'nextMonth', { enumerable: true, get: function get() { return _utils.nextMonth; } }); Object.defineProperty(exports, 'nextHour', { enumerable: true, get: function get() { return _utils.nextHour; } }); Object.defineProperty(exports, 'makeUUID4', { enumerable: true, get: function get() { return _utils.makeUUID4; } }); Object.defineProperty(exports, 'updateQueryStringParameter', { enumerable: true, get: function get() { return _utils.updateQueryStringParameter; } }); Object.defineProperty(exports, 'isLaterVersion', { enumerable: true, get: function get() { return _utils.isLaterVersion; } }); Object.defineProperty(exports, 'isSameOriginAbsoluteUrl', { enumerable: true, get: function get() { return _utils.isSameOriginAbsoluteUrl; } }); Object.defineProperty(exports, 'hexStringToECPair', { enumerable: true, get: function get() { return _utils.hexStringToECPair; } }); Object.defineProperty(exports, 'ecPairToHexString', { enumerable: true, get: function get() { return _utils.ecPairToHexString; } }); Object.defineProperty(exports, 'ecPairToAddress', { enumerable: true, get: function get() { return _utils.ecPairToAddress; } }); var _operations = require('./operations'); Object.defineProperty(exports, 'transactions', { enumerable: true, get: function get() { return _operations.transactions; } }); Object.defineProperty(exports, 'safety', { enumerable: true, get: function get() { return _operations.safety; } }); Object.defineProperty(exports, 'TransactionSigner', { enumerable: true, get: function get() { return _operations.TransactionSigner; } }); Object.defineProperty(exports, 'PubkeyHashSigner', { enumerable: true, get: function get() { return _operations.PubkeyHashSigner; } }); Object.defineProperty(exports, 'addUTXOsToFund', { enumerable: true, get: function get() { return _operations.addUTXOsToFund; } }); Object.defineProperty(exports, 'estimateTXBytes', { enumerable: true, get: function get() { return _operations.estimateTXBytes; } }); var _wallet = require('./wallet'); Object.defineProperty(exports, 'BlockstackWallet', { enumerable: true, get: function get() { return _wallet.BlockstackWallet; } }); Object.defineProperty(exports, 'IdentityKeyPair', { enumerable: true, get: function get() { return _wallet.IdentityKeyPair; } }); var _network = require('./network'); Object.defineProperty(exports, 'network', { enumerable: true, get: function get() { return _network.network; } }); var _jsontokens = require('jsontokens'); Object.defineProperty(exports, 'decodeToken', { enumerable: true, get: function get() { return _jsontokens.decodeToken; } }); var _config = require('./config'); Object.defineProperty(exports, 'config', { enumerable: true, get: function get() { return _config.config; } }); var _encryption = require('./encryption'); Object.defineProperty(exports, 'encryptMnemonic', { enumerable: true, get: function get() { return _encryption.encryptMnemonic; } }); Object.defineProperty(exports, 'decryptMnemonic', { enumerable: true, get: function get() { return _encryption.decryptMnemonic; } }); },{"./auth":7,"./config":8,"./dids":9,"./encryption":10,"./keys":13,"./network":15,"./operations":16,"./profiles":22,"./storage":45,"./utils":46,"./wallet":47,"jsontokens":384}],13:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getEntropy = getEntropy; exports.makeECPrivateKey = makeECPrivateKey; exports.publicKeyToAddress = publicKeyToAddress; exports.getPublicKeyFromPrivate = getPublicKeyFromPrivate; var _crypto = require('crypto'); var _bitcoinjsLib = require('bitcoinjs-lib'); function getEntropy(numberOfBytes) { if (!numberOfBytes) { numberOfBytes = 32; } return (0, _crypto.randomBytes)(numberOfBytes); } function makeECPrivateKey() { var keyPair = new _bitcoinjsLib.ECPair.makeRandom({ rng: getEntropy }); return keyPair.privateKey.toString('hex'); } function publicKeyToAddress(publicKey) { var publicKeyBuffer = Buffer.from(publicKey, 'hex'); var publicKeyHash160 = _bitcoinjsLib.crypto.hash160(publicKeyBuffer); var address = _bitcoinjsLib.address.toBase58Check(publicKeyHash160, 0x00); return address; } function getPublicKeyFromPrivate(privateKey) { var keyPair = _bitcoinjsLib.ECPair.fromPrivateKey(Buffer.from(privateKey, 'hex')); return keyPair.publicKey.toString('hex'); } }).call(this,require("buffer").Buffer) },{"bitcoinjs-lib":92,"buffer":179,"crypto":188}],14:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Logger = exports.levels = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _config = require('./config'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var levels = exports.levels = ['debug', 'info', 'warn', 'error', 'none']; var levelToInt = {}; var intToLevel = {}; for (var index = 0; index < levels.length; index++) { var level = levels[index]; levelToInt[level] = index; intToLevel[index] = level; } var Logger = exports.Logger = function () { function Logger() { _classCallCheck(this, Logger); } _createClass(Logger, null, [{ key: 'error', value: function error(message) { if (!this.shouldLog('error')) return; console.error(this.logMessage('error', message)); } }, { key: 'warn', value: function warn(message) { if (!this.shouldLog('warn')) return; console.warn(this.logMessage('warn', message)); } }, { key: 'info', value: function info(message) { if (!this.shouldLog('info')) return; console.log(this.logMessage('info', message)); } }, { key: 'debug', value: function debug(message) { if (!this.shouldLog('debug')) return; console.log(this.logMessage('debug', message)); } }, { key: 'logMessage', value: function logMessage(level, message) { return '[' + level.toUpperCase() + '] ' + message; } }, { key: 'shouldLog', value: function shouldLog(level) { var currentLevel = levelToInt[_config.config.logLevel]; return currentLevel <= levelToInt[level]; } }]); return Logger; }(); },{"./config":8}],15:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.network = exports.BlockchainInfoApi = exports.InsightClient = exports.BitcoindAPI = exports.LocalRegtest = exports.BlockstackNetwork = exports.BitcoinNetwork = undefined; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _bitcoinjsLib = require('bitcoinjs-lib'); var _bitcoinjsLib2 = _interopRequireDefault(_bitcoinjsLib); var _formData = require('form-data'); var _formData2 = _interopRequireDefault(_formData); var _bigi = require('bigi'); var _bigi2 = _interopRequireDefault(_bigi); var _ripemd = require('ripemd160'); var _ripemd2 = _interopRequireDefault(_ripemd); var _errors = require('./errors'); var _logger = require('./logger'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var SATOSHIS_PER_BTC = 1e8; var TX_BROADCAST_SERVICE_ZONE_FILE_ENDPOINT = 'zone-file'; var TX_BROADCAST_SERVICE_REGISTRATION_ENDPOINT = 'registration'; var TX_BROADCAST_SERVICE_TX_ENDPOINT = 'transaction'; var BitcoinNetwork = exports.BitcoinNetwork = function () { function BitcoinNetwork() { _classCallCheck(this, BitcoinNetwork); } _createClass(BitcoinNetwork, [{ key: 'broadcastTransaction', value: function broadcastTransaction(transaction) { return Promise.reject(new Error('Not implemented, broadcastTransaction(' + transaction + ')')); } }, { key: 'getBlockHeight', value: function getBlockHeight() { return Promise.reject(new Error('Not implemented, getBlockHeight()')); } }, { key: 'getTransactionInfo', value: function getTransactionInfo(txid) { return Promise.reject(new Error('Not implemented, getTransactionInfo(' + txid + ')')); } }, { key: 'getNetworkedUTXOs', value: function getNetworkedUTXOs(address) { return Promise.reject(new Error('Not implemented, getNetworkedUTXOs(' + address + ')')); } }]); return BitcoinNetwork; }(); var BlockstackNetwork = exports.BlockstackNetwork = function () { function BlockstackNetwork(apiUrl, broadcastServiceUrl, bitcoinAPI) { var network = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : _bitcoinjsLib2.default.networks.bitcoin; _classCallCheck(this, BlockstackNetwork); this.blockstackAPIUrl = apiUrl; this.broadcastServiceUrl = broadcastServiceUrl; this.layer1 = network; this.btc = bitcoinAPI; this.DUST_MINIMUM = 5500; this.includeUtxoMap = {}; this.excludeUtxoSet = []; this.MAGIC_BYTES = 'id'; } _createClass(BlockstackNetwork, [{ key: 'coerceAddress', value: function coerceAddress(address) { var _bitcoinjs$address$fr = _bitcoinjsLib2.default.address.fromBase58Check(address), hash = _bitcoinjs$address$fr.hash, version = _bitcoinjs$address$fr.version; var scriptHashes = [_bitcoinjsLib2.default.networks.bitcoin.scriptHash, _bitcoinjsLib2.default.networks.testnet.scriptHash]; var pubKeyHashes = [_bitcoinjsLib2.default.networks.bitcoin.pubKeyHash, _bitcoinjsLib2.default.networks.testnet.pubKeyHash]; var coercedVersion = void 0; if (scriptHashes.indexOf(version) >= 0) { coercedVersion = this.layer1.scriptHash; } else if (pubKeyHashes.indexOf(version) >= 0) { coercedVersion = this.layer1.pubKeyHash; } else { throw new Error('Unrecognized address version number ' + version + ' in ' + address); } return _bitcoinjsLib2.default.address.toBase58Check(hash, coercedVersion); } }, { key: 'getDefaultBurnAddress', value: function getDefaultBurnAddress() { return this.coerceAddress('1111111111111111111114oLvT2'); } /** * Get the price of a name via the legacy /v1/prices API endpoint. * @param {String} fullyQualifiedName the name to query * @return {Promise} a promise to an Object with { units: String, amount: BigInteger } * @private */ }, { key: 'getNamePriceV1', value: function getNamePriceV1(fullyQualifiedName) { var _this = this; // legacy code path return fetch(this.blockstackAPIUrl + '/v1/prices/names/' + fullyQualifiedName).then(function (resp) { if (!resp.ok) { throw new Error('Failed to query name price for ' + fullyQualifiedName); } return resp; }).then(function (resp) { return resp.json(); }).then(function (resp) { return resp.name_price; }).then(function (namePrice) { if (!namePrice || !namePrice.satoshis) { throw new Error('Failed to get price for ' + fullyQualifiedName + '. Does the namespace exist?'); } if (namePrice.satoshis < _this.DUST_MINIMUM) { namePrice.satoshis = _this.DUST_MINIMUM; } var result = { units: 'BTC', amount: _bigi2.default.fromByteArrayUnsigned(String(namePrice.satoshis)) }; return result; }); } /** * Get the price of a namespace via the legacy /v1/prices API endpoint. * @param {String} namespaceID the namespace to query * @return {Promise} a promise to an Object with { units: String, amount: BigInteger } * @private */ }, { key: 'getNamespacePriceV1', value: function getNamespacePriceV1(namespaceID) { var _this2 = this; // legacy code path return fetch(this.blockstackAPIUrl + '/v1/prices/namespaces/' + namespaceID).then(function (resp) { if (!resp.ok) { throw new Error('Failed to query name price for ' + namespaceID); } return resp; }).then(function (resp) { return resp.json(); }).then(function (namespacePrice) { if (!namespacePrice || !namespacePrice.satoshis) { throw new Error('Failed to get price for ' + namespaceID); } if (namespacePrice.satoshis < _this2.DUST_MINIMUM) { namespacePrice.satoshis = _this2.DUST_MINIMUM; } var result = { units: 'BTC', amount: _bigi2.default.fromByteArrayUnsigned(String(namespacePrice.satoshis)) }; return result; }); } /** * Get the price of a name via the /v2/prices API endpoint. * @param {String} fullyQualifiedName the name to query * @return {Promise} a promise to an Object with { units: String, amount: BigInteger } * @private */ }, { key: 'getNamePriceV2', value: function getNamePriceV2(fullyQualifiedName) { var _this3 = this; return fetch(this.blockstackAPIUrl + '/v2/prices/names/' + fullyQualifiedName).then(function (resp) { if (resp.status !== 200) { // old core node throw new Error('The upstream node does not handle the /v2/ price namespace'); } return resp; }).then(function (resp) { return resp.json(); }).then(function (resp) { return resp.name_price; }).then(function (namePrice) { if (!namePrice) { throw new Error('Failed to get price for ' + fullyQualifiedName + '. Does the namespace exist?'); } var result = { units: namePrice.units, amount: _bigi2.default.fromByteArrayUnsigned(namePrice.amount) }; if (namePrice.units === 'BTC') { // must be at least dust-minimum var dustMin = _bigi2.default.fromByteArrayUnsigned(String(_this3.DUST_MINIMUM)); if (result.amount.compareTo(dustMin) < 0) { result.amount = dustMin; } } return result; }); } /** * Get the price of a namespace via the /v2/prices API endpoint. * @param {String} namespaceID the namespace to query * @return {Promise} a promise to an Object with { units: String, amount: BigInteger } * @private */ }, { key: 'getNamespacePriceV2', value: function getNamespacePriceV2(namespaceID) { var _this4 = this; return fetch(this.blockstackAPIUrl + '/v2/prices/namespaces/' + namespaceID).then(function (resp) { if (resp.status !== 200) { // old core node throw new Error('The upstream node does not handle the /v2/ price namespace'); } return resp; }).then(function (resp) { return resp.json(); }).then(function (namespacePrice) { if (!namespacePrice) { throw new Error('Failed to get price for ' + namespaceID); } var result = { units: namespacePrice.units, amount: _bigi2.default.fromByteArrayUnsigned(namespacePrice.amount) }; if (namespacePrice.units === 'BTC') { // must be at least dust-minimum var dustMin = _bigi2.default.fromByteArrayUnsigned(String(_this4.DUST_MINIMUM)); if (result.amount.compareTo(dustMin) < 0) { result.amount = dustMin; } } return result; }); } /** * Get the price of a name. * @param {String} fullyQualifiedName the name to query * @return {Promise} a promise to an Object with { units: String, amount: BigInteger }, where * .units encodes the cryptocurrency units to pay (e.g. BTC, STACKS), and * .amount encodes the number of units, in the smallest denominiated amount * (e.g. if .units is BTC, .amount will be satoshis; if .units is STACKS, * .amount will be microStacks) */ }, { key: 'getNamePrice', value: function getNamePrice(fullyQualifiedName) { var _this5 = this; // handle v1 or v2 return Promise.resolve().then(function () { return _this5.getNamePriceV2(fullyQualifiedName); }).catch(function () { return _this5.getNamePriceV1(fullyQualifiedName); }); } /** * Get the price of a namespace * @param {String} namespaceID the namespace to query * @return {Promise} a promise to an Object with { units: String, amount: BigInteger }, where * .units encodes the cryptocurrency units to pay (e.g. BTC, STACKS), and * .amount encodes the number of units, in the smallest denominiated amount * (e.g. if .units is BTC, .amount will be satoshis; if .units is STACKS, * .amount will be microStacks) */ }, { key: 'getNamespacePrice', value: function getNamespacePrice(namespaceID) { var _this6 = this; // handle v1 or v2 return Promise.resolve().then(function () { return _this6.getNamespacePriceV2(namespaceID); }).catch(function () { return _this6.getNamespacePriceV1(namespaceID); }); } /** * How many blocks can pass between a name expiring and the name being able to be * re-registered by a different owner? * @return {Promise} a promise to the number of blocks */ }, { key: 'getGracePeriod', value: function getGracePeriod() { return new Promise(function (resolve) { return resolve(5000); }); } /** * Get the names -- both on-chain and off-chain -- owned by an address. * @param {String} address the blockchain address (the hash of the owner public key) * @return {Promise} a promise that resolves to a list of names (Strings) */ }, { key: 'getNamesOwned', value: function getNamesOwned(address) { var networkAddress = this.coerceAddress(address); return fetch(this.blockstackAPIUrl + '/v1/addresses/bitcoin/' + networkAddress).then(function (resp) { return resp.json(); }).then(function (obj) { return obj.names; }); } /** * Get the blockchain address to which a name's registration fee must be sent * (the address will depend on the namespace in which it is registered.) * @param {String} namespace the namespace ID * @return {Promise} a promise that resolves to an address (String) */ }, { key: 'getNamespaceBurnAddress', value: function getNamespaceBurnAddress(namespace) { var _this7 = this; return Promise.all([fetch(this.blockstackAPIUrl + '/v1/namespaces/' + namespace), this.getBlockHeight()]).then(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), resp = _ref2[0], blockHeight = _ref2[1]; if (resp.status === 404) { throw new Error('No such namespace \'' + namespace + '\''); } else { return Promise.all([resp.json(), blockHeight]); } }).then(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), namespaceInfo = _ref4[0], blockHeight = _ref4[1]; var address = _this7.getDefaultBurnAddress(); if (namespaceInfo.version === 2) { // pay-to-namespace-creator if this namespace is less than 1 year old if (namespaceInfo.reveal_block + 52595 >= blockHeight) { address = namespaceInfo.address; } } return address; }).then(function (address) { return _this7.coerceAddress(address); }); } /** * Get WHOIS-like information for a name, including the address that owns it, * the block at which it expires, and the zone file anchored to it (if available). * @param {String} fullyQualifiedName the name to query. Can be on-chain of off-chain. * @return {Promise} a promise that resolves to the WHOIS-like information */ }, { key: 'getNameInfo', value: function getNameInfo(fullyQualifiedName) { var _this8 = this; return fetch(this.blockstackAPIUrl + '/v1/names/' + fullyQualifiedName).then(function (resp) { if (resp.status === 404) { throw new Error('Name not found'); } else if (resp.status !== 200) { throw new Error('Bad response status: ' + resp.status); } else { return resp.json(); } }).then(function (nameInfo) { // the returned address _should_ be in the correct network --- // blockstackd gets into trouble because it tries to coerce back to mainnet // and the regtest transaction generation libraries want to use testnet addresses if (nameInfo.address) { return Object.assign({}, nameInfo, { address: _this8.coerceAddress(nameInfo.address) }); } else { return nameInfo; } }); } /** * Get the pricing parameters and creation history of a namespace. * @param {String} namespaceID the namespace to query * @return {Promise} a promise that resolves to the namespace information. */ }, { key: 'getNamespaceInfo', value: function getNamespaceInfo(namespaceID) { var _this9 = this; return fetch(this.blockstackAPIUrl + '/v1/namespaces/' + namespaceID).then(function (resp) { if (resp.status === 404) { throw new Error('Namespace not found'); } else if (resp.status !== 200) { throw new Error('Bad response status: ' + resp.status); } else { return resp.json(); } }).then(function (namespaceInfo) { // the returned address _should_ be in the correct network --- // blockstackd gets into trouble because it tries to coerce back to mainnet // and the regtest transaction generation libraries want to use testnet addresses if (namespaceInfo.address && namespaceInfo.recipient_address) { return Object.assign({}, namespaceInfo, { address: _this9.coerceAddress(namespaceInfo.address), recipient_address: _this9.coerceAddress(namespaceInfo.recipient_address) }); } else { return namespaceInfo; } }); } /** * Get a zone file, given its hash. Throws an exception if the zone file * obtained does not match the hash. * @param {String} zonefileHash the ripemd160(sha256) hash of the zone file * @return {Promise} a promise that resolves to the zone file's text */ }, { key: 'getZonefile', value: function getZonefile(zonefileHash) { return fetch(this.blockstackAPIUrl + '/v1/zonefiles/' + zonefileHash).then(function (resp) { if (resp.status === 200) { return resp.text().then(function (body) { var sha256 = _bitcoinjsLib2.default.crypto.sha256(body); var h = new _ripemd2.default().update(sha256).digest('hex'); if (h !== zonefileHash) { throw new Error('Zone file contents hash to ' + h + ', not ' + zonefileHash); } return body; }); } else { throw new Error('Bad response status: ' + resp.status); } }); } /** * Get the status of an account for a particular token holding. This includes its total number of * expenditures and credits, lockup times, last txid, and so on. * @param {String} address the account * @param {String} tokenType the token type to query * @return {Promise} a promise that resolves to an object representing the state of the account * for this token */ }, { key: 'getAccountStatus', value: function getAccountStatus(address, tokenType) { var _this10 = this; return fetch(this.blockstackAPIUrl + '/v1/accounts/' + address + '/' + tokenType + '/status').then(function (resp) { if (resp.status === 404) { throw new Error('Account not found'); } else if (resp.status !== 200) { throw new Error('Bad response status: ' + resp.status); } else { return resp.json(); } }).then(function (accountStatus) { // coerce all addresses, and convert credit/debit to biginteger var formattedStatus = Object.assign({}, accountStatus, { address: _this10.coerceAddress(accountStatus.address), debit_value: _bigi2.default.fromByteArrayUnsigned(String(accountStatus.debit_value)), credit_value: _bigi2.default.fromByteArrayUnsigned(String(accountStatus.credit_value)) }); return formattedStatus; }); } /** * Get a page of an account's transaction history. * @param {String} address the account's address * @param {number} page the page number. Page 0 is the most recent transactions * @return {Promise} a promise that resolves to an Array of Objects, where each Object encodes * states of the account at various block heights (e.g. prior balances, txids, etc) */ }, { key: 'getAccountHistoryPage', value: function getAccountHistoryPage(address, page) { var _this11 = this; var url = this.blockstackAPIUrl + '/v1/accounts/' + address + '/history?page=' + page; return fetch(url).then(function (resp) { if (resp.status === 404) { throw new Error('Account not found'); } else if (resp.status !== 200) { throw new Error('Bad response status: ' + resp.status); } else { return resp.json(); } }).then(function (historyList) { if (historyList.error) { throw new Error('Unable to get account history page: ' + historyList.error); } // coerse all addresses and convert to bigint return historyList.map(function (histEntry) { histEntry.address = _this11.coerceAddress(histEntry.address); histEntry.debit_value = _bigi2.default.fromByteArrayUnsigned(String(histEntry.debit_value)); histEntry.credit_value = _bigi2.default.fromByteArrayUnsigned(String(histEntry.credit_value)); return histEntry; }); }); } /** * Get the state(s) of an account at a particular block height. This includes the state of the * account beginning with this block's transactions, as well as all of the states the account * passed through when this block was processed (if any). * @param {String} address the account's address * @param {Integer} blockHeight the block to query * @return {Promise} a promise that resolves to an Array of Objects, where each Object encodes * states of the account at this block. */ }, { key: 'getAccountAt', value: function getAccountAt(address, blockHeight) { var _this12 = this; var url = this.blockstackAPIUrl + '/v1/accounts/' + address + '/history/' + blockHeight; return fetch(url).then(function (resp) { if (resp.status === 404) { throw new Error('Account not found'); } else if (resp.status !== 200) { throw new Error('Bad response status: ' + resp.status); } else { return resp.json(); } }).then(function (historyList) { if (historyList.error) { throw new Error('Unable to get historic account state: ' + historyList.error); } // coerce all addresses return historyList.map(function (histEntry) { histEntry.address = _this12.coerceAddress(histEntry.address); histEntry.debit_value = _bigi2.default.fromByteArrayUnsigned(String(histEntry.debit_value)); histEntry.credit_value = _bigi2.default.fromByteArrayUnsigned(String(histEntry.credit_value)); return histEntry; }); }); } /** * Get the set of token types that this account owns * @param {String} address the account's address * @return {Promise} a promise that resolves to an Array of Strings, where each item encodes the * type of token this account holds (excluding the underlying blockchain's tokens) */ }, { key: 'getAccountTokens', value: function getAccountTokens(address) { return fetch(this.blockstackAPIUrl + '/v1/accounts/' + address + '/tokens').then(function (resp) { if (resp.status === 404) { throw new Error('Account not found'); } else if (resp.status !== 200) { throw new Error('Bad response status: ' + resp.status); } else { return resp.json(); } }).then(function (tokenList) { if (tokenList.error) { throw new Error('Unable to get token list: ' + tokenList.error); } return tokenList; }); } /** * Get the number of tokens owned by an account. If the account does not exist or has no * tokens of this type, then 0 will be returned. * @param {String} address the account's address * @param {String} tokenType the type of token to query. * @return {Promise} a promise that resolves to a BigInteger that encodes the number of tokens * held by this account. */ }, { key: 'getAccountBalance', value: function getAccountBalance(address, tokenType) { return fetch(this.blockstackAPIUrl + '/v1/accounts/' + address + '/' + tokenType + '/balance').then(function (resp) { if (resp.status === 404) { // talking to an older blockstack core node without the accounts API return Promise.resolve().then(function () { return _bigi2.default.fromByteArrayUnsigned('0'); }); } else if (resp.status !== 200) { throw new Error('Bad response status: ' + resp.status); } else { return resp.json(); } }).then(function (tokenBalance) { if (tokenBalance.error) { throw new Error('Unable to get account balance: ' + tokenBalance.error); } var balance = '0'; if (tokenBalance && tokenBalance.balance) { balance = tokenBalance.balance; } return _bigi2.default.fromByteArrayUnsigned(balance); }); } /** * Performs a POST request to the given URL * @param {String} endpoint the name of * @param {String} body [description] * @return {Promise} Returns a `Promise` that resolves to the object requested. * In the event of an error, it rejects with: * * a `RemoteServiceError` if there is a problem * with the transaction broadcast service * * `MissingParameterError` if you call the function without a required * parameter * * @private */ }, { key: 'broadcastServiceFetchHelper', value: function broadcastServiceFetchHelper(endpoint, body) { var requestHeaders = { Accept: 'application/json', 'Content-Type': 'application/json' }; var options = { method: 'POST', headers: requestHeaders, body: JSON.stringify(body) }; var url = this.broadcastServiceUrl + '/v1/broadcast/' + endpoint; return fetch(url, options).then(function (response) { if (response.ok) { return response.json(); } else { throw new _errors.RemoteServiceError(response); } }); } /** * Broadcasts a signed bitcoin transaction to the network optionally waiting to broadcast the * transaction until a second transaction has a certain number of confirmations. * * @param {string} transaction the hex-encoded transaction to broadcast * @param {string} transactionToWatch the hex transaction id of the transaction to watch for * the specified number of confirmations before broadcasting the `transaction` * @param {number} confirmations the number of confirmations `transactionToWatch` must have * before broadcasting `transaction`. * @return {Promise} Returns a Promise that resolves to an object with a * `transaction_hash` key containing the transaction hash of the broadcasted transaction. * * In the event of an error, it rejects with: * * a `RemoteServiceError` if there is a problem * with the transaction broadcast service * * `MissingParameterError` if you call the function without a required * parameter * @private */ }, { key: 'broadcastTransaction', value: function broadcastTransaction(transaction) { var transactionToWatch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var confirmations = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : 6; if (!transaction) { var error = new _errors.MissingParameterError('transaction'); return Promise.reject(error); } if (!confirmations && confirmations !== 0) { var _error = new _errors.MissingParameterError('confirmations'); return Promise.reject(_error); } if (transactionToWatch === null) { return this.btc.broadcastTransaction(transaction); } else { /* * POST /v1/broadcast/transaction * Request body: * JSON.stringify({ * transaction, * transactionToWatch, * confirmations * }) */ var endpoint = TX_BROADCAST_SERVICE_TX_ENDPOINT; var requestBody = { transaction: transaction, transactionToWatch: transactionToWatch, confirmations: confirmations }; return this.broadcastServiceFetchHelper(endpoint, requestBody); } } /** * Broadcasts a zone file to the Atlas network via the transaction broadcast service. * * @param {String} zoneFile the zone file to be broadcast to the Atlas network * @param {String} transactionToWatch the hex transaction id of the transaction * to watch for confirmation before broadcasting the zone file to the Atlas network * @return {Promise} Returns a Promise that resolves to an object with a * `transaction_hash` key containing the transaction hash of the broadcasted transaction. * * In the event of an error, it rejects with: * * a `RemoteServiceError` if there is a problem * with the transaction broadcast service * * `MissingParameterError` if you call the function without a required * parameter * @private */ }, { key: 'broadcastZoneFile', value: function broadcastZoneFile(zoneFile) { var transactionToWatch = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (!zoneFile) { return Promise.reject(new _errors.MissingParameterError('zoneFile')); } // TODO: validate zonefile if (transactionToWatch) { // broadcast via transaction broadcast service /* * POST /v1/broadcast/zone-file * Request body: * JSON.stringify({ * zoneFile, * transactionToWatch * }) */ var requestBody = { zoneFile: zoneFile, transactionToWatch: transactionToWatch }; var endpoint = TX_BROADCAST_SERVICE_ZONE_FILE_ENDPOINT; return this.broadcastServiceFetchHelper(endpoint, requestBody); } else { // broadcast via core endpoint // zone file is two words but core's api treats it as one word 'zonefile' var _requestBody = { zonefile: zoneFile }; return fetch(this.blockstackAPIUrl + '/v1/zonefile/', { method: 'POST', body: JSON.stringify(_requestBody), headers: { 'Content-Type': 'application/json' } }).then(function (resp) { var json = resp.json(); return json.then(function (respObj) { if (respObj.hasOwnProperty('error')) { throw new _errors.RemoteServiceError(resp); } return respObj.servers; }); }); } } /** * Sends the preorder and registration transactions and zone file * for a Blockstack name registration * along with the to the transaction broadcast service. * * The transaction broadcast: * * * immediately broadcasts the preorder transaction * * broadcasts the register transactions after the preorder transaction * has an appropriate number of confirmations * * broadcasts the zone file to the Atlas network after the register transaction * has an appropriate number of confirmations * * @param {String} preorderTransaction the hex-encoded, signed preorder transaction generated * using the `makePreorder` function * @param {String} registerTransaction the hex-encoded, signed register transaction generated * using the `makeRegister` function * @param {String} zoneFile the zone file to be broadcast to the Atlas network * @return {Promise} Returns a Promise that resolves to an object with a * `transaction_hash` key containing the transaction hash of the broadcasted transaction. * * In the event of an error, it rejects with: * * a `RemoteServiceError` if there is a problem * with the transaction broadcast service * * `MissingParameterError` if you call the function without a required * parameter * @private */ }, { key: 'broadcastNameRegistration', value: function broadcastNameRegistration(preorderTransaction, registerTransaction, zoneFile) { /* * POST /v1/broadcast/registration * Request body: * JSON.stringify({ * preorderTransaction, * registerTransaction, * zoneFile * }) */ if (!preorderTransaction) { var error = new _errors.MissingParameterError('preorderTransaction'); return Promise.reject(error); } if (!registerTransaction) { var _error2 = new _errors.MissingParameterError('registerTransaction'); return Promise.reject(_error2); } if (!zoneFile) { var _error3 = new _errors.MissingParameterError('zoneFile'); return Promise.reject(_error3); } var requestBody = { preorderTransaction: preorderTransaction, registerTransaction: registerTransaction, zoneFile: zoneFile }; var endpoint = TX_BROADCAST_SERVICE_REGISTRATION_ENDPOINT; return this.broadcastServiceFetchHelper(endpoint, requestBody); } }, { key: 'getFeeRate', value: function getFeeRate() { return fetch('https://bitcoinfees.earn.com/api/v1/fees/recommended').then(function (resp) { return resp.json(); }).then(function (rates) { return Math.floor(rates.fastestFee); }); } }, { key: 'countDustOutputs', value: function countDustOutputs() { throw new Error('Not implemented.'); } }, { key: 'getUTXOs', value: function getUTXOs(address) { var _this13 = this; return this.getNetworkedUTXOs(address).then(function (networkedUTXOs) { var returnSet = networkedUTXOs.concat(); if (_this13.includeUtxoMap.hasOwnProperty(address)) { returnSet = networkedUTXOs.concat(_this13.includeUtxoMap[address]); } // aaron: I am *well* aware this is O(n)*O(m) runtime // however, clients should clear the exclude set periodically var excludeSet = _this13.excludeUtxoSet; returnSet = returnSet.filter(function (utxo) { var inExcludeSet = excludeSet.reduce(function (inSet, utxoToCheck) { return inSet || utxoToCheck.tx_hash === utxo.tx_hash && utxoToCheck.tx_output_n === utxo.tx_output_n; }, false); return !inExcludeSet; }); return returnSet; }); } /** * This will modify the network's utxo set to include UTXOs * from the given transaction and exclude UTXOs *spent* in * that transaction * @param {String} txHex - the hex-encoded transaction to use * @return {void} no return value, this modifies the UTXO config state * @private */ }, { key: 'modifyUTXOSetFrom', value: function modifyUTXOSetFrom(txHex) { var _this14 = this; var tx = _bitcoinjsLib2.default.Transaction.fromHex(txHex); var excludeSet = this.excludeUtxoSet.concat(); tx.ins.forEach(function (utxoUsed) { var reverseHash = Buffer.from(utxoUsed.hash); reverseHash.reverse(); excludeSet.push({ tx_hash: reverseHash.toString('hex'), tx_output_n: utxoUsed.index }); }); this.excludeUtxoSet = excludeSet; var txHash = tx.getHash().reverse().toString('hex'); tx.outs.forEach(function (utxoCreated, txOutputN) { var isNullData = function isNullData(script) { try { _bitcoinjsLib2.default.payments.embed({ output: script }, { validate: true }); return true; } catch (_) { return false; } }; if (isNullData(utxoCreated.script)) { return; } var address = _bitcoinjsLib2.default.address.fromOutputScript(utxoCreated.script, _this14.layer1); var includeSet = []; if (_this14.includeUtxoMap.hasOwnProperty(address)) { includeSet = includeSet.concat(_this14.includeUtxoMap[address]); } includeSet.push({ tx_hash: txHash, confirmations: 0, value: utxoCreated.value, tx_output_n: txOutputN }); _this14.includeUtxoMap[address] = includeSet; }); } }, { key: 'resetUTXOs', value: function resetUTXOs(address) { delete this.includeUtxoMap[address]; this.excludeUtxoSet = []; } }, { key: 'getConsensusHash', value: function getConsensusHash() { return fetch(this.blockstackAPIUrl + '/v1/blockchains/bitcoin/consensus').then(function (resp) { return resp.json(); }).then(function (x) { return x.consensus_hash; }); } }, { key: 'getTransactionInfo', value: function getTransactionInfo(txHash) { return this.btc.getTransactionInfo(txHash); } }, { key: 'getBlockHeight', value: function getBlockHeight() { return this.btc.getBlockHeight(); } }, { key: 'getNetworkedUTXOs', value: function getNetworkedUTXOs(address) { return this.btc.getNetworkedUTXOs(address); } }]); return BlockstackNetwork; }(); var LocalRegtest = exports.LocalRegtest = function (_BlockstackNetwork) { _inherits(LocalRegtest, _BlockstackNetwork); function LocalRegtest(apiUrl, broadcastServiceUrl, bitcoinAPI) { _classCallCheck(this, LocalRegtest); return _possibleConstructorReturn(this, (LocalRegtest.__proto__ || Object.getPrototypeOf(LocalRegtest)).call(this, apiUrl, broadcastServiceUrl, bitcoinAPI, _bitcoinjsLib2.default.networks.testnet)); } _createClass(LocalRegtest, [{ key: 'getFeeRate', value: function getFeeRate() { return Promise.resolve(Math.floor(0.00001000 * SATOSHIS_PER_BTC)); } }]); return LocalRegtest; }(BlockstackNetwork); var BitcoindAPI = exports.BitcoindAPI = function (_BitcoinNetwork) { _inherits(BitcoindAPI, _BitcoinNetwork); function BitcoindAPI(bitcoindUrl, bitcoindCredentials) { _classCallCheck(this, BitcoindAPI); var _this16 = _possibleConstructorReturn(this, (BitcoindAPI.__proto__ || Object.getPrototypeOf(BitcoindAPI)).call(this)); _this16.bitcoindUrl = bitcoindUrl; _this16.bitcoindCredentials = bitcoindCredentials; _this16.importedBefore = {}; return _this16; } _createClass(BitcoindAPI, [{ key: 'broadcastTransaction', value: function broadcastTransaction(transaction) { var jsonRPC = { jsonrpc: '1.0', method: 'sendrawtransaction', params: [transaction] }; var authString = Buffer.from(this.bitcoindCredentials.username + ':' + this.bitcoindCredentials.password).toString('base64'); var headers = { Authorization: 'Basic ' + authString }; return fetch(this.bitcoindUrl, { method: 'POST', body: JSON.stringify(jsonRPC), headers: headers }).then(function (resp) { return resp.json(); }).then(function (respObj) { return respObj.result; }); } }, { key: 'getBlockHeight', value: function getBlockHeight() { var jsonRPC = { jsonrpc: '1.0', method: 'getblockcount' }; var authString = Buffer.from(this.bitcoindCredentials.username + ':' + this.bitcoindCredentials.password).toString('base64'); var headers = { Authorization: 'Basic ' + authString }; return fetch(this.bitcoindUrl, { method: 'POST', body: JSON.stringify(jsonRPC), headers: headers }).then(function (resp) { return resp.json(); }).then(function (respObj) { return respObj.result; }); } }, { key: 'getTransactionInfo', value: function getTransactionInfo(txHash) { var _this17 = this; var jsonRPC = { jsonrpc: '1.0', method: 'gettransaction', params: [txHash] }; var authString = Buffer.from(this.bitcoindCredentials.username + ':' + this.bitcoindCredentials.password).toString('base64'); var headers = { Authorization: 'Basic ' + authString }; return fetch(this.bitcoindUrl, { method: 'POST', body: JSON.stringify(jsonRPC), headers: headers }).then(function (resp) { return resp.json(); }).then(function (respObj) { return respObj.result; }).then(function (txInfo) { return txInfo.blockhash; }).then(function (blockhash) { var jsonRPCBlock = { jsonrpc: '1.0', method: 'getblockheader', params: [blockhash] }; headers.Authorization = 'Basic ' + authString; return fetch(_this17.bitcoindUrl, { method: 'POST', body: JSON.stringify(jsonRPCBlock), headers: headers }); }).then(function (resp) { return resp.json(); }).then(function (respObj) { if (!respObj || !respObj.result) { // unconfirmed throw new Error('Unconfirmed transaction'); } else { return { block_height: respObj.result.height }; } }); } }, { key: 'getNetworkedUTXOs', value: function getNetworkedUTXOs(address) { var _this18 = this; var jsonRPCImport = { jsonrpc: '1.0', method: 'importaddress', params: [address] }; var jsonRPCUnspent = { jsonrpc: '1.0', method: 'listunspent', params: [0, 9999999, [address]] }; var authString = Buffer.from(this.bitcoindCredentials.username + ':' + this.bitcoindCredentials.password).toString('base64'); var headers = { Authorization: 'Basic ' + authString }; var importPromise = this.importedBefore[address] ? Promise.resolve() : fetch(this.bitcoindUrl, { method: 'POST', body: JSON.stringify(jsonRPCImport), headers: headers }).then(function () { _this18.importedBefore[address] = true; }); return importPromise.then(function () { return fetch(_this18.bitcoindUrl, { method: 'POST', body: JSON.stringify(jsonRPCUnspent), headers: headers }); }).then(function (resp) { return resp.json(); }).then(function (x) { return x.result; }).then(function (utxos) { return utxos.map(function (x) { return Object({ value: Math.round(x.amount * SATOSHIS_PER_BTC), confirmations: x.confirmations, tx_hash: x.txid, tx_output_n: x.vout }); }); }); } }]); return BitcoindAPI; }(BitcoinNetwork); var InsightClient = exports.InsightClient = function (_BitcoinNetwork2) { _inherits(InsightClient, _BitcoinNetwork2); function InsightClient() { var insightUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'https://utxo.technofractal.com/'; _classCallCheck(this, InsightClient); var _this19 = _possibleConstructorReturn(this, (InsightClient.__proto__ || Object.getPrototypeOf(InsightClient)).call(this)); _this19.apiUrl = insightUrl; return _this19; } _createClass(InsightClient, [{ key: 'broadcastTransaction', value: function broadcastTransaction(transaction) { var jsonData = { tx: transaction }; return fetch(this.apiUrl + '/tx/send', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(jsonData) }).then(function (resp) { return resp.json(); }); } }, { key: 'getBlockHeight', value: function getBlockHeight() { return fetch(this.apiUrl + '/status').then(function (resp) { return resp.json(); }).then(function (status) { return status.blocks; }); } }, { key: 'getTransactionInfo', value: function getTransactionInfo(txHash) { var _this20 = this; return fetch(this.apiUrl + '/tx/' + txHash).then(function (resp) { return resp.json(); }).then(function (transactionInfo) { if (transactionInfo.error) { throw new Error('Error finding transaction: ' + transactionInfo.error); } return fetch(_this20.apiUrl + '/block/' + transactionInfo.blockHash); }).then(function (resp) { return resp.json(); }).then(function (blockInfo) { return { block_height: blockInfo.height }; }); } }, { key: 'getNetworkedUTXOs', value: function getNetworkedUTXOs(address) { return fetch(this.apiUrl + '/addr/' + address + '/utxo').then(function (resp) { return resp.json(); }).then(function (utxos) { return utxos.map(function (x) { return { value: x.satoshis, confirmations: x.confirmations, tx_hash: x.txid, tx_output_n: x.vout }; }); }); } }]); return InsightClient; }(BitcoinNetwork); var BlockchainInfoApi = exports.BlockchainInfoApi = function (_BitcoinNetwork3) { _inherits(BlockchainInfoApi, _BitcoinNetwork3); function BlockchainInfoApi() { var blockchainInfoUrl = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'https://blockchain.info'; _classCallCheck(this, BlockchainInfoApi); var _this21 = _possibleConstructorReturn(this, (BlockchainInfoApi.__proto__ || Object.getPrototypeOf(BlockchainInfoApi)).call(this)); _this21.utxoProviderUrl = blockchainInfoUrl; return _this21; } _createClass(BlockchainInfoApi, [{ key: 'getBlockHeight', value: function getBlockHeight() { return fetch(this.utxoProviderUrl + '/latestblock?cors=true').then(function (resp) { return resp.json(); }).then(function (blockObj) { return blockObj.height; }); } }, { key: 'getNetworkedUTXOs', value: function getNetworkedUTXOs(address) { return fetch(this.utxoProviderUrl + '/unspent?format=json&active=' + address + '&cors=true').then(function (resp) { if (resp.status === 500) { _logger.Logger.debug('UTXO provider 500 usually means no UTXOs: returning []'); return { unspent_outputs: [] }; } else { return resp.json(); } }).then(function (utxoJSON) { return utxoJSON.unspent_outputs; }).then(function (utxoList) { return utxoList.map(function (utxo) { var utxoOut = { value: utxo.value, tx_output_n: utxo.tx_output_n, confirmations: utxo.confirmations, tx_hash: utxo.tx_hash_big_endian }; return utxoOut; }); }); } }, { key: 'getTransactionInfo', value: function getTransactionInfo(txHash) { return fetch(this.utxoProviderUrl + '/rawtx/' + txHash + '?cors=true').then(function (resp) { if (resp.status === 200) { return resp.json(); } else { throw new Error('Could not lookup transaction info for \'' + txHash + '\'. Server error.'); } }).then(function (respObj) { return { block_height: respObj.block_height }; }); } }, { key: 'broadcastTransaction', value: function broadcastTransaction(transaction) { var form = new _formData2.default(); form.append('tx', transaction); return fetch(this.utxoProviderUrl + '/pushtx?cors=true', { method: 'POST', body: form }).then(function (resp) { var text = resp.text(); return text.then(function (respText) { if (respText.toLowerCase().indexOf('transaction submitted') >= 0) { var txHash = _bitcoinjsLib2.default.Transaction.fromHex(transaction).getHash().reverse().toString('hex'); // big_endian return txHash; } else { throw new _errors.RemoteServiceError(resp, 'Broadcast transaction failed with message: ' + respText); } }); }); } }]); return BlockchainInfoApi; }(BitcoinNetwork); var LOCAL_REGTEST = new LocalRegtest('http://localhost:16268', 'http://localhost:16269', new BitcoindAPI('http://localhost:18332/', { username: 'blockstack', password: 'blockstacksystem' })); var MAINNET_DEFAULT = new BlockstackNetwork('https://core.blockstack.org', 'https://broadcast.blockstack.org', new BlockchainInfoApi()); var network = exports.network = { BlockstackNetwork: BlockstackNetwork, LocalRegtest: LocalRegtest, BlockchainInfoApi: BlockchainInfoApi, BitcoindAPI: BitcoindAPI, InsightClient: InsightClient, defaults: { LOCAL_REGTEST: LOCAL_REGTEST, MAINNET_DEFAULT: MAINNET_DEFAULT } }; }).call(this,require("buffer").Buffer) },{"./errors":11,"./logger":14,"bigi":70,"bitcoinjs-lib":92,"buffer":179,"form-data":348,"ripemd160":456}],16:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _skeletons = require('./skeletons'); Object.defineProperty(exports, 'makePreorderSkeleton', { enumerable: true, get: function get() { return _skeletons.makePreorderSkeleton; } }); var _txbuild = require('./txbuild'); Object.defineProperty(exports, 'transactions', { enumerable: true, get: function get() { return _txbuild.transactions; } }); var _utils = require('./utils'); Object.keys(_utils).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _utils[key]; } }); }); var _signers = require('./signers'); Object.keys(_signers).forEach(function (key) { if (key === "default" || key === "__esModule") return; Object.defineProperty(exports, key, { enumerable: true, get: function get() { return _signers[key]; } }); }); var _safety = require('./safety'); Object.defineProperty(exports, 'safety', { enumerable: true, get: function get() { return _safety.safety; } }); },{"./safety":17,"./signers":18,"./skeletons":19,"./txbuild":20,"./utils":21}],17:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.safety = undefined; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _config = require('../config'); function isNameValid() { var fullyQualifiedName = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ''; var NAME_PART_RULE = /^[a-z0-9\-_+]+$/; var LENGTH_MAX_NAME = 37; if (!fullyQualifiedName || fullyQualifiedName.length > LENGTH_MAX_NAME) { return Promise.resolve(false); } var nameParts = fullyQualifiedName.split('.'); if (nameParts.length !== 2) { return Promise.resolve(false); } return Promise.resolve(nameParts.reduce(function (agg, namePart) { if (!agg) { return false; } else { return NAME_PART_RULE.test(namePart); } }, true)); } function isNamespaceValid(namespaceID) { var NAMESPACE_RULE = /^[a-z0-9\-_]{1,19}$/; return Promise.resolve(namespaceID.match(NAMESPACE_RULE) !== null); } function isNameAvailable(fullyQualifiedName) { return _config.config.network.getNameInfo(fullyQualifiedName).then(function () { return false; }).catch(function (e) { if (e.message === 'Name not found') { return true; } else { throw e; } }); } function isNamespaceAvailable(namespaceID) { return _config.config.network.getNamespaceInfo(namespaceID).then(function () { return false; }).catch(function (e) { if (e.message === 'Namespace not found') { return true; } else { throw e; } }); } function ownsName(fullyQualifiedName, ownerAddress) { return _config.config.network.getNameInfo(fullyQualifiedName).then(function (nameInfo) { return nameInfo.address === ownerAddress; }).catch(function (e) { if (e.message === 'Name not found') { return false; } else { throw e; } }); } function revealedNamespace(namespaceID, revealAddress) { return _config.config.network.getNamespaceInfo(namespaceID).then(function (namespaceInfo) { return namespaceInfo.recipient_address === revealAddress; }).catch(function (e) { if (e.message === 'Namespace not found') { return false; } else { throw e; } }); } function namespaceIsReady(namespaceID) { return _config.config.network.getNamespaceInfo(namespaceID).then(function (namespaceInfo) { return namespaceInfo.ready; }).catch(function (e) { if (e.message === 'Namespace not found') { return false; } else { throw e; } }); } function namespaceIsRevealed(namespaceID) { return _config.config.network.getNamespaceInfo(namespaceID).then(function (namespaceInfo) { return !namespaceInfo.ready; }).catch(function (e) { if (e.message === 'Namespace not found') { return false; } else { throw e; } }); } function isInGracePeriod(fullyQualifiedName) { var network = _config.config.network; return Promise.all([network.getNameInfo(fullyQualifiedName), network.getBlockHeight(), network.getGracePeriod(fullyQualifiedName)]).then(function (_ref) { var _ref2 = _slicedToArray(_ref, 3), nameInfo = _ref2[0], blockHeight = _ref2[1], gracePeriod = _ref2[2]; var expiresAt = nameInfo.expire_block; return blockHeight >= expiresAt && blockHeight < gracePeriod + expiresAt; }).catch(function (e) { if (e.message === 'Name not found') { return false; } else { throw e; } }); } function addressCanReceiveName(address) { return _config.config.network.getNamesOwned(address).then(function (names) { return Promise.all(names.map(function (name) { return isNameValid(name); })).then(function (validNames) { return validNames.filter(function (nameValid) { return nameValid; }).length < 25; }); }); } function isAccountSpendable(address, tokenType, blockHeight) { return _config.config.network.getAccountStatus(address, tokenType).then(function (accountStatus) { return accountStatus.transfer_send_block_id >= blockHeight; }); } var safety = exports.safety = { addressCanReceiveName: addressCanReceiveName, isInGracePeriod: isInGracePeriod, ownsName: ownsName, isNameAvailable: isNameAvailable, isNameValid: isNameValid, isNamespaceValid: isNamespaceValid, isNamespaceAvailable: isNamespaceAvailable, revealedNamespace: revealedNamespace, namespaceIsReady: namespaceIsReady, namespaceIsRevealed: namespaceIsRevealed, isAccountSpendable: isAccountSpendable }; },{"../config":8}],18:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.PubkeyHashSigner = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _bitcoinjsLib = require('bitcoinjs-lib'); var _bitcoinjsLib2 = _interopRequireDefault(_bitcoinjsLib); var _utils = require('../utils'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } /** * Class representing a transaction signer for pubkeyhash addresses * (a.k.a. single-sig addresses) * @private */ var PubkeyHashSigner = exports.PubkeyHashSigner = function () { function PubkeyHashSigner(ecPair) { _classCallCheck(this, PubkeyHashSigner); this.ecPair = ecPair; } _createClass(PubkeyHashSigner, [{ key: 'signerVersion', value: function signerVersion() { return 1; } }, { key: 'getAddress', value: function getAddress() { var _this = this; return Promise.resolve().then(function () { return (0, _utils.ecPairToAddress)(_this.ecPair); }); } }, { key: 'signTransaction', value: function signTransaction(transaction, inputIndex) { var _this2 = this; return Promise.resolve().then(function () { transaction.sign(inputIndex, _this2.ecPair); }); } }], [{ key: 'fromHexString', value: function fromHexString(keyHex) { return new PubkeyHashSigner((0, _utils.hexStringToECPair)(keyHex)); } }]); return PubkeyHashSigner; }(); },{"../utils":46,"bitcoinjs-lib":92}],19:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.BlockstackNamespace = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); exports.makePreorderSkeleton = makePreorderSkeleton; exports.makeRegisterSkeleton = makeRegisterSkeleton; exports.makeRenewalSkeleton = makeRenewalSkeleton; exports.makeTransferSkeleton = makeTransferSkeleton; exports.makeUpdateSkeleton = makeUpdateSkeleton; exports.makeRevokeSkeleton = makeRevokeSkeleton; exports.makeNamespacePreorderSkeleton = makeNamespacePreorderSkeleton; exports.makeNamespaceRevealSkeleton = makeNamespaceRevealSkeleton; exports.makeNamespaceReadySkeleton = makeNamespaceReadySkeleton; exports.makeNameImportSkeleton = makeNameImportSkeleton; exports.makeAnnounceSkeleton = makeAnnounceSkeleton; exports.makeTokenTransferSkeleton = makeTokenTransferSkeleton; var _bitcoinjsLib = require('bitcoinjs-lib'); var _bitcoinjsLib2 = _interopRequireDefault(_bitcoinjsLib); var _bigi = require('bigi'); var _bigi2 = _interopRequireDefault(_bigi); var _utils = require('./utils'); var _config = require('../config'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } // todo : add name length / character verification // support v1 and v2 price API endpoint return values var BlockstackNamespace = exports.BlockstackNamespace = function () { function BlockstackNamespace(namespaceID) { _classCallCheck(this, BlockstackNamespace); if (namespaceID.length > 19) { throw new Error('Namespace ID too long (19 chars max)'); } if (!namespaceID.match('[0123456789abcdefghijklmnopqrstuvwxyz_-]+')) { throw new Error('Namespace ID can only use characters 0123456789abcdefghijklmnopqrstuvwxyz-_'); } this.namespaceID = namespaceID; this.version = -1; this.lifetime = -1; this.coeff = -1; this.base = -1; this.buckets = [-1]; this.nonalphaDiscount = -1; this.noVowelDiscount = -1; } _createClass(BlockstackNamespace, [{ key: 'check', value: function check() { try { this.setVersion(this.version); this.setLifetime(this.lifetime); this.setCoeff(this.coeff); this.setBase(this.base); this.setBuckets(this.buckets); this.setNonalphaDiscount(this.nonalphaDiscount); this.setNoVowelDiscount(this.noVowelDiscount); return true; } catch (e) { return false; } } }, { key: 'setVersion', value: function setVersion(version) { if (version < 0 || version > Math.pow(2, 16) - 1) { throw new Error('Invalid version: must be a 16-bit number'); } this.version = version; } }, { key: 'setLifetime', value: function setLifetime(lifetime) { if (lifetime < 0 || lifetime > Math.pow(2, 32) - 1) { throw new Error('Invalid lifetime: must be a 32-bit number'); } this.lifetime = lifetime; } }, { key: 'setCoeff', value: function setCoeff(coeff) { if (coeff < 0 || coeff > 255) { throw new Error('Invalid coeff: must be an 8-bit number'); } this.coeff = coeff; } }, { key: 'setBase', value: function setBase(base) { if (base < 0 || base > 255) { throw new Error('Invalid base: must be an 8-bit number'); } this.base = base; } }, { key: 'setBuckets', value: function setBuckets(buckets) { if (buckets.length !== 16) { throw new Error('Invalid buckets: must have 16 entries'); } for (var i = 0; i < buckets.length; i++) { if (buckets[i] < 0 || buckets[i] > 15) { throw new Error('Invalid buckets: must be 4-bit numbers'); } } this.buckets = buckets.slice(0); } }, { key: 'setNonalphaDiscount', value: function setNonalphaDiscount(nonalphaDiscount) { if (nonalphaDiscount <= 0 || nonalphaDiscount > 15) { throw new Error('Invalid nonalphaDiscount: must be a positive 4-bit number'); } this.nonalphaDiscount = nonalphaDiscount; } }, { key: 'setNoVowelDiscount', value: function setNoVowelDiscount(noVowelDiscount) { if (noVowelDiscount <= 0 || noVowelDiscount > 15) { throw new Error('Invalid noVowelDiscount: must be a positive 4-bit number'); } this.noVowelDiscount = noVowelDiscount; } }, { key: 'toHexPayload', value: function toHexPayload() { var lifeHex = ('00000000' + this.lifetime.toString(16)).slice(-8); var coeffHex = ('00' + this.coeff.toString(16)).slice(-2); var baseHex = ('00' + this.base.toString(16)).slice(-2); var bucketHex = this.buckets.map(function (b) { return b.toString(16); }).reduce(function (b1, b2) { return b1 + b2; }, ''); var discountHex = this.nonalphaDiscount.toString(16) + this.noVowelDiscount.toString(16); var versionHex = ('0000' + this.version.toString(16)).slice(-4); var namespaceIDHex = new Buffer(this.namespaceID).toString('hex'); return lifeHex + coeffHex + baseHex + bucketHex + discountHex + versionHex + namespaceIDHex; } }]); return BlockstackNamespace; }(); function asAmountV2(amount) { // convert an AmountType v1 or v2 to an AmountTypeV2. // the "units" of a v1 amount type are always 'BTC' if (typeof amount === 'number') { return { units: 'BTC', amount: _bigi2.default.fromByteArrayUnsigned(String(amount)) }; } else { return { units: amount.units, amount: amount.amount }; } } function makeTXbuilder() { var txb = new _bitcoinjsLib2.default.TransactionBuilder(_config.config.network.layer1); txb.setVersion(1); return txb; } function opEncode(opcode) { // NOTE: must *always* a 3-character string var res = '' + _config.config.network.MAGIC_BYTES + opcode; if (res.length !== 3) { throw new Error('Runtime error: invalid MAGIC_BYTES'); } return res; } function makePreorderSkeleton(fullyQualifiedName, consensusHash, preorderAddress, burnAddress, burn) { var registerAddress = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; // Returns a preorder tx skeleton. // with 3 outputs : 1. the Blockstack Preorder OP_RETURN data // 2. the Preorder's change address (5500 satoshi minimum) // 3. the BURN // // 0 2 3 23 39 47 66 // |-----|--|--------------------------------------|--------------|-----------|-------------| // magic op hash160(fqn,scriptPubkey,registerAddr) consensus hash token burn token type // (optional) (optional) // // output 0: name preorder code // output 1: preorder address // output 2: burn address // // Returns an unsigned serialized transaction. var burnAmount = asAmountV2(burn); var network = _config.config.network; var nameBuff = Buffer.from((0, _utils.decodeB40)(fullyQualifiedName), 'hex'); // base40 var scriptPublicKey = _bitcoinjsLib2.default.address.toOutputScript(preorderAddress, network.layer1); var dataBuffers = [nameBuff, scriptPublicKey]; if (!!registerAddress) { var registerBuff = Buffer.from(registerAddress, 'ascii'); dataBuffers.push(registerBuff); } var dataBuff = Buffer.concat(dataBuffers); var hashed = (0, _utils.hash160)(dataBuff); var opReturnBufferLen = burnAmount.units === 'BTC' ? 39 : 66; var opReturnBuffer = Buffer.alloc(opReturnBufferLen); opReturnBuffer.write(opEncode('?'), 0, 3, 'ascii'); hashed.copy(opReturnBuffer, 3); opReturnBuffer.write(consensusHash, 23, 16, 'hex'); if (burnAmount.units !== 'BTC') { var burnHex = burnAmount.amount.toHex(); if (burnHex.length > 16) { // exceeds 2**64; can't fit throw new Error('Cannot preorder \'' + fullyQualifiedName + '\': cannot fit price into 8 bytes'); } var paddedBurnHex = ('0000000000000000' + burnHex).slice(-16); opReturnBuffer.write(paddedBurnHex, 39, 8, 'hex'); opReturnBuffer.write(burnAmount.units, 47, burnAmount.units.length, 'ascii'); } var nullOutput = _bitcoinjsLib2.default.payments.embed({ data: [opReturnBuffer] }).output; var tx = makeTXbuilder(); tx.addOutput(nullOutput, 0); tx.addOutput(preorderAddress, _utils.DUST_MINIMUM); if (burnAmount.units === 'BTC') { var btcBurnAmount = parseInt(burnAmount.amount.toHex(), 16); tx.addOutput(burnAddress, btcBurnAmount); } else { tx.addOutput(burnAddress, _utils.DUST_MINIMUM); } return tx.buildIncomplete(); } function makeRegisterSkeleton(fullyQualifiedName, ownerAddress) { var valueHash = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var burnTokenAmountHex = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; // Returns a register tx skeleton. // with 2 outputs : 1. The register OP_RETURN // 2. The owner address (can be different from REGISTER address on renewals) // You MUST make the first input a UTXO from the current OWNER *or* the // funder of the PREORDER // in the case of a renewal, this would need to be modified to include a change address // as output (3) before the burn output (4) /* Formats No zonefile hash, and pay with BTC: 0 2 3 39 |----|--|----------------------------------| magic op name.ns_id (up to 37 bytes) With zonefile hash, and pay with BTC: 0 2 3 39 59 |----|--|----------------------------------|-------------------| magic op name.ns_id (37 bytes, 0-padded) zone file hash output 0: name registration code output 1: owner address */ var payload = void 0; if (!!burnTokenAmountHex && !valueHash) { // empty value hash valueHash = '0000000000000000000000000000000000000000'; } if (!!valueHash) { if (valueHash.length !== 40) { throw new Error('Value hash length incorrect. Expecting 20-bytes, hex-encoded'); } if (!!burnTokenAmountHex) { if (burnTokenAmountHex.length !== 16) { throw new Error('Burn field length incorrect. Expecting 8-bytes, hex-encoded'); } } var payloadLen = burnTokenAmountHex ? 65 : 57; payload = Buffer.alloc(payloadLen, 0); payload.write(fullyQualifiedName, 0, 37, 'ascii'); payload.write(valueHash, 37, 20, 'hex'); if (!!burnTokenAmountHex) { payload.write(burnTokenAmountHex, 57, 8, 'hex'); } } else { payload = Buffer.from(fullyQualifiedName, 'ascii'); } var opReturnBuffer = Buffer.concat([Buffer.from(opEncode(':'), 'ascii'), payload]); var nullOutput = _bitcoinjsLib2.default.payments.embed({ data: [opReturnBuffer] }).output; var tx = makeTXbuilder(); tx.addOutput(nullOutput, 0); tx.addOutput(ownerAddress, _utils.DUST_MINIMUM); return tx.buildIncomplete(); } function makeRenewalSkeleton(fullyQualifiedName, nextOwnerAddress, lastOwnerAddress, burnAddress, burn) { var valueHash = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; /* Formats No zonefile hash, and pay with BTC: 0 2 3 39 |----|--|----------------------------------| magic op name.ns_id (up to 37 bytes) With zonefile hash, and pay with BTC: 0 2 3 39 59 |----|--|----------------------------------|-------------------| magic op name.ns_id (37 bytes, 0-padded) zone file hash With renewal payment in a token: (for register, tokens burned is not included) (for renew, tokens burned is the number of tokens to burn) 0 2 3 39 59 67 |----|--|----------------------------------|-------------------|------------------------------| magic op name.ns_id (37 bytes, 0-padded) zone file hash tokens burned (big-endian) output 0: renewal code output 1: new owner address output 2: current owner address output 3: burn address */ var burnAmount = asAmountV2(burn); var network = _config.config.network; var burnTokenAmount = burnAmount.units === 'BTC' ? null : burnAmount.amount; var burnBTCAmount = burnAmount.units === 'BTC' ? parseInt(burnAmount.amount.toHex(), 16) : _utils.DUST_MINIMUM; var burnTokenHex = null; if (!!burnTokenAmount) { var burnHex = burnTokenAmount.toHex(); if (burnHex.length > 16) { // exceeds 2**64; can't fit throw new Error('Cannot renew \'' + fullyQualifiedName + '\': cannot fit price into 8 bytes'); } burnTokenHex = ('0000000000000000' + burnHex).slice(-16); } var registerTX = makeRegisterSkeleton(fullyQualifiedName, nextOwnerAddress, valueHash, burnTokenHex); var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(registerTX, network.layer1); txB.addOutput(lastOwnerAddress, _utils.DUST_MINIMUM); txB.addOutput(burnAddress, burnBTCAmount); return txB.buildIncomplete(); } function makeTransferSkeleton(fullyQualifiedName, consensusHash, newOwner) { var keepZonefile = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; // Returns a transfer tx skeleton. // with 2 outputs : 1. the Blockstack Transfer OP_RETURN data // 2. the new owner with a DUST_MINIMUM value (5500 satoshi) // // You MUST make the first input a UTXO from the current OWNER // // Returns an unsigned serialized transaction. /* Format 0 2 3 4 20 36 |-----|--|----|-------------------|---------------| magic op keep hash128(name.ns_id) consensus hash data? output 0: transfer code output 1: new owner */ var opRet = Buffer.alloc(36); var keepChar = '~'; if (keepZonefile) { keepChar = '>'; } opRet.write(opEncode('>'), 0, 3, 'ascii'); opRet.write(keepChar, 3, 1, 'ascii'); var hashed = (0, _utils.hash128)(Buffer.from(fullyQualifiedName, 'ascii')); hashed.copy(opRet, 4); opRet.write(consensusHash, 20, 16, 'hex'); var opRetPayload = _bitcoinjsLib2.default.payments.embed({ data: [opRet] }).output; var tx = makeTXbuilder(); tx.addOutput(opRetPayload, 0); tx.addOutput(newOwner, _utils.DUST_MINIMUM); return tx.buildIncomplete(); } function makeUpdateSkeleton(fullyQualifiedName, consensusHash, valueHash) { // Returns an update tx skeleton. // with 1 output : 1. the Blockstack update OP_RETURN // // You MUST make the first input a UTXO from the current OWNER // // Returns an unsigned serialized transaction. // // output 0: the revoke code /* Format: 0 2 3 19 39 |-----|--|-----------------------------------|-----------------------| magic op hash128(name.ns_id,consensus hash) hash160(data) output 0: update code */ var opRet = Buffer.alloc(39); var nameBuff = Buffer.from(fullyQualifiedName, 'ascii'); var consensusBuff = Buffer.from(consensusHash, 'ascii'); var hashedName = (0, _utils.hash128)(Buffer.concat([nameBuff, consensusBuff])); opRet.write(opEncode('+'), 0, 3, 'ascii'); hashedName.copy(opRet, 3); opRet.write(valueHash, 19, 20, 'hex'); var opRetPayload = _bitcoinjsLib2.default.payments.embed({ data: [opRet] }).output; var tx = makeTXbuilder(); tx.addOutput(opRetPayload, 0); return tx.buildIncomplete(); } function makeRevokeSkeleton(fullyQualifiedName) { // Returns a revoke tx skeleton // with 1 output: 1. the Blockstack revoke OP_RETURN // // You MUST make the first input a UTXO from the current OWNER // // Returns an unsigned serialized transaction /* Format: 0 2 3 39 |----|--|-----------------------------| magic op name.ns_id (37 bytes) output 0: the revoke code */ var opRet = Buffer.alloc(3); var nameBuff = Buffer.from(fullyQualifiedName, 'ascii'); opRet.write(opEncode('~'), 0, 3, 'ascii'); var opReturnBuffer = Buffer.concat([opRet, nameBuff]); var nullOutput = _bitcoinjsLib2.default.payments.embed({ data: [opReturnBuffer] }).output; var tx = makeTXbuilder(); tx.addOutput(nullOutput, 0); return tx.buildIncomplete(); } function makeNamespacePreorderSkeleton(namespaceID, consensusHash, preorderAddress, registerAddress, burn) { // Returns a namespace preorder tx skeleton. // Returns an unsigned serialized transaction. /* Formats: Without STACKS: 0 2 3 23 39 |-----|---|--------------------------------------|----------------| magic op hash(ns_id,script_pubkey,reveal_addr) consensus hash with STACKs: 0 2 3 23 39 47 |-----|---|--------------------------------------|----------------|--------------------------| magic op hash(ns_id,script_pubkey,reveal_addr) consensus hash token fee (big-endian) output 0: namespace preorder code output 1: change address otuput 2: burn address */ var burnAmount = asAmountV2(burn); if (burnAmount.units !== 'BTC' && burnAmount.units !== 'STACKS') { throw new Error('Invalid burnUnits ' + burnAmount.units); } var network = _config.config.network; var burnAddress = network.getDefaultBurnAddress(); var namespaceIDBuff = Buffer.from((0, _utils.decodeB40)(namespaceID), 'hex'); // base40 var scriptPublicKey = _bitcoinjsLib2.default.address.toOutputScript(preorderAddress, network.layer1); var registerBuff = Buffer.from(registerAddress, 'ascii'); var dataBuffers = [namespaceIDBuff, scriptPublicKey, registerBuff]; var dataBuff = Buffer.concat(dataBuffers); var hashed = (0, _utils.hash160)(dataBuff); var btcBurnAmount = _utils.DUST_MINIMUM; var opReturnBufferLen = 39; if (burnAmount.units === 'STACKS') { opReturnBufferLen = 47; } else { btcBurnAmount = parseInt(burnAmount.amount.toHex(), 16); } var opReturnBuffer = Buffer.alloc(opReturnBufferLen); opReturnBuffer.write(opEncode('*'), 0, 3, 'ascii'); hashed.copy(opReturnBuffer, 3); opReturnBuffer.write(consensusHash, 23, 16, 'hex'); if (burnAmount.units === 'STACKS') { var burnHex = burnAmount.amount.toHex(); var paddedBurnHex = ('0000000000000000' + burnHex).slice(-16); opReturnBuffer.write(paddedBurnHex, 39, 8, 'hex'); } var nullOutput = _bitcoinjsLib2.default.payments.embed({ data: [opReturnBuffer] }).output; var tx = makeTXbuilder(); tx.addOutput(nullOutput, 0); tx.addOutput(preorderAddress, _utils.DUST_MINIMUM); tx.addOutput(burnAddress, btcBurnAmount); return tx.buildIncomplete(); } function makeNamespaceRevealSkeleton(namespace, revealAddress) { /* Format: 0 2 3 7 8 9 10 11 12 13 14 15 16 17 18 20 39 |-----|---|----|-----|-----|----|----|----|----|----|-----|-----|-----|--------|-------|-------| magic op life coeff. base 1-2 3-4 5-6 7-8 9-10 11-12 13-14 15-16 nonalpha version ns ID bucket exponents no-vowel discounts output 0: namespace reveal code output 1: reveal address */ var hexPayload = namespace.toHexPayload(); var opReturnBuffer = Buffer.alloc(3 + hexPayload.length / 2); opReturnBuffer.write(opEncode('&'), 0, 3, 'ascii'); opReturnBuffer.write(hexPayload, 3, hexPayload.length / 2, 'hex'); var nullOutput = _bitcoinjsLib2.default.payments.embed({ data: [opReturnBuffer] }).output; var tx = makeTXbuilder(); tx.addOutput(nullOutput, 0); tx.addOutput(revealAddress, _utils.DUST_MINIMUM); return tx.buildIncomplete(); } function makeNamespaceReadySkeleton(namespaceID) { /* Format: 0 2 3 4 23 |-----|--|--|------------| magic op . ns_id output 0: namespace ready code */ var opReturnBuffer = Buffer.alloc(3 + namespaceID.length + 1); opReturnBuffer.write(opEncode('!'), 0, 3, 'ascii'); opReturnBuffer.write('.' + namespaceID, 3, namespaceID.length + 1, 'ascii'); var nullOutput = _bitcoinjsLib2.default.payments.embed({ data: [opReturnBuffer] }).output; var tx = makeTXbuilder(); tx.addOutput(nullOutput, 0); return tx.buildIncomplete(); } function makeNameImportSkeleton(name, recipientAddr, zonefileHash) { /* Format: 0 2 3 39 |----|--|-----------------------------| magic op name.ns_id (37 bytes) Output 0: the OP_RETURN Output 1: the recipient Output 2: the zonefile hash */ if (zonefileHash.length !== 40) { throw new Error('Invalid zonefile hash: must be 20 bytes hex-encoded'); } var network = _config.config.network; var opReturnBuffer = Buffer.alloc(3 + name.length); opReturnBuffer.write(opEncode(';'), 0, 3, 'ascii'); opReturnBuffer.write(name, 3, name.length, 'ascii'); var nullOutput = _bitcoinjsLib2.default.payments.embed({ data: [opReturnBuffer] }).output; var tx = makeTXbuilder(); var zonefileHashB58 = _bitcoinjsLib2.default.address.toBase58Check(new Buffer(zonefileHash, 'hex'), network.layer1.pubKeyHash); tx.addOutput(nullOutput, 0); tx.addOutput(recipientAddr, _utils.DUST_MINIMUM); tx.addOutput(zonefileHashB58, _utils.DUST_MINIMUM); return tx.buildIncomplete(); } function makeAnnounceSkeleton(messageHash) { /* Format: 0 2 3 23 |----|--|-----------------------------| magic op message hash (160-bit) output 0: the OP_RETURN */ if (messageHash.length !== 40) { throw new Error('Invalid message hash: must be 20 bytes hex-encoded'); } var opReturnBuffer = Buffer.alloc(3 + messageHash.length / 2); opReturnBuffer.write(opEncode('#'), 0, 3, 'ascii'); opReturnBuffer.write(messageHash, 3, messageHash.length / 2, 'hex'); var nullOutput = _bitcoinjsLib2.default.payments.embed({ data: [opReturnBuffer] }).output; var tx = makeTXbuilder(); tx.addOutput(nullOutput, 0); return tx.buildIncomplete(); } function makeTokenTransferSkeleton(recipientAddress, consensusHash, tokenType, tokenAmount, scratchArea) { /* Format: 0 2 3 19 38 46 80 |-----|--|--------------|----------|-----------|-------------------------| magic op consensus_hash token_type amount (BE) scratch area (ns_id) output 0: token transfer code output 1: recipient address */ if (scratchArea.length > 34) { throw new Error('Invalid scratch area: must be no more than 34 bytes'); } var opReturnBuffer = Buffer.alloc(46 + scratchArea.length); var tokenTypeHex = new Buffer(tokenType).toString('hex'); var tokenTypeHexPadded = ('00000000000000000000000000000000000000' + tokenTypeHex).slice(-38); var tokenValueHex = tokenAmount.toHex(); if (tokenValueHex.length > 16) { // exceeds 2**64; can't fit throw new Error('Cannot send tokens: cannot fit ' + tokenAmount.toString() + ' into 8 bytes'); } var tokenValueHexPadded = ('0000000000000000' + tokenValueHex).slice(-16); opReturnBuffer.write(opEncode('$'), 0, 3, 'ascii'); opReturnBuffer.write(consensusHash, 3, consensusHash.length / 2, 'hex'); opReturnBuffer.write(tokenTypeHexPadded, 19, tokenTypeHexPadded.length / 2, 'hex'); opReturnBuffer.write(tokenValueHexPadded, 38, tokenValueHexPadded.length / 2, 'hex'); opReturnBuffer.write(scratchArea, 46, scratchArea.length, 'ascii'); var nullOutput = _bitcoinjsLib2.default.payments.embed({ data: [opReturnBuffer] }).output; var tx = makeTXbuilder(); tx.addOutput(nullOutput, 0); tx.addOutput(recipientAddress, _utils.DUST_MINIMUM); return tx.buildIncomplete(); } }).call(this,require("buffer").Buffer) },{"../config":8,"./utils":21,"bigi":70,"bitcoinjs-lib":92,"buffer":179}],20:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.transactions = undefined; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); var _bitcoinjsLib = require('bitcoinjs-lib'); var _bitcoinjsLib2 = _interopRequireDefault(_bitcoinjsLib); var _bigi = require('bigi'); var _bigi2 = _interopRequireDefault(_bigi); var _utils = require('./utils'); var _skeletons = require('./skeletons'); var _config = require('../config'); var _errors = require('../errors'); var _signers = require('./signers'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var dummyConsensusHash = 'aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa'; var dummyZonefileHash = 'ffffffffffffffffffffffffffffffffffffffff'; function addOwnerInput(utxos, ownerAddress, txB) { var addChangeOut = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : true; // add an owner UTXO and a change out. if (utxos.length <= 0) { throw new Error('Owner has no UTXOs for UPDATE.'); } utxos.sort(function (a, b) { return a.value - b.value; }); var ownerUTXO = utxos[0]; var ownerInput = txB.addInput(ownerUTXO.tx_hash, ownerUTXO.tx_output_n); if (addChangeOut) { txB.addOutput(ownerAddress, ownerUTXO.value); } return { index: ownerInput, value: ownerUTXO.value }; } function fundTransaction(txB, paymentAddress, utxos, feeRate, inAmounts) { var changeIndex = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; // change index for the payer. if (changeIndex === null) { changeIndex = txB.addOutput(paymentAddress, _utils.DUST_MINIMUM); } // fund the transaction fee. var txFee = (0, _utils.estimateTXBytes)(txB, 0, 0) * feeRate; var outAmounts = (0, _utils.sumOutputValues)(txB); var change = (0, _utils.addUTXOsToFund)(txB, utxos, txFee + outAmounts - inAmounts, feeRate); txB.__tx.outs[changeIndex].value += change; return txB; } function returnTransactionHex(txB) { var buildIncomplete = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; if (buildIncomplete) { return txB.buildIncomplete().toHex(); } else { return txB.build().toHex(); } } function getTransactionSigner(input) { if (typeof input === 'string') { return _signers.PubkeyHashSigner.fromHexString(input); } else { return input; } } /** * Estimates cost of a preorder transaction for a domain name. * @param {String} fullyQualifiedName - the name to preorder * @param {String} destinationAddress - the address to receive the name (this * must be passed as the 'registrationAddress' in the register transaction) * @param {String} paymentAddress - the address funding the preorder * @param {Number} paymentUtxos - the number of UTXOs we expect will be required * from the payment address. * @returns {Promise} - a promise which resolves to the satoshi cost to fund * the preorder. This includes a 5500 satoshi dust output for the preorder. * Even though this is a change output, the payer must supply enough funds * to generate this output, so we include it in the cost. * @private */ function estimatePreorder(fullyQualifiedName, destinationAddress, paymentAddress) { var paymentUtxos = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; var network = _config.config.network; var preorderPromise = network.getNamePrice(fullyQualifiedName).then(function (namePrice) { return (0, _skeletons.makePreorderSkeleton)(fullyQualifiedName, dummyConsensusHash, paymentAddress, network.getDefaultBurnAddress(), namePrice, destinationAddress); }); return Promise.all([network.getFeeRate(), preorderPromise]).then(function (_ref) { var _ref2 = _slicedToArray(_ref, 2), feeRate = _ref2[0], preorderTX = _ref2[1]; var outputsValue = (0, _utils.sumOutputValues)(preorderTX); var txFee = feeRate * (0, _utils.estimateTXBytes)(preorderTX, paymentUtxos, 0); return txFee + outputsValue; }); } /** * Estimates cost of a register transaction for a domain name. * @param {String} fullyQualifiedName - the name to register * @param {String} registerAddress - the address to receive the name * @param {String} paymentAddress - the address funding the register * @param {Boolean} includingZonefile - whether or not we will broadcast * a zonefile hash as part of the register * @param {Number} paymentUtxos - the number of UTXOs we expect will be required * from the payment address. * @returns {Promise} - a promise which resolves to the satoshi cost to fund * the register. * @private */ function estimateRegister(fullyQualifiedName, registerAddress, paymentAddress) { var includingZonefile = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var paymentUtxos = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1; var network = _config.config.network; var valueHash = void 0; if (includingZonefile) { valueHash = dummyZonefileHash; } var registerTX = (0, _skeletons.makeRegisterSkeleton)(fullyQualifiedName, registerAddress, valueHash); return network.getFeeRate().then(function (feeRate) { var outputsValue = (0, _utils.sumOutputValues)(registerTX); // 1 additional output for payer change var txFee = feeRate * (0, _utils.estimateTXBytes)(registerTX, paymentUtxos, 1); return txFee + outputsValue; }); } /** * Estimates cost of an update transaction for a domain name. * @param {String} fullyQualifiedName - the name to update * @param {String} ownerAddress - the owner of the name * @param {String} paymentAddress - the address funding the update * @param {Number} paymentUtxos - the number of UTXOs we expect will be required * from the payment address. * @returns {Promise} - a promise which resolves to the satoshi cost to fund * the update. * @private */ function estimateUpdate(fullyQualifiedName, ownerAddress, paymentAddress) { var paymentUtxos = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; var network = _config.config.network; var updateTX = (0, _skeletons.makeUpdateSkeleton)(fullyQualifiedName, dummyConsensusHash, dummyZonefileHash); return network.getFeeRate().then(function (feeRate) { var outputsValue = (0, _utils.sumOutputValues)(updateTX); // 1 additional input for the owner // 2 additional outputs for owner / payer change var txFee = feeRate * (0, _utils.estimateTXBytes)(updateTX, 1 + paymentUtxos, 2); return txFee + outputsValue; }); } /** * Estimates cost of an transfer transaction for a domain name. * @param {String} fullyQualifiedName - the name to transfer * @param {String} destinationAddress - the next owner of the name * @param {String} ownerAddress - the current owner of the name * @param {String} paymentAddress - the address funding the transfer * @param {Number} paymentUtxos - the number of UTXOs we expect will be required * from the payment address. * @returns {Promise} - a promise which resolves to the satoshi cost to fund * the transfer. * @private */ function estimateTransfer(fullyQualifiedName, destinationAddress, ownerAddress, paymentAddress) { var paymentUtxos = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1; var network = _config.config.network; var transferTX = (0, _skeletons.makeTransferSkeleton)(fullyQualifiedName, dummyConsensusHash, destinationAddress); return network.getFeeRate().then(function (feeRate) { var outputsValue = (0, _utils.sumOutputValues)(transferTX); // 1 additional input for the owner // 2 additional outputs for owner / payer change var txFee = feeRate * (0, _utils.estimateTXBytes)(transferTX, 1 + paymentUtxos, 2); return txFee + outputsValue; }); } /** * Estimates cost of an transfer transaction for a domain name. * @param {String} fullyQualifiedName - the name to renew * @param {String} destinationAddress - the next owner of the name * @param {String} ownerAddress - the current owner of the name * @param {String} paymentAddress - the address funding the transfer * @param {Boolean} includingZonefile - whether or not we will broadcast a zonefile hash in the renewal operation * @param {Number} paymentUtxos - the number of UTXOs we expect will be required * from the payment address. * @returns {Promise} - a promise which resolves to the satoshi cost to fund * the transfer. * @private */ function estimateRenewal(fullyQualifiedName, destinationAddress, ownerAddress, paymentAddress) { var includingZonefile = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var paymentUtxos = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 1; var network = _config.config.network; var valueHash = void 0; if (includingZonefile) { valueHash = dummyZonefileHash; } var renewalPromise = network.getNamePrice(fullyQualifiedName).then(function (namePrice) { return (0, _skeletons.makeRenewalSkeleton)(fullyQualifiedName, destinationAddress, ownerAddress, network.getDefaultBurnAddress(), namePrice, valueHash); }); return Promise.all([network.getFeeRate(), renewalPromise]).then(function (_ref3) { var _ref4 = _slicedToArray(_ref3, 2), feeRate = _ref4[0], renewalTX = _ref4[1]; var outputsValue = (0, _utils.sumOutputValues)(renewalTX); // 1 additional input for the owner // and renewal skeleton includes all outputs for owner change, but not for payer change. var txFee = feeRate * (0, _utils.estimateTXBytes)(renewalTX, 1 + paymentUtxos, 1); return txFee + outputsValue - 5500; // don't count the dust change for old owner. }); } /** * Estimates cost of a revoke transaction for a domain name. * @param {String} fullyQualifiedName - the name to revoke * @param {String} ownerAddress - the current owner of the name * @param {String} paymentAddress the address funding the revoke * @param {Number} paymentUtxos - the number of UTXOs we expect will be required * from the payment address. * @returns {Promise} - a promise which resolves to the satoshi cost to fund the * revoke. * @private */ function estimateRevoke(fullyQualifiedName, ownerAddress, paymentAddress) { var paymentUtxos = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; var network = _config.config.network; var revokeTX = (0, _skeletons.makeRevokeSkeleton)(fullyQualifiedName); return Promise.all([network.getFeeRate()]).then(function (_ref5) { var _ref6 = _slicedToArray(_ref5, 1), feeRate = _ref6[0]; var outputsValue = (0, _utils.sumOutputValues)(revokeTX); // 1 additional input for owner // 1 additional output for payer change var txFee = feeRate * (0, _utils.estimateTXBytes)(revokeTX, 1 + paymentUtxos, 2); return txFee + outputsValue; }); } /** * Estimates cost of a namespace preorder transaction for a namespace * @param {String} namespaceID - the namespace to preorder * @param {String} revealAddress - the address to receive the namespace (this * must be passed as the 'revealAddress' in the namespace-reveal transaction) * @param {String} paymentAddress - the address funding the preorder * @param {Number} paymentUtxos - the number of UTXOs we expect will be required * from the payment address. * @returns {Promise} - a promise which resolves to the satoshi cost to fund * the preorder. This includes a 5500 satoshi dust output for the preorder. * Even though this is a change output, the payer must supply enough funds * to generate this output, so we include it in the cost. * @private */ function estimateNamespacePreorder(namespaceID, revealAddress, paymentAddress) { var paymentUtxos = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; var network = _config.config.network; var preorderPromise = network.getNamespacePrice(namespaceID).then(function (namespacePrice) { return (0, _skeletons.makeNamespacePreorderSkeleton)(namespaceID, dummyConsensusHash, paymentAddress, revealAddress, namespacePrice); }); return Promise.all([network.getFeeRate(), preorderPromise]).then(function (_ref7) { var _ref8 = _slicedToArray(_ref7, 2), feeRate = _ref8[0], preorderTX = _ref8[1]; var outputsValue = (0, _utils.sumOutputValues)(preorderTX); var txFee = feeRate * (0, _utils.estimateTXBytes)(preorderTX, paymentUtxos, 0); return txFee + outputsValue; }); } /** * Estimates cost of a namesapce reveal transaction for a namespace * @param {BlockstackNamespace} namespace - the namespace to reveal * @param {String} revealAddress - the address to receive the namespace * (this must have been passed as 'revealAddress' to a prior namespace * preorder) * @param {String} paymentAddress - the address that pays for this transaction * @param {Number} paymentUtxos - the number of UTXOs we expect will be required * from the payment address * @returns {Promise} - a promise which resolves to the satoshi cost to * fund the reveal. This includes a 5500 satoshi dust output for the * preorder. Even though this is a change output, the payer must have * enough funds to generate this output, so we include it in the cost. * @private */ function estimateNamespaceReveal(namespace, revealAddress, paymentAddress) { var paymentUtxos = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; var network = _config.config.network; var revealTX = (0, _skeletons.makeNamespaceRevealSkeleton)(namespace, revealAddress); return network.getFeeRate().then(function (feeRate) { var outputsValue = (0, _utils.sumOutputValues)(revealTX); // 1 additional output for payer change var txFee = feeRate * (0, _utils.estimateTXBytes)(revealTX, paymentUtxos, 1); return txFee + outputsValue; }); } /** * Estimates the cost of a namespace-ready transaction for a namespace * @param {String} namespaceID - the namespace to ready * @param {Number} revealUtxos - the number of UTXOs we expect will * be required from the reveal address * @returns {Promise} - a promise which resolves to the satoshi cost to * fund this namespacey-ready transaction. * @private */ function estimateNamespaceReady(namespaceID) { var revealUtxos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var network = _config.config.network; var readyTX = (0, _skeletons.makeNamespaceReadySkeleton)(namespaceID); return network.getFeeRate().then(function (feeRate) { var outputsValue = (0, _utils.sumOutputValues)(readyTX); var txFee = feeRate * (0, _utils.estimateTXBytes)(readyTX, revealUtxos, 1); return txFee + outputsValue; }); } /** * Estimates the cost of a name-import transaction * @param {String} name - the fully-qualified name * @param {String} recipientAddr - the recipient * @param {String} zonefileHash - the zone file hash * @param {Number} importUtxos - the number of UTXOs we expect will * be required from the importer address * @returns {Promise} - a promise which resolves to the satoshi cost * to fund this name-import transaction * @private */ function estimateNameImport(name, recipientAddr, zonefileHash) { var importUtxos = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 1; var network = _config.config.network; var importTX = (0, _skeletons.makeNameImportSkeleton)(name, recipientAddr, zonefileHash); return network.getFeeRate().then(function (feeRate) { var outputsValue = (0, _utils.sumOutputValues)(importTX); var txFee = feeRate * (0, _utils.estimateTXBytes)(importTX, importUtxos, 1); return txFee + outputsValue; }); } /** * Estimates the cost of an announce transaction * @param {String} messageHash - the hash of the message * @param {Number} senderUtxos - the number of utxos we expect will * be required from the importer address * @returns {Promise} - a promise which resolves to the satoshi cost * to fund this announce transaction * @private */ function estimateAnnounce(messageHash) { var senderUtxos = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : 1; var network = _config.config.network; var announceTX = (0, _skeletons.makeAnnounceSkeleton)(messageHash); return network.getFeeRate().then(function (feeRate) { var outputsValue = (0, _utils.sumOutputValues)(announceTX); var txFee = feeRate * (0, _utils.estimateTXBytes)(announceTX, senderUtxos, 1); return txFee + outputsValue; }); } /** * Estimates the cost of a token-transfer transaction * @param {String} recipientAddress - the recipient of the tokens * @param {String} tokenType - the type of token to spend * @param {Object} tokenAmount - a 64-bit unsigned BigInteger encoding the number of tokens * to spend * @param {String} scratchArea - an arbitrary string to store with the transaction * @param {Number} senderUtxos - the number of utxos we expect will * be required from the importer address * @param {Number} additionalOutputs - the number of outputs we expect to add beyond * just the recipient output (default = 1, if the token owner is also the bitcoin funder) * @returns {Promise} - a promise which resolves to the satoshi cost to * fund this token-transfer transaction */ function estimateTokenTransfer(recipientAddress, tokenType, tokenAmount, scratchArea) { var senderUtxos = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 1; var additionalOutputs = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : 1; var network = _config.config.network; var tokenTransferTX = (0, _skeletons.makeTokenTransferSkeleton)(recipientAddress, dummyConsensusHash, tokenType, tokenAmount, scratchArea); return network.getFeeRate().then(function (feeRate) { var outputsValue = (0, _utils.sumOutputValues)(tokenTransferTX); var txFee = feeRate * (0, _utils.estimateTXBytes)(tokenTransferTX, senderUtxos, additionalOutputs); return txFee + outputsValue; }); } /** * Generates a preorder transaction for a domain name. * @param {String} fullyQualifiedName - the name to pre-order * @param {String} destinationAddress - the address to receive the name (this * must be passed as the 'registrationAddress' in the register transaction) * @param {String | TransactionSigner} paymentKeyIn - a hex string of * the private key used to fund the transaction or a transaction signer object * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function *does not* perform the requisite safety checks -- please see * the safety module for those. * @private */ function makePreorder(fullyQualifiedName, destinationAddress, paymentKeyIn) { var buildIncomplete = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var network = _config.config.network; var namespace = fullyQualifiedName.split('.').pop(); var paymentKey = getTransactionSigner(paymentKeyIn); return paymentKey.getAddress().then(function (preorderAddress) { var preorderPromise = Promise.all([network.getConsensusHash(), network.getNamePrice(fullyQualifiedName), network.getNamespaceBurnAddress(namespace)]).then(function (_ref9) { var _ref10 = _slicedToArray(_ref9, 3), consensusHash = _ref10[0], namePrice = _ref10[1], burnAddress = _ref10[2]; return (0, _skeletons.makePreorderSkeleton)(fullyQualifiedName, consensusHash, preorderAddress, burnAddress, namePrice, destinationAddress); }); return Promise.all([network.getUTXOs(preorderAddress), network.getFeeRate(), preorderPromise]).then(function (_ref11) { var _ref12 = _slicedToArray(_ref11, 3), utxos = _ref12[0], feeRate = _ref12[1], preorderSkeleton = _ref12[2]; var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(preorderSkeleton, network.layer1); txB.setVersion(1); var changeIndex = 1; // preorder skeleton always creates a change output at index = 1 var signingTxB = fundTransaction(txB, preorderAddress, utxos, feeRate, 0, changeIndex); return (0, _utils.signInputs)(signingTxB, paymentKey); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); }); } /** * Generates an update transaction for a domain name. * @param {String} fullyQualifiedName - the name to update * @param {String | TransactionSigner} ownerKeyIn - a hex string of the * owner key, or a transaction signer object. This will provide one * UTXO input, and also recieve a dust output. * @param {String | TransactionSigner} paymentKeyIn - a hex string, or a * transaction signer object, of the private key used to fund the * transaction's txfees * @param {String} zonefile - the zonefile data to update (this will be hashed * to include in the transaction), the zonefile itself must be published * after the UPDATE propagates. * @param {String} valueHash - if given, this is the hash to store (instead of * zonefile). zonefile will be ignored if this is given. * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function *does not* perform the requisite safety checks -- please see * the safety module for those. * @private */ function makeUpdate(fullyQualifiedName, ownerKeyIn, paymentKeyIn, zonefile) { var valueHash = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : ''; var buildIncomplete = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; var network = _config.config.network; if (!valueHash && !zonefile) { return Promise.reject(new Error('Need zonefile or valueHash arguments')); } if (valueHash.length === 0) { if (!zonefile) { return Promise.reject(new Error('Need zonefile or valueHash arguments')); } valueHash = (0, _utils.hash160)(Buffer.from(zonefile)).toString('hex'); } else if (valueHash.length !== 40) { return Promise.reject(new Error('Invalid valueHash ' + valueHash)); } var paymentKey = getTransactionSigner(paymentKeyIn); var ownerKey = getTransactionSigner(ownerKeyIn); return Promise.all([ownerKey.getAddress(), paymentKey.getAddress()]).then(function (_ref13) { var _ref14 = _slicedToArray(_ref13, 2), ownerAddress = _ref14[0], paymentAddress = _ref14[1]; var txPromise = network.getConsensusHash().then(function (consensusHash) { return (0, _skeletons.makeUpdateSkeleton)(fullyQualifiedName, consensusHash, valueHash); }).then(function (updateTX) { var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(updateTX, network.layer1); txB.setVersion(1); return txB; }); return Promise.all([txPromise, network.getUTXOs(paymentAddress), network.getUTXOs(ownerAddress), network.getFeeRate()]).then(function (_ref15) { var _ref16 = _slicedToArray(_ref15, 4), txB = _ref16[0], payerUtxos = _ref16[1], ownerUtxos = _ref16[2], feeRate = _ref16[3]; var ownerInput = addOwnerInput(ownerUtxos, ownerAddress, txB); var signingTxB = fundTransaction(txB, paymentAddress, payerUtxos, feeRate, ownerInput.value); return (0, _utils.signInputs)(signingTxB, paymentKey, [{ index: ownerInput.index, signer: ownerKey }]); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates a register transaction for a domain name. * @param {String} fullyQualifiedName - the name to register * @param {String} registerAddress - the address to receive the name (this * must have been passed as the 'destinationAddress' in the preorder transaction) * this address will receive a dust UTXO * @param {String | TransactionSigner} paymentKeyIn - a hex string of * the private key (or a TransactionSigner object) used to fund the * transaction (this *must* be the same as the payment address used * to fund the preorder) * @param {String} zonefile - the zonefile data to include (this will be hashed * to include in the transaction), the zonefile itself must be published * after the UPDATE propagates. * @param {String} valueHash - the hash of the zone file data to include. * It will be used instead of zonefile, if given * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function *does not* perform the requisite safety checks -- please see * the safety module for those. * @private */ function makeRegister(fullyQualifiedName, registerAddress, paymentKeyIn) { var zonefile = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var valueHash = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; var buildIncomplete = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; var network = _config.config.network; if (!valueHash && !!zonefile) { valueHash = (0, _utils.hash160)(Buffer.from(zonefile)).toString('hex'); } else if (!!valueHash && valueHash.length !== 40) { return Promise.reject(new Error('Invalid zonefile hash ' + valueHash)); } var registerSkeleton = (0, _skeletons.makeRegisterSkeleton)(fullyQualifiedName, registerAddress, valueHash); var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(registerSkeleton, network.layer1); txB.setVersion(1); var paymentKey = getTransactionSigner(paymentKeyIn); return paymentKey.getAddress().then(function (paymentAddress) { return Promise.all([network.getUTXOs(paymentAddress), network.getFeeRate()]).then(function (_ref17) { var _ref18 = _slicedToArray(_ref17, 2), utxos = _ref18[0], feeRate = _ref18[1]; var signingTxB = fundTransaction(txB, paymentAddress, utxos, feeRate, 0); return (0, _utils.signInputs)(signingTxB, paymentKey); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates a transfer transaction for a domain name. * @param {String} fullyQualifiedName - the name to transfer * @param {String} destinationAddress - the address to receive the name. * this address will receive a dust UTXO * @param {String | TransactionSigner} ownerKeyIn - a hex string of * the current owner's private key (or a TransactionSigner object) * @param {String | TransactionSigner} paymentKeyIn - a hex string of * the private key used to fund the transaction (or a * TransactionSigner object) * @param {Boolean} keepZonefile - if true, then preserve the name's zone file * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function *does not* perform the requisite safety checks -- please see * the safety module for those. * @private */ function makeTransfer(fullyQualifiedName, destinationAddress, ownerKeyIn, paymentKeyIn) { var keepZonefile = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var buildIncomplete = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : false; var network = _config.config.network; var paymentKey = getTransactionSigner(paymentKeyIn); var ownerKey = getTransactionSigner(ownerKeyIn); return Promise.all([ownerKey.getAddress(), paymentKey.getAddress()]).then(function (_ref19) { var _ref20 = _slicedToArray(_ref19, 2), ownerAddress = _ref20[0], paymentAddress = _ref20[1]; var txPromise = network.getConsensusHash().then(function (consensusHash) { return (0, _skeletons.makeTransferSkeleton)(fullyQualifiedName, consensusHash, destinationAddress, keepZonefile); }).then(function (transferTX) { var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(transferTX, network.layer1); txB.setVersion(1); return txB; }); return Promise.all([txPromise, network.getUTXOs(paymentAddress), network.getUTXOs(ownerAddress), network.getFeeRate()]).then(function (_ref21) { var _ref22 = _slicedToArray(_ref21, 4), txB = _ref22[0], payerUtxos = _ref22[1], ownerUtxos = _ref22[2], feeRate = _ref22[3]; var ownerInput = addOwnerInput(ownerUtxos, ownerAddress, txB); var signingTxB = fundTransaction(txB, paymentAddress, payerUtxos, feeRate, ownerInput.value); return (0, _utils.signInputs)(signingTxB, paymentKey, [{ index: ownerInput.index, signer: ownerKey }]); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates a revoke transaction for a domain name. * @param {String} fullyQualifiedName - the name to revoke * @param {String | TransactionSigner} ownerKeyIn - a hex string of * the current owner's private key (or a TransactionSigner object) * @param {String | TransactionSigner} paymentKeyIn - a hex string of * the private key used to fund the transaction (or a * TransactionSigner object) * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function *does not* perform the requisite safety checks -- please see * the safety module for those. * @private */ function makeRevoke(fullyQualifiedName, ownerKeyIn, paymentKeyIn) { var buildIncomplete = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var network = _config.config.network; var paymentKey = getTransactionSigner(paymentKeyIn); var ownerKey = getTransactionSigner(ownerKeyIn); return Promise.all([ownerKey.getAddress(), paymentKey.getAddress()]).then(function (_ref23) { var _ref24 = _slicedToArray(_ref23, 2), ownerAddress = _ref24[0], paymentAddress = _ref24[1]; var revokeTX = (0, _skeletons.makeRevokeSkeleton)(fullyQualifiedName); var txPromise = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(revokeTX, network.layer1); txPromise.setVersion(1); return Promise.all([txPromise, network.getUTXOs(paymentAddress), network.getUTXOs(ownerAddress), network.getFeeRate()]).then(function (_ref25) { var _ref26 = _slicedToArray(_ref25, 4), txB = _ref26[0], payerUtxos = _ref26[1], ownerUtxos = _ref26[2], feeRate = _ref26[3]; var ownerInput = addOwnerInput(ownerUtxos, ownerAddress, txB); var signingTxB = fundTransaction(txB, paymentAddress, payerUtxos, feeRate, ownerInput.value); return (0, _utils.signInputs)(signingTxB, paymentKey, [{ index: ownerInput.index, signer: ownerKey }]); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates a renewal transaction for a domain name. * @param {String} fullyQualifiedName - the name to transfer * @param {String} destinationAddress - the address to receive the name after renewal * this address will receive a dust UTXO * @param {String | TransactionSigner} ownerKeyIn - a hex string of * the current owner's private key (or a TransactionSigner object) * @param {String | TransactionSigner} paymentKeyIn - a hex string of * the private key used to fund the renewal (or a TransactionSigner * object) * @param {String} zonefile - the zonefile data to include, if given (this will be hashed * to include in the transaction), the zonefile itself must be published * after the RENEWAL propagates. * @param {String} valueHash - the raw zone file hash to include (this will be used * instead of zonefile, if given). * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function *does not* perform the requisite safety checks -- please see * the safety module for those. * @private */ function makeRenewal(fullyQualifiedName, destinationAddress, ownerKeyIn, paymentKeyIn) { var zonefile = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : null; var valueHash = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : null; var buildIncomplete = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false; var network = _config.config.network; if (!valueHash && !!zonefile) { valueHash = (0, _utils.hash160)(Buffer.from(zonefile)).toString('hex'); } var namespace = fullyQualifiedName.split('.').pop(); var paymentKey = getTransactionSigner(paymentKeyIn); var ownerKey = getTransactionSigner(ownerKeyIn); return Promise.all([ownerKey.getAddress(), paymentKey.getAddress()]).then(function (_ref27) { var _ref28 = _slicedToArray(_ref27, 2), ownerAddress = _ref28[0], paymentAddress = _ref28[1]; var txPromise = Promise.all([network.getNamePrice(fullyQualifiedName), network.getNamespaceBurnAddress(namespace)]).then(function (_ref29) { var _ref30 = _slicedToArray(_ref29, 2), namePrice = _ref30[0], burnAddress = _ref30[1]; return (0, _skeletons.makeRenewalSkeleton)(fullyQualifiedName, destinationAddress, ownerAddress, burnAddress, namePrice, valueHash); }).then(function (tx) { var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(tx, network.layer1); txB.setVersion(1); return txB; }); return Promise.all([txPromise, network.getUTXOs(paymentAddress), network.getUTXOs(ownerAddress), network.getFeeRate()]).then(function (_ref31) { var _ref32 = _slicedToArray(_ref31, 4), txB = _ref32[0], payerUtxos = _ref32[1], ownerUtxos = _ref32[2], feeRate = _ref32[3]; var ownerInput = addOwnerInput(ownerUtxos, ownerAddress, txB, false); var ownerOutput = txB.__tx.outs[2]; var ownerOutputAddr = _bitcoinjsLib2.default.address.fromOutputScript(ownerOutput.script, network.layer1); if (ownerOutputAddr !== ownerAddress) { return Promise.reject(new Error('Original owner ' + ownerAddress + ' should have an output at ' + ('index 2 in transaction was ' + ownerOutputAddr))); } ownerOutput.value = ownerInput.value; var signingTxB = fundTransaction(txB, paymentAddress, payerUtxos, feeRate, ownerInput.value); return (0, _utils.signInputs)(signingTxB, paymentKey, [{ index: ownerInput.index, signer: ownerKey }]); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates a namespace preorder transaction for a namespace * @param {String} namespaceID - the namespace to pre-order * @param {String} revealAddress - the address to receive the namespace (this * must be passed as the 'revealAddress' in the namespace-reveal transaction) * @param {String | TransactionSigner} paymentKeyIn - a hex string of * the private key used to fund the transaction (or a * TransactionSigner object) * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function *does not* perform the requisite safety checks -- please see * the safety module for those. * @private */ function makeNamespacePreorder(namespaceID, revealAddress, paymentKeyIn) { var buildIncomplete = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var network = _config.config.network; var paymentKey = getTransactionSigner(paymentKeyIn); return paymentKey.getAddress().then(function (preorderAddress) { var preorderPromise = Promise.all([network.getConsensusHash(), network.getNamespacePrice(namespaceID)]).then(function (_ref33) { var _ref34 = _slicedToArray(_ref33, 2), consensusHash = _ref34[0], namespacePrice = _ref34[1]; return (0, _skeletons.makeNamespacePreorderSkeleton)(namespaceID, consensusHash, preorderAddress, revealAddress, namespacePrice); }); return Promise.all([network.getUTXOs(preorderAddress), network.getFeeRate(), preorderPromise]).then(function (_ref35) { var _ref36 = _slicedToArray(_ref35, 3), utxos = _ref36[0], feeRate = _ref36[1], preorderSkeleton = _ref36[2]; var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(preorderSkeleton, network.layer1); txB.setVersion(1); var changeIndex = 1; // preorder skeleton always creates a change output at index = 1 var signingTxB = fundTransaction(txB, preorderAddress, utxos, feeRate, 0, changeIndex); return (0, _utils.signInputs)(signingTxB, paymentKey); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); }); } /** * Generates a namespace reveal transaction for a namespace * @param {BlockstackNamespace} namespace - the namespace to reveal * @param {String} revealAddress - the address to receive the namespace (this * must be passed as the 'revealAddress' in the namespace-reveal transaction) * @param {String | TransactionSigner} paymentKeyIn - a hex string (or * a TransactionSigner object) of the private key used to fund the * transaction * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function *does not* perform the requisite safety checks -- please see * the safety module for those. * @private */ function makeNamespaceReveal(namespace, revealAddress, paymentKeyIn) { var buildIncomplete = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; var network = _config.config.network; if (!namespace.check()) { return Promise.reject(new Error('Invalid namespace')); } var namespaceRevealTX = (0, _skeletons.makeNamespaceRevealSkeleton)(namespace, revealAddress); var paymentKey = getTransactionSigner(paymentKeyIn); return paymentKey.getAddress().then(function (preorderAddress) { return Promise.all([network.getUTXOs(preorderAddress), network.getFeeRate()]).then(function (_ref37) { var _ref38 = _slicedToArray(_ref37, 2), utxos = _ref38[0], feeRate = _ref38[1]; var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(namespaceRevealTX, network.layer1); txB.setVersion(1); var signingTxB = fundTransaction(txB, preorderAddress, utxos, feeRate, 0); return (0, _utils.signInputs)(signingTxB, paymentKey); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates a namespace ready transaction for a namespace * @param {String} namespaceID - the namespace to launch * @param {String | TransactionSigner} revealKeyIn - the private key * of the 'revealAddress' used to reveal the namespace * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function *does not* perform the requisite safety checks -- please see * the safety module for those. * @private */ function makeNamespaceReady(namespaceID, revealKeyIn) { var buildIncomplete = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var network = _config.config.network; var namespaceReadyTX = (0, _skeletons.makeNamespaceReadySkeleton)(namespaceID); var revealKey = getTransactionSigner(revealKeyIn); return revealKey.getAddress().then(function (revealAddress) { return Promise.all([network.getUTXOs(revealAddress), network.getFeeRate()]).then(function (_ref39) { var _ref40 = _slicedToArray(_ref39, 2), utxos = _ref40[0], feeRate = _ref40[1]; var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(namespaceReadyTX, network.layer1); txB.setVersion(1); var signingTxB = fundTransaction(txB, revealAddress, utxos, feeRate, 0); return (0, _utils.signInputs)(signingTxB, revealKey); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates a name import transaction for a namespace * @param {String} name - the name to import * @param {String} recipientAddr - the address to receive the name * @param {String} zonefileHash - the hash of the zonefile to give this name * @param {String | TransactionSigner} importerKeyIn - the private key * that pays for the import * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function does not perform the requisite safety checks -- please see * the safety module for those. * @private */ function makeNameImport(name, recipientAddr, zonefileHash, importerKeyIn) { var buildIncomplete = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : false; var network = _config.config.network; var nameImportTX = (0, _skeletons.makeNameImportSkeleton)(name, recipientAddr, zonefileHash); var importerKey = getTransactionSigner(importerKeyIn); return importerKey.getAddress().then(function (importerAddress) { return Promise.all([network.getUTXOs(importerAddress), network.getFeeRate()]).then(function (_ref41) { var _ref42 = _slicedToArray(_ref41, 2), utxos = _ref42[0], feeRate = _ref42[1]; var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(nameImportTX, network.layer1); var signingTxB = fundTransaction(txB, importerAddress, utxos, feeRate, 0); return (0, _utils.signInputs)(signingTxB, importerKey); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates an announce transaction * @param {String} messageHash - the hash of the message to send. Should be * an already-announced zone file hash * @param {String | TransactionSigner} senderKeyIn - the private key * that pays for the transaction. Should be the key that owns the * name that the message recipients subscribe to * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * this function does not perform the requisite safety checks -- please see the * safety module for those. * @private */ function makeAnnounce(messageHash, senderKeyIn) { var buildIncomplete = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; var network = _config.config.network; var announceTX = (0, _skeletons.makeAnnounceSkeleton)(messageHash); var senderKey = getTransactionSigner(senderKeyIn); return senderKey.getAddress().then(function (senderAddress) { return Promise.all([network.getUTXOs(senderAddress), network.getFeeRate()]).then(function (_ref43) { var _ref44 = _slicedToArray(_ref43, 2), utxos = _ref44[0], feeRate = _ref44[1]; var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(announceTX, network.layer1); var signingTxB = fundTransaction(txB, senderAddress, utxos, feeRate, 0); return (0, _utils.signInputs)(signingTxB, senderKey); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates a token-transfer transaction * @param {String} recipientAddress - the address to receive the tokens * @param {String} tokenType - the type of tokens to send * @param {Object} tokenAmount - the BigInteger encoding of an unsigned 64-bit number of * tokens to send * @param {String} scratchArea - an arbitrary string to include with the transaction * @param {String | TransactionSigner} senderKeyIn - the hex-encoded private key to send * the tokens * @param {String | TransactionSigner} btcFunderKeyIn - the hex-encoded private key to fund * the bitcoin fees for the transaction. Optional -- if not passed, will attempt to * fund with sender key. * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * This function does not perform the requisite safety checks -- please see the * safety module for those. * @private */ function makeTokenTransfer(recipientAddress, tokenType, tokenAmount, scratchArea, senderKeyIn, btcFunderKeyIn) { var buildIncomplete = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : false; var network = _config.config.network; var separateFunder = !!btcFunderKeyIn; var senderKey = getTransactionSigner(senderKeyIn); var btcKey = btcFunderKeyIn ? getTransactionSigner(btcFunderKeyIn) : senderKey; var txPromise = network.getConsensusHash().then(function (consensusHash) { return (0, _skeletons.makeTokenTransferSkeleton)(recipientAddress, consensusHash, tokenType, tokenAmount, scratchArea); }); return Promise.all([senderKey.getAddress(), btcKey.getAddress()]).then(function (_ref45) { var _ref46 = _slicedToArray(_ref45, 2), senderAddress = _ref46[0], btcAddress = _ref46[1]; var btcUTXOsPromise = separateFunder ? network.getUTXOs(btcAddress) : Promise.resolve([]); var networkPromises = [network.getUTXOs(senderAddress), btcUTXOsPromise, network.getFeeRate(), txPromise]; return Promise.all(networkPromises).then(function (_ref47) { var _ref48 = _slicedToArray(_ref47, 4), senderUTXOs = _ref48[0], btcUTXOs = _ref48[1], feeRate = _ref48[2], tokenTransferTX = _ref48[3]; var txB = _bitcoinjsLib2.default.TransactionBuilder.fromTransaction(tokenTransferTX, network.layer1); if (separateFunder) { var payerInput = addOwnerInput(senderUTXOs, senderAddress, txB); var signingTxB = fundTransaction(txB, btcAddress, btcUTXOs, feeRate, payerInput.value); return (0, _utils.signInputs)(signingTxB, btcKey, [{ index: payerInput.index, signer: senderKey }]); } else { var _signingTxB = fundTransaction(txB, senderAddress, senderUTXOs, feeRate, 0); return (0, _utils.signInputs)(_signingTxB, senderKey); } }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } /** * Generates a bitcoin spend to a specified address. This will fund up to `amount` * of satoshis from the payer's UTXOs. It will generate a change output if and only * if the amount of leftover change is *greater* than the additional fees associated * with the extra output. If the requested amount is not enough to fund the transaction's * associated fees, then this will reject with a InvalidAmountError * * UTXOs are selected largest to smallest, and UTXOs which cannot fund the fees associated * with their own input will not be included. * * If you specify an amount > the total balance of the payer address, then this will * generate a maximum spend transaction * * @param {String} destinationAddress - the address to receive the bitcoin payment * @param {String | TransactionSigner} paymentKeyIn - the private key * used to fund the bitcoin spend * @param {number} amount - the amount in satoshis for the payment address to * spend in this transaction * @param {boolean} buildIncomplete - optional boolean, defaults to false, * indicating whether the function should attempt to return an unsigned (or not fully signed) * transaction. Useful for passing around a TX for multi-sig input signing. * @returns {Promise} - a promise which resolves to the hex-encoded transaction. * @private */ function makeBitcoinSpend(destinationAddress, paymentKeyIn, amount) { var buildIncomplete = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : false; if (amount <= 0) { return Promise.reject(new _errors.InvalidParameterError('amount', 'amount must be greater than zero')); } var network = _config.config.network; var paymentKey = getTransactionSigner(paymentKeyIn); return paymentKey.getAddress().then(function (paymentAddress) { return Promise.all([network.getUTXOs(paymentAddress), network.getFeeRate()]).then(function (_ref49) { var _ref50 = _slicedToArray(_ref49, 2), utxos = _ref50[0], feeRate = _ref50[1]; var txB = new _bitcoinjsLib2.default.TransactionBuilder(network.layer1); txB.setVersion(1); var destinationIndex = txB.addOutput(destinationAddress, 0); // will add utxos up to _amount_ and return the amount of leftover _change_ var change = void 0; try { change = (0, _utils.addUTXOsToFund)(txB, utxos, amount, feeRate, false); } catch (err) { if (err.name === 'NotEnoughFundsError') { // actual amount funded = amount requested - remainder amount -= err.leftToFund; change = 0; } else { throw err; } } var feesToPay = feeRate * (0, _utils.estimateTXBytes)(txB, 0, 0); var feeForChange = feeRate * (0, _utils.estimateTXBytes)(txB, 0, 1) - feesToPay; // it's worthwhile to add a change output if (change > feeForChange) { feesToPay += feeForChange; txB.addOutput(paymentAddress, change); } // now let's compute how much output is leftover once we pay the fees. var outputAmount = amount - feesToPay; if (outputAmount < _utils.DUST_MINIMUM) { throw new _errors.InvalidAmountError(feesToPay, amount); } // we need to manually set the output values now txB.__tx.outs[destinationIndex].value = outputAmount; // ready to sign. return (0, _utils.signInputs)(txB, paymentKey); }); }).then(function (signingTxB) { return returnTransactionHex(signingTxB, buildIncomplete); }); } var transactions = exports.transactions = { makeRenewal: makeRenewal, makeUpdate: makeUpdate, makePreorder: makePreorder, makeRegister: makeRegister, makeTransfer: makeTransfer, makeRevoke: makeRevoke, makeNamespacePreorder: makeNamespacePreorder, makeNamespaceReveal: makeNamespaceReveal, makeNamespaceReady: makeNamespaceReady, makeBitcoinSpend: makeBitcoinSpend, makeNameImport: makeNameImport, makeAnnounce: makeAnnounce, makeTokenTransfer: makeTokenTransfer, BlockstackNamespace: _skeletons.BlockstackNamespace, estimatePreorder: estimatePreorder, estimateRegister: estimateRegister, estimateTransfer: estimateTransfer, estimateUpdate: estimateUpdate, estimateRenewal: estimateRenewal, estimateRevoke: estimateRevoke, estimateNamespacePreorder: estimateNamespacePreorder, estimateNamespaceReveal: estimateNamespaceReveal, estimateNamespaceReady: estimateNamespaceReady, estimateNameImport: estimateNameImport, estimateAnnounce: estimateAnnounce, estimateTokenTransfer: estimateTokenTransfer }; }).call(this,require("buffer").Buffer) },{"../config":8,"../errors":11,"./signers":18,"./skeletons":19,"./utils":21,"bigi":70,"bitcoinjs-lib":92,"buffer":179}],21:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.DUST_MINIMUM = undefined; exports.hash160 = hash160; exports.hash128 = hash128; exports.estimateTXBytes = estimateTXBytes; exports.sumOutputValues = sumOutputValues; exports.decodeB40 = decodeB40; exports.addUTXOsToFund = addUTXOsToFund; exports.signInputs = signInputs; var _bitcoinjsLib = require('bitcoinjs-lib'); var _bitcoinjsLib2 = _interopRequireDefault(_bitcoinjsLib); var _ripemd = require('ripemd160'); var _ripemd2 = _interopRequireDefault(_ripemd); var _bigi = require('bigi'); var _bigi2 = _interopRequireDefault(_bigi); var _errors = require('../errors'); var _signers = require('./signers'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var DUST_MINIMUM = exports.DUST_MINIMUM = 5500; function hash160(buff) { var sha256 = _bitcoinjsLib2.default.crypto.sha256(buff); return new _ripemd2.default().update(sha256).digest(); } function hash128(buff) { return Buffer.from(_bitcoinjsLib2.default.crypto.sha256(buff).slice(0, 16)); } // COPIED FROM coinselect, because 1 byte matters sometimes. // baseline estimates, used to improve performance var TX_EMPTY_SIZE = 4 + 1 + 1 + 4; var TX_INPUT_BASE = 32 + 4 + 1 + 4; var TX_INPUT_PUBKEYHASH = 107; var TX_OUTPUT_BASE = 8 + 1; var TX_OUTPUT_PUBKEYHASH = 25; function inputBytes(input) { if (input && input.script && input.script.length > 0) { return TX_INPUT_BASE + input.script.length; } else { return TX_INPUT_BASE + TX_INPUT_PUBKEYHASH; } } function outputBytes(output) { if (output && output.script && output.script.length > 0) { return TX_OUTPUT_BASE + output.script.length; } else { return TX_OUTPUT_BASE + TX_OUTPUT_PUBKEYHASH; } } function transactionBytes(inputs, outputs) { return TX_EMPTY_SIZE + inputs.reduce(function (a, x) { return a + inputBytes(x); }, 0) + outputs.reduce(function (a, x) { return a + outputBytes(x); }, 0); } // function estimateTXBytes(txIn, additionalInputs, additionalOutputs) { var innerTx = txIn; if (txIn instanceof _bitcoinjsLib2.default.TransactionBuilder) { innerTx = txIn.__tx; } var dummyInputs = new Array(additionalInputs); dummyInputs.fill(null); var dummyOutputs = new Array(additionalOutputs); dummyOutputs.fill(null); var inputs = [].concat(innerTx.ins, dummyInputs); var outputs = [].concat(innerTx.outs, dummyOutputs); return transactionBytes(inputs, outputs); } function sumOutputValues(txIn) { var innerTx = txIn; if (txIn instanceof _bitcoinjsLib2.default.TransactionBuilder) { innerTx = txIn.__tx; } return innerTx.outs.reduce(function (agg, x) { return agg + x.value; }, 0); } function decodeB40(input) { // treat input as a base40 integer, and output a hex encoding // of that integer. // // for each digit of the string, find its location in `characters` // to get the value of the digit, then multiply by 40^(-index in input) // e.g., // the 'right-most' character has value: (digit-value) * 40^0 // the next character has value: (digit-value) * 40^1 // // hence, we reverse the characters first, and use the index // to compute the value of each digit, then sum var characters = '0123456789abcdefghijklmnopqrstuvwxyz-_.+'; var base = _bigi2.default.valueOf(40); var inputDigits = input.split('').reverse(); var digitValues = inputDigits.map(function (character, exponent) { return _bigi2.default.valueOf(characters.indexOf(character)).multiply(base.pow(_bigi2.default.valueOf(exponent))); }); var sum = digitValues.reduce(function (agg, cur) { return agg.add(cur); }, _bigi2.default.ZERO); return sum.toHex(); } /** * Adds UTXOs to fund a transaction * @param {TransactionBuilder} txBuilderIn - a transaction builder object to add the inputs to. this * object is _always_ mutated. If not enough UTXOs exist to fund, the tx builder object * will still contain as many inputs as could be found. * @param {Array<{value: number, tx_hash: string, tx_output_n}>} utxos - the utxo set for the * payer's address. * @param {number} amountToFund - the amount of satoshis to fund in the transaction. the payer's * utxos will be included to fund up to this amount of *output* and the corresponding *fees* * for those additional inputs * @param {number} feeRate - the satoshis/byte fee rate to use for fee calculation * @param {boolean} fundNewFees - if true, this function will fund `amountToFund` and any new fees * associated with including the new inputs. * if false, this function will fund _at most_ `amountToFund` * @returns {number} - the amount of leftover change (in satoshis) * @private */ function addUTXOsToFund(txBuilderIn, utxos, amountToFund, feeRate) { var fundNewFees = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : true; if (utxos.length === 0) { throw new _errors.NotEnoughFundsError(amountToFund); } // how much are we increasing fees by adding an input ? var newFees = feeRate * (estimateTXBytes(txBuilderIn, 1, 0) - estimateTXBytes(txBuilderIn, 0, 0)); var utxoThreshhold = amountToFund; if (fundNewFees) { utxoThreshhold += newFees; } var goodUtxos = utxos.filter(function (utxo) { return utxo.value >= utxoThreshhold; }); if (goodUtxos.length > 0) { goodUtxos.sort(function (a, b) { return a.value - b.value; }); var selected = goodUtxos[0]; var change = selected.value - amountToFund; if (fundNewFees) { change -= newFees; } txBuilderIn.addInput(selected.tx_hash, selected.tx_output_n); return change; } else { utxos.sort(function (a, b) { return b.value - a.value; }); var largest = utxos[0]; if (newFees >= largest.value) { throw new _errors.NotEnoughFundsError(amountToFund); } txBuilderIn.addInput(largest.tx_hash, largest.tx_output_n); var remainToFund = amountToFund - largest.value; if (fundNewFees) { remainToFund += newFees; } return addUTXOsToFund(txBuilderIn, utxos.slice(1), remainToFund, feeRate, fundNewFees); } } function signInputs(txB, defaultSigner, otherSigners) { var signerArray = txB.__tx.ins.map(function () { return defaultSigner; }); if (otherSigners) { otherSigners.forEach(function (signerPair) { signerArray[signerPair.index] = signerPair.signer; }); } var signingPromise = Promise.resolve(); var _loop = function _loop(i) { signingPromise = signingPromise.then(function () { return signerArray[i].signTransaction(txB, i); }); }; for (var i = 0; i < txB.__tx.ins.length; i++) { _loop(i); } return signingPromise.then(function () { return txB; }); } }).call(this,require("buffer").Buffer) },{"../errors":11,"./signers":18,"bigi":70,"bitcoinjs-lib":92,"buffer":179,"ripemd160":456}],22:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _profile = require('./profile'); Object.defineProperty(exports, 'Profile', { enumerable: true, get: function get() { return _profile.Profile; } }); var _profileSchemas = require('./profileSchemas'); Object.defineProperty(exports, 'Person', { enumerable: true, get: function get() { return _profileSchemas.Person; } }); Object.defineProperty(exports, 'Organization', { enumerable: true, get: function get() { return _profileSchemas.Organization; } }); Object.defineProperty(exports, 'CreativeWork', { enumerable: true, get: function get() { return _profileSchemas.CreativeWork; } }); Object.defineProperty(exports, 'resolveZoneFileToPerson', { enumerable: true, get: function get() { return _profileSchemas.resolveZoneFileToPerson; } }); var _profileTokens = require('./profileTokens'); Object.defineProperty(exports, 'signProfileToken', { enumerable: true, get: function get() { return _profileTokens.signProfileToken; } }); Object.defineProperty(exports, 'wrapProfileToken', { enumerable: true, get: function get() { return _profileTokens.wrapProfileToken; } }); Object.defineProperty(exports, 'verifyProfileToken', { enumerable: true, get: function get() { return _profileTokens.verifyProfileToken; } }); Object.defineProperty(exports, 'extractProfile', { enumerable: true, get: function get() { return _profileTokens.extractProfile; } }); var _profileProofs = require('./profileProofs'); Object.defineProperty(exports, 'validateProofs', { enumerable: true, get: function get() { return _profileProofs.validateProofs; } }); var _services = require('./services'); Object.defineProperty(exports, 'profileServices', { enumerable: true, get: function get() { return _services.profileServices; } }); Object.defineProperty(exports, 'containsValidProofStatement', { enumerable: true, get: function get() { return _services.containsValidProofStatement; } }); Object.defineProperty(exports, 'containsValidAddressProofStatement', { enumerable: true, get: function get() { return _services.containsValidAddressProofStatement; } }); var _profileZoneFiles = require('./profileZoneFiles'); Object.defineProperty(exports, 'makeProfileZoneFile', { enumerable: true, get: function get() { return _profileZoneFiles.makeProfileZoneFile; } }); Object.defineProperty(exports, 'getTokenFileUrl', { enumerable: true, get: function get() { return _profileZoneFiles.getTokenFileUrl; } }); Object.defineProperty(exports, 'resolveZoneFileToProfile', { enumerable: true, get: function get() { return _profileZoneFiles.resolveZoneFileToProfile; } }); var _profileLookup = require('./profileLookup'); Object.defineProperty(exports, 'lookupProfile', { enumerable: true, get: function get() { return _profileLookup.lookupProfile; } }); },{"./profile":23,"./profileLookup":24,"./profileProofs":25,"./profileSchemas":27,"./profileTokens":33,"./profileZoneFiles":34,"./services":38}],23:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Profile = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _schemaInspector = require('schema-inspector'); var _schemaInspector2 = _interopRequireDefault(_schemaInspector); var _profileTokens = require('./profileTokens'); var _profileProofs = require('./profileProofs'); var _profileZoneFiles = require('./profileZoneFiles'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var schemaDefinition = { type: 'object', properties: { '@context': { type: 'string', optional: true }, '@type': { type: 'string' } } }; var Profile = exports.Profile = function () { function Profile() { var profile = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Profile); this._profile = Object.assign({}, { '@context': 'http://schema.org/' }, profile); } _createClass(Profile, [{ key: 'toJSON', value: function toJSON() { return Object.assign({}, this._profile); } }, { key: 'toToken', value: function toToken(privateKey) { return (0, _profileTokens.signProfileToken)(this.toJSON(), privateKey); } }], [{ key: 'validateSchema', value: function validateSchema(profile) { var strict = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; schemaDefinition.strict = strict; return _schemaInspector2.default.validate(schemaDefinition, profile); } }, { key: 'fromToken', value: function fromToken(token) { var publicKeyOrAddress = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var profile = (0, _profileTokens.extractProfile)(token, publicKeyOrAddress); return new Profile(profile); } }, { key: 'makeZoneFile', value: function makeZoneFile(domainName, tokenFileURL) { return (0, _profileZoneFiles.makeProfileZoneFile)(domainName, tokenFileURL); } }, { key: 'validateProofs', value: function validateProofs(domainName) { return (0, _profileProofs.validateProofs)(this.toJSON(), domainName); } }]); return Profile; }(); },{"./profileProofs":25,"./profileTokens":33,"./profileZoneFiles":34,"schema-inspector":458}],24:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.lookupProfile = lookupProfile; var _profileZoneFiles = require('./profileZoneFiles'); var _config = require('../config'); /** * Look up a user profile by blockstack ID * * @param {string} username - The Blockstack ID of the profile to look up * @param {string} [zoneFileLookupURL=null] - The URL * to use for zonefile lookup. If falsey, lookupProfile will use the * blockstack.js getNameInfo function. * @returns {Promise} that resolves to a profile object */ function lookupProfile(username) { var zoneFileLookupURL = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (!username) { return Promise.reject(); } var lookupPromise = void 0; if (zoneFileLookupURL) { var url = zoneFileLookupURL.replace(/\/$/, '') + '/' + username; lookupPromise = fetch(url).then(function (response) { return response.json(); }); } else { lookupPromise = _config.config.network.getNameInfo(username); } return lookupPromise.then(function (responseJSON) { if (responseJSON.hasOwnProperty('zonefile') && responseJSON.hasOwnProperty('address')) { return (0, _profileZoneFiles.resolveZoneFileToProfile)(responseJSON.zonefile, responseJSON.address); } else { throw new Error('Invalid zonefile lookup response: did not contain `address`' + ' or `zonefile` field'); } }); } },{"../config":8,"./profileZoneFiles":34}],25:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.validateProofs = validateProofs; var _services = require('./services'); /** * Validates the social proofs in a user's profile. Currently supports validation of * Facebook, Twitter, GitHub, Instagram, LinkedIn and HackerNews accounts. * * @param {Object} profile The JSON of the profile to be validated * @param {string} ownerAddress The owner bitcoin address to be validated * @param {string} [name=null] The Blockstack name to be validated * @returns {Promise} that resolves to an array of validated proof objects */ function validateProofs(profile, ownerAddress) { var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; if (!profile) { throw new Error('Profile must not be null'); } var accounts = []; var proofsToValidate = []; if (profile.hasOwnProperty('account')) { accounts = profile.account; } else { return new Promise(function (resolve) { resolve([]); }); } accounts.forEach(function (account) { // skip if proof service is not supported if (account.hasOwnProperty('service') && !_services.profileServices.hasOwnProperty(account.service)) { return; } if (!(account.hasOwnProperty('proofType') && account.proofType === 'http' && account.hasOwnProperty('proofUrl'))) { return; } var proof = { service: account.service, proof_url: account.proofUrl, identifier: account.identifier, valid: false }; proofsToValidate.push(_services.profileServices[account.service].validateProof(proof, ownerAddress, name)); }); return Promise.all(proofsToValidate); } },{"./services":38}],26:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.CreativeWork = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _schemaInspector = require('schema-inspector'); var _schemaInspector2 = _interopRequireDefault(_schemaInspector); var _profileTokens = require('../profileTokens'); var _profile = require('../profile'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var schemaDefinition = { type: 'object', properties: { '@context': { type: 'string', optional: true }, '@type': { type: 'string' }, '@id': { type: 'string', optional: true } } }; var CreativeWork = exports.CreativeWork = function (_Profile) { _inherits(CreativeWork, _Profile); function CreativeWork() { var profile = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, CreativeWork); var _this = _possibleConstructorReturn(this, (CreativeWork.__proto__ || Object.getPrototypeOf(CreativeWork)).call(this, profile)); _this._profile = Object.assign({}, { '@type': 'CreativeWork' }, _this._profile); return _this; } _createClass(CreativeWork, null, [{ key: 'validateSchema', value: function validateSchema(profile) { var strict = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; schemaDefinition.strict = strict; return _schemaInspector2.default.validate(schemaDefinition, profile); } }, { key: 'fromToken', value: function fromToken(token) { var publicKeyOrAddress = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var profile = (0, _profileTokens.extractProfile)(token, publicKeyOrAddress); return new CreativeWork(profile); } }]); return CreativeWork; }(_profile.Profile); },{"../profile":23,"../profileTokens":33,"schema-inspector":458}],27:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _person = require('./person'); Object.defineProperty(exports, 'Person', { enumerable: true, get: function get() { return _person.Person; } }); var _organization = require('./organization'); Object.defineProperty(exports, 'Organization', { enumerable: true, get: function get() { return _organization.Organization; } }); var _creativework = require('./creativework'); Object.defineProperty(exports, 'CreativeWork', { enumerable: true, get: function get() { return _creativework.CreativeWork; } }); var _personLegacy = require('./personLegacy'); Object.defineProperty(exports, 'getPersonFromLegacyFormat', { enumerable: true, get: function get() { return _personLegacy.getPersonFromLegacyFormat; } }); var _personZoneFiles = require('./personZoneFiles'); Object.defineProperty(exports, 'resolveZoneFileToPerson', { enumerable: true, get: function get() { return _personZoneFiles.resolveZoneFileToPerson; } }); },{"./creativework":26,"./organization":28,"./person":29,"./personLegacy":30,"./personZoneFiles":32}],28:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Organization = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _schemaInspector = require('schema-inspector'); var _schemaInspector2 = _interopRequireDefault(_schemaInspector); var _profileTokens = require('../profileTokens'); var _profile = require('../profile'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var schemaDefinition = { type: 'object', properties: { '@context': { type: 'string', optional: true }, '@type': { type: 'string' }, '@id': { type: 'string', optional: true } } }; var Organization = exports.Organization = function (_Profile) { _inherits(Organization, _Profile); function Organization() { var profile = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Organization); var _this = _possibleConstructorReturn(this, (Organization.__proto__ || Object.getPrototypeOf(Organization)).call(this, profile)); _this._profile = Object.assign({}, { '@type': 'Organization' }, _this._profile); return _this; } _createClass(Organization, null, [{ key: 'validateSchema', value: function validateSchema(profile) { var strict = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; schemaDefinition.strict = strict; return _schemaInspector2.default.validate(schemaDefinition, profile); } }, { key: 'fromToken', value: function fromToken(token) { var publicKeyOrAddress = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var profile = (0, _profileTokens.extractProfile)(token, publicKeyOrAddress); return new Organization(profile); } }]); return Organization; }(_profile.Profile); },{"../profile":23,"../profileTokens":33,"schema-inspector":458}],29:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Person = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _schemaInspector = require('schema-inspector'); var _schemaInspector2 = _interopRequireDefault(_schemaInspector); var _profile = require('../profile'); var _profileTokens = require('../profileTokens'); var _personLegacy = require('./personLegacy'); var _personUtils = require('./personUtils'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var schemaDefinition = { type: 'object', strict: false, properties: { '@context': { type: 'string', optional: true }, '@type': { type: 'string' }, '@id': { type: 'string', optional: true }, name: { type: 'string', optional: true }, givenName: { type: 'string', optional: true }, familyName: { type: 'string', optional: true }, description: { type: 'string', optional: true }, image: { type: 'array', optional: true, items: { type: 'object', properties: { '@type': { type: 'string' }, name: { type: 'string', optional: true }, contentUrl: { type: 'string', optional: true } } } }, website: { type: 'array', optional: true, items: { type: 'object', properties: { '@type': { type: 'string' }, url: { type: 'string', optional: true } } } }, account: { type: 'array', optional: true, items: { type: 'object', properties: { '@type': { type: 'string' }, service: { type: 'string', optional: true }, identifier: { type: 'string', optional: true }, proofType: { type: 'string', optional: true }, proofUrl: { type: 'string', optional: true }, proofMessage: { type: 'string', optional: true }, proofSignature: { type: 'string', optional: true } } } }, worksFor: { type: 'array', optional: true, items: { type: 'object', properties: { '@type': { type: 'string' }, '@id': { type: 'string', optional: true } } } }, knows: { type: 'array', optional: true, items: { type: 'object', properties: { '@type': { type: 'string' }, '@id': { type: 'string', optional: true } } } }, address: { type: 'object', optional: true, properties: { '@type': { type: 'string' }, streetAddress: { type: 'string', optional: true }, addressLocality: { type: 'string', optional: true }, postalCode: { type: 'string', optional: true }, addressCountry: { type: 'string', optional: true } } }, birthDate: { type: 'string', optional: true }, taxID: { type: 'string', optional: true } } }; var Person = exports.Person = function (_Profile) { _inherits(Person, _Profile); function Person() { var profile = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; _classCallCheck(this, Person); var _this = _possibleConstructorReturn(this, (Person.__proto__ || Object.getPrototypeOf(Person)).call(this, profile)); _this._profile = Object.assign({}, { '@type': 'Person' }, _this._profile); return _this; } _createClass(Person, [{ key: 'toJSON', value: function toJSON() { return { profile: this.profile(), name: this.name(), givenName: this.givenName(), familyName: this.familyName(), description: this.description(), avatarUrl: this.avatarUrl(), verifiedAccounts: this.verifiedAccounts(), address: this.address(), birthDate: this.birthDate(), connections: this.connections(), organizations: this.organizations() }; } }, { key: 'profile', value: function profile() { return Object.assign({}, this._profile); } }, { key: 'name', value: function name() { return (0, _personUtils.getName)(this.profile()); } }, { key: 'givenName', value: function givenName() { return (0, _personUtils.getGivenName)(this.profile()); } }, { key: 'familyName', value: function familyName() { return (0, _personUtils.getFamilyName)(this.profile()); } }, { key: 'description', value: function description() { return (0, _personUtils.getDescription)(this.profile()); } }, { key: 'avatarUrl', value: function avatarUrl() { return (0, _personUtils.getAvatarUrl)(this.profile()); } }, { key: 'verifiedAccounts', value: function verifiedAccounts(verifications) { return (0, _personUtils.getVerifiedAccounts)(this.profile(), verifications); } }, { key: 'address', value: function address() { return (0, _personUtils.getAddress)(this.profile()); } }, { key: 'birthDate', value: function birthDate() { return (0, _personUtils.getBirthDate)(this.profile()); } }, { key: 'connections', value: function connections() { return (0, _personUtils.getConnections)(this.profile()); } }, { key: 'organizations', value: function organizations() { return (0, _personUtils.getOrganizations)(this.profile()); } }], [{ key: 'validateSchema', value: function validateSchema(profile) { var strict = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; schemaDefinition.strict = strict; return _schemaInspector2.default.validate(schemaDefinition, profile); } }, { key: 'fromToken', value: function fromToken(token) { var publicKeyOrAddress = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var profile = (0, _profileTokens.extractProfile)(token, publicKeyOrAddress); return new Person(profile); } }, { key: 'fromLegacyFormat', value: function fromLegacyFormat(legacyProfile) { var profile = (0, _personLegacy.getPersonFromLegacyFormat)(legacyProfile); return new Person(profile); } }]); return Person; }(_profile.Profile); },{"../profile":23,"../profileTokens":33,"./personLegacy":30,"./personUtils":31,"schema-inspector":458}],30:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getPersonFromLegacyFormat = getPersonFromLegacyFormat; function formatAccount(serviceName, data) { var proofUrl = void 0; if (data.proof && data.proof.url) { proofUrl = data.proof.url; } return { '@type': 'Account', service: serviceName, identifier: data.username, proofType: 'http', proofUrl: proofUrl }; } function getPersonFromLegacyFormat(profile) { var profileData = { '@type': 'Person' }; if (profile) { if (profile.name && profile.name.formatted) { profileData.name = profile.name.formatted; } if (profile.bio) { profileData.description = profile.bio; } if (profile.location && profile.location.formatted) { profileData.address = { '@type': 'PostalAddress', addressLocality: profile.location.formatted }; } var images = []; if (profile.avatar && profile.avatar.url) { images.push({ '@type': 'ImageObject', name: 'avatar', contentUrl: profile.avatar.url }); } if (profile.cover && profile.cover.url) { images.push({ '@type': 'ImageObject', name: 'cover', contentUrl: profile.cover.url }); } if (images.length) { profileData.image = images; } if (profile.website) { profileData.website = [{ '@type': 'WebSite', url: profile.website }]; } var accounts = []; if (profile.bitcoin && profile.bitcoin.address) { accounts.push({ '@type': 'Account', role: 'payment', service: 'bitcoin', identifier: profile.bitcoin.address }); } if (profile.twitter && profile.twitter.username) { accounts.push(formatAccount('twitter', profile.twitter)); } if (profile.facebook && profile.facebook.username) { accounts.push(formatAccount('facebook', profile.facebook)); } if (profile.github && profile.github.username) { accounts.push(formatAccount('github', profile.github)); } if (profile.auth) { if (profile.auth.length > 0) { if (profile.auth[0] && profile.auth[0].publicKeychain) { accounts.push({ '@type': 'Account', role: 'key', service: 'bip32', identifier: profile.auth[0].publicKeychain }); } } } if (profile.pgp && profile.pgp.url) { accounts.push({ '@type': 'Account', role: 'key', service: 'pgp', identifier: profile.pgp.fingerprint, contentUrl: profile.pgp.url }); } profileData.account = accounts; } return profileData; } },{}],31:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.getName = getName; exports.getGivenName = getGivenName; exports.getFamilyName = getFamilyName; exports.getDescription = getDescription; exports.getAvatarUrl = getAvatarUrl; exports.getVerifiedAccounts = getVerifiedAccounts; exports.getOrganizations = getOrganizations; exports.getConnections = getConnections; exports.getAddress = getAddress; exports.getBirthDate = getBirthDate; function getName(profile) { if (!profile) { return null; } var name = null; if (profile.name) { name = profile.name; } else if (profile.givenName || profile.familyName) { name = ''; if (profile.givenName) { name = profile.givenName; } if (profile.familyName) { name += ' ' + profile.familyName; } } return name; } function getGivenName(profile) { if (!profile) { return null; } var givenName = null; if (profile.givenName) { givenName = profile.givenName; } else if (profile.name) { var nameParts = profile.name.split(' '); givenName = nameParts.slice(0, -1).join(' '); } return givenName; } function getFamilyName(profile) { if (!profile) { return null; } var familyName = null; if (profile.familyName) { familyName = profile.familyName; } else if (profile.name) { var nameParts = profile.name.split(' '); familyName = nameParts.pop(); } return familyName; } function getDescription(profile) { if (!profile) { return null; } var description = null; if (profile.description) { description = profile.description; } return description; } function getAvatarUrl(profile) { if (!profile) { return null; } var avatarContentUrl = null; if (profile.image) { profile.image.map(function (image) { if (image.name === 'avatar') { avatarContentUrl = image.contentUrl; return avatarContentUrl; } else { return null; } }); } return avatarContentUrl; } function getVerifiedAccounts(profile, verifications) { if (!profile) { return null; } var filteredAccounts = []; if (profile.hasOwnProperty('account') && verifications) { profile.account.map(function (account) { var accountIsValid = false; var proofUrl = null; verifications.map(function (verification) { if (verification.hasOwnProperty('proof_url')) { verification.proofUrl = verification.proof_url; } if (verification.valid && verification.service === account.service && verification.identifier === account.identifier && verification.proofUrl) { accountIsValid = true; proofUrl = verification.proofUrl; return true; } else { return false; } }); if (accountIsValid) { account.proofUrl = proofUrl; filteredAccounts.push(account); return account; } else { return null; } }); } return filteredAccounts; } function getOrganizations(profile) { if (!profile) { return null; } var organizations = []; if (profile.hasOwnProperty('worksFor')) { return profile.worksFor; } return organizations; } function getConnections(profile) { if (!profile) { return null; } var connections = []; if (profile.hasOwnProperty('knows')) { connections = profile.knows; } return connections; } function getAddress(profile) { if (!profile) { return null; } var addressString = null; if (profile.hasOwnProperty('address')) { var addressParts = []; if (profile.address.hasOwnProperty('streetAddress')) { addressParts.push(profile.address.streetAddress); } if (profile.address.hasOwnProperty('addressLocality')) { addressParts.push(profile.address.addressLocality); } if (profile.address.hasOwnProperty('postalCode')) { addressParts.push(profile.address.postalCode); } if (profile.address.hasOwnProperty('addressCountry')) { addressParts.push(profile.address.addressCountry); } if (addressParts.length) { addressString = addressParts.join(', '); } } return addressString; } function getBirthDate(profile) { if (!profile) { return null; } var monthNames = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var birthDateString = null; if (profile.hasOwnProperty('birthDate')) { var date = new Date(profile.birthDate); birthDateString = monthNames[date.getMonth()] + ' ' + date.getDate() + ', ' + date.getFullYear(); } return birthDateString; } },{}],32:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.resolveZoneFileToPerson = resolveZoneFileToPerson; var _zoneFile = require('zone-file'); var _person = require('./person'); var _profileZoneFiles = require('../profileZoneFiles'); var _profileTokens = require('../profileTokens'); function resolveZoneFileToPerson(zoneFile, publicKeyOrAddress, callback) { var zoneFileJson = null; try { zoneFileJson = (0, _zoneFile.parseZoneFile)(zoneFile); if (!zoneFileJson.hasOwnProperty('$origin')) { zoneFileJson = null; throw new Error('zone file is missing an origin'); } } catch (e) { console.error(e); } var tokenFileUrl = null; if (zoneFileJson && Object.keys(zoneFileJson).length > 0) { tokenFileUrl = (0, _profileZoneFiles.getTokenFileUrl)(zoneFileJson); } else { var profile = null; try { profile = JSON.parse(zoneFile); var person = _person.Person.fromLegacyFormat(profile); profile = person.profile(); } catch (error) { console.warn(error); } callback(profile); return; } if (tokenFileUrl) { fetch(tokenFileUrl).then(function (response) { return response.text(); }).then(function (responseText) { return JSON.parse(responseText); }).then(function (responseJson) { var tokenRecords = responseJson; var token = tokenRecords[0].token; var profile = (0, _profileTokens.extractProfile)(token, publicKeyOrAddress); callback(profile); }).catch(function (error) { console.warn(error); }); } else { console.warn('Token file url not found'); callback({}); } } },{"../profileTokens":33,"../profileZoneFiles":34,"./person":29,"zone-file":566}],33:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.signProfileToken = signProfileToken; exports.wrapProfileToken = wrapProfileToken; exports.verifyProfileToken = verifyProfileToken; exports.extractProfile = extractProfile; var _bitcoinjsLib = require('bitcoinjs-lib'); var _jsontokens = require('jsontokens'); var _utils = require('../utils'); /** * Signs a profile token * @param {Object} profile - the JSON of the profile to be signed * @param {String} privateKey - the signing private key * @param {Object} subject - the entity that the information is about * @param {Object} issuer - the entity that is issuing the token * @param {String} signingAlgorithm - the signing algorithm to use * @param {Date} issuedAt - the time of issuance of the token * @param {Date} expiresAt - the time of expiration of the token * @returns {Object} - the signed profile token */ function signProfileToken(profile, privateKey) { var subject = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var issuer = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; var signingAlgorithm = arguments.length > 4 && arguments[4] !== undefined ? arguments[4] : 'ES256K'; var issuedAt = arguments.length > 5 && arguments[5] !== undefined ? arguments[5] : new Date(); var expiresAt = arguments.length > 6 && arguments[6] !== undefined ? arguments[6] : (0, _utils.nextYear)(); if (signingAlgorithm !== 'ES256K') { throw new Error('Signing algorithm not supported'); } var publicKey = _jsontokens.SECP256K1Client.derivePublicKey(privateKey); if (subject === null) { subject = { publicKey: publicKey }; } if (issuer === null) { issuer = { publicKey: publicKey }; } var tokenSigner = new _jsontokens.TokenSigner(signingAlgorithm, privateKey); var payload = { jti: (0, _utils.makeUUID4)(), iat: issuedAt.toISOString(), exp: expiresAt.toISOString(), subject: subject, issuer: issuer, claim: profile }; return tokenSigner.sign(payload); } /** * Wraps a token for a profile token file * @param {String} token - the token to be wrapped * @returns {Object} - including `token` and `decodedToken` */ function wrapProfileToken(token) { return { token: token, decodedToken: (0, _jsontokens.decodeToken)(token) }; } /** * Verifies a profile token * @param {String} token - the token to be verified * @param {String} publicKeyOrAddress - the public key or address of the * keypair that is thought to have signed the token * @returns {Object} - the verified, decoded profile token * @throws {Error} - throws an error if token verification fails */ function verifyProfileToken(token, publicKeyOrAddress) { var decodedToken = (0, _jsontokens.decodeToken)(token); var payload = decodedToken.payload; // Inspect and verify the subject if (payload.hasOwnProperty('subject')) { if (!payload.subject.hasOwnProperty('publicKey')) { throw new Error('Token doesn\'t have a subject public key'); } } else { throw new Error('Token doesn\'t have a subject'); } // Inspect and verify the issuer if (payload.hasOwnProperty('issuer')) { if (!payload.issuer.hasOwnProperty('publicKey')) { throw new Error('Token doesn\'t have an issuer public key'); } } else { throw new Error('Token doesn\'t have an issuer'); } // Inspect and verify the claim if (!payload.hasOwnProperty('claim')) { throw new Error('Token doesn\'t have a claim'); } var issuerPublicKey = payload.issuer.publicKey; var publicKeyBuffer = new Buffer(issuerPublicKey, 'hex'); var compressedKeyPair = _bitcoinjsLib.ECPair.fromPublicKey(publicKeyBuffer, { compressed: true }); var compressedAddress = (0, _utils.ecPairToAddress)(compressedKeyPair); var uncompressedKeyPair = _bitcoinjsLib.ECPair.fromPublicKey(publicKeyBuffer, { compressed: false }); var uncompressedAddress = (0, _utils.ecPairToAddress)(uncompressedKeyPair); if (publicKeyOrAddress === issuerPublicKey) { // pass } else if (publicKeyOrAddress === compressedAddress) { // pass } else if (publicKeyOrAddress === uncompressedAddress) { // pass } else { throw new Error('Token issuer public key does not match the verifying value'); } var tokenVerifier = new _jsontokens.TokenVerifier(decodedToken.header.alg, issuerPublicKey); if (!tokenVerifier) { throw new Error('Invalid token verifier'); } var tokenVerified = tokenVerifier.verify(token); if (!tokenVerified) { throw new Error('Token verification failed'); } return decodedToken; } /** * Extracts a profile from an encoded token and optionally verifies it, * if `publicKeyOrAddress` is provided. * @param {String} token - the token to be extracted * @param {String} publicKeyOrAddress - the public key or address of the * keypair that is thought to have signed the token * @returns {Object} - the profile extracted from the encoded token * @throws {Error} - if the token isn't signed by the provided `publicKeyOrAddress` */ function extractProfile(token) { var publicKeyOrAddress = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; var decodedToken = void 0; if (publicKeyOrAddress) { decodedToken = verifyProfileToken(token, publicKeyOrAddress); } else { decodedToken = (0, _jsontokens.decodeToken)(token); } var profile = {}; if (decodedToken.hasOwnProperty('payload')) { var payload = decodedToken.payload; if (payload.hasOwnProperty('claim')) { profile = decodedToken.payload.claim; } } return profile; } }).call(this,require("buffer").Buffer) },{"../utils":46,"bitcoinjs-lib":92,"buffer":179,"jsontokens":384}],34:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.makeProfileZoneFile = makeProfileZoneFile; exports.getTokenFileUrl = getTokenFileUrl; exports.resolveZoneFileToProfile = resolveZoneFileToProfile; var _zoneFile = require('zone-file'); var _profileTokens = require('./profileTokens'); var _index = require('./index'); var _logger = require('../logger'); function makeProfileZoneFile(origin, tokenFileUrl) { if (tokenFileUrl.indexOf('://') < 0) { throw new Error('Invalid token file url'); } var urlScheme = tokenFileUrl.split('://')[0]; var urlParts = tokenFileUrl.split('://')[1].split('/'); var domain = urlParts[0]; var pathname = '/' + urlParts.slice(1).join('/'); var zoneFile = { $origin: origin, $ttl: 3600, uri: [{ name: '_http._tcp', priority: 10, weight: 1, target: urlScheme + '://' + domain + pathname }] }; var zoneFileTemplate = '{$origin}\n{$ttl}\n{uri}\n'; return (0, _zoneFile.makeZoneFile)(zoneFile, zoneFileTemplate); } function getTokenFileUrl(zoneFileJson) { if (!zoneFileJson.hasOwnProperty('uri')) { return null; } if (!Array.isArray(zoneFileJson.uri)) { return null; } if (zoneFileJson.uri.length < 1) { return null; } var firstUriRecord = zoneFileJson.uri[0]; if (!firstUriRecord.hasOwnProperty('target')) { return null; } var tokenFileUrl = firstUriRecord.target; if (tokenFileUrl.startsWith('https')) { // pass } else if (tokenFileUrl.startsWith('http')) { // pass } else { tokenFileUrl = 'https://' + tokenFileUrl; } return tokenFileUrl; } function resolveZoneFileToProfile(zoneFile, publicKeyOrAddress) { return new Promise(function (resolve, reject) { var zoneFileJson = null; try { zoneFileJson = (0, _zoneFile.parseZoneFile)(zoneFile); if (!zoneFileJson.hasOwnProperty('$origin')) { zoneFileJson = null; } } catch (e) { reject(e); } var tokenFileUrl = null; if (zoneFileJson && Object.keys(zoneFileJson).length > 0) { tokenFileUrl = getTokenFileUrl(zoneFileJson); } else { var profile = null; try { profile = JSON.parse(zoneFile); profile = _index.Person.fromLegacyFormat(profile).profile(); } catch (error) { reject(error); } resolve(profile); return; } if (tokenFileUrl) { fetch(tokenFileUrl).then(function (response) { return response.text(); }).then(function (responseText) { return JSON.parse(responseText); }).then(function (responseJson) { var tokenRecords = responseJson; var profile = (0, _profileTokens.extractProfile)(tokenRecords[0].token, publicKeyOrAddress); resolve(profile); }).catch(function (error) { _logger.Logger.error('resolveZoneFileToProfile: error fetching token file ' + tokenFileUrl, error); reject(error); }); } else { _logger.Logger.debug('Token file url not found. Resolving to blank profile.'); resolve({}); } }); } },{"../logger":14,"./index":22,"./profileTokens":33,"zone-file":566}],35:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Facebook = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _cheerio = require('cheerio'); var _cheerio2 = _interopRequireDefault(_cheerio); var _service = require('./service'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Facebook = function (_Service) { _inherits(Facebook, _Service); function Facebook() { _classCallCheck(this, Facebook); return _possibleConstructorReturn(this, (Facebook.__proto__ || Object.getPrototypeOf(Facebook)).apply(this, arguments)); } _createClass(Facebook, null, [{ key: 'getProofUrl', value: function getProofUrl(proof) { return this.normalizeFacebookUrl(proof); } }, { key: 'normalizeFacebookUrl', value: function normalizeFacebookUrl(proof) { var proofUrl = proof.proof_url.toLowerCase(); var urlRegex = /(?:http[s]*:\/\/){0,1}(?:[a-zA-Z0-9-]+\.)+facebook\.com/; proofUrl = _get(Facebook.__proto__ || Object.getPrototypeOf(Facebook), 'prefixScheme', this).call(this, proofUrl); if (proofUrl.startsWith('https://facebook.com')) { var tokens = proofUrl.split('https://facebook.com'); proofUrl = 'https://www.facebook.com' + tokens[1]; tokens = proofUrl.split('https://www.facebook.com/')[1].split('/posts/'); var postId = tokens[1]; proofUrl = 'https://www.facebook.com/' + proof.identifier + '/posts/' + postId; } else if (proofUrl.match(urlRegex)) { var _tokens = proofUrl.split('facebook.com/')[1].split('/posts/'); var _postId = _tokens[1]; proofUrl = 'https://www.facebook.com/' + proof.identifier + '/posts/' + _postId; } else { throw new Error('Proof url ' + proof.proof_url + ' is not valid for service ' + proof.service); } return proofUrl; } }, { key: 'getProofStatement', value: function getProofStatement(searchText) { var $ = _cheerio2.default.load(searchText); var statement = $('meta[name="description"]').attr('content'); return statement !== undefined ? statement.trim() : ''; } }]); return Facebook; }(_service.Service); exports.Facebook = Facebook; },{"./service":41,"cheerio":267}],36:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Github = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _service = require('./service'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Github = function (_Service) { _inherits(Github, _Service); function Github() { _classCallCheck(this, Github); return _possibleConstructorReturn(this, (Github.__proto__ || Object.getPrototypeOf(Github)).apply(this, arguments)); } _createClass(Github, null, [{ key: 'getBaseUrls', value: function getBaseUrls() { var baseUrls = ['https://gist.github.com/', 'http://gist.github.com', 'gist.github.com']; return baseUrls; } }, { key: 'getProofUrl', value: function getProofUrl(proof) { var baseUrls = this.getBaseUrls(); var proofUrl = proof.proof_url.toLowerCase(); proofUrl = _get(Github.__proto__ || Object.getPrototypeOf(Github), 'prefixScheme', this).call(this, proofUrl); for (var i = 0; i < baseUrls.length; i++) { var requiredPrefix = ('' + baseUrls[i] + proof.identifier).toLowerCase(); if (proofUrl.startsWith(requiredPrefix)) { var raw = proofUrl.endsWith('/') ? 'raw' : '/raw'; return '' + proofUrl + raw; } } throw new Error('Proof url ' + proof.proof_url + ' is not valid for service ' + proof.service); } }]); return Github; }(_service.Service); exports.Github = Github; },{"./service":41}],37:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.HackerNews = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _cheerio = require('cheerio'); var _cheerio2 = _interopRequireDefault(_cheerio); var _service = require('./service'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var HackerNews = function (_Service) { _inherits(HackerNews, _Service); function HackerNews() { _classCallCheck(this, HackerNews); return _possibleConstructorReturn(this, (HackerNews.__proto__ || Object.getPrototypeOf(HackerNews)).apply(this, arguments)); } _createClass(HackerNews, null, [{ key: 'getBaseUrls', value: function getBaseUrls() { var baseUrls = ['https://news.ycombinator.com/user?id=', 'http://news.ycombinator.com/user?id=', 'news.ycombinator.com/user?id=']; return baseUrls; } }, { key: 'getProofUrl', value: function getProofUrl(proof) { var baseUrls = this.getBaseUrls(); var proofUrl = _get(HackerNews.__proto__ || Object.getPrototypeOf(HackerNews), 'prefixScheme', this).call(this, proof.proof_url); for (var i = 0; i < baseUrls.length; i++) { if (proofUrl === '' + baseUrls[i] + proof.identifier) { return proofUrl; } } throw new Error('Proof url ' + proof.proof_url + ' is not valid for service ' + proof.service); } }, { key: 'getProofStatement', value: function getProofStatement(searchText) { var $ = _cheerio2.default.load(searchText); var tables = $('#hnmain').children().find('table'); var statement = ''; if (tables.length > 0) { tables.each(function (tableIndex, table) { var rows = $(table).find('tr'); if (rows.length > 0) { rows.each(function (idx, row) { var heading = $(row).find('td').first().text().trim(); if (heading === 'about:') { statement = $(row).find('td').last().text().trim(); } }); } }); } return statement; } }]); return HackerNews; }(_service.Service); exports.HackerNews = HackerNews; },{"./service":41,"cheerio":267}],38:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.containsValidAddressProofStatement = exports.containsValidProofStatement = exports.profileServices = undefined; var _serviceUtils = require('./serviceUtils'); Object.defineProperty(exports, 'containsValidProofStatement', { enumerable: true, get: function get() { return _serviceUtils.containsValidProofStatement; } }); Object.defineProperty(exports, 'containsValidAddressProofStatement', { enumerable: true, get: function get() { return _serviceUtils.containsValidAddressProofStatement; } }); var _facebook = require('./facebook'); var _github = require('./github'); var _twitter = require('./twitter'); var _instagram = require('./instagram'); var _hackerNews = require('./hackerNews'); var _linkedIn = require('./linkedIn'); var profileServices = exports.profileServices = { facebook: _facebook.Facebook, github: _github.Github, twitter: _twitter.Twitter, instagram: _instagram.Instagram, hackerNews: _hackerNews.HackerNews, linkedIn: _linkedIn.LinkedIn }; },{"./facebook":35,"./github":36,"./hackerNews":37,"./instagram":39,"./linkedIn":40,"./serviceUtils":42,"./twitter":43}],39:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Instagram = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _cheerio = require('cheerio'); var _cheerio2 = _interopRequireDefault(_cheerio); var _service = require('./service'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Instagram = function (_Service) { _inherits(Instagram, _Service); function Instagram() { _classCallCheck(this, Instagram); return _possibleConstructorReturn(this, (Instagram.__proto__ || Object.getPrototypeOf(Instagram)).apply(this, arguments)); } _createClass(Instagram, null, [{ key: 'getBaseUrls', value: function getBaseUrls() { var baseUrls = ['https://www.instagram.com/', 'https://instagram.com/']; return baseUrls; } }, { key: 'getProofUrl', value: function getProofUrl(proof) { var baseUrls = this.getBaseUrls(); var normalizedProofUrl = this.normalizeInstagramUrl(proof); for (var i = 0; i < baseUrls.length; i++) { if (normalizedProofUrl.startsWith('' + baseUrls[i])) { return normalizedProofUrl; } } throw new Error('Proof url ' + proof.proof_url + ' is not valid for service ' + proof.service); } }, { key: 'normalizeInstagramUrl', value: function normalizeInstagramUrl(proof) { var proofUrl = proof.proof_url; proofUrl = _get(Instagram.__proto__ || Object.getPrototypeOf(Instagram), 'prefixScheme', this).call(this, proofUrl); if (proofUrl.startsWith('https://instagram.com')) { var tokens = proofUrl.split('https://instagram.com'); proofUrl = 'https://www.instagram.com' + tokens[1]; } return proofUrl; } }, { key: 'shouldValidateIdentityInBody', value: function shouldValidateIdentityInBody() { return true; } }, { key: 'getProofIdentity', value: function getProofIdentity(searchText) { var $ = _cheerio2.default.load(searchText); var username = $('meta[property="og:description"]').attr('content'); if (username !== undefined && username.split(':').length > 1) { return username.split(':')[0].match(/(@\w+)/)[0].substr(1); } else { return ''; } } }, { key: 'getProofStatement', value: function getProofStatement(searchText) { var $ = _cheerio2.default.load(searchText); var statement = $('meta[property="og:description"]').attr('content'); if (statement !== undefined && statement.split(':').length > 1) { return statement.split(':')[1].trim().replace('“', '').replace('”', ''); } else { return ''; } } }]); return Instagram; }(_service.Service); exports.Instagram = Instagram; },{"./service":41,"cheerio":267}],40:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.LinkedIn = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _get = function get(object, property, receiver) { if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { return get(parent, property, receiver); } } else if ("value" in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } }; var _cheerio = require('cheerio'); var _cheerio2 = _interopRequireDefault(_cheerio); var _service = require('./service'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var LinkedIn = function (_Service) { _inherits(LinkedIn, _Service); function LinkedIn() { _classCallCheck(this, LinkedIn); return _possibleConstructorReturn(this, (LinkedIn.__proto__ || Object.getPrototypeOf(LinkedIn)).apply(this, arguments)); } _createClass(LinkedIn, null, [{ key: 'getBaseUrls', value: function getBaseUrls() { var baseUrls = ['https://www.linkedin.com/feed/update/', 'http://www.linkedin.com/feed/update/', 'www.linkedin.com/feed/update/']; return baseUrls; } }, { key: 'getProofUrl', value: function getProofUrl(proof) { var baseUrls = this.getBaseUrls(); var proofUrl = proof.proof_url.toLowerCase(); proofUrl = _get(LinkedIn.__proto__ || Object.getPrototypeOf(LinkedIn), 'prefixScheme', this).call(this, proofUrl); for (var i = 0; i < baseUrls.length; i++) { if (proofUrl.startsWith('' + baseUrls[i])) { return proofUrl; } } throw new Error('Proof url ' + proof.proof_url + ' is not valid for service ' + proof.service); } }, { key: 'shouldValidateIdentityInBody', value: function shouldValidateIdentityInBody() { return true; } }, { key: 'getProofIdentity', value: function getProofIdentity(searchText) { var $ = _cheerio2.default.load(searchText); var profileLink = $('article').find('.post-meta__profile-link'); if (profileLink !== undefined) { if (profileLink.attr('href') === undefined) { return ''; } return profileLink.attr('href').split('/').pop(); } else { return ''; } } }, { key: 'getProofStatement', value: function getProofStatement(searchText) { var $ = _cheerio2.default.load(searchText); var postContent = $('article').find('.commentary'); var statement = ''; if (postContent !== undefined) { statement = postContent.text(); } return statement; } }]); return LinkedIn; }(_service.Service); exports.LinkedIn = LinkedIn; },{"./service":41,"cheerio":267}],41:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Service = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); require('cross-fetch/polyfill'); var _serviceUtils = require('./serviceUtils'); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Service = exports.Service = function () { function Service() { _classCallCheck(this, Service); } _createClass(Service, null, [{ key: 'validateProof', value: function validateProof(proof, ownerAddress) { var _this = this; var name = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : null; var proofUrl = void 0; return Promise.resolve().then(function () { proofUrl = _this.getProofUrl(proof); return fetch(proofUrl); }).then(function (res) { if (res.status !== 200) { throw new Error('Proof url ' + proofUrl + ' returned unexpected http status ' + res.status + '.\n Unable to validate proof.'); } return res.text(); }).then(function (text) { // Validate identity in provided proof body/tags if required if (_this.shouldValidateIdentityInBody() && proof.identifier !== _this.getProofIdentity(text)) { return proof; } var proofText = _this.getProofStatement(text); proof.valid = (0, _serviceUtils.containsValidProofStatement)(proofText, name) || (0, _serviceUtils.containsValidAddressProofStatement)(proofText, ownerAddress); return proof; }).catch(function (error) { console.error(error); proof.valid = false; return proof; }); } }, { key: 'getBaseUrls', value: function getBaseUrls() { return []; } }, { key: 'getProofIdentity', value: function getProofIdentity(searchText) { return searchText; } }, { key: 'getProofStatement', value: function getProofStatement(searchText) { return searchText; } }, { key: 'shouldValidateIdentityInBody', value: function shouldValidateIdentityInBody() { return false; } }, { key: 'prefixScheme', value: function prefixScheme(proofUrl) { if (!proofUrl.startsWith('https://') && !proofUrl.startsWith('http://')) { return 'https://' + proofUrl; } else if (proofUrl.startsWith('http://')) { return proofUrl.replace('http://', 'https://'); } else { return proofUrl; } } }, { key: 'getProofUrl', value: function getProofUrl(proof) { var baseUrls = this.getBaseUrls(); var proofUrl = proof.proof_url.toLowerCase(); proofUrl = this.prefixScheme(proofUrl); for (var i = 0; i < baseUrls.length; i++) { var requiredPrefix = ('' + baseUrls[i] + proof.identifier).toLowerCase(); if (proofUrl.startsWith(requiredPrefix)) { return proofUrl; } } throw new Error('Proof url ' + proof.proof_url + ' is not valid for service ' + proof.service); } }]); return Service; }(); },{"./serviceUtils":42,"cross-fetch/polyfill":283}],42:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.containsValidProofStatement = containsValidProofStatement; exports.containsValidAddressProofStatement = containsValidAddressProofStatement; function containsValidProofStatement(searchText) { var name = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null; if (!name) { return false; } searchText = searchText.toLowerCase(); if (name.split('.').length < 2) { throw new Error('Please provide the fully qualified Blockstack name.'); } var username = null; // support legacy Blockstack ID proofs if (name.endsWith('.id')) { username = name.split('.id')[0]; } var verificationStyles = username != null ? ['verifying myself: my bitcoin username is +' + username, 'verifying myself: my bitcoin username is ' + username, 'verifying myself: my openname is ' + username, 'verifying that +' + username + ' is my bitcoin username', 'verifying that ' + username + ' is my bitcoin username', 'verifying that ' + username + ' is my openname', 'verifying that +' + username + ' is my openname', 'verifying i am +' + username + ' on my passcard', 'verifying that +' + username + ' is my blockchain id', 'verifying that "' + name + '" is my blockstack id', // id 'verifying that ' + name + ' is my blockstack id', 'verifying that "' + name + '" is my blockstack id'] : [// only these formats are valid for non-.id tlds 'verifying that "' + name + '" is my blockstack id', // id 'verifying that ' + name + ' is my blockstack id', 'verifying that "' + name + '" is my blockstack id']; for (var i = 0; i < verificationStyles.length; i++) { var verificationStyle = verificationStyles[i]; if (searchText.includes(verificationStyle)) { return true; } } if (username != null && searchText.includes('verifymyonename') && searchText.includes('+' + username)) { return true; } return false; } function containsValidAddressProofStatement(proofStatement, address) { proofStatement = proofStatement.split(address)[0].toLowerCase() + address; var verificationStyles = ['verifying my blockstack id is secured with the address ' + address]; for (var i = 0; i < verificationStyles.length; i++) { var verificationStyle = verificationStyles[i]; if (proofStatement.includes(verificationStyle)) { return true; } } return false; } },{}],43:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Twitter = undefined; var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _cheerio = require('cheerio'); var _cheerio2 = _interopRequireDefault(_cheerio); var _service = require('./service'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; } function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } var Twitter = function (_Service) { _inherits(Twitter, _Service); function Twitter() { _classCallCheck(this, Twitter); return _possibleConstructorReturn(this, (Twitter.__proto__ || Object.getPrototypeOf(Twitter)).apply(this, arguments)); } _createClass(Twitter, null, [{ key: 'getBaseUrls', value: function getBaseUrls() { var baseUrls = ['https://twitter.com/', 'http://twitter.com/', 'twitter.com/']; return baseUrls; } }, { key: 'getProofStatement', value: function getProofStatement(searchText) { var $ = _cheerio2.default.load(searchText); var statement = $('meta[property="og:description"]').attr('content'); if (statement !== undefined) { return statement.trim().replace('“', '').replace('”', ''); } else { return ''; } } }]); return Twitter; }(_service.Service); exports.Twitter = Twitter; },{"./service":41,"cheerio":267}],44:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.BLOCKSTACK_GAIA_HUB_LABEL = undefined; exports.uploadToGaiaHub = uploadToGaiaHub; exports.getFullReadUrl = getFullReadUrl; exports.connectToGaiaHub = connectToGaiaHub; exports.setLocalGaiaHubConnection = setLocalGaiaHubConnection; exports.getOrSetLocalGaiaHubConnection = getOrSetLocalGaiaHubConnection; exports.getBucketUrl = getBucketUrl; var _bitcoinjsLib = require('bitcoinjs-lib'); var _bitcoinjsLib2 = _interopRequireDefault(_bitcoinjsLib); var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto); var _jsontokens = require('jsontokens'); var _authApp = require('../auth/authApp'); var _utils = require('../utils'); var _index = require('../index'); var _authConstants = require('../auth/authConstants'); var _logger = require('../logger'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var BLOCKSTACK_GAIA_HUB_LABEL = exports.BLOCKSTACK_GAIA_HUB_LABEL = 'blockstack-gaia-hub-config'; function uploadToGaiaHub(filename, contents, hubConfig) { var contentType = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : 'application/octet-stream'; _logger.Logger.debug('uploadToGaiaHub: uploading ' + filename + ' to ' + hubConfig.server); return fetch(hubConfig.server + '/store/' + hubConfig.address + '/' + filename, { method: 'POST', headers: { 'Content-Type': contentType, Authorization: 'bearer ' + hubConfig.token }, body: contents }).then(function (response) { if (response.ok) { return response.text(); } else { throw new Error('Error when uploading to Gaia hub'); } }).then(function (responseText) { return JSON.parse(responseText); }).then(function (responseJSON) { return responseJSON.publicURL; }); } function getFullReadUrl(filename, hubConfig) { return '' + hubConfig.url_prefix + hubConfig.address + '/' + filename; } function makeLegacyAuthToken(challengeText, signerKeyHex) { // only sign specific legacy auth challenges. var parsedChallenge = void 0; try { parsedChallenge = JSON.parse(challengeText); } catch (err) { throw new Error('Failed in parsing legacy challenge text from the gaia hub.'); } if (parsedChallenge[0] === 'gaiahub' && parsedChallenge[3] === 'blockstack_storage_please_sign') { var signer = (0, _index.hexStringToECPair)(signerKeyHex + (signerKeyHex.length === 64 ? '01' : '')); var digest = _bitcoinjsLib2.default.crypto.sha256(challengeText); var signature = signer.sign(digest).toDER().toString('hex'); var publickey = (0, _index.getPublicKeyFromPrivate)(signerKeyHex); var _token = Buffer.from(JSON.stringify({ publickey: publickey, signature: signature })).toString('base64'); return _token; } else { throw new Error('Failed to connect to legacy gaia hub. If you operate this hub, please update.'); } } function makeV1GaiaAuthToken(hubInfo, signerKeyHex, hubUrl, associationToken) { var challengeText = hubInfo.challenge_text; var handlesV1Auth = hubInfo.latest_auth_version && parseInt(hubInfo.latest_auth_version.slice(1), 10) >= 1; var iss = (0, _index.getPublicKeyFromPrivate)(signerKeyHex); if (!handlesV1Auth) { return makeLegacyAuthToken(challengeText, signerKeyHex); } var salt = _crypto2.default.randomBytes(16).toString('hex'); var payload = { gaiaChallenge: challengeText, hubUrl: hubUrl, iss: iss, salt: salt, associationToken: associationToken }; var token = new _jsontokens.TokenSigner('ES256K', signerKeyHex).sign(payload); return 'v1:' + token; } function connectToGaiaHub(gaiaHubUrl, challengeSignerHex, associationToken) { if (!associationToken) { // maybe given in local storage? try { var userData = (0, _authApp.loadUserData)(); if (userData && userData.gaiaAssociationToken) { associationToken = userData.gaiaAssociationToken; } } catch (e) { associationToken = undefined; } } _logger.Logger.debug('connectToGaiaHub: ' + gaiaHubUrl + '/hub_info'); return fetch(gaiaHubUrl + '/hub_info').then(function (response) { return response.json(); }).then(function (hubInfo) { var readURL = hubInfo.read_url_prefix; var token = makeV1GaiaAuthToken(hubInfo, challengeSignerHex, gaiaHubUrl, associationToken); var address = (0, _utils.ecPairToAddress)((0, _index.hexStringToECPair)(challengeSignerHex + (challengeSignerHex.length === 64 ? '01' : ''))); return { url_prefix: readURL, address: address, token: token, server: gaiaHubUrl }; }); } /** * These two functions are app-specific connections to gaia hub, * they read the user data object for information on setting up * a hub connection, and store the hub config to localstorage * @private * @returns {Promise} that resolves to the new gaia hub connection */ function setLocalGaiaHubConnection() { var userData = (0, _authApp.loadUserData)(); if (!userData.hubUrl) { userData.hubUrl = _authConstants.BLOCKSTACK_DEFAULT_GAIA_HUB_URL; window.localStorage.setItem(_authConstants.BLOCKSTACK_STORAGE_LABEL, JSON.stringify(userData)); userData = (0, _authApp.loadUserData)(); } return connectToGaiaHub(userData.hubUrl, userData.appPrivateKey, userData.associationToken).then(function (gaiaConfig) { localStorage.setItem(BLOCKSTACK_GAIA_HUB_LABEL, JSON.stringify(gaiaConfig)); return gaiaConfig; }); } function getOrSetLocalGaiaHubConnection() { var hubConfig = localStorage.getItem(BLOCKSTACK_GAIA_HUB_LABEL); if (hubConfig) { var hubJSON = JSON.parse(hubConfig); if (hubJSON !== null) { return Promise.resolve(hubJSON); } } return setLocalGaiaHubConnection(); } function getBucketUrl(gaiaHubUrl, appPrivateKey) { var challengeSigner = void 0; try { challengeSigner = _bitcoinjsLib2.default.ECPair.fromPrivateKey(new Buffer(appPrivateKey, 'hex')); } catch (e) { return Promise.reject(e); } return fetch(gaiaHubUrl + '/hub_info').then(function (response) { return response.text(); }).then(function (responseText) { return JSON.parse(responseText); }).then(function (responseJSON) { var readURL = responseJSON.read_url_prefix; var address = (0, _utils.ecPairToAddress)(challengeSigner); var bucketUrl = '' + readURL + address + '/'; return bucketUrl; }); } }).call(this,require("buffer").Buffer) },{"../auth/authApp":1,"../auth/authConstants":2,"../index":12,"../logger":14,"../utils":46,"bitcoinjs-lib":92,"buffer":179,"crypto":188,"jsontokens":384}],45:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.BLOCKSTACK_GAIA_HUB_LABEL = exports.uploadToGaiaHub = exports.connectToGaiaHub = undefined; var _slicedToArray = function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"]) _i["return"](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError("Invalid attempt to destructure non-iterable instance"); } }; }(); // export { type GaiaHubConfig } from './hub' exports.getUserAppFileUrl = getUserAppFileUrl; exports.encryptContent = encryptContent; exports.decryptContent = decryptContent; exports.getFile = getFile; exports.putFile = putFile; exports.getAppBucketUrl = getAppBucketUrl; exports.deleteFile = deleteFile; exports.listFiles = listFiles; var _hub = require('./hub'); var _encryption = require('../encryption'); var _auth = require('../auth'); var _keys = require('../keys'); var _profiles = require('../profiles'); var _errors = require('../errors'); var _logger = require('../logger'); var SIGNATURE_FILE_SUFFIX = '.sig'; /** * Fetch the public read URL of a user file for the specified app. * @param {String} path - the path to the file to read * @param {String} username - The Blockstack ID of the user to look up * @param {String} appOrigin - The app origin * @param {String} [zoneFileLookupURL=null] - The URL * to use for zonefile lookup. If falsey, this will use the * blockstack.js's getNameInfo function instead. * @return {Promise} that resolves to the public read URL of the file * or rejects with an error */ function getUserAppFileUrl(path, username, appOrigin) { var zoneFileLookupURL = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : null; return (0, _profiles.lookupProfile)(username, zoneFileLookupURL).then(function (profile) { if (profile.hasOwnProperty('apps')) { if (profile.apps.hasOwnProperty(appOrigin)) { return profile.apps[appOrigin]; } else { return null; } } else { return null; } }).then(function (bucketUrl) { if (bucketUrl) { var bucket = bucketUrl.replace(/\/?(\?|#|$)/, '/$1'); return '' + bucket + path; } else { return null; } }); } /** * Encrypts the data provided with the app public key. * @param {String|Buffer} content - data to encrypt * @param {Object} [options=null] - options object * @param {String} options.publicKey - the hex string of the ECDSA public * key to use for encryption. If not provided, will use user's appPrivateKey. * @return {String} Stringified ciphertext object */ function encryptContent(content, options) { var defaults = { publicKey: null }; var opt = Object.assign({}, defaults, options); if (!opt.publicKey) { var privateKey = (0, _auth.loadUserData)().appPrivateKey; opt.publicKey = (0, _keys.getPublicKeyFromPrivate)(privateKey); } var cipherObject = (0, _encryption.encryptECIES)(opt.publicKey, content); return JSON.stringify(cipherObject); } /** * Decrypts data encrypted with `encryptContent` with the * transit private key. * @param {String|Buffer} content - encrypted content. * @param {Object} [options=null] - options object * @param {String} options.privateKey - the hex string of the ECDSA private * key to use for decryption. If not provided, will use user's appPrivateKey. * @return {String|Buffer} decrypted content. */ function decryptContent(content, options) { var defaults = { privateKey: null }; var opt = Object.assign({}, defaults, options); var privateKey = opt.privateKey; if (!privateKey) { privateKey = (0, _auth.loadUserData)().appPrivateKey; } try { var cipherObject = JSON.parse(content); return (0, _encryption.decryptECIES)(privateKey, cipherObject); } catch (err) { if (err instanceof SyntaxError) { throw new Error('Failed to parse encrypted content JSON. The content may not ' + 'be encrypted. If using getFile, try passing { decrypt: false }.'); } else { throw err; } } } /* Get the gaia address used for servicing multiplayer reads for the given * (username, app) pair. * @private */ function getGaiaAddress(app, username, zoneFileLookupURL) { return Promise.resolve().then(function () { if (username) { return getUserAppFileUrl('/', username, app, zoneFileLookupURL); } else { return (0, _hub.getOrSetLocalGaiaHubConnection)().then(function (gaiaHubConfig) { return (0, _hub.getFullReadUrl)('/', gaiaHubConfig); }); } }).then(function (fileUrl) { var matches = fileUrl.match(/([13][a-km-zA-HJ-NP-Z0-9]{26,35})/); if (!matches) { throw new Error('Failed to parse gaia address'); } return matches[matches.length - 1]; }); } /* Handle fetching the contents from a given path. Handles both * multi-player reads and reads from own storage. * @private */ function getFileContents(path, app, username, zoneFileLookupURL, forceText) { return Promise.resolve().then(function () { if (username) { return getUserAppFileUrl(path, username, app, zoneFileLookupURL); } else { return (0, _hub.getOrSetLocalGaiaHubConnection)().then(function (gaiaHubConfig) { return (0, _hub.getFullReadUrl)(path, gaiaHubConfig); }); } }).then(function (readUrl) { return new Promise(function (resolve, reject) { if (!readUrl) { reject(null); } else { resolve(readUrl); } }); }).then(function (readUrl) { return fetch(readUrl); }).then(function (response) { if (response.status !== 200) { if (response.status === 404) { _logger.Logger.debug('getFile ' + path + ' returned 404, returning null'); return null; } else { throw new Error('getFile ' + path + ' failed with HTTP status ' + response.status); } } var contentType = response.headers.get('Content-Type'); if (forceText || contentType === null || contentType.startsWith('text') || contentType === 'application/json') { return response.text(); } else { return response.arrayBuffer(); } }); } /* Handle fetching an unencrypted file, its associated signature * and then validate it. Handles both multi-player reads and reads * from own storage. * @private */ function getFileSignedUnencrypted(path, opt) { // future optimization note: // in the case of _multi-player_ reads, this does a lot of excess // profile lookups to figure out where to read files // do browsers cache all these requests if Content-Cache is set? return Promise.all([getFileContents(path, opt.app, opt.username, opt.zoneFileLookupURL, false), getFileContents('' + path + SIGNATURE_FILE_SUFFIX, opt.app, opt.username, opt.zoneFileLookupURL, true), getGaiaAddress(opt.app, opt.username, opt.zoneFileLookupURL)]).then(function (_ref) { var _ref2 = _slicedToArray(_ref, 3), fileContents = _ref2[0], signatureContents = _ref2[1], gaiaAddress = _ref2[2]; if (!fileContents) { return fileContents; } if (!gaiaAddress) { throw new _errors.SignatureVerificationError('Failed to get gaia address for verification of: ' + ('' + path)); } if (!signatureContents || typeof signatureContents !== 'string') { throw new _errors.SignatureVerificationError('Failed to obtain signature for file: ' + (path + ' -- looked in ' + path + SIGNATURE_FILE_SUFFIX)); } var signature = void 0; var publicKey = void 0; try { var sigObject = JSON.parse(signatureContents); signature = sigObject.signature; publicKey = sigObject.publicKey; } catch (err) { if (err instanceof SyntaxError) { throw new Error('Failed to parse signature content JSON ' + ('(path: ' + path + SIGNATURE_FILE_SUFFIX + ')') + ' The content may be corrupted.'); } else { throw err; } } var signerAddress = (0, _keys.publicKeyToAddress)(publicKey); if (gaiaAddress !== signerAddress) { throw new _errors.SignatureVerificationError('Signer pubkey address (' + signerAddress + ') doesn\'t' + (' match gaia address (' + gaiaAddress + ')')); } else if (!(0, _encryption.verifyECDSA)(Buffer.from(fileContents), publicKey, signature)) { throw new _errors.SignatureVerificationError('Contents do not match ECDSA signature: ' + ('path: ' + path + ', signature: ' + path + SIGNATURE_FILE_SUFFIX)); } else { return fileContents; } }); } /* Handle signature verification and decryption for contents which are * expected to be signed and encrypted. This works for single and * multiplayer reads. In the case of multiplayer reads, it uses the * gaia address for verification of the claimed public key. * @private */ function handleSignedEncryptedContents(path, storedContents, app, username, zoneFileLookupURL) { var appPrivateKey = (0, _auth.loadUserData)().appPrivateKey; var appPublicKey = (0, _keys.getPublicKeyFromPrivate)(appPrivateKey); var addressPromise = void 0; if (username) { addressPromise = getGaiaAddress(app, username, zoneFileLookupURL); } else { var address = (0, _keys.publicKeyToAddress)(appPublicKey); addressPromise = Promise.resolve(address); } return addressPromise.then(function (address) { if (!address) { throw new _errors.SignatureVerificationError('Failed to get gaia address for verification of: ' + ('' + path)); } var sigObject = void 0; try { sigObject = JSON.parse(storedContents); } catch (err) { if (err instanceof SyntaxError) { throw new Error('Failed to parse encrypted, signed content JSON. The content may not ' + 'be encrypted. If using getFile, try passing' + ' { verify: false, decrypt: false }.'); } else { throw err; } } var signature = sigObject.signature; var signerPublicKey = sigObject.publicKey; var cipherText = sigObject.cipherText; var signerAddress = (0, _keys.publicKeyToAddress)(signerPublicKey); if (!signerPublicKey || !cipherText || !signature) { throw new _errors.SignatureVerificationError('Failed to get signature verification data from file:' + (' ' + path)); } else if (signerAddress !== address) { throw new _errors.SignatureVerificationError('Signer pubkey address (' + signerAddress + ') doesn\'t' + (' match gaia address (' + address + ')')); } else if (!(0, _encryption.verifyECDSA)(cipherText, signerPublicKey, signature)) { throw new _errors.SignatureVerificationError('Contents do not match ECDSA signature in file:' + (' ' + path)); } else { return decryptContent(cipherText); } }); } /** * Retrieves the specified file from the app's data store. * @param {String} path - the path to the file to read * @param {Object} [options=null] - options object * @param {Boolean} [options.decrypt=true] - try to decrypt the data with the app private key * @param {String} options.username - the Blockstack ID to lookup for multi-player storage * @param {Boolean} options.verify - Whether the content should be verified, only to be used * when `putFile` was set to `sign = true` * @param {String} options.app - the app to lookup for multi-player storage - * defaults to current origin * @param {String} [options.zoneFileLookupURL=null] - The URL * to use for zonefile lookup. If falsey, this will use the * blockstack.js's getNameInfo function instead. * @returns {Promise} that resolves to the raw data in the file * or rejects with an error */ function getFile(path, options) { var defaults = { decrypt: true, verify: false, username: null, app: window.location.origin, zoneFileLookupURL: null }; var opt = Object.assign({}, defaults, options); // in the case of signature verification, but no // encryption expected, need to fetch _two_ files. if (opt.verify && !opt.decrypt) { return getFileSignedUnencrypted(path, opt); } return getFileContents(path, opt.app, opt.username, opt.zoneFileLookupURL, !!opt.decrypt).then(function (storedContents) { if (storedContents === null) { return storedContents; } else if (opt.decrypt && !opt.verify) { if (typeof storedContents !== 'string') { throw new Error('Expected to get back a string for the cipherText'); } return decryptContent(storedContents); } else if (opt.decrypt && opt.verify) { if (typeof storedContents !== 'string') { throw new Error('Expected to get back a string for the cipherText'); } return handleSignedEncryptedContents(path, storedContents, opt.app, opt.username, opt.zoneFileLookupURL); } else if (!opt.verify && !opt.decrypt) { return storedContents; } else { throw new Error('Should be unreachable.'); } }); } /** * Stores the data provided in the app's data store to to the file specified. * @param {String} path - the path to store the data in * @param {String|Buffer} content - the data to store in the file * @param {Object} [options=null] - options object * @param {Boolean|String} [options.encrypt=true] - encrypt the data with the app private key * or the provided public key * @param {Boolean} [options.sign=false] - sign the data using ECDSA on SHA256 hashes with * the app private key * @param {String} [options.contentType=''] - set a Content-Type header for unencrypted data * @return {Promise} that resolves if the operation succeed and rejects * if it failed */ function putFile(path, content, options) { var defaults = { encrypt: true, sign: false, contentType: '' }; var opt = Object.assign({}, defaults, options); var contentType = opt.contentType; if (!contentType) { contentType = typeof content === 'string' ? 'text/plain; charset=utf-8' : 'application/octet-stream'; } // First, let's figure out if we need to get public/private keys, // or if they were passed in var privateKey = ''; var publicKey = ''; if (opt.sign) { if (typeof opt.sign === 'string') { privateKey = opt.sign; } else { privateKey = (0, _auth.loadUserData)().appPrivateKey; } } if (opt.encrypt) { if (typeof opt.encrypt === 'string') { publicKey = opt.encrypt; } else { if (!privateKey) { privateKey = (0, _auth.loadUserData)().appPrivateKey; } publicKey = (0, _keys.getPublicKeyFromPrivate)(privateKey); } } // In the case of signing, but *not* encrypting, // we perform two uploads. So the control-flow // here will return there. if (!opt.encrypt && opt.sign) { var signatureObject = (0, _encryption.signECDSA)(privateKey, content); var signatureContent = JSON.stringify(signatureObject); return (0, _hub.getOrSetLocalGaiaHubConnection)().then(function (gaiaHubConfig) { return new Promise(function (resolve, reject) { return Promise.all([(0, _hub.uploadToGaiaHub)(path, content, gaiaHubConfig, contentType), (0, _hub.uploadToGaiaHub)('' + path + SIGNATURE_FILE_SUFFIX, signatureContent, gaiaHubConfig, 'application/json')]).then(resolve).catch(function () { (0, _hub.setLocalGaiaHubConnection)().then(function (freshHubConfig) { return Promise.all([(0, _hub.uploadToGaiaHub)(path, content, freshHubConfig, contentType), (0, _hub.uploadToGaiaHub)('' + path + SIGNATURE_FILE_SUFFIX, signatureContent, freshHubConfig, 'application/json')]).then(resolve).catch(reject); }); }); }); }).then(function (fileUrls) { return fileUrls[0]; }); } // In all other cases, we only need one upload. if (opt.encrypt && !opt.sign) { content = encryptContent(content, { publicKey: publicKey }); contentType = 'application/json'; } else if (opt.encrypt && opt.sign) { var cipherText = encryptContent(content, { publicKey: publicKey }); var _signatureObject = (0, _encryption.signECDSA)(privateKey, cipherText); var signedCipherObject = { signature: _signatureObject.signature, publicKey: _signatureObject.publicKey, cipherText: cipherText }; content = JSON.stringify(signedCipherObject); contentType = 'application/json'; } return (0, _hub.getOrSetLocalGaiaHubConnection)().then(function (gaiaHubConfig) { return new Promise(function (resolve, reject) { (0, _hub.uploadToGaiaHub)(path, content, gaiaHubConfig, contentType).then(resolve).catch(function (error) { console.log(error); return (0, _hub.setLocalGaiaHubConnection)().then(function (freshHubConfig) { return (0, _hub.uploadToGaiaHub)(path, content, freshHubConfig, contentType).then(resolve).catch(reject); }); }); }); }); } /** * Get the app storage bucket URL * @param {String} gaiaHubUrl - the gaia hub URL * @param {String} appPrivateKey - the app private key used to generate the app address * @returns {Promise} That resolves to the URL of the app index file * or rejects if it fails */ function getAppBucketUrl(gaiaHubUrl, appPrivateKey) { return (0, _hub.getBucketUrl)(gaiaHubUrl, appPrivateKey); } /** * Deletes the specified file from the app's data store. Currently not implemented. * @param {String} path - the path to the file to delete * @returns {Promise} that resolves when the file has been removed * or rejects with an error * @private */ function deleteFile(path) { Promise.reject(new Error('Delete of ' + path + ' not supported by gaia hubs')); } /** * Loop over the list of files in a Gaia hub, and run a callback on each entry. * Not meant to be called by external clients. * @param {GaiaHubConfig} hubConfig - the Gaia hub config * @param {String | null} page - the page ID * @param {number} callCount - the loop count * @param {number} fileCount - the number of files listed so far * @param {function} callback - the callback to invoke on each file. If it returns a falsey * value, then the loop stops. If it returns a truthy value, the loop continues. * @returns {Promise} that resolves to the number of files listed. * @private */ function listFilesLoop(hubConfig, page, callCount, fileCount, callback) { if (callCount > 65536) { // this is ridiculously huge, and probably indicates // a faulty Gaia hub anyway (e.g. on that serves endless data) throw new Error('Too many entries to list'); } var httpStatus = void 0; var pageRequest = JSON.stringify({ page: page }); var fetchOptions = { method: 'POST', headers: { 'Content-Type': 'application/json', 'Content-Length': '' + pageRequest.length, Authorization: 'bearer ' + hubConfig.token }, body: pageRequest }; return fetch(hubConfig.server + '/list-files/' + hubConfig.address, fetchOptions).then(function (response) { httpStatus = response.status; if (httpStatus >= 400) { throw new Error('listFiles failed with HTTP status ' + httpStatus); } return response.text(); }).then(function (responseText) { return JSON.parse(responseText); }).then(function (responseJSON) { var entries = responseJSON.entries; var nextPage = responseJSON.page; if (entries === null || entries === undefined) { // indicates a misbehaving Gaia hub or a misbehaving driver // (i.e. the data is malformed) throw new Error('Bad listFiles response: no entries'); } for (var i = 0; i < entries.length; i++) { var rc = callback(entries[i]); if (!rc) { // callback indicates that we're done return Promise.resolve(fileCount + i); } } if (nextPage && entries.length > 0) { // keep going -- have more entries return listFilesLoop(hubConfig, nextPage, callCount + 1, fileCount + entries.length, callback); } else { // no more entries -- end of data return Promise.resolve(fileCount + entries.length); } }); } /** * List the set of files in this application's Gaia storage bucket. * @param {function} callback - a callback to invoke on each named file that * returns `true` to continue the listing operation or `false` to end it * @return {Promise} that resolves to the number of files listed */ function listFiles(callback) { return (0, _hub.getOrSetLocalGaiaHubConnection)().then(function (gaiaHubConfig) { return listFilesLoop(gaiaHubConfig, null, 0, 0, callback); }); } exports.connectToGaiaHub = _hub.connectToGaiaHub; exports.uploadToGaiaHub = _hub.uploadToGaiaHub; exports.BLOCKSTACK_GAIA_HUB_LABEL = _hub.BLOCKSTACK_GAIA_HUB_LABEL; }).call(this,require("buffer").Buffer) },{"../auth":7,"../encryption":10,"../errors":11,"../keys":13,"../logger":14,"../profiles":22,"./hub":44,"buffer":179}],46:[function(require,module,exports){ (function (Buffer){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.BLOCKSTACK_HANDLER = undefined; exports.nextYear = nextYear; exports.nextMonth = nextMonth; exports.nextHour = nextHour; exports.updateQueryStringParameter = updateQueryStringParameter; exports.isLaterVersion = isLaterVersion; exports.hexStringToECPair = hexStringToECPair; exports.ecPairToHexString = ecPairToHexString; exports.ecPairToAddress = ecPairToAddress; exports.makeUUID4 = makeUUID4; exports.isSameOriginAbsoluteUrl = isSameOriginAbsoluteUrl; var _url = require('url'); var _url2 = _interopRequireDefault(_url); var _bitcoinjsLib = require('bitcoinjs-lib'); var _config = require('./config'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var BLOCKSTACK_HANDLER = exports.BLOCKSTACK_HANDLER = 'blockstack'; /** * Time * @private */ function nextYear() { return new Date(new Date().setFullYear(new Date().getFullYear() + 1)); } function nextMonth() { return new Date(new Date().setMonth(new Date().getMonth() + 1)); } function nextHour() { return new Date(new Date().setHours(new Date().getHours() + 1)); } /** * Query Strings * @private */ function updateQueryStringParameter(uri, key, value) { var re = new RegExp('([?&])' + key + '=.*?(&|$)', 'i'); var separator = uri.indexOf('?') !== -1 ? '&' : '?'; if (uri.match(re)) { return uri.replace(re, '$1' + key + '=' + value + '$2'); } else { return '' + uri + separator + key + '=' + value; } } /** * Versioning * @param {string} v1 - the left half of the version inequality * @param {string} v2 - right half of the version inequality * @returns {bool} iff v1 >= v2 * @private */ function isLaterVersion(v1, v2) { if (v1 === undefined) { v1 = '0.0.0'; } if (v2 === undefined) { v2 = '0.0.0'; } var v1tuple = v1.split('.').map(function (x) { return parseInt(x, 10); }); var v2tuple = v2.split('.').map(function (x) { return parseInt(x, 10); }); for (var index = 0; index < v2.length; index++) { if (index >= v1.length) { v2tuple.push(0); } if (v1tuple[index] < v2tuple[index]) { return false; } } return true; } function hexStringToECPair(skHex) { var ecPairOptions = { network: _config.config.network.layer1, compressed: true }; if (skHex.length === 66) { if (skHex.slice(64) !== '01') { throw new Error('Improperly formatted private-key hex string. 66-length hex usually ' + 'indicates compressed key, but last byte must be == 1'); } return _bitcoinjsLib.ECPair.fromPrivateKey(new Buffer(skHex.slice(0, 64), 'hex'), ecPairOptions); } else if (skHex.length === 64) { ecPairOptions.compressed = false; return _bitcoinjsLib.ECPair.fromPrivateKey(new Buffer(skHex, 'hex'), ecPairOptions); } else { throw new Error('Improperly formatted private-key hex string: length should be 64 or 66.'); } } function ecPairToHexString(secretKey) { var ecPointHex = secretKey.privateKey.toString('hex'); if (secretKey.compressed) { return ecPointHex + '01'; } else { return ecPointHex; } } function ecPairToAddress(keyPair) { return _bitcoinjsLib.address.toBase58Check(_bitcoinjsLib.crypto.hash160(keyPair.publicKey), keyPair.network.pubKeyHash); } /** * UUIDs * @private */ function makeUUID4() { var d = new Date().getTime(); if (typeof performance !== 'undefined' && typeof performance.now === 'function') { d += performance.now(); // use high-precision timer if available } return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) { var r = (d + Math.random() * 16) % 16 | 0; d = Math.floor(d / 16); return (c === 'x' ? r : r & 0x3 | 0x8).toString(16); }); } /** * Checks if both urls pass the same origin check & are absolute * @param {[type]} uri1 first uri to check * @param {[type]} uri2 second uri to check * @return {Boolean} true if they pass the same origin check * @private */ function isSameOriginAbsoluteUrl(uri1, uri2) { var parsedUri1 = _url2.default.parse(uri1); var parsedUri2 = _url2.default.parse(uri2); var port1 = parseInt(parsedUri1.port, 10) | 0 || (parsedUri1.protocol === 'https:' ? 443 : 80); var port2 = parseInt(parsedUri2.port, 10) | 0 || (parsedUri2.protocol === 'https:' ? 443 : 80); var match = { scheme: parsedUri1.protocol === parsedUri2.protocol, hostname: parsedUri1.hostname === parsedUri2.hostname, port: port1 === port2, absolute: (uri1.includes('http://') || uri1.includes('https://')) && (uri2.includes('http://') || uri2.includes('https://')) }; return match.scheme && match.hostname && match.port && match.absolute; } }).call(this,require("buffer").Buffer) },{"./config":8,"bitcoinjs-lib":92,"buffer":179,"url":256}],47:[function(require,module,exports){ 'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.BlockstackWallet = undefined; var _regenerator = require('babel-runtime/regenerator'); var _regenerator2 = _interopRequireDefault(_regenerator); var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }(); var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto); var _bitcoinjsLib = require('bitcoinjs-lib'); var _bitcoinjsLib2 = _interopRequireDefault(_bitcoinjsLib); var _bip = require('bip39'); var _bip2 = _interopRequireDefault(_bip); var _bip3 = require('bip32'); var _bip4 = _interopRequireDefault(_bip3); var _utils = require('./utils'); var _encryption = require('./encryption'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _asyncToGenerator(fn) { return function () { var gen = fn.apply(this, arguments); return new Promise(function (resolve, reject) { function step(key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { return Promise.resolve(value).then(function (value) { step("next", value); }, function (err) { step("throw", err); }); } } return step("next"); }); }; } function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var APPS_NODE_INDEX = 0; var IDENTITY_KEYCHAIN = 888; var BLOCKSTACK_ON_BITCOIN = 0; var BITCOIN_BIP_44_PURPOSE = 44; var BITCOIN_COIN_TYPE = 0; var BITCOIN_ACCOUNT_INDEX = 0; var EXTERNAL_ADDRESS = 'EXTERNAL_ADDRESS'; var CHANGE_ADDRESS = 'CHANGE_ADDRESS'; function hashCode(string) { var hash = 0; if (string.length === 0) return hash; for (var i = 0; i < string.length; i++) { var character = string.charCodeAt(i); hash = (hash << 5) - hash + character; hash &= hash; } return hash & 0x7fffffff; } function getNodePrivateKey(node) { return (0, _utils.ecPairToHexString)(_bitcoinjsLib.ECPair.fromPrivateKey(node.privateKey)); } function getNodePublicKey(node) { return node.publicKey.toString('hex'); } /** * The BlockstackWallet class manages the hierarchical derivation * paths for a standard blockstack client wallet. This includes paths * for bitcoin payment address, blockstack identity addresses, blockstack * application specific addresses. * @private */ var BlockstackWallet = exports.BlockstackWallet = function () { function BlockstackWallet(rootNode) { _classCallCheck(this, BlockstackWallet); this.rootNode = rootNode; } _createClass(BlockstackWallet, [{ key: 'toBase58', value: function toBase58() { return this.rootNode.toBase58(); } /** * Initialize a blockstack wallet from a seed buffer * @param {Buffer} seed - the input seed for initializing the root node * of the hierarchical wallet * @return {BlockstackWallet} the constructed wallet */ }, { key: 'getIdentityPrivateKeychain', value: function getIdentityPrivateKeychain() { return this.rootNode.deriveHardened(IDENTITY_KEYCHAIN).deriveHardened(BLOCKSTACK_ON_BITCOIN); } }, { key: 'getBitcoinPrivateKeychain', value: function getBitcoinPrivateKeychain() { return this.rootNode.deriveHardened(BITCOIN_BIP_44_PURPOSE).deriveHardened(BITCOIN_COIN_TYPE).deriveHardened(BITCOIN_ACCOUNT_INDEX); } }, { key: 'getBitcoinNode', value: function getBitcoinNode(addressIndex) { var chainType = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : EXTERNAL_ADDRESS; return BlockstackWallet.getNodeFromBitcoinKeychain(this.getBitcoinPrivateKeychain().toBase58(), addressIndex, chainType); } }, { key: 'getIdentityAddressNode', value: function getIdentityAddressNode(identityIndex) { var identityPrivateKeychain = this.getIdentityPrivateKeychain(); return identityPrivateKeychain.deriveHardened(identityIndex); } }, { key: 'getIdentitySalt', /** * Get a salt for use with creating application specific addresses * @return {String} the salt */ value: function getIdentitySalt() { var identityPrivateKeychain = this.getIdentityPrivateKeychain(); var publicKeyHex = getNodePublicKey(identityPrivateKeychain); return _crypto2.default.createHash('sha256').update(publicKeyHex).digest('hex'); } /** * Get a bitcoin receive address at a given index * @param {number} addressIndex - the index of the address * @return {String} address */ }, { key: 'getBitcoinAddress', value: function getBitcoinAddress(addressIndex) { return BlockstackWallet.getAddressFromBIP32Node(this.getBitcoinNode(addressIndex)); } /** * Get the private key hex-string for a given bitcoin receive address * @param {number} addressIndex - the index of the address * @return {String} the hex-string. this will be either 64 * characters long to denote an uncompressed bitcoin address, or 66 * characters long for a compressed bitcoin address. */ }, { key: 'getBitcoinPrivateKey', value: function getBitcoinPrivateKey(addressIndex) { return getNodePrivateKey(this.getBitcoinNode(addressIndex)); } /** * Get the root node for the bitcoin public keychain * @return {String} base58-encoding of the public node */ }, { key: 'getBitcoinPublicKeychain', value: function getBitcoinPublicKeychain() { return this.getBitcoinPrivateKeychain().neutered(); } /** * Get the root node for the identity public keychain * @return {String} base58-encoding of the public node */ }, { key: 'getIdentityPublicKeychain', value: function getIdentityPublicKeychain() { return this.getIdentityPrivateKeychain().neutered(); } }, { key: 'getIdentityKeyPair', /** * Get the keypair information for a given identity index. This * information is used to obtain the private key for an identity address * and derive application specific keys for that address. * @param {number} addressIndex - the identity index * @param {boolean} alwaysUncompressed - if true, always return a * private-key hex string corresponding to the uncompressed address * @return {Object} an IdentityKeyPair type object with keys: * .key {String} - the private key hex-string * .keyID {String} - the public key hex-string * .address {String} - the identity address * .appsNodeKey {String} - the base-58 encoding of the applications node * .salt {String} - the salt used for creating app-specific addresses */ value: function getIdentityKeyPair(addressIndex) { var alwaysUncompressed = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : false; var identityNode = this.getIdentityAddressNode(addressIndex); var address = BlockstackWallet.getAddressFromBIP32Node(identityNode); var identityKey = getNodePrivateKey(identityNode); if (alwaysUncompressed && identityKey.length === 66) { identityKey = identityKey.slice(0, 64); } var identityKeyID = getNodePublicKey(identityNode); var appsNodeKey = BlockstackWallet.getAppsNode(identityNode).toBase58(); var salt = this.getIdentitySalt(); var keyPair = { key: identityKey, keyID: identityKeyID, address: address, appsNodeKey: appsNodeKey, salt: salt }; return keyPair; } }], [{ key: 'fromSeedBuffer', value: function fromSeedBuffer(seed) { return new BlockstackWallet(_bip4.default.fromSeed(seed)); } /** * Initialize a blockstack wallet from a base58 string * @param {string} keychain - the Base58 string used to initialize * the root node of the hierarchical wallet * @return {BlockstackWallet} the constructed wallet */ }, { key: 'fromBase58', value: function fromBase58(keychain) { return new BlockstackWallet(_bip4.default.fromBase58(keychain)); } /** * Initialize a blockstack wallet from an encrypted phrase & password. Throws * if the password is incorrect. Supports all formats of Blockstack phrases. * @param {string} data - The encrypted phrase as a hex-encoded string * @param {string} password - The plain password * @return {Promise} the constructed wallet */ }, { key: 'fromEncryptedMnemonic', value: function fromEncryptedMnemonic(data, password) { return (0, _encryption.decryptMnemonic)(data, password).then(function (mnemonic) { var seed = _bip2.default.mnemonicToSeed(mnemonic); return new BlockstackWallet(_bip4.default.fromSeed(seed)); }).catch(function (err) { if (err.message && err.message.startsWith('bad header;')) { throw new Error('Incorrect password'); } else { throw err; } }); } /** * Generate a BIP-39 12 word mnemonic * @return {Promise} space-separated 12 word phrase */ }, { key: 'generateMnemonic', value: function generateMnemonic() { return _bip2.default.generateMnemonic(128, _crypto.randomBytes); } /** * Encrypt a mnemonic phrase with a password * @param {string} mnemonic - Raw mnemonic phrase * @param {string} password - Password to encrypt mnemonic with * @return {Promise} Hex-encoded encrypted mnemonic */ }, { key: 'encryptMnemonic', value: function () { var _ref = _asyncToGenerator( /*#__PURE__*/_regenerator2.default.mark(function _callee(mnemonic, password) { var encryptedBuffer; return _regenerator2.default.wrap(function _callee$(_context) { while (1) { switch (_context.prev = _context.next) { case 0: _context.next = 2; return (0, _encryption.encryptMnemonic)(mnemonic, password); case 2: encryptedBuffer = _context.sent; return _context.abrupt('return', encryptedBuffer.toString('hex')); case 4: case 'end': return _context.stop(); } } }, _callee, this); })); function encryptMnemonic(_x3, _x4) { return _ref.apply(this, arguments); } return encryptMnemonic; }() }, { key: 'getAppsNode', value: function getAppsNode(identityNode) { return identityNode.deriveHardened(APPS_NODE_INDEX); } }, { key: 'getNodeFromBitcoinKeychain', value: function getNodeFromBitcoinKeychain(keychainBase58, addressIndex) { var chainType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EXTERNAL_ADDRESS; var chain = void 0; if (chainType === EXTERNAL_ADDRESS) { chain = 0; } else if (chainType === CHANGE_ADDRESS) { chain = 1; } else { throw new Error('Invalid chain type'); } var keychain = _bip4.default.fromBase58(keychainBase58); return keychain.derive(chain).derive(addressIndex); } /** * Get a bitcoin address given a base-58 encoded bitcoin node * (usually called the account node) * @param {String} keychainBase58 - base58-encoding of the node * @param {number} addressIndex - index of the address to get * @param {String} chainType - either 'EXTERNAL_ADDRESS' (for a * "receive" address) or 'CHANGE_ADDRESS' * @return {String} the address */ }, { key: 'getAddressFromBitcoinKeychain', value: function getAddressFromBitcoinKeychain(keychainBase58, addressIndex) { var chainType = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : EXTERNAL_ADDRESS; return BlockstackWallet.getAddressFromBIP32Node(BlockstackWallet.getNodeFromBitcoinKeychain(keychainBase58, addressIndex, chainType)); } /** * Get a ECDSA private key hex-string for an application-specific * address. * @param {String} appsNodeKey - the base58-encoded private key for * applications node (the `appsNodeKey` return in getIdentityKeyPair()) * @param {String} salt - a string, used to salt the * application-specific addresses * @param {String} appDomain - the appDomain to generate a key for * @return {String} the private key hex-string. this will be a 64 * character string */ }, { key: 'getLegacyAppPrivateKey', value: function getLegacyAppPrivateKey(appsNodeKey, salt, appDomain) { var hash = _crypto2.default.createHash('sha256').update('' + appDomain + salt).digest('hex'); var appIndex = hashCode(hash); var appNode = _bip4.default.fromBase58(appsNodeKey).deriveHardened(appIndex); return getNodePrivateKey(appNode).slice(0, 64); } }, { key: 'getAddressFromBIP32Node', value: function getAddressFromBIP32Node(node) { return _bitcoinjsLib2.default.payments.p2pkh({ pubkey: node.publicKey }).address; } /** * Get a ECDSA private key hex-string for an application-specific * address. * @param {String} appsNodeKey - the base58-encoded private key for * applications node (the `appsNodeKey` return in getIdentityKeyPair()) * @param {String} salt - a string, used to salt the * application-specific addresses * @param {String} appDomain - the appDomain to generate a key for * @return {String} the private key hex-string. this will be a 64 * character string */ }, { key: 'getAppPrivateKey', value: function getAppPrivateKey(appsNodeKey, salt, appDomain) { var hash = _crypto2.default.createHash('sha256').update('' + appDomain + salt).digest('hex'); var appIndexHexes = []; // note: there's hardcoded numbers here, precisely because I want this // code to be very specific to the derivation paths we expect. if (hash.length !== 64) { throw new Error('Unexpected app-domain hash length of ' + hash.length); } for (var i = 0; i < 11; i++) { // split the hash into 3-byte chunks // because child nodes can only be up to 2^31, // and we shouldn't deal in partial bytes. appIndexHexes.push(hash.slice(i * 6, i * 6 + 6)); } var appNode = _bip4.default.fromBase58(appsNodeKey); appIndexHexes.forEach(function (hex) { if (hex.length > 6) { throw new Error('Invalid hex string length'); } appNode = appNode.deriveHardened(parseInt(hex, 16)); }); return getNodePrivateKey(appNode).slice(0, 64); } }]); return BlockstackWallet; }(); },{"./encryption":10,"./utils":46,"babel-runtime/regenerator":62,"bip32":73,"bip39":74,"bitcoinjs-lib":92,"crypto":188}],48:[function(require,module,exports){ var asn1 = exports; asn1.bignum = require('bn.js'); asn1.define = require('./asn1/api').define; asn1.base = require('./asn1/base'); asn1.constants = require('./asn1/constants'); asn1.decoders = require('./asn1/decoders'); asn1.encoders = require('./asn1/encoders'); },{"./asn1/api":49,"./asn1/base":51,"./asn1/constants":55,"./asn1/decoders":57,"./asn1/encoders":60,"bn.js":130}],49:[function(require,module,exports){ var asn1 = require('../asn1'); var inherits = require('inherits'); var api = exports; api.define = function define(name, body) { return new Entity(name, body); }; function Entity(name, body) { this.name = name; this.body = body; this.decoders = {}; this.encoders = {}; }; Entity.prototype._createNamed = function createNamed(base) { var named; try { named = require('vm').runInThisContext( '(function ' + this.name + '(entity) {\n' + ' this._initNamed(entity);\n' + '})' ); } catch (e) { named = function (entity) { this._initNamed(entity); }; } inherits(named, base); named.prototype._initNamed = function initnamed(entity) { base.call(this, entity); }; return new named(this); }; Entity.prototype._getDecoder = function _getDecoder(enc) { enc = enc || 'der'; // Lazily create decoder if (!this.decoders.hasOwnProperty(enc)) this.decoders[enc] = this._createNamed(asn1.decoders[enc]); return this.decoders[enc]; }; Entity.prototype.decode = function decode(data, enc, options) { return this._getDecoder(enc).decode(data, options); }; Entity.prototype._getEncoder = function _getEncoder(enc) { enc = enc || 'der'; // Lazily create encoder if (!this.encoders.hasOwnProperty(enc)) this.encoders[enc] = this._createNamed(asn1.encoders[enc]); return this.encoders[enc]; }; Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) { return this._getEncoder(enc).encode(data, reporter); }; },{"../asn1":48,"inherits":378,"vm":262}],50:[function(require,module,exports){ var inherits = require('inherits'); var Reporter = require('../base').Reporter; var Buffer = require('buffer').Buffer; function DecoderBuffer(base, options) { Reporter.call(this, options); if (!Buffer.isBuffer(base)) { this.error('Input not Buffer'); return; } this.base = base; this.offset = 0; this.length = base.length; } inherits(DecoderBuffer, Reporter); exports.DecoderBuffer = DecoderBuffer; DecoderBuffer.prototype.save = function save() { return { offset: this.offset, reporter: Reporter.prototype.save.call(this) }; }; DecoderBuffer.prototype.restore = function restore(save) { // Return skipped data var res = new DecoderBuffer(this.base); res.offset = save.offset; res.length = this.offset; this.offset = save.offset; Reporter.prototype.restore.call(this, save.reporter); return res; }; DecoderBuffer.prototype.isEmpty = function isEmpty() { return this.offset === this.length; }; DecoderBuffer.prototype.readUInt8 = function readUInt8(fail) { if (this.offset + 1 <= this.length) return this.base.readUInt8(this.offset++, true); else return this.error(fail || 'DecoderBuffer overrun'); } DecoderBuffer.prototype.skip = function skip(bytes, fail) { if (!(this.offset + bytes <= this.length)) return this.error(fail || 'DecoderBuffer overrun'); var res = new DecoderBuffer(this.base); // Share reporter state res._reporterState = this._reporterState; res.offset = this.offset; res.length = this.offset + bytes; this.offset += bytes; return res; } DecoderBuffer.prototype.raw = function raw(save) { return this.base.slice(save ? save.offset : this.offset, this.length); } function EncoderBuffer(value, reporter) { if (Array.isArray(value)) { this.length = 0; this.value = value.map(function(item) { if (!(item instanceof EncoderBuffer)) item = new EncoderBuffer(item, reporter); this.length += item.length; return item; }, this); } else if (typeof value === 'number') { if (!(0 <= value && value <= 0xff)) return reporter.error('non-byte EncoderBuffer value'); this.value = value; this.length = 1; } else if (typeof value === 'string') { this.value = value; this.length = Buffer.byteLength(value); } else if (Buffer.isBuffer(value)) { this.value = value; this.length = value.length; } else { return reporter.error('Unsupported type: ' + typeof value); } } exports.EncoderBuffer = EncoderBuffer; EncoderBuffer.prototype.join = function join(out, offset) { if (!out) out = new Buffer(this.length); if (!offset) offset = 0; if (this.length === 0) return out; if (Array.isArray(this.value)) { this.value.forEach(function(item) { item.join(out, offset); offset += item.length; }); } else { if (typeof this.value === 'number') out[offset] = this.value; else if (typeof this.value === 'string') out.write(this.value, offset); else if (Buffer.isBuffer(this.value)) this.value.copy(out, offset); offset += this.length; } return out; }; },{"../base":51,"buffer":179,"inherits":378}],51:[function(require,module,exports){ var base = exports; base.Reporter = require('./reporter').Reporter; base.DecoderBuffer = require('./buffer').DecoderBuffer; base.EncoderBuffer = require('./buffer').EncoderBuffer; base.Node = require('./node'); },{"./buffer":50,"./node":52,"./reporter":53}],52:[function(require,module,exports){ var Reporter = require('../base').Reporter; var EncoderBuffer = require('../base').EncoderBuffer; var DecoderBuffer = require('../base').DecoderBuffer; var assert = require('minimalistic-assert'); // Supported tags var tags = [ 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' ]; // Public methods list var methods = [ 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains' ].concat(tags); // Overrided methods list var overrided = [ '_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool' ]; function Node(enc, parent) { var state = {}; this._baseState = state; state.enc = enc; state.parent = parent || null; state.children = null; // State state.tag = null; state.args = null; state.reverseArgs = null; state.choice = null; state.optional = false; state.any = false; state.obj = false; state.use = null; state.useDecoder = null; state.key = null; state['default'] = null; state.explicit = null; state.implicit = null; state.contains = null; // Should create new instance on each method if (!state.parent) { state.children = []; this._wrap(); } } module.exports = Node; var stateProps = [ 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains' ]; Node.prototype.clone = function clone() { var state = this._baseState; var cstate = {}; stateProps.forEach(function(prop) { cstate[prop] = state[prop]; }); var res = new this.constructor(cstate.parent); res._baseState = cstate; return res; }; Node.prototype._wrap = function wrap() { var state = this._baseState; methods.forEach(function(method) { this[method] = function _wrappedMethod() { var clone = new this.constructor(this); state.children.push(clone); return clone[method].apply(clone, arguments); }; }, this); }; Node.prototype._init = function init(body) { var state = this._baseState; assert(state.parent === null); body.call(this); // Filter children state.children = state.children.filter(function(child) { return child._baseState.parent === this; }, this); assert.equal(state.children.length, 1, 'Root node can have only one child'); }; Node.prototype._useArgs = function useArgs(args) { var state = this._baseState; // Filter children and args var children = args.filter(function(arg) { return arg instanceof this.constructor; }, this); args = args.filter(function(arg) { return !(arg instanceof this.constructor); }, this); if (children.length !== 0) { assert(state.children === null); state.children = children; // Replace parent to maintain backward link children.forEach(function(child) { child._baseState.parent = this; }, this); } if (args.length !== 0) { assert(state.args === null); state.args = args; state.reverseArgs = args.map(function(arg) { if (typeof arg !== 'object' || arg.constructor !== Object) return arg; var res = {}; Object.keys(arg).forEach(function(key) { if (key == (key | 0)) key |= 0; var value = arg[key]; res[value] = key; }); return res; }); } }; // // Overrided methods // overrided.forEach(function(method) { Node.prototype[method] = function _overrided() { var state = this._baseState; throw new Error(method + ' not implemented for encoding: ' + state.enc); }; }); // // Public methods // tags.forEach(function(tag) { Node.prototype[tag] = function _tagMethod() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); assert(state.tag === null); state.tag = tag; this._useArgs(args); return this; }; }); Node.prototype.use = function use(item) { assert(item); var state = this._baseState; assert(state.use === null); state.use = item; return this; }; Node.prototype.optional = function optional() { var state = this._baseState; state.optional = true; return this; }; Node.prototype.def = function def(val) { var state = this._baseState; assert(state['default'] === null); state['default'] = val; state.optional = true; return this; }; Node.prototype.explicit = function explicit(num) { var state = this._baseState; assert(state.explicit === null && state.implicit === null); state.explicit = num; return this; }; Node.prototype.implicit = function implicit(num) { var state = this._baseState; assert(state.explicit === null && state.implicit === null); state.implicit = num; return this; }; Node.prototype.obj = function obj() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); state.obj = true; if (args.length !== 0) this._useArgs(args); return this; }; Node.prototype.key = function key(newKey) { var state = this._baseState; assert(state.key === null); state.key = newKey; return this; }; Node.prototype.any = function any() { var state = this._baseState; state.any = true; return this; }; Node.prototype.choice = function choice(obj) { var state = this._baseState; assert(state.choice === null); state.choice = obj; this._useArgs(Object.keys(obj).map(function(key) { return obj[key]; })); return this; }; Node.prototype.contains = function contains(item) { var state = this._baseState; assert(state.use === null); state.contains = item; return this; }; // // Decoding // Node.prototype._decode = function decode(input, options) { var state = this._baseState; // Decode root node if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); var result = state['default']; var present = true; var prevKey = null; if (state.key !== null) prevKey = input.enterKey(state.key); // Check if tag is there if (state.optional) { var tag = null; if (state.explicit !== null) tag = state.explicit; else if (state.implicit !== null) tag = state.implicit; else if (state.tag !== null) tag = state.tag; if (tag === null && !state.any) { // Trial and Error var save = input.save(); try { if (state.choice === null) this._decodeGeneric(state.tag, input, options); else this._decodeChoice(input, options); present = true; } catch (e) { present = false; } input.restore(save); } else { present = this._peekTag(input, tag, state.any); if (input.isError(present)) return present; } } // Push object on stack var prevObj; if (state.obj && present) prevObj = input.enterObject(); if (present) { // Unwrap explicit values if (state.explicit !== null) { var explicit = this._decodeTag(input, state.explicit); if (input.isError(explicit)) return explicit; input = explicit; } var start = input.offset; // Unwrap implicit and normal values if (state.use === null && state.choice === null) { if (state.any) var save = input.save(); var body = this._decodeTag( input, state.implicit !== null ? state.implicit : state.tag, state.any ); if (input.isError(body)) return body; if (state.any) result = input.raw(save); else input = body; } if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged'); if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content'); // Select proper method for tag if (state.any) result = result; else if (state.choice === null) result = this._decodeGeneric(state.tag, input, options); else result = this._decodeChoice(input, options); if (input.isError(result)) return result; // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren(child) { // NOTE: We are ignoring errors here, to let parser continue with other // parts of encoded data child._decode(input, options); }); } // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { var data = new DecoderBuffer(result); result = this._getUse(state.contains, input._reporterState.obj) ._decode(data, options); } } // Pop object if (state.obj && present) result = input.leaveObject(prevObj); // Set key if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result); else if (prevKey !== null) input.exitKey(prevKey); return result; }; Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { var state = this._baseState; if (tag === 'seq' || tag === 'set') return null; if (tag === 'seqof' || tag === 'setof') return this._decodeList(input, tag, state.args[0], options); else if (/str$/.test(tag)) return this._decodeStr(input, tag, options); else if (tag === 'objid' && state.args) return this._decodeObjid(input, state.args[0], state.args[1], options); else if (tag === 'objid') return this._decodeObjid(input, null, null, options); else if (tag === 'gentime' || tag === 'utctime') return this._decodeTime(input, tag, options); else if (tag === 'null_') return this._decodeNull(input, options); else if (tag === 'bool') return this._decodeBool(input, options); else if (tag === 'objDesc') return this._decodeStr(input, tag, options); else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options); if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj) ._decode(input, options); } else { return input.error('unknown tag: ' + tag); } }; Node.prototype._getUse = function _getUse(entity, obj) { var state = this._baseState; // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj); assert(state.useDecoder._baseState.parent === null); state.useDecoder = state.useDecoder._baseState.children[0]; if (state.implicit !== state.useDecoder._baseState.implicit) { state.useDecoder = state.useDecoder.clone(); state.useDecoder._baseState.implicit = state.implicit; } return state.useDecoder; }; Node.prototype._decodeChoice = function decodeChoice(input, options) { var state = this._baseState; var result = null; var match = false; Object.keys(state.choice).some(function(key) { var save = input.save(); var node = state.choice[key]; try { var value = node._decode(input, options); if (input.isError(value)) return false; result = { type: key, value: value }; match = true; } catch (e) { input.restore(save); return false; } return true; }, this); if (!match) return input.error('Choice not matched'); return result; }; // // Encoding // Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { return new EncoderBuffer(data, this.reporter); }; Node.prototype._encode = function encode(data, reporter, parent) { var state = this._baseState; if (state['default'] !== null && state['default'] === data) return; var result = this._encodeValue(data, reporter, parent); if (result === undefined) return; if (this._skipDefault(result, reporter, parent)) return; return result; }; Node.prototype._encodeValue = function encode(data, reporter, parent) { var state = this._baseState; // Decode root node if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); var result = null; // Set reporter to share it with a child class this.reporter = reporter; // Check if data is there if (state.optional && data === undefined) { if (state['default'] !== null) data = state['default'] else return; } // Encode children first var content = null; var primitive = false; if (state.any) { // Anything that was given is translated to buffer result = this._createEncoderBuffer(data); } else if (state.choice) { result = this._encodeChoice(data, reporter); } else if (state.contains) { content = this._getUse(state.contains, parent)._encode(data, reporter); primitive = true; } else if (state.children) { content = state.children.map(function(child) { if (child._baseState.tag === 'null_') return child._encode(null, reporter, data); if (child._baseState.key === null) return reporter.error('Child should have a key'); var prevKey = reporter.enterKey(child._baseState.key); if (typeof data !== 'object') return reporter.error('Child expected, but input is not object'); var res = child._encode(data[child._baseState.key], reporter, data); reporter.leaveKey(prevKey); return res; }, this).filter(function(child) { return child; }); content = this._createEncoderBuffer(content); } else { if (state.tag === 'seqof' || state.tag === 'setof') { // TODO(indutny): this should be thrown on DSL level if (!(state.args && state.args.length === 1)) return reporter.error('Too many args for : ' + state.tag); if (!Array.isArray(data)) return reporter.error('seqof/setof, but data is not Array'); var child = this.clone(); child._baseState.implicit = null; content = this._createEncoderBuffer(data.map(function(item) { var state = this._baseState; return this._getUse(state.args[0], data)._encode(item, reporter); }, child)); } else if (state.use !== null) { result = this._getUse(state.use, parent)._encode(data, reporter); } else { content = this._encodePrimitive(state.tag, data); primitive = true; } } // Encode data itself var result; if (!state.any && state.choice === null) { var tag = state.implicit !== null ? state.implicit : state.tag; var cls = state.implicit === null ? 'universal' : 'context'; if (tag === null) { if (state.use === null) reporter.error('Tag could be omitted only for .use()'); } else { if (state.use === null) result = this._encodeComposite(tag, primitive, cls, content); } } // Wrap in explicit if (state.explicit !== null) result = this._encodeComposite(state.explicit, false, 'context', result); return result; }; Node.prototype._encodeChoice = function encodeChoice(data, reporter) { var state = this._baseState; var node = state.choice[data.type]; if (!node) { assert( false, data.type + ' not found in ' + JSON.stringify(Object.keys(state.choice))); } return node._encode(data.value, reporter); }; Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { var state = this._baseState; if (/str$/.test(tag)) return this._encodeStr(data, tag); else if (tag === 'objid' && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); else if (tag === 'objid') return this._encodeObjid(data, null, null); else if (tag === 'gentime' || tag === 'utctime') return this._encodeTime(data, tag); else if (tag === 'null_') return this._encodeNull(); else if (tag === 'int' || tag === 'enum') return this._encodeInt(data, state.args && state.reverseArgs[0]); else if (tag === 'bool') return this._encodeBool(data); else if (tag === 'objDesc') return this._encodeStr(data, tag); else throw new Error('Unsupported tag: ' + tag); }; Node.prototype._isNumstr = function isNumstr(str) { return /^[0-9 ]*$/.test(str); }; Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); }; },{"../base":51,"minimalistic-assert":438}],53:[function(require,module,exports){ var inherits = require('inherits'); function Reporter(options) { this._reporterState = { obj: null, path: [], options: options || {}, errors: [] }; } exports.Reporter = Reporter; Reporter.prototype.isError = function isError(obj) { return obj instanceof ReporterError; }; Reporter.prototype.save = function save() { var state = this._reporterState; return { obj: state.obj, pathLen: state.path.length }; }; Reporter.prototype.restore = function restore(data) { var state = this._reporterState; state.obj = data.obj; state.path = state.path.slice(0, data.pathLen); }; Reporter.prototype.enterKey = function enterKey(key) { return this._reporterState.path.push(key); }; Reporter.prototype.exitKey = function exitKey(index) { var state = this._reporterState; state.path = state.path.slice(0, index - 1); }; Reporter.prototype.leaveKey = function leaveKey(index, key, value) { var state = this._reporterState; this.exitKey(index); if (state.obj !== null) state.obj[key] = value; }; Reporter.prototype.path = function path() { return this._reporterState.path.join('/'); }; Reporter.prototype.enterObject = function enterObject() { var state = this._reporterState; var prev = state.obj; state.obj = {}; return prev; }; Reporter.prototype.leaveObject = function leaveObject(prev) { var state = this._reporterState; var now = state.obj; state.obj = prev; return now; }; Reporter.prototype.error = function error(msg) { var err; var state = this._reporterState; var inherited = msg instanceof ReporterError; if (inherited) { err = msg; } else { err = new ReporterError(state.path.map(function(elem) { return '[' + JSON.stringify(elem) + ']'; }).join(''), msg.message || msg, msg.stack); } if (!state.options.partial) throw err; if (!inherited) state.errors.push(err); return err; }; Reporter.prototype.wrapResult = function wrapResult(result) { var state = this._reporterState; if (!state.options.partial) return result; return { result: this.isError(result) ? null : result, errors: state.errors }; }; function ReporterError(path, msg) { this.path = path; this.rethrow(msg); }; inherits(ReporterError, Error); ReporterError.prototype.rethrow = function rethrow(msg) { this.message = msg + ' at: ' + (this.path || '(shallow)'); if (Error.captureStackTrace) Error.captureStackTrace(this, ReporterError); if (!this.stack) { try { // IE only adds stack when thrown throw new Error(this.message); } catch (e) { this.stack = e.stack; } } return this; }; },{"inherits":378}],54:[function(require,module,exports){ var constants = require('../constants'); exports.tagClass = { 0: 'universal', 1: 'application', 2: 'context', 3: 'private' }; exports.tagClassByName = constants._reverse(exports.tagClass); exports.tag = { 0x00: 'end', 0x01: 'bool', 0x02: 'int', 0x03: 'bitstr', 0x04: 'octstr', 0x05: 'null_', 0x06: 'objid', 0x07: 'objDesc', 0x08: 'external', 0x09: 'real', 0x0a: 'enum', 0x0b: 'embed', 0x0c: 'utf8str', 0x0d: 'relativeOid', 0x10: 'seq', 0x11: 'set', 0x12: 'numstr', 0x13: 'printstr', 0x14: 't61str', 0x15: 'videostr', 0x16: 'ia5str', 0x17: 'utctime', 0x18: 'gentime', 0x19: 'graphstr', 0x1a: 'iso646str', 0x1b: 'genstr', 0x1c: 'unistr', 0x1d: 'charstr', 0x1e: 'bmpstr' }; exports.tagByName = constants._reverse(exports.tag); },{"../constants":55}],55:[function(require,module,exports){ var constants = exports; // Helper constants._reverse = function reverse(map) { var res = {}; Object.keys(map).forEach(function(key) { // Convert key to integer if it is stringified if ((key | 0) == key) key = key | 0; var value = map[key]; res[value] = key; }); return res; }; constants.der = require('./der'); },{"./der":54}],56:[function(require,module,exports){ var inherits = require('inherits'); var asn1 = require('../../asn1'); var base = asn1.base; var bignum = asn1.bignum; // Import DER constants var der = asn1.constants.der; function DERDecoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); }; module.exports = DERDecoder; DERDecoder.prototype.decode = function decode(data, options) { if (!(data instanceof base.DecoderBuffer)) data = new base.DecoderBuffer(data, options); return this.tree._decode(data, options); }; // Tree methods function DERNode(parent) { base.Node.call(this, 'der', parent); } inherits(DERNode, base.Node); DERNode.prototype._peekTag = function peekTag(buffer, tag, any) { if (buffer.isEmpty()) return false; var state = buffer.save(); var decodedTag = derDecodeTag(buffer, 'Failed to peek tag: "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; buffer.restore(state); return decodedTag.tag === tag || decodedTag.tagStr === tag || (decodedTag.tagStr + 'of') === tag || any; }; DERNode.prototype._decodeTag = function decodeTag(buffer, tag, any) { var decodedTag = derDecodeTag(buffer, 'Failed to decode tag of "' + tag + '"'); if (buffer.isError(decodedTag)) return decodedTag; var len = derDecodeLen(buffer, decodedTag.primitive, 'Failed to get length of "' + tag + '"'); // Failure if (buffer.isError(len)) return len; if (!any && decodedTag.tag !== tag && decodedTag.tagStr !== tag && decodedTag.tagStr + 'of' !== tag) { return buffer.error('Failed to match tag: "' + tag + '"'); } if (decodedTag.primitive || len !== null) return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); // Indefinite length... find END tag var state = buffer.save(); var res = this._skipUntilEnd( buffer, 'Failed to skip indefinite length body: "' + this.tag + '"'); if (buffer.isError(res)) return res; len = buffer.offset - state.offset; buffer.restore(state); return buffer.skip(len, 'Failed to match body of: "' + tag + '"'); }; DERNode.prototype._skipUntilEnd = function skipUntilEnd(buffer, fail) { while (true) { var tag = derDecodeTag(buffer, fail); if (buffer.isError(tag)) return tag; var len = derDecodeLen(buffer, tag.primitive, fail); if (buffer.isError(len)) return len; var res; if (tag.primitive || len !== null) res = buffer.skip(len) else res = this._skipUntilEnd(buffer, fail); // Failure if (buffer.isError(res)) return res; if (tag.tagStr === 'end') break; } }; DERNode.prototype._decodeList = function decodeList(buffer, tag, decoder, options) { var result = []; while (!buffer.isEmpty()) { var possibleEnd = this._peekTag(buffer, 'end'); if (buffer.isError(possibleEnd)) return possibleEnd; var res = decoder.decode(buffer, 'der', options); if (buffer.isError(res) && possibleEnd) break; result.push(res); } return result; }; DERNode.prototype._decodeStr = function decodeStr(buffer, tag) { if (tag === 'bitstr') { var unused = buffer.readUInt8(); if (buffer.isError(unused)) return unused; return { unused: unused, data: buffer.raw() }; } else if (tag === 'bmpstr') { var raw = buffer.raw(); if (raw.length % 2 === 1) return buffer.error('Decoding of string type: bmpstr length mismatch'); var str = ''; for (var i = 0; i < raw.length / 2; i++) { str += String.fromCharCode(raw.readUInt16BE(i * 2)); } return str; } else if (tag === 'numstr') { var numstr = buffer.raw().toString('ascii'); if (!this._isNumstr(numstr)) { return buffer.error('Decoding of string type: ' + 'numstr unsupported characters'); } return numstr; } else if (tag === 'octstr') { return buffer.raw(); } else if (tag === 'objDesc') { return buffer.raw(); } else if (tag === 'printstr') { var printstr = buffer.raw().toString('ascii'); if (!this._isPrintstr(printstr)) { return buffer.error('Decoding of string type: ' + 'printstr unsupported characters'); } return printstr; } else if (/str$/.test(tag)) { return buffer.raw().toString(); } else { return buffer.error('Decoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._decodeObjid = function decodeObjid(buffer, values, relative) { var result; var identifiers = []; var ident = 0; while (!buffer.isEmpty()) { var subident = buffer.readUInt8(); ident <<= 7; ident |= subident & 0x7f; if ((subident & 0x80) === 0) { identifiers.push(ident); ident = 0; } } if (subident & 0x80) identifiers.push(ident); var first = (identifiers[0] / 40) | 0; var second = identifiers[0] % 40; if (relative) result = identifiers; else result = [first, second].concat(identifiers.slice(1)); if (values) { var tmp = values[result.join(' ')]; if (tmp === undefined) tmp = values[result.join('.')]; if (tmp !== undefined) result = tmp; } return result; }; DERNode.prototype._decodeTime = function decodeTime(buffer, tag) { var str = buffer.raw().toString(); if (tag === 'gentime') { var year = str.slice(0, 4) | 0; var mon = str.slice(4, 6) | 0; var day = str.slice(6, 8) | 0; var hour = str.slice(8, 10) | 0; var min = str.slice(10, 12) | 0; var sec = str.slice(12, 14) | 0; } else if (tag === 'utctime') { var year = str.slice(0, 2) | 0; var mon = str.slice(2, 4) | 0; var day = str.slice(4, 6) | 0; var hour = str.slice(6, 8) | 0; var min = str.slice(8, 10) | 0; var sec = str.slice(10, 12) | 0; if (year < 70) year = 2000 + year; else year = 1900 + year; } else { return buffer.error('Decoding ' + tag + ' time is not supported yet'); } return Date.UTC(year, mon - 1, day, hour, min, sec, 0); }; DERNode.prototype._decodeNull = function decodeNull(buffer) { return null; }; DERNode.prototype._decodeBool = function decodeBool(buffer) { var res = buffer.readUInt8(); if (buffer.isError(res)) return res; else return res !== 0; }; DERNode.prototype._decodeInt = function decodeInt(buffer, values) { // Bigint, return as it is (assume big endian) var raw = buffer.raw(); var res = new bignum(raw); if (values) res = values[res.toString(10)] || res; return res; }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getDecoder('der').tree; }; // Utility methods function derDecodeTag(buf, fail) { var tag = buf.readUInt8(fail); if (buf.isError(tag)) return tag; var cls = der.tagClass[tag >> 6]; var primitive = (tag & 0x20) === 0; // Multi-octet tag - load if ((tag & 0x1f) === 0x1f) { var oct = tag; tag = 0; while ((oct & 0x80) === 0x80) { oct = buf.readUInt8(fail); if (buf.isError(oct)) return oct; tag <<= 7; tag |= oct & 0x7f; } } else { tag &= 0x1f; } var tagStr = der.tag[tag]; return { cls: cls, primitive: primitive, tag: tag, tagStr: tagStr }; } function derDecodeLen(buf, primitive, fail) { var len = buf.readUInt8(fail); if (buf.isError(len)) return len; // Indefinite form if (!primitive && len === 0x80) return null; // Definite form if ((len & 0x80) === 0) { // Short form return len; } // Long form var num = len & 0x7f; if (num > 4) return buf.error('length octect is too long'); len = 0; for (var i = 0; i < num; i++) { len <<= 8; var j = buf.readUInt8(fail); if (buf.isError(j)) return j; len |= j; } return len; } },{"../../asn1":48,"inherits":378}],57:[function(require,module,exports){ var decoders = exports; decoders.der = require('./der'); decoders.pem = require('./pem'); },{"./der":56,"./pem":58}],58:[function(require,module,exports){ var inherits = require('inherits'); var Buffer = require('buffer').Buffer; var DERDecoder = require('./der'); function PEMDecoder(entity) { DERDecoder.call(this, entity); this.enc = 'pem'; }; inherits(PEMDecoder, DERDecoder); module.exports = PEMDecoder; PEMDecoder.prototype.decode = function decode(data, options) { var lines = data.toString().split(/[\r\n]+/g); var label = options.label.toUpperCase(); var re = /^-----(BEGIN|END) ([^-]+)-----$/; var start = -1; var end = -1; for (var i = 0; i < lines.length; i++) { var match = lines[i].match(re); if (match === null) continue; if (match[2] !== label) continue; if (start === -1) { if (match[1] !== 'BEGIN') break; start = i; } else { if (match[1] !== 'END') break; end = i; break; } } if (start === -1 || end === -1) throw new Error('PEM section not found for: ' + label); var base64 = lines.slice(start + 1, end).join(''); // Remove excessive symbols base64.replace(/[^a-z0-9\+\/=]+/gi, ''); var input = new Buffer(base64, 'base64'); return DERDecoder.prototype.decode.call(this, input, options); }; },{"./der":56,"buffer":179,"inherits":378}],59:[function(require,module,exports){ var inherits = require('inherits'); var Buffer = require('buffer').Buffer; var asn1 = require('../../asn1'); var base = asn1.base; // Import DER constants var der = asn1.constants.der; function DEREncoder(entity) { this.enc = 'der'; this.name = entity.name; this.entity = entity; // Construct base tree this.tree = new DERNode(); this.tree._init(entity.body); }; module.exports = DEREncoder; DEREncoder.prototype.encode = function encode(data, reporter) { return this.tree._encode(data, reporter).join(); }; // Tree methods function DERNode(parent) { base.Node.call(this, 'der', parent); } inherits(DERNode, base.Node); DERNode.prototype._encodeComposite = function encodeComposite(tag, primitive, cls, content) { var encodedTag = encodeTag(tag, primitive, cls, this.reporter); // Short form if (content.length < 0x80) { var header = new Buffer(2); header[0] = encodedTag; header[1] = content.length; return this._createEncoderBuffer([ header, content ]); } // Long form // Count octets required to store length var lenOctets = 1; for (var i = content.length; i >= 0x100; i >>= 8) lenOctets++; var header = new Buffer(1 + 1 + lenOctets); header[0] = encodedTag; header[1] = 0x80 | lenOctets; for (var i = 1 + lenOctets, j = content.length; j > 0; i--, j >>= 8) header[i] = j & 0xff; return this._createEncoderBuffer([ header, content ]); }; DERNode.prototype._encodeStr = function encodeStr(str, tag) { if (tag === 'bitstr') { return this._createEncoderBuffer([ str.unused | 0, str.data ]); } else if (tag === 'bmpstr') { var buf = new Buffer(str.length * 2); for (var i = 0; i < str.length; i++) { buf.writeUInt16BE(str.charCodeAt(i), i * 2); } return this._createEncoderBuffer(buf); } else if (tag === 'numstr') { if (!this._isNumstr(str)) { return this.reporter.error('Encoding of string type: numstr supports ' + 'only digits and space'); } return this._createEncoderBuffer(str); } else if (tag === 'printstr') { if (!this._isPrintstr(str)) { return this.reporter.error('Encoding of string type: printstr supports ' + 'only latin upper and lower case letters, ' + 'digits, space, apostrophe, left and rigth ' + 'parenthesis, plus sign, comma, hyphen, ' + 'dot, slash, colon, equal sign, ' + 'question mark'); } return this._createEncoderBuffer(str); } else if (/str$/.test(tag)) { return this._createEncoderBuffer(str); } else if (tag === 'objDesc') { return this._createEncoderBuffer(str); } else { return this.reporter.error('Encoding of string type: ' + tag + ' unsupported'); } }; DERNode.prototype._encodeObjid = function encodeObjid(id, values, relative) { if (typeof id === 'string') { if (!values) return this.reporter.error('string objid given, but no values map found'); if (!values.hasOwnProperty(id)) return this.reporter.error('objid not found in values map'); id = values[id].split(/[\s\.]+/g); for (var i = 0; i < id.length; i++) id[i] |= 0; } else if (Array.isArray(id)) { id = id.slice(); for (var i = 0; i < id.length; i++) id[i] |= 0; } if (!Array.isArray(id)) { return this.reporter.error('objid() should be either array or string, ' + 'got: ' + JSON.stringify(id)); } if (!relative) { if (id[1] >= 40) return this.reporter.error('Second objid identifier OOB'); id.splice(0, 2, id[0] * 40 + id[1]); } // Count number of octets var size = 0; for (var i = 0; i < id.length; i++) { var ident = id[i]; for (size++; ident >= 0x80; ident >>= 7) size++; } var objid = new Buffer(size); var offset = objid.length - 1; for (var i = id.length - 1; i >= 0; i--) { var ident = id[i]; objid[offset--] = ident & 0x7f; while ((ident >>= 7) > 0) objid[offset--] = 0x80 | (ident & 0x7f); } return this._createEncoderBuffer(objid); }; function two(num) { if (num < 10) return '0' + num; else return num; } DERNode.prototype._encodeTime = function encodeTime(time, tag) { var str; var date = new Date(time); if (tag === 'gentime') { str = [ two(date.getFullYear()), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join(''); } else if (tag === 'utctime') { str = [ two(date.getFullYear() % 100), two(date.getUTCMonth() + 1), two(date.getUTCDate()), two(date.getUTCHours()), two(date.getUTCMinutes()), two(date.getUTCSeconds()), 'Z' ].join(''); } else { this.reporter.error('Encoding ' + tag + ' time is not supported yet'); } return this._encodeStr(str, 'octstr'); }; DERNode.prototype._encodeNull = function encodeNull() { return this._createEncoderBuffer(''); }; DERNode.prototype._encodeInt = function encodeInt(num, values) { if (typeof num === 'string') { if (!values) return this.reporter.error('String int or enum given, but no values map'); if (!values.hasOwnProperty(num)) { return this.reporter.error('Values map doesn\'t contain: ' + JSON.stringify(num)); } num = values[num]; } // Bignum, assume big endian if (typeof num !== 'number' && !Buffer.isBuffer(num)) { var numArray = num.toArray(); if (!num.sign && numArray[0] & 0x80) { numArray.unshift(0); } num = new Buffer(numArray); } if (Buffer.isBuffer(num)) { var size = num.length; if (num.length === 0) size++; var out = new Buffer(size); num.copy(out); if (num.length === 0) out[0] = 0 return this._createEncoderBuffer(out); } if (num < 0x80) return this._createEncoderBuffer(num); if (num < 0x100) return this._createEncoderBuffer([0, num]); var size = 1; for (var i = num; i >= 0x100; i >>= 8) size++; var out = new Array(size); for (var i = out.length - 1; i >= 0; i--) { out[i] = num & 0xff; num >>= 8; } if(out[0] & 0x80) { out.unshift(0); } return this._createEncoderBuffer(new Buffer(out)); }; DERNode.prototype._encodeBool = function encodeBool(value) { return this._createEncoderBuffer(value ? 0xff : 0); }; DERNode.prototype._use = function use(entity, obj) { if (typeof entity === 'function') entity = entity(obj); return entity._getEncoder('der').tree; }; DERNode.prototype._skipDefault = function skipDefault(dataBuffer, reporter, parent) { var state = this._baseState; var i; if (state['default'] === null) return false; var data = dataBuffer.join(); if (state.defaultBuffer === undefined) state.defaultBuffer = this._encodeValue(state['default'], reporter, parent).join(); if (data.length !== state.defaultBuffer.length) return false; for (i=0; i < data.length; i++) if (data[i] !== state.defaultBuffer[i]) return false; return true; }; // Utility methods function encodeTag(tag, primitive, cls, reporter) { var res; if (tag === 'seqof') tag = 'seq'; else if (tag === 'setof') tag = 'set'; if (der.tagByName.hasOwnProperty(tag)) res = der.tagByName[tag]; else if (typeof tag === 'number' && (tag | 0) === tag) res = tag; else return reporter.error('Unknown tag: ' + tag); if (res >= 0x1f) return reporter.error('Multi-octet tag encoding unsupported'); if (!primitive) res |= 0x20; res |= (der.tagClassByName[cls || 'universal'] << 6); return res; } },{"../../asn1":48,"buffer":179,"inherits":378}],60:[function(require,module,exports){ var encoders = exports; encoders.der = require('./der'); encoders.pem = require('./pem'); },{"./der":59,"./pem":61}],61:[function(require,module,exports){ var inherits = require('inherits'); var DEREncoder = require('./der'); function PEMEncoder(entity) { DEREncoder.call(this, entity); this.enc = 'pem'; }; inherits(PEMEncoder, DEREncoder); module.exports = PEMEncoder; PEMEncoder.prototype.encode = function encode(data, options) { var buf = DEREncoder.prototype.encode.call(this, data); var p = buf.toString('base64'); var out = [ '-----BEGIN ' + options.label + '-----' ]; for (var i = 0; i < p.length; i += 64) out.push(p.slice(i, i + 64)); out.push('-----END ' + options.label + '-----'); return out.join('\n'); }; },{"./der":59,"inherits":378}],62:[function(require,module,exports){ module.exports = require("regenerator-runtime"); },{"regenerator-runtime":454}],63:[function(require,module,exports){ // base-x encoding // Forked from https://github.com/cryptocoinjs/bs58 // 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 Buffer = require('safe-buffer').Buffer module.exports = function base (ALPHABET) { var ALPHABET_MAP = {} var BASE = ALPHABET.length var LEADER = ALPHABET.charAt(0) // pre-compute lookup table for (var z = 0; z < ALPHABET.length; z++) { var x = ALPHABET.charAt(z) if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') ALPHABET_MAP[x] = z } function encode (source) { if (source.length === 0) return '' var digits = [0] for (var i = 0; i < source.length; ++i) { for (var j = 0, carry = source[i]; j < digits.length; ++j) { carry += digits[j] << 8 digits[j] = carry % BASE carry = (carry / BASE) | 0 } while (carry > 0) { digits.push(carry % BASE) carry = (carry / BASE) | 0 } } var string = '' // deal with leading zeros for (var k = 0; source[k] === 0 && k < source.length - 1; ++k) string += LEADER // convert digits to a string for (var q = digits.length - 1; q >= 0; --q) string += ALPHABET[digits[q]] return string } function decodeUnsafe (string) { if (typeof string !== 'string') throw new TypeError('Expected String') if (string.length === 0) return Buffer.allocUnsafe(0) var bytes = [0] for (var i = 0; i < string.length; i++) { var value = ALPHABET_MAP[string[i]] if (value === undefined) return for (var j = 0, carry = value; j < bytes.length; ++j) { carry += bytes[j] * BASE bytes[j] = carry & 0xff carry >>= 8 } while (carry > 0) { bytes.push(carry & 0xff) carry >>= 8 } } // deal with leading zeros for (var k = 0; string[k] === LEADER && k < string.length - 1; ++k) { bytes.push(0) } return Buffer.from(bytes.reverse()) } function decode (string) { var buffer = decodeUnsafe(string) if (buffer) return buffer throw new Error('Non-base' + BASE + ' character') } return { encode: encode, decodeUnsafe: decodeUnsafe, decode: decode } } },{"safe-buffer":457}],64:[function(require,module,exports){ (function (Buffer){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const pad_string_1 = require("./pad-string"); function encode(input, encoding = "utf8") { if (Buffer.isBuffer(input)) { return fromBase64(input.toString("base64")); } return fromBase64(Buffer.from(input, encoding).toString("base64")); } ; function decode(base64url, encoding = "utf8") { return Buffer.from(toBase64(base64url), "base64").toString(encoding); } function toBase64(base64url) { base64url = base64url.toString(); return pad_string_1.default(base64url) .replace(/\-/g, "+") .replace(/_/g, "/"); } function fromBase64(base64) { return base64 .replace(/=/g, "") .replace(/\+/g, "-") .replace(/\//g, "_"); } function toBuffer(base64url) { return Buffer.from(toBase64(base64url), "base64"); } let base64url = encode; base64url.encode = encode; base64url.decode = decode; base64url.toBase64 = toBase64; base64url.fromBase64 = fromBase64; base64url.toBuffer = toBuffer; exports.default = base64url; }).call(this,require("buffer").Buffer) },{"./pad-string":65,"buffer":179}],65:[function(require,module,exports){ (function (Buffer){ "use strict"; Object.defineProperty(exports, "__esModule", { value: true }); function padString(input) { let segmentLength = 4; let stringLength = input.length; let diff = stringLength % segmentLength; if (!diff) { return input; } let position = stringLength; let padLength = segmentLength - diff; let paddedStringLength = stringLength + padLength; let buffer = Buffer.alloc(paddedStringLength); buffer.write(input); while (padLength--) { buffer.write("=", position++); } return buffer.toString(); } exports.default = padString; }).call(this,require("buffer").Buffer) },{"buffer":179}],66:[function(require,module,exports){ module.exports = require('./dist/base64url').default; module.exports.default = module.exports; },{"./dist/base64url":64}],67:[function(require,module,exports){ 'use strict' var ALPHABET = 'qpzry9x8gf2tvdw0s3jn54khce6mua7l' // pre-compute lookup table var ALPHABET_MAP = {} for (var z = 0; z < ALPHABET.length; z++) { var x = ALPHABET.charAt(z) if (ALPHABET_MAP[x] !== undefined) throw new TypeError(x + ' is ambiguous') ALPHABET_MAP[x] = z } function polymodStep (pre) { var b = pre >> 25 return ((pre & 0x1FFFFFF) << 5) ^ (-((b >> 0) & 1) & 0x3b6a57b2) ^ (-((b >> 1) & 1) & 0x26508e6d) ^ (-((b >> 2) & 1) & 0x1ea119fa) ^ (-((b >> 3) & 1) & 0x3d4233dd) ^ (-((b >> 4) & 1) & 0x2a1462b3) } function prefixChk (prefix) { var chk = 1 for (var i = 0; i < prefix.length; ++i) { var c = prefix.charCodeAt(i) if (c < 33 || c > 126) throw new Error('Invalid prefix (' + prefix + ')') chk = polymodStep(chk) ^ (c >> 5) } chk = polymodStep(chk) for (i = 0; i < prefix.length; ++i) { var v = prefix.charCodeAt(i) chk = polymodStep(chk) ^ (v & 0x1f) } return chk } function encode (prefix, words, LIMIT) { LIMIT = LIMIT || 90 if ((prefix.length + 7 + words.length) > LIMIT) throw new TypeError('Exceeds length limit') prefix = prefix.toLowerCase() // determine chk mod var chk = prefixChk(prefix) var result = prefix + '1' for (var i = 0; i < words.length; ++i) { var x = words[i] if ((x >> 5) !== 0) throw new Error('Non 5-bit word') chk = polymodStep(chk) ^ x result += ALPHABET.charAt(x) } for (i = 0; i < 6; ++i) { chk = polymodStep(chk) } chk ^= 1 for (i = 0; i < 6; ++i) { var v = (chk >> ((5 - i) * 5)) & 0x1f result += ALPHABET.charAt(v) } return result } function decode (str, LIMIT) { LIMIT = LIMIT || 90 if (str.length < 8) throw new TypeError(str + ' too short') if (str.length > LIMIT) throw new TypeError('Exceeds length limit') // don't allow mixed case var lowered = str.toLowerCase() var uppered = str.toUpperCase() if (str !== lowered && str !== uppered) throw new Error('Mixed-case string ' + str) str = lowered var split = str.lastIndexOf('1') if (split === -1) throw new Error('No separator character for ' + str) if (split === 0) throw new Error('Missing prefix for ' + str) var prefix = str.slice(0, split) var wordChars = str.slice(split + 1) if (wordChars.length < 6) throw new Error('Data too short') var chk = prefixChk(prefix) var words = [] for (var i = 0; i < wordChars.length; ++i) { var c = wordChars.charAt(i) var v = ALPHABET_MAP[c] if (v === undefined) throw new Error('Unknown character ' + c) chk = polymodStep(chk) ^ v // not in the checksum? if (i + 6 >= wordChars.length) continue words.push(v) } if (chk !== 1) throw new Error('Invalid checksum for ' + str) return { prefix: prefix, words: words } } function convert (data, inBits, outBits, pad) { var value = 0 var bits = 0 var maxV = (1 << outBits) - 1 var result = [] for (var i = 0; i < data.length; ++i) { value = (value << inBits) | data[i] bits += inBits while (bits >= outBits) { bits -= outBits result.push((value >> bits) & maxV) } } if (pad) { if (bits > 0) { result.push((value << (outBits - bits)) & maxV) } } else { if (bits >= inBits) throw new Error('Excess padding') if ((value << (outBits - bits)) & maxV) throw new Error('Non-zero padding') } return result } function toWords (bytes) { return convert(bytes, 8, 5, true) } function fromWords (words) { return convert(words, 5, 8, false) } module.exports = { decode: decode, encode: encode, toWords: toWords, fromWords: fromWords } },{}],68:[function(require,module,exports){ // (public) Constructor function BigInteger(a, b, c) { if (!(this instanceof BigInteger)) return new BigInteger(a, b, c) if (a != null) { if ("number" == typeof a) this.fromNumber(a, b, c) else if (b == null && "string" != typeof a) this.fromString(a, 256) else this.fromString(a, b) } } var proto = BigInteger.prototype // duck-typed isBigInteger proto.__bigi = require('../package.json').version BigInteger.isBigInteger = function (obj, check_ver) { return obj && obj.__bigi && (!check_ver || obj.__bigi === proto.__bigi) } // Bits per digit var dbits // am: Compute w_j += (x*this_i), propagate carries, // c is initial carry, returns final carry. // c < 3*dvalue, x < 2*dvalue, this_i < dvalue // We need to select the fastest one that works in this environment. // am1: use a single mult and divide to get the high bits, // max digit bits should be 26 because // max internal value = 2*dvalue^2-2*dvalue (< 2^53) function am1(i, x, w, j, c, n) { while (--n >= 0) { var v = x * this[i++] + w[j] + c c = Math.floor(v / 0x4000000) w[j++] = v & 0x3ffffff } return c } // am2 avoids a big mult-and-extract completely. // Max digit bits should be <= 30 because we do bitwise ops // on values up to 2*hdvalue^2-hdvalue-1 (< 2^31) function am2(i, x, w, j, c, n) { var xl = x & 0x7fff, xh = x >> 15 while (--n >= 0) { var l = this[i] & 0x7fff var h = this[i++] >> 15 var m = xh * l + h * xl l = xl * l + ((m & 0x7fff) << 15) + w[j] + (c & 0x3fffffff) c = (l >>> 30) + (m >>> 15) + xh * h + (c >>> 30) w[j++] = l & 0x3fffffff } return c } // Alternately, set max digit bits to 28 since some // browsers slow down when dealing with 32-bit numbers. function am3(i, x, w, j, c, n) { var xl = x & 0x3fff, xh = x >> 14 while (--n >= 0) { var l = this[i] & 0x3fff var h = this[i++] >> 14 var m = xh * l + h * xl l = xl * l + ((m & 0x3fff) << 14) + w[j] + c c = (l >> 28) + (m >> 14) + xh * h w[j++] = l & 0xfffffff } return c } // wtf? BigInteger.prototype.am = am1 dbits = 26 BigInteger.prototype.DB = dbits BigInteger.prototype.DM = ((1 << dbits) - 1) var DV = BigInteger.prototype.DV = (1 << dbits) var BI_FP = 52 BigInteger.prototype.FV = Math.pow(2, BI_FP) BigInteger.prototype.F1 = BI_FP - dbits BigInteger.prototype.F2 = 2 * dbits - BI_FP // Digit conversions var BI_RM = "0123456789abcdefghijklmnopqrstuvwxyz" var BI_RC = new Array() var rr, vv rr = "0".charCodeAt(0) for (vv = 0; vv <= 9; ++vv) BI_RC[rr++] = vv rr = "a".charCodeAt(0) for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv rr = "A".charCodeAt(0) for (vv = 10; vv < 36; ++vv) BI_RC[rr++] = vv function int2char(n) { return BI_RM.charAt(n) } function intAt(s, i) { var c = BI_RC[s.charCodeAt(i)] return (c == null) ? -1 : c } // (protected) copy this to r function bnpCopyTo(r) { for (var i = this.t - 1; i >= 0; --i) r[i] = this[i] r.t = this.t r.s = this.s } // (protected) set from integer value x, -DV <= x < DV function bnpFromInt(x) { this.t = 1 this.s = (x < 0) ? -1 : 0 if (x > 0) this[0] = x else if (x < -1) this[0] = x + DV else this.t = 0 } // return bigint initialized to value function nbv(i) { var r = new BigInteger() r.fromInt(i) return r } // (protected) set from string and radix function bnpFromString(s, b) { var self = this var k if (b == 16) k = 4 else if (b == 8) k = 3 else if (b == 256) k = 8; // byte array else if (b == 2) k = 1 else if (b == 32) k = 5 else if (b == 4) k = 2 else { self.fromRadix(s, b) return } self.t = 0 self.s = 0 var i = s.length, mi = false, sh = 0 while (--i >= 0) { var x = (k == 8) ? s[i] & 0xff : intAt(s, i) if (x < 0) { if (s.charAt(i) == "-") mi = true continue } mi = false if (sh == 0) self[self.t++] = x else if (sh + k > self.DB) { self[self.t - 1] |= (x & ((1 << (self.DB - sh)) - 1)) << sh self[self.t++] = (x >> (self.DB - sh)) } else self[self.t - 1] |= x << sh sh += k if (sh >= self.DB) sh -= self.DB } if (k == 8 && (s[0] & 0x80) != 0) { self.s = -1 if (sh > 0) self[self.t - 1] |= ((1 << (self.DB - sh)) - 1) << sh } self.clamp() if (mi) BigInteger.ZERO.subTo(self, self) } // (protected) clamp off excess high words function bnpClamp() { var c = this.s & this.DM while (this.t > 0 && this[this.t - 1] == c)--this.t } // (public) return string representation in given radix function bnToString(b) { var self = this if (self.s < 0) return "-" + self.negate() .toString(b) var k if (b == 16) k = 4 else if (b == 8) k = 3 else if (b == 2) k = 1 else if (b == 32) k = 5 else if (b == 4) k = 2 else return self.toRadix(b) var km = (1 << k) - 1, d, m = false, r = "", i = self.t var p = self.DB - (i * self.DB) % k if (i-- > 0) { if (p < self.DB && (d = self[i] >> p) > 0) { m = true r = int2char(d) } while (i >= 0) { if (p < k) { d = (self[i] & ((1 << p) - 1)) << (k - p) d |= self[--i] >> (p += self.DB - k) } else { d = (self[i] >> (p -= k)) & km if (p <= 0) { p += self.DB --i } } if (d > 0) m = true if (m) r += int2char(d) } } return m ? r : "0" } // (public) -this function bnNegate() { var r = new BigInteger() BigInteger.ZERO.subTo(this, r) return r } // (public) |this| function bnAbs() { return (this.s < 0) ? this.negate() : this } // (public) return + if this > a, - if this < a, 0 if equal function bnCompareTo(a) { var r = this.s - a.s if (r != 0) return r var i = this.t r = i - a.t if (r != 0) return (this.s < 0) ? -r : r while (--i >= 0) if ((r = this[i] - a[i]) != 0) return r return 0 } // returns bit length of the integer x function nbits(x) { var r = 1, t if ((t = x >>> 16) != 0) { x = t r += 16 } if ((t = x >> 8) != 0) { x = t r += 8 } if ((t = x >> 4) != 0) { x = t r += 4 } if ((t = x >> 2) != 0) { x = t r += 2 } if ((t = x >> 1) != 0) { x = t r += 1 } return r } // (public) return the number of bits in "this" function bnBitLength() { if (this.t <= 0) return 0 return this.DB * (this.t - 1) + nbits(this[this.t - 1] ^ (this.s & this.DM)) } // (public) return the number of bytes in "this" function bnByteLength() { return this.bitLength() >> 3 } // (protected) r = this << n*DB function bnpDLShiftTo(n, r) { var i for (i = this.t - 1; i >= 0; --i) r[i + n] = this[i] for (i = n - 1; i >= 0; --i) r[i] = 0 r.t = this.t + n r.s = this.s } // (protected) r = this >> n*DB function bnpDRShiftTo(n, r) { for (var i = n; i < this.t; ++i) r[i - n] = this[i] r.t = Math.max(this.t - n, 0) r.s = this.s } // (protected) r = this << n function bnpLShiftTo(n, r) { var self = this var bs = n % self.DB var cbs = self.DB - bs var bm = (1 << cbs) - 1 var ds = Math.floor(n / self.DB), c = (self.s << bs) & self.DM, i for (i = self.t - 1; i >= 0; --i) { r[i + ds + 1] = (self[i] >> cbs) | c c = (self[i] & bm) << bs } for (i = ds - 1; i >= 0; --i) r[i] = 0 r[ds] = c r.t = self.t + ds + 1 r.s = self.s r.clamp() } // (protected) r = this >> n function bnpRShiftTo(n, r) { var self = this r.s = self.s var ds = Math.floor(n / self.DB) if (ds >= self.t) { r.t = 0 return } var bs = n % self.DB var cbs = self.DB - bs var bm = (1 << bs) - 1 r[0] = self[ds] >> bs for (var i = ds + 1; i < self.t; ++i) { r[i - ds - 1] |= (self[i] & bm) << cbs r[i - ds] = self[i] >> bs } if (bs > 0) r[self.t - ds - 1] |= (self.s & bm) << cbs r.t = self.t - ds r.clamp() } // (protected) r = this - a function bnpSubTo(a, r) { var self = this var i = 0, c = 0, m = Math.min(a.t, self.t) while (i < m) { c += self[i] - a[i] r[i++] = c & self.DM c >>= self.DB } if (a.t < self.t) { c -= a.s while (i < self.t) { c += self[i] r[i++] = c & self.DM c >>= self.DB } c += self.s } else { c += self.s while (i < a.t) { c -= a[i] r[i++] = c & self.DM c >>= self.DB } c -= a.s } r.s = (c < 0) ? -1 : 0 if (c < -1) r[i++] = self.DV + c else if (c > 0) r[i++] = c r.t = i r.clamp() } // (protected) r = this * a, r != this,a (HAC 14.12) // "this" should be the larger one if appropriate. function bnpMultiplyTo(a, r) { var x = this.abs(), y = a.abs() var i = x.t r.t = i + y.t while (--i >= 0) r[i] = 0 for (i = 0; i < y.t; ++i) r[i + x.t] = x.am(0, y[i], r, i, 0, x.t) r.s = 0 r.clamp() if (this.s != a.s) BigInteger.ZERO.subTo(r, r) } // (protected) r = this^2, r != this (HAC 14.16) function bnpSquareTo(r) { var x = this.abs() var i = r.t = 2 * x.t while (--i >= 0) r[i] = 0 for (i = 0; i < x.t - 1; ++i) { var c = x.am(i, x[i], r, 2 * i, 0, 1) if ((r[i + x.t] += x.am(i + 1, 2 * x[i], r, 2 * i + 1, c, x.t - i - 1)) >= x.DV) { r[i + x.t] -= x.DV r[i + x.t + 1] = 1 } } if (r.t > 0) r[r.t - 1] += x.am(i, x[i], r, 2 * i, 0, 1) r.s = 0 r.clamp() } // (protected) divide this by m, quotient and remainder to q, r (HAC 14.20) // r != q, this != m. q or r may be null. function bnpDivRemTo(m, q, r) { var self = this var pm = m.abs() if (pm.t <= 0) return var pt = self.abs() if (pt.t < pm.t) { if (q != null) q.fromInt(0) if (r != null) self.copyTo(r) return } if (r == null) r = new BigInteger() var y = new BigInteger(), ts = self.s, ms = m.s var nsh = self.DB - nbits(pm[pm.t - 1]); // normalize modulus if (nsh > 0) { pm.lShiftTo(nsh, y) pt.lShiftTo(nsh, r) } else { pm.copyTo(y) pt.copyTo(r) } var ys = y.t var y0 = y[ys - 1] if (y0 == 0) return var yt = y0 * (1 << self.F1) + ((ys > 1) ? y[ys - 2] >> self.F2 : 0) var d1 = self.FV / yt, d2 = (1 << self.F1) / yt, e = 1 << self.F2 var i = r.t, j = i - ys, t = (q == null) ? new BigInteger() : q y.dlShiftTo(j, t) if (r.compareTo(t) >= 0) { r[r.t++] = 1 r.subTo(t, r) } BigInteger.ONE.dlShiftTo(ys, t) t.subTo(y, y); // "negative" y so we can replace sub with am later while (y.t < ys) y[y.t++] = 0 while (--j >= 0) { // Estimate quotient digit var qd = (r[--i] == y0) ? self.DM : Math.floor(r[i] * d1 + (r[i - 1] + e) * d2) if ((r[i] += y.am(0, qd, r, j, 0, ys)) < qd) { // Try it out y.dlShiftTo(j, t) r.subTo(t, r) while (r[i] < --qd) r.subTo(t, r) } } if (q != null) { r.drShiftTo(ys, q) if (ts != ms) BigInteger.ZERO.subTo(q, q) } r.t = ys r.clamp() if (nsh > 0) r.rShiftTo(nsh, r); // Denormalize remainder if (ts < 0) BigInteger.ZERO.subTo(r, r) } // (public) this mod a function bnMod(a) { var r = new BigInteger() this.abs() .divRemTo(a, null, r) if (this.s < 0 && r.compareTo(BigInteger.ZERO) > 0) a.subTo(r, r) return r } // Modular reduction using "classic" algorithm function Classic(m) { this.m = m } function cConvert(x) { if (x.s < 0 || x.compareTo(this.m) >= 0) return x.mod(this.m) else return x } function cRevert(x) { return x } function cReduce(x) { x.divRemTo(this.m, null, x) } function cMulTo(x, y, r) { x.multiplyTo(y, r) this.reduce(r) } function cSqrTo(x, r) { x.squareTo(r) this.reduce(r) } Classic.prototype.convert = cConvert Classic.prototype.revert = cRevert Classic.prototype.reduce = cReduce Classic.prototype.mulTo = cMulTo Classic.prototype.sqrTo = cSqrTo // (protected) return "-1/this % 2^DB"; useful for Mont. reduction // justification: // xy == 1 (mod m) // xy = 1+km // xy(2-xy) = (1+km)(1-km) // x[y(2-xy)] = 1-k^2m^2 // x[y(2-xy)] == 1 (mod m^2) // if y is 1/x mod m, then y(2-xy) is 1/x mod m^2 // should reduce x and y(2-xy) by m^2 at each step to keep size bounded. // JS multiply "overflows" differently from C/C++, so care is needed here. function bnpInvDigit() { if (this.t < 1) return 0 var x = this[0] if ((x & 1) == 0) return 0 var y = x & 3; // y == 1/x mod 2^2 y = (y * (2 - (x & 0xf) * y)) & 0xf; // y == 1/x mod 2^4 y = (y * (2 - (x & 0xff) * y)) & 0xff; // y == 1/x mod 2^8 y = (y * (2 - (((x & 0xffff) * y) & 0xffff))) & 0xffff; // y == 1/x mod 2^16 // last step - calculate inverse mod DV directly // assumes 16 < DB <= 32 and assumes ability to handle 48-bit ints y = (y * (2 - x * y % this.DV)) % this.DV; // y == 1/x mod 2^dbits // we really want the negative inverse, and -DV < y < DV return (y > 0) ? this.DV - y : -y } // Montgomery reduction function Montgomery(m) { this.m = m this.mp = m.invDigit() this.mpl = this.mp & 0x7fff this.mph = this.mp >> 15 this.um = (1 << (m.DB - 15)) - 1 this.mt2 = 2 * m.t } // xR mod m function montConvert(x) { var r = new BigInteger() x.abs() .dlShiftTo(this.m.t, r) r.divRemTo(this.m, null, r) if (x.s < 0 && r.compareTo(BigInteger.ZERO) > 0) this.m.subTo(r, r) return r } // x/R mod m function montRevert(x) { var r = new BigInteger() x.copyTo(r) this.reduce(r) return r } // x = x/R mod m (HAC 14.32) function montReduce(x) { while (x.t <= this.mt2) // pad x so am has enough room later x[x.t++] = 0 for (var i = 0; i < this.m.t; ++i) { // faster way of calculating u0 = x[i]*mp mod DV var j = x[i] & 0x7fff var u0 = (j * this.mpl + (((j * this.mph + (x[i] >> 15) * this.mpl) & this.um) << 15)) & x.DM // use am to combine the multiply-shift-add into one call j = i + this.m.t x[j] += this.m.am(0, u0, x, i, 0, this.m.t) // propagate carry while (x[j] >= x.DV) { x[j] -= x.DV x[++j]++ } } x.clamp() x.drShiftTo(this.m.t, x) if (x.compareTo(this.m) >= 0) x.subTo(this.m, x) } // r = "x^2/R mod m"; x != r function montSqrTo(x, r) { x.squareTo(r) this.reduce(r) } // r = "xy/R mod m"; x,y != r function montMulTo(x, y, r) { x.multiplyTo(y, r) this.reduce(r) } Montgomery.prototype.convert = montConvert Montgomery.prototype.revert = montRevert Montgomery.prototype.reduce = montReduce Montgomery.prototype.mulTo = montMulTo Montgomery.prototype.sqrTo = montSqrTo // (protected) true iff this is even function bnpIsEven() { return ((this.t > 0) ? (this[0] & 1) : this.s) == 0 } // (protected) this^e, e < 2^32, doing sqr and mul with "r" (HAC 14.79) function bnpExp(e, z) { if (e > 0xffffffff || e < 1) return BigInteger.ONE var r = new BigInteger(), r2 = new BigInteger(), g = z.convert(this), i = nbits(e) - 1 g.copyTo(r) while (--i >= 0) { z.sqrTo(r, r2) if ((e & (1 << i)) > 0) z.mulTo(r2, g, r) else { var t = r r = r2 r2 = t } } return z.revert(r) } // (public) this^e % m, 0 <= e < 2^32 function bnModPowInt(e, m) { var z if (e < 256 || m.isEven()) z = new Classic(m) else z = new Montgomery(m) return this.exp(e, z) } // protected proto.copyTo = bnpCopyTo proto.fromInt = bnpFromInt proto.fromString = bnpFromString proto.clamp = bnpClamp proto.dlShiftTo = bnpDLShiftTo proto.drShiftTo = bnpDRShiftTo proto.lShiftTo = bnpLShiftTo proto.rShiftTo = bnpRShiftTo proto.subTo = bnpSubTo proto.multiplyTo = bnpMultiplyTo proto.squareTo = bnpSquareTo proto.divRemTo = bnpDivRemTo proto.invDigit = bnpInvDigit proto.isEven = bnpIsEven proto.exp = bnpExp // public proto.toString = bnToString proto.negate = bnNegate proto.abs = bnAbs proto.compareTo = bnCompareTo proto.bitLength = bnBitLength proto.byteLength = bnByteLength proto.mod = bnMod proto.modPowInt = bnModPowInt // (public) function bnClone() { var r = new BigInteger() this.copyTo(r) return r } // (public) return value as integer 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 // assumes 16 < DB < 32 return ((this[1] & ((1 << (32 - this.DB)) - 1)) << this.DB) | this[0] } // (public) return value as byte function bnByteValue() { return (this.t == 0) ? this.s : (this[0] << 24) >> 24 } // (public) return value as short (assumes DB>=16) function bnShortValue() { return (this.t == 0) ? this.s : (this[0] << 16) >> 16 } // (protected) return x s.t. r^x < DV function bnpChunkSize(r) { return Math.floor(Math.LN2 * this.DB / Math.log(r)) } // (public) 0 if this == 0, 1 if this > 0 function bnSigNum() { if (this.s < 0) return -1 else if (this.t <= 0 || (this.t == 1 && this[0] <= 0)) return 0 else return 1 } // (protected) convert to radix string function bnpToRadix(b) { if (b == null) b = 10 if (this.signum() == 0 || b < 2 || b > 36) return "0" var cs = this.chunkSize(b) var a = Math.pow(b, cs) var d = nbv(a), y = new BigInteger(), z = new BigInteger(), r = "" this.divRemTo(d, y, z) while (y.signum() > 0) { r = (a + z.intValue()) .toString(b) .substr(1) + r y.divRemTo(d, y, z) } return z.intValue() .toString(b) + r } // (protected) convert from radix string function bnpFromRadix(s, b) { var self = this self.fromInt(0) if (b == null) b = 10 var cs = self.chunkSize(b) var d = Math.pow(b, cs), mi = false, j = 0, w = 0 for (var i = 0; i < s.length; ++i) { var x = intAt(s, i) if (x < 0) { if (s.charAt(i) == "-" && self.signum() == 0) mi = true continue } w = b * w + x if (++j >= cs) { self.dMultiply(d) self.dAddOffset(w, 0) j = 0 w = 0 } } if (j > 0) { self.dMultiply(Math.pow(b, j)) self.dAddOffset(w, 0) } if (mi) BigInteger.ZERO.subTo(self, self) } // (protected) alternate constructor function bnpFromNumber(a, b, c) { var self = this if ("number" == typeof b) { // new BigInteger(int,int,RNG) if (a < 2) self.fromInt(1) else { self.fromNumber(a, c) if (!self.testBit(a - 1)) // force MSB set self.bitwiseTo(BigInteger.ONE.shiftLeft(a - 1), op_or, self) if (self.isEven()) self.dAddOffset(1, 0); // force odd while (!self.isProbablePrime(b)) { self.dAddOffset(2, 0) if (self.bitLength() > a) self.subTo(BigInteger.ONE.shiftLeft(a - 1), self) } } } else { // new BigInteger(int,RNG) var x = new Array(), t = a & 7 x.length = (a >> 3) + 1 b.nextBytes(x) if (t > 0) x[0] &= ((1 << t) - 1) else x[0] = 0 self.fromString(x, 256) } } // (public) convert to bigendian byte array function bnToByteArray() { var self = this var i = self.t, r = new Array() r[0] = self.s var p = self.DB - (i * self.DB) % 8, d, k = 0 if (i-- > 0) { if (p < self.DB && (d = self[i] >> p) != (self.s & self.DM) >> p) r[k++] = d | (self.s << (self.DB - p)) while (i >= 0) { if (p < 8) { d = (self[i] & ((1 << p) - 1)) << (8 - p) d |= self[--i] >> (p += self.DB - 8) } else { d = (self[i] >> (p -= 8)) & 0xff if (p <= 0) { p += self.DB --i } } if ((d & 0x80) != 0) d |= -256 if (k === 0 && (self.s & 0x80) != (d & 0x80))++k if (k > 0 || d != self.s) r[k++] = d } } return r } function bnEquals(a) { return (this.compareTo(a) == 0) } function bnMin(a) { return (this.compareTo(a) < 0) ? this : a } function bnMax(a) { return (this.compareTo(a) > 0) ? this : a } // (protected) r = this op a (bitwise) function bnpBitwiseTo(a, op, r) { var self = this var i, f, m = Math.min(a.t, self.t) for (i = 0; i < m; ++i) r[i] = op(self[i], a[i]) if (a.t < self.t) { f = a.s & self.DM for (i = m; i < self.t; ++i) r[i] = op(self[i], f) r.t = self.t } else { f = self.s & self.DM for (i = m; i < a.t; ++i) r[i] = op(f, a[i]) r.t = a.t } r.s = op(self.s, a.s) r.clamp() } // (public) this & a function op_and(x, y) { return x & y } function bnAnd(a) { var r = new BigInteger() this.bitwiseTo(a, op_and, r) return r } // (public) this | a function op_or(x, y) { return x | y } function bnOr(a) { var r = new BigInteger() this.bitwiseTo(a, op_or, r) return r } // (public) this ^ a function op_xor(x, y) { return x ^ y } function bnXor(a) { var r = new BigInteger() this.bitwiseTo(a, op_xor, r) return r } // (public) this & ~a function op_andnot(x, y) { return x & ~y } function bnAndNot(a) { var r = new BigInteger() this.bitwiseTo(a, op_andnot, r) return r } // (public) ~this function bnNot() { var r = new BigInteger() for (var i = 0; i < this.t; ++i) r[i] = this.DM & ~this[i] r.t = this.t r.s = ~this.s return r } // (public) this << n function bnShiftLeft(n) { var r = new BigInteger() if (n < 0) this.rShiftTo(-n, r) else this.lShiftTo(n, r) return r } // (public) this >> n function bnShiftRight(n) { var r = new BigInteger() if (n < 0) this.lShiftTo(-n, r) else this.rShiftTo(n, r) return r } // return index of lowest 1-bit in x, x < 2^31 function lbit(x) { if (x == 0) return -1 var r = 0 if ((x & 0xffff) == 0) { x >>= 16 r += 16 } if ((x & 0xff) == 0) { x >>= 8 r += 8 } if ((x & 0xf) == 0) { x >>= 4 r += 4 } if ((x & 3) == 0) { x >>= 2 r += 2 } if ((x & 1) == 0)++r return r } // (public) returns index of lowest 1-bit (or -1 if none) function bnGetLowestSetBit() { for (var i = 0; i < this.t; ++i) if (this[i] != 0) return i * this.DB + lbit(this[i]) if (this.s < 0) return this.t * this.DB return -1 } // return number of 1 bits in x function cbit(x) { var r = 0 while (x != 0) { x &= x - 1 ++r } return r } // (public) return number of set bits function bnBitCount() { var r = 0, x = this.s & this.DM for (var i = 0; i < this.t; ++i) r += cbit(this[i] ^ x) return r } // (public) true iff nth bit is set function bnTestBit(n) { var j = Math.floor(n / this.DB) if (j >= this.t) return (this.s != 0) return ((this[j] & (1 << (n % this.DB))) != 0) } // (protected) this op (1<>= self.DB } if (a.t < self.t) { c += a.s while (i < self.t) { c += self[i] r[i++] = c & self.DM c >>= self.DB } c += self.s } else { c += self.s while (i < a.t) { c += a[i] r[i++] = c & self.DM c >>= self.DB } c += a.s } r.s = (c < 0) ? -1 : 0 if (c > 0) r[i++] = c else if (c < -1) r[i++] = self.DV + c r.t = i r.clamp() } // (public) this + a function bnAdd(a) { var r = new BigInteger() this.addTo(a, r) return r } // (public) this - a function bnSubtract(a) { var r = new BigInteger() this.subTo(a, r) return r } // (public) this * a function bnMultiply(a) { var r = new BigInteger() this.multiplyTo(a, r) return r } // (public) this^2 function bnSquare() { var r = new BigInteger() this.squareTo(r) return r } // (public) this / a function bnDivide(a) { var r = new BigInteger() this.divRemTo(a, r, null) return r } // (public) this % a function bnRemainder(a) { var r = new BigInteger() this.divRemTo(a, null, r) return r } // (public) [this/a,this%a] function bnDivideAndRemainder(a) { var q = new BigInteger(), r = new BigInteger() this.divRemTo(a, q, r) return new Array(q, r) } // (protected) this *= n, this >= 0, 1 < n < DV function bnpDMultiply(n) { this[this.t] = this.am(0, n - 1, this, 0, 0, this.t) ++this.t this.clamp() } // (protected) this += n << w words, this >= 0 function bnpDAddOffset(n, w) { if (n == 0) return while (this.t <= w) this[this.t++] = 0 this[w] += n while (this[w] >= this.DV) { this[w] -= this.DV if (++w >= this.t) this[this.t++] = 0 ++this[w] } } // A "null" reducer function NullExp() {} function nNop(x) { return x } function nMulTo(x, y, r) { x.multiplyTo(y, r) } function nSqrTo(x, r) { x.squareTo(r) } NullExp.prototype.convert = nNop NullExp.prototype.revert = nNop NullExp.prototype.mulTo = nMulTo NullExp.prototype.sqrTo = nSqrTo // (public) this^e function bnPow(e) { return this.exp(e, new NullExp()) } // (protected) r = lower n words of "this * a", a.t <= n // "this" should be the larger one if appropriate. function bnpMultiplyLowerTo(a, n, r) { var i = Math.min(this.t + a.t, n) r.s = 0; // assumes a,this >= 0 r.t = i while (i > 0) r[--i] = 0 var j for (j = r.t - this.t; i < j; ++i) r[i + this.t] = this.am(0, a[i], r, i, 0, this.t) for (j = Math.min(a.t, n); i < j; ++i) this.am(0, a[i], r, i, 0, n - i) r.clamp() } // (protected) r = "this * a" without lower n words, n > 0 // "this" should be the larger one if appropriate. function bnpMultiplyUpperTo(a, n, r) { --n var i = r.t = this.t + a.t - n r.s = 0; // assumes a,this >= 0 while (--i >= 0) r[i] = 0 for (i = Math.max(n - this.t, 0); i < a.t; ++i) r[this.t + i - n] = this.am(n - i, a[i], r, 0, 0, this.t + i - n) r.clamp() r.drShiftTo(1, r) } // Barrett modular reduction function Barrett(m) { // setup Barrett this.r2 = new BigInteger() this.q3 = new BigInteger() BigInteger.ONE.dlShiftTo(2 * m.t, this.r2) this.mu = this.r2.divide(m) this.m = m } function barrettConvert(x) { if (x.s < 0 || x.t > 2 * this.m.t) return x.mod(this.m) else if (x.compareTo(this.m) < 0) return x else { var r = new BigInteger() x.copyTo(r) this.reduce(r) return r } } function barrettRevert(x) { return x } // x = x mod m (HAC 14.42) function barrettReduce(x) { var self = this x.drShiftTo(self.m.t - 1, self.r2) if (x.t > self.m.t + 1) { x.t = self.m.t + 1 x.clamp() } self.mu.multiplyUpperTo(self.r2, self.m.t + 1, self.q3) self.m.multiplyLowerTo(self.q3, self.m.t + 1, self.r2) while (x.compareTo(self.r2) < 0) x.dAddOffset(1, self.m.t + 1) x.subTo(self.r2, x) while (x.compareTo(self.m) >= 0) x.subTo(self.m, x) } // r = x^2 mod m; x != r function barrettSqrTo(x, r) { x.squareTo(r) this.reduce(r) } // r = x*y mod m; x,y != r function barrettMulTo(x, y, r) { x.multiplyTo(y, r) this.reduce(r) } Barrett.prototype.convert = barrettConvert Barrett.prototype.revert = barrettRevert Barrett.prototype.reduce = barrettReduce Barrett.prototype.mulTo = barrettMulTo Barrett.prototype.sqrTo = barrettSqrTo // (public) this^e % m (HAC 14.85) function bnModPow(e, m) { var i = e.bitLength(), k, r = nbv(1), z if (i <= 0) return r else if (i < 18) k = 1 else if (i < 48) k = 3 else if (i < 144) k = 4 else if (i < 768) k = 5 else k = 6 if (i < 8) z = new Classic(m) else if (m.isEven()) z = new Barrett(m) else z = new Montgomery(m) // precomputation var g = new Array(), n = 3, k1 = k - 1, km = (1 << k) - 1 g[1] = z.convert(this) if (k > 1) { var g2 = new BigInteger() z.sqrTo(g[1], g2) while (n <= km) { g[n] = new BigInteger() z.mulTo(g2, g[n - 2], g[n]) n += 2 } } var j = e.t - 1, w, is1 = true, r2 = new BigInteger(), t i = nbits(e[j]) - 1 while (j >= 0) { if (i >= k1) w = (e[j] >> (i - k1)) & km else { w = (e[j] & ((1 << (i + 1)) - 1)) << (k1 - i) if (j > 0) w |= e[j - 1] >> (this.DB + i - k1) } n = k while ((w & 1) == 0) { w >>= 1 --n } if ((i -= n) < 0) { i += this.DB --j } if (is1) { // ret == 1, don't bother squaring or multiplying it g[w].copyTo(r) is1 = false } else { while (n > 1) { z.sqrTo(r, r2) z.sqrTo(r2, r) n -= 2 } if (n > 0) z.sqrTo(r, r2) else { t = r r = r2 r2 = t } z.mulTo(r2, g[w], r) } while (j >= 0 && (e[j] & (1 << i)) == 0) { z.sqrTo(r, r2) t = r r = r2 r2 = t if (--i < 0) { i = this.DB - 1 --j } } } return z.revert(r) } // (public) gcd(this,a) (HAC 14.54) function bnGCD(a) { var x = (this.s < 0) ? this.negate() : this.clone() var y = (a.s < 0) ? a.negate() : a.clone() if (x.compareTo(y) < 0) { var t = x x = y y = t } var i = x.getLowestSetBit(), g = y.getLowestSetBit() if (g < 0) return x if (i < g) g = i if (g > 0) { x.rShiftTo(g, x) y.rShiftTo(g, y) } while (x.signum() > 0) { if ((i = x.getLowestSetBit()) > 0) x.rShiftTo(i, x) if ((i = y.getLowestSetBit()) > 0) y.rShiftTo(i, y) if (x.compareTo(y) >= 0) { x.subTo(y, x) x.rShiftTo(1, x) } else { y.subTo(x, y) y.rShiftTo(1, y) } } if (g > 0) y.lShiftTo(g, y) return y } // (protected) this % n, n < 2^26 function bnpModInt(n) { if (n <= 0) return 0 var d = this.DV % n, r = (this.s < 0) ? n - 1 : 0 if (this.t > 0) if (d == 0) r = this[0] % n else for (var i = this.t - 1; i >= 0; --i) r = (d * r + this[i]) % n return r } // (public) 1/this % m (HAC 14.61) function bnModInverse(m) { var ac = m.isEven() if (this.signum() === 0) throw new Error('division by zero') if ((this.isEven() && ac) || m.signum() == 0) return BigInteger.ZERO var u = m.clone(), v = this.clone() var a = nbv(1), b = nbv(0), c = nbv(0), d = nbv(1) while (u.signum() != 0) { while (u.isEven()) { u.rShiftTo(1, u) if (ac) { if (!a.isEven() || !b.isEven()) { a.addTo(this, a) b.subTo(m, b) } a.rShiftTo(1, a) } else if (!b.isEven()) b.subTo(m, b) b.rShiftTo(1, b) } while (v.isEven()) { v.rShiftTo(1, v) if (ac) { if (!c.isEven() || !d.isEven()) { c.addTo(this, c) d.subTo(m, d) } c.rShiftTo(1, c) } else if (!d.isEven()) d.subTo(m, d) d.rShiftTo(1, d) } if (u.compareTo(v) >= 0) { u.subTo(v, u) if (ac) a.subTo(c, a) b.subTo(d, b) } else { v.subTo(u, v) if (ac) c.subTo(a, c) d.subTo(b, d) } } if (v.compareTo(BigInteger.ONE) != 0) return BigInteger.ZERO while (d.compareTo(m) >= 0) d.subTo(m, d) while (d.signum() < 0) d.addTo(m, d) return d } 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] // (public) test primality with certainty >= 1-.5^t function bnIsProbablePrime(t) { var i, x = this.abs() if (x.t == 1 && x[0] <= lowprimes[lowprimes.length - 1]) { for (i = 0; i < lowprimes.length; ++i) if (x[0] == lowprimes[i]) return true return false } if (x.isEven()) return false i = 1 while (i < lowprimes.length) { var m = lowprimes[i], j = i + 1 while (j < lowprimes.length && m < lplim) m *= lowprimes[j++] m = x.modInt(m) while (i < j) if (m % lowprimes[i++] == 0) return false } return x.millerRabin(t) } // (protected) true if probably prime (HAC 4.24, Miller-Rabin) function bnpMillerRabin(t) { var n1 = this.subtract(BigInteger.ONE) var k = n1.getLowestSetBit() if (k <= 0) return false var r = n1.shiftRight(k) t = (t + 1) >> 1 if (t > lowprimes.length) t = lowprimes.length var a = new BigInteger(null) var j, bases = [] for (var i = 0; i < t; ++i) { for (;;) { j = lowprimes[Math.floor(Math.random() * lowprimes.length)] if (bases.indexOf(j) == -1) break } bases.push(j) a.fromInt(j) var y = a.modPow(r, this) if (y.compareTo(BigInteger.ONE) != 0 && y.compareTo(n1) != 0) { var j = 1 while (j++ < k && y.compareTo(n1) != 0) { y = y.modPowInt(2, this) if (y.compareTo(BigInteger.ONE) == 0) return false } if (y.compareTo(n1) != 0) return false } } return true } // protected proto.chunkSize = bnpChunkSize proto.toRadix = bnpToRadix proto.fromRadix = bnpFromRadix proto.fromNumber = bnpFromNumber proto.bitwiseTo = bnpBitwiseTo proto.changeBit = bnpChangeBit proto.addTo = bnpAddTo proto.dMultiply = bnpDMultiply proto.dAddOffset = bnpDAddOffset proto.multiplyLowerTo = bnpMultiplyLowerTo proto.multiplyUpperTo = bnpMultiplyUpperTo proto.modInt = bnpModInt proto.millerRabin = bnpMillerRabin // public proto.clone = bnClone proto.intValue = bnIntValue proto.byteValue = bnByteValue proto.shortValue = bnShortValue proto.signum = bnSigNum proto.toByteArray = bnToByteArray proto.equals = bnEquals proto.min = bnMin proto.max = bnMax proto.and = bnAnd proto.or = bnOr proto.xor = bnXor proto.andNot = bnAndNot proto.not = bnNot proto.shiftLeft = bnShiftLeft proto.shiftRight = bnShiftRight proto.getLowestSetBit = bnGetLowestSetBit proto.bitCount = bnBitCount proto.testBit = bnTestBit proto.setBit = bnSetBit proto.clearBit = bnClearBit proto.flipBit = bnFlipBit proto.add = bnAdd proto.subtract = bnSubtract proto.multiply = bnMultiply proto.divide = bnDivide proto.remainder = bnRemainder proto.divideAndRemainder = bnDivideAndRemainder proto.modPow = bnModPow proto.modInverse = bnModInverse proto.pow = bnPow proto.gcd = bnGCD proto.isProbablePrime = bnIsProbablePrime // JSBN-specific extension proto.square = bnSquare // constants BigInteger.ZERO = nbv(0) BigInteger.ONE = nbv(1) BigInteger.valueOf = nbv module.exports = BigInteger },{"../package.json":71}],69:[function(require,module,exports){ (function (Buffer){ // FIXME: Kind of a weird way to throw exceptions, consider removing var assert = require('assert') var BigInteger = require('./bigi') /** * Turns a byte array into a big integer. * * This function will interpret a byte array as a big integer in big * endian notation. */ BigInteger.fromByteArrayUnsigned = function(byteArray) { // BigInteger expects a DER integer conformant byte array if (byteArray[0] & 0x80) { return new BigInteger([0].concat(byteArray)) } return new BigInteger(byteArray) } /** * Returns a byte array representation of the big integer. * * This returns the absolute of the contained value in big endian * form. A value of zero results in an empty array. */ BigInteger.prototype.toByteArrayUnsigned = function() { var byteArray = this.toByteArray() return byteArray[0] === 0 ? byteArray.slice(1) : byteArray } BigInteger.fromDERInteger = function(byteArray) { return new BigInteger(byteArray) } /* * Converts BigInteger to a DER integer representation. * * The format for this value uses the most significant bit as a sign * bit. If the most significant bit is already set and the integer is * positive, a 0x00 is prepended. * * Examples: * * 0 => 0x00 * 1 => 0x01 * -1 => 0xff * 127 => 0x7f * -127 => 0x81 * 128 => 0x0080 * -128 => 0x80 * 255 => 0x00ff * -255 => 0xff01 * 16300 => 0x3fac * -16300 => 0xc054 * 62300 => 0x00f35c * -62300 => 0xff0ca4 */ BigInteger.prototype.toDERInteger = BigInteger.prototype.toByteArray BigInteger.fromBuffer = function(buffer) { // BigInteger expects a DER integer conformant byte array if (buffer[0] & 0x80) { var byteArray = Array.prototype.slice.call(buffer) return new BigInteger([0].concat(byteArray)) } return new BigInteger(buffer) } BigInteger.fromHex = function(hex) { if (hex === '') return BigInteger.ZERO assert.equal(hex, hex.match(/^[A-Fa-f0-9]+/), 'Invalid hex string') assert.equal(hex.length % 2, 0, 'Incomplete hex') return new BigInteger(hex, 16) } BigInteger.prototype.toBuffer = function(size) { var byteArray = this.toByteArrayUnsigned() var zeros = [] var padding = size - byteArray.length while (zeros.length < padding) zeros.push(0) return new Buffer(zeros.concat(byteArray)) } BigInteger.prototype.toHex = function(size) { return this.toBuffer(size).toString('hex') } }).call(this,require("buffer").Buffer) },{"./bigi":68,"assert":147,"buffer":179}],70:[function(require,module,exports){ var BigInteger = require('./bigi') //addons require('./convert') module.exports = BigInteger },{"./bigi":68,"./convert":69}],71:[function(require,module,exports){ module.exports={ "_args": [ [ "bigi@1.4.2", "/Users/hank/blockstack/js" ] ], "_from": "bigi@1.4.2", "_id": "bigi@1.4.2", "_inBundle": false, "_integrity": "sha1-nGZalfiLiwj8Bc/XMfVhhZ1yWCU=", "_location": "/bigi", "_phantomChildren": {}, "_requested": { "type": "version", "registry": true, "raw": "bigi@1.4.2", "name": "bigi", "escapedName": "bigi", "rawSpec": "1.4.2", "saveSpec": null, "fetchSpec": "1.4.2" }, "_requiredBy": [ "/", "/ecurve" ], "_resolved": "https://registry.npmjs.org/bigi/-/bigi-1.4.2.tgz", "_spec": "1.4.2", "_where": "/Users/hank/blockstack/js", "bugs": { "url": "https://github.com/cryptocoinjs/bigi/issues" }, "dependencies": {}, "description": "Big integers.", "devDependencies": { "coveralls": "^2.11.2", "istanbul": "^0.3.5", "jshint": "^2.5.1", "mocha": "^2.1.0", "mochify": "^2.1.0" }, "homepage": "https://github.com/cryptocoinjs/bigi#readme", "keywords": [ "cryptography", "math", "bitcoin", "arbitrary", "precision", "arithmetic", "big", "integer", "int", "number", "biginteger", "bigint", "bignumber", "decimal", "float" ], "main": "./lib/index.js", "name": "bigi", "repository": { "url": "git+https://github.com/cryptocoinjs/bigi.git", "type": "git" }, "scripts": { "browser-test": "mochify --wd -R spec", "coverage": "istanbul cover ./node_modules/.bin/_mocha -- --reporter list test/*.js", "coveralls": "npm run-script coverage && node ./node_modules/.bin/coveralls < coverage/lcov.info", "jshint": "jshint --config jshint.json lib/*.js ; true", "test": "_mocha -- test/*.js", "unit": "mocha" }, "testling": { "files": "test/*.js", "harness": "mocha", "browsers": [ "ie/9..latest", "firefox/latest", "chrome/latest", "safari/6.0..latest", "iphone/6.0..latest", "android-browser/4.2..latest" ] }, "version": "1.4.2" } },{}],72:[function(require,module,exports){ let createHash = require('create-hash') let createHmac = require('create-hmac') function hash160 (buffer) { return createHash('rmd160').update( createHash('sha256').update(buffer).digest() ).digest() } function hmacSHA512 (key, data) { return createHmac('sha512', key).update(data).digest() } module.exports = { hash160, hmacSHA512 } },{"create-hash":279,"create-hmac":281}],73:[function(require,module,exports){ let Buffer = require('safe-buffer').Buffer let bs58check = require('bs58check') let crypto = require('./crypto') let ecc = require('tiny-secp256k1') let typeforce = require('typeforce') let wif = require('wif') let UINT256_TYPE = typeforce.BufferN(32) let NETWORK_TYPE = typeforce.compile({ wif: typeforce.UInt8, bip32: { public: typeforce.UInt32, private: typeforce.UInt32 } }) let BITCOIN = { wif: 0x80, bip32: { public: 0x0488b21e, private: 0x0488ade4 } } function BIP32 (d, Q, chainCode, network) { typeforce(NETWORK_TYPE, network) this.__d = d || null this.__Q = Q || null this.chainCode = chainCode this.depth = 0 this.index = 0 this.network = network this.parentFingerprint = 0x00000000 } Object.defineProperty(BIP32.prototype, 'identifier', { get: function () { return crypto.hash160(this.publicKey) } }) Object.defineProperty(BIP32.prototype, 'fingerprint', { get: function () { return this.identifier.slice(0, 4) } }) Object.defineProperty(BIP32.prototype, 'privateKey', { enumerable: false, get: function () { return this.__d } }) Object.defineProperty(BIP32.prototype, 'publicKey', { get: function () { if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__d, this.compressed) return this.__Q }}) // Private === not neutered // Public === neutered BIP32.prototype.isNeutered = function () { return this.__d === null } BIP32.prototype.neutered = function () { let neutered = fromPublicKey(this.publicKey, this.chainCode, this.network) neutered.depth = this.depth neutered.index = this.index neutered.parentFingerprint = this.parentFingerprint return neutered } BIP32.prototype.toBase58 = function () { let network = this.network let version = (!this.isNeutered()) ? network.bip32.private : network.bip32.public let buffer = Buffer.allocUnsafe(78) // 4 bytes: version bytes buffer.writeUInt32BE(version, 0) // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, .... buffer.writeUInt8(this.depth, 4) // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) buffer.writeUInt32BE(this.parentFingerprint, 5) // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. // This is encoded in big endian. (0x00000000 if master key) buffer.writeUInt32BE(this.index, 9) // 32 bytes: the chain code this.chainCode.copy(buffer, 13) // 33 bytes: the public key or private key data if (!this.isNeutered()) { // 0x00 + k for private keys buffer.writeUInt8(0, 45) this.privateKey.copy(buffer, 46) // 33 bytes: the public key } else { // X9.62 encoding for public keys this.publicKey.copy(buffer, 45) } return bs58check.encode(buffer) } BIP32.prototype.toWIF = function () { if (!this.privateKey) throw new TypeError('Missing private key') return wif.encode(this.network.wif, this.privateKey, true) } let HIGHEST_BIT = 0x80000000 // https://github.com/bitcoin/bips/blob/master/bip-0032.mediawiki#child-key-derivation-ckd-functions BIP32.prototype.derive = function (index) { typeforce(typeforce.UInt32, index) let isHardened = index >= HIGHEST_BIT let data = Buffer.allocUnsafe(37) // Hardened child if (isHardened) { if (this.isNeutered()) throw new TypeError('Missing private key for hardened child key') // data = 0x00 || ser256(kpar) || ser32(index) data[0] = 0x00 this.privateKey.copy(data, 1) data.writeUInt32BE(index, 33) // Normal child } else { // data = serP(point(kpar)) || ser32(index) // = serP(Kpar) || ser32(index) this.publicKey.copy(data, 0) data.writeUInt32BE(index, 33) } let I = crypto.hmacSHA512(this.chainCode, data) let IL = I.slice(0, 32) let IR = I.slice(32) // if parse256(IL) >= n, proceed with the next value for i if (!ecc.isPrivate(IL)) return this.derive(index + 1) // Private parent key -> private child key let hd if (!this.isNeutered()) { // ki = parse256(IL) + kpar (mod n) let ki = ecc.privateAdd(this.privateKey, IL) // In case ki == 0, proceed with the next value for i if (ki == null) return this.derive(index + 1) hd = fromPrivateKey(ki, IR, this.network) // Public parent key -> public child key } else { // Ki = point(parse256(IL)) + Kpar // = G*IL + Kpar let Ki = ecc.pointAddScalar(this.publicKey, IL, true) // In case Ki is the point at infinity, proceed with the next value for i if (Ki === null) return this.derive(index + 1) hd = fromPublicKey(Ki, IR, this.network) } hd.depth = this.depth + 1 hd.index = index hd.parentFingerprint = this.fingerprint.readUInt32BE(0) return hd } let UINT31_MAX = Math.pow(2, 31) - 1 function UInt31 (value) { return typeforce.UInt32(value) && value <= UINT31_MAX } BIP32.prototype.deriveHardened = function (index) { typeforce(UInt31, index) // Only derives hardened private keys by default return this.derive(index + HIGHEST_BIT) } function BIP32Path (value) { return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) } BIP32.prototype.derivePath = function (path) { typeforce(BIP32Path, path) let splitPath = path.split('/') if (splitPath[0] === 'm') { if (this.parentFingerprint) throw new TypeError('Expected master, got child') splitPath = splitPath.slice(1) } return splitPath.reduce(function (prevHd, indexStr) { let index if (indexStr.slice(-1) === "'") { index = parseInt(indexStr.slice(0, -1), 10) return prevHd.deriveHardened(index) } else { index = parseInt(indexStr, 10) return prevHd.derive(index) } }, this) } BIP32.prototype.sign = function (hash) { return ecc.sign(hash, this.privateKey) } BIP32.prototype.verify = function (hash, signature) { return ecc.verify(hash, this.publicKey, signature) } function fromBase58 (string, network) { let buffer = bs58check.decode(string) if (buffer.length !== 78) throw new TypeError('Invalid buffer length') network = network || BITCOIN // 4 bytes: version bytes let version = buffer.readUInt32BE(0) if (version !== network.bip32.private && version !== network.bip32.public) throw new TypeError('Invalid network version') // 1 byte: depth: 0x00 for master nodes, 0x01 for level-1 descendants, ... let depth = buffer[4] // 4 bytes: the fingerprint of the parent's key (0x00000000 if master key) let parentFingerprint = buffer.readUInt32BE(5) if (depth === 0) { if (parentFingerprint !== 0x00000000) throw new TypeError('Invalid parent fingerprint') } // 4 bytes: child number. This is the number i in xi = xpar/i, with xi the key being serialized. // This is encoded in MSB order. (0x00000000 if master key) let index = buffer.readUInt32BE(9) if (depth === 0 && index !== 0) throw new TypeError('Invalid index') // 32 bytes: the chain code let chainCode = buffer.slice(13, 45) let hd // 33 bytes: private key data (0x00 + k) if (version === network.bip32.private) { if (buffer.readUInt8(45) !== 0x00) throw new TypeError('Invalid private key') let k = buffer.slice(46, 78) hd = fromPrivateKey(k, chainCode, network) // 33 bytes: public key data (0x02 + X or 0x03 + X) } else { let X = buffer.slice(45, 78) hd = fromPublicKey(X, chainCode, network) } hd.depth = depth hd.index = index hd.parentFingerprint = parentFingerprint return hd } function fromPrivateKey (privateKey, chainCode, network) { typeforce({ privateKey: UINT256_TYPE, chainCode: UINT256_TYPE }, { privateKey, chainCode }) network = network || BITCOIN if (!ecc.isPrivate(privateKey)) throw new TypeError('Private key not in range [1, n)') return new BIP32(privateKey, null, chainCode, network) } function fromPublicKey (publicKey, chainCode, network) { typeforce({ publicKey: typeforce.BufferN(33), chainCode: UINT256_TYPE }, { publicKey, chainCode }) network = network || BITCOIN // verify the X coordinate is a point on the curve if (!ecc.isPoint(publicKey)) throw new TypeError('Point is not on the curve') return new BIP32(null, publicKey, chainCode, network) } function fromSeed (seed, network) { typeforce(typeforce.Buffer, seed) if (seed.length < 16) throw new TypeError('Seed should be at least 128 bits') if (seed.length > 64) throw new TypeError('Seed should be at most 512 bits') network = network || BITCOIN let I = crypto.hmacSHA512('Bitcoin seed', seed) let IL = I.slice(0, 32) let IR = I.slice(32) return fromPrivateKey(IL, IR, network) } module.exports = { fromBase58, fromPrivateKey, fromPublicKey, fromSeed } },{"./crypto":72,"bs58check":265,"safe-buffer":457,"tiny-secp256k1":469,"typeforce":496,"wif":565}],74:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var createHash = require('create-hash') var pbkdf2 = require('pbkdf2').pbkdf2Sync var randomBytes = require('randombytes') // use unorm until String.prototype.normalize gets better browser support var unorm = require('unorm') var CHINESE_SIMPLIFIED_WORDLIST = require('./wordlists/chinese_simplified.json') var CHINESE_TRADITIONAL_WORDLIST = require('./wordlists/chinese_traditional.json') var ENGLISH_WORDLIST = require('./wordlists/english.json') var FRENCH_WORDLIST = require('./wordlists/french.json') var ITALIAN_WORDLIST = require('./wordlists/italian.json') var JAPANESE_WORDLIST = require('./wordlists/japanese.json') var KOREAN_WORDLIST = require('./wordlists/korean.json') var SPANISH_WORDLIST = require('./wordlists/spanish.json') var DEFAULT_WORDLIST = ENGLISH_WORDLIST var INVALID_MNEMONIC = 'Invalid mnemonic' var INVALID_ENTROPY = 'Invalid entropy' var INVALID_CHECKSUM = 'Invalid mnemonic checksum' function lpad (str, padString, length) { while (str.length < length) str = padString + str return str } function binaryToByte (bin) { return parseInt(bin, 2) } function bytesToBinary (bytes) { return bytes.map(function (x) { return lpad(x.toString(2), '0', 8) }).join('') } function deriveChecksumBits (entropyBuffer) { var ENT = entropyBuffer.length * 8 var CS = ENT / 32 var hash = createHash('sha256').update(entropyBuffer).digest() return bytesToBinary([].slice.call(hash)).slice(0, CS) } function salt (password) { return 'mnemonic' + (password || '') } function mnemonicToSeed (mnemonic, password) { var mnemonicBuffer = Buffer.from(unorm.nfkd(mnemonic), 'utf8') var saltBuffer = Buffer.from(salt(unorm.nfkd(password)), 'utf8') return pbkdf2(mnemonicBuffer, saltBuffer, 2048, 64, 'sha512') } function mnemonicToSeedHex (mnemonic, password) { return mnemonicToSeed(mnemonic, password).toString('hex') } function mnemonicToEntropy (mnemonic, wordlist) { wordlist = wordlist || DEFAULT_WORDLIST var words = unorm.nfkd(mnemonic).split(' ') if (words.length % 3 !== 0) throw new Error(INVALID_MNEMONIC) // convert word indices to 11 bit binary strings var bits = words.map(function (word) { var index = wordlist.indexOf(word) if (index === -1) throw new Error(INVALID_MNEMONIC) return lpad(index.toString(2), '0', 11) }).join('') // split the binary string into ENT/CS var dividerIndex = Math.floor(bits.length / 33) * 32 var entropyBits = bits.slice(0, dividerIndex) var checksumBits = bits.slice(dividerIndex) // calculate the checksum and compare var entropyBytes = entropyBits.match(/(.{1,8})/g).map(binaryToByte) if (entropyBytes.length < 16) throw new Error(INVALID_ENTROPY) if (entropyBytes.length > 32) throw new Error(INVALID_ENTROPY) if (entropyBytes.length % 4 !== 0) throw new Error(INVALID_ENTROPY) var entropy = Buffer.from(entropyBytes) var newChecksum = deriveChecksumBits(entropy) if (newChecksum !== checksumBits) throw new Error(INVALID_CHECKSUM) return entropy.toString('hex') } function entropyToMnemonic (entropy, wordlist) { if (!Buffer.isBuffer(entropy)) entropy = Buffer.from(entropy, 'hex') wordlist = wordlist || DEFAULT_WORDLIST // 128 <= ENT <= 256 if (entropy.length < 16) throw new TypeError(INVALID_ENTROPY) if (entropy.length > 32) throw new TypeError(INVALID_ENTROPY) if (entropy.length % 4 !== 0) throw new TypeError(INVALID_ENTROPY) var entropyBits = bytesToBinary([].slice.call(entropy)) var checksumBits = deriveChecksumBits(entropy) var bits = entropyBits + checksumBits var chunks = bits.match(/(.{1,11})/g) var words = chunks.map(function (binary) { var index = binaryToByte(binary) return wordlist[index] }) return wordlist === JAPANESE_WORDLIST ? words.join('\u3000') : words.join(' ') } function generateMnemonic (strength, rng, wordlist) { strength = strength || 128 if (strength % 32 !== 0) throw new TypeError(INVALID_ENTROPY) rng = rng || randomBytes return entropyToMnemonic(rng(strength / 8), wordlist) } function validateMnemonic (mnemonic, wordlist) { try { mnemonicToEntropy(mnemonic, wordlist) } catch (e) { return false } return true } module.exports = { mnemonicToSeed: mnemonicToSeed, mnemonicToSeedHex: mnemonicToSeedHex, mnemonicToEntropy: mnemonicToEntropy, entropyToMnemonic: entropyToMnemonic, generateMnemonic: generateMnemonic, validateMnemonic: validateMnemonic, wordlists: { EN: ENGLISH_WORDLIST, JA: JAPANESE_WORDLIST, chinese_simplified: CHINESE_SIMPLIFIED_WORDLIST, chinese_traditional: CHINESE_TRADITIONAL_WORDLIST, english: ENGLISH_WORDLIST, french: FRENCH_WORDLIST, italian: ITALIAN_WORDLIST, japanese: JAPANESE_WORDLIST, korean: KOREAN_WORDLIST, spanish: SPANISH_WORDLIST } } },{"./wordlists/chinese_simplified.json":75,"./wordlists/chinese_traditional.json":76,"./wordlists/english.json":77,"./wordlists/french.json":78,"./wordlists/italian.json":79,"./wordlists/japanese.json":80,"./wordlists/korean.json":81,"./wordlists/spanish.json":82,"create-hash":279,"pbkdf2":444,"randombytes":453,"safe-buffer":457,"unorm":498}],75:[function(require,module,exports){ module.exports=[ "的", "一", "是", "在", "不", "了", "有", "和", "人", "这", "中", "大", "为", "上", "个", "国", "我", "以", "要", "他", "时", "来", "用", "们", "生", "到", "作", "地", "于", "出", "就", "分", "对", "成", "会", "可", "主", "发", "年", "动", "同", "工", "也", "能", "下", "过", "子", "说", "产", "种", "面", "而", "方", "后", "多", "定", "行", "学", "法", "所", "民", "得", "经", "十", "三", "之", "进", "着", "等", "部", "度", "家", "电", "力", "里", "如", "水", "化", "高", "自", "二", "理", "起", "小", "物", "现", "实", "加", "量", "都", "两", "体", "制", "机", "当", "使", "点", "从", "业", "本", "去", "把", "性", "好", "应", "开", "它", "合", "还", "因", "由", "其", "些", "然", "前", "外", "天", "政", "四", "日", "那", "社", "义", "事", "平", "形", "相", "全", "表", "间", "样", "与", "关", "各", "重", "新", "线", "内", "数", "正", "心", "反", "你", "明", "看", "原", "又", "么", "利", "比", "或", "但", "质", "气", "第", "向", "道", "命", "此", "变", "条", "只", "没", "结", "解", "问", "意", "建", "月", "公", "无", "系", "军", "很", "情", "者", "最", "立", "代", "想", "已", "通", "并", "提", "直", "题", "党", "程", "展", "五", "果", "料", "象", "员", "革", "位", "入", "常", "文", "总", "次", "品", "式", "活", "设", "及", "管", "特", "件", "长", "求", "老", "头", "基", "资", "边", "流", "路", "级", "少", "图", "山", "统", "接", "知", "较", "将", "组", "见", "计", "别", "她", "手", "角", "期", "根", "论", "运", "农", "指", "几", "九", "区", "强", "放", "决", "西", "被", "干", "做", "必", "战", "先", "回", "则", "任", "取", "据", "处", "队", "南", "给", "色", "光", "门", "即", "保", "治", "北", "造", "百", "规", "热", "领", "七", "海", "口", "东", "导", "器", "压", "志", "世", "金", "增", "争", "济", "阶", "油", "思", "术", "极", "交", "受", "联", "什", "认", "六", "共", "权", "收", "证", "改", "清", "美", "再", "采", "转", "更", "单", "风", "切", "打", "白", "教", "速", "花", "带", "安", "场", "身", "车", "例", "真", "务", "具", "万", "每", "目", "至", "达", "走", "积", "示", "议", "声", "报", "斗", "完", "类", "八", "离", "华", "名", "确", "才", "科", "张", "信", "马", "节", "话", "米", "整", "空", "元", "况", "今", "集", "温", "传", "土", "许", "步", "群", "广", "石", "记", "需", "段", "研", "界", "拉", "林", "律", "叫", "且", "究", "观", "越", "织", "装", "影", "算", "低", "持", "音", "众", "书", "布", "复", "容", "儿", "须", "际", "商", "非", "验", "连", "断", "深", "难", "近", "矿", "千", "周", "委", "素", "技", "备", "半", "办", "青", "省", "列", "习", "响", "约", "支", "般", "史", "感", "劳", "便", "团", "往", "酸", "历", "市", "克", "何", "除", "消", "构", "府", "称", "太", "准", "精", "值", "号", "率", "族", "维", "划", "选", "标", "写", "存", "候", "毛", "亲", "快", "效", "斯", "院", "查", "江", "型", "眼", "王", "按", "格", "养", "易", "置", "派", "层", "片", "始", "却", "专", "状", "育", "厂", "京", "识", "适", "属", "圆", "包", "火", "住", "调", "满", "县", "局", "照", "参", "红", "细", "引", "听", "该", "铁", "价", "严", "首", "底", "液", "官", "德", "随", "病", "苏", "失", "尔", "死", "讲", "配", "女", "黄", "推", "显", "谈", "罪", "神", "艺", "呢", "席", "含", "企", "望", "密", "批", "营", "项", "防", "举", "球", "英", "氧", "势", "告", "李", "台", "落", "木", "帮", "轮", "破", "亚", "师", "围", "注", "远", "字", "材", "排", "供", "河", "态", "封", "另", "施", "减", "树", "溶", "怎", "止", "案", "言", "士", "均", "武", "固", "叶", "鱼", "波", "视", "仅", "费", "紧", "爱", "左", "章", "早", "朝", "害", "续", "轻", "服", "试", "食", "充", "兵", "源", "判", "护", "司", "足", "某", "练", "差", "致", "板", "田", "降", "黑", "犯", "负", "击", "范", "继", "兴", "似", "余", "坚", "曲", "输", "修", "故", "城", "夫", "够", "送", "笔", "船", "占", "右", "财", "吃", "富", "春", "职", "觉", "汉", "画", "功", "巴", "跟", "虽", "杂", "飞", "检", "吸", "助", "升", "阳", "互", "初", "创", "抗", "考", "投", "坏", "策", "古", "径", "换", "未", "跑", "留", "钢", "曾", "端", "责", "站", "简", "述", "钱", "副", "尽", "帝", "射", "草", "冲", "承", "独", "令", "限", "阿", "宣", "环", "双", "请", "超", "微", "让", "控", "州", "良", "轴", "找", "否", "纪", "益", "依", "优", "顶", "础", "载", "倒", "房", "突", "坐", "粉", "敌", "略", "客", "袁", "冷", "胜", "绝", "析", "块", "剂", "测", "丝", "协", "诉", "念", "陈", "仍", "罗", "盐", "友", "洋", "错", "苦", "夜", "刑", "移", "频", "逐", "靠", "混", "母", "短", "皮", "终", "聚", "汽", "村", "云", "哪", "既", "距", "卫", "停", "烈", "央", "察", "烧", "迅", "境", "若", "印", "洲", "刻", "括", "激", "孔", "搞", "甚", "室", "待", "核", "校", "散", "侵", "吧", "甲", "游", "久", "菜", "味", "旧", "模", "湖", "货", "损", "预", "阻", "毫", "普", "稳", "乙", "妈", "植", "息", "扩", "银", "语", "挥", "酒", "守", "拿", "序", "纸", "医", "缺", "雨", "吗", "针", "刘", "啊", "急", "唱", "误", "训", "愿", "审", "附", "获", "茶", "鲜", "粮", "斤", "孩", "脱", "硫", "肥", "善", "龙", "演", "父", "渐", "血", "欢", "械", "掌", "歌", "沙", "刚", "攻", "谓", "盾", "讨", "晚", "粒", "乱", "燃", "矛", "乎", "杀", "药", "宁", "鲁", "贵", "钟", "煤", "读", "班", "伯", "香", "介", "迫", "句", "丰", "培", "握", "兰", "担", "弦", "蛋", "沉", "假", "穿", "执", "答", "乐", "谁", "顺", "烟", "缩", "征", "脸", "喜", "松", "脚", "困", "异", "免", "背", "星", "福", "买", "染", "井", "概", "慢", "怕", "磁", "倍", "祖", "皇", "促", "静", "补", "评", "翻", "肉", "践", "尼", "衣", "宽", "扬", "棉", "希", "伤", "操", "垂", "秋", "宜", "氢", "套", "督", "振", "架", "亮", "末", "宪", "庆", "编", "牛", "触", "映", "雷", "销", "诗", "座", "居", "抓", "裂", "胞", "呼", "娘", "景", "威", "绿", "晶", "厚", "盟", "衡", "鸡", "孙", "延", "危", "胶", "屋", "乡", "临", "陆", "顾", "掉", "呀", "灯", "岁", "措", "束", "耐", "剧", "玉", "赵", "跳", "哥", "季", "课", "凯", "胡", "额", "款", "绍", "卷", "齐", "伟", "蒸", "殖", "永", "宗", "苗", "川", "炉", "岩", "弱", "零", "杨", "奏", "沿", "露", "杆", "探", "滑", "镇", "饭", "浓", "航", "怀", "赶", "库", "夺", "伊", "灵", "税", "途", "灭", "赛", "归", "召", "鼓", "播", "盘", "裁", "险", "康", "唯", "录", "菌", "纯", "借", "糖", "盖", "横", "符", "私", "努", "堂", "域", "枪", "润", "幅", "哈", "竟", "熟", "虫", "泽", "脑", "壤", "碳", "欧", "遍", "侧", "寨", "敢", "彻", "虑", "斜", "薄", "庭", "纳", "弹", "饲", "伸", "折", "麦", "湿", "暗", "荷", "瓦", "塞", "床", "筑", "恶", "户", "访", "塔", "奇", "透", "梁", "刀", "旋", "迹", "卡", "氯", "遇", "份", "毒", "泥", "退", "洗", "摆", "灰", "彩", "卖", "耗", "夏", "择", "忙", "铜", "献", "硬", "予", "繁", "圈", "雪", "函", "亦", "抽", "篇", "阵", "阴", "丁", "尺", "追", "堆", "雄", "迎", "泛", "爸", "楼", "避", "谋", "吨", "野", "猪", "旗", "累", "偏", "典", "馆", "索", "秦", "脂", "潮", "爷", "豆", "忽", "托", "惊", "塑", "遗", "愈", "朱", "替", "纤", "粗", "倾", "尚", "痛", "楚", "谢", "奋", "购", "磨", "君", "池", "旁", "碎", "骨", "监", "捕", "弟", "暴", "割", "贯", "殊", "释", "词", "亡", "壁", "顿", "宝", "午", "尘", "闻", "揭", "炮", "残", "冬", "桥", "妇", "警", "综", "招", "吴", "付", "浮", "遭", "徐", "您", "摇", "谷", "赞", "箱", "隔", "订", "男", "吹", "园", "纷", "唐", "败", "宋", "玻", "巨", "耕", "坦", "荣", "闭", "湾", "键", "凡", "驻", "锅", "救", "恩", "剥", "凝", "碱", "齿", "截", "炼", "麻", "纺", "禁", "废", "盛", "版", "缓", "净", "睛", "昌", "婚", "涉", "筒", "嘴", "插", "岸", "朗", "庄", "街", "藏", "姑", "贸", "腐", "奴", "啦", "惯", "乘", "伙", "恢", "匀", "纱", "扎", "辩", "耳", "彪", "臣", "亿", "璃", "抵", "脉", "秀", "萨", "俄", "网", "舞", "店", "喷", "纵", "寸", "汗", "挂", "洪", "贺", "闪", "柬", "爆", "烯", "津", "稻", "墙", "软", "勇", "像", "滚", "厘", "蒙", "芳", "肯", "坡", "柱", "荡", "腿", "仪", "旅", "尾", "轧", "冰", "贡", "登", "黎", "削", "钻", "勒", "逃", "障", "氨", "郭", "峰", "币", "港", "伏", "轨", "亩", "毕", "擦", "莫", "刺", "浪", "秘", "援", "株", "健", "售", "股", "岛", "甘", "泡", "睡", "童", "铸", "汤", "阀", "休", "汇", "舍", "牧", "绕", "炸", "哲", "磷", "绩", "朋", "淡", "尖", "启", "陷", "柴", "呈", "徒", "颜", "泪", "稍", "忘", "泵", "蓝", "拖", "洞", "授", "镜", "辛", "壮", "锋", "贫", "虚", "弯", "摩", "泰", "幼", "廷", "尊", "窗", "纲", "弄", "隶", "疑", "氏", "宫", "姐", "震", "瑞", "怪", "尤", "琴", "循", "描", "膜", "违", "夹", "腰", "缘", "珠", "穷", "森", "枝", "竹", "沟", "催", "绳", "忆", "邦", "剩", "幸", "浆", "栏", "拥", "牙", "贮", "礼", "滤", "钠", "纹", "罢", "拍", "咱", "喊", "袖", "埃", "勤", "罚", "焦", "潜", "伍", "墨", "欲", "缝", "姓", "刊", "饱", "仿", "奖", "铝", "鬼", "丽", "跨", "默", "挖", "链", "扫", "喝", "袋", "炭", "污", "幕", "诸", "弧", "励", "梅", "奶", "洁", "灾", "舟", "鉴", "苯", "讼", "抱", "毁", "懂", "寒", "智", "埔", "寄", "届", "跃", "渡", "挑", "丹", "艰", "贝", "碰", "拔", "爹", "戴", "码", "梦", "芽", "熔", "赤", "渔", "哭", "敬", "颗", "奔", "铅", "仲", "虎", "稀", "妹", "乏", "珍", "申", "桌", "遵", "允", "隆", "螺", "仓", "魏", "锐", "晓", "氮", "兼", "隐", "碍", "赫", "拨", "忠", "肃", "缸", "牵", "抢", "博", "巧", "壳", "兄", "杜", "讯", "诚", "碧", "祥", "柯", "页", "巡", "矩", "悲", "灌", "龄", "伦", "票", "寻", "桂", "铺", "圣", "恐", "恰", "郑", "趣", "抬", "荒", "腾", "贴", "柔", "滴", "猛", "阔", "辆", "妻", "填", "撤", "储", "签", "闹", "扰", "紫", "砂", "递", "戏", "吊", "陶", "伐", "喂", "疗", "瓶", "婆", "抚", "臂", "摸", "忍", "虾", "蜡", "邻", "胸", "巩", "挤", "偶", "弃", "槽", "劲", "乳", "邓", "吉", "仁", "烂", "砖", "租", "乌", "舰", "伴", "瓜", "浅", "丙", "暂", "燥", "橡", "柳", "迷", "暖", "牌", "秧", "胆", "详", "簧", "踏", "瓷", "谱", "呆", "宾", "糊", "洛", "辉", "愤", "竞", "隙", "怒", "粘", "乃", "绪", "肩", "籍", "敏", "涂", "熙", "皆", "侦", "悬", "掘", "享", "纠", "醒", "狂", "锁", "淀", "恨", "牲", "霸", "爬", "赏", "逆", "玩", "陵", "祝", "秒", "浙", "貌", "役", "彼", "悉", "鸭", "趋", "凤", "晨", "畜", "辈", "秩", "卵", "署", "梯", "炎", "滩", "棋", "驱", "筛", "峡", "冒", "啥", "寿", "译", "浸", "泉", "帽", "迟", "硅", "疆", "贷", "漏", "稿", "冠", "嫩", "胁", "芯", "牢", "叛", "蚀", "奥", "鸣", "岭", "羊", "凭", "串", "塘", "绘", "酵", "融", "盆", "锡", "庙", "筹", "冻", "辅", "摄", "袭", "筋", "拒", "僚", "旱", "钾", "鸟", "漆", "沈", "眉", "疏", "添", "棒", "穗", "硝", "韩", "逼", "扭", "侨", "凉", "挺", "碗", "栽", "炒", "杯", "患", "馏", "劝", "豪", "辽", "勃", "鸿", "旦", "吏", "拜", "狗", "埋", "辊", "掩", "饮", "搬", "骂", "辞", "勾", "扣", "估", "蒋", "绒", "雾", "丈", "朵", "姆", "拟", "宇", "辑", "陕", "雕", "偿", "蓄", "崇", "剪", "倡", "厅", "咬", "驶", "薯", "刷", "斥", "番", "赋", "奉", "佛", "浇", "漫", "曼", "扇", "钙", "桃", "扶", "仔", "返", "俗", "亏", "腔", "鞋", "棱", "覆", "框", "悄", "叔", "撞", "骗", "勘", "旺", "沸", "孤", "吐", "孟", "渠", "屈", "疾", "妙", "惜", "仰", "狠", "胀", "谐", "抛", "霉", "桑", "岗", "嘛", "衰", "盗", "渗", "脏", "赖", "涌", "甜", "曹", "阅", "肌", "哩", "厉", "烃", "纬", "毅", "昨", "伪", "症", "煮", "叹", "钉", "搭", "茎", "笼", "酷", "偷", "弓", "锥", "恒", "杰", "坑", "鼻", "翼", "纶", "叙", "狱", "逮", "罐", "络", "棚", "抑", "膨", "蔬", "寺", "骤", "穆", "冶", "枯", "册", "尸", "凸", "绅", "坯", "牺", "焰", "轰", "欣", "晋", "瘦", "御", "锭", "锦", "丧", "旬", "锻", "垄", "搜", "扑", "邀", "亭", "酯", "迈", "舒", "脆", "酶", "闲", "忧", "酚", "顽", "羽", "涨", "卸", "仗", "陪", "辟", "惩", "杭", "姚", "肚", "捉", "飘", "漂", "昆", "欺", "吾", "郎", "烷", "汁", "呵", "饰", "萧", "雅", "邮", "迁", "燕", "撒", "姻", "赴", "宴", "烦", "债", "帐", "斑", "铃", "旨", "醇", "董", "饼", "雏", "姿", "拌", "傅", "腹", "妥", "揉", "贤", "拆", "歪", "葡", "胺", "丢", "浩", "徽", "昂", "垫", "挡", "览", "贪", "慰", "缴", "汪", "慌", "冯", "诺", "姜", "谊", "凶", "劣", "诬", "耀", "昏", "躺", "盈", "骑", "乔", "溪", "丛", "卢", "抹", "闷", "咨", "刮", "驾", "缆", "悟", "摘", "铒", "掷", "颇", "幻", "柄", "惠", "惨", "佳", "仇", "腊", "窝", "涤", "剑", "瞧", "堡", "泼", "葱", "罩", "霍", "捞", "胎", "苍", "滨", "俩", "捅", "湘", "砍", "霞", "邵", "萄", "疯", "淮", "遂", "熊", "粪", "烘", "宿", "档", "戈", "驳", "嫂", "裕", "徙", "箭", "捐", "肠", "撑", "晒", "辨", "殿", "莲", "摊", "搅", "酱", "屏", "疫", "哀", "蔡", "堵", "沫", "皱", "畅", "叠", "阁", "莱", "敲", "辖", "钩", "痕", "坝", "巷", "饿", "祸", "丘", "玄", "溜", "曰", "逻", "彭", "尝", "卿", "妨", "艇", "吞", "韦", "怨", "矮", "歇" ] },{}],76:[function(require,module,exports){ module.exports=[ "的", "一", "是", "在", "不", "了", "有", "和", "人", "這", "中", "大", "為", "上", "個", "國", "我", "以", "要", "他", "時", "來", "用", "們", "生", "到", "作", "地", "於", "出", "就", "分", "對", "成", "會", "可", "主", "發", "年", "動", "同", "工", "也", "能", "下", "過", "子", "說", "產", "種", "面", "而", "方", "後", "多", "定", "行", "學", "法", "所", "民", "得", "經", "十", "三", "之", "進", "著", "等", "部", "度", "家", "電", "力", "裡", "如", "水", "化", "高", "自", "二", "理", "起", "小", "物", "現", "實", "加", "量", "都", "兩", "體", "制", "機", "當", "使", "點", "從", "業", "本", "去", "把", "性", "好", "應", "開", "它", "合", "還", "因", "由", "其", "些", "然", "前", "外", "天", "政", "四", "日", "那", "社", "義", "事", "平", "形", "相", "全", "表", "間", "樣", "與", "關", "各", "重", "新", "線", "內", "數", "正", "心", "反", "你", "明", "看", "原", "又", "麼", "利", "比", "或", "但", "質", "氣", "第", "向", "道", "命", "此", "變", "條", "只", "沒", "結", "解", "問", "意", "建", "月", "公", "無", "系", "軍", "很", "情", "者", "最", "立", "代", "想", "已", "通", "並", "提", "直", "題", "黨", "程", "展", "五", "果", "料", "象", "員", "革", "位", "入", "常", "文", "總", "次", "品", "式", "活", "設", "及", "管", "特", "件", "長", "求", "老", "頭", "基", "資", "邊", "流", "路", "級", "少", "圖", "山", "統", "接", "知", "較", "將", "組", "見", "計", "別", "她", "手", "角", "期", "根", "論", "運", "農", "指", "幾", "九", "區", "強", "放", "決", "西", "被", "幹", "做", "必", "戰", "先", "回", "則", "任", "取", "據", "處", "隊", "南", "給", "色", "光", "門", "即", "保", "治", "北", "造", "百", "規", "熱", "領", "七", "海", "口", "東", "導", "器", "壓", "志", "世", "金", "增", "爭", "濟", "階", "油", "思", "術", "極", "交", "受", "聯", "什", "認", "六", "共", "權", "收", "證", "改", "清", "美", "再", "採", "轉", "更", "單", "風", "切", "打", "白", "教", "速", "花", "帶", "安", "場", "身", "車", "例", "真", "務", "具", "萬", "每", "目", "至", "達", "走", "積", "示", "議", "聲", "報", "鬥", "完", "類", "八", "離", "華", "名", "確", "才", "科", "張", "信", "馬", "節", "話", "米", "整", "空", "元", "況", "今", "集", "溫", "傳", "土", "許", "步", "群", "廣", "石", "記", "需", "段", "研", "界", "拉", "林", "律", "叫", "且", "究", "觀", "越", "織", "裝", "影", "算", "低", "持", "音", "眾", "書", "布", "复", "容", "兒", "須", "際", "商", "非", "驗", "連", "斷", "深", "難", "近", "礦", "千", "週", "委", "素", "技", "備", "半", "辦", "青", "省", "列", "習", "響", "約", "支", "般", "史", "感", "勞", "便", "團", "往", "酸", "歷", "市", "克", "何", "除", "消", "構", "府", "稱", "太", "準", "精", "值", "號", "率", "族", "維", "劃", "選", "標", "寫", "存", "候", "毛", "親", "快", "效", "斯", "院", "查", "江", "型", "眼", "王", "按", "格", "養", "易", "置", "派", "層", "片", "始", "卻", "專", "狀", "育", "廠", "京", "識", "適", "屬", "圓", "包", "火", "住", "調", "滿", "縣", "局", "照", "參", "紅", "細", "引", "聽", "該", "鐵", "價", "嚴", "首", "底", "液", "官", "德", "隨", "病", "蘇", "失", "爾", "死", "講", "配", "女", "黃", "推", "顯", "談", "罪", "神", "藝", "呢", "席", "含", "企", "望", "密", "批", "營", "項", "防", "舉", "球", "英", "氧", "勢", "告", "李", "台", "落", "木", "幫", "輪", "破", "亞", "師", "圍", "注", "遠", "字", "材", "排", "供", "河", "態", "封", "另", "施", "減", "樹", "溶", "怎", "止", "案", "言", "士", "均", "武", "固", "葉", "魚", "波", "視", "僅", "費", "緊", "愛", "左", "章", "早", "朝", "害", "續", "輕", "服", "試", "食", "充", "兵", "源", "判", "護", "司", "足", "某", "練", "差", "致", "板", "田", "降", "黑", "犯", "負", "擊", "范", "繼", "興", "似", "餘", "堅", "曲", "輸", "修", "故", "城", "夫", "夠", "送", "筆", "船", "佔", "右", "財", "吃", "富", "春", "職", "覺", "漢", "畫", "功", "巴", "跟", "雖", "雜", "飛", "檢", "吸", "助", "昇", "陽", "互", "初", "創", "抗", "考", "投", "壞", "策", "古", "徑", "換", "未", "跑", "留", "鋼", "曾", "端", "責", "站", "簡", "述", "錢", "副", "盡", "帝", "射", "草", "衝", "承", "獨", "令", "限", "阿", "宣", "環", "雙", "請", "超", "微", "讓", "控", "州", "良", "軸", "找", "否", "紀", "益", "依", "優", "頂", "礎", "載", "倒", "房", "突", "坐", "粉", "敵", "略", "客", "袁", "冷", "勝", "絕", "析", "塊", "劑", "測", "絲", "協", "訴", "念", "陳", "仍", "羅", "鹽", "友", "洋", "錯", "苦", "夜", "刑", "移", "頻", "逐", "靠", "混", "母", "短", "皮", "終", "聚", "汽", "村", "雲", "哪", "既", "距", "衛", "停", "烈", "央", "察", "燒", "迅", "境", "若", "印", "洲", "刻", "括", "激", "孔", "搞", "甚", "室", "待", "核", "校", "散", "侵", "吧", "甲", "遊", "久", "菜", "味", "舊", "模", "湖", "貨", "損", "預", "阻", "毫", "普", "穩", "乙", "媽", "植", "息", "擴", "銀", "語", "揮", "酒", "守", "拿", "序", "紙", "醫", "缺", "雨", "嗎", "針", "劉", "啊", "急", "唱", "誤", "訓", "願", "審", "附", "獲", "茶", "鮮", "糧", "斤", "孩", "脫", "硫", "肥", "善", "龍", "演", "父", "漸", "血", "歡", "械", "掌", "歌", "沙", "剛", "攻", "謂", "盾", "討", "晚", "粒", "亂", "燃", "矛", "乎", "殺", "藥", "寧", "魯", "貴", "鐘", "煤", "讀", "班", "伯", "香", "介", "迫", "句", "豐", "培", "握", "蘭", "擔", "弦", "蛋", "沉", "假", "穿", "執", "答", "樂", "誰", "順", "煙", "縮", "徵", "臉", "喜", "松", "腳", "困", "異", "免", "背", "星", "福", "買", "染", "井", "概", "慢", "怕", "磁", "倍", "祖", "皇", "促", "靜", "補", "評", "翻", "肉", "踐", "尼", "衣", "寬", "揚", "棉", "希", "傷", "操", "垂", "秋", "宜", "氫", "套", "督", "振", "架", "亮", "末", "憲", "慶", "編", "牛", "觸", "映", "雷", "銷", "詩", "座", "居", "抓", "裂", "胞", "呼", "娘", "景", "威", "綠", "晶", "厚", "盟", "衡", "雞", "孫", "延", "危", "膠", "屋", "鄉", "臨", "陸", "顧", "掉", "呀", "燈", "歲", "措", "束", "耐", "劇", "玉", "趙", "跳", "哥", "季", "課", "凱", "胡", "額", "款", "紹", "卷", "齊", "偉", "蒸", "殖", "永", "宗", "苗", "川", "爐", "岩", "弱", "零", "楊", "奏", "沿", "露", "桿", "探", "滑", "鎮", "飯", "濃", "航", "懷", "趕", "庫", "奪", "伊", "靈", "稅", "途", "滅", "賽", "歸", "召", "鼓", "播", "盤", "裁", "險", "康", "唯", "錄", "菌", "純", "借", "糖", "蓋", "橫", "符", "私", "努", "堂", "域", "槍", "潤", "幅", "哈", "竟", "熟", "蟲", "澤", "腦", "壤", "碳", "歐", "遍", "側", "寨", "敢", "徹", "慮", "斜", "薄", "庭", "納", "彈", "飼", "伸", "折", "麥", "濕", "暗", "荷", "瓦", "塞", "床", "築", "惡", "戶", "訪", "塔", "奇", "透", "梁", "刀", "旋", "跡", "卡", "氯", "遇", "份", "毒", "泥", "退", "洗", "擺", "灰", "彩", "賣", "耗", "夏", "擇", "忙", "銅", "獻", "硬", "予", "繁", "圈", "雪", "函", "亦", "抽", "篇", "陣", "陰", "丁", "尺", "追", "堆", "雄", "迎", "泛", "爸", "樓", "避", "謀", "噸", "野", "豬", "旗", "累", "偏", "典", "館", "索", "秦", "脂", "潮", "爺", "豆", "忽", "托", "驚", "塑", "遺", "愈", "朱", "替", "纖", "粗", "傾", "尚", "痛", "楚", "謝", "奮", "購", "磨", "君", "池", "旁", "碎", "骨", "監", "捕", "弟", "暴", "割", "貫", "殊", "釋", "詞", "亡", "壁", "頓", "寶", "午", "塵", "聞", "揭", "炮", "殘", "冬", "橋", "婦", "警", "綜", "招", "吳", "付", "浮", "遭", "徐", "您", "搖", "谷", "贊", "箱", "隔", "訂", "男", "吹", "園", "紛", "唐", "敗", "宋", "玻", "巨", "耕", "坦", "榮", "閉", "灣", "鍵", "凡", "駐", "鍋", "救", "恩", "剝", "凝", "鹼", "齒", "截", "煉", "麻", "紡", "禁", "廢", "盛", "版", "緩", "淨", "睛", "昌", "婚", "涉", "筒", "嘴", "插", "岸", "朗", "莊", "街", "藏", "姑", "貿", "腐", "奴", "啦", "慣", "乘", "夥", "恢", "勻", "紗", "扎", "辯", "耳", "彪", "臣", "億", "璃", "抵", "脈", "秀", "薩", "俄", "網", "舞", "店", "噴", "縱", "寸", "汗", "掛", "洪", "賀", "閃", "柬", "爆", "烯", "津", "稻", "牆", "軟", "勇", "像", "滾", "厘", "蒙", "芳", "肯", "坡", "柱", "盪", "腿", "儀", "旅", "尾", "軋", "冰", "貢", "登", "黎", "削", "鑽", "勒", "逃", "障", "氨", "郭", "峰", "幣", "港", "伏", "軌", "畝", "畢", "擦", "莫", "刺", "浪", "秘", "援", "株", "健", "售", "股", "島", "甘", "泡", "睡", "童", "鑄", "湯", "閥", "休", "匯", "舍", "牧", "繞", "炸", "哲", "磷", "績", "朋", "淡", "尖", "啟", "陷", "柴", "呈", "徒", "顏", "淚", "稍", "忘", "泵", "藍", "拖", "洞", "授", "鏡", "辛", "壯", "鋒", "貧", "虛", "彎", "摩", "泰", "幼", "廷", "尊", "窗", "綱", "弄", "隸", "疑", "氏", "宮", "姐", "震", "瑞", "怪", "尤", "琴", "循", "描", "膜", "違", "夾", "腰", "緣", "珠", "窮", "森", "枝", "竹", "溝", "催", "繩", "憶", "邦", "剩", "幸", "漿", "欄", "擁", "牙", "貯", "禮", "濾", "鈉", "紋", "罷", "拍", "咱", "喊", "袖", "埃", "勤", "罰", "焦", "潛", "伍", "墨", "欲", "縫", "姓", "刊", "飽", "仿", "獎", "鋁", "鬼", "麗", "跨", "默", "挖", "鏈", "掃", "喝", "袋", "炭", "污", "幕", "諸", "弧", "勵", "梅", "奶", "潔", "災", "舟", "鑑", "苯", "訟", "抱", "毀", "懂", "寒", "智", "埔", "寄", "屆", "躍", "渡", "挑", "丹", "艱", "貝", "碰", "拔", "爹", "戴", "碼", "夢", "芽", "熔", "赤", "漁", "哭", "敬", "顆", "奔", "鉛", "仲", "虎", "稀", "妹", "乏", "珍", "申", "桌", "遵", "允", "隆", "螺", "倉", "魏", "銳", "曉", "氮", "兼", "隱", "礙", "赫", "撥", "忠", "肅", "缸", "牽", "搶", "博", "巧", "殼", "兄", "杜", "訊", "誠", "碧", "祥", "柯", "頁", "巡", "矩", "悲", "灌", "齡", "倫", "票", "尋", "桂", "鋪", "聖", "恐", "恰", "鄭", "趣", "抬", "荒", "騰", "貼", "柔", "滴", "猛", "闊", "輛", "妻", "填", "撤", "儲", "簽", "鬧", "擾", "紫", "砂", "遞", "戲", "吊", "陶", "伐", "餵", "療", "瓶", "婆", "撫", "臂", "摸", "忍", "蝦", "蠟", "鄰", "胸", "鞏", "擠", "偶", "棄", "槽", "勁", "乳", "鄧", "吉", "仁", "爛", "磚", "租", "烏", "艦", "伴", "瓜", "淺", "丙", "暫", "燥", "橡", "柳", "迷", "暖", "牌", "秧", "膽", "詳", "簧", "踏", "瓷", "譜", "呆", "賓", "糊", "洛", "輝", "憤", "競", "隙", "怒", "粘", "乃", "緒", "肩", "籍", "敏", "塗", "熙", "皆", "偵", "懸", "掘", "享", "糾", "醒", "狂", "鎖", "淀", "恨", "牲", "霸", "爬", "賞", "逆", "玩", "陵", "祝", "秒", "浙", "貌", "役", "彼", "悉", "鴨", "趨", "鳳", "晨", "畜", "輩", "秩", "卵", "署", "梯", "炎", "灘", "棋", "驅", "篩", "峽", "冒", "啥", "壽", "譯", "浸", "泉", "帽", "遲", "矽", "疆", "貸", "漏", "稿", "冠", "嫩", "脅", "芯", "牢", "叛", "蝕", "奧", "鳴", "嶺", "羊", "憑", "串", "塘", "繪", "酵", "融", "盆", "錫", "廟", "籌", "凍", "輔", "攝", "襲", "筋", "拒", "僚", "旱", "鉀", "鳥", "漆", "沈", "眉", "疏", "添", "棒", "穗", "硝", "韓", "逼", "扭", "僑", "涼", "挺", "碗", "栽", "炒", "杯", "患", "餾", "勸", "豪", "遼", "勃", "鴻", "旦", "吏", "拜", "狗", "埋", "輥", "掩", "飲", "搬", "罵", "辭", "勾", "扣", "估", "蔣", "絨", "霧", "丈", "朵", "姆", "擬", "宇", "輯", "陝", "雕", "償", "蓄", "崇", "剪", "倡", "廳", "咬", "駛", "薯", "刷", "斥", "番", "賦", "奉", "佛", "澆", "漫", "曼", "扇", "鈣", "桃", "扶", "仔", "返", "俗", "虧", "腔", "鞋", "棱", "覆", "框", "悄", "叔", "撞", "騙", "勘", "旺", "沸", "孤", "吐", "孟", "渠", "屈", "疾", "妙", "惜", "仰", "狠", "脹", "諧", "拋", "黴", "桑", "崗", "嘛", "衰", "盜", "滲", "臟", "賴", "湧", "甜", "曹", "閱", "肌", "哩", "厲", "烴", "緯", "毅", "昨", "偽", "症", "煮", "嘆", "釘", "搭", "莖", "籠", "酷", "偷", "弓", "錐", "恆", "傑", "坑", "鼻", "翼", "綸", "敘", "獄", "逮", "罐", "絡", "棚", "抑", "膨", "蔬", "寺", "驟", "穆", "冶", "枯", "冊", "屍", "凸", "紳", "坯", "犧", "焰", "轟", "欣", "晉", "瘦", "禦", "錠", "錦", "喪", "旬", "鍛", "壟", "搜", "撲", "邀", "亭", "酯", "邁", "舒", "脆", "酶", "閒", "憂", "酚", "頑", "羽", "漲", "卸", "仗", "陪", "闢", "懲", "杭", "姚", "肚", "捉", "飄", "漂", "昆", "欺", "吾", "郎", "烷", "汁", "呵", "飾", "蕭", "雅", "郵", "遷", "燕", "撒", "姻", "赴", "宴", "煩", "債", "帳", "斑", "鈴", "旨", "醇", "董", "餅", "雛", "姿", "拌", "傅", "腹", "妥", "揉", "賢", "拆", "歪", "葡", "胺", "丟", "浩", "徽", "昂", "墊", "擋", "覽", "貪", "慰", "繳", "汪", "慌", "馮", "諾", "姜", "誼", "兇", "劣", "誣", "耀", "昏", "躺", "盈", "騎", "喬", "溪", "叢", "盧", "抹", "悶", "諮", "刮", "駕", "纜", "悟", "摘", "鉺", "擲", "頗", "幻", "柄", "惠", "慘", "佳", "仇", "臘", "窩", "滌", "劍", "瞧", "堡", "潑", "蔥", "罩", "霍", "撈", "胎", "蒼", "濱", "倆", "捅", "湘", "砍", "霞", "邵", "萄", "瘋", "淮", "遂", "熊", "糞", "烘", "宿", "檔", "戈", "駁", "嫂", "裕", "徙", "箭", "捐", "腸", "撐", "曬", "辨", "殿", "蓮", "攤", "攪", "醬", "屏", "疫", "哀", "蔡", "堵", "沫", "皺", "暢", "疊", "閣", "萊", "敲", "轄", "鉤", "痕", "壩", "巷", "餓", "禍", "丘", "玄", "溜", "曰", "邏", "彭", "嘗", "卿", "妨", "艇", "吞", "韋", "怨", "矮", "歇" ] },{}],77:[function(require,module,exports){ module.exports=[ "abandon", "ability", "able", "about", "above", "absent", "absorb", "abstract", "absurd", "abuse", "access", "accident", "account", "accuse", "achieve", "acid", "acoustic", "acquire", "across", "act", "action", "actor", "actress", "actual", "adapt", "add", "addict", "address", "adjust", "admit", "adult", "advance", "advice", "aerobic", "affair", "afford", "afraid", "again", "age", "agent", "agree", "ahead", "aim", "air", "airport", "aisle", "alarm", "album", "alcohol", "alert", "alien", "all", "alley", "allow", "almost", "alone", "alpha", "already", "also", "alter", "always", "amateur", "amazing", "among", "amount", "amused", "analyst", "anchor", "ancient", "anger", "angle", "angry", "animal", "ankle", "announce", "annual", "another", "answer", "antenna", "antique", "anxiety", "any", "apart", "apology", "appear", "apple", "approve", "april", "arch", "arctic", "area", "arena", "argue", "arm", "armed", "armor", "army", "around", "arrange", "arrest", "arrive", "arrow", "art", "artefact", "artist", "artwork", "ask", "aspect", "assault", "asset", "assist", "assume", "asthma", "athlete", "atom", "attack", "attend", "attitude", "attract", "auction", "audit", "august", "aunt", "author", "auto", "autumn", "average", "avocado", "avoid", "awake", "aware", "away", "awesome", "awful", "awkward", "axis", "baby", "bachelor", "bacon", "badge", "bag", "balance", "balcony", "ball", "bamboo", "banana", "banner", "bar", "barely", "bargain", "barrel", "base", "basic", "basket", "battle", "beach", "bean", "beauty", "because", "become", "beef", "before", "begin", "behave", "behind", "believe", "below", "belt", "bench", "benefit", "best", "betray", "better", "between", "beyond", "bicycle", "bid", "bike", "bind", "biology", "bird", "birth", "bitter", "black", "blade", "blame", "blanket", "blast", "bleak", "bless", "blind", "blood", "blossom", "blouse", "blue", "blur", "blush", "board", "boat", "body", "boil", "bomb", "bone", "bonus", "book", "boost", "border", "boring", "borrow", "boss", "bottom", "bounce", "box", "boy", "bracket", "brain", "brand", "brass", "brave", "bread", "breeze", "brick", "bridge", "brief", "bright", "bring", "brisk", "broccoli", "broken", "bronze", "broom", "brother", "brown", "brush", "bubble", "buddy", "budget", "buffalo", "build", "bulb", "bulk", "bullet", "bundle", "bunker", "burden", "burger", "burst", "bus", "business", "busy", "butter", "buyer", "buzz", "cabbage", "cabin", "cable", "cactus", "cage", "cake", "call", "calm", "camera", "camp", "can", "canal", "cancel", "candy", "cannon", "canoe", "canvas", "canyon", "capable", "capital", "captain", "car", "carbon", "card", "cargo", "carpet", "carry", "cart", "case", "cash", "casino", "castle", "casual", "cat", "catalog", "catch", "category", "cattle", "caught", "cause", "caution", "cave", "ceiling", "celery", "cement", "census", "century", "cereal", "certain", "chair", "chalk", "champion", "change", "chaos", "chapter", "charge", "chase", "chat", "cheap", "check", "cheese", "chef", "cherry", "chest", "chicken", "chief", "child", "chimney", "choice", "choose", "chronic", "chuckle", "chunk", "churn", "cigar", "cinnamon", "circle", "citizen", "city", "civil", "claim", "clap", "clarify", "claw", "clay", "clean", "clerk", "clever", "click", "client", "cliff", "climb", "clinic", "clip", "clock", "clog", "close", "cloth", "cloud", "clown", "club", "clump", "cluster", "clutch", "coach", "coast", "coconut", "code", "coffee", "coil", "coin", "collect", "color", "column", "combine", "come", "comfort", "comic", "common", "company", "concert", "conduct", "confirm", "congress", "connect", "consider", "control", "convince", "cook", "cool", "copper", "copy", "coral", "core", "corn", "correct", "cost", "cotton", "couch", "country", "couple", "course", "cousin", "cover", "coyote", "crack", "cradle", "craft", "cram", "crane", "crash", "crater", "crawl", "crazy", "cream", "credit", "creek", "crew", "cricket", "crime", "crisp", "critic", "crop", "cross", "crouch", "crowd", "crucial", "cruel", "cruise", "crumble", "crunch", "crush", "cry", "crystal", "cube", "culture", "cup", "cupboard", "curious", "current", "curtain", "curve", "cushion", "custom", "cute", "cycle", "dad", "damage", "damp", "dance", "danger", "daring", "dash", "daughter", "dawn", "day", "deal", "debate", "debris", "decade", "december", "decide", "decline", "decorate", "decrease", "deer", "defense", "define", "defy", "degree", "delay", "deliver", "demand", "demise", "denial", "dentist", "deny", "depart", "depend", "deposit", "depth", "deputy", "derive", "describe", "desert", "design", "desk", "despair", "destroy", "detail", "detect", "develop", "device", "devote", "diagram", "dial", "diamond", "diary", "dice", "diesel", "diet", "differ", "digital", "dignity", "dilemma", "dinner", "dinosaur", "direct", "dirt", "disagree", "discover", "disease", "dish", "dismiss", "disorder", "display", "distance", "divert", "divide", "divorce", "dizzy", "doctor", "document", "dog", "doll", "dolphin", "domain", "donate", "donkey", "donor", "door", "dose", "double", "dove", "draft", "dragon", "drama", "drastic", "draw", "dream", "dress", "drift", "drill", "drink", "drip", "drive", "drop", "drum", "dry", "duck", "dumb", "dune", "during", "dust", "dutch", "duty", "dwarf", "dynamic", "eager", "eagle", "early", "earn", "earth", "easily", "east", "easy", "echo", "ecology", "economy", "edge", "edit", "educate", "effort", "egg", "eight", "either", "elbow", "elder", "electric", "elegant", "element", "elephant", "elevator", "elite", "else", "embark", "embody", "embrace", "emerge", "emotion", "employ", "empower", "empty", "enable", "enact", "end", "endless", "endorse", "enemy", "energy", "enforce", "engage", "engine", "enhance", "enjoy", "enlist", "enough", "enrich", "enroll", "ensure", "enter", "entire", "entry", "envelope", "episode", "equal", "equip", "era", "erase", "erode", "erosion", "error", "erupt", "escape", "essay", "essence", "estate", "eternal", "ethics", "evidence", "evil", "evoke", "evolve", "exact", "example", "excess", "exchange", "excite", "exclude", "excuse", "execute", "exercise", "exhaust", "exhibit", "exile", "exist", "exit", "exotic", "expand", "expect", "expire", "explain", "expose", "express", "extend", "extra", "eye", "eyebrow", "fabric", "face", "faculty", "fade", "faint", "faith", "fall", "false", "fame", "family", "famous", "fan", "fancy", "fantasy", "farm", "fashion", "fat", "fatal", "father", "fatigue", "fault", "favorite", "feature", "february", "federal", "fee", "feed", "feel", "female", "fence", "festival", "fetch", "fever", "few", "fiber", "fiction", "field", "figure", "file", "film", "filter", "final", "find", "fine", "finger", "finish", "fire", "firm", "first", "fiscal", "fish", "fit", "fitness", "fix", "flag", "flame", "flash", "flat", "flavor", "flee", "flight", "flip", "float", "flock", "floor", "flower", "fluid", "flush", "fly", "foam", "focus", "fog", "foil", "fold", "follow", "food", "foot", "force", "forest", "forget", "fork", "fortune", "forum", "forward", "fossil", "foster", "found", "fox", "fragile", "frame", "frequent", "fresh", "friend", "fringe", "frog", "front", "frost", "frown", "frozen", "fruit", "fuel", "fun", "funny", "furnace", "fury", "future", "gadget", "gain", "galaxy", "gallery", "game", "gap", "garage", "garbage", "garden", "garlic", "garment", "gas", "gasp", "gate", "gather", "gauge", "gaze", "general", "genius", "genre", "gentle", "genuine", "gesture", "ghost", "giant", "gift", "giggle", "ginger", "giraffe", "girl", "give", "glad", "glance", "glare", "glass", "glide", "glimpse", "globe", "gloom", "glory", "glove", "glow", "glue", "goat", "goddess", "gold", "good", "goose", "gorilla", "gospel", "gossip", "govern", "gown", "grab", "grace", "grain", "grant", "grape", "grass", "gravity", "great", "green", "grid", "grief", "grit", "grocery", "group", "grow", "grunt", "guard", "guess", "guide", "guilt", "guitar", "gun", "gym", "habit", "hair", "half", "hammer", "hamster", "hand", "happy", "harbor", "hard", "harsh", "harvest", "hat", "have", "hawk", "hazard", "head", "health", "heart", "heavy", "hedgehog", "height", "hello", "helmet", "help", "hen", "hero", "hidden", "high", "hill", "hint", "hip", "hire", "history", "hobby", "hockey", "hold", "hole", "holiday", "hollow", "home", "honey", "hood", "hope", "horn", "horror", "horse", "hospital", "host", "hotel", "hour", "hover", "hub", "huge", "human", "humble", "humor", "hundred", "hungry", "hunt", "hurdle", "hurry", "hurt", "husband", "hybrid", "ice", "icon", "idea", "identify", "idle", "ignore", "ill", "illegal", "illness", "image", "imitate", "immense", "immune", "impact", "impose", "improve", "impulse", "inch", "include", "income", "increase", "index", "indicate", "indoor", "industry", "infant", "inflict", "inform", "inhale", "inherit", "initial", "inject", "injury", "inmate", "inner", "innocent", "input", "inquiry", "insane", "insect", "inside", "inspire", "install", "intact", "interest", "into", "invest", "invite", "involve", "iron", "island", "isolate", "issue", "item", "ivory", "jacket", "jaguar", "jar", "jazz", "jealous", "jeans", "jelly", "jewel", "job", "join", "joke", "journey", "joy", "judge", "juice", "jump", "jungle", "junior", "junk", "just", "kangaroo", "keen", "keep", "ketchup", "key", "kick", "kid", "kidney", "kind", "kingdom", "kiss", "kit", "kitchen", "kite", "kitten", "kiwi", "knee", "knife", "knock", "know", "lab", "label", "labor", "ladder", "lady", "lake", "lamp", "language", "laptop", "large", "later", "latin", "laugh", "laundry", "lava", "law", "lawn", "lawsuit", "layer", "lazy", "leader", "leaf", "learn", "leave", "lecture", "left", "leg", "legal", "legend", "leisure", "lemon", "lend", "length", "lens", "leopard", "lesson", "letter", "level", "liar", "liberty", "library", "license", "life", "lift", "light", "like", "limb", "limit", "link", "lion", "liquid", "list", "little", "live", "lizard", "load", "loan", "lobster", "local", "lock", "logic", "lonely", "long", "loop", "lottery", "loud", "lounge", "love", "loyal", "lucky", "luggage", "lumber", "lunar", "lunch", "luxury", "lyrics", "machine", "mad", "magic", "magnet", "maid", "mail", "main", "major", "make", "mammal", "man", "manage", "mandate", "mango", "mansion", "manual", "maple", "marble", "march", "margin", "marine", "market", "marriage", "mask", "mass", "master", "match", "material", "math", "matrix", "matter", "maximum", "maze", "meadow", "mean", "measure", "meat", "mechanic", "medal", "media", "melody", "melt", "member", "memory", "mention", "menu", "mercy", "merge", "merit", "merry", "mesh", "message", "metal", "method", "middle", "midnight", "milk", "million", "mimic", "mind", "minimum", "minor", "minute", "miracle", "mirror", "misery", "miss", "mistake", "mix", "mixed", "mixture", "mobile", "model", "modify", "mom", "moment", "monitor", "monkey", "monster", "month", "moon", "moral", "more", "morning", "mosquito", "mother", "motion", "motor", "mountain", "mouse", "move", "movie", "much", "muffin", "mule", "multiply", "muscle", "museum", "mushroom", "music", "must", "mutual", "myself", "mystery", "myth", "naive", "name", "napkin", "narrow", "nasty", "nation", "nature", "near", "neck", "need", "negative", "neglect", "neither", "nephew", "nerve", "nest", "net", "network", "neutral", "never", "news", "next", "nice", "night", "noble", "noise", "nominee", "noodle", "normal", "north", "nose", "notable", "note", "nothing", "notice", "novel", "now", "nuclear", "number", "nurse", "nut", "oak", "obey", "object", "oblige", "obscure", "observe", "obtain", "obvious", "occur", "ocean", "october", "odor", "off", "offer", "office", "often", "oil", "okay", "old", "olive", "olympic", "omit", "once", "one", "onion", "online", "only", "open", "opera", "opinion", "oppose", "option", "orange", "orbit", "orchard", "order", "ordinary", "organ", "orient", "original", "orphan", "ostrich", "other", "outdoor", "outer", "output", "outside", "oval", "oven", "over", "own", "owner", "oxygen", "oyster", "ozone", "pact", "paddle", "page", "pair", "palace", "palm", "panda", "panel", "panic", "panther", "paper", "parade", "parent", "park", "parrot", "party", "pass", "patch", "path", "patient", "patrol", "pattern", "pause", "pave", "payment", "peace", "peanut", "pear", "peasant", "pelican", "pen", "penalty", "pencil", "people", "pepper", "perfect", "permit", "person", "pet", "phone", "photo", "phrase", "physical", "piano", "picnic", "picture", "piece", "pig", "pigeon", "pill", "pilot", "pink", "pioneer", "pipe", "pistol", "pitch", "pizza", "place", "planet", "plastic", "plate", "play", "please", "pledge", "pluck", "plug", "plunge", "poem", "poet", "point", "polar", "pole", "police", "pond", "pony", "pool", "popular", "portion", "position", "possible", "post", "potato", "pottery", "poverty", "powder", "power", "practice", "praise", "predict", "prefer", "prepare", "present", "pretty", "prevent", "price", "pride", "primary", "print", "priority", "prison", "private", "prize", "problem", "process", "produce", "profit", "program", "project", "promote", "proof", "property", "prosper", "protect", "proud", "provide", "public", "pudding", "pull", "pulp", "pulse", "pumpkin", "punch", "pupil", "puppy", "purchase", "purity", "purpose", "purse", "push", "put", "puzzle", "pyramid", "quality", "quantum", "quarter", "question", "quick", "quit", "quiz", "quote", "rabbit", "raccoon", "race", "rack", "radar", "radio", "rail", "rain", "raise", "rally", "ramp", "ranch", "random", "range", "rapid", "rare", "rate", "rather", "raven", "raw", "razor", "ready", "real", "reason", "rebel", "rebuild", "recall", "receive", "recipe", "record", "recycle", "reduce", "reflect", "reform", "refuse", "region", "regret", "regular", "reject", "relax", "release", "relief", "rely", "remain", "remember", "remind", "remove", "render", "renew", "rent", "reopen", "repair", "repeat", "replace", "report", "require", "rescue", "resemble", "resist", "resource", "response", "result", "retire", "retreat", "return", "reunion", "reveal", "review", "reward", "rhythm", "rib", "ribbon", "rice", "rich", "ride", "ridge", "rifle", "right", "rigid", "ring", "riot", "ripple", "risk", "ritual", "rival", "river", "road", "roast", "robot", "robust", "rocket", "romance", "roof", "rookie", "room", "rose", "rotate", "rough", "round", "route", "royal", "rubber", "rude", "rug", "rule", "run", "runway", "rural", "sad", "saddle", "sadness", "safe", "sail", "salad", "salmon", "salon", "salt", "salute", "same", "sample", "sand", "satisfy", "satoshi", "sauce", "sausage", "save", "say", "scale", "scan", "scare", "scatter", "scene", "scheme", "school", "science", "scissors", "scorpion", "scout", "scrap", "screen", "script", "scrub", "sea", "search", "season", "seat", "second", "secret", "section", "security", "seed", "seek", "segment", "select", "sell", "seminar", "senior", "sense", "sentence", "series", "service", "session", "settle", "setup", "seven", "shadow", "shaft", "shallow", "share", "shed", "shell", "sheriff", "shield", "shift", "shine", "ship", "shiver", "shock", "shoe", "shoot", "shop", "short", "shoulder", "shove", "shrimp", "shrug", "shuffle", "shy", "sibling", "sick", "side", "siege", "sight", "sign", "silent", "silk", "silly", "silver", "similar", "simple", "since", "sing", "siren", "sister", "situate", "six", "size", "skate", "sketch", "ski", "skill", "skin", "skirt", "skull", "slab", "slam", "sleep", "slender", "slice", "slide", "slight", "slim", "slogan", "slot", "slow", "slush", "small", "smart", "smile", "smoke", "smooth", "snack", "snake", "snap", "sniff", "snow", "soap", "soccer", "social", "sock", "soda", "soft", "solar", "soldier", "solid", "solution", "solve", "someone", "song", "soon", "sorry", "sort", "soul", "sound", "soup", "source", "south", "space", "spare", "spatial", "spawn", "speak", "special", "speed", "spell", "spend", "sphere", "spice", "spider", "spike", "spin", "spirit", "split", "spoil", "sponsor", "spoon", "sport", "spot", "spray", "spread", "spring", "spy", "square", "squeeze", "squirrel", "stable", "stadium", "staff", "stage", "stairs", "stamp", "stand", "start", "state", "stay", "steak", "steel", "stem", "step", "stereo", "stick", "still", "sting", "stock", "stomach", "stone", "stool", "story", "stove", "strategy", "street", "strike", "strong", "struggle", "student", "stuff", "stumble", "style", "subject", "submit", "subway", "success", "such", "sudden", "suffer", "sugar", "suggest", "suit", "summer", "sun", "sunny", "sunset", "super", "supply", "supreme", "sure", "surface", "surge", "surprise", "surround", "survey", "suspect", "sustain", "swallow", "swamp", "swap", "swarm", "swear", "sweet", "swift", "swim", "swing", "switch", "sword", "symbol", "symptom", "syrup", "system", "table", "tackle", "tag", "tail", "talent", "talk", "tank", "tape", "target", "task", "taste", "tattoo", "taxi", "teach", "team", "tell", "ten", "tenant", "tennis", "tent", "term", "test", "text", "thank", "that", "theme", "then", "theory", "there", "they", "thing", "this", "thought", "three", "thrive", "throw", "thumb", "thunder", "ticket", "tide", "tiger", "tilt", "timber", "time", "tiny", "tip", "tired", "tissue", "title", "toast", "tobacco", "today", "toddler", "toe", "together", "toilet", "token", "tomato", "tomorrow", "tone", "tongue", "tonight", "tool", "tooth", "top", "topic", "topple", "torch", "tornado", "tortoise", "toss", "total", "tourist", "toward", "tower", "town", "toy", "track", "trade", "traffic", "tragic", "train", "transfer", "trap", "trash", "travel", "tray", "treat", "tree", "trend", "trial", "tribe", "trick", "trigger", "trim", "trip", "trophy", "trouble", "truck", "true", "truly", "trumpet", "trust", "truth", "try", "tube", "tuition", "tumble", "tuna", "tunnel", "turkey", "turn", "turtle", "twelve", "twenty", "twice", "twin", "twist", "two", "type", "typical", "ugly", "umbrella", "unable", "unaware", "uncle", "uncover", "under", "undo", "unfair", "unfold", "unhappy", "uniform", "unique", "unit", "universe", "unknown", "unlock", "until", "unusual", "unveil", "update", "upgrade", "uphold", "upon", "upper", "upset", "urban", "urge", "usage", "use", "used", "useful", "useless", "usual", "utility", "vacant", "vacuum", "vague", "valid", "valley", "valve", "van", "vanish", "vapor", "various", "vast", "vault", "vehicle", "velvet", "vendor", "venture", "venue", "verb", "verify", "version", "very", "vessel", "veteran", "viable", "vibrant", "vicious", "victory", "video", "view", "village", "vintage", "violin", "virtual", "virus", "visa", "visit", "visual", "vital", "vivid", "vocal", "voice", "void", "volcano", "volume", "vote", "voyage", "wage", "wagon", "wait", "walk", "wall", "walnut", "want", "warfare", "warm", "warrior", "wash", "wasp", "waste", "water", "wave", "way", "wealth", "weapon", "wear", "weasel", "weather", "web", "wedding", "weekend", "weird", "welcome", "west", "wet", "whale", "what", "wheat", "wheel", "when", "where", "whip", "whisper", "wide", "width", "wife", "wild", "will", "win", "window", "wine", "wing", "wink", "winner", "winter", "wire", "wisdom", "wise", "wish", "witness", "wolf", "woman", "wonder", "wood", "wool", "word", "work", "world", "worry", "worth", "wrap", "wreck", "wrestle", "wrist", "write", "wrong", "yard", "year", "yellow", "you", "young", "youth", "zebra", "zero", "zone", "zoo" ] },{}],78:[function(require,module,exports){ module.exports=[ "abaisser", "abandon", "abdiquer", "abeille", "abolir", "aborder", "aboutir", "aboyer", "abrasif", "abreuver", "abriter", "abroger", "abrupt", "absence", "absolu", "absurde", "abusif", "abyssal", "académie", "acajou", "acarien", "accabler", "accepter", "acclamer", "accolade", "accroche", "accuser", "acerbe", "achat", "acheter", "aciduler", "acier", "acompte", "acquérir", "acronyme", "acteur", "actif", "actuel", "adepte", "adéquat", "adhésif", "adjectif", "adjuger", "admettre", "admirer", "adopter", "adorer", "adoucir", "adresse", "adroit", "adulte", "adverbe", "aérer", "aéronef", "affaire", "affecter", "affiche", "affreux", "affubler", "agacer", "agencer", "agile", "agiter", "agrafer", "agréable", "agrume", "aider", "aiguille", "ailier", "aimable", "aisance", "ajouter", "ajuster", "alarmer", "alchimie", "alerte", "algèbre", "algue", "aliéner", "aliment", "alléger", "alliage", "allouer", "allumer", "alourdir", "alpaga", "altesse", "alvéole", "amateur", "ambigu", "ambre", "aménager", "amertume", "amidon", "amiral", "amorcer", "amour", "amovible", "amphibie", "ampleur", "amusant", "analyse", "anaphore", "anarchie", "anatomie", "ancien", "anéantir", "angle", "angoisse", "anguleux", "animal", "annexer", "annonce", "annuel", "anodin", "anomalie", "anonyme", "anormal", "antenne", "antidote", "anxieux", "apaiser", "apéritif", "aplanir", "apologie", "appareil", "appeler", "apporter", "appuyer", "aquarium", "aqueduc", "arbitre", "arbuste", "ardeur", "ardoise", "argent", "arlequin", "armature", "armement", "armoire", "armure", "arpenter", "arracher", "arriver", "arroser", "arsenic", "artériel", "article", "aspect", "asphalte", "aspirer", "assaut", "asservir", "assiette", "associer", "assurer", "asticot", "astre", "astuce", "atelier", "atome", "atrium", "atroce", "attaque", "attentif", "attirer", "attraper", "aubaine", "auberge", "audace", "audible", "augurer", "aurore", "automne", "autruche", "avaler", "avancer", "avarice", "avenir", "averse", "aveugle", "aviateur", "avide", "avion", "aviser", "avoine", "avouer", "avril", "axial", "axiome", "badge", "bafouer", "bagage", "baguette", "baignade", "balancer", "balcon", "baleine", "balisage", "bambin", "bancaire", "bandage", "banlieue", "bannière", "banquier", "barbier", "baril", "baron", "barque", "barrage", "bassin", "bastion", "bataille", "bateau", "batterie", "baudrier", "bavarder", "belette", "bélier", "belote", "bénéfice", "berceau", "berger", "berline", "bermuda", "besace", "besogne", "bétail", "beurre", "biberon", "bicycle", "bidule", "bijou", "bilan", "bilingue", "billard", "binaire", "biologie", "biopsie", "biotype", "biscuit", "bison", "bistouri", "bitume", "bizarre", "blafard", "blague", "blanchir", "blessant", "blinder", "blond", "bloquer", "blouson", "bobard", "bobine", "boire", "boiser", "bolide", "bonbon", "bondir", "bonheur", "bonifier", "bonus", "bordure", "borne", "botte", "boucle", "boueux", "bougie", "boulon", "bouquin", "bourse", "boussole", "boutique", "boxeur", "branche", "brasier", "brave", "brebis", "brèche", "breuvage", "bricoler", "brigade", "brillant", "brioche", "brique", "brochure", "broder", "bronzer", "brousse", "broyeur", "brume", "brusque", "brutal", "bruyant", "buffle", "buisson", "bulletin", "bureau", "burin", "bustier", "butiner", "butoir", "buvable", "buvette", "cabanon", "cabine", "cachette", "cadeau", "cadre", "caféine", "caillou", "caisson", "calculer", "calepin", "calibre", "calmer", "calomnie", "calvaire", "camarade", "caméra", "camion", "campagne", "canal", "caneton", "canon", "cantine", "canular", "capable", "caporal", "caprice", "capsule", "capter", "capuche", "carabine", "carbone", "caresser", "caribou", "carnage", "carotte", "carreau", "carton", "cascade", "casier", "casque", "cassure", "causer", "caution", "cavalier", "caverne", "caviar", "cédille", "ceinture", "céleste", "cellule", "cendrier", "censurer", "central", "cercle", "cérébral", "cerise", "cerner", "cerveau", "cesser", "chagrin", "chaise", "chaleur", "chambre", "chance", "chapitre", "charbon", "chasseur", "chaton", "chausson", "chavirer", "chemise", "chenille", "chéquier", "chercher", "cheval", "chien", "chiffre", "chignon", "chimère", "chiot", "chlorure", "chocolat", "choisir", "chose", "chouette", "chrome", "chute", "cigare", "cigogne", "cimenter", "cinéma", "cintrer", "circuler", "cirer", "cirque", "citerne", "citoyen", "citron", "civil", "clairon", "clameur", "claquer", "classe", "clavier", "client", "cligner", "climat", "clivage", "cloche", "clonage", "cloporte", "cobalt", "cobra", "cocasse", "cocotier", "coder", "codifier", "coffre", "cogner", "cohésion", "coiffer", "coincer", "colère", "colibri", "colline", "colmater", "colonel", "combat", "comédie", "commande", "compact", "concert", "conduire", "confier", "congeler", "connoter", "consonne", "contact", "convexe", "copain", "copie", "corail", "corbeau", "cordage", "corniche", "corpus", "correct", "cortège", "cosmique", "costume", "coton", "coude", "coupure", "courage", "couteau", "couvrir", "coyote", "crabe", "crainte", "cravate", "crayon", "créature", "créditer", "crémeux", "creuser", "crevette", "cribler", "crier", "cristal", "critère", "croire", "croquer", "crotale", "crucial", "cruel", "crypter", "cubique", "cueillir", "cuillère", "cuisine", "cuivre", "culminer", "cultiver", "cumuler", "cupide", "curatif", "curseur", "cyanure", "cycle", "cylindre", "cynique", "daigner", "damier", "danger", "danseur", "dauphin", "débattre", "débiter", "déborder", "débrider", "débutant", "décaler", "décembre", "déchirer", "décider", "déclarer", "décorer", "décrire", "décupler", "dédale", "déductif", "déesse", "défensif", "défiler", "défrayer", "dégager", "dégivrer", "déglutir", "dégrafer", "déjeuner", "délice", "déloger", "demander", "demeurer", "démolir", "dénicher", "dénouer", "dentelle", "dénuder", "départ", "dépenser", "déphaser", "déplacer", "déposer", "déranger", "dérober", "désastre", "descente", "désert", "désigner", "désobéir", "dessiner", "destrier", "détacher", "détester", "détourer", "détresse", "devancer", "devenir", "deviner", "devoir", "diable", "dialogue", "diamant", "dicter", "différer", "digérer", "digital", "digne", "diluer", "dimanche", "diminuer", "dioxyde", "directif", "diriger", "discuter", "disposer", "dissiper", "distance", "divertir", "diviser", "docile", "docteur", "dogme", "doigt", "domaine", "domicile", "dompter", "donateur", "donjon", "donner", "dopamine", "dortoir", "dorure", "dosage", "doseur", "dossier", "dotation", "douanier", "double", "douceur", "douter", "doyen", "dragon", "draper", "dresser", "dribbler", "droiture", "duperie", "duplexe", "durable", "durcir", "dynastie", "éblouir", "écarter", "écharpe", "échelle", "éclairer", "éclipse", "éclore", "écluse", "école", "économie", "écorce", "écouter", "écraser", "écrémer", "écrivain", "écrou", "écume", "écureuil", "édifier", "éduquer", "effacer", "effectif", "effigie", "effort", "effrayer", "effusion", "égaliser", "égarer", "éjecter", "élaborer", "élargir", "électron", "élégant", "éléphant", "élève", "éligible", "élitisme", "éloge", "élucider", "éluder", "emballer", "embellir", "embryon", "émeraude", "émission", "emmener", "émotion", "émouvoir", "empereur", "employer", "emporter", "emprise", "émulsion", "encadrer", "enchère", "enclave", "encoche", "endiguer", "endosser", "endroit", "enduire", "énergie", "enfance", "enfermer", "enfouir", "engager", "engin", "englober", "énigme", "enjamber", "enjeu", "enlever", "ennemi", "ennuyeux", "enrichir", "enrobage", "enseigne", "entasser", "entendre", "entier", "entourer", "entraver", "énumérer", "envahir", "enviable", "envoyer", "enzyme", "éolien", "épaissir", "épargne", "épatant", "épaule", "épicerie", "épidémie", "épier", "épilogue", "épine", "épisode", "épitaphe", "époque", "épreuve", "éprouver", "épuisant", "équerre", "équipe", "ériger", "érosion", "erreur", "éruption", "escalier", "espadon", "espèce", "espiègle", "espoir", "esprit", "esquiver", "essayer", "essence", "essieu", "essorer", "estime", "estomac", "estrade", "étagère", "étaler", "étanche", "étatique", "éteindre", "étendoir", "éternel", "éthanol", "éthique", "ethnie", "étirer", "étoffer", "étoile", "étonnant", "étourdir", "étrange", "étroit", "étude", "euphorie", "évaluer", "évasion", "éventail", "évidence", "éviter", "évolutif", "évoquer", "exact", "exagérer", "exaucer", "exceller", "excitant", "exclusif", "excuse", "exécuter", "exemple", "exercer", "exhaler", "exhorter", "exigence", "exiler", "exister", "exotique", "expédier", "explorer", "exposer", "exprimer", "exquis", "extensif", "extraire", "exulter", "fable", "fabuleux", "facette", "facile", "facture", "faiblir", "falaise", "fameux", "famille", "farceur", "farfelu", "farine", "farouche", "fasciner", "fatal", "fatigue", "faucon", "fautif", "faveur", "favori", "fébrile", "féconder", "fédérer", "félin", "femme", "fémur", "fendoir", "féodal", "fermer", "féroce", "ferveur", "festival", "feuille", "feutre", "février", "fiasco", "ficeler", "fictif", "fidèle", "figure", "filature", "filetage", "filière", "filleul", "filmer", "filou", "filtrer", "financer", "finir", "fiole", "firme", "fissure", "fixer", "flairer", "flamme", "flasque", "flatteur", "fléau", "flèche", "fleur", "flexion", "flocon", "flore", "fluctuer", "fluide", "fluvial", "folie", "fonderie", "fongible", "fontaine", "forcer", "forgeron", "formuler", "fortune", "fossile", "foudre", "fougère", "fouiller", "foulure", "fourmi", "fragile", "fraise", "franchir", "frapper", "frayeur", "frégate", "freiner", "frelon", "frémir", "frénésie", "frère", "friable", "friction", "frisson", "frivole", "froid", "fromage", "frontal", "frotter", "fruit", "fugitif", "fuite", "fureur", "furieux", "furtif", "fusion", "futur", "gagner", "galaxie", "galerie", "gambader", "garantir", "gardien", "garnir", "garrigue", "gazelle", "gazon", "géant", "gélatine", "gélule", "gendarme", "général", "génie", "genou", "gentil", "géologie", "géomètre", "géranium", "germe", "gestuel", "geyser", "gibier", "gicler", "girafe", "givre", "glace", "glaive", "glisser", "globe", "gloire", "glorieux", "golfeur", "gomme", "gonfler", "gorge", "gorille", "goudron", "gouffre", "goulot", "goupille", "gourmand", "goutte", "graduel", "graffiti", "graine", "grand", "grappin", "gratuit", "gravir", "grenat", "griffure", "griller", "grimper", "grogner", "gronder", "grotte", "groupe", "gruger", "grutier", "gruyère", "guépard", "guerrier", "guide", "guimauve", "guitare", "gustatif", "gymnaste", "gyrostat", "habitude", "hachoir", "halte", "hameau", "hangar", "hanneton", "haricot", "harmonie", "harpon", "hasard", "hélium", "hématome", "herbe", "hérisson", "hermine", "héron", "hésiter", "heureux", "hiberner", "hibou", "hilarant", "histoire", "hiver", "homard", "hommage", "homogène", "honneur", "honorer", "honteux", "horde", "horizon", "horloge", "hormone", "horrible", "houleux", "housse", "hublot", "huileux", "humain", "humble", "humide", "humour", "hurler", "hydromel", "hygiène", "hymne", "hypnose", "idylle", "ignorer", "iguane", "illicite", "illusion", "image", "imbiber", "imiter", "immense", "immobile", "immuable", "impact", "impérial", "implorer", "imposer", "imprimer", "imputer", "incarner", "incendie", "incident", "incliner", "incolore", "indexer", "indice", "inductif", "inédit", "ineptie", "inexact", "infini", "infliger", "informer", "infusion", "ingérer", "inhaler", "inhiber", "injecter", "injure", "innocent", "inoculer", "inonder", "inscrire", "insecte", "insigne", "insolite", "inspirer", "instinct", "insulter", "intact", "intense", "intime", "intrigue", "intuitif", "inutile", "invasion", "inventer", "inviter", "invoquer", "ironique", "irradier", "irréel", "irriter", "isoler", "ivoire", "ivresse", "jaguar", "jaillir", "jambe", "janvier", "jardin", "jauger", "jaune", "javelot", "jetable", "jeton", "jeudi", "jeunesse", "joindre", "joncher", "jongler", "joueur", "jouissif", "journal", "jovial", "joyau", "joyeux", "jubiler", "jugement", "junior", "jupon", "juriste", "justice", "juteux", "juvénile", "kayak", "kimono", "kiosque", "label", "labial", "labourer", "lacérer", "lactose", "lagune", "laine", "laisser", "laitier", "lambeau", "lamelle", "lampe", "lanceur", "langage", "lanterne", "lapin", "largeur", "larme", "laurier", "lavabo", "lavoir", "lecture", "légal", "léger", "légume", "lessive", "lettre", "levier", "lexique", "lézard", "liasse", "libérer", "libre", "licence", "licorne", "liège", "lièvre", "ligature", "ligoter", "ligue", "limer", "limite", "limonade", "limpide", "linéaire", "lingot", "lionceau", "liquide", "lisière", "lister", "lithium", "litige", "littoral", "livreur", "logique", "lointain", "loisir", "lombric", "loterie", "louer", "lourd", "loutre", "louve", "loyal", "lubie", "lucide", "lucratif", "lueur", "lugubre", "luisant", "lumière", "lunaire", "lundi", "luron", "lutter", "luxueux", "machine", "magasin", "magenta", "magique", "maigre", "maillon", "maintien", "mairie", "maison", "majorer", "malaxer", "maléfice", "malheur", "malice", "mallette", "mammouth", "mandater", "maniable", "manquant", "manteau", "manuel", "marathon", "marbre", "marchand", "mardi", "maritime", "marqueur", "marron", "marteler", "mascotte", "massif", "matériel", "matière", "matraque", "maudire", "maussade", "mauve", "maximal", "méchant", "méconnu", "médaille", "médecin", "méditer", "méduse", "meilleur", "mélange", "mélodie", "membre", "mémoire", "menacer", "mener", "menhir", "mensonge", "mentor", "mercredi", "mérite", "merle", "messager", "mesure", "métal", "météore", "méthode", "métier", "meuble", "miauler", "microbe", "miette", "mignon", "migrer", "milieu", "million", "mimique", "mince", "minéral", "minimal", "minorer", "minute", "miracle", "miroiter", "missile", "mixte", "mobile", "moderne", "moelleux", "mondial", "moniteur", "monnaie", "monotone", "monstre", "montagne", "monument", "moqueur", "morceau", "morsure", "mortier", "moteur", "motif", "mouche", "moufle", "moulin", "mousson", "mouton", "mouvant", "multiple", "munition", "muraille", "murène", "murmure", "muscle", "muséum", "musicien", "mutation", "muter", "mutuel", "myriade", "myrtille", "mystère", "mythique", "nageur", "nappe", "narquois", "narrer", "natation", "nation", "nature", "naufrage", "nautique", "navire", "nébuleux", "nectar", "néfaste", "négation", "négliger", "négocier", "neige", "nerveux", "nettoyer", "neurone", "neutron", "neveu", "niche", "nickel", "nitrate", "niveau", "noble", "nocif", "nocturne", "noirceur", "noisette", "nomade", "nombreux", "nommer", "normatif", "notable", "notifier", "notoire", "nourrir", "nouveau", "novateur", "novembre", "novice", "nuage", "nuancer", "nuire", "nuisible", "numéro", "nuptial", "nuque", "nutritif", "obéir", "objectif", "obliger", "obscur", "observer", "obstacle", "obtenir", "obturer", "occasion", "occuper", "océan", "octobre", "octroyer", "octupler", "oculaire", "odeur", "odorant", "offenser", "officier", "offrir", "ogive", "oiseau", "oisillon", "olfactif", "olivier", "ombrage", "omettre", "onctueux", "onduler", "onéreux", "onirique", "opale", "opaque", "opérer", "opinion", "opportun", "opprimer", "opter", "optique", "orageux", "orange", "orbite", "ordonner", "oreille", "organe", "orgueil", "orifice", "ornement", "orque", "ortie", "osciller", "osmose", "ossature", "otarie", "ouragan", "ourson", "outil", "outrager", "ouvrage", "ovation", "oxyde", "oxygène", "ozone", "paisible", "palace", "palmarès", "palourde", "palper", "panache", "panda", "pangolin", "paniquer", "panneau", "panorama", "pantalon", "papaye", "papier", "papoter", "papyrus", "paradoxe", "parcelle", "paresse", "parfumer", "parler", "parole", "parrain", "parsemer", "partager", "parure", "parvenir", "passion", "pastèque", "paternel", "patience", "patron", "pavillon", "pavoiser", "payer", "paysage", "peigne", "peintre", "pelage", "pélican", "pelle", "pelouse", "peluche", "pendule", "pénétrer", "pénible", "pensif", "pénurie", "pépite", "péplum", "perdrix", "perforer", "période", "permuter", "perplexe", "persil", "perte", "peser", "pétale", "petit", "pétrir", "peuple", "pharaon", "phobie", "phoque", "photon", "phrase", "physique", "piano", "pictural", "pièce", "pierre", "pieuvre", "pilote", "pinceau", "pipette", "piquer", "pirogue", "piscine", "piston", "pivoter", "pixel", "pizza", "placard", "plafond", "plaisir", "planer", "plaque", "plastron", "plateau", "pleurer", "plexus", "pliage", "plomb", "plonger", "pluie", "plumage", "pochette", "poésie", "poète", "pointe", "poirier", "poisson", "poivre", "polaire", "policier", "pollen", "polygone", "pommade", "pompier", "ponctuel", "pondérer", "poney", "portique", "position", "posséder", "posture", "potager", "poteau", "potion", "pouce", "poulain", "poumon", "pourpre", "poussin", "pouvoir", "prairie", "pratique", "précieux", "prédire", "préfixe", "prélude", "prénom", "présence", "prétexte", "prévoir", "primitif", "prince", "prison", "priver", "problème", "procéder", "prodige", "profond", "progrès", "proie", "projeter", "prologue", "promener", "propre", "prospère", "protéger", "prouesse", "proverbe", "prudence", "pruneau", "psychose", "public", "puceron", "puiser", "pulpe", "pulsar", "punaise", "punitif", "pupitre", "purifier", "puzzle", "pyramide", "quasar", "querelle", "question", "quiétude", "quitter", "quotient", "racine", "raconter", "radieux", "ragondin", "raideur", "raisin", "ralentir", "rallonge", "ramasser", "rapide", "rasage", "ratisser", "ravager", "ravin", "rayonner", "réactif", "réagir", "réaliser", "réanimer", "recevoir", "réciter", "réclamer", "récolter", "recruter", "reculer", "recycler", "rédiger", "redouter", "refaire", "réflexe", "réformer", "refrain", "refuge", "régalien", "région", "réglage", "régulier", "réitérer", "rejeter", "rejouer", "relatif", "relever", "relief", "remarque", "remède", "remise", "remonter", "remplir", "remuer", "renard", "renfort", "renifler", "renoncer", "rentrer", "renvoi", "replier", "reporter", "reprise", "reptile", "requin", "réserve", "résineux", "résoudre", "respect", "rester", "résultat", "rétablir", "retenir", "réticule", "retomber", "retracer", "réunion", "réussir", "revanche", "revivre", "révolte", "révulsif", "richesse", "rideau", "rieur", "rigide", "rigoler", "rincer", "riposter", "risible", "risque", "rituel", "rival", "rivière", "rocheux", "romance", "rompre", "ronce", "rondin", "roseau", "rosier", "rotatif", "rotor", "rotule", "rouge", "rouille", "rouleau", "routine", "royaume", "ruban", "rubis", "ruche", "ruelle", "rugueux", "ruiner", "ruisseau", "ruser", "rustique", "rythme", "sabler", "saboter", "sabre", "sacoche", "safari", "sagesse", "saisir", "salade", "salive", "salon", "saluer", "samedi", "sanction", "sanglier", "sarcasme", "sardine", "saturer", "saugrenu", "saumon", "sauter", "sauvage", "savant", "savonner", "scalpel", "scandale", "scélérat", "scénario", "sceptre", "schéma", "science", "scinder", "score", "scrutin", "sculpter", "séance", "sécable", "sécher", "secouer", "sécréter", "sédatif", "séduire", "seigneur", "séjour", "sélectif", "semaine", "sembler", "semence", "séminal", "sénateur", "sensible", "sentence", "séparer", "séquence", "serein", "sergent", "sérieux", "serrure", "sérum", "service", "sésame", "sévir", "sevrage", "sextuple", "sidéral", "siècle", "siéger", "siffler", "sigle", "signal", "silence", "silicium", "simple", "sincère", "sinistre", "siphon", "sirop", "sismique", "situer", "skier", "social", "socle", "sodium", "soigneux", "soldat", "soleil", "solitude", "soluble", "sombre", "sommeil", "somnoler", "sonde", "songeur", "sonnette", "sonore", "sorcier", "sortir", "sosie", "sottise", "soucieux", "soudure", "souffle", "soulever", "soupape", "source", "soutirer", "souvenir", "spacieux", "spatial", "spécial", "sphère", "spiral", "stable", "station", "sternum", "stimulus", "stipuler", "strict", "studieux", "stupeur", "styliste", "sublime", "substrat", "subtil", "subvenir", "succès", "sucre", "suffixe", "suggérer", "suiveur", "sulfate", "superbe", "supplier", "surface", "suricate", "surmener", "surprise", "sursaut", "survie", "suspect", "syllabe", "symbole", "symétrie", "synapse", "syntaxe", "système", "tabac", "tablier", "tactile", "tailler", "talent", "talisman", "talonner", "tambour", "tamiser", "tangible", "tapis", "taquiner", "tarder", "tarif", "tartine", "tasse", "tatami", "tatouage", "taupe", "taureau", "taxer", "témoin", "temporel", "tenaille", "tendre", "teneur", "tenir", "tension", "terminer", "terne", "terrible", "tétine", "texte", "thème", "théorie", "thérapie", "thorax", "tibia", "tiède", "timide", "tirelire", "tiroir", "tissu", "titane", "titre", "tituber", "toboggan", "tolérant", "tomate", "tonique", "tonneau", "toponyme", "torche", "tordre", "tornade", "torpille", "torrent", "torse", "tortue", "totem", "toucher", "tournage", "tousser", "toxine", "traction", "trafic", "tragique", "trahir", "train", "trancher", "travail", "trèfle", "tremper", "trésor", "treuil", "triage", "tribunal", "tricoter", "trilogie", "triomphe", "tripler", "triturer", "trivial", "trombone", "tronc", "tropical", "troupeau", "tuile", "tulipe", "tumulte", "tunnel", "turbine", "tuteur", "tutoyer", "tuyau", "tympan", "typhon", "typique", "tyran", "ubuesque", "ultime", "ultrason", "unanime", "unifier", "union", "unique", "unitaire", "univers", "uranium", "urbain", "urticant", "usage", "usine", "usuel", "usure", "utile", "utopie", "vacarme", "vaccin", "vagabond", "vague", "vaillant", "vaincre", "vaisseau", "valable", "valise", "vallon", "valve", "vampire", "vanille", "vapeur", "varier", "vaseux", "vassal", "vaste", "vecteur", "vedette", "végétal", "véhicule", "veinard", "véloce", "vendredi", "vénérer", "venger", "venimeux", "ventouse", "verdure", "vérin", "vernir", "verrou", "verser", "vertu", "veston", "vétéran", "vétuste", "vexant", "vexer", "viaduc", "viande", "victoire", "vidange", "vidéo", "vignette", "vigueur", "vilain", "village", "vinaigre", "violon", "vipère", "virement", "virtuose", "virus", "visage", "viseur", "vision", "visqueux", "visuel", "vital", "vitesse", "viticole", "vitrine", "vivace", "vivipare", "vocation", "voguer", "voile", "voisin", "voiture", "volaille", "volcan", "voltiger", "volume", "vorace", "vortex", "voter", "vouloir", "voyage", "voyelle", "wagon", "xénon", "yacht", "zèbre", "zénith", "zeste", "zoologie" ] },{}],79:[function(require,module,exports){ module.exports=[ "abaco", "abbaglio", "abbinato", "abete", "abisso", "abolire", "abrasivo", "abrogato", "accadere", "accenno", "accusato", "acetone", "achille", "acido", "acqua", "acre", "acrilico", "acrobata", "acuto", "adagio", "addebito", "addome", "adeguato", "aderire", "adipe", "adottare", "adulare", "affabile", "affetto", "affisso", "affranto", "aforisma", "afoso", "africano", "agave", "agente", "agevole", "aggancio", "agire", "agitare", "agonismo", "agricolo", "agrumeto", "aguzzo", "alabarda", "alato", "albatro", "alberato", "albo", "albume", "alce", "alcolico", "alettone", "alfa", "algebra", "aliante", "alibi", "alimento", "allagato", "allegro", "allievo", "allodola", "allusivo", "almeno", "alogeno", "alpaca", "alpestre", "altalena", "alterno", "alticcio", "altrove", "alunno", "alveolo", "alzare", "amalgama", "amanita", "amarena", "ambito", "ambrato", "ameba", "america", "ametista", "amico", "ammasso", "ammenda", "ammirare", "ammonito", "amore", "ampio", "ampliare", "amuleto", "anacardo", "anagrafe", "analista", "anarchia", "anatra", "anca", "ancella", "ancora", "andare", "andrea", "anello", "angelo", "angolare", "angusto", "anima", "annegare", "annidato", "anno", "annuncio", "anonimo", "anticipo", "anzi", "apatico", "apertura", "apode", "apparire", "appetito", "appoggio", "approdo", "appunto", "aprile", "arabica", "arachide", "aragosta", "araldica", "arancio", "aratura", "arazzo", "arbitro", "archivio", "ardito", "arenile", "argento", "argine", "arguto", "aria", "armonia", "arnese", "arredato", "arringa", "arrosto", "arsenico", "arso", "artefice", "arzillo", "asciutto", "ascolto", "asepsi", "asettico", "asfalto", "asino", "asola", "aspirato", "aspro", "assaggio", "asse", "assoluto", "assurdo", "asta", "astenuto", "astice", "astratto", "atavico", "ateismo", "atomico", "atono", "attesa", "attivare", "attorno", "attrito", "attuale", "ausilio", "austria", "autista", "autonomo", "autunno", "avanzato", "avere", "avvenire", "avviso", "avvolgere", "azione", "azoto", "azzimo", "azzurro", "babele", "baccano", "bacino", "baco", "badessa", "badilata", "bagnato", "baita", "balcone", "baldo", "balena", "ballata", "balzano", "bambino", "bandire", "baraonda", "barbaro", "barca", "baritono", "barlume", "barocco", "basilico", "basso", "batosta", "battuto", "baule", "bava", "bavosa", "becco", "beffa", "belgio", "belva", "benda", "benevole", "benigno", "benzina", "bere", "berlina", "beta", "bibita", "bici", "bidone", "bifido", "biga", "bilancia", "bimbo", "binocolo", "biologo", "bipede", "bipolare", "birbante", "birra", "biscotto", "bisesto", "bisnonno", "bisonte", "bisturi", "bizzarro", "blando", "blatta", "bollito", "bonifico", "bordo", "bosco", "botanico", "bottino", "bozzolo", "braccio", "bradipo", "brama", "branca", "bravura", "bretella", "brevetto", "brezza", "briglia", "brillante", "brindare", "broccolo", "brodo", "bronzina", "brullo", "bruno", "bubbone", "buca", "budino", "buffone", "buio", "bulbo", "buono", "burlone", "burrasca", "bussola", "busta", "cadetto", "caduco", "calamaro", "calcolo", "calesse", "calibro", "calmo", "caloria", "cambusa", "camerata", "camicia", "cammino", "camola", "campale", "canapa", "candela", "cane", "canino", "canotto", "cantina", "capace", "capello", "capitolo", "capogiro", "cappero", "capra", "capsula", "carapace", "carcassa", "cardo", "carisma", "carovana", "carretto", "cartolina", "casaccio", "cascata", "caserma", "caso", "cassone", "castello", "casuale", "catasta", "catena", "catrame", "cauto", "cavillo", "cedibile", "cedrata", "cefalo", "celebre", "cellulare", "cena", "cenone", "centesimo", "ceramica", "cercare", "certo", "cerume", "cervello", "cesoia", "cespo", "ceto", "chela", "chiaro", "chicca", "chiedere", "chimera", "china", "chirurgo", "chitarra", "ciao", "ciclismo", "cifrare", "cigno", "cilindro", "ciottolo", "circa", "cirrosi", "citrico", "cittadino", "ciuffo", "civetta", "civile", "classico", "clinica", "cloro", "cocco", "codardo", "codice", "coerente", "cognome", "collare", "colmato", "colore", "colposo", "coltivato", "colza", "coma", "cometa", "commando", "comodo", "computer", "comune", "conciso", "condurre", "conferma", "congelare", "coniuge", "connesso", "conoscere", "consumo", "continuo", "convegno", "coperto", "copione", "coppia", "copricapo", "corazza", "cordata", "coricato", "cornice", "corolla", "corpo", "corredo", "corsia", "cortese", "cosmico", "costante", "cottura", "covato", "cratere", "cravatta", "creato", "credere", "cremoso", "crescita", "creta", "criceto", "crinale", "crisi", "critico", "croce", "cronaca", "crostata", "cruciale", "crusca", "cucire", "cuculo", "cugino", "cullato", "cupola", "curatore", "cursore", "curvo", "cuscino", "custode", "dado", "daino", "dalmata", "damerino", "daniela", "dannoso", "danzare", "datato", "davanti", "davvero", "debutto", "decennio", "deciso", "declino", "decollo", "decreto", "dedicato", "definito", "deforme", "degno", "delegare", "delfino", "delirio", "delta", "demenza", "denotato", "dentro", "deposito", "derapata", "derivare", "deroga", "descritto", "deserto", "desiderio", "desumere", "detersivo", "devoto", "diametro", "dicembre", "diedro", "difeso", "diffuso", "digerire", "digitale", "diluvio", "dinamico", "dinnanzi", "dipinto", "diploma", "dipolo", "diradare", "dire", "dirotto", "dirupo", "disagio", "discreto", "disfare", "disgelo", "disposto", "distanza", "disumano", "dito", "divano", "divelto", "dividere", "divorato", "doblone", "docente", "doganale", "dogma", "dolce", "domato", "domenica", "dominare", "dondolo", "dono", "dormire", "dote", "dottore", "dovuto", "dozzina", "drago", "druido", "dubbio", "dubitare", "ducale", "duna", "duomo", "duplice", "duraturo", "ebano", "eccesso", "ecco", "eclissi", "economia", "edera", "edicola", "edile", "editoria", "educare", "egemonia", "egli", "egoismo", "egregio", "elaborato", "elargire", "elegante", "elencato", "eletto", "elevare", "elfico", "elica", "elmo", "elsa", "eluso", "emanato", "emblema", "emesso", "emiro", "emotivo", "emozione", "empirico", "emulo", "endemico", "enduro", "energia", "enfasi", "enoteca", "entrare", "enzima", "epatite", "epilogo", "episodio", "epocale", "eppure", "equatore", "erario", "erba", "erboso", "erede", "eremita", "erigere", "ermetico", "eroe", "erosivo", "errante", "esagono", "esame", "esanime", "esaudire", "esca", "esempio", "esercito", "esibito", "esigente", "esistere", "esito", "esofago", "esortato", "esoso", "espanso", "espresso", "essenza", "esso", "esteso", "estimare", "estonia", "estroso", "esultare", "etilico", "etnico", "etrusco", "etto", "euclideo", "europa", "evaso", "evidenza", "evitato", "evoluto", "evviva", "fabbrica", "faccenda", "fachiro", "falco", "famiglia", "fanale", "fanfara", "fango", "fantasma", "fare", "farfalla", "farinoso", "farmaco", "fascia", "fastoso", "fasullo", "faticare", "fato", "favoloso", "febbre", "fecola", "fede", "fegato", "felpa", "feltro", "femmina", "fendere", "fenomeno", "fermento", "ferro", "fertile", "fessura", "festivo", "fetta", "feudo", "fiaba", "fiducia", "fifa", "figurato", "filo", "finanza", "finestra", "finire", "fiore", "fiscale", "fisico", "fiume", "flacone", "flamenco", "flebo", "flemma", "florido", "fluente", "fluoro", "fobico", "focaccia", "focoso", "foderato", "foglio", "folata", "folclore", "folgore", "fondente", "fonetico", "fonia", "fontana", "forbito", "forchetta", "foresta", "formica", "fornaio", "foro", "fortezza", "forzare", "fosfato", "fosso", "fracasso", "frana", "frassino", "fratello", "freccetta", "frenata", "fresco", "frigo", "frollino", "fronde", "frugale", "frutta", "fucilata", "fucsia", "fuggente", "fulmine", "fulvo", "fumante", "fumetto", "fumoso", "fune", "funzione", "fuoco", "furbo", "furgone", "furore", "fuso", "futile", "gabbiano", "gaffe", "galateo", "gallina", "galoppo", "gambero", "gamma", "garanzia", "garbo", "garofano", "garzone", "gasdotto", "gasolio", "gastrico", "gatto", "gaudio", "gazebo", "gazzella", "geco", "gelatina", "gelso", "gemello", "gemmato", "gene", "genitore", "gennaio", "genotipo", "gergo", "ghepardo", "ghiaccio", "ghisa", "giallo", "gilda", "ginepro", "giocare", "gioiello", "giorno", "giove", "girato", "girone", "gittata", "giudizio", "giurato", "giusto", "globulo", "glutine", "gnomo", "gobba", "golf", "gomito", "gommone", "gonfio", "gonna", "governo", "gracile", "grado", "grafico", "grammo", "grande", "grattare", "gravoso", "grazia", "greca", "gregge", "grifone", "grigio", "grinza", "grotta", "gruppo", "guadagno", "guaio", "guanto", "guardare", "gufo", "guidare", "ibernato", "icona", "identico", "idillio", "idolo", "idra", "idrico", "idrogeno", "igiene", "ignaro", "ignorato", "ilare", "illeso", "illogico", "illudere", "imballo", "imbevuto", "imbocco", "imbuto", "immane", "immerso", "immolato", "impacco", "impeto", "impiego", "importo", "impronta", "inalare", "inarcare", "inattivo", "incanto", "incendio", "inchino", "incisivo", "incluso", "incontro", "incrocio", "incubo", "indagine", "india", "indole", "inedito", "infatti", "infilare", "inflitto", "ingaggio", "ingegno", "inglese", "ingordo", "ingrosso", "innesco", "inodore", "inoltrare", "inondato", "insano", "insetto", "insieme", "insonnia", "insulina", "intasato", "intero", "intonaco", "intuito", "inumidire", "invalido", "invece", "invito", "iperbole", "ipnotico", "ipotesi", "ippica", "iride", "irlanda", "ironico", "irrigato", "irrorare", "isolato", "isotopo", "isterico", "istituto", "istrice", "italia", "iterare", "labbro", "labirinto", "lacca", "lacerato", "lacrima", "lacuna", "laddove", "lago", "lampo", "lancetta", "lanterna", "lardoso", "larga", "laringe", "lastra", "latenza", "latino", "lattuga", "lavagna", "lavoro", "legale", "leggero", "lembo", "lentezza", "lenza", "leone", "lepre", "lesivo", "lessato", "lesto", "letterale", "leva", "levigato", "libero", "lido", "lievito", "lilla", "limatura", "limitare", "limpido", "lineare", "lingua", "liquido", "lira", "lirica", "lisca", "lite", "litigio", "livrea", "locanda", "lode", "logica", "lombare", "londra", "longevo", "loquace", "lorenzo", "loto", "lotteria", "luce", "lucidato", "lumaca", "luminoso", "lungo", "lupo", "luppolo", "lusinga", "lusso", "lutto", "macabro", "macchina", "macero", "macinato", "madama", "magico", "maglia", "magnete", "magro", "maiolica", "malafede", "malgrado", "malinteso", "malsano", "malto", "malumore", "mana", "mancia", "mandorla", "mangiare", "manifesto", "mannaro", "manovra", "mansarda", "mantide", "manubrio", "mappa", "maratona", "marcire", "maretta", "marmo", "marsupio", "maschera", "massaia", "mastino", "materasso", "matricola", "mattone", "maturo", "mazurca", "meandro", "meccanico", "mecenate", "medesimo", "meditare", "mega", "melassa", "melis", "melodia", "meninge", "meno", "mensola", "mercurio", "merenda", "merlo", "meschino", "mese", "messere", "mestolo", "metallo", "metodo", "mettere", "miagolare", "mica", "micelio", "michele", "microbo", "midollo", "miele", "migliore", "milano", "milite", "mimosa", "minerale", "mini", "minore", "mirino", "mirtillo", "miscela", "missiva", "misto", "misurare", "mitezza", "mitigare", "mitra", "mittente", "mnemonico", "modello", "modifica", "modulo", "mogano", "mogio", "mole", "molosso", "monastero", "monco", "mondina", "monetario", "monile", "monotono", "monsone", "montato", "monviso", "mora", "mordere", "morsicato", "mostro", "motivato", "motosega", "motto", "movenza", "movimento", "mozzo", "mucca", "mucosa", "muffa", "mughetto", "mugnaio", "mulatto", "mulinello", "multiplo", "mummia", "munto", "muovere", "murale", "musa", "muscolo", "musica", "mutevole", "muto", "nababbo", "nafta", "nanometro", "narciso", "narice", "narrato", "nascere", "nastrare", "naturale", "nautica", "naviglio", "nebulosa", "necrosi", "negativo", "negozio", "nemmeno", "neofita", "neretto", "nervo", "nessuno", "nettuno", "neutrale", "neve", "nevrotico", "nicchia", "ninfa", "nitido", "nobile", "nocivo", "nodo", "nome", "nomina", "nordico", "normale", "norvegese", "nostrano", "notare", "notizia", "notturno", "novella", "nucleo", "nulla", "numero", "nuovo", "nutrire", "nuvola", "nuziale", "oasi", "obbedire", "obbligo", "obelisco", "oblio", "obolo", "obsoleto", "occasione", "occhio", "occidente", "occorrere", "occultare", "ocra", "oculato", "odierno", "odorare", "offerta", "offrire", "offuscato", "oggetto", "oggi", "ognuno", "olandese", "olfatto", "oliato", "oliva", "ologramma", "oltre", "omaggio", "ombelico", "ombra", "omega", "omissione", "ondoso", "onere", "onice", "onnivoro", "onorevole", "onta", "operato", "opinione", "opposto", "oracolo", "orafo", "ordine", "orecchino", "orefice", "orfano", "organico", "origine", "orizzonte", "orma", "ormeggio", "ornativo", "orologio", "orrendo", "orribile", "ortensia", "ortica", "orzata", "orzo", "osare", "oscurare", "osmosi", "ospedale", "ospite", "ossa", "ossidare", "ostacolo", "oste", "otite", "otre", "ottagono", "ottimo", "ottobre", "ovale", "ovest", "ovino", "oviparo", "ovocito", "ovunque", "ovviare", "ozio", "pacchetto", "pace", "pacifico", "padella", "padrone", "paese", "paga", "pagina", "palazzina", "palesare", "pallido", "palo", "palude", "pandoro", "pannello", "paolo", "paonazzo", "paprica", "parabola", "parcella", "parere", "pargolo", "pari", "parlato", "parola", "partire", "parvenza", "parziale", "passivo", "pasticca", "patacca", "patologia", "pattume", "pavone", "peccato", "pedalare", "pedonale", "peggio", "peloso", "penare", "pendice", "penisola", "pennuto", "penombra", "pensare", "pentola", "pepe", "pepita", "perbene", "percorso", "perdonato", "perforare", "pergamena", "periodo", "permesso", "perno", "perplesso", "persuaso", "pertugio", "pervaso", "pesatore", "pesista", "peso", "pestifero", "petalo", "pettine", "petulante", "pezzo", "piacere", "pianta", "piattino", "piccino", "picozza", "piega", "pietra", "piffero", "pigiama", "pigolio", "pigro", "pila", "pilifero", "pillola", "pilota", "pimpante", "pineta", "pinna", "pinolo", "pioggia", "piombo", "piramide", "piretico", "pirite", "pirolisi", "pitone", "pizzico", "placebo", "planare", "plasma", "platano", "plenario", "pochezza", "poderoso", "podismo", "poesia", "poggiare", "polenta", "poligono", "pollice", "polmonite", "polpetta", "polso", "poltrona", "polvere", "pomice", "pomodoro", "ponte", "popoloso", "porfido", "poroso", "porpora", "porre", "portata", "posa", "positivo", "possesso", "postulato", "potassio", "potere", "pranzo", "prassi", "pratica", "precluso", "predica", "prefisso", "pregiato", "prelievo", "premere", "prenotare", "preparato", "presenza", "pretesto", "prevalso", "prima", "principe", "privato", "problema", "procura", "produrre", "profumo", "progetto", "prolunga", "promessa", "pronome", "proposta", "proroga", "proteso", "prova", "prudente", "prugna", "prurito", "psiche", "pubblico", "pudica", "pugilato", "pugno", "pulce", "pulito", "pulsante", "puntare", "pupazzo", "pupilla", "puro", "quadro", "qualcosa", "quasi", "querela", "quota", "raccolto", "raddoppio", "radicale", "radunato", "raffica", "ragazzo", "ragione", "ragno", "ramarro", "ramingo", "ramo", "randagio", "rantolare", "rapato", "rapina", "rappreso", "rasatura", "raschiato", "rasente", "rassegna", "rastrello", "rata", "ravveduto", "reale", "recepire", "recinto", "recluta", "recondito", "recupero", "reddito", "redimere", "regalato", "registro", "regola", "regresso", "relazione", "remare", "remoto", "renna", "replica", "reprimere", "reputare", "resa", "residente", "responso", "restauro", "rete", "retina", "retorica", "rettifica", "revocato", "riassunto", "ribadire", "ribelle", "ribrezzo", "ricarica", "ricco", "ricevere", "riciclato", "ricordo", "ricreduto", "ridicolo", "ridurre", "rifasare", "riflesso", "riforma", "rifugio", "rigare", "rigettato", "righello", "rilassato", "rilevato", "rimanere", "rimbalzo", "rimedio", "rimorchio", "rinascita", "rincaro", "rinforzo", "rinnovo", "rinomato", "rinsavito", "rintocco", "rinuncia", "rinvenire", "riparato", "ripetuto", "ripieno", "riportare", "ripresa", "ripulire", "risata", "rischio", "riserva", "risibile", "riso", "rispetto", "ristoro", "risultato", "risvolto", "ritardo", "ritegno", "ritmico", "ritrovo", "riunione", "riva", "riverso", "rivincita", "rivolto", "rizoma", "roba", "robotico", "robusto", "roccia", "roco", "rodaggio", "rodere", "roditore", "rogito", "rollio", "romantico", "rompere", "ronzio", "rosolare", "rospo", "rotante", "rotondo", "rotula", "rovescio", "rubizzo", "rubrica", "ruga", "rullino", "rumine", "rumoroso", "ruolo", "rupe", "russare", "rustico", "sabato", "sabbiare", "sabotato", "sagoma", "salasso", "saldatura", "salgemma", "salivare", "salmone", "salone", "saltare", "saluto", "salvo", "sapere", "sapido", "saporito", "saraceno", "sarcasmo", "sarto", "sassoso", "satellite", "satira", "satollo", "saturno", "savana", "savio", "saziato", "sbadiglio", "sbalzo", "sbancato", "sbarra", "sbattere", "sbavare", "sbendare", "sbirciare", "sbloccato", "sbocciato", "sbrinare", "sbruffone", "sbuffare", "scabroso", "scadenza", "scala", "scambiare", "scandalo", "scapola", "scarso", "scatenare", "scavato", "scelto", "scenico", "scettro", "scheda", "schiena", "sciarpa", "scienza", "scindere", "scippo", "sciroppo", "scivolo", "sclerare", "scodella", "scolpito", "scomparto", "sconforto", "scoprire", "scorta", "scossone", "scozzese", "scriba", "scrollare", "scrutinio", "scuderia", "scultore", "scuola", "scuro", "scusare", "sdebitare", "sdoganare", "seccatura", "secondo", "sedano", "seggiola", "segnalato", "segregato", "seguito", "selciato", "selettivo", "sella", "selvaggio", "semaforo", "sembrare", "seme", "seminato", "sempre", "senso", "sentire", "sepolto", "sequenza", "serata", "serbato", "sereno", "serio", "serpente", "serraglio", "servire", "sestina", "setola", "settimana", "sfacelo", "sfaldare", "sfamato", "sfarzoso", "sfaticato", "sfera", "sfida", "sfilato", "sfinge", "sfocato", "sfoderare", "sfogo", "sfoltire", "sforzato", "sfratto", "sfruttato", "sfuggito", "sfumare", "sfuso", "sgabello", "sgarbato", "sgonfiare", "sgorbio", "sgrassato", "sguardo", "sibilo", "siccome", "sierra", "sigla", "signore", "silenzio", "sillaba", "simbolo", "simpatico", "simulato", "sinfonia", "singolo", "sinistro", "sino", "sintesi", "sinusoide", "sipario", "sisma", "sistole", "situato", "slitta", "slogatura", "sloveno", "smarrito", "smemorato", "smentito", "smeraldo", "smilzo", "smontare", "smottato", "smussato", "snellire", "snervato", "snodo", "sobbalzo", "sobrio", "soccorso", "sociale", "sodale", "soffitto", "sogno", "soldato", "solenne", "solido", "sollazzo", "solo", "solubile", "solvente", "somatico", "somma", "sonda", "sonetto", "sonnifero", "sopire", "soppeso", "sopra", "sorgere", "sorpasso", "sorriso", "sorso", "sorteggio", "sorvolato", "sospiro", "sosta", "sottile", "spada", "spalla", "spargere", "spatola", "spavento", "spazzola", "specie", "spedire", "spegnere", "spelatura", "speranza", "spessore", "spettrale", "spezzato", "spia", "spigoloso", "spillato", "spinoso", "spirale", "splendido", "sportivo", "sposo", "spranga", "sprecare", "spronato", "spruzzo", "spuntino", "squillo", "sradicare", "srotolato", "stabile", "stacco", "staffa", "stagnare", "stampato", "stantio", "starnuto", "stasera", "statuto", "stelo", "steppa", "sterzo", "stiletto", "stima", "stirpe", "stivale", "stizzoso", "stonato", "storico", "strappo", "stregato", "stridulo", "strozzare", "strutto", "stuccare", "stufo", "stupendo", "subentro", "succoso", "sudore", "suggerito", "sugo", "sultano", "suonare", "superbo", "supporto", "surgelato", "surrogato", "sussurro", "sutura", "svagare", "svedese", "sveglio", "svelare", "svenuto", "svezia", "sviluppo", "svista", "svizzera", "svolta", "svuotare", "tabacco", "tabulato", "tacciare", "taciturno", "tale", "talismano", "tampone", "tannino", "tara", "tardivo", "targato", "tariffa", "tarpare", "tartaruga", "tasto", "tattico", "taverna", "tavolata", "tazza", "teca", "tecnico", "telefono", "temerario", "tempo", "temuto", "tendone", "tenero", "tensione", "tentacolo", "teorema", "terme", "terrazzo", "terzetto", "tesi", "tesserato", "testato", "tetro", "tettoia", "tifare", "tigella", "timbro", "tinto", "tipico", "tipografo", "tiraggio", "tiro", "titanio", "titolo", "titubante", "tizio", "tizzone", "toccare", "tollerare", "tolto", "tombola", "tomo", "tonfo", "tonsilla", "topazio", "topologia", "toppa", "torba", "tornare", "torrone", "tortora", "toscano", "tossire", "tostatura", "totano", "trabocco", "trachea", "trafila", "tragedia", "tralcio", "tramonto", "transito", "trapano", "trarre", "trasloco", "trattato", "trave", "treccia", "tremolio", "trespolo", "tributo", "tricheco", "trifoglio", "trillo", "trincea", "trio", "tristezza", "triturato", "trivella", "tromba", "trono", "troppo", "trottola", "trovare", "truccato", "tubatura", "tuffato", "tulipano", "tumulto", "tunisia", "turbare", "turchino", "tuta", "tutela", "ubicato", "uccello", "uccisore", "udire", "uditivo", "uffa", "ufficio", "uguale", "ulisse", "ultimato", "umano", "umile", "umorismo", "uncinetto", "ungere", "ungherese", "unicorno", "unificato", "unisono", "unitario", "unte", "uovo", "upupa", "uragano", "urgenza", "urlo", "usanza", "usato", "uscito", "usignolo", "usuraio", "utensile", "utilizzo", "utopia", "vacante", "vaccinato", "vagabondo", "vagliato", "valanga", "valgo", "valico", "valletta", "valoroso", "valutare", "valvola", "vampata", "vangare", "vanitoso", "vano", "vantaggio", "vanvera", "vapore", "varano", "varcato", "variante", "vasca", "vedetta", "vedova", "veduto", "vegetale", "veicolo", "velcro", "velina", "velluto", "veloce", "venato", "vendemmia", "vento", "verace", "verbale", "vergogna", "verifica", "vero", "verruca", "verticale", "vescica", "vessillo", "vestale", "veterano", "vetrina", "vetusto", "viandante", "vibrante", "vicenda", "vichingo", "vicinanza", "vidimare", "vigilia", "vigneto", "vigore", "vile", "villano", "vimini", "vincitore", "viola", "vipera", "virgola", "virologo", "virulento", "viscoso", "visione", "vispo", "vissuto", "visura", "vita", "vitello", "vittima", "vivanda", "vivido", "viziare", "voce", "voga", "volatile", "volere", "volpe", "voragine", "vulcano", "zampogna", "zanna", "zappato", "zattera", "zavorra", "zefiro", "zelante", "zelo", "zenzero", "zerbino", "zibetto", "zinco", "zircone", "zitto", "zolla", "zotico", "zucchero", "zufolo", "zulu", "zuppa" ] },{}],80:[function(require,module,exports){ module.exports=[ "あいこくしん", "あいさつ", "あいだ", "あおぞら", "あかちゃん", "あきる", "あけがた", "あける", "あこがれる", "あさい", "あさひ", "あしあと", "あじわう", "あずかる", "あずき", "あそぶ", "あたえる", "あたためる", "あたりまえ", "あたる", "あつい", "あつかう", "あっしゅく", "あつまり", "あつめる", "あてな", "あてはまる", "あひる", "あぶら", "あぶる", "あふれる", "あまい", "あまど", "あまやかす", "あまり", "あみもの", "あめりか", "あやまる", "あゆむ", "あらいぐま", "あらし", "あらすじ", "あらためる", "あらゆる", "あらわす", "ありがとう", "あわせる", "あわてる", "あんい", "あんがい", "あんこ", "あんぜん", "あんてい", "あんない", "あんまり", "いいだす", "いおん", "いがい", "いがく", "いきおい", "いきなり", "いきもの", "いきる", "いくじ", "いくぶん", "いけばな", "いけん", "いこう", "いこく", "いこつ", "いさましい", "いさん", "いしき", "いじゅう", "いじょう", "いじわる", "いずみ", "いずれ", "いせい", "いせえび", "いせかい", "いせき", "いぜん", "いそうろう", "いそがしい", "いだい", "いだく", "いたずら", "いたみ", "いたりあ", "いちおう", "いちじ", "いちど", "いちば", "いちぶ", "いちりゅう", "いつか", "いっしゅん", "いっせい", "いっそう", "いったん", "いっち", "いってい", "いっぽう", "いてざ", "いてん", "いどう", "いとこ", "いない", "いなか", "いねむり", "いのち", "いのる", "いはつ", "いばる", "いはん", "いびき", "いひん", "いふく", "いへん", "いほう", "いみん", "いもうと", "いもたれ", "いもり", "いやがる", "いやす", "いよかん", "いよく", "いらい", "いらすと", "いりぐち", "いりょう", "いれい", "いれもの", "いれる", "いろえんぴつ", "いわい", "いわう", "いわかん", "いわば", "いわゆる", "いんげんまめ", "いんさつ", "いんしょう", "いんよう", "うえき", "うえる", "うおざ", "うがい", "うかぶ", "うかべる", "うきわ", "うくらいな", "うくれれ", "うけたまわる", "うけつけ", "うけとる", "うけもつ", "うける", "うごかす", "うごく", "うこん", "うさぎ", "うしなう", "うしろがみ", "うすい", "うすぎ", "うすぐらい", "うすめる", "うせつ", "うちあわせ", "うちがわ", "うちき", "うちゅう", "うっかり", "うつくしい", "うったえる", "うつる", "うどん", "うなぎ", "うなじ", "うなずく", "うなる", "うねる", "うのう", "うぶげ", "うぶごえ", "うまれる", "うめる", "うもう", "うやまう", "うよく", "うらがえす", "うらぐち", "うらない", "うりあげ", "うりきれ", "うるさい", "うれしい", "うれゆき", "うれる", "うろこ", "うわき", "うわさ", "うんこう", "うんちん", "うんてん", "うんどう", "えいえん", "えいが", "えいきょう", "えいご", "えいせい", "えいぶん", "えいよう", "えいわ", "えおり", "えがお", "えがく", "えきたい", "えくせる", "えしゃく", "えすて", "えつらん", "えのぐ", "えほうまき", "えほん", "えまき", "えもじ", "えもの", "えらい", "えらぶ", "えりあ", "えんえん", "えんかい", "えんぎ", "えんげき", "えんしゅう", "えんぜつ", "えんそく", "えんちょう", "えんとつ", "おいかける", "おいこす", "おいしい", "おいつく", "おうえん", "おうさま", "おうじ", "おうせつ", "おうたい", "おうふく", "おうべい", "おうよう", "おえる", "おおい", "おおう", "おおどおり", "おおや", "おおよそ", "おかえり", "おかず", "おがむ", "おかわり", "おぎなう", "おきる", "おくさま", "おくじょう", "おくりがな", "おくる", "おくれる", "おこす", "おこなう", "おこる", "おさえる", "おさない", "おさめる", "おしいれ", "おしえる", "おじぎ", "おじさん", "おしゃれ", "おそらく", "おそわる", "おたがい", "おたく", "おだやか", "おちつく", "おっと", "おつり", "おでかけ", "おとしもの", "おとなしい", "おどり", "おどろかす", "おばさん", "おまいり", "おめでとう", "おもいで", "おもう", "おもたい", "おもちゃ", "おやつ", "おやゆび", "およぼす", "おらんだ", "おろす", "おんがく", "おんけい", "おんしゃ", "おんせん", "おんだん", "おんちゅう", "おんどけい", "かあつ", "かいが", "がいき", "がいけん", "がいこう", "かいさつ", "かいしゃ", "かいすいよく", "かいぜん", "かいぞうど", "かいつう", "かいてん", "かいとう", "かいふく", "がいへき", "かいほう", "かいよう", "がいらい", "かいわ", "かえる", "かおり", "かかえる", "かがく", "かがし", "かがみ", "かくご", "かくとく", "かざる", "がぞう", "かたい", "かたち", "がちょう", "がっきゅう", "がっこう", "がっさん", "がっしょう", "かなざわし", "かのう", "がはく", "かぶか", "かほう", "かほご", "かまう", "かまぼこ", "かめれおん", "かゆい", "かようび", "からい", "かるい", "かろう", "かわく", "かわら", "がんか", "かんけい", "かんこう", "かんしゃ", "かんそう", "かんたん", "かんち", "がんばる", "きあい", "きあつ", "きいろ", "ぎいん", "きうい", "きうん", "きえる", "きおう", "きおく", "きおち", "きおん", "きかい", "きかく", "きかんしゃ", "ききて", "きくばり", "きくらげ", "きけんせい", "きこう", "きこえる", "きこく", "きさい", "きさく", "きさま", "きさらぎ", "ぎじかがく", "ぎしき", "ぎじたいけん", "ぎじにってい", "ぎじゅつしゃ", "きすう", "きせい", "きせき", "きせつ", "きそう", "きぞく", "きぞん", "きたえる", "きちょう", "きつえん", "ぎっちり", "きつつき", "きつね", "きてい", "きどう", "きどく", "きない", "きなが", "きなこ", "きぬごし", "きねん", "きのう", "きのした", "きはく", "きびしい", "きひん", "きふく", "きぶん", "きぼう", "きほん", "きまる", "きみつ", "きむずかしい", "きめる", "きもだめし", "きもち", "きもの", "きゃく", "きやく", "ぎゅうにく", "きよう", "きょうりゅう", "きらい", "きらく", "きりん", "きれい", "きれつ", "きろく", "ぎろん", "きわめる", "ぎんいろ", "きんかくじ", "きんじょ", "きんようび", "ぐあい", "くいず", "くうかん", "くうき", "くうぐん", "くうこう", "ぐうせい", "くうそう", "ぐうたら", "くうふく", "くうぼ", "くかん", "くきょう", "くげん", "ぐこう", "くさい", "くさき", "くさばな", "くさる", "くしゃみ", "くしょう", "くすのき", "くすりゆび", "くせげ", "くせん", "ぐたいてき", "くださる", "くたびれる", "くちこみ", "くちさき", "くつした", "ぐっすり", "くつろぐ", "くとうてん", "くどく", "くなん", "くねくね", "くのう", "くふう", "くみあわせ", "くみたてる", "くめる", "くやくしょ", "くらす", "くらべる", "くるま", "くれる", "くろう", "くわしい", "ぐんかん", "ぐんしょく", "ぐんたい", "ぐんて", "けあな", "けいかく", "けいけん", "けいこ", "けいさつ", "げいじゅつ", "けいたい", "げいのうじん", "けいれき", "けいろ", "けおとす", "けおりもの", "げきか", "げきげん", "げきだん", "げきちん", "げきとつ", "げきは", "げきやく", "げこう", "げこくじょう", "げざい", "けさき", "げざん", "けしき", "けしごむ", "けしょう", "げすと", "けたば", "けちゃっぷ", "けちらす", "けつあつ", "けつい", "けつえき", "けっこん", "けつじょ", "けっせき", "けってい", "けつまつ", "げつようび", "げつれい", "けつろん", "げどく", "けとばす", "けとる", "けなげ", "けなす", "けなみ", "けぬき", "げねつ", "けねん", "けはい", "げひん", "けぶかい", "げぼく", "けまり", "けみかる", "けむし", "けむり", "けもの", "けらい", "けろけろ", "けわしい", "けんい", "けんえつ", "けんお", "けんか", "げんき", "けんげん", "けんこう", "けんさく", "けんしゅう", "けんすう", "げんそう", "けんちく", "けんてい", "けんとう", "けんない", "けんにん", "げんぶつ", "けんま", "けんみん", "けんめい", "けんらん", "けんり", "こあくま", "こいぬ", "こいびと", "ごうい", "こうえん", "こうおん", "こうかん", "ごうきゅう", "ごうけい", "こうこう", "こうさい", "こうじ", "こうすい", "ごうせい", "こうそく", "こうたい", "こうちゃ", "こうつう", "こうてい", "こうどう", "こうない", "こうはい", "ごうほう", "ごうまん", "こうもく", "こうりつ", "こえる", "こおり", "ごかい", "ごがつ", "ごかん", "こくご", "こくさい", "こくとう", "こくない", "こくはく", "こぐま", "こけい", "こける", "ここのか", "こころ", "こさめ", "こしつ", "こすう", "こせい", "こせき", "こぜん", "こそだて", "こたい", "こたえる", "こたつ", "こちょう", "こっか", "こつこつ", "こつばん", "こつぶ", "こてい", "こてん", "ことがら", "ことし", "ことば", "ことり", "こなごな", "こねこね", "このまま", "このみ", "このよ", "ごはん", "こひつじ", "こふう", "こふん", "こぼれる", "ごまあぶら", "こまかい", "ごますり", "こまつな", "こまる", "こむぎこ", "こもじ", "こもち", "こもの", "こもん", "こやく", "こやま", "こゆう", "こゆび", "こよい", "こよう", "こりる", "これくしょん", "ころっけ", "こわもて", "こわれる", "こんいん", "こんかい", "こんき", "こんしゅう", "こんすい", "こんだて", "こんとん", "こんなん", "こんびに", "こんぽん", "こんまけ", "こんや", "こんれい", "こんわく", "ざいえき", "さいかい", "さいきん", "ざいげん", "ざいこ", "さいしょ", "さいせい", "ざいたく", "ざいちゅう", "さいてき", "ざいりょう", "さうな", "さかいし", "さがす", "さかな", "さかみち", "さがる", "さぎょう", "さくし", "さくひん", "さくら", "さこく", "さこつ", "さずかる", "ざせき", "さたん", "さつえい", "ざつおん", "ざっか", "ざつがく", "さっきょく", "ざっし", "さつじん", "ざっそう", "さつたば", "さつまいも", "さてい", "さといも", "さとう", "さとおや", "さとし", "さとる", "さのう", "さばく", "さびしい", "さべつ", "さほう", "さほど", "さます", "さみしい", "さみだれ", "さむけ", "さめる", "さやえんどう", "さゆう", "さよう", "さよく", "さらだ", "ざるそば", "さわやか", "さわる", "さんいん", "さんか", "さんきゃく", "さんこう", "さんさい", "ざんしょ", "さんすう", "さんせい", "さんそ", "さんち", "さんま", "さんみ", "さんらん", "しあい", "しあげ", "しあさって", "しあわせ", "しいく", "しいん", "しうち", "しえい", "しおけ", "しかい", "しかく", "じかん", "しごと", "しすう", "じだい", "したうけ", "したぎ", "したて", "したみ", "しちょう", "しちりん", "しっかり", "しつじ", "しつもん", "してい", "してき", "してつ", "じてん", "じどう", "しなぎれ", "しなもの", "しなん", "しねま", "しねん", "しのぐ", "しのぶ", "しはい", "しばかり", "しはつ", "しはらい", "しはん", "しひょう", "しふく", "じぶん", "しへい", "しほう", "しほん", "しまう", "しまる", "しみん", "しむける", "じむしょ", "しめい", "しめる", "しもん", "しゃいん", "しゃうん", "しゃおん", "じゃがいも", "しやくしょ", "しゃくほう", "しゃけん", "しゃこ", "しゃざい", "しゃしん", "しゃせん", "しゃそう", "しゃたい", "しゃちょう", "しゃっきん", "じゃま", "しゃりん", "しゃれい", "じゆう", "じゅうしょ", "しゅくはく", "じゅしん", "しゅっせき", "しゅみ", "しゅらば", "じゅんばん", "しょうかい", "しょくたく", "しょっけん", "しょどう", "しょもつ", "しらせる", "しらべる", "しんか", "しんこう", "じんじゃ", "しんせいじ", "しんちく", "しんりん", "すあげ", "すあし", "すあな", "ずあん", "すいえい", "すいか", "すいとう", "ずいぶん", "すいようび", "すうがく", "すうじつ", "すうせん", "すおどり", "すきま", "すくう", "すくない", "すける", "すごい", "すこし", "ずさん", "すずしい", "すすむ", "すすめる", "すっかり", "ずっしり", "ずっと", "すてき", "すてる", "すねる", "すのこ", "すはだ", "すばらしい", "ずひょう", "ずぶぬれ", "すぶり", "すふれ", "すべて", "すべる", "ずほう", "すぼん", "すまい", "すめし", "すもう", "すやき", "すらすら", "するめ", "すれちがう", "すろっと", "すわる", "すんぜん", "すんぽう", "せあぶら", "せいかつ", "せいげん", "せいじ", "せいよう", "せおう", "せかいかん", "せきにん", "せきむ", "せきゆ", "せきらんうん", "せけん", "せこう", "せすじ", "せたい", "せたけ", "せっかく", "せっきゃく", "ぜっく", "せっけん", "せっこつ", "せっさたくま", "せつぞく", "せつだん", "せつでん", "せっぱん", "せつび", "せつぶん", "せつめい", "せつりつ", "せなか", "せのび", "せはば", "せびろ", "せぼね", "せまい", "せまる", "せめる", "せもたれ", "せりふ", "ぜんあく", "せんい", "せんえい", "せんか", "せんきょ", "せんく", "せんげん", "ぜんご", "せんさい", "せんしゅ", "せんすい", "せんせい", "せんぞ", "せんたく", "せんちょう", "せんてい", "せんとう", "せんぬき", "せんねん", "せんぱい", "ぜんぶ", "ぜんぽう", "せんむ", "せんめんじょ", "せんもん", "せんやく", "せんゆう", "せんよう", "ぜんら", "ぜんりゃく", "せんれい", "せんろ", "そあく", "そいとげる", "そいね", "そうがんきょう", "そうき", "そうご", "そうしん", "そうだん", "そうなん", "そうび", "そうめん", "そうり", "そえもの", "そえん", "そがい", "そげき", "そこう", "そこそこ", "そざい", "そしな", "そせい", "そせん", "そそぐ", "そだてる", "そつう", "そつえん", "そっかん", "そつぎょう", "そっけつ", "そっこう", "そっせん", "そっと", "そとがわ", "そとづら", "そなえる", "そなた", "そふぼ", "そぼく", "そぼろ", "そまつ", "そまる", "そむく", "そむりえ", "そめる", "そもそも", "そよかぜ", "そらまめ", "そろう", "そんかい", "そんけい", "そんざい", "そんしつ", "そんぞく", "そんちょう", "ぞんび", "ぞんぶん", "そんみん", "たあい", "たいいん", "たいうん", "たいえき", "たいおう", "だいがく", "たいき", "たいぐう", "たいけん", "たいこ", "たいざい", "だいじょうぶ", "だいすき", "たいせつ", "たいそう", "だいたい", "たいちょう", "たいてい", "だいどころ", "たいない", "たいねつ", "たいのう", "たいはん", "だいひょう", "たいふう", "たいへん", "たいほ", "たいまつばな", "たいみんぐ", "たいむ", "たいめん", "たいやき", "たいよう", "たいら", "たいりょく", "たいる", "たいわん", "たうえ", "たえる", "たおす", "たおる", "たおれる", "たかい", "たかね", "たきび", "たくさん", "たこく", "たこやき", "たさい", "たしざん", "だじゃれ", "たすける", "たずさわる", "たそがれ", "たたかう", "たたく", "ただしい", "たたみ", "たちばな", "だっかい", "だっきゃく", "だっこ", "だっしゅつ", "だったい", "たてる", "たとえる", "たなばた", "たにん", "たぬき", "たのしみ", "たはつ", "たぶん", "たべる", "たぼう", "たまご", "たまる", "だむる", "ためいき", "ためす", "ためる", "たもつ", "たやすい", "たよる", "たらす", "たりきほんがん", "たりょう", "たりる", "たると", "たれる", "たれんと", "たろっと", "たわむれる", "だんあつ", "たんい", "たんおん", "たんか", "たんき", "たんけん", "たんご", "たんさん", "たんじょうび", "だんせい", "たんそく", "たんたい", "だんち", "たんてい", "たんとう", "だんな", "たんにん", "だんねつ", "たんのう", "たんぴん", "だんぼう", "たんまつ", "たんめい", "だんれつ", "だんろ", "だんわ", "ちあい", "ちあん", "ちいき", "ちいさい", "ちえん", "ちかい", "ちから", "ちきゅう", "ちきん", "ちけいず", "ちけん", "ちこく", "ちさい", "ちしき", "ちしりょう", "ちせい", "ちそう", "ちたい", "ちたん", "ちちおや", "ちつじょ", "ちてき", "ちてん", "ちぬき", "ちぬり", "ちのう", "ちひょう", "ちへいせん", "ちほう", "ちまた", "ちみつ", "ちみどろ", "ちめいど", "ちゃんこなべ", "ちゅうい", "ちゆりょく", "ちょうし", "ちょさくけん", "ちらし", "ちらみ", "ちりがみ", "ちりょう", "ちるど", "ちわわ", "ちんたい", "ちんもく", "ついか", "ついたち", "つうか", "つうじょう", "つうはん", "つうわ", "つかう", "つかれる", "つくね", "つくる", "つけね", "つける", "つごう", "つたえる", "つづく", "つつじ", "つつむ", "つとめる", "つながる", "つなみ", "つねづね", "つのる", "つぶす", "つまらない", "つまる", "つみき", "つめたい", "つもり", "つもる", "つよい", "つるぼ", "つるみく", "つわもの", "つわり", "てあし", "てあて", "てあみ", "ていおん", "ていか", "ていき", "ていけい", "ていこく", "ていさつ", "ていし", "ていせい", "ていたい", "ていど", "ていねい", "ていひょう", "ていへん", "ていぼう", "てうち", "ておくれ", "てきとう", "てくび", "でこぼこ", "てさぎょう", "てさげ", "てすり", "てそう", "てちがい", "てちょう", "てつがく", "てつづき", "でっぱ", "てつぼう", "てつや", "でぬかえ", "てぬき", "てぬぐい", "てのひら", "てはい", "てぶくろ", "てふだ", "てほどき", "てほん", "てまえ", "てまきずし", "てみじか", "てみやげ", "てらす", "てれび", "てわけ", "てわたし", "でんあつ", "てんいん", "てんかい", "てんき", "てんぐ", "てんけん", "てんごく", "てんさい", "てんし", "てんすう", "でんち", "てんてき", "てんとう", "てんない", "てんぷら", "てんぼうだい", "てんめつ", "てんらんかい", "でんりょく", "でんわ", "どあい", "といれ", "どうかん", "とうきゅう", "どうぐ", "とうし", "とうむぎ", "とおい", "とおか", "とおく", "とおす", "とおる", "とかい", "とかす", "ときおり", "ときどき", "とくい", "とくしゅう", "とくてん", "とくに", "とくべつ", "とけい", "とける", "とこや", "とさか", "としょかん", "とそう", "とたん", "とちゅう", "とっきゅう", "とっくん", "とつぜん", "とつにゅう", "とどける", "ととのえる", "とない", "となえる", "となり", "とのさま", "とばす", "どぶがわ", "とほう", "とまる", "とめる", "ともだち", "ともる", "どようび", "とらえる", "とんかつ", "どんぶり", "ないかく", "ないこう", "ないしょ", "ないす", "ないせん", "ないそう", "なおす", "ながい", "なくす", "なげる", "なこうど", "なさけ", "なたでここ", "なっとう", "なつやすみ", "ななおし", "なにごと", "なにもの", "なにわ", "なのか", "なふだ", "なまいき", "なまえ", "なまみ", "なみだ", "なめらか", "なめる", "なやむ", "ならう", "ならび", "ならぶ", "なれる", "なわとび", "なわばり", "にあう", "にいがた", "にうけ", "におい", "にかい", "にがて", "にきび", "にくしみ", "にくまん", "にげる", "にさんかたんそ", "にしき", "にせもの", "にちじょう", "にちようび", "にっか", "にっき", "にっけい", "にっこう", "にっさん", "にっしょく", "にっすう", "にっせき", "にってい", "になう", "にほん", "にまめ", "にもつ", "にやり", "にゅういん", "にりんしゃ", "にわとり", "にんい", "にんか", "にんき", "にんげん", "にんしき", "にんずう", "にんそう", "にんたい", "にんち", "にんてい", "にんにく", "にんぷ", "にんまり", "にんむ", "にんめい", "にんよう", "ぬいくぎ", "ぬかす", "ぬぐいとる", "ぬぐう", "ぬくもり", "ぬすむ", "ぬまえび", "ぬめり", "ぬらす", "ぬんちゃく", "ねあげ", "ねいき", "ねいる", "ねいろ", "ねぐせ", "ねくたい", "ねくら", "ねこぜ", "ねこむ", "ねさげ", "ねすごす", "ねそべる", "ねだん", "ねつい", "ねっしん", "ねつぞう", "ねったいぎょ", "ねぶそく", "ねふだ", "ねぼう", "ねほりはほり", "ねまき", "ねまわし", "ねみみ", "ねむい", "ねむたい", "ねもと", "ねらう", "ねわざ", "ねんいり", "ねんおし", "ねんかん", "ねんきん", "ねんぐ", "ねんざ", "ねんし", "ねんちゃく", "ねんど", "ねんぴ", "ねんぶつ", "ねんまつ", "ねんりょう", "ねんれい", "のいず", "のおづま", "のがす", "のきなみ", "のこぎり", "のこす", "のこる", "のせる", "のぞく", "のぞむ", "のたまう", "のちほど", "のっく", "のばす", "のはら", "のべる", "のぼる", "のみもの", "のやま", "のらいぬ", "のらねこ", "のりもの", "のりゆき", "のれん", "のんき", "ばあい", "はあく", "ばあさん", "ばいか", "ばいく", "はいけん", "はいご", "はいしん", "はいすい", "はいせん", "はいそう", "はいち", "ばいばい", "はいれつ", "はえる", "はおる", "はかい", "ばかり", "はかる", "はくしゅ", "はけん", "はこぶ", "はさみ", "はさん", "はしご", "ばしょ", "はしる", "はせる", "ぱそこん", "はそん", "はたん", "はちみつ", "はつおん", "はっかく", "はづき", "はっきり", "はっくつ", "はっけん", "はっこう", "はっさん", "はっしん", "はったつ", "はっちゅう", "はってん", "はっぴょう", "はっぽう", "はなす", "はなび", "はにかむ", "はぶらし", "はみがき", "はむかう", "はめつ", "はやい", "はやし", "はらう", "はろうぃん", "はわい", "はんい", "はんえい", "はんおん", "はんかく", "はんきょう", "ばんぐみ", "はんこ", "はんしゃ", "はんすう", "はんだん", "ぱんち", "ぱんつ", "はんてい", "はんとし", "はんのう", "はんぱ", "はんぶん", "はんぺん", "はんぼうき", "はんめい", "はんらん", "はんろん", "ひいき", "ひうん", "ひえる", "ひかく", "ひかり", "ひかる", "ひかん", "ひくい", "ひけつ", "ひこうき", "ひこく", "ひさい", "ひさしぶり", "ひさん", "びじゅつかん", "ひしょ", "ひそか", "ひそむ", "ひたむき", "ひだり", "ひたる", "ひつぎ", "ひっこし", "ひっし", "ひつじゅひん", "ひっす", "ひつぜん", "ぴったり", "ぴっちり", "ひつよう", "ひてい", "ひとごみ", "ひなまつり", "ひなん", "ひねる", "ひはん", "ひびく", "ひひょう", "ひほう", "ひまわり", "ひまん", "ひみつ", "ひめい", "ひめじし", "ひやけ", "ひやす", "ひよう", "びょうき", "ひらがな", "ひらく", "ひりつ", "ひりょう", "ひるま", "ひるやすみ", "ひれい", "ひろい", "ひろう", "ひろき", "ひろゆき", "ひんかく", "ひんけつ", "ひんこん", "ひんしゅ", "ひんそう", "ぴんち", "ひんぱん", "びんぼう", "ふあん", "ふいうち", "ふうけい", "ふうせん", "ぷうたろう", "ふうとう", "ふうふ", "ふえる", "ふおん", "ふかい", "ふきん", "ふくざつ", "ふくぶくろ", "ふこう", "ふさい", "ふしぎ", "ふじみ", "ふすま", "ふせい", "ふせぐ", "ふそく", "ぶたにく", "ふたん", "ふちょう", "ふつう", "ふつか", "ふっかつ", "ふっき", "ふっこく", "ぶどう", "ふとる", "ふとん", "ふのう", "ふはい", "ふひょう", "ふへん", "ふまん", "ふみん", "ふめつ", "ふめん", "ふよう", "ふりこ", "ふりる", "ふるい", "ふんいき", "ぶんがく", "ぶんぐ", "ふんしつ", "ぶんせき", "ふんそう", "ぶんぽう", "へいあん", "へいおん", "へいがい", "へいき", "へいげん", "へいこう", "へいさ", "へいしゃ", "へいせつ", "へいそ", "へいたく", "へいてん", "へいねつ", "へいわ", "へきが", "へこむ", "べにいろ", "べにしょうが", "へらす", "へんかん", "べんきょう", "べんごし", "へんさい", "へんたい", "べんり", "ほあん", "ほいく", "ぼうぎょ", "ほうこく", "ほうそう", "ほうほう", "ほうもん", "ほうりつ", "ほえる", "ほおん", "ほかん", "ほきょう", "ぼきん", "ほくろ", "ほけつ", "ほけん", "ほこう", "ほこる", "ほしい", "ほしつ", "ほしゅ", "ほしょう", "ほせい", "ほそい", "ほそく", "ほたて", "ほたる", "ぽちぶくろ", "ほっきょく", "ほっさ", "ほったん", "ほとんど", "ほめる", "ほんい", "ほんき", "ほんけ", "ほんしつ", "ほんやく", "まいにち", "まかい", "まかせる", "まがる", "まける", "まこと", "まさつ", "まじめ", "ますく", "まぜる", "まつり", "まとめ", "まなぶ", "まぬけ", "まねく", "まほう", "まもる", "まゆげ", "まよう", "まろやか", "まわす", "まわり", "まわる", "まんが", "まんきつ", "まんぞく", "まんなか", "みいら", "みうち", "みえる", "みがく", "みかた", "みかん", "みけん", "みこん", "みじかい", "みすい", "みすえる", "みせる", "みっか", "みつかる", "みつける", "みてい", "みとめる", "みなと", "みなみかさい", "みねらる", "みのう", "みのがす", "みほん", "みもと", "みやげ", "みらい", "みりょく", "みわく", "みんか", "みんぞく", "むいか", "むえき", "むえん", "むかい", "むかう", "むかえ", "むかし", "むぎちゃ", "むける", "むげん", "むさぼる", "むしあつい", "むしば", "むじゅん", "むしろ", "むすう", "むすこ", "むすぶ", "むすめ", "むせる", "むせん", "むちゅう", "むなしい", "むのう", "むやみ", "むよう", "むらさき", "むりょう", "むろん", "めいあん", "めいうん", "めいえん", "めいかく", "めいきょく", "めいさい", "めいし", "めいそう", "めいぶつ", "めいれい", "めいわく", "めぐまれる", "めざす", "めした", "めずらしい", "めだつ", "めまい", "めやす", "めんきょ", "めんせき", "めんどう", "もうしあげる", "もうどうけん", "もえる", "もくし", "もくてき", "もくようび", "もちろん", "もどる", "もらう", "もんく", "もんだい", "やおや", "やける", "やさい", "やさしい", "やすい", "やすたろう", "やすみ", "やせる", "やそう", "やたい", "やちん", "やっと", "やっぱり", "やぶる", "やめる", "ややこしい", "やよい", "やわらかい", "ゆうき", "ゆうびんきょく", "ゆうべ", "ゆうめい", "ゆけつ", "ゆしゅつ", "ゆせん", "ゆそう", "ゆたか", "ゆちゃく", "ゆでる", "ゆにゅう", "ゆびわ", "ゆらい", "ゆれる", "ようい", "ようか", "ようきゅう", "ようじ", "ようす", "ようちえん", "よかぜ", "よかん", "よきん", "よくせい", "よくぼう", "よけい", "よごれる", "よさん", "よしゅう", "よそう", "よそく", "よっか", "よてい", "よどがわく", "よねつ", "よやく", "よゆう", "よろこぶ", "よろしい", "らいう", "らくがき", "らくご", "らくさつ", "らくだ", "らしんばん", "らせん", "らぞく", "らたい", "らっか", "られつ", "りえき", "りかい", "りきさく", "りきせつ", "りくぐん", "りくつ", "りけん", "りこう", "りせい", "りそう", "りそく", "りてん", "りねん", "りゆう", "りゅうがく", "りよう", "りょうり", "りょかん", "りょくちゃ", "りょこう", "りりく", "りれき", "りろん", "りんご", "るいけい", "るいさい", "るいじ", "るいせき", "るすばん", "るりがわら", "れいかん", "れいぎ", "れいせい", "れいぞうこ", "れいとう", "れいぼう", "れきし", "れきだい", "れんあい", "れんけい", "れんこん", "れんさい", "れんしゅう", "れんぞく", "れんらく", "ろうか", "ろうご", "ろうじん", "ろうそく", "ろくが", "ろこつ", "ろじうら", "ろしゅつ", "ろせん", "ろてん", "ろめん", "ろれつ", "ろんぎ", "ろんぱ", "ろんぶん", "ろんり", "わかす", "わかめ", "わかやま", "わかれる", "わしつ", "わじまし", "わすれもの", "わらう", "われる" ] },{}],81:[function(require,module,exports){ module.exports=[ "가격", "가끔", "가난", "가능", "가득", "가르침", "가뭄", "가방", "가상", "가슴", "가운데", "가을", "가이드", "가입", "가장", "가정", "가족", "가죽", "각오", "각자", "간격", "간부", "간섭", "간장", "간접", "간판", "갈등", "갈비", "갈색", "갈증", "감각", "감기", "감소", "감수성", "감자", "감정", "갑자기", "강남", "강당", "강도", "강력히", "강변", "강북", "강사", "강수량", "강아지", "강원도", "강의", "강제", "강조", "같이", "개구리", "개나리", "개방", "개별", "개선", "개성", "개인", "객관적", "거실", "거액", "거울", "거짓", "거품", "걱정", "건강", "건물", "건설", "건조", "건축", "걸음", "검사", "검토", "게시판", "게임", "겨울", "견해", "결과", "결국", "결론", "결석", "결승", "결심", "결정", "결혼", "경계", "경고", "경기", "경력", "경복궁", "경비", "경상도", "경영", "경우", "경쟁", "경제", "경주", "경찰", "경치", "경향", "경험", "계곡", "계단", "계란", "계산", "계속", "계약", "계절", "계층", "계획", "고객", "고구려", "고궁", "고급", "고등학생", "고무신", "고민", "고양이", "고장", "고전", "고집", "고춧가루", "고통", "고향", "곡식", "골목", "골짜기", "골프", "공간", "공개", "공격", "공군", "공급", "공기", "공동", "공무원", "공부", "공사", "공식", "공업", "공연", "공원", "공장", "공짜", "공책", "공통", "공포", "공항", "공휴일", "과목", "과일", "과장", "과정", "과학", "관객", "관계", "관광", "관념", "관람", "관련", "관리", "관습", "관심", "관점", "관찰", "광경", "광고", "광장", "광주", "괴로움", "굉장히", "교과서", "교문", "교복", "교실", "교양", "교육", "교장", "교직", "교통", "교환", "교훈", "구경", "구름", "구멍", "구별", "구분", "구석", "구성", "구속", "구역", "구입", "구청", "구체적", "국가", "국기", "국내", "국립", "국물", "국민", "국수", "국어", "국왕", "국적", "국제", "국회", "군대", "군사", "군인", "궁극적", "권리", "권위", "권투", "귀국", "귀신", "규정", "규칙", "균형", "그날", "그냥", "그늘", "그러나", "그룹", "그릇", "그림", "그제서야", "그토록", "극복", "극히", "근거", "근교", "근래", "근로", "근무", "근본", "근원", "근육", "근처", "글씨", "글자", "금강산", "금고", "금년", "금메달", "금액", "금연", "금요일", "금지", "긍정적", "기간", "기관", "기념", "기능", "기독교", "기둥", "기록", "기름", "기법", "기본", "기분", "기쁨", "기숙사", "기술", "기억", "기업", "기온", "기운", "기원", "기적", "기준", "기침", "기혼", "기획", "긴급", "긴장", "길이", "김밥", "김치", "김포공항", "깍두기", "깜빡", "깨달음", "깨소금", "껍질", "꼭대기", "꽃잎", "나들이", "나란히", "나머지", "나물", "나침반", "나흘", "낙엽", "난방", "날개", "날씨", "날짜", "남녀", "남대문", "남매", "남산", "남자", "남편", "남학생", "낭비", "낱말", "내년", "내용", "내일", "냄비", "냄새", "냇물", "냉동", "냉면", "냉방", "냉장고", "넥타이", "넷째", "노동", "노란색", "노력", "노인", "녹음", "녹차", "녹화", "논리", "논문", "논쟁", "놀이", "농구", "농담", "농민", "농부", "농업", "농장", "농촌", "높이", "눈동자", "눈물", "눈썹", "뉴욕", "느낌", "늑대", "능동적", "능력", "다방", "다양성", "다음", "다이어트", "다행", "단계", "단골", "단독", "단맛", "단순", "단어", "단위", "단점", "단체", "단추", "단편", "단풍", "달걀", "달러", "달력", "달리", "닭고기", "담당", "담배", "담요", "담임", "답변", "답장", "당근", "당분간", "당연히", "당장", "대규모", "대낮", "대단히", "대답", "대도시", "대략", "대량", "대륙", "대문", "대부분", "대신", "대응", "대장", "대전", "대접", "대중", "대책", "대출", "대충", "대통령", "대학", "대한민국", "대합실", "대형", "덩어리", "데이트", "도대체", "도덕", "도둑", "도망", "도서관", "도심", "도움", "도입", "도자기", "도저히", "도전", "도중", "도착", "독감", "독립", "독서", "독일", "독창적", "동화책", "뒷모습", "뒷산", "딸아이", "마누라", "마늘", "마당", "마라톤", "마련", "마무리", "마사지", "마약", "마요네즈", "마을", "마음", "마이크", "마중", "마지막", "마찬가지", "마찰", "마흔", "막걸리", "막내", "막상", "만남", "만두", "만세", "만약", "만일", "만점", "만족", "만화", "많이", "말기", "말씀", "말투", "맘대로", "망원경", "매년", "매달", "매력", "매번", "매스컴", "매일", "매장", "맥주", "먹이", "먼저", "먼지", "멀리", "메일", "며느리", "며칠", "면담", "멸치", "명단", "명령", "명예", "명의", "명절", "명칭", "명함", "모금", "모니터", "모델", "모든", "모범", "모습", "모양", "모임", "모조리", "모집", "모퉁이", "목걸이", "목록", "목사", "목소리", "목숨", "목적", "목표", "몰래", "몸매", "몸무게", "몸살", "몸속", "몸짓", "몸통", "몹시", "무관심", "무궁화", "무더위", "무덤", "무릎", "무슨", "무엇", "무역", "무용", "무조건", "무지개", "무척", "문구", "문득", "문법", "문서", "문제", "문학", "문화", "물가", "물건", "물결", "물고기", "물론", "물리학", "물음", "물질", "물체", "미국", "미디어", "미사일", "미술", "미역", "미용실", "미움", "미인", "미팅", "미혼", "민간", "민족", "민주", "믿음", "밀가루", "밀리미터", "밑바닥", "바가지", "바구니", "바나나", "바늘", "바닥", "바닷가", "바람", "바이러스", "바탕", "박물관", "박사", "박수", "반대", "반드시", "반말", "반발", "반성", "반응", "반장", "반죽", "반지", "반찬", "받침", "발가락", "발걸음", "발견", "발달", "발레", "발목", "발바닥", "발생", "발음", "발자국", "발전", "발톱", "발표", "밤하늘", "밥그릇", "밥맛", "밥상", "밥솥", "방금", "방면", "방문", "방바닥", "방법", "방송", "방식", "방안", "방울", "방지", "방학", "방해", "방향", "배경", "배꼽", "배달", "배드민턴", "백두산", "백색", "백성", "백인", "백제", "백화점", "버릇", "버섯", "버튼", "번개", "번역", "번지", "번호", "벌금", "벌레", "벌써", "범위", "범인", "범죄", "법률", "법원", "법적", "법칙", "베이징", "벨트", "변경", "변동", "변명", "변신", "변호사", "변화", "별도", "별명", "별일", "병실", "병아리", "병원", "보관", "보너스", "보라색", "보람", "보름", "보상", "보안", "보자기", "보장", "보전", "보존", "보통", "보편적", "보험", "복도", "복사", "복숭아", "복습", "볶음", "본격적", "본래", "본부", "본사", "본성", "본인", "본질", "볼펜", "봉사", "봉지", "봉투", "부근", "부끄러움", "부담", "부동산", "부문", "부분", "부산", "부상", "부엌", "부인", "부작용", "부장", "부정", "부족", "부지런히", "부친", "부탁", "부품", "부회장", "북부", "북한", "분노", "분량", "분리", "분명", "분석", "분야", "분위기", "분필", "분홍색", "불고기", "불과", "불교", "불꽃", "불만", "불법", "불빛", "불안", "불이익", "불행", "브랜드", "비극", "비난", "비닐", "비둘기", "비디오", "비로소", "비만", "비명", "비밀", "비바람", "비빔밥", "비상", "비용", "비율", "비중", "비타민", "비판", "빌딩", "빗물", "빗방울", "빗줄기", "빛깔", "빨간색", "빨래", "빨리", "사건", "사계절", "사나이", "사냥", "사람", "사랑", "사립", "사모님", "사물", "사방", "사상", "사생활", "사설", "사슴", "사실", "사업", "사용", "사월", "사장", "사전", "사진", "사촌", "사춘기", "사탕", "사투리", "사흘", "산길", "산부인과", "산업", "산책", "살림", "살인", "살짝", "삼계탕", "삼국", "삼십", "삼월", "삼촌", "상관", "상금", "상대", "상류", "상반기", "상상", "상식", "상업", "상인", "상자", "상점", "상처", "상추", "상태", "상표", "상품", "상황", "새벽", "색깔", "색연필", "생각", "생명", "생물", "생방송", "생산", "생선", "생신", "생일", "생활", "서랍", "서른", "서명", "서민", "서비스", "서양", "서울", "서적", "서점", "서쪽", "서클", "석사", "석유", "선거", "선물", "선배", "선생", "선수", "선원", "선장", "선전", "선택", "선풍기", "설거지", "설날", "설렁탕", "설명", "설문", "설사", "설악산", "설치", "설탕", "섭씨", "성공", "성당", "성명", "성별", "성인", "성장", "성적", "성질", "성함", "세금", "세미나", "세상", "세월", "세종대왕", "세탁", "센터", "센티미터", "셋째", "소규모", "소극적", "소금", "소나기", "소년", "소득", "소망", "소문", "소설", "소속", "소아과", "소용", "소원", "소음", "소중히", "소지품", "소질", "소풍", "소형", "속담", "속도", "속옷", "손가락", "손길", "손녀", "손님", "손등", "손목", "손뼉", "손실", "손질", "손톱", "손해", "솔직히", "솜씨", "송아지", "송이", "송편", "쇠고기", "쇼핑", "수건", "수년", "수단", "수돗물", "수동적", "수면", "수명", "수박", "수상", "수석", "수술", "수시로", "수업", "수염", "수영", "수입", "수준", "수집", "수출", "수컷", "수필", "수학", "수험생", "수화기", "숙녀", "숙소", "숙제", "순간", "순서", "순수", "순식간", "순위", "숟가락", "술병", "술집", "숫자", "스님", "스물", "스스로", "스승", "스웨터", "스위치", "스케이트", "스튜디오", "스트레스", "스포츠", "슬쩍", "슬픔", "습관", "습기", "승객", "승리", "승부", "승용차", "승진", "시각", "시간", "시골", "시금치", "시나리오", "시댁", "시리즈", "시멘트", "시민", "시부모", "시선", "시설", "시스템", "시아버지", "시어머니", "시월", "시인", "시일", "시작", "시장", "시절", "시점", "시중", "시즌", "시집", "시청", "시합", "시험", "식구", "식기", "식당", "식량", "식료품", "식물", "식빵", "식사", "식생활", "식초", "식탁", "식품", "신고", "신규", "신념", "신문", "신발", "신비", "신사", "신세", "신용", "신제품", "신청", "신체", "신화", "실감", "실내", "실력", "실례", "실망", "실수", "실습", "실시", "실장", "실정", "실질적", "실천", "실체", "실컷", "실태", "실패", "실험", "실현", "심리", "심부름", "심사", "심장", "심정", "심판", "쌍둥이", "씨름", "씨앗", "아가씨", "아나운서", "아드님", "아들", "아쉬움", "아스팔트", "아시아", "아울러", "아저씨", "아줌마", "아직", "아침", "아파트", "아프리카", "아픔", "아홉", "아흔", "악기", "악몽", "악수", "안개", "안경", "안과", "안내", "안녕", "안동", "안방", "안부", "안주", "알루미늄", "알코올", "암시", "암컷", "압력", "앞날", "앞문", "애인", "애정", "액수", "앨범", "야간", "야단", "야옹", "약간", "약국", "약속", "약수", "약점", "약품", "약혼녀", "양념", "양력", "양말", "양배추", "양주", "양파", "어둠", "어려움", "어른", "어젯밤", "어쨌든", "어쩌다가", "어쩐지", "언니", "언덕", "언론", "언어", "얼굴", "얼른", "얼음", "얼핏", "엄마", "업무", "업종", "업체", "엉덩이", "엉망", "엉터리", "엊그제", "에너지", "에어컨", "엔진", "여건", "여고생", "여관", "여군", "여권", "여대생", "여덟", "여동생", "여든", "여론", "여름", "여섯", "여성", "여왕", "여인", "여전히", "여직원", "여학생", "여행", "역사", "역시", "역할", "연결", "연구", "연극", "연기", "연락", "연설", "연세", "연속", "연습", "연애", "연예인", "연인", "연장", "연주", "연출", "연필", "연합", "연휴", "열기", "열매", "열쇠", "열심히", "열정", "열차", "열흘", "염려", "엽서", "영국", "영남", "영상", "영양", "영역", "영웅", "영원히", "영하", "영향", "영혼", "영화", "옆구리", "옆방", "옆집", "예감", "예금", "예방", "예산", "예상", "예선", "예술", "예습", "예식장", "예약", "예전", "예절", "예정", "예컨대", "옛날", "오늘", "오락", "오랫동안", "오렌지", "오로지", "오른발", "오븐", "오십", "오염", "오월", "오전", "오직", "오징어", "오페라", "오피스텔", "오히려", "옥상", "옥수수", "온갖", "온라인", "온몸", "온종일", "온통", "올가을", "올림픽", "올해", "옷차림", "와이셔츠", "와인", "완성", "완전", "왕비", "왕자", "왜냐하면", "왠지", "외갓집", "외국", "외로움", "외삼촌", "외출", "외침", "외할머니", "왼발", "왼손", "왼쪽", "요금", "요일", "요즘", "요청", "용기", "용서", "용어", "우산", "우선", "우승", "우연히", "우정", "우체국", "우편", "운동", "운명", "운반", "운전", "운행", "울산", "울음", "움직임", "웃어른", "웃음", "워낙", "원고", "원래", "원서", "원숭이", "원인", "원장", "원피스", "월급", "월드컵", "월세", "월요일", "웨이터", "위반", "위법", "위성", "위원", "위험", "위협", "윗사람", "유난히", "유럽", "유명", "유물", "유산", "유적", "유치원", "유학", "유행", "유형", "육군", "육상", "육십", "육체", "은행", "음력", "음료", "음반", "음성", "음식", "음악", "음주", "의견", "의논", "의문", "의복", "의식", "의심", "의외로", "의욕", "의원", "의학", "이것", "이곳", "이념", "이놈", "이달", "이대로", "이동", "이렇게", "이력서", "이론적", "이름", "이민", "이발소", "이별", "이불", "이빨", "이상", "이성", "이슬", "이야기", "이용", "이웃", "이월", "이윽고", "이익", "이전", "이중", "이튿날", "이틀", "이혼", "인간", "인격", "인공", "인구", "인근", "인기", "인도", "인류", "인물", "인생", "인쇄", "인연", "인원", "인재", "인종", "인천", "인체", "인터넷", "인하", "인형", "일곱", "일기", "일단", "일대", "일등", "일반", "일본", "일부", "일상", "일생", "일손", "일요일", "일월", "일정", "일종", "일주일", "일찍", "일체", "일치", "일행", "일회용", "임금", "임무", "입대", "입력", "입맛", "입사", "입술", "입시", "입원", "입장", "입학", "자가용", "자격", "자극", "자동", "자랑", "자부심", "자식", "자신", "자연", "자원", "자율", "자전거", "자정", "자존심", "자판", "작가", "작년", "작성", "작업", "작용", "작은딸", "작품", "잔디", "잔뜩", "잔치", "잘못", "잠깐", "잠수함", "잠시", "잠옷", "잠자리", "잡지", "장관", "장군", "장기간", "장래", "장례", "장르", "장마", "장면", "장모", "장미", "장비", "장사", "장소", "장식", "장애인", "장인", "장점", "장차", "장학금", "재능", "재빨리", "재산", "재생", "재작년", "재정", "재채기", "재판", "재학", "재활용", "저것", "저고리", "저곳", "저녁", "저런", "저렇게", "저번", "저울", "저절로", "저축", "적극", "적당히", "적성", "적용", "적응", "전개", "전공", "전기", "전달", "전라도", "전망", "전문", "전반", "전부", "전세", "전시", "전용", "전자", "전쟁", "전주", "전철", "전체", "전통", "전혀", "전후", "절대", "절망", "절반", "절약", "절차", "점검", "점수", "점심", "점원", "점점", "점차", "접근", "접시", "접촉", "젓가락", "정거장", "정도", "정류장", "정리", "정말", "정면", "정문", "정반대", "정보", "정부", "정비", "정상", "정성", "정오", "정원", "정장", "정지", "정치", "정확히", "제공", "제과점", "제대로", "제목", "제발", "제법", "제삿날", "제안", "제일", "제작", "제주도", "제출", "제품", "제한", "조각", "조건", "조금", "조깅", "조명", "조미료", "조상", "조선", "조용히", "조절", "조정", "조직", "존댓말", "존재", "졸업", "졸음", "종교", "종로", "종류", "종소리", "종업원", "종종", "종합", "좌석", "죄인", "주관적", "주름", "주말", "주머니", "주먹", "주문", "주민", "주방", "주변", "주식", "주인", "주일", "주장", "주전자", "주택", "준비", "줄거리", "줄기", "줄무늬", "중간", "중계방송", "중국", "중년", "중단", "중독", "중반", "중부", "중세", "중소기업", "중순", "중앙", "중요", "중학교", "즉석", "즉시", "즐거움", "증가", "증거", "증권", "증상", "증세", "지각", "지갑", "지경", "지극히", "지금", "지급", "지능", "지름길", "지리산", "지방", "지붕", "지식", "지역", "지우개", "지원", "지적", "지점", "지진", "지출", "직선", "직업", "직원", "직장", "진급", "진동", "진로", "진료", "진리", "진짜", "진찰", "진출", "진통", "진행", "질문", "질병", "질서", "짐작", "집단", "집안", "집중", "짜증", "찌꺼기", "차남", "차라리", "차량", "차림", "차별", "차선", "차츰", "착각", "찬물", "찬성", "참가", "참기름", "참새", "참석", "참여", "참외", "참조", "찻잔", "창가", "창고", "창구", "창문", "창밖", "창작", "창조", "채널", "채점", "책가방", "책방", "책상", "책임", "챔피언", "처벌", "처음", "천국", "천둥", "천장", "천재", "천천히", "철도", "철저히", "철학", "첫날", "첫째", "청년", "청바지", "청소", "청춘", "체계", "체력", "체온", "체육", "체중", "체험", "초등학생", "초반", "초밥", "초상화", "초순", "초여름", "초원", "초저녁", "초점", "초청", "초콜릿", "촛불", "총각", "총리", "총장", "촬영", "최근", "최상", "최선", "최신", "최악", "최종", "추석", "추억", "추진", "추천", "추측", "축구", "축소", "축제", "축하", "출근", "출발", "출산", "출신", "출연", "출입", "출장", "출판", "충격", "충고", "충돌", "충분히", "충청도", "취업", "취직", "취향", "치약", "친구", "친척", "칠십", "칠월", "칠판", "침대", "침묵", "침실", "칫솔", "칭찬", "카메라", "카운터", "칼국수", "캐릭터", "캠퍼스", "캠페인", "커튼", "컨디션", "컬러", "컴퓨터", "코끼리", "코미디", "콘서트", "콜라", "콤플렉스", "콩나물", "쾌감", "쿠데타", "크림", "큰길", "큰딸", "큰소리", "큰아들", "큰어머니", "큰일", "큰절", "클래식", "클럽", "킬로", "타입", "타자기", "탁구", "탁자", "탄생", "태권도", "태양", "태풍", "택시", "탤런트", "터널", "터미널", "테니스", "테스트", "테이블", "텔레비전", "토론", "토마토", "토요일", "통계", "통과", "통로", "통신", "통역", "통일", "통장", "통제", "통증", "통합", "통화", "퇴근", "퇴원", "퇴직금", "튀김", "트럭", "특급", "특별", "특성", "특수", "특징", "특히", "튼튼히", "티셔츠", "파란색", "파일", "파출소", "판결", "판단", "판매", "판사", "팔십", "팔월", "팝송", "패션", "팩스", "팩시밀리", "팬티", "퍼센트", "페인트", "편견", "편의", "편지", "편히", "평가", "평균", "평생", "평소", "평양", "평일", "평화", "포스터", "포인트", "포장", "포함", "표면", "표정", "표준", "표현", "품목", "품질", "풍경", "풍속", "풍습", "프랑스", "프린터", "플라스틱", "피곤", "피망", "피아노", "필름", "필수", "필요", "필자", "필통", "핑계", "하느님", "하늘", "하드웨어", "하룻밤", "하반기", "하숙집", "하순", "하여튼", "하지만", "하천", "하품", "하필", "학과", "학교", "학급", "학기", "학년", "학력", "학번", "학부모", "학비", "학생", "학술", "학습", "학용품", "학원", "학위", "학자", "학점", "한계", "한글", "한꺼번에", "한낮", "한눈", "한동안", "한때", "한라산", "한마디", "한문", "한번", "한복", "한식", "한여름", "한쪽", "할머니", "할아버지", "할인", "함께", "함부로", "합격", "합리적", "항공", "항구", "항상", "항의", "해결", "해군", "해답", "해당", "해물", "해석", "해설", "해수욕장", "해안", "핵심", "핸드백", "햄버거", "햇볕", "햇살", "행동", "행복", "행사", "행운", "행위", "향기", "향상", "향수", "허락", "허용", "헬기", "현관", "현금", "현대", "현상", "현실", "현장", "현재", "현지", "혈액", "협력", "형부", "형사", "형수", "형식", "형제", "형태", "형편", "혜택", "호기심", "호남", "호랑이", "호박", "호텔", "호흡", "혹시", "홀로", "홈페이지", "홍보", "홍수", "홍차", "화면", "화분", "화살", "화요일", "화장", "화학", "확보", "확인", "확장", "확정", "환갑", "환경", "환영", "환율", "환자", "활기", "활동", "활발히", "활용", "활짝", "회견", "회관", "회복", "회색", "회원", "회장", "회전", "횟수", "횡단보도", "효율적", "후반", "후춧가루", "훈련", "훨씬", "휴식", "휴일", "흉내", "흐름", "흑백", "흑인", "흔적", "흔히", "흥미", "흥분", "희곡", "희망", "희생", "흰색", "힘껏" ] },{}],82:[function(require,module,exports){ module.exports=[ "ábaco", "abdomen", "abeja", "abierto", "abogado", "abono", "aborto", "abrazo", "abrir", "abuelo", "abuso", "acabar", "academia", "acceso", "acción", "aceite", "acelga", "acento", "aceptar", "ácido", "aclarar", "acné", "acoger", "acoso", "activo", "acto", "actriz", "actuar", "acudir", "acuerdo", "acusar", "adicto", "admitir", "adoptar", "adorno", "aduana", "adulto", "aéreo", "afectar", "afición", "afinar", "afirmar", "ágil", "agitar", "agonía", "agosto", "agotar", "agregar", "agrio", "agua", "agudo", "águila", "aguja", "ahogo", "ahorro", "aire", "aislar", "ajedrez", "ajeno", "ajuste", "alacrán", "alambre", "alarma", "alba", "álbum", "alcalde", "aldea", "alegre", "alejar", "alerta", "aleta", "alfiler", "alga", "algodón", "aliado", "aliento", "alivio", "alma", "almeja", "almíbar", "altar", "alteza", "altivo", "alto", "altura", "alumno", "alzar", "amable", "amante", "amapola", "amargo", "amasar", "ámbar", "ámbito", "ameno", "amigo", "amistad", "amor", "amparo", "amplio", "ancho", "anciano", "ancla", "andar", "andén", "anemia", "ángulo", "anillo", "ánimo", "anís", "anotar", "antena", "antiguo", "antojo", "anual", "anular", "anuncio", "añadir", "añejo", "año", "apagar", "aparato", "apetito", "apio", "aplicar", "apodo", "aporte", "apoyo", "aprender", "aprobar", "apuesta", "apuro", "arado", "araña", "arar", "árbitro", "árbol", "arbusto", "archivo", "arco", "arder", "ardilla", "arduo", "área", "árido", "aries", "armonía", "arnés", "aroma", "arpa", "arpón", "arreglo", "arroz", "arruga", "arte", "artista", "asa", "asado", "asalto", "ascenso", "asegurar", "aseo", "asesor", "asiento", "asilo", "asistir", "asno", "asombro", "áspero", "astilla", "astro", "astuto", "asumir", "asunto", "atajo", "ataque", "atar", "atento", "ateo", "ático", "atleta", "átomo", "atraer", "atroz", "atún", "audaz", "audio", "auge", "aula", "aumento", "ausente", "autor", "aval", "avance", "avaro", "ave", "avellana", "avena", "avestruz", "avión", "aviso", "ayer", "ayuda", "ayuno", "azafrán", "azar", "azote", "azúcar", "azufre", "azul", "baba", "babor", "bache", "bahía", "baile", "bajar", "balanza", "balcón", "balde", "bambú", "banco", "banda", "baño", "barba", "barco", "barniz", "barro", "báscula", "bastón", "basura", "batalla", "batería", "batir", "batuta", "baúl", "bazar", "bebé", "bebida", "bello", "besar", "beso", "bestia", "bicho", "bien", "bingo", "blanco", "bloque", "blusa", "boa", "bobina", "bobo", "boca", "bocina", "boda", "bodega", "boina", "bola", "bolero", "bolsa", "bomba", "bondad", "bonito", "bono", "bonsái", "borde", "borrar", "bosque", "bote", "botín", "bóveda", "bozal", "bravo", "brazo", "brecha", "breve", "brillo", "brinco", "brisa", "broca", "broma", "bronce", "brote", "bruja", "brusco", "bruto", "buceo", "bucle", "bueno", "buey", "bufanda", "bufón", "búho", "buitre", "bulto", "burbuja", "burla", "burro", "buscar", "butaca", "buzón", "caballo", "cabeza", "cabina", "cabra", "cacao", "cadáver", "cadena", "caer", "café", "caída", "caimán", "caja", "cajón", "cal", "calamar", "calcio", "caldo", "calidad", "calle", "calma", "calor", "calvo", "cama", "cambio", "camello", "camino", "campo", "cáncer", "candil", "canela", "canguro", "canica", "canto", "caña", "cañón", "caoba", "caos", "capaz", "capitán", "capote", "captar", "capucha", "cara", "carbón", "cárcel", "careta", "carga", "cariño", "carne", "carpeta", "carro", "carta", "casa", "casco", "casero", "caspa", "castor", "catorce", "catre", "caudal", "causa", "cazo", "cebolla", "ceder", "cedro", "celda", "célebre", "celoso", "célula", "cemento", "ceniza", "centro", "cerca", "cerdo", "cereza", "cero", "cerrar", "certeza", "césped", "cetro", "chacal", "chaleco", "champú", "chancla", "chapa", "charla", "chico", "chiste", "chivo", "choque", "choza", "chuleta", "chupar", "ciclón", "ciego", "cielo", "cien", "cierto", "cifra", "cigarro", "cima", "cinco", "cine", "cinta", "ciprés", "circo", "ciruela", "cisne", "cita", "ciudad", "clamor", "clan", "claro", "clase", "clave", "cliente", "clima", "clínica", "cobre", "cocción", "cochino", "cocina", "coco", "código", "codo", "cofre", "coger", "cohete", "cojín", "cojo", "cola", "colcha", "colegio", "colgar", "colina", "collar", "colmo", "columna", "combate", "comer", "comida", "cómodo", "compra", "conde", "conejo", "conga", "conocer", "consejo", "contar", "copa", "copia", "corazón", "corbata", "corcho", "cordón", "corona", "correr", "coser", "cosmos", "costa", "cráneo", "cráter", "crear", "crecer", "creído", "crema", "cría", "crimen", "cripta", "crisis", "cromo", "crónica", "croqueta", "crudo", "cruz", "cuadro", "cuarto", "cuatro", "cubo", "cubrir", "cuchara", "cuello", "cuento", "cuerda", "cuesta", "cueva", "cuidar", "culebra", "culpa", "culto", "cumbre", "cumplir", "cuna", "cuneta", "cuota", "cupón", "cúpula", "curar", "curioso", "curso", "curva", "cutis", "dama", "danza", "dar", "dardo", "dátil", "deber", "débil", "década", "decir", "dedo", "defensa", "definir", "dejar", "delfín", "delgado", "delito", "demora", "denso", "dental", "deporte", "derecho", "derrota", "desayuno", "deseo", "desfile", "desnudo", "destino", "desvío", "detalle", "detener", "deuda", "día", "diablo", "diadema", "diamante", "diana", "diario", "dibujo", "dictar", "diente", "dieta", "diez", "difícil", "digno", "dilema", "diluir", "dinero", "directo", "dirigir", "disco", "diseño", "disfraz", "diva", "divino", "doble", "doce", "dolor", "domingo", "don", "donar", "dorado", "dormir", "dorso", "dos", "dosis", "dragón", "droga", "ducha", "duda", "duelo", "dueño", "dulce", "dúo", "duque", "durar", "dureza", "duro", "ébano", "ebrio", "echar", "eco", "ecuador", "edad", "edición", "edificio", "editor", "educar", "efecto", "eficaz", "eje", "ejemplo", "elefante", "elegir", "elemento", "elevar", "elipse", "élite", "elixir", "elogio", "eludir", "embudo", "emitir", "emoción", "empate", "empeño", "empleo", "empresa", "enano", "encargo", "enchufe", "encía", "enemigo", "enero", "enfado", "enfermo", "engaño", "enigma", "enlace", "enorme", "enredo", "ensayo", "enseñar", "entero", "entrar", "envase", "envío", "época", "equipo", "erizo", "escala", "escena", "escolar", "escribir", "escudo", "esencia", "esfera", "esfuerzo", "espada", "espejo", "espía", "esposa", "espuma", "esquí", "estar", "este", "estilo", "estufa", "etapa", "eterno", "ética", "etnia", "evadir", "evaluar", "evento", "evitar", "exacto", "examen", "exceso", "excusa", "exento", "exigir", "exilio", "existir", "éxito", "experto", "explicar", "exponer", "extremo", "fábrica", "fábula", "fachada", "fácil", "factor", "faena", "faja", "falda", "fallo", "falso", "faltar", "fama", "familia", "famoso", "faraón", "farmacia", "farol", "farsa", "fase", "fatiga", "fauna", "favor", "fax", "febrero", "fecha", "feliz", "feo", "feria", "feroz", "fértil", "fervor", "festín", "fiable", "fianza", "fiar", "fibra", "ficción", "ficha", "fideo", "fiebre", "fiel", "fiera", "fiesta", "figura", "fijar", "fijo", "fila", "filete", "filial", "filtro", "fin", "finca", "fingir", "finito", "firma", "flaco", "flauta", "flecha", "flor", "flota", "fluir", "flujo", "flúor", "fobia", "foca", "fogata", "fogón", "folio", "folleto", "fondo", "forma", "forro", "fortuna", "forzar", "fosa", "foto", "fracaso", "frágil", "franja", "frase", "fraude", "freír", "freno", "fresa", "frío", "frito", "fruta", "fuego", "fuente", "fuerza", "fuga", "fumar", "función", "funda", "furgón", "furia", "fusil", "fútbol", "futuro", "gacela", "gafas", "gaita", "gajo", "gala", "galería", "gallo", "gamba", "ganar", "gancho", "ganga", "ganso", "garaje", "garza", "gasolina", "gastar", "gato", "gavilán", "gemelo", "gemir", "gen", "género", "genio", "gente", "geranio", "gerente", "germen", "gesto", "gigante", "gimnasio", "girar", "giro", "glaciar", "globo", "gloria", "gol", "golfo", "goloso", "golpe", "goma", "gordo", "gorila", "gorra", "gota", "goteo", "gozar", "grada", "gráfico", "grano", "grasa", "gratis", "grave", "grieta", "grillo", "gripe", "gris", "grito", "grosor", "grúa", "grueso", "grumo", "grupo", "guante", "guapo", "guardia", "guerra", "guía", "guiño", "guion", "guiso", "guitarra", "gusano", "gustar", "haber", "hábil", "hablar", "hacer", "hacha", "hada", "hallar", "hamaca", "harina", "haz", "hazaña", "hebilla", "hebra", "hecho", "helado", "helio", "hembra", "herir", "hermano", "héroe", "hervir", "hielo", "hierro", "hígado", "higiene", "hijo", "himno", "historia", "hocico", "hogar", "hoguera", "hoja", "hombre", "hongo", "honor", "honra", "hora", "hormiga", "horno", "hostil", "hoyo", "hueco", "huelga", "huerta", "hueso", "huevo", "huida", "huir", "humano", "húmedo", "humilde", "humo", "hundir", "huracán", "hurto", "icono", "ideal", "idioma", "ídolo", "iglesia", "iglú", "igual", "ilegal", "ilusión", "imagen", "imán", "imitar", "impar", "imperio", "imponer", "impulso", "incapaz", "índice", "inerte", "infiel", "informe", "ingenio", "inicio", "inmenso", "inmune", "innato", "insecto", "instante", "interés", "íntimo", "intuir", "inútil", "invierno", "ira", "iris", "ironía", "isla", "islote", "jabalí", "jabón", "jamón", "jarabe", "jardín", "jarra", "jaula", "jazmín", "jefe", "jeringa", "jinete", "jornada", "joroba", "joven", "joya", "juerga", "jueves", "juez", "jugador", "jugo", "juguete", "juicio", "junco", "jungla", "junio", "juntar", "júpiter", "jurar", "justo", "juvenil", "juzgar", "kilo", "koala", "labio", "lacio", "lacra", "lado", "ladrón", "lagarto", "lágrima", "laguna", "laico", "lamer", "lámina", "lámpara", "lana", "lancha", "langosta", "lanza", "lápiz", "largo", "larva", "lástima", "lata", "látex", "latir", "laurel", "lavar", "lazo", "leal", "lección", "leche", "lector", "leer", "legión", "legumbre", "lejano", "lengua", "lento", "leña", "león", "leopardo", "lesión", "letal", "letra", "leve", "leyenda", "libertad", "libro", "licor", "líder", "lidiar", "lienzo", "liga", "ligero", "lima", "límite", "limón", "limpio", "lince", "lindo", "línea", "lingote", "lino", "linterna", "líquido", "liso", "lista", "litera", "litio", "litro", "llaga", "llama", "llanto", "llave", "llegar", "llenar", "llevar", "llorar", "llover", "lluvia", "lobo", "loción", "loco", "locura", "lógica", "logro", "lombriz", "lomo", "lonja", "lote", "lucha", "lucir", "lugar", "lujo", "luna", "lunes", "lupa", "lustro", "luto", "luz", "maceta", "macho", "madera", "madre", "maduro", "maestro", "mafia", "magia", "mago", "maíz", "maldad", "maleta", "malla", "malo", "mamá", "mambo", "mamut", "manco", "mando", "manejar", "manga", "maniquí", "manjar", "mano", "manso", "manta", "mañana", "mapa", "máquina", "mar", "marco", "marea", "marfil", "margen", "marido", "mármol", "marrón", "martes", "marzo", "masa", "máscara", "masivo", "matar", "materia", "matiz", "matriz", "máximo", "mayor", "mazorca", "mecha", "medalla", "medio", "médula", "mejilla", "mejor", "melena", "melón", "memoria", "menor", "mensaje", "mente", "menú", "mercado", "merengue", "mérito", "mes", "mesón", "meta", "meter", "método", "metro", "mezcla", "miedo", "miel", "miembro", "miga", "mil", "milagro", "militar", "millón", "mimo", "mina", "minero", "mínimo", "minuto", "miope", "mirar", "misa", "miseria", "misil", "mismo", "mitad", "mito", "mochila", "moción", "moda", "modelo", "moho", "mojar", "molde", "moler", "molino", "momento", "momia", "monarca", "moneda", "monja", "monto", "moño", "morada", "morder", "moreno", "morir", "morro", "morsa", "mortal", "mosca", "mostrar", "motivo", "mover", "móvil", "mozo", "mucho", "mudar", "mueble", "muela", "muerte", "muestra", "mugre", "mujer", "mula", "muleta", "multa", "mundo", "muñeca", "mural", "muro", "músculo", "museo", "musgo", "música", "muslo", "nácar", "nación", "nadar", "naipe", "naranja", "nariz", "narrar", "nasal", "natal", "nativo", "natural", "náusea", "naval", "nave", "navidad", "necio", "néctar", "negar", "negocio", "negro", "neón", "nervio", "neto", "neutro", "nevar", "nevera", "nicho", "nido", "niebla", "nieto", "niñez", "niño", "nítido", "nivel", "nobleza", "noche", "nómina", "noria", "norma", "norte", "nota", "noticia", "novato", "novela", "novio", "nube", "nuca", "núcleo", "nudillo", "nudo", "nuera", "nueve", "nuez", "nulo", "número", "nutria", "oasis", "obeso", "obispo", "objeto", "obra", "obrero", "observar", "obtener", "obvio", "oca", "ocaso", "océano", "ochenta", "ocho", "ocio", "ocre", "octavo", "octubre", "oculto", "ocupar", "ocurrir", "odiar", "odio", "odisea", "oeste", "ofensa", "oferta", "oficio", "ofrecer", "ogro", "oído", "oír", "ojo", "ola", "oleada", "olfato", "olivo", "olla", "olmo", "olor", "olvido", "ombligo", "onda", "onza", "opaco", "opción", "ópera", "opinar", "oponer", "optar", "óptica", "opuesto", "oración", "orador", "oral", "órbita", "orca", "orden", "oreja", "órgano", "orgía", "orgullo", "oriente", "origen", "orilla", "oro", "orquesta", "oruga", "osadía", "oscuro", "osezno", "oso", "ostra", "otoño", "otro", "oveja", "óvulo", "óxido", "oxígeno", "oyente", "ozono", "pacto", "padre", "paella", "página", "pago", "país", "pájaro", "palabra", "palco", "paleta", "pálido", "palma", "paloma", "palpar", "pan", "panal", "pánico", "pantera", "pañuelo", "papá", "papel", "papilla", "paquete", "parar", "parcela", "pared", "parir", "paro", "párpado", "parque", "párrafo", "parte", "pasar", "paseo", "pasión", "paso", "pasta", "pata", "patio", "patria", "pausa", "pauta", "pavo", "payaso", "peatón", "pecado", "pecera", "pecho", "pedal", "pedir", "pegar", "peine", "pelar", "peldaño", "pelea", "peligro", "pellejo", "pelo", "peluca", "pena", "pensar", "peñón", "peón", "peor", "pepino", "pequeño", "pera", "percha", "perder", "pereza", "perfil", "perico", "perla", "permiso", "perro", "persona", "pesa", "pesca", "pésimo", "pestaña", "pétalo", "petróleo", "pez", "pezuña", "picar", "pichón", "pie", "piedra", "pierna", "pieza", "pijama", "pilar", "piloto", "pimienta", "pino", "pintor", "pinza", "piña", "piojo", "pipa", "pirata", "pisar", "piscina", "piso", "pista", "pitón", "pizca", "placa", "plan", "plata", "playa", "plaza", "pleito", "pleno", "plomo", "pluma", "plural", "pobre", "poco", "poder", "podio", "poema", "poesía", "poeta", "polen", "policía", "pollo", "polvo", "pomada", "pomelo", "pomo", "pompa", "poner", "porción", "portal", "posada", "poseer", "posible", "poste", "potencia", "potro", "pozo", "prado", "precoz", "pregunta", "premio", "prensa", "preso", "previo", "primo", "príncipe", "prisión", "privar", "proa", "probar", "proceso", "producto", "proeza", "profesor", "programa", "prole", "promesa", "pronto", "propio", "próximo", "prueba", "público", "puchero", "pudor", "pueblo", "puerta", "puesto", "pulga", "pulir", "pulmón", "pulpo", "pulso", "puma", "punto", "puñal", "puño", "pupa", "pupila", "puré", "quedar", "queja", "quemar", "querer", "queso", "quieto", "química", "quince", "quitar", "rábano", "rabia", "rabo", "ración", "radical", "raíz", "rama", "rampa", "rancho", "rango", "rapaz", "rápido", "rapto", "rasgo", "raspa", "rato", "rayo", "raza", "razón", "reacción", "realidad", "rebaño", "rebote", "recaer", "receta", "rechazo", "recoger", "recreo", "recto", "recurso", "red", "redondo", "reducir", "reflejo", "reforma", "refrán", "refugio", "regalo", "regir", "regla", "regreso", "rehén", "reino", "reír", "reja", "relato", "relevo", "relieve", "relleno", "reloj", "remar", "remedio", "remo", "rencor", "rendir", "renta", "reparto", "repetir", "reposo", "reptil", "res", "rescate", "resina", "respeto", "resto", "resumen", "retiro", "retorno", "retrato", "reunir", "revés", "revista", "rey", "rezar", "rico", "riego", "rienda", "riesgo", "rifa", "rígido", "rigor", "rincón", "riñón", "río", "riqueza", "risa", "ritmo", "rito", "rizo", "roble", "roce", "rociar", "rodar", "rodeo", "rodilla", "roer", "rojizo", "rojo", "romero", "romper", "ron", "ronco", "ronda", "ropa", "ropero", "rosa", "rosca", "rostro", "rotar", "rubí", "rubor", "rudo", "rueda", "rugir", "ruido", "ruina", "ruleta", "rulo", "rumbo", "rumor", "ruptura", "ruta", "rutina", "sábado", "saber", "sabio", "sable", "sacar", "sagaz", "sagrado", "sala", "saldo", "salero", "salir", "salmón", "salón", "salsa", "salto", "salud", "salvar", "samba", "sanción", "sandía", "sanear", "sangre", "sanidad", "sano", "santo", "sapo", "saque", "sardina", "sartén", "sastre", "satán", "sauna", "saxofón", "sección", "seco", "secreto", "secta", "sed", "seguir", "seis", "sello", "selva", "semana", "semilla", "senda", "sensor", "señal", "señor", "separar", "sepia", "sequía", "ser", "serie", "sermón", "servir", "sesenta", "sesión", "seta", "setenta", "severo", "sexo", "sexto", "sidra", "siesta", "siete", "siglo", "signo", "sílaba", "silbar", "silencio", "silla", "símbolo", "simio", "sirena", "sistema", "sitio", "situar", "sobre", "socio", "sodio", "sol", "solapa", "soldado", "soledad", "sólido", "soltar", "solución", "sombra", "sondeo", "sonido", "sonoro", "sonrisa", "sopa", "soplar", "soporte", "sordo", "sorpresa", "sorteo", "sostén", "sótano", "suave", "subir", "suceso", "sudor", "suegra", "suelo", "sueño", "suerte", "sufrir", "sujeto", "sultán", "sumar", "superar", "suplir", "suponer", "supremo", "sur", "surco", "sureño", "surgir", "susto", "sutil", "tabaco", "tabique", "tabla", "tabú", "taco", "tacto", "tajo", "talar", "talco", "talento", "talla", "talón", "tamaño", "tambor", "tango", "tanque", "tapa", "tapete", "tapia", "tapón", "taquilla", "tarde", "tarea", "tarifa", "tarjeta", "tarot", "tarro", "tarta", "tatuaje", "tauro", "taza", "tazón", "teatro", "techo", "tecla", "técnica", "tejado", "tejer", "tejido", "tela", "teléfono", "tema", "temor", "templo", "tenaz", "tender", "tener", "tenis", "tenso", "teoría", "terapia", "terco", "término", "ternura", "terror", "tesis", "tesoro", "testigo", "tetera", "texto", "tez", "tibio", "tiburón", "tiempo", "tienda", "tierra", "tieso", "tigre", "tijera", "tilde", "timbre", "tímido", "timo", "tinta", "tío", "típico", "tipo", "tira", "tirón", "titán", "títere", "título", "tiza", "toalla", "tobillo", "tocar", "tocino", "todo", "toga", "toldo", "tomar", "tono", "tonto", "topar", "tope", "toque", "tórax", "torero", "tormenta", "torneo", "toro", "torpedo", "torre", "torso", "tortuga", "tos", "tosco", "toser", "tóxico", "trabajo", "tractor", "traer", "tráfico", "trago", "traje", "tramo", "trance", "trato", "trauma", "trazar", "trébol", "tregua", "treinta", "tren", "trepar", "tres", "tribu", "trigo", "tripa", "triste", "triunfo", "trofeo", "trompa", "tronco", "tropa", "trote", "trozo", "truco", "trueno", "trufa", "tubería", "tubo", "tuerto", "tumba", "tumor", "túnel", "túnica", "turbina", "turismo", "turno", "tutor", "ubicar", "úlcera", "umbral", "unidad", "unir", "universo", "uno", "untar", "uña", "urbano", "urbe", "urgente", "urna", "usar", "usuario", "útil", "utopía", "uva", "vaca", "vacío", "vacuna", "vagar", "vago", "vaina", "vajilla", "vale", "válido", "valle", "valor", "válvula", "vampiro", "vara", "variar", "varón", "vaso", "vecino", "vector", "vehículo", "veinte", "vejez", "vela", "velero", "veloz", "vena", "vencer", "venda", "veneno", "vengar", "venir", "venta", "venus", "ver", "verano", "verbo", "verde", "vereda", "verja", "verso", "verter", "vía", "viaje", "vibrar", "vicio", "víctima", "vida", "vídeo", "vidrio", "viejo", "viernes", "vigor", "vil", "villa", "vinagre", "vino", "viñedo", "violín", "viral", "virgo", "virtud", "visor", "víspera", "vista", "vitamina", "viudo", "vivaz", "vivero", "vivir", "vivo", "volcán", "volumen", "volver", "voraz", "votar", "voto", "voz", "vuelo", "vulgar", "yacer", "yate", "yegua", "yema", "yerno", "yeso", "yodo", "yoga", "yogur", "zafiro", "zanja", "zapato", "zarza", "zona", "zorro", "zumo", "zurdo" ] },{}],83:[function(require,module,exports){ // Reference https://github.com/bitcoin/bips/blob/master/bip-0066.mediawiki // Format: 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] // NOTE: SIGHASH byte ignored AND restricted, truncate before use var Buffer = require('safe-buffer').Buffer function check (buffer) { if (buffer.length < 8) return false if (buffer.length > 72) return false if (buffer[0] !== 0x30) return false if (buffer[1] !== buffer.length - 2) return false if (buffer[2] !== 0x02) return false var lenR = buffer[3] if (lenR === 0) return false if (5 + lenR >= buffer.length) return false if (buffer[4 + lenR] !== 0x02) return false var lenS = buffer[5 + lenR] if (lenS === 0) return false if ((6 + lenR + lenS) !== buffer.length) return false if (buffer[4] & 0x80) return false if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) return false if (buffer[lenR + 6] & 0x80) return false if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) return false return true } function decode (buffer) { if (buffer.length < 8) throw new Error('DER sequence length is too short') if (buffer.length > 72) throw new Error('DER sequence length is too long') if (buffer[0] !== 0x30) throw new Error('Expected DER sequence') if (buffer[1] !== buffer.length - 2) throw new Error('DER sequence length is invalid') if (buffer[2] !== 0x02) throw new Error('Expected DER integer') var lenR = buffer[3] if (lenR === 0) throw new Error('R length is zero') if (5 + lenR >= buffer.length) throw new Error('R length is too long') if (buffer[4 + lenR] !== 0x02) throw new Error('Expected DER integer (2)') var lenS = buffer[5 + lenR] if (lenS === 0) throw new Error('S length is zero') if ((6 + lenR + lenS) !== buffer.length) throw new Error('S length is invalid') if (buffer[4] & 0x80) throw new Error('R value is negative') if (lenR > 1 && (buffer[4] === 0x00) && !(buffer[5] & 0x80)) throw new Error('R value excessively padded') if (buffer[lenR + 6] & 0x80) throw new Error('S value is negative') if (lenS > 1 && (buffer[lenR + 6] === 0x00) && !(buffer[lenR + 7] & 0x80)) throw new Error('S value excessively padded') // non-BIP66 - extract R, S values return { r: buffer.slice(4, 4 + lenR), s: buffer.slice(6 + lenR) } } /* * Expects r and s to be positive DER integers. * * The DER format uses the most significant bit as a sign bit (& 0x80). * If the significant bit is set AND the integer is positive, a 0x00 is prepended. * * Examples: * * 0 => 0x00 * 1 => 0x01 * -1 => 0xff * 127 => 0x7f * -127 => 0x81 * 128 => 0x0080 * -128 => 0x80 * 255 => 0x00ff * -255 => 0xff01 * 16300 => 0x3fac * -16300 => 0xc054 * 62300 => 0x00f35c * -62300 => 0xff0ca4 */ function encode (r, s) { var lenR = r.length var lenS = s.length if (lenR === 0) throw new Error('R length is zero') if (lenS === 0) throw new Error('S length is zero') if (lenR > 33) throw new Error('R length is too long') if (lenS > 33) throw new Error('S length is too long') if (r[0] & 0x80) throw new Error('R value is negative') if (s[0] & 0x80) throw new Error('S value is negative') if (lenR > 1 && (r[0] === 0x00) && !(r[1] & 0x80)) throw new Error('R value excessively padded') if (lenS > 1 && (s[0] === 0x00) && !(s[1] & 0x80)) throw new Error('S value excessively padded') var signature = Buffer.allocUnsafe(6 + lenR + lenS) // 0x30 [total-length] 0x02 [R-length] [R] 0x02 [S-length] [S] signature[0] = 0x30 signature[1] = signature.length - 2 signature[2] = 0x02 signature[3] = r.length r.copy(signature, 4) signature[4 + lenR] = 0x02 signature[5 + lenR] = s.length s.copy(signature, 6 + lenR) return signature } module.exports = { check: check, decode: decode, encode: encode } },{"safe-buffer":457}],84:[function(require,module,exports){ module.exports={ "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, "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, "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, "OP_CAT": 126, "OP_SUBSTR": 127, "OP_LEFT": 128, "OP_RIGHT": 129, "OP_SIZE": 130, "OP_INVERT": 131, "OP_AND": 132, "OP_OR": 133, "OP_XOR": 134, "OP_EQUAL": 135, "OP_EQUALVERIFY": 136, "OP_RESERVED1": 137, "OP_RESERVED2": 138, "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, "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, "OP_NOP1": 176, "OP_NOP2": 177, "OP_CHECKLOCKTIMEVERIFY": 177, "OP_NOP3": 178, "OP_CHECKSEQUENCEVERIFY": 178, "OP_NOP4": 179, "OP_NOP5": 180, "OP_NOP6": 181, "OP_NOP7": 182, "OP_NOP8": 183, "OP_NOP9": 184, "OP_NOP10": 185, "OP_PUBKEYHASH": 253, "OP_PUBKEY": 254, "OP_INVALIDOPCODE": 255 } },{}],85:[function(require,module,exports){ var OPS = require('./index.json') var map = {} for (var op in OPS) { var code = OPS[op] map[code] = op } module.exports = map },{"./index.json":84}],86:[function(require,module,exports){ const Buffer = require('safe-buffer').Buffer const bech32 = require('bech32') const bs58check = require('bs58check') const bscript = require('./script') const networks = require('./networks') const typeforce = require('typeforce') const types = require('./types') const payments = require('./payments') function fromBase58Check (address) { const payload = bs58check.decode(address) // TODO: 4.0.0, move to "toOutputScript" if (payload.length < 21) throw new TypeError(address + ' is too short') if (payload.length > 21) throw new TypeError(address + ' is too long') const version = payload.readUInt8(0) const hash = payload.slice(1) return { version: version, hash: hash } } function fromBech32 (address) { const result = bech32.decode(address) const data = bech32.fromWords(result.words.slice(1)) return { version: result.words[0], prefix: result.prefix, data: Buffer.from(data) } } function toBase58Check (hash, version) { typeforce(types.tuple(types.Hash160bit, types.UInt8), arguments) const payload = Buffer.allocUnsafe(21) payload.writeUInt8(version, 0) hash.copy(payload, 1) return bs58check.encode(payload) } function toBech32 (data, version, prefix) { const words = bech32.toWords(data) words.unshift(version) return bech32.encode(prefix, words) } function fromOutputScript (output, network) { network = network || networks.bitcoin try { return payments.p2pkh({ output, network }).address } catch (e) {} try { return payments.p2sh({ output, network }).address } catch (e) {} try { return payments.p2wpkh({ output, network }).address } catch (e) {} try { return payments.p2wsh({ output, network }).address } catch (e) {} throw new Error(bscript.toASM(output) + ' has no matching Address') } function toOutputScript (address, network) { network = network || networks.bitcoin let decode try { decode = fromBase58Check(address) } catch (e) {} if (decode) { if (decode.version === network.pubKeyHash) return payments.p2pkh({ hash: decode.hash }).output if (decode.version === network.scriptHash) return payments.p2sh({ hash: decode.hash }).output } else { try { decode = fromBech32(address) } catch (e) {} if (decode) { if (decode.prefix !== network.bech32) throw new Error(address + ' has an invalid prefix') if (decode.version === 0) { if (decode.data.length === 20) return payments.p2wpkh({ hash: decode.data }).output if (decode.data.length === 32) return payments.p2wsh({ hash: decode.data }).output } } } throw new Error(address + ' has no matching Script') } module.exports = { fromBase58Check: fromBase58Check, fromBech32: fromBech32, fromOutputScript: fromOutputScript, toBase58Check: toBase58Check, toBech32: toBech32, toOutputScript: toOutputScript } },{"./networks":93,"./payments":95,"./script":103,"./types":129,"bech32":67,"bs58check":265,"safe-buffer":457,"typeforce":496}],87:[function(require,module,exports){ const Buffer = require('safe-buffer').Buffer const bcrypto = require('./crypto') const fastMerkleRoot = require('merkle-lib/fastRoot') const typeforce = require('typeforce') const types = require('./types') const varuint = require('varuint-bitcoin') const Transaction = require('./transaction') function Block () { this.version = 1 this.prevHash = null this.merkleRoot = null this.timestamp = 0 this.bits = 0 this.nonce = 0 } Block.fromBuffer = function (buffer) { if (buffer.length < 80) throw new Error('Buffer too small (< 80 bytes)') let offset = 0 function readSlice (n) { offset += n return buffer.slice(offset - n, offset) } function readUInt32 () { const i = buffer.readUInt32LE(offset) offset += 4 return i } function readInt32 () { const i = buffer.readInt32LE(offset) offset += 4 return i } const block = new Block() block.version = readInt32() block.prevHash = readSlice(32) block.merkleRoot = readSlice(32) block.timestamp = readUInt32() block.bits = readUInt32() block.nonce = readUInt32() if (buffer.length === 80) return block function readVarInt () { const vi = varuint.decode(buffer, offset) offset += varuint.decode.bytes return vi } function readTransaction () { const tx = Transaction.fromBuffer(buffer.slice(offset), true) offset += tx.byteLength() return tx } const nTransactions = readVarInt() block.transactions = [] for (var i = 0; i < nTransactions; ++i) { const tx = readTransaction() block.transactions.push(tx) } return block } Block.prototype.byteLength = function (headersOnly) { if (headersOnly || !this.transactions) return 80 return 80 + varuint.encodingLength(this.transactions.length) + this.transactions.reduce(function (a, x) { return a + x.byteLength() }, 0) } Block.fromHex = function (hex) { return Block.fromBuffer(Buffer.from(hex, 'hex')) } Block.prototype.getHash = function () { return bcrypto.hash256(this.toBuffer(true)) } Block.prototype.getId = function () { return this.getHash().reverse().toString('hex') } Block.prototype.getUTCDate = function () { const date = new Date(0) // epoch date.setUTCSeconds(this.timestamp) return date } // TODO: buffer, offset compatibility Block.prototype.toBuffer = function (headersOnly) { const buffer = Buffer.allocUnsafe(this.byteLength(headersOnly)) let offset = 0 function writeSlice (slice) { slice.copy(buffer, offset) offset += slice.length } function writeInt32 (i) { buffer.writeInt32LE(i, offset) offset += 4 } function writeUInt32 (i) { buffer.writeUInt32LE(i, offset) offset += 4 } writeInt32(this.version) writeSlice(this.prevHash) writeSlice(this.merkleRoot) writeUInt32(this.timestamp) writeUInt32(this.bits) writeUInt32(this.nonce) if (headersOnly || !this.transactions) return buffer varuint.encode(this.transactions.length, buffer, offset) offset += varuint.encode.bytes this.transactions.forEach(function (tx) { const txSize = tx.byteLength() // TODO: extract from toBuffer? tx.toBuffer(buffer, offset) offset += txSize }) return buffer } Block.prototype.toHex = function (headersOnly) { return this.toBuffer(headersOnly).toString('hex') } Block.calculateTarget = function (bits) { const exponent = ((bits & 0xff000000) >> 24) - 3 const mantissa = bits & 0x007fffff const target = Buffer.alloc(32, 0) target.writeUInt32BE(mantissa, 28 - exponent) return target } Block.calculateMerkleRoot = function (transactions) { typeforce([{ getHash: types.Function }], transactions) if (transactions.length === 0) throw TypeError('Cannot compute merkle root for zero transactions') const hashes = transactions.map(function (transaction) { return transaction.getHash() }) return fastMerkleRoot(hashes, bcrypto.hash256) } Block.prototype.checkMerkleRoot = function () { if (!this.transactions) return false const actualMerkleRoot = Block.calculateMerkleRoot(this.transactions) return this.merkleRoot.compare(actualMerkleRoot) === 0 } Block.prototype.checkProofOfWork = function () { const hash = this.getHash().reverse() const target = Block.calculateTarget(this.bits) return hash.compare(target) <= 0 } module.exports = Block },{"./crypto":90,"./transaction":127,"./types":129,"merkle-lib/fastRoot":437,"safe-buffer":457,"typeforce":496,"varuint-bitcoin":564}],88:[function(require,module,exports){ // https://github.com/feross/buffer/blob/master/index.js#L1127 function verifuint (value, max) { if (typeof value !== 'number') throw new Error('cannot write a non-number as a number') if (value < 0) throw new Error('specified a negative value for writing an unsigned value') if (value > max) throw new Error('RangeError: value out of range') if (Math.floor(value) !== value) throw new Error('value has a fractional component') } function readUInt64LE (buffer, offset) { const a = buffer.readUInt32LE(offset) let b = buffer.readUInt32LE(offset + 4) b *= 0x100000000 verifuint(b + a, 0x001fffffffffffff) return b + a } function writeUInt64LE (buffer, value, offset) { verifuint(value, 0x001fffffffffffff) buffer.writeInt32LE(value & -1, offset) buffer.writeUInt32LE(Math.floor(value / 0x100000000), offset + 4) return offset + 8 } module.exports = { readUInt64LE: readUInt64LE, writeUInt64LE: writeUInt64LE } },{}],89:[function(require,module,exports){ const decompile = require('./script').decompile const multisig = require('./templates/multisig') const nullData = require('./templates/nulldata') const pubKey = require('./templates/pubkey') const pubKeyHash = require('./templates/pubkeyhash') const scriptHash = require('./templates/scripthash') const witnessPubKeyHash = require('./templates/witnesspubkeyhash') const witnessScriptHash = require('./templates/witnessscripthash') const witnessCommitment = require('./templates/witnesscommitment') const types = { MULTISIG: 'multisig', NONSTANDARD: 'nonstandard', NULLDATA: 'nulldata', P2PK: 'pubkey', P2PKH: 'pubkeyhash', P2SH: 'scripthash', P2WPKH: 'witnesspubkeyhash', P2WSH: 'witnessscripthash', WITNESS_COMMITMENT: 'witnesscommitment' } function classifyOutput (script) { if (witnessPubKeyHash.output.check(script)) return types.P2WPKH if (witnessScriptHash.output.check(script)) return types.P2WSH if (pubKeyHash.output.check(script)) return types.P2PKH if (scriptHash.output.check(script)) return types.P2SH // XXX: optimization, below functions .decompile before use const chunks = decompile(script) if (!chunks) throw new TypeError('Invalid script') if (multisig.output.check(chunks)) return types.MULTISIG if (pubKey.output.check(chunks)) return types.P2PK if (witnessCommitment.output.check(chunks)) return types.WITNESS_COMMITMENT if (nullData.output.check(chunks)) return types.NULLDATA return types.NONSTANDARD } function classifyInput (script, allowIncomplete) { // XXX: optimization, below functions .decompile before use const chunks = decompile(script) if (!chunks) throw new TypeError('Invalid script') if (pubKeyHash.input.check(chunks)) return types.P2PKH if (scriptHash.input.check(chunks, allowIncomplete)) return types.P2SH if (multisig.input.check(chunks, allowIncomplete)) return types.MULTISIG if (pubKey.input.check(chunks)) return types.P2PK return types.NONSTANDARD } function classifyWitness (script, allowIncomplete) { // XXX: optimization, below functions .decompile before use const chunks = decompile(script) if (!chunks) throw new TypeError('Invalid script') if (witnessPubKeyHash.input.check(chunks)) return types.P2WPKH if (witnessScriptHash.input.check(chunks, allowIncomplete)) return types.P2WSH return types.NONSTANDARD } module.exports = { input: classifyInput, output: classifyOutput, witness: classifyWitness, types: types } },{"./script":103,"./templates/multisig":106,"./templates/nulldata":109,"./templates/pubkey":110,"./templates/pubkeyhash":113,"./templates/scripthash":116,"./templates/witnesscommitment":119,"./templates/witnesspubkeyhash":121,"./templates/witnessscripthash":124}],90:[function(require,module,exports){ const createHash = require('create-hash') function ripemd160 (buffer) { return createHash('rmd160').update(buffer).digest() } function sha1 (buffer) { return createHash('sha1').update(buffer).digest() } function sha256 (buffer) { return createHash('sha256').update(buffer).digest() } function hash160 (buffer) { return ripemd160(sha256(buffer)) } function hash256 (buffer) { return sha256(sha256(buffer)) } module.exports = { hash160: hash160, hash256: hash256, ripemd160: ripemd160, sha1: sha1, sha256: sha256 } },{"create-hash":279}],91:[function(require,module,exports){ const ecc = require('tiny-secp256k1') const randomBytes = require('randombytes') const typeforce = require('typeforce') const types = require('./types') const wif = require('wif') const NETWORKS = require('./networks') // TODO: why is the function name toJSON weird? function isPoint (x) { return ecc.isPoint(x) } const isOptions = typeforce.maybe(typeforce.compile({ compressed: types.maybe(types.Boolean), network: types.maybe(types.Network) })) function ECPair (d, Q, options) { options = options || {} this.compressed = options.compressed === undefined ? true : options.compressed this.network = options.network || NETWORKS.bitcoin this.__d = d || null this.__Q = null if (Q) this.__Q = ecc.pointCompress(Q, this.compressed) } Object.defineProperty(ECPair.prototype, 'privateKey', { enumerable: false, get: function () { return this.__d } }) Object.defineProperty(ECPair.prototype, 'publicKey', { get: function () { if (!this.__Q) this.__Q = ecc.pointFromScalar(this.__d, this.compressed) return this.__Q }}) ECPair.prototype.toWIF = function () { if (!this.__d) throw new Error('Missing private key') return wif.encode(this.network.wif, this.__d, this.compressed) } ECPair.prototype.sign = function (hash) { if (!this.__d) throw new Error('Missing private key') return ecc.sign(hash, this.__d) } ECPair.prototype.verify = function (hash, signature) { return ecc.verify(hash, this.publicKey, signature) } function fromPrivateKey (buffer, options) { typeforce(types.Buffer256bit, buffer) if (!ecc.isPrivate(buffer)) throw new TypeError('Private key not in range [1, n)') typeforce(isOptions, options) return new ECPair(buffer, null, options) } function fromPublicKey (buffer, options) { typeforce(isPoint, buffer) typeforce(isOptions, options) return new ECPair(null, buffer, options) } function fromWIF (string, network) { const decoded = wif.decode(string) const version = decoded.version // list of networks? if (types.Array(network)) { network = network.filter(function (x) { return version === x.wif }).pop() if (!network) throw new Error('Unknown network version') // otherwise, assume a network object (or default to bitcoin) } else { network = network || NETWORKS.bitcoin if (version !== network.wif) throw new Error('Invalid network version') } return fromPrivateKey(decoded.privateKey, { compressed: decoded.compressed, network: network }) } function makeRandom (options) { typeforce(isOptions, options) options = options || {} const rng = options.rng || randomBytes let d do { d = rng(32) typeforce(types.Buffer256bit, d) } while (!ecc.isPrivate(d)) return fromPrivateKey(d, options) } module.exports = { makeRandom, fromPrivateKey, fromPublicKey, fromWIF } },{"./networks":93,"./types":129,"randombytes":453,"tiny-secp256k1":469,"typeforce":496,"wif":565}],92:[function(require,module,exports){ const script = require('./script') module.exports = { Block: require('./block'), ECPair: require('./ecpair'), Transaction: require('./transaction'), TransactionBuilder: require('./transaction_builder'), address: require('./address'), bip32: require('bip32'), crypto: require('./crypto'), networks: require('./networks'), opcodes: require('bitcoin-ops'), payments: require('./payments'), script: script } },{"./address":86,"./block":87,"./crypto":90,"./ecpair":91,"./networks":93,"./payments":95,"./script":103,"./transaction":127,"./transaction_builder":128,"bip32":73,"bitcoin-ops":84}],93:[function(require,module,exports){ // https://en.bitcoin.it/wiki/List_of_address_prefixes // Dogecoin BIP32 is a proposed standard: https://bitcointalk.org/index.php?topic=409731 module.exports = { bitcoin: { messagePrefix: '\x18Bitcoin Signed Message:\n', bech32: 'bc', bip32: { public: 0x0488b21e, private: 0x0488ade4 }, pubKeyHash: 0x00, scriptHash: 0x05, wif: 0x80 }, testnet: { messagePrefix: '\x18Bitcoin Signed Message:\n', bech32: 'tb', bip32: { public: 0x043587cf, private: 0x04358394 }, pubKeyHash: 0x6f, scriptHash: 0xc4, wif: 0xef } } },{}],94:[function(require,module,exports){ const lazy = require('./lazy') const typef = require('typeforce') const OPS = require('bitcoin-ops') const bscript = require('../script') const BITCOIN_NETWORK = require('../networks').bitcoin function stacksEqual (a, b) { if (a.length !== b.length) return false return a.every(function (x, i) { return x.equals(b[i]) }) } // output: OP_RETURN ... function p2data (a, opts) { if ( !a.data && !a.output ) throw new TypeError('Not enough data') opts = opts || { validate: true } typef({ network: typef.maybe(typef.Object), output: typef.maybe(typef.Buffer), data: typef.maybe(typef.arrayOf(typef.Buffer)) }, a) const network = a.network || BITCOIN_NETWORK const o = { network } lazy.prop(o, 'output', function () { if (!a.data) return return bscript.compile([OPS.OP_RETURN].concat(a.data)) }) lazy.prop(o, 'data', function () { if (!a.output) return return bscript.decompile(a.output).slice(1) }) // extended validation if (opts.validate) { if (a.output) { const chunks = bscript.decompile(a.output) if (chunks[0] !== OPS.OP_RETURN) throw new TypeError('Output is invalid') if (!chunks.slice(1).every(typef.Buffer)) throw new TypeError('Output is invalid') if (a.data && !stacksEqual(a.data, o.data)) throw new TypeError('Data mismatch') } } return Object.assign(o, a) } module.exports = p2data },{"../networks":93,"../script":103,"./lazy":96,"bitcoin-ops":84,"typeforce":496}],95:[function(require,module,exports){ const embed = require('./embed') const p2ms = require('./p2ms') const p2pk = require('./p2pk') const p2pkh = require('./p2pkh') const p2sh = require('./p2sh') const p2wpkh = require('./p2wpkh') const p2wsh = require('./p2wsh') module.exports = { embed, p2ms, p2pk, p2pkh, p2sh, p2wpkh, p2wsh } // TODO // witness commitment },{"./embed":94,"./p2ms":97,"./p2pk":98,"./p2pkh":99,"./p2sh":100,"./p2wpkh":101,"./p2wsh":102}],96:[function(require,module,exports){ function prop (object, name, f) { Object.defineProperty(object, name, { configurable: true, enumerable: true, get: function () { let value = f.call(this) this[name] = value return value }, set: function (value) { Object.defineProperty(this, name, { configurable: true, enumerable: true, value: value, writable: true }) } }) } function value (f) { let value return function () { if (value !== undefined) return value value = f() return value } } module.exports = { prop, value } },{}],97:[function(require,module,exports){ const lazy = require('./lazy') const typef = require('typeforce') const OPS = require('bitcoin-ops') const ecc = require('tiny-secp256k1') const bscript = require('../script') const BITCOIN_NETWORK = require('../networks').bitcoin const OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1 function stacksEqual (a, b) { if (a.length !== b.length) return false return a.every(function (x, i) { return x.equals(b[i]) }) } // input: OP_0 [signatures ...] // output: m [pubKeys ...] n OP_CHECKMULTISIG function p2ms (a, opts) { if ( !a.input && !a.output && !(a.pubkeys && a.m !== undefined) && !a.signatures ) throw new TypeError('Not enough data') opts = opts || { validate: true } function isAcceptableSignature (x) { return bscript.isCanonicalScriptSignature(x) || (opts.allowIncomplete && (x === OPS.OP_0)) } typef({ network: typef.maybe(typef.Object), m: typef.maybe(typef.Number), n: typef.maybe(typef.Number), output: typef.maybe(typef.Buffer), pubkeys: typef.maybe(typef.arrayOf(ecc.isPoint)), signatures: typef.maybe(typef.arrayOf(isAcceptableSignature)), input: typef.maybe(typef.Buffer) }, a) const network = a.network || BITCOIN_NETWORK const o = { network } let chunks let decoded = false function decode (output) { if (decoded) return decoded = true chunks = bscript.decompile(output) o.m = chunks[0] - OP_INT_BASE o.n = chunks[chunks.length - 2] - OP_INT_BASE o.pubkeys = chunks.slice(1, -2) } lazy.prop(o, 'output', function () { if (!a.m) return if (!o.n) return if (!a.pubkeys) return return bscript.compile([].concat( OP_INT_BASE + a.m, a.pubkeys, OP_INT_BASE + o.n, OPS.OP_CHECKMULTISIG )) }) lazy.prop(o, 'm', function () { if (!o.output) return decode(o.output) return o.m }) lazy.prop(o, 'n', function () { if (!o.pubkeys) return return o.pubkeys.length }) lazy.prop(o, 'pubkeys', function () { if (!a.output) return decode(a.output) return o.pubkeys }) lazy.prop(o, 'signatures', function () { if (!a.input) return return bscript.decompile(a.input).slice(1) }) lazy.prop(o, 'input', function () { if (!a.signatures) return return bscript.compile([OPS.OP_0].concat(a.signatures)) }) lazy.prop(o, 'witness', function () { if (!o.input) return return [] }) // extended validation if (opts.validate) { if (a.output) { decode(a.output) if (!typef.Number(chunks[0])) throw new TypeError('Output is invalid') if (!typef.Number(chunks[chunks.length - 2])) throw new TypeError('Output is invalid') if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) throw new TypeError('Output is invalid') if ( o.m <= 0 || o.n > 16 || o.m > o.n || o.n !== chunks.length - 3) throw new TypeError('Output is invalid') if (!o.pubkeys.every(x => ecc.isPoint(x))) throw new TypeError('Output is invalid') if (a.m !== undefined && a.m !== o.m) throw new TypeError('m mismatch') if (a.n !== undefined && a.n !== o.n) throw new TypeError('n mismatch') if (a.pubkeys && !stacksEqual(a.pubkeys, o.pubkeys)) throw new TypeError('Pubkeys mismatch') } if (a.pubkeys) { if (a.n !== undefined && a.n !== a.pubkeys.length) throw new TypeError('Pubkey count mismatch') o.n = a.pubkeys.length if (o.n < o.m) throw new TypeError('Pubkey count cannot be less than m') } if (a.signatures) { if (a.signatures.length < o.m) throw new TypeError('Not enough signatures provided') if (a.signatures.length > o.m) throw new TypeError('Too many signatures provided') } if (a.input) { if (a.input[0] !== OPS.OP_0) throw new TypeError('Input is invalid') if (o.signatures.length === 0 || !o.signatures.every(isAcceptableSignature)) throw new TypeError('Input has invalid signature(s)') if (a.signatures && !stacksEqual(a.signatures.equals(o.signatures))) throw new TypeError('Signature mismatch') if (a.m !== undefined && a.m !== a.signatures.length) throw new TypeError('Signature count mismatch') } } return Object.assign(o, a) } module.exports = p2ms },{"../networks":93,"../script":103,"./lazy":96,"bitcoin-ops":84,"tiny-secp256k1":469,"typeforce":496}],98:[function(require,module,exports){ let lazy = require('./lazy') let typef = require('typeforce') let OPS = require('bitcoin-ops') let ecc = require('tiny-secp256k1') let bscript = require('../script') let BITCOIN_NETWORK = require('../networks').bitcoin // input: {signature} // output: {pubKey} OP_CHECKSIG function p2pk (a, opts) { if ( !a.input && !a.output && !a.pubkey && !a.input && !a.signature ) throw new TypeError('Not enough data') opts = opts || { validate: true } typef({ network: typef.maybe(typef.Object), output: typef.maybe(typef.Buffer), pubkey: typef.maybe(ecc.isPoint), signature: typef.maybe(bscript.isCanonicalScriptSignature), input: typef.maybe(typef.Buffer) }, a) let _chunks = lazy.value(function () { return bscript.decompile(a.input) }) let network = a.network || BITCOIN_NETWORK let o = { network } lazy.prop(o, 'output', function () { if (!a.pubkey) return return bscript.compile([ a.pubkey, OPS.OP_CHECKSIG ]) }) lazy.prop(o, 'pubkey', function () { if (!a.output) return return a.output.slice(1, -1) }) lazy.prop(o, 'signature', function () { if (!a.input) return return _chunks()[0] }) lazy.prop(o, 'input', function () { if (!a.signature) return return bscript.compile([a.signature]) }) lazy.prop(o, 'witness', function () { if (!o.input) return return [] }) // extended validation if (opts.validate) { if (a.pubkey && a.output) { if (!a.pubkey.equals(o.pubkey)) throw new TypeError('Pubkey mismatch') } if (a.output) { if (a.output[a.output.length - 1] !== OPS.OP_CHECKSIG) throw new TypeError('Output is invalid') if (!ecc.isPoint(o.pubkey)) throw new TypeError('Output pubkey is invalid') } if (a.signature) { if (a.input && !a.input.equals(o.input)) throw new TypeError('Input mismatch') } if (a.input) { if (_chunks().length !== 1) throw new TypeError('Input is invalid') if (!bscript.isCanonicalScriptSignature(_chunks()[0])) throw new TypeError('Input has invalid signature') } } return Object.assign(o, a) } module.exports = p2pk },{"../networks":93,"../script":103,"./lazy":96,"bitcoin-ops":84,"tiny-secp256k1":469,"typeforce":496}],99:[function(require,module,exports){ (function (Buffer){ const lazy = require('./lazy') const typef = require('typeforce') const OPS = require('bitcoin-ops') const ecc = require('tiny-secp256k1') const bcrypto = require('../crypto') const bscript = require('../script') const BITCOIN_NETWORK = require('../networks').bitcoin const bs58check = require('bs58check') // input: {signature} {pubkey} // output: OP_DUP OP_HASH160 {hash160(pubkey)} OP_EQUALVERIFY OP_CHECKSIG function p2pkh (a, opts) { if ( !a.address && !a.hash && !a.output && !a.pubkey && !a.input ) throw new TypeError('Not enough data') opts = opts || { validate: true } typef({ network: typef.maybe(typef.Object), address: typef.maybe(typef.String), hash: typef.maybe(typef.BufferN(20)), output: typef.maybe(typef.BufferN(25)), pubkey: typef.maybe(ecc.isPoint), signature: typef.maybe(bscript.isCanonicalScriptSignature), input: typef.maybe(typef.Buffer) }, a) const _address = lazy.value(function () { const payload = bs58check.decode(a.address) const version = payload.readUInt8(0) const hash = payload.slice(1) return { version, hash } }) const _chunks = lazy.value(function () { return bscript.decompile(a.input) }) const network = a.network || BITCOIN_NETWORK const o = { network } lazy.prop(o, 'address', function () { if (!o.hash) return const payload = Buffer.allocUnsafe(21) payload.writeUInt8(network.pubKeyHash, 0) o.hash.copy(payload, 1) return bs58check.encode(payload) }) lazy.prop(o, 'hash', function () { if (a.output) return a.output.slice(3, 23) if (a.address) return _address().hash if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey) }) lazy.prop(o, 'output', function () { if (!o.hash) return return bscript.compile([ OPS.OP_DUP, OPS.OP_HASH160, o.hash, OPS.OP_EQUALVERIFY, OPS.OP_CHECKSIG ]) }) lazy.prop(o, 'pubkey', function () { if (!a.input) return return _chunks()[1] }) lazy.prop(o, 'signature', function () { if (!a.input) return return _chunks()[0] }) lazy.prop(o, 'input', function () { if (!a.pubkey) return if (!a.signature) return return bscript.compile([a.signature, a.pubkey]) }) lazy.prop(o, 'witness', function () { if (!o.input) return return [] }) // extended validation if (opts.validate) { let hash if (a.address) { if (_address().version !== network.pubKeyHash) throw new TypeError('Invalid version or Network mismatch') if (_address().hash.length !== 20) throw new TypeError('Invalid address') hash = _address().hash } if (a.hash) { if (hash && !hash.equals(a.hash)) throw new TypeError('Hash mismatch') else hash = a.hash } if (a.output) { if ( a.output.length !== 25 || a.output[0] !== OPS.OP_DUP || a.output[1] !== OPS.OP_HASH160 || a.output[2] !== 0x14 || a.output[23] !== OPS.OP_EQUALVERIFY || a.output[24] !== OPS.OP_CHECKSIG) throw new TypeError('Output is invalid') if (hash && !hash.equals(a.output.slice(3, 23))) throw new TypeError('Hash mismatch') else hash = a.output.slice(3, 23) } if (a.pubkey) { let pkh = bcrypto.hash160(a.pubkey) if (hash && !hash.equals(pkh)) throw new TypeError('Hash mismatch') else hash = pkh } if (a.input) { let chunks = _chunks() if (chunks.length !== 2) throw new TypeError('Input is invalid') if (!bscript.isCanonicalScriptSignature(chunks[0])) throw new TypeError('Input has invalid signature') if (!ecc.isPoint(chunks[1])) throw new TypeError('Input has invalid pubkey') if (a.signature && !a.signature.equals(chunks[0])) throw new TypeError('Signature mismatch') if (a.pubkey && !a.pubkey.equals(chunks[1])) throw new TypeError('Pubkey mismatch') let pkh = bcrypto.hash160(chunks[1]) if (hash && !hash.equals(pkh)) throw new TypeError('Hash mismatch') } } return Object.assign(o, a) } module.exports = p2pkh }).call(this,require("buffer").Buffer) },{"../crypto":90,"../networks":93,"../script":103,"./lazy":96,"bitcoin-ops":84,"bs58check":265,"buffer":179,"tiny-secp256k1":469,"typeforce":496}],100:[function(require,module,exports){ (function (Buffer){ const lazy = require('./lazy') const typef = require('typeforce') const OPS = require('bitcoin-ops') const bcrypto = require('../crypto') const bscript = require('../script') const BITCOIN_NETWORK = require('../networks').bitcoin const bs58check = require('bs58check') function stacksEqual (a, b) { if (a.length !== b.length) return false return a.every(function (x, i) { return x.equals(b[i]) }) } // input: [redeemScriptSig ...] {redeemScript} // witness: // output: OP_HASH160 {hash160(redeemScript)} OP_EQUAL function p2sh (a, opts) { if ( !a.address && !a.hash && !a.output && !a.redeem && !a.input ) throw new TypeError('Not enough data') opts = opts || { validate: true } typef({ network: typef.maybe(typef.Object), address: typef.maybe(typef.String), hash: typef.maybe(typef.BufferN(20)), output: typef.maybe(typef.BufferN(23)), redeem: typef.maybe({ network: typef.maybe(typef.Object), output: typef.maybe(typef.Buffer), input: typef.maybe(typef.Buffer), witness: typef.maybe(typef.arrayOf(typef.Buffer)) }), input: typef.maybe(typef.Buffer), witness: typef.maybe(typef.arrayOf(typef.Buffer)) }, a) const network = a.network || BITCOIN_NETWORK const o = { network } const _address = lazy.value(function () { const payload = bs58check.decode(a.address) const version = payload.readUInt8(0) const hash = payload.slice(1) return { version, hash } }) const _chunks = lazy.value(function () { return bscript.decompile(a.input) }) const _redeem = lazy.value(function () { const chunks = _chunks() return { network: network, output: chunks[chunks.length - 1], input: bscript.compile(chunks.slice(0, -1)), witness: a.witness || [] } }) // output dependents lazy.prop(o, 'address', function () { if (!o.hash) return const payload = Buffer.allocUnsafe(21) payload.writeUInt8(network.scriptHash, 0) o.hash.copy(payload, 1) return bs58check.encode(payload) }) lazy.prop(o, 'hash', function () { // in order of least effort if (a.output) return a.output.slice(2, 22) if (a.address) return _address().hash if (o.redeem && o.redeem.output) return bcrypto.hash160(o.redeem.output) }) lazy.prop(o, 'output', function () { if (!o.hash) return return bscript.compile([ OPS.OP_HASH160, o.hash, OPS.OP_EQUAL ]) }) // input dependents lazy.prop(o, 'redeem', function () { if (!a.input) return return _redeem() }) lazy.prop(o, 'input', function () { if (!a.redeem || !a.redeem.input || !a.redeem.output) return return bscript.compile([].concat( bscript.decompile(a.redeem.input), a.redeem.output )) }) lazy.prop(o, 'witness', function () { if (o.redeem && o.redeem.witness) return o.redeem.witness if (o.input) return [] }) if (opts.validate) { let hash if (a.address) { if (_address().version !== network.scriptHash) throw new TypeError('Invalid version or Network mismatch') if (_address().hash.length !== 20) throw new TypeError('Invalid address') else hash = _address().hash } if (a.hash) { if (hash && !hash.equals(a.hash)) throw new TypeError('Hash mismatch') else hash = a.hash } if (a.output) { if ( a.output.length !== 23 || a.output[0] !== OPS.OP_HASH160 || a.output[1] !== 0x14 || a.output[22] !== OPS.OP_EQUAL) throw new TypeError('Output is invalid') const hash2 = a.output.slice(2, 22) if (hash && !hash.equals(hash2)) throw new TypeError('Hash mismatch') else hash = hash2 } // inlined to prevent 'no-inner-declarations' failing const checkRedeem = function (redeem) { // is the redeem output empty/invalid? if (redeem.output) { const decompile = bscript.decompile(redeem.output) if (!decompile || decompile.length < 1) throw new TypeError('Redeem.output too short') // match hash against other sources const hash2 = bcrypto.hash160(redeem.output) if (hash && !hash.equals(hash2)) throw new TypeError('Hash mismatch') else hash = hash2 } if (redeem.input) { const hasInput = redeem.input.length > 0 const hasWitness = redeem.witness && redeem.witness.length > 0 if (!hasInput && !hasWitness) throw new TypeError('Empty input') if (hasInput && hasWitness) throw new TypeError('Input and witness provided') if (hasInput) { const richunks = bscript.decompile(redeem.input) if (!bscript.isPushOnly(richunks)) throw new TypeError('Non push-only scriptSig') } } } if (a.input) { const chunks = _chunks() if (!chunks || chunks.length < 1) throw new TypeError('Input too short') if (!Buffer.isBuffer(_redeem().output)) throw new TypeError('Input is invalid') checkRedeem(_redeem()) } if (a.redeem) { if (a.redeem.network && a.redeem.network !== network) throw new TypeError('Network mismatch') if (o.redeem) { if (a.redeem.output && !a.redeem.output.equals(o.redeem.output)) throw new TypeError('Redeem.output mismatch') if (a.redeem.input && !a.redeem.input.equals(o.redeem.input)) throw new TypeError('Redeem.input mismatch') } checkRedeem(a.redeem) } if (a.witness) { if ( a.redeem && a.redeem.witness && !stacksEqual(a.redeem.witness, a.witness)) throw new TypeError('Witness and redeem.witness mismatch') } } return Object.assign(o, a) } module.exports = p2sh }).call(this,require("buffer").Buffer) },{"../crypto":90,"../networks":93,"../script":103,"./lazy":96,"bitcoin-ops":84,"bs58check":265,"buffer":179,"typeforce":496}],101:[function(require,module,exports){ (function (Buffer){ const lazy = require('./lazy') const typef = require('typeforce') const OPS = require('bitcoin-ops') const ecc = require('tiny-secp256k1') const bcrypto = require('../crypto') const bech32 = require('bech32') const bscript = require('../script') const BITCOIN_NETWORK = require('../networks').bitcoin const EMPTY_BUFFER = Buffer.alloc(0) // witness: {signature} {pubKey} // input: <> // output: OP_0 {pubKeyHash} function p2wpkh (a, opts) { if ( !a.address && !a.hash && !a.output && !a.pubkey && !a.witness ) throw new TypeError('Not enough data') opts = opts || { validate: true } typef({ address: typef.maybe(typef.String), hash: typef.maybe(typef.BufferN(20)), input: typef.maybe(typef.BufferN(0)), network: typef.maybe(typef.Object), output: typef.maybe(typef.BufferN(22)), pubkey: typef.maybe(ecc.isPoint), signature: typef.maybe(bscript.isCanonicalScriptSignature), witness: typef.maybe(typef.arrayOf(typef.Buffer)) }, a) const _address = lazy.value(function () { const result = bech32.decode(a.address) const version = result.words.shift() const data = bech32.fromWords(result.words) return { version, prefix: result.prefix, data: Buffer.from(data) } }) const network = a.network || BITCOIN_NETWORK const o = { network } lazy.prop(o, 'address', function () { if (!o.hash) return const words = bech32.toWords(o.hash) words.unshift(0x00) return bech32.encode(network.bech32, words) }) lazy.prop(o, 'hash', function () { if (a.output) return a.output.slice(2, 22) if (a.address) return _address().data if (a.pubkey || o.pubkey) return bcrypto.hash160(a.pubkey || o.pubkey) }) lazy.prop(o, 'output', function () { if (!o.hash) return return bscript.compile([ OPS.OP_0, o.hash ]) }) lazy.prop(o, 'pubkey', function () { if (a.pubkey) return a.pubkey if (!a.witness) return return a.witness[1] }) lazy.prop(o, 'signature', function () { if (!a.witness) return return a.witness[0] }) lazy.prop(o, 'input', function () { if (!o.witness) return return EMPTY_BUFFER }) lazy.prop(o, 'witness', function () { if (!a.pubkey) return if (!a.signature) return return [a.signature, a.pubkey] }) // extended validation if (opts.validate) { let hash if (a.address) { if (network && network.bech32 !== _address().prefix) throw new TypeError('Invalid prefix or Network mismatch') if (_address().version !== 0x00) throw new TypeError('Invalid address version') if (_address().data.length !== 20) throw new TypeError('Invalid address data') // if (hash && !hash.equals(_address().data)) throw new TypeError('Hash mismatch') hash = _address().data } if (a.hash) { if (hash && !hash.equals(a.hash)) throw new TypeError('Hash mismatch') else hash = a.hash } if (a.output) { if ( a.output.length !== 22 || a.output[0] !== OPS.OP_0 || a.output[1] !== 0x14) throw new TypeError('Output is invalid') if (hash && !hash.equals(a.output.slice(2))) throw new TypeError('Hash mismatch') else hash = a.output.slice(2) } if (a.pubkey) { const pkh = bcrypto.hash160(a.pubkey) if (hash && !hash.equals(pkh)) throw new TypeError('Hash mismatch') else hash = pkh } if (a.witness) { if (a.witness.length !== 2) throw new TypeError('Witness is invalid') if (!bscript.isCanonicalScriptSignature(a.witness[0])) throw new TypeError('Witness has invalid signature') if (!ecc.isPoint(a.witness[1])) throw new TypeError('Witness has invalid pubkey') if (a.signature && !a.signature.equals(a.witness[0])) throw new TypeError('Signature mismatch') if (a.pubkey && !a.pubkey.equals(a.witness[1])) throw new TypeError('Pubkey mismatch') const pkh = bcrypto.hash160(a.witness[1]) if (hash && !hash.equals(pkh)) throw new TypeError('Hash mismatch') } } return Object.assign(o, a) } module.exports = p2wpkh }).call(this,require("buffer").Buffer) },{"../crypto":90,"../networks":93,"../script":103,"./lazy":96,"bech32":67,"bitcoin-ops":84,"buffer":179,"tiny-secp256k1":469,"typeforce":496}],102:[function(require,module,exports){ (function (Buffer){ const lazy = require('./lazy') const typef = require('typeforce') const OPS = require('bitcoin-ops') const bech32 = require('bech32') const bcrypto = require('../crypto') const bscript = require('../script') const BITCOIN_NETWORK = require('../networks').bitcoin const EMPTY_BUFFER = Buffer.alloc(0) function stacksEqual (a, b) { if (a.length !== b.length) return false return a.every(function (x, i) { return x.equals(b[i]) }) } // input: <> // witness: [redeemScriptSig ...] {redeemScript} // output: OP_0 {sha256(redeemScript)} function p2wsh (a, opts) { if ( !a.address && !a.hash && !a.output && !a.redeem && !a.witness ) throw new TypeError('Not enough data') opts = opts || { validate: true } typef({ network: typef.maybe(typef.Object), address: typef.maybe(typef.String), hash: typef.maybe(typef.BufferN(32)), output: typef.maybe(typef.BufferN(34)), redeem: typef.maybe({ input: typef.maybe(typef.Buffer), network: typef.maybe(typef.Object), output: typef.maybe(typef.Buffer), witness: typef.maybe(typef.arrayOf(typef.Buffer)) }), input: typef.maybe(typef.BufferN(0)), witness: typef.maybe(typef.arrayOf(typef.Buffer)) }, a) const _address = lazy.value(function () { const result = bech32.decode(a.address) const version = result.words.shift() const data = bech32.fromWords(result.words) return { version, prefix: result.prefix, data: Buffer.from(data) } }) const _rchunks = lazy.value(function () { return bscript.decompile(a.redeem.input) }) const network = a.network || BITCOIN_NETWORK const o = { network } lazy.prop(o, 'address', function () { if (!o.hash) return const words = bech32.toWords(o.hash) words.unshift(0x00) return bech32.encode(network.bech32, words) }) lazy.prop(o, 'hash', function () { if (a.output) return a.output.slice(2) if (a.address) return _address().data if (o.redeem && o.redeem.output) return bcrypto.sha256(o.redeem.output) }) lazy.prop(o, 'output', function () { if (!o.hash) return return bscript.compile([ OPS.OP_0, o.hash ]) }) lazy.prop(o, 'redeem', function () { if (!a.witness) return return { output: a.witness[a.witness.length - 1], input: EMPTY_BUFFER, witness: a.witness.slice(0, -1) } }) lazy.prop(o, 'input', function () { if (!o.witness) return return EMPTY_BUFFER }) lazy.prop(o, 'witness', function () { // transform redeem input to witness stack? if ( a.redeem && a.redeem.input && a.redeem.input.length > 0 && a.redeem.output && a.redeem.output.length > 0 ) { const stack = bscript.toStack(_rchunks()) // assign, and blank the existing input o.redeem = Object.assign({ witness: stack }, a.redeem) o.redeem.input = EMPTY_BUFFER return [].concat(stack, a.redeem.output) } if (!a.redeem) return if (!a.redeem.output) return if (!a.redeem.witness) return return [].concat(a.redeem.witness, a.redeem.output) }) // extended validation if (opts.validate) { let hash if (a.address) { if (_address().prefix !== network.bech32) throw new TypeError('Invalid prefix or Network mismatch') if (_address().version !== 0x00) throw new TypeError('Invalid address version') if (_address().data.length !== 32) throw new TypeError('Invalid address data') else hash = _address().data } if (a.hash) { if (hash && !hash.equals(a.hash)) throw new TypeError('Hash mismatch') else hash = a.hash } if (a.output) { if ( a.output.length !== 34 || a.output[0] !== OPS.OP_0 || a.output[1] !== 0x20) throw new TypeError('Output is invalid') const hash2 = a.output.slice(2) if (hash && !hash.equals(hash2)) throw new TypeError('Hash mismatch') else hash = hash2 } if (a.redeem) { if (a.redeem.network && a.redeem.network !== network) throw new TypeError('Network mismatch') // is there two redeem sources? if ( a.redeem.input && a.redeem.input.length > 0 && a.redeem.witness && a.redeem.witness.length > 0 ) throw new TypeError('Ambiguous witness source') // is the redeem output non-empty? if (a.redeem.output) { if (bscript.decompile(a.redeem.output).length === 0) throw new TypeError('Redeem.output is invalid') // match hash against other sources const hash2 = bcrypto.sha256(a.redeem.output) if (hash && !hash.equals(hash2)) throw new TypeError('Hash mismatch') else hash = hash2 } if (a.redeem.input && !bscript.isPushOnly(_rchunks())) throw new TypeError('Non push-only scriptSig') if (a.witness && a.redeem.witness && !stacksEqual(a.witness, a.redeem.witness)) throw new TypeError('Witness and redeem.witness mismatch') } if (a.witness) { if (a.redeem && a.redeem.output && !a.redeem.output.equals(a.witness[a.witness.length - 1])) throw new TypeError('Witness and redeem.output mismatch') } } return Object.assign(o, a) } module.exports = p2wsh }).call(this,require("buffer").Buffer) },{"../crypto":90,"../networks":93,"../script":103,"./lazy":96,"bech32":67,"bitcoin-ops":84,"buffer":179,"typeforce":496}],103:[function(require,module,exports){ const Buffer = require('safe-buffer').Buffer const bip66 = require('bip66') const ecc = require('tiny-secp256k1') const pushdata = require('pushdata-bitcoin') const typeforce = require('typeforce') const types = require('./types') const scriptNumber = require('./script_number') const OPS = require('bitcoin-ops') const REVERSE_OPS = require('bitcoin-ops/map') const OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1 function isOPInt (value) { return types.Number(value) && ((value === OPS.OP_0) || (value >= OPS.OP_1 && value <= OPS.OP_16) || (value === OPS.OP_1NEGATE)) } function isPushOnlyChunk (value) { return types.Buffer(value) || isOPInt(value) } function isPushOnly (value) { return types.Array(value) && value.every(isPushOnlyChunk) } function asMinimalOP (buffer) { if (buffer.length === 0) return OPS.OP_0 if (buffer.length !== 1) return if (buffer[0] >= 1 && buffer[0] <= 16) return OP_INT_BASE + buffer[0] if (buffer[0] === 0x81) return OPS.OP_1NEGATE } function compile (chunks) { // TODO: remove me if (Buffer.isBuffer(chunks)) return chunks typeforce(types.Array, chunks) const bufferSize = chunks.reduce(function (accum, chunk) { // data chunk if (Buffer.isBuffer(chunk)) { // adhere to BIP62.3, minimal push policy if (chunk.length === 1 && asMinimalOP(chunk) !== undefined) { return accum + 1 } return accum + pushdata.encodingLength(chunk.length) + chunk.length } // opcode return accum + 1 }, 0.0) const buffer = Buffer.allocUnsafe(bufferSize) let offset = 0 chunks.forEach(function (chunk) { // data chunk if (Buffer.isBuffer(chunk)) { // adhere to BIP62.3, minimal push policy const opcode = asMinimalOP(chunk) if (opcode !== undefined) { buffer.writeUInt8(opcode, offset) offset += 1 return } offset += pushdata.encode(buffer, chunk.length, offset) chunk.copy(buffer, offset) offset += chunk.length // opcode } else { buffer.writeUInt8(chunk, offset) offset += 1 } }) if (offset !== buffer.length) throw new Error('Could not decode chunks') return buffer } function decompile (buffer) { // TODO: remove me if (types.Array(buffer)) return buffer typeforce(types.Buffer, buffer) const chunks = [] let i = 0 while (i < buffer.length) { const opcode = buffer[i] // data chunk if ((opcode > OPS.OP_0) && (opcode <= OPS.OP_PUSHDATA4)) { const d = pushdata.decode(buffer, i) // did reading a pushDataInt fail? if (d === null) return null i += d.size // attempt to read too much data? if (i + d.number > buffer.length) return null const data = buffer.slice(i, i + d.number) i += d.number // decompile minimally const op = asMinimalOP(data) if (op !== undefined) { chunks.push(op) } else { chunks.push(data) } // opcode } else { chunks.push(opcode) i += 1 } } return chunks } function toASM (chunks) { if (Buffer.isBuffer(chunks)) { chunks = decompile(chunks) } return chunks.map(function (chunk) { // data? if (Buffer.isBuffer(chunk)) { const op = asMinimalOP(chunk) if (op === undefined) return chunk.toString('hex') chunk = op } // opcode! return REVERSE_OPS[chunk] }).join(' ') } function fromASM (asm) { typeforce(types.String, asm) return compile(asm.split(' ').map(function (chunkStr) { // opcode? if (OPS[chunkStr] !== undefined) return OPS[chunkStr] typeforce(types.Hex, chunkStr) // data! return Buffer.from(chunkStr, 'hex') })) } function toStack (chunks) { chunks = decompile(chunks) typeforce(isPushOnly, chunks) return chunks.map(function (op) { if (Buffer.isBuffer(op)) return op if (op === OPS.OP_0) return Buffer.allocUnsafe(0) return scriptNumber.encode(op - OP_INT_BASE) }) } function isCanonicalPubKey (buffer) { return ecc.isPoint(buffer) } function isDefinedHashType (hashType) { const hashTypeMod = hashType & ~0x80 // return hashTypeMod > SIGHASH_ALL && hashTypeMod < SIGHASH_SINGLE return hashTypeMod > 0x00 && hashTypeMod < 0x04 } function isCanonicalScriptSignature (buffer) { if (!Buffer.isBuffer(buffer)) return false if (!isDefinedHashType(buffer[buffer.length - 1])) return false return bip66.check(buffer.slice(0, -1)) } module.exports = { compile: compile, decompile: decompile, fromASM: fromASM, toASM: toASM, toStack: toStack, number: require('./script_number'), signature: require('./script_signature'), isCanonicalPubKey: isCanonicalPubKey, isCanonicalScriptSignature: isCanonicalScriptSignature, isPushOnly: isPushOnly, isDefinedHashType: isDefinedHashType } },{"./script_number":104,"./script_signature":105,"./types":129,"bip66":83,"bitcoin-ops":84,"bitcoin-ops/map":85,"pushdata-bitcoin":449,"safe-buffer":457,"tiny-secp256k1":469,"typeforce":496}],104:[function(require,module,exports){ const Buffer = require('safe-buffer').Buffer function decode (buffer, maxLength, minimal) { maxLength = maxLength || 4 minimal = minimal === undefined ? true : minimal const length = buffer.length if (length === 0) return 0 if (length > maxLength) throw new TypeError('Script number overflow') if (minimal) { if ((buffer[length - 1] & 0x7f) === 0) { if (length <= 1 || (buffer[length - 2] & 0x80) === 0) throw new Error('Non-minimally encoded script number') } } // 40-bit if (length === 5) { const a = buffer.readUInt32LE(0) const b = buffer.readUInt8(4) if (b & 0x80) return -(((b & ~0x80) * 0x100000000) + a) return (b * 0x100000000) + a } // 32-bit / 24-bit / 16-bit / 8-bit let result = 0 for (var i = 0; i < length; ++i) { result |= buffer[i] << (8 * i) } if (buffer[length - 1] & 0x80) return -(result & ~(0x80 << (8 * (length - 1)))) return result } function scriptNumSize (i) { return i > 0x7fffffff ? 5 : i > 0x7fffff ? 4 : i > 0x7fff ? 3 : i > 0x7f ? 2 : i > 0x00 ? 1 : 0 } function encode (number) { let value = Math.abs(number) const size = scriptNumSize(value) const buffer = Buffer.allocUnsafe(size) const negative = number < 0 for (var i = 0; i < size; ++i) { buffer.writeUInt8(value & 0xff, i) value >>= 8 } if (buffer[size - 1] & 0x80) { buffer.writeUInt8(negative ? 0x80 : 0x00, size - 1) } else if (negative) { buffer[size - 1] |= 0x80 } return buffer } module.exports = { decode: decode, encode: encode } },{"safe-buffer":457}],105:[function(require,module,exports){ const bip66 = require('bip66') const Buffer = require('safe-buffer').Buffer const typeforce = require('typeforce') const types = require('./types') const ZERO = Buffer.alloc(1, 0) function toDER (x) { let i = 0 while (x[i] === 0) ++i if (i === x.length) return ZERO x = x.slice(i) if (x[0] & 0x80) return Buffer.concat([ZERO, x], 1 + x.length) return x } function fromDER (x) { if (x[0] === 0x00) x = x.slice(1) const buffer = Buffer.alloc(32, 0) const bstart = Math.max(0, 32 - x.length) x.copy(buffer, bstart) return buffer } // BIP62: 1 byte hashType flag (only 0x01, 0x02, 0x03, 0x81, 0x82 and 0x83 are allowed) function decode (buffer) { const hashType = buffer.readUInt8(buffer.length - 1) const hashTypeMod = hashType & ~0x80 if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType) const decode = bip66.decode(buffer.slice(0, -1)) const r = fromDER(decode.r) const s = fromDER(decode.s) return { signature: Buffer.concat([r, s], 64), hashType: hashType } } function encode (signature, hashType) { typeforce({ signature: types.BufferN(64), hashType: types.UInt8 }, { signature, hashType }) const hashTypeMod = hashType & ~0x80 if (hashTypeMod <= 0 || hashTypeMod >= 4) throw new Error('Invalid hashType ' + hashType) const hashTypeBuffer = Buffer.allocUnsafe(1) hashTypeBuffer.writeUInt8(hashType, 0) const r = toDER(signature.slice(0, 32)) const s = toDER(signature.slice(32, 64)) return Buffer.concat([ bip66.encode(r, s), hashTypeBuffer ]) } module.exports = { decode: decode, encode: encode } },{"./types":129,"bip66":83,"safe-buffer":457,"typeforce":496}],106:[function(require,module,exports){ module.exports = { input: require('./input'), output: require('./output') } },{"./input":107,"./output":108}],107:[function(require,module,exports){ // OP_0 [signatures ...] const bscript = require('../../script') const OPS = require('bitcoin-ops') function partialSignature (value) { return value === OPS.OP_0 || bscript.isCanonicalScriptSignature(value) } function check (script, allowIncomplete) { const chunks = bscript.decompile(script) if (chunks.length < 2) return false if (chunks[0] !== OPS.OP_0) return false if (allowIncomplete) { return chunks.slice(1).every(partialSignature) } return chunks.slice(1).every(bscript.isCanonicalScriptSignature) } check.toJSON = function () { return 'multisig input' } module.exports = { check } },{"../../script":103,"bitcoin-ops":84}],108:[function(require,module,exports){ // m [pubKeys ...] n OP_CHECKMULTISIG const bscript = require('../../script') const types = require('../../types') const OPS = require('bitcoin-ops') const OP_INT_BASE = OPS.OP_RESERVED // OP_1 - 1 function check (script, allowIncomplete) { const chunks = bscript.decompile(script) if (chunks.length < 4) return false if (chunks[chunks.length - 1] !== OPS.OP_CHECKMULTISIG) return false if (!types.Number(chunks[0])) return false if (!types.Number(chunks[chunks.length - 2])) return false const m = chunks[0] - OP_INT_BASE const n = chunks[chunks.length - 2] - OP_INT_BASE if (m <= 0) return false if (n > 16) return false if (m > n) return false if (n !== chunks.length - 3) return false if (allowIncomplete) return true const keys = chunks.slice(1, -2) return keys.every(bscript.isCanonicalPubKey) } check.toJSON = function () { return 'multi-sig output' } module.exports = { check } },{"../../script":103,"../../types":129,"bitcoin-ops":84}],109:[function(require,module,exports){ // OP_RETURN {data} const bscript = require('../script') const OPS = require('bitcoin-ops') function check (script) { const buffer = bscript.compile(script) return buffer.length > 1 && buffer[0] === OPS.OP_RETURN } check.toJSON = function () { return 'null data output' } module.exports = { output: { check: check } } },{"../script":103,"bitcoin-ops":84}],110:[function(require,module,exports){ arguments[4][106][0].apply(exports,arguments) },{"./input":111,"./output":112,"dup":106}],111:[function(require,module,exports){ // {signature} const bscript = require('../../script') function check (script) { const chunks = bscript.decompile(script) return chunks.length === 1 && bscript.isCanonicalScriptSignature(chunks[0]) } check.toJSON = function () { return 'pubKey input' } module.exports = { check: check } },{"../../script":103}],112:[function(require,module,exports){ // {pubKey} OP_CHECKSIG const bscript = require('../../script') const OPS = require('bitcoin-ops') function check (script) { const chunks = bscript.decompile(script) return chunks.length === 2 && bscript.isCanonicalPubKey(chunks[0]) && chunks[1] === OPS.OP_CHECKSIG } check.toJSON = function () { return 'pubKey output' } module.exports = { check } },{"../../script":103,"bitcoin-ops":84}],113:[function(require,module,exports){ arguments[4][106][0].apply(exports,arguments) },{"./input":114,"./output":115,"dup":106}],114:[function(require,module,exports){ // {signature} {pubKey} const bscript = require('../../script') function check (script) { const chunks = bscript.decompile(script) return chunks.length === 2 && bscript.isCanonicalScriptSignature(chunks[0]) && bscript.isCanonicalPubKey(chunks[1]) } check.toJSON = function () { return 'pubKeyHash input' } module.exports = { check } },{"../../script":103}],115:[function(require,module,exports){ // OP_DUP OP_HASH160 {pubKeyHash} OP_EQUALVERIFY OP_CHECKSIG const bscript = require('../../script') const OPS = require('bitcoin-ops') function check (script) { const buffer = bscript.compile(script) return buffer.length === 25 && buffer[0] === OPS.OP_DUP && buffer[1] === OPS.OP_HASH160 && buffer[2] === 0x14 && buffer[23] === OPS.OP_EQUALVERIFY && buffer[24] === OPS.OP_CHECKSIG } check.toJSON = function () { return 'pubKeyHash output' } module.exports = { check } },{"../../script":103,"bitcoin-ops":84}],116:[function(require,module,exports){ arguments[4][106][0].apply(exports,arguments) },{"./input":117,"./output":118,"dup":106}],117:[function(require,module,exports){ // {serialized scriptPubKey script} const Buffer = require('safe-buffer').Buffer const bscript = require('../../script') const p2ms = require('../multisig/') const p2pk = require('../pubkey/') const p2pkh = require('../pubkeyhash/') const p2wpkho = require('../witnesspubkeyhash/output') const p2wsho = require('../witnessscripthash/output') function check (script, allowIncomplete) { const chunks = bscript.decompile(script) if (chunks.length < 1) return false const lastChunk = chunks[chunks.length - 1] if (!Buffer.isBuffer(lastChunk)) return false const scriptSigChunks = bscript.decompile(bscript.compile(chunks.slice(0, -1))) const redeemScriptChunks = bscript.decompile(lastChunk) // is redeemScript a valid script? if (!redeemScriptChunks) return false // is redeemScriptSig push only? if (!bscript.isPushOnly(scriptSigChunks)) return false // is witness? if (chunks.length === 1) { return p2wsho.check(redeemScriptChunks) || p2wpkho.check(redeemScriptChunks) } // match types if (p2pkh.input.check(scriptSigChunks) && p2pkh.output.check(redeemScriptChunks)) return true if (p2ms.input.check(scriptSigChunks, allowIncomplete) && p2ms.output.check(redeemScriptChunks)) return true if (p2pk.input.check(scriptSigChunks) && p2pk.output.check(redeemScriptChunks)) return true return false } check.toJSON = function () { return 'scriptHash input' } module.exports = { check } },{"../../script":103,"../multisig/":106,"../pubkey/":110,"../pubkeyhash/":113,"../witnesspubkeyhash/output":123,"../witnessscripthash/output":126,"safe-buffer":457}],118:[function(require,module,exports){ // OP_HASH160 {scriptHash} OP_EQUAL const bscript = require('../../script') const OPS = require('bitcoin-ops') function check (script) { const buffer = bscript.compile(script) return buffer.length === 23 && buffer[0] === OPS.OP_HASH160 && buffer[1] === 0x14 && buffer[22] === OPS.OP_EQUAL } check.toJSON = function () { return 'scriptHash output' } module.exports = { check } },{"../../script":103,"bitcoin-ops":84}],119:[function(require,module,exports){ module.exports = { output: require('./output') } },{"./output":120}],120:[function(require,module,exports){ // OP_RETURN {aa21a9ed} {commitment} const Buffer = require('safe-buffer').Buffer const bscript = require('../../script') const types = require('../../types') const typeforce = require('typeforce') const OPS = require('bitcoin-ops') const HEADER = Buffer.from('aa21a9ed', 'hex') function check (script) { const buffer = bscript.compile(script) return buffer.length > 37 && buffer[0] === OPS.OP_RETURN && buffer[1] === 0x24 && buffer.slice(2, 6).equals(HEADER) } check.toJSON = function () { return 'Witness commitment output' } function encode (commitment) { typeforce(types.Hash256bit, commitment) const buffer = Buffer.allocUnsafe(36) HEADER.copy(buffer, 0) commitment.copy(buffer, 4) return bscript.compile([OPS.OP_RETURN, buffer]) } function decode (buffer) { typeforce(check, buffer) return bscript.decompile(buffer)[1].slice(4, 36) } module.exports = { check: check, decode: decode, encode: encode } },{"../../script":103,"../../types":129,"bitcoin-ops":84,"safe-buffer":457,"typeforce":496}],121:[function(require,module,exports){ arguments[4][106][0].apply(exports,arguments) },{"./input":122,"./output":123,"dup":106}],122:[function(require,module,exports){ // {signature} {pubKey} const bscript = require('../../script') function isCompressedCanonicalPubKey (pubKey) { return bscript.isCanonicalPubKey(pubKey) && pubKey.length === 33 } function check (script) { const chunks = bscript.decompile(script) return chunks.length === 2 && bscript.isCanonicalScriptSignature(chunks[0]) && isCompressedCanonicalPubKey(chunks[1]) } check.toJSON = function () { return 'witnessPubKeyHash input' } module.exports = { check } },{"../../script":103}],123:[function(require,module,exports){ // OP_0 {pubKeyHash} const bscript = require('../../script') const OPS = require('bitcoin-ops') function check (script) { const buffer = bscript.compile(script) return buffer.length === 22 && buffer[0] === OPS.OP_0 && buffer[1] === 0x14 } check.toJSON = function () { return 'Witness pubKeyHash output' } module.exports = { check } },{"../../script":103,"bitcoin-ops":84}],124:[function(require,module,exports){ arguments[4][106][0].apply(exports,arguments) },{"./input":125,"./output":126,"dup":106}],125:[function(require,module,exports){ (function (Buffer){ // {serialized scriptPubKey script} const bscript = require('../../script') const types = require('../../types') const typeforce = require('typeforce') const p2ms = require('../multisig/') const p2pk = require('../pubkey/') const p2pkh = require('../pubkeyhash/') function check (chunks, allowIncomplete) { typeforce(types.Array, chunks) if (chunks.length < 1) return false const witnessScript = chunks[chunks.length - 1] if (!Buffer.isBuffer(witnessScript)) return false const witnessScriptChunks = bscript.decompile(witnessScript) // is witnessScript a valid script? if (!witnessScriptChunks || witnessScriptChunks.length === 0) return false const witnessRawScriptSig = bscript.compile(chunks.slice(0, -1)) // match types if (p2pkh.input.check(witnessRawScriptSig) && p2pkh.output.check(witnessScriptChunks)) return true if (p2ms.input.check(witnessRawScriptSig, allowIncomplete) && p2ms.output.check(witnessScriptChunks)) return true if (p2pk.input.check(witnessRawScriptSig) && p2pk.output.check(witnessScriptChunks)) return true return false } check.toJSON = function () { return 'witnessScriptHash input' } module.exports = { check } }).call(this,{"isBuffer":require("../../../../browserify/node_modules/is-buffer/index.js")}) },{"../../../../browserify/node_modules/is-buffer/index.js":204,"../../script":103,"../../types":129,"../multisig/":106,"../pubkey/":110,"../pubkeyhash/":113,"typeforce":496}],126:[function(require,module,exports){ // OP_0 {scriptHash} const bscript = require('../../script') const OPS = require('bitcoin-ops') function check (script) { const buffer = bscript.compile(script) return buffer.length === 34 && buffer[0] === OPS.OP_0 && buffer[1] === 0x20 } check.toJSON = function () { return 'Witness scriptHash output' } module.exports = { check } },{"../../script":103,"bitcoin-ops":84}],127:[function(require,module,exports){ const Buffer = require('safe-buffer').Buffer const bcrypto = require('./crypto') const bscript = require('./script') const bufferutils = require('./bufferutils') const opcodes = require('bitcoin-ops') const typeforce = require('typeforce') const types = require('./types') const varuint = require('varuint-bitcoin') function varSliceSize (someScript) { const length = someScript.length return varuint.encodingLength(length) + length } function vectorSize (someVector) { const length = someVector.length return varuint.encodingLength(length) + someVector.reduce(function (sum, witness) { return sum + varSliceSize(witness) }, 0) } function Transaction () { this.version = 1 this.locktime = 0 this.ins = [] this.outs = [] } Transaction.DEFAULT_SEQUENCE = 0xffffffff Transaction.SIGHASH_ALL = 0x01 Transaction.SIGHASH_NONE = 0x02 Transaction.SIGHASH_SINGLE = 0x03 Transaction.SIGHASH_ANYONECANPAY = 0x80 Transaction.ADVANCED_TRANSACTION_MARKER = 0x00 Transaction.ADVANCED_TRANSACTION_FLAG = 0x01 const EMPTY_SCRIPT = Buffer.allocUnsafe(0) const EMPTY_WITNESS = [] const ZERO = Buffer.from('0000000000000000000000000000000000000000000000000000000000000000', 'hex') const ONE = Buffer.from('0000000000000000000000000000000000000000000000000000000000000001', 'hex') const VALUE_UINT64_MAX = Buffer.from('ffffffffffffffff', 'hex') const BLANK_OUTPUT = { script: EMPTY_SCRIPT, valueBuffer: VALUE_UINT64_MAX } Transaction.fromBuffer = function (buffer, __noStrict) { let offset = 0 function readSlice (n) { offset += n return buffer.slice(offset - n, offset) } function readUInt32 () { const i = buffer.readUInt32LE(offset) offset += 4 return i } function readInt32 () { const i = buffer.readInt32LE(offset) offset += 4 return i } function readUInt64 () { const i = bufferutils.readUInt64LE(buffer, offset) offset += 8 return i } function readVarInt () { const vi = varuint.decode(buffer, offset) offset += varuint.decode.bytes return vi } function readVarSlice () { return readSlice(readVarInt()) } function readVector () { const count = readVarInt() const vector = [] for (var i = 0; i < count; i++) vector.push(readVarSlice()) return vector } const tx = new Transaction() tx.version = readInt32() const marker = buffer.readUInt8(offset) const flag = buffer.readUInt8(offset + 1) let hasWitnesses = false if (marker === Transaction.ADVANCED_TRANSACTION_MARKER && flag === Transaction.ADVANCED_TRANSACTION_FLAG) { offset += 2 hasWitnesses = true } const vinLen = readVarInt() for (var i = 0; i < vinLen; ++i) { tx.ins.push({ hash: readSlice(32), index: readUInt32(), script: readVarSlice(), sequence: readUInt32(), witness: EMPTY_WITNESS }) } const voutLen = readVarInt() for (i = 0; i < voutLen; ++i) { tx.outs.push({ value: readUInt64(), script: readVarSlice() }) } if (hasWitnesses) { for (i = 0; i < vinLen; ++i) { tx.ins[i].witness = readVector() } // was this pointless? if (!tx.hasWitnesses()) throw new Error('Transaction has superfluous witness data') } tx.locktime = readUInt32() if (__noStrict) return tx if (offset !== buffer.length) throw new Error('Transaction has unexpected data') return tx } Transaction.fromHex = function (hex) { return Transaction.fromBuffer(Buffer.from(hex, 'hex')) } Transaction.isCoinbaseHash = function (buffer) { typeforce(types.Hash256bit, buffer) for (var i = 0; i < 32; ++i) { if (buffer[i] !== 0) return false } return true } Transaction.prototype.isCoinbase = function () { return this.ins.length === 1 && Transaction.isCoinbaseHash(this.ins[0].hash) } Transaction.prototype.addInput = function (hash, index, sequence, scriptSig) { typeforce(types.tuple( types.Hash256bit, types.UInt32, types.maybe(types.UInt32), types.maybe(types.Buffer) ), arguments) if (types.Null(sequence)) { sequence = Transaction.DEFAULT_SEQUENCE } // Add the input and return the input's index return (this.ins.push({ hash: hash, index: index, script: scriptSig || EMPTY_SCRIPT, sequence: sequence, witness: EMPTY_WITNESS }) - 1) } Transaction.prototype.addOutput = function (scriptPubKey, value) { typeforce(types.tuple(types.Buffer, types.Satoshi), arguments) // Add the output and return the output's index return (this.outs.push({ script: scriptPubKey, value: value }) - 1) } Transaction.prototype.hasWitnesses = function () { return this.ins.some(function (x) { return x.witness.length !== 0 }) } Transaction.prototype.weight = function () { const base = this.__byteLength(false) const total = this.__byteLength(true) return base * 3 + total } Transaction.prototype.virtualSize = function () { return Math.ceil(this.weight() / 4) } Transaction.prototype.byteLength = function () { return this.__byteLength(true) } Transaction.prototype.__byteLength = function (__allowWitness) { const hasWitnesses = __allowWitness && this.hasWitnesses() return ( (hasWitnesses ? 10 : 8) + varuint.encodingLength(this.ins.length) + varuint.encodingLength(this.outs.length) + this.ins.reduce(function (sum, input) { return sum + 40 + varSliceSize(input.script) }, 0) + this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) + (hasWitnesses ? this.ins.reduce(function (sum, input) { return sum + vectorSize(input.witness) }, 0) : 0) ) } Transaction.prototype.clone = function () { const newTx = new Transaction() newTx.version = this.version newTx.locktime = this.locktime newTx.ins = this.ins.map(function (txIn) { return { hash: txIn.hash, index: txIn.index, script: txIn.script, sequence: txIn.sequence, witness: txIn.witness } }) newTx.outs = this.outs.map(function (txOut) { return { script: txOut.script, value: txOut.value } }) return newTx } /** * Hash transaction for signing a specific input. * * Bitcoin uses a different hash for each signed transaction input. * This method copies the transaction, makes the necessary changes based on the * hashType, and then hashes the result. * This hash can then be used to sign the provided transaction input. */ Transaction.prototype.hashForSignature = function (inIndex, prevOutScript, hashType) { typeforce(types.tuple(types.UInt32, types.Buffer, /* types.UInt8 */ types.Number), arguments) // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L29 if (inIndex >= this.ins.length) return ONE // ignore OP_CODESEPARATOR const ourScript = bscript.compile(bscript.decompile(prevOutScript).filter(function (x) { return x !== opcodes.OP_CODESEPARATOR })) const txTmp = this.clone() // SIGHASH_NONE: ignore all outputs? (wildcard payee) if ((hashType & 0x1f) === Transaction.SIGHASH_NONE) { txTmp.outs = [] // ignore sequence numbers (except at inIndex) txTmp.ins.forEach(function (input, i) { if (i === inIndex) return input.sequence = 0 }) // SIGHASH_SINGLE: ignore all outputs, except at the same index? } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE) { // https://github.com/bitcoin/bitcoin/blob/master/src/test/sighash_tests.cpp#L60 if (inIndex >= this.outs.length) return ONE // truncate outputs after txTmp.outs.length = inIndex + 1 // "blank" outputs before for (var i = 0; i < inIndex; i++) { txTmp.outs[i] = BLANK_OUTPUT } // ignore sequence numbers (except at inIndex) txTmp.ins.forEach(function (input, y) { if (y === inIndex) return input.sequence = 0 }) } // SIGHASH_ANYONECANPAY: ignore inputs entirely? if (hashType & Transaction.SIGHASH_ANYONECANPAY) { txTmp.ins = [txTmp.ins[inIndex]] txTmp.ins[0].script = ourScript // SIGHASH_ALL: only ignore input scripts } else { // "blank" others input scripts txTmp.ins.forEach(function (input) { input.script = EMPTY_SCRIPT }) txTmp.ins[inIndex].script = ourScript } // serialize and hash const buffer = Buffer.allocUnsafe(txTmp.__byteLength(false) + 4) buffer.writeInt32LE(hashType, buffer.length - 4) txTmp.__toBuffer(buffer, 0, false) return bcrypto.hash256(buffer) } Transaction.prototype.hashForWitnessV0 = function (inIndex, prevOutScript, value, hashType) { typeforce(types.tuple(types.UInt32, types.Buffer, types.Satoshi, types.UInt32), arguments) let tbuffer, toffset function writeSlice (slice) { toffset += slice.copy(tbuffer, toffset) } function writeUInt32 (i) { toffset = tbuffer.writeUInt32LE(i, toffset) } function writeUInt64 (i) { toffset = bufferutils.writeUInt64LE(tbuffer, i, toffset) } function writeVarInt (i) { varuint.encode(i, tbuffer, toffset) toffset += varuint.encode.bytes } function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) } let hashOutputs = ZERO let hashPrevouts = ZERO let hashSequence = ZERO if (!(hashType & Transaction.SIGHASH_ANYONECANPAY)) { tbuffer = Buffer.allocUnsafe(36 * this.ins.length) toffset = 0 this.ins.forEach(function (txIn) { writeSlice(txIn.hash) writeUInt32(txIn.index) }) hashPrevouts = bcrypto.hash256(tbuffer) } if (!(hashType & Transaction.SIGHASH_ANYONECANPAY) && (hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { tbuffer = Buffer.allocUnsafe(4 * this.ins.length) toffset = 0 this.ins.forEach(function (txIn) { writeUInt32(txIn.sequence) }) hashSequence = bcrypto.hash256(tbuffer) } if ((hashType & 0x1f) !== Transaction.SIGHASH_SINGLE && (hashType & 0x1f) !== Transaction.SIGHASH_NONE) { const txOutsSize = this.outs.reduce(function (sum, output) { return sum + 8 + varSliceSize(output.script) }, 0) tbuffer = Buffer.allocUnsafe(txOutsSize) toffset = 0 this.outs.forEach(function (out) { writeUInt64(out.value) writeVarSlice(out.script) }) hashOutputs = bcrypto.hash256(tbuffer) } else if ((hashType & 0x1f) === Transaction.SIGHASH_SINGLE && inIndex < this.outs.length) { const output = this.outs[inIndex] tbuffer = Buffer.allocUnsafe(8 + varSliceSize(output.script)) toffset = 0 writeUInt64(output.value) writeVarSlice(output.script) hashOutputs = bcrypto.hash256(tbuffer) } tbuffer = Buffer.allocUnsafe(156 + varSliceSize(prevOutScript)) toffset = 0 const input = this.ins[inIndex] writeUInt32(this.version) writeSlice(hashPrevouts) writeSlice(hashSequence) writeSlice(input.hash) writeUInt32(input.index) writeVarSlice(prevOutScript) writeUInt64(value) writeUInt32(input.sequence) writeSlice(hashOutputs) writeUInt32(this.locktime) writeUInt32(hashType) return bcrypto.hash256(tbuffer) } Transaction.prototype.getHash = function () { return bcrypto.hash256(this.__toBuffer(undefined, undefined, false)) } Transaction.prototype.getId = function () { // transaction hash's are displayed in reverse order return this.getHash().reverse().toString('hex') } Transaction.prototype.toBuffer = function (buffer, initialOffset) { return this.__toBuffer(buffer, initialOffset, true) } Transaction.prototype.__toBuffer = function (buffer, initialOffset, __allowWitness) { if (!buffer) buffer = Buffer.allocUnsafe(this.__byteLength(__allowWitness)) let offset = initialOffset || 0 function writeSlice (slice) { offset += slice.copy(buffer, offset) } function writeUInt8 (i) { offset = buffer.writeUInt8(i, offset) } function writeUInt32 (i) { offset = buffer.writeUInt32LE(i, offset) } function writeInt32 (i) { offset = buffer.writeInt32LE(i, offset) } function writeUInt64 (i) { offset = bufferutils.writeUInt64LE(buffer, i, offset) } function writeVarInt (i) { varuint.encode(i, buffer, offset) offset += varuint.encode.bytes } function writeVarSlice (slice) { writeVarInt(slice.length); writeSlice(slice) } function writeVector (vector) { writeVarInt(vector.length); vector.forEach(writeVarSlice) } writeInt32(this.version) const hasWitnesses = __allowWitness && this.hasWitnesses() if (hasWitnesses) { writeUInt8(Transaction.ADVANCED_TRANSACTION_MARKER) writeUInt8(Transaction.ADVANCED_TRANSACTION_FLAG) } writeVarInt(this.ins.length) this.ins.forEach(function (txIn) { writeSlice(txIn.hash) writeUInt32(txIn.index) writeVarSlice(txIn.script) writeUInt32(txIn.sequence) }) writeVarInt(this.outs.length) this.outs.forEach(function (txOut) { if (!txOut.valueBuffer) { writeUInt64(txOut.value) } else { writeSlice(txOut.valueBuffer) } writeVarSlice(txOut.script) }) if (hasWitnesses) { this.ins.forEach(function (input) { writeVector(input.witness) }) } writeUInt32(this.locktime) // avoid slicing unless necessary if (initialOffset !== undefined) return buffer.slice(initialOffset, offset) return buffer } Transaction.prototype.toHex = function () { return this.toBuffer().toString('hex') } Transaction.prototype.setInputScript = function (index, scriptSig) { typeforce(types.tuple(types.Number, types.Buffer), arguments) this.ins[index].script = scriptSig } Transaction.prototype.setWitness = function (index, witness) { typeforce(types.tuple(types.Number, [types.Buffer]), arguments) this.ins[index].witness = witness } module.exports = Transaction },{"./bufferutils":88,"./crypto":90,"./script":103,"./types":129,"bitcoin-ops":84,"safe-buffer":457,"typeforce":496,"varuint-bitcoin":564}],128:[function(require,module,exports){ const Buffer = require('safe-buffer').Buffer const baddress = require('./address') const bcrypto = require('./crypto') const bscript = require('./script') const networks = require('./networks') const ops = require('bitcoin-ops') const payments = require('./payments') const typeforce = require('typeforce') const types = require('./types') const classify = require('./classify') const SCRIPT_TYPES = classify.types const ECPair = require('./ecpair') const Transaction = require('./transaction') function expandInput (scriptSig, witnessStack, type, scriptPubKey) { if (scriptSig.length === 0 && witnessStack.length === 0) return {} if (!type) { let ssType = classify.input(scriptSig, true) let wsType = classify.witness(witnessStack, true) if (ssType === SCRIPT_TYPES.NONSTANDARD) ssType = undefined if (wsType === SCRIPT_TYPES.NONSTANDARD) wsType = undefined type = ssType || wsType } switch (type) { case SCRIPT_TYPES.P2WPKH: { const { output, pubkey, signature } = payments.p2wpkh({ witness: witnessStack }) return { prevOutScript: output, prevOutType: SCRIPT_TYPES.P2WPKH, pubkeys: [pubkey], signatures: [signature] } } case SCRIPT_TYPES.P2PKH: { const { output, pubkey, signature } = payments.p2pkh({ input: scriptSig }) return { prevOutScript: output, prevOutType: SCRIPT_TYPES.P2PKH, pubkeys: [pubkey], signatures: [signature] } } case SCRIPT_TYPES.P2PK: { const { signature } = payments.p2pk({ input: scriptSig }) return { prevOutType: SCRIPT_TYPES.P2PK, pubkeys: [undefined], signatures: [signature] } } case SCRIPT_TYPES.MULTISIG: { const { pubkeys, signatures } = payments.p2ms({ input: scriptSig, output: scriptPubKey }, { allowIncomplete: true }) return { prevOutType: SCRIPT_TYPES.MULTISIG, pubkeys: pubkeys, signatures: signatures } } } if (type === SCRIPT_TYPES.P2SH) { const { output, redeem } = payments.p2sh({ input: scriptSig, witness: witnessStack }) const outputType = classify.output(redeem.output) const expanded = expandInput(redeem.input, redeem.witness, outputType, redeem.output) if (!expanded.prevOutType) return {} return { prevOutScript: output, prevOutType: SCRIPT_TYPES.P2SH, redeemScript: redeem.output, redeemScriptType: expanded.prevOutType, witnessScript: expanded.witnessScript, witnessScriptType: expanded.witnessScriptType, pubkeys: expanded.pubkeys, signatures: expanded.signatures } } if (type === SCRIPT_TYPES.P2WSH) { const { output, redeem } = payments.p2wsh({ input: scriptSig, witness: witnessStack }) const outputType = classify.output(redeem.output) let expanded if (outputType === SCRIPT_TYPES.P2WPKH) { expanded = expandInput(redeem.input, redeem.witness, outputType) } else { expanded = expandInput(bscript.compile(redeem.witness), [], outputType, redeem.output) } if (!expanded.prevOutType) return {} return { prevOutScript: output, prevOutType: SCRIPT_TYPES.P2WSH, witnessScript: redeem.output, witnessScriptType: expanded.prevOutType, pubkeys: expanded.pubkeys, signatures: expanded.signatures } } return { prevOutType: SCRIPT_TYPES.NONSTANDARD, prevOutScript: scriptSig } } // could be done in expandInput, but requires the original Transaction for hashForSignature function fixMultisigOrder (input, transaction, vin) { if (input.redeemScriptType !== SCRIPT_TYPES.MULTISIG || !input.redeemScript) return if (input.pubkeys.length === input.signatures.length) return const unmatched = input.signatures.concat() input.signatures = input.pubkeys.map(function (pubKey) { const keyPair = ECPair.fromPublicKey(pubKey) let match // check for a signature unmatched.some(function (signature, i) { // skip if undefined || OP_0 if (!signature) return false // TODO: avoid O(n) hashForSignature const parsed = bscript.signature.decode(signature) const hash = transaction.hashForSignature(vin, input.redeemScript, parsed.hashType) // skip if signature does not match pubKey if (!keyPair.verify(hash, parsed.signature)) return false // remove matched signature from unmatched unmatched[i] = undefined match = signature return true }) return match }) } function expandOutput (script, ourPubKey) { typeforce(types.Buffer, script) const type = classify.output(script) switch (type) { case SCRIPT_TYPES.P2PKH: { if (!ourPubKey) return { type } // does our hash160(pubKey) match the output scripts? const pkh1 = payments.p2pkh({ output: script }).hash const pkh2 = bcrypto.hash160(ourPubKey) if (!pkh1.equals(pkh2)) return { type } return { type, pubkeys: [ourPubKey], signatures: [undefined] } } case SCRIPT_TYPES.P2WPKH: { if (!ourPubKey) return { type } // does our hash160(pubKey) match the output scripts? const wpkh1 = payments.p2wpkh({ output: script }).hash const wpkh2 = bcrypto.hash160(ourPubKey) if (!wpkh1.equals(wpkh2)) return { type } return { type, pubkeys: [ourPubKey], signatures: [undefined] } } case SCRIPT_TYPES.P2PK: { const p2pk = payments.p2pk({ output: script }) return { type, pubkeys: [p2pk.pubkey], signatures: [undefined] } } case SCRIPT_TYPES.MULTISIG: { const p2ms = payments.p2ms({ output: script }) return { type, pubkeys: p2ms.pubkeys, signatures: p2ms.pubkeys.map(() => undefined) } } } return { type } } function prepareInput (input, ourPubKey, redeemScript, witnessValue, witnessScript) { if (redeemScript && witnessScript) { const p2wsh = payments.p2wsh({ redeem: { output: witnessScript } }) const p2wshAlt = payments.p2wsh({ output: redeemScript }) const p2sh = payments.p2sh({ redeem: { output: redeemScript } }) const p2shAlt = payments.p2sh({ redeem: p2wsh }) // enforces P2SH(P2WSH(...)) if (!p2wsh.hash.equals(p2wshAlt.hash)) throw new Error('Witness script inconsistent with prevOutScript') if (!p2sh.hash.equals(p2shAlt.hash)) throw new Error('Redeem script inconsistent with prevOutScript') const expanded = expandOutput(p2wsh.redeem.output, ourPubKey) if (!expanded.pubkeys) throw new Error(expanded.type + ' not supported as witnessScript (' + bscript.toASM(witnessScript) + ')') if (input.signatures && input.signatures.some(x => x)) { expanded.signatures = input.signatures } let signScript = witnessScript if (expanded.type === SCRIPT_TYPES.P2WPKH) throw new Error('P2SH(P2WSH(P2WPKH)) is a consensus failure') return { redeemScript, redeemScriptType: SCRIPT_TYPES.P2WSH, witnessScript, witnessScriptType: expanded.type, prevOutType: SCRIPT_TYPES.P2SH, prevOutScript: p2sh.output, hasWitness: true, signScript, signType: expanded.type, pubkeys: expanded.pubkeys, signatures: expanded.signatures } } if (redeemScript) { const p2sh = payments.p2sh({ redeem: { output: redeemScript } }) if (input.prevOutScript) { let p2shAlt try { p2shAlt = payments.p2sh({ output: input.prevOutScript }) } catch (e) { throw new Error('PrevOutScript must be P2SH') } if (!p2sh.hash.equals(p2shAlt.hash)) throw new Error('Redeem script inconsistent with prevOutScript') } const expanded = expandOutput(p2sh.redeem.output, ourPubKey) if (!expanded.pubkeys) throw new Error(expanded.type + ' not supported as redeemScript (' + bscript.toASM(redeemScript) + ')') if (input.signatures && input.signatures.some(x => x)) { expanded.signatures = input.signatures } let signScript = redeemScript if (expanded.type === SCRIPT_TYPES.P2WPKH) { signScript = payments.p2pkh({ pubkey: expanded.pubkeys[0] }).output } return { redeemScript, redeemScriptType: expanded.type, prevOutType: SCRIPT_TYPES.P2SH, prevOutScript: p2sh.output, hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, signScript, signType: expanded.type, pubkeys: expanded.pubkeys, signatures: expanded.signatures } } if (witnessScript) { const p2wsh = payments.p2wsh({ redeem: { output: witnessScript } }) if (input.prevOutScript) { const p2wshAlt = payments.p2wsh({ output: input.prevOutScript }) if (!p2wsh.hash.equals(p2wshAlt.hash)) throw new Error('Witness script inconsistent with prevOutScript') } const expanded = expandOutput(p2wsh.redeem.output, ourPubKey) if (!expanded.pubkeys) throw new Error(expanded.type + ' not supported as witnessScript (' + bscript.toASM(witnessScript) + ')') if (input.signatures && input.signatures.some(x => x)) { expanded.signatures = input.signatures } let signScript = witnessScript if (expanded.type === SCRIPT_TYPES.P2WPKH) throw new Error('P2WSH(P2WPKH) is a consensus failure') return { witnessScript, witnessScriptType: expanded.type, prevOutType: SCRIPT_TYPES.P2WSH, prevOutScript: p2wsh.output, hasWitness: true, signScript, signType: expanded.type, pubkeys: expanded.pubkeys, signatures: expanded.signatures } } if (input.prevOutType && input.prevOutScript) { // embedded scripts are not possible without extra information if (input.prevOutType === SCRIPT_TYPES.P2SH) throw new Error('PrevOutScript is ' + input.prevOutType + ', requires redeemScript') if (input.prevOutType === SCRIPT_TYPES.P2WSH) throw new Error('PrevOutScript is ' + input.prevOutType + ', requires witnessScript') if (!input.prevOutScript) throw new Error('PrevOutScript is missing') const expanded = expandOutput(input.prevOutScript, ourPubKey) if (!expanded.pubkeys) throw new Error(expanded.type + ' not supported (' + bscript.toASM(input.prevOutScript) + ')') if (input.signatures && input.signatures.some(x => x)) { expanded.signatures = input.signatures } let signScript = input.prevOutScript if (expanded.type === SCRIPT_TYPES.P2WPKH) { signScript = payments.p2pkh({ pubkey: expanded.pubkeys[0] }).output } return { prevOutType: expanded.type, prevOutScript: input.prevOutScript, hasWitness: expanded.type === SCRIPT_TYPES.P2WPKH, signScript, signType: expanded.type, pubkeys: expanded.pubkeys, signatures: expanded.signatures } } const prevOutScript = payments.p2pkh({ pubkey: ourPubKey }).output return { prevOutType: SCRIPT_TYPES.P2PKH, prevOutScript: prevOutScript, hasWitness: false, signScript: prevOutScript, signType: SCRIPT_TYPES.P2PKH, pubkeys: [ourPubKey], signatures: [undefined] } } function build (type, input, allowIncomplete) { const pubkeys = input.pubkeys || [] let signatures = input.signatures || [] switch (type) { case SCRIPT_TYPES.P2PKH: { if (pubkeys.length === 0) break if (signatures.length === 0) break return payments.p2pkh({ pubkey: pubkeys[0], signature: signatures[0] }) } case SCRIPT_TYPES.P2WPKH: { if (pubkeys.length === 0) break if (signatures.length === 0) break return payments.p2wpkh({ pubkey: pubkeys[0], signature: signatures[0] }) } case SCRIPT_TYPES.P2PK: { if (pubkeys.length === 0) break if (signatures.length === 0) break return payments.p2pk({ signature: signatures[0] }) } case SCRIPT_TYPES.MULTISIG: { if (allowIncomplete) { signatures = signatures.map(x => x || ops.OP_0) } else { signatures = signatures.filter(x => x) } return payments.p2ms({ signatures }, { allowIncomplete }) } case SCRIPT_TYPES.P2SH: { const redeem = build(input.redeemScriptType, input, allowIncomplete) if (!redeem) return return payments.p2sh({ redeem: { output: redeem.output || input.redeemScript, input: redeem.input, witness: redeem.witness } }) } case SCRIPT_TYPES.P2WSH: { const redeem = build(input.witnessScriptType, input, allowIncomplete) if (!redeem) return return payments.p2wsh({ redeem: { output: input.witnessScript, input: redeem.input, witness: redeem.witness } }) } } } function TransactionBuilder (network, maximumFeeRate) { this.__prevTxSet = {} this.network = network || networks.bitcoin // WARNING: This is __NOT__ to be relied on, its just another potential safety mechanism (safety in-depth) this.maximumFeeRate = maximumFeeRate || 2500 this.__inputs = [] this.__tx = new Transaction() this.__tx.version = 2 } TransactionBuilder.prototype.setLockTime = function (locktime) { typeforce(types.UInt32, locktime) // if any signatures exist, throw if (this.__inputs.some(function (input) { if (!input.signatures) return false return input.signatures.some(function (s) { return s }) })) { throw new Error('No, this would invalidate signatures') } this.__tx.locktime = locktime } TransactionBuilder.prototype.setVersion = function (version) { typeforce(types.UInt32, version) // XXX: this might eventually become more complex depending on what the versions represent this.__tx.version = version } TransactionBuilder.fromTransaction = function (transaction, network) { const txb = new TransactionBuilder(network) // Copy transaction fields txb.setVersion(transaction.version) txb.setLockTime(transaction.locktime) // Copy outputs (done first to avoid signature invalidation) transaction.outs.forEach(function (txOut) { txb.addOutput(txOut.script, txOut.value) }) // Copy inputs transaction.ins.forEach(function (txIn) { txb.__addInputUnsafe(txIn.hash, txIn.index, { sequence: txIn.sequence, script: txIn.script, witness: txIn.witness }) }) // fix some things not possible through the public API txb.__inputs.forEach(function (input, i) { fixMultisigOrder(input, transaction, i) }) return txb } TransactionBuilder.prototype.addInput = function (txHash, vout, sequence, prevOutScript) { if (!this.__canModifyInputs()) { throw new Error('No, this would invalidate signatures') } let value // is it a hex string? if (typeof txHash === 'string') { // transaction hashs's are displayed in reverse order, un-reverse it txHash = Buffer.from(txHash, 'hex').reverse() // is it a Transaction object? } else if (txHash instanceof Transaction) { const txOut = txHash.outs[vout] prevOutScript = txOut.script value = txOut.value txHash = txHash.getHash() } return this.__addInputUnsafe(txHash, vout, { sequence: sequence, prevOutScript: prevOutScript, value: value }) } TransactionBuilder.prototype.__addInputUnsafe = function (txHash, vout, options) { if (Transaction.isCoinbaseHash(txHash)) { throw new Error('coinbase inputs not supported') } const prevTxOut = txHash.toString('hex') + ':' + vout if (this.__prevTxSet[prevTxOut] !== undefined) throw new Error('Duplicate TxOut: ' + prevTxOut) let input = {} // derive what we can from the scriptSig if (options.script !== undefined) { input = expandInput(options.script, options.witness || []) } // if an input value was given, retain it if (options.value !== undefined) { input.value = options.value } // derive what we can from the previous transactions output script if (!input.prevOutScript && options.prevOutScript) { let prevOutType if (!input.pubkeys && !input.signatures) { const expanded = expandOutput(options.prevOutScript) if (expanded.pubkeys) { input.pubkeys = expanded.pubkeys input.signatures = expanded.signatures } prevOutType = expanded.type } input.prevOutScript = options.prevOutScript input.prevOutType = prevOutType || classify.output(options.prevOutScript) } const vin = this.__tx.addInput(txHash, vout, options.sequence, options.scriptSig) this.__inputs[vin] = input this.__prevTxSet[prevTxOut] = true return vin } TransactionBuilder.prototype.addOutput = function (scriptPubKey, value) { if (!this.__canModifyOutputs()) { throw new Error('No, this would invalidate signatures') } // Attempt to get a script if it's a base58 or bech32 address string if (typeof scriptPubKey === 'string') { scriptPubKey = baddress.toOutputScript(scriptPubKey, this.network) } return this.__tx.addOutput(scriptPubKey, value) } TransactionBuilder.prototype.build = function () { return this.__build(false) } TransactionBuilder.prototype.buildIncomplete = function () { return this.__build(true) } TransactionBuilder.prototype.__build = function (allowIncomplete) { if (!allowIncomplete) { if (!this.__tx.ins.length) throw new Error('Transaction has no inputs') if (!this.__tx.outs.length) throw new Error('Transaction has no outputs') } const tx = this.__tx.clone() // create script signatures from inputs this.__inputs.forEach(function (input, i) { if (!input.prevOutType && !allowIncomplete) throw new Error('Transaction is not complete') const result = build(input.prevOutType, input, allowIncomplete) if (!result) { if (!allowIncomplete && input.prevOutType === SCRIPT_TYPES.NONSTANDARD) throw new Error('Unknown input type') if (!allowIncomplete) throw new Error('Not enough information') return } tx.setInputScript(i, result.input) tx.setWitness(i, result.witness) }) if (!allowIncomplete) { // do not rely on this, its merely a last resort if (this.__overMaximumFees(tx.virtualSize())) { throw new Error('Transaction has absurd fees') } } return tx } function canSign (input) { return input.signScript !== undefined && input.signType !== undefined && input.pubkeys !== undefined && input.signatures !== undefined && input.signatures.length === input.pubkeys.length && input.pubkeys.length > 0 && ( input.hasWitness === false || input.value !== undefined ) } TransactionBuilder.prototype.sign = function (vin, keyPair, redeemScript, hashType, witnessValue, witnessScript) { // TODO: remove keyPair.network matching in 4.0.0 if (keyPair.network && keyPair.network !== this.network) throw new TypeError('Inconsistent network') if (!this.__inputs[vin]) throw new Error('No input at index: ' + vin) hashType = hashType || Transaction.SIGHASH_ALL const input = this.__inputs[vin] // if redeemScript was previously provided, enforce consistency if (input.redeemScript !== undefined && redeemScript && !input.redeemScript.equals(redeemScript)) { throw new Error('Inconsistent redeemScript') } const ourPubKey = keyPair.publicKey || keyPair.getPublicKey() if (!canSign(input)) { if (witnessValue !== undefined) { if (input.value !== undefined && input.value !== witnessValue) throw new Error('Input didn\'t match witnessValue') typeforce(types.Satoshi, witnessValue) input.value = witnessValue } if (!canSign(input)) { const prepared = prepareInput(input, ourPubKey, redeemScript, witnessValue, witnessScript) // updates inline Object.assign(input, prepared) } if (!canSign(input)) throw Error(input.prevOutType + ' not supported') } // ready to sign let signatureHash if (input.hasWitness) { signatureHash = this.__tx.hashForWitnessV0(vin, input.signScript, input.value, hashType) } else { signatureHash = this.__tx.hashForSignature(vin, input.signScript, hashType) } // enforce in order signing of public keys const signed = input.pubkeys.some(function (pubKey, i) { if (!ourPubKey.equals(pubKey)) return false if (input.signatures[i]) throw new Error('Signature already exists') // TODO: add tests if (ourPubKey.length !== 33 && input.hasWitness) { throw new Error('BIP143 rejects uncompressed public keys in P2WPKH or P2WSH') } const signature = keyPair.sign(signatureHash) input.signatures[i] = bscript.signature.encode(signature, hashType) return true }) if (!signed) throw new Error('Key pair cannot sign for this input') } function signatureHashType (buffer) { return buffer.readUInt8(buffer.length - 1) } TransactionBuilder.prototype.__canModifyInputs = function () { return this.__inputs.every(function (input) { // any signatures? if (input.signatures === undefined) return true return input.signatures.every(function (signature) { if (!signature) return true const hashType = signatureHashType(signature) // if SIGHASH_ANYONECANPAY is set, signatures would not // be invalidated by more inputs return hashType & Transaction.SIGHASH_ANYONECANPAY }) }) } TransactionBuilder.prototype.__canModifyOutputs = function () { const nInputs = this.__tx.ins.length const nOutputs = this.__tx.outs.length return this.__inputs.every(function (input) { if (input.signatures === undefined) return true return input.signatures.every(function (signature) { if (!signature) return true const hashType = signatureHashType(signature) const hashTypeMod = hashType & 0x1f if (hashTypeMod === Transaction.SIGHASH_NONE) return true if (hashTypeMod === Transaction.SIGHASH_SINGLE) { // if SIGHASH_SINGLE is set, and nInputs > nOutputs // some signatures would be invalidated by the addition // of more outputs return nInputs <= nOutputs } }) }) } TransactionBuilder.prototype.__overMaximumFees = function (bytes) { // not all inputs will have .value defined const incoming = this.__inputs.reduce(function (a, x) { return a + (x.value >>> 0) }, 0) // but all outputs do, and if we have any input value // we can immediately determine if the outputs are too small const outgoing = this.__tx.outs.reduce(function (a, x) { return a + x.value }, 0) const fee = incoming - outgoing const feeRate = fee / bytes return feeRate > this.maximumFeeRate } module.exports = TransactionBuilder },{"./address":86,"./classify":89,"./crypto":90,"./ecpair":91,"./networks":93,"./payments":95,"./script":103,"./transaction":127,"./types":129,"bitcoin-ops":84,"safe-buffer":457,"typeforce":496}],129:[function(require,module,exports){ const typeforce = require('typeforce') const UINT31_MAX = Math.pow(2, 31) - 1 function UInt31 (value) { return typeforce.UInt32(value) && value <= UINT31_MAX } function BIP32Path (value) { return typeforce.String(value) && value.match(/^(m\/)?(\d+'?\/)*\d+'?$/) } BIP32Path.toJSON = function () { return 'BIP32 derivation path' } const SATOSHI_MAX = 21 * 1e14 function Satoshi (value) { return typeforce.UInt53(value) && value <= SATOSHI_MAX } // external dependent types const ECPoint = typeforce.quacksLike('Point') // exposed, external API const Network = typeforce.compile({ messagePrefix: typeforce.oneOf(typeforce.Buffer, typeforce.String), bip32: { public: typeforce.UInt32, private: typeforce.UInt32 }, pubKeyHash: typeforce.UInt8, scriptHash: typeforce.UInt8, wif: typeforce.UInt8 }) // extend typeforce types with ours const types = { BIP32Path: BIP32Path, Buffer256bit: typeforce.BufferN(32), ECPoint: ECPoint, Hash160bit: typeforce.BufferN(20), Hash256bit: typeforce.BufferN(32), Network: Network, Satoshi: Satoshi, UInt31: UInt31 } for (var typeName in typeforce) { types[typeName] = typeforce[typeName] } module.exports = types },{"typeforce":496}],130:[function(require,module,exports){ (function (module, exports) { 'use strict'; // Utils function assert (val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } // 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) { if (BN.isBN(number)) { return number; } this.negative = 0; this.words = null; this.length = 0; // Reduction context this.red = null; if (number !== null) { if (base === 'le' || base === 'be') { endian = base; base = 10; } this._init(number || 0, base || 10, endian || 'be'); } } if (typeof module === 'object') { module.exports = BN; } else { exports.BN = BN; } BN.BN = BN; BN.wordSize = 26; var Buffer; try { Buffer = require('buffer').Buffer; } catch (e) { } BN.isBN = function isBN (num) { if (num instanceof BN) { return true; } return num !== null && typeof num === 'object' && num.constructor.wordSize === BN.wordSize && Array.isArray(num.words); }; BN.max = function max (left, right) { if (left.cmp(right) > 0) return left; return right; }; BN.min = function min (left, right) { if (left.cmp(right) < 0) return left; return right; }; BN.prototype._init = function init (number, base, endian) { if (typeof number === 'number') { return this._initNumber(number, base, endian); } 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.negative = 1; } this.strip(); if (endian !== 'le') return; this._initArray(this.toArray(), base, endian); }; BN.prototype._initNumber = function _initNumber (number, base, endian) { if (number < 0) { this.negative = 1; number = -number; } if (number < 0x4000000) { this.words = [ number & 0x3ffffff ]; this.length = 1; } else if (number < 0x10000000000000) { this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff ]; this.length = 2; } else { assert(number < 0x20000000000000); // 2 ^ 53 (unsafe) this.words = [ number & 0x3ffffff, (number / 0x4000000) & 0x3ffffff, 1 ]; this.length = 3; } if (endian !== 'le') return; // Reverse the bytes this._initArray(this.toArray(), base, endian); }; BN.prototype._initArray = function _initArray (number, base, endian) { // Perhaps a Uint8Array assert(typeof number.length === 'number'); if (number.length <= 0) { this.words = [ 0 ]; this.length = 1; return this; } 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 j, w; var off = 0; if (endian === 'be') { for (i = number.length - 1, j = 0; i >= 0; i -= 3) { 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 (i = 0, j = 0; i < number.length; i += 3) { 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(); }; function parseHex (str, start, end) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r <<= 4; // 'a' - 'f' if (c >= 49 && c <= 54) { r |= c - 49 + 0xa; // 'A' - 'F' } else if (c >= 17 && c <= 22) { r |= c - 17 + 0xa; // '0' - '9' } else { r |= c & 0xf; } } return r; } 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; } var j, w; // Scan 24-bit chunks and add them to the number var off = 0; for (i = number.length - 6, j = 0; i >= start; i -= 6) { w = parseHex(number, i, i + 6); this.words[j] |= (w << off) & 0x3ffffff; // NOTE: `0x3fffff` is intentional here, 26bits max shift + 24bit hex limb this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; off += 24; if (off >= 26) { off -= 26; j++; } } if (i + 6 !== start) { w = parseHex(number, start, i + 6); this.words[j] |= (w << off) & 0x3ffffff; this.words[j + 1] |= w >>> (26 - off) & 0x3fffff; } this.strip(); }; function parseBase (str, start, end, mul) { var r = 0; var len = Math.min(str.length, end); for (var i = start; i < len; i++) { var c = str.charCodeAt(i) - 48; r *= mul; // 'a' if (c >= 49) { r += c - 49 + 0xa; // 'A' } else if (c >= 17) { r += c - 17 + 0xa; // '0' - '9' } else { r += c; } } return r; } BN.prototype._parseBase = function _parseBase (number, base, start) { // Initialize as zero this.words = [ 0 ]; this.length = 1; // Find length of limb in base for (var limbLen = 0, limbPow = 1; limbPow <= 0x3ffffff; limbPow *= base) { limbLen++; } limbLen--; limbPow = (limbPow / base) | 0; var total = number.length - start; var mod = total % limbLen; var end = Math.min(total, total - mod) + start; var word = 0; for (var i = start; i < end; i += limbLen) { word = parseBase(number, i, i + limbLen, base); this.imuln(limbPow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(word); } } if (mod !== 0) { var pow = 1; word = parseBase(number, i, number.length, base); for (i = 0; i < mod; i++) { pow *= base; } this.imuln(pow); if (this.words[0] + word < 0x4000000) { this.words[0] += word; } else { this._iaddn(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.negative = this.negative; dest.red = this.red; }; BN.prototype.clone = function clone () { var r = new BN(null); this.copy(r); return r; }; BN.prototype._expand = function _expand (size) { while (this.length < size) { this.words[this.length++] = 0; } return this; }; // 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.negative = 0; } 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; 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; padding = padding | 0 || 1; var out; if (base === 16 || base === 'hex') { out = ''; var off = 0; 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.negative !== 0) { out = '-' + out; } return out; } 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]; out = ''; var c = this.clone(); c.negative = 0; while (!c.isZero()) { var r = c.modn(groupBase).toString(base); c = c.idivn(groupBase); if (!c.isZero()) { out = zeros[groupSize - r.length] + r + out; } else { out = r + out; } } if (this.isZero()) { out = '0' + out; } while (out.length % padding !== 0) { out = '0' + out; } if (this.negative !== 0) { out = '-' + out; } return out; } assert(false, 'Base should be between 2 and 36'); }; BN.prototype.toNumber = function toNumber () { var ret = this.words[0]; if (this.length === 2) { ret += this.words[1] * 0x4000000; } else if (this.length === 3 && this.words[2] === 0x01) { // NOTE: at this stage it is known that the top bit is set ret += 0x10000000000000 + (this.words[1] * 0x4000000); } else if (this.length > 2) { assert(false, 'Number can only safely store up to 53 bits'); } return (this.negative !== 0) ? -ret : ret; }; BN.prototype.toJSON = function toJSON () { return this.toString(16); }; BN.prototype.toBuffer = function toBuffer (endian, length) { assert(typeof Buffer !== 'undefined'); return this.toArrayLike(Buffer, endian, length); }; BN.prototype.toArray = function toArray (endian, length) { return this.toArrayLike(Array, endian, length); }; BN.prototype.toArrayLike = function toArrayLike (ArrayType, endian, length) { var byteLength = this.byteLength(); var reqLength = length || Math.max(1, byteLength); assert(byteLength <= reqLength, 'byte array longer than desired length'); assert(reqLength > 0, 'Requested array length <= 0'); this.strip(); var littleEndian = endian === 'le'; var res = new ArrayType(reqLength); var b, i; var q = this.clone(); if (!littleEndian) { // Assume big-endian for (i = 0; i < reqLength - byteLength; i++) { res[i] = 0; } for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[reqLength - i - 1] = b; } } else { for (i = 0; !q.isZero(); i++) { b = q.andln(0xff); q.iushrn(8); res[i] = b; } for (; i < reqLength; i++) { res[i] = 0; } } return res; }; if (Math.clz32) { BN.prototype._countBits = function _countBits (w) { return 32 - Math.clz32(w); }; } else { BN.prototype._countBits = function _countBits (w) { var t = w; var r = 0; if (t >= 0x1000) { r += 13; t >>>= 13; } if (t >= 0x40) { r += 7; t >>>= 7; } if (t >= 0x8) { r += 4; t >>>= 4; } if (t >= 0x02) { r += 2; t >>>= 2; } return r + t; }; } BN.prototype._zeroBits = function _zeroBits (w) { // Short-cut if (w === 0) return 26; var t = w; var r = 0; if ((t & 0x1fff) === 0) { r += 13; t >>>= 13; } if ((t & 0x7f) === 0) { r += 7; t >>>= 7; } if ((t & 0xf) === 0) { r += 4; t >>>= 4; } if ((t & 0x3) === 0) { r += 2; t >>>= 2; } if ((t & 0x1) === 0) { r++; } return r; }; // Return number of used bits in a BN BN.prototype.bitLength = function bitLength () { var w = this.words[this.length - 1]; var hi = this._countBits(w); return (this.length - 1) * 26 + hi; }; function toBitArray (num) { var w = new Array(num.bitLength()); for (var bit = 0; bit < w.length; bit++) { var off = (bit / 26) | 0; var wbit = bit % 26; w[bit] = (num.words[off] & (1 << wbit)) >>> wbit; } return w; } // Number of trailing zero bits BN.prototype.zeroBits = function zeroBits () { if (this.isZero()) return 0; var r = 0; for (var i = 0; i < this.length; i++) { var b = this._zeroBits(this.words[i]); r += b; if (b !== 26) break; } return r; }; BN.prototype.byteLength = function byteLength () { return Math.ceil(this.bitLength() / 8); }; BN.prototype.toTwos = function toTwos (width) { if (this.negative !== 0) { return this.abs().inotn(width).iaddn(1); } return this.clone(); }; BN.prototype.fromTwos = function fromTwos (width) { if (this.testn(width - 1)) { return this.notn(width).iaddn(1).ineg(); } return this.clone(); }; BN.prototype.isNeg = function isNeg () { return this.negative !== 0; }; // Return negative clone of `this` BN.prototype.neg = function neg () { return this.clone().ineg(); }; BN.prototype.ineg = function ineg () { if (!this.isZero()) { this.negative ^= 1; } return this; }; // Or `num` with `this` in-place BN.prototype.iuor = function iuor (num) { while (this.length < num.length) { this.words[this.length++] = 0; } for (var i = 0; i < num.length; i++) { this.words[i] = this.words[i] | num.words[i]; } return this.strip(); }; BN.prototype.ior = function ior (num) { assert((this.negative | num.negative) === 0); return this.iuor(num); }; // Or `num` with `this` BN.prototype.or = function or (num) { if (this.length > num.length) return this.clone().ior(num); return num.clone().ior(this); }; BN.prototype.uor = function uor (num) { if (this.length > num.length) return this.clone().iuor(num); return num.clone().iuor(this); }; // And `num` with `this` in-place BN.prototype.iuand = function iuand (num) { // b = min-length(num, this) var b; if (this.length > num.length) { b = num; } else { b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = this.words[i] & num.words[i]; } this.length = b.length; return this.strip(); }; BN.prototype.iand = function iand (num) { assert((this.negative | num.negative) === 0); return this.iuand(num); }; // And `num` with `this` BN.prototype.and = function and (num) { if (this.length > num.length) return this.clone().iand(num); return num.clone().iand(this); }; BN.prototype.uand = function uand (num) { if (this.length > num.length) return this.clone().iuand(num); return num.clone().iuand(this); }; // Xor `num` with `this` in-place BN.prototype.iuxor = function iuxor (num) { // a.length > b.length var a; var b; if (this.length > num.length) { a = this; b = num; } else { a = num; b = this; } for (var i = 0; i < b.length; i++) { this.words[i] = a.words[i] ^ b.words[i]; } if (this !== a) { for (; i < a.length; i++) { this.words[i] = a.words[i]; } } this.length = a.length; return this.strip(); }; BN.prototype.ixor = function ixor (num) { assert((this.negative | num.negative) === 0); return this.iuxor(num); }; // Xor `num` with `this` BN.prototype.xor = function xor (num) { if (this.length > num.length) return this.clone().ixor(num); return num.clone().ixor(this); }; BN.prototype.uxor = function uxor (num) { if (this.length > num.length) return this.clone().iuxor(num); return num.clone().iuxor(this); }; // Not ``this`` with ``width`` bitwidth BN.prototype.inotn = function inotn (width) { assert(typeof width === 'number' && width >= 0); var bytesNeeded = Math.ceil(width / 26) | 0; var bitsLeft = width % 26; // Extend the buffer with leading zeroes this._expand(bytesNeeded); if (bitsLeft > 0) { bytesNeeded--; } // Handle complete words for (var i = 0; i < bytesNeeded; i++) { this.words[i] = ~this.words[i] & 0x3ffffff; } // Handle the residue if (bitsLeft > 0) { this.words[i] = ~this.words[i] & (0x3ffffff >> (26 - bitsLeft)); } // And remove leading zeroes return this.strip(); }; BN.prototype.notn = function notn (width) { return this.clone().inotn(width); }; // Set `bit` of `this` BN.prototype.setn = function setn (bit, val) { assert(typeof bit === 'number' && bit >= 0); var off = (bit / 26) | 0; var wbit = bit % 26; this._expand(off + 1); if (val) { this.words[off] = this.words[off] | (1 << wbit); } else { this.words[off] = this.words[off] & ~(1 << wbit); } return this.strip(); }; // Add `num` to `this` in-place BN.prototype.iadd = function iadd (num) { var r; // negative + positive if (this.negative !== 0 && num.negative === 0) { this.negative = 0; r = this.isub(num); this.negative ^= 1; return this._normSign(); // positive + negative } else if (this.negative === 0 && num.negative !== 0) { num.negative = 0; r = this.isub(num); num.negative = 1; return r._normSign(); } // a.length > b.length var a, 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++) { r = (a.words[i] | 0) + (b.words[i] | 0) + carry; this.words[i] = r & 0x3ffffff; carry = r >>> 26; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + 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) { var res; if (num.negative !== 0 && this.negative === 0) { num.negative = 0; res = this.sub(num); num.negative ^= 1; return res; } else if (num.negative === 0 && this.negative !== 0) { this.negative = 0; res = num.sub(this); this.negative = 1; return res; } if (this.length > num.length) return this.clone().iadd(num); return num.clone().iadd(this); }; // Subtract `num` from `this` in-place BN.prototype.isub = function isub (num) { // this - (-num) = this + num if (num.negative !== 0) { num.negative = 0; var r = this.iadd(num); num.negative = 1; return r._normSign(); // -this - num = -(this + num) } else if (this.negative !== 0) { this.negative = 0; this.iadd(num); this.negative = 1; return this._normSign(); } // At this point both numbers are positive var cmp = this.cmp(num); // Optimization - zeroify if (cmp === 0) { this.negative = 0; this.length = 1; this.words[0] = 0; return this; } // a > b var a, b; if (cmp > 0) { a = this; b = num; } else { a = num; b = this; } var carry = 0; for (var i = 0; i < b.length; i++) { r = (a.words[i] | 0) - (b.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } for (; carry !== 0 && i < a.length; i++) { r = (a.words[i] | 0) + carry; carry = r >> 26; this.words[i] = r & 0x3ffffff; } // 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.negative = 1; } return this.strip(); }; // Subtract `num` from `this` BN.prototype.sub = function sub (num) { return this.clone().isub(num); }; function smallMulTo (self, num, out) { out.negative = num.negative ^ self.negative; var len = (self.length + num.length) | 0; out.length = len; len = (len - 1) | 0; // Peel one iteration (compiler can't do it, because of code complexity) var a = self.words[0] | 0; var b = num.words[0] | 0; var r = a * b; var lo = r & 0x3ffffff; var carry = (r / 0x4000000) | 0; out.words[0] = lo; for (var k = 1; k < len; 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 - self.length + 1); j <= maxJ; j++) { var i = (k - j) | 0; a = self.words[i] | 0; b = num.words[j] | 0; r = a * b + rword; ncarry += (r / 0x4000000) | 0; rword = r & 0x3ffffff; } out.words[k] = rword | 0; carry = ncarry | 0; } if (carry !== 0) { out.words[k] = carry | 0; } else { out.length--; } return out.strip(); } // TODO(indutny): it may be reasonable to omit it for users who don't need // to work with 256-bit numbers, otherwise it gives 20% improvement for 256-bit // multiplication (like elliptic secp256k1). var comb10MulTo = function comb10MulTo (self, num, out) { var a = self.words; var b = num.words; var o = out.words; var c = 0; var lo; var mid; var hi; var a0 = a[0] | 0; var al0 = a0 & 0x1fff; var ah0 = a0 >>> 13; var a1 = a[1] | 0; var al1 = a1 & 0x1fff; var ah1 = a1 >>> 13; var a2 = a[2] | 0; var al2 = a2 & 0x1fff; var ah2 = a2 >>> 13; var a3 = a[3] | 0; var al3 = a3 & 0x1fff; var ah3 = a3 >>> 13; var a4 = a[4] | 0; var al4 = a4 & 0x1fff; var ah4 = a4 >>> 13; var a5 = a[5] | 0; var al5 = a5 & 0x1fff; var ah5 = a5 >>> 13; var a6 = a[6] | 0; var al6 = a6 & 0x1fff; var ah6 = a6 >>> 13; var a7 = a[7] | 0; var al7 = a7 & 0x1fff; var ah7 = a7 >>> 13; var a8 = a[8] | 0; var al8 = a8 & 0x1fff; var ah8 = a8 >>> 13; var a9 = a[9] | 0; var al9 = a9 & 0x1fff; var ah9 = a9 >>> 13; var b0 = b[0] | 0; var bl0 = b0 & 0x1fff; var bh0 = b0 >>> 13; var b1 = b[1] | 0; var bl1 = b1 & 0x1fff; var bh1 = b1 >>> 13; var b2 = b[2] | 0; var bl2 = b2 & 0x1fff; var bh2 = b2 >>> 13; var b3 = b[3] | 0; var bl3 = b3 & 0x1fff; var bh3 = b3 >>> 13; var b4 = b[4] | 0; var bl4 = b4 & 0x1fff; var bh4 = b4 >>> 13; var b5 = b[5] | 0; var bl5 = b5 & 0x1fff; var bh5 = b5 >>> 13; var b6 = b[6] | 0; var bl6 = b6 & 0x1fff; var bh6 = b6 >>> 13; var b7 = b[7] | 0; var bl7 = b7 & 0x1fff; var bh7 = b7 >>> 13; var b8 = b[8] | 0; var bl8 = b8 & 0x1fff; var bh8 = b8 >>> 13; var b9 = b[9] | 0; var bl9 = b9 & 0x1fff; var bh9 = b9 >>> 13; out.negative = self.negative ^ num.negative; out.length = 19; /* k = 0 */ lo = Math.imul(al0, bl0); mid = Math.imul(al0, bh0); mid = (mid + Math.imul(ah0, bl0)) | 0; hi = Math.imul(ah0, bh0); var w0 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w0 >>> 26)) | 0; w0 &= 0x3ffffff; /* k = 1 */ lo = Math.imul(al1, bl0); mid = Math.imul(al1, bh0); mid = (mid + Math.imul(ah1, bl0)) | 0; hi = Math.imul(ah1, bh0); lo = (lo + Math.imul(al0, bl1)) | 0; mid = (mid + Math.imul(al0, bh1)) | 0; mid = (mid + Math.imul(ah0, bl1)) | 0; hi = (hi + Math.imul(ah0, bh1)) | 0; var w1 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w1 >>> 26)) | 0; w1 &= 0x3ffffff; /* k = 2 */ lo = Math.imul(al2, bl0); mid = Math.imul(al2, bh0); mid = (mid + Math.imul(ah2, bl0)) | 0; hi = Math.imul(ah2, bh0); lo = (lo + Math.imul(al1, bl1)) | 0; mid = (mid + Math.imul(al1, bh1)) | 0; mid = (mid + Math.imul(ah1, bl1)) | 0; hi = (hi + Math.imul(ah1, bh1)) | 0; lo = (lo + Math.imul(al0, bl2)) | 0; mid = (mid + Math.imul(al0, bh2)) | 0; mid = (mid + Math.imul(ah0, bl2)) | 0; hi = (hi + Math.imul(ah0, bh2)) | 0; var w2 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w2 >>> 26)) | 0; w2 &= 0x3ffffff; /* k = 3 */ lo = Math.imul(al3, bl0); mid = Math.imul(al3, bh0); mid = (mid + Math.imul(ah3, bl0)) | 0; hi = Math.imul(ah3, bh0); lo = (lo + Math.imul(al2, bl1)) | 0; mid = (mid + Math.imul(al2, bh1)) | 0; mid = (mid + Math.imul(ah2, bl1)) | 0; hi = (hi + Math.imul(ah2, bh1)) | 0; lo = (lo + Math.imul(al1, bl2)) | 0; mid = (mid + Math.imul(al1, bh2)) | 0; mid = (mid + Math.imul(ah1, bl2)) | 0; hi = (hi + Math.imul(ah1, bh2)) | 0; lo = (lo + Math.imul(al0, bl3)) | 0; mid = (mid + Math.imul(al0, bh3)) | 0; mid = (mid + Math.imul(ah0, bl3)) | 0; hi = (hi + Math.imul(ah0, bh3)) | 0; var w3 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w3 >>> 26)) | 0; w3 &= 0x3ffffff; /* k = 4 */ lo = Math.imul(al4, bl0); mid = Math.imul(al4, bh0); mid = (mid + Math.imul(ah4, bl0)) | 0; hi = Math.imul(ah4, bh0); lo = (lo + Math.imul(al3, bl1)) | 0; mid = (mid + Math.imul(al3, bh1)) | 0; mid = (mid + Math.imul(ah3, bl1)) | 0; hi = (hi + Math.imul(ah3, bh1)) | 0; lo = (lo + Math.imul(al2, bl2)) | 0; mid = (mid + Math.imul(al2, bh2)) | 0; mid = (mid + Math.imul(ah2, bl2)) | 0; hi = (hi + Math.imul(ah2, bh2)) | 0; lo = (lo + Math.imul(al1, bl3)) | 0; mid = (mid + Math.imul(al1, bh3)) | 0; mid = (mid + Math.imul(ah1, bl3)) | 0; hi = (hi + Math.imul(ah1, bh3)) | 0; lo = (lo + Math.imul(al0, bl4)) | 0; mid = (mid + Math.imul(al0, bh4)) | 0; mid = (mid + Math.imul(ah0, bl4)) | 0; hi = (hi + Math.imul(ah0, bh4)) | 0; var w4 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w4 >>> 26)) | 0; w4 &= 0x3ffffff; /* k = 5 */ lo = Math.imul(al5, bl0); mid = Math.imul(al5, bh0); mid = (mid + Math.imul(ah5, bl0)) | 0; hi = Math.imul(ah5, bh0); lo = (lo + Math.imul(al4, bl1)) | 0; mid = (mid + Math.imul(al4, bh1)) | 0; mid = (mid + Math.imul(ah4, bl1)) | 0; hi = (hi + Math.imul(ah4, bh1)) | 0; lo = (lo + Math.imul(al3, bl2)) | 0; mid = (mid + Math.imul(al3, bh2)) | 0; mid = (mid + Math.imul(ah3, bl2)) | 0; hi = (hi + Math.imul(ah3, bh2)) | 0; lo = (lo + Math.imul(al2, bl3)) | 0; mid = (mid + Math.imul(al2, bh3)) | 0; mid = (mid + Math.imul(ah2, bl3)) | 0; hi = (hi + Math.imul(ah2, bh3)) | 0; lo = (lo + Math.imul(al1, bl4)) | 0; mid = (mid + Math.imul(al1, bh4)) | 0; mid = (mid + Math.imul(ah1, bl4)) | 0; hi = (hi + Math.imul(ah1, bh4)) | 0; lo = (lo + Math.imul(al0, bl5)) | 0; mid = (mid + Math.imul(al0, bh5)) | 0; mid = (mid + Math.imul(ah0, bl5)) | 0; hi = (hi + Math.imul(ah0, bh5)) | 0; var w5 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w5 >>> 26)) | 0; w5 &= 0x3ffffff; /* k = 6 */ lo = Math.imul(al6, bl0); mid = Math.imul(al6, bh0); mid = (mid + Math.imul(ah6, bl0)) | 0; hi = Math.imul(ah6, bh0); lo = (lo + Math.imul(al5, bl1)) | 0; mid = (mid + Math.imul(al5, bh1)) | 0; mid = (mid + Math.imul(ah5, bl1)) | 0; hi = (hi + Math.imul(ah5, bh1)) | 0; lo = (lo + Math.imul(al4, bl2)) | 0; mid = (mid + Math.imul(al4, bh2)) | 0; mid = (mid + Math.imul(ah4, bl2)) | 0; hi = (hi + Math.imul(ah4, bh2)) | 0; lo = (lo + Math.imul(al3, bl3)) | 0; mid = (mid + Math.imul(al3, bh3)) | 0; mid = (mid + Math.imul(ah3, bl3)) | 0; hi = (hi + Math.imul(ah3, bh3)) | 0; lo = (lo + Math.imul(al2, bl4)) | 0; mid = (mid + Math.imul(al2, bh4)) | 0; mid = (mid + Math.imul(ah2, bl4)) | 0; hi = (hi + Math.imul(ah2, bh4)) | 0; lo = (lo + Math.imul(al1, bl5)) | 0; mid = (mid + Math.imul(al1, bh5)) | 0; mid = (mid + Math.imul(ah1, bl5)) | 0; hi = (hi + Math.imul(ah1, bh5)) | 0; lo = (lo + Math.imul(al0, bl6)) | 0; mid = (mid + Math.imul(al0, bh6)) | 0; mid = (mid + Math.imul(ah0, bl6)) | 0; hi = (hi + Math.imul(ah0, bh6)) | 0; var w6 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w6 >>> 26)) | 0; w6 &= 0x3ffffff; /* k = 7 */ lo = Math.imul(al7, bl0); mid = Math.imul(al7, bh0); mid = (mid + Math.imul(ah7, bl0)) | 0; hi = Math.imul(ah7, bh0); lo = (lo + Math.imul(al6, bl1)) | 0; mid = (mid + Math.imul(al6, bh1)) | 0; mid = (mid + Math.imul(ah6, bl1)) | 0; hi = (hi + Math.imul(ah6, bh1)) | 0; lo = (lo + Math.imul(al5, bl2)) | 0; mid = (mid + Math.imul(al5, bh2)) | 0; mid = (mid + Math.imul(ah5, bl2)) | 0; hi = (hi + Math.imul(ah5, bh2)) | 0; lo = (lo + Math.imul(al4, bl3)) | 0; mid = (mid + Math.imul(al4, bh3)) | 0; mid = (mid + Math.imul(ah4, bl3)) | 0; hi = (hi + Math.imul(ah4, bh3)) | 0; lo = (lo + Math.imul(al3, bl4)) | 0; mid = (mid + Math.imul(al3, bh4)) | 0; mid = (mid + Math.imul(ah3, bl4)) | 0; hi = (hi + Math.imul(ah3, bh4)) | 0; lo = (lo + Math.imul(al2, bl5)) | 0; mid = (mid + Math.imul(al2, bh5)) | 0; mid = (mid + Math.imul(ah2, bl5)) | 0; hi = (hi + Math.imul(ah2, bh5)) | 0; lo = (lo + Math.imul(al1, bl6)) | 0; mid = (mid + Math.imul(al1, bh6)) | 0; mid = (mid + Math.imul(ah1, bl6)) | 0; hi = (hi + Math.imul(ah1, bh6)) | 0; lo = (lo + Math.imul(al0, bl7)) | 0; mid = (mid + Math.imul(al0, bh7)) | 0; mid = (mid + Math.imul(ah0, bl7)) | 0; hi = (hi + Math.imul(ah0, bh7)) | 0; var w7 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w7 >>> 26)) | 0; w7 &= 0x3ffffff; /* k = 8 */ lo = Math.imul(al8, bl0); mid = Math.imul(al8, bh0); mid = (mid + Math.imul(ah8, bl0)) | 0; hi = Math.imul(ah8, bh0); lo = (lo + Math.imul(al7, bl1)) | 0; mid = (mid + Math.imul(al7, bh1)) | 0; mid = (mid + Math.imul(ah7, bl1)) | 0; hi = (hi + Math.imul(ah7, bh1)) | 0; lo = (lo + Math.imul(al6, bl2)) | 0; mid = (mid + Math.imul(al6, bh2)) | 0; mid = (mid + Math.imul(ah6, bl2)) | 0; hi = (hi + Math.imul(ah6, bh2)) | 0; lo = (lo + Math.imul(al5, bl3)) | 0; mid = (mid + Math.imul(al5, bh3)) | 0; mid = (mid + Math.imul(ah5, bl3)) | 0; hi = (hi + Math.imul(ah5, bh3)) | 0; lo = (lo + Math.imul(al4, bl4)) | 0; mid = (mid + Math.imul(al4, bh4)) | 0; mid = (mid + Math.imul(ah4, bl4)) | 0; hi = (hi + Math.imul(ah4, bh4)) | 0; lo = (lo + Math.imul(al3, bl5)) | 0; mid = (mid + Math.imul(al3, bh5)) | 0; mid = (mid + Math.imul(ah3, bl5)) | 0; hi = (hi + Math.imul(ah3, bh5)) | 0; lo = (lo + Math.imul(al2, bl6)) | 0; mid = (mid + Math.imul(al2, bh6)) | 0; mid = (mid + Math.imul(ah2, bl6)) | 0; hi = (hi + Math.imul(ah2, bh6)) | 0; lo = (lo + Math.imul(al1, bl7)) | 0; mid = (mid + Math.imul(al1, bh7)) | 0; mid = (mid + Math.imul(ah1, bl7)) | 0; hi = (hi + Math.imul(ah1, bh7)) | 0; lo = (lo + Math.imul(al0, bl8)) | 0; mid = (mid + Math.imul(al0, bh8)) | 0; mid = (mid + Math.imul(ah0, bl8)) | 0; hi = (hi + Math.imul(ah0, bh8)) | 0; var w8 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w8 >>> 26)) | 0; w8 &= 0x3ffffff; /* k = 9 */ lo = Math.imul(al9, bl0); mid = Math.imul(al9, bh0); mid = (mid + Math.imul(ah9, bl0)) | 0; hi = Math.imul(ah9, bh0); lo = (lo + Math.imul(al8, bl1)) | 0; mid = (mid + Math.imul(al8, bh1)) | 0; mid = (mid + Math.imul(ah8, bl1)) | 0; hi = (hi + Math.imul(ah8, bh1)) | 0; lo = (lo + Math.imul(al7, bl2)) | 0; mid = (mid + Math.imul(al7, bh2)) | 0; mid = (mid + Math.imul(ah7, bl2)) | 0; hi = (hi + Math.imul(ah7, bh2)) | 0; lo = (lo + Math.imul(al6, bl3)) | 0; mid = (mid + Math.imul(al6, bh3)) | 0; mid = (mid + Math.imul(ah6, bl3)) | 0; hi = (hi + Math.imul(ah6, bh3)) | 0; lo = (lo + Math.imul(al5, bl4)) | 0; mid = (mid + Math.imul(al5, bh4)) | 0; mid = (mid + Math.imul(ah5, bl4)) | 0; hi = (hi + Math.imul(ah5, bh4)) | 0; lo = (lo + Math.imul(al4, bl5)) | 0; mid = (mid + Math.imul(al4, bh5)) | 0; mid = (mid + Math.imul(ah4, bl5)) | 0; hi = (hi + Math.imul(ah4, bh5)) | 0; lo = (lo + Math.imul(al3, bl6)) | 0; mid = (mid + Math.imul(al3, bh6)) | 0; mid = (mid + Math.imul(ah3, bl6)) | 0; hi = (hi + Math.imul(ah3, bh6)) | 0; lo = (lo + Math.imul(al2, bl7)) | 0; mid = (mid + Math.imul(al2, bh7)) | 0; mid = (mid + Math.imul(ah2, bl7)) | 0; hi = (hi + Math.imul(ah2, bh7)) | 0; lo = (lo + Math.imul(al1, bl8)) | 0; mid = (mid + Math.imul(al1, bh8)) | 0; mid = (mid + Math.imul(ah1, bl8)) | 0; hi = (hi + Math.imul(ah1, bh8)) | 0; lo = (lo + Math.imul(al0, bl9)) | 0; mid = (mid + Math.imul(al0, bh9)) | 0; mid = (mid + Math.imul(ah0, bl9)) | 0; hi = (hi + Math.imul(ah0, bh9)) | 0; var w9 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w9 >>> 26)) | 0; w9 &= 0x3ffffff; /* k = 10 */ lo = Math.imul(al9, bl1); mid = Math.imul(al9, bh1); mid = (mid + Math.imul(ah9, bl1)) | 0; hi = Math.imul(ah9, bh1); lo = (lo + Math.imul(al8, bl2)) | 0; mid = (mid + Math.imul(al8, bh2)) | 0; mid = (mid + Math.imul(ah8, bl2)) | 0; hi = (hi + Math.imul(ah8, bh2)) | 0; lo = (lo + Math.imul(al7, bl3)) | 0; mid = (mid + Math.imul(al7, bh3)) | 0; mid = (mid + Math.imul(ah7, bl3)) | 0; hi = (hi + Math.imul(ah7, bh3)) | 0; lo = (lo + Math.imul(al6, bl4)) | 0; mid = (mid + Math.imul(al6, bh4)) | 0; mid = (mid + Math.imul(ah6, bl4)) | 0; hi = (hi + Math.imul(ah6, bh4)) | 0; lo = (lo + Math.imul(al5, bl5)) | 0; mid = (mid + Math.imul(al5, bh5)) | 0; mid = (mid + Math.imul(ah5, bl5)) | 0; hi = (hi + Math.imul(ah5, bh5)) | 0; lo = (lo + Math.imul(al4, bl6)) | 0; mid = (mid + Math.imul(al4, bh6)) | 0; mid = (mid + Math.imul(ah4, bl6)) | 0; hi = (hi + Math.imul(ah4, bh6)) | 0; lo = (lo + Math.imul(al3, bl7)) | 0; mid = (mid + Math.imul(al3, bh7)) | 0; mid = (mid + Math.imul(ah3, bl7)) | 0; hi = (hi + Math.imul(ah3, bh7)) | 0; lo = (lo + Math.imul(al2, bl8)) | 0; mid = (mid + Math.imul(al2, bh8)) | 0; mid = (mid + Math.imul(ah2, bl8)) | 0; hi = (hi + Math.imul(ah2, bh8)) | 0; lo = (lo + Math.imul(al1, bl9)) | 0; mid = (mid + Math.imul(al1, bh9)) | 0; mid = (mid + Math.imul(ah1, bl9)) | 0; hi = (hi + Math.imul(ah1, bh9)) | 0; var w10 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w10 >>> 26)) | 0; w10 &= 0x3ffffff; /* k = 11 */ lo = Math.imul(al9, bl2); mid = Math.imul(al9, bh2); mid = (mid + Math.imul(ah9, bl2)) | 0; hi = Math.imul(ah9, bh2); lo = (lo + Math.imul(al8, bl3)) | 0; mid = (mid + Math.imul(al8, bh3)) | 0; mid = (mid + Math.imul(ah8, bl3)) | 0; hi = (hi + Math.imul(ah8, bh3)) | 0; lo = (lo + Math.imul(al7, bl4)) | 0; mid = (mid + Math.imul(al7, bh4)) | 0; mid = (mid + Math.imul(ah7, bl4)) | 0; hi = (hi + Math.imul(ah7, bh4)) | 0; lo = (lo + Math.imul(al6, bl5)) | 0; mid = (mid + Math.imul(al6, bh5)) | 0; mid = (mid + Math.imul(ah6, bl5)) | 0; hi = (hi + Math.imul(ah6, bh5)) | 0; lo = (lo + Math.imul(al5, bl6)) | 0; mid = (mid + Math.imul(al5, bh6)) | 0; mid = (mid + Math.imul(ah5, bl6)) | 0; hi = (hi + Math.imul(ah5, bh6)) | 0; lo = (lo + Math.imul(al4, bl7)) | 0; mid = (mid + Math.imul(al4, bh7)) | 0; mid = (mid + Math.imul(ah4, bl7)) | 0; hi = (hi + Math.imul(ah4, bh7)) | 0; lo = (lo + Math.imul(al3, bl8)) | 0; mid = (mid + Math.imul(al3, bh8)) | 0; mid = (mid + Math.imul(ah3, bl8)) | 0; hi = (hi + Math.imul(ah3, bh8)) | 0; lo = (lo + Math.imul(al2, bl9)) | 0; mid = (mid + Math.imul(al2, bh9)) | 0; mid = (mid + Math.imul(ah2, bl9)) | 0; hi = (hi + Math.imul(ah2, bh9)) | 0; var w11 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w11 >>> 26)) | 0; w11 &= 0x3ffffff; /* k = 12 */ lo = Math.imul(al9, bl3); mid = Math.imul(al9, bh3); mid = (mid + Math.imul(ah9, bl3)) | 0; hi = Math.imul(ah9, bh3); lo = (lo + Math.imul(al8, bl4)) | 0; mid = (mid + Math.imul(al8, bh4)) | 0; mid = (mid + Math.imul(ah8, bl4)) | 0; hi = (hi + Math.imul(ah8, bh4)) | 0; lo = (lo + Math.imul(al7, bl5)) | 0; mid = (mid + Math.imul(al7, bh5)) | 0; mid = (mid + Math.imul(ah7, bl5)) | 0; hi = (hi + Math.imul(ah7, bh5)) | 0; lo = (lo + Math.imul(al6, bl6)) | 0; mid = (mid + Math.imul(al6, bh6)) | 0; mid = (mid + Math.imul(ah6, bl6)) | 0; hi = (hi + Math.imul(ah6, bh6)) | 0; lo = (lo + Math.imul(al5, bl7)) | 0; mid = (mid + Math.imul(al5, bh7)) | 0; mid = (mid + Math.imul(ah5, bl7)) | 0; hi = (hi + Math.imul(ah5, bh7)) | 0; lo = (lo + Math.imul(al4, bl8)) | 0; mid = (mid + Math.imul(al4, bh8)) | 0; mid = (mid + Math.imul(ah4, bl8)) | 0; hi = (hi + Math.imul(ah4, bh8)) | 0; lo = (lo + Math.imul(al3, bl9)) | 0; mid = (mid + Math.imul(al3, bh9)) | 0; mid = (mid + Math.imul(ah3, bl9)) | 0; hi = (hi + Math.imul(ah3, bh9)) | 0; var w12 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w12 >>> 26)) | 0; w12 &= 0x3ffffff; /* k = 13 */ lo = Math.imul(al9, bl4); mid = Math.imul(al9, bh4); mid = (mid + Math.imul(ah9, bl4)) | 0; hi = Math.imul(ah9, bh4); lo = (lo + Math.imul(al8, bl5)) | 0; mid = (mid + Math.imul(al8, bh5)) | 0; mid = (mid + Math.imul(ah8, bl5)) | 0; hi = (hi + Math.imul(ah8, bh5)) | 0; lo = (lo + Math.imul(al7, bl6)) | 0; mid = (mid + Math.imul(al7, bh6)) | 0; mid = (mid + Math.imul(ah7, bl6)) | 0; hi = (hi + Math.imul(ah7, bh6)) | 0; lo = (lo + Math.imul(al6, bl7)) | 0; mid = (mid + Math.imul(al6, bh7)) | 0; mid = (mid + Math.imul(ah6, bl7)) | 0; hi = (hi + Math.imul(ah6, bh7)) | 0; lo = (lo + Math.imul(al5, bl8)) | 0; mid = (mid + Math.imul(al5, bh8)) | 0; mid = (mid + Math.imul(ah5, bl8)) | 0; hi = (hi + Math.imul(ah5, bh8)) | 0; lo = (lo + Math.imul(al4, bl9)) | 0; mid = (mid + Math.imul(al4, bh9)) | 0; mid = (mid + Math.imul(ah4, bl9)) | 0; hi = (hi + Math.imul(ah4, bh9)) | 0; var w13 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w13 >>> 26)) | 0; w13 &= 0x3ffffff; /* k = 14 */ lo = Math.imul(al9, bl5); mid = Math.imul(al9, bh5); mid = (mid + Math.imul(ah9, bl5)) | 0; hi = Math.imul(ah9, bh5); lo = (lo + Math.imul(al8, bl6)) | 0; mid = (mid + Math.imul(al8, bh6)) | 0; mid = (mid + Math.imul(ah8, bl6)) | 0; hi = (hi + Math.imul(ah8, bh6)) | 0; lo = (lo + Math.imul(al7, bl7)) | 0; mid = (mid + Math.imul(al7, bh7)) | 0; mid = (mid + Math.imul(ah7, bl7)) | 0; hi = (hi + Math.imul(ah7, bh7)) | 0; lo = (lo + Math.imul(al6, bl8)) | 0; mid = (mid + Math.imul(al6, bh8)) | 0; mid = (mid + Math.imul(ah6, bl8)) | 0; hi = (hi + Math.imul(ah6, bh8)) | 0; lo = (lo + Math.imul(al5, bl9)) | 0; mid = (mid + Math.imul(al5, bh9)) | 0; mid = (mid + Math.imul(ah5, bl9)) | 0; hi = (hi + Math.imul(ah5, bh9)) | 0; var w14 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w14 >>> 26)) | 0; w14 &= 0x3ffffff; /* k = 15 */ lo = Math.imul(al9, bl6); mid = Math.imul(al9, bh6); mid = (mid + Math.imul(ah9, bl6)) | 0; hi = Math.imul(ah9, bh6); lo = (lo + Math.imul(al8, bl7)) | 0; mid = (mid + Math.imul(al8, bh7)) | 0; mid = (mid + Math.imul(ah8, bl7)) | 0; hi = (hi + Math.imul(ah8, bh7)) | 0; lo = (lo + Math.imul(al7, bl8)) | 0; mid = (mid + Math.imul(al7, bh8)) | 0; mid = (mid + Math.imul(ah7, bl8)) | 0; hi = (hi + Math.imul(ah7, bh8)) | 0; lo = (lo + Math.imul(al6, bl9)) | 0; mid = (mid + Math.imul(al6, bh9)) | 0; mid = (mid + Math.imul(ah6, bl9)) | 0; hi = (hi + Math.imul(ah6, bh9)) | 0; var w15 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w15 >>> 26)) | 0; w15 &= 0x3ffffff; /* k = 16 */ lo = Math.imul(al9, bl7); mid = Math.imul(al9, bh7); mid = (mid + Math.imul(ah9, bl7)) | 0; hi = Math.imul(ah9, bh7); lo = (lo + Math.imul(al8, bl8)) | 0; mid = (mid + Math.imul(al8, bh8)) | 0; mid = (mid + Math.imul(ah8, bl8)) | 0; hi = (hi + Math.imul(ah8, bh8)) | 0; lo = (lo + Math.imul(al7, bl9)) | 0; mid = (mid + Math.imul(al7, bh9)) | 0; mid = (mid + Math.imul(ah7, bl9)) | 0; hi = (hi + Math.imul(ah7, bh9)) | 0; var w16 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w16 >>> 26)) | 0; w16 &= 0x3ffffff; /* k = 17 */ lo = Math.imul(al9, bl8); mid = Math.imul(al9, bh8); mid = (mid + Math.imul(ah9, bl8)) | 0; hi = Math.imul(ah9, bh8); lo = (lo + Math.imul(al8, bl9)) | 0; mid = (mid + Math.imul(al8, bh9)) | 0; mid = (mid + Math.imul(ah8, bl9)) | 0; hi = (hi + Math.imul(ah8, bh9)) | 0; var w17 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w17 >>> 26)) | 0; w17 &= 0x3ffffff; /* k = 18 */ lo = Math.imul(al9, bl9); mid = Math.imul(al9, bh9); mid = (mid + Math.imul(ah9, bl9)) | 0; hi = Math.imul(ah9, bh9); var w18 = (((c + lo) | 0) + ((mid & 0x1fff) << 13)) | 0; c = (((hi + (mid >>> 13)) | 0) + (w18 >>> 26)) | 0; w18 &= 0x3ffffff; o[0] = w0; o[1] = w1; o[2] = w2; o[3] = w3; o[4] = w4; o[5] = w5; o[6] = w6; o[7] = w7; o[8] = w8; o[9] = w9; o[10] = w10; o[11] = w11; o[12] = w12; o[13] = w13; o[14] = w14; o[15] = w15; o[16] = w16; o[17] = w17; o[18] = w18; if (c !== 0) { o[19] = c; out.length++; } return out; }; // Polyfill comb if (!Math.imul) { comb10MulTo = smallMulTo; } function bigMulTo (self, num, out) { out.negative = num.negative ^ self.negative; out.length = self.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 - self.length + 1); j <= maxJ; j++) { var i = k - j; var a = self.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(); } function jumboMulTo (self, num, out) { var fftm = new FFTM(); return fftm.mulp(self, num, out); } BN.prototype.mulTo = function mulTo (num, out) { var res; var len = this.length + num.length; if (this.length === 10 && num.length === 10) { res = comb10MulTo(this, num, out); } else if (len < 63) { res = smallMulTo(this, num, out); } else if (len < 1024) { res = bigMulTo(this, num, out); } else { res = jumboMulTo(this, num, out); } return res; }; // Cooley-Tukey algorithm for FFT // slightly revisited to rely on looping instead of recursion function FFTM (x, y) { this.x = x; this.y = y; } FFTM.prototype.makeRBT = function makeRBT (N) { var t = new Array(N); var l = BN.prototype._countBits(N) - 1; for (var i = 0; i < N; i++) { t[i] = this.revBin(i, l, N); } return t; }; // Returns binary-reversed representation of `x` FFTM.prototype.revBin = function revBin (x, l, N) { if (x === 0 || x === N - 1) return x; var rb = 0; for (var i = 0; i < l; i++) { rb |= (x & 1) << (l - i - 1); x >>= 1; } return rb; }; // Performs "tweedling" phase, therefore 'emulating' // behaviour of the recursive algorithm FFTM.prototype.permute = function permute (rbt, rws, iws, rtws, itws, N) { for (var i = 0; i < N; i++) { rtws[i] = rws[rbt[i]]; itws[i] = iws[rbt[i]]; } }; FFTM.prototype.transform = function transform (rws, iws, rtws, itws, N, rbt) { this.permute(rbt, rws, iws, rtws, itws, N); for (var s = 1; s < N; s <<= 1) { var l = s << 1; var rtwdf = Math.cos(2 * Math.PI / l); var itwdf = Math.sin(2 * Math.PI / l); for (var p = 0; p < N; p += l) { var rtwdf_ = rtwdf; var itwdf_ = itwdf; for (var j = 0; j < s; j++) { var re = rtws[p + j]; var ie = itws[p + j]; var ro = rtws[p + j + s]; var io = itws[p + j + s]; var rx = rtwdf_ * ro - itwdf_ * io; io = rtwdf_ * io + itwdf_ * ro; ro = rx; rtws[p + j] = re + ro; itws[p + j] = ie + io; rtws[p + j + s] = re - ro; itws[p + j + s] = ie - io; /* jshint maxdepth : false */ if (j !== l) { rx = rtwdf * rtwdf_ - itwdf * itwdf_; itwdf_ = rtwdf * itwdf_ + itwdf * rtwdf_; rtwdf_ = rx; } } } } }; FFTM.prototype.guessLen13b = function guessLen13b (n, m) { var N = Math.max(m, n) | 1; var odd = N & 1; var i = 0; for (N = N / 2 | 0; N; N = N >>> 1) { i++; } return 1 << i + 1 + odd; }; FFTM.prototype.conjugate = function conjugate (rws, iws, N) { if (N <= 1) return; for (var i = 0; i < N / 2; i++) { var t = rws[i]; rws[i] = rws[N - i - 1]; rws[N - i - 1] = t; t = iws[i]; iws[i] = -iws[N - i - 1]; iws[N - i - 1] = -t; } }; FFTM.prototype.normalize13b = function normalize13b (ws, N) { var carry = 0; for (var i = 0; i < N / 2; i++) { var w = Math.round(ws[2 * i + 1] / N) * 0x2000 + Math.round(ws[2 * i] / N) + carry; ws[i] = w & 0x3ffffff; if (w < 0x4000000) { carry = 0; } else { carry = w / 0x4000000 | 0; } } return ws; }; FFTM.prototype.convert13b = function convert13b (ws, len, rws, N) { var carry = 0; for (var i = 0; i < len; i++) { carry = carry + (ws[i] | 0); rws[2 * i] = carry & 0x1fff; carry = carry >>> 13; rws[2 * i + 1] = carry & 0x1fff; carry = carry >>> 13; } // Pad with zeroes for (i = 2 * len; i < N; ++i) { rws[i] = 0; } assert(carry === 0); assert((carry & ~0x1fff) === 0); }; FFTM.prototype.stub = function stub (N) { var ph = new Array(N); for (var i = 0; i < N; i++) { ph[i] = 0; } return ph; }; FFTM.prototype.mulp = function mulp (x, y, out) { var N = 2 * this.guessLen13b(x.length, y.length); var rbt = this.makeRBT(N); var _ = this.stub(N); var rws = new Array(N); var rwst = new Array(N); var iwst = new Array(N); var nrws = new Array(N); var nrwst = new Array(N); var niwst = new Array(N); var rmws = out.words; rmws.length = N; this.convert13b(x.words, x.length, rws, N); this.convert13b(y.words, y.length, nrws, N); this.transform(rws, _, rwst, iwst, N, rbt); this.transform(nrws, _, nrwst, niwst, N, rbt); for (var i = 0; i < N; i++) { var rx = rwst[i] * nrwst[i] - iwst[i] * niwst[i]; iwst[i] = rwst[i] * niwst[i] + iwst[i] * nrwst[i]; rwst[i] = rx; } this.conjugate(rwst, iwst, N); this.transform(rwst, iwst, rmws, _, N, rbt); this.conjugate(rmws, _, N); this.normalize13b(rmws, N); out.negative = x.negative ^ y.negative; out.length = x.length + y.length; return out.strip(); }; // 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); }; // Multiply employing FFT BN.prototype.mulf = function mulf (num) { var out = new BN(null); out.words = new Array(this.length + num.length); return jumboMulTo(this, num, out); }; // In-place Multiplication BN.prototype.imul = function imul (num) { return this.clone().mulTo(num, this); }; BN.prototype.imuln = function imuln (num) { assert(typeof num === 'number'); assert(num < 0x4000000); // Carry var carry = 0; for (var i = 0; i < this.length; i++) { var w = (this.words[i] | 0) * num; var lo = (w & 0x3ffffff) + (carry & 0x3ffffff); carry >>= 26; carry += (w / 0x4000000) | 0; // NOTE: lo is 27bit maximum carry += lo >>> 26; this.words[i] = lo & 0x3ffffff; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.muln = function muln (num) { return this.clone().imuln(num); }; // `this` * `this` BN.prototype.sqr = function sqr () { return this.mul(this); }; // `this` * `this` in-place BN.prototype.isqr = function isqr () { return this.imul(this.clone()); }; // Math.pow(`this`, `num`) BN.prototype.pow = function pow (num) { var w = toBitArray(num); if (w.length === 0) return new BN(1); // Skip leading zeroes var res = this; for (var i = 0; i < w.length; i++, res = res.sqr()) { if (w[i] !== 0) break; } if (++i < w.length) { for (var q = res.sqr(); i < w.length; i++, q = q.sqr()) { if (w[i] === 0) continue; res = res.mul(q); } } return res; }; // Shift-left in-place BN.prototype.iushln = function iushln (bits) { assert(typeof bits === 'number' && bits >= 0); var r = bits % 26; var s = (bits - r) / 26; var carryMask = (0x3ffffff >>> (26 - r)) << (26 - r); var i; if (r !== 0) { var carry = 0; for (i = 0; i < this.length; i++) { var newCarry = this.words[i] & carryMask; var c = ((this.words[i] | 0) - newCarry) << r; this.words[i] = c | carry; carry = newCarry >>> (26 - r); } if (carry) { this.words[i] = carry; this.length++; } } if (s !== 0) { for (i = this.length - 1; i >= 0; i--) { this.words[i + s] = this.words[i]; } for (i = 0; i < s; i++) { this.words[i] = 0; } this.length += s; } return this.strip(); }; BN.prototype.ishln = function ishln (bits) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushln(bits); }; // Shift-right in-place // NOTE: `hint` is a lowest bit before trailing zeroes // NOTE: if `extended` is present - it will be filled with destroyed bits BN.prototype.iushrn = function iushrn (bits, hint, extended) { assert(typeof bits === 'number' && bits >= 0); var h; if (hint) { h = (hint - (hint % 26)) / 26; } else { h = 0; } var r = bits % 26; var s = Math.min((bits - r) / 26, this.length); var mask = 0x3ffffff ^ ((0x3ffffff >>> r) << r); var maskedWords = extended; h -= s; h = Math.max(0, h); // 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 (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 (i = this.length - 1; i >= 0 && (carry !== 0 || i >= h); i--) { var word = this.words[i] | 0; 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; } return this.strip(); }; BN.prototype.ishrn = function ishrn (bits, hint, extended) { // TODO(indutny): implement me assert(this.negative === 0); return this.iushrn(bits, hint, extended); }; // Shift-left BN.prototype.shln = function shln (bits) { return this.clone().ishln(bits); }; BN.prototype.ushln = function ushln (bits) { return this.clone().iushln(bits); }; // Shift-right BN.prototype.shrn = function shrn (bits) { return this.clone().ishrn(bits); }; BN.prototype.ushrn = function ushrn (bits) { return this.clone().iushrn(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.negative === 0, 'imaskn works only with positive numbers'); if (this.length <= s) { return this; } 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'); assert(num < 0x4000000); if (num < 0) return this.isubn(-num); // Possible sign change if (this.negative !== 0) { if (this.length === 1 && (this.words[0] | 0) < num) { this.words[0] = num - (this.words[0] | 0); this.negative = 0; return this; } this.negative = 0; this.isubn(num); this.negative = 1; return this; } // Add without checks return this._iaddn(num); }; BN.prototype._iaddn = function _iaddn (num) { 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'); assert(num < 0x4000000); if (num < 0) return this.iaddn(-num); if (this.negative !== 0) { this.negative = 0; this.iaddn(num); this.negative = 1; return this; } this.words[0] -= num; if (this.length === 1 && this.words[0] < 0) { this.words[0] = -this.words[0]; this.negative = 1; } else { // 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.negative = 0; return this; }; BN.prototype.abs = function abs () { return this.clone().iabs(); }; BN.prototype._ishlnsubmul = function _ishlnsubmul (num, mul, shift) { var len = num.length + shift; var i; this._expand(len); var w; var carry = 0; for (i = 0; i < num.length; i++) { w = (this.words[i + shift] | 0) + carry; var right = (num.words[i] | 0) * mul; w -= right & 0x3ffffff; carry = (w >> 26) - ((right / 0x4000000) | 0); this.words[i + shift] = w & 0x3ffffff; } for (; i < this.length - shift; i++) { w = (this.words[i + shift] | 0) + carry; carry = w >> 26; this.words[i + shift] = w & 0x3ffffff; } if (carry === 0) return this.strip(); // Subtraction overflow assert(carry === -1); carry = 0; for (i = 0; i < this.length; i++) { w = -(this.words[i] | 0) + carry; carry = w >> 26; this.words[i] = w & 0x3ffffff; } this.negative = 1; return this.strip(); }; BN.prototype._wordDiv = function _wordDiv (num, mode) { var shift = this.length - num.length; var a = this.clone(); var b = num; // Normalize var bhi = b.words[b.length - 1] | 0; var bhiBits = this._countBits(bhi); shift = 26 - bhiBits; if (shift !== 0) { b = b.ushln(shift); a.iushln(shift); bhi = b.words[b.length - 1] | 0; } // Initialize quotient var m = a.length - b.length; var q; if (mode !== 'mod') { q = new BN(null); q.length = m + 1; q.words = new Array(q.length); for (var i = 0; i < q.length; i++) { q.words[i] = 0; } } var diff = a.clone()._ishlnsubmul(b, 1, m); if (diff.negative === 0) { a = diff; if (q) { q.words[m] = 1; } } for (var j = m - 1; j >= 0; j--) { var qj = (a.words[b.length + j] | 0) * 0x4000000 + (a.words[b.length + j - 1] | 0); // NOTE: (qj / bhi) is (0x3ffffff * 0x4000000 + 0x3ffffff) / 0x2000000 max // (0x7ffffff) qj = Math.min((qj / bhi) | 0, 0x3ffffff); a._ishlnsubmul(b, qj, j); while (a.negative !== 0) { qj--; a.negative = 0; a._ishlnsubmul(b, 1, j); if (!a.isZero()) { a.negative ^= 1; } } if (q) { q.words[j] = qj; } } if (q) { q.strip(); } a.strip(); // Denormalize if (mode !== 'div' && shift !== 0) { a.iushrn(shift); } return { div: q || null, mod: a }; }; // NOTE: 1) `mode` can be set to `mod` to request mod only, // to `div` to request div only, or be absent to // request both div & mod // 2) `positive` is true if unsigned mod is requested BN.prototype.divmod = function divmod (num, mode, positive) { assert(!num.isZero()); if (this.isZero()) { return { div: new BN(0), mod: new BN(0) }; } var div, mod, res; if (this.negative !== 0 && num.negative === 0) { res = this.neg().divmod(num, mode); if (mode !== 'mod') { div = res.div.neg(); } if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.iadd(num); } } return { div: div, mod: mod }; } if (this.negative === 0 && num.negative !== 0) { res = this.divmod(num.neg(), mode); if (mode !== 'mod') { div = res.div.neg(); } return { div: div, mod: res.mod }; } if ((this.negative & num.negative) !== 0) { res = this.neg().divmod(num.neg(), mode); if (mode !== 'div') { mod = res.mod.neg(); if (positive && mod.negative !== 0) { mod.isub(num); } } return { div: res.div, mod: mod }; } // 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 }; } 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', false).div; }; // Find `this` % `num` BN.prototype.mod = function mod (num) { return this.divmod(num, 'mod', false).mod; }; BN.prototype.umod = function umod (num) { return this.divmod(num, 'mod', true).mod; }; // Find Round(`this` / `num`) BN.prototype.divRound = function divRound (num) { var dm = this.divmod(num); // Fast case - exact division if (dm.mod.isZero()) return dm.div; var mod = dm.div.negative !== 0 ? dm.mod.isub(num) : dm.mod; var half = num.ushrn(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.negative !== 0 ? 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] | 0)) % 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] | 0) + 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 (p) { assert(p.negative === 0); assert(!p.isZero()); var x = this; var y = p.clone(); if (x.negative !== 0) { x = x.umod(p); } else { x = x.clone(); } // A * x + B * y = x var A = new BN(1); var B = new BN(0); // C * x + D * y = y var C = new BN(0); var D = new BN(1); var g = 0; while (x.isEven() && y.isEven()) { x.iushrn(1); y.iushrn(1); ++g; } var yp = y.clone(); var xp = x.clone(); while (!x.isZero()) { for (var i = 0, im = 1; (x.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { x.iushrn(i); while (i-- > 0) { if (A.isOdd() || B.isOdd()) { A.iadd(yp); B.isub(xp); } A.iushrn(1); B.iushrn(1); } } for (var j = 0, jm = 1; (y.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { y.iushrn(j); while (j-- > 0) { if (C.isOdd() || D.isOdd()) { C.iadd(yp); D.isub(xp); } C.iushrn(1); D.iushrn(1); } } if (x.cmp(y) >= 0) { x.isub(y); A.isub(C); B.isub(D); } else { y.isub(x); C.isub(A); D.isub(B); } } return { a: C, b: D, gcd: y.iushln(g) }; }; // This is reduced incarnation of the binary EEA // above, designated to invert members of the // _prime_ fields F(p) at a maximal speed BN.prototype._invmp = function _invmp (p) { assert(p.negative === 0); assert(!p.isZero()); var a = this; var b = p.clone(); if (a.negative !== 0) { a = a.umod(p); } else { a = a.clone(); } var x1 = new BN(1); var x2 = new BN(0); var delta = b.clone(); while (a.cmpn(1) > 0 && b.cmpn(1) > 0) { for (var i = 0, im = 1; (a.words[0] & im) === 0 && i < 26; ++i, im <<= 1); if (i > 0) { a.iushrn(i); while (i-- > 0) { if (x1.isOdd()) { x1.iadd(delta); } x1.iushrn(1); } } for (var j = 0, jm = 1; (b.words[0] & jm) === 0 && j < 26; ++j, jm <<= 1); if (j > 0) { b.iushrn(j); while (j-- > 0) { if (x2.isOdd()) { x2.iadd(delta); } x2.iushrn(1); } } if (a.cmp(b) >= 0) { a.isub(b); x1.isub(x2); } else { b.isub(a); x2.isub(x1); } } var res; if (a.cmpn(1) === 0) { res = x1; } else { res = x2; } if (res.cmpn(0) < 0) { res.iadd(p); } return res; }; BN.prototype.gcd = function gcd (num) { if (this.isZero()) return num.abs(); if (num.isZero()) return this.abs(); var a = this.clone(); var b = num.clone(); a.negative = 0; b.negative = 0; // Remove common factor of two for (var shift = 0; a.isEven() && b.isEven(); shift++) { a.iushrn(1); b.iushrn(1); } do { while (a.isEven()) { a.iushrn(1); } while (b.isEven()) { b.iushrn(1); } var r = a.cmp(b); if (r < 0) { // Swap `a` and `b` to make `a` always bigger than `b` var t = a; a = b; b = t; } else if (r === 0 || b.cmpn(1) === 0) { break; } a.isub(b); } while (true); return b.iushln(shift); }; // Invert number in the field F(num) BN.prototype.invm = function invm (num) { return this.egcd(num).a.umod(num); }; BN.prototype.isEven = function isEven () { return (this.words[0] & 1) === 0; }; BN.prototype.isOdd = function isOdd () { 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) { this._expand(s + 1); this.words[s] |= q; 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] | 0; w += carry; carry = w >>> 26; w &= 0x3ffffff; this.words[i] = w; } if (carry !== 0) { this.words[i] = carry; this.length++; } return this; }; BN.prototype.isZero = function isZero () { return this.length === 1 && this.words[0] === 0; }; BN.prototype.cmpn = function cmpn (num) { var negative = num < 0; if (this.negative !== 0 && !negative) return -1; if (this.negative === 0 && negative) return 1; this.strip(); var res; if (this.length > 1) { res = 1; } else { if (negative) { num = -num; } assert(num <= 0x3ffffff, 'Number is too big'); var w = this.words[0] | 0; res = w === num ? 0 : w < num ? -1 : 1; } if (this.negative !== 0) return -res | 0; 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.negative !== 0 && num.negative === 0) return -1; if (this.negative === 0 && num.negative !== 0) return 1; var res = this.ucmp(num); if (this.negative !== 0) return -res | 0; 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; if (this.length < num.length) return -1; var res = 0; for (var i = this.length - 1; i >= 0; i--) { var a = this.words[i] | 0; var b = num.words[i] | 0; if (a === b) continue; if (a < b) { res = -1; } else if (a > b) { res = 1; } break; } return res; }; BN.prototype.gtn = function gtn (num) { return this.cmpn(num) === 1; }; BN.prototype.gt = function gt (num) { return this.cmp(num) === 1; }; BN.prototype.gten = function gten (num) { return this.cmpn(num) >= 0; }; BN.prototype.gte = function gte (num) { return this.cmp(num) >= 0; }; BN.prototype.ltn = function ltn (num) { return this.cmpn(num) === -1; }; BN.prototype.lt = function lt (num) { return this.cmp(num) === -1; }; BN.prototype.lten = function lten (num) { return this.cmpn(num) <= 0; }; BN.prototype.lte = function lte (num) { return this.cmp(num) <= 0; }; BN.prototype.eqn = function eqn (num) { return this.cmpn(num) === 0; }; BN.prototype.eq = function eq (num) { return this.cmp(num) === 0; }; // // 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.negative === 0, '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).iushln(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 { this.split(r, this.tmp); r = this.imulK(r); r = r.iadd(this.tmp); rlen = r.bitLength(); } while (rlen > this.n); var cmp = rlen < this.n ? -1 : r.ucmp(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.split = function split (input, out) { input.iushrn(this.n, 0, out); }; 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.split = function split (input, output) { // 256 = 9 * 26 + 22 var mask = 0x3fffff; var outLen = Math.min(input.length, 9); for (var i = 0; i < outLen; i++) { output.words[i] = input.words[i]; } output.length = outLen; if (input.length <= 9) { input.words[0] = 0; input.length = 1; return; } // Shift by 9 limbs var prev = input.words[9]; output.words[output.length++] = prev & mask; for (i = 10; i < input.length; i++) { var next = input.words[i] | 0; input.words[i - 10] = ((next & mask) << 4) | (prev >>> 22); prev = next; } prev >>>= 22; input.words[i - 10] = prev; if (prev === 0 && input.length > 10) { input.length -= 10; } else { input.length -= 9; } }; K256.prototype.imulK = function imulK (num) { // K = 0x1000003d1 = [ 0x40, 0x3d1 ] num.words[num.length] = 0; num.words[num.length + 1] = 0; num.length += 2; // bounded at: 0x40 * 0x3ffffff + 0x3d0 = 0x100000390 var lo = 0; for (var i = 0; i < num.length; i++) { var w = num.words[i] | 0; lo += w * 0x3d1; num.words[i] = lo & 0x3ffffff; lo = w * 0x40 + ((lo / 0x4000000) | 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] | 0) * 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 { assert(m.gtn(1), 'modulus must be greater than 1'); this.m = m; this.prime = null; } } Red.prototype._verify1 = function _verify1 (a) { assert(a.negative === 0, 'red works only with positives'); assert(a.red, 'red works only with red numbers'); }; Red.prototype._verify2 = function _verify2 (a, b) { assert((a.negative | b.negative) === 0, '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.umod(this.m)._forceRed(this); }; Red.prototype.neg = function neg (a) { if (a.isZero()) { return a.clone(); } return this.m.sub(a)._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.ushln(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.clone()); }; Red.prototype.sqr = function sqr (a) { return this.mul(a, a); }; Red.prototype.sqrt = function sqrt (a) { if (a.isZero()) 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)).iushrn(2); return this.pow(a, pow); } // 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.isZero() && q.andln(1) === 0) { s++; q.iushrn(1); } assert(!q.isZero()); 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).iushrn(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).iushrn(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).iushln(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._invmp(this.m); if (inv.negative !== 0) { inv.negative = 0; return this.imod(inv).redNeg(); } else { return this.imod(inv); } }; Red.prototype.pow = function pow (a, num) { if (num.isZero()) return new BN(1).toRed(this); if (num.cmpn(1) === 0) return a.clone(); var windowSize = 4; var wnd = new Array(1 << windowSize); wnd[0] = new BN(1).toRed(this); wnd[1] = a; for (var i = 2; i < wnd.length; i++) { wnd[i] = this.mul(wnd[i - 1], a); } var res = wnd[0]; var current = 0; var currentLen = 0; var start = num.bitLength() % 26; if (start === 0) { start = 26; } for (i = num.length - 1; i >= 0; i--) { var word = num.words[i]; for (var j = start - 1; j >= 0; j--) { var bit = (word >> j) & 1; if (res !== wnd[0]) { res = this.sqr(res); } if (bit === 0 && current === 0) { currentLen = 0; continue; } current <<= 1; current |= bit; currentLen++; if (currentLen !== windowSize && (i !== 0 || j !== 0)) continue; res = this.mul(res, wnd[current]); currentLen = 0; current = 0; } start = 26; } return res; }; Red.prototype.convertTo = function convertTo (num) { var r = num.umod(this.m); return r === num ? r.clone() : r; }; 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).iushln(this.shift); this.r2 = this.imod(this.r.sqr()); this.rinv = this.r._invmp(this.m); this.minv = this.rinv.mul(this.r).isubn(1).div(this.m); this.minv = this.minv.umod(this.r); this.minv = this.r.sub(this.minv); } inherits(Mont, Red); Mont.prototype.convertTo = function convertTo (num) { return this.imod(num.ushln(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.isZero() || b.isZero()) { 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).iushrn(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.isZero() || b.isZero()) 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).iushrn(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._invmp(this.m).mul(this.r2)); return res._forceRed(this); }; })(typeof module === 'undefined' || module, this); },{"buffer":151}],131:[function(require,module,exports){ module.exports = { trueFunc: function trueFunc(){ return true; }, falseFunc: function falseFunc(){ return false; } }; },{}],132:[function(require,module,exports){ var r; module.exports = function rand(len) { if (!r) r = new Rand(null); return r.generate(len); }; function Rand(rand) { this.rand = rand; } module.exports.Rand = Rand; Rand.prototype.generate = function generate(len) { return this._rand(len); }; // Emulate crypto API using randy Rand.prototype._rand = function _rand(n) { if (this.rand.getBytes) return this.rand.getBytes(n); var res = new Uint8Array(n); for (var i = 0; i < res.length; i++) res[i] = this.rand.getByte(); return res; }; if (typeof self === 'object') { if (self.crypto && self.crypto.getRandomValues) { // Modern browsers Rand.prototype._rand = function _rand(n) { var arr = new Uint8Array(n); self.crypto.getRandomValues(arr); return arr; }; } else if (self.msCrypto && self.msCrypto.getRandomValues) { // IE Rand.prototype._rand = function _rand(n) { var arr = new Uint8Array(n); self.msCrypto.getRandomValues(arr); return arr; }; // Safari's WebWorkers do not have `crypto` } else if (typeof window === 'object') { // Old junk Rand.prototype._rand = function() { throw new Error('Not implemented yet'); }; } } else { // Node.js or Web worker with no crypto support try { var crypto = require('crypto'); if (typeof crypto.randomBytes !== 'function') throw new Error('Not supported'); Rand.prototype._rand = function _rand(n) { return crypto.randomBytes(n); }; } catch (e) { } } },{"crypto":151}],133:[function(require,module,exports){ arguments[4][48][0].apply(exports,arguments) },{"./asn1/api":134,"./asn1/base":136,"./asn1/constants":140,"./asn1/decoders":142,"./asn1/encoders":145,"bn.js":149,"dup":48}],134:[function(require,module,exports){ arguments[4][49][0].apply(exports,arguments) },{"../asn1":133,"dup":49,"inherits":203,"vm":262}],135:[function(require,module,exports){ arguments[4][50][0].apply(exports,arguments) },{"../base":136,"buffer":179,"dup":50,"inherits":203}],136:[function(require,module,exports){ arguments[4][51][0].apply(exports,arguments) },{"./buffer":135,"./node":137,"./reporter":138,"dup":51}],137:[function(require,module,exports){ var Reporter = require('../base').Reporter; var EncoderBuffer = require('../base').EncoderBuffer; var DecoderBuffer = require('../base').DecoderBuffer; var assert = require('minimalistic-assert'); // Supported tags var tags = [ 'seq', 'seqof', 'set', 'setof', 'objid', 'bool', 'gentime', 'utctime', 'null_', 'enum', 'int', 'objDesc', 'bitstr', 'bmpstr', 'charstr', 'genstr', 'graphstr', 'ia5str', 'iso646str', 'numstr', 'octstr', 'printstr', 't61str', 'unistr', 'utf8str', 'videostr' ]; // Public methods list var methods = [ 'key', 'obj', 'use', 'optional', 'explicit', 'implicit', 'def', 'choice', 'any', 'contains' ].concat(tags); // Overrided methods list var overrided = [ '_peekTag', '_decodeTag', '_use', '_decodeStr', '_decodeObjid', '_decodeTime', '_decodeNull', '_decodeInt', '_decodeBool', '_decodeList', '_encodeComposite', '_encodeStr', '_encodeObjid', '_encodeTime', '_encodeNull', '_encodeInt', '_encodeBool' ]; function Node(enc, parent) { var state = {}; this._baseState = state; state.enc = enc; state.parent = parent || null; state.children = null; // State state.tag = null; state.args = null; state.reverseArgs = null; state.choice = null; state.optional = false; state.any = false; state.obj = false; state.use = null; state.useDecoder = null; state.key = null; state['default'] = null; state.explicit = null; state.implicit = null; state.contains = null; // Should create new instance on each method if (!state.parent) { state.children = []; this._wrap(); } } module.exports = Node; var stateProps = [ 'enc', 'parent', 'children', 'tag', 'args', 'reverseArgs', 'choice', 'optional', 'any', 'obj', 'use', 'alteredUse', 'key', 'default', 'explicit', 'implicit', 'contains' ]; Node.prototype.clone = function clone() { var state = this._baseState; var cstate = {}; stateProps.forEach(function(prop) { cstate[prop] = state[prop]; }); var res = new this.constructor(cstate.parent); res._baseState = cstate; return res; }; Node.prototype._wrap = function wrap() { var state = this._baseState; methods.forEach(function(method) { this[method] = function _wrappedMethod() { var clone = new this.constructor(this); state.children.push(clone); return clone[method].apply(clone, arguments); }; }, this); }; Node.prototype._init = function init(body) { var state = this._baseState; assert(state.parent === null); body.call(this); // Filter children state.children = state.children.filter(function(child) { return child._baseState.parent === this; }, this); assert.equal(state.children.length, 1, 'Root node can have only one child'); }; Node.prototype._useArgs = function useArgs(args) { var state = this._baseState; // Filter children and args var children = args.filter(function(arg) { return arg instanceof this.constructor; }, this); args = args.filter(function(arg) { return !(arg instanceof this.constructor); }, this); if (children.length !== 0) { assert(state.children === null); state.children = children; // Replace parent to maintain backward link children.forEach(function(child) { child._baseState.parent = this; }, this); } if (args.length !== 0) { assert(state.args === null); state.args = args; state.reverseArgs = args.map(function(arg) { if (typeof arg !== 'object' || arg.constructor !== Object) return arg; var res = {}; Object.keys(arg).forEach(function(key) { if (key == (key | 0)) key |= 0; var value = arg[key]; res[value] = key; }); return res; }); } }; // // Overrided methods // overrided.forEach(function(method) { Node.prototype[method] = function _overrided() { var state = this._baseState; throw new Error(method + ' not implemented for encoding: ' + state.enc); }; }); // // Public methods // tags.forEach(function(tag) { Node.prototype[tag] = function _tagMethod() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); assert(state.tag === null); state.tag = tag; this._useArgs(args); return this; }; }); Node.prototype.use = function use(item) { assert(item); var state = this._baseState; assert(state.use === null); state.use = item; return this; }; Node.prototype.optional = function optional() { var state = this._baseState; state.optional = true; return this; }; Node.prototype.def = function def(val) { var state = this._baseState; assert(state['default'] === null); state['default'] = val; state.optional = true; return this; }; Node.prototype.explicit = function explicit(num) { var state = this._baseState; assert(state.explicit === null && state.implicit === null); state.explicit = num; return this; }; Node.prototype.implicit = function implicit(num) { var state = this._baseState; assert(state.explicit === null && state.implicit === null); state.implicit = num; return this; }; Node.prototype.obj = function obj() { var state = this._baseState; var args = Array.prototype.slice.call(arguments); state.obj = true; if (args.length !== 0) this._useArgs(args); return this; }; Node.prototype.key = function key(newKey) { var state = this._baseState; assert(state.key === null); state.key = newKey; return this; }; Node.prototype.any = function any() { var state = this._baseState; state.any = true; return this; }; Node.prototype.choice = function choice(obj) { var state = this._baseState; assert(state.choice === null); state.choice = obj; this._useArgs(Object.keys(obj).map(function(key) { return obj[key]; })); return this; }; Node.prototype.contains = function contains(item) { var state = this._baseState; assert(state.use === null); state.contains = item; return this; }; // // Decoding // Node.prototype._decode = function decode(input, options) { var state = this._baseState; // Decode root node if (state.parent === null) return input.wrapResult(state.children[0]._decode(input, options)); var result = state['default']; var present = true; var prevKey = null; if (state.key !== null) prevKey = input.enterKey(state.key); // Check if tag is there if (state.optional) { var tag = null; if (state.explicit !== null) tag = state.explicit; else if (state.implicit !== null) tag = state.implicit; else if (state.tag !== null) tag = state.tag; if (tag === null && !state.any) { // Trial and Error var save = input.save(); try { if (state.choice === null) this._decodeGeneric(state.tag, input, options); else this._decodeChoice(input, options); present = true; } catch (e) { present = false; } input.restore(save); } else { present = this._peekTag(input, tag, state.any); if (input.isError(present)) return present; } } // Push object on stack var prevObj; if (state.obj && present) prevObj = input.enterObject(); if (present) { // Unwrap explicit values if (state.explicit !== null) { var explicit = this._decodeTag(input, state.explicit); if (input.isError(explicit)) return explicit; input = explicit; } var start = input.offset; // Unwrap implicit and normal values if (state.use === null && state.choice === null) { if (state.any) var save = input.save(); var body = this._decodeTag( input, state.implicit !== null ? state.implicit : state.tag, state.any ); if (input.isError(body)) return body; if (state.any) result = input.raw(save); else input = body; } if (options && options.track && state.tag !== null) options.track(input.path(), start, input.length, 'tagged'); if (options && options.track && state.tag !== null) options.track(input.path(), input.offset, input.length, 'content'); // Select proper method for tag if (state.any) result = result; else if (state.choice === null) result = this._decodeGeneric(state.tag, input, options); else result = this._decodeChoice(input, options); if (input.isError(result)) return result; // Decode children if (!state.any && state.choice === null && state.children !== null) { state.children.forEach(function decodeChildren(child) { // NOTE: We are ignoring errors here, to let parser continue with other // parts of encoded data child._decode(input, options); }); } // Decode contained/encoded by schema, only in bit or octet strings if (state.contains && (state.tag === 'octstr' || state.tag === 'bitstr')) { var data = new DecoderBuffer(result); result = this._getUse(state.contains, input._reporterState.obj) ._decode(data, options); } } // Pop object if (state.obj && present) result = input.leaveObject(prevObj); // Set key if (state.key !== null && (result !== null || present === true)) input.leaveKey(prevKey, state.key, result); else if (prevKey !== null) input.exitKey(prevKey); return result; }; Node.prototype._decodeGeneric = function decodeGeneric(tag, input, options) { var state = this._baseState; if (tag === 'seq' || tag === 'set') return null; if (tag === 'seqof' || tag === 'setof') return this._decodeList(input, tag, state.args[0], options); else if (/str$/.test(tag)) return this._decodeStr(input, tag, options); else if (tag === 'objid' && state.args) return this._decodeObjid(input, state.args[0], state.args[1], options); else if (tag === 'objid') return this._decodeObjid(input, null, null, options); else if (tag === 'gentime' || tag === 'utctime') return this._decodeTime(input, tag, options); else if (tag === 'null_') return this._decodeNull(input, options); else if (tag === 'bool') return this._decodeBool(input, options); else if (tag === 'objDesc') return this._decodeStr(input, tag, options); else if (tag === 'int' || tag === 'enum') return this._decodeInt(input, state.args && state.args[0], options); if (state.use !== null) { return this._getUse(state.use, input._reporterState.obj) ._decode(input, options); } else { return input.error('unknown tag: ' + tag); } }; Node.prototype._getUse = function _getUse(entity, obj) { var state = this._baseState; // Create altered use decoder if implicit is set state.useDecoder = this._use(entity, obj); assert(state.useDecoder._baseState.parent === null); state.useDecoder = state.useDecoder._baseState.children[0]; if (state.implicit !== state.useDecoder._baseState.implicit) { state.useDecoder = state.useDecoder.clone(); state.useDecoder._baseState.implicit = state.implicit; } return state.useDecoder; }; Node.prototype._decodeChoice = function decodeChoice(input, options) { var state = this._baseState; var result = null; var match = false; Object.keys(state.choice).some(function(key) { var save = input.save(); var node = state.choice[key]; try { var value = node._decode(input, options); if (input.isError(value)) return false; result = { type: key, value: value }; match = true; } catch (e) { input.restore(save); return false; } return true; }, this); if (!match) return input.error('Choice not matched'); return result; }; // // Encoding // Node.prototype._createEncoderBuffer = function createEncoderBuffer(data) { return new EncoderBuffer(data, this.reporter); }; Node.prototype._encode = function encode(data, reporter, parent) { var state = this._baseState; if (state['default'] !== null && state['default'] === data) return; var result = this._encodeValue(data, reporter, parent); if (result === undefined) return; if (this._skipDefault(result, reporter, parent)) return; return result; }; Node.prototype._encodeValue = function encode(data, reporter, parent) { var state = this._baseState; // Decode root node if (state.parent === null) return state.children[0]._encode(data, reporter || new Reporter()); var result = null; // Set reporter to share it with a child class this.reporter = reporter; // Check if data is there if (state.optional && data === undefined) { if (state['default'] !== null) data = state['default'] else return; } // Encode children first var content = null; var primitive = false; if (state.any) { // Anything that was given is translated to buffer result = this._createEncoderBuffer(data); } else if (state.choice) { result = this._encodeChoice(data, reporter); } else if (state.contains) { content = this._getUse(state.contains, parent)._encode(data, reporter); primitive = true; } else if (state.children) { content = state.children.map(function(child) { if (child._baseState.tag === 'null_') return child._encode(null, reporter, data); if (child._baseState.key === null) return reporter.error('Child should have a key'); var prevKey = reporter.enterKey(child._baseState.key); if (typeof data !== 'object') return reporter.error('Child expected, but input is not object'); var res = child._encode(data[child._baseState.key], reporter, data); reporter.leaveKey(prevKey); return res; }, this).filter(function(child) { return child; }); content = this._createEncoderBuffer(content); } else { if (state.tag === 'seqof' || state.tag === 'setof') { // TODO(indutny): this should be thrown on DSL level if (!(state.args && state.args.length === 1)) return reporter.error('Too many args for : ' + state.tag); if (!Array.isArray(data)) return reporter.error('seqof/setof, but data is not Array'); var child = this.clone(); child._baseState.implicit = null; content = this._createEncoderBuffer(data.map(function(item) { var state = this._baseState; return this._getUse(state.args[0], data)._encode(item, reporter); }, child)); } else if (state.use !== null) { result = this._getUse(state.use, parent)._encode(data, reporter); } else { content = this._encodePrimitive(state.tag, data); primitive = true; } } // Encode data itself var result; if (!state.any && state.choice === null) { var tag = state.implicit !== null ? state.implicit : state.tag; var cls = state.implicit === null ? 'universal' : 'context'; if (tag === null) { if (state.use === null) reporter.error('Tag could be ommited only for .use()'); } else { if (state.use === null) result = this._encodeComposite(tag, primitive, cls, content); } } // Wrap in explicit if (state.explicit !== null) result = this._encodeComposite(state.explicit, false, 'context', result); return result; }; Node.prototype._encodeChoice = function encodeChoice(data, reporter) { var state = this._baseState; var node = state.choice[data.type]; if (!node) { assert( false, data.type + ' not found in ' + JSON.stringify(Object.keys(state.choice))); } return node._encode(data.value, reporter); }; Node.prototype._encodePrimitive = function encodePrimitive(tag, data) { var state = this._baseState; if (/str$/.test(tag)) return this._encodeStr(data, tag); else if (tag === 'objid' && state.args) return this._encodeObjid(data, state.reverseArgs[0], state.args[1]); else if (tag === 'objid') return this._encodeObjid(data, null, null); else if (tag === 'gentime' || tag === 'utctime') return this._encodeTime(data, tag); else if (tag === 'null_') return this._encodeNull(); else if (tag === 'int' || tag === 'enum') return this._encodeInt(data, state.args && state.reverseArgs[0]); else if (tag === 'bool') return this._encodeBool(data); else if (tag === 'objDesc') return this._encodeStr(data, tag); else throw new Error('Unsupported tag: ' + tag); }; Node.prototype._isNumstr = function isNumstr(str) { return /^[0-9 ]*$/.test(str); }; Node.prototype._isPrintstr = function isPrintstr(str) { return /^[A-Za-z0-9 '\(\)\+,\-\.\/:=\?]*$/.test(str); }; },{"../base":136,"minimalistic-assert":207}],138:[function(require,module,exports){ arguments[4][53][0].apply(exports,arguments) },{"dup":53,"inherits":203}],139:[function(require,module,exports){ arguments[4][54][0].apply(exports,arguments) },{"../constants":140,"dup":54}],140:[function(require,module,exports){ arguments[4][55][0].apply(exports,arguments) },{"./der":139,"dup":55}],141:[function(require,module,exports){ arguments[4][56][0].apply(exports,arguments) },{"../../asn1":133,"dup":56,"inherits":203}],142:[function(require,module,exports){ arguments[4][57][0].apply(exports,arguments) },{"./der":141,"./pem":143,"dup":57}],143:[function(require,module,exports){ arguments[4][58][0].apply(exports,arguments) },{"./der":141,"buffer":179,"dup":58,"inherits":203}],144:[function(require,module,exports){ arguments[4][59][0].apply(exports,arguments) },{"../../asn1":133,"buffer":179,"dup":59,"inherits":203}],145:[function(require,module,exports){ arguments[4][60][0].apply(exports,arguments) },{"./der":144,"./pem":146,"dup":60}],146:[function(require,module,exports){ arguments[4][61][0].apply(exports,arguments) },{"./der":144,"dup":61,"inherits":203}],147:[function(require,module,exports){ (function (global){ 'use strict'; // compare and isBuffer taken from https://github.com/feross/buffer/blob/680e9e5e488f22aac27599a57dc844a6315928dd/index.js // original notice: /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ function compare(a, b) { if (a === b) { return 0; } var x = a.length; var y = b.length; for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i]; y = b[i]; break; } } if (x < y) { return -1; } if (y < x) { return 1; } return 0; } function isBuffer(b) { if (global.Buffer && typeof global.Buffer.isBuffer === 'function') { return global.Buffer.isBuffer(b); } return !!(b != null && b._isBuffer); } // based on node assert, original notice: // http://wiki.commonjs.org/wiki/Unit_Testing/1.0 // // THIS IS NOT TESTED NOR LIKELY TO WORK OUTSIDE V8! // // Originally from narwhal.js (http://narwhaljs.org) // Copyright (c) 2009 Thomas Robinson <280north.com> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the 'Software'), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN // ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. var util = require('util/'); var hasOwn = Object.prototype.hasOwnProperty; var pSlice = Array.prototype.slice; var functionsHaveNames = (function () { return function foo() {}.name === 'foo'; }()); function pToString (obj) { return Object.prototype.toString.call(obj); } function isView(arrbuf) { if (isBuffer(arrbuf)) { return false; } if (typeof global.ArrayBuffer !== 'function') { return false; } if (typeof ArrayBuffer.isView === 'function') { return ArrayBuffer.isView(arrbuf); } if (!arrbuf) { return false; } if (arrbuf instanceof DataView) { return true; } if (arrbuf.buffer && arrbuf.buffer instanceof ArrayBuffer) { return true; } return false; } // 1. The assert module provides functions that throw // AssertionError's when particular conditions are not met. The // assert module must conform to the following interface. var assert = module.exports = ok; // 2. The AssertionError is defined in assert. // new assert.AssertionError({ message: message, // actual: actual, // expected: expected }) var regex = /\s*function\s+([^\(\s]*)\s*/; // based on https://github.com/ljharb/function.prototype.name/blob/adeeeec8bfcc6068b187d7d9fb3d5bb1d3a30899/implementation.js function getName(func) { if (!util.isFunction(func)) { return; } if (functionsHaveNames) { return func.name; } var str = func.toString(); var match = str.match(regex); return match && match[1]; } assert.AssertionError = function AssertionError(options) { this.name = 'AssertionError'; this.actual = options.actual; this.expected = options.expected; this.operator = options.operator; if (options.message) { this.message = options.message; this.generatedMessage = false; } else { this.message = getMessage(this); this.generatedMessage = true; } var stackStartFunction = options.stackStartFunction || fail; if (Error.captureStackTrace) { Error.captureStackTrace(this, stackStartFunction); } else { // non v8 browsers so we can have a stacktrace var err = new Error(); if (err.stack) { var out = err.stack; // try to strip useless frames var fn_name = getName(stackStartFunction); var idx = out.indexOf('\n' + fn_name); if (idx >= 0) { // once we have located the function frame // we need to strip out everything before it (and its line) var next_line = out.indexOf('\n', idx + 1); out = out.substring(next_line + 1); } this.stack = out; } } }; // assert.AssertionError instanceof Error util.inherits(assert.AssertionError, Error); function truncate(s, n) { if (typeof s === 'string') { return s.length < n ? s : s.slice(0, n); } else { return s; } } function inspect(something) { if (functionsHaveNames || !util.isFunction(something)) { return util.inspect(something); } var rawname = getName(something); var name = rawname ? ': ' + rawname : ''; return '[Function' + name + ']'; } function getMessage(self) { return truncate(inspect(self.actual), 128) + ' ' + self.operator + ' ' + truncate(inspect(self.expected), 128); } // At present only the three keys mentioned above are used and // understood by the spec. Implementations or sub modules can pass // other keys to the AssertionError's constructor - they will be // ignored. // 3. All of the following functions must throw an AssertionError // when a corresponding condition is not met, with a message that // may be undefined if not provided. All assertion methods provide // both the actual and expected values to the assertion error for // display purposes. function fail(actual, expected, message, operator, stackStartFunction) { throw new assert.AssertionError({ message: message, actual: actual, expected: expected, operator: operator, stackStartFunction: stackStartFunction }); } // EXTENSION! allows for well behaved errors defined elsewhere. assert.fail = fail; // 4. Pure assertion tests whether a value is truthy, as determined // by !!guard. // assert.ok(guard, message_opt); // This statement is equivalent to assert.equal(true, !!guard, // message_opt);. To test strictly for the value true, use // assert.strictEqual(true, guard, message_opt);. function ok(value, message) { if (!value) fail(value, true, message, '==', assert.ok); } assert.ok = ok; // 5. The equality assertion tests shallow, coercive equality with // ==. // assert.equal(actual, expected, message_opt); assert.equal = function equal(actual, expected, message) { if (actual != expected) fail(actual, expected, message, '==', assert.equal); }; // 6. The non-equality assertion tests for whether two objects are not equal // with != assert.notEqual(actual, expected, message_opt); assert.notEqual = function notEqual(actual, expected, message) { if (actual == expected) { fail(actual, expected, message, '!=', assert.notEqual); } }; // 7. The equivalence assertion tests a deep equality relation. // assert.deepEqual(actual, expected, message_opt); assert.deepEqual = function deepEqual(actual, expected, message) { if (!_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'deepEqual', assert.deepEqual); } }; assert.deepStrictEqual = function deepStrictEqual(actual, expected, message) { if (!_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'deepStrictEqual', assert.deepStrictEqual); } }; function _deepEqual(actual, expected, strict, memos) { // 7.1. All identical values are equivalent, as determined by ===. if (actual === expected) { return true; } else if (isBuffer(actual) && isBuffer(expected)) { return compare(actual, expected) === 0; // 7.2. If the expected value is a Date object, the actual value is // equivalent if it is also a Date object that refers to the same time. } else if (util.isDate(actual) && util.isDate(expected)) { return actual.getTime() === expected.getTime(); // 7.3 If the expected value is a RegExp object, the actual value is // equivalent if it is also a RegExp object with the same source and // properties (`global`, `multiline`, `lastIndex`, `ignoreCase`). } else if (util.isRegExp(actual) && util.isRegExp(expected)) { return actual.source === expected.source && actual.global === expected.global && actual.multiline === expected.multiline && actual.lastIndex === expected.lastIndex && actual.ignoreCase === expected.ignoreCase; // 7.4. Other pairs that do not both pass typeof value == 'object', // equivalence is determined by ==. } else if ((actual === null || typeof actual !== 'object') && (expected === null || typeof expected !== 'object')) { return strict ? actual === expected : actual == expected; // If both values are instances of typed arrays, wrap their underlying // ArrayBuffers in a Buffer each to increase performance // This optimization requires the arrays to have the same type as checked by // Object.prototype.toString (aka pToString). Never perform binary // comparisons for Float*Arrays, though, since e.g. +0 === -0 but their // bit patterns are not identical. } else if (isView(actual) && isView(expected) && pToString(actual) === pToString(expected) && !(actual instanceof Float32Array || actual instanceof Float64Array)) { return compare(new Uint8Array(actual.buffer), new Uint8Array(expected.buffer)) === 0; // 7.5 For all other Object pairs, including Array objects, equivalence is // determined by having the same number of owned properties (as verified // with Object.prototype.hasOwnProperty.call), the same set of keys // (although not necessarily the same order), equivalent values for every // corresponding key, and an identical 'prototype' property. Note: this // accounts for both named and indexed properties on Arrays. } else if (isBuffer(actual) !== isBuffer(expected)) { return false; } else { memos = memos || {actual: [], expected: []}; var actualIndex = memos.actual.indexOf(actual); if (actualIndex !== -1) { if (actualIndex === memos.expected.indexOf(expected)) { return true; } } memos.actual.push(actual); memos.expected.push(expected); return objEquiv(actual, expected, strict, memos); } } function isArguments(object) { return Object.prototype.toString.call(object) == '[object Arguments]'; } function objEquiv(a, b, strict, actualVisitedObjects) { if (a === null || a === undefined || b === null || b === undefined) return false; // if one is a primitive, the other must be same if (util.isPrimitive(a) || util.isPrimitive(b)) return a === b; if (strict && Object.getPrototypeOf(a) !== Object.getPrototypeOf(b)) return false; var aIsArgs = isArguments(a); var bIsArgs = isArguments(b); if ((aIsArgs && !bIsArgs) || (!aIsArgs && bIsArgs)) return false; if (aIsArgs) { a = pSlice.call(a); b = pSlice.call(b); return _deepEqual(a, b, strict); } var ka = objectKeys(a); var kb = objectKeys(b); var key, i; // having the same number of owned properties (keys incorporates // hasOwnProperty) if (ka.length !== kb.length) return false; //the same set of keys (although not necessarily the same order), ka.sort(); kb.sort(); //~~~cheap key test for (i = ka.length - 1; i >= 0; i--) { if (ka[i] !== kb[i]) return false; } //equivalent values for every corresponding key, and //~~~possibly expensive deep test for (i = ka.length - 1; i >= 0; i--) { key = ka[i]; if (!_deepEqual(a[key], b[key], strict, actualVisitedObjects)) return false; } return true; } // 8. The non-equivalence assertion tests for any deep inequality. // assert.notDeepEqual(actual, expected, message_opt); assert.notDeepEqual = function notDeepEqual(actual, expected, message) { if (_deepEqual(actual, expected, false)) { fail(actual, expected, message, 'notDeepEqual', assert.notDeepEqual); } }; assert.notDeepStrictEqual = notDeepStrictEqual; function notDeepStrictEqual(actual, expected, message) { if (_deepEqual(actual, expected, true)) { fail(actual, expected, message, 'notDeepStrictEqual', notDeepStrictEqual); } } // 9. The strict equality assertion tests strict equality, as determined by ===. // assert.strictEqual(actual, expected, message_opt); assert.strictEqual = function strictEqual(actual, expected, message) { if (actual !== expected) { fail(actual, expected, message, '===', assert.strictEqual); } }; // 10. The strict non-equality assertion tests for strict inequality, as // determined by !==. assert.notStrictEqual(actual, expected, message_opt); assert.notStrictEqual = function notStrictEqual(actual, expected, message) { if (actual === expected) { fail(actual, expected, message, '!==', assert.notStrictEqual); } }; function expectedException(actual, expected) { if (!actual || !expected) { return false; } if (Object.prototype.toString.call(expected) == '[object RegExp]') { return expected.test(actual); } try { if (actual instanceof expected) { return true; } } catch (e) { // Ignore. The instanceof check doesn't work for arrow functions. } if (Error.isPrototypeOf(expected)) { return false; } return expected.call({}, actual) === true; } function _tryBlock(block) { var error; try { block(); } catch (e) { error = e; } return error; } function _throws(shouldThrow, block, expected, message) { var actual; if (typeof block !== 'function') { throw new TypeError('"block" argument must be a function'); } if (typeof expected === 'string') { message = expected; expected = null; } actual = _tryBlock(block); message = (expected && expected.name ? ' (' + expected.name + ').' : '.') + (message ? ' ' + message : '.'); if (shouldThrow && !actual) { fail(actual, expected, 'Missing expected exception' + message); } var userProvidedMessage = typeof message === 'string'; var isUnwantedException = !shouldThrow && util.isError(actual); var isUnexpectedException = !shouldThrow && actual && !expected; if ((isUnwantedException && userProvidedMessage && expectedException(actual, expected)) || isUnexpectedException) { fail(actual, expected, 'Got unwanted exception' + message); } if ((shouldThrow && actual && expected && !expectedException(actual, expected)) || (!shouldThrow && actual)) { throw actual; } } // 11. Expected to throw an error: // assert.throws(block, Error_opt, message_opt); assert.throws = function(block, /*optional*/error, /*optional*/message) { _throws(true, block, error, message); }; // EXTENSION! This is annoying to write outside this module. assert.doesNotThrow = function(block, /*optional*/error, /*optional*/message) { _throws(false, block, error, message); }; assert.ifError = function(err) { if (err) throw err; }; var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { if (hasOwn.call(obj, key)) keys.push(key); } return keys; }; }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"util/":261}],148:[function(require,module,exports){ 'use strict' exports.byteLength = byteLength exports.toByteArray = toByteArray exports.fromByteArray = fromByteArray var lookup = [] var revLookup = [] var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/' for (var i = 0, len = code.length; i < len; ++i) { lookup[i] = code[i] revLookup[code.charCodeAt(i)] = i } revLookup['-'.charCodeAt(0)] = 62 revLookup['_'.charCodeAt(0)] = 63 function placeHoldersCount (b64) { var len = b64.length if (len % 4 > 0) { throw new Error('Invalid string. Length must be a multiple of 4') } // the number of equal signs (place holders) // if there are two placeholders, than the two characters before it // represent one byte // if there is only one, then the three characters before it represent 2 bytes // this is just a cheap hack to not do indexOf twice return b64[len - 2] === '=' ? 2 : b64[len - 1] === '=' ? 1 : 0 } function byteLength (b64) { // base64 is 4/3 + up to two characters of the original data return (b64.length * 3 / 4) - placeHoldersCount(b64) } function toByteArray (b64) { var i, l, tmp, placeHolders, arr var len = b64.length placeHolders = placeHoldersCount(b64) arr = new Arr((len * 3 / 4) - placeHolders) // if there are placeholders, only get up to the last complete 4 chars l = placeHolders > 0 ? len - 4 : len var L = 0 for (i = 0; i < l; i += 4) { tmp = (revLookup[b64.charCodeAt(i)] << 18) | (revLookup[b64.charCodeAt(i + 1)] << 12) | (revLookup[b64.charCodeAt(i + 2)] << 6) | revLookup[b64.charCodeAt(i + 3)] arr[L++] = (tmp >> 16) & 0xFF arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } if (placeHolders === 2) { tmp = (revLookup[b64.charCodeAt(i)] << 2) | (revLookup[b64.charCodeAt(i + 1)] >> 4) arr[L++] = tmp & 0xFF } else if (placeHolders === 1) { tmp = (revLookup[b64.charCodeAt(i)] << 10) | (revLookup[b64.charCodeAt(i + 1)] << 4) | (revLookup[b64.charCodeAt(i + 2)] >> 2) arr[L++] = (tmp >> 8) & 0xFF arr[L++] = tmp & 0xFF } return arr } function tripletToBase64 (num) { return lookup[num >> 18 & 0x3F] + lookup[num >> 12 & 0x3F] + lookup[num >> 6 & 0x3F] + lookup[num & 0x3F] } function encodeChunk (uint8, start, end) { var tmp var output = [] for (var i = start; i < end; i += 3) { tmp = (uint8[i] << 16) + (uint8[i + 1] << 8) + (uint8[i + 2]) output.push(tripletToBase64(tmp)) } return output.join('') } function fromByteArray (uint8) { var tmp var len = uint8.length var extraBytes = len % 3 // if we have 1 byte left, pad 2 bytes var output = '' var parts = [] var maxChunkLength = 16383 // must be multiple of 3 // go through the array every three bytes, we'll deal with trailing stuff later for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))) } // pad the end with zeros, but make sure to not forget the extra bytes if (extraBytes === 1) { tmp = uint8[len - 1] output += lookup[tmp >> 2] output += lookup[(tmp << 4) & 0x3F] output += '==' } else if (extraBytes === 2) { tmp = (uint8[len - 2] << 8) + (uint8[len - 1]) output += lookup[tmp >> 10] output += lookup[(tmp >> 4) & 0x3F] output += lookup[(tmp << 2) & 0x3F] output += '=' } parts.push(output) return parts.join('') } },{}],149:[function(require,module,exports){ arguments[4][130][0].apply(exports,arguments) },{"buffer":151,"dup":130}],150:[function(require,module,exports){ arguments[4][132][0].apply(exports,arguments) },{"crypto":151,"dup":132}],151:[function(require,module,exports){ },{}],152:[function(require,module,exports){ // based on the aes implimentation in triple sec // https://github.com/keybase/triplesec // which is in turn based on the one from crypto-js // https://code.google.com/p/crypto-js/ var Buffer = require('safe-buffer').Buffer function asUInt32Array (buf) { if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf) var len = (buf.length / 4) | 0 var out = new Array(len) for (var i = 0; i < len; i++) { out[i] = buf.readUInt32BE(i * 4) } return out } function scrubVec (v) { for (var i = 0; i < v.length; v++) { v[i] = 0 } } function cryptBlock (M, keySchedule, SUB_MIX, SBOX, nRounds) { var SUB_MIX0 = SUB_MIX[0] var SUB_MIX1 = SUB_MIX[1] var SUB_MIX2 = SUB_MIX[2] var SUB_MIX3 = SUB_MIX[3] var s0 = M[0] ^ keySchedule[0] var s1 = M[1] ^ keySchedule[1] var s2 = M[2] ^ keySchedule[2] var s3 = M[3] ^ keySchedule[3] var t0, t1, t2, t3 var ksRow = 4 for (var round = 1; round < nRounds; round++) { t0 = SUB_MIX0[s0 >>> 24] ^ SUB_MIX1[(s1 >>> 16) & 0xff] ^ SUB_MIX2[(s2 >>> 8) & 0xff] ^ SUB_MIX3[s3 & 0xff] ^ keySchedule[ksRow++] t1 = SUB_MIX0[s1 >>> 24] ^ SUB_MIX1[(s2 >>> 16) & 0xff] ^ SUB_MIX2[(s3 >>> 8) & 0xff] ^ SUB_MIX3[s0 & 0xff] ^ keySchedule[ksRow++] t2 = SUB_MIX0[s2 >>> 24] ^ SUB_MIX1[(s3 >>> 16) & 0xff] ^ SUB_MIX2[(s0 >>> 8) & 0xff] ^ SUB_MIX3[s1 & 0xff] ^ keySchedule[ksRow++] t3 = SUB_MIX0[s3 >>> 24] ^ SUB_MIX1[(s0 >>> 16) & 0xff] ^ SUB_MIX2[(s1 >>> 8) & 0xff] ^ SUB_MIX3[s2 & 0xff] ^ keySchedule[ksRow++] s0 = t0 s1 = t1 s2 = t2 s3 = t3 } t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++] t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++] t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++] t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++] t0 = t0 >>> 0 t1 = t1 >>> 0 t2 = t2 >>> 0 t3 = t3 >>> 0 return [t0, t1, t2, t3] } // AES constants var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36] var G = (function () { // Compute double table var d = new Array(256) for (var j = 0; j < 256; j++) { if (j < 128) { d[j] = j << 1 } else { d[j] = (j << 1) ^ 0x11b } } var SBOX = [] var INV_SBOX = [] var SUB_MIX = [[], [], [], []] var INV_SUB_MIX = [[], [], [], []] // Walk GF(2^8) var x = 0 var xi = 0 for (var i = 0; i < 256; ++i) { // Compute sbox var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4) sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63 SBOX[x] = sx INV_SBOX[sx] = x // Compute multiplication var x2 = d[x] var x4 = d[x2] var x8 = d[x4] // Compute sub bytes, mix columns tables var t = (d[sx] * 0x101) ^ (sx * 0x1010100) SUB_MIX[0][x] = (t << 24) | (t >>> 8) SUB_MIX[1][x] = (t << 16) | (t >>> 16) SUB_MIX[2][x] = (t << 8) | (t >>> 24) SUB_MIX[3][x] = t // Compute inv sub bytes, inv mix columns tables t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100) INV_SUB_MIX[0][sx] = (t << 24) | (t >>> 8) INV_SUB_MIX[1][sx] = (t << 16) | (t >>> 16) INV_SUB_MIX[2][sx] = (t << 8) | (t >>> 24) INV_SUB_MIX[3][sx] = t if (x === 0) { x = xi = 1 } else { x = x2 ^ d[d[d[x8 ^ x2]]] xi ^= d[d[xi]] } } return { SBOX: SBOX, INV_SBOX: INV_SBOX, SUB_MIX: SUB_MIX, INV_SUB_MIX: INV_SUB_MIX } })() function AES (key) { this._key = asUInt32Array(key) this._reset() } AES.blockSize = 4 * 4 AES.keySize = 256 / 8 AES.prototype.blockSize = AES.blockSize AES.prototype.keySize = AES.keySize AES.prototype._reset = function () { var keyWords = this._key var keySize = keyWords.length var nRounds = keySize + 6 var ksRows = (nRounds + 1) * 4 var keySchedule = [] for (var k = 0; k < keySize; k++) { keySchedule[k] = keyWords[k] } for (k = keySize; k < ksRows; k++) { var t = keySchedule[k - 1] if (k % keySize === 0) { t = (t << 8) | (t >>> 24) t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | (G.SBOX[t & 0xff]) t ^= RCON[(k / keySize) | 0] << 24 } else if (keySize > 6 && k % keySize === 4) { t = (G.SBOX[t >>> 24] << 24) | (G.SBOX[(t >>> 16) & 0xff] << 16) | (G.SBOX[(t >>> 8) & 0xff] << 8) | (G.SBOX[t & 0xff]) } keySchedule[k] = keySchedule[k - keySize] ^ t } var invKeySchedule = [] for (var ik = 0; ik < ksRows; ik++) { var ksR = ksRows - ik var tt = keySchedule[ksR - (ik % 4 ? 0 : 4)] if (ik < 4 || ksR <= 4) { invKeySchedule[ik] = tt } else { invKeySchedule[ik] = G.INV_SUB_MIX[0][G.SBOX[tt >>> 24]] ^ G.INV_SUB_MIX[1][G.SBOX[(tt >>> 16) & 0xff]] ^ G.INV_SUB_MIX[2][G.SBOX[(tt >>> 8) & 0xff]] ^ G.INV_SUB_MIX[3][G.SBOX[tt & 0xff]] } } this._nRounds = nRounds this._keySchedule = keySchedule this._invKeySchedule = invKeySchedule } AES.prototype.encryptBlockRaw = function (M) { M = asUInt32Array(M) return cryptBlock(M, this._keySchedule, G.SUB_MIX, G.SBOX, this._nRounds) } AES.prototype.encryptBlock = function (M) { var out = this.encryptBlockRaw(M) var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0], 0) buf.writeUInt32BE(out[1], 4) buf.writeUInt32BE(out[2], 8) buf.writeUInt32BE(out[3], 12) return buf } AES.prototype.decryptBlock = function (M) { M = asUInt32Array(M) // swap var m1 = M[1] M[1] = M[3] M[3] = m1 var out = cryptBlock(M, this._invKeySchedule, G.INV_SUB_MIX, G.INV_SBOX, this._nRounds) var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0], 0) buf.writeUInt32BE(out[3], 4) buf.writeUInt32BE(out[2], 8) buf.writeUInt32BE(out[1], 12) return buf } AES.prototype.scrub = function () { scrubVec(this._keySchedule) scrubVec(this._invKeySchedule) scrubVec(this._key) } module.exports.AES = AES },{"safe-buffer":457}],153:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer var Transform = require('cipher-base') var inherits = require('inherits') var GHASH = require('./ghash') var xor = require('buffer-xor') function xorTest (a, b) { var out = 0 if (a.length !== b.length) out++ var len = Math.min(a.length, b.length) for (var i = 0; i < len; ++i) { out += (a[i] ^ b[i]) } return out } function StreamCipher (mode, key, iv, decrypt) { Transform.call(this) this._finID = Buffer.concat([iv, Buffer.from([0, 0, 0, 1])]) iv = Buffer.concat([iv, Buffer.from([0, 0, 0, 2])]) this._cipher = new aes.AES(key) this._prev = Buffer.from(iv) this._cache = Buffer.allocUnsafe(0) this._secCache = Buffer.allocUnsafe(0) this._decrypt = decrypt this._alen = 0 this._len = 0 this._mode = mode var h = Buffer.alloc(4, 0) this._ghash = new GHASH(this._cipher.encryptBlock(h)) this._authTag = null this._called = false } inherits(StreamCipher, Transform) StreamCipher.prototype._update = function (chunk) { if (!this._called && this._alen) { var rump = 16 - (this._alen % 16) if (rump < 16) { rump = Buffer.alloc(rump, 0) this._ghash.update(rump) } } this._called = true var out = this._mode.encrypt(this, chunk) if (this._decrypt) { this._ghash.update(chunk) } else { this._ghash.update(out) } this._len += chunk.length return out } StreamCipher.prototype._final = function () { if (this._decrypt && !this._authTag) throw new Error('Unsupported state or unable to authenticate data') var tag = xor(this._ghash.final(this._alen * 8, this._len * 8), this._cipher.encryptBlock(this._finID)) if (this._decrypt && xorTest(tag, this._authTag)) throw new Error('Unsupported state or unable to authenticate data') this._authTag = tag this._cipher.scrub() } StreamCipher.prototype.getAuthTag = function getAuthTag () { if (this._decrypt || !Buffer.isBuffer(this._authTag)) throw new Error('Attempting to get auth tag in unsupported state') return this._authTag } StreamCipher.prototype.setAuthTag = function setAuthTag (tag) { if (!this._decrypt) throw new Error('Attempting to set auth tag in unsupported state') this._authTag = tag } StreamCipher.prototype.setAAD = function setAAD (buf) { if (this._called) throw new Error('Attempting to set AAD in unsupported state') this._ghash.update(buf) this._alen += buf.length } module.exports = StreamCipher },{"./aes":152,"./ghash":157,"buffer-xor":178,"cipher-base":180,"inherits":203,"safe-buffer":457}],154:[function(require,module,exports){ var ciphers = require('./encrypter') var deciphers = require('./decrypter') var modes = require('./modes/list.json') function getCiphers () { return Object.keys(modes) } exports.createCipher = exports.Cipher = ciphers.createCipher exports.createCipheriv = exports.Cipheriv = ciphers.createCipheriv exports.createDecipher = exports.Decipher = deciphers.createDecipher exports.createDecipheriv = exports.Decipheriv = deciphers.createDecipheriv exports.listCiphers = exports.getCiphers = getCiphers },{"./decrypter":155,"./encrypter":156,"./modes/list.json":165}],155:[function(require,module,exports){ var AuthCipher = require('./authCipher') var Buffer = require('safe-buffer').Buffer var MODES = require('./modes') var StreamCipher = require('./streamCipher') var Transform = require('cipher-base') var aes = require('./aes') var ebtk = require('evp_bytestokey') var inherits = require('inherits') function Decipher (mode, key, iv) { Transform.call(this) this._cache = new Splitter() this._last = void 0 this._cipher = new aes.AES(key) this._prev = Buffer.from(iv) this._mode = mode this._autopadding = true } inherits(Decipher, Transform) Decipher.prototype._update = function (data) { this._cache.add(data) var chunk var thing var out = [] while ((chunk = this._cache.get(this._autopadding))) { thing = this._mode.decrypt(this, chunk) out.push(thing) } return Buffer.concat(out) } Decipher.prototype._final = function () { var chunk = this._cache.flush() if (this._autopadding) { return unpad(this._mode.decrypt(this, chunk)) } else if (chunk) { throw new Error('data not multiple of block length') } } Decipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo return this } function Splitter () { this.cache = Buffer.allocUnsafe(0) } Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]) } Splitter.prototype.get = function (autoPadding) { var out if (autoPadding) { if (this.cache.length > 16) { out = this.cache.slice(0, 16) this.cache = this.cache.slice(16) return out } } else { if (this.cache.length >= 16) { out = this.cache.slice(0, 16) this.cache = this.cache.slice(16) return out } } return null } Splitter.prototype.flush = function () { if (this.cache.length) return this.cache } function unpad (last) { var padded = last[15] var i = -1 while (++i < padded) { if (last[(i + (16 - padded))] !== padded) { throw new Error('unable to decrypt data') } } if (padded === 16) return return last.slice(0, 16 - padded) } function createDecipheriv (suite, password, iv) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') if (typeof iv === 'string') iv = Buffer.from(iv) if (iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) if (typeof password === 'string') password = Buffer.from(password) if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) if (config.type === 'stream') { return new StreamCipher(config.module, password, iv, true) } else if (config.type === 'auth') { return new AuthCipher(config.module, password, iv, true) } return new Decipher(config.module, password, iv) } function createDecipher (suite, password) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') var keys = ebtk(password, false, config.key, config.iv) return createDecipheriv(suite, keys.key, keys.iv) } exports.createDecipher = createDecipher exports.createDecipheriv = createDecipheriv },{"./aes":152,"./authCipher":153,"./modes":164,"./streamCipher":167,"cipher-base":180,"evp_bytestokey":200,"inherits":203,"safe-buffer":457}],156:[function(require,module,exports){ var MODES = require('./modes') var AuthCipher = require('./authCipher') var Buffer = require('safe-buffer').Buffer var StreamCipher = require('./streamCipher') var Transform = require('cipher-base') var aes = require('./aes') var ebtk = require('evp_bytestokey') var inherits = require('inherits') function Cipher (mode, key, iv) { Transform.call(this) this._cache = new Splitter() this._cipher = new aes.AES(key) this._prev = Buffer.from(iv) this._mode = mode this._autopadding = true } inherits(Cipher, Transform) Cipher.prototype._update = function (data) { this._cache.add(data) var chunk var thing var out = [] while ((chunk = this._cache.get())) { thing = this._mode.encrypt(this, chunk) out.push(thing) } return Buffer.concat(out) } var PADDING = Buffer.alloc(16, 0x10) Cipher.prototype._final = function () { var chunk = this._cache.flush() if (this._autopadding) { chunk = this._mode.encrypt(this, chunk) this._cipher.scrub() return chunk } if (!chunk.equals(PADDING)) { this._cipher.scrub() throw new Error('data not multiple of block length') } } Cipher.prototype.setAutoPadding = function (setTo) { this._autopadding = !!setTo return this } function Splitter () { this.cache = Buffer.allocUnsafe(0) } Splitter.prototype.add = function (data) { this.cache = Buffer.concat([this.cache, data]) } Splitter.prototype.get = function () { if (this.cache.length > 15) { var out = this.cache.slice(0, 16) this.cache = this.cache.slice(16) return out } return null } Splitter.prototype.flush = function () { var len = 16 - this.cache.length var padBuff = Buffer.allocUnsafe(len) var i = -1 while (++i < len) { padBuff.writeUInt8(len, i) } return Buffer.concat([this.cache, padBuff]) } function createCipheriv (suite, password, iv) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') if (typeof password === 'string') password = Buffer.from(password) if (password.length !== config.key / 8) throw new TypeError('invalid key length ' + password.length) if (typeof iv === 'string') iv = Buffer.from(iv) if (iv.length !== config.iv) throw new TypeError('invalid iv length ' + iv.length) if (config.type === 'stream') { return new StreamCipher(config.module, password, iv) } else if (config.type === 'auth') { return new AuthCipher(config.module, password, iv) } return new Cipher(config.module, password, iv) } function createCipher (suite, password) { var config = MODES[suite.toLowerCase()] if (!config) throw new TypeError('invalid suite type') var keys = ebtk(password, false, config.key, config.iv) return createCipheriv(suite, keys.key, keys.iv) } exports.createCipheriv = createCipheriv exports.createCipher = createCipher },{"./aes":152,"./authCipher":153,"./modes":164,"./streamCipher":167,"cipher-base":180,"evp_bytestokey":200,"inherits":203,"safe-buffer":457}],157:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var ZEROES = Buffer.alloc(16, 0) function toArray (buf) { return [ buf.readUInt32BE(0), buf.readUInt32BE(4), buf.readUInt32BE(8), buf.readUInt32BE(12) ] } function fromArray (out) { var buf = Buffer.allocUnsafe(16) buf.writeUInt32BE(out[0] >>> 0, 0) buf.writeUInt32BE(out[1] >>> 0, 4) buf.writeUInt32BE(out[2] >>> 0, 8) buf.writeUInt32BE(out[3] >>> 0, 12) return buf } function GHASH (key) { this.h = key this.state = Buffer.alloc(16, 0) this.cache = Buffer.allocUnsafe(0) } // from http://bitwiseshiftleft.github.io/sjcl/doc/symbols/src/core_gcm.js.html // by Juho Vähä-Herttua GHASH.prototype.ghash = function (block) { var i = -1 while (++i < block.length) { this.state[i] ^= block[i] } this._multiply() } GHASH.prototype._multiply = function () { var Vi = toArray(this.h) var Zi = [0, 0, 0, 0] var j, xi, lsbVi var i = -1 while (++i < 128) { xi = (this.state[~~(i / 8)] & (1 << (7 - (i % 8)))) !== 0 if (xi) { // Z_i+1 = Z_i ^ V_i Zi[0] ^= Vi[0] Zi[1] ^= Vi[1] Zi[2] ^= Vi[2] Zi[3] ^= Vi[3] } // Store the value of LSB(V_i) lsbVi = (Vi[3] & 1) !== 0 // V_i+1 = V_i >> 1 for (j = 3; j > 0; j--) { Vi[j] = (Vi[j] >>> 1) | ((Vi[j - 1] & 1) << 31) } Vi[0] = Vi[0] >>> 1 // If LSB(V_i) is 1, V_i+1 = (V_i >> 1) ^ R if (lsbVi) { Vi[0] = Vi[0] ^ (0xe1 << 24) } } this.state = fromArray(Zi) } GHASH.prototype.update = function (buf) { this.cache = Buffer.concat([this.cache, buf]) var chunk while (this.cache.length >= 16) { chunk = this.cache.slice(0, 16) this.cache = this.cache.slice(16) this.ghash(chunk) } } GHASH.prototype.final = function (abl, bl) { if (this.cache.length) { this.ghash(Buffer.concat([this.cache, ZEROES], 16)) } this.ghash(fromArray([0, abl, 0, bl])) return this.state } module.exports = GHASH },{"safe-buffer":457}],158:[function(require,module,exports){ var xor = require('buffer-xor') exports.encrypt = function (self, block) { var data = xor(block, self._prev) self._prev = self._cipher.encryptBlock(data) return self._prev } exports.decrypt = function (self, block) { var pad = self._prev self._prev = block var out = self._cipher.decryptBlock(block) return xor(out, pad) } },{"buffer-xor":178}],159:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var xor = require('buffer-xor') function encryptStart (self, data, decrypt) { var len = data.length var out = xor(data, self._cache) self._cache = self._cache.slice(len) self._prev = Buffer.concat([self._prev, decrypt ? data : out]) return out } exports.encrypt = function (self, data, decrypt) { var out = Buffer.allocUnsafe(0) var len while (data.length) { if (self._cache.length === 0) { self._cache = self._cipher.encryptBlock(self._prev) self._prev = Buffer.allocUnsafe(0) } if (self._cache.length <= data.length) { len = self._cache.length out = Buffer.concat([out, encryptStart(self, data.slice(0, len), decrypt)]) data = data.slice(len) } else { out = Buffer.concat([out, encryptStart(self, data, decrypt)]) break } } return out } },{"buffer-xor":178,"safe-buffer":457}],160:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer function encryptByte (self, byteParam, decrypt) { var pad var i = -1 var len = 8 var out = 0 var bit, value while (++i < len) { pad = self._cipher.encryptBlock(self._prev) bit = (byteParam & (1 << (7 - i))) ? 0x80 : 0 value = pad[0] ^ bit out += ((value & 0x80) >> (i % 8)) self._prev = shiftIn(self._prev, decrypt ? bit : value) } return out } function shiftIn (buffer, value) { var len = buffer.length var i = -1 var out = Buffer.allocUnsafe(buffer.length) buffer = Buffer.concat([buffer, Buffer.from([value])]) while (++i < len) { out[i] = buffer[i] << 1 | buffer[i + 1] >> (7) } return out } exports.encrypt = function (self, chunk, decrypt) { var len = chunk.length var out = Buffer.allocUnsafe(len) var i = -1 while (++i < len) { out[i] = encryptByte(self, chunk[i], decrypt) } return out } },{"safe-buffer":457}],161:[function(require,module,exports){ (function (Buffer){ function encryptByte (self, byteParam, decrypt) { var pad = self._cipher.encryptBlock(self._prev) var out = pad[0] ^ byteParam self._prev = Buffer.concat([ self._prev.slice(1), Buffer.from([decrypt ? byteParam : out]) ]) return out } exports.encrypt = function (self, chunk, decrypt) { var len = chunk.length var out = Buffer.allocUnsafe(len) var i = -1 while (++i < len) { out[i] = encryptByte(self, chunk[i], decrypt) } return out } }).call(this,require("buffer").Buffer) },{"buffer":179}],162:[function(require,module,exports){ (function (Buffer){ var xor = require('buffer-xor') function incr32 (iv) { var len = iv.length var item while (len--) { item = iv.readUInt8(len) if (item === 255) { iv.writeUInt8(0, len) } else { item++ iv.writeUInt8(item, len) break } } } function getBlock (self) { var out = self._cipher.encryptBlockRaw(self._prev) incr32(self._prev) return out } var blockSize = 16 exports.encrypt = function (self, chunk) { var chunkNum = Math.ceil(chunk.length / blockSize) var start = self._cache.length self._cache = Buffer.concat([ self._cache, Buffer.allocUnsafe(chunkNum * blockSize) ]) for (var i = 0; i < chunkNum; i++) { var out = getBlock(self) var offset = start + i * blockSize self._cache.writeUInt32BE(out[0], offset + 0) self._cache.writeUInt32BE(out[1], offset + 4) self._cache.writeUInt32BE(out[2], offset + 8) self._cache.writeUInt32BE(out[3], offset + 12) } var pad = self._cache.slice(0, chunk.length) self._cache = self._cache.slice(chunk.length) return xor(chunk, pad) } }).call(this,require("buffer").Buffer) },{"buffer":179,"buffer-xor":178}],163:[function(require,module,exports){ exports.encrypt = function (self, block) { return self._cipher.encryptBlock(block) } exports.decrypt = function (self, block) { return self._cipher.decryptBlock(block) } },{}],164:[function(require,module,exports){ var modeModules = { ECB: require('./ecb'), CBC: require('./cbc'), CFB: require('./cfb'), CFB8: require('./cfb8'), CFB1: require('./cfb1'), OFB: require('./ofb'), CTR: require('./ctr'), GCM: require('./ctr') } var modes = require('./list.json') for (var key in modes) { modes[key].module = modeModules[modes[key].mode] } module.exports = modes },{"./cbc":158,"./cfb":159,"./cfb1":160,"./cfb8":161,"./ctr":162,"./ecb":163,"./list.json":165,"./ofb":166}],165:[function(require,module,exports){ module.exports={ "aes-128-ecb": { "cipher": "AES", "key": 128, "iv": 0, "mode": "ECB", "type": "block" }, "aes-192-ecb": { "cipher": "AES", "key": 192, "iv": 0, "mode": "ECB", "type": "block" }, "aes-256-ecb": { "cipher": "AES", "key": 256, "iv": 0, "mode": "ECB", "type": "block" }, "aes-128-cbc": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CBC", "type": "block" }, "aes-192-cbc": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CBC", "type": "block" }, "aes-256-cbc": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CBC", "type": "block" }, "aes128": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CBC", "type": "block" }, "aes192": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CBC", "type": "block" }, "aes256": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CBC", "type": "block" }, "aes-128-cfb": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB", "type": "stream" }, "aes-192-cfb": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB", "type": "stream" }, "aes-256-cfb": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB", "type": "stream" }, "aes-128-cfb8": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB8", "type": "stream" }, "aes-192-cfb8": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB8", "type": "stream" }, "aes-256-cfb8": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB8", "type": "stream" }, "aes-128-cfb1": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CFB1", "type": "stream" }, "aes-192-cfb1": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CFB1", "type": "stream" }, "aes-256-cfb1": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CFB1", "type": "stream" }, "aes-128-ofb": { "cipher": "AES", "key": 128, "iv": 16, "mode": "OFB", "type": "stream" }, "aes-192-ofb": { "cipher": "AES", "key": 192, "iv": 16, "mode": "OFB", "type": "stream" }, "aes-256-ofb": { "cipher": "AES", "key": 256, "iv": 16, "mode": "OFB", "type": "stream" }, "aes-128-ctr": { "cipher": "AES", "key": 128, "iv": 16, "mode": "CTR", "type": "stream" }, "aes-192-ctr": { "cipher": "AES", "key": 192, "iv": 16, "mode": "CTR", "type": "stream" }, "aes-256-ctr": { "cipher": "AES", "key": 256, "iv": 16, "mode": "CTR", "type": "stream" }, "aes-128-gcm": { "cipher": "AES", "key": 128, "iv": 12, "mode": "GCM", "type": "auth" }, "aes-192-gcm": { "cipher": "AES", "key": 192, "iv": 12, "mode": "GCM", "type": "auth" }, "aes-256-gcm": { "cipher": "AES", "key": 256, "iv": 12, "mode": "GCM", "type": "auth" } } },{}],166:[function(require,module,exports){ (function (Buffer){ var xor = require('buffer-xor') function getBlock (self) { self._prev = self._cipher.encryptBlock(self._prev) return self._prev } exports.encrypt = function (self, chunk) { while (self._cache.length < chunk.length) { self._cache = Buffer.concat([self._cache, getBlock(self)]) } var pad = self._cache.slice(0, chunk.length) self._cache = self._cache.slice(chunk.length) return xor(chunk, pad) } }).call(this,require("buffer").Buffer) },{"buffer":179,"buffer-xor":178}],167:[function(require,module,exports){ var aes = require('./aes') var Buffer = require('safe-buffer').Buffer var Transform = require('cipher-base') var inherits = require('inherits') function StreamCipher (mode, key, iv, decrypt) { Transform.call(this) this._cipher = new aes.AES(key) this._prev = Buffer.from(iv) this._cache = Buffer.allocUnsafe(0) this._secCache = Buffer.allocUnsafe(0) this._decrypt = decrypt this._mode = mode } inherits(StreamCipher, Transform) StreamCipher.prototype._update = function (chunk) { return this._mode.encrypt(this, chunk, this._decrypt) } StreamCipher.prototype._final = function () { this._cipher.scrub() } module.exports = StreamCipher },{"./aes":152,"cipher-base":180,"inherits":203,"safe-buffer":457}],168:[function(require,module,exports){ var ebtk = require('evp_bytestokey') var aes = require('browserify-aes/browser') var DES = require('browserify-des') var desModes = require('browserify-des/modes') var aesModes = require('browserify-aes/modes') function createCipher (suite, password) { var keyLen, ivLen suite = suite.toLowerCase() if (aesModes[suite]) { keyLen = aesModes[suite].key ivLen = aesModes[suite].iv } else if (desModes[suite]) { keyLen = desModes[suite].key * 8 ivLen = desModes[suite].iv } else { throw new TypeError('invalid suite type') } var keys = ebtk(password, false, keyLen, ivLen) return createCipheriv(suite, keys.key, keys.iv) } function createDecipher (suite, password) { var keyLen, ivLen suite = suite.toLowerCase() if (aesModes[suite]) { keyLen = aesModes[suite].key ivLen = aesModes[suite].iv } else if (desModes[suite]) { keyLen = desModes[suite].key * 8 ivLen = desModes[suite].iv } else { throw new TypeError('invalid suite type') } var keys = ebtk(password, false, keyLen, ivLen) return createDecipheriv(suite, keys.key, keys.iv) } function createCipheriv (suite, key, iv) { suite = suite.toLowerCase() if (aesModes[suite]) { return aes.createCipheriv(suite, key, iv) } else if (desModes[suite]) { return new DES({ key: key, iv: iv, mode: suite }) } else { throw new TypeError('invalid suite type') } } function createDecipheriv (suite, key, iv) { suite = suite.toLowerCase() if (aesModes[suite]) { return aes.createDecipheriv(suite, key, iv) } else if (desModes[suite]) { return new DES({ key: key, iv: iv, mode: suite, decrypt: true }) } else { throw new TypeError('invalid suite type') } } exports.createCipher = exports.Cipher = createCipher exports.createCipheriv = exports.Cipheriv = createCipheriv exports.createDecipher = exports.Decipher = createDecipher exports.createDecipheriv = exports.Decipheriv = createDecipheriv function getCiphers () { return Object.keys(desModes).concat(aes.getCiphers()) } exports.listCiphers = exports.getCiphers = getCiphers },{"browserify-aes/browser":154,"browserify-aes/modes":164,"browserify-des":169,"browserify-des/modes":170,"evp_bytestokey":200}],169:[function(require,module,exports){ (function (Buffer){ var CipherBase = require('cipher-base') var des = require('des.js') var inherits = require('inherits') var modes = { 'des-ede3-cbc': des.CBC.instantiate(des.EDE), 'des-ede3': des.EDE, 'des-ede-cbc': des.CBC.instantiate(des.EDE), 'des-ede': des.EDE, 'des-cbc': des.CBC.instantiate(des.DES), 'des-ecb': des.DES } modes.des = modes['des-cbc'] modes.des3 = modes['des-ede3-cbc'] module.exports = DES inherits(DES, CipherBase) function DES (opts) { CipherBase.call(this) var modeName = opts.mode.toLowerCase() var mode = modes[modeName] var type if (opts.decrypt) { type = 'decrypt' } else { type = 'encrypt' } var key = opts.key if (modeName === 'des-ede' || modeName === 'des-ede-cbc') { key = Buffer.concat([key, key.slice(0, 8)]) } var iv = opts.iv this._des = mode.create({ key: key, iv: iv, type: type }) } DES.prototype._update = function (data) { return new Buffer(this._des.update(data)) } DES.prototype._final = function () { return new Buffer(this._des.final()) } }).call(this,require("buffer").Buffer) },{"buffer":179,"cipher-base":180,"des.js":189,"inherits":203}],170:[function(require,module,exports){ exports['des-ecb'] = { key: 8, iv: 0 } exports['des-cbc'] = exports.des = { key: 8, iv: 8 } exports['des-ede3-cbc'] = exports.des3 = { key: 24, iv: 8 } exports['des-ede3'] = { key: 24, iv: 0 } exports['des-ede-cbc'] = { key: 16, iv: 8 } exports['des-ede'] = { key: 16, iv: 0 } },{}],171:[function(require,module,exports){ (function (Buffer){ var bn = require('bn.js'); var randomBytes = require('randombytes'); module.exports = crt; function blind(priv) { var r = getr(priv); var blinder = r.toRed(bn.mont(priv.modulus)) .redPow(new bn(priv.publicExponent)).fromRed(); return { blinder: blinder, unblinder:r.invm(priv.modulus) }; } function crt(msg, priv) { var blinds = blind(priv); var len = priv.modulus.byteLength(); var mod = bn.mont(priv.modulus); var blinded = new bn(msg).mul(blinds.blinder).umod(priv.modulus); var c1 = blinded.toRed(bn.mont(priv.prime1)); var c2 = blinded.toRed(bn.mont(priv.prime2)); var qinv = priv.coefficient; var p = priv.prime1; var q = priv.prime2; var m1 = c1.redPow(priv.exponent1); var m2 = c2.redPow(priv.exponent2); m1 = m1.fromRed(); m2 = m2.fromRed(); var h = m1.isub(m2).imul(qinv).umod(p); h.imul(q); m2.iadd(h); return new Buffer(m2.imul(blinds.unblinder).umod(priv.modulus).toArray(false, len)); } crt.getr = getr; function getr(priv) { var len = priv.modulus.byteLength(); var r = new bn(randomBytes(len)); while (r.cmp(priv.modulus) >= 0 || !r.umod(priv.prime1) || !r.umod(priv.prime2)) { r = new bn(randomBytes(len)); } return r; } }).call(this,require("buffer").Buffer) },{"bn.js":149,"buffer":179,"randombytes":230}],172:[function(require,module,exports){ module.exports = require('./browser/algorithms.json') },{"./browser/algorithms.json":173}],173:[function(require,module,exports){ module.exports={ "sha224WithRSAEncryption": { "sign": "rsa", "hash": "sha224", "id": "302d300d06096086480165030402040500041c" }, "RSA-SHA224": { "sign": "ecdsa/rsa", "hash": "sha224", "id": "302d300d06096086480165030402040500041c" }, "sha256WithRSAEncryption": { "sign": "rsa", "hash": "sha256", "id": "3031300d060960864801650304020105000420" }, "RSA-SHA256": { "sign": "ecdsa/rsa", "hash": "sha256", "id": "3031300d060960864801650304020105000420" }, "sha384WithRSAEncryption": { "sign": "rsa", "hash": "sha384", "id": "3041300d060960864801650304020205000430" }, "RSA-SHA384": { "sign": "ecdsa/rsa", "hash": "sha384", "id": "3041300d060960864801650304020205000430" }, "sha512WithRSAEncryption": { "sign": "rsa", "hash": "sha512", "id": "3051300d060960864801650304020305000440" }, "RSA-SHA512": { "sign": "ecdsa/rsa", "hash": "sha512", "id": "3051300d060960864801650304020305000440" }, "RSA-SHA1": { "sign": "rsa", "hash": "sha1", "id": "3021300906052b0e03021a05000414" }, "ecdsa-with-SHA1": { "sign": "ecdsa", "hash": "sha1", "id": "" }, "sha256": { "sign": "ecdsa", "hash": "sha256", "id": "" }, "sha224": { "sign": "ecdsa", "hash": "sha224", "id": "" }, "sha384": { "sign": "ecdsa", "hash": "sha384", "id": "" }, "sha512": { "sign": "ecdsa", "hash": "sha512", "id": "" }, "DSA-SHA": { "sign": "dsa", "hash": "sha1", "id": "" }, "DSA-SHA1": { "sign": "dsa", "hash": "sha1", "id": "" }, "DSA": { "sign": "dsa", "hash": "sha1", "id": "" }, "DSA-WITH-SHA224": { "sign": "dsa", "hash": "sha224", "id": "" }, "DSA-SHA224": { "sign": "dsa", "hash": "sha224", "id": "" }, "DSA-WITH-SHA256": { "sign": "dsa", "hash": "sha256", "id": "" }, "DSA-SHA256": { "sign": "dsa", "hash": "sha256", "id": "" }, "DSA-WITH-SHA384": { "sign": "dsa", "hash": "sha384", "id": "" }, "DSA-SHA384": { "sign": "dsa", "hash": "sha384", "id": "" }, "DSA-WITH-SHA512": { "sign": "dsa", "hash": "sha512", "id": "" }, "DSA-SHA512": { "sign": "dsa", "hash": "sha512", "id": "" }, "DSA-RIPEMD160": { "sign": "dsa", "hash": "rmd160", "id": "" }, "ripemd160WithRSA": { "sign": "rsa", "hash": "rmd160", "id": "3021300906052b2403020105000414" }, "RSA-RIPEMD160": { "sign": "rsa", "hash": "rmd160", "id": "3021300906052b2403020105000414" }, "md5WithRSAEncryption": { "sign": "rsa", "hash": "md5", "id": "3020300c06082a864886f70d020505000410" }, "RSA-MD5": { "sign": "rsa", "hash": "md5", "id": "3020300c06082a864886f70d020505000410" } } },{}],174:[function(require,module,exports){ module.exports={ "1.3.132.0.10": "secp256k1", "1.3.132.0.33": "p224", "1.2.840.10045.3.1.1": "p192", "1.2.840.10045.3.1.7": "p256", "1.3.132.0.34": "p384", "1.3.132.0.35": "p521" } },{}],175:[function(require,module,exports){ (function (Buffer){ var createHash = require('create-hash') var stream = require('stream') var inherits = require('inherits') var sign = require('./sign') var verify = require('./verify') var algorithms = require('./algorithms.json') Object.keys(algorithms).forEach(function (key) { algorithms[key].id = new Buffer(algorithms[key].id, 'hex') algorithms[key.toLowerCase()] = algorithms[key] }) function Sign (algorithm) { stream.Writable.call(this) var data = algorithms[algorithm] if (!data) throw new Error('Unknown message digest') this._hashType = data.hash this._hash = createHash(data.hash) this._tag = data.id this._signType = data.sign } inherits(Sign, stream.Writable) Sign.prototype._write = function _write (data, _, done) { this._hash.update(data) done() } Sign.prototype.update = function update (data, enc) { if (typeof data === 'string') data = new Buffer(data, enc) this._hash.update(data) return this } Sign.prototype.sign = function signMethod (key, enc) { this.end() var hash = this._hash.digest() var sig = sign(hash, key, this._hashType, this._signType, this._tag) return enc ? sig.toString(enc) : sig } function Verify (algorithm) { stream.Writable.call(this) var data = algorithms[algorithm] if (!data) throw new Error('Unknown message digest') this._hash = createHash(data.hash) this._tag = data.id this._signType = data.sign } inherits(Verify, stream.Writable) Verify.prototype._write = function _write (data, _, done) { this._hash.update(data) done() } Verify.prototype.update = function update (data, enc) { if (typeof data === 'string') data = new Buffer(data, enc) this._hash.update(data) return this } Verify.prototype.verify = function verifyMethod (key, sig, enc) { if (typeof sig === 'string') sig = new Buffer(sig, enc) this.end() var hash = this._hash.digest() return verify(sig, hash, key, this._signType, this._tag) } function createSign (algorithm) { return new Sign(algorithm) } function createVerify (algorithm) { return new Verify(algorithm) } module.exports = { Sign: createSign, Verify: createVerify, createSign: createSign, createVerify: createVerify } }).call(this,require("buffer").Buffer) },{"./algorithms.json":173,"./sign":176,"./verify":177,"buffer":179,"create-hash":183,"inherits":203,"stream":254}],176:[function(require,module,exports){ (function (Buffer){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var createHmac = require('create-hmac') var crt = require('browserify-rsa') var EC = require('elliptic').ec var BN = require('bn.js') var parseKeys = require('parse-asn1') var curves = require('./curves.json') function sign (hash, key, hashType, signType, tag) { var priv = parseKeys(key) if (priv.curve) { // rsa keys can be interpreted as ecdsa ones in openssl if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') return ecSign(hash, priv) } else if (priv.type === 'dsa') { if (signType !== 'dsa') throw new Error('wrong private key type') return dsaSign(hash, priv, hashType) } else { if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong private key type') } hash = Buffer.concat([tag, hash]) var len = priv.modulus.byteLength() var pad = [ 0, 1 ] while (hash.length + pad.length + 1 < len) pad.push(0xff) pad.push(0x00) var i = -1 while (++i < hash.length) pad.push(hash[i]) var out = crt(pad, priv) return out } function ecSign (hash, priv) { var curveId = curves[priv.curve.join('.')] if (!curveId) throw new Error('unknown curve ' + priv.curve.join('.')) var curve = new EC(curveId) var key = curve.keyFromPrivate(priv.privateKey) var out = key.sign(hash) return new Buffer(out.toDER()) } function dsaSign (hash, priv, algo) { var x = priv.params.priv_key var p = priv.params.p var q = priv.params.q var g = priv.params.g var r = new BN(0) var k var H = bits2int(hash, q).mod(q) var s = false var kv = getKey(x, q, hash, algo) while (s === false) { k = makeKey(q, kv, algo) r = makeR(g, k, p, q) s = k.invm(q).imul(H.add(x.mul(r))).mod(q) if (s.cmpn(0) === 0) { s = false r = new BN(0) } } return toDER(r, s) } function toDER (r, s) { r = r.toArray() s = s.toArray() // Pad values if (r[0] & 0x80) r = [ 0 ].concat(r) 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 new Buffer(res) } function getKey (x, q, hash, algo) { x = new Buffer(x.toArray()) if (x.length < q.byteLength()) { var zeros = new Buffer(q.byteLength() - x.length) zeros.fill(0) x = Buffer.concat([ zeros, x ]) } var hlen = hash.length var hbits = bits2octets(hash, q) var v = new Buffer(hlen) v.fill(1) var k = new Buffer(hlen) k.fill(0) k = createHmac(algo, k).update(v).update(new Buffer([ 0 ])).update(x).update(hbits).digest() v = createHmac(algo, k).update(v).digest() k = createHmac(algo, k).update(v).update(new Buffer([ 1 ])).update(x).update(hbits).digest() v = createHmac(algo, k).update(v).digest() return { k: k, v: v } } function bits2int (obits, q) { var bits = new BN(obits) var shift = (obits.length << 3) - q.bitLength() if (shift > 0) bits.ishrn(shift) return bits } function bits2octets (bits, q) { bits = bits2int(bits, q) bits = bits.mod(q) var out = new Buffer(bits.toArray()) if (out.length < q.byteLength()) { var zeros = new Buffer(q.byteLength() - out.length) zeros.fill(0) out = Buffer.concat([ zeros, out ]) } return out } function makeKey (q, kv, algo) { var t var k do { t = new Buffer(0) while (t.length * 8 < q.bitLength()) { kv.v = createHmac(algo, kv.k).update(kv.v).digest() t = Buffer.concat([ t, kv.v ]) } k = bits2int(t, q) kv.k = createHmac(algo, kv.k).update(kv.v).update(new Buffer([ 0 ])).digest() kv.v = createHmac(algo, kv.k).update(kv.v).digest() } while (k.cmp(q) !== -1) return k } function makeR (g, k, p, q) { return g.toRed(BN.mont(p)).redPow(k).fromRed().mod(q) } module.exports = sign module.exports.getKey = getKey module.exports.makeKey = makeKey }).call(this,require("buffer").Buffer) },{"./curves.json":174,"bn.js":149,"browserify-rsa":171,"buffer":179,"create-hmac":186,"elliptic":306,"parse-asn1":212}],177:[function(require,module,exports){ (function (Buffer){ // much of this based on https://github.com/indutny/self-signed/blob/gh-pages/lib/rsa.js var BN = require('bn.js') var EC = require('elliptic').ec var parseKeys = require('parse-asn1') var curves = require('./curves.json') function verify (sig, hash, key, signType, tag) { var pub = parseKeys(key) if (pub.type === 'ec') { // rsa keys can be interpreted as ecdsa ones in openssl if (signType !== 'ecdsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') return ecVerify(sig, hash, pub) } else if (pub.type === 'dsa') { if (signType !== 'dsa') throw new Error('wrong public key type') return dsaVerify(sig, hash, pub) } else { if (signType !== 'rsa' && signType !== 'ecdsa/rsa') throw new Error('wrong public key type') } hash = Buffer.concat([tag, hash]) var len = pub.modulus.byteLength() var pad = [ 1 ] var padNum = 0 while (hash.length + pad.length + 2 < len) { pad.push(0xff) padNum++ } pad.push(0x00) var i = -1 while (++i < hash.length) { pad.push(hash[i]) } pad = new Buffer(pad) var red = BN.mont(pub.modulus) sig = new BN(sig).toRed(red) sig = sig.redPow(new BN(pub.publicExponent)) sig = new Buffer(sig.fromRed().toArray()) var out = padNum < 8 ? 1 : 0 len = Math.min(sig.length, pad.length) if (sig.length !== pad.length) out = 1 i = -1 while (++i < len) out |= sig[i] ^ pad[i] return out === 0 } function ecVerify (sig, hash, pub) { var curveId = curves[pub.data.algorithm.curve.join('.')] if (!curveId) throw new Error('unknown curve ' + pub.data.algorithm.curve.join('.')) var curve = new EC(curveId) var pubkey = pub.data.subjectPrivateKey.data return curve.verify(hash, sig, pubkey) } function dsaVerify (sig, hash, pub) { var p = pub.data.p var q = pub.data.q var g = pub.data.g var y = pub.data.pub_key var unpacked = parseKeys.signature.decode(sig, 'der') var s = unpacked.s var r = unpacked.r checkValue(s, q) checkValue(r, q) var montp = BN.mont(p) var w = s.invm(q) var v = g.toRed(montp) .redPow(new BN(hash).mul(w).mod(q)) .fromRed() .mul(y.toRed(montp).redPow(r.mul(w).mod(q)).fromRed()) .mod(p) .mod(q) return v.cmp(r) === 0 } function checkValue (b, q) { if (b.cmpn(0) <= 0) throw new Error('invalid sig') if (b.cmp(q) >= q) throw new Error('invalid sig') } module.exports = verify }).call(this,require("buffer").Buffer) },{"./curves.json":174,"bn.js":149,"buffer":179,"elliptic":306,"parse-asn1":212}],178:[function(require,module,exports){ (function (Buffer){ module.exports = function xor (a, b) { var length = Math.min(a.length, b.length) var buffer = new Buffer(length) for (var i = 0; i < length; ++i) { buffer[i] = a[i] ^ b[i] } return buffer } }).call(this,require("buffer").Buffer) },{"buffer":179}],179:[function(require,module,exports){ (function (global){ /*! * The buffer module from node.js, for the browser. * * @author Feross Aboukhadijeh * @license MIT */ /* eslint-disable no-proto */ 'use strict' var base64 = require('base64-js') var ieee754 = require('ieee754') var isArray = require('isarray') exports.Buffer = Buffer exports.SlowBuffer = SlowBuffer exports.INSPECT_MAX_BYTES = 50 /** * If `Buffer.TYPED_ARRAY_SUPPORT`: * === true Use Uint8Array implementation (fastest) * === false Use Object implementation (most compatible, even IE6) * * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, * Opera 11.6+, iOS 4.2+. * * Due to various browser bugs, sometimes the Object implementation will be used even * when the browser supports typed arrays. * * Note: * * - Firefox 4-29 lacks support for adding new properties to `Uint8Array` instances, * See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438. * * - Chrome 9-10 is missing the `TypedArray.prototype.subarray` function. * * - IE10 has a broken `TypedArray.prototype.subarray` function which returns arrays of * incorrect length in some situations. * We detect these buggy browsers and set `Buffer.TYPED_ARRAY_SUPPORT` to `false` so they * get the Object implementation, which is slower but behaves correctly. */ Buffer.TYPED_ARRAY_SUPPORT = global.TYPED_ARRAY_SUPPORT !== undefined ? global.TYPED_ARRAY_SUPPORT : typedArraySupport() /* * Export kMaxLength after typed array support is determined. */ exports.kMaxLength = kMaxLength() function typedArraySupport () { try { var arr = new Uint8Array(1) arr.__proto__ = {__proto__: Uint8Array.prototype, foo: function () { return 42 }} return arr.foo() === 42 && // typed array instances can be augmented typeof arr.subarray === 'function' && // chrome 9-10 lack `subarray` arr.subarray(1, 1).byteLength === 0 // ie10 has broken `subarray` } catch (e) { return false } } function kMaxLength () { return Buffer.TYPED_ARRAY_SUPPORT ? 0x7fffffff : 0x3fffffff } function createBuffer (that, length) { if (kMaxLength() < length) { throw new RangeError('Invalid typed array length') } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = new Uint8Array(length) that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class if (that === null) { that = new Buffer(length) } that.length = length } return that } /** * The Buffer constructor returns instances of `Uint8Array` that have their * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of * `Uint8Array`, so the returned instances will have all the node `Buffer` methods * and the `Uint8Array` methods. Square bracket notation works as expected -- it * returns a single octet. * * The `Uint8Array` prototype remains unmodified. */ function Buffer (arg, encodingOrOffset, length) { if (!Buffer.TYPED_ARRAY_SUPPORT && !(this instanceof Buffer)) { return new Buffer(arg, encodingOrOffset, length) } // Common case. if (typeof arg === 'number') { if (typeof encodingOrOffset === 'string') { throw new Error( 'If encoding is specified then the first argument must be a string' ) } return allocUnsafe(this, arg) } return from(this, arg, encodingOrOffset, length) } Buffer.poolSize = 8192 // not used by this implementation // TODO: Legacy, not needed anymore. Remove in next major version. Buffer._augment = function (arr) { arr.__proto__ = Buffer.prototype return arr } function from (that, value, encodingOrOffset, length) { if (typeof value === 'number') { throw new TypeError('"value" argument must not be a number') } if (typeof ArrayBuffer !== 'undefined' && value instanceof ArrayBuffer) { return fromArrayBuffer(that, value, encodingOrOffset, length) } if (typeof value === 'string') { return fromString(that, value, encodingOrOffset) } return fromObject(that, value) } /** * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError * if value is a number. * Buffer.from(str[, encoding]) * Buffer.from(array) * Buffer.from(buffer) * Buffer.from(arrayBuffer[, byteOffset[, length]]) **/ Buffer.from = function (value, encodingOrOffset, length) { return from(null, value, encodingOrOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { Buffer.prototype.__proto__ = Uint8Array.prototype Buffer.__proto__ = Uint8Array if (typeof Symbol !== 'undefined' && Symbol.species && Buffer[Symbol.species] === Buffer) { // Fix subarray() in ES2016. See: https://github.com/feross/buffer/pull/97 Object.defineProperty(Buffer, Symbol.species, { value: null, configurable: true }) } } function assertSize (size) { if (typeof size !== 'number') { throw new TypeError('"size" argument must be a number') } else if (size < 0) { throw new RangeError('"size" argument must not be negative') } } function alloc (that, size, fill, encoding) { assertSize(size) if (size <= 0) { return createBuffer(that, size) } if (fill !== undefined) { // Only pay attention to encoding if it's a string. This // prevents accidentally sending in a number that would // be interpretted as a start offset. return typeof encoding === 'string' ? createBuffer(that, size).fill(fill, encoding) : createBuffer(that, size).fill(fill) } return createBuffer(that, size) } /** * Creates a new filled Buffer instance. * alloc(size[, fill[, encoding]]) **/ Buffer.alloc = function (size, fill, encoding) { return alloc(null, size, fill, encoding) } function allocUnsafe (that, size) { assertSize(size) that = createBuffer(that, size < 0 ? 0 : checked(size) | 0) if (!Buffer.TYPED_ARRAY_SUPPORT) { for (var i = 0; i < size; ++i) { that[i] = 0 } } return that } /** * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. * */ Buffer.allocUnsafe = function (size) { return allocUnsafe(null, size) } /** * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. */ Buffer.allocUnsafeSlow = function (size) { return allocUnsafe(null, size) } function fromString (that, string, encoding) { if (typeof encoding !== 'string' || encoding === '') { encoding = 'utf8' } if (!Buffer.isEncoding(encoding)) { throw new TypeError('"encoding" must be a valid string encoding') } var length = byteLength(string, encoding) | 0 that = createBuffer(that, length) var actual = that.write(string, encoding) if (actual !== length) { // Writing a hex string, for example, that contains invalid characters will // cause everything after the first invalid character to be ignored. (e.g. // 'abxxcd' will be treated as 'ab') that = that.slice(0, actual) } return that } function fromArrayLike (that, array) { var length = array.length < 0 ? 0 : checked(array.length) | 0 that = createBuffer(that, length) for (var i = 0; i < length; i += 1) { that[i] = array[i] & 255 } return that } function fromArrayBuffer (that, array, byteOffset, length) { array.byteLength // this throws if `array` is not a valid ArrayBuffer if (byteOffset < 0 || array.byteLength < byteOffset) { throw new RangeError('\'offset\' is out of bounds') } if (array.byteLength < byteOffset + (length || 0)) { throw new RangeError('\'length\' is out of bounds') } if (byteOffset === undefined && length === undefined) { array = new Uint8Array(array) } else if (length === undefined) { array = new Uint8Array(array, byteOffset) } else { array = new Uint8Array(array, byteOffset, length) } if (Buffer.TYPED_ARRAY_SUPPORT) { // Return an augmented `Uint8Array` instance, for best performance that = array that.__proto__ = Buffer.prototype } else { // Fallback: Return an object instance of the Buffer class that = fromArrayLike(that, array) } return that } function fromObject (that, obj) { if (Buffer.isBuffer(obj)) { var len = checked(obj.length) | 0 that = createBuffer(that, len) if (that.length === 0) { return that } obj.copy(that, 0, 0, len) return that } if (obj) { if ((typeof ArrayBuffer !== 'undefined' && obj.buffer instanceof ArrayBuffer) || 'length' in obj) { if (typeof obj.length !== 'number' || isnan(obj.length)) { return createBuffer(that, 0) } return fromArrayLike(that, obj) } if (obj.type === 'Buffer' && isArray(obj.data)) { return fromArrayLike(that, obj.data) } } throw new TypeError('First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.') } function checked (length) { // Note: cannot use `length < kMaxLength()` here because that fails when // length is NaN (which is otherwise coerced to zero.) if (length >= kMaxLength()) { throw new RangeError('Attempt to allocate Buffer larger than maximum ' + 'size: 0x' + kMaxLength().toString(16) + ' bytes') } return length | 0 } function SlowBuffer (length) { if (+length != length) { // eslint-disable-line eqeqeq length = 0 } return Buffer.alloc(+length) } Buffer.isBuffer = function isBuffer (b) { return !!(b != null && b._isBuffer) } Buffer.compare = function compare (a, b) { if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { throw new TypeError('Arguments must be Buffers') } if (a === b) return 0 var x = a.length var y = b.length for (var i = 0, len = Math.min(x, y); i < len; ++i) { if (a[i] !== b[i]) { x = a[i] y = b[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } Buffer.isEncoding = function isEncoding (encoding) { switch (String(encoding).toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'latin1': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return true default: return false } } Buffer.concat = function concat (list, length) { if (!isArray(list)) { throw new TypeError('"list" argument must be an Array of Buffers') } if (list.length === 0) { return Buffer.alloc(0) } var i if (length === undefined) { length = 0 for (i = 0; i < list.length; ++i) { length += list[i].length } } var buffer = Buffer.allocUnsafe(length) var pos = 0 for (i = 0; i < list.length; ++i) { var buf = list[i] if (!Buffer.isBuffer(buf)) { throw new TypeError('"list" argument must be an Array of Buffers') } buf.copy(buffer, pos) pos += buf.length } return buffer } function byteLength (string, encoding) { if (Buffer.isBuffer(string)) { return string.length } if (typeof ArrayBuffer !== 'undefined' && typeof ArrayBuffer.isView === 'function' && (ArrayBuffer.isView(string) || string instanceof ArrayBuffer)) { return string.byteLength } if (typeof string !== 'string') { string = '' + string } var len = string.length if (len === 0) return 0 // Use a for loop to avoid recursion var loweredCase = false for (;;) { switch (encoding) { case 'ascii': case 'latin1': case 'binary': return len case 'utf8': case 'utf-8': case undefined: return utf8ToBytes(string).length case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return len * 2 case 'hex': return len >>> 1 case 'base64': return base64ToBytes(string).length default: if (loweredCase) return utf8ToBytes(string).length // assume utf8 encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.byteLength = byteLength function slowToString (encoding, start, end) { var loweredCase = false // No need to verify that "this.length <= MAX_UINT32" since it's a read-only // property of a typed array. // This behaves neither like String nor Uint8Array in that we set start/end // to their upper/lower bounds if the value passed is out of range. // undefined is handled specially as per ECMA-262 6th Edition, // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. if (start === undefined || start < 0) { start = 0 } // Return early if start > this.length. Done here to prevent potential uint32 // coercion fail below. if (start > this.length) { return '' } if (end === undefined || end > this.length) { end = this.length } if (end <= 0) { return '' } // Force coersion to uint32. This will also coerce falsey/NaN values to 0. end >>>= 0 start >>>= 0 if (end <= start) { return '' } if (!encoding) encoding = 'utf8' while (true) { switch (encoding) { case 'hex': return hexSlice(this, start, end) case 'utf8': case 'utf-8': return utf8Slice(this, start, end) case 'ascii': return asciiSlice(this, start, end) case 'latin1': case 'binary': return latin1Slice(this, start, end) case 'base64': return base64Slice(this, start, end) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return utf16leSlice(this, start, end) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = (encoding + '').toLowerCase() loweredCase = true } } } // The property is used by `Buffer.isBuffer` and `is-buffer` (in Safari 5-7) to detect // Buffer instances. Buffer.prototype._isBuffer = true function swap (b, n, m) { var i = b[n] b[n] = b[m] b[m] = i } Buffer.prototype.swap16 = function swap16 () { var len = this.length if (len % 2 !== 0) { throw new RangeError('Buffer size must be a multiple of 16-bits') } for (var i = 0; i < len; i += 2) { swap(this, i, i + 1) } return this } Buffer.prototype.swap32 = function swap32 () { var len = this.length if (len % 4 !== 0) { throw new RangeError('Buffer size must be a multiple of 32-bits') } for (var i = 0; i < len; i += 4) { swap(this, i, i + 3) swap(this, i + 1, i + 2) } return this } Buffer.prototype.swap64 = function swap64 () { var len = this.length if (len % 8 !== 0) { throw new RangeError('Buffer size must be a multiple of 64-bits') } for (var i = 0; i < len; i += 8) { swap(this, i, i + 7) swap(this, i + 1, i + 6) swap(this, i + 2, i + 5) swap(this, i + 3, i + 4) } return this } Buffer.prototype.toString = function toString () { var length = this.length | 0 if (length === 0) return '' if (arguments.length === 0) return utf8Slice(this, 0, length) return slowToString.apply(this, arguments) } Buffer.prototype.equals = function equals (b) { if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') if (this === b) return true return Buffer.compare(this, b) === 0 } Buffer.prototype.inspect = function inspect () { var str = '' var max = exports.INSPECT_MAX_BYTES if (this.length > 0) { str = this.toString('hex', 0, max).match(/.{2}/g).join(' ') if (this.length > max) str += ' ... ' } return '' } Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { if (!Buffer.isBuffer(target)) { throw new TypeError('Argument must be a Buffer') } if (start === undefined) { start = 0 } if (end === undefined) { end = target ? target.length : 0 } if (thisStart === undefined) { thisStart = 0 } if (thisEnd === undefined) { thisEnd = this.length } if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { throw new RangeError('out of range index') } if (thisStart >= thisEnd && start >= end) { return 0 } if (thisStart >= thisEnd) { return -1 } if (start >= end) { return 1 } start >>>= 0 end >>>= 0 thisStart >>>= 0 thisEnd >>>= 0 if (this === target) return 0 var x = thisEnd - thisStart var y = end - start var len = Math.min(x, y) var thisCopy = this.slice(thisStart, thisEnd) var targetCopy = target.slice(start, end) for (var i = 0; i < len; ++i) { if (thisCopy[i] !== targetCopy[i]) { x = thisCopy[i] y = targetCopy[i] break } } if (x < y) return -1 if (y < x) return 1 return 0 } // Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, // OR the last index of `val` in `buffer` at offset <= `byteOffset`. // // Arguments: // - buffer - a Buffer to search // - val - a string, Buffer, or number // - byteOffset - an index into `buffer`; will be clamped to an int32 // - encoding - an optional encoding, relevant is val is a string // - dir - true for indexOf, false for lastIndexOf function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { // Empty buffer means no match if (buffer.length === 0) return -1 // Normalize byteOffset if (typeof byteOffset === 'string') { encoding = byteOffset byteOffset = 0 } else if (byteOffset > 0x7fffffff) { byteOffset = 0x7fffffff } else if (byteOffset < -0x80000000) { byteOffset = -0x80000000 } byteOffset = +byteOffset // Coerce to Number. if (isNaN(byteOffset)) { // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer byteOffset = dir ? 0 : (buffer.length - 1) } // Normalize byteOffset: negative offsets start from the end of the buffer if (byteOffset < 0) byteOffset = buffer.length + byteOffset if (byteOffset >= buffer.length) { if (dir) return -1 else byteOffset = buffer.length - 1 } else if (byteOffset < 0) { if (dir) byteOffset = 0 else return -1 } // Normalize val if (typeof val === 'string') { val = Buffer.from(val, encoding) } // Finally, search either indexOf (if dir is true) or lastIndexOf if (Buffer.isBuffer(val)) { // Special case: looking for empty string/buffer always fails if (val.length === 0) { return -1 } return arrayIndexOf(buffer, val, byteOffset, encoding, dir) } else if (typeof val === 'number') { val = val & 0xFF // Search for a byte value [0-255] if (Buffer.TYPED_ARRAY_SUPPORT && typeof Uint8Array.prototype.indexOf === 'function') { if (dir) { return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) } else { return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) } } return arrayIndexOf(buffer, [ val ], byteOffset, encoding, dir) } throw new TypeError('val must be string, number or Buffer') } function arrayIndexOf (arr, val, byteOffset, encoding, dir) { var indexSize = 1 var arrLength = arr.length var valLength = val.length if (encoding !== undefined) { encoding = String(encoding).toLowerCase() if (encoding === 'ucs2' || encoding === 'ucs-2' || encoding === 'utf16le' || encoding === 'utf-16le') { if (arr.length < 2 || val.length < 2) { return -1 } indexSize = 2 arrLength /= 2 valLength /= 2 byteOffset /= 2 } } function read (buf, i) { if (indexSize === 1) { return buf[i] } else { return buf.readUInt16BE(i * indexSize) } } var i if (dir) { var foundIndex = -1 for (i = byteOffset; i < arrLength; i++) { if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { if (foundIndex === -1) foundIndex = i if (i - foundIndex + 1 === valLength) return foundIndex * indexSize } else { if (foundIndex !== -1) i -= i - foundIndex foundIndex = -1 } } } else { if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength for (i = byteOffset; i >= 0; i--) { var found = true for (var j = 0; j < valLength; j++) { if (read(arr, i + j) !== read(val, j)) { found = false break } } if (found) return i } } return -1 } Buffer.prototype.includes = function includes (val, byteOffset, encoding) { return this.indexOf(val, byteOffset, encoding) !== -1 } Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, true) } Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { return bidirectionalIndexOf(this, val, byteOffset, encoding, false) } function hexWrite (buf, string, offset, length) { offset = Number(offset) || 0 var remaining = buf.length - offset if (!length) { length = remaining } else { length = Number(length) if (length > remaining) { length = remaining } } // must be an even number of digits var strLen = string.length if (strLen % 2 !== 0) throw new TypeError('Invalid hex string') if (length > strLen / 2) { length = strLen / 2 } for (var i = 0; i < length; ++i) { var parsed = parseInt(string.substr(i * 2, 2), 16) if (isNaN(parsed)) return i buf[offset + i] = parsed } return i } function utf8Write (buf, string, offset, length) { return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) } function asciiWrite (buf, string, offset, length) { return blitBuffer(asciiToBytes(string), buf, offset, length) } function latin1Write (buf, string, offset, length) { return asciiWrite(buf, string, offset, length) } function base64Write (buf, string, offset, length) { return blitBuffer(base64ToBytes(string), buf, offset, length) } function ucs2Write (buf, string, offset, length) { return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) } Buffer.prototype.write = function write (string, offset, length, encoding) { // Buffer#write(string) if (offset === undefined) { encoding = 'utf8' length = this.length offset = 0 // Buffer#write(string, encoding) } else if (length === undefined && typeof offset === 'string') { encoding = offset length = this.length offset = 0 // Buffer#write(string, offset[, length][, encoding]) } else if (isFinite(offset)) { offset = offset | 0 if (isFinite(length)) { length = length | 0 if (encoding === undefined) encoding = 'utf8' } else { encoding = length length = undefined } // legacy write(string, encoding, offset, length) - remove in v0.13 } else { throw new Error( 'Buffer.write(string, encoding, offset[, length]) is no longer supported' ) } var remaining = this.length - offset if (length === undefined || length > remaining) length = remaining if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { throw new RangeError('Attempt to write outside buffer bounds') } if (!encoding) encoding = 'utf8' var loweredCase = false for (;;) { switch (encoding) { case 'hex': return hexWrite(this, string, offset, length) case 'utf8': case 'utf-8': return utf8Write(this, string, offset, length) case 'ascii': return asciiWrite(this, string, offset, length) case 'latin1': case 'binary': return latin1Write(this, string, offset, length) case 'base64': // Warning: maxLength not taken into account in base64Write return base64Write(this, string, offset, length) case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return ucs2Write(this, string, offset, length) default: if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) encoding = ('' + encoding).toLowerCase() loweredCase = true } } } Buffer.prototype.toJSON = function toJSON () { return { type: 'Buffer', data: Array.prototype.slice.call(this._arr || this, 0) } } function base64Slice (buf, start, end) { if (start === 0 && end === buf.length) { return base64.fromByteArray(buf) } else { return base64.fromByteArray(buf.slice(start, end)) } } function utf8Slice (buf, start, end) { end = Math.min(buf.length, end) var res = [] var i = start while (i < end) { var firstByte = buf[i] var codePoint = null var bytesPerSequence = (firstByte > 0xEF) ? 4 : (firstByte > 0xDF) ? 3 : (firstByte > 0xBF) ? 2 : 1 if (i + bytesPerSequence <= end) { var secondByte, thirdByte, fourthByte, tempCodePoint switch (bytesPerSequence) { case 1: if (firstByte < 0x80) { codePoint = firstByte } break case 2: secondByte = buf[i + 1] if ((secondByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F) if (tempCodePoint > 0x7F) { codePoint = tempCodePoint } } break case 3: secondByte = buf[i + 1] thirdByte = buf[i + 2] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F) if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { codePoint = tempCodePoint } } break case 4: secondByte = buf[i + 1] thirdByte = buf[i + 2] fourthByte = buf[i + 3] if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F) if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { codePoint = tempCodePoint } } } } if (codePoint === null) { // we did not generate a valid codePoint so insert a // replacement char (U+FFFD) and advance only 1 byte codePoint = 0xFFFD bytesPerSequence = 1 } else if (codePoint > 0xFFFF) { // encode to utf16 (surrogate pair dance) codePoint -= 0x10000 res.push(codePoint >>> 10 & 0x3FF | 0xD800) codePoint = 0xDC00 | codePoint & 0x3FF } res.push(codePoint) i += bytesPerSequence } return decodeCodePointsArray(res) } // Based on http://stackoverflow.com/a/22747272/680742, the browser with // the lowest limit is Chrome, with 0x10000 args. // We go 1 magnitude less, for safety var MAX_ARGUMENTS_LENGTH = 0x1000 function decodeCodePointsArray (codePoints) { var len = codePoints.length if (len <= MAX_ARGUMENTS_LENGTH) { return String.fromCharCode.apply(String, codePoints) // avoid extra slice() } // Decode in chunks to avoid "call stack size exceeded". var res = '' var i = 0 while (i < len) { res += String.fromCharCode.apply( String, codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) ) } return res } function asciiSlice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i] & 0x7F) } return ret } function latin1Slice (buf, start, end) { var ret = '' end = Math.min(buf.length, end) for (var i = start; i < end; ++i) { ret += String.fromCharCode(buf[i]) } return ret } function hexSlice (buf, start, end) { var len = buf.length if (!start || start < 0) start = 0 if (!end || end < 0 || end > len) end = len var out = '' for (var i = start; i < end; ++i) { out += toHex(buf[i]) } return out } function utf16leSlice (buf, start, end) { var bytes = buf.slice(start, end) var res = '' for (var i = 0; i < bytes.length; i += 2) { res += String.fromCharCode(bytes[i] + bytes[i + 1] * 256) } return res } Buffer.prototype.slice = function slice (start, end) { var len = this.length start = ~~start end = end === undefined ? len : ~~end if (start < 0) { start += len if (start < 0) start = 0 } else if (start > len) { start = len } if (end < 0) { end += len if (end < 0) end = 0 } else if (end > len) { end = len } if (end < start) end = start var newBuf if (Buffer.TYPED_ARRAY_SUPPORT) { newBuf = this.subarray(start, end) newBuf.__proto__ = Buffer.prototype } else { var sliceLen = end - start newBuf = new Buffer(sliceLen, undefined) for (var i = 0; i < sliceLen; ++i) { newBuf[i] = this[i + start] } } return newBuf } /* * Need to make sure that buffer isn't trying to write out of bounds. */ function checkOffset (offset, ext, length) { if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') } Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } return val } Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { checkOffset(offset, byteLength, this.length) } var val = this[offset + --byteLength] var mul = 1 while (byteLength > 0 && (mul *= 0x100)) { val += this[offset + --byteLength] * mul } return val } Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) return this[offset] } Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return this[offset] | (this[offset + 1] << 8) } Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) return (this[offset] << 8) | this[offset + 1] } Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ((this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16)) + (this[offset + 3] * 0x1000000) } Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] * 0x1000000) + ((this[offset + 1] << 16) | (this[offset + 2] << 8) | this[offset + 3]) } Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var val = this[offset] var mul = 1 var i = 0 while (++i < byteLength && (mul *= 0x100)) { val += this[offset + i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) checkOffset(offset, byteLength, this.length) var i = byteLength var mul = 1 var val = this[offset + --i] while (i > 0 && (mul *= 0x100)) { val += this[offset + --i] * mul } mul *= 0x80 if (val >= mul) val -= Math.pow(2, 8 * byteLength) return val } Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { if (!noAssert) checkOffset(offset, 1, this.length) if (!(this[offset] & 0x80)) return (this[offset]) return ((0xff - this[offset] + 1) * -1) } Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset] | (this[offset + 1] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 2, this.length) var val = this[offset + 1] | (this[offset] << 8) return (val & 0x8000) ? val | 0xFFFF0000 : val } Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset]) | (this[offset + 1] << 8) | (this[offset + 2] << 16) | (this[offset + 3] << 24) } Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return (this[offset] << 24) | (this[offset + 1] << 16) | (this[offset + 2] << 8) | (this[offset + 3]) } Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, true, 23, 4) } Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 4, this.length) return ieee754.read(this, offset, false, 23, 4) } Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, true, 52, 8) } Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { if (!noAssert) checkOffset(offset, 8, this.length) return ieee754.read(this, offset, false, 52, 8) } function checkInt (buf, value, offset, ext, max, min) { if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') if (offset + ext > buf.length) throw new RangeError('Index out of range') } Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var mul = 1 var i = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 byteLength = byteLength | 0 if (!noAssert) { var maxBytes = Math.pow(2, 8 * byteLength) - 1 checkInt(this, value, offset, byteLength, maxBytes, 0) } var i = byteLength - 1 var mul = 1 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { this[offset + i] = (value / mul) & 0xFF } return offset + byteLength } Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) this[offset] = (value & 0xff) return offset + 1 } function objectWriteUInt16 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 2); i < j; ++i) { buf[offset + i] = (value & (0xff << (8 * (littleEndian ? i : 1 - i)))) >>> (littleEndian ? i : 1 - i) * 8 } } Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } function objectWriteUInt32 (buf, value, offset, littleEndian) { if (value < 0) value = 0xffffffff + value + 1 for (var i = 0, j = Math.min(buf.length - offset, 4); i < j; ++i) { buf[offset + i] = (value >>> (littleEndian ? i : 3 - i) * 8) & 0xff } } Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset + 3] = (value >>> 24) this[offset + 2] = (value >>> 16) this[offset + 1] = (value >>> 8) this[offset] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = 0 var mul = 1 var sub = 0 this[offset] = value & 0xFF while (++i < byteLength && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { value = +value offset = offset | 0 if (!noAssert) { var limit = Math.pow(2, 8 * byteLength - 1) checkInt(this, value, offset, byteLength, limit - 1, -limit) } var i = byteLength - 1 var mul = 1 var sub = 0 this[offset + i] = value & 0xFF while (--i >= 0 && (mul *= 0x100)) { if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { sub = 1 } this[offset + i] = ((value / mul) >> 0) - sub & 0xFF } return offset + byteLength } Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -0x80) if (!Buffer.TYPED_ARRAY_SUPPORT) value = Math.floor(value) if (value < 0) value = 0xff + value + 1 this[offset] = (value & 0xff) return offset + 1 } Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) } else { objectWriteUInt16(this, value, offset, true) } return offset + 2 } Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -0x8000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 8) this[offset + 1] = (value & 0xff) } else { objectWriteUInt16(this, value, offset, false) } return offset + 2 } Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value & 0xff) this[offset + 1] = (value >>> 8) this[offset + 2] = (value >>> 16) this[offset + 3] = (value >>> 24) } else { objectWriteUInt32(this, value, offset, true) } return offset + 4 } Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { value = +value offset = offset | 0 if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -0x80000000) if (value < 0) value = 0xffffffff + value + 1 if (Buffer.TYPED_ARRAY_SUPPORT) { this[offset] = (value >>> 24) this[offset + 1] = (value >>> 16) this[offset + 2] = (value >>> 8) this[offset + 3] = (value & 0xff) } else { objectWriteUInt32(this, value, offset, false) } return offset + 4 } function checkIEEE754 (buf, value, offset, ext, max, min) { if (offset + ext > buf.length) throw new RangeError('Index out of range') if (offset < 0) throw new RangeError('Index out of range') } function writeFloat (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 4, 3.4028234663852886e+38, -3.4028234663852886e+38) } ieee754.write(buf, value, offset, littleEndian, 23, 4) return offset + 4 } Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { return writeFloat(this, value, offset, true, noAssert) } Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { return writeFloat(this, value, offset, false, noAssert) } function writeDouble (buf, value, offset, littleEndian, noAssert) { if (!noAssert) { checkIEEE754(buf, value, offset, 8, 1.7976931348623157E+308, -1.7976931348623157E+308) } ieee754.write(buf, value, offset, littleEndian, 52, 8) return offset + 8 } Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { return writeDouble(this, value, offset, true, noAssert) } Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { return writeDouble(this, value, offset, false, noAssert) } // copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) Buffer.prototype.copy = function copy (target, targetStart, start, end) { if (!start) start = 0 if (!end && end !== 0) end = this.length if (targetStart >= target.length) targetStart = target.length if (!targetStart) targetStart = 0 if (end > 0 && end < start) end = start // Copy 0 bytes; we're done if (end === start) return 0 if (target.length === 0 || this.length === 0) return 0 // Fatal error conditions if (targetStart < 0) { throw new RangeError('targetStart out of bounds') } if (start < 0 || start >= this.length) throw new RangeError('sourceStart out of bounds') if (end < 0) throw new RangeError('sourceEnd out of bounds') // Are we oob? if (end > this.length) end = this.length if (target.length - targetStart < end - start) { end = target.length - targetStart + start } var len = end - start var i if (this === target && start < targetStart && targetStart < end) { // descending copy from end for (i = len - 1; i >= 0; --i) { target[i + targetStart] = this[i + start] } } else if (len < 1000 || !Buffer.TYPED_ARRAY_SUPPORT) { // ascending copy from start for (i = 0; i < len; ++i) { target[i + targetStart] = this[i + start] } } else { Uint8Array.prototype.set.call( target, this.subarray(start, start + len), targetStart ) } return len } // Usage: // buffer.fill(number[, offset[, end]]) // buffer.fill(buffer[, offset[, end]]) // buffer.fill(string[, offset[, end]][, encoding]) Buffer.prototype.fill = function fill (val, start, end, encoding) { // Handle string cases: if (typeof val === 'string') { if (typeof start === 'string') { encoding = start start = 0 end = this.length } else if (typeof end === 'string') { encoding = end end = this.length } if (val.length === 1) { var code = val.charCodeAt(0) if (code < 256) { val = code } } if (encoding !== undefined && typeof encoding !== 'string') { throw new TypeError('encoding must be a string') } if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { throw new TypeError('Unknown encoding: ' + encoding) } } else if (typeof val === 'number') { val = val & 255 } // Invalid ranges are not set to a default, so can range check early. if (start < 0 || this.length < start || this.length < end) { throw new RangeError('Out of range index') } if (end <= start) { return this } start = start >>> 0 end = end === undefined ? this.length : end >>> 0 if (!val) val = 0 var i if (typeof val === 'number') { for (i = start; i < end; ++i) { this[i] = val } } else { var bytes = Buffer.isBuffer(val) ? val : utf8ToBytes(new Buffer(val, encoding).toString()) var len = bytes.length for (i = 0; i < end - start; ++i) { this[i + start] = bytes[i % len] } } return this } // HELPER FUNCTIONS // ================ var INVALID_BASE64_RE = /[^+\/0-9A-Za-z-_]/g function base64clean (str) { // Node strips out invalid characters like \n and \t from the string, base64-js does not str = stringtrim(str).replace(INVALID_BASE64_RE, '') // Node converts strings with length < 2 to '' if (str.length < 2) return '' // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not while (str.length % 4 !== 0) { str = str + '=' } return str } function stringtrim (str) { if (str.trim) return str.trim() return str.replace(/^\s+|\s+$/g, '') } function toHex (n) { if (n < 16) return '0' + n.toString(16) return n.toString(16) } function utf8ToBytes (string, units) { units = units || Infinity var codePoint var length = string.length var leadSurrogate = null var bytes = [] for (var i = 0; i < length; ++i) { codePoint = string.charCodeAt(i) // is surrogate component if (codePoint > 0xD7FF && codePoint < 0xE000) { // last char was a lead if (!leadSurrogate) { // no lead yet if (codePoint > 0xDBFF) { // unexpected trail if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } else if (i + 1 === length) { // unpaired lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) continue } // valid lead leadSurrogate = codePoint continue } // 2 leads in a row if (codePoint < 0xDC00) { if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) leadSurrogate = codePoint continue } // valid surrogate pair codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000 } else if (leadSurrogate) { // valid bmp char, but last char was a lead if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD) } leadSurrogate = null // encode utf8 if (codePoint < 0x80) { if ((units -= 1) < 0) break bytes.push(codePoint) } else if (codePoint < 0x800) { if ((units -= 2) < 0) break bytes.push( codePoint >> 0x6 | 0xC0, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x10000) { if ((units -= 3) < 0) break bytes.push( codePoint >> 0xC | 0xE0, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else if (codePoint < 0x110000) { if ((units -= 4) < 0) break bytes.push( codePoint >> 0x12 | 0xF0, codePoint >> 0xC & 0x3F | 0x80, codePoint >> 0x6 & 0x3F | 0x80, codePoint & 0x3F | 0x80 ) } else { throw new Error('Invalid code point') } } return bytes } function asciiToBytes (str) { var byteArray = [] for (var i = 0; i < str.length; ++i) { // Node's code seems to be doing this and not & 0x7F.. byteArray.push(str.charCodeAt(i) & 0xFF) } return byteArray } function utf16leToBytes (str, units) { var c, hi, lo var byteArray = [] for (var i = 0; i < str.length; ++i) { if ((units -= 2) < 0) break c = str.charCodeAt(i) hi = c >> 8 lo = c % 256 byteArray.push(lo) byteArray.push(hi) } return byteArray } function base64ToBytes (str) { return base64.toByteArray(base64clean(str)) } function blitBuffer (src, dst, offset, length) { for (var i = 0; i < length; ++i) { if ((i + offset >= dst.length) || (i >= src.length)) break dst[i + offset] = src[i] } return i } function isnan (val) { return val !== val // eslint-disable-line no-self-compare } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"base64-js":148,"ieee754":201,"isarray":205}],180:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var Transform = require('stream').Transform var StringDecoder = require('string_decoder').StringDecoder var inherits = require('inherits') function CipherBase (hashMode) { Transform.call(this) this.hashMode = typeof hashMode === 'string' if (this.hashMode) { this[hashMode] = this._finalOrDigest } else { this.final = this._finalOrDigest } if (this._final) { this.__final = this._final this._final = null } this._decoder = null this._encoding = null } inherits(CipherBase, Transform) CipherBase.prototype.update = function (data, inputEnc, outputEnc) { if (typeof data === 'string') { data = Buffer.from(data, inputEnc) } var outData = this._update(data) if (this.hashMode) return this if (outputEnc) { outData = this._toString(outData, outputEnc) } return outData } CipherBase.prototype.setAutoPadding = function () {} CipherBase.prototype.getAuthTag = function () { throw new Error('trying to get auth tag in unsupported state') } CipherBase.prototype.setAuthTag = function () { throw new Error('trying to set auth tag in unsupported state') } CipherBase.prototype.setAAD = function () { throw new Error('trying to set aad in unsupported state') } CipherBase.prototype._transform = function (data, _, next) { var err try { if (this.hashMode) { this._update(data) } else { this.push(this._update(data)) } } catch (e) { err = e } finally { next(err) } } CipherBase.prototype._flush = function (done) { var err try { this.push(this.__final()) } catch (e) { err = e } done(err) } CipherBase.prototype._finalOrDigest = function (outputEnc) { var outData = this.__final() || Buffer.alloc(0) if (outputEnc) { outData = this._toString(outData, outputEnc, true) } return outData } CipherBase.prototype._toString = function (value, enc, fin) { if (!this._decoder) { this._decoder = new StringDecoder(enc) this._encoding = enc } if (this._encoding !== enc) throw new Error('can\'t switch encodings') var out = this._decoder.write(value) if (fin) { out += this._decoder.end() } return out } module.exports = CipherBase },{"inherits":203,"safe-buffer":457,"stream":254,"string_decoder":255}],181:[function(require,module,exports){ (function (Buffer){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(arg) { if (Array.isArray) { return Array.isArray(arg); } return objectToString(arg) === '[object Array]'; } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = Buffer.isBuffer; function objectToString(o) { return Object.prototype.toString.call(o); } }).call(this,{"isBuffer":require("../../is-buffer/index.js")}) },{"../../is-buffer/index.js":204}],182:[function(require,module,exports){ (function (Buffer){ var elliptic = require('elliptic'); var BN = require('bn.js'); module.exports = function createECDH(curve) { return new ECDH(curve); }; var aliases = { secp256k1: { name: 'secp256k1', byteLength: 32 }, secp224r1: { name: 'p224', byteLength: 28 }, prime256v1: { name: 'p256', byteLength: 32 }, prime192v1: { name: 'p192', byteLength: 24 }, ed25519: { name: 'ed25519', byteLength: 32 }, secp384r1: { name: 'p384', byteLength: 48 }, secp521r1: { name: 'p521', byteLength: 66 } }; aliases.p224 = aliases.secp224r1; aliases.p256 = aliases.secp256r1 = aliases.prime256v1; aliases.p192 = aliases.secp192r1 = aliases.prime192v1; aliases.p384 = aliases.secp384r1; aliases.p521 = aliases.secp521r1; function ECDH(curve) { this.curveType = aliases[curve]; if (!this.curveType ) { this.curveType = { name: curve }; } this.curve = new elliptic.ec(this.curveType.name); this.keys = void 0; } ECDH.prototype.generateKeys = function (enc, format) { this.keys = this.curve.genKeyPair(); return this.getPublicKey(enc, format); }; ECDH.prototype.computeSecret = function (other, inenc, enc) { inenc = inenc || 'utf8'; if (!Buffer.isBuffer(other)) { other = new Buffer(other, inenc); } var otherPub = this.curve.keyFromPublic(other).getPublic(); var out = otherPub.mul(this.keys.getPrivate()).getX(); return formatReturnValue(out, enc, this.curveType.byteLength); }; ECDH.prototype.getPublicKey = function (enc, format) { var key = this.keys.getPublic(format === 'compressed', true); if (format === 'hybrid') { if (key[key.length - 1] % 2) { key[0] = 7; } else { key [0] = 6; } } return formatReturnValue(key, enc); }; ECDH.prototype.getPrivateKey = function (enc) { return formatReturnValue(this.keys.getPrivate(), enc); }; ECDH.prototype.setPublicKey = function (pub, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(pub)) { pub = new Buffer(pub, enc); } this.keys._importPublic(pub); return this; }; ECDH.prototype.setPrivateKey = function (priv, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(priv)) { priv = new Buffer(priv, enc); } var _priv = new BN(priv); _priv = _priv.toString(16); this.keys._importPrivate(_priv); return this; }; function formatReturnValue(bn, enc, len) { if (!Array.isArray(bn)) { bn = bn.toArray(); } var buf = new Buffer(bn); if (len && buf.length < len) { var zeros = new Buffer(len - buf.length); zeros.fill(0); buf = Buffer.concat([zeros, buf]); } if (!enc) { return buf; } else { return buf.toString(enc); } } }).call(this,require("buffer").Buffer) },{"bn.js":149,"buffer":179,"elliptic":306}],183:[function(require,module,exports){ (function (Buffer){ 'use strict' var inherits = require('inherits') var md5 = require('./md5') var RIPEMD160 = require('ripemd160') var sha = require('sha.js') var Base = require('cipher-base') function HashNoConstructor (hash) { Base.call(this, 'digest') this._hash = hash this.buffers = [] } inherits(HashNoConstructor, Base) HashNoConstructor.prototype._update = function (data) { this.buffers.push(data) } HashNoConstructor.prototype._final = function () { var buf = Buffer.concat(this.buffers) var r = this._hash(buf) this.buffers = null return r } function Hash (hash) { Base.call(this, 'digest') this._hash = hash } inherits(Hash, Base) Hash.prototype._update = function (data) { this._hash.update(data) } Hash.prototype._final = function () { return this._hash.digest() } module.exports = function createHash (alg) { alg = alg.toLowerCase() if (alg === 'md5') return new HashNoConstructor(md5) if (alg === 'rmd160' || alg === 'ripemd160') return new Hash(new RIPEMD160()) return new Hash(sha(alg)) } }).call(this,require("buffer").Buffer) },{"./md5":185,"buffer":179,"cipher-base":180,"inherits":203,"ripemd160":245,"sha.js":247}],184:[function(require,module,exports){ (function (Buffer){ 'use strict' var intSize = 4 var zeroBuffer = new Buffer(intSize) zeroBuffer.fill(0) var charSize = 8 var hashSize = 16 function toArray (buf) { if ((buf.length % intSize) !== 0) { var len = buf.length + (intSize - (buf.length % intSize)) buf = Buffer.concat([buf, zeroBuffer], len) } var arr = new Array(buf.length >>> 2) for (var i = 0, j = 0; i < buf.length; i += intSize, j++) { arr[j] = buf.readInt32LE(i) } return arr } module.exports = function hash (buf, fn) { var arr = fn(toArray(buf), buf.length * charSize) buf = new Buffer(hashSize) for (var i = 0; i < arr.length; i++) { buf.writeInt32LE(arr[i], i << 2, true) } return buf } }).call(this,require("buffer").Buffer) },{"buffer":179}],185:[function(require,module,exports){ 'use strict' /* * A JavaScript implementation of the RSA Data Security, Inc. MD5 Message * Digest Algorithm, as defined in RFC 1321. * Version 2.1 Copyright (C) Paul Johnston 1999 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for more info. */ var makeHash = require('./make-hash') /* * Calculate the MD5 of an array of little-endian words, and a bit length */ function core_md5 (x, len) { /* append padding */ x[len >> 5] |= 0x80 << ((len) % 32) x[(((len + 64) >>> 9) << 4) + 14] = len var a = 1732584193 var b = -271733879 var c = -1732584194 var d = 271733878 for (var i = 0; i < x.length; i += 16) { var olda = a var oldb = b var oldc = c var oldd = d a = md5_ff(a, b, c, d, x[i + 0], 7, -680876936) d = md5_ff(d, a, b, c, x[i + 1], 12, -389564586) c = md5_ff(c, d, a, b, x[i + 2], 17, 606105819) b = md5_ff(b, c, d, a, x[i + 3], 22, -1044525330) a = md5_ff(a, b, c, d, x[i + 4], 7, -176418897) d = md5_ff(d, a, b, c, x[i + 5], 12, 1200080426) c = md5_ff(c, d, a, b, x[i + 6], 17, -1473231341) b = md5_ff(b, c, d, a, x[i + 7], 22, -45705983) a = md5_ff(a, b, c, d, x[i + 8], 7, 1770035416) d = md5_ff(d, a, b, c, x[i + 9], 12, -1958414417) c = md5_ff(c, d, a, b, x[i + 10], 17, -42063) b = md5_ff(b, c, d, a, x[i + 11], 22, -1990404162) a = md5_ff(a, b, c, d, x[i + 12], 7, 1804603682) d = md5_ff(d, a, b, c, x[i + 13], 12, -40341101) c = md5_ff(c, d, a, b, x[i + 14], 17, -1502002290) b = md5_ff(b, c, d, a, x[i + 15], 22, 1236535329) a = md5_gg(a, b, c, d, x[i + 1], 5, -165796510) d = md5_gg(d, a, b, c, x[i + 6], 9, -1069501632) c = md5_gg(c, d, a, b, x[i + 11], 14, 643717713) b = md5_gg(b, c, d, a, x[i + 0], 20, -373897302) a = md5_gg(a, b, c, d, x[i + 5], 5, -701558691) d = md5_gg(d, a, b, c, x[i + 10], 9, 38016083) c = md5_gg(c, d, a, b, x[i + 15], 14, -660478335) b = md5_gg(b, c, d, a, x[i + 4], 20, -405537848) a = md5_gg(a, b, c, d, x[i + 9], 5, 568446438) d = md5_gg(d, a, b, c, x[i + 14], 9, -1019803690) c = md5_gg(c, d, a, b, x[i + 3], 14, -187363961) b = md5_gg(b, c, d, a, x[i + 8], 20, 1163531501) a = md5_gg(a, b, c, d, x[i + 13], 5, -1444681467) d = md5_gg(d, a, b, c, x[i + 2], 9, -51403784) c = md5_gg(c, d, a, b, x[i + 7], 14, 1735328473) b = md5_gg(b, c, d, a, x[i + 12], 20, -1926607734) a = md5_hh(a, b, c, d, x[i + 5], 4, -378558) d = md5_hh(d, a, b, c, x[i + 8], 11, -2022574463) c = md5_hh(c, d, a, b, x[i + 11], 16, 1839030562) b = md5_hh(b, c, d, a, x[i + 14], 23, -35309556) a = md5_hh(a, b, c, d, x[i + 1], 4, -1530992060) d = md5_hh(d, a, b, c, x[i + 4], 11, 1272893353) c = md5_hh(c, d, a, b, x[i + 7], 16, -155497632) b = md5_hh(b, c, d, a, x[i + 10], 23, -1094730640) a = md5_hh(a, b, c, d, x[i + 13], 4, 681279174) d = md5_hh(d, a, b, c, x[i + 0], 11, -358537222) c = md5_hh(c, d, a, b, x[i + 3], 16, -722521979) b = md5_hh(b, c, d, a, x[i + 6], 23, 76029189) a = md5_hh(a, b, c, d, x[i + 9], 4, -640364487) d = md5_hh(d, a, b, c, x[i + 12], 11, -421815835) c = md5_hh(c, d, a, b, x[i + 15], 16, 530742520) b = md5_hh(b, c, d, a, x[i + 2], 23, -995338651) a = md5_ii(a, b, c, d, x[i + 0], 6, -198630844) d = md5_ii(d, a, b, c, x[i + 7], 10, 1126891415) c = md5_ii(c, d, a, b, x[i + 14], 15, -1416354905) b = md5_ii(b, c, d, a, x[i + 5], 21, -57434055) a = md5_ii(a, b, c, d, x[i + 12], 6, 1700485571) d = md5_ii(d, a, b, c, x[i + 3], 10, -1894986606) c = md5_ii(c, d, a, b, x[i + 10], 15, -1051523) b = md5_ii(b, c, d, a, x[i + 1], 21, -2054922799) a = md5_ii(a, b, c, d, x[i + 8], 6, 1873313359) d = md5_ii(d, a, b, c, x[i + 15], 10, -30611744) c = md5_ii(c, d, a, b, x[i + 6], 15, -1560198380) b = md5_ii(b, c, d, a, x[i + 13], 21, 1309151649) a = md5_ii(a, b, c, d, x[i + 4], 6, -145523070) d = md5_ii(d, a, b, c, x[i + 11], 10, -1120210379) c = md5_ii(c, d, a, b, x[i + 2], 15, 718787259) b = md5_ii(b, c, d, a, x[i + 9], 21, -343485551) a = safe_add(a, olda) b = safe_add(b, oldb) c = safe_add(c, oldc) d = safe_add(d, oldd) } return [a, b, c, d] } /* * These functions implement the four basic operations the algorithm uses. */ function md5_cmn (q, a, b, x, s, t) { return safe_add(bit_rol(safe_add(safe_add(a, q), safe_add(x, t)), s), b) } function md5_ff (a, b, c, d, x, s, t) { return md5_cmn((b & c) | ((~b) & d), a, b, x, s, t) } function md5_gg (a, b, c, d, x, s, t) { return md5_cmn((b & d) | (c & (~d)), a, b, x, s, t) } function md5_hh (a, b, c, d, x, s, t) { return md5_cmn(b ^ c ^ d, a, b, x, s, t) } function md5_ii (a, b, c, d, x, s, t) { return md5_cmn(c ^ (b | (~d)), a, b, x, s, t) } /* * Add integers, wrapping at 2^32. This uses 16-bit operations internally * to work around bugs in some JS interpreters. */ function safe_add (x, y) { var lsw = (x & 0xFFFF) + (y & 0xFFFF) var msw = (x >> 16) + (y >> 16) + (lsw >> 16) return (msw << 16) | (lsw & 0xFFFF) } /* * Bitwise rotate a 32-bit number to the left. */ function bit_rol (num, cnt) { return (num << cnt) | (num >>> (32 - cnt)) } module.exports = function md5 (buf) { return makeHash(buf, core_md5) } },{"./make-hash":184}],186:[function(require,module,exports){ 'use strict' var inherits = require('inherits') var Legacy = require('./legacy') var Base = require('cipher-base') var Buffer = require('safe-buffer').Buffer var md5 = require('create-hash/md5') var RIPEMD160 = require('ripemd160') var sha = require('sha.js') var ZEROS = Buffer.alloc(128) function Hmac (alg, key) { Base.call(this, 'digest') if (typeof key === 'string') { key = Buffer.from(key) } var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 this._alg = alg this._key = key if (key.length > blocksize) { var hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) key = hash.update(key).digest() } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize) } var ipad = this._ipad = Buffer.allocUnsafe(blocksize) var opad = this._opad = Buffer.allocUnsafe(blocksize) for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } this._hash = alg === 'rmd160' ? new RIPEMD160() : sha(alg) this._hash.update(ipad) } inherits(Hmac, Base) Hmac.prototype._update = function (data) { this._hash.update(data) } Hmac.prototype._final = function () { var h = this._hash.digest() var hash = this._alg === 'rmd160' ? new RIPEMD160() : sha(this._alg) return hash.update(this._opad).update(h).digest() } module.exports = function createHmac (alg, key) { alg = alg.toLowerCase() if (alg === 'rmd160' || alg === 'ripemd160') { return new Hmac('rmd160', key) } if (alg === 'md5') { return new Legacy(md5, key) } return new Hmac(alg, key) } },{"./legacy":187,"cipher-base":180,"create-hash/md5":185,"inherits":203,"ripemd160":245,"safe-buffer":457,"sha.js":247}],187:[function(require,module,exports){ 'use strict' var inherits = require('inherits') var Buffer = require('safe-buffer').Buffer var Base = require('cipher-base') var ZEROS = Buffer.alloc(128) var blocksize = 64 function Hmac (alg, key) { Base.call(this, 'digest') if (typeof key === 'string') { key = Buffer.from(key) } this._alg = alg this._key = key if (key.length > blocksize) { key = alg(key) } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize) } var ipad = this._ipad = Buffer.allocUnsafe(blocksize) var opad = this._opad = Buffer.allocUnsafe(blocksize) for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } this._hash = [ipad] } inherits(Hmac, Base) Hmac.prototype._update = function (data) { this._hash.push(data) } Hmac.prototype._final = function () { var h = this._alg(Buffer.concat(this._hash)) return this._alg(Buffer.concat([this._opad, h])) } module.exports = Hmac },{"cipher-base":180,"inherits":203,"safe-buffer":457}],188:[function(require,module,exports){ 'use strict' exports.randomBytes = exports.rng = exports.pseudoRandomBytes = exports.prng = require('randombytes') exports.createHash = exports.Hash = require('create-hash') exports.createHmac = exports.Hmac = require('create-hmac') var algos = require('browserify-sign/algos') var algoKeys = Object.keys(algos) var hashes = ['sha1', 'sha224', 'sha256', 'sha384', 'sha512', 'md5', 'rmd160'].concat(algoKeys) exports.getHashes = function () { return hashes } var p = require('pbkdf2') exports.pbkdf2 = p.pbkdf2 exports.pbkdf2Sync = p.pbkdf2Sync var aes = require('browserify-cipher') exports.Cipher = aes.Cipher exports.createCipher = aes.createCipher exports.Cipheriv = aes.Cipheriv exports.createCipheriv = aes.createCipheriv exports.Decipher = aes.Decipher exports.createDecipher = aes.createDecipher exports.Decipheriv = aes.Decipheriv exports.createDecipheriv = aes.createDecipheriv exports.getCiphers = aes.getCiphers exports.listCiphers = aes.listCiphers var dh = require('diffie-hellman') exports.DiffieHellmanGroup = dh.DiffieHellmanGroup exports.createDiffieHellmanGroup = dh.createDiffieHellmanGroup exports.getDiffieHellman = dh.getDiffieHellman exports.createDiffieHellman = dh.createDiffieHellman exports.DiffieHellman = dh.DiffieHellman var sign = require('browserify-sign') exports.createSign = sign.createSign exports.Sign = sign.Sign exports.createVerify = sign.createVerify exports.Verify = sign.Verify exports.createECDH = require('create-ecdh') var publicEncrypt = require('public-encrypt') exports.publicEncrypt = publicEncrypt.publicEncrypt exports.privateEncrypt = publicEncrypt.privateEncrypt exports.publicDecrypt = publicEncrypt.publicDecrypt exports.privateDecrypt = publicEncrypt.privateDecrypt // the least I can do is make error messages for the rest of the node.js/crypto api. // ;[ // 'createCredentials' // ].forEach(function (name) { // exports[name] = function () { // throw new Error([ // 'sorry, ' + name + ' is not implemented yet', // 'we accept pull requests', // 'https://github.com/crypto-browserify/crypto-browserify' // ].join('\n')) // } // }) exports.createCredentials = function () { throw new Error([ 'sorry, createCredentials is not implemented yet', 'we accept pull requests', 'https://github.com/crypto-browserify/crypto-browserify' ].join('\n')) } exports.constants = { 'DH_CHECK_P_NOT_SAFE_PRIME': 2, 'DH_CHECK_P_NOT_PRIME': 1, 'DH_UNABLE_TO_CHECK_GENERATOR': 4, 'DH_NOT_SUITABLE_GENERATOR': 8, 'NPN_ENABLED': 1, 'ALPN_ENABLED': 1, 'RSA_PKCS1_PADDING': 1, 'RSA_SSLV23_PADDING': 2, 'RSA_NO_PADDING': 3, 'RSA_PKCS1_OAEP_PADDING': 4, 'RSA_X931_PADDING': 5, 'RSA_PKCS1_PSS_PADDING': 6, 'POINT_CONVERSION_COMPRESSED': 2, 'POINT_CONVERSION_UNCOMPRESSED': 4, 'POINT_CONVERSION_HYBRID': 6 } },{"browserify-cipher":168,"browserify-sign":175,"browserify-sign/algos":172,"create-ecdh":182,"create-hash":183,"create-hmac":186,"diffie-hellman":195,"pbkdf2":213,"public-encrypt":220,"randombytes":230}],189:[function(require,module,exports){ 'use strict'; exports.utils = require('./des/utils'); exports.Cipher = require('./des/cipher'); exports.DES = require('./des/des'); exports.CBC = require('./des/cbc'); exports.EDE = require('./des/ede'); },{"./des/cbc":190,"./des/cipher":191,"./des/des":192,"./des/ede":193,"./des/utils":194}],190:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); var inherits = require('inherits'); var proto = {}; function CBCState(iv) { assert.equal(iv.length, 8, 'Invalid IV length'); this.iv = new Array(8); for (var i = 0; i < this.iv.length; i++) this.iv[i] = iv[i]; } function instantiate(Base) { function CBC(options) { Base.call(this, options); this._cbcInit(); } inherits(CBC, Base); var keys = Object.keys(proto); for (var i = 0; i < keys.length; i++) { var key = keys[i]; CBC.prototype[key] = proto[key]; } CBC.create = function create(options) { return new CBC(options); }; return CBC; } exports.instantiate = instantiate; proto._cbcInit = function _cbcInit() { var state = new CBCState(this.options.iv); this._cbcState = state; }; proto._update = function _update(inp, inOff, out, outOff) { var state = this._cbcState; var superProto = this.constructor.super_.prototype; var iv = state.iv; if (this.type === 'encrypt') { for (var i = 0; i < this.blockSize; i++) iv[i] ^= inp[inOff + i]; superProto._update.call(this, iv, 0, out, outOff); for (var i = 0; i < this.blockSize; i++) iv[i] = out[outOff + i]; } else { superProto._update.call(this, inp, inOff, out, outOff); for (var i = 0; i < this.blockSize; i++) out[outOff + i] ^= iv[i]; for (var i = 0; i < this.blockSize; i++) iv[i] = inp[inOff + i]; } }; },{"inherits":203,"minimalistic-assert":207}],191:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); function Cipher(options) { this.options = options; this.type = this.options.type; this.blockSize = 8; this._init(); this.buffer = new Array(this.blockSize); this.bufferOff = 0; } module.exports = Cipher; Cipher.prototype._init = function _init() { // Might be overrided }; Cipher.prototype.update = function update(data) { if (data.length === 0) return []; if (this.type === 'decrypt') return this._updateDecrypt(data); else return this._updateEncrypt(data); }; Cipher.prototype._buffer = function _buffer(data, off) { // Append data to buffer var min = Math.min(this.buffer.length - this.bufferOff, data.length - off); for (var i = 0; i < min; i++) this.buffer[this.bufferOff + i] = data[off + i]; this.bufferOff += min; // Shift next return min; }; Cipher.prototype._flushBuffer = function _flushBuffer(out, off) { this._update(this.buffer, 0, out, off); this.bufferOff = 0; return this.blockSize; }; Cipher.prototype._updateEncrypt = function _updateEncrypt(data) { var inputOff = 0; var outputOff = 0; var count = ((this.bufferOff + data.length) / this.blockSize) | 0; var out = new Array(count * this.blockSize); if (this.bufferOff !== 0) { inputOff += this._buffer(data, inputOff); if (this.bufferOff === this.buffer.length) outputOff += this._flushBuffer(out, outputOff); } // Write blocks var max = data.length - ((data.length - inputOff) % this.blockSize); for (; inputOff < max; inputOff += this.blockSize) { this._update(data, inputOff, out, outputOff); outputOff += this.blockSize; } // Queue rest for (; inputOff < data.length; inputOff++, this.bufferOff++) this.buffer[this.bufferOff] = data[inputOff]; return out; }; Cipher.prototype._updateDecrypt = function _updateDecrypt(data) { var inputOff = 0; var outputOff = 0; var count = Math.ceil((this.bufferOff + data.length) / this.blockSize) - 1; var out = new Array(count * this.blockSize); // TODO(indutny): optimize it, this is far from optimal for (; count > 0; count--) { inputOff += this._buffer(data, inputOff); outputOff += this._flushBuffer(out, outputOff); } // Buffer rest of the input inputOff += this._buffer(data, inputOff); return out; }; Cipher.prototype.final = function final(buffer) { var first; if (buffer) first = this.update(buffer); var last; if (this.type === 'encrypt') last = this._finalEncrypt(); else last = this._finalDecrypt(); if (first) return first.concat(last); else return last; }; Cipher.prototype._pad = function _pad(buffer, off) { if (off === 0) return false; while (off < buffer.length) buffer[off++] = 0; return true; }; Cipher.prototype._finalEncrypt = function _finalEncrypt() { if (!this._pad(this.buffer, this.bufferOff)) return []; var out = new Array(this.blockSize); this._update(this.buffer, 0, out, 0); return out; }; Cipher.prototype._unpad = function _unpad(buffer) { return buffer; }; Cipher.prototype._finalDecrypt = function _finalDecrypt() { assert.equal(this.bufferOff, this.blockSize, 'Not enough data to decrypt'); var out = new Array(this.blockSize); this._flushBuffer(out, 0); return this._unpad(out); }; },{"minimalistic-assert":207}],192:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); var inherits = require('inherits'); var des = require('../des'); var utils = des.utils; var Cipher = des.Cipher; function DESState() { this.tmp = new Array(2); this.keys = null; } function DES(options) { Cipher.call(this, options); var state = new DESState(); this._desState = state; this.deriveKeys(state, options.key); } inherits(DES, Cipher); module.exports = DES; DES.create = function create(options) { return new DES(options); }; var shiftTable = [ 1, 1, 2, 2, 2, 2, 2, 2, 1, 2, 2, 2, 2, 2, 2, 1 ]; DES.prototype.deriveKeys = function deriveKeys(state, key) { state.keys = new Array(16 * 2); assert.equal(key.length, this.blockSize, 'Invalid key length'); var kL = utils.readUInt32BE(key, 0); var kR = utils.readUInt32BE(key, 4); utils.pc1(kL, kR, state.tmp, 0); kL = state.tmp[0]; kR = state.tmp[1]; for (var i = 0; i < state.keys.length; i += 2) { var shift = shiftTable[i >>> 1]; kL = utils.r28shl(kL, shift); kR = utils.r28shl(kR, shift); utils.pc2(kL, kR, state.keys, i); } }; DES.prototype._update = function _update(inp, inOff, out, outOff) { var state = this._desState; var l = utils.readUInt32BE(inp, inOff); var r = utils.readUInt32BE(inp, inOff + 4); // Initial Permutation utils.ip(l, r, state.tmp, 0); l = state.tmp[0]; r = state.tmp[1]; if (this.type === 'encrypt') this._encrypt(state, l, r, state.tmp, 0); else this._decrypt(state, l, r, state.tmp, 0); l = state.tmp[0]; r = state.tmp[1]; utils.writeUInt32BE(out, l, outOff); utils.writeUInt32BE(out, r, outOff + 4); }; DES.prototype._pad = function _pad(buffer, off) { var value = buffer.length - off; for (var i = off; i < buffer.length; i++) buffer[i] = value; return true; }; DES.prototype._unpad = function _unpad(buffer) { var pad = buffer[buffer.length - 1]; for (var i = buffer.length - pad; i < buffer.length; i++) assert.equal(buffer[i], pad); return buffer.slice(0, buffer.length - pad); }; DES.prototype._encrypt = function _encrypt(state, lStart, rStart, out, off) { var l = lStart; var r = rStart; // Apply f() x16 times for (var i = 0; i < state.keys.length; i += 2) { var keyL = state.keys[i]; var keyR = state.keys[i + 1]; // f(r, k) utils.expand(r, state.tmp, 0); keyL ^= state.tmp[0]; keyR ^= state.tmp[1]; var s = utils.substitute(keyL, keyR); var f = utils.permute(s); var t = r; r = (l ^ f) >>> 0; l = t; } // Reverse Initial Permutation utils.rip(r, l, out, off); }; DES.prototype._decrypt = function _decrypt(state, lStart, rStart, out, off) { var l = rStart; var r = lStart; // Apply f() x16 times for (var i = state.keys.length - 2; i >= 0; i -= 2) { var keyL = state.keys[i]; var keyR = state.keys[i + 1]; // f(r, k) utils.expand(l, state.tmp, 0); keyL ^= state.tmp[0]; keyR ^= state.tmp[1]; var s = utils.substitute(keyL, keyR); var f = utils.permute(s); var t = l; l = (r ^ f) >>> 0; r = t; } // Reverse Initial Permutation utils.rip(l, r, out, off); }; },{"../des":189,"inherits":203,"minimalistic-assert":207}],193:[function(require,module,exports){ 'use strict'; var assert = require('minimalistic-assert'); var inherits = require('inherits'); var des = require('../des'); var Cipher = des.Cipher; var DES = des.DES; function EDEState(type, key) { assert.equal(key.length, 24, 'Invalid key length'); var k1 = key.slice(0, 8); var k2 = key.slice(8, 16); var k3 = key.slice(16, 24); if (type === 'encrypt') { this.ciphers = [ DES.create({ type: 'encrypt', key: k1 }), DES.create({ type: 'decrypt', key: k2 }), DES.create({ type: 'encrypt', key: k3 }) ]; } else { this.ciphers = [ DES.create({ type: 'decrypt', key: k3 }), DES.create({ type: 'encrypt', key: k2 }), DES.create({ type: 'decrypt', key: k1 }) ]; } } function EDE(options) { Cipher.call(this, options); var state = new EDEState(this.type, this.options.key); this._edeState = state; } inherits(EDE, Cipher); module.exports = EDE; EDE.create = function create(options) { return new EDE(options); }; EDE.prototype._update = function _update(inp, inOff, out, outOff) { var state = this._edeState; state.ciphers[0]._update(inp, inOff, out, outOff); state.ciphers[1]._update(out, outOff, out, outOff); state.ciphers[2]._update(out, outOff, out, outOff); }; EDE.prototype._pad = DES.prototype._pad; EDE.prototype._unpad = DES.prototype._unpad; },{"../des":189,"inherits":203,"minimalistic-assert":207}],194:[function(require,module,exports){ 'use strict'; exports.readUInt32BE = function readUInt32BE(bytes, off) { var res = (bytes[0 + off] << 24) | (bytes[1 + off] << 16) | (bytes[2 + off] << 8) | bytes[3 + off]; return res >>> 0; }; exports.writeUInt32BE = function writeUInt32BE(bytes, value, off) { bytes[0 + off] = value >>> 24; bytes[1 + off] = (value >>> 16) & 0xff; bytes[2 + off] = (value >>> 8) & 0xff; bytes[3 + off] = value & 0xff; }; exports.ip = function ip(inL, inR, out, off) { var outL = 0; var outR = 0; for (var i = 6; i >= 0; i -= 2) { for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inR >>> (j + i)) & 1; } for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inL >>> (j + i)) & 1; } } for (var i = 6; i >= 0; i -= 2) { for (var j = 1; j <= 25; j += 8) { outR <<= 1; outR |= (inR >>> (j + i)) & 1; } for (var j = 1; j <= 25; j += 8) { outR <<= 1; outR |= (inL >>> (j + i)) & 1; } } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.rip = function rip(inL, inR, out, off) { var outL = 0; var outR = 0; for (var i = 0; i < 4; i++) { for (var j = 24; j >= 0; j -= 8) { outL <<= 1; outL |= (inR >>> (j + i)) & 1; outL <<= 1; outL |= (inL >>> (j + i)) & 1; } } for (var i = 4; i < 8; i++) { for (var j = 24; j >= 0; j -= 8) { outR <<= 1; outR |= (inR >>> (j + i)) & 1; outR <<= 1; outR |= (inL >>> (j + i)) & 1; } } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.pc1 = function pc1(inL, inR, out, off) { var outL = 0; var outR = 0; // 7, 15, 23, 31, 39, 47, 55, 63 // 6, 14, 22, 30, 39, 47, 55, 63 // 5, 13, 21, 29, 39, 47, 55, 63 // 4, 12, 20, 28 for (var i = 7; i >= 5; i--) { for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inR >> (j + i)) & 1; } for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inL >> (j + i)) & 1; } } for (var j = 0; j <= 24; j += 8) { outL <<= 1; outL |= (inR >> (j + i)) & 1; } // 1, 9, 17, 25, 33, 41, 49, 57 // 2, 10, 18, 26, 34, 42, 50, 58 // 3, 11, 19, 27, 35, 43, 51, 59 // 36, 44, 52, 60 for (var i = 1; i <= 3; i++) { for (var j = 0; j <= 24; j += 8) { outR <<= 1; outR |= (inR >> (j + i)) & 1; } for (var j = 0; j <= 24; j += 8) { outR <<= 1; outR |= (inL >> (j + i)) & 1; } } for (var j = 0; j <= 24; j += 8) { outR <<= 1; outR |= (inL >> (j + i)) & 1; } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.r28shl = function r28shl(num, shift) { return ((num << shift) & 0xfffffff) | (num >>> (28 - shift)); }; var pc2table = [ // inL => outL 14, 11, 17, 4, 27, 23, 25, 0, 13, 22, 7, 18, 5, 9, 16, 24, 2, 20, 12, 21, 1, 8, 15, 26, // inR => outR 15, 4, 25, 19, 9, 1, 26, 16, 5, 11, 23, 8, 12, 7, 17, 0, 22, 3, 10, 14, 6, 20, 27, 24 ]; exports.pc2 = function pc2(inL, inR, out, off) { var outL = 0; var outR = 0; var len = pc2table.length >>> 1; for (var i = 0; i < len; i++) { outL <<= 1; outL |= (inL >>> pc2table[i]) & 0x1; } for (var i = len; i < pc2table.length; i++) { outR <<= 1; outR |= (inR >>> pc2table[i]) & 0x1; } out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; exports.expand = function expand(r, out, off) { var outL = 0; var outR = 0; outL = ((r & 1) << 5) | (r >>> 27); for (var i = 23; i >= 15; i -= 4) { outL <<= 6; outL |= (r >>> i) & 0x3f; } for (var i = 11; i >= 3; i -= 4) { outR |= (r >>> i) & 0x3f; outR <<= 6; } outR |= ((r & 0x1f) << 1) | (r >>> 31); out[off + 0] = outL >>> 0; out[off + 1] = outR >>> 0; }; var sTable = [ 14, 0, 4, 15, 13, 7, 1, 4, 2, 14, 15, 2, 11, 13, 8, 1, 3, 10, 10, 6, 6, 12, 12, 11, 5, 9, 9, 5, 0, 3, 7, 8, 4, 15, 1, 12, 14, 8, 8, 2, 13, 4, 6, 9, 2, 1, 11, 7, 15, 5, 12, 11, 9, 3, 7, 14, 3, 10, 10, 0, 5, 6, 0, 13, 15, 3, 1, 13, 8, 4, 14, 7, 6, 15, 11, 2, 3, 8, 4, 14, 9, 12, 7, 0, 2, 1, 13, 10, 12, 6, 0, 9, 5, 11, 10, 5, 0, 13, 14, 8, 7, 10, 11, 1, 10, 3, 4, 15, 13, 4, 1, 2, 5, 11, 8, 6, 12, 7, 6, 12, 9, 0, 3, 5, 2, 14, 15, 9, 10, 13, 0, 7, 9, 0, 14, 9, 6, 3, 3, 4, 15, 6, 5, 10, 1, 2, 13, 8, 12, 5, 7, 14, 11, 12, 4, 11, 2, 15, 8, 1, 13, 1, 6, 10, 4, 13, 9, 0, 8, 6, 15, 9, 3, 8, 0, 7, 11, 4, 1, 15, 2, 14, 12, 3, 5, 11, 10, 5, 14, 2, 7, 12, 7, 13, 13, 8, 14, 11, 3, 5, 0, 6, 6, 15, 9, 0, 10, 3, 1, 4, 2, 7, 8, 2, 5, 12, 11, 1, 12, 10, 4, 14, 15, 9, 10, 3, 6, 15, 9, 0, 0, 6, 12, 10, 11, 1, 7, 13, 13, 8, 15, 9, 1, 4, 3, 5, 14, 11, 5, 12, 2, 7, 8, 2, 4, 14, 2, 14, 12, 11, 4, 2, 1, 12, 7, 4, 10, 7, 11, 13, 6, 1, 8, 5, 5, 0, 3, 15, 15, 10, 13, 3, 0, 9, 14, 8, 9, 6, 4, 11, 2, 8, 1, 12, 11, 7, 10, 1, 13, 14, 7, 2, 8, 13, 15, 6, 9, 15, 12, 0, 5, 9, 6, 10, 3, 4, 0, 5, 14, 3, 12, 10, 1, 15, 10, 4, 15, 2, 9, 7, 2, 12, 6, 9, 8, 5, 0, 6, 13, 1, 3, 13, 4, 14, 14, 0, 7, 11, 5, 3, 11, 8, 9, 4, 14, 3, 15, 2, 5, 12, 2, 9, 8, 5, 12, 15, 3, 10, 7, 11, 0, 14, 4, 1, 10, 7, 1, 6, 13, 0, 11, 8, 6, 13, 4, 13, 11, 0, 2, 11, 14, 7, 15, 4, 0, 9, 8, 1, 13, 10, 3, 14, 12, 3, 9, 5, 7, 12, 5, 2, 10, 15, 6, 8, 1, 6, 1, 6, 4, 11, 11, 13, 13, 8, 12, 1, 3, 4, 7, 10, 14, 7, 10, 9, 15, 5, 6, 0, 8, 15, 0, 14, 5, 2, 9, 3, 2, 12, 13, 1, 2, 15, 8, 13, 4, 8, 6, 10, 15, 3, 11, 7, 1, 4, 10, 12, 9, 5, 3, 6, 14, 11, 5, 0, 0, 14, 12, 9, 7, 2, 7, 2, 11, 1, 4, 14, 1, 7, 9, 4, 12, 10, 14, 8, 2, 13, 0, 15, 6, 12, 10, 9, 13, 0, 15, 3, 3, 5, 5, 6, 8, 11 ]; exports.substitute = function substitute(inL, inR) { var out = 0; for (var i = 0; i < 4; i++) { var b = (inL >>> (18 - i * 6)) & 0x3f; var sb = sTable[i * 0x40 + b]; out <<= 4; out |= sb; } for (var i = 0; i < 4; i++) { var b = (inR >>> (18 - i * 6)) & 0x3f; var sb = sTable[4 * 0x40 + i * 0x40 + b]; out <<= 4; out |= sb; } return out >>> 0; }; var permuteTable = [ 16, 25, 12, 11, 3, 20, 4, 15, 31, 17, 9, 6, 27, 14, 1, 22, 30, 24, 8, 18, 0, 5, 29, 23, 13, 19, 2, 26, 10, 21, 28, 7 ]; exports.permute = function permute(num) { var out = 0; for (var i = 0; i < permuteTable.length; i++) { out <<= 1; out |= (num >>> permuteTable[i]) & 0x1; } return out >>> 0; }; exports.padSplit = function padSplit(num, size, group) { var str = num.toString(2); while (str.length < size) str = '0' + str; var out = []; for (var i = 0; i < size; i += group) out.push(str.slice(i, i + group)); return out.join(' '); }; },{}],195:[function(require,module,exports){ (function (Buffer){ var generatePrime = require('./lib/generatePrime') var primes = require('./lib/primes.json') var DH = require('./lib/dh') function getDiffieHellman (mod) { var prime = new Buffer(primes[mod].prime, 'hex') var gen = new Buffer(primes[mod].gen, 'hex') return new DH(prime, gen) } var ENCODINGS = { 'binary': true, 'hex': true, 'base64': true } function createDiffieHellman (prime, enc, generator, genc) { if (Buffer.isBuffer(enc) || ENCODINGS[enc] === undefined) { return createDiffieHellman(prime, 'binary', enc, generator) } enc = enc || 'binary' genc = genc || 'binary' generator = generator || new Buffer([2]) if (!Buffer.isBuffer(generator)) { generator = new Buffer(generator, genc) } if (typeof prime === 'number') { return new DH(generatePrime(prime, generator), generator, true) } if (!Buffer.isBuffer(prime)) { prime = new Buffer(prime, enc) } return new DH(prime, generator, true) } exports.DiffieHellmanGroup = exports.createDiffieHellmanGroup = exports.getDiffieHellman = getDiffieHellman exports.createDiffieHellman = exports.DiffieHellman = createDiffieHellman }).call(this,require("buffer").Buffer) },{"./lib/dh":196,"./lib/generatePrime":197,"./lib/primes.json":198,"buffer":179}],196:[function(require,module,exports){ (function (Buffer){ var BN = require('bn.js'); var MillerRabin = require('miller-rabin'); var millerRabin = new MillerRabin(); var TWENTYFOUR = new BN(24); var ELEVEN = new BN(11); var TEN = new BN(10); var THREE = new BN(3); var SEVEN = new BN(7); var primes = require('./generatePrime'); var randomBytes = require('randombytes'); module.exports = DH; function setPublicKey(pub, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(pub)) { pub = new Buffer(pub, enc); } this._pub = new BN(pub); return this; } function setPrivateKey(priv, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(priv)) { priv = new Buffer(priv, enc); } this._priv = new BN(priv); return this; } var primeCache = {}; function checkPrime(prime, generator) { var gen = generator.toString('hex'); var hex = [gen, prime.toString(16)].join('_'); if (hex in primeCache) { return primeCache[hex]; } var error = 0; if (prime.isEven() || !primes.simpleSieve || !primes.fermatTest(prime) || !millerRabin.test(prime)) { //not a prime so +1 error += 1; if (gen === '02' || gen === '05') { // we'd be able to check the generator // it would fail so +8 error += 8; } else { //we wouldn't be able to test the generator // so +4 error += 4; } primeCache[hex] = error; return error; } if (!millerRabin.test(prime.shrn(1))) { //not a safe prime error += 2; } var rem; switch (gen) { case '02': if (prime.mod(TWENTYFOUR).cmp(ELEVEN)) { // unsuidable generator error += 8; } break; case '05': rem = prime.mod(TEN); if (rem.cmp(THREE) && rem.cmp(SEVEN)) { // prime mod 10 needs to equal 3 or 7 error += 8; } break; default: error += 4; } primeCache[hex] = error; return error; } function DH(prime, generator, malleable) { this.setGenerator(generator); this.__prime = new BN(prime); this._prime = BN.mont(this.__prime); this._primeLen = prime.length; this._pub = undefined; this._priv = undefined; this._primeCode = undefined; if (malleable) { this.setPublicKey = setPublicKey; this.setPrivateKey = setPrivateKey; } else { this._primeCode = 8; } } Object.defineProperty(DH.prototype, 'verifyError', { enumerable: true, get: function () { if (typeof this._primeCode !== 'number') { this._primeCode = checkPrime(this.__prime, this.__gen); } return this._primeCode; } }); DH.prototype.generateKeys = function () { if (!this._priv) { this._priv = new BN(randomBytes(this._primeLen)); } this._pub = this._gen.toRed(this._prime).redPow(this._priv).fromRed(); return this.getPublicKey(); }; DH.prototype.computeSecret = function (other) { other = new BN(other); other = other.toRed(this._prime); var secret = other.redPow(this._priv).fromRed(); var out = new Buffer(secret.toArray()); var prime = this.getPrime(); if (out.length < prime.length) { var front = new Buffer(prime.length - out.length); front.fill(0); out = Buffer.concat([front, out]); } return out; }; DH.prototype.getPublicKey = function getPublicKey(enc) { return formatReturnValue(this._pub, enc); }; DH.prototype.getPrivateKey = function getPrivateKey(enc) { return formatReturnValue(this._priv, enc); }; DH.prototype.getPrime = function (enc) { return formatReturnValue(this.__prime, enc); }; DH.prototype.getGenerator = function (enc) { return formatReturnValue(this._gen, enc); }; DH.prototype.setGenerator = function (gen, enc) { enc = enc || 'utf8'; if (!Buffer.isBuffer(gen)) { gen = new Buffer(gen, enc); } this.__gen = gen; this._gen = new BN(gen); return this; }; function formatReturnValue(bn, enc) { var buf = new Buffer(bn.toArray()); if (!enc) { return buf; } else { return buf.toString(enc); } } }).call(this,require("buffer").Buffer) },{"./generatePrime":197,"bn.js":149,"buffer":179,"miller-rabin":206,"randombytes":230}],197:[function(require,module,exports){ var randomBytes = require('randombytes'); module.exports = findPrime; findPrime.simpleSieve = simpleSieve; findPrime.fermatTest = fermatTest; var BN = require('bn.js'); var TWENTYFOUR = new BN(24); var MillerRabin = require('miller-rabin'); var millerRabin = new MillerRabin(); var ONE = new BN(1); var TWO = new BN(2); var FIVE = new BN(5); var SIXTEEN = new BN(16); var EIGHT = new BN(8); var TEN = new BN(10); var THREE = new BN(3); var SEVEN = new BN(7); var ELEVEN = new BN(11); var FOUR = new BN(4); var TWELVE = new BN(12); var primes = null; function _getPrimes() { if (primes !== null) return primes; var limit = 0x100000; var res = []; res[0] = 2; for (var i = 1, k = 3; k < limit; k += 2) { var sqrt = Math.ceil(Math.sqrt(k)); for (var j = 0; j < i && res[j] <= sqrt; j++) if (k % res[j] === 0) break; if (i !== j && res[j] <= sqrt) continue; res[i++] = k; } primes = res; return res; } function simpleSieve(p) { var primes = _getPrimes(); for (var i = 0; i < primes.length; i++) if (p.modn(primes[i]) === 0) { if (p.cmpn(primes[i]) === 0) { return true; } else { return false; } } return true; } function fermatTest(p) { var red = BN.mont(p); return TWO.toRed(red).redPow(p.subn(1)).fromRed().cmpn(1) === 0; } function findPrime(bits, gen) { if (bits < 16) { // this is what openssl does if (gen === 2 || gen === 5) { return new BN([0x8c, 0x7b]); } else { return new BN([0x8c, 0x27]); } } gen = new BN(gen); var num, n2; while (true) { num = new BN(randomBytes(Math.ceil(bits / 8))); while (num.bitLength() > bits) { num.ishrn(1); } if (num.isEven()) { num.iadd(ONE); } if (!num.testn(1)) { num.iadd(TWO); } if (!gen.cmp(TWO)) { while (num.mod(TWENTYFOUR).cmp(ELEVEN)) { num.iadd(FOUR); } } else if (!gen.cmp(FIVE)) { while (num.mod(TEN).cmp(THREE)) { num.iadd(FOUR); } } n2 = num.shrn(1); if (simpleSieve(n2) && simpleSieve(num) && fermatTest(n2) && fermatTest(num) && millerRabin.test(n2) && millerRabin.test(num)) { return num; } } } },{"bn.js":149,"miller-rabin":206,"randombytes":230}],198:[function(require,module,exports){ module.exports={ "modp1": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a63a3620ffffffffffffffff" }, "modp2": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece65381ffffffffffffffff" }, "modp5": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca237327ffffffffffffffff" }, "modp14": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aacaa68ffffffffffffffff" }, "modp15": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a93ad2caffffffffffffffff" }, "modp16": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c934063199ffffffffffffffff" }, "modp17": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dcc4024ffffffffffffffff" }, "modp18": { "gen": "02", "prime": "ffffffffffffffffc90fdaa22168c234c4c6628b80dc1cd129024e088a67cc74020bbea63b139b22514a08798e3404ddef9519b3cd3a431b302b0a6df25f14374fe1356d6d51c245e485b576625e7ec6f44c42e9a637ed6b0bff5cb6f406b7edee386bfb5a899fa5ae9f24117c4b1fe649286651ece45b3dc2007cb8a163bf0598da48361c55d39a69163fa8fd24cf5f83655d23dca3ad961c62f356208552bb9ed529077096966d670c354e4abc9804f1746c08ca18217c32905e462e36ce3be39e772c180e86039b2783a2ec07a28fb5c55df06f4c52c9de2bcbf6955817183995497cea956ae515d2261898fa051015728e5a8aaac42dad33170d04507a33a85521abdf1cba64ecfb850458dbef0a8aea71575d060c7db3970f85a6e1e4c7abf5ae8cdb0933d71e8c94e04a25619dcee3d2261ad2ee6bf12ffa06d98a0864d87602733ec86a64521f2b18177b200cbbe117577a615d6c770988c0bad946e208e24fa074e5ab3143db5bfce0fd108e4b82d120a92108011a723c12a787e6d788719a10bdba5b2699c327186af4e23c1a946834b6150bda2583e9ca2ad44ce8dbbbc2db04de8ef92e8efc141fbecaa6287c59474e6bc05d99b2964fa090c3a2233ba186515be7ed1f612970cee2d7afb81bdd762170481cd0069127d5b05aa993b4ea988d8fddc186ffb7dc90a6c08f4df435c93402849236c3fab4d27c7026c1d4dcb2602646dec9751e763dba37bdf8ff9406ad9e530ee5db382f413001aeb06a53ed9027d831179727b0865a8918da3edbebcf9b14ed44ce6cbaced4bb1bdb7f1447e6cc254b332051512bd7af426fb8f401378cd2bf5983ca01c64b92ecf032ea15d1721d03f482d7ce6e74fef6d55e702f46980c82b5a84031900b1c9e59e7c97fbec7e8f323a97a7e36cc88be0f1d45b7ff585ac54bd407b22b4154aacc8f6d7ebf48e1d814cc5ed20f8037e0a79715eef29be32806a1d58bb7c5da76f550aa3d8a1fbff0eb19ccb1a313d55cda56c9ec2ef29632387fe8d76e3c0468043e8f663f4860ee12bf2d5b0b7474d6e694f91e6dbe115974a3926f12fee5e438777cb6a932df8cd8bec4d073b931ba3bc832b68d9dd300741fa7bf8afc47ed2576f6936ba424663aab639c5ae4f5683423b4742bf1c978238f16cbe39d652de3fdb8befc848ad922222e04a4037c0713eb57a81a23f0c73473fc646cea306b4bcbc8862f8385ddfa9d4b7fa2c087e879683303ed5bdd3a062b3cf5b3a278a66d2a13f83f44f82ddf310ee074ab6a364597e899a0255dc164f31cc50846851df9ab48195ded7ea1b1d510bd7ee74d73faf36bc31ecfa268359046f4eb879f924009438b481c6cd7889a002ed5ee382bc9190da6fc026e479558e4475677e9aa9e3050e2765694dfc81f56e880b96e7160c980dd98edd3dfffffffffffffffff" } } },{}],199:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. function EventEmitter() { this._events = this._events || {}; this._maxListeners = this._maxListeners || undefined; } module.exports = EventEmitter; // Backwards-compat with node 0.10.x EventEmitter.EventEmitter = EventEmitter; EventEmitter.prototype._events = undefined; EventEmitter.prototype._maxListeners = undefined; // By default EventEmitters will print a warning if more than 10 listeners are // added to it. This is a useful default which helps finding memory leaks. EventEmitter.defaultMaxListeners = 10; // Obviously not all Emitters should be limited to 10. This function allows // that to be increased. Set to zero for unlimited. EventEmitter.prototype.setMaxListeners = function(n) { if (!isNumber(n) || n < 0 || isNaN(n)) throw TypeError('n must be a positive number'); this._maxListeners = n; return this; }; EventEmitter.prototype.emit = function(type) { var er, handler, len, args, i, listeners; if (!this._events) this._events = {}; // If there is no 'error' event listener then throw. if (type === 'error') { if (!this._events.error || (isObject(this._events.error) && !this._events.error.length)) { er = arguments[1]; if (er instanceof Error) { throw er; // Unhandled 'error' event } else { // At least give some kind of context to the user var err = new Error('Uncaught, unspecified "error" event. (' + er + ')'); err.context = er; throw err; } } } handler = this._events[type]; if (isUndefined(handler)) return false; if (isFunction(handler)) { switch (arguments.length) { // fast cases case 1: handler.call(this); break; case 2: handler.call(this, arguments[1]); break; case 3: handler.call(this, arguments[1], arguments[2]); break; // slower default: args = Array.prototype.slice.call(arguments, 1); handler.apply(this, args); } } else if (isObject(handler)) { args = Array.prototype.slice.call(arguments, 1); listeners = handler.slice(); len = listeners.length; for (i = 0; i < len; i++) listeners[i].apply(this, args); } return true; }; EventEmitter.prototype.addListener = function(type, listener) { var m; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events) this._events = {}; // To avoid recursion in the case that type === "newListener"! Before // adding it to the listeners, first emit "newListener". if (this._events.newListener) this.emit('newListener', type, isFunction(listener.listener) ? listener.listener : listener); if (!this._events[type]) // Optimize the case of one listener. Don't need the extra array object. this._events[type] = listener; else if (isObject(this._events[type])) // If we've already got an array, just append. this._events[type].push(listener); else // Adding the second element, need to change to array. this._events[type] = [this._events[type], listener]; // Check for listener leak if (isObject(this._events[type]) && !this._events[type].warned) { if (!isUndefined(this._maxListeners)) { m = this._maxListeners; } else { m = EventEmitter.defaultMaxListeners; } if (m && m > 0 && this._events[type].length > m) { this._events[type].warned = true; console.error('(node) warning: possible EventEmitter memory ' + 'leak detected. %d listeners added. ' + 'Use emitter.setMaxListeners() to increase limit.', this._events[type].length); if (typeof console.trace === 'function') { // not supported in IE 10 console.trace(); } } } return this; }; EventEmitter.prototype.on = EventEmitter.prototype.addListener; EventEmitter.prototype.once = function(type, listener) { if (!isFunction(listener)) throw TypeError('listener must be a function'); var fired = false; function g() { this.removeListener(type, g); if (!fired) { fired = true; listener.apply(this, arguments); } } g.listener = listener; this.on(type, g); return this; }; // emits a 'removeListener' event iff the listener was removed EventEmitter.prototype.removeListener = function(type, listener) { var list, position, length, i; if (!isFunction(listener)) throw TypeError('listener must be a function'); if (!this._events || !this._events[type]) return this; list = this._events[type]; length = list.length; position = -1; if (list === listener || (isFunction(list.listener) && list.listener === listener)) { delete this._events[type]; if (this._events.removeListener) this.emit('removeListener', type, listener); } else if (isObject(list)) { for (i = length; i-- > 0;) { if (list[i] === listener || (list[i].listener && list[i].listener === listener)) { position = i; break; } } if (position < 0) return this; if (list.length === 1) { list.length = 0; delete this._events[type]; } else { list.splice(position, 1); } if (this._events.removeListener) this.emit('removeListener', type, listener); } return this; }; EventEmitter.prototype.removeAllListeners = function(type) { var key, listeners; if (!this._events) return this; // not listening for removeListener, no need to emit if (!this._events.removeListener) { if (arguments.length === 0) this._events = {}; else if (this._events[type]) delete this._events[type]; return this; } // emit removeListener for all listeners on all events if (arguments.length === 0) { for (key in this._events) { if (key === 'removeListener') continue; this.removeAllListeners(key); } this.removeAllListeners('removeListener'); this._events = {}; return this; } listeners = this._events[type]; if (isFunction(listeners)) { this.removeListener(type, listeners); } else if (listeners) { // LIFO order while (listeners.length) this.removeListener(type, listeners[listeners.length - 1]); } delete this._events[type]; return this; }; EventEmitter.prototype.listeners = function(type) { var ret; if (!this._events || !this._events[type]) ret = []; else if (isFunction(this._events[type])) ret = [this._events[type]]; else ret = this._events[type].slice(); return ret; }; EventEmitter.prototype.listenerCount = function(type) { if (this._events) { var evlistener = this._events[type]; if (isFunction(evlistener)) return 1; else if (evlistener) return evlistener.length; } return 0; }; EventEmitter.listenerCount = function(emitter, type) { return emitter.listenerCount(type); }; function isFunction(arg) { return typeof arg === 'function'; } function isNumber(arg) { return typeof arg === 'number'; } function isObject(arg) { return typeof arg === 'object' && arg !== null; } function isUndefined(arg) { return arg === void 0; } },{}],200:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer var MD5 = require('md5.js') /* eslint-disable camelcase */ function EVP_BytesToKey (password, salt, keyBits, ivLen) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, 'binary') if (salt) { if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, 'binary') if (salt.length !== 8) throw new RangeError('salt should be Buffer with 8 byte length') } var keyLen = keyBits / 8 var key = Buffer.alloc(keyLen) var iv = Buffer.alloc(ivLen || 0) var tmp = Buffer.alloc(0) while (keyLen > 0 || ivLen > 0) { var hash = new MD5() hash.update(tmp) hash.update(password) if (salt) hash.update(salt) tmp = hash.digest() var used = 0 if (keyLen > 0) { var keyStart = key.length - keyLen used = Math.min(keyLen, tmp.length) tmp.copy(key, keyStart, 0, used) keyLen -= used } if (used < tmp.length && ivLen > 0) { var ivStart = iv.length - ivLen var length = Math.min(ivLen, tmp.length - used) tmp.copy(iv, ivStart, used, used + length) ivLen -= length } } tmp.fill(0) return { key: key, iv: iv } } module.exports = EVP_BytesToKey },{"md5.js":434,"safe-buffer":457}],201:[function(require,module,exports){ exports.read = function (buffer, offset, isLE, mLen, nBytes) { var e, m var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var nBits = -7 var i = isLE ? (nBytes - 1) : 0 var d = isLE ? -1 : 1 var s = buffer[offset + i] i += d e = s & ((1 << (-nBits)) - 1) s >>= (-nBits) nBits += eLen for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) {} m = e & ((1 << (-nBits)) - 1) e >>= (-nBits) nBits += mLen for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) {} if (e === 0) { e = 1 - eBias } else if (e === eMax) { return m ? NaN : ((s ? -1 : 1) * Infinity) } else { m = m + Math.pow(2, mLen) e = e - eBias } return (s ? -1 : 1) * m * Math.pow(2, e - mLen) } exports.write = function (buffer, value, offset, isLE, mLen, nBytes) { var e, m, c var eLen = nBytes * 8 - mLen - 1 var eMax = (1 << eLen) - 1 var eBias = eMax >> 1 var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0) var i = isLE ? 0 : (nBytes - 1) var d = isLE ? 1 : -1 var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0 value = Math.abs(value) if (isNaN(value) || value === Infinity) { m = isNaN(value) ? 1 : 0 e = eMax } else { e = Math.floor(Math.log(value) / Math.LN2) if (value * (c = Math.pow(2, -e)) < 1) { e-- c *= 2 } if (e + eBias >= 1) { value += rt / c } else { value += rt * Math.pow(2, 1 - eBias) } if (value * c >= 2) { e++ c /= 2 } if (e + eBias >= eMax) { m = 0 e = eMax } else if (e + eBias >= 1) { m = (value * c - 1) * Math.pow(2, mLen) e = e + eBias } else { m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen) e = 0 } } for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} e = (e << mLen) | m eLen += mLen for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} buffer[offset + i - d] |= s * 128 } },{}],202:[function(require,module,exports){ var indexOf = [].indexOf; module.exports = function(arr, obj){ if (indexOf) return arr.indexOf(obj); for (var i = 0; i < arr.length; ++i) { if (arr[i] === obj) return i; } return -1; }; },{}],203:[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 } } },{}],204:[function(require,module,exports){ /*! * Determine if an object is a Buffer * * @author Feross Aboukhadijeh * @license MIT */ // The _isBuffer check is for Safari 5-7 support, because it's missing // Object.prototype.constructor. Remove this eventually module.exports = function (obj) { return obj != null && (isBuffer(obj) || isSlowBuffer(obj) || !!obj._isBuffer) } function isBuffer (obj) { return !!obj.constructor && typeof obj.constructor.isBuffer === 'function' && obj.constructor.isBuffer(obj) } // For Node v0.10 support. Remove this eventually. function isSlowBuffer (obj) { return typeof obj.readFloatLE === 'function' && typeof obj.slice === 'function' && isBuffer(obj.slice(0, 0)) } },{}],205:[function(require,module,exports){ var toString = {}.toString; module.exports = Array.isArray || function (arr) { return toString.call(arr) == '[object Array]'; }; },{}],206:[function(require,module,exports){ var bn = require('bn.js'); var brorand = require('brorand'); function MillerRabin(rand) { this.rand = rand || new brorand.Rand(); } module.exports = MillerRabin; MillerRabin.create = function create(rand) { return new MillerRabin(rand); }; MillerRabin.prototype._randbelow = function _randbelow(n) { var len = n.bitLength(); var min_bytes = Math.ceil(len / 8); // Generage random bytes until a number less than n is found. // This ensures that 0..n-1 have an equal probability of being selected. do var a = new bn(this.rand.generate(min_bytes)); while (a.cmp(n) >= 0); return a; }; MillerRabin.prototype._randrange = function _randrange(start, stop) { // Generate a random number greater than or equal to start and less than stop. var size = stop.sub(start); return start.add(this._randbelow(size)); }; MillerRabin.prototype.test = function test(n, k, cb) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, (len / 48) | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); var prime = true; for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); if (cb) cb(a); var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return false; if (x.cmp(rn1) === 0) break; } if (i === s) return false; } return prime; }; MillerRabin.prototype.getDivisor = function getDivisor(n, k) { var len = n.bitLength(); var red = bn.mont(n); var rone = new bn(1).toRed(red); if (!k) k = Math.max(1, (len / 48) | 0); // Find d and s, (n - 1) = (2 ^ s) * d; var n1 = n.subn(1); for (var s = 0; !n1.testn(s); s++) {} var d = n.shrn(s); var rn1 = n1.toRed(red); for (; k > 0; k--) { var a = this._randrange(new bn(2), n1); var g = n.gcd(a); if (g.cmpn(1) !== 0) return g; var x = a.toRed(red).redPow(d); if (x.cmp(rone) === 0 || x.cmp(rn1) === 0) continue; for (var i = 1; i < s; i++) { x = x.redSqr(); if (x.cmp(rone) === 0) return x.fromRed().subn(1).gcd(n); if (x.cmp(rn1) === 0) break; } if (i === s) { x = x.redSqr(); return x.fromRed().subn(1).gcd(n); } } return false; }; },{"bn.js":149,"brorand":150}],207:[function(require,module,exports){ module.exports = assert; function assert(val, msg) { if (!val) throw new Error(msg || 'Assertion failed'); } assert.equal = function assertEqual(l, r, msg) { if (l != r) throw new Error(msg || ('Assertion failed: ' + l + ' != ' + r)); }; },{}],208:[function(require,module,exports){ module.exports={"2.16.840.1.101.3.4.1.1": "aes-128-ecb", "2.16.840.1.101.3.4.1.2": "aes-128-cbc", "2.16.840.1.101.3.4.1.3": "aes-128-ofb", "2.16.840.1.101.3.4.1.4": "aes-128-cfb", "2.16.840.1.101.3.4.1.21": "aes-192-ecb", "2.16.840.1.101.3.4.1.22": "aes-192-cbc", "2.16.840.1.101.3.4.1.23": "aes-192-ofb", "2.16.840.1.101.3.4.1.24": "aes-192-cfb", "2.16.840.1.101.3.4.1.41": "aes-256-ecb", "2.16.840.1.101.3.4.1.42": "aes-256-cbc", "2.16.840.1.101.3.4.1.43": "aes-256-ofb", "2.16.840.1.101.3.4.1.44": "aes-256-cfb" } },{}],209:[function(require,module,exports){ // from https://github.com/indutny/self-signed/blob/gh-pages/lib/asn1.js // Fedor, you are amazing. 'use strict' var asn1 = require('asn1.js') exports.certificate = require('./certificate') var RSAPrivateKey = asn1.define('RSAPrivateKey', function () { this.seq().obj( this.key('version').int(), this.key('modulus').int(), this.key('publicExponent').int(), this.key('privateExponent').int(), this.key('prime1').int(), this.key('prime2').int(), this.key('exponent1').int(), this.key('exponent2').int(), this.key('coefficient').int() ) }) exports.RSAPrivateKey = RSAPrivateKey var RSAPublicKey = asn1.define('RSAPublicKey', function () { this.seq().obj( this.key('modulus').int(), this.key('publicExponent').int() ) }) exports.RSAPublicKey = RSAPublicKey var PublicKey = asn1.define('SubjectPublicKeyInfo', function () { this.seq().obj( this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr() ) }) exports.PublicKey = PublicKey var AlgorithmIdentifier = asn1.define('AlgorithmIdentifier', function () { this.seq().obj( this.key('algorithm').objid(), this.key('none').null_().optional(), this.key('curve').objid().optional(), this.key('params').seq().obj( this.key('p').int(), this.key('q').int(), this.key('g').int() ).optional() ) }) var PrivateKeyInfo = asn1.define('PrivateKeyInfo', function () { this.seq().obj( this.key('version').int(), this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPrivateKey').octstr() ) }) exports.PrivateKey = PrivateKeyInfo var EncryptedPrivateKeyInfo = asn1.define('EncryptedPrivateKeyInfo', function () { this.seq().obj( this.key('algorithm').seq().obj( this.key('id').objid(), this.key('decrypt').seq().obj( this.key('kde').seq().obj( this.key('id').objid(), this.key('kdeparams').seq().obj( this.key('salt').octstr(), this.key('iters').int() ) ), this.key('cipher').seq().obj( this.key('algo').objid(), this.key('iv').octstr() ) ) ), this.key('subjectPrivateKey').octstr() ) }) exports.EncryptedPrivateKey = EncryptedPrivateKeyInfo var DSAPrivateKey = asn1.define('DSAPrivateKey', function () { this.seq().obj( this.key('version').int(), this.key('p').int(), this.key('q').int(), this.key('g').int(), this.key('pub_key').int(), this.key('priv_key').int() ) }) exports.DSAPrivateKey = DSAPrivateKey exports.DSAparam = asn1.define('DSAparam', function () { this.int() }) var ECPrivateKey = asn1.define('ECPrivateKey', function () { this.seq().obj( this.key('version').int(), this.key('privateKey').octstr(), this.key('parameters').optional().explicit(0).use(ECParameters), this.key('publicKey').optional().explicit(1).bitstr() ) }) exports.ECPrivateKey = ECPrivateKey var ECParameters = asn1.define('ECParameters', function () { this.choice({ namedCurve: this.objid() }) }) exports.signature = asn1.define('signature', function () { this.seq().obj( this.key('r').int(), this.key('s').int() ) }) },{"./certificate":210,"asn1.js":133}],210:[function(require,module,exports){ // from https://github.com/Rantanen/node-dtls/blob/25a7dc861bda38cfeac93a723500eea4f0ac2e86/Certificate.js // thanks to @Rantanen 'use strict' var asn = require('asn1.js') var Time = asn.define('Time', function () { this.choice({ utcTime: this.utctime(), generalTime: this.gentime() }) }) var AttributeTypeValue = asn.define('AttributeTypeValue', function () { this.seq().obj( this.key('type').objid(), this.key('value').any() ) }) var AlgorithmIdentifier = asn.define('AlgorithmIdentifier', function () { this.seq().obj( this.key('algorithm').objid(), this.key('parameters').optional() ) }) var SubjectPublicKeyInfo = asn.define('SubjectPublicKeyInfo', function () { this.seq().obj( this.key('algorithm').use(AlgorithmIdentifier), this.key('subjectPublicKey').bitstr() ) }) var RelativeDistinguishedName = asn.define('RelativeDistinguishedName', function () { this.setof(AttributeTypeValue) }) var RDNSequence = asn.define('RDNSequence', function () { this.seqof(RelativeDistinguishedName) }) var Name = asn.define('Name', function () { this.choice({ rdnSequence: this.use(RDNSequence) }) }) var Validity = asn.define('Validity', function () { this.seq().obj( this.key('notBefore').use(Time), this.key('notAfter').use(Time) ) }) var Extension = asn.define('Extension', function () { this.seq().obj( this.key('extnID').objid(), this.key('critical').bool().def(false), this.key('extnValue').octstr() ) }) var TBSCertificate = asn.define('TBSCertificate', function () { this.seq().obj( this.key('version').explicit(0).int(), this.key('serialNumber').int(), this.key('signature').use(AlgorithmIdentifier), this.key('issuer').use(Name), this.key('validity').use(Validity), this.key('subject').use(Name), this.key('subjectPublicKeyInfo').use(SubjectPublicKeyInfo), this.key('issuerUniqueID').implicit(1).bitstr().optional(), this.key('subjectUniqueID').implicit(2).bitstr().optional(), this.key('extensions').explicit(3).seqof(Extension).optional() ) }) var X509Certificate = asn.define('X509Certificate', function () { this.seq().obj( this.key('tbsCertificate').use(TBSCertificate), this.key('signatureAlgorithm').use(AlgorithmIdentifier), this.key('signatureValue').bitstr() ) }) module.exports = X509Certificate },{"asn1.js":133}],211:[function(require,module,exports){ (function (Buffer){ // adapted from https://github.com/apatil/pemstrip var findProc = /Proc-Type: 4,ENCRYPTED\n\r?DEK-Info: AES-((?:128)|(?:192)|(?:256))-CBC,([0-9A-H]+)\n\r?\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?/m var startRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n/m var fullRegex = /^-----BEGIN ((?:.* KEY)|CERTIFICATE)-----\n\r?([0-9A-z\n\r\+\/\=]+)\n\r?-----END \1-----$/m var evp = require('evp_bytestokey') var ciphers = require('browserify-aes') module.exports = function (okey, password) { var key = okey.toString() var match = key.match(findProc) var decrypted if (!match) { var match2 = key.match(fullRegex) decrypted = new Buffer(match2[2].replace(/\r?\n/g, ''), 'base64') } else { var suite = 'aes' + match[1] var iv = new Buffer(match[2], 'hex') var cipherText = new Buffer(match[3].replace(/\r?\n/g, ''), 'base64') var cipherKey = evp(password, iv.slice(0, 8), parseInt(match[1], 10)).key var out = [] var cipher = ciphers.createDecipheriv(suite, cipherKey, iv) out.push(cipher.update(cipherText)) out.push(cipher.final()) decrypted = Buffer.concat(out) } var tag = key.match(startRegex)[1] return { tag: tag, data: decrypted } } }).call(this,require("buffer").Buffer) },{"browserify-aes":154,"buffer":179,"evp_bytestokey":200}],212:[function(require,module,exports){ (function (Buffer){ var asn1 = require('./asn1') var aesid = require('./aesid.json') var fixProc = require('./fixProc') var ciphers = require('browserify-aes') var compat = require('pbkdf2') module.exports = parseKeys function parseKeys (buffer) { var password if (typeof buffer === 'object' && !Buffer.isBuffer(buffer)) { password = buffer.passphrase buffer = buffer.key } if (typeof buffer === 'string') { buffer = new Buffer(buffer) } var stripped = fixProc(buffer, password) var type = stripped.tag var data = stripped.data var subtype, ndata switch (type) { case 'CERTIFICATE': ndata = asn1.certificate.decode(data, 'der').tbsCertificate.subjectPublicKeyInfo // falls through case 'PUBLIC KEY': if (!ndata) { ndata = asn1.PublicKey.decode(data, 'der') } subtype = ndata.algorithm.algorithm.join('.') switch (subtype) { case '1.2.840.113549.1.1.1': return asn1.RSAPublicKey.decode(ndata.subjectPublicKey.data, 'der') case '1.2.840.10045.2.1': ndata.subjectPrivateKey = ndata.subjectPublicKey return { type: 'ec', data: ndata } case '1.2.840.10040.4.1': ndata.algorithm.params.pub_key = asn1.DSAparam.decode(ndata.subjectPublicKey.data, 'der') return { type: 'dsa', data: ndata.algorithm.params } default: throw new Error('unknown key id ' + subtype) } throw new Error('unknown key type ' + type) case 'ENCRYPTED PRIVATE KEY': data = asn1.EncryptedPrivateKey.decode(data, 'der') data = decrypt(data, password) // falls through case 'PRIVATE KEY': ndata = asn1.PrivateKey.decode(data, 'der') subtype = ndata.algorithm.algorithm.join('.') switch (subtype) { case '1.2.840.113549.1.1.1': return asn1.RSAPrivateKey.decode(ndata.subjectPrivateKey, 'der') case '1.2.840.10045.2.1': return { curve: ndata.algorithm.curve, privateKey: asn1.ECPrivateKey.decode(ndata.subjectPrivateKey, 'der').privateKey } case '1.2.840.10040.4.1': ndata.algorithm.params.priv_key = asn1.DSAparam.decode(ndata.subjectPrivateKey, 'der') return { type: 'dsa', params: ndata.algorithm.params } default: throw new Error('unknown key id ' + subtype) } throw new Error('unknown key type ' + type) case 'RSA PUBLIC KEY': return asn1.RSAPublicKey.decode(data, 'der') case 'RSA PRIVATE KEY': return asn1.RSAPrivateKey.decode(data, 'der') case 'DSA PRIVATE KEY': return { type: 'dsa', params: asn1.DSAPrivateKey.decode(data, 'der') } case 'EC PRIVATE KEY': data = asn1.ECPrivateKey.decode(data, 'der') return { curve: data.parameters.value, privateKey: data.privateKey } default: throw new Error('unknown key type ' + type) } } parseKeys.signature = asn1.signature function decrypt (data, password) { var salt = data.algorithm.decrypt.kde.kdeparams.salt var iters = parseInt(data.algorithm.decrypt.kde.kdeparams.iters.toString(), 10) var algo = aesid[data.algorithm.decrypt.cipher.algo.join('.')] var iv = data.algorithm.decrypt.cipher.iv var cipherText = data.subjectPrivateKey var keylen = parseInt(algo.split('-')[1], 10) / 8 var key = compat.pbkdf2Sync(password, salt, iters, keylen) var cipher = ciphers.createDecipheriv(algo, key, iv) var out = [] out.push(cipher.update(cipherText)) out.push(cipher.final()) return Buffer.concat(out) } }).call(this,require("buffer").Buffer) },{"./aesid.json":208,"./asn1":209,"./fixProc":211,"browserify-aes":154,"buffer":179,"pbkdf2":213}],213:[function(require,module,exports){ exports.pbkdf2 = require('./lib/async') exports.pbkdf2Sync = require('./lib/sync') },{"./lib/async":214,"./lib/sync":217}],214:[function(require,module,exports){ (function (process,global){ var checkParameters = require('./precondition') var defaultEncoding = require('./default-encoding') var sync = require('./sync') var Buffer = require('safe-buffer').Buffer var ZERO_BUF var subtle = global.crypto && global.crypto.subtle var toBrowser = { 'sha': 'SHA-1', 'sha-1': 'SHA-1', 'sha1': 'SHA-1', 'sha256': 'SHA-256', 'sha-256': 'SHA-256', 'sha384': 'SHA-384', 'sha-384': 'SHA-384', 'sha-512': 'SHA-512', 'sha512': 'SHA-512' } var checks = [] function checkNative (algo) { if (global.process && !global.process.browser) { return Promise.resolve(false) } if (!subtle || !subtle.importKey || !subtle.deriveBits) { return Promise.resolve(false) } if (checks[algo] !== undefined) { return checks[algo] } ZERO_BUF = ZERO_BUF || Buffer.alloc(8) var prom = browserPbkdf2(ZERO_BUF, ZERO_BUF, 10, 128, algo) .then(function () { return true }).catch(function () { return false }) checks[algo] = prom return prom } function browserPbkdf2 (password, salt, iterations, length, algo) { return subtle.importKey( 'raw', password, {name: 'PBKDF2'}, false, ['deriveBits'] ).then(function (key) { return subtle.deriveBits({ name: 'PBKDF2', salt: salt, iterations: iterations, hash: { name: algo } }, key, length << 3) }).then(function (res) { return Buffer.from(res) }) } function resolvePromise (promise, callback) { promise.then(function (out) { process.nextTick(function () { callback(null, out) }) }, function (e) { process.nextTick(function () { callback(e) }) }) } module.exports = function (password, salt, iterations, keylen, digest, callback) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) checkParameters(iterations, keylen) if (typeof digest === 'function') { callback = digest digest = undefined } if (typeof callback !== 'function') throw new Error('No callback provided to pbkdf2') digest = digest || 'sha1' var algo = toBrowser[digest.toLowerCase()] if (!algo || typeof global.Promise !== 'function') { return process.nextTick(function () { var out try { out = sync(password, salt, iterations, keylen, digest) } catch (e) { return callback(e) } callback(null, out) }) } resolvePromise(checkNative(algo).then(function (resp) { if (resp) { return browserPbkdf2(password, salt, iterations, keylen, algo) } else { return sync(password, salt, iterations, keylen, digest) } }), callback) } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./default-encoding":215,"./precondition":216,"./sync":217,"_process":219,"safe-buffer":457}],215:[function(require,module,exports){ (function (process){ var defaultEncoding /* istanbul ignore next */ if (process.browser) { defaultEncoding = 'utf-8' } else { var pVersionMajor = parseInt(process.version.split('.')[0].slice(1), 10) defaultEncoding = pVersionMajor >= 6 ? 'utf-8' : 'binary' } module.exports = defaultEncoding }).call(this,require('_process')) },{"_process":219}],216:[function(require,module,exports){ var MAX_ALLOC = Math.pow(2, 30) - 1 // default in iojs module.exports = function (iterations, keylen) { if (typeof iterations !== 'number') { throw new TypeError('Iterations not a number') } if (iterations < 0) { throw new TypeError('Bad iterations') } if (typeof keylen !== 'number') { throw new TypeError('Key length not a number') } if (keylen < 0 || keylen > MAX_ALLOC || keylen !== keylen) { /* eslint no-self-compare: 0 */ throw new TypeError('Bad key length') } } },{}],217:[function(require,module,exports){ var md5 = require('create-hash/md5') var rmd160 = require('ripemd160') var sha = require('sha.js') var checkParameters = require('./precondition') var defaultEncoding = require('./default-encoding') var Buffer = require('safe-buffer').Buffer var ZEROS = Buffer.alloc(128) var sizes = { md5: 16, sha1: 20, sha224: 28, sha256: 32, sha384: 48, sha512: 64, rmd160: 20, ripemd160: 20 } function Hmac (alg, key, saltLen) { var hash = getDigest(alg) var blocksize = (alg === 'sha512' || alg === 'sha384') ? 128 : 64 if (key.length > blocksize) { key = hash(key) } else if (key.length < blocksize) { key = Buffer.concat([key, ZEROS], blocksize) } var ipad = Buffer.allocUnsafe(blocksize + sizes[alg]) var opad = Buffer.allocUnsafe(blocksize + sizes[alg]) for (var i = 0; i < blocksize; i++) { ipad[i] = key[i] ^ 0x36 opad[i] = key[i] ^ 0x5C } var ipad1 = Buffer.allocUnsafe(blocksize + saltLen + 4) ipad.copy(ipad1, 0, 0, blocksize) this.ipad1 = ipad1 this.ipad2 = ipad this.opad = opad this.alg = alg this.blocksize = blocksize this.hash = hash this.size = sizes[alg] } Hmac.prototype.run = function (data, ipad) { data.copy(ipad, this.blocksize) var h = this.hash(ipad) h.copy(this.opad, this.blocksize) return this.hash(this.opad) } function getDigest (alg) { function shaFunc (data) { return sha(alg).update(data).digest() } if (alg === 'rmd160' || alg === 'ripemd160') return rmd160 if (alg === 'md5') return md5 return shaFunc } function pbkdf2 (password, salt, iterations, keylen, digest) { if (!Buffer.isBuffer(password)) password = Buffer.from(password, defaultEncoding) if (!Buffer.isBuffer(salt)) salt = Buffer.from(salt, defaultEncoding) checkParameters(iterations, keylen) digest = digest || 'sha1' var hmac = new Hmac(digest, password, salt.length) var DK = Buffer.allocUnsafe(keylen) var block1 = Buffer.allocUnsafe(salt.length + 4) salt.copy(block1, 0, 0, salt.length) var destPos = 0 var hLen = sizes[digest] var l = Math.ceil(keylen / hLen) for (var i = 1; i <= l; i++) { block1.writeUInt32BE(i, salt.length) var T = hmac.run(block1, hmac.ipad1) var U = T for (var j = 1; j < iterations; j++) { U = hmac.run(U, hmac.ipad2) for (var k = 0; k < hLen; k++) T[k] ^= U[k] } T.copy(DK, destPos) destPos += hLen } return DK } module.exports = pbkdf2 },{"./default-encoding":215,"./precondition":216,"create-hash/md5":185,"ripemd160":245,"safe-buffer":457,"sha.js":247}],218:[function(require,module,exports){ (function (process){ 'use strict'; if (!process.version || process.version.indexOf('v0.') === 0 || process.version.indexOf('v1.') === 0 && process.version.indexOf('v1.8.') !== 0) { module.exports = nextTick; } else { module.exports = process.nextTick; } function nextTick(fn, arg1, arg2, arg3) { if (typeof fn !== 'function') { throw new TypeError('"callback" argument must be a function'); } var len = arguments.length; var args, i; switch (len) { case 0: case 1: return process.nextTick(fn); case 2: return process.nextTick(function afterTickOne() { fn.call(null, arg1); }); case 3: return process.nextTick(function afterTickTwo() { fn.call(null, arg1, arg2); }); case 4: return process.nextTick(function afterTickThree() { fn.call(null, arg1, arg2, arg3); }); default: args = new Array(len - 1); i = 0; while (i < args.length) { args[i++] = arguments[i]; } return process.nextTick(function afterTick() { fn.apply(null, args); }); } } }).call(this,require('_process')) },{"_process":219}],219:[function(require,module,exports){ // shim for using process in browser var process = module.exports = {}; // cached from whatever global is present so that test runners that stub it // don't break things. But we need to wrap it in a try catch in case it is // wrapped in strict mode code which doesn't define any globals. It's inside a // function because try/catches deoptimize in certain engines. var cachedSetTimeout; var cachedClearTimeout; function defaultSetTimout() { throw new Error('setTimeout has not been defined'); } function defaultClearTimeout () { throw new Error('clearTimeout has not been defined'); } (function () { try { if (typeof setTimeout === 'function') { cachedSetTimeout = setTimeout; } else { cachedSetTimeout = defaultSetTimout; } } catch (e) { cachedSetTimeout = defaultSetTimout; } try { if (typeof clearTimeout === 'function') { cachedClearTimeout = clearTimeout; } else { cachedClearTimeout = defaultClearTimeout; } } catch (e) { cachedClearTimeout = defaultClearTimeout; } } ()) function runTimeout(fun) { if (cachedSetTimeout === setTimeout) { //normal enviroments in sane situations return setTimeout(fun, 0); } // if setTimeout wasn't available but was latter defined if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { cachedSetTimeout = setTimeout; return setTimeout(fun, 0); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedSetTimeout(fun, 0); } catch(e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedSetTimeout.call(null, fun, 0); } catch(e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error return cachedSetTimeout.call(this, fun, 0); } } } function runClearTimeout(marker) { if (cachedClearTimeout === clearTimeout) { //normal enviroments in sane situations return clearTimeout(marker); } // if clearTimeout wasn't available but was latter defined if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { cachedClearTimeout = clearTimeout; return clearTimeout(marker); } try { // when when somebody has screwed with setTimeout but no I.E. maddness return cachedClearTimeout(marker); } catch (e){ try { // When we are in I.E. but the script has been evaled so I.E. doesn't trust the global object when called normally return cachedClearTimeout.call(null, marker); } catch (e){ // same as above but when it's a version of I.E. that must have the global object for 'this', hopfully our context correct otherwise it will throw a global error. // Some versions of I.E. have different rules for clearTimeout vs setTimeout return cachedClearTimeout.call(this, marker); } } } var queue = []; var draining = false; var currentQueue; var queueIndex = -1; function cleanUpNextTick() { if (!draining || !currentQueue) { return; } draining = false; if (currentQueue.length) { queue = currentQueue.concat(queue); } else { queueIndex = -1; } if (queue.length) { drainQueue(); } } function drainQueue() { if (draining) { return; } var timeout = runTimeout(cleanUpNextTick); draining = true; var len = queue.length; while(len) { currentQueue = queue; queue = []; while (++queueIndex < len) { if (currentQueue) { currentQueue[queueIndex].run(); } } queueIndex = -1; len = queue.length; } currentQueue = null; draining = false; runClearTimeout(timeout); } process.nextTick = function (fun) { var args = new Array(arguments.length - 1); if (arguments.length > 1) { for (var i = 1; i < arguments.length; i++) { args[i - 1] = arguments[i]; } } queue.push(new Item(fun, args)); if (queue.length === 1 && !draining) { runTimeout(drainQueue); } }; // v8 likes predictible objects function Item(fun, array) { this.fun = fun; this.array = array; } Item.prototype.run = function () { this.fun.apply(null, this.array); }; process.title = 'browser'; process.browser = true; process.env = {}; process.argv = []; process.version = ''; // empty string to avoid regexp issues process.versions = {}; function noop() {} process.on = noop; process.addListener = noop; process.once = noop; process.off = noop; process.removeListener = noop; process.removeAllListeners = noop; process.emit = noop; process.prependListener = noop; process.prependOnceListener = noop; process.listeners = function (name) { return [] } process.binding = function (name) { throw new Error('process.binding is not supported'); }; process.cwd = function () { return '/' }; process.chdir = function (dir) { throw new Error('process.chdir is not supported'); }; process.umask = function() { return 0; }; },{}],220:[function(require,module,exports){ exports.publicEncrypt = require('./publicEncrypt'); exports.privateDecrypt = require('./privateDecrypt'); exports.privateEncrypt = function privateEncrypt(key, buf) { return exports.publicEncrypt(key, buf, true); }; exports.publicDecrypt = function publicDecrypt(key, buf) { return exports.privateDecrypt(key, buf, true); }; },{"./privateDecrypt":222,"./publicEncrypt":223}],221:[function(require,module,exports){ (function (Buffer){ var createHash = require('create-hash'); module.exports = function (seed, len) { var t = new Buffer(''); var i = 0, c; while (t.length < len) { c = i2ops(i++); t = Buffer.concat([t, createHash('sha1').update(seed).update(c).digest()]); } return t.slice(0, len); }; function i2ops(c) { var out = new Buffer(4); out.writeUInt32BE(c,0); return out; } }).call(this,require("buffer").Buffer) },{"buffer":179,"create-hash":183}],222:[function(require,module,exports){ (function (Buffer){ var parseKeys = require('parse-asn1'); var mgf = require('./mgf'); var xor = require('./xor'); var bn = require('bn.js'); var crt = require('browserify-rsa'); var createHash = require('create-hash'); var withPublic = require('./withPublic'); module.exports = function privateDecrypt(private_key, enc, reverse) { var padding; if (private_key.padding) { padding = private_key.padding; } else if (reverse) { padding = 1; } else { padding = 4; } var key = parseKeys(private_key); var k = key.modulus.byteLength(); if (enc.length > k || new bn(enc).cmp(key.modulus) >= 0) { throw new Error('decryption error'); } var msg; if (reverse) { msg = withPublic(new bn(enc), key); } else { msg = crt(enc, key); } var zBuffer = new Buffer(k - msg.length); zBuffer.fill(0); msg = Buffer.concat([zBuffer, msg], k); if (padding === 4) { return oaep(key, msg); } else if (padding === 1) { return pkcs1(key, msg, reverse); } else if (padding === 3) { return msg; } else { throw new Error('unknown padding'); } }; function oaep(key, msg){ var n = key.modulus; var k = key.modulus.byteLength(); var mLen = msg.length; var iHash = createHash('sha1').update(new Buffer('')).digest(); var hLen = iHash.length; var hLen2 = 2 * hLen; if (msg[0] !== 0) { throw new Error('decryption error'); } var maskedSeed = msg.slice(1, hLen + 1); var maskedDb = msg.slice(hLen + 1); var seed = xor(maskedSeed, mgf(maskedDb, hLen)); var db = xor(maskedDb, mgf(seed, k - hLen - 1)); if (compare(iHash, db.slice(0, hLen))) { throw new Error('decryption error'); } var i = hLen; while (db[i] === 0) { i++; } if (db[i++] !== 1) { throw new Error('decryption error'); } return db.slice(i); } function pkcs1(key, msg, reverse){ var p1 = msg.slice(0, 2); var i = 2; var status = 0; while (msg[i++] !== 0) { if (i >= msg.length) { status++; break; } } var ps = msg.slice(2, i - 1); var p2 = msg.slice(i - 1, i); if ((p1.toString('hex') !== '0002' && !reverse) || (p1.toString('hex') !== '0001' && reverse)){ status++; } if (ps.length < 8) { status++; } if (status) { throw new Error('decryption error'); } return msg.slice(i); } function compare(a, b){ a = new Buffer(a); b = new Buffer(b); var dif = 0; var len = a.length; if (a.length !== b.length) { dif++; len = Math.min(a.length, b.length); } var i = -1; while (++i < len) { dif += (a[i] ^ b[i]); } return dif; } }).call(this,require("buffer").Buffer) },{"./mgf":221,"./withPublic":224,"./xor":225,"bn.js":149,"browserify-rsa":171,"buffer":179,"create-hash":183,"parse-asn1":212}],223:[function(require,module,exports){ (function (Buffer){ var parseKeys = require('parse-asn1'); var randomBytes = require('randombytes'); var createHash = require('create-hash'); var mgf = require('./mgf'); var xor = require('./xor'); var bn = require('bn.js'); var withPublic = require('./withPublic'); var crt = require('browserify-rsa'); var constants = { RSA_PKCS1_OAEP_PADDING: 4, RSA_PKCS1_PADDIN: 1, RSA_NO_PADDING: 3 }; module.exports = function publicEncrypt(public_key, msg, reverse) { var padding; if (public_key.padding) { padding = public_key.padding; } else if (reverse) { padding = 1; } else { padding = 4; } var key = parseKeys(public_key); var paddedMsg; if (padding === 4) { paddedMsg = oaep(key, msg); } else if (padding === 1) { paddedMsg = pkcs1(key, msg, reverse); } else if (padding === 3) { paddedMsg = new bn(msg); if (paddedMsg.cmp(key.modulus) >= 0) { throw new Error('data too long for modulus'); } } else { throw new Error('unknown padding'); } if (reverse) { return crt(paddedMsg, key); } else { return withPublic(paddedMsg, key); } }; function oaep(key, msg){ var k = key.modulus.byteLength(); var mLen = msg.length; var iHash = createHash('sha1').update(new Buffer('')).digest(); var hLen = iHash.length; var hLen2 = 2 * hLen; if (mLen > k - hLen2 - 2) { throw new Error('message too long'); } var ps = new Buffer(k - mLen - hLen2 - 2); ps.fill(0); var dblen = k - hLen - 1; var seed = randomBytes(hLen); var maskedDb = xor(Buffer.concat([iHash, ps, new Buffer([1]), msg], dblen), mgf(seed, dblen)); var maskedSeed = xor(seed, mgf(maskedDb, hLen)); return new bn(Buffer.concat([new Buffer([0]), maskedSeed, maskedDb], k)); } function pkcs1(key, msg, reverse){ var mLen = msg.length; var k = key.modulus.byteLength(); if (mLen > k - 11) { throw new Error('message too long'); } var ps; if (reverse) { ps = new Buffer(k - mLen - 3); ps.fill(0xff); } else { ps = nonZero(k - mLen - 3); } return new bn(Buffer.concat([new Buffer([0, reverse?1:2]), ps, new Buffer([0]), msg], k)); } function nonZero(len, crypto) { var out = new Buffer(len); var i = 0; var cache = randomBytes(len*2); var cur = 0; var num; while (i < len) { if (cur === cache.length) { cache = randomBytes(len*2); cur = 0; } num = cache[cur++]; if (num) { out[i++] = num; } } return out; } }).call(this,require("buffer").Buffer) },{"./mgf":221,"./withPublic":224,"./xor":225,"bn.js":149,"browserify-rsa":171,"buffer":179,"create-hash":183,"parse-asn1":212,"randombytes":230}],224:[function(require,module,exports){ (function (Buffer){ var bn = require('bn.js'); function withPublic(paddedMsg, key) { return new Buffer(paddedMsg .toRed(bn.mont(key.modulus)) .redPow(new bn(key.publicExponent)) .fromRed() .toArray()); } module.exports = withPublic; }).call(this,require("buffer").Buffer) },{"bn.js":149,"buffer":179}],225:[function(require,module,exports){ module.exports = function xor(a, b) { var len = a.length; var i = -1; while (++i < len) { a[i] ^= b[i]; } return a }; },{}],226:[function(require,module,exports){ (function (global){ /*! https://mths.be/punycode v1.4.1 by @mathias */ ;(function(root) { /** Detect free variables */ var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; var freeModule = typeof module == 'object' && module && !module.nodeType && module; var freeGlobal = typeof global == 'object' && global; if ( freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal || freeGlobal.self === freeGlobal ) { root = freeGlobal; } /** * The `punycode` object. * @name punycode * @type Object */ var punycode, /** Highest positive signed 32-bit float value */ maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 /** Bootstring parameters */ base = 36, tMin = 1, tMax = 26, skew = 38, damp = 700, initialBias = 72, initialN = 128, // 0x80 delimiter = '-', // '\x2D' /** Regular expressions */ regexPunycode = /^xn--/, regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators /** Error messages */ errors = { 'overflow': 'Overflow: input needs wider integers to process', 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', 'invalid-input': 'Invalid input' }, /** Convenience shortcuts */ baseMinusTMin = base - tMin, floor = Math.floor, stringFromCharCode = String.fromCharCode, /** Temporary variable */ key; /*--------------------------------------------------------------------------*/ /** * A generic error utility function. * @private * @param {String} type The error type. * @returns {Error} Throws a `RangeError` with the applicable error message. */ function error(type) { throw new RangeError(errors[type]); } /** * A generic `Array#map` utility function. * @private * @param {Array} array The array to iterate over. * @param {Function} callback The function that gets called for every array * item. * @returns {Array} A new array of values returned by the callback function. */ function map(array, fn) { var length = array.length; var result = []; while (length--) { result[length] = fn(array[length]); } return result; } /** * A simple `Array#map`-like wrapper to work with domain name strings or email * addresses. * @private * @param {String} domain The domain name or email address. * @param {Function} callback The function that gets called for every * character. * @returns {Array} A new string of characters returned by the callback * function. */ function mapDomain(string, fn) { var parts = string.split('@'); var result = ''; if (parts.length > 1) { // In email addresses, only the domain name should be punycoded. Leave // the local part (i.e. everything up to `@`) intact. result = parts[0] + '@'; string = parts[1]; } // Avoid `split(regex)` for IE8 compatibility. See #17. string = string.replace(regexSeparators, '\x2E'); var labels = string.split('.'); var encoded = map(labels, fn).join('.'); return result + encoded; } /** * Creates an array containing the numeric code points of each Unicode * character in the string. While JavaScript uses UCS-2 internally, * this function will convert a pair of surrogate halves (each of which * UCS-2 exposes as separate characters) into a single code point, * matching UTF-16. * @see `punycode.ucs2.encode` * @see * @memberOf punycode.ucs2 * @name decode * @param {String} string The Unicode input string (UCS-2). * @returns {Array} The new array of code points. */ function ucs2decode(string) { var output = [], counter = 0, length = string.length, value, extra; while (counter < length) { value = string.charCodeAt(counter++); if (value >= 0xD800 && value <= 0xDBFF && counter < length) { // high surrogate, and there is a next character extra = string.charCodeAt(counter++); if ((extra & 0xFC00) == 0xDC00) { // low surrogate output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); } else { // unmatched surrogate; only append this code unit, in case the next // code unit is the high surrogate of a surrogate pair output.push(value); counter--; } } else { output.push(value); } } return output; } /** * Creates a string based on an array of numeric code points. * @see `punycode.ucs2.decode` * @memberOf punycode.ucs2 * @name encode * @param {Array} codePoints The array of numeric code points. * @returns {String} The new Unicode string (UCS-2). */ function ucs2encode(array) { return map(array, function(value) { var output = ''; if (value > 0xFFFF) { value -= 0x10000; output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); value = 0xDC00 | value & 0x3FF; } output += stringFromCharCode(value); return output; }).join(''); } /** * Converts a basic code point into a digit/integer. * @see `digitToBasic()` * @private * @param {Number} codePoint The basic numeric code point value. * @returns {Number} The numeric value of a basic code point (for use in * representing integers) in the range `0` to `base - 1`, or `base` if * the code point does not represent a value. */ function basicToDigit(codePoint) { if (codePoint - 48 < 10) { return codePoint - 22; } if (codePoint - 65 < 26) { return codePoint - 65; } if (codePoint - 97 < 26) { return codePoint - 97; } return base; } /** * Converts a digit/integer into a basic code point. * @see `basicToDigit()` * @private * @param {Number} digit The numeric value of a basic code point. * @returns {Number} The basic code point whose value (when used for * representing integers) is `digit`, which needs to be in the range * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is * used; else, the lowercase form is used. The behavior is undefined * if `flag` is non-zero and `digit` has no uppercase form. */ function digitToBasic(digit, flag) { // 0..25 map to ASCII a..z or A..Z // 26..35 map to ASCII 0..9 return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); } /** * Bias adaptation function as per section 3.4 of RFC 3492. * https://tools.ietf.org/html/rfc3492#section-3.4 * @private */ function adapt(delta, numPoints, firstTime) { var k = 0; delta = firstTime ? floor(delta / damp) : delta >> 1; delta += floor(delta / numPoints); for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { delta = floor(delta / baseMinusTMin); } return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); } /** * Converts a Punycode string of ASCII-only symbols to a string of Unicode * symbols. * @memberOf punycode * @param {String} input The Punycode string of ASCII-only symbols. * @returns {String} The resulting string of Unicode symbols. */ function decode(input) { // Don't use UCS-2 var output = [], inputLength = input.length, out, i = 0, n = initialN, bias = initialBias, basic, j, index, oldi, w, k, digit, t, /** Cached calculation results */ baseMinusT; // Handle the basic code points: let `basic` be the number of input code // points before the last delimiter, or `0` if there is none, then copy // the first basic code points to the output. basic = input.lastIndexOf(delimiter); if (basic < 0) { basic = 0; } for (j = 0; j < basic; ++j) { // if it's not a basic code point if (input.charCodeAt(j) >= 0x80) { error('not-basic'); } output.push(input.charCodeAt(j)); } // Main decoding loop: start just after the last delimiter if any basic code // points were copied; start at the beginning otherwise. for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { // `index` is the index of the next character to be consumed. // Decode a generalized variable-length integer into `delta`, // which gets added to `i`. The overflow checking is easier // if we increase `i` as we go, then subtract off its starting // value at the end to obtain `delta`. for (oldi = i, w = 1, k = base; /* no condition */; k += base) { if (index >= inputLength) { error('invalid-input'); } digit = basicToDigit(input.charCodeAt(index++)); if (digit >= base || digit > floor((maxInt - i) / w)) { error('overflow'); } i += digit * w; t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (digit < t) { break; } baseMinusT = base - t; if (w > floor(maxInt / baseMinusT)) { error('overflow'); } w *= baseMinusT; } out = output.length + 1; bias = adapt(i - oldi, out, oldi == 0); // `i` was supposed to wrap around from `out` to `0`, // incrementing `n` each time, so we'll fix that now: if (floor(i / out) > maxInt - n) { error('overflow'); } n += floor(i / out); i %= out; // Insert `n` at position `i` of the output output.splice(i++, 0, n); } return ucs2encode(output); } /** * Converts a string of Unicode symbols (e.g. a domain name label) to a * Punycode string of ASCII-only symbols. * @memberOf punycode * @param {String} input The string of Unicode symbols. * @returns {String} The resulting Punycode string of ASCII-only symbols. */ function encode(input) { var n, delta, handledCPCount, basicLength, bias, j, m, q, k, t, currentValue, output = [], /** `inputLength` will hold the number of code points in `input`. */ inputLength, /** Cached calculation results */ handledCPCountPlusOne, baseMinusT, qMinusT; // Convert the input in UCS-2 to Unicode input = ucs2decode(input); // Cache the length inputLength = input.length; // Initialize the state n = initialN; delta = 0; bias = initialBias; // Handle the basic code points for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < 0x80) { output.push(stringFromCharCode(currentValue)); } } handledCPCount = basicLength = output.length; // `handledCPCount` is the number of code points that have been handled; // `basicLength` is the number of basic code points. // Finish the basic string - if it is not empty - with a delimiter if (basicLength) { output.push(delimiter); } // Main encoding loop: while (handledCPCount < inputLength) { // All non-basic code points < n have been handled already. Find the next // larger one: for (m = maxInt, j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue >= n && currentValue < m) { m = currentValue; } } // Increase `delta` enough to advance the decoder's state to , // but guard against overflow handledCPCountPlusOne = handledCPCount + 1; if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { error('overflow'); } delta += (m - n) * handledCPCountPlusOne; n = m; for (j = 0; j < inputLength; ++j) { currentValue = input[j]; if (currentValue < n && ++delta > maxInt) { error('overflow'); } if (currentValue == n) { // Represent delta as a generalized variable-length integer for (q = delta, k = base; /* no condition */; k += base) { t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); if (q < t) { break; } qMinusT = q - t; baseMinusT = base - t; output.push( stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) ); q = floor(qMinusT / baseMinusT); } output.push(stringFromCharCode(digitToBasic(q, 0))); bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); delta = 0; ++handledCPCount; } } ++delta; ++n; } return output.join(''); } /** * Converts a Punycode string representing a domain name or an email address * to Unicode. Only the Punycoded parts of the input will be converted, i.e. * it doesn't matter if you call it on a string that has already been * converted to Unicode. * @memberOf punycode * @param {String} input The Punycoded domain name or email address to * convert to Unicode. * @returns {String} The Unicode representation of the given Punycode * string. */ function toUnicode(input) { return mapDomain(input, function(string) { return regexPunycode.test(string) ? decode(string.slice(4).toLowerCase()) : string; }); } /** * Converts a Unicode string representing a domain name or an email address to * Punycode. Only the non-ASCII parts of the domain name will be converted, * i.e. it doesn't matter if you call it with a domain that's already in * ASCII. * @memberOf punycode * @param {String} input The domain name or email address to convert, as a * Unicode string. * @returns {String} The Punycode representation of the given domain name or * email address. */ function toASCII(input) { return mapDomain(input, function(string) { return regexNonASCII.test(string) ? 'xn--' + encode(string) : string; }); } /*--------------------------------------------------------------------------*/ /** Define the public API */ punycode = { /** * A string representing the current Punycode.js version number. * @memberOf punycode * @type String */ 'version': '1.4.1', /** * An object of methods to convert from JavaScript's internal character * representation (UCS-2) to Unicode code points, and back. * @see * @memberOf punycode * @type Object */ 'ucs2': { 'decode': ucs2decode, 'encode': ucs2encode }, 'decode': decode, 'encode': encode, 'toASCII': toASCII, 'toUnicode': toUnicode }; /** Expose `punycode` */ // Some AMD build optimizers, like r.js, check for specific condition patterns // like the following: if ( typeof define == 'function' && typeof define.amd == 'object' && define.amd ) { define('punycode', function() { return punycode; }); } else if (freeExports && freeModule) { if (module.exports == freeExports) { // in Node.js, io.js, or RingoJS v0.8.0+ freeModule.exports = punycode; } else { // in Narwhal or RingoJS v0.7.0- for (key in punycode) { punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); } } } else { // in Rhino or a web browser root.punycode = punycode; } }(this)); }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],227:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; // If obj.hasOwnProperty has been overridden, then calling // obj.hasOwnProperty(prop) will break. // See: https://github.com/joyent/node/issues/1707 function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } module.exports = function(qs, sep, eq, options) { sep = sep || '&'; eq = eq || '='; var obj = {}; if (typeof qs !== 'string' || qs.length === 0) { return obj; } var regexp = /\+/g; qs = qs.split(sep); var maxKeys = 1000; if (options && typeof options.maxKeys === 'number') { maxKeys = options.maxKeys; } var len = qs.length; // maxKeys <= 0 means that we should not limit keys count if (maxKeys > 0 && len > maxKeys) { len = maxKeys; } for (var i = 0; i < len; ++i) { var x = qs[i].replace(regexp, '%20'), idx = x.indexOf(eq), kstr, vstr, k, v; if (idx >= 0) { kstr = x.substr(0, idx); vstr = x.substr(idx + 1); } else { kstr = x; vstr = ''; } k = decodeURIComponent(kstr); v = decodeURIComponent(vstr); if (!hasOwnProperty(obj, k)) { obj[k] = v; } else if (isArray(obj[k])) { obj[k].push(v); } else { obj[k] = [obj[k], v]; } } return obj; }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; },{}],228:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var stringifyPrimitive = function(v) { switch (typeof v) { case 'string': return v; case 'boolean': return v ? 'true' : 'false'; case 'number': return isFinite(v) ? v : ''; default: return ''; } }; module.exports = function(obj, sep, eq, name) { sep = sep || '&'; eq = eq || '='; if (obj === null) { obj = undefined; } if (typeof obj === 'object') { return map(objectKeys(obj), function(k) { var ks = encodeURIComponent(stringifyPrimitive(k)) + eq; if (isArray(obj[k])) { return map(obj[k], function(v) { return ks + encodeURIComponent(stringifyPrimitive(v)); }).join(sep); } else { return ks + encodeURIComponent(stringifyPrimitive(obj[k])); } }).join(sep); } if (!name) return ''; return encodeURIComponent(stringifyPrimitive(name)) + eq + encodeURIComponent(stringifyPrimitive(obj)); }; var isArray = Array.isArray || function (xs) { return Object.prototype.toString.call(xs) === '[object Array]'; }; function map (xs, f) { if (xs.map) return xs.map(f); var res = []; for (var i = 0; i < xs.length; i++) { res.push(f(xs[i], i)); } return res; } var objectKeys = Object.keys || function (obj) { var res = []; for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) res.push(key); } return res; }; },{}],229:[function(require,module,exports){ 'use strict'; exports.decode = exports.parse = require('./decode'); exports.encode = exports.stringify = require('./encode'); },{"./decode":227,"./encode":228}],230:[function(require,module,exports){ (function (process,global){ 'use strict' function oldBrowser () { throw new Error('secure random number generation not supported by this browser\nuse chrome, FireFox or Internet Explorer 11') } var Buffer = require('safe-buffer').Buffer var crypto = global.crypto || global.msCrypto if (crypto && crypto.getRandomValues) { module.exports = randomBytes } else { module.exports = oldBrowser } function randomBytes (size, cb) { // phantomjs needs to throw if (size > 65536) throw new Error('requested too many random bytes') // in case browserify isn't using the Uint8Array version var rawBytes = new global.Uint8Array(size) // This will not work in older browsers. // See https://developer.mozilla.org/en-US/docs/Web/API/window.crypto.getRandomValues if (size > 0) { // getRandomValues fails on IE if size == 0 crypto.getRandomValues(rawBytes) } // XXX: phantomjs doesn't like a buffer being passed here var bytes = Buffer.from(rawBytes.buffer) if (typeof cb === 'function') { return process.nextTick(function () { cb(null, bytes) }) } return bytes } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"_process":219,"safe-buffer":457}],231:[function(require,module,exports){ module.exports = require('./lib/_stream_duplex.js'); },{"./lib/_stream_duplex.js":232}],232:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a duplex stream is just a stream that is both readable and writable. // Since JS doesn't have multiple prototypal inheritance, this class // prototypally inherits from Readable, and then parasitically from // Writable. 'use strict'; /**/ var processNextTick = require('process-nextick-args'); /**/ /**/ var objectKeys = Object.keys || function (obj) { var keys = []; for (var key in obj) { keys.push(key); }return keys; }; /**/ module.exports = Duplex; /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ var Readable = require('./_stream_readable'); var Writable = require('./_stream_writable'); util.inherits(Duplex, Readable); var keys = objectKeys(Writable.prototype); for (var v = 0; v < keys.length; v++) { var method = keys[v]; if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; } function Duplex(options) { if (!(this instanceof Duplex)) return new Duplex(options); Readable.call(this, options); Writable.call(this, options); if (options && options.readable === false) this.readable = false; if (options && options.writable === false) this.writable = false; this.allowHalfOpen = true; if (options && options.allowHalfOpen === false) this.allowHalfOpen = false; this.once('end', onend); } // the no-half-open enforcer function onend() { // if we allow half-open state, or if the writable side ended, // then we're ok. if (this.allowHalfOpen || this._writableState.ended) return; // no more data can be written. // But allow more writes to happen in this tick. processNextTick(onEndNT, this); } function onEndNT(self) { self.end(); } Object.defineProperty(Duplex.prototype, 'destroyed', { get: function () { if (this._readableState === undefined || this._writableState === undefined) { return false; } return this._readableState.destroyed && this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (this._readableState === undefined || this._writableState === undefined) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; this._writableState.destroyed = value; } }); Duplex.prototype._destroy = function (err, cb) { this.push(null); this.end(); processNextTick(cb, err); }; function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } },{"./_stream_readable":234,"./_stream_writable":236,"core-util-is":181,"inherits":203,"process-nextick-args":218}],233:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a passthrough stream. // basically just the most minimal sort of Transform stream. // Every written chunk gets output as-is. 'use strict'; module.exports = PassThrough; var Transform = require('./_stream_transform'); /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ util.inherits(PassThrough, Transform); function PassThrough(options) { if (!(this instanceof PassThrough)) return new PassThrough(options); Transform.call(this, options); } PassThrough.prototype._transform = function (chunk, encoding, cb) { cb(null, chunk); }; },{"./_stream_transform":235,"core-util-is":181,"inherits":203}],234:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; /**/ var processNextTick = require('process-nextick-args'); /**/ module.exports = Readable; /**/ var isArray = require('isarray'); /**/ /**/ var Duplex; /**/ Readable.ReadableState = ReadableState; /**/ var EE = require('events').EventEmitter; var EElistenerCount = function (emitter, type) { return emitter.listeners(type).length; }; /**/ /**/ var Stream = require('./internal/streams/stream'); /**/ // TODO(bmeurer): Change this back to const once hole checks are // properly optimized away early in Ignition+TurboFan. /**/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ /**/ var debugUtil = require('util'); var debug = void 0; if (debugUtil && debugUtil.debuglog) { debug = debugUtil.debuglog('stream'); } else { debug = function () {}; } /**/ var BufferList = require('./internal/streams/BufferList'); var destroyImpl = require('./internal/streams/destroy'); var StringDecoder; util.inherits(Readable, Stream); var kProxyEvents = ['error', 'close', 'destroy', 'pause', 'resume']; function prependListener(emitter, event, fn) { // Sadly this is not cacheable as some libraries bundle their own // event emitter implementation with them. if (typeof emitter.prependListener === 'function') { return emitter.prependListener(event, fn); } else { // This is a hack to make sure that our error handler is attached before any // userland ones. NEVER DO THIS. This is here only because this code needs // to continue to work with older versions of Node.js that do not include // the prependListener() method. The goal is to eventually remove this hack. if (!emitter._events || !emitter._events[event]) emitter.on(event, fn);else if (isArray(emitter._events[event])) emitter._events[event].unshift(fn);else emitter._events[event] = [fn, emitter._events[event]]; } } function ReadableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // object stream flag. Used to make read(n) ignore n and to // make all the buffer merging and length checks go away this.objectMode = !!options.objectMode; if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.readableObjectMode; // the point at which it stops calling _read() to fill the buffer // Note: 0 is a valid value, means "don't call _read preemptively ever" var hwm = options.highWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // A linked list is used to store data chunks instead of an array because the // linked list can remove elements from the beginning faster than // array.shift() this.buffer = new BufferList(); this.length = 0; this.pipes = null; this.pipesCount = 0; this.flowing = null; this.ended = false; this.endEmitted = false; this.reading = false; // a flag to be able to tell if the event 'readable'/'data' is emitted // immediately, or on a later tick. We set this to true at first, because // any actions that shouldn't happen until "later" should generally also // not happen before the first read call. this.sync = true; // whenever we return null, then we set a flag to say // that we're awaiting a 'readable' event emission. this.needReadable = false; this.emittedReadable = false; this.readableListening = false; this.resumeScheduled = false; // has it been destroyed this.destroyed = false; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // the number of writers that are awaiting a drain event in .pipe()s this.awaitDrain = 0; // if true, a maybeReadMore has been scheduled this.readingMore = false; this.decoder = null; this.encoding = null; if (options.encoding) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this.decoder = new StringDecoder(options.encoding); this.encoding = options.encoding; } } function Readable(options) { Duplex = Duplex || require('./_stream_duplex'); if (!(this instanceof Readable)) return new Readable(options); this._readableState = new ReadableState(options, this); // legacy this.readable = true; if (options) { if (typeof options.read === 'function') this._read = options.read; if (typeof options.destroy === 'function') this._destroy = options.destroy; } Stream.call(this); } Object.defineProperty(Readable.prototype, 'destroyed', { get: function () { if (this._readableState === undefined) { return false; } return this._readableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._readableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._readableState.destroyed = value; } }); Readable.prototype.destroy = destroyImpl.destroy; Readable.prototype._undestroy = destroyImpl.undestroy; Readable.prototype._destroy = function (err, cb) { this.push(null); cb(err); }; // Manually shove something into the read() buffer. // This returns true if the highWaterMark has not been hit yet, // similar to how Writable.write() returns true if you should // write() some more. Readable.prototype.push = function (chunk, encoding) { var state = this._readableState; var skipChunkCheck; if (!state.objectMode) { if (typeof chunk === 'string') { encoding = encoding || state.defaultEncoding; if (encoding !== state.encoding) { chunk = Buffer.from(chunk, encoding); encoding = ''; } skipChunkCheck = true; } } else { skipChunkCheck = true; } return readableAddChunk(this, chunk, encoding, false, skipChunkCheck); }; // Unshift should *always* be something directly out of read() Readable.prototype.unshift = function (chunk) { return readableAddChunk(this, chunk, null, true, false); }; function readableAddChunk(stream, chunk, encoding, addToFront, skipChunkCheck) { var state = stream._readableState; if (chunk === null) { state.reading = false; onEofChunk(stream, state); } else { var er; if (!skipChunkCheck) er = chunkInvalid(state, chunk); if (er) { stream.emit('error', er); } else if (state.objectMode || chunk && chunk.length > 0) { if (typeof chunk !== 'string' && !state.objectMode && Object.getPrototypeOf(chunk) !== Buffer.prototype) { chunk = _uint8ArrayToBuffer(chunk); } if (addToFront) { if (state.endEmitted) stream.emit('error', new Error('stream.unshift() after end event'));else addChunk(stream, state, chunk, true); } else if (state.ended) { stream.emit('error', new Error('stream.push() after EOF')); } else { state.reading = false; if (state.decoder && !encoding) { chunk = state.decoder.write(chunk); if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false);else maybeReadMore(stream, state); } else { addChunk(stream, state, chunk, false); } } } else if (!addToFront) { state.reading = false; } } return needMoreData(state); } function addChunk(stream, state, chunk, addToFront) { if (state.flowing && state.length === 0 && !state.sync) { stream.emit('data', chunk); stream.read(0); } else { // update the buffer info. state.length += state.objectMode ? 1 : chunk.length; if (addToFront) state.buffer.unshift(chunk);else state.buffer.push(chunk); if (state.needReadable) emitReadable(stream); } maybeReadMore(stream, state); } function chunkInvalid(state, chunk) { var er; if (!_isUint8Array(chunk) && typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } return er; } // if it's past the high water mark, we can push in some more. // Also, if we have no data yet, we can stand some // more bytes. This is to work around cases where hwm=0, // such as the repl. Also, if the push() triggered a // readable event, and the user called read(largeNumber) such that // needReadable was set, then we ought to push more, so that another // 'readable' event will be triggered. function needMoreData(state) { return !state.ended && (state.needReadable || state.length < state.highWaterMark || state.length === 0); } Readable.prototype.isPaused = function () { return this._readableState.flowing === false; }; // backwards compatibility. Readable.prototype.setEncoding = function (enc) { if (!StringDecoder) StringDecoder = require('string_decoder/').StringDecoder; this._readableState.decoder = new StringDecoder(enc); this._readableState.encoding = enc; return this; }; // Don't raise the hwm > 8MB var MAX_HWM = 0x800000; function computeNewHighWaterMark(n) { if (n >= MAX_HWM) { n = MAX_HWM; } else { // Get the next highest power of 2 to prevent increasing hwm excessively in // tiny amounts n--; n |= n >>> 1; n |= n >>> 2; n |= n >>> 4; n |= n >>> 8; n |= n >>> 16; n++; } return n; } // This function is designed to be inlinable, so please take care when making // changes to the function body. function howMuchToRead(n, state) { if (n <= 0 || state.length === 0 && state.ended) return 0; if (state.objectMode) return 1; if (n !== n) { // Only flow one buffer at a time if (state.flowing && state.length) return state.buffer.head.data.length;else return state.length; } // If we're asking for more than the current hwm, then raise the hwm. if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); if (n <= state.length) return n; // Don't have enough if (!state.ended) { state.needReadable = true; return 0; } return state.length; } // you can override either this method, or the async _read(n) below. Readable.prototype.read = function (n) { debug('read', n); n = parseInt(n, 10); var state = this._readableState; var nOrig = n; if (n !== 0) state.emittedReadable = false; // if we're doing read(0) to trigger a readable event, but we // already have a bunch of data in the buffer, then just trigger // the 'readable' event and move on. if (n === 0 && state.needReadable && (state.length >= state.highWaterMark || state.ended)) { debug('read: emitReadable', state.length, state.ended); if (state.length === 0 && state.ended) endReadable(this);else emitReadable(this); return null; } n = howMuchToRead(n, state); // if we've ended, and we're now clear, then finish it up. if (n === 0 && state.ended) { if (state.length === 0) endReadable(this); return null; } // All the actual chunk generation logic needs to be // *below* the call to _read. The reason is that in certain // synthetic stream cases, such as passthrough streams, _read // may be a completely synchronous operation which may change // the state of the read buffer, providing enough data when // before there was *not* enough. // // So, the steps are: // 1. Figure out what the state of things will be after we do // a read from the buffer. // // 2. If that resulting state will trigger a _read, then call _read. // Note that this may be asynchronous, or synchronous. Yes, it is // deeply ugly to write APIs this way, but that still doesn't mean // that the Readable class should behave improperly, as streams are // designed to be sync/async agnostic. // Take note if the _read call is sync or async (ie, if the read call // has returned yet), so that we know whether or not it's safe to emit // 'readable' etc. // // 3. Actually pull the requested chunks out of the buffer and return. // if we need a readable event, then we need to do some reading. var doRead = state.needReadable; debug('need readable', doRead); // if we currently have less than the highWaterMark, then also read some if (state.length === 0 || state.length - n < state.highWaterMark) { doRead = true; debug('length less than watermark', doRead); } // however, if we've ended, then there's no point, and if we're already // reading, then it's unnecessary. if (state.ended || state.reading) { doRead = false; debug('reading or ended', doRead); } else if (doRead) { debug('do read'); state.reading = true; state.sync = true; // if the length is currently zero, then we *need* a readable event. if (state.length === 0) state.needReadable = true; // call internal read method this._read(state.highWaterMark); state.sync = false; // If _read pushed data synchronously, then `reading` will be false, // and we need to re-evaluate how much data we can return to the user. if (!state.reading) n = howMuchToRead(nOrig, state); } var ret; if (n > 0) ret = fromList(n, state);else ret = null; if (ret === null) { state.needReadable = true; n = 0; } else { state.length -= n; } if (state.length === 0) { // If we have nothing in the buffer, then we want to know // as soon as we *do* get something into the buffer. if (!state.ended) state.needReadable = true; // If we tried to read() past the EOF, then emit end on the next tick. if (nOrig !== n && state.ended) endReadable(this); } if (ret !== null) this.emit('data', ret); return ret; }; function onEofChunk(stream, state) { if (state.ended) return; if (state.decoder) { var chunk = state.decoder.end(); if (chunk && chunk.length) { state.buffer.push(chunk); state.length += state.objectMode ? 1 : chunk.length; } } state.ended = true; // emit 'readable' now to make sure it gets picked up. emitReadable(stream); } // Don't emit readable right away in sync mode, because this can trigger // another read() call => stack overflow. This way, it might trigger // a nextTick recursion warning, but that's not so bad. function emitReadable(stream) { var state = stream._readableState; state.needReadable = false; if (!state.emittedReadable) { debug('emitReadable', state.flowing); state.emittedReadable = true; if (state.sync) processNextTick(emitReadable_, stream);else emitReadable_(stream); } } function emitReadable_(stream) { debug('emit readable'); stream.emit('readable'); flow(stream); } // at this point, the user has presumably seen the 'readable' event, // and called read() to consume some data. that may have triggered // in turn another _read(n) call, in which case reading = true if // it's in progress. // However, if we're not ended, or reading, and the length < hwm, // then go ahead and try to read some more preemptively. function maybeReadMore(stream, state) { if (!state.readingMore) { state.readingMore = true; processNextTick(maybeReadMore_, stream, state); } } function maybeReadMore_(stream, state) { var len = state.length; while (!state.reading && !state.flowing && !state.ended && state.length < state.highWaterMark) { debug('maybeReadMore read 0'); stream.read(0); if (len === state.length) // didn't get any data, stop spinning. break;else len = state.length; } state.readingMore = false; } // abstract method. to be overridden in specific implementation classes. // call cb(er, data) where data is <= n in length. // for virtual (non-string, non-buffer) streams, "length" is somewhat // arbitrary, and perhaps not very meaningful. Readable.prototype._read = function (n) { this.emit('error', new Error('_read() is not implemented')); }; Readable.prototype.pipe = function (dest, pipeOpts) { var src = this; var state = this._readableState; switch (state.pipesCount) { case 0: state.pipes = dest; break; case 1: state.pipes = [state.pipes, dest]; break; default: state.pipes.push(dest); break; } state.pipesCount += 1; debug('pipe count=%d opts=%j', state.pipesCount, pipeOpts); var doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; var endFn = doEnd ? onend : unpipe; if (state.endEmitted) processNextTick(endFn);else src.once('end', endFn); dest.on('unpipe', onunpipe); function onunpipe(readable, unpipeInfo) { debug('onunpipe'); if (readable === src) { if (unpipeInfo && unpipeInfo.hasUnpiped === false) { unpipeInfo.hasUnpiped = true; cleanup(); } } } function onend() { debug('onend'); dest.end(); } // when the dest drains, it reduces the awaitDrain counter // on the source. This would be more elegant with a .once() // handler in flow(), but adding and removing repeatedly is // too slow. var ondrain = pipeOnDrain(src); dest.on('drain', ondrain); var cleanedUp = false; function cleanup() { debug('cleanup'); // cleanup event handlers once the pipe is broken dest.removeListener('close', onclose); dest.removeListener('finish', onfinish); dest.removeListener('drain', ondrain); dest.removeListener('error', onerror); dest.removeListener('unpipe', onunpipe); src.removeListener('end', onend); src.removeListener('end', unpipe); src.removeListener('data', ondata); cleanedUp = true; // if the reader is waiting for a drain event from this // specific writer, then it would cause it to never start // flowing again. // So, if this is awaiting a drain, then we just call it now. // If we don't know, then assume that we are waiting for one. if (state.awaitDrain && (!dest._writableState || dest._writableState.needDrain)) ondrain(); } // If the user pushes more data while we're writing to dest then we'll end up // in ondata again. However, we only want to increase awaitDrain once because // dest will only emit one 'drain' event for the multiple writes. // => Introduce a guard on increasing awaitDrain. var increasedAwaitDrain = false; src.on('data', ondata); function ondata(chunk) { debug('ondata'); increasedAwaitDrain = false; var ret = dest.write(chunk); if (false === ret && !increasedAwaitDrain) { // If the user unpiped during `dest.write()`, it is possible // to get stuck in a permanently paused state if that write // also returned false. // => Check whether `dest` is still a piping destination. if ((state.pipesCount === 1 && state.pipes === dest || state.pipesCount > 1 && indexOf(state.pipes, dest) !== -1) && !cleanedUp) { debug('false write response, pause', src._readableState.awaitDrain); src._readableState.awaitDrain++; increasedAwaitDrain = true; } src.pause(); } } // if the dest has an error, then stop piping into it. // however, don't suppress the throwing behavior for this. function onerror(er) { debug('onerror', er); unpipe(); dest.removeListener('error', onerror); if (EElistenerCount(dest, 'error') === 0) dest.emit('error', er); } // Make sure our error handler is attached before userland ones. prependListener(dest, 'error', onerror); // Both close and finish should trigger unpipe, but only once. function onclose() { dest.removeListener('finish', onfinish); unpipe(); } dest.once('close', onclose); function onfinish() { debug('onfinish'); dest.removeListener('close', onclose); unpipe(); } dest.once('finish', onfinish); function unpipe() { debug('unpipe'); src.unpipe(dest); } // tell the dest that it's being piped to dest.emit('pipe', src); // start the flow if it hasn't been started already. if (!state.flowing) { debug('pipe resume'); src.resume(); } return dest; }; function pipeOnDrain(src) { return function () { var state = src._readableState; debug('pipeOnDrain', state.awaitDrain); if (state.awaitDrain) state.awaitDrain--; if (state.awaitDrain === 0 && EElistenerCount(src, 'data')) { state.flowing = true; flow(src); } }; } Readable.prototype.unpipe = function (dest) { var state = this._readableState; var unpipeInfo = { hasUnpiped: false }; // if we're not piping anywhere, then do nothing. if (state.pipesCount === 0) return this; // just one destination. most common case. if (state.pipesCount === 1) { // passed in one, but it's not the right one. if (dest && dest !== state.pipes) return this; if (!dest) dest = state.pipes; // got a match. state.pipes = null; state.pipesCount = 0; state.flowing = false; if (dest) dest.emit('unpipe', this, unpipeInfo); return this; } // slow case. multiple pipe destinations. if (!dest) { // remove all. var dests = state.pipes; var len = state.pipesCount; state.pipes = null; state.pipesCount = 0; state.flowing = false; for (var i = 0; i < len; i++) { dests[i].emit('unpipe', this, unpipeInfo); }return this; } // try to find the right one. var index = indexOf(state.pipes, dest); if (index === -1) return this; state.pipes.splice(index, 1); state.pipesCount -= 1; if (state.pipesCount === 1) state.pipes = state.pipes[0]; dest.emit('unpipe', this, unpipeInfo); return this; }; // set up data events if they are asked for // Ensure readable listeners eventually get something Readable.prototype.on = function (ev, fn) { var res = Stream.prototype.on.call(this, ev, fn); if (ev === 'data') { // Start flowing on next tick if stream isn't explicitly paused if (this._readableState.flowing !== false) this.resume(); } else if (ev === 'readable') { var state = this._readableState; if (!state.endEmitted && !state.readableListening) { state.readableListening = state.needReadable = true; state.emittedReadable = false; if (!state.reading) { processNextTick(nReadingNextTick, this); } else if (state.length) { emitReadable(this); } } } return res; }; Readable.prototype.addListener = Readable.prototype.on; function nReadingNextTick(self) { debug('readable nexttick read 0'); self.read(0); } // pause() and resume() are remnants of the legacy readable stream API // If the user uses them, then switch into old mode. Readable.prototype.resume = function () { var state = this._readableState; if (!state.flowing) { debug('resume'); state.flowing = true; resume(this, state); } return this; }; function resume(stream, state) { if (!state.resumeScheduled) { state.resumeScheduled = true; processNextTick(resume_, stream, state); } } function resume_(stream, state) { if (!state.reading) { debug('resume read 0'); stream.read(0); } state.resumeScheduled = false; state.awaitDrain = 0; stream.emit('resume'); flow(stream); if (state.flowing && !state.reading) stream.read(0); } Readable.prototype.pause = function () { debug('call pause flowing=%j', this._readableState.flowing); if (false !== this._readableState.flowing) { debug('pause'); this._readableState.flowing = false; this.emit('pause'); } return this; }; function flow(stream) { var state = stream._readableState; debug('flow', state.flowing); while (state.flowing && stream.read() !== null) {} } // wrap an old-style stream as the async data source. // This is *not* part of the readable stream interface. // It is an ugly unfortunate mess of history. Readable.prototype.wrap = function (stream) { var state = this._readableState; var paused = false; var self = this; stream.on('end', function () { debug('wrapped end'); if (state.decoder && !state.ended) { var chunk = state.decoder.end(); if (chunk && chunk.length) self.push(chunk); } self.push(null); }); stream.on('data', function (chunk) { debug('wrapped data'); if (state.decoder) chunk = state.decoder.write(chunk); // don't skip over falsy values in objectMode if (state.objectMode && (chunk === null || chunk === undefined)) return;else if (!state.objectMode && (!chunk || !chunk.length)) return; var ret = self.push(chunk); if (!ret) { paused = true; stream.pause(); } }); // proxy all the other methods. // important when wrapping filters and duplexes. for (var i in stream) { if (this[i] === undefined && typeof stream[i] === 'function') { this[i] = function (method) { return function () { return stream[method].apply(stream, arguments); }; }(i); } } // proxy certain important events. for (var n = 0; n < kProxyEvents.length; n++) { stream.on(kProxyEvents[n], self.emit.bind(self, kProxyEvents[n])); } // when we try to consume some more bytes, simply unpause the // underlying stream. self._read = function (n) { debug('wrapped _read', n); if (paused) { paused = false; stream.resume(); } }; return self; }; // exposed for testing purposes only. Readable._fromList = fromList; // Pluck off n bytes from an array of buffers. // Length is the combined lengths of all the buffers in the list. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromList(n, state) { // nothing buffered if (state.length === 0) return null; var ret; if (state.objectMode) ret = state.buffer.shift();else if (!n || n >= state.length) { // read it all, truncate the list if (state.decoder) ret = state.buffer.join('');else if (state.buffer.length === 1) ret = state.buffer.head.data;else ret = state.buffer.concat(state.length); state.buffer.clear(); } else { // read part of list ret = fromListPartial(n, state.buffer, state.decoder); } return ret; } // Extracts only enough buffered data to satisfy the amount requested. // This function is designed to be inlinable, so please take care when making // changes to the function body. function fromListPartial(n, list, hasStrings) { var ret; if (n < list.head.data.length) { // slice is the same for buffers and strings ret = list.head.data.slice(0, n); list.head.data = list.head.data.slice(n); } else if (n === list.head.data.length) { // first chunk is a perfect match ret = list.shift(); } else { // result spans more than one buffer ret = hasStrings ? copyFromBufferString(n, list) : copyFromBuffer(n, list); } return ret; } // Copies a specified amount of characters from the list of buffered data // chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBufferString(n, list) { var p = list.head; var c = 1; var ret = p.data; n -= ret.length; while (p = p.next) { var str = p.data; var nb = n > str.length ? str.length : n; if (nb === str.length) ret += str;else ret += str.slice(0, n); n -= nb; if (n === 0) { if (nb === str.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = str.slice(nb); } break; } ++c; } list.length -= c; return ret; } // Copies a specified amount of bytes from the list of buffered data chunks. // This function is designed to be inlinable, so please take care when making // changes to the function body. function copyFromBuffer(n, list) { var ret = Buffer.allocUnsafe(n); var p = list.head; var c = 1; p.data.copy(ret); n -= p.data.length; while (p = p.next) { var buf = p.data; var nb = n > buf.length ? buf.length : n; buf.copy(ret, ret.length - n, 0, nb); n -= nb; if (n === 0) { if (nb === buf.length) { ++c; if (p.next) list.head = p.next;else list.head = list.tail = null; } else { list.head = p; p.data = buf.slice(nb); } break; } ++c; } list.length -= c; return ret; } function endReadable(stream) { var state = stream._readableState; // If we get here before consuming all the bytes, then that is a // bug in node. Should never happen. if (state.length > 0) throw new Error('"endReadable()" called on non-empty stream'); if (!state.endEmitted) { state.ended = true; processNextTick(endReadableNT, state, stream); } } function endReadableNT(state, stream) { // Check that we didn't get one last unshift. if (!state.endEmitted && state.length === 0) { state.endEmitted = true; stream.readable = false; stream.emit('end'); } } function forEach(xs, f) { for (var i = 0, l = xs.length; i < l; i++) { f(xs[i], i); } } function indexOf(xs, x) { for (var i = 0, l = xs.length; i < l; i++) { if (xs[i] === x) return i; } return -1; } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":232,"./internal/streams/BufferList":237,"./internal/streams/destroy":238,"./internal/streams/stream":239,"_process":219,"core-util-is":181,"events":199,"inherits":203,"isarray":205,"process-nextick-args":218,"safe-buffer":457,"string_decoder/":240,"util":151}],235:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // a transform stream is a readable/writable stream where you do // something with the data. Sometimes it's called a "filter", // but that's not a great name for it, since that implies a thing where // some bits pass through, and others are simply ignored. (That would // be a valid example of a transform, of course.) // // While the output is causally related to the input, it's not a // necessarily symmetric or synchronous transformation. For example, // a zlib stream might take multiple plain-text writes(), and then // emit a single compressed chunk some time in the future. // // Here's how this works: // // The Transform stream has all the aspects of the readable and writable // stream classes. When you write(chunk), that calls _write(chunk,cb) // internally, and returns false if there's a lot of pending writes // buffered up. When you call read(), that calls _read(n) until // there's enough pending readable data buffered up. // // In a transform stream, the written data is placed in a buffer. When // _read(n) is called, it transforms the queued up data, calling the // buffered _write cb's as it consumes chunks. If consuming a single // written chunk would result in multiple output chunks, then the first // outputted bit calls the readcb, and subsequent chunks just go into // the read buffer, and will cause it to emit 'readable' if necessary. // // This way, back-pressure is actually determined by the reading side, // since _read has to be called to start processing a new chunk. However, // a pathological inflate type of transform can cause excessive buffering // here. For example, imagine a stream where every byte of input is // interpreted as an integer from 0-255, and then results in that many // bytes of output. Writing the 4 bytes {ff,ff,ff,ff} would result in // 1kb of data being output. In this case, you could write a very small // amount of input, and end up with a very large amount of output. In // such a pathological inflating mechanism, there'd be no way to tell // the system to stop doing the transform. A single 4MB write could // cause the system to run out of memory. // // However, even in such a pathological case, only a single written chunk // would be consumed, and then the rest would wait (un-transformed) until // the results of the previous transformed chunk were consumed. 'use strict'; module.exports = Transform; var Duplex = require('./_stream_duplex'); /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ util.inherits(Transform, Duplex); function TransformState(stream) { this.afterTransform = function (er, data) { return afterTransform(stream, er, data); }; this.needTransform = false; this.transforming = false; this.writecb = null; this.writechunk = null; this.writeencoding = null; } function afterTransform(stream, er, data) { var ts = stream._transformState; ts.transforming = false; var cb = ts.writecb; if (!cb) { return stream.emit('error', new Error('write callback called multiple times')); } ts.writechunk = null; ts.writecb = null; if (data !== null && data !== undefined) stream.push(data); cb(er); var rs = stream._readableState; rs.reading = false; if (rs.needReadable || rs.length < rs.highWaterMark) { stream._read(rs.highWaterMark); } } function Transform(options) { if (!(this instanceof Transform)) return new Transform(options); Duplex.call(this, options); this._transformState = new TransformState(this); var stream = this; // start out asking for a readable event once data is transformed. this._readableState.needReadable = true; // we have implemented the _read method, and done the other things // that Readable wants before the first _read call, so unset the // sync guard flag. this._readableState.sync = false; if (options) { if (typeof options.transform === 'function') this._transform = options.transform; if (typeof options.flush === 'function') this._flush = options.flush; } // When the writable side finishes, then flush out anything remaining. this.once('prefinish', function () { if (typeof this._flush === 'function') this._flush(function (er, data) { done(stream, er, data); });else done(stream); }); } Transform.prototype.push = function (chunk, encoding) { this._transformState.needTransform = false; return Duplex.prototype.push.call(this, chunk, encoding); }; // This is the part where you do stuff! // override this function in implementation classes. // 'chunk' is an input chunk. // // Call `push(newChunk)` to pass along transformed output // to the readable side. You may call 'push' zero or more times. // // Call `cb(err)` when you are done with this chunk. If you pass // an error, then that'll put the hurt on the whole operation. If you // never call cb(), then you'll never get another chunk. Transform.prototype._transform = function (chunk, encoding, cb) { throw new Error('_transform() is not implemented'); }; Transform.prototype._write = function (chunk, encoding, cb) { var ts = this._transformState; ts.writecb = cb; ts.writechunk = chunk; ts.writeencoding = encoding; if (!ts.transforming) { var rs = this._readableState; if (ts.needTransform || rs.needReadable || rs.length < rs.highWaterMark) this._read(rs.highWaterMark); } }; // Doesn't matter what the args are here. // _transform does all the work. // That we got here means that the readable side wants more data. Transform.prototype._read = function (n) { var ts = this._transformState; if (ts.writechunk !== null && ts.writecb && !ts.transforming) { ts.transforming = true; this._transform(ts.writechunk, ts.writeencoding, ts.afterTransform); } else { // mark that we need a transform, so that any data that comes in // will get processed, now that we've asked for it. ts.needTransform = true; } }; Transform.prototype._destroy = function (err, cb) { var _this = this; Duplex.prototype._destroy.call(this, err, function (err2) { cb(err2); _this.emit('close'); }); }; function done(stream, er, data) { if (er) return stream.emit('error', er); if (data !== null && data !== undefined) stream.push(data); // if there's nothing in the write buffer, then that means // that nothing more will ever be provided var ws = stream._writableState; var ts = stream._transformState; if (ws.length) throw new Error('Calling transform done when ws.length != 0'); if (ts.transforming) throw new Error('Calling transform done when still transforming'); return stream.push(null); } },{"./_stream_duplex":232,"core-util-is":181,"inherits":203}],236:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. // A bit simpler than readable streams. // Implement an async ._write(chunk, encoding, cb), and it'll handle all // the drain event emission and buffering. 'use strict'; /**/ var processNextTick = require('process-nextick-args'); /**/ module.exports = Writable; /* */ function WriteReq(chunk, encoding, cb) { this.chunk = chunk; this.encoding = encoding; this.callback = cb; this.next = null; } // It seems a linked list but it is not // there will be only 2 of these for each stream function CorkedRequest(state) { var _this = this; this.next = null; this.entry = null; this.finish = function () { onCorkedFinish(_this, state); }; } /* */ /**/ var asyncWrite = !process.browser && ['v0.10', 'v0.9.'].indexOf(process.version.slice(0, 5)) > -1 ? setImmediate : processNextTick; /**/ /**/ var Duplex; /**/ Writable.WritableState = WritableState; /**/ var util = require('core-util-is'); util.inherits = require('inherits'); /**/ /**/ var internalUtil = { deprecate: require('util-deprecate') }; /**/ /**/ var Stream = require('./internal/streams/stream'); /**/ /**/ var Buffer = require('safe-buffer').Buffer; var OurUint8Array = global.Uint8Array || function () {}; function _uint8ArrayToBuffer(chunk) { return Buffer.from(chunk); } function _isUint8Array(obj) { return Buffer.isBuffer(obj) || obj instanceof OurUint8Array; } /**/ var destroyImpl = require('./internal/streams/destroy'); util.inherits(Writable, Stream); function nop() {} function WritableState(options, stream) { Duplex = Duplex || require('./_stream_duplex'); options = options || {}; // object stream flag to indicate whether or not this stream // contains buffers or objects. this.objectMode = !!options.objectMode; if (stream instanceof Duplex) this.objectMode = this.objectMode || !!options.writableObjectMode; // the point at which write() starts returning false // Note: 0 is a valid value, means that we always return false if // the entire buffer is not flushed immediately on write() var hwm = options.highWaterMark; var defaultHwm = this.objectMode ? 16 : 16 * 1024; this.highWaterMark = hwm || hwm === 0 ? hwm : defaultHwm; // cast to ints. this.highWaterMark = Math.floor(this.highWaterMark); // if _final has been called this.finalCalled = false; // drain event flag. this.needDrain = false; // at the start of calling end() this.ending = false; // when end() has been called, and returned this.ended = false; // when 'finish' is emitted this.finished = false; // has it been destroyed this.destroyed = false; // should we decode strings into buffers before passing to _write? // this is here so that some node-core streams can optimize string // handling at a lower level. var noDecode = options.decodeStrings === false; this.decodeStrings = !noDecode; // Crypto is kind of old and crusty. Historically, its default string // encoding is 'binary' so we have to make this configurable. // Everything else in the universe uses 'utf8', though. this.defaultEncoding = options.defaultEncoding || 'utf8'; // not an actual buffer we keep track of, but a measurement // of how much we're waiting to get pushed to some underlying // socket or file. this.length = 0; // a flag to see when we're in the middle of a write. this.writing = false; // when true all writes will be buffered until .uncork() call this.corked = 0; // a flag to be able to tell if the onwrite cb is called immediately, // or on a later tick. We set this to true at first, because any // actions that shouldn't happen until "later" should generally also // not happen before the first write call. this.sync = true; // a flag to know if we're processing previously buffered items, which // may call the _write() callback in the same tick, so that we don't // end up in an overlapped onwrite situation. this.bufferProcessing = false; // the callback that's passed to _write(chunk,cb) this.onwrite = function (er) { onwrite(stream, er); }; // the callback that the user supplies to write(chunk,encoding,cb) this.writecb = null; // the amount that is being written when _write is called. this.writelen = 0; this.bufferedRequest = null; this.lastBufferedRequest = null; // number of pending user-supplied write callbacks // this must be 0 before 'finish' can be emitted this.pendingcb = 0; // emit prefinish if the only thing we're waiting for is _write cbs // This is relevant for synchronous Transform streams this.prefinished = false; // True if the error was already emitted and should not be thrown again this.errorEmitted = false; // count buffered requests this.bufferedRequestCount = 0; // allocate the first CorkedRequest, there is always // one allocated and free to use, and we maintain at most two this.corkedRequestsFree = new CorkedRequest(this); } WritableState.prototype.getBuffer = function getBuffer() { var current = this.bufferedRequest; var out = []; while (current) { out.push(current); current = current.next; } return out; }; (function () { try { Object.defineProperty(WritableState.prototype, 'buffer', { get: internalUtil.deprecate(function () { return this.getBuffer(); }, '_writableState.buffer is deprecated. Use _writableState.getBuffer ' + 'instead.', 'DEP0003') }); } catch (_) {} })(); // Test _writableState for inheritance to account for Duplex streams, // whose prototype chain only points to Readable. var realHasInstance; if (typeof Symbol === 'function' && Symbol.hasInstance && typeof Function.prototype[Symbol.hasInstance] === 'function') { realHasInstance = Function.prototype[Symbol.hasInstance]; Object.defineProperty(Writable, Symbol.hasInstance, { value: function (object) { if (realHasInstance.call(this, object)) return true; return object && object._writableState instanceof WritableState; } }); } else { realHasInstance = function (object) { return object instanceof this; }; } function Writable(options) { Duplex = Duplex || require('./_stream_duplex'); // Writable ctor is applied to Duplexes, too. // `realHasInstance` is necessary because using plain `instanceof` // would return false, as no `_writableState` property is attached. // Trying to use the custom `instanceof` for Writable here will also break the // Node.js LazyTransform implementation, which has a non-trivial getter for // `_writableState` that would lead to infinite recursion. if (!realHasInstance.call(Writable, this) && !(this instanceof Duplex)) { return new Writable(options); } this._writableState = new WritableState(options, this); // legacy. this.writable = true; if (options) { if (typeof options.write === 'function') this._write = options.write; if (typeof options.writev === 'function') this._writev = options.writev; if (typeof options.destroy === 'function') this._destroy = options.destroy; if (typeof options.final === 'function') this._final = options.final; } Stream.call(this); } // Otherwise people can pipe Writable streams, which is just wrong. Writable.prototype.pipe = function () { this.emit('error', new Error('Cannot pipe, not readable')); }; function writeAfterEnd(stream, cb) { var er = new Error('write after end'); // TODO: defer error events consistently everywhere, not just the cb stream.emit('error', er); processNextTick(cb, er); } // Checks that a user-supplied chunk is valid, especially for the particular // mode the stream is in. Currently this means that `null` is never accepted // and undefined/non-string values are only allowed in object mode. function validChunk(stream, state, chunk, cb) { var valid = true; var er = false; if (chunk === null) { er = new TypeError('May not write null values to stream'); } else if (typeof chunk !== 'string' && chunk !== undefined && !state.objectMode) { er = new TypeError('Invalid non-string/buffer chunk'); } if (er) { stream.emit('error', er); processNextTick(cb, er); valid = false; } return valid; } Writable.prototype.write = function (chunk, encoding, cb) { var state = this._writableState; var ret = false; var isBuf = _isUint8Array(chunk) && !state.objectMode; if (isBuf && !Buffer.isBuffer(chunk)) { chunk = _uint8ArrayToBuffer(chunk); } if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (isBuf) encoding = 'buffer';else if (!encoding) encoding = state.defaultEncoding; if (typeof cb !== 'function') cb = nop; if (state.ended) writeAfterEnd(this, cb);else if (isBuf || validChunk(this, state, chunk, cb)) { state.pendingcb++; ret = writeOrBuffer(this, state, isBuf, chunk, encoding, cb); } return ret; }; Writable.prototype.cork = function () { var state = this._writableState; state.corked++; }; Writable.prototype.uncork = function () { var state = this._writableState; if (state.corked) { state.corked--; if (!state.writing && !state.corked && !state.finished && !state.bufferProcessing && state.bufferedRequest) clearBuffer(this, state); } }; Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { // node::ParseEncoding() requires lower case. if (typeof encoding === 'string') encoding = encoding.toLowerCase(); if (!(['hex', 'utf8', 'utf-8', 'ascii', 'binary', 'base64', 'ucs2', 'ucs-2', 'utf16le', 'utf-16le', 'raw'].indexOf((encoding + '').toLowerCase()) > -1)) throw new TypeError('Unknown encoding: ' + encoding); this._writableState.defaultEncoding = encoding; return this; }; function decodeChunk(state, chunk, encoding) { if (!state.objectMode && state.decodeStrings !== false && typeof chunk === 'string') { chunk = Buffer.from(chunk, encoding); } return chunk; } // if we're already writing something, then just put this // in the queue, and wait our turn. Otherwise, call _write // If we return false, then we need a drain event, so set that flag. function writeOrBuffer(stream, state, isBuf, chunk, encoding, cb) { if (!isBuf) { var newChunk = decodeChunk(state, chunk, encoding); if (chunk !== newChunk) { isBuf = true; encoding = 'buffer'; chunk = newChunk; } } var len = state.objectMode ? 1 : chunk.length; state.length += len; var ret = state.length < state.highWaterMark; // we must ensure that previous needDrain will not be reset to false. if (!ret) state.needDrain = true; if (state.writing || state.corked) { var last = state.lastBufferedRequest; state.lastBufferedRequest = { chunk: chunk, encoding: encoding, isBuf: isBuf, callback: cb, next: null }; if (last) { last.next = state.lastBufferedRequest; } else { state.bufferedRequest = state.lastBufferedRequest; } state.bufferedRequestCount += 1; } else { doWrite(stream, state, false, len, chunk, encoding, cb); } return ret; } function doWrite(stream, state, writev, len, chunk, encoding, cb) { state.writelen = len; state.writecb = cb; state.writing = true; state.sync = true; if (writev) stream._writev(chunk, state.onwrite);else stream._write(chunk, encoding, state.onwrite); state.sync = false; } function onwriteError(stream, state, sync, er, cb) { --state.pendingcb; if (sync) { // defer the callback if we are being called synchronously // to avoid piling up things on the stack processNextTick(cb, er); // this can emit finish, and it will always happen // after error processNextTick(finishMaybe, stream, state); stream._writableState.errorEmitted = true; stream.emit('error', er); } else { // the caller expect this to happen before if // it is async cb(er); stream._writableState.errorEmitted = true; stream.emit('error', er); // this can emit finish, but finish must // always follow error finishMaybe(stream, state); } } function onwriteStateUpdate(state) { state.writing = false; state.writecb = null; state.length -= state.writelen; state.writelen = 0; } function onwrite(stream, er) { var state = stream._writableState; var sync = state.sync; var cb = state.writecb; onwriteStateUpdate(state); if (er) onwriteError(stream, state, sync, er, cb);else { // Check if we're actually ready to finish, but don't emit yet var finished = needFinish(state); if (!finished && !state.corked && !state.bufferProcessing && state.bufferedRequest) { clearBuffer(stream, state); } if (sync) { /**/ asyncWrite(afterWrite, stream, state, finished, cb); /**/ } else { afterWrite(stream, state, finished, cb); } } } function afterWrite(stream, state, finished, cb) { if (!finished) onwriteDrain(stream, state); state.pendingcb--; cb(); finishMaybe(stream, state); } // Must force callback to be called on nextTick, so that we don't // emit 'drain' before the write() consumer gets the 'false' return // value, and has a chance to attach a 'drain' listener. function onwriteDrain(stream, state) { if (state.length === 0 && state.needDrain) { state.needDrain = false; stream.emit('drain'); } } // if there's something in the buffer waiting, then process it function clearBuffer(stream, state) { state.bufferProcessing = true; var entry = state.bufferedRequest; if (stream._writev && entry && entry.next) { // Fast case, write everything using _writev() var l = state.bufferedRequestCount; var buffer = new Array(l); var holder = state.corkedRequestsFree; holder.entry = entry; var count = 0; var allBuffers = true; while (entry) { buffer[count] = entry; if (!entry.isBuf) allBuffers = false; entry = entry.next; count += 1; } buffer.allBuffers = allBuffers; doWrite(stream, state, true, state.length, buffer, '', holder.finish); // doWrite is almost always async, defer these to save a bit of time // as the hot path ends with doWrite state.pendingcb++; state.lastBufferedRequest = null; if (holder.next) { state.corkedRequestsFree = holder.next; holder.next = null; } else { state.corkedRequestsFree = new CorkedRequest(state); } } else { // Slow case, write chunks one-by-one while (entry) { var chunk = entry.chunk; var encoding = entry.encoding; var cb = entry.callback; var len = state.objectMode ? 1 : chunk.length; doWrite(stream, state, false, len, chunk, encoding, cb); entry = entry.next; // if we didn't call the onwrite immediately, then // it means that we need to wait until it does. // also, that means that the chunk and cb are currently // being processed, so move the buffer counter past them. if (state.writing) { break; } } if (entry === null) state.lastBufferedRequest = null; } state.bufferedRequestCount = 0; state.bufferedRequest = entry; state.bufferProcessing = false; } Writable.prototype._write = function (chunk, encoding, cb) { cb(new Error('_write() is not implemented')); }; Writable.prototype._writev = null; Writable.prototype.end = function (chunk, encoding, cb) { var state = this._writableState; if (typeof chunk === 'function') { cb = chunk; chunk = null; encoding = null; } else if (typeof encoding === 'function') { cb = encoding; encoding = null; } if (chunk !== null && chunk !== undefined) this.write(chunk, encoding); // .end() fully uncorks if (state.corked) { state.corked = 1; this.uncork(); } // ignore unnecessary end() calls. if (!state.ending && !state.finished) endWritable(this, state, cb); }; function needFinish(state) { return state.ending && state.length === 0 && state.bufferedRequest === null && !state.finished && !state.writing; } function callFinal(stream, state) { stream._final(function (err) { state.pendingcb--; if (err) { stream.emit('error', err); } state.prefinished = true; stream.emit('prefinish'); finishMaybe(stream, state); }); } function prefinish(stream, state) { if (!state.prefinished && !state.finalCalled) { if (typeof stream._final === 'function') { state.pendingcb++; state.finalCalled = true; processNextTick(callFinal, stream, state); } else { state.prefinished = true; stream.emit('prefinish'); } } } function finishMaybe(stream, state) { var need = needFinish(state); if (need) { prefinish(stream, state); if (state.pendingcb === 0) { state.finished = true; stream.emit('finish'); } } return need; } function endWritable(stream, state, cb) { state.ending = true; finishMaybe(stream, state); if (cb) { if (state.finished) processNextTick(cb);else stream.once('finish', cb); } state.ended = true; stream.writable = false; } function onCorkedFinish(corkReq, state, err) { var entry = corkReq.entry; corkReq.entry = null; while (entry) { var cb = entry.callback; state.pendingcb--; cb(err); entry = entry.next; } if (state.corkedRequestsFree) { state.corkedRequestsFree.next = corkReq; } else { state.corkedRequestsFree = corkReq; } } Object.defineProperty(Writable.prototype, 'destroyed', { get: function () { if (this._writableState === undefined) { return false; } return this._writableState.destroyed; }, set: function (value) { // we ignore the value if the stream // has not been initialized yet if (!this._writableState) { return; } // backward compatibility, the user is explicitly // managing destroyed this._writableState.destroyed = value; } }); Writable.prototype.destroy = destroyImpl.destroy; Writable.prototype._undestroy = destroyImpl.undestroy; Writable.prototype._destroy = function (err, cb) { this.end(); cb(err); }; }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./_stream_duplex":232,"./internal/streams/destroy":238,"./internal/streams/stream":239,"_process":219,"core-util-is":181,"inherits":203,"process-nextick-args":218,"safe-buffer":457,"util-deprecate":258}],237:[function(require,module,exports){ 'use strict'; /**/ function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var Buffer = require('safe-buffer').Buffer; /**/ function copyBuffer(src, target, offset) { src.copy(target, offset); } module.exports = function () { function BufferList() { _classCallCheck(this, BufferList); this.head = null; this.tail = null; this.length = 0; } BufferList.prototype.push = function push(v) { var entry = { data: v, next: null }; if (this.length > 0) this.tail.next = entry;else this.head = entry; this.tail = entry; ++this.length; }; BufferList.prototype.unshift = function unshift(v) { var entry = { data: v, next: this.head }; if (this.length === 0) this.tail = entry; this.head = entry; ++this.length; }; BufferList.prototype.shift = function shift() { if (this.length === 0) return; var ret = this.head.data; if (this.length === 1) this.head = this.tail = null;else this.head = this.head.next; --this.length; return ret; }; BufferList.prototype.clear = function clear() { this.head = this.tail = null; this.length = 0; }; BufferList.prototype.join = function join(s) { if (this.length === 0) return ''; var p = this.head; var ret = '' + p.data; while (p = p.next) { ret += s + p.data; }return ret; }; BufferList.prototype.concat = function concat(n) { if (this.length === 0) return Buffer.alloc(0); if (this.length === 1) return this.head.data; var ret = Buffer.allocUnsafe(n >>> 0); var p = this.head; var i = 0; while (p) { copyBuffer(p.data, ret, i); i += p.data.length; p = p.next; } return ret; }; return BufferList; }(); },{"safe-buffer":457}],238:[function(require,module,exports){ 'use strict'; /**/ var processNextTick = require('process-nextick-args'); /**/ // undocumented cb() API, needed for core, not for public API function destroy(err, cb) { var _this = this; var readableDestroyed = this._readableState && this._readableState.destroyed; var writableDestroyed = this._writableState && this._writableState.destroyed; if (readableDestroyed || writableDestroyed) { if (cb) { cb(err); } else if (err && (!this._writableState || !this._writableState.errorEmitted)) { processNextTick(emitErrorNT, this, err); } return; } // we set destroyed to true before firing error callbacks in order // to make it re-entrance safe in case destroy() is called within callbacks if (this._readableState) { this._readableState.destroyed = true; } // if this is a duplex stream mark the writable part as destroyed as well if (this._writableState) { this._writableState.destroyed = true; } this._destroy(err || null, function (err) { if (!cb && err) { processNextTick(emitErrorNT, _this, err); if (_this._writableState) { _this._writableState.errorEmitted = true; } } else if (cb) { cb(err); } }); } function undestroy() { if (this._readableState) { this._readableState.destroyed = false; this._readableState.reading = false; this._readableState.ended = false; this._readableState.endEmitted = false; } if (this._writableState) { this._writableState.destroyed = false; this._writableState.ended = false; this._writableState.ending = false; this._writableState.finished = false; this._writableState.errorEmitted = false; } } function emitErrorNT(self, err) { self.emit('error', err); } module.exports = { destroy: destroy, undestroy: undestroy }; },{"process-nextick-args":218}],239:[function(require,module,exports){ module.exports = require('events').EventEmitter; },{"events":199}],240:[function(require,module,exports){ 'use strict'; var Buffer = require('safe-buffer').Buffer; var isEncoding = Buffer.isEncoding || function (encoding) { encoding = '' + encoding; switch (encoding && encoding.toLowerCase()) { case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': return true; default: return false; } }; function _normalizeEncoding(enc) { if (!enc) return 'utf8'; var retried; while (true) { switch (enc) { case 'utf8': case 'utf-8': return 'utf8'; case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': return 'utf16le'; case 'latin1': case 'binary': return 'latin1'; case 'base64': case 'ascii': case 'hex': return enc; default: if (retried) return; // undefined enc = ('' + enc).toLowerCase(); retried = true; } } }; // Do not cache `Buffer.isEncoding` when checking encoding names as some // modules monkey-patch it to support additional encodings function normalizeEncoding(enc) { var nenc = _normalizeEncoding(enc); if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); return nenc || enc; } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. exports.StringDecoder = StringDecoder; function StringDecoder(encoding) { this.encoding = normalizeEncoding(encoding); var nb; switch (this.encoding) { case 'utf16le': this.text = utf16Text; this.end = utf16End; nb = 4; break; case 'utf8': this.fillLast = utf8FillLast; nb = 4; break; case 'base64': this.text = base64Text; this.end = base64End; nb = 3; break; default: this.write = simpleWrite; this.end = simpleEnd; return; } this.lastNeed = 0; this.lastTotal = 0; this.lastChar = Buffer.allocUnsafe(nb); } StringDecoder.prototype.write = function (buf) { if (buf.length === 0) return ''; var r; var i; if (this.lastNeed) { r = this.fillLast(buf); if (r === undefined) return ''; i = this.lastNeed; this.lastNeed = 0; } else { i = 0; } if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); return r || ''; }; StringDecoder.prototype.end = utf8End; // Returns only complete characters in a Buffer StringDecoder.prototype.text = utf8Text; // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer StringDecoder.prototype.fillLast = function (buf) { if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); this.lastNeed -= buf.length; }; // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a // continuation byte. function utf8CheckByte(byte) { if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; return -1; } // Checks at most 3 bytes at the end of a Buffer in order to detect an // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) // needed to complete the UTF-8 character (if applicable) are returned. function utf8CheckIncomplete(self, buf, i) { var j = buf.length - 1; if (j < i) return 0; var nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 1; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) self.lastNeed = nb - 2; return nb; } if (--j < i) return 0; nb = utf8CheckByte(buf[j]); if (nb >= 0) { if (nb > 0) { if (nb === 2) nb = 0;else self.lastNeed = nb - 3; } return nb; } return 0; } // Validates as many continuation bytes for a multi-byte UTF-8 character as // needed or are available. If we see a non-continuation byte where we expect // one, we "replace" the validated continuation bytes we've seen so far with // UTF-8 replacement characters ('\ufffd'), to match v8's UTF-8 decoding // behavior. The continuation byte check is included three times in the case // where all of the continuation bytes for a character exist in the same buffer. // It is also done this way as a slight performance increase instead of using a // loop. function utf8CheckExtraBytes(self, buf, p) { if ((buf[0] & 0xC0) !== 0x80) { self.lastNeed = 0; return '\ufffd'.repeat(p); } if (self.lastNeed > 1 && buf.length > 1) { if ((buf[1] & 0xC0) !== 0x80) { self.lastNeed = 1; return '\ufffd'.repeat(p + 1); } if (self.lastNeed > 2 && buf.length > 2) { if ((buf[2] & 0xC0) !== 0x80) { self.lastNeed = 2; return '\ufffd'.repeat(p + 2); } } } } // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. function utf8FillLast(buf) { var p = this.lastTotal - this.lastNeed; var r = utf8CheckExtraBytes(this, buf, p); if (r !== undefined) return r; if (this.lastNeed <= buf.length) { buf.copy(this.lastChar, p, 0, this.lastNeed); return this.lastChar.toString(this.encoding, 0, this.lastTotal); } buf.copy(this.lastChar, p, 0, buf.length); this.lastNeed -= buf.length; } // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a // partial character, the character's bytes are buffered until the required // number of bytes are available. function utf8Text(buf, i) { var total = utf8CheckIncomplete(this, buf, i); if (!this.lastNeed) return buf.toString('utf8', i); this.lastTotal = total; var end = buf.length - (total - this.lastNeed); buf.copy(this.lastChar, 0, end); return buf.toString('utf8', i, end); } // For UTF-8, a replacement character for each buffered byte of a (partial) // character needs to be added to the output. function utf8End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + '\ufffd'.repeat(this.lastTotal - this.lastNeed); return r; } // UTF-16LE typically needs two bytes per character, but even if we have an even // number of bytes available, we need to check if we end on a leading/high // surrogate. In that case, we need to wait for the next two bytes in order to // decode the last character properly. function utf16Text(buf, i) { if ((buf.length - i) % 2 === 0) { var r = buf.toString('utf16le', i); if (r) { var c = r.charCodeAt(r.length - 1); if (c >= 0xD800 && c <= 0xDBFF) { this.lastNeed = 2; this.lastTotal = 4; this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; return r.slice(0, -1); } } return r; } this.lastNeed = 1; this.lastTotal = 2; this.lastChar[0] = buf[buf.length - 1]; return buf.toString('utf16le', i, buf.length - 1); } // For UTF-16LE we do not explicitly append special replacement characters if we // end on a partial character, we simply let v8 handle that. function utf16End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) { var end = this.lastTotal - this.lastNeed; return r + this.lastChar.toString('utf16le', 0, end); } return r; } function base64Text(buf, i) { var n = (buf.length - i) % 3; if (n === 0) return buf.toString('base64', i); this.lastNeed = 3 - n; this.lastTotal = 3; if (n === 1) { this.lastChar[0] = buf[buf.length - 1]; } else { this.lastChar[0] = buf[buf.length - 2]; this.lastChar[1] = buf[buf.length - 1]; } return buf.toString('base64', i, buf.length - n); } function base64End(buf) { var r = buf && buf.length ? this.write(buf) : ''; if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); return r; } // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) function simpleWrite(buf) { return buf.toString(this.encoding); } function simpleEnd(buf) { return buf && buf.length ? this.write(buf) : ''; } },{"safe-buffer":457}],241:[function(require,module,exports){ module.exports = require('./readable').PassThrough },{"./readable":242}],242:[function(require,module,exports){ exports = module.exports = require('./lib/_stream_readable.js'); exports.Stream = exports; exports.Readable = exports; exports.Writable = require('./lib/_stream_writable.js'); exports.Duplex = require('./lib/_stream_duplex.js'); exports.Transform = require('./lib/_stream_transform.js'); exports.PassThrough = require('./lib/_stream_passthrough.js'); },{"./lib/_stream_duplex.js":232,"./lib/_stream_passthrough.js":233,"./lib/_stream_readable.js":234,"./lib/_stream_transform.js":235,"./lib/_stream_writable.js":236}],243:[function(require,module,exports){ module.exports = require('./readable').Transform },{"./readable":242}],244:[function(require,module,exports){ module.exports = require('./lib/_stream_writable.js'); },{"./lib/_stream_writable.js":236}],245:[function(require,module,exports){ (function (Buffer){ 'use strict' var inherits = require('inherits') var HashBase = require('hash-base') function RIPEMD160 () { HashBase.call(this, 64) // state this._a = 0x67452301 this._b = 0xefcdab89 this._c = 0x98badcfe this._d = 0x10325476 this._e = 0xc3d2e1f0 } inherits(RIPEMD160, HashBase) RIPEMD160.prototype._update = function () { var m = new Array(16) for (var i = 0; i < 16; ++i) m[i] = this._block.readInt32LE(i * 4) var al = this._a var bl = this._b var cl = this._c var dl = this._d var el = this._e // Mj = 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 // K = 0x00000000 // Sj = 11, 14, 15, 12, 5, 8, 7, 9, 11, 13, 14, 15, 6, 7, 9, 8 al = fn1(al, bl, cl, dl, el, m[0], 0x00000000, 11); cl = rotl(cl, 10) el = fn1(el, al, bl, cl, dl, m[1], 0x00000000, 14); bl = rotl(bl, 10) dl = fn1(dl, el, al, bl, cl, m[2], 0x00000000, 15); al = rotl(al, 10) cl = fn1(cl, dl, el, al, bl, m[3], 0x00000000, 12); el = rotl(el, 10) bl = fn1(bl, cl, dl, el, al, m[4], 0x00000000, 5); dl = rotl(dl, 10) al = fn1(al, bl, cl, dl, el, m[5], 0x00000000, 8); cl = rotl(cl, 10) el = fn1(el, al, bl, cl, dl, m[6], 0x00000000, 7); bl = rotl(bl, 10) dl = fn1(dl, el, al, bl, cl, m[7], 0x00000000, 9); al = rotl(al, 10) cl = fn1(cl, dl, el, al, bl, m[8], 0x00000000, 11); el = rotl(el, 10) bl = fn1(bl, cl, dl, el, al, m[9], 0x00000000, 13); dl = rotl(dl, 10) al = fn1(al, bl, cl, dl, el, m[10], 0x00000000, 14); cl = rotl(cl, 10) el = fn1(el, al, bl, cl, dl, m[11], 0x00000000, 15); bl = rotl(bl, 10) dl = fn1(dl, el, al, bl, cl, m[12], 0x00000000, 6); al = rotl(al, 10) cl = fn1(cl, dl, el, al, bl, m[13], 0x00000000, 7); el = rotl(el, 10) bl = fn1(bl, cl, dl, el, al, m[14], 0x00000000, 9); dl = rotl(dl, 10) al = fn1(al, bl, cl, dl, el, m[15], 0x00000000, 8); cl = rotl(cl, 10) // Mj = 7, 4, 13, 1, 10, 6, 15, 3, 12, 0, 9, 5, 2, 14, 11, 8 // K = 0x5a827999 // Sj = 7, 6, 8, 13, 11, 9, 7, 15, 7, 12, 15, 9, 11, 7, 13, 12 el = fn2(el, al, bl, cl, dl, m[7], 0x5a827999, 7); bl = rotl(bl, 10) dl = fn2(dl, el, al, bl, cl, m[4], 0x5a827999, 6); al = rotl(al, 10) cl = fn2(cl, dl, el, al, bl, m[13], 0x5a827999, 8); el = rotl(el, 10) bl = fn2(bl, cl, dl, el, al, m[1], 0x5a827999, 13); dl = rotl(dl, 10) al = fn2(al, bl, cl, dl, el, m[10], 0x5a827999, 11); cl = rotl(cl, 10) el = fn2(el, al, bl, cl, dl, m[6], 0x5a827999, 9); bl = rotl(bl, 10) dl = fn2(dl, el, al, bl, cl, m[15], 0x5a827999, 7); al = rotl(al, 10) cl = fn2(cl, dl, el, al, bl, m[3], 0x5a827999, 15); el = rotl(el, 10) bl = fn2(bl, cl, dl, el, al, m[12], 0x5a827999, 7); dl = rotl(dl, 10) al = fn2(al, bl, cl, dl, el, m[0], 0x5a827999, 12); cl = rotl(cl, 10) el = fn2(el, al, bl, cl, dl, m[9], 0x5a827999, 15); bl = rotl(bl, 10) dl = fn2(dl, el, al, bl, cl, m[5], 0x5a827999, 9); al = rotl(al, 10) cl = fn2(cl, dl, el, al, bl, m[2], 0x5a827999, 11); el = rotl(el, 10) bl = fn2(bl, cl, dl, el, al, m[14], 0x5a827999, 7); dl = rotl(dl, 10) al = fn2(al, bl, cl, dl, el, m[11], 0x5a827999, 13); cl = rotl(cl, 10) el = fn2(el, al, bl, cl, dl, m[8], 0x5a827999, 12); bl = rotl(bl, 10) // Mj = 3, 10, 14, 4, 9, 15, 8, 1, 2, 7, 0, 6, 13, 11, 5, 12 // K = 0x6ed9eba1 // Sj = 11, 13, 6, 7, 14, 9, 13, 15, 14, 8, 13, 6, 5, 12, 7, 5 dl = fn3(dl, el, al, bl, cl, m[3], 0x6ed9eba1, 11); al = rotl(al, 10) cl = fn3(cl, dl, el, al, bl, m[10], 0x6ed9eba1, 13); el = rotl(el, 10) bl = fn3(bl, cl, dl, el, al, m[14], 0x6ed9eba1, 6); dl = rotl(dl, 10) al = fn3(al, bl, cl, dl, el, m[4], 0x6ed9eba1, 7); cl = rotl(cl, 10) el = fn3(el, al, bl, cl, dl, m[9], 0x6ed9eba1, 14); bl = rotl(bl, 10) dl = fn3(dl, el, al, bl, cl, m[15], 0x6ed9eba1, 9); al = rotl(al, 10) cl = fn3(cl, dl, el, al, bl, m[8], 0x6ed9eba1, 13); el = rotl(el, 10) bl = fn3(bl, cl, dl, el, al, m[1], 0x6ed9eba1, 15); dl = rotl(dl, 10) al = fn3(al, bl, cl, dl, el, m[2], 0x6ed9eba1, 14); cl = rotl(cl, 10) el = fn3(el, al, bl, cl, dl, m[7], 0x6ed9eba1, 8); bl = rotl(bl, 10) dl = fn3(dl, el, al, bl, cl, m[0], 0x6ed9eba1, 13); al = rotl(al, 10) cl = fn3(cl, dl, el, al, bl, m[6], 0x6ed9eba1, 6); el = rotl(el, 10) bl = fn3(bl, cl, dl, el, al, m[13], 0x6ed9eba1, 5); dl = rotl(dl, 10) al = fn3(al, bl, cl, dl, el, m[11], 0x6ed9eba1, 12); cl = rotl(cl, 10) el = fn3(el, al, bl, cl, dl, m[5], 0x6ed9eba1, 7); bl = rotl(bl, 10) dl = fn3(dl, el, al, bl, cl, m[12], 0x6ed9eba1, 5); al = rotl(al, 10) // Mj = 1, 9, 11, 10, 0, 8, 12, 4, 13, 3, 7, 15, 14, 5, 6, 2 // K = 0x8f1bbcdc // Sj = 11, 12, 14, 15, 14, 15, 9, 8, 9, 14, 5, 6, 8, 6, 5, 12 cl = fn4(cl, dl, el, al, bl, m[1], 0x8f1bbcdc, 11); el = rotl(el, 10) bl = fn4(bl, cl, dl, el, al, m[9], 0x8f1bbcdc, 12); dl = rotl(dl, 10) al = fn4(al, bl, cl, dl, el, m[11], 0x8f1bbcdc, 14); cl = rotl(cl, 10) el = fn4(el, al, bl, cl, dl, m[10], 0x8f1bbcdc, 15); bl = rotl(bl, 10) dl = fn4(dl, el, al, bl, cl, m[0], 0x8f1bbcdc, 14); al = rotl(al, 10) cl = fn4(cl, dl, el, al, bl, m[8], 0x8f1bbcdc, 15); el = rotl(el, 10) bl = fn4(bl, cl, dl, el, al, m[12], 0x8f1bbcdc, 9); dl = rotl(dl, 10) al = fn4(al, bl, cl, dl, el, m[4], 0x8f1bbcdc, 8); cl = rotl(cl, 10) el = fn4(el, al, bl, cl, dl, m[13], 0x8f1bbcdc, 9); bl = rotl(bl, 10) dl = fn4(dl, el, al, bl, cl, m[3], 0x8f1bbcdc, 14); al = rotl(al, 10) cl = fn4(cl, dl, el, al, bl, m[7], 0x8f1bbcdc, 5); el = rotl(el, 10) bl = fn4(bl, cl, dl, el, al, m[15], 0x8f1bbcdc, 6); dl = rotl(dl, 10) al = fn4(al, bl, cl, dl, el, m[14], 0x8f1bbcdc, 8); cl = rotl(cl, 10) el = fn4(el, al, bl, cl, dl, m[5], 0x8f1bbcdc, 6); bl = rotl(bl, 10) dl = fn4(dl, el, al, bl, cl, m[6], 0x8f1bbcdc, 5); al = rotl(al, 10) cl = fn4(cl, dl, el, al, bl, m[2], 0x8f1bbcdc, 12); el = rotl(el, 10) // Mj = 4, 0, 5, 9, 7, 12, 2, 10, 14, 1, 3, 8, 11, 6, 15, 13 // K = 0xa953fd4e // Sj = 9, 15, 5, 11, 6, 8, 13, 12, 5, 12, 13, 14, 11, 8, 5, 6 bl = fn5(bl, cl, dl, el, al, m[4], 0xa953fd4e, 9); dl = rotl(dl, 10) al = fn5(al, bl, cl, dl, el, m[0], 0xa953fd4e, 15); cl = rotl(cl, 10) el = fn5(el, al, bl, cl, dl, m[5], 0xa953fd4e, 5); bl = rotl(bl, 10) dl = fn5(dl, el, al, bl, cl, m[9], 0xa953fd4e, 11); al = rotl(al, 10) cl = fn5(cl, dl, el, al, bl, m[7], 0xa953fd4e, 6); el = rotl(el, 10) bl = fn5(bl, cl, dl, el, al, m[12], 0xa953fd4e, 8); dl = rotl(dl, 10) al = fn5(al, bl, cl, dl, el, m[2], 0xa953fd4e, 13); cl = rotl(cl, 10) el = fn5(el, al, bl, cl, dl, m[10], 0xa953fd4e, 12); bl = rotl(bl, 10) dl = fn5(dl, el, al, bl, cl, m[14], 0xa953fd4e, 5); al = rotl(al, 10) cl = fn5(cl, dl, el, al, bl, m[1], 0xa953fd4e, 12); el = rotl(el, 10) bl = fn5(bl, cl, dl, el, al, m[3], 0xa953fd4e, 13); dl = rotl(dl, 10) al = fn5(al, bl, cl, dl, el, m[8], 0xa953fd4e, 14); cl = rotl(cl, 10) el = fn5(el, al, bl, cl, dl, m[11], 0xa953fd4e, 11); bl = rotl(bl, 10) dl = fn5(dl, el, al, bl, cl, m[6], 0xa953fd4e, 8); al = rotl(al, 10) cl = fn5(cl, dl, el, al, bl, m[15], 0xa953fd4e, 5); el = rotl(el, 10) bl = fn5(bl, cl, dl, el, al, m[13], 0xa953fd4e, 6); dl = rotl(dl, 10) var ar = this._a var br = this._b var cr = this._c var dr = this._d var er = this._e // M'j = 5, 14, 7, 0, 9, 2, 11, 4, 13, 6, 15, 8, 1, 10, 3, 12 // K' = 0x50a28be6 // S'j = 8, 9, 9, 11, 13, 15, 15, 5, 7, 7, 8, 11, 14, 14, 12, 6 ar = fn5(ar, br, cr, dr, er, m[5], 0x50a28be6, 8); cr = rotl(cr, 10) er = fn5(er, ar, br, cr, dr, m[14], 0x50a28be6, 9); br = rotl(br, 10) dr = fn5(dr, er, ar, br, cr, m[7], 0x50a28be6, 9); ar = rotl(ar, 10) cr = fn5(cr, dr, er, ar, br, m[0], 0x50a28be6, 11); er = rotl(er, 10) br = fn5(br, cr, dr, er, ar, m[9], 0x50a28be6, 13); dr = rotl(dr, 10) ar = fn5(ar, br, cr, dr, er, m[2], 0x50a28be6, 15); cr = rotl(cr, 10) er = fn5(er, ar, br, cr, dr, m[11], 0x50a28be6, 15); br = rotl(br, 10) dr = fn5(dr, er, ar, br, cr, m[4], 0x50a28be6, 5); ar = rotl(ar, 10) cr = fn5(cr, dr, er, ar, br, m[13], 0x50a28be6, 7); er = rotl(er, 10) br = fn5(br, cr, dr, er, ar, m[6], 0x50a28be6, 7); dr = rotl(dr, 10) ar = fn5(ar, br, cr, dr, er, m[15], 0x50a28be6, 8); cr = rotl(cr, 10) er = fn5(er, ar, br, cr, dr, m[8], 0x50a28be6, 11); br = rotl(br, 10) dr = fn5(dr, er, ar, br, cr, m[1], 0x50a28be6, 14); ar = rotl(ar, 10) cr = fn5(cr, dr, er, ar, br, m[10], 0x50a28be6, 14); er = rotl(er, 10) br = fn5(br, cr, dr, er, ar, m[3], 0x50a28be6, 12); dr = rotl(dr, 10) ar = fn5(ar, br, cr, dr, er, m[12], 0x50a28be6, 6); cr = rotl(cr, 10) // M'j = 6, 11, 3, 7, 0, 13, 5, 10, 14, 15, 8, 12, 4, 9, 1, 2 // K' = 0x5c4dd124 // S'j = 9, 13, 15, 7, 12, 8, 9, 11, 7, 7, 12, 7, 6, 15, 13, 11 er = fn4(er, ar, br, cr, dr, m[6], 0x5c4dd124, 9); br = rotl(br, 10) dr = fn4(dr, er, ar, br, cr, m[11], 0x5c4dd124, 13); ar = rotl(ar, 10) cr = fn4(cr, dr, er, ar, br, m[3], 0x5c4dd124, 15); er = rotl(er, 10) br = fn4(br, cr, dr, er, ar, m[7], 0x5c4dd124, 7); dr = rotl(dr, 10) ar = fn4(ar, br, cr, dr, er, m[0], 0x5c4dd124, 12); cr = rotl(cr, 10) er = fn4(er, ar, br, cr, dr, m[13], 0x5c4dd124, 8); br = rotl(br, 10) dr = fn4(dr, er, ar, br, cr, m[5], 0x5c4dd124, 9); ar = rotl(ar, 10) cr = fn4(cr, dr, er, ar, br, m[10], 0x5c4dd124, 11); er = rotl(er, 10) br = fn4(br, cr, dr, er, ar, m[14], 0x5c4dd124, 7); dr = rotl(dr, 10) ar = fn4(ar, br, cr, dr, er, m[15], 0x5c4dd124, 7); cr = rotl(cr, 10) er = fn4(er, ar, br, cr, dr, m[8], 0x5c4dd124, 12); br = rotl(br, 10) dr = fn4(dr, er, ar, br, cr, m[12], 0x5c4dd124, 7); ar = rotl(ar, 10) cr = fn4(cr, dr, er, ar, br, m[4], 0x5c4dd124, 6); er = rotl(er, 10) br = fn4(br, cr, dr, er, ar, m[9], 0x5c4dd124, 15); dr = rotl(dr, 10) ar = fn4(ar, br, cr, dr, er, m[1], 0x5c4dd124, 13); cr = rotl(cr, 10) er = fn4(er, ar, br, cr, dr, m[2], 0x5c4dd124, 11); br = rotl(br, 10) // M'j = 15, 5, 1, 3, 7, 14, 6, 9, 11, 8, 12, 2, 10, 0, 4, 13 // K' = 0x6d703ef3 // S'j = 9, 7, 15, 11, 8, 6, 6, 14, 12, 13, 5, 14, 13, 13, 7, 5 dr = fn3(dr, er, ar, br, cr, m[15], 0x6d703ef3, 9); ar = rotl(ar, 10) cr = fn3(cr, dr, er, ar, br, m[5], 0x6d703ef3, 7); er = rotl(er, 10) br = fn3(br, cr, dr, er, ar, m[1], 0x6d703ef3, 15); dr = rotl(dr, 10) ar = fn3(ar, br, cr, dr, er, m[3], 0x6d703ef3, 11); cr = rotl(cr, 10) er = fn3(er, ar, br, cr, dr, m[7], 0x6d703ef3, 8); br = rotl(br, 10) dr = fn3(dr, er, ar, br, cr, m[14], 0x6d703ef3, 6); ar = rotl(ar, 10) cr = fn3(cr, dr, er, ar, br, m[6], 0x6d703ef3, 6); er = rotl(er, 10) br = fn3(br, cr, dr, er, ar, m[9], 0x6d703ef3, 14); dr = rotl(dr, 10) ar = fn3(ar, br, cr, dr, er, m[11], 0x6d703ef3, 12); cr = rotl(cr, 10) er = fn3(er, ar, br, cr, dr, m[8], 0x6d703ef3, 13); br = rotl(br, 10) dr = fn3(dr, er, ar, br, cr, m[12], 0x6d703ef3, 5); ar = rotl(ar, 10) cr = fn3(cr, dr, er, ar, br, m[2], 0x6d703ef3, 14); er = rotl(er, 10) br = fn3(br, cr, dr, er, ar, m[10], 0x6d703ef3, 13); dr = rotl(dr, 10) ar = fn3(ar, br, cr, dr, er, m[0], 0x6d703ef3, 13); cr = rotl(cr, 10) er = fn3(er, ar, br, cr, dr, m[4], 0x6d703ef3, 7); br = rotl(br, 10) dr = fn3(dr, er, ar, br, cr, m[13], 0x6d703ef3, 5); ar = rotl(ar, 10) // M'j = 8, 6, 4, 1, 3, 11, 15, 0, 5, 12, 2, 13, 9, 7, 10, 14 // K' = 0x7a6d76e9 // S'j = 15, 5, 8, 11, 14, 14, 6, 14, 6, 9, 12, 9, 12, 5, 15, 8 cr = fn2(cr, dr, er, ar, br, m[8], 0x7a6d76e9, 15); er = rotl(er, 10) br = fn2(br, cr, dr, er, ar, m[6], 0x7a6d76e9, 5); dr = rotl(dr, 10) ar = fn2(ar, br, cr, dr, er, m[4], 0x7a6d76e9, 8); cr = rotl(cr, 10) er = fn2(er, ar, br, cr, dr, m[1], 0x7a6d76e9, 11); br = rotl(br, 10) dr = fn2(dr, er, ar, br, cr, m[3], 0x7a6d76e9, 14); ar = rotl(ar, 10) cr = fn2(cr, dr, er, ar, br, m[11], 0x7a6d76e9, 14); er = rotl(er, 10) br = fn2(br, cr, dr, er, ar, m[15], 0x7a6d76e9, 6); dr = rotl(dr, 10) ar = fn2(ar, br, cr, dr, er, m[0], 0x7a6d76e9, 14); cr = rotl(cr, 10) er = fn2(er, ar, br, cr, dr, m[5], 0x7a6d76e9, 6); br = rotl(br, 10) dr = fn2(dr, er, ar, br, cr, m[12], 0x7a6d76e9, 9); ar = rotl(ar, 10) cr = fn2(cr, dr, er, ar, br, m[2], 0x7a6d76e9, 12); er = rotl(er, 10) br = fn2(br, cr, dr, er, ar, m[13], 0x7a6d76e9, 9); dr = rotl(dr, 10) ar = fn2(ar, br, cr, dr, er, m[9], 0x7a6d76e9, 12); cr = rotl(cr, 10) er = fn2(er, ar, br, cr, dr, m[7], 0x7a6d76e9, 5); br = rotl(br, 10) dr = fn2(dr, er, ar, br, cr, m[10], 0x7a6d76e9, 15); ar = rotl(ar, 10) cr = fn2(cr, dr, er, ar, br, m[14], 0x7a6d76e9, 8); er = rotl(er, 10) // M'j = 12, 15, 10, 4, 1, 5, 8, 7, 6, 2, 13, 14, 0, 3, 9, 11 // K' = 0x00000000 // S'j = 8, 5, 12, 9, 12, 5, 14, 6, 8, 13, 6, 5, 15, 13, 11, 11 br = fn1(br, cr, dr, er, ar, m[12], 0x00000000, 8); dr = rotl(dr, 10) ar = fn1(ar, br, cr, dr, er, m[15], 0x00000000, 5); cr = rotl(cr, 10) er = fn1(er, ar, br, cr, dr, m[10], 0x00000000, 12); br = rotl(br, 10) dr = fn1(dr, er, ar, br, cr, m[4], 0x00000000, 9); ar = rotl(ar, 10) cr = fn1(cr, dr, er, ar, br, m[1], 0x00000000, 12); er = rotl(er, 10) br = fn1(br, cr, dr, er, ar, m[5], 0x00000000, 5); dr = rotl(dr, 10) ar = fn1(ar, br, cr, dr, er, m[8], 0x00000000, 14); cr = rotl(cr, 10) er = fn1(er, ar, br, cr, dr, m[7], 0x00000000, 6); br = rotl(br, 10) dr = fn1(dr, er, ar, br, cr, m[6], 0x00000000, 8); ar = rotl(ar, 10) cr = fn1(cr, dr, er, ar, br, m[2], 0x00000000, 13); er = rotl(er, 10) br = fn1(br, cr, dr, er, ar, m[13], 0x00000000, 6); dr = rotl(dr, 10) ar = fn1(ar, br, cr, dr, er, m[14], 0x00000000, 5); cr = rotl(cr, 10) er = fn1(er, ar, br, cr, dr, m[0], 0x00000000, 15); br = rotl(br, 10) dr = fn1(dr, er, ar, br, cr, m[3], 0x00000000, 13); ar = rotl(ar, 10) cr = fn1(cr, dr, er, ar, br, m[9], 0x00000000, 11); er = rotl(er, 10) br = fn1(br, cr, dr, er, ar, m[11], 0x00000000, 11); dr = rotl(dr, 10) // change state var t = (this._b + cl + dr) | 0 this._b = (this._c + dl + er) | 0 this._c = (this._d + el + ar) | 0 this._d = (this._e + al + br) | 0 this._e = (this._a + bl + cr) | 0 this._a = t } RIPEMD160.prototype._digest = function () { // create padding and handle blocks this._block[this._blockOffset++] = 0x80 if (this._blockOffset > 56) { this._block.fill(0, this._blockOffset, 64) this._update() this._blockOffset = 0 } this._block.fill(0, this._blockOffset, 56) this._block.writeUInt32LE(this._length[0], 56) this._block.writeUInt32LE(this._length[1], 60) this._update() // produce result var buffer = new Buffer(20) buffer.writeInt32LE(this._a, 0) buffer.writeInt32LE(this._b, 4) buffer.writeInt32LE(this._c, 8) buffer.writeInt32LE(this._d, 12) buffer.writeInt32LE(this._e, 16) return buffer } function rotl (x, n) { return (x << n) | (x >>> (32 - n)) } function fn1 (a, b, c, d, e, m, k, s) { return (rotl((a + (b ^ c ^ d) + m + k) | 0, s) + e) | 0 } function fn2 (a, b, c, d, e, m, k, s) { return (rotl((a + ((b & c) | ((~b) & d)) + m + k) | 0, s) + e) | 0 } function fn3 (a, b, c, d, e, m, k, s) { return (rotl((a + ((b | (~c)) ^ d) + m + k) | 0, s) + e) | 0 } function fn4 (a, b, c, d, e, m, k, s) { return (rotl((a + ((b & d) | (c & (~d))) + m + k) | 0, s) + e) | 0 } function fn5 (a, b, c, d, e, m, k, s) { return (rotl((a + (b ^ (c | (~d))) + m + k) | 0, s) + e) | 0 } module.exports = RIPEMD160 }).call(this,require("buffer").Buffer) },{"buffer":179,"hash-base":349,"inherits":203}],246:[function(require,module,exports){ var Buffer = require('safe-buffer').Buffer // prototype class for hash functions function Hash (blockSize, finalSize) { this._block = Buffer.alloc(blockSize) this._finalSize = finalSize this._blockSize = blockSize this._len = 0 } Hash.prototype.update = function (data, enc) { if (typeof data === 'string') { enc = enc || 'utf8' data = Buffer.from(data, enc) } var block = this._block var blockSize = this._blockSize var length = data.length var accum = this._len for (var offset = 0; offset < length;) { var assigned = accum % blockSize var remainder = Math.min(length - offset, blockSize - assigned) for (var i = 0; i < remainder; i++) { block[assigned + i] = data[offset + i] } accum += remainder offset += remainder if ((accum % blockSize) === 0) { this._update(block) } } this._len += length return this } Hash.prototype.digest = function (enc) { var rem = this._len % this._blockSize this._block[rem] = 0x80 // zero (rem + 1) trailing bits, where (rem + 1) is the smallest // non-negative solution to the equation (length + 1 + (rem + 1)) === finalSize mod blockSize this._block.fill(0, rem + 1) if (rem >= this._finalSize) { this._update(this._block) this._block.fill(0) } var bits = this._len * 8 // uint32 if (bits <= 0xffffffff) { this._block.writeUInt32BE(bits, this._blockSize - 4) // uint64 } else { var lowBits = bits & 0xffffffff var highBits = (bits - lowBits) / 0x100000000 this._block.writeUInt32BE(highBits, this._blockSize - 8) this._block.writeUInt32BE(lowBits, this._blockSize - 4) } this._update(this._block) var hash = this._hash() return enc ? hash.toString(enc) : hash } Hash.prototype._update = function () { throw new Error('_update must be implemented by subclass') } module.exports = Hash },{"safe-buffer":457}],247:[function(require,module,exports){ var exports = module.exports = function SHA (algorithm) { algorithm = algorithm.toLowerCase() var Algorithm = exports[algorithm] if (!Algorithm) throw new Error(algorithm + ' is not supported (we accept pull requests)') return new Algorithm() } exports.sha = require('./sha') exports.sha1 = require('./sha1') exports.sha224 = require('./sha224') exports.sha256 = require('./sha256') exports.sha384 = require('./sha384') exports.sha512 = require('./sha512') },{"./sha":248,"./sha1":249,"./sha224":250,"./sha256":251,"./sha384":252,"./sha512":253}],248:[function(require,module,exports){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-0, as defined * in FIPS PUB 180-1 * This source code is derived from sha1.js of the same repository. * The difference between SHA-0 and SHA-1 is just a bitwise rotate left * operation was added. */ var inherits = require('inherits') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var K = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 ] var W = new Array(80) function Sha () { this.init() this._w = W Hash.call(this, 64, 56) } inherits(Sha, Hash) Sha.prototype.init = function () { this._a = 0x67452301 this._b = 0xefcdab89 this._c = 0x98badcfe this._d = 0x10325476 this._e = 0xc3d2e1f0 return this } function rotl5 (num) { return (num << 5) | (num >>> 27) } function rotl30 (num) { return (num << 30) | (num >>> 2) } function ft (s, b, c, d) { if (s === 0) return (b & c) | ((~b) & d) if (s === 2) return (b & c) | (b & d) | (c & d) return b ^ c ^ d } Sha.prototype._update = function (M) { var W = this._w var a = this._a | 0 var b = this._b | 0 var c = this._c | 0 var d = this._d | 0 var e = this._e | 0 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) for (; i < 80; ++i) W[i] = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16] for (var j = 0; j < 80; ++j) { var s = ~~(j / 20) var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 e = d d = c c = rotl30(b) b = a a = t } this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 this._d = (d + this._d) | 0 this._e = (e + this._e) | 0 } Sha.prototype._hash = function () { var H = Buffer.allocUnsafe(20) H.writeInt32BE(this._a | 0, 0) H.writeInt32BE(this._b | 0, 4) H.writeInt32BE(this._c | 0, 8) H.writeInt32BE(this._d | 0, 12) H.writeInt32BE(this._e | 0, 16) return H } module.exports = Sha },{"./hash":246,"inherits":203,"safe-buffer":457}],249:[function(require,module,exports){ /* * A JavaScript implementation of the Secure Hash Algorithm, SHA-1, as defined * in FIPS PUB 180-1 * Version 2.1a Copyright Paul Johnston 2000 - 2002. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * Distributed under the BSD License * See http://pajhome.org.uk/crypt/md5 for details. */ var inherits = require('inherits') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var K = [ 0x5a827999, 0x6ed9eba1, 0x8f1bbcdc | 0, 0xca62c1d6 | 0 ] var W = new Array(80) function Sha1 () { this.init() this._w = W Hash.call(this, 64, 56) } inherits(Sha1, Hash) Sha1.prototype.init = function () { this._a = 0x67452301 this._b = 0xefcdab89 this._c = 0x98badcfe this._d = 0x10325476 this._e = 0xc3d2e1f0 return this } function rotl1 (num) { return (num << 1) | (num >>> 31) } function rotl5 (num) { return (num << 5) | (num >>> 27) } function rotl30 (num) { return (num << 30) | (num >>> 2) } function ft (s, b, c, d) { if (s === 0) return (b & c) | ((~b) & d) if (s === 2) return (b & c) | (b & d) | (c & d) return b ^ c ^ d } Sha1.prototype._update = function (M) { var W = this._w var a = this._a | 0 var b = this._b | 0 var c = this._c | 0 var d = this._d | 0 var e = this._e | 0 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) for (; i < 80; ++i) W[i] = rotl1(W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16]) for (var j = 0; j < 80; ++j) { var s = ~~(j / 20) var t = (rotl5(a) + ft(s, b, c, d) + e + W[j] + K[s]) | 0 e = d d = c c = rotl30(b) b = a a = t } this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 this._d = (d + this._d) | 0 this._e = (e + this._e) | 0 } Sha1.prototype._hash = function () { var H = Buffer.allocUnsafe(20) H.writeInt32BE(this._a | 0, 0) H.writeInt32BE(this._b | 0, 4) H.writeInt32BE(this._c | 0, 8) H.writeInt32BE(this._d | 0, 12) H.writeInt32BE(this._e | 0, 16) return H } module.exports = Sha1 },{"./hash":246,"inherits":203,"safe-buffer":457}],250:[function(require,module,exports){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * */ var inherits = require('inherits') var Sha256 = require('./sha256') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var W = new Array(64) function Sha224 () { this.init() this._w = W // new Array(64) Hash.call(this, 64, 56) } inherits(Sha224, Sha256) Sha224.prototype.init = function () { this._a = 0xc1059ed8 this._b = 0x367cd507 this._c = 0x3070dd17 this._d = 0xf70e5939 this._e = 0xffc00b31 this._f = 0x68581511 this._g = 0x64f98fa7 this._h = 0xbefa4fa4 return this } Sha224.prototype._hash = function () { var H = Buffer.allocUnsafe(28) H.writeInt32BE(this._a, 0) H.writeInt32BE(this._b, 4) H.writeInt32BE(this._c, 8) H.writeInt32BE(this._d, 12) H.writeInt32BE(this._e, 16) H.writeInt32BE(this._f, 20) H.writeInt32BE(this._g, 24) return H } module.exports = Sha224 },{"./hash":246,"./sha256":251,"inherits":203,"safe-buffer":457}],251:[function(require,module,exports){ /** * A JavaScript implementation of the Secure Hash Algorithm, SHA-256, as defined * in FIPS 180-2 * Version 2.2-beta Copyright Angel Marin, Paul Johnston 2000 - 2009. * Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet * */ var inherits = require('inherits') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var 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 W = new Array(64) function Sha256 () { this.init() this._w = W // new Array(64) Hash.call(this, 64, 56) } inherits(Sha256, Hash) Sha256.prototype.init = function () { this._a = 0x6a09e667 this._b = 0xbb67ae85 this._c = 0x3c6ef372 this._d = 0xa54ff53a this._e = 0x510e527f this._f = 0x9b05688c this._g = 0x1f83d9ab this._h = 0x5be0cd19 return this } function ch (x, y, z) { return z ^ (x & (y ^ z)) } function maj (x, y, z) { return (x & y) | (z & (x | y)) } function sigma0 (x) { return (x >>> 2 | x << 30) ^ (x >>> 13 | x << 19) ^ (x >>> 22 | x << 10) } function sigma1 (x) { return (x >>> 6 | x << 26) ^ (x >>> 11 | x << 21) ^ (x >>> 25 | x << 7) } function gamma0 (x) { return (x >>> 7 | x << 25) ^ (x >>> 18 | x << 14) ^ (x >>> 3) } function gamma1 (x) { return (x >>> 17 | x << 15) ^ (x >>> 19 | x << 13) ^ (x >>> 10) } Sha256.prototype._update = function (M) { var W = this._w var a = this._a | 0 var b = this._b | 0 var c = this._c | 0 var d = this._d | 0 var e = this._e | 0 var f = this._f | 0 var g = this._g | 0 var h = this._h | 0 for (var i = 0; i < 16; ++i) W[i] = M.readInt32BE(i * 4) for (; i < 64; ++i) W[i] = (gamma1(W[i - 2]) + W[i - 7] + gamma0(W[i - 15]) + W[i - 16]) | 0 for (var j = 0; j < 64; ++j) { var T1 = (h + sigma1(e) + ch(e, f, g) + K[j] + W[j]) | 0 var T2 = (sigma0(a) + maj(a, b, c)) | 0 h = g g = f f = e e = (d + T1) | 0 d = c c = b b = a a = (T1 + T2) | 0 } this._a = (a + this._a) | 0 this._b = (b + this._b) | 0 this._c = (c + this._c) | 0 this._d = (d + this._d) | 0 this._e = (e + this._e) | 0 this._f = (f + this._f) | 0 this._g = (g + this._g) | 0 this._h = (h + this._h) | 0 } Sha256.prototype._hash = function () { var H = Buffer.allocUnsafe(32) H.writeInt32BE(this._a, 0) H.writeInt32BE(this._b, 4) H.writeInt32BE(this._c, 8) H.writeInt32BE(this._d, 12) H.writeInt32BE(this._e, 16) H.writeInt32BE(this._f, 20) H.writeInt32BE(this._g, 24) H.writeInt32BE(this._h, 28) return H } module.exports = Sha256 },{"./hash":246,"inherits":203,"safe-buffer":457}],252:[function(require,module,exports){ var inherits = require('inherits') var SHA512 = require('./sha512') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var W = new Array(160) function Sha384 () { this.init() this._w = W Hash.call(this, 128, 112) } inherits(Sha384, SHA512) Sha384.prototype.init = function () { this._ah = 0xcbbb9d5d this._bh = 0x629a292a this._ch = 0x9159015a this._dh = 0x152fecd8 this._eh = 0x67332667 this._fh = 0x8eb44a87 this._gh = 0xdb0c2e0d this._hh = 0x47b5481d this._al = 0xc1059ed8 this._bl = 0x367cd507 this._cl = 0x3070dd17 this._dl = 0xf70e5939 this._el = 0xffc00b31 this._fl = 0x68581511 this._gl = 0x64f98fa7 this._hl = 0xbefa4fa4 return this } Sha384.prototype._hash = function () { var H = Buffer.allocUnsafe(48) function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset) H.writeInt32BE(l, offset + 4) } writeInt64BE(this._ah, this._al, 0) writeInt64BE(this._bh, this._bl, 8) writeInt64BE(this._ch, this._cl, 16) writeInt64BE(this._dh, this._dl, 24) writeInt64BE(this._eh, this._el, 32) writeInt64BE(this._fh, this._fl, 40) return H } module.exports = Sha384 },{"./hash":246,"./sha512":253,"inherits":203,"safe-buffer":457}],253:[function(require,module,exports){ var inherits = require('inherits') var Hash = require('./hash') var Buffer = require('safe-buffer').Buffer var K = [ 0x428a2f98, 0xd728ae22, 0x71374491, 0x23ef65cd, 0xb5c0fbcf, 0xec4d3b2f, 0xe9b5dba5, 0x8189dbbc, 0x3956c25b, 0xf348b538, 0x59f111f1, 0xb605d019, 0x923f82a4, 0xaf194f9b, 0xab1c5ed5, 0xda6d8118, 0xd807aa98, 0xa3030242, 0x12835b01, 0x45706fbe, 0x243185be, 0x4ee4b28c, 0x550c7dc3, 0xd5ffb4e2, 0x72be5d74, 0xf27b896f, 0x80deb1fe, 0x3b1696b1, 0x9bdc06a7, 0x25c71235, 0xc19bf174, 0xcf692694, 0xe49b69c1, 0x9ef14ad2, 0xefbe4786, 0x384f25e3, 0x0fc19dc6, 0x8b8cd5b5, 0x240ca1cc, 0x77ac9c65, 0x2de92c6f, 0x592b0275, 0x4a7484aa, 0x6ea6e483, 0x5cb0a9dc, 0xbd41fbd4, 0x76f988da, 0x831153b5, 0x983e5152, 0xee66dfab, 0xa831c66d, 0x2db43210, 0xb00327c8, 0x98fb213f, 0xbf597fc7, 0xbeef0ee4, 0xc6e00bf3, 0x3da88fc2, 0xd5a79147, 0x930aa725, 0x06ca6351, 0xe003826f, 0x14292967, 0x0a0e6e70, 0x27b70a85, 0x46d22ffc, 0x2e1b2138, 0x5c26c926, 0x4d2c6dfc, 0x5ac42aed, 0x53380d13, 0x9d95b3df, 0x650a7354, 0x8baf63de, 0x766a0abb, 0x3c77b2a8, 0x81c2c92e, 0x47edaee6, 0x92722c85, 0x1482353b, 0xa2bfe8a1, 0x4cf10364, 0xa81a664b, 0xbc423001, 0xc24b8b70, 0xd0f89791, 0xc76c51a3, 0x0654be30, 0xd192e819, 0xd6ef5218, 0xd6990624, 0x5565a910, 0xf40e3585, 0x5771202a, 0x106aa070, 0x32bbd1b8, 0x19a4c116, 0xb8d2d0c8, 0x1e376c08, 0x5141ab53, 0x2748774c, 0xdf8eeb99, 0x34b0bcb5, 0xe19b48a8, 0x391c0cb3, 0xc5c95a63, 0x4ed8aa4a, 0xe3418acb, 0x5b9cca4f, 0x7763e373, 0x682e6ff3, 0xd6b2b8a3, 0x748f82ee, 0x5defb2fc, 0x78a5636f, 0x43172f60, 0x84c87814, 0xa1f0ab72, 0x8cc70208, 0x1a6439ec, 0x90befffa, 0x23631e28, 0xa4506ceb, 0xde82bde9, 0xbef9a3f7, 0xb2c67915, 0xc67178f2, 0xe372532b, 0xca273ece, 0xea26619c, 0xd186b8c7, 0x21c0c207, 0xeada7dd6, 0xcde0eb1e, 0xf57d4f7f, 0xee6ed178, 0x06f067aa, 0x72176fba, 0x0a637dc5, 0xa2c898a6, 0x113f9804, 0xbef90dae, 0x1b710b35, 0x131c471b, 0x28db77f5, 0x23047d84, 0x32caab7b, 0x40c72493, 0x3c9ebe0a, 0x15c9bebc, 0x431d67c4, 0x9c100d4c, 0x4cc5d4be, 0xcb3e42b6, 0x597f299c, 0xfc657e2a, 0x5fcb6fab, 0x3ad6faec, 0x6c44198c, 0x4a475817 ] var W = new Array(160) function Sha512 () { this.init() this._w = W Hash.call(this, 128, 112) } inherits(Sha512, Hash) Sha512.prototype.init = function () { this._ah = 0x6a09e667 this._bh = 0xbb67ae85 this._ch = 0x3c6ef372 this._dh = 0xa54ff53a this._eh = 0x510e527f this._fh = 0x9b05688c this._gh = 0x1f83d9ab this._hh = 0x5be0cd19 this._al = 0xf3bcc908 this._bl = 0x84caa73b this._cl = 0xfe94f82b this._dl = 0x5f1d36f1 this._el = 0xade682d1 this._fl = 0x2b3e6c1f this._gl = 0xfb41bd6b this._hl = 0x137e2179 return this } function Ch (x, y, z) { return z ^ (x & (y ^ z)) } function maj (x, y, z) { return (x & y) | (z & (x | y)) } function sigma0 (x, xl) { return (x >>> 28 | xl << 4) ^ (xl >>> 2 | x << 30) ^ (xl >>> 7 | x << 25) } function sigma1 (x, xl) { return (x >>> 14 | xl << 18) ^ (x >>> 18 | xl << 14) ^ (xl >>> 9 | x << 23) } function Gamma0 (x, xl) { return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7) } function Gamma0l (x, xl) { return (x >>> 1 | xl << 31) ^ (x >>> 8 | xl << 24) ^ (x >>> 7 | xl << 25) } function Gamma1 (x, xl) { return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6) } function Gamma1l (x, xl) { return (x >>> 19 | xl << 13) ^ (xl >>> 29 | x << 3) ^ (x >>> 6 | xl << 26) } function getCarry (a, b) { return (a >>> 0) < (b >>> 0) ? 1 : 0 } Sha512.prototype._update = function (M) { var W = this._w var ah = this._ah | 0 var bh = this._bh | 0 var ch = this._ch | 0 var dh = this._dh | 0 var eh = this._eh | 0 var fh = this._fh | 0 var gh = this._gh | 0 var hh = this._hh | 0 var al = this._al | 0 var bl = this._bl | 0 var cl = this._cl | 0 var dl = this._dl | 0 var el = this._el | 0 var fl = this._fl | 0 var gl = this._gl | 0 var hl = this._hl | 0 for (var i = 0; i < 32; i += 2) { W[i] = M.readInt32BE(i * 4) W[i + 1] = M.readInt32BE(i * 4 + 4) } for (; i < 160; i += 2) { var xh = W[i - 15 * 2] var xl = W[i - 15 * 2 + 1] var gamma0 = Gamma0(xh, xl) var gamma0l = Gamma0l(xl, xh) xh = W[i - 2 * 2] xl = W[i - 2 * 2 + 1] var gamma1 = Gamma1(xh, xl) var gamma1l = Gamma1l(xl, xh) // W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16] var Wi7h = W[i - 7 * 2] var Wi7l = W[i - 7 * 2 + 1] var Wi16h = W[i - 16 * 2] var Wi16l = W[i - 16 * 2 + 1] var Wil = (gamma0l + Wi7l) | 0 var Wih = (gamma0 + Wi7h + getCarry(Wil, gamma0l)) | 0 Wil = (Wil + gamma1l) | 0 Wih = (Wih + gamma1 + getCarry(Wil, gamma1l)) | 0 Wil = (Wil + Wi16l) | 0 Wih = (Wih + Wi16h + getCarry(Wil, Wi16l)) | 0 W[i] = Wih W[i + 1] = Wil } for (var j = 0; j < 160; j += 2) { Wih = W[j] Wil = W[j + 1] var majh = maj(ah, bh, ch) var majl = maj(al, bl, cl) var sigma0h = sigma0(ah, al) var sigma0l = sigma0(al, ah) var sigma1h = sigma1(eh, el) var sigma1l = sigma1(el, eh) // t1 = h + sigma1 + ch + K[j] + W[j] var Kih = K[j] var Kil = K[j + 1] var chh = Ch(eh, fh, gh) var chl = Ch(el, fl, gl) var t1l = (hl + sigma1l) | 0 var t1h = (hh + sigma1h + getCarry(t1l, hl)) | 0 t1l = (t1l + chl) | 0 t1h = (t1h + chh + getCarry(t1l, chl)) | 0 t1l = (t1l + Kil) | 0 t1h = (t1h + Kih + getCarry(t1l, Kil)) | 0 t1l = (t1l + Wil) | 0 t1h = (t1h + Wih + getCarry(t1l, Wil)) | 0 // t2 = sigma0 + maj var t2l = (sigma0l + majl) | 0 var t2h = (sigma0h + majh + getCarry(t2l, sigma0l)) | 0 hh = gh hl = gl gh = fh gl = fl fh = eh fl = el el = (dl + t1l) | 0 eh = (dh + t1h + getCarry(el, dl)) | 0 dh = ch dl = cl ch = bh cl = bl bh = ah bl = al al = (t1l + t2l) | 0 ah = (t1h + t2h + getCarry(al, t1l)) | 0 } this._al = (this._al + al) | 0 this._bl = (this._bl + bl) | 0 this._cl = (this._cl + cl) | 0 this._dl = (this._dl + dl) | 0 this._el = (this._el + el) | 0 this._fl = (this._fl + fl) | 0 this._gl = (this._gl + gl) | 0 this._hl = (this._hl + hl) | 0 this._ah = (this._ah + ah + getCarry(this._al, al)) | 0 this._bh = (this._bh + bh + getCarry(this._bl, bl)) | 0 this._ch = (this._ch + ch + getCarry(this._cl, cl)) | 0 this._dh = (this._dh + dh + getCarry(this._dl, dl)) | 0 this._eh = (this._eh + eh + getCarry(this._el, el)) | 0 this._fh = (this._fh + fh + getCarry(this._fl, fl)) | 0 this._gh = (this._gh + gh + getCarry(this._gl, gl)) | 0 this._hh = (this._hh + hh + getCarry(this._hl, hl)) | 0 } Sha512.prototype._hash = function () { var H = Buffer.allocUnsafe(64) function writeInt64BE (h, l, offset) { H.writeInt32BE(h, offset) H.writeInt32BE(l, offset + 4) } writeInt64BE(this._ah, this._al, 0) writeInt64BE(this._bh, this._bl, 8) writeInt64BE(this._ch, this._cl, 16) writeInt64BE(this._dh, this._dl, 24) writeInt64BE(this._eh, this._el, 32) writeInt64BE(this._fh, this._fl, 40) writeInt64BE(this._gh, this._gl, 48) writeInt64BE(this._hh, this._hl, 56) return H } module.exports = Sha512 },{"./hash":246,"inherits":203,"safe-buffer":457}],254:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. module.exports = Stream; var EE = require('events').EventEmitter; var inherits = require('inherits'); inherits(Stream, EE); Stream.Readable = require('readable-stream/readable.js'); Stream.Writable = require('readable-stream/writable.js'); Stream.Duplex = require('readable-stream/duplex.js'); Stream.Transform = require('readable-stream/transform.js'); Stream.PassThrough = require('readable-stream/passthrough.js'); // Backwards-compat with node 0.4.x Stream.Stream = Stream; // old-style streams. Note that the pipe method (the only relevant // part of this class) is overridden in the Readable class. function Stream() { EE.call(this); } Stream.prototype.pipe = function(dest, options) { var source = this; function ondata(chunk) { if (dest.writable) { if (false === dest.write(chunk) && source.pause) { source.pause(); } } } source.on('data', ondata); function ondrain() { if (source.readable && source.resume) { source.resume(); } } dest.on('drain', ondrain); // If the 'end' option is not supplied, dest.end() will be called when // source gets the 'end' or 'close' events. Only dest.end() once. if (!dest._isStdio && (!options || options.end !== false)) { source.on('end', onend); source.on('close', onclose); } var didOnEnd = false; function onend() { if (didOnEnd) return; didOnEnd = true; dest.end(); } function onclose() { if (didOnEnd) return; didOnEnd = true; if (typeof dest.destroy === 'function') dest.destroy(); } // don't leave dangling pipes when there are errors. function onerror(er) { cleanup(); if (EE.listenerCount(this, 'error') === 0) { throw er; // Unhandled stream error in pipe. } } source.on('error', onerror); dest.on('error', onerror); // remove all the event listeners that were added. function cleanup() { source.removeListener('data', ondata); dest.removeListener('drain', ondrain); source.removeListener('end', onend); source.removeListener('close', onclose); source.removeListener('error', onerror); dest.removeListener('error', onerror); source.removeListener('end', cleanup); source.removeListener('close', cleanup); dest.removeListener('close', cleanup); } source.on('end', cleanup); source.on('close', cleanup); dest.on('close', cleanup); dest.emit('pipe', source); // Allow for unix-like usage: A.pipe(B).pipe(C) return dest; }; },{"events":199,"inherits":203,"readable-stream/duplex.js":231,"readable-stream/passthrough.js":241,"readable-stream/readable.js":242,"readable-stream/transform.js":243,"readable-stream/writable.js":244}],255:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var Buffer = require('buffer').Buffer; var isBufferEncoding = Buffer.isEncoding || function(encoding) { switch (encoding && encoding.toLowerCase()) { case 'hex': case 'utf8': case 'utf-8': case 'ascii': case 'binary': case 'base64': case 'ucs2': case 'ucs-2': case 'utf16le': case 'utf-16le': case 'raw': return true; default: return false; } } function assertEncoding(encoding) { if (encoding && !isBufferEncoding(encoding)) { throw new Error('Unknown encoding: ' + encoding); } } // StringDecoder provides an interface for efficiently splitting a series of // buffers into a series of JS strings without breaking apart multi-byte // characters. CESU-8 is handled as part of the UTF-8 encoding. // // @TODO Handling all encodings inside a single object makes it very difficult // to reason about this code, so it should be split up in the future. // @TODO There should be a utf8-strict encoding that rejects invalid UTF-8 code // points as used by CESU-8. var StringDecoder = exports.StringDecoder = function(encoding) { this.encoding = (encoding || 'utf8').toLowerCase().replace(/[-_]/, ''); assertEncoding(encoding); switch (this.encoding) { case 'utf8': // CESU-8 represents each of Surrogate Pair by 3-bytes this.surrogateSize = 3; break; case 'ucs2': case 'utf16le': // UTF-16 represents each of Surrogate Pair by 2-bytes this.surrogateSize = 2; this.detectIncompleteChar = utf16DetectIncompleteChar; break; case 'base64': // Base-64 stores 3 bytes in 4 chars, and pads the remainder. this.surrogateSize = 3; this.detectIncompleteChar = base64DetectIncompleteChar; break; default: this.write = passThroughWrite; return; } // Enough space to store all bytes of a single character. UTF-8 needs 4 // bytes, but CESU-8 may require up to 6 (3 bytes per surrogate). this.charBuffer = new Buffer(6); // Number of bytes received for the current incomplete multi-byte character. this.charReceived = 0; // Number of bytes expected for the current incomplete multi-byte character. this.charLength = 0; }; // write decodes the given buffer and returns it as JS string that is // guaranteed to not contain any partial multi-byte characters. Any partial // character found at the end of the buffer is buffered up, and will be // returned when calling write again with the remaining bytes. // // Note: Converting a Buffer containing an orphan surrogate to a String // currently works, but converting a String to a Buffer (via `new Buffer`, or // Buffer#write) will replace incomplete surrogates with the unicode // replacement character. See https://codereview.chromium.org/121173009/ . StringDecoder.prototype.write = function(buffer) { var charStr = ''; // if our last write ended with an incomplete multibyte character while (this.charLength) { // determine how many remaining bytes this buffer has to offer for this char var available = (buffer.length >= this.charLength - this.charReceived) ? this.charLength - this.charReceived : buffer.length; // add the new bytes to the char buffer buffer.copy(this.charBuffer, this.charReceived, 0, available); this.charReceived += available; if (this.charReceived < this.charLength) { // still not enough chars in this buffer? wait for more ... return ''; } // remove bytes belonging to the current character from the buffer buffer = buffer.slice(available, buffer.length); // get the character that was split charStr = this.charBuffer.slice(0, this.charLength).toString(this.encoding); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character var charCode = charStr.charCodeAt(charStr.length - 1); if (charCode >= 0xD800 && charCode <= 0xDBFF) { this.charLength += this.surrogateSize; charStr = ''; continue; } this.charReceived = this.charLength = 0; // if there are no more bytes in this buffer, just emit our char if (buffer.length === 0) { return charStr; } break; } // determine and set charLength / charReceived this.detectIncompleteChar(buffer); var end = buffer.length; if (this.charLength) { // buffer the incomplete character bytes we got buffer.copy(this.charBuffer, 0, buffer.length - this.charReceived, end); end -= this.charReceived; } charStr += buffer.toString(this.encoding, 0, end); var end = charStr.length - 1; var charCode = charStr.charCodeAt(end); // CESU-8: lead surrogate (D800-DBFF) is also the incomplete character if (charCode >= 0xD800 && charCode <= 0xDBFF) { var size = this.surrogateSize; this.charLength += size; this.charReceived += size; this.charBuffer.copy(this.charBuffer, size, 0, size); buffer.copy(this.charBuffer, 0, 0, size); return charStr.substring(0, end); } // or just emit the charStr return charStr; }; // detectIncompleteChar determines if there is an incomplete UTF-8 character at // the end of the given buffer. If so, it sets this.charLength to the byte // length that character, and sets this.charReceived to the number of bytes // that are available for this character. StringDecoder.prototype.detectIncompleteChar = function(buffer) { // determine how many bytes we have to check at the end of this buffer var i = (buffer.length >= 3) ? 3 : buffer.length; // Figure out if one of the last i bytes of our buffer announces an // incomplete char. for (; i > 0; i--) { var c = buffer[buffer.length - i]; // See http://en.wikipedia.org/wiki/UTF-8#Description // 110XXXXX if (i == 1 && c >> 5 == 0x06) { this.charLength = 2; break; } // 1110XXXX if (i <= 2 && c >> 4 == 0x0E) { this.charLength = 3; break; } // 11110XXX if (i <= 3 && c >> 3 == 0x1E) { this.charLength = 4; break; } } this.charReceived = i; }; StringDecoder.prototype.end = function(buffer) { var res = ''; if (buffer && buffer.length) res = this.write(buffer); if (this.charReceived) { var cr = this.charReceived; var buf = this.charBuffer; var enc = this.encoding; res += buf.slice(0, cr).toString(enc); } return res; }; function passThroughWrite(buffer) { return buffer.toString(this.encoding); } function utf16DetectIncompleteChar(buffer) { this.charReceived = buffer.length % 2; this.charLength = this.charReceived ? 2 : 0; } function base64DetectIncompleteChar(buffer) { this.charReceived = buffer.length % 3; this.charLength = this.charReceived ? 3 : 0; } },{"buffer":179}],256:[function(require,module,exports){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. 'use strict'; var punycode = require('punycode'); var util = require('./util'); exports.parse = urlParse; exports.resolve = urlResolve; exports.resolveObject = urlResolveObject; exports.format = urlFormat; exports.Url = Url; function Url() { this.protocol = null; this.slashes = null; this.auth = null; this.host = null; this.port = null; this.hostname = null; this.hash = null; this.search = null; this.query = null; this.pathname = null; this.path = null; this.href = null; } // Reference: RFC 3986, RFC 1808, RFC 2396 // define these here so at least they only have to be // compiled once on the first module load. var protocolPattern = /^([a-z0-9.+-]+:)/i, portPattern = /:[0-9]*$/, // Special case for a simple path URL simplePathPattern = /^(\/\/?(?!\/)[^\?\s]*)(\?[^\s]*)?$/, // RFC 2396: characters reserved for delimiting URLs. // We actually just auto-escape these. delims = ['<', '>', '"', '`', ' ', '\r', '\n', '\t'], // RFC 2396: characters not allowed for various reasons. unwise = ['{', '}', '|', '\\', '^', '`'].concat(delims), // Allowed by RFCs, but cause of XSS attacks. Always escape these. autoEscape = ['\''].concat(unwise), // Characters that are never ever allowed in a hostname. // Note that any invalid chars are also handled, but these // are the ones that are *expected* to be seen, so we fast-path // them. nonHostChars = ['%', '/', '?', ';', '#'].concat(autoEscape), hostEndingChars = ['/', '?', '#'], hostnameMaxLen = 255, hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, // protocols that can allow "unsafe" and "unwise" chars. unsafeProtocol = { 'javascript': true, 'javascript:': true }, // protocols that never have a hostname. hostlessProtocol = { 'javascript': true, 'javascript:': true }, // protocols that always contain a // bit. slashedProtocol = { 'http': true, 'https': true, 'ftp': true, 'gopher': true, 'file': true, 'http:': true, 'https:': true, 'ftp:': true, 'gopher:': true, 'file:': true }, querystring = require('querystring'); function urlParse(url, parseQueryString, slashesDenoteHost) { if (url && util.isObject(url) && url instanceof Url) return url; var u = new Url; u.parse(url, parseQueryString, slashesDenoteHost); return u; } Url.prototype.parse = function(url, parseQueryString, slashesDenoteHost) { if (!util.isString(url)) { throw new TypeError("Parameter 'url' must be a string, not " + typeof url); } // Copy chrome, IE, opera backslash-handling behavior. // Back slashes before the query string get converted to forward slashes // See: https://code.google.com/p/chromium/issues/detail?id=25916 var queryIndex = url.indexOf('?'), splitter = (queryIndex !== -1 && queryIndex < url.indexOf('#')) ? '?' : '#', uSplit = url.split(splitter), slashRegex = /\\/g; uSplit[0] = uSplit[0].replace(slashRegex, '/'); url = uSplit.join(splitter); var rest = url; // trim before proceeding. // This is to support parse stuff like " http://foo.com \n" rest = rest.trim(); if (!slashesDenoteHost && url.split('#').length === 1) { // Try fast path regexp var simplePath = simplePathPattern.exec(rest); if (simplePath) { this.path = rest; this.href = rest; this.pathname = simplePath[1]; if (simplePath[2]) { this.search = simplePath[2]; if (parseQueryString) { this.query = querystring.parse(this.search.substr(1)); } else { this.query = this.search.substr(1); } } else if (parseQueryString) { this.search = ''; this.query = {}; } return this; } } var proto = protocolPattern.exec(rest); if (proto) { proto = proto[0]; var lowerProto = proto.toLowerCase(); this.protocol = lowerProto; rest = rest.substr(proto.length); } // figure out if it's got a host // user@server is *always* interpreted as a hostname, and url // resolution will treat //foo/bar as host=foo,path=bar because that's // how the browser resolves relative URLs. if (slashesDenoteHost || proto || rest.match(/^\/\/[^@\/]+@[^@\/]+/)) { var slashes = rest.substr(0, 2) === '//'; if (slashes && !(proto && hostlessProtocol[proto])) { rest = rest.substr(2); this.slashes = true; } } if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { // there's a hostname. // the first instance of /, ?, ;, or # ends the host. // // If there is an @ in the hostname, then non-host chars *are* allowed // to the left of the last @ sign, unless some host-ending character // comes *before* the @-sign. // URLs are obnoxious. // // ex: // http://a@b@c/ => user:a@b host:c // http://a@b?@c => user:a host:c path:/?@c // v0.12 TODO(isaacs): This is not quite how Chrome does things. // Review our test case against browsers more comprehensively. // find the first instance of any hostEndingChars var hostEnd = -1; for (var i = 0; i < hostEndingChars.length; i++) { var hec = rest.indexOf(hostEndingChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // at this point, either we have an explicit point where the // auth portion cannot go past, or the last @ char is the decider. var auth, atSign; if (hostEnd === -1) { // atSign can be anywhere. atSign = rest.lastIndexOf('@'); } else { // atSign must be in auth portion. // http://a@b/c@d => host:b auth:a path:/c@d atSign = rest.lastIndexOf('@', hostEnd); } // Now we have a portion which is definitely the auth. // Pull that off. if (atSign !== -1) { auth = rest.slice(0, atSign); rest = rest.slice(atSign + 1); this.auth = decodeURIComponent(auth); } // the host is the remaining to the left of the first non-host char hostEnd = -1; for (var i = 0; i < nonHostChars.length; i++) { var hec = rest.indexOf(nonHostChars[i]); if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) hostEnd = hec; } // if we still have not hit it, then the entire thing is a host. if (hostEnd === -1) hostEnd = rest.length; this.host = rest.slice(0, hostEnd); rest = rest.slice(hostEnd); // pull out port. this.parseHost(); // we've indicated that there is a hostname, // so even if it's empty, it has to be present. this.hostname = this.hostname || ''; // if hostname begins with [ and ends with ] // assume that it's an IPv6 address. var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; // validate a little. if (!ipv6Hostname) { var hostparts = this.hostname.split(/\./); for (var i = 0, l = hostparts.length; i < l; i++) { var part = hostparts[i]; if (!part) continue; if (!part.match(hostnamePartPattern)) { var newpart = ''; for (var j = 0, k = part.length; j < k; j++) { if (part.charCodeAt(j) > 127) { // we replace non-ASCII char with a temporary placeholder // we need this to make sure size of hostname is not // broken by replacing non-ASCII by nothing newpart += 'x'; } else { newpart += part[j]; } } // we test again with ASCII char only if (!newpart.match(hostnamePartPattern)) { var validParts = hostparts.slice(0, i); var notHost = hostparts.slice(i + 1); var bit = part.match(hostnamePartStart); if (bit) { validParts.push(bit[1]); notHost.unshift(bit[2]); } if (notHost.length) { rest = '/' + notHost.join('.') + rest; } this.hostname = validParts.join('.'); break; } } } } if (this.hostname.length > hostnameMaxLen) { this.hostname = ''; } else { // hostnames are always lower case. this.hostname = this.hostname.toLowerCase(); } if (!ipv6Hostname) { // IDNA Support: Returns a punycoded representation of "domain". // It only converts parts of the domain name that // have non-ASCII characters, i.e. it doesn't matter if // you call it with a domain that already is ASCII-only. this.hostname = punycode.toASCII(this.hostname); } var p = this.port ? ':' + this.port : ''; var h = this.hostname || ''; this.host = h + p; this.href += this.host; // strip [ and ] from the hostname // the host field still retains them, though if (ipv6Hostname) { this.hostname = this.hostname.substr(1, this.hostname.length - 2); if (rest[0] !== '/') { rest = '/' + rest; } } } // now rest is set to the post-host stuff. // chop off any delim chars. if (!unsafeProtocol[lowerProto]) { // First, make 100% sure that any "autoEscape" chars get // escaped, even if encodeURIComponent doesn't think they // need to be. for (var i = 0, l = autoEscape.length; i < l; i++) { var ae = autoEscape[i]; if (rest.indexOf(ae) === -1) continue; var esc = encodeURIComponent(ae); if (esc === ae) { esc = escape(ae); } rest = rest.split(ae).join(esc); } } // chop off from the tail first. var hash = rest.indexOf('#'); if (hash !== -1) { // got a fragment string. this.hash = rest.substr(hash); rest = rest.slice(0, hash); } var qm = rest.indexOf('?'); if (qm !== -1) { this.search = rest.substr(qm); this.query = rest.substr(qm + 1); if (parseQueryString) { this.query = querystring.parse(this.query); } rest = rest.slice(0, qm); } else if (parseQueryString) { // no query string, but parseQueryString still requested this.search = ''; this.query = {}; } if (rest) this.pathname = rest; if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { this.pathname = '/'; } //to support http.request if (this.pathname || this.search) { var p = this.pathname || ''; var s = this.search || ''; this.path = p + s; } // finally, reconstruct the href based on what has been validated. this.href = this.format(); return this; }; // format a parsed object into a url string function urlFormat(obj) { // ensure it's an object, and not a string url. // If it's an obj, this is a no-op. // this way, you can call url_format() on strings // to clean up potentially wonky urls. if (util.isString(obj)) obj = urlParse(obj); if (!(obj instanceof Url)) return Url.prototype.format.call(obj); return obj.format(); } Url.prototype.format = function() { var auth = this.auth || ''; if (auth) { auth = encodeURIComponent(auth); auth = auth.replace(/%3A/i, ':'); auth += '@'; } var protocol = this.protocol || '', pathname = this.pathname || '', hash = this.hash || '', host = false, query = ''; if (this.host) { host = auth + this.host; } else if (this.hostname) { host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); if (this.port) { host += ':' + this.port; } } if (this.query && util.isObject(this.query) && Object.keys(this.query).length) { query = querystring.stringify(this.query); } var search = this.search || (query && ('?' + query)) || ''; if (protocol && protocol.substr(-1) !== ':') protocol += ':'; // only the slashedProtocols get the //. Not mailto:, xmpp:, etc. // unless they had them to begin with. if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { host = '//' + (host || ''); if (pathname && pathname.charAt(0) !== '/') pathname = '/' + pathname; } else if (!host) { host = ''; } if (hash && hash.charAt(0) !== '#') hash = '#' + hash; if (search && search.charAt(0) !== '?') search = '?' + search; pathname = pathname.replace(/[?#]/g, function(match) { return encodeURIComponent(match); }); search = search.replace('#', '%23'); return protocol + host + pathname + search + hash; }; function urlResolve(source, relative) { return urlParse(source, false, true).resolve(relative); } Url.prototype.resolve = function(relative) { return this.resolveObject(urlParse(relative, false, true)).format(); }; function urlResolveObject(source, relative) { if (!source) return relative; return urlParse(source, false, true).resolveObject(relative); } Url.prototype.resolveObject = function(relative) { if (util.isString(relative)) { var rel = new Url(); rel.parse(relative, false, true); relative = rel; } var result = new Url(); var tkeys = Object.keys(this); for (var tk = 0; tk < tkeys.length; tk++) { var tkey = tkeys[tk]; result[tkey] = this[tkey]; } // hash is always overridden, no matter what. // even href="" will remove it. result.hash = relative.hash; // if the relative url is empty, then there's nothing left to do here. if (relative.href === '') { result.href = result.format(); return result; } // hrefs like //foo/bar always cut to the protocol. if (relative.slashes && !relative.protocol) { // take everything except the protocol from relative var rkeys = Object.keys(relative); for (var rk = 0; rk < rkeys.length; rk++) { var rkey = rkeys[rk]; if (rkey !== 'protocol') result[rkey] = relative[rkey]; } //urlParse appends trailing / to urls like http://www.example.com if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { result.path = result.pathname = '/'; } result.href = result.format(); return result; } if (relative.protocol && relative.protocol !== result.protocol) { // if it's a known url protocol, then changing // the protocol does weird things // first, if it's not file:, then we MUST have a host, // and if there was a path // to begin with, then we MUST have a path. // if it is file:, then the host is dropped, // because that's known to be hostless. // anything else is assumed to be absolute. if (!slashedProtocol[relative.protocol]) { var keys = Object.keys(relative); for (var v = 0; v < keys.length; v++) { var k = keys[v]; result[k] = relative[k]; } result.href = result.format(); return result; } result.protocol = relative.protocol; if (!relative.host && !hostlessProtocol[relative.protocol]) { var relPath = (relative.pathname || '').split('/'); while (relPath.length && !(relative.host = relPath.shift())); if (!relative.host) relative.host = ''; if (!relative.hostname) relative.hostname = ''; if (relPath[0] !== '') relPath.unshift(''); if (relPath.length < 2) relPath.unshift(''); result.pathname = relPath.join('/'); } else { result.pathname = relative.pathname; } result.search = relative.search; result.query = relative.query; result.host = relative.host || ''; result.auth = relative.auth; result.hostname = relative.hostname || relative.host; result.port = relative.port; // to support http.request if (result.pathname || result.search) { var p = result.pathname || ''; var s = result.search || ''; result.path = p + s; } result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; } var isSourceAbs = (result.pathname && result.pathname.charAt(0) === '/'), isRelAbs = ( relative.host || relative.pathname && relative.pathname.charAt(0) === '/' ), mustEndAbs = (isRelAbs || isSourceAbs || (result.host && relative.pathname)), removeAllDots = mustEndAbs, srcPath = result.pathname && result.pathname.split('/') || [], relPath = relative.pathname && relative.pathname.split('/') || [], psychotic = result.protocol && !slashedProtocol[result.protocol]; // if the url is a non-slashed url, then relative // links like ../.. should be able // to crawl up to the hostname, as well. This is strange. // result.protocol has already been set by now. // Later on, put the first path part into the host field. if (psychotic) { result.hostname = ''; result.port = null; if (result.host) { if (srcPath[0] === '') srcPath[0] = result.host; else srcPath.unshift(result.host); } result.host = ''; if (relative.protocol) { relative.hostname = null; relative.port = null; if (relative.host) { if (relPath[0] === '') relPath[0] = relative.host; else relPath.unshift(relative.host); } relative.host = null; } mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); } if (isRelAbs) { // it's absolute. result.host = (relative.host || relative.host === '') ? relative.host : result.host; result.hostname = (relative.hostname || relative.hostname === '') ? relative.hostname : result.hostname; result.search = relative.search; result.query = relative.query; srcPath = relPath; // fall through to the dot-handling below. } else if (relPath.length) { // it's relative // throw away the existing file, and take the new path instead. if (!srcPath) srcPath = []; srcPath.pop(); srcPath = srcPath.concat(relPath); result.search = relative.search; result.query = relative.query; } else if (!util.isNullOrUndefined(relative.search)) { // just pull out the search. // like href='?foo'. // Put this after the other two cases because it simplifies the booleans if (psychotic) { result.hostname = result.host = srcPath.shift(); //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } result.search = relative.search; result.query = relative.query; //to support http.request if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.href = result.format(); return result; } if (!srcPath.length) { // no path at all. easy. // we've already handled the other stuff above. result.pathname = null; //to support http.request if (result.search) { result.path = '/' + result.search; } else { result.path = null; } result.href = result.format(); return result; } // if a url ENDs in . or .., then it must get a trailing slash. // however, if it ends in anything else non-slashy, // then it must NOT get a trailing slash. var last = srcPath.slice(-1)[0]; var hasTrailingSlash = ( (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''); // strip single dots, resolve double dots to parent dir // if the path tries to go above the root, `up` ends up > 0 var up = 0; for (var i = srcPath.length; i >= 0; i--) { last = srcPath[i]; if (last === '.') { srcPath.splice(i, 1); } else if (last === '..') { srcPath.splice(i, 1); up++; } else if (up) { srcPath.splice(i, 1); up--; } } // if the path is allowed to go above the root, restore leading ..s if (!mustEndAbs && !removeAllDots) { for (; up--; up) { srcPath.unshift('..'); } } if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { srcPath.unshift(''); } if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { srcPath.push(''); } var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); // put the host back if (psychotic) { result.hostname = result.host = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; //occationaly the auth can get stuck only in host //this especially happens in cases like //url.resolveObject('mailto:local1@domain1', 'local2@domain2') var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; if (authInHost) { result.auth = authInHost.shift(); result.host = result.hostname = authInHost.shift(); } } mustEndAbs = mustEndAbs || (result.host && srcPath.length); if (mustEndAbs && !isAbsolute) { srcPath.unshift(''); } if (!srcPath.length) { result.pathname = null; result.path = null; } else { result.pathname = srcPath.join('/'); } //to support request.http if (!util.isNull(result.pathname) || !util.isNull(result.search)) { result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); } result.auth = relative.auth || result.auth; result.slashes = result.slashes || relative.slashes; result.href = result.format(); return result; }; Url.prototype.parseHost = function() { var host = this.host; var port = portPattern.exec(host); if (port) { port = port[0]; if (port !== ':') { this.port = port.substr(1); } host = host.substr(0, host.length - port.length); } if (host) this.hostname = host; }; },{"./util":257,"punycode":226,"querystring":229}],257:[function(require,module,exports){ 'use strict'; module.exports = { isString: function(arg) { return typeof(arg) === 'string'; }, isObject: function(arg) { return typeof(arg) === 'object' && arg !== null; }, isNull: function(arg) { return arg === null; }, isNullOrUndefined: function(arg) { return arg == null; } }; },{}],258:[function(require,module,exports){ (function (global){ /** * Module exports. */ module.exports = deprecate; /** * Mark that a method should not be used. * Returns a modified function which warns once by default. * * If `localStorage.noDeprecation = true` is set, then it is a no-op. * * If `localStorage.throwDeprecation = true` is set, then deprecated functions * will throw an Error when invoked. * * If `localStorage.traceDeprecation = true` is set, then deprecated functions * will invoke `console.trace()` instead of `console.error()`. * * @param {Function} fn - the function to deprecate * @param {String} msg - the string to print to the console when `fn` is invoked * @returns {Function} a new "deprecated" version of `fn` * @api public */ function deprecate (fn, msg) { if (config('noDeprecation')) { return fn; } var warned = false; function deprecated() { if (!warned) { if (config('throwDeprecation')) { throw new Error(msg); } else if (config('traceDeprecation')) { console.trace(msg); } else { console.warn(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; } /** * Checks `localStorage` for boolean values for the given `name`. * * @param {String} name * @returns {Boolean} * @api private */ function config (name) { // accessing global.localStorage can trigger a DOMException in sandboxed iframes try { if (!global.localStorage) return false; } catch (_) { return false; } var val = global.localStorage[name]; if (null == val) return false; return String(val).toLowerCase() === 'true'; } }).call(this,typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{}],259:[function(require,module,exports){ arguments[4][203][0].apply(exports,arguments) },{"dup":203}],260:[function(require,module,exports){ module.exports = function isBuffer(arg) { return arg && typeof arg === 'object' && typeof arg.copy === 'function' && typeof arg.fill === 'function' && typeof arg.readUInt8 === 'function'; } },{}],261:[function(require,module,exports){ (function (process,global){ // Copyright Joyent, Inc. and other Node contributors. // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to permit // persons to whom the Software is furnished to do so, subject to the // following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS // OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN // NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, // DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE // USE OR OTHER DEALINGS IN THE SOFTWARE. var formatRegExp = /%[sdj%]/g; exports.format = function(f) { if (!isString(f)) { var objects = []; for (var i = 0; i < arguments.length; i++) { objects.push(inspect(arguments[i])); } return objects.join(' '); } var i = 1; var args = arguments; var len = args.length; var str = String(f).replace(formatRegExp, function(x) { if (x === '%%') return '%'; if (i >= len) return x; switch (x) { case '%s': return String(args[i++]); case '%d': return Number(args[i++]); case '%j': try { return JSON.stringify(args[i++]); } catch (_) { return '[Circular]'; } default: return x; } }); for (var x = args[i]; i < len; x = args[++i]) { if (isNull(x) || !isObject(x)) { str += ' ' + x; } else { str += ' ' + inspect(x); } } return str; }; // Mark that a method should not be used. // Returns a modified function which warns once by default. // If --no-deprecation is set, then it is a no-op. exports.deprecate = function(fn, msg) { // Allow for deprecating things in the process of starting up. if (isUndefined(global.process)) { return function() { return exports.deprecate(fn, msg).apply(this, arguments); }; } if (process.noDeprecation === true) { return fn; } var warned = false; function deprecated() { if (!warned) { if (process.throwDeprecation) { throw new Error(msg); } else if (process.traceDeprecation) { console.trace(msg); } else { console.error(msg); } warned = true; } return fn.apply(this, arguments); } return deprecated; }; var debugs = {}; var debugEnviron; exports.debuglog = function(set) { if (isUndefined(debugEnviron)) debugEnviron = process.env.NODE_DEBUG || ''; set = set.toUpperCase(); if (!debugs[set]) { if (new RegExp('\\b' + set + '\\b', 'i').test(debugEnviron)) { var pid = process.pid; debugs[set] = function() { var msg = exports.format.apply(exports, arguments); console.error('%s %d: %s', set, pid, msg); }; } else { debugs[set] = function() {}; } } return debugs[set]; }; /** * Echos the value of a value. Trys to print the value out * in the best way possible given the different types. * * @param {Object} obj The object to print out. * @param {Object} opts Optional options object that alters the output. */ /* legacy: obj, showHidden, depth, colors*/ function inspect(obj, opts) { // default options var ctx = { seen: [], stylize: stylizeNoColor }; // legacy... if (arguments.length >= 3) ctx.depth = arguments[2]; if (arguments.length >= 4) ctx.colors = arguments[3]; if (isBoolean(opts)) { // legacy... ctx.showHidden = opts; } else if (opts) { // got an "options" object exports._extend(ctx, opts); } // set default options if (isUndefined(ctx.showHidden)) ctx.showHidden = false; if (isUndefined(ctx.depth)) ctx.depth = 2; if (isUndefined(ctx.colors)) ctx.colors = false; if (isUndefined(ctx.customInspect)) ctx.customInspect = true; if (ctx.colors) ctx.stylize = stylizeWithColor; return formatValue(ctx, obj, ctx.depth); } exports.inspect = inspect; // http://en.wikipedia.org/wiki/ANSI_escape_code#graphics inspect.colors = { 'bold' : [1, 22], 'italic' : [3, 23], 'underline' : [4, 24], 'inverse' : [7, 27], 'white' : [37, 39], 'grey' : [90, 39], 'black' : [30, 39], 'blue' : [34, 39], 'cyan' : [36, 39], 'green' : [32, 39], 'magenta' : [35, 39], 'red' : [31, 39], 'yellow' : [33, 39] }; // Don't use 'blue' not visible on cmd.exe inspect.styles = { 'special': 'cyan', 'number': 'yellow', 'boolean': 'yellow', 'undefined': 'grey', 'null': 'bold', 'string': 'green', 'date': 'magenta', // "name": intentionally not styling 'regexp': 'red' }; function stylizeWithColor(str, styleType) { var style = inspect.styles[styleType]; if (style) { return '\u001b[' + inspect.colors[style][0] + 'm' + str + '\u001b[' + inspect.colors[style][1] + 'm'; } else { return str; } } function stylizeNoColor(str, styleType) { return str; } function arrayToHash(array) { var hash = {}; array.forEach(function(val, idx) { hash[val] = true; }); return hash; } function formatValue(ctx, value, recurseTimes) { // Provide a hook for user-specified inspect functions. // Check that value is an object with an inspect function on it if (ctx.customInspect && value && isFunction(value.inspect) && // Filter out the util module, it's inspect function is special value.inspect !== exports.inspect && // Also filter out any prototype objects using the circular check. !(value.constructor && value.constructor.prototype === value)) { var ret = value.inspect(recurseTimes, ctx); if (!isString(ret)) { ret = formatValue(ctx, ret, recurseTimes); } return ret; } // Primitive types cannot have properties var primitive = formatPrimitive(ctx, value); if (primitive) { return primitive; } // Look up the keys of the object. var keys = Object.keys(value); var visibleKeys = arrayToHash(keys); if (ctx.showHidden) { keys = Object.getOwnPropertyNames(value); } // IE doesn't make error fields non-enumerable // http://msdn.microsoft.com/en-us/library/ie/dww52sbt(v=vs.94).aspx if (isError(value) && (keys.indexOf('message') >= 0 || keys.indexOf('description') >= 0)) { return formatError(value); } // Some type of object without properties can be shortcutted. if (keys.length === 0) { if (isFunction(value)) { var name = value.name ? ': ' + value.name : ''; return ctx.stylize('[Function' + name + ']', 'special'); } if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } if (isDate(value)) { return ctx.stylize(Date.prototype.toString.call(value), 'date'); } if (isError(value)) { return formatError(value); } } var base = '', array = false, braces = ['{', '}']; // Make Array say that they are Array if (isArray(value)) { array = true; braces = ['[', ']']; } // Make functions say that they are functions if (isFunction(value)) { var n = value.name ? ': ' + value.name : ''; base = ' [Function' + n + ']'; } // Make RegExps say that they are RegExps if (isRegExp(value)) { base = ' ' + RegExp.prototype.toString.call(value); } // Make dates with properties first say the date if (isDate(value)) { base = ' ' + Date.prototype.toUTCString.call(value); } // Make error with message first say the error if (isError(value)) { base = ' ' + formatError(value); } if (keys.length === 0 && (!array || value.length == 0)) { return braces[0] + base + braces[1]; } if (recurseTimes < 0) { if (isRegExp(value)) { return ctx.stylize(RegExp.prototype.toString.call(value), 'regexp'); } else { return ctx.stylize('[Object]', 'special'); } } ctx.seen.push(value); var output; if (array) { output = formatArray(ctx, value, recurseTimes, visibleKeys, keys); } else { output = keys.map(function(key) { return formatProperty(ctx, value, recurseTimes, visibleKeys, key, array); }); } ctx.seen.pop(); return reduceToSingleString(output, base, braces); } function formatPrimitive(ctx, value) { if (isUndefined(value)) return ctx.stylize('undefined', 'undefined'); if (isString(value)) { var simple = '\'' + JSON.stringify(value).replace(/^"|"$/g, '') .replace(/'/g, "\\'") .replace(/\\"/g, '"') + '\''; return ctx.stylize(simple, 'string'); } if (isNumber(value)) return ctx.stylize('' + value, 'number'); if (isBoolean(value)) return ctx.stylize('' + value, 'boolean'); // For some reason typeof null is "object", so special case here. if (isNull(value)) return ctx.stylize('null', 'null'); } function formatError(value) { return '[' + Error.prototype.toString.call(value) + ']'; } function formatArray(ctx, value, recurseTimes, visibleKeys, keys) { var output = []; for (var i = 0, l = value.length; i < l; ++i) { if (hasOwnProperty(value, String(i))) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, String(i), true)); } else { output.push(''); } } keys.forEach(function(key) { if (!key.match(/^\d+$/)) { output.push(formatProperty(ctx, value, recurseTimes, visibleKeys, key, true)); } }); return output; } function formatProperty(ctx, value, recurseTimes, visibleKeys, key, array) { var name, str, desc; desc = Object.getOwnPropertyDescriptor(value, key) || { value: value[key] }; if (desc.get) { if (desc.set) { str = ctx.stylize('[Getter/Setter]', 'special'); } else { str = ctx.stylize('[Getter]', 'special'); } } else { if (desc.set) { str = ctx.stylize('[Setter]', 'special'); } } if (!hasOwnProperty(visibleKeys, key)) { name = '[' + key + ']'; } if (!str) { if (ctx.seen.indexOf(desc.value) < 0) { if (isNull(recurseTimes)) { str = formatValue(ctx, desc.value, null); } else { str = formatValue(ctx, desc.value, recurseTimes - 1); } if (str.indexOf('\n') > -1) { if (array) { str = str.split('\n').map(function(line) { return ' ' + line; }).join('\n').substr(2); } else { str = '\n' + str.split('\n').map(function(line) { return ' ' + line; }).join('\n'); } } } else { str = ctx.stylize('[Circular]', 'special'); } } if (isUndefined(name)) { if (array && key.match(/^\d+$/)) { return str; } name = JSON.stringify('' + key); if (name.match(/^"([a-zA-Z_][a-zA-Z_0-9]*)"$/)) { name = name.substr(1, name.length - 2); name = ctx.stylize(name, 'name'); } else { name = name.replace(/'/g, "\\'") .replace(/\\"/g, '"') .replace(/(^"|"$)/g, "'"); name = ctx.stylize(name, 'string'); } } return name + ': ' + str; } function reduceToSingleString(output, base, braces) { var numLinesEst = 0; var length = output.reduce(function(prev, cur) { numLinesEst++; if (cur.indexOf('\n') >= 0) numLinesEst++; return prev + cur.replace(/\u001b\[\d\d?m/g, '').length + 1; }, 0); if (length > 60) { return braces[0] + (base === '' ? '' : base + '\n ') + ' ' + output.join(',\n ') + ' ' + braces[1]; } return braces[0] + base + ' ' + output.join(', ') + ' ' + braces[1]; } // NOTE: These type checking functions intentionally don't use `instanceof` // because it is fragile and can be easily faked with `Object.create()`. function isArray(ar) { return Array.isArray(ar); } exports.isArray = isArray; function isBoolean(arg) { return typeof arg === 'boolean'; } exports.isBoolean = isBoolean; function isNull(arg) { return arg === null; } exports.isNull = isNull; function isNullOrUndefined(arg) { return arg == null; } exports.isNullOrUndefined = isNullOrUndefined; function isNumber(arg) { return typeof arg === 'number'; } exports.isNumber = isNumber; function isString(arg) { return typeof arg === 'string'; } exports.isString = isString; function isSymbol(arg) { return typeof arg === 'symbol'; } exports.isSymbol = isSymbol; function isUndefined(arg) { return arg === void 0; } exports.isUndefined = isUndefined; function isRegExp(re) { return isObject(re) && objectToString(re) === '[object RegExp]'; } exports.isRegExp = isRegExp; function isObject(arg) { return typeof arg === 'object' && arg !== null; } exports.isObject = isObject; function isDate(d) { return isObject(d) && objectToString(d) === '[object Date]'; } exports.isDate = isDate; function isError(e) { return isObject(e) && (objectToString(e) === '[object Error]' || e instanceof Error); } exports.isError = isError; function isFunction(arg) { return typeof arg === 'function'; } exports.isFunction = isFunction; function isPrimitive(arg) { return arg === null || typeof arg === 'boolean' || typeof arg === 'number' || typeof arg === 'string' || typeof arg === 'symbol' || // ES6 symbol typeof arg === 'undefined'; } exports.isPrimitive = isPrimitive; exports.isBuffer = require('./support/isBuffer'); function objectToString(o) { return Object.prototype.toString.call(o); } function pad(n) { return n < 10 ? '0' + n.toString(10) : n.toString(10); } var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']; // 26 Feb 16:19:34 function timestamp() { var d = new Date(); var time = [pad(d.getHours()), pad(d.getMinutes()), pad(d.getSeconds())].join(':'); return [d.getDate(), months[d.getMonth()], time].join(' '); } // log is just a thin wrapper to console.log that prepends a timestamp exports.log = function() { console.log('%s - %s', timestamp(), exports.format.apply(exports, arguments)); }; /** * Inherit the prototype methods from one constructor into another. * * The Function.prototype.inherits from lang.js rewritten as a standalone * function (not on Function.prototype). NOTE: If this file is to be loaded * during bootstrapping this function needs to be rewritten using some native * functions as prototype setup using normal JavaScript does not work as * expected during bootstrapping (see mirror.js in r114903). * * @param {function} ctor Constructor function which needs to inherit the * prototype. * @param {function} superCtor Constructor function to inherit prototype from. */ exports.inherits = require('inherits'); exports._extend = function(origin, add) { // Don't do anything if add isn't an object if (!add || !isObject(add)) return origin; var keys = Object.keys(add); var i = keys.length; while (i--) { origin[keys[i]] = add[keys[i]]; } return origin; }; function hasOwnProperty(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); } }).call(this,require('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {}) },{"./support/isBuffer":260,"_process":219,"inherits":259}],262:[function(require,module,exports){ var indexOf = require('indexof'); var Object_keys = function (obj) { if (Object.keys) return Object.keys(obj) else { var res = []; for (var key in obj) res.push(key) return res; } }; var forEach = function (xs, fn) { if (xs.forEach) return xs.forEach(fn) else for (var i = 0; i < xs.length; i++) { fn(xs[i], i, xs); } }; var defineProp = (function() { try { Object.defineProperty({}, '_', {}); return function(obj, name, value) { Object.defineProperty(obj, name, { writable: true, enumerable: false, configurable: true, value: value }) }; } catch(e) { return function(obj, name, value) { obj[name] = value; }; } }()); var globals = ['Array', 'Boolean', 'Date', 'Error', 'EvalError', 'Function', 'Infinity', 'JSON', 'Math', 'NaN', 'Number', 'Object', 'RangeError', 'ReferenceError', 'RegExp', 'String', 'SyntaxError', 'TypeError', 'URIError', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'escape', 'eval', 'isFinite', 'isNaN', 'parseFloat', 'parseInt', 'undefined', 'unescape']; function Context() {} Context.prototype = {}; var Script = exports.Script = function NodeScript (code) { if (!(this instanceof Script)) return new Script(code); this.code = code; }; Script.prototype.runInContext = function (context) { if (!(context instanceof Context)) { throw new TypeError("needs a 'context' argument."); } var iframe = document.createElement('iframe'); if (!iframe.style) iframe.style = {}; iframe.style.display = 'none'; document.body.appendChild(iframe); var win = iframe.contentWindow; var wEval = win.eval, wExecScript = win.execScript; if (!wEval && wExecScript) { // win.eval() magically appears when this is called in IE: wExecScript.call(win, 'null'); wEval = win.eval; } forEach(Object_keys(context), function (key) { win[key] = context[key]; }); forEach(globals, function (key) { if (context[key]) { win[key] = context[key]; } }); var winKeys = Object_keys(win); var res = wEval.call(win, this.code); forEach(Object_keys(win), function (key) { // Avoid copying circular objects like `top` and `window` by only // updating existing context properties or new properties in the `win` // that was only introduced after the eval. if (key in context || indexOf(winKeys, key) === -1) { context[key] = win[key]; } }); forEach(globals, function (key) { if (!(key in context)) { defineProp(context, key, win[key]); } }); document.body.removeChild(iframe); return res; }; Script.prototype.runInThisContext = function () { return eval(this.code); // maybe... }; Script.prototype.runInNewContext = function (context) { var ctx = Script.createContext(context); var res = this.runInContext(ctx); forEach(Object_keys(ctx), function (key) { context[key] = ctx[key]; }); return res; }; forEach(Object_keys(Script.prototype), function (name) { exports[name] = Script[name] = function (code) { var s = Script(code); return s[name].apply(s, [].slice.call(arguments, 1)); }; }); exports.createScript = function (code) { return exports.Script(code); }; exports.createContext = Script.createContext = function (context) { var copy = new Context(); if(typeof context === 'object') { forEach(Object_keys(context), function (key) { copy[key] = context[key]; }); } return copy; }; },{"indexof":202}],263:[function(require,module,exports){ var basex = require('base-x') var ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz' module.exports = basex(ALPHABET) },{"base-x":63}],264:[function(require,module,exports){ 'use strict' var base58 = require('bs58') var Buffer = require('safe-buffer').Buffer module.exports = function (checksumFn) { // Encode a buffer as a base58-check encoded string function encode (payload) { var checksum = checksumFn(payload) return base58.encode(Buffer.concat([ payload, checksum ], payload.length + 4)) } function decodeRaw (buffer) { var payload = buffer.slice(0, -4) var checksum = buffer.slice(-4) var newChecksum = checksumFn(payload) if (checksum[0] ^ newChecksum[0] | checksum[1] ^ newChecksum[1] | checksum[2] ^ newChecksum[2] | checksum[3] ^ newChecksum[3]) return return payload } // Decode a base58-check encoded string to a buffer, no result if checksum is wrong function decodeUnsafe (string) { var buffer = base58.decodeUnsafe(string) if (!buffer) return return decodeRaw(buffer) } function decode (string) { var buffer = base58.decode(string) var payload = decodeRaw(buffer, checksumFn) if (!payload) throw new Error('Invalid checksum') return payload } return { encode: encode, decode: decode, decodeUnsafe: decodeUnsafe } } },{"bs58":263,"safe-buffer":266}],265:[function(require,module,exports){ 'use strict' var createHash = require('create-hash') var bs58checkBase = require('./base') // SHA256(SHA256(buffer)) function sha256x2 (buffer) { var tmp = createHash('sha256').update(buffer).digest() return createHash('sha256').update(tmp).digest() } module.exports = bs58checkBase(sha256x2) },{"./base":264,"create-hash":279}],266:[function(require,module,exports){ /* eslint-disable node/no-deprecated-api */ var buffer = require('buffer') var Buffer = buffer.Buffer // alternative to using Object.keys for old browsers function copyProps (src, dst) { for (var key in src) { dst[key] = src[key] } } if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { module.exports = buffer } else { // Copy properties from require('buffer') copyProps(buffer, exports) exports.Buffer = SafeBuffer } function SafeBuffer (arg, encodingOrOffset, length) { return Buffer(arg, encodingOrOffset, length) } // Copy static methods from Buffer copyProps(Buffer, SafeBuffer) SafeBuffer.from = function (arg, encodingOrOffset, length) { if (typeof arg === 'number') { throw new TypeError('Argument must not be a number') } return Buffer(arg, encodingOrOffset, length) } SafeBuffer.alloc = function (size, fill, encoding) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } var buf = Buffer(size) if (fill !== undefined) { if (typeof encoding === 'string') { buf.fill(fill, encoding) } else { buf.fill(fill) } } else { buf.fill(0) } return buf } SafeBuffer.allocUnsafe = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return Buffer(size) } SafeBuffer.allocUnsafeSlow = function (size) { if (typeof size !== 'number') { throw new TypeError('Argument must be a number') } return buffer.SlowBuffer(size) } },{"buffer":179}],267:[function(require,module,exports){ /** * Export cheerio (with ) */ exports = module.exports = require('./lib/cheerio'); /* Export the version */ exports.version = require('./package.json').version; },{"./lib/cheerio":273,"./package.json":277}],268:[function(require,module,exports){ var $ = require('../static'), utils = require('../utils'), isTag = utils.isTag, domEach = utils.domEach, hasOwn = Object.prototype.hasOwnProperty, camelCase = utils.camelCase, cssCase = utils.cssCase, rspace = /\s+/, dataAttrPrefix = 'data-', _ = { forEach: require('lodash.foreach'), extend: require('lodash.assignin'), some: require('lodash.some') }, // Lookup table for coercing string data-* attributes to their corresponding // JavaScript primitives primitives = { null: null, true: true, false: false }, // Attributes that are booleans rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i, // Matches strings that look like JSON objects or arrays rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/; var getAttr = function(elem, name) { if (!elem || !isTag(elem)) return; if (!elem.attribs) { elem.attribs = {}; } // Return the entire attribs object if no attribute specified if (!name) { return elem.attribs; } if (hasOwn.call(elem.attribs, name)) { // Get the (decoded) attribute return rboolean.test(name) ? name : elem.attribs[name]; } // Mimic the DOM and return text content as value for `option's` if (elem.name === 'option' && name === 'value') { return $.text(elem.children); } // Mimic DOM with default value for radios/checkboxes if (elem.name === 'input' && (elem.attribs.type === 'radio' || elem.attribs.type === 'checkbox') && name === 'value') { return 'on'; } }; var setAttr = function(el, name, value) { if (value === null) { removeAttribute(el, name); } else { el.attribs[name] = value+''; } }; exports.attr = function(name, value) { // Set the value (with attr map support) if (typeof name === 'object' || value !== undefined) { if (typeof value === 'function') { return domEach(this, function(i, el) { setAttr(el, name, value.call(el, i, el.attribs[name])); }); } return domEach(this, function(i, el) { if (!isTag(el)) return; if (typeof name === 'object') { _.forEach(name, function(value, name) { setAttr(el, name, value); }); } else { setAttr(el, name, value); } }); } return getAttr(this[0], name); }; var getProp = function (el, name) { if (!el || !isTag(el)) return; return el.hasOwnProperty(name) ? el[name] : rboolean.test(name) ? getAttr(el, name) !== undefined : getAttr(el, name); }; var setProp = function (el, name, value) { el[name] = rboolean.test(name) ? !!value : value; }; exports.prop = function (name, value) { var i = 0, property; if (typeof name === 'string' && value === undefined) { switch (name) { case 'style': property = this.css(); _.forEach(property, function (v, p) { property[i++] = p; }); property.length = i; break; case 'tagName': case 'nodeName': property = this[0].name.toUpperCase(); break; default: property = getProp(this[0], name); } return property; } if (typeof name === 'object' || value !== undefined) { if (typeof value === 'function') { return domEach(this, function(i, el) { setProp(el, name, value.call(el, i, getProp(el, name))); }); } return domEach(this, function(i, el) { if (!isTag(el)) return; if (typeof name === 'object') { _.forEach(name, function(val, name) { setProp(el, name, val); }); } else { setProp(el, name, value); } }); } }; var setData = function(el, name, value) { if (!el.data) { el.data = {}; } if (typeof name === 'object') return _.extend(el.data, name); if (typeof name === 'string' && value !== undefined) { el.data[name] = value; } else if (typeof name === 'object') { _.extend(el.data, name); } }; // Read the specified attribute from the equivalent HTML5 `data-*` attribute, // and (if present) cache the value in the node's internal data store. If no // attribute name is specified, read *all* HTML5 `data-*` attributes in this // manner. var readData = function(el, name) { var readAll = arguments.length === 1; var domNames, domName, jsNames, jsName, value, idx, length; if (readAll) { domNames = Object.keys(el.attribs).filter(function(attrName) { return attrName.slice(0, dataAttrPrefix.length) === dataAttrPrefix; }); jsNames = domNames.map(function(domName) { return camelCase(domName.slice(dataAttrPrefix.length)); }); } else { domNames = [dataAttrPrefix + cssCase(name)]; jsNames = [name]; } for (idx = 0, length = domNames.length; idx < length; ++idx) { domName = domNames[idx]; jsName = jsNames[idx]; if (hasOwn.call(el.attribs, domName)) { value = el.attribs[domName]; if (hasOwn.call(primitives, value)) { value = primitives[value]; } else if (value === String(Number(value))) { value = Number(value); } else if (rbrace.test(value)) { try { value = JSON.parse(value); } catch(e){ } } el.data[jsName] = value; } } return readAll ? el.data : value; }; exports.data = function(name, value) { var elem = this[0]; if (!elem || !isTag(elem)) return; if (!elem.data) { elem.data = {}; } // Return the entire data object if no data specified if (!name) { return readData(elem); } // Set the value (with attr map support) if (typeof name === 'object' || value !== undefined) { domEach(this, function(i, el) { setData(el, name, value); }); return this; } else if (hasOwn.call(elem.data, name)) { return elem.data[name]; } return readData(elem, name); }; /** * Get the value of an element */ exports.val = function(value) { var querying = arguments.length === 0, element = this[0]; if(!element) return; switch (element.name) { case 'textarea': return this.text(value); case 'input': switch (this.attr('type')) { case 'radio': if (querying) { return this.attr('value'); } else { this.attr('value', value); return this; } break; default: return this.attr('value', value); } return; case 'select': var option = this.find('option:selected'), returnValue; if (option === undefined) return undefined; if (!querying) { if (!this.attr().hasOwnProperty('multiple') && typeof value == 'object') { return this; } if (typeof value != 'object') { value = [value]; } this.find('option').removeAttr('selected'); for (var i = 0; i < value.length; i++) { this.find('option[value="' + value[i] + '"]').attr('selected', ''); } return this; } returnValue = option.attr('value'); if (this.attr().hasOwnProperty('multiple')) { returnValue = []; domEach(option, function(i, el) { returnValue.push(getAttr(el, 'value')); }); } return returnValue; case 'option': if (!querying) { this.attr('value', value); return this; } return this.attr('value'); } }; /** * Remove an attribute */ var removeAttribute = function(elem, name) { if (!elem.attribs || !hasOwn.call(elem.attribs, name)) return; delete elem.attribs[name]; }; exports.removeAttr = function(name) { domEach(this, function(i, elem) { removeAttribute(elem, name); }); return this; }; exports.hasClass = function(className) { return _.some(this, function(elem) { var attrs = elem.attribs, clazz = attrs && attrs['class'], idx = -1, end; if (clazz) { while ((idx = clazz.indexOf(className, idx+1)) > -1) { end = idx + className.length; if ((idx === 0 || rspace.test(clazz[idx-1])) && (end === clazz.length || rspace.test(clazz[end]))) { return true; } } } }); }; exports.addClass = function(value) { // Support functions if (typeof value === 'function') { return domEach(this, function(i, el) { var className = el.attribs['class'] || ''; exports.addClass.call([el], value.call(el, i, className)); }); } // Return if no value or not a string or function if (!value || typeof value !== 'string') return this; var classNames = value.split(rspace), numElements = this.length; for (var i = 0; i < numElements; i++) { // If selected element isn't a tag, move on if (!isTag(this[i])) continue; // If we don't already have classes var className = getAttr(this[i], 'class'), numClasses, setClass; if (!className) { setAttr(this[i], 'class', classNames.join(' ').trim()); } else { setClass = ' ' + className + ' '; numClasses = classNames.length; // Check if class already exists for (var j = 0; j < numClasses; j++) { var appendClass = classNames[j] + ' '; if (setClass.indexOf(' ' + appendClass) < 0) setClass += appendClass; } setAttr(this[i], 'class', setClass.trim()); } } return this; }; var splitClass = function(className) { return className ? className.trim().split(rspace) : []; }; exports.removeClass = function(value) { var classes, numClasses, removeAll; // Handle if value is a function if (typeof value === 'function') { return domEach(this, function(i, el) { exports.removeClass.call( [el], value.call(el, i, el.attribs['class'] || '') ); }); } classes = splitClass(value); numClasses = classes.length; removeAll = arguments.length === 0; return domEach(this, function(i, el) { if (!isTag(el)) return; if (removeAll) { // Short circuit the remove all case as this is the nice one el.attribs.class = ''; } else { var elClasses = splitClass(el.attribs.class), index, changed; for (var j = 0; j < numClasses; j++) { index = elClasses.indexOf(classes[j]); if (index >= 0) { elClasses.splice(index, 1); changed = true; // We have to do another pass to ensure that there are not duplicate // classes listed j--; } } if (changed) { el.attribs.class = elClasses.join(' '); } } }); }; exports.toggleClass = function(value, stateVal) { // Support functions if (typeof value === 'function') { return domEach(this, function(i, el) { exports.toggleClass.call( [el], value.call(el, i, el.attribs['class'] || '', stateVal), stateVal ); }); } // Return if no value or not a string or function if (!value || typeof value !== 'string') return this; var classNames = value.split(rspace), numClasses = classNames.length, state = typeof stateVal === 'boolean' ? stateVal ? 1 : -1 : 0, numElements = this.length, elementClasses, index; for (var i = 0; i < numElements; i++) { // If selected element isn't a tag, move on if (!isTag(this[i])) continue; elementClasses = splitClass(this[i].attribs.class); // Check if class already exists for (var j = 0; j < numClasses; j++) { // Check if the class name is currently defined index = elementClasses.indexOf(classNames[j]); // Add if stateValue === true or we are toggling and there is no value if (state >= 0 && index < 0) { elementClasses.push(classNames[j]); } else if (state <= 0 && index >= 0) { // Otherwise remove but only if the item exists elementClasses.splice(index, 1); } } this[i].attribs.class = elementClasses.join(' '); } return this; }; exports.is = function (selector) { if (selector) { return this.filter(selector).length > 0; } return false; }; },{"../static":275,"../utils":276,"lodash.assignin":422,"lodash.foreach":427,"lodash.some":433}],269:[function(require,module,exports){ var domEach = require('../utils').domEach, _ = { pick: require('lodash.pick'), }; var toString = Object.prototype.toString; /** * Set / Get css. * * @param {String|Object} prop * @param {String} val * @return {self} * @api public */ exports.css = function(prop, val) { if (arguments.length === 2 || // When `prop` is a "plain" object (toString.call(prop) === '[object Object]')) { return domEach(this, function(idx, el) { setCss(el, prop, val, idx); }); } else { return getCss(this[0], prop); } }; /** * Set styles of all elements. * * @param {String|Object} prop * @param {String} val * @param {Number} idx - optional index within the selection * @return {self} * @api private */ function setCss(el, prop, val, idx) { if ('string' == typeof prop) { var styles = getCss(el); if (typeof val === 'function') { val = val.call(el, idx, styles[prop]); } if (val === '') { delete styles[prop]; } else if (val != null) { styles[prop] = val; } el.attribs.style = stringify(styles); } else if ('object' == typeof prop) { Object.keys(prop).forEach(function(k){ setCss(el, k, prop[k]); }); } } /** * Get parsed styles of the first element. * * @param {String} prop * @return {Object} * @api private */ function getCss(el, prop) { var styles = parse(el.attribs.style); if (typeof prop === 'string') { return styles[prop]; } else if (Array.isArray(prop)) { return _.pick(styles, prop); } else { return styles; } } /** * Stringify `obj` to styles. * * @param {Object} obj * @return {Object} * @api private */ function stringify(obj) { return Object.keys(obj || {}) .reduce(function(str, prop){ return str += '' + (str ? ' ' : '') + prop + ': ' + obj[prop] + ';'; }, ''); } /** * Parse `styles`. * * @param {String} styles * @return {Object} * @api private */ function parse(styles) { styles = (styles || '').trim(); if (!styles) return {}; return styles .split(';') .reduce(function(obj, str){ var n = str.indexOf(':'); // skip if there is no :, or if it is the first/last character if (n < 1 || n === str.length-1) return obj; obj[str.slice(0,n).trim()] = str.slice(n+1).trim(); return obj; }, {}); } },{"../utils":276,"lodash.pick":430}],270:[function(require,module,exports){ // https://github.com/jquery/jquery/blob/2.1.3/src/manipulation/var/rcheckableType.js // https://github.com/jquery/jquery/blob/2.1.3/src/serialize.js var submittableSelector = 'input,select,textarea,keygen', r20 = /%20/g, rCRLF = /\r?\n/g, _ = { map: require('lodash.map') }; exports.serialize = function() { // Convert form elements into name/value objects var arr = this.serializeArray(); // Serialize each element into a key/value string var retArr = _.map(arr, function(data) { return encodeURIComponent(data.name) + '=' + encodeURIComponent(data.value); }); // Return the resulting serialization return retArr.join('&').replace(r20, '+'); }; exports.serializeArray = function() { // Resolve all form elements from either forms or collections of form elements var Cheerio = this.constructor; return this.map(function() { var elem = this; var $elem = Cheerio(elem); if (elem.name === 'form') { return $elem.find(submittableSelector).toArray(); } else { return $elem.filter(submittableSelector).toArray(); } }).filter( // Verify elements have a name (`attr.name`) and are not disabled (`:disabled`) '[name!=""]:not(:disabled)' // and cannot be clicked (`[type=submit]`) or are used in `x-www-form-urlencoded` (`[type=file]`) + ':not(:submit, :button, :image, :reset, :file)' // and are either checked/don't have a checkable state + ':matches([checked], :not(:checkbox, :radio))' // Convert each of the elements to its value(s) ).map(function(i, elem) { var $elem = Cheerio(elem); var name = $elem.attr('name'); var val = $elem.val(); // If there is no value set (e.g. `undefined`, `null`), then return nothing if (val == null) { return null; } else { // If we have an array of values (e.g. `