bitcore-wallet-client
Version:
Client for bitcore-wallet-service
2 lines • 2.1 MB
JavaScript
!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<d.length;g++)e(d[g]);return e}({1:[function(a,b,c){var d=a("./lib");b.exports=d},{"./lib":10}],2:[function(a,b,c){(function(c,d){"use strict";function e(a){a=a||{},this.verbose=!!a.verbose,this.request=a.request||f,this.baseUrl=a.baseUrl||A;var b=n.parse(this.baseUrl);this.basePath=b.path,this.baseHost=b.protocol+"//"+b.host,this.payProHttp=null,this.doNotVerifyPayPro=a.doNotVerifyPayPro,this.timeout=a.timeout||5e4,this.verbose?u.setLevel("debug"):u.setLevel("info")}var f,g=a("lodash"),h=a("preconditions").singleton(),i=a("util"),j=a("async"),k=a("events"),l=a("bitcore-lib"),m=a("sjcl"),n=a("url"),o=a("querystring");a("json-stable-stringify");f=a(c&&!c.browser?"request":"browser-request");var p=a("./common"),q=p.Constants,r=p.Defaults,s=p.Utils,t=a("./paypro"),u=a("./log"),v=a("./credentials"),w=a("./verifier"),x=a("../package.json"),y=a("./errors/clienterror"),z=a("./errors/errordefinitions"),A="http://localhost:3232/bws/api";i.inherits(e,k.EventEmitter),e.privateKeyEncryptionOpts={iter:1e4},e.prototype.initNotifications=function(a){u.warn("DEPRECATED: use initialize() instead."),this.initialize({},a)},e.prototype.initialize=function(a,b){h.checkState(this.credentials);var c=this;return c._initNotifications(a),b()},e.prototype.dispose=function(a){var b=this;return b._disposeNotifications(),a()},e.prototype._fetchLatestNotifications=function(a,b){var c=this;b=b||function(){};var d={lastNotificationId:c.lastNotificationId};c.lastNotificationId||(d.timeSpan=a+1),c.getNotifications(d,function(a,d){return a?(u.warn("Error receiving notifications."),u.debug(a),b(a)):(d.length>0&&(c.lastNotificationId=g.last(d).id),g.each(d,function(a){c.emit("notification",a)}),b())})},e.prototype._initNotifications=function(a){var b=this;a=a||{};var c=a.notificationIntervalSeconds||5;b.notificationsIntervalId=setInterval(function(){b._fetchLatestNotifications(c,function(a){a&&("NOT_FOUND"==a.code||"NOT_AUTHORIZED"==a.code)&&b._disposeNotifications()})},1e3*c)},e.prototype._disposeNotifications=function(){var a=this;a.notificationsIntervalId&&(clearInterval(a.notificationsIntervalId),a.notificationsIntervalId=null)},e.prototype.setNotificationsInterval=function(a){var b=this;b._disposeNotifications(),a>0&&b._initNotifications({notificationIntervalSeconds:a})},e._encryptMessage=function(a,b){return a?s.encryptMessage(a,b):null},e._decryptMessage=function(a,b){if(!a)return"";try{return s.decryptMessage(a,b)}catch(c){return"<ECANNOTDECRYPT>"}},e.prototype._processTxps=function(a){var b=this;if(a){var c=b.credentials.sharedEncryptingKey;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 y(a.code,a.message):{code:"ERROR",error:a?a.error:"There was an unknown error processing the request"},u.error(c),c},e._signRequest=function(a,b,c,d){var e=[a.toLowerCase(),b,JSON.stringify(c)].join("|");return s.signMessage(e,d)},e.prototype.seedFromRandom=function(a){h.checkArgument(arguments.length<=1,"DEPRECATED: only 1 argument accepted."),h.checkArgument(g.isUndefined(a)||g.isObject(a),"DEPRECATED: argument should be an options object."),a=a||{},this.credentials=v.create(a.network||"livenet")},e.prototype.seedFromRandomWithMnemonic=function(a){h.checkArgument(arguments.length<=1,"DEPRECATED: only 1 argument accepted."),h.checkArgument(g.isUndefined(a)||g.isObject(a),"DEPRECATED: argument should be an options object."),a=a||{},this.credentials=v.createWithMnemonic(a.network||"livenet",a.passphrase,a.language||"en",a.account||0)},e.prototype.getMnemonic=function(){return this.credentials.getMnemonic()},e.prototype.mnemonicHasPassphrase=function(){return this.credentials.mnemonicHasPassphrase},e.prototype.clearMnemonic=function(){return this.credentials.clearMnemonic()},e.prototype.seedFromExtendedPrivateKey=function(a){this.credentials=v.fromExtendedPrivateKey(a)},e.prototype.seedFromMnemonic=function(a,b){h.checkArgument(g.isUndefined(b)||g.isObject(b),"DEPRECATED: second argument should be an options object."),b=b||{},this.credentials=v.fromMnemonic(b.network||"livenet",a,b.passphrase,b.account||0,b.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44)},e.prototype.seedFromExtendedPublicKey=function(a,b,c,d){h.checkArgument(g.isUndefined(d)||g.isObject(d)),d=d||{},this.credentials=v.fromExtendedPublicKey(a,b,c,d.account||0,d.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44)},e.prototype["export"]=function(a){h.checkState(this.credentials),a=a||{};var b,c=v.fromObj(this.credentials);return a.noSign&&c.setNoSign(),b=JSON.stringify(c.toObj())},e.prototype["import"]=function(a,b){b=b||{};try{var c=v.fromObj(JSON.parse(a));this.credentials=c}catch(d){throw z.INVALID_BACKUP}},e.prototype._import=function(a){h.checkState(this.credentials);var b=this;b.openWallet(function(c,d){return c?"NOT_AUTHORIZED"!=c.code||b.isPrivKeyExternal()?a(c):(u.info("Copayer not found, trying to add access"),void b.addAccess({},function(c){return c||b.openWallet(a),a(z.WALLET_DOES_NOT_EXIST)})):a(null,d)})},e.prototype.importFromMnemonic=function(a,b,c){u.debug("Importing from 12 Words"),b=b||{};try{this.credentials=v.fromMnemonic(b.network||"livenet",a,b.passphrase,b.account||0,b.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44)}catch(d){return u.info("Mnemonic error:",d),c(z.INVALID_BACKUP)}this._import(c)},e.prototype.importFromExtendedPrivateKey=function(a,b){u.debug("Importing from Extended Private Key");try{this.credentials=v.fromExtendedPrivateKey(a)}catch(c){return u.info("xPriv error:",c),b(z.INVALID_BACKUP)}this._import(b)},e.prototype.importFromExtendedPublicKey=function(a,b,c,d,e){h.checkArgument(5==arguments.length,"DEPRECATED: should receive 5 arguments"),h.checkArgument(g.isUndefined(d)||g.isObject(d)),h.shouldBeFunction(e),d=d||{},u.debug("Importing from Extended Private Key");try{this.credentials=v.fromExtendedPublicKey(a,b,c,d.account||0,d.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44)}catch(f){return u.info("xPriv error:",f),e(z.INVALID_BACKUP)}this._import(e)},e.prototype.decryptBIP38PrivateKey=function(b,c,e,f){var g,h=a("bip38"),i=new h;try{g=i.decrypt(b,c)}catch(j){return f(new Error("Could not decrypt BIP38 private key",j))}var k=new l.PrivateKey(g),m=k.publicKey.toAddress().toString(),n=new d(m,"ascii"),o=l.crypto.Hash.sha256sha256(n).toString("hex").substring(0,8),p=l.encoding.Base58Check.decode(b).toString("hex").substring(6,14);return o!=p?f(new Error("Incorrect passphrase")):f(null,g)},e.prototype.getBalanceFromPrivateKey=function(a,b){var c=this,a=new l.PrivateKey(a),d=a.publicKey.toAddress();c.getUtxos({addresses:d.toString()},function(a,c){return a?b(a):b(null,g.sum(c,"satoshis"))})},e.prototype.buildTxFromPrivateKey=function(a,b,c,d){var e=this;c=c||{};var a=new l.PrivateKey(a),f=a.publicKey.toAddress();j.waterfall([function(a){e.getUtxos({addresses:f.toString()},function(b,c){return a(b,c)})},function(d,e){if(!g.isArray(d)||0==d.length)return e(new Error("No utxos found"));var f=c.fee||1e4,h=g.sum(d,"satoshis")-f;if(0>=h)return e(z.INSUFFICIENT_FUNDS);var i;try{var j=l.Address.fromString(b);i=(new l.Transaction).from(d).to(j,h).fee(f).sign(a),i.serialize()}catch(k){return u.error("Could not build transaction from private key",k),e(z.COULD_NOT_BUILD_TRANSACTION)}return e(null,i)}],d)},e.prototype.openWallet=function(a){h.checkState(this.credentials);var b=this;return b.credentials.isComplete()&&b.credentials.hasWalletInfo()?a(null,!0):void b._doGetRequest("/v2/wallets/?includeExtendedInfo=1",function(c,d){if(c)return a(c);var f=d.wallet;if(!b.credentials.hasWalletInfo()){var h=g.find(f.copayers,{id:b.credentials.copayerId});b.credentials.addWalletInfo(f.id,f.name,f.m,f.n,null,h.name)}if("complete"!=f.status)return a();if(b.credentials.walletPrivKey){if(!w.checkCopayers(b.credentials,f.copayers))return a(z.SERVER_COMPROMISED)}else u.warn("Could not verify copayers key (missing wallet Private Key)");return b.credentials.addPublicKeyRing(e._extractPublicKeyRing(f.copayers)),b.emit("walletCompleted",f),b._processTxps(d.pendingTxps),b._processCustomData(d),a(null,d)})},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-"+x.version},method:a,url:j,body:c,json:!0,withCredentials:!1,timeout:this.timeout};u.debug("Request Args",i.inspect(c,{depth:10})),this.request(c,function(a,b,c){return u.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._buildSecret=function(a,b,c){g.isString(b)&&(b=l.PrivateKey.fromString(b));var e=new d(a.replace(/-/g,""),"hex"),f=new l.encoding.Base58(e).toString();return g.padRight(f,22,"0")+b.toWIF()+("testnet"==c?"T":"L")},e.parseSecret=function(a){function b(a,b){var c=[];b.push(a.length);for(var d=0;d<b.length;)c.push(a.substring(0==d?0:b[d-1],b[d])),d++;return c}h.checkArgument(a);try{var c=b(a,[22,74]),d=c[0].replace(/0/g,""),e=l.encoding.Base58.decode(d).toString("hex"),f=b(e,[8,12,16,20]).join("-"),g=l.PrivateKey.fromString(c[1]),i=c[2];return{walletId:f,walletPrivKey:g,network:"T"==i?"testnet":"livenet"}}catch(j){throw new Error("Invalid secret")}},e.buildTx=function(a){var b=new l.Transaction;switch(h.checkState(g.contains(g.values(q.SCRIPT_TYPES),a.addressType)),a.addressType){case q.SCRIPT_TYPES.P2SH:g.each(a.inputs,function(c){b.from(c,c.publicKeys,a.requiredSignatures)});break;case q.SCRIPT_TYPES.P2PKH:b.from(a.inputs)}if(a.toAddress&&a.amount&&!a.outputs?b.to(a.toAddress,a.amount):a.outputs&&g.each(a.outputs,function(a){h.checkState(a.script||a.toAddress,"Output should have either toAddress or script specified"),a.script?b.addOutput(new l.Transaction.Output({script:a.script,satoshis:a.amount})):b.to(a.toAddress,a.amount)}),g.startsWith(a.version,"1.")?(l.Transaction.FEE_SECURITY_MARGIN=1,b.feePerKb(a.feePerKb)):b.fee(a.fee),b.change(a.changeAddress.address),b.outputs.length>1){var c=g.reject(a.outputOrder,function(a){return a>=b.outputs.length});h.checkState(b.outputs.length==c.length),b.sortOutputs(function(a){return g.map(c,function(b){return a[b]})})}var d=g.reduce(a.inputs,function(a,b){return+b.satoshis+a},0),e=g.reduce(b.outputs,function(a,b){return+b.satoshis+a},0);return h.checkState(d-e>=0),h.checkState(d-e<=r.MAX_TX_FEE),b},e.signTxp=function(a,b){var c=[],d={},f=new l.HDPrivateKey(b);g.each(a.inputs,function(a){d[a.path]||(d[a.path]=f.derive(a.path).privateKey,c.push(d[a.path]))});var h=e.buildTx(a),i=g.map(c,function(a,b){return h.getSignatures(a)});return i=g.map(g.sortBy(g.flatten(i),"inputIndex"),function(a){return a.signature.toDER().toString("hex")})},e.prototype._signTxp=function(a){return e.signTxp(a,this.credentials.getDerivedXPrivKey())},e.prototype._doJoinWallet=function(a,b,c,d,e,f,i){h.shouldBeFunction(i),f=f||{},f.customData=f.customData||{},f.customData.walletPrivKey=b.toString();var j=s.encryptMessage(JSON.stringify(f.customData),this.credentials.personalEncryptingKey),k={walletId:a,name:e,xPubKey:c,requestPubKey:d,customData:j};f.dryRun&&(k.dryRun=!0),g.isBoolean(f.supportBIP44AndP2PKH)&&(k.supportBIP44AndP2PKH=f.supportBIP44AndP2PKH);var l=s.getCopayerHash(k.name,k.xPubKey,k.requestPubKey);k.copayerSignature=s.signMessage(l,b);var m="/v2/wallets/"+a+"/copayers";this._doPostRequest(m,k,function(a,b){return a?i(a):i(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.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"]);return b.copayerName=a.name,b})},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.getVersion=function(a){this._doGetRequest("/v1/version/",a)},e.prototype.createWallet=function(a,b,c,d,f,i){var j=this;f&&h.shouldBeObject(f),f=f||{};var k=f.network||"livenet";if(!g.contains(["testnet","livenet"],k))return i(new Error("Invalid network"));if(j.credentials?u.info("Using existing keys"):(u.info("Generating new keys"),j.seedFromRandom({network:k})),k!=j.credentials.network)return i(new Error("Existing keys were created for a different network"));var m=f.walletPrivKey||new l.PrivateKey,n={name:a,m:c,n:d,pubKey:new l.PrivateKey(m).toPublicKey().toString(),network:k,id:f.id};j._doPostRequest("/v2/wallets/",n,function(f,g){if(f)return i(f);var h=g.walletId;j.credentials.addWalletInfo(h,a,c,d,m.toString(),b);var k=j.credentials,l=e._buildSecret(k.walletId,k.walletPrivKey,k.network);j._doJoinWallet(h,m,j.credentials.xPubKey,j.credentials.requestPubKey,b,{},function(a,b){return a?i(a):i(null,d>1?l:null)})})},e.prototype.joinWallet=function(a,b,c,d){var f=this;d||(d=c,c={},u.warn("DEPRECATED WARN: joinWallet should receive 4 parameters.")),c=c||{};try{var g=e.parseSecret(a)}catch(h){return d(h)}f.credentials||f.seedFromRandom({network:g.network}),f._doJoinWallet(g.walletId,g.walletPrivKey,f.credentials.xPubKey,f.credentials.requestPubKey,b,{dryRun:!!c.dryRun},function(a,e){return a?d(a):(c.dryRun||f.credentials.addWalletInfo(e.id,e.name,e.m,e.n,g.walletPrivKey.toString(),b),d(null,e))})},e.prototype.recreateWallet=function(a){h.checkState(this.credentials),h.checkState(this.credentials.isComplete()),h.checkState(this.credentials.walletPrivKey);var b=this;this.getStatus({includeExtendedInfo:!0},function(c){if(!c)return u.info("Wallet is already created"),a();var d=l.PrivateKey.fromString(b.credentials.walletPrivKey),e=b.credentials.walletId,f=b.credentials.derivationStrategy!=q.DERIVATION_STRATEGIES.BIP45,g={name:b.credentials.walletName||"recovered wallet",m:b.credentials.m,n:b.credentials.n,pubKey:d.toPublicKey().toString(),network:b.credentials.network,id:e,supportBIP44AndP2PKH:f};b._doPostRequest("/v2/wallets/",g,function(c,g){if(c)return"WALLET_ALREADY_EXISTS"!=c.code?a(c):b.addAccess({},function(c){return c?a(c):void b.openWallet(function(b){return a(b)})});e||(e=g.walletId);var h=1;j.each(b.credentials.publicKeyRing,function(a,c){var g=a.copayerName||"copayer "+h++;b._doJoinWallet(e,d,a.xPubKey,a.requestPubKey,g,{supportBIP44AndP2PKH:f},function(a){return a&&"COPAYER_IN_WALLET"==a.code?c():c(a)})},a)})})},e.prototype._processCustomData=function(a){var b=a.wallet.copayers;if(b){var c=g.find(b,{id:this.credentials.copayerId});if(c&&c.customData){var d;try{d=JSON.parse(s.decryptMessage(c.customData,this.credentials.personalEncryptingKey))}catch(e){u.warn("Could not decrypt customData:",c.customData)}d&&(a.customData=d,!this.credentials.walletPrivKey&&d.walletPrivKey&&this.credentials.addWalletPrivateKey(d.walletPrivKey))}}},e.prototype.getNotifications=function(a,b){h.checkState(this.credentials);var c=this;a=a||{};var d="/v1/notifications/";a.lastNotificationId?d+="?notificationId="+a.lastNotificationId:a.timeSpan&&(d+="?timeSpan="+a.timeSpan),c._doGetRequest(d,function(a,d){if(a)return b(a);var e=g.filter(d,function(a){return a.creatorId!=c.credentials.copayerId});return b(null,e)})},e.prototype.getStatus=function(a,b){h.checkState(this.credentials),b||(b=a,a={},u.warn("DEPRECATED WARN: getStatus should receive 2 parameters."));var c=this;a=a||{};var d=[];d.push("includeExtendedInfo="+(a.includeExtendedInfo?"1":"0")),d.push("twoStep="+(a.twoStep?"1":"0")),c._doGetRequest("/v2/wallets/?"+d.join("&"),function(a,d){if(a)return b(a);if("pending"==d.wallet.status){var f=c.credentials;d.wallet.secret=e._buildSecret(f.walletId,f.walletPrivKey,f.network)}return c._processTxps(d.pendingTxps),c._processCustomData(d),b(a,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||null};b=s.getProposalHash(c)}else h.shouldBeNumber(a.amount),b=s.getProposalHash(a.toAddress,a.amount,a.message||null,a.payProUrl||null);return s.signMessage(b,this.credentials.requestPrivKey)},e.prototype.fetchPayPro=function(a,b){h.checkArgument(a).checkArgument(a.payProUrl),t.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,b){h.checkState(this.credentials&&this.credentials.isComplete()),a=a||{};var c="/v1/utxos/";a.addresses&&(c+="?"+o.stringify({addresses:[].concat(a.addresses).join(",")})),this._doGetRequest(c,b)},e.prototype.sendTxProposal=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete()),h.checkArgument(!a.message||this.credentials.sharedEncryptingKey,"Cannot create transaction with message without shared Encrypting key"),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||null,excludeUnconfirmedUtxos:!!a.excludeUnconfirmedUtxos,type:a.type,customData:a.customData,inputs:a.inputs,utxosToExclude:a.utxosToExclude};a.outputs&&(d.outputs=g.map(a.outputs,function(a){return{toAddress:a.toAddress,script:a.script,amount:a.amount,message:e._encryptMessage(a.message,c.credentials.sharedEncryptingKey)||null}})),u.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,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this;b||(b=a,a={},u.warn("DEPRECATED WARN: createAddress should receive 2 parameters.")),a=a||{},c._doPostRequest("/v2/addresses/",a,function(a,d){return a?b(a):w.checkAddress(c.credentials,d)?b(null,d):b(z.SERVER_COMPROMISED)})},e.prototype.getMainAddresses=function(a,b){h.checkState(this.credentials&&this.credentials.isComplete());var c=this;a=a||{};var d=[];a.limit&&d.push("limit="+a.limit),a.reverse&&d.push("reverse=1");var e="";d.length>0&&(e="?"+d.join("&"));var f="/v1/addresses/"+e;c._doGetRequest(f,function(d,e){if(d)return b(d);if(!a.doNotVerify){var f=g.any(e,function(a){return!w.checkAddress(c.credentials,a)});if(f)return b(z.SERVER_COMPROMISED)}return b(null,e)})},e.prototype.getBalance=function(a,b){b||(b=a,a={},u.warn("DEPRECATED WARN: getBalance should receive 2 parameters."));a=a||{},h.checkState(this.credentials&&this.credentials.isComplete());var c="/v1/balance/";a.twoStep&&(c+="?twoStep=1"),this._doGetRequest(c,b)},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=w.checkTxProposal(c.credentials,b,{paypro:e});return d(f)})},function(d){if(!d)return b(z.SERVER_COMPROMISED);var f;return f=a.forAirGapped?{txps:JSON.parse(JSON.stringify(e)),encryptedPkr:s.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 t.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=w.checkTxProposal(c.credentials,a,{paypro:e});if(!f)return b(z.SERVER_COMPROMISED);var g=a.signatures||c._signTxp(a),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 z.MISSING_PRIVATE_KEY;if(e.isPrivKeyEncrypted())throw z.ENCRYPTED_PRIVATE_KEY;var f;try{f=JSON.parse(s.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.addressType=a.addressType,e.credentials.addPublicKeyRing(f),!w.checkTxProposalBody(e.credentials,a))throw new Error("Fake transaction proposal");return e._signTxp(a)},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.broadcastRawTx=function(a,b){h.checkState(this.credentials),h.checkArgument(b);var c=this;a=a||{};var d="/v1/broadcast_raw/";c._doPostRequest(d,a,function(a,c){return a?b(a):b(null,c)})},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,f){if(f){var g=e.buildTx(a);t.send({http:c.payProHttp,url:a.payProUrl,amountSat:a.amount,refundAddr:a.changeAddress.address,merchant_data:f.merchant_data,rawTx:g.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=m.decrypt(g,c)}catch(h){g=a+f+b;try{d=m.decrypt(g,c)}catch(h){u.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.createWalletFromOldCopay=function(a,b,c,d){var e=this._oldCopayDecrypt(a,b,c);return e?e.publicKeyRing.copayersExtPubKeys.length!=e.opts.totalCopayers?d("Wallet is incomplete, cannot be imported"):(this.credentials=v.fromOldCopayWallet(e),void this.recreateWallet(d)):d("Could not decrypt")},e.prototype.addAccess=function(a,b){h.checkState(this.credentials&&this.credentials.canSign());var c=new l.PrivateKey(a.generateNewKey?null:this.credentials.requestPrivKey),d=c.toPublicKey().toString(),e=new l.HDPrivateKey(this.credentials.xPrivKey).derive(this.credentials.getBaseAddressDerivationPath()),f=s.signRequestPubKey(d,e),g=this.credentials.copayerId,a={copayerId:g,requestPubKey:d,signature:f,name:a.name,restrictions:a.restrictions};this._doPutRequest("/v1/copayers/"+g+"/",a,function(a,d){return a?b(a):b(null,d.wallet,c)})},b.exports=e}).call(this,a("_process"),a("buffer").Buffer)},{"../package.json":527,"./common":5,"./credentials":7,"./errors/clienterror":8,"./errors/errordefinitions":9,"./log":11,"./paypro":12,"./verifier":13,_process:399,async:14,bip38:15,"bitcore-lib":64,"browser-request":176,buffer:193,events:389,"json-stable-stringify":422,lodash:426,preconditions:427,querystring:403,request:432,sjcl:526,url:417,util:419}],3:[function(a,b,c){"use strict";var d={};d.SCRIPT_TYPES={P2SH:"P2SH",P2PKH:"P2PKH"},d.DERIVATION_STRATEGIES={BIP44:"BIP44",BIP45:"BIP45",BIP48:"BIP48"},d.PATHS={REQUEST_KEY:"m/1'/0",TXPROPOSAL_KEY:"m/1'/1",REQUEST_KEY_AUTH:"m/2"},d.BIP45_SHARED_INDEX=2147483647,d.UNITS={btc:{toSatoshis:1e8,maxDecimals:6,minDecimals:2},bit:{toSatoshis:100,maxDecimals:0,minDecimals:0}},b.exports=d},{}],4:[function(a,b,c){"use strict";var d={};d.DEFAULT_FEE_PER_KB=1e4,d.MIN_FEE_PER_KB=0,d.MAX_FEE_PER_KB=1e6,d.MAX_TX_FEE=1e8,b.exports=d},{}],5:[function(a,b,c){var d={};d.Constants=a("./constants"),d.Defaults=a("./defaults"),d.Utils=a("./utils"),b.exports=d},{"./constants":3,"./defaults":4,"./utils":6}],6:[function(a,b,c){(function(c){"use strict";function d(){}var e=a("lodash"),f=a("preconditions").singleton(),g=a("sjcl"),h=a("json-stable-stringify"),i=a("bitcore-lib"),j=i.Address,k=i.PrivateKey,l=i.PublicKey,m=i.crypto,n=(i.encoding,a("./constants"));d.encryptMessage=function(a,b){var c=g.codec.base64.toBits(b);return g.encrypt(c,a,{ks:128,iter:1})},d.decryptMessage=function(a,b){var c=g.codec.base64.toBits(b);return g.decrypt(c,a)},d.hashMessage=function(a){f.checkArgument(a);var b=new c(a),d=m.Hash.sha256sha256(b);return d=new i.encoding.BufferReader(d).readReverse()},d.signMessage=function(a,b){f.checkArgument(a);var c=new k(b),e=d.hashMessage(a);return m.ECDSA.sign(e,c,"little").toString()},d.verifyMessage=function(a,b,c){if(f.checkArgument(a),f.checkArgument(c),!b)return!1;var e=new l(c),g=d.hashMessage(a);try{var h=new m.Signature.fromString(b);return m.ECDSA.verify(g,h,e,"little")}catch(i){return!1}},d.privateKeyToAESKey=function(a){f.checkArgument(a&&e.isString(a)),f.checkArgument(i.PrivateKey.isValid(a),"The private key received is invalid");var b=i.PrivateKey.fromString(a);return i.crypto.Hash.sha256(b.toBuffer()).slice(0,16).toString("base64")},d.getCopayerHash=function(a,b,c){return[a,b,c].join("|")},d.getProposalHash=function(a){function b(a,b,c,d){return[a,b,c||"",d||""].join("|")}return arguments.length>1?b.apply(this,arguments):h(a)},d.deriveAddress=function(a,b,c,d,g){f.checkArgument(e.contains(e.values(n.SCRIPT_TYPES),a));var h,k=e.map(b,function(a){var b=new i.HDPublicKey(a.xPubKey);return b.derive(c).publicKey});switch(a){case n.SCRIPT_TYPES.P2SH:h=j.createMultisig(k,d,g);break;case n.SCRIPT_TYPES.P2PKH:f.checkState(e.isArray(k)&&1==k.length),h=j.fromPublicKey(k[0],g)}return{address:h.toString(),path:c,publicKeys:e.invoke(k,"toString")}},d.xPubToCopayerId=function(a){var b=g.hash.sha256.hash(a);return g.codec.hex.fromBits(b)},d.signRequestPubKey=function(a,b){var c=new i.HDPrivateKey(b).derive(n.PATHS.REQUEST_KEY_AUTH).privateKey;return d.signMessage(a,c)},d.verifyRequestPubKey=function(a,b,c){var e=new i.HDPublicKey(c).derive(n.PATHS.REQUEST_KEY_AUTH).publicKey;return d.verifyMessage(a,b,e.toString())},d.formatAmount=function(a,b,c){function d(a,b,c,d){a=a.replace(".",c);var f=a.split(c),g=f[0],h=f[1];h=e.dropRightWhile(h,function(a,b){return"0"==a&&b>=d}).join("");var i=f.length>1?c+h:"";return g=g.replace(/\B(?=(\d{3})+(?!\d))/g,b),g+i}f.shouldBeNumber(a),f.checkArgument(e.contains(e.keys(n.UNITS),b)),c=c||{};var g=n.UNITS[b],h=(a/g.toSatoshis).toFixed(g.maxDecimals);return d(h,c.thousandsSeparator||",",c.decimalSeparator||".",g.minDecimals)},b.exports=d}).call(this,a("buffer").Buffer)},{"./constants":3,"bitcore-lib":64,buffer:193,"json-stable-stringify":422,lodash:426,preconditions:427,sjcl:526}],7:[function(a,b,c){(function(c){"use strict";function d(){this.version="1.0.0",this.derivationStrategy=l.DERIVATION_STRATEGIES.BIP44,this.account=0}function e(a){if(!g.contains(["livenet","testnet"],a))throw new Error("Invalid network")}var f=a("preconditions").singleton(),g=a("lodash"),h=a("bitcore-lib"),i=a("bitcore-mnemonic"),j=a("sjcl"),k=a("./common"),l=k.Constants,m=k.Utils,n=["network","xPrivKey","xPrivKeyEncrypted","xPubKey","requestPrivKey","requestPubKey","copayerId","publicKeyRing","walletId","walletName","m","n","walletPrivKey","personalEncryptingKey","sharedEncryptingKey","copayerName","externalSource","mnemonic","mnemonicEncrypted","entropySource","mnemonicHasPassphrase","derivationStrategy","account","addressType"];d.create=function(a){e(a);var b=new d;return b.network=a,b.xPrivKey=new h.HDPrivateKey(a).toString(),b._expand(),b};var o={en:i.Words.ENGLISH,es:i.Words.SPANISH,ja:i.Words.JAPANESE,zh:i.Words.CHINESE,fr:i.Words.FRENCH};d.createWithMnemonic=function(a,b,c,g){if(e(a),!o[c])throw new Error("Unsupported language");f.shouldBeNumber(g);for(var h=new i(o[c]);!i.isValid(h.toString());)h=new i(o[c]);var j=new d;return j.network=a,j.account=g,j.xPrivKey=h.toHDPrivateKey(b,a).toString(),j._expand(),j.mnemonic=h.phrase,j.mnemonicHasPassphrase=!!b,j},d.fromExtendedPrivateKey=function(a){var b=new d;return b.xPrivKey=a,b._expand(),b},d.fromMnemonic=function(a,b,c,h,j){e(a),f.shouldBeNumber(h),f.checkArgument(g.contains(g.values(l.DERIVATION_STRATEGIES),j));
var k=new i(b),m=new d;return m.xPrivKey=k.toHDPrivateKey(c,a).toString(),m.mnemonicHasPassphrase=!!c,m.account=h,m.derivationStrategy=j,m._expand(),m},d.fromExtendedPublicKey=function(a,b,e,i,j){f.checkArgument(e),f.shouldBeNumber(i),f.checkArgument(g.contains(g.values(l.DERIVATION_STRATEGIES),j));var k=new c(e,"hex");f.checkArgument(k.length>=14,"At least 112 bits of entropy are needed");var m=new d;return m.xPubKey=a,m.entropySource=h.crypto.Hash.sha256sha256(k).toString("hex"),m.account=i,m.derivationStrategy=j,m.externalSource=b,m._expand(),m},d._getNetworkFromExtendedKey=function(a){return f.checkArgument(a&&g.isString(a)),"t"==a.charAt(0)?"testnet":"livenet"},d._xPubToCopayerId=function(a){var b=j.hash.sha256.hash(a);return j.codec.hex.fromBits(b)},d.prototype._hashFromEntropy=function(a,b){f.checkState(a);var d=new c(this.entropySource,"hex"),e=h.crypto.Hash.sha256hmac(d,new c(a));return e.slice(0,b)},d.prototype._expand=function(){f.checkState(this.xPrivKey||this.xPubKey&&this.entropySource);var a=d._getNetworkFromExtendedKey(this.xPrivKey||this.xPubKey);if(this.network?f.checkState(this.network==a):this.network=a,this.xPrivKey){var b=new h.HDPrivateKey.fromString(this.xPrivKey),c=b.derive(this.getBaseAddressDerivationPath());this.xPubKey=new h.HDPublicKey(c).toString();var e=b.derive(l.PATHS.REQUEST_KEY);this.requestPrivKey=e.privateKey.toString();var g=e.publicKey;this.requestPubKey=g.toString(),this.entropySource=h.crypto.Hash.sha256(e.privateKey.toBuffer()).toString("hex")}else{var i=this._hashFromEntropy("reqPrivKey",32),j=new h.PrivateKey(i.toString("hex"),a);this.requestPrivKey=j.toString(),this.requestPubKey=j.toPublicKey().toString()}this.personalEncryptingKey=this._hashFromEntropy("personalKey",16).toString("base64"),this.copayerId=d._xPubToCopayerId(this.xPubKey),this.publicKeyRing=[{xPubKey:this.xPubKey,requestPubKey:this.requestPubKey}]},d.fromObj=function(a){var b=new d;return g.each(n,function(c){b[c]=a[c]}),b.derivationStrategy=b.derivationStrategy||l.DERIVATION_STRATEGIES.BIP45,b.addressType=b.addressType||l.SCRIPT_TYPES.P2SH,b.account=b.account||0,f.checkState(b.xPrivKey||b.xPubKey||b.xPrivKeyEncrypted,"invalid input"),b},d.prototype.toObj=function(){var a=this;a.hasPrivKeyEncrypted()&&a.lock();var b={};return g.each(n,function(c){b[c]=a[c]}),b},d.prototype.getBaseAddressDerivationPath=function(){var a;switch(this.derivationStrategy){case l.DERIVATION_STRATEGIES.BIP45:return"m/45'";case l.DERIVATION_STRATEGIES.BIP44:a="44";break;case l.DERIVATION_STRATEGIES.BIP48:a="48"}var b="livenet"==this.network?"0":"1";return"m/"+a+"'/"+b+"'/"+this.account+"'"},d.prototype.getDerivedXPrivKey=function(){var a=this.getBaseAddressDerivationPath();return new h.HDPrivateKey(this.xPrivKey,this.network).derive(a)},d.prototype.addWalletPrivateKey=function(a){this.walletPrivKey=a,this.sharedEncryptingKey=m.privateKeyToAESKey(a)},d.prototype.addWalletInfo=function(a,b,c,d,e,f){this.walletId=a,this.walletName=b,this.m=c,this.n=d,e&&this.addWalletPrivateKey(e),f&&(this.copayerName=f),this.addressType=1==d?l.SCRIPT_TYPES.P2PKH:l.SCRIPT_TYPES.P2SH,!this.xPrivKey&&this.externalSource&&d>1&&(this.derivationStrategy=l.DERIVATION_STRATEGIES.BIP48),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=j.encrypt(a,this.xPrivKey,b),!this.xPrivKeyEncrypted)throw new Error("Could not encrypt");this.mnemonic&&(this.mnemonicEncrypted=j.encrypt(a,this.mnemonic,b))},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,this.mnemonicEncrypted=null},d.prototype.lock=function(){if(!this.xPrivKeyEncrypted)throw new Error("Could not lock, no encrypted private key");delete this.xPrivKey,delete this.mnemonic},d.prototype.unlock=function(a){f.checkArgument(a),this.xPrivKeyEncrypted&&(this.xPrivKey=j.decrypt(a,this.xPrivKeyEncrypted),this.mnemonicEncrypted&&(this.mnemonic=j.decrypt(a,this.mnemonicEncrypted)))},d.prototype.addPublicKeyRing=function(a){this.publicKeyRing=g.clone(a)},d.prototype.canSign=function(){return!!this.xPrivKey||!!this.xPrivKeyEncrypted},d.prototype.setNoSign=function(){delete this.xPrivKey,delete this.xPrivKeyEncrypted,delete this.mnemonic,delete this.mnemonicEncrypted},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.getMnemonic=function(){if(this.mnemonicEncrypted&&!this.mnemonic)throw new Error("Credentials are encrypted");return this.mnemonic},d.prototype.clearMnemonic=function(){delete this.mnemonic,delete this.mnemonicEncrypted},d.fromOldCopayWallet=function(a){function b(a){var b=a.publicKeyRing.copayersExtPubKeys.sort().join(""),d=new c(b),e=new h.PrivateKey.fromBuffer(h.crypto.Hash.sha256(d));return e.toString()}var e=new d;e.derivationStrategy=l.DERIVATION_STRATEGIES.BIP45,e.xPrivKey=a.privateKey.extendedPrivateKeyString,e._expand(),e.addWalletInfo(a.opts.id,a.opts.name,a.opts.requiredCopayers,a.opts.totalCopayers,b(a));var f=g.map(a.publicKeyRing.copayersExtPubKeys,function(b){var c,d=b===e.xPubKey;if(d){var f=l.PATHS.REQUEST_KEY;c=new h.HDPrivateKey(e.xPrivKey).derive(f).hdPublicKey}else{var f=l.PATHS.REQUEST_KEY_AUTH;c=new h.HDPublicKey(b).derive(f)}var g=new h.HDPublicKey(b).derive("m/2147483646/0/0"),i=g.publicKey.toString("hex"),j=a.publicKeyRing.nicknameFor[i];return d&&(e.copayerName=j),{xPubKey:b,requestPubKey:c.publicKey.toString(),copayerName:j}});return e.addPublicKeyRing(f),e},b.exports=d}).call(this,a("buffer").Buffer)},{"./common":5,"bitcore-lib":64,"bitcore-mnemonic":142,buffer:193,lodash:426,preconditions:427,sjcl:526}],8:[function(a,b,c){"use strict";function d(a,b){this.code=a,this.message=b}d.prototype.toString=function(){return"<ClientError:"+this.code+" "+this.message+">"},b.exports=d},{}],9:[function(a,b,c){"use strict";var d=a("lodash"),e=a("./clienterror"),f={INVALID_BACKUP:"Invalid Backup",WALLET_DOES_NOT_EXIST:"Wallet does not exist. Need to recreate",MISSING_PRIVATE_KEY:"Missing private keys to sign",ENCRYPTED_PRIVATE_KEY:"Private key is encrypted, cannot sign",SERVER_COMPROMISED:"Server response could not be verified",COULD_NOT_BUILD_TRANSACTION:"Could not build transaction",INSUFFICIENT_FUNDS:"Insufficient funds"},g=d.zipObject(d.map(f,function(a,b){return[b,new e(b,a)]}));g.codes=d.mapValues(f,function(a,b){return b}),b.exports=g},{"./clienterror":8,lodash:426}],10:[function(a,b,c){var d=b.exports=a("./api");d.Verifier=a("./verifier"),d.Utils=a("./common/utils"),d.sjcl=a("sjcl"),d.Bitcore=a("bitcore-lib")},{"./api":2,"./common/utils":6,"./verifier":13,"bitcore-lib":64,sjcl:526}],11:[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:426}],12:[function(a,b,c){(function(c,d){var e=a("preconditions").singleton(),f=a("bitcore-lib"),g=a("bitcore-payment-protocol"),h={};h._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)})})},h._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)},e.body?f.send(e.body):f.send(null)};var i=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?h._nodeRequest:http=h._browserRequest};h.get=function(a,b){e.checkArgument(a&&a.url);var c=i(a);a.headers=a.headers||{Accept:g.PAYMENT_REQUEST_CONTENT_TYPE,"Content-Type":"application/octet-stream"},c(a,function(c,e){if(c)return b(c);var h,i,j,k;try{var l=g.PaymentRequest.decode(e);h=(new g).makePaymentRequest(l),j=h.get("signature"),k=h.get("serialized_payment_details"),i=h.verify(!0)}catch(m){return b("Could not parse payment protocol: "+m)}var n=g.PaymentDetails.decode(k),o=new g;o=o.makePaymentDetails(n);var p=o.get("outputs");if(p.length>1)return b(new Error("Payment Protocol Error: Requests with more that one output are not supported"));var q=p[0],r=q.get("amount").toNumber(),s="test"==o.get("network")?"testnet":"livenet",t=q.get("script").offset,u=q.get("script").limit,v=new d(new Uint8Array(q.get("script").buffer)),w=v.slice(t,u),x=new f.Address.fromScript(new f.Script(w),s),y=o.get("merchant_data");y&&(y=y.toString());var z=i.verified;return i.isChain&&(z=z&&i.chainVerified),b(null,{verified:z,caTrusted:i.caTrusted,caName:i.caName,selfSigned:i.selfSigned,expires:o.get("expires"),memo:o.get("memo"),time:o.get("time"),merchant_data:y,toAddress:x.toString(),amount:r,network:s,domain:a.host,url:a.url})})},h._getPayProRefundOutputs=function(a,b){b=b.toString(10);var c=new g.Output,e=new f.Address(a),h=e.toObject().hash,i=new f.Script;return i.add(f.Opcode.OP_HASH160).add(new d(h,"hex")).add(f.Opcode.OP_EQUAL),c.set("script",i.toBuffer()),c.set("amount",b),[c]},h._createPayment=function(a,b,c,e){var f=new g;f=f.makePayment(),a&&(a=new d(a),f.set("merchant_data",a));var h=new d(b,"hex");f.set("transactions",[h]);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<f.length;l++)k[l]=f[l];return k},h.send=function(a,b){e.checkArgument(a.merchant_data).checkArgument(a.url).checkArgument(a.rawTx).checkArgument(a.refundAddr).checkArgument(a.amountSat);var c=h._createPayment(a.merchant_data,a.rawTx,a.refundAddr,a.amountSat),d=i(a);a.method="POST",a.headers=a.headers||{Accept:g.PAYMENT_ACK_CONTENT_TYPE,"Content-Type":g.PAYMENT_CONTENT_TYPE},a.body=c,d(a,function(a,c){if(a)return b(a);var d;if(c)try{var e=g.PaymentACK.decode(c),f=new g,h=f.makePaymentACK(e);d=h.get("memo")}catch(i){}return b(null,c,d)})},b.exports=h}).call(this,a("_process"),a("buffer").Buffer)},{_process:399,"bitcore-lib":64,"bitcore-payment-protocol":153,buffer:193,http:390,https:394,preconditions:427}],13:[function(a,b,c){function d(a){}var e=a("preconditions").singleton(),f=a("lodash"),g=a("bitcore-lib"),h=a("./common"),i=h.Utils,j=a("./log");d.checkAddress=function(a,b){e.checkState(a.isComplete());var c=i.deriveAddress(b.type||a.addressType,a.publicKeyRing,b.path,a.m,a.network);return c.address==b.address&&0===f.difference(c.publicKeys,b.publicKeys).length},d.checkCopayers=function(a,b){e.checkState(a.walletPrivKey);var c=g.PrivateKey.fromString(a.walletPrivKey).toPublicKey().toString();if(b.length!=a.n)return j.error("Missing public keys in server response"),!1;var d,h=[];return f.each(b,function(a){if(!d)if(h[b.xPubKey]++&&(j.error("Repeated public keys in server response"),d=!0),a.name&&a.xPubKey&&a.requestPubKey&&a.signature){var e=i.getCopayerHash(a.name,a.xPubKey,a.requestPubKey);i.verifyMessage(e,a.signature,c)||(j.error("Invalid signatures in server response"),d=!0)}else j.error("Missing copayer fields in server response"),d=!0}),d?!1:f.contains(f.pluck(b,"xPubKey"),a.xPubKey)?!0:(j.error("Server response does not contains our public keys"),!1)},d.checkTxProposalBody=function(a,b){e.checkArgument(b.creatorId),e.checkState(a.isComplete());var c=f.find(a.publicKeyRing,function(a){return i.xPubToCopayerId(a.xPubKey)===b.creatorId?!0:void 0});if(!c)return!1;var g;if(b.proposalSignaturePubKey){if(!i.verifyRequestPubKey(b.proposalSignaturePubKey,b.proposalSignaturePubKeySig,c.xPubKey))return!1;g=b.proposalSignaturePubKey}else g=c.requestPubKey;if(!g)return!1;var h;if(b.outputs){var k=f.map(b.outputs,function(a){return{toAddress:a.toAddress,amount:a.amount,message:a.encryptedMessage||a.message||null}}),l={outputs:k,message:b.encryptedMessage||b.message||null,payProUrl:b.payProUrl||null};h=i.getProposalHash(l)}else h=i.getProposalHash(b.toAddress,b.amount,b.encryptedMessage||b.message||null,b.payProUrl||null);return j.debug("Regenerating & verifying tx proposal hash -> Hash: ",h," Signature: ",b.proposalSignature),i.verifyMessage(h,b.proposalSignature,g)&&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},{"./common":5,"./log":11,"bitcore-lib":64,lodash:426,preconditions:427}],14:[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){for(var c=0;c<a.length;c+=1)b(a[c],c,a)},j=function(a,b){if(a.map)return a.map(b);var c=[];return i(a,function(a,d,e){c.push(b(a,d,e))}),c},k=function(a,b,c){return a.reduce?a.reduce(b,c):(i(a,function(a,d,e){c=b(c,a,d,e)}),c)},l=function(a){if(Object.keys)return Object.keys(a);var b=[];for(var c in a)a.hasOwnProperty(c)&&b.push(c);return b};"undefined"!=typeof a&&a.nextTick?(f.nextTick=a.nextTick,"undefined"!=typeof setImmediate?f.setImmediate=function(a){setImmediate(a)}:f.setImmediate=f.nextTick):"function"==typeof setImmediate?(f.nextTick=function(a){setImmediate(a)},f.setImmediate=f.nextTick):(f.nextTick=function(a){setTimeout(a,0)},f.setImmediate=f.nextTick),f.each=function(a,b,d){function e(b){b?(d(b),d=function(){}):(f+=1,f>=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;)f+=1,g+=1,c(b[f-1],function(a){a?(d(a),d=function(){}):(e+=1,g-=1,e>=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}