diff --git a/bitcore-wallet-client.js b/bitcore-wallet-client.js index 7e26e58c..705dda94 100644 --- a/bitcore-wallet-client.js +++ b/bitcore-wallet-client.js @@ -335,7 +335,7 @@ API.prototype._doRequest = function(method, url, args, cb) { headers: { 'x-identity': this.credentials.copayerId, 'x-signature': reqSignature, - 'x-client-version': 'bws-' + Package.version, + 'x-client-version': 'bwc-' + Package.version, }, method: method, url: absUrl, @@ -106004,7 +106004,7 @@ module.exports={ "name": "bitcore-wallet-client", "description": "Client for bitcore-wallet-service", "author": "BitPay Inc", - "version": "0.1.1", + "version": "0.1.2", "keywords": [ "bitcoin", "copay", @@ -106036,7 +106036,7 @@ module.exports={ "uglify": "^0.1.1" }, "devDependencies": { - "bitcore-wallet-service": "0.1.1", + "bitcore-wallet-service": "0.1.3", "chai": "^1.9.1", "coveralls": "^2.11.2", "grunt-jsdoc": "^0.5.8", diff --git a/bitcore-wallet-client.min.js b/bitcore-wallet-client.min.js index 34a2be64..c2b182b2 100644 --- a/bitcore-wallet-client.min.js +++ b/bitcore-wallet-client.min.js @@ -1,4 +1,4 @@ -!function b(a,c,d){function e(g,h){if(!c[g]){if(!a[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};a[g][0].call(k.exports,function(b){var c=a[g][1][b];return e(c?c:b)},k,k.exports,b,a,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g"}},e.prototype._processTxps=function(a){var b=this,c=b.credentials.sharedEncryptingKey;a&&g.each([].concat(a),function(a){a.encryptedMessage=a.message,a.message=e._decryptMessage(a.message,c)||null,g.each(a.actions,function(a){a.comment=e._decryptMessage(a.comment,c)}),g.each(a.outputs,function(a){a.encryptedMessage=a.message,a.message=e._decryptMessage(a.message,c)||null}),a.hasUnconfirmedInputs=g.any(a.inputs,function(a){return 0==a.confirmations})})},e._parseError=function(a){if(g.isString(a))try{a=JSON.parse(a)}catch(b){a={error:a}}var c;return c=a&&a.code?new v(a.code,a.message):{code:"ERROR",error:a?a.error:"There was an unknown error processing the request"},r.error(c),c},e._signRequest=function(a,b,c,d){var e=[a.toLowerCase(),b,JSON.stringify(c)].join("|");return l.signMessage(e,d)},e.prototype.seedFromRandom=function(a){this.credentials=s.create(a)},e.prototype.seedFromExtendedPrivateKey=function(a){this.credentials=s.fromExtendedPrivateKey(a)},e.prototype.seedFromExternalWalletPublicKey=function(a,b,c){this.credentials=s.fromExternalWalletPublicKey(a,b,c)},e.prototype["export"]=function(a){h.checkState(this.credentials),a=a||{};var b,c=s.fromObj(this.credentials);return a.noSign&&(delete c.xPrivKey,delete c.xPrivKeyEncrypted),b=a.compressed?c.exportCompressed():JSON.stringify(c.toObj())},e.prototype["import"]=function(a,b){b=b||{};var c;try{b.compressed?(c=s.importCompressed(a,b.password),delete c.m):c=s.fromObj(JSON.parse(a))}catch(d){throw new Error("Error importing from source:"+d)}this.credentials=c},e.prototype._doRequest=function(a,b,c,d){h.checkState(this.credentials);var f,g=c._requestPrivKey||this.credentials.requestPrivKey;g&&(delete c._requestPrivKey,f=e._signRequest(a,b,c,g));var j=this.baseUrl+b,c={relUrl:this.basePath+b,headers:{"x-identity":this.credentials.copayerId,"x-signature":f,"x-client-version":"bws-"+w.version},method:a,url:j,body:c,json:!0,withCredentials:!1,timeout:1e4};r.debug("Request Args",i.inspect(c,{depth:10})),this.request(c,function(a,b,c){return r.debug(i.inspect(c,{depth:10})),b?200!=b.statusCode?d(404==b.statusCode?{code:"NOT_FOUND"}:b.statusCode?e._parseError(c):{code:"CONNECTION_ERROR"}):'{"error":"read ECONNRESET"}'===c?d(JSON.parse(c)):d(null,c,b.header):d({code:"CONNECTION_ERROR"})})},e.prototype._doPostRequest=function(a,b,c){return this._doRequest("post",a,b,c)},e.prototype._doPutRequest=function(a,b,c){return this._doRequest("put",a,b,c)},e.prototype._doGetRequest=function(a,b){return a+=a.indexOf("?")>0?"&":"?",a+="r="+g.random(1e4,99999),this._doRequest("get",a,{},b)},e.prototype._doDeleteRequest=function(a,b){return this._doRequest("delete",a,{},b)},e.prototype._doJoinWallet=function(a,b,c,d,e,f,g){f=f||{},h.shouldBeFunction(g);var i={walletId:a,name:e,xPubKey:c,requestPubKey:d,isTemporaryRequestKey:!!f.isTemporaryRequestKey},j=l.getCopayerHash(i.name,i.xPubKey,i.requestPubKey);i.copayerSignature=l.signMessage(j,b);var k="/v1/wallets/"+a+"/copayers";this._doPostRequest(k,i,function(a,b){return a?g(a):g(null,b.wallet)})},e.prototype.isComplete=function(){return this.credentials&&this.credentials.isComplete()},e.prototype.isPrivKeyEncrypted=function(){return this.credentials&&this.credentials.isPrivKeyEncrypted()},e.prototype.hasPrivKeyEncrypted=function(){return this.credentials&&this.credentials.hasPrivKeyEncrypted()},e.prototype.isPrivKeyExternal=function(){return this.credentials&&this.credentials.hasExternalSource()},e.prototype.getPrivKeyExternalSourceName=function(){return this.credentials?this.credentials.getExternalSourceName():null},e.prototype.getExternalIndex=function(){return this.credentials?this.credentials.getExternalIndex():null},e.prototype.unlock=function(a){try{this.credentials.unlock(a)}catch(b){throw new Error("Could not unlock:"+b)}},e.prototype.canSign=function(){return this.credentials&&this.credentials.canSign()},e._extractPublicKeyRing=function(a){return g.map(a,function(a){var b=g.pick(a,["xPubKey","requestPubKey","isTemporaryRequestKey"]);return b.copayerName=a.name,b})},e.prototype.openWallet=function(a){h.checkState(this.credentials);var b=this,c=b.credentials.isComplete();return c&&!b.credentials.hasTemporaryRequestKeys()?a(null,!0):void b._doGetRequest("/v1/wallets/",function(d,f){if(d)return a(d);var h=f.wallet;if("complete"!=h.status)return a();if(b.credentials.walletPrivKey){if(!t.checkCopayers(b.credentials,h.copayers))return a(new u("Copayers in the wallet could not be verified to have known the wallet secret"))}else r.warn("Could not verify copayers key (missing wallet Private Key)");if(c)b.credentials.updatePublicKeyRing(e._extractPublicKeyRing(h.copayers)),b.credentials.hasTemporaryRequestKeys()||b.emit("walletCompleted",h);else{if(b.credentials.addPublicKeyRing(e._extractPublicKeyRing(h.copayers)),!b.credentials.hasWalletInfo()){var i=g.find(h.copayers,{id:b.credentials.copayerId});b.credentials.addWalletInfo(h.id,h.name,h.m,h.n,null,i.name)}b.emit("walletCompleted",h)}return f.pendingTxps&&b._processTxps(f.pendingTxps),a(null,f)})},e.prototype.setPrivateKeyEncryption=function(a,b){this.credentials.setPrivateKeyEncryption(a,b||e.privateKeyEncryptionOpts)},e.prototype.disablePrivateKeyEncryption=function(a,b){return this.credentials.disablePrivateKeyEncryption()},e.prototype.lock=function(){this.credentials.lock()},e.prototype.getFeeLevels=function(a,b){var c=this;h.checkArgument(a||g.contains(["livenet","testnet"],a)),c._doGetRequest("/v1/feelevels/?network="+(a||"livenet"),function(a,c){return a?b(a):b(a,c)})},e.prototype.createWallet=function(a,b,c,d,e,f){var i=this;e&&h.shouldBeObject(e),e=e||{};var j=e.network||"livenet";if(!g.contains(["testnet","livenet"],j))return f(new Error("Invalid network"));if(i.credentials?r.info("Using existing keys"):(r.info("Generating new keys"),i.seedFromRandom(j)),j!=i.credentials.network)return f(new Error("Existing keys were created for a different network"));var k=e.walletPrivKey||new m.PrivateKey,n={name:a,m:c,n:d,pubKey:new m.PrivateKey(k).toPublicKey().toString(),network:j,id:e.id};i._doPostRequest("/v1/wallets/",n,function(e,g){if(e)return f(e);var h=g.walletId,m=l.toSecret(h,k,j);i.credentials.addWalletInfo(h,a,c,d,k.toString(),b),i._doJoinWallet(h,k,i.credentials.xPubKey,i.credentials.requestPubKey,b,{},function(a,b){return a?f(a):f(null,d>1?m:null)})})},e.prototype.joinWallet=function(a,b,c){var d=this;try{var e=l.fromSecret(a)}catch(f){return c(f)}d.credentials||d.seedFromRandom(e.network),d._doJoinWallet(e.walletId,e.walletPrivKey,d.credentials.xPubKey,d.credentials.requestPubKey,b,{},function(a,f){return a?c(a):(d.credentials.addWalletInfo(f.id,f.name,f.m,f.n,e.walletPrivKey.toString(),b),c(null,f))})},e.prototype.recreateWallet=function(a){h.checkState(this.credentials&&this.credentials.isComplete()&&this.credentials.hasWalletInfo());var b=this,c=m.PrivateKey.fromString(b.credentials.walletPrivKey),d=b.credentials.walletId,e={name:b.credentials.walletName||"recovered wallet",m:b.credentials.m,n:b.credentials.n,pubKey:c.toPublicKey().toString(),network:b.credentials.network,id:d};b._doPostRequest("/v1/wallets/",e,function(e,f){if(e&&"WALLET_ALREADY_EXISTS"!=e.code)return a(e);var g=1;j.each(b.credentials.publicKeyRing,function(a,e){var f=a.copayerName||"copayer "+g++;b._doJoinWallet(d,c,a.xPubKey,a.requestPubKey,f,{isTemporaryRequestKey:a.isTemporaryRequestKey},function(a){return a&&"COPAYER_IN_WALLET"==a.code?e():e(a)})},a)})},e.prototype.getStatus=function(a){h.checkState(this.credentials);var b=this;b._doGetRequest("/v1/wallets/",function(c,d){if(c)return a(c);if("pending"==d.wallet.status){var e=b.credentials;d.wallet.secret=l.toSecret(e.walletId,e.walletPrivKey,e.network)}return b._processTxps(d.pendingTxps),a(c,d)})},e.prototype.getPreferences=function(a){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(a);var b=this;b._doGetRequest("/v1/preferences/",function(b,c){return b?a(b):a(null,c)})},e.prototype.savePreferences=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(b);var c=this;c._doPutRequest("/v1/preferences/",a,b)},e.prototype._computeProposalSignature=function(a){var b;if(a.outputs){h.shouldBeArray(a.outputs);var c={outputs:g.map(a.outputs,function(a){return h.shouldBeNumber(a.amount),g.pick(a,["toAddress","amount","message"])}),message:a.message||null,payProUrl:a.payProUrl};b=l.getProposalHash(c)}else h.shouldBeNumber(a.amount),b=l.getProposalHash(a.toAddress,a.amount,a.message||null,a.payProUrl);return l.signMessage(b,this.credentials.requestPrivKey)},e.prototype.fetchPayPro=function(a,b){h.checkArgument(a).checkArgument(a.payProUrl),q.get({url:a.payProUrl,http:this.payProHttp},function(a,c){return a?b(a||"Could not fetch PayPro request"):b(null,c)})},e.prototype.getUtxos=function(a){h.checkState(this.credentials&&this.credentials.isComplete()),this._doGetRequest("/v1/utxos/",a)},e.prototype.sendTxProposal=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(a);var c=this,d={toAddress:a.toAddress,amount:a.amount,message:e._encryptMessage(a.message,this.credentials.sharedEncryptingKey)||null,feePerKb:a.feePerKb,payProUrl:a.payProUrl,excludeUnconfirmedUtxos:!!a.excludeUnconfirmedUtxos,type:a.type,outputs:a.outputs};d.outputs&&g.each(d.outputs,function(a){a.message=e._encryptMessage(a.message,c.credentials.sharedEncryptingKey)||null}),r.debug("Generating & signing tx proposal:",JSON.stringify(d)),d.proposalSignature=this._computeProposalSignature(d),this._doPostRequest("/v1/txproposals/",d,function(a,c){return a?b(a):b(null,c)})},e.prototype.createAddress=function(a){h.checkState(this.credentials&&this.credentials.isComplete());var b=this;b._doPostRequest("/v1/addresses/",{},function(c,d){return c?a(c):t.checkAddress(b.credentials,d)?a(null,d):a(new u("Server sent fake address"))})},e.prototype.getMainAddresses=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this;c._doGetRequest("/v1/addresses/",function(d,e){if(d)return b(d);if(!a.doNotVerify){var f=g.any(e,function(a){return!t.checkAddress(c.credentials,a)});if(f)return b(new u("Server sent fake address"))}return b(null,e)})},e.prototype.getBalance=function(a){h.checkState(this.credentials&&this.credentials.isComplete()),this._doGetRequest("/v1/balance/",a)},e.prototype.getTxProposals=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this;c._doGetRequest("/v1/txproposals/",function(d,e){return d?b(d):(c._processTxps(e),void j.every(e,function(b,d){return a.doNotVerify?d(!0):void c.getPayPro(b,function(a,e){var f=t.checkTxProposal(c.credentials,b,{paypro:e});return d(f)})},function(d){if(!d)return b(new u("Server sent fake transaction proposal"));var f;return f=a.forAirGapped?{txps:JSON.parse(JSON.stringify(e)),encryptedPkr:l.encryptMessage(JSON.stringify(c.credentials.publicKeyRing),c.credentials.personalEncryptingKey),m:c.credentials.m,n:c.credentials.n}:e,b(null,f)}))})},e.prototype.getPayPro=function(a,b){var c=this;return!a.payProUrl||this.doNotVerifyPayPro?b():void q.get({url:a.payProUrl,http:c.payProHttp},function(a,c){return a?b(new Error("Cannot check transaction now:"+a)):b(null,c)})},e.prototype.signTxProposal=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(a.creatorId);var c=this;return c.canSign()||a.signatures?c.isPrivKeyEncrypted()?b(new Error("Private Key is encrypted, cannot sign")):void c.getPayPro(a,function(d,e){if(d)return b(d);var f=t.checkTxProposal(c.credentials,a,{paypro:e});if(!f)return b(new u("Server sent fake transaction proposal"));var g=a.signatures||l.signTxp(a,c.credentials.xPrivKey),h="/v1/txproposals/"+a.id+"/signatures/",i={signatures:g};c._doPostRequest(h,i,function(a,d){return a?b(a):(c._processTxps([d]),b(null,d))})}):b(new Error("You do not have the required keys to sign transactions"))},e.prototype.signTxProposalFromAirGapped=function(a,b,c,d){h.checkState(this.credentials);var e=this;if(!e.canSign())throw new Error("You do not have the required keys to sign transactions");if(e.isPrivKeyEncrypted())return cb(new Error("Private Key is encrypted, cannot sign"));var f;try{f=JSON.parse(l.decryptMessage(b,e.credentials.personalEncryptingKey))}catch(i){throw new Error("Could not decrypt public key ring")}if(!g.isArray(f)||f.length!=d)throw new Error("Invalid public key ring");if(e.credentials.m=c,e.credentials.n=d,e.credentials.addPublicKeyRing(f),!t.checkTxProposalBody(e.credentials,a))throw new Error("Fake transaction proposal");return l.signTxp(a,e.credentials.xPrivKey)},e.prototype.rejectTxProposal=function(a,b,c){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(c);var d=this,f="/v1/txproposals/"+a.id+"/rejections/",g={reason:e._encryptMessage(b,d.credentials.sharedEncryptingKey)||""};d._doPostRequest(f,g,function(a,b){return a?c(a):(d._processTxps([b]),c(null,b))})},e.prototype._doBroadcast=function(a,b){var c=this,d="/v1/txproposals/"+a.id+"/broadcast/";c._doPostRequest(d,{},function(a,c){return a?b(a):b(null,c)})},e.prototype.broadcastTxProposal=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this;c.getPayPro(a,function(d,e){if(e){var f=l.buildTx(a);c.createAddress(function(d,g){return d?b(d):void q.send({http:c.payProHttp,url:a.payProUrl,amountSat:a.amount,refundAddr:g.address,merchant_data:e.merchant_data,rawTx:f.uncheckedSerialize()},function(d,e,f){return d?b(d):void c._doBroadcast(a,function(a,c){return b(a,c,f)})})})}else c._doBroadcast(a,b)})},e.prototype.removeTxProposal=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this,d="/v1/txproposals/"+a.id;c._doDeleteRequest(d,function(a){return b(a)})},e.prototype.getTxHistory=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this,d=[];a&&(a.skip&&d.push("skip="+a.skip),a.limit&&d.push("limit="+a.limit));var e="";d.length>0&&(e="?"+d.join("&"));var f="/v1/txhistory/"+e;c._doGetRequest(f,function(a,d){return a?b(a):(c._processTxps(d),b(null,d))})},e.prototype.getTx=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this,d="/v1/txproposals/"+a;this._doGetRequest(d,function(a,d){return a?b(a):(c._processTxps([d]),b(null,d))})},e.prototype.startScan=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this,d={includeCopayerBranches:a.includeCopayerBranches};c._doPostRequest("/v1/addresses/scan",d,function(a){return b(a)})},e.prototype._oldCopayDecrypt=function(a,b,c){var d,e="@#$",f="%^#@";try{var g=a+e+b;d=n.decrypt(g,c)}catch(h){g=a+f+b;try{d=n.decrypt(g,c)}catch(h){r.debug(h)}}if(!d)return null;var i;try{i=JSON.parse(d)}catch(h){}return i},e.prototype.getWalletIdsFromOldCopay=function(a,b,c){var d=this._oldCopayDecrypt(a,b,c);if(!d)return null;var e=d.walletIds.concat(g.keys(d.focusedTimestamps));return g.uniq(e)},e.prototype._walletPrivKeyFromOldCopayWallet=function(a){var b=a.publicKeyRing.copayersExtPubKeys.sort().join(""),c=new d(b),e=new m.PrivateKey.fromBuffer(m.crypto.Hash.sha256(c));return e.toString()},e.prototype.createWalletFromOldCopay=function(a,b,c,d){var e=this,f=this._oldCopayDecrypt(a,b,c);if(!f)return d("Could not decrypt");if(f.publicKeyRing.copayersExtPubKeys.length!=f.opts.totalCopayers)return d("Wallet is incomplete, cannot be imported");var g=f.opts.requiredCopayers,h=f.opts.totalCopayers,i=f.opts.id,k=f.opts.name,l=f.opts.networkName;this.credentials=s.fromOldCopayWallet(f);var m=this._walletPrivKeyFromOldCopayWallet(f),n=this.credentials.copayerName;this.getStatus(function(a){return a?void e.createWallet(k,n,g,h,{network:l,id:i,walletPrivKey:m},function(a,b){if(a&&"WALLET_ALREADY_EXISTS"==a.code)return e.credentials.addWalletInfo(i,k,g,h,m,n),e._replaceTemporaryRequestKey(function(a){return a?d(a):void e.openWallet(function(a){return d(a,!0)})});if(a)return d(a);j.eachSeries(e.credentials.publicKeyRing,function(a,b){return a.xPubKey==e.credentials.xPubKey?b():void e._doJoinWallet(i,m,a.xPubKey,a.requestPubKey,a.copayerName,{isTemporaryRequestKey:!0},b)},d)}):(r.debug("Wallet is already imported"),e.credentials.addWalletInfo(i,k,g,h,m,n),d())})},e.prototype._replaceTemporaryRequestKey=function(a){h.checkState(this.credentials&&this.credentials.isComplete());var b={name:this.credentials.copayerName,xPubKey:this.credentials.xPubKey,requestPubKey:this.credentials.requestPubKey,isTemporaryRequestKey:!1},c=l.getCopayerHash(b.name,b.xPubKey,b.requestPubKey);b.copayerSignature=l.signMessage(c,this.credentials.walletPrivKey);var d=l.PATHS.BASE_ADDRESS_DERIVATION,e=new m.HDPrivateKey(this.credentials.xPrivKey).derive(d),f=l.PATHS.TMP_REQUEST_KEY,g=e.derive(f);b._requestPrivKey=g.privateKey.toString(),this._doPutRequest("/v1/copayers/",b,function(b,c){return b?a(b):a(null,c)})},b.exports=e}).call(this,a("_process"),a("buffer").Buffer)},{"../package.json":448,"./clienterror":3,"./credentials":4,"./log":6,"./paypro":7,"./servercompromisederror":8,"./verifier":9,_process:283,async:10,"bitcore-wallet-utils":34,"browser-request":116,buffer:133,events:274,lodash:306,preconditions:307,request:312,sjcl:397,"socket.io-client":398,url:301,util:303}],3:[function(a,b,c){function d(a,b){this.code=a,this.message=b}d.prototype.toString=function(){return""},b.exports=d},{}],4:[function(a,b,c){"use strict";function d(){this.version="1.0.0"}var e=a("preconditions").singleton(),f=a("lodash"),g=a("bitcore-wallet-utils"),h=g.Bitcore,i=a("sjcl"),j=["network","xPrivKey","xPrivKeyEncrypted","xPubKey","requestPrivKey","requestPubKey","copayerId","publicKeyRing","walletId","walletName","m","n","walletPrivKey","personalEncryptingKey","sharedEncryptingKey","copayerName","externalSource","externalIndex"],k=["xPrivKey","xPrivKeyEncrypted","requestPrivKey","xPubKey","m","n","publicKeyRing","sharedEncryptingKey","externalSource","externalIndex"];d.create=function(a){var b=new d;return b.network=a,b.xPrivKey=new h.HDPrivateKey(a).toString(),b._expand(),b},d.fromExtendedPrivateKey=function(a){var b=new d;return b.xPrivKey=a,b._expand(),b},d.fromExternalWalletPublicKey=function(a,b,c){var e=new d;return e.xPubKey=a,e.externalSource=b,e.externalIndex=c,e._expand(),e},d.prototype._expand=function(){if(e.checkState(this.xPrivKey||this.xPubKey),this.xPrivKey){var a=new h.HDPrivateKey.fromString(this.xPrivKey),b=a.derive(g.PATHS.BASE_ADDRESS_DERIVATION);this.xPubKey=new h.HDPublicKey(b).toString();var c=a.derive(g.PATHS.REQUEST_KEY);this.requestPrivKey=c.privateKey.toString(),this.requestPubKey=c.publicKey.toString()}var d=g.getNetworkFromXPubKey(this.xPubKey);if(this.hasExternalSource()){var a=new h.PrivateKey(d);this.requestPrivKey=a.toString(),this.requestPubKey=a.toPublicKey().toString()}this.network?e.checkState(this.network==d):this.network=d,this.personalEncryptingKey=g.privateKeyToAESKey(this.requestPrivKey),this.copayerId=g.xPubToCopayerId(this.xPubKey)},d.fromObj=function(a){var b=new d;return f.each(j,function(c){b[c]=a[c]}),e.checkState(b.xPrivKey||b.xPubKey||b.xPrivKeyEncrypted,"invalid input"),b},d.prototype.toObj=function(){var a=this,b={};return f.each(j,function(c){b[c]=a[c]}),b},d.prototype.addWalletInfo=function(a,b,c,d,e,f){this.walletId=a,this.walletName=b,this.m=c,this.n=d,this.walletPrivKey=e,e&&(this.sharedEncryptingKey=g.privateKeyToAESKey(e)),f&&(this.copayerName=f),1==d&&this.addPublicKeyRing([{xPubKey:this.xPubKey,requestPubKey:this.requestPubKey}])},d.prototype.hasWalletInfo=function(){return!!this.walletId},d.prototype.isPrivKeyEncrypted=function(){return!!this.xPrivKeyEncrypted&&!this.xPrivKey},d.prototype.hasPrivKeyEncrypted=function(){return!!this.xPrivKeyEncrypted},d.prototype.setPrivateKeyEncryption=function(a,b){if(this.xPrivKeyEncrypted)throw new Error("Encrypted Privkey Already exists");if(!this.xPrivKey)throw new Error("No private key to encrypt");if(this.xPrivKeyEncrypted=i.encrypt(a,this.xPrivKey,b),!this.xPrivKeyEncrypted)throw new Error("Could not encrypt")},d.prototype.disablePrivateKeyEncryption=function(){if(!this.xPrivKeyEncrypted)throw new Error("Private Key is not encrypted");if(!this.xPrivKey)throw new Error("Wallet is locked, cannot disable encryption");this.xPrivKeyEncrypted=null},d.prototype.lock=function(){if(!this.xPrivKeyEncrypted)throw new Error("Could not lock, no encrypted private key");delete this.xPrivKey},d.prototype.unlock=function(a){this.xPrivKeyEncrypted&&(this.xPrivKey=i.decrypt(a,this.xPrivKeyEncrypted))},d.prototype.addPublicKeyRing=function(a){this.publicKeyRing=f.clone(a)},d.prototype.updatePublicKeyRing=function(a){f.each(this.publicKeyRing,function(b){if(b.isTemporaryRequestKey){var c=f.find(a,{xPubKey:b.xPubKey});c&&!c.isTemporaryRequestKey&&(b.requestPubKey=c.requestPubKey,b.isTemporaryRequestKey=c.isTemporaryRequestKey)}})},d.prototype.canSign=function(){return!!this.xPrivKey||!!this.xPrivKeyEncrypted},d.prototype.isComplete=function(){return this.m&&this.n&&this.publicKeyRing&&this.publicKeyRing.length==this.n?!0:!1},d.prototype.hasExternalSource=function(){return"string"==typeof this.externalSource},d.prototype.getExternalSourceName=function(){return this.externalSource},d.prototype.getExternalIndex=function(){return this.externalIndex},d.prototype.hasTemporaryRequestKeys=function(){return this.isComplete()?f.any(this.publicKeyRing,function(a){return a.isTemporaryRequestKey}):null},d.prototype.exportCompressed=function(){var a=this,b=f.map(k,function(b){return"xPubKey"!=b&&"requestPrivKey"!=b||!a.canSign()?"requestPrivKey"==b?h.PrivateKey.fromString(a.requestPrivKey).toWIF():"publicKeyRing"==b?f.reject(a.publicKeyRing,{xPubKey:a.xPubKey}):a[b]:""});return b.unshift(a.version),JSON.stringify(b)},d.importCompressed=function(a,b){var c;try{c=JSON.parse(a)}catch(e){throw new Error("Invalid compressed format")}{var h=new d;c[0]}return c=f.rest(c),f.each(k,function(a,b){h[a]=c[b]}),b&&h.unlock(b),h._expand(),b&&h.lock(b),h.network=g.getNetworkFromXPubKey(h.xPubKey),h.publicKeyRing.push({xPubKey:h.xPubKey,requestPubKey:h.requestPubKey}),h},d.fromOldCopayWallet=function(a){var b=d.fromExtendedPrivateKey(a.privateKey.extendedPrivateKeyString),c=f.map(a.publicKeyRing.copayersExtPubKeys,function(c){var d,e=c===b.xPubKey;if(e){var f=g.PATHS.REQUEST_KEY;d=new h.HDPrivateKey(b.xPrivKey).derive(f).hdPublicKey}else{var f=g.PATHS.TMP_REQUEST_KEY;d=new h.HDPublicKey(c).derive(f)}var i=new h.HDPublicKey(c).derive("m/2147483646/0/0"),j=i.publicKey.toString("hex"),k=a.publicKeyRing.nicknameFor[j];return e&&(b.copayerName=k),{xPubKey:c,requestPubKey:d.publicKey.toString(),isTemporaryRequestKey:!e,copayerName:k}});return b.addPublicKeyRing(c),b},b.exports=d},{"bitcore-wallet-utils":34,lodash:306,preconditions:307,sjcl:397}],5:[function(a,b,c){var d=b.exports=a("./api");d.Verifier=a("./verifier"),d.Utils=a("bitcore-wallet-utils"),d.sjcl=a("sjcl"),d.Bitcore=a("bitcore-wallet-utils").Bitcore},{"./api":2,"./verifier":9,"bitcore-wallet-utils":34,sjcl:397}],6:[function(a,b,c){var d=a("lodash"),e=function(a){this.name=a||"log",this.level=2};e.prototype.getLevels=function(){return f};var f={debug:0,info:1,log:2,warn:3,error:4,fatal:5};d.each(f,function(a,b){e.prototype[b]=function(){if(a>=f[this.level]){if(Error.stackTraceLimit&&"debug"==this.level){var c=Error.stackTraceLimit;Error.stackTraceLimit=2;var d;try{anerror()}catch(e){d=e.stack}var g=d.split("\n"),h=g[2];h=":"+h.substr(6),Error.stackTraceLimit=c}var i,j="["+b+(h||"")+"] "+arguments[0],i=[].slice.call(arguments,1);console[b]?(i.unshift(j),console[b].apply(console,i)):(i.length&&(j+=JSON.stringify(i)),console.log(j))}}}),e.prototype.setLevel=function(a){this.level=a};{var g=new e("copay");new Error}g.setLevel("info"),b.exports=g},{lodash:306}],7:[function(a,b,c){(function(c,d){var e=a("preconditions").singleton(),f=a("bitcore-wallet-utils"),g=f.Bitcore,h=a("bitcore-payment-protocol"),i={};i._nodeRequest=function(b,c){b.agent=!1;var e=b.httpNode||a("http"===b.proto?"http":"https"),f="POST"==b.method?"post":"get";e[f](b,function(a){if(200!=a.statusCode)return c("HTTP Request Error");var b=[];a.on("data",function(a){b.push(a)}),a.on("end",function(){return b=d.concat(b),c(null,b)})})},i._browserRequest=function(a,b){var c=(a.method||"GET").toUpperCase(),d=a.url,e=a;e.headers=e.headers||{},e.body=e.body||e.data||"";var f=a.xhr||new XMLHttpRequest;f.open(c,d,!0),Object.keys(e.headers).forEach(function(a){var b=e.headers[a];"Content-Length"!==a&&"Content-Transfer-Encoding"!==a&&f.setRequestHeader(a,b)}),f.responseType="arraybuffer",f.onload=function(a){var c=f.response;return b(null,new Uint8Array(c))},f.onerror=function(a){var c;return c=0!==f.status&&f.statusText?f.statusText:"HTTP Request Error",b(c)},f.send(e.body?e.body:null)};var j=function(a){a.url.match(/^((http[s]?):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/);if(a.proto=RegExp.$2,a.host=RegExp.$3,a.path=RegExp.$4+RegExp.$6,a.http)return a.http;var b=a.env;return b||(b=c&&!c.browser?"node":"browser"),"node"==b?i._nodeRequest:http=i._browserRequest};i.get=function(a,b){e.checkArgument(a&&a.url);var c=j(a);a.headers=a.headers||{Accept:h.PAYMENT_REQUEST_CONTENT_TYPE,"Content-Type":"application/octet-stream"},c(a,function(c,e){if(c)return b(c);var f;try{var i=h.PaymentRequest.decode(e);f=(new h).makePaymentRequest(i)}catch(j){return b("Could not parse payment protocol:"+j)}var k=(f.get("signature"),f.get("serialized_payment_details")),l=f.verify(!0),m=h.PaymentDetails.decode(k),n=new h;n=n.makePaymentDetails(m);var o=n.get("outputs");if(o.length>1)return b(new Error("Payment Protocol Error: Requests with more that one output are not supported"));var p=o[0],q=p.get("amount");q=q.low+4294967296*q.high;var r="test"==n.get("network")?"testnet":"livenet",s=p.get("script").offset,t=p.get("script").limit,u=new d(new Uint8Array(p.get("script").buffer)),v=u.slice(s,t),w=new g.Address.fromScript(new g.Script(v),r),x=n.get("merchant_data");return x&&(x=x.toString()),b(null,{verified:l.verified,verifyData:{caName:l.caName,selfSigned:l.selfSigned},expires:n.get("expires"),memo:n.get("memo"),time:n.get("time"),merchant_data:x,toAddress:w.toString(),amount:q,network:r,domain:a.host,url:a.url})})},i._getPayProRefundOutputs=function(a,b){b=b.toString(10);var c=new h.Output,e=new g.Address(a),f=e.toObject().hash,i=new g.Script;return i.add(g.Opcode.OP_HASH160).add(new d(f,"hex")).add(g.Opcode.OP_EQUAL),c.set("script",i.toBuffer()),c.set("amount",b),[c]},i._createPayment=function(a,b,c,e){var f=new h;f=f.makePayment(),a&&(a=new d(a),f.set("merchant_data",a));var g=new d(b,"hex");f.set("transactions",[g]);var i=this._getPayProRefundOutputs(c,e);i&&f.set("refund_to",i),f=f.serialize();for(var j=new ArrayBuffer(f.length),k=new Uint8Array(j),l=0;l Hash: ",h," Signature: ",b.proposalSignature),g.verifyMessage(h,b.proposalSignature,j)&&d.checkAddress(a,b.changeAddress)?!0:!1},d.checkTxProposal=function(a,b,c){return c=c||{},this.checkTxProposalBody(a,b)&&(!c.paypro||b.toAddress==c.paypro.toAddress&&b.amount==c.paypro.amount)?!0:!1},b.exports=d},{"./log":6,"bitcore-wallet-utils":34,lodash:306,preconditions:307}],10:[function(a,b,c){(function(a){!function(){function c(a){var b=!1;return function(){if(b)throw new Error("Callback was already called."); +!function b(a,c,d){function e(g,h){if(!c[g]){if(!a[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};a[g][0].call(k.exports,function(b){var c=a[g][1][b];return e(c?c:b)},k,k.exports,b,a,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g"}},e.prototype._processTxps=function(a){var b=this,c=b.credentials.sharedEncryptingKey;a&&g.each([].concat(a),function(a){a.encryptedMessage=a.message,a.message=e._decryptMessage(a.message,c)||null,g.each(a.actions,function(a){a.comment=e._decryptMessage(a.comment,c)}),g.each(a.outputs,function(a){a.encryptedMessage=a.message,a.message=e._decryptMessage(a.message,c)||null}),a.hasUnconfirmedInputs=g.any(a.inputs,function(a){return 0==a.confirmations})})},e._parseError=function(a){if(g.isString(a))try{a=JSON.parse(a)}catch(b){a={error:a}}var c;return c=a&&a.code?new v(a.code,a.message):{code:"ERROR",error:a?a.error:"There was an unknown error processing the request"},r.error(c),c},e._signRequest=function(a,b,c,d){var e=[a.toLowerCase(),b,JSON.stringify(c)].join("|");return l.signMessage(e,d)},e.prototype.seedFromRandom=function(a){this.credentials=s.create(a)},e.prototype.seedFromExtendedPrivateKey=function(a){this.credentials=s.fromExtendedPrivateKey(a)},e.prototype.seedFromExternalWalletPublicKey=function(a,b,c){this.credentials=s.fromExternalWalletPublicKey(a,b,c)},e.prototype["export"]=function(a){h.checkState(this.credentials),a=a||{};var b,c=s.fromObj(this.credentials);return a.noSign&&(delete c.xPrivKey,delete c.xPrivKeyEncrypted),b=a.compressed?c.exportCompressed():JSON.stringify(c.toObj())},e.prototype["import"]=function(a,b){b=b||{};var c;try{b.compressed?(c=s.importCompressed(a,b.password),delete c.m):c=s.fromObj(JSON.parse(a))}catch(d){throw new Error("Error importing from source:"+d)}this.credentials=c},e.prototype._doRequest=function(a,b,c,d){h.checkState(this.credentials);var f,g=c._requestPrivKey||this.credentials.requestPrivKey;g&&(delete c._requestPrivKey,f=e._signRequest(a,b,c,g));var j=this.baseUrl+b,c={relUrl:this.basePath+b,headers:{"x-identity":this.credentials.copayerId,"x-signature":f,"x-client-version":"bwc-"+w.version},method:a,url:j,body:c,json:!0,withCredentials:!1,timeout:1e4};r.debug("Request Args",i.inspect(c,{depth:10})),this.request(c,function(a,b,c){return r.debug(i.inspect(c,{depth:10})),b?200!=b.statusCode?d(404==b.statusCode?{code:"NOT_FOUND"}:b.statusCode?e._parseError(c):{code:"CONNECTION_ERROR"}):'{"error":"read ECONNRESET"}'===c?d(JSON.parse(c)):d(null,c,b.header):d({code:"CONNECTION_ERROR"})})},e.prototype._doPostRequest=function(a,b,c){return this._doRequest("post",a,b,c)},e.prototype._doPutRequest=function(a,b,c){return this._doRequest("put",a,b,c)},e.prototype._doGetRequest=function(a,b){return a+=a.indexOf("?")>0?"&":"?",a+="r="+g.random(1e4,99999),this._doRequest("get",a,{},b)},e.prototype._doDeleteRequest=function(a,b){return this._doRequest("delete",a,{},b)},e.prototype._doJoinWallet=function(a,b,c,d,e,f,g){f=f||{},h.shouldBeFunction(g);var i={walletId:a,name:e,xPubKey:c,requestPubKey:d,isTemporaryRequestKey:!!f.isTemporaryRequestKey},j=l.getCopayerHash(i.name,i.xPubKey,i.requestPubKey);i.copayerSignature=l.signMessage(j,b);var k="/v1/wallets/"+a+"/copayers";this._doPostRequest(k,i,function(a,b){return a?g(a):g(null,b.wallet)})},e.prototype.isComplete=function(){return this.credentials&&this.credentials.isComplete()},e.prototype.isPrivKeyEncrypted=function(){return this.credentials&&this.credentials.isPrivKeyEncrypted()},e.prototype.hasPrivKeyEncrypted=function(){return this.credentials&&this.credentials.hasPrivKeyEncrypted()},e.prototype.isPrivKeyExternal=function(){return this.credentials&&this.credentials.hasExternalSource()},e.prototype.getPrivKeyExternalSourceName=function(){return this.credentials?this.credentials.getExternalSourceName():null},e.prototype.getExternalIndex=function(){return this.credentials?this.credentials.getExternalIndex():null},e.prototype.unlock=function(a){try{this.credentials.unlock(a)}catch(b){throw new Error("Could not unlock:"+b)}},e.prototype.canSign=function(){return this.credentials&&this.credentials.canSign()},e._extractPublicKeyRing=function(a){return g.map(a,function(a){var b=g.pick(a,["xPubKey","requestPubKey","isTemporaryRequestKey"]);return b.copayerName=a.name,b})},e.prototype.openWallet=function(a){h.checkState(this.credentials);var b=this,c=b.credentials.isComplete();return c&&!b.credentials.hasTemporaryRequestKeys()?a(null,!0):void b._doGetRequest("/v1/wallets/",function(d,f){if(d)return a(d);var h=f.wallet;if("complete"!=h.status)return a();if(b.credentials.walletPrivKey){if(!t.checkCopayers(b.credentials,h.copayers))return a(new u("Copayers in the wallet could not be verified to have known the wallet secret"))}else r.warn("Could not verify copayers key (missing wallet Private Key)");if(c)b.credentials.updatePublicKeyRing(e._extractPublicKeyRing(h.copayers)),b.credentials.hasTemporaryRequestKeys()||b.emit("walletCompleted",h);else{if(b.credentials.addPublicKeyRing(e._extractPublicKeyRing(h.copayers)),!b.credentials.hasWalletInfo()){var i=g.find(h.copayers,{id:b.credentials.copayerId});b.credentials.addWalletInfo(h.id,h.name,h.m,h.n,null,i.name)}b.emit("walletCompleted",h)}return f.pendingTxps&&b._processTxps(f.pendingTxps),a(null,f)})},e.prototype.setPrivateKeyEncryption=function(a,b){this.credentials.setPrivateKeyEncryption(a,b||e.privateKeyEncryptionOpts)},e.prototype.disablePrivateKeyEncryption=function(a,b){return this.credentials.disablePrivateKeyEncryption()},e.prototype.lock=function(){this.credentials.lock()},e.prototype.getFeeLevels=function(a,b){var c=this;h.checkArgument(a||g.contains(["livenet","testnet"],a)),c._doGetRequest("/v1/feelevels/?network="+(a||"livenet"),function(a,c){return a?b(a):b(a,c)})},e.prototype.createWallet=function(a,b,c,d,e,f){var i=this;e&&h.shouldBeObject(e),e=e||{};var j=e.network||"livenet";if(!g.contains(["testnet","livenet"],j))return f(new Error("Invalid network"));if(i.credentials?r.info("Using existing keys"):(r.info("Generating new keys"),i.seedFromRandom(j)),j!=i.credentials.network)return f(new Error("Existing keys were created for a different network"));var k=e.walletPrivKey||new m.PrivateKey,n={name:a,m:c,n:d,pubKey:new m.PrivateKey(k).toPublicKey().toString(),network:j,id:e.id};i._doPostRequest("/v1/wallets/",n,function(e,g){if(e)return f(e);var h=g.walletId,m=l.toSecret(h,k,j);i.credentials.addWalletInfo(h,a,c,d,k.toString(),b),i._doJoinWallet(h,k,i.credentials.xPubKey,i.credentials.requestPubKey,b,{},function(a,b){return a?f(a):f(null,d>1?m:null)})})},e.prototype.joinWallet=function(a,b,c){var d=this;try{var e=l.fromSecret(a)}catch(f){return c(f)}d.credentials||d.seedFromRandom(e.network),d._doJoinWallet(e.walletId,e.walletPrivKey,d.credentials.xPubKey,d.credentials.requestPubKey,b,{},function(a,f){return a?c(a):(d.credentials.addWalletInfo(f.id,f.name,f.m,f.n,e.walletPrivKey.toString(),b),c(null,f))})},e.prototype.recreateWallet=function(a){h.checkState(this.credentials&&this.credentials.isComplete()&&this.credentials.hasWalletInfo());var b=this,c=m.PrivateKey.fromString(b.credentials.walletPrivKey),d=b.credentials.walletId,e={name:b.credentials.walletName||"recovered wallet",m:b.credentials.m,n:b.credentials.n,pubKey:c.toPublicKey().toString(),network:b.credentials.network,id:d};b._doPostRequest("/v1/wallets/",e,function(e,f){if(e&&"WALLET_ALREADY_EXISTS"!=e.code)return a(e);var g=1;j.each(b.credentials.publicKeyRing,function(a,e){var f=a.copayerName||"copayer "+g++;b._doJoinWallet(d,c,a.xPubKey,a.requestPubKey,f,{isTemporaryRequestKey:a.isTemporaryRequestKey},function(a){return a&&"COPAYER_IN_WALLET"==a.code?e():e(a)})},a)})},e.prototype.getStatus=function(a){h.checkState(this.credentials);var b=this;b._doGetRequest("/v1/wallets/",function(c,d){if(c)return a(c);if("pending"==d.wallet.status){var e=b.credentials;d.wallet.secret=l.toSecret(e.walletId,e.walletPrivKey,e.network)}return b._processTxps(d.pendingTxps),a(c,d)})},e.prototype.getPreferences=function(a){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(a);var b=this;b._doGetRequest("/v1/preferences/",function(b,c){return b?a(b):a(null,c)})},e.prototype.savePreferences=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(b);var c=this;c._doPutRequest("/v1/preferences/",a,b)},e.prototype._computeProposalSignature=function(a){var b;if(a.outputs){h.shouldBeArray(a.outputs);var c={outputs:g.map(a.outputs,function(a){return h.shouldBeNumber(a.amount),g.pick(a,["toAddress","amount","message"])}),message:a.message||null,payProUrl:a.payProUrl};b=l.getProposalHash(c)}else h.shouldBeNumber(a.amount),b=l.getProposalHash(a.toAddress,a.amount,a.message||null,a.payProUrl);return l.signMessage(b,this.credentials.requestPrivKey)},e.prototype.fetchPayPro=function(a,b){h.checkArgument(a).checkArgument(a.payProUrl),q.get({url:a.payProUrl,http:this.payProHttp},function(a,c){return a?b(a||"Could not fetch PayPro request"):b(null,c)})},e.prototype.getUtxos=function(a){h.checkState(this.credentials&&this.credentials.isComplete()),this._doGetRequest("/v1/utxos/",a)},e.prototype.sendTxProposal=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(a);var c=this,d={toAddress:a.toAddress,amount:a.amount,message:e._encryptMessage(a.message,this.credentials.sharedEncryptingKey)||null,feePerKb:a.feePerKb,payProUrl:a.payProUrl,excludeUnconfirmedUtxos:!!a.excludeUnconfirmedUtxos,type:a.type,outputs:a.outputs};d.outputs&&g.each(d.outputs,function(a){a.message=e._encryptMessage(a.message,c.credentials.sharedEncryptingKey)||null}),r.debug("Generating & signing tx proposal:",JSON.stringify(d)),d.proposalSignature=this._computeProposalSignature(d),this._doPostRequest("/v1/txproposals/",d,function(a,c){return a?b(a):b(null,c)})},e.prototype.createAddress=function(a){h.checkState(this.credentials&&this.credentials.isComplete());var b=this;b._doPostRequest("/v1/addresses/",{},function(c,d){return c?a(c):t.checkAddress(b.credentials,d)?a(null,d):a(new u("Server sent fake address"))})},e.prototype.getMainAddresses=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this;c._doGetRequest("/v1/addresses/",function(d,e){if(d)return b(d);if(!a.doNotVerify){var f=g.any(e,function(a){return!t.checkAddress(c.credentials,a)});if(f)return b(new u("Server sent fake address"))}return b(null,e)})},e.prototype.getBalance=function(a){h.checkState(this.credentials&&this.credentials.isComplete()),this._doGetRequest("/v1/balance/",a)},e.prototype.getTxProposals=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this;c._doGetRequest("/v1/txproposals/",function(d,e){return d?b(d):(c._processTxps(e),void j.every(e,function(b,d){return a.doNotVerify?d(!0):void c.getPayPro(b,function(a,e){var f=t.checkTxProposal(c.credentials,b,{paypro:e});return d(f)})},function(d){if(!d)return b(new u("Server sent fake transaction proposal"));var f;return f=a.forAirGapped?{txps:JSON.parse(JSON.stringify(e)),encryptedPkr:l.encryptMessage(JSON.stringify(c.credentials.publicKeyRing),c.credentials.personalEncryptingKey),m:c.credentials.m,n:c.credentials.n}:e,b(null,f)}))})},e.prototype.getPayPro=function(a,b){var c=this;return!a.payProUrl||this.doNotVerifyPayPro?b():void q.get({url:a.payProUrl,http:c.payProHttp},function(a,c){return a?b(new Error("Cannot check transaction now:"+a)):b(null,c)})},e.prototype.signTxProposal=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(a.creatorId);var c=this;return c.canSign()||a.signatures?c.isPrivKeyEncrypted()?b(new Error("Private Key is encrypted, cannot sign")):void c.getPayPro(a,function(d,e){if(d)return b(d);var f=t.checkTxProposal(c.credentials,a,{paypro:e});if(!f)return b(new u("Server sent fake transaction proposal"));var g=a.signatures||l.signTxp(a,c.credentials.xPrivKey),h="/v1/txproposals/"+a.id+"/signatures/",i={signatures:g};c._doPostRequest(h,i,function(a,d){return a?b(a):(c._processTxps([d]),b(null,d))})}):b(new Error("You do not have the required keys to sign transactions"))},e.prototype.signTxProposalFromAirGapped=function(a,b,c,d){h.checkState(this.credentials);var e=this;if(!e.canSign())throw new Error("You do not have the required keys to sign transactions");if(e.isPrivKeyEncrypted())return cb(new Error("Private Key is encrypted, cannot sign"));var f;try{f=JSON.parse(l.decryptMessage(b,e.credentials.personalEncryptingKey))}catch(i){throw new Error("Could not decrypt public key ring")}if(!g.isArray(f)||f.length!=d)throw new Error("Invalid public key ring");if(e.credentials.m=c,e.credentials.n=d,e.credentials.addPublicKeyRing(f),!t.checkTxProposalBody(e.credentials,a))throw new Error("Fake transaction proposal");return l.signTxp(a,e.credentials.xPrivKey)},e.prototype.rejectTxProposal=function(a,b,c){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(c);var d=this,f="/v1/txproposals/"+a.id+"/rejections/",g={reason:e._encryptMessage(b,d.credentials.sharedEncryptingKey)||""};d._doPostRequest(f,g,function(a,b){return a?c(a):(d._processTxps([b]),c(null,b))})},e.prototype._doBroadcast=function(a,b){var c=this,d="/v1/txproposals/"+a.id+"/broadcast/";c._doPostRequest(d,{},function(a,c){return a?b(a):b(null,c)})},e.prototype.broadcastTxProposal=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this;c.getPayPro(a,function(d,e){if(e){var f=l.buildTx(a);c.createAddress(function(d,g){return d?b(d):void q.send({http:c.payProHttp,url:a.payProUrl,amountSat:a.amount,refundAddr:g.address,merchant_data:e.merchant_data,rawTx:f.uncheckedSerialize()},function(d,e,f){return d?b(d):void c._doBroadcast(a,function(a,c){return b(a,c,f)})})})}else c._doBroadcast(a,b)})},e.prototype.removeTxProposal=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this,d="/v1/txproposals/"+a.id;c._doDeleteRequest(d,function(a){return b(a)})},e.prototype.getTxHistory=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this,d=[];a&&(a.skip&&d.push("skip="+a.skip),a.limit&&d.push("limit="+a.limit));var e="";d.length>0&&(e="?"+d.join("&"));var f="/v1/txhistory/"+e;c._doGetRequest(f,function(a,d){return a?b(a):(c._processTxps(d),b(null,d))})},e.prototype.getTx=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this,d="/v1/txproposals/"+a;this._doGetRequest(d,function(a,d){return a?b(a):(c._processTxps([d]),b(null,d))})},e.prototype.startScan=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this,d={includeCopayerBranches:a.includeCopayerBranches};c._doPostRequest("/v1/addresses/scan",d,function(a){return b(a)})},e.prototype._oldCopayDecrypt=function(a,b,c){var d,e="@#$",f="%^#@";try{var g=a+e+b;d=n.decrypt(g,c)}catch(h){g=a+f+b;try{d=n.decrypt(g,c)}catch(h){r.debug(h)}}if(!d)return null;var i;try{i=JSON.parse(d)}catch(h){}return i},e.prototype.getWalletIdsFromOldCopay=function(a,b,c){var d=this._oldCopayDecrypt(a,b,c);if(!d)return null;var e=d.walletIds.concat(g.keys(d.focusedTimestamps));return g.uniq(e)},e.prototype._walletPrivKeyFromOldCopayWallet=function(a){var b=a.publicKeyRing.copayersExtPubKeys.sort().join(""),c=new d(b),e=new m.PrivateKey.fromBuffer(m.crypto.Hash.sha256(c));return e.toString()},e.prototype.createWalletFromOldCopay=function(a,b,c,d){var e=this,f=this._oldCopayDecrypt(a,b,c);if(!f)return d("Could not decrypt");if(f.publicKeyRing.copayersExtPubKeys.length!=f.opts.totalCopayers)return d("Wallet is incomplete, cannot be imported");var g=f.opts.requiredCopayers,h=f.opts.totalCopayers,i=f.opts.id,k=f.opts.name,l=f.opts.networkName;this.credentials=s.fromOldCopayWallet(f);var m=this._walletPrivKeyFromOldCopayWallet(f),n=this.credentials.copayerName;this.getStatus(function(a){return a?void e.createWallet(k,n,g,h,{network:l,id:i,walletPrivKey:m},function(a,b){if(a&&"WALLET_ALREADY_EXISTS"==a.code)return e.credentials.addWalletInfo(i,k,g,h,m,n),e._replaceTemporaryRequestKey(function(a){return a?d(a):void e.openWallet(function(a){return d(a,!0)})});if(a)return d(a);j.eachSeries(e.credentials.publicKeyRing,function(a,b){return a.xPubKey==e.credentials.xPubKey?b():void e._doJoinWallet(i,m,a.xPubKey,a.requestPubKey,a.copayerName,{isTemporaryRequestKey:!0},b)},d)}):(r.debug("Wallet is already imported"),e.credentials.addWalletInfo(i,k,g,h,m,n),d())})},e.prototype._replaceTemporaryRequestKey=function(a){h.checkState(this.credentials&&this.credentials.isComplete());var b={name:this.credentials.copayerName,xPubKey:this.credentials.xPubKey,requestPubKey:this.credentials.requestPubKey,isTemporaryRequestKey:!1},c=l.getCopayerHash(b.name,b.xPubKey,b.requestPubKey);b.copayerSignature=l.signMessage(c,this.credentials.walletPrivKey);var d=l.PATHS.BASE_ADDRESS_DERIVATION,e=new m.HDPrivateKey(this.credentials.xPrivKey).derive(d),f=l.PATHS.TMP_REQUEST_KEY,g=e.derive(f);b._requestPrivKey=g.privateKey.toString(),this._doPutRequest("/v1/copayers/",b,function(b,c){return b?a(b):a(null,c)})},b.exports=e}).call(this,a("_process"),a("buffer").Buffer)},{"../package.json":448,"./clienterror":3,"./credentials":4,"./log":6,"./paypro":7,"./servercompromisederror":8,"./verifier":9,_process:283,async:10,"bitcore-wallet-utils":34,"browser-request":116,buffer:133,events:274,lodash:306,preconditions:307,request:312,sjcl:397,"socket.io-client":398,url:301,util:303}],3:[function(a,b,c){function d(a,b){this.code=a,this.message=b}d.prototype.toString=function(){return""},b.exports=d},{}],4:[function(a,b,c){"use strict";function d(){this.version="1.0.0"}var e=a("preconditions").singleton(),f=a("lodash"),g=a("bitcore-wallet-utils"),h=g.Bitcore,i=a("sjcl"),j=["network","xPrivKey","xPrivKeyEncrypted","xPubKey","requestPrivKey","requestPubKey","copayerId","publicKeyRing","walletId","walletName","m","n","walletPrivKey","personalEncryptingKey","sharedEncryptingKey","copayerName","externalSource","externalIndex"],k=["xPrivKey","xPrivKeyEncrypted","requestPrivKey","xPubKey","m","n","publicKeyRing","sharedEncryptingKey","externalSource","externalIndex"];d.create=function(a){var b=new d;return b.network=a,b.xPrivKey=new h.HDPrivateKey(a).toString(),b._expand(),b},d.fromExtendedPrivateKey=function(a){var b=new d;return b.xPrivKey=a,b._expand(),b},d.fromExternalWalletPublicKey=function(a,b,c){var e=new d;return e.xPubKey=a,e.externalSource=b,e.externalIndex=c,e._expand(),e},d.prototype._expand=function(){if(e.checkState(this.xPrivKey||this.xPubKey),this.xPrivKey){var a=new h.HDPrivateKey.fromString(this.xPrivKey),b=a.derive(g.PATHS.BASE_ADDRESS_DERIVATION);this.xPubKey=new h.HDPublicKey(b).toString();var c=a.derive(g.PATHS.REQUEST_KEY);this.requestPrivKey=c.privateKey.toString(),this.requestPubKey=c.publicKey.toString()}var d=g.getNetworkFromXPubKey(this.xPubKey);if(this.hasExternalSource()){var a=new h.PrivateKey(d);this.requestPrivKey=a.toString(),this.requestPubKey=a.toPublicKey().toString()}this.network?e.checkState(this.network==d):this.network=d,this.personalEncryptingKey=g.privateKeyToAESKey(this.requestPrivKey),this.copayerId=g.xPubToCopayerId(this.xPubKey)},d.fromObj=function(a){var b=new d;return f.each(j,function(c){b[c]=a[c]}),e.checkState(b.xPrivKey||b.xPubKey||b.xPrivKeyEncrypted,"invalid input"),b},d.prototype.toObj=function(){var a=this,b={};return f.each(j,function(c){b[c]=a[c]}),b},d.prototype.addWalletInfo=function(a,b,c,d,e,f){this.walletId=a,this.walletName=b,this.m=c,this.n=d,this.walletPrivKey=e,e&&(this.sharedEncryptingKey=g.privateKeyToAESKey(e)),f&&(this.copayerName=f),1==d&&this.addPublicKeyRing([{xPubKey:this.xPubKey,requestPubKey:this.requestPubKey}])},d.prototype.hasWalletInfo=function(){return!!this.walletId},d.prototype.isPrivKeyEncrypted=function(){return!!this.xPrivKeyEncrypted&&!this.xPrivKey},d.prototype.hasPrivKeyEncrypted=function(){return!!this.xPrivKeyEncrypted},d.prototype.setPrivateKeyEncryption=function(a,b){if(this.xPrivKeyEncrypted)throw new Error("Encrypted Privkey Already exists");if(!this.xPrivKey)throw new Error("No private key to encrypt");if(this.xPrivKeyEncrypted=i.encrypt(a,this.xPrivKey,b),!this.xPrivKeyEncrypted)throw new Error("Could not encrypt")},d.prototype.disablePrivateKeyEncryption=function(){if(!this.xPrivKeyEncrypted)throw new Error("Private Key is not encrypted");if(!this.xPrivKey)throw new Error("Wallet is locked, cannot disable encryption");this.xPrivKeyEncrypted=null},d.prototype.lock=function(){if(!this.xPrivKeyEncrypted)throw new Error("Could not lock, no encrypted private key");delete this.xPrivKey},d.prototype.unlock=function(a){this.xPrivKeyEncrypted&&(this.xPrivKey=i.decrypt(a,this.xPrivKeyEncrypted))},d.prototype.addPublicKeyRing=function(a){this.publicKeyRing=f.clone(a)},d.prototype.updatePublicKeyRing=function(a){f.each(this.publicKeyRing,function(b){if(b.isTemporaryRequestKey){var c=f.find(a,{xPubKey:b.xPubKey});c&&!c.isTemporaryRequestKey&&(b.requestPubKey=c.requestPubKey,b.isTemporaryRequestKey=c.isTemporaryRequestKey)}})},d.prototype.canSign=function(){return!!this.xPrivKey||!!this.xPrivKeyEncrypted},d.prototype.isComplete=function(){return this.m&&this.n&&this.publicKeyRing&&this.publicKeyRing.length==this.n?!0:!1},d.prototype.hasExternalSource=function(){return"string"==typeof this.externalSource},d.prototype.getExternalSourceName=function(){return this.externalSource},d.prototype.getExternalIndex=function(){return this.externalIndex},d.prototype.hasTemporaryRequestKeys=function(){return this.isComplete()?f.any(this.publicKeyRing,function(a){return a.isTemporaryRequestKey}):null},d.prototype.exportCompressed=function(){var a=this,b=f.map(k,function(b){return"xPubKey"!=b&&"requestPrivKey"!=b||!a.canSign()?"requestPrivKey"==b?h.PrivateKey.fromString(a.requestPrivKey).toWIF():"publicKeyRing"==b?f.reject(a.publicKeyRing,{xPubKey:a.xPubKey}):a[b]:""});return b.unshift(a.version),JSON.stringify(b)},d.importCompressed=function(a,b){var c;try{c=JSON.parse(a)}catch(e){throw new Error("Invalid compressed format")}{var h=new d;c[0]}return c=f.rest(c),f.each(k,function(a,b){h[a]=c[b]}),b&&h.unlock(b),h._expand(),b&&h.lock(b),h.network=g.getNetworkFromXPubKey(h.xPubKey),h.publicKeyRing.push({xPubKey:h.xPubKey,requestPubKey:h.requestPubKey}),h},d.fromOldCopayWallet=function(a){var b=d.fromExtendedPrivateKey(a.privateKey.extendedPrivateKeyString),c=f.map(a.publicKeyRing.copayersExtPubKeys,function(c){var d,e=c===b.xPubKey;if(e){var f=g.PATHS.REQUEST_KEY;d=new h.HDPrivateKey(b.xPrivKey).derive(f).hdPublicKey}else{var f=g.PATHS.TMP_REQUEST_KEY;d=new h.HDPublicKey(c).derive(f)}var i=new h.HDPublicKey(c).derive("m/2147483646/0/0"),j=i.publicKey.toString("hex"),k=a.publicKeyRing.nicknameFor[j];return e&&(b.copayerName=k),{xPubKey:c,requestPubKey:d.publicKey.toString(),isTemporaryRequestKey:!e,copayerName:k}});return b.addPublicKeyRing(c),b},b.exports=d},{"bitcore-wallet-utils":34,lodash:306,preconditions:307,sjcl:397}],5:[function(a,b,c){var d=b.exports=a("./api");d.Verifier=a("./verifier"),d.Utils=a("bitcore-wallet-utils"),d.sjcl=a("sjcl"),d.Bitcore=a("bitcore-wallet-utils").Bitcore},{"./api":2,"./verifier":9,"bitcore-wallet-utils":34,sjcl:397}],6:[function(a,b,c){var d=a("lodash"),e=function(a){this.name=a||"log",this.level=2};e.prototype.getLevels=function(){return f};var f={debug:0,info:1,log:2,warn:3,error:4,fatal:5};d.each(f,function(a,b){e.prototype[b]=function(){if(a>=f[this.level]){if(Error.stackTraceLimit&&"debug"==this.level){var c=Error.stackTraceLimit;Error.stackTraceLimit=2;var d;try{anerror()}catch(e){d=e.stack}var g=d.split("\n"),h=g[2];h=":"+h.substr(6),Error.stackTraceLimit=c}var i,j="["+b+(h||"")+"] "+arguments[0],i=[].slice.call(arguments,1);console[b]?(i.unshift(j),console[b].apply(console,i)):(i.length&&(j+=JSON.stringify(i)),console.log(j))}}}),e.prototype.setLevel=function(a){this.level=a};{var g=new e("copay");new Error}g.setLevel("info"),b.exports=g},{lodash:306}],7:[function(a,b,c){(function(c,d){var e=a("preconditions").singleton(),f=a("bitcore-wallet-utils"),g=f.Bitcore,h=a("bitcore-payment-protocol"),i={};i._nodeRequest=function(b,c){b.agent=!1;var e=b.httpNode||a("http"===b.proto?"http":"https"),f="POST"==b.method?"post":"get";e[f](b,function(a){if(200!=a.statusCode)return c("HTTP Request Error");var b=[];a.on("data",function(a){b.push(a)}),a.on("end",function(){return b=d.concat(b),c(null,b)})})},i._browserRequest=function(a,b){var c=(a.method||"GET").toUpperCase(),d=a.url,e=a;e.headers=e.headers||{},e.body=e.body||e.data||"";var f=a.xhr||new XMLHttpRequest;f.open(c,d,!0),Object.keys(e.headers).forEach(function(a){var b=e.headers[a];"Content-Length"!==a&&"Content-Transfer-Encoding"!==a&&f.setRequestHeader(a,b)}),f.responseType="arraybuffer",f.onload=function(a){var c=f.response;return b(null,new Uint8Array(c))},f.onerror=function(a){var c;return c=0!==f.status&&f.statusText?f.statusText:"HTTP Request Error",b(c)},f.send(e.body?e.body:null)};var j=function(a){a.url.match(/^((http[s]?):\/)?\/?([^:\/\s]+)((\/\w+)*\/)([\w\-\.]+[^#?\s]+)(.*)?(#[\w\-]+)?$/);if(a.proto=RegExp.$2,a.host=RegExp.$3,a.path=RegExp.$4+RegExp.$6,a.http)return a.http;var b=a.env;return b||(b=c&&!c.browser?"node":"browser"),"node"==b?i._nodeRequest:http=i._browserRequest};i.get=function(a,b){e.checkArgument(a&&a.url);var c=j(a);a.headers=a.headers||{Accept:h.PAYMENT_REQUEST_CONTENT_TYPE,"Content-Type":"application/octet-stream"},c(a,function(c,e){if(c)return b(c);var f;try{var i=h.PaymentRequest.decode(e);f=(new h).makePaymentRequest(i)}catch(j){return b("Could not parse payment protocol:"+j)}var k=(f.get("signature"),f.get("serialized_payment_details")),l=f.verify(!0),m=h.PaymentDetails.decode(k),n=new h;n=n.makePaymentDetails(m);var o=n.get("outputs");if(o.length>1)return b(new Error("Payment Protocol Error: Requests with more that one output are not supported"));var p=o[0],q=p.get("amount");q=q.low+4294967296*q.high;var r="test"==n.get("network")?"testnet":"livenet",s=p.get("script").offset,t=p.get("script").limit,u=new d(new Uint8Array(p.get("script").buffer)),v=u.slice(s,t),w=new g.Address.fromScript(new g.Script(v),r),x=n.get("merchant_data");return x&&(x=x.toString()),b(null,{verified:l.verified,verifyData:{caName:l.caName,selfSigned:l.selfSigned},expires:n.get("expires"),memo:n.get("memo"),time:n.get("time"),merchant_data:x,toAddress:w.toString(),amount:q,network:r,domain:a.host,url:a.url})})},i._getPayProRefundOutputs=function(a,b){b=b.toString(10);var c=new h.Output,e=new g.Address(a),f=e.toObject().hash,i=new g.Script;return i.add(g.Opcode.OP_HASH160).add(new d(f,"hex")).add(g.Opcode.OP_EQUAL),c.set("script",i.toBuffer()),c.set("amount",b),[c]},i._createPayment=function(a,b,c,e){var f=new h;f=f.makePayment(),a&&(a=new d(a),f.set("merchant_data",a));var g=new d(b,"hex");f.set("transactions",[g]);var i=this._getPayProRefundOutputs(c,e);i&&f.set("refund_to",i),f=f.serialize();for(var j=new ArrayBuffer(f.length),k=new Uint8Array(j),l=0;l Hash: ",h," Signature: ",b.proposalSignature),g.verifyMessage(h,b.proposalSignature,j)&&d.checkAddress(a,b.changeAddress)?!0:!1},d.checkTxProposal=function(a,b,c){return c=c||{},this.checkTxProposalBody(a,b)&&(!c.paypro||b.toAddress==c.paypro.toAddress&&b.amount==c.paypro.amount)?!0:!1},b.exports=d},{"./log":6,"bitcore-wallet-utils":34,lodash:306,preconditions:307}],10:[function(a,b,c){(function(a){!function(){function c(a){var b=!1;return function(){if(b)throw new Error("Callback was already called."); b=!0,a.apply(d,arguments)}}var d,e,f={};d=this,null!=d&&(e=d.async),f.noConflict=function(){return d.async=e,f};var g=Object.prototype.toString,h=Array.isArray||function(a){return"[object Array]"===g.call(a)},i=function(a,b){if(a.forEach)return a.forEach(b);for(var c=0;c=a.length&&d())}if(d=d||function(){},!a.length)return d();var f=0;i(a,function(a){b(a,c(e))})},f.forEach=f.each,f.eachSeries=function(a,b,c){if(c=c||function(){},!a.length)return c();var d=0,e=function(){b(a[d],function(b){b?(c(b),c=function(){}):(d+=1,d>=a.length?c():e())})};e()},f.forEachSeries=f.eachSeries,f.eachLimit=function(a,b,c,d){var e=m(b);e.apply(null,[a,c,d])},f.forEachLimit=f.eachLimit;var m=function(a){return function(b,c,d){if(d=d||function(){},!b.length||0>=a)return d();var e=0,f=0,g=0;!function h(){if(e>=b.length)return d();for(;a>g&&f=b.length?d():h())})}()}},n=function(a){return function(){var b=Array.prototype.slice.call(arguments);return a.apply(null,[f.each].concat(b))}},o=function(a,b){return function(){var c=Array.prototype.slice.call(arguments);return b.apply(null,[m(a)].concat(c))}},p=function(a){return function(){var b=Array.prototype.slice.call(arguments);return a.apply(null,[f.eachSeries].concat(b))}},q=function(a,b,c,d){if(b=j(b,function(a,b){return{index:b,value:a}}),d){var e=[];a(b,function(a,b){c(a.value,function(c,d){e[a.index]=d,b(c)})},function(a){d(a,e)})}else a(b,function(a,b){c(a.value,function(a){b(a)})})};f.map=n(q),f.mapSeries=p(q),f.mapLimit=function(a,b,c,d){return r(b)(a,c,d)};var r=function(a){return o(a,q)};f.reduce=function(a,b,c,d){f.eachSeries(a,function(a,d){c(b,a,function(a,c){b=c,d(a)})},function(a){d(a,b)})},f.inject=f.reduce,f.foldl=f.reduce,f.reduceRight=function(a,b,c,d){var e=j(a,function(a){return a}).reverse();f.reduce(e,b,c,d)},f.foldr=f.reduceRight;var s=function(a,b,c,d){var e=[];b=j(b,function(a,b){return{index:b,value:a}}),a(b,function(a,b){c(a.value,function(c){c&&e.push(a),b()})},function(a){d(j(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})};f.filter=n(s),f.filterSeries=p(s),f.select=f.filter,f.selectSeries=f.filterSeries;var t=function(a,b,c,d){var e=[];b=j(b,function(a,b){return{index:b,value:a}}),a(b,function(a,b){c(a.value,function(c){c||e.push(a),b()})},function(a){d(j(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})};f.reject=n(t),f.rejectSeries=p(t);var u=function(a,b,c,d){a(b,function(a,b){c(a,function(c){c?(d(a),d=function(){}):b()})},function(a){d()})};f.detect=n(u),f.detectSeries=p(u),f.some=function(a,b,c){f.each(a,function(a,d){b(a,function(a){a&&(c(!0),c=function(){}),d()})},function(a){c(!1)})},f.any=f.some,f.every=function(a,b,c){f.each(a,function(a,d){b(a,function(a){a||(c(!1),c=function(){}),d()})},function(a){c(!0)})},f.all=f.every,f.sortBy=function(a,b,c){f.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){if(a)return c(a);var d=function(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0};c(null,j(b.sort(d),function(a){return a.value}))})},f.auto=function(a,b){b=b||function(){};var c=l(a),d=c.length;if(!d)return b();var e={},g=[],j=function(a){g.unshift(a)},m=function(a){for(var b=0;bd;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function e(a,b,e,g){return a.started||(a.started=!0),h(b)||(b=[b]),0==b.length?f.setImmediate(function(){a.drain&&a.drain()}):void i(b,function(b){var h={data:b,priority:e,callback:"function"==typeof g?g:null};a.tasks.splice(d(a.tasks,h,c)+1,0,h),a.saturated&&a.tasks.length===a.concurrency&&a.saturated(),f.setImmediate(a.process)})}var g=f.queue(a,b);return g.push=function(a,b,c){e(g,a,b,c)},delete g.unshift,g},f.cargo=function(a,b){var c=!1,d=[],e={tasks:d,payload:b,saturated:null,empty:null,drain:null,drained:!0,push:function(a,c){h(a)||(a=[a]),i(a,function(a){d.push({data:a,callback:"function"==typeof c?c:null}),e.drained=!1,e.saturated&&d.length===b&&e.saturated()}),f.setImmediate(e.process)},process:function g(){if(!c){if(0===d.length)return e.drain&&!e.drained&&e.drain(),void(e.drained=!0);var f="number"==typeof b?d.splice(0,b):d.splice(0,d.length),h=j(f,function(a){return a.data});e.empty&&e.empty(),c=!0,a(h,function(){c=!1;var a=arguments;i(f,function(b){b.callback&&b.callback.apply(null,a)}),g()})}},length:function(){return d.length},running:function(){return c}};return e};var x=function(a){return function(b){var c=Array.prototype.slice.call(arguments,1);b.apply(null,c.concat([function(b){var c=Array.prototype.slice.call(arguments,1);"undefined"!=typeof console&&(b?console.error&&console.error(b):console[a]&&i(c,function(b){console[a](b)}))}]))}};f.log=x("log"),f.dir=x("dir"),f.memoize=function(a,b){var c={},d={};b=b||function(a){return a};var e=function(){var e=Array.prototype.slice.call(arguments),g=e.pop(),h=b.apply(null,e);h in c?f.nextTick(function(){g.apply(null,c[h])}):h in d?d[h].push(g):(d[h]=[g],a.apply(null,e.concat([function(){c[h]=arguments;var a=d[h];delete d[h];for(var b=0,e=a.length;e>b;b++)a[b].apply(null,arguments)}])))};return e.memo=c,e.unmemoized=a,e},f.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},f.times=function(a,b,c){for(var d=[],e=0;a>e;e++)d.push(e);return f.map(d,b,c)},f.timesSeries=function(a,b,c){for(var d=[],e=0;a>e;e++)d.push(e);return f.mapSeries(d,b,c)},f.seq=function(){var a=arguments;return function(){var b=this,c=Array.prototype.slice.call(arguments),d=c.pop();f.reduce(a,c,function(a,c,d){c.apply(b,a.concat([function(){var a=arguments[0],b=Array.prototype.slice.call(arguments,1);d(a,b)}]))},function(a,c){d.apply(b,[a].concat(c))})}},f.compose=function(){return f.seq.apply(null,Array.prototype.reverse.call(arguments))};var y=function(a,b){var c=function(){var c=this,d=Array.prototype.slice.call(arguments),e=d.pop();return a(b,function(a,b){a.apply(c,d.concat([b]))},e)};if(arguments.length>2){var d=Array.prototype.slice.call(arguments,2);return c.apply(this,d)}return c};f.applyEach=n(y),f.applyEachSeries=p(y),f.forever=function(a,b){function c(d){if(d){if(b)return b(d);throw d}a(c)}c()},"undefined"!=typeof b&&b.exports?b.exports=f:"undefined"!=typeof define&&define.amd?define([],function(){return f}):d.async=f}()}).call(this,a("_process"))},{_process:283}],11:[function(a,b,c){(function(c){"use strict";var d=a("jsrsasign"),e=a("./common"),f=a("./rootcerts"),g=a("asn1.js/rfc/3280");e.prototype.x509Sign=function(a,b){var g=this.get("pki_type"),h=this.get("pki_data");h=e.X509Certificates.decode(h),h=h.certificate;var i="none"!==g?g.split("+")[1].toUpperCase():g,j=this.serializeForSig(),k=new d.RSAKey;k.readPrivateKeyFromPEMString(a.toString()),a=k;var l;if("none"!==i){var m=new d.crypto.Signature({alg:i+"withRSA",prov:"cryptojs/jsrsa"});m.init(a),m.updateHex(j.toString("hex")),l=new c(m.sign(),"hex")}else l="";if(b){var n=h[h.length-1],o=n.toString("hex"),p=d.asn1.ASN1Util.getPEMStringFromHex(o,"CERTIFICATE"),q=f.getTrusted(p),r=0;return q||(r=h.length>1?-1:1),{selfSigned:r,isChain:h.length>1,signature:l,caTrusted:!!q,caName:q||null}}return l},e.prototype.x509Verify=function(a){var b=this.get("signature"),c=this.get("pki_type"),g=this.get("pki_data");g=e.X509Certificates.decode(g),g=g.certificate;var h,i,j,k=this.serializeForSig(),l="none"!==c?c.split("+")[1].toUpperCase():c;if("none"!==l){var m=new d.crypto.Signature({alg:l+"withRSA",prov:"cryptojs/jsrsa"}),n=g[0];h=n.toString("hex"),i=d.asn1.ASN1Util.getPEMStringFromHex(h,"CERTIFICATE"),m.initVerifyByCertificatePEM(i),m.updateHex(k.toString("hex")),j=m.verify(b.toString("hex"))}else j=!0;var o=g,p=o[o.length-1];h=p.toString("hex"),i=d.asn1.ASN1Util.getPEMStringFromHex(h,"CERTIFICATE");var q=f.getTrusted(i);if(1===o.length&&!q)return a?{selfSigned:1,isChain:!1,verified:j,caTrusted:!1,caName:null,chainVerified:!1}:j;if(!q)return a?{selfSigned:-1,isChain:o.length>1,verified:j,caTrusted:!1,caName:null,chainVerified:!1}:j;var r=e.verifyCertChain(o,l);return a?{selfSigned:0,isChain:!0,verified:j,caTrusted:!!q,caName:q||null,chainVerified:r}:j&&r},e.verifyCertChain=function(a,b){return"none"===b?!0:a.every(function(h,i){var j=h.toString("hex"),k=d.asn1.ASN1Util.getPEMStringFromHex(j,"CERTIFICATE"),l=f.getTrusted(k),m=a[i+1];if(!m||l)return l?(a.length=0,!0):!1;var n,o=m.toString("hex"),p=d.asn1.ASN1Util.getPEMStringFromHex(o,"CERTIFICATE"),q=new c(o,"hex"),r=g.Certificate.decode(q,"der");if("none"!==b){var s=new d.crypto.Signature({alg:b+"withRSA",prov:"cryptojs/jsrsa"});s.initVerifyByCertificatePEM(p),n=s.pubKey}var t,u=new c(j,"hex"),v=g.Certificate.decode(u,"der"),w=v.signature.data,x=e.validateCertTime(v,r),y=e.validateCertIssuer(v,r);if("none"!==b){var z=new d.crypto.Signature({alg:b+"withRSA",prov:"cryptojs/jsrsa"});z.initVerifyByPublicKey(n);var A=e.getTBSCertificate(u);z.updateHex(A.toString("hex")),t=z.verify(w.toString("hex"))}else t=!0;return x&&y&&t})},b.exports=e}).call(this,a("buffer").Buffer)},{"./common":12,"./rootcerts":14,"asn1.js/rfc/3280":28,buffer:133,jsrsasign:29}],12:[function(a,b,c){(function(c){"use strict";function d(){this.messageType=null,this.message=null}function e(a){var b=new c("Bitcoin Signed Message:\n"),d=n(b.length),e=new c(a),f=n(e.length),g=c.concat([d,b,f,e]),h=m(g);return h}var f=a("bitcore"),g=a("protobufjs/dist/ProtoBuf"),h=a("./rootcerts"),i=f.PublicKey,j=f.PrivateKey,k=f.crypto.Signature,l=f.crypto.ECDSA,m=f.crypto.Hash.sha256sha256,n=f.encoding.BufferWriter.varintBufNum;d.PAYMENT_REQUEST_MAX_SIZE=5e4,d.PAYMENT_MAX_SIZE=5e4,d.PAYMENT_ACK_MAX_SIZE=6e4,d.PAYMENT_REQUEST_CONTENT_TYPE="application/bitcoin-paymentrequest",d.PAYMENT_CONTENT_TYPE="application/bitcoin-payment",d.PAYMENT_ACK_CONTENT_TYPE="application/bitcoin-paymentack",d.X509_ALGORITHM={"1.2.840.113549.1.1.1":"RSA","1.2.840.113549.1.1.2":"RSA_MD2","1.2.840.113549.1.1.4":"RSA_MD5","1.2.840.113549.1.1.5":"RSA_SHA1","1.2.840.113549.1.1.11":"RSA_SHA256","1.2.840.113549.1.1.12":"RSA_SHA384","1.2.840.113549.1.1.13":"RSA_SHA512","1.2.840.10045.4.3.2":"ECDSA_SHA256","1.2.840.10045.4.3.3":"ECDSA_SHA384","1.2.840.10045.4.3.4":"ECDSA_SHA512"},d.getAlgorithm=function(a,b){return Array.isArray(a)&&(a=a.join(".")),a=d.X509_ALGORITHM[a],"undefined"!=typeof b?(a=a.split("_"),b===!0?{cipher:a[0],hash:a[1]}:a[b]):a},d.getTBSCertificate=function(a){var b=0,c=0;for(b=0;bc&&48===a[b]&&c++;var d=0,e=0;for(d=a.length-1;d>0&&(2!==e||48!==a[d]);d--)2>e&&0===a[d]&&e++;return a.slice(b,d)},d.validateCertTime=function(a,b){var c=!0,d=Date.now(),e=a.tbsCertificate.validity.notBefore.value,f=a.tbsCertificate.validity.notAfter.value,g=b.tbsCertificate.validity.notBefore.value,h=b.tbsCertificate.validity.notAfter.value;return(e>d||d>f||g>d||d>h)&&(c=!1),c},d.validateCertIssuer=function(a,b){var c=a.tbsCertificate.issuer,d=b.tbsCertificate.subject,e=c.type===d.type&&c.value.every(function(a,b){var c=d.value[b];return a.every(function(a,b){var d=c[b],e=a.type.join("."),f=d.type.join("."),g=a.value.toString("hex"),h=d.value.toString("hex");return e===f&&g===h})});return e},d.RootCerts=h,d.proto={},d.proto.Output="message Output { optional uint64 amount = 1 [default = 0]; optional bytes script = 2;}\n",d.proto.PaymentDetails='message PaymentDetails { optional string network = 1 [default = "main"]; repeated Output outputs = 2; required uint64 time = 3; optional uint64 expires = 4; optional string memo = 5; optional string payment_url = 6; optional bytes merchant_data = 7;}\n',d.proto.PaymentRequest='message PaymentRequest { optional uint32 payment_details_version = 1 [default = 1]; optional string pki_type = 2 [default = "none"]; optional bytes pki_data = 3; required bytes serialized_payment_details = 4; optional bytes signature = 5;}\n',d.proto.Payment="message Payment { optional bytes merchant_data = 1; repeated bytes transactions = 2; repeated Output refund_to = 3; optional string memo = 4;}\n",d.proto.PaymentACK="message PaymentACK { required Payment payment = 1; optional string memo = 2;}\n",d.proto.X509Certificates="message X509Certificates { repeated bytes certificate = 1;}\n",d.proto.all="",d.proto.all=d.proto.all+d.proto.Output,d.proto.all=d.proto.all+d.proto.PaymentDetails,d.proto.all=d.proto.all+d.proto.PaymentRequest,d.proto.all=d.proto.all+d.proto.Payment,d.proto.all=d.proto.all+d.proto.PaymentACK,d.proto.all=d.proto.all+d.proto.X509Certificates,d.builder=g.loadProto(d.proto.all),d.Output=d.builder.build("Output"),d.PaymentDetails=d.builder.build("PaymentDetails"),d.PaymentRequest=d.builder.build("PaymentRequest"),d.Payment=d.builder.build("Payment"),d.PaymentACK=d.builder.build("PaymentACK"),d.X509Certificates=d.builder.build("X509Certificates"),d.prototype.makeOutput=function(a){return this.messageType="Output",this.message=new d.Output,this.setObj(a),this},d.prototype.makePaymentDetails=function(a){return this.messageType="PaymentDetails",this.message=new d.PaymentDetails,this.setObj(a),this},d.prototype.makePaymentRequest=function(a){return this.messageType="PaymentRequest",this.message=new d.PaymentRequest,this.setObj(a),this},d.prototype.makePayment=function(a){return this.messageType="Payment",this.message=new d.Payment,this.setObj(a),this},d.prototype.makePaymentACK=function(a){return this.messageType="PaymentACK",this.message=new d.PaymentACK,this.setObj(a),this},d.prototype.makeX509Certificates=function(a){return this.messageType="X509Certificates",this.message=new d.X509Certificates,this.setObj(a),this},d.prototype.isValidSize=function(){var a=this.serialize();return"PaymentRequest"===this.messageType?a.length0&&"\ufeff"===k[0][0]&&(k[0]=k[0].substring(1)),a.body=k.join("")),b._json)try{a.body=JSON.parse(a.body,b._jsonReviver)}catch(c){}r("emitting complete",b.uri.href),"undefined"!=typeof a.body||b._json||(a.body=null===b.encoding?new d(0):""),b.emit("complete",a,a.body)})}else b.on("end",function(){return b._aborted?void r("aborted",b.uri.href):void b.emit("complete",a)});r("finish init function",b.uri.href)}},q.prototype.abort=function(){var a=this;a._aborted=!0,a.req?a.req.abort():a.response&&a.response.abort(),a.emit("abort")},q.prototype.pipeDest=function(a){var b=this,c=b.response;if(a.headers&&!a.headersSent){if(c.caseless.has("content-type")){var d=c.caseless.has("content-type");a.setHeader?a.setHeader(d,c.headers[d]):a.headers[d]=c.headers[d]}if(c.caseless.has("content-length")){var e=c.caseless.has("content-length");a.setHeader?a.setHeader(e,c.headers[e]):a.headers[e]=c.headers[e]}}if(a.setHeader&&!a.headersSent){for(var f in c.headers)b.gzip&&"content-encoding"===f||a.setHeader(f,c.headers[f]);a.statusCode=c.statusCode}b.pipefilter&&b.pipefilter(c,a)},q.prototype.qs=function(a,b){var c,d=this;c=!b&&d.uri.query?d.qsLib.parse(d.uri.query,d.qsParseOptions):{};for(var e in a)c[e]=a[e];if(""===d.qsLib.stringify(c,d.qsStringifyOptions))return d;var f=d.qsLib.stringify(c,d.qsStringifyOptions);return d.uri=u.parse(d.uri.href.split("?")[0]+"?"+p(f)),d.url=d.uri,d.path=d.uri.path,d},q.prototype.form=function(a){var b=this;return a?(b.setHeader("content-type","application/x-www-form-urlencoded"),b.body="string"==typeof a?a.toString("utf8"):b.qsLib.stringify(a,b.qsStringifyOptions).toString("utf8"),b.body=p(b.body),b):(b._form=new K,b._form.on("error",function(a){a.message="form-data: "+a.message,b.emit("error",a),b.abort()}),b._form)},q.prototype.multipart=function(a){var b=this;return b._multipart.onRequest(a),b._multipart.chunked||(b.body=b._multipart.body),b},q.prototype.json=function(a){var b=this;return b.hasHeader("accept")||b.setHeader("accept","application/json"),b._json=!0,"boolean"==typeof a?void 0!==b.body&&(b.body=/^application\/x-www-form-urlencoded\b/.test(b.getHeader("content-type"))?p(b.body):T(b.body),b.hasHeader("content-type")||b.setHeader("content-type","application/json")):(b.body=T(a),b.hasHeader("content-type")||b.setHeader("content-type","application/json")),"function"==typeof b.jsonReviver&&(b._jsonReviver=b.jsonReviver),b},q.prototype.getHeader=function(a,b){var c,d,e,f=this;return b||(b=f.headers),Object.keys(b).forEach(function(f){f.length===a.length&&(d=new RegExp(a,"i"),e=f.match(d),e&&(c=b[f]))}),c},q.prototype.auth=function(a,b,c,d){var e=this;return e._auth.onRequest(a,b,c,d),e},q.prototype.aws=function(a,b){var c=this;if(!b)return c._aws=a,c;var d=new Date;c.setHeader("date",d.toUTCString());var e={key:a.key,secret:a.secret,verb:c.method.toUpperCase(),date:d,contentType:c.getHeader("content-type")||"",md5:c.getHeader("content-md5")||"",amazonHeaders:D.canonicalizeHeaders(c.headers)},f=c.uri.path;return a.bucket&&f?e.resource="/"+a.bucket+f:a.bucket&&!f?e.resource="/"+a.bucket:!a.bucket&&f?e.resource=f:a.bucket||f||(e.resource="/"),e.resource=D.canonicalizeResource(e.resource),c.setHeader("authorization",D.authorization(e)),c},q.prototype.httpSignature=function(a){var b=this;return E.signRequest({getHeader:function(a){return b.getHeader(a,b.headers)},setHeader:function(a,c){b.setHeader(a,c)},method:b.method,path:b.path},a),r("httpSignature authorization",b.getHeader("authorization")),b},q.prototype.hawk=function(a){var b=this;b.setHeader("Authorization",C.client.header(b.uri,b.method,a).field)},q.prototype.oauth=function(a){var b=this;return b._oauth.onRequest(a),b},q.prototype.jar=function(a){var b,c=this;if(0===c._redirect.redirectsFollowed&&(c.originalCookieHeader=c.getHeader("cookie")),a){var d=a&&a.getCookieString?a:X,e=c.uri.href;d&&(b=d.getCookieString(e))}else b=!1,c._disableCookies=!0;return b&&b.length&&(c.originalCookieHeader?c.setHeader("cookie",c.originalCookieHeader+"; "+b):c.setHeader("cookie",b)),c._jar=a,c},q.prototype.pipe=function(a,b){var c=this;if(c.response){if(c._destdata)throw new Error("You cannot pipe after data has been emitted from the response.");if(c._ended)throw new Error("You cannot pipe after the response has been ended.");return w.Stream.prototype.pipe.call(c,a,b),c.pipeDest(a),a}return c.dests.push(a),w.Stream.prototype.pipe.call(c,a,b),a},q.prototype.write=function(){var a=this;return a._started||a.start(),a.req.write.apply(a.req,arguments)},q.prototype.end=function(a){var b=this;a&&b.write(a),b._started||b.start(),b.req.end()},q.prototype.pause=function(){var a=this;a.response?a.response.pause.apply(a.response,arguments):a._paused=!0},q.prototype.resume=function(){var a=this;a.response?a.response.resume.apply(a.response,arguments):a._paused=!1},q.prototype.destroy=function(){var a=this;a._ended?a.response&&a.response.destroy():a.end()},q.defaultProxyHeaderWhiteList=Z.slice(),q.defaultProxyHeaderExclusiveList=$.slice(),q.prototype.toJSON=n,b.exports=q}).call(this,a("_process"),a("buffer").Buffer)},{"./lib/auth":313,"./lib/cookies":314,"./lib/copy":315,"./lib/getProxyFromURI":316,"./lib/har":317,"./lib/helpers":318,"./lib/multipart":319,"./lib/oauth":320,"./lib/redirect":321,_process:283,"aws-sign2":322,bl:323,buffer:133,caseless:332,"forever-agent":335,"form-data":336,hawk:362,http:275,"http-signature":363,https:279,"mime-types":380,qs:385,querystring:287,stream:299,stringstream:390,"tunnel-agent":395,url:301,util:303,zlib:132}],397:[function(a,b,c){"use strict";function d(a){throw a}function e(a,b,c){4!==b.length&&d(new n.exception.invalid("invalid aes block size"));var e=a.b[c],f=b[0]^e[0],g=b[c?3:1]^e[1],h=b[2]^e[2];b=b[c?1:3]^e[3];var i,j,k,l,m=e.length/4-2,o=4,p=[0,0,0,0];i=a.k[c],a=i[0];var q=i[1],r=i[2],s=i[3],t=i[4];for(l=0;m>l;l++)i=a[f>>>24]^q[g>>16&255]^r[h>>8&255]^s[255&b]^e[o],j=a[g>>>24]^q[h>>16&255]^r[b>>8&255]^s[255&f]^e[o+1],k=a[h>>>24]^q[b>>16&255]^r[f>>8&255]^s[255&g]^e[o+2],b=a[b>>>24]^q[f>>16&255]^r[g>>8&255]^s[255&h]^e[o+3],o+=4,f=i,g=j,h=k;for(l=0;4>l;l++)p[c?3&-l:l]=t[f>>>24]<<24^t[g>>16&255]<<16^t[h>>8&255]<<8^t[255&b]^e[o++],i=f,f=g,g=h,h=b,b=i;return p}function f(a,b){var c,d,e,f=b.slice(0),g=a.r,h=a.b,i=g[0],j=g[1],k=g[2],l=g[3],m=g[4],n=g[5],o=g[6],p=g[7];for(c=0;64>c;c++)16>c?d=f[c]:(d=f[c+1&15],e=f[c+14&15],d=f[15&c]=(d>>>7^d>>>18^d>>>3^d<<25^d<<14)+(e>>>17^e>>>19^e>>>10^e<<15^e<<13)+f[15&c]+f[c+9&15]|0),d=d+p+(m>>>6^m>>>11^m>>>25^m<<26^m<<21^m<<7)+(o^m&(n^o))+h[c],p=o,o=n,n=m,m=l+d|0,l=k,k=j,j=i,i=d+(j&k^l&(j^k))+(j>>>2^j>>>13^j>>>22^j<<30^j<<19^j<<10)|0;g[0]=g[0]+i|0,g[1]=g[1]+j|0,g[2]=g[2]+k|0,g[3]=g[3]+l|0,g[4]=g[4]+m|0,g[5]=g[5]+n|0,g[6]=g[6]+o|0,g[7]=g[7]+p|0}function g(a,b){var c,d=n.random.w[a],e=[];for(c in d)d.hasOwnProperty(c)&&e.push(d[c]);for(c=0;cb&&(a.f[b]=a.f[b]+1|0,!a.f[b]);b++);return a.A.encrypt(a.f)}function k(a,b){return function(){b.apply(a,arguments)}}var l=void 0,m=!1,n={cipher:{},hash:{},keyexchange:{},mode:{},misc:{},codec:{},exception:{corrupt:function(a){this.toString=function(){return"CORRUPT: "+this.message},this.message=a},invalid:function(a){this.toString=function(){return"INVALID: "+this.message},this.message=a},bug:function(a){this.toString=function(){return"BUG: "+this.message},this.message=a},notReady:function(a){this.toString=function(){return"NOT READY: "+this.message},this.message=a}}};"undefined"!=typeof b&&b.exports&&(b.exports=n),"function"==typeof define&&define([],function(){return n}),n.cipher.aes=function(a){this.k[0][0][0]||this.D();var b,c,e,f,g=this.k[0][4],h=this.k[1];b=a.length;var i=1;for(4!==b&&6!==b&&8!==b&&d(new n.exception.invalid("invalid aes key size")),this.b=[e=a.slice(0),f=[]],a=b;4*b+28>a;a++)c=e[a-1],(0===a%b||8===b&&4===a%b)&&(c=g[c>>>24]<<24^g[c>>16&255]<<16^g[c>>8&255]<<8^g[255&c],0===a%b&&(c=c<<8^c>>>24^i<<24,i=i<<1^283*(i>>7))),e[a]=e[a-b]^c;for(b=0;a;b++,a--)c=e[3&b?a:a-4],f[b]=4>=a||4>b?c:h[0][g[c>>>24]]^h[1][g[c>>16&255]]^h[2][g[c>>8&255]]^h[3][g[255&c]]},n.cipher.aes.prototype={encrypt:function(a){return e(this,a,0)},decrypt:function(a){return e(this,a,1)},k:[[[],[],[],[],[]],[[],[],[],[],[]]],D:function(){var a,b,c,d,e,f,g,h=this.k[0],i=this.k[1],j=h[4],k=i[4],l=[],m=[];for(a=0;256>a;a++)m[(l[a]=a<<1^283*(a>>7))^a]=a;for(b=c=0;!j[b];b^=d||1,c=m[c]||1)for(f=c^c<<1^c<<2^c<<3^c<<4,f=f>>8^255&f^99,j[b]=f,k[f]=b,e=l[a=l[d=l[b]]],g=16843009*e^65537*a^257*d^16843008*b,e=257*l[f]^16843008*f,a=0;4>a;a++)h[a][b]=e=e<<24^e>>>8,i[a][f]=g=g<<24^g>>>8;for(a=0;5>a;a++)h[a]=h[a].slice(0),i[a]=i[a].slice(0)}},n.bitArray={bitSlice:function(a,b,c){return a=n.bitArray.P(a.slice(b/32),32-(31&b)).slice(1),c===l?a:n.bitArray.clamp(a,c-b)},extract:function(a,b,c){var d=Math.floor(-b-c&31);return(-32&(b+c-1^b)?a[b/32|0]<<32-d^a[b/32+1|0]>>>d:a[b/32|0]>>>d)&(1<0&&b&&(a[c-1]=n.bitArray.partial(b,a[c-1]&2147483648>>b-1,1)),a},partial:function(a,b,c){return 32===a?b:(c?0|b:b<<32-a)+1099511627776*a},getPartial:function(a){return Math.round(a/1099511627776)||32},equal:function(a,b){if(n.bitArray.bitLength(a)!==n.bitArray.bitLength(b))return m;var c,d=0;for(c=0;c=32;b-=32)d.push(c),c=0;if(0===b)return d.concat(a);for(e=0;e>>b),c=a[e]<<32-b;return e=a.length?a[a.length-1]:0,a=n.bitArray.getPartial(e),d.push(n.bitArray.partial(b+a&31,b+a>32?c:d.pop(),1)),d},l:function(a,b){return[a[0]^b[0],a[1]^b[1],a[2]^b[2],a[3]^b[3]]},byteswapM:function(a){var b,c;for(b=0;b>>24|c>>>8&65280|(65280&c)<<8|c<<24;return a}},n.codec.utf8String={fromBits:function(a){var b,c,d="",e=n.bitArray.bitLength(a);for(b=0;e/8>b;b++)0===(3&b)&&(c=a[b/4]),d+=String.fromCharCode(c>>>24),c<<=8;return decodeURIComponent(escape(d))},toBits:function(a){a=unescape(encodeURIComponent(a));var b,c=[],d=0;for(b=0;b>>e)>>>26),6>e?(g=a[c]<<6-e,e+=26,c++):(g<<=6,e-=6);for(;3&d.length&&!b;)d+="=";return d},toBits:function(a,b){a=a.replace(/\s|=/g,"");var c,e,f=[],g=0,h=n.codec.base64.J,i=0;for(b&&(h=h.substr(0,62)+"-_"),c=0;ce&&d(new n.exception.invalid("this isn't base64!")),g>26?(g-=26,f.push(i^e>>>g),i=e<<32-g):(g+=6,i^=e<<32-g);return 56&g&&f.push(n.bitArray.partial(56&g,i,1)),f}},n.codec.base64url={fromBits:function(a){return n.codec.base64.fromBits(a,1,1)},toBits:function(a){return n.codec.base64.toBits(a,1)}},n.hash.sha256=function(a){this.b[0]||this.D(),a?(this.r=a.r.slice(0),this.o=a.o.slice(0),this.h=a.h):this.reset()},n.hash.sha256.hash=function(a){return(new n.hash.sha256).update(a).finalize()},n.hash.sha256.prototype={blockSize:512,reset:function(){return this.r=this.N.slice(0),this.o=[],this.h=0,this},update:function(a){"string"==typeof a&&(a=n.codec.utf8String.toBits(a));var b,c=this.o=n.bitArray.concat(this.o,a);for(b=this.h,a=this.h=b+n.bitArray.bitLength(a),b=512+b&-512;a>=b;b+=512)f(this,c.splice(0,16));return this},finalize:function(){var a,b=this.o,c=this.r,b=n.bitArray.concat(b,[n.bitArray.partial(1,1)]);for(a=b.length+2;15&a;a++)b.push(0);for(b.push(Math.floor(this.h/4294967296)),b.push(0|this.h);b.length;)f(this,b.splice(0,16));return this.reset(),c},N:[],b:[],D:function(){function a(a){return 4294967296*(a-Math.floor(a))|0}var b,c=0,d=2;a:for(;64>c;d++){for(b=2;d>=b*b;b++)if(0===d%b)continue a;8>c&&(this.N[c]=a(Math.pow(d,.5))),this.b[c]=a(Math.pow(d,1/3)),c++}}},n.mode.ccm={name:"ccm",encrypt:function(a,b,c,e,f){var g,h=b.slice(0),i=n.bitArray,j=i.bitLength(c)/8,k=i.bitLength(h)/8;for(f=f||64,e=e||[],7>j&&d(new n.exception.invalid("ccm: iv must be at least 7 bytes")),g=2;4>g&&k>>>8*g;g++);return 15-j>g&&(g=15-j),c=i.clamp(c,8*(15-g)),b=n.mode.ccm.L(a,b,c,e,f,g),h=n.mode.ccm.p(a,h,c,b,f,g),i.concat(h.data,h.tag)},decrypt:function(a,b,c,e,f){f=f||64,e=e||[];var g=n.bitArray,h=g.bitLength(c)/8,i=g.bitLength(b),j=g.clamp(b,i-f),k=g.bitSlice(b,i-f),i=(i-f)/8;for(7>h&&d(new n.exception.invalid("ccm: iv must be at least 7 bytes")),b=2;4>b&&i>>>8*b;b++);return 15-h>b&&(b=15-h),c=g.clamp(c,8*(15-b)),j=n.mode.ccm.p(a,j,c,k,f,b),a=n.mode.ccm.L(a,j.data,c,e,f,b),g.equal(j.tag,a)||d(new n.exception.corrupt("ccm: tag doesn't match")),j.data},L:function(a,b,c,e,f,g){var h=[],i=n.bitArray,j=i.l;if(f/=8,(f%2||4>f||f>16)&&d(new n.exception.invalid("ccm: invalid tag length")),(4294967295=c?h=[i.partial(16,c)]:4294967295>=c&&(h=i.concat([i.partial(16,65534)],[c])),h=i.concat(h,e),e=0;eg;g+=4)c[3]++,e=a.encrypt(c),b[g]^=e[0],b[g+1]^=e[1],b[g+2]^=e[2],b[g+3]^=e[3];return{tag:d,data:h.clamp(b,j)}}},n.mode.ocb2={name:"ocb2",encrypt:function(a,b,c,e,f,g){128!==n.bitArray.bitLength(c)&&d(new n.exception.invalid("ocb iv must be 128 bits"));var h,i=n.mode.ocb2.H,j=n.bitArray,k=j.l,l=[0,0,0,0];c=i(a.encrypt(c));var m,o=[];for(e=e||[],f=f||64,h=0;h+4c+4;c+=4)h=l(o,a.decrypt(l(o,b.slice(c,c+4)))),m=l(m,h),q=q.concat(h),o=j(o);return i=p-32*c,h=a.encrypt(l(o,[0,0,0,i])),h=l(h,k.clamp(b.slice(c),i).concat([0,0,0])),m=l(m,h),m=a.encrypt(l(m,l(o,j(o)))),e.length&&(m=l(m,g?e:n.mode.ocb2.pmac(a,e))),k.equal(k.clamp(m,f),k.bitSlice(b,p))||d(new n.exception.corrupt("ocb: tag doesn't match")),q.concat(k.clamp(h,i))},pmac:function(a,b){var c,d=n.mode.ocb2.H,e=n.bitArray,f=e.l,g=[0,0,0,0],h=a.encrypt([0,0,0,0]),h=f(h,d(d(h)));for(c=0;c+4e.bitLength(c)&&(h=f(h,d(h)),c=e.concat(c,[-2147483648,0,0,0])),g=f(g,c),a.encrypt(f(d(f(h,d(h))),g))},H:function(a){return[a[0]<<1^a[1]>>>31,a[1]<<1^a[2]>>>31,a[2]<<1^a[3]>>>31,a[3]<<1^135*(a[0]>>>31)]}},n.mode.gcm={name:"gcm",encrypt:function(a,b,c,d,e){var f=b.slice(0);return b=n.bitArray,d=d||[],a=n.mode.gcm.p(!0,a,f,d,c,e||128),b.concat(a.data,a.tag)},decrypt:function(a,b,c,e,f){var g=b.slice(0),h=n.bitArray,i=h.bitLength(g);return f=f||128,e=e||[],i>=f?(b=h.bitSlice(g,i-f),g=h.bitSlice(g,0,i-f)):(b=g,g=[]),a=n.mode.gcm.p(m,a,g,e,c,f),h.equal(a.tag,b)||d(new n.exception.corrupt("gcm: tag doesn't match")),a.data},Z:function(a,b){var c,d,e,f,g,h=n.bitArray.l;for(e=[0,0,0,0],f=b.slice(0),c=0;128>c;c++){for((d=0!==(a[Math.floor(c/32)]&1<<31-c%32))&&(e=h(e,f)),g=0!==(1&f[3]),d=3;d>0;d--)f[d]=f[d]>>>1|(1&f[d-1])<<31;f[0]>>>=1,g&&(f[0]^=-520093696)}return e},g:function(a,b,c){var d,e=c.length;for(b=b.slice(0),d=0;e>d;d+=4)b[0]^=4294967295&c[d],b[1]^=4294967295&c[d+1],b[2]^=4294967295&c[d+2],b[3]^=4294967295&c[d+3],b=n.mode.gcm.Z(b,a);return b},p:function(a,b,c,d,e,f){var g,h,i,j,k,l,m,o,p=n.bitArray;for(l=c.length,m=p.bitLength(c),o=p.bitLength(d),h=p.bitLength(e),g=b.encrypt([0,0,0,0]),96===h?(e=e.slice(0),e=p.concat(e,[1])):(e=n.mode.gcm.g(g,[0,0,0,0],e),e=n.mode.gcm.g(g,e,[0,0,Math.floor(h/4294967296),4294967295&h])),h=n.mode.gcm.g(g,[0,0,0,0],d),k=e.slice(0),d=h.slice(0),a||(d=n.mode.gcm.g(g,h,c)),j=0;l>j;j+=4)k[3]++,i=b.encrypt(k),c[j]^=i[0],c[j+1]^=i[1],c[j+2]^=i[2],c[j+3]^=i[3];return c=p.clamp(c,m),a&&(d=n.mode.gcm.g(g,h,c)),a=[Math.floor(o/4294967296),4294967295&o,Math.floor(m/4294967296),4294967295&m],d=n.mode.gcm.g(g,d,a),i=b.encrypt(e),d[0]^=i[0],d[1]^=i[1],d[2]^=i[2],d[3]^=i[3],{tag:p.bitSlice(d,0,f),data:c}}},n.misc.hmac=function(a,b){this.M=b=b||n.hash.sha256;var c,d=[[],[]],e=b.prototype.blockSize/32;for(this.n=[new b,new b],a.length>e&&(a=b.hash(a)),c=0;e>c;c++)d[0][c]=909522486^a[c],d[1][c]=1549556828^a[c];this.n[0].update(d[0]),this.n[1].update(d[1]),this.G=new b(this.n[0])},n.misc.hmac.prototype.encrypt=n.misc.hmac.prototype.mac=function(a){return this.Q&&d(new n.exception.invalid("encrypt on already updated hmac called!")),this.update(a),this.digest(a)},n.misc.hmac.prototype.reset=function(){this.G=new this.M(this.n[0]),this.Q=m},n.misc.hmac.prototype.update=function(a){this.Q=!0,this.G.update(a)},n.misc.hmac.prototype.digest=function(){var a=this.G.finalize(),a=new this.M(this.n[1]).update(a).finalize();return this.reset(),a},n.misc.pbkdf2=function(a,b,c,e,f){c=c||1e3,(0>e||0>c)&&d(n.exception.invalid("invalid params to pbkdf2")),"string"==typeof a&&(a=n.codec.utf8String.toBits(a)),"string"==typeof b&&(b=n.codec.utf8String.toBits(b)),f=f||n.misc.hmac,a=new f(a);var g,h,i,j,k=[],l=n.bitArray;for(j=1;32*k.length<(e||1);j++){for(f=g=a.encrypt(l.concat(b,[j])),h=1;c>h;h++)for(g=a.encrypt(g),i=0;ig;g++)f.push(4294967296*Math.random()|0);for(g=0;g=1<this.j&&(this.j=h),this.F++,this.b=n.hash.sha256.hash(this.b.concat(f)),this.A=new n.cipher.aes(this.b),c=0;4>c&&(this.f[c]=this.f[c]+1|0,!this.f[c]);c++);}for(c=0;a>c;c+=4)0===(c+1)%this.S&&i(this),f=j(this),e.push(f[0],f[1],f[2],f[3]);return i(this),e.slice(0,a)},setDefaultParanoia:function(a,b){0===a&&"Setting paranoia=0 will ruin your security; use it only for testing"!==b&&d("Setting paranoia=0 will ruin your security; use it only for testing"),this.B=a},addEntropy:function(a,b,c){c=c||"user";var e,f,h=(new Date).valueOf(),i=this.s[c],j=this.isReady(),k=0;switch(e=this.K[c],e===l&&(e=this.K[c]=this.W++),i===l&&(i=this.s[c]=0),this.s[c]=(this.s[c]+1)%this.c.length,typeof a){case"number":b===l&&(b=1),this.c[i].update([e,this.C++,1,b,h,1,0|a]);break;case"object":if(c=Object.prototype.toString.call(a),"[object Uint32Array]"===c){for(f=[],c=0;c0;)b++,f>>>=1;this.c[i].update([e,this.C++,2,b,h,a.length].concat(a))}break;case"string":b===l&&(b=a.length),this.c[i].update([e,this.C++,3,b,h,a.length]),this.c[i].update(a);break;default:k=1}k&&d(new n.exception.bug("random: addEntropy only supports number, array of numbers or string")),this.i[i]+=b,this.d+=b,j===this.m&&(this.isReady()!==this.m&&g("seeded",Math.max(this.j,this.d)),g("progress",this.getProgress()))},isReady:function(a){return a=this.I[a!==l?a:this.B],this.j&&this.j>=a?this.i[0]>this.R&&(new Date).valueOf()>this.O?this.u|this.t:this.t:this.d>=a?this.u|this.m:this.m},getProgress:function(a){return a=this.I[a?a:this.B],this.j>=a?1:this.d>a?1:this.d/a},startCollectors:function(){this.q||(this.a={loadTimeCollector:k(this,this.aa),mouseCollector:k(this,this.ba),keyboardCollector:k(this,this.$),accelerometerCollector:k(this,this.U),touchCollector:k(this,this.da)},window.addEventListener?(window.addEventListener("load",this.a.loadTimeCollector,m),window.addEventListener("mousemove",this.a.mouseCollector,m),window.addEventListener("keypress",this.a.keyboardCollector,m),window.addEventListener("devicemotion",this.a.accelerometerCollector,m),window.addEventListener("touchmove",this.a.touchCollector,m)):document.attachEvent?(document.attachEvent("onload",this.a.loadTimeCollector),document.attachEvent("onmousemove",this.a.mouseCollector),document.attachEvent("keypress",this.a.keyboardCollector)):d(new n.exception.bug("can't attach event")),this.q=!0)},stopCollectors:function(){this.q&&(window.removeEventListener?(window.removeEventListener("load",this.a.loadTimeCollector,m),window.removeEventListener("mousemove",this.a.mouseCollector,m),window.removeEventListener("keypress",this.a.keyboardCollector,m),window.removeEventListener("devicemotion",this.a.accelerometerCollector,m),window.removeEventListener("touchmove",this.a.touchCollector,m)):document.detachEvent&&(document.detachEvent("onload",this.a.loadTimeCollector),document.detachEvent("onmousemove",this.a.mouseCollector),document.detachEvent("keypress",this.a.keyboardCollector)),this.q=m)},addEventListener:function(a,b){this.w[a][this.V++]=b},removeEventListener:function(a,b){var c,d,e=this.w[a],f=[];for(d in e)e.hasOwnProperty(d)&&e[d]===b&&f.push(d);for(c=0;c=h.iter||64!==h.ts&&96!==h.ts&&128!==h.ts||128!==h.ks&&192!==h.ks&&256!==h.ks||2>h.iv.length||4=b.iter||64!==b.ts&&96!==b.ts&&128!==b.ts||128!==b.ks&&192!==b.ks&&256!==b.ks||!b.iv||2>b.iv.length||40&&!this.encoding){var a=this.packetBuffer.shift();this.packet(a)}},d.prototype.cleanup=function(){for(var a;a=this.subs.shift();)a.destroy();this.packetBuffer=[],this.encoding=!1,this.decoder.destroy()},d.prototype.close=d.prototype.disconnect=function(){this.skipReconnect=!0,this.backoff.reset(),this.readyState="closed",this.engine&&this.engine.close()},d.prototype.onclose=function(a){k("close"),this.cleanup(),this.backoff.reset(),this.readyState="closed",this.emit("close",a),this._reconnection&&!this.skipReconnect&&this.reconnect()},d.prototype.reconnect=function(){if(this.reconnecting||this.skipReconnect)return this;var a=this;if(this.backoff.attempts>=this._reconnectionAttempts)k("reconnect failed"),this.backoff.reset(),this.emitAll("reconnect_failed"),this.reconnecting=!1;else{var b=this.backoff.duration();k("will wait %dms before reconnect attempt",b),this.reconnecting=!0;var c=setTimeout(function(){a.skipReconnect||(k("attempting reconnect"),a.emitAll("reconnect_attempt",a.backoff.attempts),a.emitAll("reconnecting",a.backoff.attempts),a.skipReconnect||a.open(function(b){b?(k("reconnect attempt error"),a.reconnecting=!1,a.reconnect(),a.emitAll("reconnect_error",b.data)):(k("reconnect success"),a.onreconnect())}))},b);this.subs.push({destroy:function(){clearTimeout(c)}})}},d.prototype.onreconnect=function(){var a=this.backoff.attempts;this.reconnecting=!1,this.backoff.reset(),this.updateSocketIds(),this.emitAll("reconnect",a)}},{"./on":401,"./socket":402,"./url":403,backo2:404,"component-bind":405,"component-emitter":406,debug:407,"engine.io-client":408,indexof:439,"object-component":440,"socket.io-parser":443}],401:[function(a,b,c){function d(a,b,c){return a.on(b,c),{destroy:function(){a.removeListener(b,c)}}}b.exports=d},{}],402:[function(a,b,c){function d(a,b){this.io=a,this.nsp=b,this.json=this,this.ids=0,this.acks={},this.io.autoConnect&&this.open(),this.receiveBuffer=[],this.sendBuffer=[],this.connected=!1,this.disconnected=!0}var e=a("socket.io-parser"),f=a("component-emitter"),g=a("to-array"),h=a("./on"),i=a("component-bind"),j=a("debug")("socket.io-client:socket"),k=a("has-binary");b.exports=c=d;var l={connect:1,connect_error:1,connect_timeout:1,disconnect:1,error:1,reconnect:1,reconnect_attempt:1,reconnect_failed:1,reconnect_error:1,reconnecting:1},m=f.prototype.emit;f(d.prototype),d.prototype.subEvents=function(){if(!this.subs){var a=this.io;this.subs=[h(a,"open",i(this,"onopen")),h(a,"packet",i(this,"onpacket")),h(a,"close",i(this,"onclose"))]}},d.prototype.open=d.prototype.connect=function(){return this.connected?this:(this.subEvents(),this.io.open(),"open"==this.io.readyState&&this.onopen(),this)},d.prototype.send=function(){var a=g(arguments);return a.unshift("message"),this.emit.apply(this,a),this},d.prototype.emit=function(a){if(l.hasOwnProperty(a))return m.apply(this,arguments),this;var b=g(arguments),c=e.EVENT;k(b)&&(c=e.BINARY_EVENT);var d={type:c,data:b};return"function"==typeof b[b.length-1]&&(j("emitting packet with ack id %d",this.ids),this.acks[this.ids]=b.pop(),d.id=this.ids++),this.connected?this.packet(d):this.sendBuffer.push(d),this},d.prototype.packet=function(a){a.nsp=this.nsp,this.io.packet(a)},d.prototype.onopen=function(){j("transport is open - connecting"),"/"!=this.nsp&&this.packet({type:e.CONNECT})},d.prototype.onclose=function(a){j("close (%s)",a),this.connected=!1,this.disconnected=!0,delete this.id,this.emit("disconnect",a)},d.prototype.onpacket=function(a){if(a.nsp==this.nsp)switch(a.type){case e.CONNECT:this.onconnect();break;case e.EVENT:this.onevent(a);break;case e.BINARY_EVENT:this.onevent(a);break;case e.ACK:this.onack(a);break;case e.BINARY_ACK:this.onack(a);break;case e.DISCONNECT:this.ondisconnect();break;case e.ERROR:this.emit("error",a.data)}},d.prototype.onevent=function(a){var b=a.data||[];j("emitting event %j",b),null!=a.id&&(j("attaching ack callback to event"),b.push(this.ack(a.id))),this.connected?m.apply(this,b):this.receiveBuffer.push(b)},d.prototype.ack=function(a){var b=this,c=!1;return function(){if(!c){c=!0;var d=g(arguments);j("sending ack %j",d);var f=k(d)?e.BINARY_ACK:e.ACK;b.packet({type:f,id:a,data:d})}}},d.prototype.onack=function(a){j("calling ack %s with %j",a.id,a.data);var b=this.acks[a.id];b.apply(this,a.data),delete this.acks[a.id]},d.prototype.onconnect=function(){this.connected=!0,this.disconnected=!1,this.emit("connect"),this.emitBuffered()},d.prototype.emitBuffered=function(){var a;for(a=0;a0&&a.jitter<=1?a.jitter:0,this.attempts=0}b.exports=d,d.prototype.duration=function(){var a=this.ms*Math.pow(this.factor,this.attempts++);if(this.jitter){var b=Math.random(),c=Math.floor(b*this.jitter*a);a=0==(1&Math.floor(10*b))?a-c:a+c}return 0|Math.min(a,this.max)},d.prototype.reset=function(){this.attempts=0},d.prototype.setMin=function(a){this.ms=a},d.prototype.setMax=function(a){this.max=a},d.prototype.setJitter=function(a){this.jitter=a}},{}],405:[function(a,b,c){var d=[].slice;b.exports=function(a,b){if("string"==typeof b&&(b=a[b]),"function"!=typeof b)throw new Error("bind() requires a function");var c=d.call(arguments,2);return function(){return b.apply(a,c.concat(d.call(arguments)))}}},{}],406:[function(a,b,c){function d(a){return a?e(a):void 0}function e(a){for(var b in d.prototype)a[b]=d.prototype[b];return a}b.exports=d,d.prototype.on=d.prototype.addEventListener=function(a,b){return this._callbacks=this._callbacks||{},(this._callbacks[a]=this._callbacks[a]||[]).push(b),this},d.prototype.once=function(a,b){function c(){d.off(a,c),b.apply(this,arguments)}var d=this;return this._callbacks=this._callbacks||{},c.fn=b,this.on(a,c),this},d.prototype.off=d.prototype.removeListener=d.prototype.removeAllListeners=d.prototype.removeEventListener=function(a,b){if(this._callbacks=this._callbacks||{},0==arguments.length)return this._callbacks={},this;var c=this._callbacks[a];if(!c)return this;if(1==arguments.length)return delete this._callbacks[a],this;for(var d,e=0;ed;++d)c[d].apply(this,b)}return this},d.prototype.listeners=function(a){return this._callbacks=this._callbacks||{},this._callbacks[a]||[]},d.prototype.hasListeners=function(a){return!!this.listeners(a).length}},{}],407:[function(a,b,c){function d(a){return d.enabled(a)?function(b){b=e(b);var c=new Date,f=c-(d[a]||c);d[a]=c,b=a+" "+b+" +"+d.humanize(f),window.console&&console.log&&Function.prototype.apply.call(console.log,console,arguments)}:function(){}}function e(a){return a instanceof Error?a.stack||a.message:a}b.exports=d,d.names=[],d.skips=[],d.enable=function(a){try{localStorage.debug=a}catch(b){}for(var c=(a||"").split(/[\s,]+/),e=c.length,f=0;e>f;f++)a=c[f].replace("*",".*?"),"-"===a[0]?d.skips.push(new RegExp("^"+a.substr(1)+"$")):d.names.push(new RegExp("^"+a+"$"))},d.disable=function(){d.enable("")},d.humanize=function(a){var b=1e3,c=6e4,d=60*c;return a>=d?(a/d).toFixed(1)+"h":a>=c?(a/c).toFixed(1)+"m":a>=b?(a/b|0)+"s":a+"ms"},d.enabled=function(a){for(var b=0,c=d.skips.length;c>b;b++)if(d.skips[b].test(a))return!1;for(var b=0,c=d.names.length;c>b;b++)if(d.names[b].test(a))return!0;return!1};try{window.localStorage&&d.enable(localStorage.debug)}catch(f){}},{}],408:[function(a,b,c){b.exports=a("./lib/")},{"./lib/":409}],409:[function(a,b,c){b.exports=a("./socket"),b.exports.parser=a("engine.io-parser")},{"./socket":410,"engine.io-parser":422}],410:[function(a,b,c){(function(c){function d(a,b){if(!(this instanceof d))return new d(a,b);if(b=b||{},a&&"object"==typeof a&&(b=a,a=null),a&&(a=k(a),b.host=a.host,b.secure="https"==a.protocol||"wss"==a.protocol,b.port=a.port,a.query&&(b.query=a.query)),this.secure=null!=b.secure?b.secure:c.location&&"https:"==location.protocol,b.host){var e=b.host.split(":");b.hostname=e.shift(),e.length?b.port=e.pop():b.port||(b.port=this.secure?"443":"80")}this.agent=b.agent||!1,this.hostname=b.hostname||(c.location?location.hostname:"localhost"),this.port=b.port||(c.location&&location.port?location.port:this.secure?443:80),this.query=b.query||{},"string"==typeof this.query&&(this.query=m.decode(this.query)),this.upgrade=!1!==b.upgrade,this.path=(b.path||"/engine.io").replace(/\/$/,"")+"/",this.forceJSONP=!!b.forceJSONP,this.jsonp=!1!==b.jsonp,this.forceBase64=!!b.forceBase64,this.enablesXDR=!!b.enablesXDR,this.timestampParam=b.timestampParam||"t",this.timestampRequests=b.timestampRequests,this.transports=b.transports||["polling","websocket"],this.readyState="",this.writeBuffer=[],this.callbackBuffer=[],this.policyPort=b.policyPort||843,this.rememberUpgrade=b.rememberUpgrade||!1,this.binaryType=null,this.onlyBinaryUpgrades=b.onlyBinaryUpgrades,this.pfx=b.pfx||null,this.key=b.key||null,this.passphrase=b.passphrase||null,this.cert=b.cert||null,this.ca=b.ca||null,this.ciphers=b.ciphers||null,this.rejectUnauthorized=b.rejectUnauthorized||null,this.open()}function e(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}var f=a("./transports"),g=a("component-emitter"),h=a("debug")("engine.io-client:socket"),i=a("indexof"),j=a("engine.io-parser"),k=a("parseuri"),l=a("parsejson"),m=a("parseqs");b.exports=d,d.priorWebsocketSuccess=!1,g(d.prototype),d.protocol=j.protocol,d.Socket=d,d.Transport=a("./transport"),d.transports=a("./transports"),d.parser=a("engine.io-parser"),d.prototype.createTransport=function(a){h('creating transport "%s"',a);var b=e(this.query);b.EIO=j.protocol,b.transport=a,this.id&&(b.sid=this.id);var c=new f[a]({agent:this.agent,hostname:this.hostname,port:this.port,secure:this.secure,path:this.path,query:b,forceJSONP:this.forceJSONP,jsonp:this.jsonp,forceBase64:this.forceBase64,enablesXDR:this.enablesXDR,timestampRequests:this.timestampRequests,timestampParam:this.timestampParam,policyPort:this.policyPort,socket:this,pfx:this.pfx,key:this.key,passphrase:this.passphrase,cert:this.cert,ca:this.ca,ciphers:this.ciphers,rejectUnauthorized:this.rejectUnauthorized});return c},d.prototype.open=function(){var a;if(this.rememberUpgrade&&d.priorWebsocketSuccess&&-1!=this.transports.indexOf("websocket"))a="websocket";else{if(0==this.transports.length){var b=this;return void setTimeout(function(){b.emit("error","No transports available")},0)}a=this.transports[0]}this.readyState="opening";var a;try{a=this.createTransport(a)}catch(c){return this.transports.shift(),void this.open()}a.open(),this.setTransport(a)},d.prototype.setTransport=function(a){h("setting transport %s",a.name);var b=this;this.transport&&(h("clearing existing transport %s",this.transport.name),this.transport.removeAllListeners()),this.transport=a,a.on("drain",function(){b.onDrain()}).on("packet",function(a){b.onPacket(a)}).on("error",function(a){b.onError(a)}).on("close",function(){b.onClose("transport close")})},d.prototype.probe=function(a){function b(){if(m.onlyBinaryUpgrades){var b=!this.supportsBinary&&m.transport.supportsBinary;l=l||b}l||(h('probe transport "%s" opened',a),k.send([{type:"ping",data:"probe"}]),k.once("packet",function(b){if(!l)if("pong"==b.type&&"probe"==b.data){if(h('probe transport "%s" pong',a),m.upgrading=!0,m.emit("upgrading",k),!k)return;d.priorWebsocketSuccess="websocket"==k.name,h('pausing current transport "%s"',m.transport.name),m.transport.pause(function(){l||"closed"!=m.readyState&&(h("changing transport and sending upgrade packet"),j(),m.setTransport(k),k.send([{type:"upgrade"}]),m.emit("upgrade",k),k=null,m.upgrading=!1,m.flush())})}else{h('probe transport "%s" failed',a);var c=new Error("probe error");c.transport=k.name,m.emit("upgradeError",c)}}))}function c(){l||(l=!0,j(),k.close(),k=null)}function e(b){var d=new Error("probe error: "+b);d.transport=k.name,c(),h('probe transport "%s" failed because of error: %s',a,b),m.emit("upgradeError",d)}function f(){e("transport closed")}function g(){e("socket closed")}function i(a){k&&a.name!=k.name&&(h('"%s" works - aborting "%s"',a.name,k.name),c())}function j(){k.removeListener("open",b),k.removeListener("error",e),k.removeListener("close",f),m.removeListener("close",g),m.removeListener("upgrading",i)}h('probing transport "%s"',a);var k=this.createTransport(a,{probe:1}),l=!1,m=this;d.priorWebsocketSuccess=!1,k.once("open",b),k.once("error",e),k.once("close",f),this.once("close",g),this.once("upgrading",i),k.open()},d.prototype.onOpen=function(){if(h("socket open"),this.readyState="open",d.priorWebsocketSuccess="websocket"==this.transport.name,this.emit("open"),this.flush(),"open"==this.readyState&&this.upgrade&&this.transport.pause){h("starting upgrade probes");for(var a=0,b=this.upgrades.length;b>a;a++)this.probe(this.upgrades[a])}},d.prototype.onPacket=function(a){if("opening"==this.readyState||"open"==this.readyState)switch(h('socket receive: type "%s", data "%s"',a.type,a.data),this.emit("packet",a),this.emit("heartbeat"),a.type){case"open":this.onHandshake(l(a.data));break;case"pong":this.setPing();break;case"error":var b=new Error("server error");b.code=a.data,this.emit("error",b);break;case"message":this.emit("data",a.data),this.emit("message",a.data)}else h('packet received with socket readyState "%s"',this.readyState)},d.prototype.onHandshake=function(a){this.emit("handshake",a),this.id=a.sid,this.transport.query.sid=a.sid,this.upgrades=this.filterUpgrades(a.upgrades),this.pingInterval=a.pingInterval,this.pingTimeout=a.pingTimeout,this.onOpen(),"closed"!=this.readyState&&(this.setPing(),this.removeListener("heartbeat",this.onHeartbeat),this.on("heartbeat",this.onHeartbeat))},d.prototype.onHeartbeat=function(a){clearTimeout(this.pingTimeoutTimer);var b=this;b.pingTimeoutTimer=setTimeout(function(){"closed"!=b.readyState&&b.onClose("ping timeout")},a||b.pingInterval+b.pingTimeout)},d.prototype.setPing=function(){var a=this;clearTimeout(a.pingIntervalTimer),a.pingIntervalTimer=setTimeout(function(){h("writing ping packet - expecting pong within %sms",a.pingTimeout),a.ping(),a.onHeartbeat(a.pingTimeout)},a.pingInterval)},d.prototype.ping=function(){this.sendPacket("ping")},d.prototype.onDrain=function(){for(var a=0;ac;c++)~i(this.transports,a[c])&&b.push(a[c]);return b}}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./transport":411,"./transports":412,"component-emitter":406,debug:419,"engine.io-parser":422,indexof:439,parsejson:433,parseqs:434,parseuri:435}],411:[function(a,b,c){function d(a){this.path=a.path,this.hostname=a.hostname,this.port=a.port,this.secure=a.secure,this.query=a.query,this.timestampParam=a.timestampParam,this.timestampRequests=a.timestampRequests,this.readyState="",this.agent=a.agent||!1,this.socket=a.socket,this.enablesXDR=a.enablesXDR,this.pfx=a.pfx,this.key=a.key,this.passphrase=a.passphrase,this.cert=a.cert,this.ca=a.ca,this.ciphers=a.ciphers,this.rejectUnauthorized=a.rejectUnauthorized}var e=a("engine.io-parser"),f=a("component-emitter");b.exports=d,f(d.prototype),d.timestamps=0,d.prototype.onError=function(a,b){var c=new Error(a);return c.type="TransportError",c.description=b,this.emit("error",c),this},d.prototype.open=function(){return("closed"==this.readyState||""==this.readyState)&&(this.readyState="opening",this.doOpen()),this},d.prototype.close=function(){return("opening"==this.readyState||"open"==this.readyState)&&(this.doClose(),this.onClose()),this},d.prototype.send=function(a){if("open"!=this.readyState)throw new Error("Transport not open");this.write(a)},d.prototype.onOpen=function(){this.readyState="open",this.writable=!0,this.emit("open")},d.prototype.onData=function(a){var b=e.decodePacket(a,this.socket.binaryType);this.onPacket(b)},d.prototype.onPacket=function(a){this.emit("packet",a)},d.prototype.onClose=function(){this.readyState="closed",this.emit("close")}},{"component-emitter":406,"engine.io-parser":422}],412:[function(a,b,c){(function(b){function d(a){var c,d=!1,h=!1,i=!1!==a.jsonp;if(b.location){var j="https:"==location.protocol,k=location.port;k||(k=j?443:80),d=a.hostname!=location.hostname||k!=a.port,h=a.secure!=j}if(a.xdomain=d,a.xscheme=h,c=new e(a),"open"in c&&!a.forceJSONP)return new f(a);if(!i)throw new Error("JSONP disabled");return new g(a)}var e=a("xmlhttprequest"),f=a("./polling-xhr"),g=a("./polling-jsonp"),h=a("./websocket");c.polling=d,c.websocket=h}).call(this,"undefined"!=typeof global?global:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{"./polling-jsonp":413,"./polling-xhr":414,"./websocket":416,xmlhttprequest:417}],413:[function(a,b,c){(function(c){function d(){}function e(a){f.call(this,a),this.query=this.query||{},h||(c.___eio||(c.___eio=[]),h=c.___eio),this.index=h.length;var b=this;h.push(function(a){b.onData(a)}),this.query.j=this.index,c.document&&c.addEventListener&&c.addEventListener("beforeunload",function(){b.script&&(b.script.onerror=d)},!1)}var f=a("./polling"),g=a("component-inherit");b.exports=e;var h,i=/\n/g,j=/\\n/g;g(e,f),e.prototype.supportsBinary=!1,e.prototype.doClose=function(){this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),this.form&&(this.form.parentNode.removeChild(this.form),this.form=null,this.iframe=null),f.prototype.doClose.call(this)},e.prototype.doPoll=function(){var a=this,b=document.createElement("script");this.script&&(this.script.parentNode.removeChild(this.script),this.script=null),b.async=!0,b.src=this.uri(),b.onerror=function(b){a.onError("jsonp poll error",b)};var c=document.getElementsByTagName("script")[0];c.parentNode.insertBefore(b,c),this.script=b;var d="undefined"!=typeof navigator&&/gecko/i.test(navigator.userAgent);d&&setTimeout(function(){var a=document.createElement("iframe");document.body.appendChild(a),document.body.removeChild(a)},100)},e.prototype.doWrite=function(a,b){function c(){d(),b()}function d(){if(e.iframe)try{e.form.removeChild(e.iframe)}catch(a){e.onError("jsonp polling iframe removal error",a)}try{var b='