UNPKG

bitcore-wallet-client-excc

Version:

Client for bitcore-wallet-service-excc

2 lines 1.97 MB
!function a(b,c,d){function e(g,h){if(!c[g]){if(!b[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:{}};b[g][0].call(k.exports,function(a){var c=b[g][1][a];return e(c?c:a)},k,k.exports,a,b,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,d.errors=a("./lib/errors")},{"./lib":10,"./lib/errors":8}],2:[function(a,b,c){(function(c){"use strict";function d(a){a=a||{},this.request=a.request||o,this.baseUrl=a.baseUrl||y,this.payProHttp=null,this.doNotVerifyPayPro=a.doNotVerifyPayPro,this.timeout=a.timeout||5e4,this.logLevel=a.logLevel||"silent",this.supportStaffWalletId=a.supportStaffWalletId,t.setLevel(this.logLevel)}var e=a("lodash"),f=a("preconditions").singleton(),g=a("util"),h=a("async"),i=a("events"),j=a("bitcore-lib-excc"),k={excc:j,bch:a("bitcore-lib-cash")},l=a("bitcore-mnemonic-excc"),m=a("sjcl"),n=(a("url"),a("querystring")),o=(a("json-stable-stringify"),a("superagent")),p=a("./common"),q=p.Constants,r=(p.Defaults,p.Utils),s=a("./paypro"),t=a("./log"),u=a("./credentials"),v=a("./verifier"),w=a("../package.json"),x=a("./errors"),y="https://explorer.excc.co:2053/bws/api";g.inherits(d,i.EventEmitter),d.privateKeyEncryptionOpts={iter:1e4},d.prototype.initNotifications=function(a){t.warn("DEPRECATED: use initialize() instead."),this.initialize({},a)},d.prototype.initialize=function(a,b){f.checkState(this.credentials);var c=this;return c.notificationIncludeOwn=!!a.notificationIncludeOwn,c._initNotifications(a),b()},d.prototype.dispose=function(a){var b=this;b._disposeNotifications(),b._logout(a)},d.prototype._fetchLatestNotifications=function(a,b){var c=this;b=b||function(){};var d={lastNotificationId:c.lastNotificationId,includeOwn:c.notificationIncludeOwn};c.lastNotificationId||(d.timeSpan=a+1),c.getNotifications(d,function(a,d){return a?(t.warn("Error receiving notifications."),t.debug(a),b(a)):(d.length>0&&(c.lastNotificationId=e.last(d).id),e.each(d,function(a){c.emit("notification",a)}),b())})},d.prototype._initNotifications=function(a){var b=this;a=a||{};var c=a.notificationIntervalSeconds||5;b.notificationsIntervalId=setInterval(function(){b._fetchLatestNotifications(c,function(a){a&&(a instanceof x.NOT_FOUND||a instanceof x.NOT_AUTHORIZED)&&b._disposeNotifications()})},1e3*c)},d.prototype._disposeNotifications=function(){var a=this;a.notificationsIntervalId&&(clearInterval(a.notificationsIntervalId),a.notificationsIntervalId=null)},d.prototype.setNotificationsInterval=function(a){var b=this;b._disposeNotifications(),a>0&&b._initNotifications({notificationIntervalSeconds:a})},d._encryptMessage=function(a,b){return a?r.encryptMessage(a,b):null},d._decryptMessage=function(a,b){if(!a)return"";try{return r.decryptMessage(a,b)}catch(c){return"<ECANNOTDECRYPT>"}},d.prototype._processTxNotes=function(a){var b=this;if(a){var c=b.credentials.sharedEncryptingKey;e.each([].concat(a),function(a){a.encryptedBody=a.body,a.body=d._decryptMessage(a.body,c),a.encryptedEditedByName=a.editedByName,a.editedByName=d._decryptMessage(a.editedByName,c)})}},d.prototype._processTxps=function(a){var b=this;if(a){var c=b.credentials.sharedEncryptingKey;e.each([].concat(a),function(a){a.encryptedMessage=a.message,a.message=d._decryptMessage(a.message,c)||null,a.creatorName=d._decryptMessage(a.creatorName,c),e.each(a.actions,function(a){a.copayerName=d._decryptMessage(a.copayerName,c),a.comment=d._decryptMessage(a.comment,c)}),e.each(a.outputs,function(a){a.encryptedMessage=a.message,a.message=d._decryptMessage(a.message,c)||null}),a.hasUnconfirmedInputs=e.some(a.inputs,function(a){return 0==a.confirmations}),b._processTxNotes(a.note)})}},d._parseError=function(a){if(a){if(e.isString(a))try{a=JSON.parse(a)}catch(b){a={error:a}}var c;return a.code?x[a.code]?(c=new x[a.code],a.message&&(c.message=a.message)):c=new Error(a.code+": "+a.message):c=new Error(a.error||JSON.stringify(a)),t.error(c),c}},d._signRequest=function(a,b,c,d){var e=[a.toLowerCase(),b,JSON.stringify(c)].join("|");return r.signMessage(e,d)},d.prototype.seedFromRandom=function(a){f.checkArgument(arguments.length<=1,"DEPRECATED: only 1 argument accepted."),f.checkArgument(e.isUndefined(a)||e.isObject(a),"DEPRECATED: argument should be an options object."),a=a||{},this.credentials=u.create(a.coin||"excc",a.network||"livenet")};var z;d.prototype.validateKeyDerivation=function(a,b){function c(a,b){var c="m/0/0",d="Lorem ipsum dolor sit amet, ne amet urbanitas percipitur vim, libris disputando his ne, et facer suavitate qui. Ei quidam laoreet sea. Cu pro dico aliquip gubergren, in mundi postea usu. Ad labitur posidonium interesset duo, est et doctus molestie adipiscing.",e=a.deriveChild(c).privateKey,f=r.signMessage(d,e),g=b.deriveChild(c).publicKey;return r.verifyMessage(d,f,g)}function d(){var a="abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about",b=l(a).toHDPrivateKey();if("xprv9s21ZrQH143K3GJpoapnV8SFfukcVBSfeCficPSGfubmSFDxo1kuHnLisriDvSnRRuL2Qrg5ggqHKNVpxR86QEC8w35uxmGoggxtQTPvfUu"!=b.toString())return!1;if(b=b.deriveChild("m/44'/0'/0'"),"xprv9xpXFhFpqdQK3TmytPBqXtGSwS3DLjojFhTGht8gwAAii8py5X6pxeBnQ6ehJiyJ6nDjWGJfZ95WxByFXVkDxHXrqu53WCRGypk2ttuqncb"!=b.toString())return!1;var d=j.HDPublicKey.fromString("xpub6BosfCnifzxcFwrSzQiqu2DBVTshkCXacvNsWGYJVVhhawA7d4R5WSWGFNbi8Aw6ZRc1brxMyWMzG3DSSSSoekkudhUd9yLb6qx39T9nMdj");return c(b,d)}function e(){var b;try{b=g.getMnemonic()}catch(d){}var e;if(b&&(!g.mnemonicHasPassphrase||a.passphrase)){var f=new l(b);e=f.toHDPrivateKey(a.passphrase,g.network)}e||(e=new j.HDPrivateKey(g.xPrivKey)),e=e.deriveChild(g.getBaseAddressDerivationPath());var h=new j.HDPublicKey(g.xPubKey);return c(e,h)}var f=this;a=a||{};var g=f.credentials,h=!0;z||a.skipDeviceValidation||(h=d(),z=!0);var i=g.canSign()&&!g.isPrivKeyEncrypted()?e():!0;return f.keyDerivationOk=h&&i,b(null,f.keyDerivationOk)},d.prototype.seedFromRandomWithMnemonic=function(a){f.checkArgument(arguments.length<=1,"DEPRECATED: only 1 argument accepted."),f.checkArgument(e.isUndefined(a)||e.isObject(a),"DEPRECATED: argument should be an options object."),a=a||{},this.credentials=u.createWithMnemonic(a.coin||"excc",a.network||"livenet",a.passphrase,a.language||"en",a.account||0)},d.prototype.getMnemonic=function(){return this.credentials.getMnemonic()},d.prototype.mnemonicHasPassphrase=function(){return this.credentials.mnemonicHasPassphrase},d.prototype.clearMnemonic=function(){return this.credentials.clearMnemonic()},d.prototype.seedFromExtendedPrivateKey=function(a,b){b=b||{},this.credentials=u.fromExtendedPrivateKey(b.coin||"excc",a,b.account||0,b.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44,b)},d.prototype.seedFromMnemonic=function(a,b){f.checkArgument(e.isUndefined(b)||e.isObject(b),"DEPRECATED: second argument should be an options object."),b=b||{},this.credentials=u.fromMnemonic(b.coin||"excc",b.network||"livenet",a,b.passphrase,b.account||0,b.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44,b)},d.prototype.seedFromExtendedPublicKey=function(a,b,c,d){f.checkArgument(e.isUndefined(d)||e.isObject(d)),d=d||{},this.credentials=u.fromExtendedPublicKey(d.coin||"excc",a,b,c,d.account||0,d.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44)},d.prototype["export"]=function(a){f.checkState(this.credentials),a=a||{};var b,c=u.fromObj(this.credentials);return a.noSign?c.setNoSign():a.password&&c.decryptPrivateKey(a.password),b=JSON.stringify(c.toObj())},d.prototype["import"]=function(a){try{var b=u.fromObj(JSON.parse(a));this.credentials=b}catch(c){throw new x.INVALID_BACKUP}},d.prototype._import=function(a){f.checkState(this.credentials);var b=this;b.openWallet(function(c,d){return c?c instanceof x.NOT_AUTHORIZED||b.isPrivKeyExternal()?a(c):(t.info("Copayer not found, trying to add access"),void b.addAccess({},function(c){return c?a(new x.WALLET_DOES_NOT_EXIST):void b.openWallet(a)})):a(null,d)})},d.prototype.importFromMnemonic=function(a,b,c){function d(c){return u.fromMnemonic(b.coin||"excc",b.network||"livenet",a,b.passphrase,b.account||0,b.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44,{nonCompliantDerivation:c,entropySourcePath:b.entropySourcePath,walletPrivKey:b.walletPrivKey})}t.debug("Importing from 12 Words");var e=this;b=b||{};try{e.credentials=d(!1)}catch(f){return t.info("Mnemonic error:",f),c(new x.INVALID_BACKUP)}e._import(function(a,b){if(!a)return c(null,b);if(a instanceof x.INVALID_BACKUP)return c(a);if(a instanceof x.NOT_AUTHORIZED||a instanceof x.WALLET_DOES_NOT_EXIST){var f=d(!0);return f.xPubKey.toString()==e.credentials.xPubKey.toString()?c(a):(e.credentials=f,e._import(c))}return c(a)})},d.prototype.importFromExtendedPrivateKey=function(a,b,c){t.debug("Importing from Extended Private Key"),c||(c=b,b={},t.warn("DEPRECATED WARN: importFromExtendedPrivateKey should receive 3 parameters."));try{this.credentials=u.fromExtendedPrivateKey(b.coin||"excc",a,b.account||0,b.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44,b)}catch(d){return t.info("xPriv error:",d),c(new x.INVALID_BACKUP)}this._import(c)},d.prototype.importFromExtendedPublicKey=function(a,b,c,d,g){f.checkArgument(5==arguments.length,"DEPRECATED: should receive 5 arguments"),f.checkArgument(e.isUndefined(d)||e.isObject(d)),f.shouldBeFunction(g),d=d||{},t.debug("Importing from Extended Private Key");try{this.credentials=u.fromExtendedPublicKey(d.coin||"excc",a,b,c,d.account||0,d.derivationStrategy||q.DERIVATION_STRATEGIES.BIP44,d)}catch(h){return t.info("xPriv error:",h),g(new x.INVALID_BACKUP)}this._import(g)},d.prototype.decryptBIP38PrivateKey=function(b,d,e,f){var g,h=a("bip38"),i=new h;try{g=i.decrypt(b,d)}catch(k){return f(new Error("Could not decrypt BIP38 private key",k))}var l=new j.PrivateKey(g),m=l.publicKey.toAddress().toString(),n=new c(m,"ascii"),o=j.crypto.Hash.sha256sha256(n).toString("hex").substring(0,8),p=j.encoding.Base58Check.decode(b).toString("hex").substring(6,14);return o!=p?f(new Error("Incorrect passphrase")):f(null,g)},d.prototype.getBalanceFromPrivateKey=function(a,b,c){var d=this;e.isFunction(b)&&(c=b,b="excc");var f=k[b],a=new f.PrivateKey(a),g=a.publicKey.toAddress();d.getUtxos({addresses:g.toString()},function(a,b){return a?c(a):c(null,e.sum(b,"satoshis"))})},d.prototype.buildTxFromPrivateKey=function(a,b,c,d){var f=this;c=c||{};var g=c.coin||"excc",i=k[g],a=i.PrivateKey(a),j=a.publicKey.toAddress();h.waterfall([function(a){f.getUtxos({addresses:j.toString()},function(b,c){return a(b,c)})},function(d,f){if(!e.isArray(d)||0==d.length)return f(new Error("No utxos found"));var g=c.fee||1e4,h=e.sum(d,"satoshis")-g;if(0>=h)return f(new x.INSUFFICIENT_FUNDS);var j;try{var k=i.Address.fromString(b);j=(new i.Transaction).from(d).to(k,h).fee(g).sign(a),j.serialize()}catch(l){return t.error("Could not build transaction from private key",l),f(new x.COULD_NOT_BUILD_TRANSACTION)}return f(null,j)}],d)},d.prototype.openWallet=function(a){f.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,f){if(c)return a(c);var g=f.wallet;if(b._processStatus(f),!b.credentials.hasWalletInfo()){var h=e.find(g.copayers,{id:b.credentials.copayerId});b.credentials.addWalletInfo(g.id,g.name,g.m,g.n,h.name)}if("complete"!=g.status)return a();if(b.credentials.walletPrivKey){if(!v.checkCopayers(b.credentials,g.copayers))return a(new x.SERVER_COMPROMISED)}else t.warn("Could not verify copayers key (missing wallet Private Key)");return b.credentials.addPublicKeyRing(d._extractPublicKeyRing(g.copayers)),b.emit("walletCompleted",g),a(null,f)})},d.prototype._getHeaders=function(a,b,c){var d={"x-client-version":"bwc-"+w.version};return this.supportStaffWalletId&&(d["x-wallet-id"]=this.supportStaffWalletId),d},d.prototype._doRequest=function(a,b,c,f,h){var i=this,j=i._getHeaders(a,b,c);if(i.credentials)if(j["x-identity"]=i.credentials.copayerId,f&&i.session)j["x-session"]=i.session;else{var k,l=c._requestPrivKey||i.credentials.requestPrivKey;l&&(delete c._requestPrivKey,k=d._signRequest(a,b,c,l)),j["x-signature"]=k}var m=i.request[a](i.baseUrl+b);m.accept("json"),e.each(j,function(a,b){a&&m.set(b,a)}),c&&("post"==a||"put"==a?m.send(c):m.query(c)),m.timeout(i.timeout),m.end(function(a,b){return b?(b.body&&t.debug(g.inspect(b.body,{depth:10})),200!==b.status?404===b.status?h(new x.NOT_FOUND):b.status?(t.error("HTTP Error:"+b.status),h(b.body?d._parseError(b.body):new Error(b.status))):h(new x.CONNECTION_ERROR):'{"error":"read ECONNRESET"}'===b.body?h(new x.ECONNRESET_ERROR(JSON.parse(b.body))):h(null,b.body,b.header)):h(new x.CONNECTION_ERROR)})},d.prototype._login=function(a){this._doPostRequest("/v1/login",{},a)},d.prototype._logout=function(a){this._doPostRequest("/v1/logout",{},a)},d.prototype._doRequestWithLogin=function(a,b,c,d){function e(a){f._login(function(b,c){return b?a(b):c?(f.session=c,void a()):a(new x.NOT_AUTHORIZED)})}var f=this;h.waterfall([function(a){return f.session?a():void e(a)},function(d){f._doRequest(a,b,c,!0,function(g,h,i){g&&g instanceof x.NOT_AUTHORIZED&&e(function(e){return e?d(e):f._doRequest(a,b,c,!0,d)}),d(null,h,i)})}],d)},d.prototype._doPostRequest=function(a,b,c){return this._doRequest("post",a,b,!1,c)},d.prototype._doPutRequest=function(a,b,c){return this._doRequest("put",a,b,!1,c)},d.prototype._doGetRequest=function(a,b){return a+=a.indexOf("?")>0?"&":"?",a+="r="+e.random(1e4,99999),this._doRequest("get",a,{},!1,b)},d.prototype._doGetRequestWithLogin=function(a,b){return a+=a.indexOf("?")>0?"&":"?",a+="r="+e.random(1e4,99999),this._doRequestWithLogin("get",a,{},b)},d.prototype._doDeleteRequest=function(a,b){return this._doRequest("delete",a,{},!1,b)},d._buildSecret=function(a,b,d,f){e.isString(b)&&(b=j.PrivateKey.fromString(b));var g=new c(a.replace(/-/g,""),"hex"),h=new j.encoding.Base58(g).toString();return e.padRight(h,22,"0")+b.toWIF()+("testnet"==f?"T":"L")+d},d.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}f.checkArgument(a);try{var c=b(a,[22,74,75]),d=c[0].replace(/0/g,""),e=j.encoding.Base58.decode(d).toString("hex"),g=b(e,[8,12,16,20]).join("-"),h=j.PrivateKey.fromString(c[1]),i=c[2],k=c[3]||"excc";return{walletId:g,walletPrivKey:h,coin:k,network:"T"==i?"testnet":"livenet"}}catch(l){throw new Error("Invalid secret")}},d.getRawTx=function(a){var b=r.buildTx(a);return b.uncheckedSerialize()},d.signTxp=function(a,b){var c=[],d={},g=new j.HDPrivateKey(b);e.each(a.inputs,function(a){f.checkState(a.path,"Input derivation path not available (signing transaction)"),d[a.path]||(d[a.path]=g.deriveChild(a.path).privateKey,c.push(d[a.path]))});var h=r.buildTx(a),i=e.map(c,function(a,b){return h.getSignatures(a)});return i=e.map(e.sortBy(e.flatten(i),"inputIndex"),function(a){return a.signature.toDER().toString("hex")})},d.prototype._signTxp=function(a,b){var c=this.credentials.getDerivedXPrivKey(b);return d.signTxp(a,c)},d.prototype._getCurrentSignatures=function(a){var b=e.filter(a.actions,{type:"accept"});return e.map(b,function(a){return{signatures:a.signatures,xpub:a.xpub}})},d.prototype._addSignaturesToBitcoreTx=function(a,b,c,d){if(c.length!=a.inputs.length)throw new Error("Number of signatures does not match number of inputs");f.checkState(a.coin);var g=k[a.coin],h=0,i=new j.HDPublicKey(d);if(e.each(c,function(c){a.inputs[h];try{var d=g.crypto.Signature.fromString(c),e=i.deriveChild(a.inputPaths[h]).publicKey,f={inputIndex:h,signature:d,sigtype:g.crypto.Signature.SIGHASH_ALL|g.crypto.Signature.SIGHASH_FORKID,publicKey:e};b.inputs[h].addSignature(b,f),h++}catch(j){}}),h!=a.inputs.length)throw new Error("Wrong signatures")},d.prototype._applyAllSignatures=function(a,b){var c=this;f.checkState("accepted"==a.status);var d=c._getCurrentSignatures(a);e.each(d,function(d){c._addSignaturesToBitcoreTx(a,b,d.signatures,d.xpub)})},d.prototype._doJoinWallet=function(a,b,c,d,g,h,i){f.shouldBeFunction(i);var j=this;h=h||{},h.customData=h.customData||{},h.customData.walletPrivKey=b.toString();var k=r.encryptMessage(JSON.stringify(h.customData),this.credentials.personalEncryptingKey),l=r.encryptMessage(g,this.credentials.sharedEncryptingKey),m={walletId:a,coin:h.coin,name:l,xPubKey:c,requestPubKey:d,customData:k};h.dryRun&&(m.dryRun=!0),e.isBoolean(h.supportBIP44AndP2PKH)&&(m.supportBIP44AndP2PKH=h.supportBIP44AndP2PKH);var n=r.getCopayerHash(m.name,m.xPubKey,m.requestPubKey);m.copayerSignature=r.signMessage(n,b);var o="/v2/wallets/"+a+"/copayers";this._doPostRequest(o,m,function(a,b){return a?i(a):(j._processWallet(b.wallet),i(null,b.wallet))})},d.prototype.isComplete=function(){return this.credentials&&this.credentials.isComplete()},d.prototype.isPrivKeyEncrypted=function(){return this.credentials&&this.credentials.isPrivKeyEncrypted()},d.prototype.isPrivKeyExternal=function(){return this.credentials&&this.credentials.hasExternalSource()},d.prototype.getPrivKeyExternalSourceName=function(){return this.credentials?this.credentials.getExternalSourceName():null},d.prototype.getKeys=function(a){return this.credentials.getKeys(a)},d.prototype.checkPassword=function(a){if(this.isPrivKeyEncrypted())try{var b=this.getKeys(a);return!!b.xPrivKey}catch(c){return!1}},d.prototype.canSign=function(){return this.credentials&&this.credentials.canSign()},d._extractPublicKeyRing=function(a){return e.map(a,function(a){var b=e.pick(a,["xPubKey","requestPubKey"]);return b.copayerName=a.name,b})},d.prototype.encryptPrivateKey=function(a,b){this.credentials.encryptPrivateKey(a,b||d.privateKeyEncryptionOpts)},d.prototype.decryptPrivateKey=function(a){return this.credentials.decryptPrivateKey(a)},d.prototype.getFeeLevels=function(a,b,c){var d=this;f.checkArgument(a||e.includes(["excc","bch"],a)),f.checkArgument(b||e.includes(["livenet","testnet"],b)),d._doGetRequest("/v2/feelevels/?coin="+(a||"excc")+"&network="+(b||"livenet"),function(a,b){return a?c(a):c(a,b)})},d.prototype.getVersion=function(a){this._doGetRequest("/v1/version/",a)},d.prototype._checkKeyDerivation=function(){var a=this.keyDerivationOk===!1;return a&&t.error("Key derivation for this device is not working as expected"),!a},d.prototype.createWallet=function(a,b,c,g,h,i){var k=this;if(!k._checkKeyDerivation())return i(new Error("Cannot create new wallet"));h&&f.shouldBeObject(h),h=h||{};var l=h.coin||"excc";if(!e.includes(["excc","bch"],l))return i(new Error("Invalid coin"));var m=h.network||"livenet";if(!e.includes(["testnet","livenet"],m))return i(new Error("Invalid network"));if(k.credentials?t.info("Using existing keys"):(t.info("Generating new keys"),k.seedFromRandom({coin:l,network:m})),l!=k.credentials.coin)return i(new Error("Existing keys were created for a different coin"));if(m!=k.credentials.network)return i(new Error("Existing keys were created for a different network"));var n=h.walletPrivKey||new j.PrivateKey,o=k.credentials;o.addWalletPrivateKey(n.toString());var p=r.encryptMessage(a,o.sharedEncryptingKey),q={name:p,m:c,n:g,pubKey:new j.PrivateKey(n).toPublicKey().toString(),coin:l,network:m,singleAddress:!!h.singleAddress,id:h.id};k._doPostRequest("/v2/wallets/",q,function(e,f){if(e)return i(e);var h=f.walletId;o.addWalletInfo(h,a,c,g,b);var j=d._buildSecret(o.walletId,o.walletPrivKey,o.coin,o.network);k._doJoinWallet(h,n,o.xPubKey,o.requestPubKey,b,{coin:l},function(a,b){return a?i(a):i(null,g>1?j:null)})})},d.prototype.joinWallet=function(a,b,c,f){var g=this;if(f||(f=c,c={},t.warn("DEPRECATED WARN: joinWallet should receive 4 parameters.")),!g._checkKeyDerivation())return f(new Error("Cannot join wallet"));c=c||{};var h=c.coin||"excc";if(!e.includes(["excc","bch"],h))return f(new Error("Invalid coin"));try{var i=d.parseSecret(a)}catch(j){return f(j)}g.credentials||g.seedFromRandom({coin:h,network:i.network}),g.credentials.addWalletPrivateKey(i.walletPrivKey.toString()),g._doJoinWallet(i.walletId,i.walletPrivKey,g.credentials.xPubKey,g.credentials.requestPubKey,b,{coin:h,dryRun:!!c.dryRun},function(a,d){return a?f(a):(c.dryRun||g.credentials.addWalletInfo(d.id,d.name,d.m,d.n,b),f(null,d))})},d.prototype.recreateWallet=function(a){f.checkState(this.credentials),f.checkState(this.credentials.isComplete()),f.checkState(this.credentials.walletPrivKey);var b=this;this.getStatus({includeExtendedInfo:!0},function(c){if(!c)return t.info("Wallet is already created"),a();var d=b.credentials,e=j.PrivateKey.fromString(d.walletPrivKey),f=d.walletId,g=d.derivationStrategy!=q.DERIVATION_STRATEGIES.BIP45,i=r.encryptMessage(d.walletName||"recovered wallet",d.sharedEncryptingKey),k=(d.coin,{name:i,m:d.m,n:d.n,pubKey:e.toPublicKey().toString(),coin:d.coin,network:d.network,id:f,supportBIP44AndP2PKH:g});b._doPostRequest("/v2/wallets/",k,function(c,i){if(c)return c instanceof x.WALLET_ALREADY_EXISTS?b.addAccess({},function(c){return c?a(c):void b.openWallet(function(b){return a(b)})}):a(c);f||(f=i.walletId);var j=1;h.each(b.credentials.publicKeyRing,function(a,c){var h=a.copayerName||"copayer "+j++;b._doJoinWallet(f,e,a.xPubKey,a.requestPubKey,h,{coin:d.coin,supportBIP44AndP2PKH:g},function(a){return a&&a instanceof x.COPAYER_IN_WALLET?c():c(a)})},a)})})},d.prototype._processWallet=function(a){var b=this,c=b.credentials.sharedEncryptingKey,d=r.decryptMessage(a.name,c);d!=a.name&&(a.encryptedName=a.name),a.name=d,e.each(a.copayers,function(a){var b=r.decryptMessage(a.name,c);b!=a.name&&(a.encryptedName=a.name),a.name=b,e.each(a.requestPubKeys,function(a){if(a.name){var b=r.decryptMessage(a.name,c);b!=a.name&&(a.encryptedName=a.name),a.name=b}})})},d.prototype._processStatus=function(a){function b(a){var b=a.wallet.copayers;if(b){var d=e.find(b,{id:c.credentials.copayerId});if(d&&d.customData){var f;try{f=JSON.parse(r.decryptMessage(d.customData,c.credentials.personalEncryptingKey))}catch(g){t.warn("Could not decrypt customData:",d.customData)}f&&(a.customData=f,!c.credentials.walletPrivKey&&f.walletPrivKey&&c.credentials.addWalletPrivateKey(f.walletPrivKey))}}}var c=this;b(a),c._processWallet(a.wallet),c._processTxps(a.pendingTxps)},d.prototype.getNotifications=function(a,b){f.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._doGetRequestWithLogin(d,function(d,f){if(d)return b(d);var g=e.filter(f,function(b){return a.includeOwn||b.creatorId!=c.credentials.copayerId});return b(null,g)})},d.prototype.getStatus=function(a,b){f.checkState(this.credentials),b||(b=a,a={},t.warn("DEPRECATED WARN: getStatus should receive 2 parameters."));var c=this;a=a||{};var e=[];e.push("includeExtendedInfo="+(a.includeExtendedInfo?"1":"0")),e.push("twoStep="+(a.twoStep?"1":"0")),c._doGetRequest("/v2/wallets/?"+e.join("&"),function(a,e){if(a)return b(a);if("pending"==e.wallet.status){var f=c.credentials;e.wallet.secret=d._buildSecret(f.walletId,f.walletPrivKey,f.coin,f.network)}return c._processStatus(e),b(a,e)})},d.prototype.getPreferences=function(a){f.checkState(this.credentials),f.checkArgument(a);var b=this;b._doGetRequest("/v1/preferences/",function(b,c){return b?a(b):a(null,c)})},d.prototype.savePreferences=function(a,b){f.checkState(this.credentials),f.checkArgument(b);var c=this;c._doPutRequest("/v1/preferences/",a,b)},d.prototype.fetchPayPro=function(a,b){f.checkArgument(a).checkArgument(a.payProUrl),s.get({url:a.payProUrl,http:this.payProHttp},function(a,c){return a?b(a):b(null,c)})},d.prototype.getUtxos=function(a,b){f.checkState(this.credentials&&this.credentials.isComplete()),a=a||{};var c="/v1/utxos/";a.addresses&&(c+="?"+n.stringify({addresses:[].concat(a.addresses).join(",")})),this._doGetRequest(c,b)},d.prototype._getCreateTxProposalArgs=function(a){var b=this,c=e.cloneDeep(a);return c.message=d._encryptMessage(a.message,this.credentials.sharedEncryptingKey)||null,c.payProUrl=a.payProUrl||null,e.each(c.outputs,function(a){a.message=d._encryptMessage(a.message,b.credentials.sharedEncryptingKey)||null}),c},d.prototype.createTxProposal=function(a,b){f.checkState(this.credentials&&this.credentials.isComplete()),f.checkState(this.credentials.sharedEncryptingKey),f.checkArgument(a);var c=this,d=c._getCreateTxProposalArgs(a);c._doPostRequest("/v2/txproposals/",d,function(a,e){return a?b(a):(c._processTxps(e),v.checkProposalCreation(d,e,c.credentials.sharedEncryptingKey)?b(null,e):b(new x.SERVER_COMPROMISED))})},d.prototype.publishTxProposal=function(a,b){f.checkState(this.credentials&&this.credentials.isComplete()),f.checkArgument(a).checkArgument(a.txp),f.checkState(parseInt(a.txp.version)>=3);var c=this,d=r.buildTx(a.txp),e=d.uncheckedSerialize(),g={proposalSignature:r.signMessage(e,c.credentials.requestPrivKey)},h="/v1/txproposals/"+a.txp.id+"/publish/";c._doPostRequest(h,g,function(a,d){return a?b(a):(c._processTxps(d),b(null,d))})},d.prototype.createAddress=function(a,b){f.checkState(this.credentials&&this.credentials.isComplete());var c=this;return b||(b=a,a={},t.warn("DEPRECATED WARN: createAddress should receive 2 parameters.")),c._checkKeyDerivation()?(a=a||{},void c._doPostRequest("/v3/addresses/",a,function(a,d){return a?b(a):v.checkAddress(c.credentials,d)?b(null,d):b(new x.SERVER_COMPROMISED)})):b(new Error("Cannot create new address for this wallet"))},d.prototype.getMainAddresses=function(a,b){f.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 g="";d.length>0&&(g="?"+d.join("&"));var h="/v1/addresses/"+g;c._doGetRequest(h,function(d,f){if(d)return b(d);if(!a.doNotVerify){var g=e.some(f,function(a){return!v.checkAddress(c.credentials,a)});if(g)return b(new x.SERVER_COMPROMISED)}return b(null,f)})},d.prototype.getBalance=function(a,b){b||(b=a,a={},t.warn("DEPRECATED WARN: getBalance should receive 2 parameters."));a=a||{},f.checkState(this.credentials&&this.credentials.isComplete());var c=[];if(a.twoStep&&c.push("?twoStep=1"),a.coin){if(!e.includes(["excc","bch"],a.coin))return b(new Error("Invalid coin"));c.push("coin="+a.coin)}var d="";c.length>0&&(d="?"+c.join("&"));var g="/v1/balance/"+d;this._doGetRequest(g,b)},d.prototype.getTxProposals=function(a,b){f.checkState(this.credentials&&this.credentials.isComplete());var c=this;c._doGetRequest("/v1/txproposals/",function(d,e){return d?b(d):(c._processTxps(e),void h.every(e,function(b,d){return a.doNotVerify?d(!0):void c.getPayPro(b,function(a,e){var f=v.checkTxProposal(c.credentials,b,{paypro:e});return d(f)})},function(d){if(!d)return b(new x.SERVER_COMPROMISED);var f;return f=a.forAirGapped?{txps:JSON.parse(JSON.stringify(e)),encryptedPkr:a.doNotEncryptPkr?null:r.encryptMessage(JSON.stringify(c.credentials.publicKeyRing),c.credentials.personalEncryptingKey),unencryptedPkr:a.doNotEncryptPkr?JSON.stringify(c.credentials.publicKeyRing):null,m:c.credentials.m,n:c.credentials.n}:e,b(null,f)}))})},d.prototype.getPayPro=function(a,b){var c=this;return!a.payProUrl||this.doNotVerifyPayPro?b():void s.get({url:a.payProUrl,http:c.payProHttp},function(a,c){return a?b(new Error("Cannot check transaction now:"+a)):b(null,c)})},d.prototype.signTxProposal=function(a,b,c){f.checkState(this.credentials&&this.credentials.isComplete()),f.checkArgument(a.creatorId),e.isFunction(b)&&(c=b,b=null);var d=this;if(!a.signatures){if(!d.canSign())return c(new x.MISSING_PRIVATE_KEY);if(d.isPrivKeyEncrypted()&&!b)return c(new x.ENCRYPTED_PRIVATE_KEY)}d.getPayPro(a,function(f,g){if(f)return c(f);var h=v.checkTxProposal(d.credentials,a,{paypro:g});if(!h)return c(new x.SERVER_COMPROMISED);var i=a.signatures;if(e.isEmpty(i))try{i=d._signTxp(a,b)}catch(j){return t.error("Error signing tx",j),c(j)}var k="/v1/txproposals/"+a.id+"/signatures/",l={signatures:i};d._doPostRequest(k,l,function(a,b){return a?c(a):(d._processTxps(b),c(null,b))})})},d.prototype.signTxProposalFromAirGapped=function(a,b,c,d,g){f.checkState(this.credentials);var h=this;if(!h.canSign())throw new x.MISSING_PRIVATE_KEY;if(h.isPrivKeyEncrypted()&&!g)throw new x.ENCRYPTED_PRIVATE_KEY;var i;try{i=JSON.parse(r.decryptMessage(b,h.credentials.personalEncryptingKey))}catch(j){throw new Error("Could not decrypt public key ring")}if(!e.isArray(i)||i.length!=d)throw new Error("Invalid public key ring");if(h.credentials.m=c,h.credentials.n=d,h.credentials.addressType=a.addressType,h.credentials.addPublicKeyRing(i),!v.checkTxProposalSignature(h.credentials,a))throw new Error("Fake transaction proposal");return h._signTxp(a,g)},d.signTxProposalFromAirGapped=function(a,b,c,f,g,h){h=h||{};var i=h.coin||"excc";if(!e.includes(["excc","bch"],i))return cb(new Error("Invalid coin"));var j=JSON.parse(c);if(!e.isArray(j)||j.length!=g)throw new Error("Invalid public key ring");var k=new d({baseUrl:"https://explorer.excc.co:2053/bws/api"});if("xprv"===a.slice(0,4)||"tprv"===a.slice(0,4)){if("xprv"===a.slice(0,4)&&"testnet"==b.network)throw new Error("testnet HD keys must start with tprv");if("tprv"===a.slice(0,4)&&"livenet"==b.network)throw new Error("livenet HD keys must start with xprv");k.seedFromExtendedPrivateKey(a,{coin:i,account:h.account,derivationStrategy:h.derivationStrategy})}else k.seedFromMnemonic(a,{coin:i,network:b.network,passphrase:h.passphrase,account:h.account,derivationStrategy:h.derivationStrategy});if(k.credentials.m=f,k.credentials.n=g,k.credentials.addressType=b.addressType,k.credentials.addPublicKeyRing(j),!v.checkTxProposalSignature(k.credentials,b))throw new Error("Fake transaction proposal");return k._signTxp(b)},d.prototype.rejectTxProposal=function(a,b,c){f.checkState(this.credentials&&this.credentials.isComplete()),f.checkArgument(c);var e=this,g="/v1/txproposals/"+a.id+"/rejections/",h={reason:d._encryptMessage(b,e.credentials.sharedEncryptingKey)||""};e._doPostRequest(g,h,function(a,b){return a?c(a):(e._processTxps(b),c(null,b))})},d.prototype.broadcastRawTx=function(a,b){f.checkState(this.credentials),f.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)})},d.prototype._doBroadcast=function(a,b){var c=this,d="/v1/txproposals/"+a.id+"/broadcast/";c._doPostRequest(d,{},function(a,d){return a?b(a):(c._processTxps(d),b(null,d))})},d.prototype.broadcastTxProposal=function(a,b){f.checkState(this.credentials&&this.credentials.isComplete());var c=this;c.getPayPro(a,function(d,e){if(e){var f=r.buildTx(a);c._applyAllSignatures(a,f),s.send({http:c.payProHttp,url:a.payProUrl,amountSat:a.amount,refundAddr:a.changeAddress.address,merchant_data:e.merchant_data,rawTx:f.serialize({disableSmallFees:!0,disableLargeFees:!0,disableDustOutputs:!0})},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)})},d.prototype.removeTxProposal=function(a,b){f.checkState(this.credentials&&this.credentials.isComplete());var c=this,d="/v1/txproposals/"+a.id;c._doDeleteRequest(d,function(a){return b(a)})},d.prototype.getTxHistory=function(a,b){f.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),a.includeExtendedInfo&&d.push("includeExtendedInfo=1"));var e="";d.length>0&&(e="?"+d.join("&"));var g="/v1/txhistory/"+e;c._doGetRequest(g,function(a,d){return a?b(a):(c._processTxps(d),b(null,d))})},d.prototype.getTx=function(a,b){f.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))})},d.prototype.startScan=function(a,b){f.checkState(this.credentials&&this.credentials.isComplete());var c=this,d={includeCopayerBranches:a.includeCopayerBranches};c._doPostRequest("/v1/addresses/scan",d,function(a){return b(a)})},d.prototype.addAccess=function(a,b){f.checkState(this.credentials&&this.credentials.canSign()), a=a||{};var c=new j.PrivateKey(a.generateNewKey?null:this.credentials.requestPrivKey),d=c.toPublicKey().toString(),e=new j.HDPrivateKey(this.credentials.xPrivKey).deriveChild(this.credentials.getBaseAddressDerivationPath()),g=r.signRequestPubKey(d,e),h=this.credentials.copayerId,i=a.name?r.encryptMessage(a.name,this.credentials.sharedEncryptingKey):null,a={copayerId:h,requestPubKey:d,signature:g,name:i,restrictions:a.restrictions};this._doPutRequest("/v1/copayers/"+h+"/",a,function(a,d){return a?b(a):b(null,d.wallet,c)})},d.prototype.getTxNote=function(a,b){f.checkState(this.credentials);var c=this;a=a||{},c._doGetRequest("/v1/txnotes/"+a.txid+"/",function(a,d){return a?b(a):(c._processTxNotes(d),b(null,d))})},d.prototype.editTxNote=function(a,b){f.checkState(this.credentials);var c=this;a=a||{},a.body&&(a.body=d._encryptMessage(a.body,this.credentials.sharedEncryptingKey)),c._doPutRequest("/v1/txnotes/"+a.txid+"/",a,function(a,d){return a?b(a):(c._processTxNotes(d),b(null,d))})},d.prototype.getTxNotes=function(a,b){f.checkState(this.credentials);var c=this;a=a||{};var d=[];e.isNumber(a.minTs)&&d.push("minTs="+a.minTs);var g="";d.length>0&&(g="?"+d.join("&")),c._doGetRequest("/v1/txnotes/"+g,function(a,d){return a?b(a):(c._processTxNotes(d),b(null,d))})},d.prototype.getFiatRate=function(a,b){f.checkState(this.credentials),f.checkArgument(b);var c=this,a=a||{},d=[];a.ts&&d.push("ts="+a.ts),a.provider&&d.push("provider="+a.provider);var e="";d.length>0&&(e="?"+d.join("&")),c._doGetRequest("/v1/fiatrates/"+a.code+"/"+e,function(a,c){return a?b(a):b(null,c)})},d.prototype.pushNotificationsSubscribe=function(a,b){var c="/v1/pushnotifications/subscriptions/";this._doPostRequest(c,a,function(a,c){return a?b(a):b(null,c)})},d.prototype.pushNotificationsUnsubscribe=function(a,b){var c="/v2/pushnotifications/subscriptions/"+a;this._doDeleteRequest(c,b)},d.prototype.txConfirmationSubscribe=function(a,b){var c="/v1/txconfirmations/";this._doPostRequest(c,a,function(a,c){return a?b(a):b(null,c)})},d.prototype.txConfirmationUnsubscribe=function(a,b){var c="/v1/txconfirmations/"+a;this._doDeleteRequest(c,b)},d.prototype.getSendMaxInfo=function(a,b){var c=this,d=[];a=a||{},a.feeLevel&&d.push("feeLevel="+a.feeLevel),a.feePerKb&&d.push("feePerKb="+a.feePerKb),a.excludeUnconfirmedUtxos&&d.push("excludeUnconfirmedUtxos=1"),a.returnInputs&&d.push("returnInputs=1");var e="";d.length>0&&(e="?"+d.join("&"));var f="/v1/sendmaxinfo/"+e;c._doGetRequest(f,function(a,c){return a?b(a):b(null,c)})},d.prototype.getStatusByIdentifier=function(a,b){f.checkState(this.credentials);var c=this;a=a||{};var e=[];e.push("includeExtendedInfo="+(a.includeExtendedInfo?"1":"0")),e.push("twoStep="+(a.twoStep?"1":"0")),c._doGetRequest("/v1/wallets/"+a.identifier+"?"+e.join("&"),function(a,e){if(a||!e||!e.wallet)return b(a);if("pending"==e.wallet.status){var f=c.credentials;e.wallet.secret=d._buildSecret(f.walletId,f.walletPrivKey,f.coin,f.network)}return c._processStatus(e),b(a,e)})},d.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){t.debug(h)}}if(!d)return null;var i;try{i=JSON.parse(d)}catch(h){}return i},d.prototype.getWalletIdsFromOldCopay=function(a,b,c){var d=this._oldCopayDecrypt(a,b,c);if(!d)return null;var f=d.walletIds.concat(e.keys(d.focusedTimestamps));return e.uniq(f)},d.prototype.createWalletFromOldCopay=function(a,b,c,d){var e=this._oldCopayDecrypt(a,b,c);return e?e.publicKeyRing.copayersExtPubKeys.length!=e.opts.totalCopayers?d(new Error("Wallet is incomplete, cannot be imported")):(this.credentials=u.fromOldCopayWallet(e),void this.recreateWallet(d)):d(new Error("Could not decrypt"))},b.exports=d}).call(this,a("buffer").Buffer)},{"../package.json":617,"./common":5,"./credentials":7,"./errors":8,"./log":11,"./paypro":12,"./verifier":13,async:14,bip38:15,"bitcore-lib-cash":88,"bitcore-lib-excc":174,"bitcore-mnemonic-excc":247,buffer:287,events:555,"json-stable-stringify":599,lodash:603,preconditions:604,querystring:563,sjcl:609,superagent:611,url:591,util:595}],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={excc:{toSatoshis:1e8,full:{maxDecimals:8,minDecimals:8},"short":{maxDecimals:6,minDecimals:2}},bit:{toSatoshis:100,full:{maxDecimals:2,minDecimals:2},"short":{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-excc"),j={excc:i,bch:a("bitcore-lib-cash")},k=i.PrivateKey,l=i.PublicKey,m=i.crypto,n=(i.encoding,a("./constants")),o=a("./defaults");d.SJCL={},d.encryptMessage=function(a,b){var c=g.codec.base64.toBits(b);return g.encrypt(c,a,e.defaults({ks:128,iter:1},d.SJCL))},d.decryptMessage=function(a,b){try{var c=g.codec.base64.toBits(b);return g.decrypt(c,a)}catch(d){return 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,h){f.checkArgument(e.includes(e.values(n.SCRIPT_TYPES),a)),h=h||"excc";var i,k=j[h],l=e.map(b,function(a){var b=new k.HDPublicKey(a.xPubKey);return b.deriveChild(c).publicKey});switch(a){case n.SCRIPT_TYPES.P2SH:i=k.Address.createMultisig(l,d,g);break;case n.SCRIPT_TYPES.P2PKH:f.checkState(e.isArray(l)&&1==l.length),i=k.Address.fromPublicKey(l[0],g)}return{address:i.toString(),path:c,publicKeys:e.invoke(l,"toString")}},d.xPubToCopayerId=function(a,b){var c="excc"==a?b:a+b,d=g.hash.sha256.hash(c);return g.codec.hex.fromBits(d)},d.signRequestPubKey=function(a,b){var c=new i.HDPrivateKey(b).deriveChild(n.PATHS.REQUEST_KEY_AUTH).privateKey;return d.signMessage(a,c)},d.verifyRequestPubKey=function(a,b,c){var e=new i.HDPublicKey(c).deriveChild(n.PATHS.REQUEST_KEY_AUTH).publicKey;return d.verifyMessage(a,b,e.toString())},d.formatAmount=function(a,b,c){function d(a,b){var c=a.toString().split("."),d=(c[1]||"0").substring(0,b);return parseFloat(c[0]+"."+d)}function g(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.includes(e.keys(n.UNITS),b)),c=c||{};var h=n.UNITS[b],i=c.fullPrecision?"full":"short",j=d(a/h.toSatoshis,h[i].maxDecimals).toFixed(h[i].maxDecimals);return g(j,c.thousandsSeparator||",",c.decimalSeparator||".",h[i].minDecimals)},d.buildTx=function(a){var b=a.coin||"excc",c=j[b],d=new c.Transaction;switch(f.checkState(e.includes(e.values(n.SCRIPT_TYPES),a.addressType)),a.addressType){case n.SCRIPT_TYPES.P2SH:e.each(a.inputs,function(b){d.from(b,b.publicKeys,a.requiredSignatures)});break;case n.SCRIPT_TYPES.P2PKH:d.from(a.inputs)}if(a.toAddress&&a.amount&&!a.outputs?d.to(a.toAddress,a.amount):a.outputs&&e.each(a.outputs,function(a){f.checkState(a.script||a.toAddress,"Output should have either toAddress or script specified"),a.script?d.addOutput(new c.Transaction.Output({script:a.script,satoshis:a.amount})):d.to(a.toAddress,a.amount)}),d.fee(a.fee),d.change(a.changeAddress.address),d.outputs.length>1){var g=e.reject(a.outputOrder,function(a){return a>=d.outputs.length});f.checkState(d.outputs.length==g.length),d.sortOutputs(function(a){return e.map(g,function(b){return a[b]})})}var h=e.reduce(a.inputs,function(a,b){return+b.satoshis+a},0),i=e.reduce(d.outputs,function(a,b){return+b.satoshis+a},0);return f.checkState(h-i>=0),f.checkState(h-i<=o.MAX_TX_FEE),d},b.exports=d}).call(this,a("buffer").Buffer)},{"./constants":3,"./defaults":4,"bitcore-lib-cash":88,"bitcore-lib-excc":174,buffer:287,"json-stable-stringify":599,lodash:603,preconditions:604,sjcl:609}],7:[function(a,b,c){(function(c){"use strict";function d(){this.version="1.0.0",this.derivationStrategy=m.DERIVATION_STRATEGIES.BIP44,this.account=0}function e(a){if(!h.includes(["excc","bch"],a))throw new Error("Invalid coin")}function f(a){if(!h.includes(["livenet","testnet"],a))throw new Error("Invalid network")}var g=a("preconditions").singleton(),h=a("lodash"),i=a("bitcore-lib-excc"),j=a("bitcore-mnemonic-excc"),k=a("sjcl"),l=a("./common"),m=l.Constants,n=l.Utils,o=["coin","network","xPrivKey","xPrivKeyEncrypted","xPubKey","requestPrivKey","requestPubKey","copayerId","publicKeyRing","walletId","walletName","m","n","walletPrivKey","personalEncryptingKey","sharedEncryptingKey","copayerName","externalSource","mnemonic","mnemonicEncrypted","entropySource","mnemonicHasPassphrase","derivationStrategy","account","compliantDerivation","addressType","hwInfo","entropySourcePath"];d.create=function(a,b){e(a),f(b);var c=new d;return c.coin=a,c.network=b,c.xPrivKey=new i.HDPrivateKey(b).toString(),c.compliantDerivation=!0,c._expand(),c};var p={en:j.Words.ENGLISH,es:j.Words.SPANISH,ja:j.Words.JAPANESE,zh:j.Words.CHINESE,fr:j.Words.FRENCH,it:j.Words.ITALIAN};d.createWithMnemonic=function(a,b,c,h,i,k){if(e(a),f(b),!p[h])throw new Error("Unsupported language");g.shouldBeNumber(i),k=k||{};for(var l=new j(p[h]);!j.isValid(l.toString());)l=new j(p[h]);var m=new d;return m.coin=a,m.network=b,m.account=i,m.xPrivKey=l.toHDPrivateKey(c,b).toString(),m.compliantDerivation=!0,m._expand(),m.mnemonic=l.phrase,m.mnemonicHasPassphrase=!!c,m},d.fromExtendedPrivateKey=function(a,b,c,f,i){e(a),g.shouldBeNumber(c),g.checkArgument(h.includes(h.values(m.DERIVATION_STRATEGIES),f)),i=i||{};var j=new d;return j.coin=a,j.xPrivKey=b,j.account=c,j.derivationStrategy=f,j.compliantDerivation=!i.nonCompliantDerivation,i.walletPrivKey&&j.addWalletPrivateKey(i.walletPrivKey),j._expand(),j},d.fromMnemonic=function(a,b,c,i,k,l,n){e(a),f(b),g.shouldBeNumber(k),g.checkArgument(h.includes(h.values(m.DERIVATION_STRATEGIES),l)),n=n||{};var o=new j(c),p=new d;return p.coin=a,p.xPrivKey=o.toHDPrivateKey(i,b).toString(),p.mnemonic=c,p.mnemonicHasPassphrase=!!i,p.account=k,p.derivationStrategy=l,p.compliantDerivation=!n.nonCompliantDerivation,p.entropySourcePath=n.entropySourcePath,n.walletPrivKey&&p.addWalletPrivateKey(n.walletPrivKey),p._expand(),p},d.fromExtendedPublicKey=function(a,b,f,j,k,l,n){e(a),g.checkArgument(j),g.shouldBeNumber(k),g.checkArgument(h.includes(h.values(m.DERIVATION_STRATEGIES),l)),n=n||{};var o=new c(j,"hex");g.checkArgument(o.length>=14,"At least 112 bits of entropy are needed");var p=new d;return p.coin=a,p.xPubKey=b,p.entropySource=i.crypto.Hash.sha256sha256(o).toString("hex"),p.account=k,p.derivationStrategy=l,p.externalSource=f,p.compliantDerivation=!0,p._expand(),p},d._getNetworkFromExtendedKey=function(a){return g.checkArgument(a&&h.isString(a)),"t"==a.charAt(0)?"testnet":"livenet"},d.prototype._hashFromEntropy=function(a,b){g.checkState(a);var d=new c(this.entropySource,"hex"),e=i.crypto.Hash.sha256hmac(d,new c(a));return e.slice(0,b)},d.prototype._expand=function(){g.checkState(this.xPrivKey||this.xPubKey&&this.entropySource);var a=d._getNetworkFromExtendedKey(this.xPrivKey||this.xPubKey);if(this.network?g.checkState(this.network==a):this.network=a,this.xPrivKey){var b=new i.HDPrivateKey.fromString(this.xPrivKey),c=this.compliantDerivation?h.bind(b.deriveChild,b):h.bind(b.deriveNonCompliantChild,b),e=c(this.getBaseAddressDerivationPath());this.xPubKey=e.hdPublicKey.toString()}if(this.entropySourcePath){var f=c(this.entropySourcePath).publicKey.toBuffer();this.entropySource=i.crypto.Hash.sha256sha256(f).toString("hex")}if(this.entropySource){var f=this._hashFromEntropy("reqPrivKey",32),j=new i.PrivateKey(f.toString("hex"),a);this.requestPrivKey=j.toString(),this.requestPubKey=j.toPublicKey().toString()}else{var k=c(m.PATHS.REQUEST_KEY);this.requestPrivKey=k.privateKey.toString();var l=k.publicKey;this.requestPubKey=l.toString(),this.entropySource=i.crypto.Hash.sha256(k.privateKey.toBuffer()).toString("hex")}this.personalEncryptingKey=this._hashFromEntropy("personalKey",16).toString("base64"),g.checkState(this.coin),this.copayerId=n.xPubToCopayerId(this.coin,this.xPubKey),this.publicKeyRing=[{xPubKey:this.xPubKey,requestPubKey:this.requestPubKey}]},d.fromObj=function(a){var b=new d;return h.each(o,function(c){b[c]=a[c]}),b.coin=b.coin||"excc",b.derivationStrategy=b.derivationStrategy||m.DERIVATION_STRATEGIES.BIP45,b.addressType=b.addressType||m.SCRIPT_TYPES.P2SH,b.account=b.account||0,g.checkState(b.xPrivKey||b.xPubKey||b.xPrivKeyEncrypted,"invalid input"),b},d.prototype.toObj=function(){var a=this,b={};return h.each(o,function(c){b[c]=a[c]}),b},d.prototype.getBaseAddressDerivationPath=function(){var a;switch(this.derivationStrategy){case m.DERIVATION_STRATEGIES.BIP45:return"m/45'";case m.DERIVATION_STRATEGIES.BIP44:a="44";break;case m.DERIVATION_STRATEGIES.BIP48:a="48"}var b="livenet"==this.network?"0":"1";return"m/"+a+"'/"+b+"'/"+this.account+"'"},d.prototype.getDerivedXPrivKey=function(a){var b=this.getBaseAddressDerivationPath(),c=new i.HDPrivateKey(this.getKeys(a).xPrivKey,this.network),d=this.compliantDerivation?h.bind(c.deriveChild,c):h.bind(c.deriveNonCompliantChild,c);return d(b)},d.prototype.addWalletPrivateKey=function(a){this.walletPrivKey=a,this.sharedEncryptingKey=n.privateKeyToAESKey(a)},d.prototype.addWalletInfo=function(a,b,c,d,e){this.walletId=a,this.walletName=b,this.m=c,this.n=d,e&&(this.copayerName=e),"BIP44"==this.derivationStrategy&&1==d?this.addressType=m.SCRIPT_TYPES.P2PKH:this.addressType=m.SCRIPT_TYPES.P2SH,!this.xPrivKey&&this.externalSource&&d>1&&(this.derivationStrategy=m.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.encryptPrivateKey=function(a,b){if(this.xPrivKeyEncrypted)throw new Error("Private key already encrypted");if(!this.xPrivKey)throw new Error("No private key to encrypt");if(this.xPrivKeyEncrypted=k.encrypt(a,this.xPrivKey,b),!this.xPrivKeyEncrypted)throw new Error("Could not encrypt");this.mnemonic&&(this.mnemonicEncrypted=k.encrypt(a,this.mnemonic,b)),delete this.xPrivKey,delete this.mnemonic},d.prototype.decryptPrivateKey=function(a){if(!this.xPrivKeyEncrypted)throw new Error("Private key is not encrypted");try{this.xPrivKey=k.decrypt(a,this.xPrivKeyEncrypted),this.mnemonicEncrypted&&(this.mnemonic=k.decrypt(a,this.mnemonicEncrypted)),delete this.xPrivKeyEncrypted,delete this.mnemonicEncrypted}catch(b){throw new Error("Could not decrypt")}},d.prototype.getKeys=function(a){var b={};if(this.isPrivKeyEncrypted()){g.checkArgument(a,"Private keys are encrypted, a password is needed");try{b.xPrivKey=k.decrypt(a,this.xPrivKeyEncrypted),this.mnemonicEncrypted&&(b.mnemonic=k.decrypt(a,this.mnemonicEncrypted))}catch(c){throw new Error("Could not decrypt")}}else b.xPrivKey=this.xPrivKey,b.mnemonic=this.mnemonic;return b},d.prototype.addPublicKeyRing=function(a){this.publicKeyRing=h.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 i.PrivateKey.fromBuffer(i.crypto.Hash.sha256(d));return e.toString()}var e=new d;e.coin="excc",e.derivationStrategy=m.DERIVATION_STRATEGIES.BIP45,e.xPrivKey=a.privateKey.extendedPrivateKeyString,e._expand(),e.addWalletPrivateKey(b(a)),e.addWalletInfo(a.opts.id,a.opts.name,a.opts.requiredCopayers,a.opts.totalCopayers);var f=h.map(a.publicKeyRing.copayersExtPubKeys,function(b){var c,d=b===e.xPubKey;if(d){var f=m.PATHS.REQUEST_KEY;c=new i.HDPrivateKey(e.xPrivKey).deriveChild(f).hdPublicKey}else{var f=m.PATHS.REQUEST_KEY_AUTH;c=new i.HDPublicKey(b).deriveChild(f)}var g=new i.HDPublicKey(b).deriveChild("m/2147483646/0/0"),h=g.publicKey.toString("hex"),j=a.publicKeyRing.nicknameFor[h];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-exc