UNPKG

bitcore-wallet-client-terracoin

Version:
2 lines 1.51 MB
require=function(){function e(t,n,r){function i(a,s){if(!n[a]){if(!t[a]){var c="function"==typeof require&&require;if(!s&&c)return c(a,!0);if(o)return o(a,!0);var u=new Error("Cannot find module '"+a+"'");throw u.code="MODULE_NOT_FOUND",u}var f=n[a]={exports:{}};t[a][0].call(f.exports,function(e){var n=t[a][1][e];return i(n||e)},f,f.exports,e,t,n,r)}return n[a].exports}for(var o="function"==typeof require&&require,a=0;a<r.length;a++)i(r[a]);return i}return e}()({1:[function(e,t,n){(function(n){"use strict";function r(e){e=e||{},this.request=e.request||d,this.baseUrl=e.baseUrl||B,this.payProHttp=null,this.doNotVerifyPayPro=e.doNotVerifyPayPro,this.timeout=e.timeout||5e4,this.logLevel=e.logLevel||"silent",y.setLevel(this.logLevel)}var i=e("lodash"),o=e("preconditions").singleton(),a=e("util"),s=e("async"),c=e("events"),u=e("bitcore-lib-terracoin"),f=e("bitcore-mnemonic-terracoin"),h=e("sjcl"),l=(e("url"),e("querystring")),d=(e("json-stable-stringify"),e("superagent")),p=e("./common"),g=p.Constants,b=(p.Defaults,p.Utils),A=e("./paypro"),y=e("./log"),m=e("./credentials"),v=e("./verifier"),E=e("../package.json"),w=e("./errors"),B="http://localhost:3232/bws/api";a.inherits(r,c.EventEmitter),r.privateKeyEncryptionOpts={iter:1e4},r.prototype.initNotifications=function(e){y.warn("DEPRECATED: use initialize() instead."),this.initialize({},e)},r.prototype.initialize=function(e,t){o.checkState(this.credentials);var n=this;return n.notificationIncludeOwn=!!e.notificationIncludeOwn,n._initNotifications(e),t()},r.prototype.dispose=function(e){var t=this;t._disposeNotifications(),t._logout(e)},r.prototype._fetchLatestNotifications=function(e,t){var n=this;t=t||function(){};var r={lastNotificationId:n.lastNotificationId,includeOwn:n.notificationIncludeOwn};n.lastNotificationId||(r.timeSpan=e+1),n.getNotifications(r,function(e,r){return e?(y.warn("Error receiving notifications."),y.debug(e),t(e)):(r.length>0&&(n.lastNotificationId=i.last(r).id),i.each(r,function(e){n.emit("notification",e)}),t())})},r.prototype._initNotifications=function(e){var t=this;e=e||{};var n=e.notificationIntervalSeconds||5;t.notificationsIntervalId=setInterval(function(){t._fetchLatestNotifications(n,function(e){e&&(e instanceof w.NOT_FOUND||e instanceof w.NOT_AUTHORIZED)&&t._disposeNotifications()})},1e3*n)},r.prototype._disposeNotifications=function(){var e=this;e.notificationsIntervalId&&(clearInterval(e.notificationsIntervalId),e.notificationsIntervalId=null)},r.prototype.setNotificationsInterval=function(e){var t=this;t._disposeNotifications(),e>0&&t._initNotifications({notificationIntervalSeconds:e})},r._encryptMessage=function(e,t){return e?b.encryptMessage(e,t):null},r._decryptMessage=function(e,t){if(!e)return"";try{return b.decryptMessage(e,t)}catch(e){return"<ECANNOTDECRYPT>"}},r.prototype._processTxNotes=function(e){var t=this;if(e){var n=t.credentials.sharedEncryptingKey;i.each([].concat(e),function(e){e.encryptedBody=e.body,e.body=r._decryptMessage(e.body,n),e.encryptedEditedByName=e.editedByName,e.editedByName=r._decryptMessage(e.editedByName,n)})}},r.prototype._processTxps=function(e){var t=this;if(e){var n=t.credentials.sharedEncryptingKey;i.each([].concat(e),function(e){e.encryptedMessage=e.message,e.message=r._decryptMessage(e.message,n)||null,e.creatorName=r._decryptMessage(e.creatorName,n),i.each(e.actions,function(e){e.copayerName=r._decryptMessage(e.copayerName,n),e.comment=r._decryptMessage(e.comment,n)}),i.each(e.outputs,function(e){e.encryptedMessage=e.message,e.message=r._decryptMessage(e.message,n)||null}),e.hasUnconfirmedInputs=i.some(e.inputs,function(e){return 0==e.confirmations}),t._processTxNotes(e.note)})}},r._parseError=function(e){if(e){if(i.isString(e))try{e=JSON.parse(e)}catch(t){e={error:e}}var t;return e.code?w[e.code]?(t=new w[e.code],e.message&&(t.message=e.message)):t=new Error(e.code+": "+e.message):t=new Error(e.error||JSON.stringify(e)),y.error(t),t}},r._signRequest=function(e,t,n,r){var i=[e.toLowerCase(),t,JSON.stringify(n)].join("|");return b.signMessage(i,r)},r.prototype.seedFromRandom=function(e){o.checkArgument(arguments.length<=1,"DEPRECATED: only 1 argument accepted."),o.checkArgument(i.isUndefined(e)||i.isObject(e),"DEPRECATED: argument should be an options object."),e=e||{},this.credentials=m.create(e.network||"livenet")};var I;r.prototype.validateKeyDerivation=function(e,t){function n(e,t){var n="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.",r=e.deriveChild("m/0/0").privateKey,i=b.signMessage(n,r),o=t.deriveChild("m/0/0").publicKey;return b.verifyMessage(n,i,o)}var r=this;e=e||{};var i=r.credentials,o=!0;I||e.skipDeviceValidation||(o=function(){var e=f("abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about").toHDPrivateKey();return"xprv9s21ZrQH143K36Qi5XRScDaVd2Y8euseex3D7kT31Sp6aoTgwPt1YFSTHsbiqxwfiufhvijo1N6NrMJ4PKPAExsxocWncPwF9M65CY15Zai"==e.toString()&&(e=e.deriveChild("m/44'/0'/0'"),"xprv9yebnyASkz8p16RVzEaHMVa56FR6EYRAFUhvQ3prvpMeUBHeuMsJXTLCFkbjTKcCbfADANUqNgYZEM4JQBZAHgVEEijHRfeoAhMBHN7XkUQ"==e.toString()&&n(e,u.HDPublicKey.fromString("xpub6CdxCUhLbMh7DaVy6G7HidWoeHFae191chdXCSEUV9tdLycoSuBZ5Feg72GZ1dR62MFbmy79gJNZMTPwEbEjPLmHd96Doqd7YBEfqcu1DsV")))}(),I=!0);var a=!(i.canSign()&&!i.isPrivKeyEncrypted())||function(){var t;try{t=i.getMnemonic()}catch(e){}var r;if(t&&(!i.mnemonicHasPassphrase||e.passphrase)){r=new f(t).toHDPrivateKey(e.passphrase,i.network)}return r||(r=new u.HDPrivateKey(i.xPrivKey)),r=r.deriveChild(i.getBaseAddressDerivationPath()),n(r,new u.HDPublicKey(i.xPubKey))}();return r.keyDerivationOk=o&&a,t(null,r.keyDerivationOk)},r.prototype.seedFromRandomWithMnemonic=function(e){o.checkArgument(arguments.length<=1,"DEPRECATED: only 1 argument accepted."),o.checkArgument(i.isUndefined(e)||i.isObject(e),"DEPRECATED: argument should be an options object."),e=e||{},this.credentials=m.createWithMnemonic(e.network||"livenet",e.passphrase,e.language||"en",e.account||0)},r.prototype.getMnemonic=function(){return this.credentials.getMnemonic()},r.prototype.mnemonicHasPassphrase=function(){return this.credentials.mnemonicHasPassphrase},r.prototype.clearMnemonic=function(){return this.credentials.clearMnemonic()},r.prototype.seedFromExtendedPrivateKey=function(e,t){t=t||{},this.credentials=m.fromExtendedPrivateKey(e,t.account||0,t.derivationStrategy||g.DERIVATION_STRATEGIES.BIP44,t)},r.prototype.seedFromMnemonic=function(e,t){o.checkArgument(i.isUndefined(t)||i.isObject(t),"DEPRECATED: second argument should be an options object."),t=t||{},this.credentials=m.fromMnemonic(t.network||"livenet",e,t.passphrase,t.account||0,t.derivationStrategy||g.DERIVATION_STRATEGIES.BIP44,t)},r.prototype.seedFromExtendedPublicKey=function(e,t,n,r){o.checkArgument(i.isUndefined(r)||i.isObject(r)),r=r||{},this.credentials=m.fromExtendedPublicKey(e,t,n,r.account||0,r.derivationStrategy||g.DERIVATION_STRATEGIES.BIP44)},r.prototype.export=function(e){o.checkState(this.credentials),e=e||{};var t=m.fromObj(this.credentials);return e.noSign?t.setNoSign():e.password&&t.decryptPrivateKey(e.password),JSON.stringify(t.toObj())},r.prototype.import=function(e){try{var t=m.fromObj(JSON.parse(e));this.credentials=t}catch(e){throw new w.INVALID_BACKUP}},r.prototype._import=function(e){o.checkState(this.credentials);var t=this;t.openWallet(function(n,r){return n?n instanceof w.NOT_AUTHORIZED||t.isPrivKeyExternal()?e(n):(y.info("Copayer not found, trying to add access"),void t.addAccess({},function(n){if(n)return e(new w.WALLET_DOES_NOT_EXIST);t.openWallet(e)})):e(null,r)})},r.prototype.importFromMnemonic=function(e,t,n){function r(n){return m.fromMnemonic(t.network||"livenet",e,t.passphrase,t.account||0,t.derivationStrategy||g.DERIVATION_STRATEGIES.BIP44,{nonCompliantDerivation:n})}y.debug("Importing from 12 Words");var i=this;t=t||{};try{i.credentials=r(!1)}catch(e){return y.info("Mnemonic error:",e),n(new w.INVALID_BACKUP)}i._import(function(e,t){if(!e)return n(null,t);if(e instanceof w.INVALID_BACKUP)return n(e);if(e instanceof w.NOT_AUTHORIZED||e instanceof w.WALLET_DOES_NOT_EXIST){var o=r(!0);return o.xPubKey.toString()==i.credentials.xPubKey.toString()?n(e):(i.credentials=o,i._import(n))}return n(e)})},r.prototype.importFromExtendedPrivateKey=function(e,t,n){y.debug("Importing from Extended Private Key"),n||(n=t,t={},y.warn("DEPRECATED WARN: importFromExtendedPrivateKey should receive 3 parameters."));try{this.credentials=m.fromExtendedPrivateKey(e,t.account||0,t.derivationStrategy||g.DERIVATION_STRATEGIES.BIP44)}catch(e){return y.info("xPriv error:",e),n(new w.INVALID_BACKUP)}this._import(n)},r.prototype.importFromExtendedPublicKey=function(e,t,n,r,a){o.checkArgument(5==arguments.length,"DEPRECATED: should receive 5 arguments"),o.checkArgument(i.isUndefined(r)||i.isObject(r)),o.shouldBeFunction(a),r=r||{},y.debug("Importing from Extended Private Key");try{this.credentials=m.fromExtendedPublicKey(e,t,n,r.account||0,r.derivationStrategy||g.DERIVATION_STRATEGIES.BIP44)}catch(e){return y.info("xPriv error:",e),a(new w.INVALID_BACKUP)}this._import(a)},r.prototype.decryptBIP38PrivateKey=function(t,r,i,o){var a,s=e("bip38"),c=new s;try{a=c.decrypt(t,r)}catch(e){return o(new Error("Could not decrypt BIP38 private key",e))}var f=new u.PrivateKey(a),h=f.publicKey.toAddress().toString(),l=new n(h,"ascii");return u.crypto.Hash.sha256sha256(l).toString("hex").substring(0,8)!=u.encoding.Base58Check.decode(t).toString("hex").substring(6,14)?o(new Error("Incorrect passphrase")):o(null,a)},r.prototype.getBalanceFromPrivateKey=function(e,t){var n=this,e=new u.PrivateKey(e),r=e.publicKey.toAddress();n.getUtxos({addresses:r.toString()},function(e,n){return e?t(e):t(null,i.sum(n,"satoshis"))})},r.prototype.buildTxFromPrivateKey=function(e,t,n,r){var o=this;n=n||{};var e=new u.PrivateKey(e),a=e.publicKey.toAddress();s.waterfall([function(e){o.getUtxos({addresses:a.toString()},function(t,n){return e(t,n)})},function(r,o){if(!i.isArray(r)||0==r.length)return o(new Error("No utxos found"));var a=n.fee||1e4,s=i.sum(r,"satoshis")-a;if(s<=0)return o(new w.INSUFFICIENT_FUNDS);var c;try{var f=u.Address.fromString(t);c=(new u.Transaction).from(r).to(f,s).fee(a).sign(e),c.serialize()}catch(e){return y.error("Could not build transaction from private key",e),o(new w.COULD_NOT_BUILD_TRANSACTION)}return o(null,c)}],r)},r.prototype.openWallet=function(e){o.checkState(this.credentials);var t=this;if(t.credentials.isComplete()&&t.credentials.hasWalletInfo())return e(null,!0);t._doGetRequest("/v2/wallets/?includeExtendedInfo=1",function(n,o){if(n)return e(n);var a=o.wallet;if(t._processStatus(o),!t.credentials.hasWalletInfo()){var s=i.find(a.copayers,{id:t.credentials.copayerId});t.credentials.addWalletInfo(a.id,a.name,a.m,a.n,s.name)}if("complete"!=a.status)return e();if(t.credentials.walletPrivKey){if(!v.checkCopayers(t.credentials,a.copayers))return e(new w.SERVER_COMPROMISED)}else y.warn("Could not verify copayers key (missing wallet Private Key)");return t.credentials.addPublicKeyRing(r._extractPublicKeyRing(a.copayers)),t.emit("walletCompleted",a),e(null,o)})},r.prototype._getHeaders=function(e,t,n){return{"x-client-version":"bwc-"+E.version}},r.prototype._doRequest=function(e,t,n,o,s){var c=this,u=c._getHeaders(e,t,n);if(c.credentials)if(u["x-identity"]=c.credentials.copayerId,o&&c.session)u["x-session"]=c.session;else{var f,h=n._requestPrivKey||c.credentials.requestPrivKey;h&&(delete n._requestPrivKey,f=r._signRequest(e,t,n,h)),u["x-signature"]=f}var l=c.request[e](c.baseUrl+t);l.accept("json"),i.each(u,function(e,t){e&&l.set(t,e)}),n&&("post"==e||"put"==e?l.send(n):l.query(n)),l.timeout(c.timeout),l.end(function(e,t){return t?(t.body&&y.debug(a.inspect(t.body,{depth:10})),200!==t.status?404===t.status?s(new w.NOT_FOUND):t.status?(y.error("HTTP Error:"+t.status),s(t.body?r._parseError(t.body):new Error(t.status))):s(new w.CONNECTION_ERROR):'{"error":"read ECONNRESET"}'===t.body?s(new w.ECONNRESET_ERROR(JSON.parse(t.body))):s(null,t.body,t.header)):s(new w.CONNECTION_ERROR)})},r.prototype._login=function(e){this._doPostRequest("/v1/login",{},e)},r.prototype._logout=function(e){this._doPostRequest("/v1/logout",{},e)},r.prototype._doRequestWithLogin=function(e,t,n,r){function i(e){o._login(function(t,n){return t?e(t):n?(o.session=n,void e()):e(new w.NOT_AUTHORIZED)})}var o=this;s.waterfall([function(e){if(o.session)return e();i(e)},function(r){o._doRequest(e,t,n,!0,function(a,s,c){a&&a instanceof w.NOT_AUTHORIZED&&i(function(i){return i?r(i):o._doRequest(e,t,n,!0,r)}),r(null,s,c)})}],r)},r.prototype._doPostRequest=function(e,t,n){return this._doRequest("post",e,t,!1,n)},r.prototype._doPutRequest=function(e,t,n){return this._doRequest("put",e,t,!1,n)},r.prototype._doGetRequest=function(e,t){return e+=e.indexOf("?")>0?"&":"?",e+="r="+i.random(1e4,99999),this._doRequest("get",e,{},!1,t)},r.prototype._doGetRequestWithLogin=function(e,t){return e+=e.indexOf("?")>0?"&":"?",e+="r="+i.random(1e4,99999),this._doRequestWithLogin("get",e,{},t)},r.prototype._doDeleteRequest=function(e,t){return this._doRequest("delete",e,{},!1,t)},r._buildSecret=function(e,t,r){i.isString(t)&&(t=u.PrivateKey.fromString(t));var o=new n(e.replace(/-/g,""),"hex"),a=new u.encoding.Base58(o).toString();return i.padRight(a,22,"0")+t.toWIF()+("testnet"==r?"T":"L")},r.parseSecret=function(e){function t(e,t){var n=[];t.push(e.length);for(var r=0;r<t.length;)n.push(e.substring(0==r?0:t[r-1],t[r])),r++;return n}o.checkArgument(e);try{var n=t(e,[22,74]),r=n[0].replace(/0/g,"");return{walletId:t(u.encoding.Base58.decode(r).toString("hex"),[8,12,16,20]).join("-"),walletPrivKey:u.PrivateKey.fromString(n[1]),network:"T"==n[2]?"testnet":"livenet"}}catch(e){throw new Error("Invalid secret")}},r.getRawTx=function(e){return b.buildTx(e).uncheckedSerialize()},r.signTxp=function(e,t){var n=[],r={},a=new u.HDPrivateKey(t);i.each(e.inputs,function(e){o.checkState(e.path,"Input derivation path not available (signing transaction)"),r[e.path]||(r[e.path]=a.deriveChild(e.path).privateKey,n.push(r[e.path]))});var s=b.buildTx(e),c=i.map(n,function(e,t){return s.getSignatures(e)});return c=i.map(i.sortBy(i.flatten(c),"inputIndex"),function(e){return e.signature.toDER().toString("hex")})},r.prototype._signTxp=function(e,t){var n=this.credentials.getDerivedXPrivKey(t);return r.signTxp(e,n)},r.prototype._getCurrentSignatures=function(e){var t=i.filter(e.actions,{type:"accept"});return i.map(t,function(e){return{signatures:e.signatures,xpub:e.xpub}})},r.prototype._addSignaturesToBitcoreTx=function(e,t,n,r){if(n.length!=e.inputs.length)throw new Error("Number of signatures does not match number of inputs");var o=0,a=new u.HDPublicKey(r);if(i.each(n,function(n){e.inputs[o];try{var r=u.crypto.Signature.fromString(n),i=a.deriveChild(e.inputPaths[o]).publicKey,s={inputIndex:o,signature:r,sigtype:u.crypto.Signature.SIGHASH_ALL,publicKey:i};t.inputs[o].addSignature(t,s),o++}catch(e){}}),o!=e.inputs.length)throw new Error("Wrong signatures")},r.prototype._applyAllSignatures=function(e,t){var n=this;o.checkState("accepted"==e.status);var r=n._getCurrentSignatures(e);i.each(r,function(r){n._addSignaturesToBitcoreTx(e,t,r.signatures,r.xpub)})},r.prototype._doJoinWallet=function(e,t,n,r,a,s,c){o.shouldBeFunction(c);var u=this;s=s||{},s.customData=s.customData||{},s.customData.walletPrivKey=t.toString();var f=b.encryptMessage(JSON.stringify(s.customData),this.credentials.personalEncryptingKey),h=b.encryptMessage(a,this.credentials.sharedEncryptingKey),l={walletId:e,name:h,xPubKey:n,requestPubKey:r,customData:f};s.dryRun&&(l.dryRun=!0),i.isBoolean(s.supportBIP44AndP2PKH)&&(l.supportBIP44AndP2PKH=s.supportBIP44AndP2PKH);var d=b.getCopayerHash(l.name,l.xPubKey,l.requestPubKey);l.copayerSignature=b.signMessage(d,t);var p="/v2/wallets/"+e+"/copayers";this._doPostRequest(p,l,function(e,t){return e?c(e):(u._processWallet(t.wallet),c(null,t.wallet))})},r.prototype.isComplete=function(){return this.credentials&&this.credentials.isComplete()},r.prototype.isPrivKeyEncrypted=function(){return this.credentials&&this.credentials.isPrivKeyEncrypted()},r.prototype.isPrivKeyExternal=function(){return this.credentials&&this.credentials.hasExternalSource()},r.prototype.getPrivKeyExternalSourceName=function(){return this.credentials?this.credentials.getExternalSourceName():null},r.prototype.getKeys=function(e){return this.credentials.getKeys(e)},r.prototype.checkPassword=function(e){if(this.isPrivKeyEncrypted())try{return!!this.getKeys(e).xPrivKey}catch(e){return!1}},r.prototype.canSign=function(){return this.credentials&&this.credentials.canSign()},r._extractPublicKeyRing=function(e){return i.map(e,function(e){var t=i.pick(e,["xPubKey","requestPubKey"]);return t.copayerName=e.name,t})},r.prototype.encryptPrivateKey=function(e,t){this.credentials.encryptPrivateKey(e,t||r.privateKeyEncryptionOpts)},r.prototype.decryptPrivateKey=function(e){return this.credentials.decryptPrivateKey(e)},r.prototype.getFeeLevels=function(e,t){var n=this;o.checkArgument(e||i.includes(["livenet","testnet"],e)),n._doGetRequest("/v1/feelevels/?network="+(e||"livenet"),function(e,n){return e?t(e):t(e,n)})},r.prototype.getVersion=function(e){this._doGetRequest("/v1/version/",e)},r.prototype._checkKeyDerivation=function(){var e=!1===this.keyDerivationOk;return e&&y.error("Key derivation for this device is not working as expected"),!e},r.prototype.createWallet=function(e,t,n,a,s,c){var f=this;if(!f._checkKeyDerivation())return c(new Error("Cannot create new wallet"));s&&o.shouldBeObject(s),s=s||{};var h=s.network||"livenet";if(!i.includes(["testnet","livenet"],h))return c(new Error("Invalid network"));if(f.credentials?y.info("Using existing keys"):(y.info("Generating new keys"),f.seedFromRandom({network:h})),h!=f.credentials.network)return c(new Error("Existing keys were created for a different network"));var l=s.walletPrivKey||new u.PrivateKey,d=f.credentials;d.addWalletPrivateKey(l.toString());var p=b.encryptMessage(e,d.sharedEncryptingKey),g={name:p,m:n,n:a,pubKey:new u.PrivateKey(l).toPublicKey().toString(),network:h,singleAddress:!!s.singleAddress,id:s.id};f._doPostRequest("/v2/wallets/",g,function(i,o){if(i)return c(i);var s=o.walletId;d.addWalletInfo(s,e,n,a,t);var u=r._buildSecret(d.walletId,d.walletPrivKey,d.network);f._doJoinWallet(s,l,d.xPubKey,d.requestPubKey,t,{},function(e,t){return e?c(e):c(null,a>1?u:null)})})},r.prototype.joinWallet=function(e,t,n,i){var o=this;if(i||(i=n,n={},y.warn("DEPRECATED WARN: joinWallet should receive 4 parameters.")),!o._checkKeyDerivation())return i(new Error("Cannot join wallet"));n=n||{};try{var a=r.parseSecret(e)}catch(e){return i(e)}o.credentials||o.seedFromRandom({network:a.network}),o.credentials.addWalletPrivateKey(a.walletPrivKey.toString()),o._doJoinWallet(a.walletId,a.walletPrivKey,o.credentials.xPubKey,o.credentials.requestPubKey,t,{dryRun:!!n.dryRun},function(e,r){return e?i(e):(n.dryRun||o.credentials.addWalletInfo(r.id,r.name,r.m,r.n,t),i(null,r))})},r.prototype.recreateWallet=function(e){o.checkState(this.credentials),o.checkState(this.credentials.isComplete()),o.checkState(this.credentials.walletPrivKey);var t=this;this.getStatus({includeExtendedInfo:!0},function(n){if(!n)return y.info("Wallet is already created"),e();var r=t.credentials,i=u.PrivateKey.fromString(r.walletPrivKey),o=r.walletId,a=r.derivationStrategy!=g.DERIVATION_STRATEGIES.BIP45,c=b.encryptMessage(r.walletName||"recovered wallet",r.sharedEncryptingKey),f={name:c,m:r.m,n:r.n,pubKey:i.toPublicKey().toString(),network:r.network,id:o,supportBIP44AndP2PKH:a};t._doPostRequest("/v2/wallets/",f,function(n,r){if(n)return n instanceof w.WALLET_ALREADY_EXISTS?t.addAccess({},function(n){if(n)return e(n);t.openWallet(function(t){return e(t)})}):e(n);o||(o=r.walletId);var c=1;s.each(t.credentials.publicKeyRing,function(e,n){var r=e.copayerName||"copayer "+c++;t._doJoinWallet(o,i,e.xPubKey,e.requestPubKey,r,{supportBIP44AndP2PKH:a},function(e){return e&&e instanceof w.COPAYER_IN_WALLET?n():n(e)})},e)})})},r.prototype._processWallet=function(e){var t=this,n=t.credentials.sharedEncryptingKey,r=b.decryptMessage(e.name,n);r!=e.name&&(e.encryptedName=e.name),e.name=r,i.each(e.copayers,function(e){var t=b.decryptMessage(e.name,n);t!=e.name&&(e.encryptedName=e.name),e.name=t,i.each(e.requestPubKeys,function(e){if(e.name){var t=b.decryptMessage(e.name,n);t!=e.name&&(e.encryptedName=e.name),e.name=t}})})},r.prototype._processStatus=function(e){var t=this;!function(e){var n=e.wallet.copayers;if(n){var r=i.find(n,{id:t.credentials.copayerId});if(r&&r.customData){var o;try{o=JSON.parse(b.decryptMessage(r.customData,t.credentials.personalEncryptingKey))}catch(e){y.warn("Could not decrypt customData:",r.customData)}o&&(e.customData=o,!t.credentials.walletPrivKey&&o.walletPrivKey&&t.credentials.addWalletPrivateKey(o.walletPrivKey))}}}(e),t._processWallet(e.wallet),t._processTxps(e.pendingTxps)},r.prototype.getNotifications=function(e,t){o.checkState(this.credentials);var n=this;e=e||{};var r="/v1/notifications/";e.lastNotificationId?r+="?notificationId="+e.lastNotificationId:e.timeSpan&&(r+="?timeSpan="+e.timeSpan),n._doGetRequestWithLogin(r,function(r,o){if(r)return t(r);var a=i.filter(o,function(t){return e.includeOwn||t.creatorId!=n.credentials.copayerId});return t(null,a)})},r.prototype.getStatus=function(e,t){o.checkState(this.credentials),t||(t=e,e={},y.warn("DEPRECATED WARN: getStatus should receive 2 parameters."));var n=this;e=e||{};var i=[];i.push("includeExtendedInfo="+(e.includeExtendedInfo?"1":"0")),i.push("twoStep="+(e.twoStep?"1":"0")),n._doGetRequest("/v2/wallets/?"+i.join("&"),function(e,i){if(e)return t(e);if("pending"==i.wallet.status){var o=n.credentials;i.wallet.secret=r._buildSecret(o.walletId,o.walletPrivKey,o.network)}return n._processStatus(i),t(e,i)})},r.prototype.getPreferences=function(e){o.checkState(this.credentials),o.checkArgument(e),this._doGetRequest("/v1/preferences/",function(t,n){return t?e(t):e(null,n)})},r.prototype.savePreferences=function(e,t){o.checkState(this.credentials),o.checkArgument(t),this._doPutRequest("/v1/preferences/",e,t)},r.prototype.fetchPayPro=function(e,t){o.checkArgument(e).checkArgument(e.payProUrl),A.get({url:e.payProUrl,http:this.payProHttp},function(e,n){return e?t(e):t(null,n)})},r.prototype.getUtxos=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete()),e=e||{};var n="/v1/utxos/";e.addresses&&(n+="?"+l.stringify({addresses:[].concat(e.addresses).join(",")})),this._doGetRequest(n,t)},r.prototype._getCreateTxProposalArgs=function(e){var t=this,n=i.cloneDeep(e);return n.message=r._encryptMessage(e.message,this.credentials.sharedEncryptingKey)||null,n.payProUrl=e.payProUrl||null,i.each(n.outputs,function(e){e.message=r._encryptMessage(e.message,t.credentials.sharedEncryptingKey)||null}),n},r.prototype.createTxProposal=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete()),o.checkState(this.credentials.sharedEncryptingKey),o.checkArgument(e);var n=this,r=n._getCreateTxProposalArgs(e);n._doPostRequest("/v2/txproposals/",r,function(e,i){return e?t(e):(n._processTxps(i),v.checkProposalCreation(r,i,n.credentials.sharedEncryptingKey)?t(null,i):t(new w.SERVER_COMPROMISED))})},r.prototype.publishTxProposal=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete()),o.checkArgument(e).checkArgument(e.txp),o.checkState(parseInt(e.txp.version)>=3);var n=this,r=b.buildTx(e.txp),i=r.uncheckedSerialize(),a={proposalSignature:b.signMessage(i,n.credentials.requestPrivKey)},s="/v1/txproposals/"+e.txp.id+"/publish/";n._doPostRequest(s,a,function(e,r){return e?t(e):(n._processTxps(r),t(null,r))})},r.prototype.createAddress=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete());var n=this;if(t||(t=e,e={},y.warn("DEPRECATED WARN: createAddress should receive 2 parameters.")),!n._checkKeyDerivation())return t(new Error("Cannot create new address for this wallet"));e=e||{},n._doPostRequest("/v3/addresses/",e,function(e,r){return e?t(e):v.checkAddress(n.credentials,r)?t(null,r):t(new w.SERVER_COMPROMISED)})},r.prototype.getMainAddresses=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete());var n=this;e=e||{};var r=[];e.limit&&r.push("limit="+e.limit),e.reverse&&r.push("reverse=1");var a="";r.length>0&&(a="?"+r.join("&"));var s="/v1/addresses/"+a;n._doGetRequest(s,function(r,o){if(r)return t(r);if(!e.doNotVerify){if(i.some(o,function(e){return!v.checkAddress(n.credentials,e)}))return t(new w.SERVER_COMPROMISED)}return t(null,o)})},r.prototype.getBalance=function(e,t){t||(t=e,e={},y.warn("DEPRECATED WARN: getBalance should receive 2 parameters."));e=e||{},o.checkState(this.credentials&&this.credentials.isComplete());var n="/v1/balance/";e.twoStep&&(n+="?twoStep=1"),this._doGetRequest(n,t)},r.prototype.getTxProposals=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete());var n=this;n._doGetRequest("/v1/txproposals/",function(r,i){if(r)return t(r);n._processTxps(i),s.every(i,function(t,r){if(e.doNotVerify)return r(!0);n.getPayPro(t,function(e,i){var o=v.checkTxProposal(n.credentials,t,{paypro:i});return r(o)})},function(r){if(!r)return t(new w.SERVER_COMPROMISED);var o;return o=e.forAirGapped?{txps:JSON.parse(JSON.stringify(i)),encryptedPkr:e.doNotEncryptPkr?null:b.encryptMessage(JSON.stringify(n.credentials.publicKeyRing),n.credentials.personalEncryptingKey),unencryptedPkr:e.doNotEncryptPkr?JSON.stringify(n.credentials.publicKeyRing):null,m:n.credentials.m,n:n.credentials.n}:i,t(null,o)})})},r.prototype.getPayPro=function(e,t){var n=this;if(!e.payProUrl||this.doNotVerifyPayPro)return t();A.get({url:e.payProUrl,http:n.payProHttp},function(e,n){return e?t(new Error("Cannot check transaction now:"+e)):t(null,n)})},r.prototype.signTxProposal=function(e,t,n){o.checkState(this.credentials&&this.credentials.isComplete()),o.checkArgument(e.creatorId),i.isFunction(t)&&(n=t,t=null);var r=this;if(!e.signatures){if(!r.canSign())return n(new w.MISSING_PRIVATE_KEY);if(r.isPrivKeyEncrypted()&&!t)return n(new w.ENCRYPTED_PRIVATE_KEY)}r.getPayPro(e,function(o,a){if(o)return n(o);if(!v.checkTxProposal(r.credentials,e,{paypro:a}))return n(new w.SERVER_COMPROMISED);var s=e.signatures;if(i.isEmpty(s))try{s=r._signTxp(e,t)}catch(e){return y.error("Error signing tx",e),n(e)}var c="/v1/txproposals/"+e.id+"/signatures/",u={signatures:s};r._doPostRequest(c,u,function(e,t){return e?n(e):(r._processTxps(t),n(null,t))})})},r.prototype.signTxProposalFromAirGapped=function(e,t,n,r,a){o.checkState(this.credentials);var s=this;if(!s.canSign())throw new w.MISSING_PRIVATE_KEY;if(s.isPrivKeyEncrypted()&&!a)throw new w.ENCRYPTED_PRIVATE_KEY;var c;try{c=JSON.parse(b.decryptMessage(t,s.credentials.personalEncryptingKey))}catch(e){throw new Error("Could not decrypt public key ring")}if(!i.isArray(c)||c.length!=r)throw new Error("Invalid public key ring");if(s.credentials.m=n,s.credentials.n=r,s.credentials.addressType=e.addressType,s.credentials.addPublicKeyRing(c),!v.checkTxProposalSignature(s.credentials,e))throw new Error("Fake transaction proposal");return s._signTxp(e,a)},r.signTxProposalFromAirGapped=function(e,t,n,o,a,s){s=s||{};var c=JSON.parse(n);if(!i.isArray(c)||c.length!=a)throw new Error("Invalid public key ring");var u=new r({baseUrl:"https://bws.example.com/bws/api"});if("xprv"===e.slice(0,4)||"tprv"===e.slice(0,4)){if("xprv"===e.slice(0,4)&&"testnet"==t.network)throw new Error("testnet HD keys must start with tprv");if("tprv"===e.slice(0,4)&&"livenet"==t.network)throw new Error("livenet HD keys must start with xprv");u.seedFromExtendedPrivateKey(e,{account:s.account,derivationStrategy:s.derivationStrategy})}else u.seedFromMnemonic(e,{network:t.network,passphrase:s.passphrase,account:s.account,derivationStrategy:s.derivationStrategy});if(u.credentials.m=o,u.credentials.n=a,u.credentials.addressType=t.addressType,u.credentials.addPublicKeyRing(c),!v.checkTxProposalSignature(u.credentials,t))throw new Error("Fake transaction proposal");return u._signTxp(t)},r.prototype.rejectTxProposal=function(e,t,n){o.checkState(this.credentials&&this.credentials.isComplete()),o.checkArgument(n);var i=this,a="/v1/txproposals/"+e.id+"/rejections/",s={reason:r._encryptMessage(t,i.credentials.sharedEncryptingKey)||""};i._doPostRequest(a,s,function(e,t){return e?n(e):(i._processTxps(t),n(null,t))})},r.prototype.broadcastRawTx=function(e,t){o.checkState(this.credentials),o.checkArgument(t);var n=this;e=e||{};n._doPostRequest("/v1/broadcast_raw/",e,function(e,n){return e?t(e):t(null,n)})},r.prototype.broadcastIXRawTx=function(e,t){o.checkState(this.credentials),o.checkArgument(t);var n=this;e=e||{};n._doPostRequest("/v1/broadcastix_raw/",e,function(e,n){return e?t(e):t(null,n)})},r.prototype._doBroadcast=function(e,t){var n=this,r="/v1/txproposals/"+e.id+"/broadcast/";n._doPostRequest(r,{},function(e,r){return e?t(e):(n._processTxps(r),t(null,r))})},r.prototype.broadcastTxProposal=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete());var n=this;n.getPayPro(e,function(r,i){if(i){var o=b.buildTx(e);n._applyAllSignatures(e,o),A.send({http:n.payProHttp,url:e.payProUrl,amountSat:e.amount,refundAddr:e.changeAddress.address,merchant_data:i.merchant_data,rawTx:o.serialize({disableSmallFees:!0,disableLargeFees:!0,disableDustOutputs:!0})},function(r,i,o){if(r)return t(r);n._doBroadcast(e,function(e,n){return t(e,n,o)})})}else n._doBroadcast(e,t)})},r.prototype.removeTxProposal=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete());var n=this,r="/v1/txproposals/"+e.id;n._doDeleteRequest(r,function(e){return t(e)})},r.prototype.getTxHistory=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete());var n=this,r=[];e&&(e.skip&&r.push("skip="+e.skip),e.limit&&r.push("limit="+e.limit),e.includeExtendedInfo&&r.push("includeExtendedInfo=1"));var i="";r.length>0&&(i="?"+r.join("&"));var a="/v1/txhistory/"+i;n._doGetRequest(a,function(e,r){return e?t(e):(n._processTxps(r),t(null,r))})},r.prototype.getTx=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete());var n=this,r="/v1/txproposals/"+e;this._doGetRequest(r,function(e,r){return e?t(e):(n._processTxps(r),t(null,r))})},r.prototype.startScan=function(e,t){o.checkState(this.credentials&&this.credentials.isComplete());var n=this,r={includeCopayerBranches:e.includeCopayerBranches};n._doPostRequest("/v1/addresses/scan",r,function(e){return t(e)})},r.prototype.addAccess=function(e,t){o.checkState(this.credentials&&this.credentials.canSign()),e=e||{};var n=new u.PrivateKey(e.generateNewKey?null:this.credentials.requestPrivKey),r=n.toPublicKey().toString(),i=new u.HDPrivateKey(this.credentials.xPrivKey).deriveChild(this.credentials.getBaseAddressDerivationPath()),a=b.signRequestPubKey(r,i),s=this.credentials.copayerId,c=e.name?b.encryptMessage(e.name,this.credentials.sharedEncryptingKey):null,e={copayerId:s,requestPubKey:r,signature:a,name:c,restrictions:e.restrictions};this._doPutRequest("/v1/copayers/"+s+"/",e,function(e,r){return e?t(e):t(null,r.wallet,n)})},r.prototype.getTxNote=function(e,t){o.checkState(this.credentials);var n=this;e=e||{},n._doGetRequest("/v1/txnotes/"+e.txid+"/",function(e,r){return e?t(e):(n._processTxNotes(r),t(null,r))})},r.prototype.editTxNote=function(e,t){o.checkState(this.credentials);var n=this;e=e||{},e.body&&(e.body=r._encryptMessage(e.body,this.credentials.sharedEncryptingKey)),n._doPutRequest("/v1/txnotes/"+e.txid+"/",e,function(e,r){return e?t(e):(n._processTxNotes(r),t(null,r))})},r.prototype.getTxNotes=function(e,t){o.checkState(this.credentials);var n=this;e=e||{};var r=[];i.isNumber(e.minTs)&&r.push("minTs="+e.minTs);var a="";r.length>0&&(a="?"+r.join("&")),n._doGetRequest("/v1/txnotes/"+a,function(e,r){return e?t(e):(n._processTxNotes(r), t(null,r))})},r.prototype.getFiatRate=function(e,t){o.checkState(this.credentials),o.checkArgument(t);var n=this,e=e||{},r=[];e.ts&&r.push("ts="+e.ts),e.provider&&r.push("provider="+e.provider);var i="";r.length>0&&(i="?"+r.join("&")),n._doGetRequest("/v1/fiatrates/"+e.code+"/"+i,function(e,n){return e?t(e):t(null,n)})},r.prototype.pushNotificationsSubscribe=function(e,t){this._doPostRequest("/v1/pushnotifications/subscriptions/",e,function(e,n){return e?t(e):t(null,n)})},r.prototype.pushNotificationsUnsubscribe=function(e,t){var n="/v2/pushnotifications/subscriptions/"+e;this._doDeleteRequest(n,function(e){return t(e?e:null)})},r.prototype.txConfirmationSubscribe=function(e,t){this._doPostRequest("/v1/txconfirmations/",e,function(e,n){return e?t(e):t(null,n)})},r.prototype.txConfirmationUnsubscribe=function(e,t){var n="/v1/txconfirmations/"+e;this._doDeleteRequest(n,t)},r.prototype.getSendMaxInfo=function(e,t){var n=this,r=[];e=e||{},e.feeLevel&&r.push("feeLevel="+e.feeLevel),e.feePerKb&&r.push("feePerKb="+e.feePerKb),e.excludeUnconfirmedUtxos&&r.push("excludeUnconfirmedUtxos=1"),e.returnInputs&&r.push("returnInputs=1"),e.isInstantSend&&r.push("instantSend=1");var i="";r.length>0&&(i="?"+r.join("&"));var o="/v1/sendmaxinfo/"+i;n._doGetRequest(o,function(e,n){return e?t(e):t(null,n)})},r.prototype._oldCopayDecrypt=function(e,t,n){var r;try{var i=e+"@#$"+t;r=h.decrypt(i,n)}catch(o){i=e+"%^#@"+t;try{r=h.decrypt(i,n)}catch(e){y.debug(e)}}if(!r)return null;var o;try{o=JSON.parse(r)}catch(e){}return o},r.prototype.getWalletIdsFromOldCopay=function(e,t,n){var r=this._oldCopayDecrypt(e,t,n);if(!r)return null;var o=r.walletIds.concat(i.keys(r.focusedTimestamps));return i.uniq(o)},r.prototype.createWalletFromOldCopay=function(e,t,n,r){var i=this._oldCopayDecrypt(e,t,n);return i?i.publicKeyRing.copayersExtPubKeys.length!=i.opts.totalCopayers?r(new Error("Wallet is incomplete, cannot be imported")):(this.credentials=m.fromOldCopayWallet(i),void this.recreateWallet(r)):r(new Error("Could not decrypt"))},t.exports=r}).call(this,e("buffer").Buffer)},{"../package.json":457,"./common":4,"./credentials":6,"./errors":7,"./log":10,"./paypro":11,"./verifier":12,async:28,bip38:29,"bitcore-lib-terracoin":"bitcore-lib-terracoin","bitcore-mnemonic-terracoin":102,buffer:120,events:388,"json-stable-stringify":434,lodash:439,preconditions:442,querystring:396,sjcl:448,superagent:450,url:424,util:428}],2:[function(e,t,n){"use strict";var r={};r.SCRIPT_TYPES={P2SH:"P2SH",P2PKH:"P2PKH"},r.DERIVATION_STRATEGIES={BIP44:"BIP44",BIP45:"BIP45",BIP48:"BIP48"},r.PATHS={REQUEST_KEY:"m/1'/0",TXPROPOSAL_KEY:"m/1'/1",REQUEST_KEY_AUTH:"m/2"},r.BIP45_SHARED_INDEX=2147483647,r.UNITS={trc:{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}}},t.exports=r},{}],3:[function(e,t,n){"use strict";var r={};r.DEFAULT_FEE_PER_KB=1e4,r.MIN_FEE_PER_KB=0,r.MAX_FEE_PER_KB=1e6,r.MAX_TX_FEE=1e8,t.exports=r},{}],4:[function(e,t,n){var r={};r.Constants=e("./constants"),r.Defaults=e("./defaults"),r.Utils=e("./utils"),t.exports=r},{"./constants":2,"./defaults":3,"./utils":5}],5:[function(e,t,n){(function(n){"use strict";function r(){}var i=e("lodash"),o=e("preconditions").singleton(),a=e("sjcl"),s=e("json-stable-stringify"),c=e("bitcore-lib-terracoin"),u=c.Address,f=c.PrivateKey,h=c.PublicKey,l=c.crypto,d=(c.encoding,e("./constants")),p=e("./defaults");r.SJCL={},r.encryptMessage=function(e,t){var n=a.codec.base64.toBits(t);return a.encrypt(n,e,i.defaults({ks:128,iter:1},r.SJCL))},r.decryptMessage=function(e,t){try{var n=a.codec.base64.toBits(t);return a.decrypt(n,e)}catch(t){return e}},r.hashMessage=function(e){o.checkArgument(e);var t=new n(e),r=l.Hash.sha256sha256(t);return r=new c.encoding.BufferReader(r).readReverse()},r.signMessage=function(e,t){o.checkArgument(e);var n=new f(t),i=r.hashMessage(e);return l.ECDSA.sign(i,n,"little").toString()},r.verifyMessage=function(e,t,n){if(o.checkArgument(e),o.checkArgument(n),!t)return!1;var i=new h(n),a=r.hashMessage(e);try{var s=new l.Signature.fromString(t);return l.ECDSA.verify(a,s,i,"little")}catch(e){return!1}},r.privateKeyToAESKey=function(e){o.checkArgument(e&&i.isString(e)),o.checkArgument(c.PrivateKey.isValid(e),"The private key received is invalid");var t=c.PrivateKey.fromString(e);return c.crypto.Hash.sha256(t.toBuffer()).slice(0,16).toString("base64")},r.getCopayerHash=function(e,t,n){return[e,t,n].join("|")},r.getProposalHash=function(e){function t(e,t,n,r){return[e,t,n||"",r||""].join("|")}return arguments.length>1?t.apply(this,arguments):s(e)},r.deriveAddress=function(e,t,n,r,a){o.checkArgument(i.includes(i.values(d.SCRIPT_TYPES),e));var s,f=i.map(t,function(e){return new c.HDPublicKey(e.xPubKey).deriveChild(n).publicKey});switch(e){case d.SCRIPT_TYPES.P2SH:s=u.createMultisig(f,r,a);break;case d.SCRIPT_TYPES.P2PKH:o.checkState(i.isArray(f)&&1==f.length),s=u.fromPublicKey(f[0],a)}return{address:s.toString(),path:n,publicKeys:i.invoke(f,"toString")}},r.xPubToCopayerId=function(e){var t=a.hash.sha256.hash(e);return a.codec.hex.fromBits(t)},r.signRequestPubKey=function(e,t){var n=new c.HDPrivateKey(t).deriveChild(d.PATHS.REQUEST_KEY_AUTH).privateKey;return r.signMessage(e,n)},r.verifyRequestPubKey=function(e,t,n){var i=new c.HDPublicKey(n).deriveChild(d.PATHS.REQUEST_KEY_AUTH).publicKey;return r.verifyMessage(e,t,i.toString())},r.formatAmount=function(e,t,n){o.shouldBeNumber(e),o.checkArgument(i.includes(i.keys(d.UNITS),t)),n=n||{};var r=d.UNITS[t],a=n.fullPrecision?"full":"short",s=function(e,t){var n=e.toString().split("."),r=(n[1]||"0").substring(0,t);return parseFloat(n[0]+"."+r)}(e/r.toSatoshis,r[a].maxDecimals).toFixed(r[a].maxDecimals);return function(e,t,n,r){e=e.replace(".",n);var o=e.split(n),a=o[0],s=o[1];s=i.dropRightWhile(s,function(e,t){return"0"==e&&t>=r}).join("");var c=o.length>1?n+s:"";return(a=a.replace(/\B(?=(\d{3})+(?!\d))/g,t))+c}(s,n.thousandsSeparator||",",n.decimalSeparator||".",r[a].minDecimals)},r.buildTx=function(e){var t=new c.Transaction;switch(o.checkState(i.includes(i.values(d.SCRIPT_TYPES),e.addressType)),e.addressType){case d.SCRIPT_TYPES.P2SH:i.each(e.inputs,function(n){t.from(n,n.publicKeys,e.requiredSignatures)});break;case d.SCRIPT_TYPES.P2PKH:t.from(e.inputs)}if(e.toAddress&&e.amount&&!e.outputs?t.to(e.toAddress,e.amount):e.outputs&&i.each(e.outputs,function(e){o.checkState(e.script||e.toAddress,"Output should have either toAddress or script specified"),e.script?t.addOutput(new c.Transaction.Output({script:e.script,satoshis:e.amount})):t.to(e.toAddress,e.amount)}),t.fee(e.fee),t.change(e.changeAddress.address),t.outputs.length>1){var n=i.reject(e.outputOrder,function(e){return e>=t.outputs.length});o.checkState(t.outputs.length==n.length),t.sortOutputs(function(e){return i.map(n,function(t){return e[t]})})}var r=i.reduce(e.inputs,function(e,t){return+t.satoshis+e},0),a=i.reduce(t.outputs,function(e,t){return+t.satoshis+e},0);return o.checkState(r-a>=0),o.checkState(r-a<=p.MAX_TX_FEE),t},t.exports=r}).call(this,e("buffer").Buffer)},{"./constants":2,"./defaults":3,"bitcore-lib-terracoin":"bitcore-lib-terracoin",buffer:120,"json-stable-stringify":434,lodash:439,preconditions:442,sjcl:448}],6:[function(e,t,n){(function(n){"use strict";function r(){this.version="1.0.0",this.derivationStrategy=h.DERIVATION_STRATEGIES.BIP44,this.account=0}function i(e){if(!a.includes(["livenet","testnet"],e))throw new Error("Invalid network")}var o=e("preconditions").singleton(),a=e("lodash"),s=e("bitcore-lib-terracoin"),c=e("bitcore-mnemonic-terracoin"),u=e("sjcl"),f=e("./common"),h=f.Constants,l=f.Utils,d=["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"];r.create=function(e){i(e);var t=new r;return t.network=e,t.xPrivKey=new s.HDPrivateKey(e).toString(),t.compliantDerivation=!0,t._expand(),t};var p={en:c.Words.ENGLISH,es:c.Words.SPANISH,ja:c.Words.JAPANESE,zh:c.Words.CHINESE,fr:c.Words.FRENCH,it:c.Words.ITALIAN};r.createWithMnemonic=function(e,t,n,a,s){if(i(e),!p[n])throw new Error("Unsupported language");o.shouldBeNumber(a),s=s||{};for(var u=new c(p[n]);!c.isValid(u.toString());)u=new c(p[n]);var f=new r;return f.network=e,f.account=a,f.xPrivKey=u.toHDPrivateKey(t,e).toString(),f.compliantDerivation=!0,f._expand(),f.mnemonic=u.phrase,f.mnemonicHasPassphrase=!!t,f},r.fromExtendedPrivateKey=function(e,t,n,i){o.shouldBeNumber(t),o.checkArgument(a.includes(a.values(h.DERIVATION_STRATEGIES),n)),i=i||{};var s=new r;return s.xPrivKey=e,s.account=t,s.derivationStrategy=n,s.compliantDerivation=!i.nonCompliantDerivation,s._expand(),s},r.fromMnemonic=function(e,t,n,s,u,f){i(e),o.shouldBeNumber(s),o.checkArgument(a.includes(a.values(h.DERIVATION_STRATEGIES),u)),f=f||{};var l=new c(t),d=new r;return d.xPrivKey=l.toHDPrivateKey(n,e).toString(),d.mnemonic=t,d.mnemonicHasPassphrase=!!n,d.account=s,d.derivationStrategy=u,d.compliantDerivation=!f.nonCompliantDerivation,d._expand(),d},r.fromExtendedPublicKey=function(e,t,i,c,u,f){o.checkArgument(i),o.shouldBeNumber(c),o.checkArgument(a.includes(a.values(h.DERIVATION_STRATEGIES),u)),f=f||{};var l=new n(i,"hex");o.checkArgument(l.length>=14,"At least 112 bits of entropy are needed");var d=new r;return d.xPubKey=e,d.entropySource=s.crypto.Hash.sha256sha256(l).toString("hex"),d.account=c,d.derivationStrategy=u,d.externalSource=t,d.compliantDerivation=!0,d._expand(),d},r._getNetworkFromExtendedKey=function(e){return o.checkArgument(e&&a.isString(e)),"t"==e.charAt(0)?"testnet":"livenet"},r._xPubToCopayerId=function(e){var t=u.hash.sha256.hash(e);return u.codec.hex.fromBits(t)},r.prototype._hashFromEntropy=function(e,t){o.checkState(e);var r=new n(this.entropySource,"hex");return s.crypto.Hash.sha256hmac(r,new n(e)).slice(0,t)},r.prototype._expand=function(){o.checkState(this.xPrivKey||this.xPubKey&&this.entropySource);var e=r._getNetworkFromExtendedKey(this.xPrivKey||this.xPubKey);if(this.network?o.checkState(this.network==e):this.network=e,this.xPrivKey){var t=new s.HDPrivateKey.fromString(this.xPrivKey),n=this.compliantDerivation?a.bind(t.deriveChild,t):a.bind(t.deriveNonCompliantChild,t),i=n(this.getBaseAddressDerivationPath());this.xPubKey=i.hdPublicKey.toString();var c=n(h.PATHS.REQUEST_KEY);this.requestPrivKey=c.privateKey.toString();var u=c.publicKey;this.requestPubKey=u.toString(),this.entropySource=s.crypto.Hash.sha256(c.privateKey.toBuffer()).toString("hex")}else{var f=this._hashFromEntropy("reqPrivKey",32),l=new s.PrivateKey(f.toString("hex"),e);this.requestPrivKey=l.toString(),this.requestPubKey=l.toPublicKey().toString()}this.personalEncryptingKey=this._hashFromEntropy("personalKey",16).toString("base64"),this.copayerId=r._xPubToCopayerId(this.xPubKey),this.publicKeyRing=[{xPubKey:this.xPubKey,requestPubKey:this.requestPubKey}]},r.fromObj=function(e){var t=new r;return a.each(d,function(n){t[n]=e[n]}),t.derivationStrategy=t.derivationStrategy||h.DERIVATION_STRATEGIES.BIP45,t.addressType=t.addressType||h.SCRIPT_TYPES.P2SH,t.account=t.account||0,o.checkState(t.xPrivKey||t.xPubKey||t.xPrivKeyEncrypted,"invalid input"),t},r.prototype.toObj=function(){var e=this,t={};return a.each(d,function(n){t[n]=e[n]}),t},r.prototype.getBaseAddressDerivationPath=function(){var e;switch(this.derivationStrategy){case h.DERIVATION_STRATEGIES.BIP45:return"m/45'";case h.DERIVATION_STRATEGIES.BIP44:e="44";break;case h.DERIVATION_STRATEGIES.BIP48:e="48"}return"m/"+e+"'/"+("livenet"==this.network?"83":"1")+"'/"+this.account+"'"},r.prototype.getDerivedXPrivKey=function(e){var t=this.getBaseAddressDerivationPath(),n=new s.HDPrivateKey(this.getKeys(e).xPrivKey,this.network);return(this.compliantDerivation?a.bind(n.deriveChild,n):a.bind(n.deriveNonCompliantChild,n))(t)},r.prototype.addWalletPrivateKey=function(e){this.walletPrivKey=e,this.sharedEncryptingKey=l.privateKeyToAESKey(e)},r.prototype.addWalletInfo=function(e,t,n,r,i){this.walletId=e,this.walletName=t,this.m=n,this.n=r,i&&(this.copayerName=i),"BIP44"==this.derivationStrategy&&1==r?this.addressType=h.SCRIPT_TYPES.P2PKH:this.addressType=h.SCRIPT_TYPES.P2SH,!this.xPrivKey&&this.externalSource&&r>1&&(this.derivationStrategy=h.DERIVATION_STRATEGIES.BIP48),1==r&&this.addPublicKeyRing([{xPubKey:this.xPubKey,requestPubKey:this.requestPubKey}])},r.prototype.hasWalletInfo=function(){return!!this.walletId},r.prototype.isPrivKeyEncrypted=function(){return!!this.xPrivKeyEncrypted&&!this.xPrivKey},r.prototype.encryptPrivateKey=function(e,t){if(this.xPrivKeyEncrypted)throw new Error("Private key already encrypted");if(!this.xPrivKey)throw new Error("No private key to encrypt");if(this.xPrivKeyEncrypted=u.encrypt(e,this.xPrivKey,t),!this.xPrivKeyEncrypted)throw new Error("Could not encrypt");this.mnemonic&&(this.mnemonicEncrypted=u.encrypt(e,this.mnemonic,t)),delete this.xPrivKey,delete this.mnemonic},r.prototype.decryptPrivateKey=function(e){if(!this.xPrivKeyEncrypted)throw new Error("Private key is not encrypted");try{this.xPrivKey=u.decrypt(e,this.xPrivKeyEncrypted),this.mnemonicEncrypted&&(this.mnemonic=u.decrypt(e,this.mnemonicEncrypted)),delete this.xPrivKeyEncrypted,delete this.mnemonicEncrypted}catch(e){throw new Error("Could not decrypt")}},r.prototype.getKeys=function(e){var t={};if(this.isPrivKeyEncrypted()){o.checkArgument(e,"Private keys are encrypted, a password is needed");try{t.xPrivKey=u.decrypt(e,this.xPrivKeyEncrypted),this.mnemonicEncrypted&&(t.mnemonic=u.decrypt(e,this.mnemonicEncrypted))}catch(e){throw new Error("Could not decrypt")}}else t.xPrivKey=this.xPrivKey,t.mnemonic=this.mnemonic;return t},r.prototype.addPublicKeyRing=function(e){this.publicKeyRing=a.clone(e)},r.prototype.canSign=function(){return!!this.xPrivKey||!!this.xPrivKeyEncrypted},r.prototype.setNoSign=function(){delete this.xPrivKey,delete this.xPrivKeyEncrypted,delete this.mnemonic,delete this.mnemonicEncrypted},r.prototype.isComplete=function(){return!(!this.m||!this.n)&&!(!this.publicKeyRing||this.publicKeyRing.length!=this.n)},r.prototype.hasExternalSource=function(){return"string"==typeof this.externalSource},r.prototype.getExternalSourceName=function(){return this.externalSource},r.prototype.getMnemonic=function(){if(this.mnemonicEncrypted&&!this.mnemonic)throw new Error("Credentials are encrypted");return this.mnemonic},r.prototype.clearMnemonic=function(){delete this.mnemonic,delete this.mnemonicEncrypted},r.fromOldCopayWallet=function(e){var t=new r;t.derivationStrategy=h.DERIVATION_STRATEGIES.BIP45,t.xPrivKey=e.privateKey.extendedPrivateKeyString,t._expand(),t.addWalletPrivateKey(function(e){var t=e.publicKeyRing.copayersExtPubKeys.sort().join(""),r=new n(t);return new s.PrivateKey.fromBuffer(s.crypto.Hash.sha256(r)).toString()}(e)),t.addWalletInfo(e.opts.id,e.opts.name,e.opts.requiredCopayers,e.opts.totalCopayers);var i=a.map(e.publicKeyRing.copayersExtPubKeys,function(n){var r,i=n===t.xPubKey;if(i){var o=h.PATHS.REQUEST_KEY;r=new s.HDPrivateKey(t.xPrivKey).deriveChild(o).hdPublicKey}else{var o=h.PATHS.REQUEST_KEY_AUTH;r=new s.HDPublicKey(n).deriveChild(o)}var a=new s.HDPublicKey(n).deriveChild("m/2147483646/0/0"),c=a.publicKey.toString("hex"),u=e.publicKeyRing.nicknameFor[c];return i&&(t.copayerName=u),{xPubKey:n,requestPubKey:r.publicKey.toString(),copayerName:u}});return t.addPublicKeyRing(i),t},t.exports=r}).call(this,e("buffer").Buffer)},{"./common":4,"bitcore-lib-terracoin":"bitcore-lib-terracoin","bitcore-mnemonic-terracoin":102,buffer:120,lodash:439,preconditions:442,sjcl:448}],7:[function(e,t,n){"use strict";function r(e,t){return e.replace("{0}",t[0]).replace("{1}",t[1]).replace("{2}",t[2])}var i=e("lodash"),o=function(e,t){var n=function(){if(i.isString(t.message))this.message=r(t.message,arguments);else{if(!i.isFunction(t.message))throw new Error("Invalid error definition for "+t.name);this.message=t.message.apply(null,arguments)}this.stack=this.message+"\n"+(new Error).stack};return n.prototype=Object.create(e.prototype),n.prototype.name=e.prototype.name+t.name,e[t.name]=n,t.errors&&a(n,t.errors),n},a=function(e,t){i.each(t,function(t){o(e,t)})},s={};s.Error=function(){this.message="Internal error",this.stack=this.message+"\n"+(new Error).stack},s.Error.prototype=Object.create(Error.prototype),s.Error.prototype.name="bwc.Error";var c=e("./spec");!function(e,t){a(e,t)}(s.Error,c),t.exports=s.Error,t.exports.extend=function(e){return o(s.Error,e)}},{"./spec":8,lodash:439}],8:[function(e,t,n){"use strict";var r=[{name:"INVALID_BACKUP",message:"Invalid Backup."},{name:"WALLET_DOES_NOT_EXIST",message:"Wallet does not exist."},{name:"MISSING_PRIVATE_KEY",message:"Missing private keys to sign."},{name:"ENCRYPTED_PRIVATE_KEY",message:"Private key is encrypted, cannot sign transaction."},{name:"SERVER_COMPROMISED",message:"Server response could not be verified."},{name:"COULD_NOT_BUILD_TRANSACTION",message:"Could not build the transaction."},{name:"INSUFFICIENT_FUNDS",message:"Insufficient funds."},{name:"CONNECTION_ERROR",message:"Wallet service connection error."},{name:"NOT_FOUND",message:"Wallet service not found."},{name:"ECONNRESET_ERROR",message:"ECONNRESET, body: {0}"},{name:"WALLET_ALREADY_EXISTS",message:"Wallet already exists."},{name:"COPAYER_IN_WALLET",message:"Copayer in wallet."},{name:"WALLET_FULL",message:"Wallet is full."},{name:"WALLET_NOT_FOUND",message:"Wallet not found."},{name:"INSUFFICIENT_FUNDS_FOR_FEE",message:"Insufficient funds for fee."},{name:"LOCKED_FUNDS",message:"Locked funds."},{name:"DUST_AMOUNT",message:"Amount below dust threshold."},{name:"COPAYER_VOTED",message:"Copayer already voted on this transaction proposal."},{name:"NOT_AUTHORIZED",message:"Not authorized."},{name:"UNAVAILABLE_UTXOS",message:"