From 6fc8bf479d216b55d75be8aa512429613aadf98c Mon Sep 17 00:00:00 2001 From: Matias Alejo Garcia Date: Tue, 10 Mar 2015 19:18:59 -0300 Subject: [PATCH 1/2] update deps and version --- package.json | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/package.json b/package.json index 8ded39da..d2f420d6 100644 --- a/package.json +++ b/package.json @@ -2,7 +2,7 @@ "name": "bitcore-wallet-client", "description": "Client for bitcore-wallet-service", "author": "BitPay Inc", - "version": "0.0.4", + "version": "0.0.5", "keywords": [ "bitcoin", "copay", @@ -22,7 +22,7 @@ "dependencies": { "async": "^0.9.0", "bitcore": "^0.11.2", - "bitcore-wallet-utils": "0.0.2", + "bitcore-wallet-utils": "0.0.3", "browserify": "^9.0.3", "coveralls": "^2.11.2", "lodash": "^3.3.1", @@ -32,7 +32,7 @@ "uglify": "^0.1.1" }, "devDependencies": { - "bitcore-wallet-service": "0.0.4", + "bitcore-wallet-service": "0.0.5", "chai": "^1.9.1", "leveldown": "^0.10.0", "levelup": "^0.19.0", From 7fe087a9c52bd543a70c69cd575954cab0cb91e5 Mon Sep 17 00:00:00 2001 From: Matias Alejo Garcia Date: Tue, 10 Mar 2015 19:21:01 -0300 Subject: [PATCH 2/2] updates bower --- bitcore-wallet-client.js | 94 +++++++++++++++++++++++++----------- bitcore-wallet-client.min.js | 2 +- bower.json | 2 +- 3 files changed, 67 insertions(+), 31 deletions(-) diff --git a/bitcore-wallet-client.js b/bitcore-wallet-client.js index c554e785..cd34a0fc 100644 --- a/bitcore-wallet-client.js +++ b/bitcore-wallet-client.js @@ -139,7 +139,7 @@ API._parseError = function(body) { * @param {String} privKey - Private key to sign the request */ API._signRequest = function(method, url, args, privKey) { - var message = method.toLowerCase() + '|' + url + '|' + JSON.stringify(args); + var message = [method.toLowerCase(), url, JSON.stringify(args)].join('|'); return WalletUtils.signMessage(message, privKey); }; @@ -276,7 +276,8 @@ API.prototype._doRequest = function(method, url, args, cb) { method: method, url: absUrl, body: args, - json: true + json: true, + withCredentials: false }; log.debug('Request Args', util.inspect(args, { @@ -337,16 +338,20 @@ API.prototype._doDeleteRequest = function(url, cb) { * @param {String} walletId * @param {String} walletPrivKey * @param {String} xPubKey + * @param {String} requestPubKey * @param {String} copayerName * @param {Callback} cb */ -API.prototype._doJoinWallet = function(walletId, walletPrivKey, xPubKey, copayerName, cb) { +API.prototype._doJoinWallet = function(walletId, walletPrivKey, xPubKey, requestPubKey, copayerName, cb) { var args = { walletId: walletId, name: copayerName, xPubKey: xPubKey, - xPubKeySignature: WalletUtils.signMessage(xPubKey, walletPrivKey), + requestPubKey: requestPubKey }; + var hash = WalletUtils.getCopayerHash(args.name, args.xPubKey, args.requestPubKey); + args.copayerSignature = WalletUtils.signMessage(hash, walletPrivKey); + var url = '/v1/wallets/' + walletId + '/copayers'; this._doPostRequest(url, args, function(err, body) { if (err) return cb(err); @@ -393,7 +398,9 @@ API.prototype.openWallet = function(cb) { log.warn('Could not perform verification of other copayers in the wallet'); } - self.credentials.addPublicKeyRing(_.pluck(wallet.copayers, 'xPubKey')); + self.credentials.addPublicKeyRing(_.map(wallet.copayers, function(copayer) { + return _.pick(copayer, ['xPubKey', 'requestPubKey']); + })); if (!self.credentials.hasWalletInfo()) { var me = _.find(wallet.copayers, { id: self.credentials.copayerId @@ -450,7 +457,7 @@ API.prototype.createWallet = function(walletName, copayerName, m, n, network, cb var secret = WalletUtils.toSecret(walletId, walletPrivKey, network); self.credentials.addWalletInfo(walletId, walletName, m, n, walletPrivKey.toString(), copayerName); - self._doJoinWallet(walletId, walletPrivKey, self.credentials.xPubKey, copayerName, + self._doJoinWallet(walletId, walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, function(err, wallet) { if (err) return cb(err); return cb(null, n > 1 ? secret : null); @@ -479,7 +486,7 @@ API.prototype.joinWallet = function(secret, copayerName, cb) { self.seedFromRandom(secretData.network); } - self._doJoinWallet(secretData.walletId, secretData.walletPrivKey, self.credentials.xPubKey, copayerName, + self._doJoinWallet(secretData.walletId, secretData.walletPrivKey, self.credentials.xPubKey, self.credentials.requestPubKey, copayerName, function(err, wallet) { if (err) return cb(err); self.credentials.addWalletInfo(wallet.id, wallet.name, wallet.m, wallet.n, secretData.walletPrivKey, copayerName); @@ -512,14 +519,14 @@ API.prototype.recreateWallet = function(cb) { var secret = WalletUtils.toSecret(walletId, walletPrivKey, self.credentials.network); var i = 1; - async.each(self.credentials.publicKeyRing, function(xpub, next) { + async.each(self.credentials.publicKeyRing, function(item, next) { var copayerName; - if (xpub == self.credentials.xPubKey) { + if (item.xPubKey == self.credentials.xPubKey) { copayerName = self.credentials.copayerName; } else { copayerName = 'recovered copayer #' + (i++); } - self._doJoinWallet(walletId, walletPrivKey, xpub, copayerName, next); + self._doJoinWallet(walletId, walletPrivKey, item.xPubKey, item.requestPubKey, copayerName, next); }, cb); }); }; @@ -898,6 +905,7 @@ var FIELDS = [ 'xPrivKey', 'xPubKey', 'requestPrivKey', + 'requestPubKey', 'copayerId', 'publicKeyRing', 'walletId', @@ -953,8 +961,13 @@ Credentials.prototype._expand = function() { if (this.xPrivKey) { var xPrivKey = new Bitcore.HDPrivateKey.fromString(this.xPrivKey); - this.xPubKey = (new Bitcore.HDPublicKey(xPrivKey)).toString(); - this.requestPrivKey = xPrivKey.derive('m/1/1').privateKey.toString(); + + var addressDerivation = xPrivKey.derive(WalletUtils.PATHS.BASE_ADDRESS_DERIVATION); + this.xPubKey = (new Bitcore.HDPublicKey(addressDerivation)).toString(); + + var requestDerivation = xPrivKey.derive(WalletUtils.PATHS.REQUEST_KEY); + this.requestPrivKey = requestDerivation.privateKey.toString(); + this.requestPubKey = requestDerivation.publicKey.toString(); } var network = WalletUtils.getNetworkFromXPubKey(this.xPubKey); if (this.network) { @@ -998,7 +1011,10 @@ Credentials.prototype.addWalletInfo = function(walletId, walletName, m, n, walle this.sharedEncryptingKey = WalletUtils.privateKeyToAESKey(walletPrivKey); this.copayerName = copayerName; if (n == 1) { - this.addPublicKeyRing([this.xPubKey]); + this.addPublicKeyRing([{ + xPubKey: this.xPubKey, + requestPubKey: this.requestPubKey, + }]); } }; @@ -1022,14 +1038,15 @@ Credentials.prototype.isComplete = function() { Credentials.prototype.exportCompressed = function() { var self = this; - var values = _.map(EXPORTABLE_FIELDS, function(field) { if ((field == 'xPubKey' || field == 'requestPrivKey') && self.canSign()) return ''; if (field == 'requestPrivKey') { return Bitcore.PrivateKey.fromString(self.requestPrivKey).toWIF(); } if (field == 'publicKeyRing') { - return _.without(self.publicKeyRing, self.xPubKey); + return _.reject(self.publicKeyRing, { + xPubKey: self.xPubKey + }); } return self[field]; }); @@ -1058,7 +1075,10 @@ Credentials.importCompressed = function(compressed) { x._expand(); x.network = WalletUtils.getNetworkFromXPubKey(x.xPubKey); - x.publicKeyRing.push(x.xPubKey); + x.publicKeyRing.push({ + xPubKey: x.xPubKey, + requestPubKey: x.requestPubKey, + }); return x; }; @@ -1278,14 +1298,19 @@ Verifier.checkCopayers = function(credentials, copayers) { } // Not signed pub keys - if (!copayer.xPubKey || !copayer.xPubKeySignature || - !WalletUtils.verifyMessage(copayer.xPubKey, copayer.xPubKeySignature, walletPubKey)) { - log.error('Invalid signatures in server response'); + if (!copayer.name || !copayer.xPubKey || !copayer.requestPubKey || !copayer.signature) { + log.error('Missing copayer fields in server response'); error = true; + } else { + var hash = WalletUtils.getCopayerHash(copayer.name, copayer.xPubKey, copayer.requestPubKey); + if (!WalletUtils.verifyMessage(hash, copayer.signature, walletPubKey)) { + log.error('Invalid signatures in server response'); + error = true; + } } }); - if (error) - return false; + + if (error) return false; if (!_.contains(_.pluck(copayers, 'xPubKey'), credentials.xPubKey)) { log.error('Server response does not contains our public keys') @@ -1305,13 +1330,14 @@ Verifier.checkTxProposal = function(credentials, txp) { $.checkArgument(txp.creatorId); $.checkState(credentials.isComplete()); - var creatorXPubKey = _.find(credentials.publicKeyRing, function(xPubKey) { - if (WalletUtils.xPubToCopayerId(xPubKey) === txp.creatorId) return true; + var creatorKeys = _.find(credentials.publicKeyRing, function(item) { + if (WalletUtils.xPubToCopayerId(item.xPubKey) === txp.creatorId) return true; }); - if (!creatorXPubKey) return false; + if (!creatorKeys) return false; - var creatorSigningPubKey = (new Bitcore.HDPublicKey(creatorXPubKey)).derive('m/1/1').publicKey.toString(); + // TODO: this should be an independent key + var creatorSigningPubKey = creatorKeys.requestPubKey; var hash = WalletUtils.getProposalHash(txp.toAddress, txp.amount, txp.encryptedMessage || txp.message); log.debug('Regenerating & verifying tx proposal hash -> Hash: ', hash, ' Signature: ', txp.proposalSignature); @@ -2472,6 +2498,12 @@ var encoding = Bitcore.encoding; function WalletUtils() {}; +WalletUtils.PATHS = { + BASE_ADDRESS_DERIVATION: "m/45'", + REQUEST_KEY: "m/1'/0", + TXPROPOSAL_KEY: "m/1'/1", +}; + /* TODO: It would be nice to be compatible with bitcoind signmessage. How * the hash is calculated there? */ WalletUtils.hashMessage = function(text) { @@ -2510,8 +2542,8 @@ WalletUtils.verifyMessage = function(text, signature, pubKey) { }; WalletUtils.deriveAddress = function(publicKeyRing, path, m, network) { - var publicKeys = _.map(publicKeyRing, function(xPubKey) { - var xpub = new Bitcore.HDPublicKey(xPubKey); + var publicKeys = _.map(publicKeyRing, function(item) { + var xpub = new Bitcore.HDPublicKey(item.xPubKey); return xpub.derive(path).publicKey; }); @@ -2525,7 +2557,11 @@ WalletUtils.deriveAddress = function(publicKeyRing, path, m, network) { }; WalletUtils.getProposalHash = function(toAddress, amount, message) { - return toAddress + '|' + amount + '|' + (message || ''); + return [toAddress, amount, (message || '')].join('|'); +}; + +WalletUtils.getCopayerHash = function(name, xPubKey, requestPubKey) { + return [name, xPubKey, requestPubKey].join('|'); }; WalletUtils.xPubToCopayerId = function(xpub) { @@ -2603,7 +2639,7 @@ WalletUtils.signTxp = function(txp, xPrivKey) { derived = {}; var network = new Bitcore.Address(txp.toAddress).network.name; - var xpriv = new Bitcore.HDPrivateKey(xPrivKey, network); + var xpriv = new Bitcore.HDPrivateKey(xPrivKey, network).derive(WalletUtils.PATHS.BASE_ADDRESS_DERIVATION); _.each(txp.inputs, function(i) { if (!derived[i.path]) { diff --git a/bitcore-wallet-client.min.js b/bitcore-wallet-client.min.js index 590510be..0cbca516 100644 --- a/bitcore-wallet-client.min.js +++ b/bitcore-wallet-client.min.js @@ -1,4 +1,4 @@ -!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"}},c._processTxps=function(a,b){a&&d.each([].concat(a),function(a){a.encryptedMessage=a.message,a.message=c._decryptMessage(a.message,b),d.each(a.actions,function(a){a.comment=c._decryptMessage(a.comment,b)})})},c._parseError=function(a){if(d.isString(a))try{a=JSON.parse(a)}catch(b){a={error:a}}var c;return c=a&&a.code?new q(a.code,a.message):{code:"ERROR",error:a?a.error:"There was an unknown error processing the request"},m.error(c),c},c._signRequest=function(a,b,c,d){var e=a.toLowerCase()+"|"+b+"|"+JSON.stringify(c);return k.signMessage(e,d)},c.prototype.seedFromRandom=function(a){this.credentials=n.create(a)},c.prototype.seedFromExtendedPrivateKey=function(a){this.credentials=n.fromExtendedPrivateKey(a)},c.prototype["export"]=function(a){e.checkState(this.credentials),a=a||{};var b,c=n.fromObj(this.credentials);return a.noSign&&delete c.xPrivKey,b=a.compressed?c.exportCompressed():JSON.stringify(c.toObj()),a.password&&(b=l.encrypt(a.password,b,s)),b},c.prototype["import"]=function(a,b){b=b||{};var c=a;if(b.password)try{c=l.decrypt(b.password,c)}catch(d){throw d}var e;try{e=b.compressed?n.importCompressed(c):n.fromObj(JSON.parse(c))}catch(d){throw new Error("Error importing from source")}this.credentials=e},c.prototype.toString=function(){return e.checkState(this.credentials),this.credentials.toObject()},c.prototype.fromString=function(a){this.credentials=n.fromObject(a)},c.prototype._doRequest=function(a,b,d,g){e.checkState(this.credentials);var h;this.credentials.requestPrivKey&&(h=c._signRequest(a,b,d,this.credentials.requestPrivKey));var i=this.baseUrl+b,d={relUrl:this.basePath+b,headers:{"x-identity":this.credentials.copayerId,"x-signature":h},method:a,url:i,body:d,json:!0};m.debug("Request Args",f.inspect(d,{depth:10})),this.request(d,function(a,b,d){return m.debug(f.inspect(d,{depth:10})),a?g(a):200!=b.statusCode?g(c._parseError(d)):g(null,d,b.header)})},c.prototype._doPostRequest=function(a,b,c){return this._doRequest("post",a,b,c)},c.prototype._doGetRequest=function(a,b){return this._doRequest("get",a,{},b)},c.prototype._doDeleteRequest=function(a,b){return this._doRequest("delete",a,{},b)},c.prototype._doJoinWallet=function(a,b,c,d,e){var f={walletId:a,name:d,xPubKey:c,xPubKeySignature:k.signMessage(c,b)},g="/v1/wallets/"+a+"/copayers";this._doPostRequest(g,f,function(a,b){return a?e(a):e(null,b.wallet)})},c.prototype.isComplete=function(){return this.credentials&&this.credentials.isComplete()},c.prototype.canSign=function(){return this.credentials&&this.credentials.canSign()},c.prototype.openWallet=function(a){e.checkState(this.credentials);var b=this;return b.credentials.isComplete()?a(null,!1):void b._doGetRequest("/v1/wallets/",function(c,e){if(c)return a(c);var f=e.wallet;if("complete"!=f.status)return a("Wallet Incomplete");if(b.credentials.walletPrivKey){if(!o.checkCopayers(b.credentials,f.copayers))return a(new p("Copayers in the wallet could not be verified to have known the wallet secret"))}else m.warn("Could not perform verification of other copayers in the wallet");if(b.credentials.addPublicKeyRing(d.pluck(f.copayers,"xPubKey")),!b.credentials.hasWalletInfo()){var g=d.find(f.copayers,{id:b.credentials.copayerId});b.credentials.addWalletInfo(f.id,f.name,f.m,f.n,null,g.name)}return a(null,!0)})},c.prototype.createWallet=function(a,b,c,e,f,g){var h=this;if(f=f||"livenet",!d.contains(["testnet","livenet"],f))return g("Invalid network");if(h.credentials?m.info("Using existing keys"):(m.info("Generating new keys"),h.seedFromRandom(f)),f!=h.credentials.network)return g(new Error("Existing keys were created for a different network"));var i=new j.PrivateKey,l={name:a,m:c,n:e,pubKey:i.toPublicKey().toString(),network:f};h._doPostRequest("/v1/wallets/",l,function(d,j){if(d)return g(d);var l=j.walletId,m=k.toSecret(l,i,f);h.credentials.addWalletInfo(l,a,c,e,i.toString(),b),h._doJoinWallet(l,i,h.credentials.xPubKey,b,function(a){return a?g(a):g(null,e>1?m:null)})})},c.prototype.joinWallet=function(a,b,c){var d=this;try{var e=k.fromSecret(a)}catch(f){return c(f)}d.credentials||d.seedFromRandom(e.network),d._doJoinWallet(e.walletId,e.walletPrivKey,d.credentials.xPubKey,b,function(a,f){return a?c(a):(d.credentials.addWalletInfo(f.id,f.name,f.m,f.n,e.walletPrivKey,b),c(null,f))})},c.prototype.recreateWallet=function(a){e.checkState(this.credentials&&this.credentials.isComplete()&&this.credentials.hasWalletInfo());var b=this,c=j.PrivateKey.fromString(b.credentials.walletPrivKey),d={name:b.credentials.walletName||"recovered wallet",m:b.credentials.m,n:b.credentials.n,pubKey:c.toPublicKey().toString(),network:b.credentials.network};b._doPostRequest("/v1/wallets/",d,function(d,e){if(d)return a(d);var f=e.walletId,h=(k.toSecret(f,c,b.credentials.network),1);g.each(b.credentials.publicKeyRing,function(a,d){var e;e=a==b.credentials.xPubKey?b.credentials.copayerName:"recovered copayer #"+h++,b._doJoinWallet(f,c,a,e,d)},a)})},c.prototype.getStatus=function(a){e.checkState(this.credentials);var b=this;b._doGetRequest("/v1/wallets/",function(d,e){if(d)return a(d);if("pending"==e.wallet.status){var f=b.credentials;e.wallet.secret=k.toSecret(f.walletId,f.walletPrivKey,f.network)}return c._processTxps(e.pendingTxps,b.credentials.sharedEncryptingKey),a(d,e)})},c.prototype.sendTxProposal=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete()),e.checkArgument(a),e.shouldBeNumber(a.amount);var d=this,f={toAddress:a.toAddress,amount:a.amount,message:c._encryptMessage(a.message,d.credentials.sharedEncryptingKey)},g=k.getProposalHash(f.toAddress,f.amount,f.message);f.proposalSignature=k.signMessage(g,d.credentials.requestPrivKey),m.debug("Generating & signing tx proposal hash -> Hash: ",g," Signature: ",f.proposalSignature),d._doPostRequest("/v1/txproposals/",f,function(a,c){return a?b(a):b(null,c)})},c.prototype.createAddress=function(a){e.checkState(this.credentials&&this.credentials.isComplete());var b=this;b._doPostRequest("/v1/addresses/",{},function(c,d){return c?a(c):o.checkAddress(b.credentials,d)?a(null,d):a(new p("Server sent fake address"))})},c.prototype.getMainAddresses=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var c=this;c._doGetRequest("/v1/addresses/",function(e,f){if(e)return b(e);if(!a.doNotVerify){var g=d.any(f,function(a){return!o.checkAddress(c.credentials,a)});if(g)return b(new p("Server sent fake address"))}return b(null,f)})},c.prototype.getBalance=function(a){e.checkState(this.credentials&&this.credentials.isComplete());var b=this;b._doGetRequest("/v1/balance/",a)},c.prototype.getTxProposals=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var f=this;f._doGetRequest("/v1/txproposals/",function(e,g){if(e)return b(e);c._processTxps(g,f.credentials.sharedEncryptingKey);var h=d.any(g,function(b){return!a.doNotVerify&&!o.checkTxProposal(f.credentials,b)});if(h)return b(new p("Server sent fake transaction proposal"));var i;return i=a.forAirGapped?{txps:JSON.parse(JSON.stringify(g)),encryptedPkr:k.encryptMessage(JSON.stringify(f.credentials.publicKeyRing),f.credentials.personalEncryptingKey),m:f.credentials.m,n:f.credentials.n}:g,b(null,i)})},c.prototype.getSignatures=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete()),e.checkArgument(a.creatorId);var c=this;return c.canSign()?o.checkTxProposal(c.credentials,a)?b(null,k.signTxp(a,c.credentials.xPrivKey)):b(new p("Transaction proposal is invalid")):b("You do not have the required keys to sign transactions")},c.prototype.signTxProposal=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete()),e.checkArgument(a.creatorId);var c=this;if(!c.canSign()&&!a.signatures)return b(new Error("You do not have the required keys to sign transactions"));if(!o.checkTxProposal(c.credentials,a))return b(new p("Server sent fake transaction proposal"));var d=a.signatures||k.signTxp(a,c.credentials.xPrivKey),f="/v1/txproposals/"+a.id+"/signatures/",g={signatures:d};c._doPostRequest(f,g,function(a,c){return a?b(a):b(null,c)})},c.prototype.signTxProposalFromAirGapped=function(a,b,c,f){e.checkState(this.credentials);var g=this;if(!g.canSign())throw new Error("You do not have the required keys to sign transactions");var h;try{h=JSON.parse(k.decryptMessage(b,g.credentials.personalEncryptingKey))}catch(i){throw new Error("Could not decrypt public key ring")}if(!d.isArray(h)||h.length!=f)throw new Error("Invalid public key ring");if(g.credentials.m=c,g.credentials.n=f,g.credentials.addPublicKeyRing(h),!o.checkTxProposal(g.credentials,a))throw new Error("Fake transaction proposal");return k.signTxp(a,g.credentials.xPrivKey)},c.prototype.rejectTxProposal=function(a,b,d){e.checkState(this.credentials&&this.credentials.isComplete()),e.checkArgument(d);var f=this,g="/v1/txproposals/"+a.id+"/rejections/",h={reason:c._encryptMessage(b,f.credentials.sharedEncryptingKey)||""};f._doPostRequest(g,h,function(a,b){return a?d(a):d(null,b)})},c.prototype.broadcastTxProposal=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var c=this,d="/v1/txproposals/"+a.id+"/broadcast/";c._doPostRequest(d,{},function(a,c){return a?b(a):b(null,c)})},c.prototype.removeTxProposal=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var c=this,d="/v1/txproposals/"+a.id;c._doDeleteRequest(d,function(a){return a?b(a):b()})},c.prototype.getTxHistory=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var d=this;d._doGetRequest("/v1/txhistory/",function(a,e){return a?b(a):(c._processTxps(e,d.credentials.sharedEncryptingKey),b(null,e))})},b.exports=c},{"./clienterror":3,"./credentials":4,"./log":6,"./servercompromisederror":7,"./verifier":8,async:9,bitcore:12,"bitcore-wallet-utils":10,events:242,lodash:274,preconditions:275,request:280,sjcl:337,util:271}],3:[function(a,b){function c(){var a=Array.prototype.slice.call(arguments);switch(a.length){case 0:this.code="BADREQUEST",this.message="Bad request";break;case 1:this.code="BADREQUEST",this.message=a[0];break;default:case 2:this.code=a[0],this.message=a[1]}}c.prototype.toString=function(){return""},b.exports=c},{}],4:[function(a,b){"use strict";function c(){this.version="1.0.0"}var d=a("preconditions").singleton(),e=a("lodash"),f=a("bitcore"),g=a("bitcore-wallet-utils"),h=["network","xPrivKey","xPubKey","requestPrivKey","copayerId","publicKeyRing","walletId","walletName","m","n","walletPrivKey","personalEncryptingKey","sharedEncryptingKey","copayerName"],i=["xPrivKey","requestPrivKey","xPubKey","m","n","publicKeyRing","sharedEncryptingKey"];c.create=function(a){var b=new c;return b.network=a,b.xPrivKey=new f.HDPrivateKey(a).toString(),b._expand(),b},c.fromExtendedPrivateKey=function(a){var b=new c;return b.xPrivKey=a,b._expand(),b},c.fromExtendedPublicKey=function(a,b){var d=new c;return d.xPubKey=a,d.requestPrivKey=b,d._expand(),d},c.prototype._expand=function(){if(d.checkState(this.xPrivKey||this.xPubKey),this.xPrivKey){var a=new f.HDPrivateKey.fromString(this.xPrivKey);this.xPubKey=new f.HDPublicKey(a).toString(),this.requestPrivKey=a.derive("m/1/1").privateKey.toString()}var b=g.getNetworkFromXPubKey(this.xPubKey);this.network?d.checkState(this.network==b):this.network=b,this.personalEncryptingKey=g.privateKeyToAESKey(this.requestPrivKey),this.copayerId=g.xPubToCopayerId(this.xPubKey)},c.fromObj=function(a){var b=new c;return e.each(h,function(c){b[c]=a[c]}),d.checkState(b.xPrivKey||b.xPubKey,"invalid input"),b},c.prototype.toObj=function(){var a=this,b={};return e.each(h,function(c){b[c]=a[c]}),b},c.prototype.addWalletInfo=function(a,b,c,d,e,f){this.walletId=a,this.walletName=b,this.m=c,this.n=d,this.walletPrivKey=e,this.sharedEncryptingKey=g.privateKeyToAESKey(e),this.copayerName=f,1==d&&this.addPublicKeyRing([this.xPubKey])},c.prototype.hasWalletInfo=function(){return!!this.walletId},c.prototype.addPublicKeyRing=function(a){this.publicKeyRing=e.clone(a)},c.prototype.canSign=function(){return!!this.xPrivKey},c.prototype.isComplete=function(){return this.m&&this.n&&this.publicKeyRing&&this.publicKeyRing.length==this.n?!0:!1},c.prototype.exportCompressed=function(){var a=this,b=e.map(i,function(b){return"xPubKey"!=b&&"requestPrivKey"!=b||!a.canSign()?"requestPrivKey"==b?f.PrivateKey.fromString(a.requestPrivKey).toWIF():"publicKeyRing"==b?e.without(a.publicKeyRing,a.xPubKey):a[b]:""});return b.unshift(a.version),JSON.stringify(b)},c.importCompressed=function(a){var b;try{b=JSON.parse(a)}catch(d){throw new Error("Invalid compressed format")}{var f=new c;b[0]}return b=e.rest(b),e.each(i,function(a,c){f[a]=b[c]}),f._expand(),f.network=g.getNetworkFromXPubKey(f.xPubKey),f.publicKeyRing.push(f.xPubKey),f},b.exports=c},{bitcore:12,"bitcore-wallet-utils":10,lodash:274,preconditions:275}],5:[function(a,b){var c=b.exports=a("./api");c.Verifier=a("./verifier"),c.Bitcore=a("bitcore")},{"./api":2,"./verifier":8,bitcore:12}],6:[function(a,b){var c=a("lodash"),d=function(a){this.name=a||"log",this.level=2};d.prototype.getLevels=function(){return e};var e={debug:0,info:1,log:2,warn:3,error:4,fatal:5};c.each(e,function(a,b){d.prototype[b]=function(){if(a>=e[this.level]){if(Error.stackTraceLimit&&"debug"==this.level){var c=Error.stackTraceLimit;Error.stackTraceLimit=2;var d;try{anerror()}catch(f){d=f.stack}var g=d.split("\n"),h=g[2];h=":"+h.substr(6),Error.stackTraceLimit=c}var i,j="["+b+(h||"")+"] "+arguments[0],i=[].slice.call(arguments,1);console[b]?(i.unshift(j),console[b].apply(console,i)):(i.length&&(j+=JSON.stringify(i)),console.log(j))}}}),d.prototype.setLevel=function(a){this.level=a};{var f=new d("copay");new Error}f.setLevel("info"),b.exports=f},{lodash:274}],7:[function(a,b){function c(a){this.code="SERVERCOMPROMISED",this.message=a}b.exports=c},{}],8:[function(a,b){function c(){}var d=a("preconditions").singleton(),e=a("lodash"),f=a("bitcore"),g=a("bitcore-wallet-utils"),h=a("./log");c.checkAddress=function(a,b){d.checkState(a.isComplete());var c=g.deriveAddress(a.publicKeyRing,b.path,a.m,a.network);return c.address==b.address&&JSON.stringify(c.publicKeys)==JSON.stringify(b.publicKeys)},c.checkCopayers=function(a,b){d.checkState(a.walletPrivKey);var c=f.PrivateKey.fromString(a.walletPrivKey).toPublicKey().toString();if(b.length!=a.n)return h.error("Missing public keys in server response"),!1;var i,j=[];return e.each(b,function(a){j[b.xPubKey]++&&(h.error("Repeated public keys in server response"),i=!0),a.xPubKey&&a.xPubKeySignature&&g.verifyMessage(a.xPubKey,a.xPubKeySignature,c)||(h.error("Invalid signatures in server response"),i=!0)}),i?!1:e.contains(e.pluck(b,"xPubKey"),a.xPubKey)?!0:(h.error("Server response does not contains our public keys"),!1)},c.checkTxProposal=function(a,b){d.checkArgument(b.creatorId),d.checkState(a.isComplete());var i=e.find(a.publicKeyRing,function(a){return g.xPubToCopayerId(a)===b.creatorId?!0:void 0});if(!i)return!1;var j=new f.HDPublicKey(i).derive("m/1/1").publicKey.toString(),k=g.getProposalHash(b.toAddress,b.amount,b.encryptedMessage||b.message);return h.debug("Regenerating & verifying tx proposal hash -> Hash: ",k," Signature: ",b.proposalSignature),g.verifyMessage(k,b.proposalSignature,j)?c.checkAddress(a,b.changeAddress):!1},b.exports=c},{"./log":6,bitcore:12,"bitcore-wallet-utils":10,lodash:274,preconditions:275}],9:[function(a,b){(function(a){!function(){function c(a){var b=!1;return function(){if(b)throw new Error("Callback was already called.");b=!0,a.apply(d,arguments)}}var d,e,f={};d=this,null!=d&&(e=d.async),f.noConflict=function(){return d.async=e,f};var g=Object.prototype.toString,h=Array.isArray||function(a){return"[object Array]"===g.call(a)},i=function(a,b){if(a.forEach)return a.forEach(b);for(var c=0;c=a.length&&d())}if(d=d||function(){},!a.length)return d();var f=0;i(a,function(a){b(a,c(e))})},f.forEach=f.each,f.eachSeries=function(a,b,c){if(c=c||function(){},!a.length)return c();var d=0,e=function(){b(a[d],function(b){b?(c(b),c=function(){}):(d+=1,d>=a.length?c():e())})};e()},f.forEachSeries=f.eachSeries,f.eachLimit=function(a,b,c,d){var e=m(b);e.apply(null,[a,c,d])},f.forEachLimit=f.eachLimit;var m=function(a){return function(b,c,d){if(d=d||function(){},!b.length||0>=a)return d();var e=0,f=0,g=0;!function h(){if(e>=b.length)return d();for(;a>g&&f=b.length?d():h())})}()}},n=function(a){return function(){var b=Array.prototype.slice.call(arguments);return a.apply(null,[f.each].concat(b))}},o=function(a,b){return function(){var c=Array.prototype.slice.call(arguments);return b.apply(null,[m(a)].concat(c))}},p=function(a){return function(){var b=Array.prototype.slice.call(arguments);return a.apply(null,[f.eachSeries].concat(b))}},q=function(a,b,c,d){if(b=j(b,function(a,b){return{index:b,value:a}}),d){var e=[];a(b,function(a,b){c(a.value,function(c,d){e[a.index]=d,b(c)})},function(a){d(a,e)})}else a(b,function(a,b){c(a.value,function(a){b(a)})})};f.map=n(q),f.mapSeries=p(q),f.mapLimit=function(a,b,c,d){return r(b)(a,c,d)};var r=function(a){return o(a,q)};f.reduce=function(a,b,c,d){f.eachSeries(a,function(a,d){c(b,a,function(a,c){b=c,d(a)})},function(a){d(a,b)})},f.inject=f.reduce,f.foldl=f.reduce,f.reduceRight=function(a,b,c,d){var e=j(a,function(a){return a}).reverse();f.reduce(e,b,c,d)},f.foldr=f.reduceRight;var s=function(a,b,c,d){var e=[];b=j(b,function(a,b){return{index:b,value:a}}),a(b,function(a,b){c(a.value,function(c){c&&e.push(a),b()})},function(){d(j(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})};f.filter=n(s),f.filterSeries=p(s),f.select=f.filter,f.selectSeries=f.filterSeries;var t=function(a,b,c,d){var e=[];b=j(b,function(a,b){return{index:b,value:a}}),a(b,function(a,b){c(a.value,function(c){c||e.push(a),b()})},function(){d(j(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})};f.reject=n(t),f.rejectSeries=p(t);var u=function(a,b,c,d){a(b,function(a,b){c(a,function(c){c?(d(a),d=function(){}):b()})},function(){d()})};f.detect=n(u),f.detectSeries=p(u),f.some=function(a,b,c){f.each(a,function(a,d){b(a,function(a){a&&(c(!0),c=function(){}),d()})},function(){c(!1)})},f.any=f.some,f.every=function(a,b,c){f.each(a,function(a,d){b(a,function(a){a||(c(!1),c=function(){}),d()})},function(){c(!0)})},f.all=f.every,f.sortBy=function(a,b,c){f.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){if(a)return c(a);var d=function(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0};c(null,j(b.sort(d),function(a){return a.value}))})},f.auto=function(a,b){b=b||function(){};var c=l(a),d=c.length;if(!d)return b();var e={},g=[],j=function(a){g.unshift(a)},m=function(a){for(var b=0;bd;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function e(a,b,e,g){return a.started||(a.started=!0),h(b)||(b=[b]),0==b.length?f.setImmediate(function(){a.drain&&a.drain()}):void i(b,function(b){var h={data:b,priority:e,callback:"function"==typeof g?g:null};a.tasks.splice(d(a.tasks,h,c)+1,0,h),a.saturated&&a.tasks.length===a.concurrency&&a.saturated(),f.setImmediate(a.process)})}var g=f.queue(a,b);return g.push=function(a,b,c){e(g,a,b,c)},delete g.unshift,g},f.cargo=function(a,b){var c=!1,d=[],e={tasks:d,payload:b,saturated:null,empty:null,drain:null,drained:!0,push:function(a,c){h(a)||(a=[a]),i(a,function(a){d.push({data:a,callback:"function"==typeof c?c:null}),e.drained=!1,e.saturated&&d.length===b&&e.saturated()}),f.setImmediate(e.process)},process:function g(){if(!c){if(0===d.length)return e.drain&&!e.drained&&e.drain(),void(e.drained=!0);var f="number"==typeof b?d.splice(0,b):d.splice(0,d.length),h=j(f,function(a){return a.data});e.empty&&e.empty(),c=!0,a(h,function(){c=!1;var a=arguments;i(f,function(b){b.callback&&b.callback.apply(null,a)}),g()})}},length:function(){return d.length},running:function(){return c}};return e};var x=function(a){return function(b){var c=Array.prototype.slice.call(arguments,1);b.apply(null,c.concat([function(b){var c=Array.prototype.slice.call(arguments,1);"undefined"!=typeof console&&(b?console.error&&console.error(b):console[a]&&i(c,function(b){console[a](b)}))}]))}};f.log=x("log"),f.dir=x("dir"),f.memoize=function(a,b){var c={},d={};b=b||function(a){return a};var e=function(){var e=Array.prototype.slice.call(arguments),g=e.pop(),h=b.apply(null,e);h in c?f.nextTick(function(){g.apply(null,c[h])}):h in d?d[h].push(g):(d[h]=[g],a.apply(null,e.concat([function(){c[h]=arguments;var a=d[h];delete d[h];for(var b=0,e=a.length;e>b;b++)a[b].apply(null,arguments)}])))};return e.memo=c,e.unmemoized=a,e},f.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},f.times=function(a,b,c){for(var d=[],e=0;a>e;e++)d.push(e);return f.map(d,b,c)},f.timesSeries=function(a,b,c){for(var d=[],e=0;a>e;e++)d.push(e);return f.mapSeries(d,b,c)},f.seq=function(){var a=arguments;return function(){var b=this,c=Array.prototype.slice.call(arguments),d=c.pop();f.reduce(a,c,function(a,c,d){c.apply(b,a.concat([function(){var a=arguments[0],b=Array.prototype.slice.call(arguments,1);d(a,b)}]))},function(a,c){d.apply(b,[a].concat(c))})}},f.compose=function(){return f.seq.apply(null,Array.prototype.reverse.call(arguments))};var y=function(a,b){var c=function(){var c=this,d=Array.prototype.slice.call(arguments),e=d.pop();return a(b,function(a,b){a.apply(c,d.concat([b]))},e)};if(arguments.length>2){var d=Array.prototype.slice.call(arguments,2);return c.apply(this,d)}return c};f.applyEach=n(y),f.applyEachSeries=p(y),f.forever=function(a,b){function c(d){if(d){if(b)return b(d);throw d}a(c)}c()},"undefined"!=typeof b&&b.exports?b.exports=f:"undefined"!=typeof define&&define.amd?define([],function(){return f}):d.async=f}()}).call(this,a("_process"))},{_process:251}],10:[function(a,b){b.exports=a("./lib/walletutils")},{"./lib/walletutils":11}],11:[function(a,b){(function(c){"use strict";function d(){}var e=a("lodash"),f=a("preconditions").singleton(),g=a("sjcl"),h=a("bitcore"),i=h.Address,j=h.PrivateKey,k=h.PublicKey,l=h.crypto,m=h.encoding;d.hashMessage=function(a){f.checkArgument(a);var b=new c(a),d=l.Hash.sha256sha256(b);return d=new h.encoding.BufferReader(d).readReverse()},d.signMessage=function(a,b){f.checkArgument(a);var c=new j(b),e=d.hashMessage(a);return l.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 k(c),g=d.hashMessage(a);try{var h=new l.Signature.fromString(b);return l.ECDSA.verify(g,h,e,"little")}catch(i){return!1}},d.deriveAddress=function(a,b,c,d){var f=e.map(a,function(a){var c=new h.HDPublicKey(a);return c.derive(b).publicKey}),g=i.createMultisig(f,c,d);return{address:g.toString(),path:b,publicKeys:e.invoke(f,"toString")}},d.getProposalHash=function(a,b,c){return a+"|"+b+"|"+(c||"")},d.xPubToCopayerId=function(a){var b=g.hash.sha256.hash(a);return g.codec.hex.fromBits(b)},d.toSecret=function(a,b,d){e.isString(b)&&(b=h.PrivateKey.fromString(b));var f=new c(a.replace(/-/g,""),"hex"),g=new m.Base58(f).toString();return e.padRight(g,22,"0")+b.toWIF()+("testnet"==d?"T":"L")},d.fromSecret=function(a){function b(a,b){var c=[];b.push(a.length);for(var d=0;d"}},c._processTxps=function(a,b){a&&d.each([].concat(a),function(a){a.encryptedMessage=a.message,a.message=c._decryptMessage(a.message,b),d.each(a.actions,function(a){a.comment=c._decryptMessage(a.comment,b)})})},c._parseError=function(a){if(d.isString(a))try{a=JSON.parse(a)}catch(b){a={error:a}}var c;return c=a&&a.code?new q(a.code,a.message):{code:"ERROR",error:a?a.error:"There was an unknown error processing the request"},m.error(c),c},c._signRequest=function(a,b,c,d){var e=[a.toLowerCase(),b,JSON.stringify(c)].join("|");return k.signMessage(e,d)},c.prototype.seedFromRandom=function(a){this.credentials=n.create(a)},c.prototype.seedFromExtendedPrivateKey=function(a){this.credentials=n.fromExtendedPrivateKey(a)},c.prototype["export"]=function(a){e.checkState(this.credentials),a=a||{};var b,c=n.fromObj(this.credentials);return a.noSign&&delete c.xPrivKey,b=a.compressed?c.exportCompressed():JSON.stringify(c.toObj()),a.password&&(b=l.encrypt(a.password,b,s)),b},c.prototype["import"]=function(a,b){b=b||{};var c=a;if(b.password)try{c=l.decrypt(b.password,c)}catch(d){throw d}var e;try{e=b.compressed?n.importCompressed(c):n.fromObj(JSON.parse(c))}catch(d){throw new Error("Error importing from source")}this.credentials=e},c.prototype.toString=function(){return e.checkState(this.credentials),this.credentials.toObject()},c.prototype.fromString=function(a){this.credentials=n.fromObject(a)},c.prototype._doRequest=function(a,b,d,g){e.checkState(this.credentials);var h;this.credentials.requestPrivKey&&(h=c._signRequest(a,b,d,this.credentials.requestPrivKey));var i=this.baseUrl+b,d={relUrl:this.basePath+b,headers:{"x-identity":this.credentials.copayerId,"x-signature":h},method:a,url:i,body:d,json:!0,withCredentials:!1};m.debug("Request Args",f.inspect(d,{depth:10})),this.request(d,function(a,b,d){return m.debug(f.inspect(d,{depth:10})),a?g(a):200!=b.statusCode?g(c._parseError(d)):g(null,d,b.header)})},c.prototype._doPostRequest=function(a,b,c){return this._doRequest("post",a,b,c)},c.prototype._doGetRequest=function(a,b){return this._doRequest("get",a,{},b)},c.prototype._doDeleteRequest=function(a,b){return this._doRequest("delete",a,{},b)},c.prototype._doJoinWallet=function(a,b,c,d,e,f){var g={walletId:a,name:e,xPubKey:c,requestPubKey:d},h=k.getCopayerHash(g.name,g.xPubKey,g.requestPubKey);g.copayerSignature=k.signMessage(h,b);var i="/v1/wallets/"+a+"/copayers";this._doPostRequest(i,g,function(a,b){return a?f(a):f(null,b.wallet)})},c.prototype.isComplete=function(){return this.credentials&&this.credentials.isComplete()},c.prototype.canSign=function(){return this.credentials&&this.credentials.canSign()},c.prototype.openWallet=function(a){e.checkState(this.credentials);var b=this;return b.credentials.isComplete()?a(null,!1):void b._doGetRequest("/v1/wallets/",function(c,e){if(c)return a(c);var f=e.wallet;if("complete"!=f.status)return a("Wallet Incomplete");if(b.credentials.walletPrivKey){if(!o.checkCopayers(b.credentials,f.copayers))return a(new p("Copayers in the wallet could not be verified to have known the wallet secret"))}else m.warn("Could not perform verification of other copayers in the wallet");if(b.credentials.addPublicKeyRing(d.map(f.copayers,function(a){return d.pick(a,["xPubKey","requestPubKey"])})),!b.credentials.hasWalletInfo()){var g=d.find(f.copayers,{id:b.credentials.copayerId});b.credentials.addWalletInfo(f.id,f.name,f.m,f.n,null,g.name)}return a(null,!0)})},c.prototype.createWallet=function(a,b,c,e,f,g){var h=this;if(f=f||"livenet",!d.contains(["testnet","livenet"],f))return g("Invalid network");if(h.credentials?m.info("Using existing keys"):(m.info("Generating new keys"),h.seedFromRandom(f)),f!=h.credentials.network)return g(new Error("Existing keys were created for a different network"));var i=new j.PrivateKey,l={name:a,m:c,n:e,pubKey:i.toPublicKey().toString(),network:f};h._doPostRequest("/v1/wallets/",l,function(d,j){if(d)return g(d);var l=j.walletId,m=k.toSecret(l,i,f);h.credentials.addWalletInfo(l,a,c,e,i.toString(),b),h._doJoinWallet(l,i,h.credentials.xPubKey,h.credentials.requestPubKey,b,function(a){return a?g(a):g(null,e>1?m:null)})})},c.prototype.joinWallet=function(a,b,c){var d=this;try{var e=k.fromSecret(a)}catch(f){return c(f)}d.credentials||d.seedFromRandom(e.network),d._doJoinWallet(e.walletId,e.walletPrivKey,d.credentials.xPubKey,d.credentials.requestPubKey,b,function(a,f){return a?c(a):(d.credentials.addWalletInfo(f.id,f.name,f.m,f.n,e.walletPrivKey,b),c(null,f))})},c.prototype.recreateWallet=function(a){e.checkState(this.credentials&&this.credentials.isComplete()&&this.credentials.hasWalletInfo());var b=this,c=j.PrivateKey.fromString(b.credentials.walletPrivKey),d={name:b.credentials.walletName||"recovered wallet",m:b.credentials.m,n:b.credentials.n,pubKey:c.toPublicKey().toString(),network:b.credentials.network};b._doPostRequest("/v1/wallets/",d,function(d,e){if(d)return a(d);var f=e.walletId,h=(k.toSecret(f,c,b.credentials.network),1);g.each(b.credentials.publicKeyRing,function(a,d){var e;e=a.xPubKey==b.credentials.xPubKey?b.credentials.copayerName:"recovered copayer #"+h++,b._doJoinWallet(f,c,a.xPubKey,a.requestPubKey,e,d)},a)})},c.prototype.getStatus=function(a){e.checkState(this.credentials);var b=this;b._doGetRequest("/v1/wallets/",function(d,e){if(d)return a(d);if("pending"==e.wallet.status){var f=b.credentials;e.wallet.secret=k.toSecret(f.walletId,f.walletPrivKey,f.network)}return c._processTxps(e.pendingTxps,b.credentials.sharedEncryptingKey),a(d,e)})},c.prototype.sendTxProposal=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete()),e.checkArgument(a),e.shouldBeNumber(a.amount);var d=this,f={toAddress:a.toAddress,amount:a.amount,message:c._encryptMessage(a.message,d.credentials.sharedEncryptingKey)},g=k.getProposalHash(f.toAddress,f.amount,f.message);f.proposalSignature=k.signMessage(g,d.credentials.requestPrivKey),m.debug("Generating & signing tx proposal hash -> Hash: ",g," Signature: ",f.proposalSignature),d._doPostRequest("/v1/txproposals/",f,function(a,c){return a?b(a):b(null,c)})},c.prototype.createAddress=function(a){e.checkState(this.credentials&&this.credentials.isComplete());var b=this;b._doPostRequest("/v1/addresses/",{},function(c,d){return c?a(c):o.checkAddress(b.credentials,d)?a(null,d):a(new p("Server sent fake address"))})},c.prototype.getMainAddresses=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var c=this;c._doGetRequest("/v1/addresses/",function(e,f){if(e)return b(e);if(!a.doNotVerify){var g=d.any(f,function(a){return!o.checkAddress(c.credentials,a)});if(g)return b(new p("Server sent fake address"))}return b(null,f)})},c.prototype.getBalance=function(a){e.checkState(this.credentials&&this.credentials.isComplete());var b=this;b._doGetRequest("/v1/balance/",a)},c.prototype.getTxProposals=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var f=this;f._doGetRequest("/v1/txproposals/",function(e,g){if(e)return b(e);c._processTxps(g,f.credentials.sharedEncryptingKey);var h=d.any(g,function(b){return!a.doNotVerify&&!o.checkTxProposal(f.credentials,b)});if(h)return b(new p("Server sent fake transaction proposal"));var i;return i=a.forAirGapped?{txps:JSON.parse(JSON.stringify(g)),encryptedPkr:k.encryptMessage(JSON.stringify(f.credentials.publicKeyRing),f.credentials.personalEncryptingKey),m:f.credentials.m,n:f.credentials.n}:g,b(null,i)})},c.prototype.getSignatures=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete()),e.checkArgument(a.creatorId);var c=this;return c.canSign()?o.checkTxProposal(c.credentials,a)?b(null,k.signTxp(a,c.credentials.xPrivKey)):b(new p("Transaction proposal is invalid")):b("You do not have the required keys to sign transactions")},c.prototype.signTxProposal=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete()),e.checkArgument(a.creatorId);var c=this;if(!c.canSign()&&!a.signatures)return b(new Error("You do not have the required keys to sign transactions"));if(!o.checkTxProposal(c.credentials,a))return b(new p("Server sent fake transaction proposal"));var d=a.signatures||k.signTxp(a,c.credentials.xPrivKey),f="/v1/txproposals/"+a.id+"/signatures/",g={signatures:d};c._doPostRequest(f,g,function(a,c){return a?b(a):b(null,c)})},c.prototype.signTxProposalFromAirGapped=function(a,b,c,f){e.checkState(this.credentials);var g=this;if(!g.canSign())throw new Error("You do not have the required keys to sign transactions");var h;try{h=JSON.parse(k.decryptMessage(b,g.credentials.personalEncryptingKey))}catch(i){throw new Error("Could not decrypt public key ring")}if(!d.isArray(h)||h.length!=f)throw new Error("Invalid public key ring");if(g.credentials.m=c,g.credentials.n=f,g.credentials.addPublicKeyRing(h),!o.checkTxProposal(g.credentials,a))throw new Error("Fake transaction proposal");return k.signTxp(a,g.credentials.xPrivKey)},c.prototype.rejectTxProposal=function(a,b,d){e.checkState(this.credentials&&this.credentials.isComplete()),e.checkArgument(d);var f=this,g="/v1/txproposals/"+a.id+"/rejections/",h={reason:c._encryptMessage(b,f.credentials.sharedEncryptingKey)||""};f._doPostRequest(g,h,function(a,b){return a?d(a):d(null,b)})},c.prototype.broadcastTxProposal=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var c=this,d="/v1/txproposals/"+a.id+"/broadcast/";c._doPostRequest(d,{},function(a,c){return a?b(a):b(null,c)})},c.prototype.removeTxProposal=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var c=this,d="/v1/txproposals/"+a.id;c._doDeleteRequest(d,function(a){return a?b(a):b()})},c.prototype.getTxHistory=function(a,b){e.checkState(this.credentials&&this.credentials.isComplete());var d=this;d._doGetRequest("/v1/txhistory/",function(a,e){return a?b(a):(c._processTxps(e,d.credentials.sharedEncryptingKey),b(null,e))})},b.exports=c},{"./clienterror":3,"./credentials":4,"./log":6,"./servercompromisederror":7,"./verifier":8,async:9,bitcore:12,"bitcore-wallet-utils":10,events:242,lodash:274,preconditions:275,request:280,sjcl:337,util:271}],3:[function(a,b){function c(){var a=Array.prototype.slice.call(arguments);switch(a.length){case 0:this.code="BADREQUEST",this.message="Bad request";break;case 1:this.code="BADREQUEST",this.message=a[0];break;default:case 2:this.code=a[0],this.message=a[1]}}c.prototype.toString=function(){return""},b.exports=c},{}],4:[function(a,b){"use strict";function c(){this.version="1.0.0"}var d=a("preconditions").singleton(),e=a("lodash"),f=a("bitcore"),g=a("bitcore-wallet-utils"),h=["network","xPrivKey","xPubKey","requestPrivKey","requestPubKey","copayerId","publicKeyRing","walletId","walletName","m","n","walletPrivKey","personalEncryptingKey","sharedEncryptingKey","copayerName"],i=["xPrivKey","requestPrivKey","xPubKey","m","n","publicKeyRing","sharedEncryptingKey"];c.create=function(a){var b=new c;return b.network=a,b.xPrivKey=new f.HDPrivateKey(a).toString(),b._expand(),b},c.fromExtendedPrivateKey=function(a){var b=new c;return b.xPrivKey=a,b._expand(),b},c.fromExtendedPublicKey=function(a,b){var d=new c;return d.xPubKey=a,d.requestPrivKey=b,d._expand(),d},c.prototype._expand=function(){if(d.checkState(this.xPrivKey||this.xPubKey),this.xPrivKey){var a=new f.HDPrivateKey.fromString(this.xPrivKey),b=a.derive(g.PATHS.BASE_ADDRESS_DERIVATION);this.xPubKey=new f.HDPublicKey(b).toString();var c=a.derive(g.PATHS.REQUEST_KEY);this.requestPrivKey=c.privateKey.toString(),this.requestPubKey=c.publicKey.toString()}var e=g.getNetworkFromXPubKey(this.xPubKey);this.network?d.checkState(this.network==e):this.network=e,this.personalEncryptingKey=g.privateKeyToAESKey(this.requestPrivKey),this.copayerId=g.xPubToCopayerId(this.xPubKey)},c.fromObj=function(a){var b=new c;return e.each(h,function(c){b[c]=a[c]}),d.checkState(b.xPrivKey||b.xPubKey,"invalid input"),b},c.prototype.toObj=function(){var a=this,b={};return e.each(h,function(c){b[c]=a[c]}),b},c.prototype.addWalletInfo=function(a,b,c,d,e,f){this.walletId=a,this.walletName=b,this.m=c,this.n=d,this.walletPrivKey=e,this.sharedEncryptingKey=g.privateKeyToAESKey(e),this.copayerName=f,1==d&&this.addPublicKeyRing([{xPubKey:this.xPubKey,requestPubKey:this.requestPubKey}])},c.prototype.hasWalletInfo=function(){return!!this.walletId},c.prototype.addPublicKeyRing=function(a){this.publicKeyRing=e.clone(a)},c.prototype.canSign=function(){return!!this.xPrivKey},c.prototype.isComplete=function(){return this.m&&this.n&&this.publicKeyRing&&this.publicKeyRing.length==this.n?!0:!1},c.prototype.exportCompressed=function(){var a=this,b=e.map(i,function(b){return"xPubKey"!=b&&"requestPrivKey"!=b||!a.canSign()?"requestPrivKey"==b?f.PrivateKey.fromString(a.requestPrivKey).toWIF():"publicKeyRing"==b?e.reject(a.publicKeyRing,{xPubKey:a.xPubKey}):a[b]:""});return b.unshift(a.version),JSON.stringify(b)},c.importCompressed=function(a){var b;try{b=JSON.parse(a)}catch(d){throw new Error("Invalid compressed format")}{var f=new c;b[0]}return b=e.rest(b),e.each(i,function(a,c){f[a]=b[c]}),f._expand(),f.network=g.getNetworkFromXPubKey(f.xPubKey),f.publicKeyRing.push({xPubKey:f.xPubKey,requestPubKey:f.requestPubKey}),f},b.exports=c},{bitcore:12,"bitcore-wallet-utils":10,lodash:274,preconditions:275}],5:[function(a,b){var c=b.exports=a("./api");c.Verifier=a("./verifier"),c.Bitcore=a("bitcore")},{"./api":2,"./verifier":8,bitcore:12}],6:[function(a,b){var c=a("lodash"),d=function(a){this.name=a||"log",this.level=2};d.prototype.getLevels=function(){return e};var e={debug:0,info:1,log:2,warn:3,error:4,fatal:5};c.each(e,function(a,b){d.prototype[b]=function(){if(a>=e[this.level]){if(Error.stackTraceLimit&&"debug"==this.level){var c=Error.stackTraceLimit;Error.stackTraceLimit=2;var d;try{anerror()}catch(f){d=f.stack}var g=d.split("\n"),h=g[2];h=":"+h.substr(6),Error.stackTraceLimit=c}var i,j="["+b+(h||"")+"] "+arguments[0],i=[].slice.call(arguments,1);console[b]?(i.unshift(j),console[b].apply(console,i)):(i.length&&(j+=JSON.stringify(i)),console.log(j))}}}),d.prototype.setLevel=function(a){this.level=a};{var f=new d("copay");new Error}f.setLevel("info"),b.exports=f},{lodash:274}],7:[function(a,b){function c(a){this.code="SERVERCOMPROMISED",this.message=a}b.exports=c},{}],8:[function(a,b){function c(){}var d=a("preconditions").singleton(),e=a("lodash"),f=a("bitcore"),g=a("bitcore-wallet-utils"),h=a("./log");c.checkAddress=function(a,b){d.checkState(a.isComplete());var c=g.deriveAddress(a.publicKeyRing,b.path,a.m,a.network);return c.address==b.address&&JSON.stringify(c.publicKeys)==JSON.stringify(b.publicKeys)},c.checkCopayers=function(a,b){d.checkState(a.walletPrivKey);var c=f.PrivateKey.fromString(a.walletPrivKey).toPublicKey().toString();if(b.length!=a.n)return h.error("Missing public keys in server response"),!1;var i,j=[];return e.each(b,function(a){if(j[b.xPubKey]++&&(h.error("Repeated public keys in server response"),i=!0),a.name&&a.xPubKey&&a.requestPubKey&&a.signature){var d=g.getCopayerHash(a.name,a.xPubKey,a.requestPubKey);g.verifyMessage(d,a.signature,c)||(h.error("Invalid signatures in server response"),i=!0)}else h.error("Missing copayer fields in server response"),i=!0}),i?!1:e.contains(e.pluck(b,"xPubKey"),a.xPubKey)?!0:(h.error("Server response does not contains our public keys"),!1)},c.checkTxProposal=function(a,b){d.checkArgument(b.creatorId),d.checkState(a.isComplete());var f=e.find(a.publicKeyRing,function(a){return g.xPubToCopayerId(a.xPubKey)===b.creatorId?!0:void 0});if(!f)return!1;var i=f.requestPubKey,j=g.getProposalHash(b.toAddress,b.amount,b.encryptedMessage||b.message);return h.debug("Regenerating & verifying tx proposal hash -> Hash: ",j," Signature: ",b.proposalSignature),g.verifyMessage(j,b.proposalSignature,i)?c.checkAddress(a,b.changeAddress):!1},b.exports=c},{"./log":6,bitcore:12,"bitcore-wallet-utils":10,lodash:274,preconditions:275}],9:[function(a,b){(function(a){!function(){function c(a){var b=!1;return function(){if(b)throw new Error("Callback was already called.");b=!0,a.apply(d,arguments)}}var d,e,f={};d=this,null!=d&&(e=d.async),f.noConflict=function(){return d.async=e,f};var g=Object.prototype.toString,h=Array.isArray||function(a){return"[object Array]"===g.call(a)},i=function(a,b){if(a.forEach)return a.forEach(b);for(var c=0;c=a.length&&d())}if(d=d||function(){},!a.length)return d();var f=0;i(a,function(a){b(a,c(e))})},f.forEach=f.each,f.eachSeries=function(a,b,c){if(c=c||function(){},!a.length)return c();var d=0,e=function(){b(a[d],function(b){b?(c(b),c=function(){}):(d+=1,d>=a.length?c():e())})};e()},f.forEachSeries=f.eachSeries,f.eachLimit=function(a,b,c,d){var e=m(b);e.apply(null,[a,c,d])},f.forEachLimit=f.eachLimit;var m=function(a){return function(b,c,d){if(d=d||function(){},!b.length||0>=a)return d();var e=0,f=0,g=0;!function h(){if(e>=b.length)return d();for(;a>g&&f=b.length?d():h())})}()}},n=function(a){return function(){var b=Array.prototype.slice.call(arguments);return a.apply(null,[f.each].concat(b))}},o=function(a,b){return function(){var c=Array.prototype.slice.call(arguments);return b.apply(null,[m(a)].concat(c))}},p=function(a){return function(){var b=Array.prototype.slice.call(arguments);return a.apply(null,[f.eachSeries].concat(b))}},q=function(a,b,c,d){if(b=j(b,function(a,b){return{index:b,value:a}}),d){var e=[];a(b,function(a,b){c(a.value,function(c,d){e[a.index]=d,b(c)})},function(a){d(a,e)})}else a(b,function(a,b){c(a.value,function(a){b(a)})})};f.map=n(q),f.mapSeries=p(q),f.mapLimit=function(a,b,c,d){return r(b)(a,c,d)};var r=function(a){return o(a,q)};f.reduce=function(a,b,c,d){f.eachSeries(a,function(a,d){c(b,a,function(a,c){b=c,d(a)})},function(a){d(a,b)})},f.inject=f.reduce,f.foldl=f.reduce,f.reduceRight=function(a,b,c,d){var e=j(a,function(a){return a}).reverse();f.reduce(e,b,c,d)},f.foldr=f.reduceRight;var s=function(a,b,c,d){var e=[];b=j(b,function(a,b){return{index:b,value:a}}),a(b,function(a,b){c(a.value,function(c){c&&e.push(a),b()})},function(){d(j(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})};f.filter=n(s),f.filterSeries=p(s),f.select=f.filter,f.selectSeries=f.filterSeries;var t=function(a,b,c,d){var e=[];b=j(b,function(a,b){return{index:b,value:a}}),a(b,function(a,b){c(a.value,function(c){c||e.push(a),b()})},function(){d(j(e.sort(function(a,b){return a.index-b.index}),function(a){return a.value}))})};f.reject=n(t),f.rejectSeries=p(t);var u=function(a,b,c,d){a(b,function(a,b){c(a,function(c){c?(d(a),d=function(){}):b()})},function(){d()})};f.detect=n(u),f.detectSeries=p(u),f.some=function(a,b,c){f.each(a,function(a,d){b(a,function(a){a&&(c(!0),c=function(){}),d()})},function(){c(!1)})},f.any=f.some,f.every=function(a,b,c){f.each(a,function(a,d){b(a,function(a){a||(c(!1),c=function(){}),d()})},function(){c(!0)})},f.all=f.every,f.sortBy=function(a,b,c){f.map(a,function(a,c){b(a,function(b,d){b?c(b):c(null,{value:a,criteria:d})})},function(a,b){if(a)return c(a);var d=function(a,b){var c=a.criteria,d=b.criteria;return d>c?-1:c>d?1:0};c(null,j(b.sort(d),function(a){return a.value}))})},f.auto=function(a,b){b=b||function(){};var c=l(a),d=c.length;if(!d)return b();var e={},g=[],j=function(a){g.unshift(a)},m=function(a){for(var b=0;bd;){var f=d+(e-d+1>>>1);c(b,a[f])>=0?d=f:e=f-1}return d}function e(a,b,e,g){return a.started||(a.started=!0),h(b)||(b=[b]),0==b.length?f.setImmediate(function(){a.drain&&a.drain()}):void i(b,function(b){var h={data:b,priority:e,callback:"function"==typeof g?g:null};a.tasks.splice(d(a.tasks,h,c)+1,0,h),a.saturated&&a.tasks.length===a.concurrency&&a.saturated(),f.setImmediate(a.process)})}var g=f.queue(a,b);return g.push=function(a,b,c){e(g,a,b,c)},delete g.unshift,g},f.cargo=function(a,b){var c=!1,d=[],e={tasks:d,payload:b,saturated:null,empty:null,drain:null,drained:!0,push:function(a,c){h(a)||(a=[a]),i(a,function(a){d.push({data:a,callback:"function"==typeof c?c:null}),e.drained=!1,e.saturated&&d.length===b&&e.saturated()}),f.setImmediate(e.process)},process:function g(){if(!c){if(0===d.length)return e.drain&&!e.drained&&e.drain(),void(e.drained=!0);var f="number"==typeof b?d.splice(0,b):d.splice(0,d.length),h=j(f,function(a){return a.data});e.empty&&e.empty(),c=!0,a(h,function(){c=!1;var a=arguments;i(f,function(b){b.callback&&b.callback.apply(null,a)}),g()})}},length:function(){return d.length},running:function(){return c}};return e};var x=function(a){return function(b){var c=Array.prototype.slice.call(arguments,1);b.apply(null,c.concat([function(b){var c=Array.prototype.slice.call(arguments,1);"undefined"!=typeof console&&(b?console.error&&console.error(b):console[a]&&i(c,function(b){console[a](b)}))}]))}};f.log=x("log"),f.dir=x("dir"),f.memoize=function(a,b){var c={},d={};b=b||function(a){return a};var e=function(){var e=Array.prototype.slice.call(arguments),g=e.pop(),h=b.apply(null,e);h in c?f.nextTick(function(){g.apply(null,c[h])}):h in d?d[h].push(g):(d[h]=[g],a.apply(null,e.concat([function(){c[h]=arguments;var a=d[h];delete d[h];for(var b=0,e=a.length;e>b;b++)a[b].apply(null,arguments)}])))};return e.memo=c,e.unmemoized=a,e},f.unmemoize=function(a){return function(){return(a.unmemoized||a).apply(null,arguments)}},f.times=function(a,b,c){for(var d=[],e=0;a>e;e++)d.push(e);return f.map(d,b,c)},f.timesSeries=function(a,b,c){for(var d=[],e=0;a>e;e++)d.push(e);return f.mapSeries(d,b,c)},f.seq=function(){var a=arguments;return function(){var b=this,c=Array.prototype.slice.call(arguments),d=c.pop();f.reduce(a,c,function(a,c,d){c.apply(b,a.concat([function(){var a=arguments[0],b=Array.prototype.slice.call(arguments,1);d(a,b)}]))},function(a,c){d.apply(b,[a].concat(c))})}},f.compose=function(){return f.seq.apply(null,Array.prototype.reverse.call(arguments))};var y=function(a,b){var c=function(){var c=this,d=Array.prototype.slice.call(arguments),e=d.pop();return a(b,function(a,b){a.apply(c,d.concat([b]))},e)};if(arguments.length>2){var d=Array.prototype.slice.call(arguments,2);return c.apply(this,d)}return c};f.applyEach=n(y),f.applyEachSeries=p(y),f.forever=function(a,b){function c(d){if(d){if(b)return b(d);throw d}a(c)}c()},"undefined"!=typeof b&&b.exports?b.exports=f:"undefined"!=typeof define&&define.amd?define([],function(){return f}):d.async=f}()}).call(this,a("_process"))},{_process:251}],10:[function(a,b){b.exports=a("./lib/walletutils")},{"./lib/walletutils":11}],11:[function(a,b){(function(c){"use strict";function d(){}var e=a("lodash"),f=a("preconditions").singleton(),g=a("sjcl"),h=a("bitcore"),i=h.Address,j=h.PrivateKey,k=h.PublicKey,l=h.crypto,m=h.encoding;d.PATHS={BASE_ADDRESS_DERIVATION:"m/45'",REQUEST_KEY:"m/1'/0",TXPROPOSAL_KEY:"m/1'/1"},d.hashMessage=function(a){f.checkArgument(a);var b=new c(a),d=l.Hash.sha256sha256(b);return d=new h.encoding.BufferReader(d).readReverse()},d.signMessage=function(a,b){f.checkArgument(a);var c=new j(b),e=d.hashMessage(a);return l.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 k(c),g=d.hashMessage(a);try{var h=new l.Signature.fromString(b);return l.ECDSA.verify(g,h,e,"little")}catch(i){return!1}},d.deriveAddress=function(a,b,c,d){var f=e.map(a,function(a){var c=new h.HDPublicKey(a.xPubKey);return c.derive(b).publicKey}),g=i.createMultisig(f,c,d);return{address:g.toString(),path:b,publicKeys:e.invoke(f,"toString")}},d.getProposalHash=function(a,b,c){return[a,b,c||""].join("|")},d.getCopayerHash=function(a,b,c){return[a,b,c].join("|")},d.xPubToCopayerId=function(a){var b=g.hash.sha256.hash(a);return g.codec.hex.fromBits(b)},d.toSecret=function(a,b,d){e.isString(b)&&(b=h.PrivateKey.fromString(b));var f=new c(a.replace(/-/g,""),"hex"),g=new m.Base58(f).toString();return e.padRight(g,22,"0")+b.toWIF()+("testnet"==d?"T":"L")},d.fromSecret=function(a){function b(a,b){var c=[];b.push(a.length);for(var d=0;d"},b.exports=d}).call(this,a("buffer").Buffer)},{"./crypto/hash":20,"./encoding/base58check":25,"./networks":34,"./publickey":37,"./script":38,"./util/js":54,"./util/preconditions":55,buffer:103,lodash:79}],14:[function(a,b){(function(c){"use strict";function d(a){return this instanceof d?(e.extend(this,d._from(a)),this):new d(a)}var e=a("lodash"),f=a("./blockheader"),g=a("../crypto/bn"),h=a("../util/buffer"),i=a("../encoding/bufferreader"),j=a("../encoding/bufferwriter"),k=a("../crypto/hash"),l=a("../util/js"),m=a("../transaction"),n=a("../util/preconditions");d.MAX_BLOCK_SIZE=1e6,d._from=function(a){var b={};if(h.isBuffer(a))b=d._fromBufferReader(i(a));else if(l.isValidJSON(a))b=d._fromJSON(a);else{if(!e.isObject(a))throw new TypeError("Unrecognized argument for Block");b={header:a.header,transactions:a.transactions}}return b},d._fromJSON=function(a){l.isValidJSON(a)&&(a=JSON.parse(a));var b=[];a.transactions.forEach(function(a){b.push(m().fromJSON(a))});var c={header:f.fromJSON(a.header),transactions:b};return c},d.fromJSON=function(a){var b=d._fromJSON(a);return new d(b)},d._fromBufferReader=function(a){var b={};n.checkState(!a.finished(),"No block data received"),b.header=f.fromBufferReader(a);var c=a.readVarintNum();b.transactions=[];for(var d=0;c>d;d++)b.transactions.push(m().fromBufferReader(a));return b},d.fromBufferReader=function(a){var b=d._fromBufferReader(a);return new d(b)},d.fromBuffer=function(a){return d.fromBufferReader(i(a))},d.fromString=function(a){var b=new c(a,"hex");return d.fromBuffer(b)},d.fromRawBlock=function(a){h.isBuffer(a)||(a=new c(a,"binary"));var b=i(a);b.pos=d.Values.START_OF_BLOCK;var e=d._fromBufferReader(b);return new d(e)},d.prototype.toObject=function(){var a=[];return this.transactions.forEach(function(b){a.push(b.toObject())}),{header:this.header.toObject(),transactions:a}},d.prototype.toJSON=function(){return JSON.stringify(this.toObject())},d.prototype.toBuffer=function(){return this.toBufferWriter().concat()},d.prototype.toString=function(){return this.toBuffer().toString("hex")},d.prototype.toBufferWriter=function(a){a||(a=new j),a.write(this.header.toBuffer()),a.writeVarintNum(this.transactions.length);for(var b=0;b1;d=Math.floor((d+1)/2)){for(var e=0;d>e;e+=2){var f=Math.min(e+1,d-1),g=c.concat([a[b+e],a[b+f]]);a.push(k.sha256sha256(g))}b+=d}return a},d.prototype.getMerkleRoot=function(){var a=this.getMerkleTree();return a[a.length-1]},d.prototype.validMerkleRoot=function(){var a=new g(this.header.merkleRoot.toString("hex"),"hex"),b=new g(this.getMerkleRoot().toString("hex"),"hex");return 0!==a.cmp(b)?!1:!0},d.prototype._getHash=function(){return this.header._getHash()};var o={configurable:!1,writeable:!1,get:function(){return this._id||(this._id=this.header.id),this._id},set:e.noop};Object.defineProperty(d.prototype,"id",o),Object.defineProperty(d.prototype,"hash",o),d.prototype.inspect=function(){return""},d.Values={START_OF_BLOCK:8,NULL_HASH:new c("0000000000000000000000000000000000000000000000000000000000000000","hex")},b.exports=d}).call(this,a("buffer").Buffer)},{"../crypto/bn":18,"../crypto/hash":20,"../encoding/bufferreader":26,"../encoding/bufferwriter":27,"../transaction":41,"../util/buffer":53,"../util/js":54,"../util/preconditions":55,"./blockheader":15,buffer:103,lodash:79}],15:[function(a,b){(function(c){"use strict";var d=a("lodash"),e=a("../crypto/bn"),f=a("../util/buffer"),g=a("../encoding/bufferreader"),h=a("../encoding/bufferwriter"),i=a("../crypto/hash"),j=a("../util/js"),k=function m(a){return this instanceof m?(d.extend(this,m._from(a)),this):new m(a)};k._from=function(a){var b={};if(f.isBuffer(a))b=k._fromBufferReader(g(a));else if(j.isValidJSON(a))b=k._fromJSON(a);else{if(!d.isObject(a))throw new TypeError("Unrecognized argument for BlockHeader");b={version:a.version,prevHash:a.prevHash,merkleRoot:a.merkleRoot,time:a.time,bits:a.bits,nonce:a.nonce}}return b},k._fromJSON=function(a){j.isValidJSON(a)&&(a=JSON.parse(a));var b={version:a.version,prevHash:new c(a.prevHash,"hex"),merkleRoot:new c(a.merkleRoot,"hex"),time:a.time,timestamp:a.time,bits:a.bits,nonce:a.nonce};return b},k.fromJSON=function(a){var b=k._fromJSON(a);return new k(b)},k.fromRawBlock=function(a){f.isBuffer(a)||(a=new c(a,"binary"));var b=g(a);b.pos=k.Constants.START_OF_HEADER;var d=k._fromBufferReader(b);return new k(d)},k.fromBuffer=function(a){var b=k._fromBufferReader(g(a));return new k(b)},k.fromString=function(a){var b=new c(a,"hex");return k.fromBuffer(b)},k._fromBufferReader=function(a){var b={};return b.version=a.readUInt32LE(),b.prevHash=a.read(32),b.merkleRoot=a.read(32),b.time=a.readUInt32LE(),b.bits=a.readUInt32LE(),b.nonce=a.readUInt32LE(),b},k.fromBufferReader=function(a){var b=k._fromBufferReader(a);return new k(b)},k.prototype.toObject=function(){return{version:this.version,prevHash:this.prevHash.toString("hex"),merkleRoot:this.merkleRoot.toString("hex"),time:this.time,bits:this.bits,nonce:this.nonce}},k.prototype.toJSON=function(){return JSON.stringify(this.toObject())},k.prototype.toBuffer=function(){return this.toBufferWriter().concat()},k.prototype.toString=function(){return this.toBuffer().toString("hex")},k.prototype.toBufferWriter=function(a){return a||(a=new h),a.writeUInt32LE(this.version),a.write(this.prevHash),a.write(this.merkleRoot),a.writeUInt32LE(this.time),a.writeUInt32LE(this.bits),a.writeUInt32LE(this.nonce),a},k.prototype.getTargetDifficulty=function(){for(var a=new e(16777215&this.bits),b=8*((this.bits>>>24)-3);b-->0;)a=a.mul(new e(2));return a},k.prototype._getHash=function(){var a=this.toBuffer();return i.sha256sha256(a)};var l={configurable:!1,writeable:!1,enumerable:!0,get:function(){return this._id||(this._id=g(this._getHash()).readReverse().toString("hex")),this._id},set:d.noop};Object.defineProperty(k.prototype,"id",l),Object.defineProperty(k.prototype,"hash",l),k.prototype.validTimestamp=function(){var a=Math.round((new Date).getTime()/1e3);return this.time>a+k.Constants.MAX_TIME_OFFSET?!1:!0},k.prototype.validProofOfWork=function(){var a=new e(this.id,"hex"),b=this.getTargetDifficulty();return a.cmp(b)>0?!1:!0},k.prototype.inspect=function(){return""},k.Constants={START_OF_HEADER:8,MAX_TIME_OFFSET:7200,LARGEST_HASH:new e("10000000000000000000000000000000000000000000000000000000000000000","hex")},b.exports=k}).call(this,a("buffer").Buffer)},{"../crypto/bn":18,"../crypto/hash":20,"../encoding/bufferreader":26,"../encoding/bufferwriter":27,"../util/buffer":53,"../util/js":54,buffer:103,lodash:79}],16:[function(a,b){b.exports=a("./block"),b.exports.BlockHeader=a("./blockheader"),b.exports.MerkleBlock=a("./merkleblock")},{"./block":14,"./blockheader":15,"./merkleblock":17}],17:[function(a,b){(function(c){"use strict";function d(a){if(!(this instanceof d))return new d(a);var b={};if(g.isBuffer(a))b=d._fromBufferReader(h(a));else if(k.isValidJSON(a))b=d._fromJSON(a);else{if(!e.isObject(a))throw new TypeError("Unrecognized argument for MerkleBlock");var c;c=a.header instanceof f?a.header:f.fromJSON(JSON.stringify(a.header)),b={header:c,numTransactions:a.numTransactions,hashes:a.hashes,flags:a.flags}}return e.extend(this,b),this._flagBitsUsed=0,this._hashesUsed=0,this}var e=a("lodash"),f=a("./blockheader"),g=a("../util/buffer"),h=a("../encoding/bufferreader"),i=a("../encoding/bufferwriter"),j=a("../crypto/hash"),k=a("../util/js"),l=a("../transaction"),m=a("../util/preconditions");d.fromBuffer=function(a){return d.fromBufferReader(h(a))},d.fromBufferReader=function(a){return new d(d._fromBufferReader(a))},d.fromJSON=function(a){return new d(d._fromJSON(a))},d.prototype.toBuffer=function(){return this.toBufferWriter().concat()},d.prototype.toBufferWriter=function(a){a||(a=new i),a.write(this.header.toBuffer()),a.writeUInt32LE(this.numTransactions),a.writeVarintNum(this.hashes.length);for(var b=0;bthis.numTransactions)return!1;if(8*this.flags.length8*this.flags.length)return null;var e=this.flags[d.flagBitsUsed>>3]>>>(7&d.flagBitsUsed++)&1;if(0!==a&&e){var f=this._traverseMerkleTree(a-1,2*b,d),g=f;return 2*b+1=this.hashes.length)return null;var h=this.hashes[d.hashesUsed++];return 0===a&&e&&d.txs.push(h),new c(h,"hex")},d.prototype._calcTreeWidth=function(a){return this.numTransactions+(1<>a},d.prototype._calcTreeHeight=function(){for(var a=0;this._calcTreeWidth(a)>1;)a++;return a},d.prototype.hasTransaction=function(a){m.checkArgument(!e.isUndefined(a),"tx cannot be undefined"),m.checkArgument(a instanceof l||"string"==typeof a,'Invalid tx given, tx must be a "string" or "Transaction"');var b=a;a instanceof l&&(b=g.reverse(new c(a.id,"hex")).toString("hex"));var d=[],f=this._calcTreeHeight();return this._traverseMerkleTree(f,0,{txs:d}),-1!==d.indexOf(b)},d._fromBufferReader=function(a){m.checkState(!a.finished(),"No merkleblock data received");var b={};b.header=f.fromBufferReader(a),b.numTransactions=a.readUInt32LE();var c=a.readVarintNum();b.hashes=[];for(var d=0;c>d;d++)b.hashes.push(a.read(32).toString("hex"));var e=a.readVarintNum();for(b.flags=[],d=0;e>d;d++)b.flags.push(a.readUInt8());return b},d._fromJSON=function(a){k.isValidJSON(a)&&(a=JSON.parse(a));var b={header:f.fromJSON(a.header),numTransactions:a.numTransactions,hashes:a.hashes,flags:a.flags};return b},b.exports=d}).call(this,a("buffer").Buffer)},{"../crypto/hash":20,"../encoding/bufferreader":26,"../encoding/bufferwriter":27,"../transaction":41,"../util/buffer":53,"../util/js":54,"../util/preconditions":55,"./blockheader":15,buffer:103,lodash:79}],18:[function(a,b){(function(c){"use strict";var d=a("bn.js"),e=a("../util/preconditions"),f=a("lodash"),g=function(a){for(var b=new c(a.length),d=0;da.size?b=d.trim(b,f):f0&&0===(127&a[a.length-1])&&(a.length<=1||0===(128&a[a.length-2])))throw new Error("non-minimally encoded script number");return d.fromSM(a,{endian:"little"})},d.prototype.toScriptNumBuffer=function(){return this.toSM({endian:"little"})},d.prototype.gt=function(a){return this.cmp(a)>0},d.prototype.lt=function(a){return this.cmp(a)<0},d.trim=function(a,b){return a.slice(b-a.length,a.length)},d.pad=function(a,b,d){for(var e=new c(d),f=0;ff;f++)e[f]=0;return e},b.exports=d}).call(this,a("buffer").Buffer)},{"../util/preconditions":55,"bn.js":56,buffer:103,lodash:79}],19:[function(a,b){(function(c){"use strict";var d=a("./bn"),e=a("./point"),f=a("./signature"),g=a("../publickey"),h=a("./random"),i=a("./hash"),j=a("../util/buffer"),k=a("lodash"),l=a("../util/preconditions"),m=function n(a){return this instanceof n?void(a&&this.set(a)):new n(a)};m.prototype.set=function(a){return this.hashbuf=a.hashbuf||this.hashbuf,this.endian=a.endian||this.endian,this.privkey=a.privkey||this.privkey,this.pubkey=a.pubkey||(this.privkey?this.privkey.publicKey:this.pubkey),this.sig=a.sig||this.sig,this.k=a.k||this.k,this.verified=a.verified||this.verified,this},m.prototype.privkey2pubkey=function(){this.pubkey=this.privkey.toPublicKey()},m.prototype.calci=function(){for(var a=0;4>a;a++){this.sig.i=a;var b;try{b=this.toPublicKey()}catch(c){console.error(c);continue}if(b.point.eq(this.pubkey.point))return this.sig.compressed=this.pubkey.compressed,this}throw this.sig.i=void 0,new Error("Unable to find valid recovery factor")},m.fromString=function(a){var b=JSON.parse(a);return new m(b)},m.prototype.randomK=function(){var a,b=e.getN();do a=d.fromBuffer(h.getRandomBuffer(32));while(!a.lt(b)||!a.gt(d.Zero));return this.k=a,this},m.prototype.deterministicK=function(a){k.isUndefined(a)&&(a=0);var b=new c(32);b.fill(1);var f=new c(32);f.fill(0);var g=this.privkey.bn.toBuffer({size:32});f=i.sha256hmac(c.concat([b,new c([0]),g,this.hashbuf]),f),b=i.sha256hmac(b,f),f=i.sha256hmac(c.concat([b,new c([1]),g,this.hashbuf]),f),b=i.sha256hmac(b,f),b=i.sha256hmac(b,f);for(var h=d.fromBuffer(b),j=e.getN(),l=0;a>l||!h.lt(j)||!h.gt(d.Zero);l++)f=i.sha256hmac(c.concat([b,new c([0])]),f),b=i.sha256hmac(b,f),b=i.sha256hmac(b,f),h=d.fromBuffer(b);return this.k=h,this},m.prototype.toPublicKey=function(){var a=this.sig.i;l.checkArgument(0===a||1===a||2===a||3===a,new Error("i must be equal to 0, 1, 2, or 3"));var b=d.fromBuffer(this.hashbuf),c=this.sig.r,f=this.sig.s,h=1&a,i=a>>1,j=e.getN(),k=e.getG(),m=i?c.add(j):c,n=e.fromX(h,m),o=n.mul(j);if(!o.isInfinity())throw new Error("nR is not a valid curve point");var p=b.neg().mod(j),q=c.invm(j),r=n.mul(f).add(k.mul(p)).mul(q),s=g.fromPoint(r,this.sig.compressed);return s},m.prototype.sigError=function(){if(!j.isBuffer(this.hashbuf)||32!==this.hashbuf.length)return"hashbuf must be a 32 byte buffer";var a=this.sig.r,b=this.sig.s;if(!(a.gt(d.Zero)&&a.lt(e.getN())&&b.gt(d.Zero)&&b.lt(e.getN())))return"r and s not in range";var c=d.fromBuffer(this.hashbuf,this.endian?{endian:this.endian}:void 0),f=e.getN(),g=b.invm(f),h=g.mul(c).mod(f),i=g.mul(a).mod(f),k=e.getG().mulAdd(h,this.pubkey.point,i);return k.isInfinity()?"p is infinity":0!==k.getX().mod(f).cmp(a)?"Invalid signature":!1},m.toLowS=function(a){return a.gt(d.fromBuffer(new c("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0","hex")))&&(a=e.getN().sub(a)),a},m.prototype._findSignature=function(a,b){var c,f,g,h,i=e.getN(),j=e.getG(),k=0;do(!this.k||k>0)&&this.deterministicK(k),k++,c=this.k,f=j.mul(c),g=f.x.mod(i),h=c.invm(i).mul(b.add(a.mul(g))).mod(i);while(g.cmp(d.Zero)<=0||h.cmp(d.Zero)<=0);return h=m.toLowS(h),{s:h,r:g}},m.prototype.sign=function(){var a=this.hashbuf,b=this.privkey,c=b.bn;l.checkState(a&&b&&c,new Error("invalid parameters")),l.checkState(j.isBuffer(a)&&32===a.length,new Error("hashbuf must be a 32 byte buffer"));var e=d.fromBuffer(a,this.endian?{endian:this.endian}:void 0),g=this._findSignature(c,e);return g.compressed=this.pubkey.compressed,this.sig=new f(g),this},m.prototype.signRandomK=function(){return this.randomK(),this.sign()},m.prototype.toString=function(){var a={};return this.hashbuf&&(a.hashbuf=this.hashbuf.toString("hex")),this.privkey&&(a.privkey=this.privkey.toString()),this.pubkey&&(a.pubkey=this.pubkey.toString()),this.sig&&(a.sig=this.sig.toString()),this.k&&(a.k=this.k.toString()),JSON.stringify(a)},m.prototype.verify=function(){return this.verified=this.sigError()?!1:!0,this},m.sign=function(a,b,c){return m().set({hashbuf:a,endian:c,privkey:b}).sign().sig},m.verify=function(a,b,c,d){return m().set({hashbuf:a,endian:d,sig:b,pubkey:c}).verify().verified},b.exports=m}).call(this,a("buffer").Buffer)},{"../publickey":37,"../util/buffer":53,"../util/preconditions":55,"./bn":18,"./hash":20,"./point":21,"./random":22,"./signature":23,buffer:103,lodash:79}],20:[function(a,b){(function(c){"use strict";var d=a("hash.js"),e=a("sha512"),f=a("crypto"),g=a("../util/buffer"),h=a("../util/preconditions"),i=b.exports;i.sha1=function(a){return h.checkArgument(g.isBuffer(a)),f.createHash("sha1").update(a).digest()},i.sha1.blocksize=512,i.sha256=function(a){return h.checkArgument(g.isBuffer(a)),f.createHash("sha256").update(a).digest()},i.sha256.blocksize=512,i.sha256sha256=function(a){return h.checkArgument(g.isBuffer(a)),i.sha256(i.sha256(a))},i.ripemd160=function(a){h.checkArgument(g.isBuffer(a));var b=(new d.ripemd160).update(a).digest();return new c(b)},i.sha256ripemd160=function(a){return h.checkArgument(g.isBuffer(a)),i.ripemd160(i.sha256(a))},i.sha512=function(a){h.checkArgument(g.isBuffer(a));var b=e(a);return new c(b)},i.sha512.blocksize=1024,i.hmac=function(a,b,d){h.checkArgument(g.isBuffer(b)),h.checkArgument(g.isBuffer(d)),h.checkArgument(a.blocksize);var e=a.blocksize/8;if(d.length>e)d=a(d);else if(e>d){var f=new c(e);f.fill(0),d.copy(f),d=f}var i=new c(e);i.fill(92);var j=new c(e);j.fill(54);for(var k=new c(e),l=new c(e),m=0;e>m;m++)k[m]=i[m]^d[m],l[m]=j[m]^d[m];return a(c.concat([k,a(c.concat([l,b]))]))},i.sha256hmac=function(a,b){return i.hmac(i.sha256,a,b)},i.sha512hmac=function(a,b){return i.hmac(i.sha512,a,b)}}).call(this,a("buffer").Buffer)},{"../util/buffer":53,"../util/preconditions":55,buffer:103,crypto:107,"hash.js":72,sha512:82}],21:[function(a,b){(function(c){"use strict";var d=a("./bn"),e=a("../util/buffer"),f=a("elliptic").curves.secp256k1,g=f.curve.point.bind(f.curve),h=f.curve.pointFromX.bind(f.curve),i=function(a,b,c){var d=g(a,b,c);return d.validate(),d};i.prototype=Object.getPrototypeOf(f.curve.point()),i.fromX=function(a,b){var c=h(a,b);return c.validate(),c},i.getG=function(){return f.curve.g},i.getN=function(){return new d(f.curve.n.toArray())},i.prototype._getX=i.prototype.getX,i.prototype.getX=function(){return new d(this._getX().toArray())},i.prototype._getY=i.prototype.getY,i.prototype.getY=function(){return new d(this._getY().toArray())},i.prototype.validate=function(){if(this.isInfinity())throw new Error("Point cannot be equal to Infinity");if(0===this.getX().cmp(d.Zero)||0===this.getY().cmp(d.Zero))throw new Error("Invalid x,y value for curve, cannot equal 0.");var a=h(this.getY().isOdd(),this.getX());if(0!==a.y.cmp(this.y))throw new Error("Invalid y value for curve.");var b=this.getX().gt(d.Minus1)&&this.getX().lt(i.getN()),c=this.getY().gt(d.Minus1)&&this.getY().lt(i.getN());if(!b||!c)throw new Error("Point does not lie on the curve");if(!this.mul(i.getN()).isInfinity())throw new Error("Point times N must be infinity");return this},i.pointToCompressed=function(a){var b,d=a.getX().toBuffer({size:32}),f=a.getY().toBuffer({size:32}),g=f[f.length-1]%2;return b=new c(g?[3]:[2]),e.concat([b,d])},b.exports=i}).call(this,a("buffer").Buffer)},{"../util/buffer":53,"./bn":18,buffer:103,elliptic:58}],22:[function(a,b){(function(c,d){"use strict";function e(){}e.getRandomBuffer=function(a){return c.browser?e.getRandomBufferBrowser(a):e.getRandomBufferNode(a)},e.getRandomBufferNode=function(b){var c=a("crypto");return c.randomBytes(b)},e.getRandomBufferBrowser=function(a){if(!window.crypto&&!window.msCrypto)throw new Error("window.crypto not available");if(window.crypto&&window.crypto.getRandomValues)var b=window.crypto;else{if(!window.msCrypto||!window.msCrypto.getRandomValues)throw new Error("window.crypto.getRandomValues not available");var b=window.msCrypto}var c=new Uint8Array(a);b.getRandomValues(c);var e=new d(c);return e},e.getPseudoRandomBuffer=function(a){for(var b,c=4294967296,e=new d(a),f=0;a>=f;f++){var g=Math.floor(f/4),h=f-4*g;0===h?(b=Math.random()*c,e[f]=255&b):e[f]=255&(b>>>=8)}return e},b.exports=e}).call(this,a("_process"),a("buffer").Buffer)},{_process:251,buffer:103,crypto:107}],23:[function(a,b){(function(c){"use strict";var d=a("./bn"),e=a("lodash"),f=a("../util/preconditions"),g=a("../util/buffer"),h=function i(a,b){if(!(this instanceof i))return new i(a,b);if(a instanceof d)this.set({r:a,s:b});else if(a){var c=a;this.set(c)}};h.prototype.set=function(a){return this.r=a.r||this.r||void 0,this.s=a.s||this.s||void 0,this.i="undefined"!=typeof a.i?a.i:this.i,this.compressed="undefined"!=typeof a.compressed?a.compressed:this.compressed,this},h.fromCompact=function(a){var b=new h,c=!0,e=a.slice(0,1)[0]-27-4,g=a.slice(1,33),i=a.slice(33,65);return f.checkArgument(0===e||1===e||2===e||3===e,new Error("i must be 0, 1, 2, or 3")),f.checkArgument(32===g.length,new Error("r must be 32 bytes")),f.checkArgument(32===i.length,new Error("s must be 32 bytes")),b.compressed=c,b.i=e,b.r=d.fromBuffer(g),b.s=d.fromBuffer(i),b},h.fromDER=h.fromBuffer=function(a,b){var c=h.parseDER(a,b),d=new h;return d.r=c.r,d.s=c.s,d},h.fromTxFormat=function(a){var b=a.readUInt8(a.length-1),c=a.slice(0,a.length-1),d=new h.fromDER(c,!1);return d.nhashtype=b,d},h.fromString=function(a){var b=new c(a,"hex");return h.fromDER(b)},h.parseDER=function(a,b){f.checkArgument(g.isBuffer(a),new Error("DER formatted signature should be a buffer")),e.isUndefined(b)&&(b=!0);var c=a[0];f.checkArgument(48===c,new Error("Header byte should be 0x30"));var h=a[1],i=a.slice(2).length;f.checkArgument(!b||h===i,new Error("Length byte should length of what follows")),h=i>h?h:i;var j=a[2];f.checkArgument(2===j,new Error("Integer byte for r should be 0x02"));var k=a[3],l=a.slice(4,4+k),m=d.fromBuffer(l),n=0===a[4]?!0:!1;f.checkArgument(k===l.length,new Error("Length of r incorrect"));var o=a[4+k+0];f.checkArgument(2===o,new Error("Integer byte for s should be 0x02"));var p=a[4+k+1],q=a.slice(4+k+2,4+k+2+p),r=d.fromBuffer(q),s=0===a[4+k+2+2]?!0:!1;f.checkArgument(p===q.length,new Error("Length of s incorrect"));var t=4+k+2+p;f.checkArgument(h===t-2,new Error("Length of signature incorrect"));var u={header:c,length:h,rheader:j,rlength:k,rneg:n,rbuf:l,r:m,sheader:o,slength:p,sneg:s,sbuf:q,s:r};return u},h.prototype.toCompact=function(a,b){if(a="number"==typeof a?a:this.i,b="boolean"==typeof b?b:this.compressed,0!==a&&1!==a&&2!==a&&3!==a)throw new Error("i must be equal to 0, 1, 2, or 3");var d=a+27+4;b===!1&&(d-=4);var e=new c([d]),f=this.r.toBuffer({size:32}),g=this.s.toBuffer({size:32});return c.concat([e,f,g])},h.prototype.toBuffer=h.prototype.toDER=function(){var a=this.r.toBuffer(),b=this.s.toBuffer(),d=128&a[0]?!0:!1,e=128&b[0]?!0:!1,f=d?c.concat([new c([0]),a]):a,g=e?c.concat([new c([0]),b]):b,h=f.length,i=g.length,j=2+h+2+i,k=2,l=2,m=48,n=c.concat([new c([m,j,k,h]),f,new c([l,i]),g]);return n},h.prototype.toString=function(){var a=this.toDER();return a.toString("hex")},h.isTxDER=function(a){if(a.length<9)return!1;if(a.length>73)return!1;if(48!==a[0])return!1;if(a[1]!==a.length-3)return!1;var b=a[3];if(5+b>=a.length)return!1;var c=a[5+b];if(b+c+7!==a.length)return!1;var d=a.slice(4);if(2!==a[2])return!1;if(0===b)return!1;if(128&d[0])return!1;if(b>1&&0===d[0]&&!(128&d[1]))return!1;var e=a.slice(6+b);return 2!==a[6+b-2]?!1:0===c?!1:128&e[0]?!1:c>1&&0===e[0]&&!(128&e[1])?!1:!0},h.prototype.hasLowS=function(){return this.s.lt(new d(1))||this.s.gt(new d("7FFFFFFFFFFFFFFFFFFFFFFFFFFFFFFF5D576E7357A4501DDFE92F46681B20A0"))?!1:!0},h.prototype.hasDefinedHashtype=function(){return this.nhashtypeh.SIGHASH_SINGLE?!1:!0},h.prototype.toTxFormat=function(){var a=this.toDER(),b=new c(1);return b.writeUInt8(this.nhashtype,0),c.concat([a,b])},h.SIGHASH_ALL=1,h.SIGHASH_NONE=2,h.SIGHASH_SINGLE=3,h.SIGHASH_ANYONECANPAY=128,b.exports=h}).call(this,a("buffer").Buffer)},{"../util/buffer":53,"../util/preconditions":55,"./bn":18,buffer:103,lodash:79}],24:[function(a,b){(function(c){"use strict";var d=a("lodash"),e=a("bs58"),f=a("buffer"),g="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz".split(""),h=function i(a){if(!(this instanceof i))return new i(a);if(c.isBuffer(a)){var b=a;this.fromBuffer(b)}else if("string"==typeof a){var d=a;this.fromString(d)}else a&&this.set(a)};h.validCharacters=function(a){return f.Buffer.isBuffer(a)&&(a=a.toString()),d.all(d.map(a,function(a){return d.contains(g,a)}))},h.prototype.set=function(a){return this.buf=a.buf||this.buf||void 0,this},h.encode=function(a){if(!f.Buffer.isBuffer(a))throw new Error("Input should be a buffer");return e.encode(a)},h.decode=function(a){if("string"!=typeof a)throw new Error("Input should be a string"); return new c(e.decode(a))},h.prototype.fromBuffer=function(a){return this.buf=a,this},h.prototype.fromString=function(a){var b=h.decode(a);return this.buf=b,this},h.prototype.toBuffer=function(){return this.buf},h.prototype.toString=function(){return h.encode(this.buf)},b.exports=h}).call(this,a("buffer").Buffer)},{bs58:57,buffer:103,lodash:79}],25:[function(a,b){(function(c){"use strict";var d=a("lodash"),e=a("./base58"),f=a("buffer"),g=a("../crypto/hash").sha256sha256,h=function i(a){if(!(this instanceof i))return new i(a);if(c.isBuffer(a)){var b=a;this.fromBuffer(b)}else if("string"==typeof a){var d=a;this.fromString(d)}else a&&this.set(a)};h.prototype.set=function(a){return this.buf=a.buf||this.buf||void 0,this},h.validChecksum=function(a,b){return d.isString(a)&&(a=new f.Buffer(e.decode(a))),d.isString(b)&&(b=new f.Buffer(e.decode(b))),b||(b=a.slice(-4),a=a.slice(0,-4)),h.checksum(a).toString("hex")===b.toString("hex")},h.decode=function(a){if("string"!=typeof a)throw new Error("Input must be a string");var b=new c(e.decode(a));if(b.length<4)throw new Error("Input string too short");var d=b.slice(0,-4),f=b.slice(-4),h=g(d),i=h.slice(0,4);if(f.toString("hex")!==i.toString("hex"))throw new Error("Checksum mismatch");return d},h.checksum=function(a){return g(a).slice(0,4)},h.encode=function(a){if(!c.isBuffer(a))throw new Error("Input must be a buffer");var b=new c(a.length+4),d=h.checksum(a);return a.copy(b),d.copy(b,a.length),e.encode(b)},h.prototype.fromBuffer=function(a){return this.buf=a,this},h.prototype.fromString=function(a){var b=h.decode(a);return this.buf=b,this},h.prototype.toBuffer=function(){return this.buf},h.prototype.toString=function(){return h.encode(this.buf)},b.exports=h}).call(this,a("buffer").Buffer)},{"../crypto/hash":20,"./base58":24,buffer:103,lodash:79}],26:[function(a,b){(function(c){"use strict";var d=a("lodash"),e=a("../util/preconditions"),f=a("../util/buffer"),g=a("../crypto/bn"),h=function i(a){if(!(this instanceof i))return new i(a);if(c.isBuffer(a))this.set({buf:a});else if(a){var b=a;this.set(b)}};h.prototype.set=function(a){return this.buf=a.buf||this.buf||void 0,this.pos=a.pos||this.pos||0,this},h.prototype.eof=function(){return this.pos>=this.buf.length},h.prototype.finished=h.prototype.eof,h.prototype.read=function(a){e.checkArgument(!d.isUndefined(a),"Must specify a length");var b=this.buf.slice(this.pos,this.pos+a);return this.pos=this.pos+a,b},h.prototype.readAll=function(){var a=this.buf.slice(this.pos,this.buf.length);return this.pos=this.buf.length,a},h.prototype.readUInt8=function(){var a=this.buf.readUInt8(this.pos);return this.pos=this.pos+1,a},h.prototype.readUInt16BE=function(){var a=this.buf.readUInt16BE(this.pos);return this.pos=this.pos+2,a},h.prototype.readUInt16LE=function(){var a=this.buf.readUInt16LE(this.pos);return this.pos=this.pos+2,a},h.prototype.readUInt32BE=function(){var a=this.buf.readUInt32BE(this.pos);return this.pos=this.pos+4,a},h.prototype.readUInt32LE=function(){var a=this.buf.readUInt32LE(this.pos);return this.pos=this.pos+4,a},h.prototype.readUInt64BEBN=function(){var a=this.buf.slice(this.pos,this.pos+8),b=g.fromBuffer(a);return this.pos=this.pos+8,b},h.prototype.readUInt64LEBN=function(){var a=this.buf.slice(this.pos,this.pos+8),b=h({buf:a}).readReverse(),c=g.fromBuffer(b);return this.pos=this.pos+8,c},h.prototype.readVarintNum=function(){var a=this.readUInt8();switch(a){case 253:return this.readUInt16LE();case 254:return this.readUInt32LE();case 255:var b=this.readUInt64LEBN(),c=b.toNumber();if(c<=Math.pow(2,53))return c;throw new Error("number too large to retain precision - use readVarintBN");default:return a}},h.prototype.readVarLengthBuffer=function(){var a=this.readVarintNum(),b=this.read(a);return e.checkState(b.length===a,"Invalid length while reading varlength buffer. Expected to read: "+a+" and read "+b.length),b},h.prototype.readVarintBuf=function(){var a=this.buf.readUInt8(this.pos);switch(a){case 253:return this.read(3);case 254:return this.read(5);case 255:return this.read(9);default:return this.read(1)}},h.prototype.readVarintBN=function(){var a=this.readUInt8();switch(a){case 253:return new g(this.readUInt16LE());case 254:return new g(this.readUInt32LE());case 255:return this.readUInt64LEBN();default:return new g(a)}},h.prototype.reverse=function(){for(var a=new c(this.buf.length),b=0;ba?(b=new c(1),b.writeUInt8(a,0)):65536>a?(b=new c(3),b.writeUInt8(253,0),b.writeUInt16LE(a,1)):4294967296>a?(b=new c(5),b.writeUInt8(254,0),b.writeUInt32LE(a,1)):(b=new c(9),b.writeUInt8(255,0),b.writeInt32LE(-1&a,1),b.writeUInt32LE(Math.floor(a/4294967296),5)),b},f.varintBufBN=function(a){var b=void 0,d=a.toNumber();if(253>d)b=new c(1),b.writeUInt8(d,0);else if(65536>d)b=new c(3),b.writeUInt8(253,0),b.writeUInt16LE(d,1);else if(4294967296>d)b=new c(5),b.writeUInt8(254,0),b.writeUInt32LE(d,1);else{var e=new f;e.writeUInt8(255),e.writeUInt64LEBN(a);var b=e.concat()}return b},b.exports=f}).call(this,a("buffer").Buffer)},{"../util/buffer":53,assert:88,buffer:103}],28:[function(a,b){(function(c){"use strict";var d=a("./bufferwriter"),e=a("./bufferreader"),f=a("../crypto/bn"),g=function h(a){if(!(this instanceof h))return new h(a);if(c.isBuffer(a))this.buf=a;else if("number"==typeof a){var b=a;this.fromNumber(b)}else if(a instanceof f){var d=a;this.fromBN(d)}else if(a){var e=a;this.set(e)}};g.prototype.set=function(a){return this.buf=a.buf||this.buf,this},g.prototype.fromString=function(a){return this.set({buf:new c(a,"hex")}),this},g.prototype.toString=function(){return this.buf.toString("hex")},g.prototype.fromBuffer=function(a){return this.buf=a,this},g.prototype.fromBufferReader=function(a){return this.buf=a.readVarintBuf(),this},g.prototype.fromBN=function(a){return this.buf=d().writeVarintBN(a).concat(),this},g.prototype.fromNumber=function(a){return this.buf=d().writeVarintNum(a).concat(),this},g.prototype.toBuffer=function(){return this.buf},g.prototype.toBN=function(){return e(this.buf).readVarintBN()},g.prototype.toNumber=function(){return e(this.buf).readVarintNum()},b.exports=g}).call(this,a("buffer").Buffer)},{"../crypto/bn":18,"./bufferreader":26,"./bufferwriter":27,buffer:103}],29:[function(a,b){"use strict";function c(a,b){return a.replace("{0}",b[0]).replace("{1}",b[1]).replace("{2}",b[2])}var d=a("lodash"),e=function(a,b){var e=function(){if(d.isString(b.message))this.message=c(b.message,arguments);else{if(!d.isFunction(b.message))throw new Error("Invalid error definition for "+b.name);this.message=b.message.apply(null,arguments)}this.stack=this.message+"\n"+(new Error).stack};return e.prototype=Object.create(a.prototype),e.prototype.name=a.prototype.name+b.name,a[b.name]=e,b.errors&&f(e,b.errors),e},f=function(a,b){d.each(b,function(b){e(a,b)})},g=function(a,b){return f(a,b),a},h={};h.Error=function(){this.message="Internal error",this.stack=this.message+"\n"+(new Error).stack},h.Error.prototype=Object.create(Error.prototype),h.Error.prototype.name="bitcore.Error";var i=a("./spec");g(h.Error,i),b.exports=h.Error,b.exports.extend=function(a){return e(h.Error,a)}},{"./spec":30,lodash:79}],30:[function(a,b){"use strict";var c="http://bitcore.io/";b.exports=[{name:"InvalidB58Char",message:"Invalid Base58 character: {0} in {1}"},{name:"InvalidB58Checksum",message:"Invalid Base58 checksum for {0}"},{name:"InvalidNetwork",message:"Invalid version for network: got {0}"},{name:"InvalidState",message:"Invalid state: {0}"},{name:"NotImplemented",message:"Function {0} was not implemented yet"},{name:"InvalidNetworkArgument",message:'Invalid network: must be "livenet" or "testnet", got {0}'},{name:"InvalidArgument",message:function(){return"Invalid Argument"+(arguments[0]?": "+arguments[0]:"")+(arguments[1]?" Documentation: "+c+arguments[1]:"")}},{name:"AbstractMethodInvoked",message:"Abstract Method Invokation: {0}"},{name:"InvalidArgumentType",message:function(){return"Invalid Argument for "+arguments[2]+", expected "+arguments[1]+" but got "+typeof arguments[0]}},{name:"Unit",message:"Internal Error on Unit {0}",errors:[{name:"UnknownCode",message:"Unrecognized unit code: {0}"},{name:"InvalidRate",message:"Invalid exchange rate: {0}"}]},{name:"Transaction",message:"Internal Error on Transaction {0}",errors:[{name:"Input",message:"Internal Error on Input {0}",errors:[{name:"MissingScript",message:"Need a script to create an input"},{name:"UnsupportedScript",message:"Unsupported input script type: {0}"},{name:"MissingPreviousOutput",message:"No previous output information."}]},{name:"NeedMoreInfo",message:"{0}"},{name:"InvalidOutputAmountSum",message:"{0}"},{name:"MissingSignatures",message:"Some inputs have not been fully signed"},{name:"InvalidIndex",message:"Invalid index: {0} is not between 0, {1}"},{name:"UnableToVerifySignature",message:"Unable to verify signature: {0}"},{name:"DustOutputs",message:"Dust amount detected in one output"},{name:"FeeError",message:"Fees are not correctly set {0}"},{name:"ChangeAddressMissing",message:"Change address is missing"},{name:"BlockHeightTooHigh",message:"Block Height can be at most 2^32 -1"},{name:"NLockTimeOutOfRange",message:"Block Height can only be between 0 and 499 999 999"},{name:"LockTimeTooEarly",message:"Lock Time can't be earlier than UNIX date 500 000 000"}]},{name:"Script",message:"Internal Error on Script {0}",errors:[{name:"UnrecognizedAddress",message:"Expected argument {0} to be an address"}]},{name:"HDPrivateKey",message:"Internal Error on HDPrivateKey {0}",errors:[{name:"InvalidDerivationArgument",message:"Invalid derivation argument {0}, expected string, or number and boolean"},{name:"InvalidEntropyArgument",message:"Invalid entropy: must be an hexa string or binary buffer, got {0}",errors:[{name:"TooMuchEntropy",message:'Invalid entropy: more than 512 bits is non standard, got "{0}"'},{name:"NotEnoughEntropy",message:'Invalid entropy: at least 128 bits needed, got "{0}"'}]},{name:"InvalidLength",message:"Invalid length for xprivkey string in {0}"},{name:"InvalidPath",message:"Invalid derivation path: {0}"},{name:"UnrecognizedArgument",message:'Invalid argument: creating a HDPrivateKey requires a string, buffer, json or object, got "{0}"'}]},{name:"HDPublicKey",message:"Internal Error on HDPublicKey {0}",errors:[{name:"ArgumentIsPrivateExtended",message:"Argument is an extended private key: {0}"},{name:"InvalidDerivationArgument",message:"Invalid derivation argument: got {0}"},{name:"InvalidLength",message:'Invalid length for xpubkey: got "{0}"'},{name:"InvalidPath",message:'Invalid derivation path, it should look like: "m/1/100", got "{0}"'},{name:"MustSupplyArgument",message:"Must supply an argument to create a HDPublicKey"},{name:"UnrecognizedArgument",message:"Invalid argument for creation, must be string, json, buffer, or object"}]}]},{}],31:[function(a,b){"use strict";b.exports={_cache:{},_count:0,_eraseIndex:0,_usedList:{},_usedIndex:{},_CACHE_SIZE:5e3,get:function(a,b,c){c=!!c;var d=a+"/"+b+"/"+c;return this._cache[d]?(this._cacheHit(d),this._cache[d]):void 0},set:function(a,b,c,d){c=!!c;var e=a+"/"+b+"/"+c;this._cache[e]=d,this._cacheHit(e)},_cacheHit:function(a){this._usedIndex[a]&&delete this._usedList[this._usedIndex[a]],this._usedList[this._count]=a,this._usedIndex[a]=this._count,this._count++,this._cacheRemove()},_cacheRemove:function(){for(;this._eraseIndex=0&&a=d.Hardened?!0:b,ax*w)throw new s.InvalidEntropyArgument.TooMuchEntropy(a);var e=l.sha512hmac(a,new f.Buffer("Bitcoin seed"));return new d({network:m.get(b)||m.defaultNetwork,depth:0,parentFingerPrint:0,childIndex:0,privateKey:e.slice(0,32),chainCode:e.slice(32,64)})},d.prototype._buildFromBuffers=function(b){d._validateBufferArguments(b),u.defineImmutable(this,{_buffers:b});var e=[b.version,b.depth,b.parentFingerPrint,b.childIndex,b.chainCode,t.emptyBuffer(1),b.privateKey],g=f.Buffer.concat(e);if(b.checksum&&b.checksum.length){if(b.checksum.toString()!==k.checksum(g).toString())throw new r.InvalidB58Checksum(g)}else b.checksum=k.checksum(g);var h,j=m.get(t.integerFromBuffer(b.version));h=k.encode(f.Buffer.concat(e)),b.xprivkey=new c(h);var n=new p(i.fromBuffer(b.privateKey),j),o=n.toPublicKey(),q=d.ParentFingerPrintSize,s=l.sha256ripemd160(o.toBuffer()).slice(0,q);u.defineImmutable(this,{xprivkey:h,network:j,depth:t.integerFromSingleByteBuffer(b.depth),privateKey:n,publicKey:o,fingerPrint:s});var v=a("./hdpublickey"),w=new v(this);return u.defineImmutable(this,{hdPublicKey:w,xpubkey:w.xpubkey}),this},d._validateBufferArguments=function(a){var b=function(b,c){var d=a[b];e(t.isBuffer(d),b+" argument is not a buffer"),e(d.length===c,b+" has not the expected size: found "+d.length+", expected "+c)};b("version",d.VersionSize),b("depth",d.DepthSize),b("parentFingerPrint",d.ParentFingerPrintSize),b("childIndex",d.ChildIndexSize),b("chainCode",d.ChainCodeSize),b("privateKey",d.PrivateKeySize),a.checksum&&a.checksum.length&&b("checksum",d.CheckSumSize)},d.prototype.toString=function(){return this.xprivkey},d.prototype.inspect=function(){return""},d.prototype.toObject=function(){return{network:m.get(t.integerFromBuffer(this._buffers.version)).name,depth:t.integerFromSingleByteBuffer(this._buffers.depth),fingerPrint:t.integerFromBuffer(this.fingerPrint),parentFingerPrint:t.integerFromBuffer(this._buffers.parentFingerPrint),childIndex:t.integerFromBuffer(this._buffers.childIndex),chainCode:t.bufferToHex(this._buffers.chainCode),privateKey:this.privateKey.toBuffer().toString("hex"),checksum:t.integerFromBuffer(this._buffers.checksum),xprivkey:this.xprivkey}},d.prototype.toJSON=function(){return JSON.stringify(this.toObject())},d.fromBuffer=function(a){return new d(a.toString())},d.prototype.toBuffer=function(){return t.copy(this._buffers.xprivkey)},d.DefaultDepth=0,d.DefaultFingerprint=0,d.DefaultChildIndex=0,d.Hardened=2147483648,d.MaxIndex=2*d.Hardened,d.RootElementAlias=["m","M","m'","M'"],d.VersionSize=4,d.DepthSize=1,d.ParentFingerPrintSize=4,d.ChildIndexSize=4,d.ChainCodeSize=32,d.PrivateKeySize=32,d.CheckSumSize=4,d.DataLength=78,d.SerializedByteSize=82,d.VersionStart=0,d.VersionEnd=d.VersionStart+d.VersionSize,d.DepthStart=d.VersionEnd,d.DepthEnd=d.DepthStart+d.DepthSize,d.ParentFingerPrintStart=d.DepthEnd,d.ParentFingerPrintEnd=d.ParentFingerPrintStart+d.ParentFingerPrintSize,d.ChildIndexStart=d.ParentFingerPrintEnd,d.ChildIndexEnd=d.ChildIndexStart+d.ChildIndexSize,d.ChainCodeStart=d.ChildIndexEnd,d.ChainCodeEnd=d.ChainCodeStart+d.ChainCodeSize,d.PrivateKeyStart=d.ChainCodeEnd+1,d.PrivateKeyEnd=d.PrivateKeyStart+d.PrivateKeySize,d.ChecksumStart=d.PrivateKeyEnd,d.ChecksumEnd=d.ChecksumStart+d.CheckSumSize,e(d.ChecksumEnd===d.SerializedByteSize),b.exports=d}).call(this,a("buffer").Buffer)},{"./crypto/bn":18,"./crypto/hash":20,"./crypto/point":21,"./crypto/random":22,"./encoding/base58":24,"./encoding/base58check":25,"./errors":29,"./hdkeycache":31,"./hdpublickey":33,"./networks":34,"./privatekey":36,"./util/buffer":53,"./util/js":54,"./util/preconditions":55,assert:88,buffer:103,lodash:79}],33:[function(a,b){(function(c){"use strict";function d(a){if(a instanceof d)return a;if(!(this instanceof d))return new d(a);if(a){if(e.isString(a)||u.isBuffer(a)){var b=d.getSerializedError(a);if(b){if(t.isValidJSON(a))return this._buildFromJSON(a);if(u.isBuffer(a)&&!d.getSerializedError(a.toString()))return this._buildFromSerialized(a.toString());if(b instanceof r.ArgumentIsPrivateExtended)return new k(a).hdPublicKey;throw b}return this._buildFromSerialized(a)}if(e.isObject(a))return a instanceof k?this._buildFromPrivate(a):this._buildFromObject(a);throw new r.UnrecognizedArgument(a)}throw new r.MustSupplyArgument}var e=a("lodash"),f=a("./util/preconditions"),g=a("./crypto/bn"),h=a("./encoding/base58"),i=a("./encoding/base58check"),j=a("./crypto/hash"),k=a("./hdprivatekey"),l=a("./hdkeycache"),m=a("./networks"),n=a("./crypto/point"),o=a("./publickey"),p=a("./errors"),q=p,r=p.HDPublicKey,s=a("assert"),t=a("./util/js"),u=a("./util/buffer");d.isValidPath=function(a){if(e.isString(a)){var b=k._getDerivationIndexes(a);return null!==b&&e.all(b,d.isValidPath)}return e.isNumber(a)?a>=0&&a=d.Hardened)throw new r.InvalidIndexCantDeriveHardened;if(0>a)throw new r.InvalidPath(a);var b=l.get(this.xpubkey,a,!1);if(b)return b;var c=u.integerAsBuffer(a),e=u.concat([this.publicKey.toBuffer(),c]),f=j.sha512hmac(e,this._buffers.chainCode),h=g.fromBuffer(f.slice(0,32),{size:32}),i=f.slice(32,64),k=o.fromPoint(n.getG().mul(h).add(this.publicKey.point)),m=new d({network:this.network,depth:this.depth+1,parentFingerPrint:this.fingerPrint,childIndex:a,chainCode:i,publicKey:k});return l.set(this.xpubkey,a,!1,m),m},d.prototype._deriveFromString=function(a){if(e.contains(a,"'"))throw new r.InvalidIndexCantDeriveHardened;if(!d.isValidPath(a))throw new r.InvalidPath(a);var b=k._getDerivationIndexes(a),c=b.reduce(function(a,b){return a._deriveWithNumber(b)},this);return c},d.isValidSerialized=function(a,b){return e.isNull(d.getSerializedError(a,b))},d.getSerializedError=function(a,b){if(!e.isString(a)&&!u.isBuffer(a))return new r.UnrecognizedArgument("expected buffer or string");if(!h.validCharacters(a))return new q.InvalidB58Char("(unknown)",a);try{a=i.decode(a)}catch(c){return new q.InvalidB58Checksum(a)}if(a.length!==d.DataSize)return new q.InvalidLength(a);if(!e.isUndefined(b)){var f=d._validateNetwork(a,b);if(f)return f}var g=u.integerFromBuffer(a.slice(0,4));return g===m.livenet.xprivkey||g===m.testnet.xprivkey?new r.ArgumentIsPrivateExtended:null},d._validateNetwork=function(a,b){var c=m.get(b);if(!c)return new q.InvalidNetworkArgument(b);var e=a.slice(d.VersionStart,d.VersionEnd);return u.integerFromBuffer(e)!==c.xpubkey?new q.InvalidNetwork(e):null},d.prototype._buildFromJSON=function(a){return this._buildFromObject(JSON.parse(a))},d.prototype._buildFromPrivate=function(a){var b=e.clone(a._buffers),c=n.getG().mul(g.fromBuffer(b.privateKey));return b.publicKey=n.pointToCompressed(c),b.version=u.integerAsBuffer(m.get(u.integerFromBuffer(b.version)).xpubkey),b.privateKey=void 0,b.checksum=void 0,b.xprivkey=void 0,this._buildFromBuffers(b)},d.prototype._buildFromObject=function(a){var b={version:a.network?u.integerAsBuffer(m.get(a.network).xpubkey):a.version,depth:e.isNumber(a.depth)?u.integerAsSingleByteBuffer(a.depth):a.depth,parentFingerPrint:e.isNumber(a.parentFingerPrint)?u.integerAsBuffer(a.parentFingerPrint):a.parentFingerPrint,childIndex:e.isNumber(a.childIndex)?u.integerAsBuffer(a.childIndex):a.childIndex,chainCode:e.isString(a.chainCode)?u.hexToBuffer(a.chainCode):a.chainCode,publicKey:e.isString(a.publicKey)?u.hexToBuffer(a.publicKey):u.isBuffer(a.publicKey)?a.publicKey:a.publicKey.toBuffer(),checksum:e.isNumber(a.checksum)?u.integerAsBuffer(a.checksum):a.checksum};return this._buildFromBuffers(b)},d.prototype._buildFromSerialized=function(a){var b=i.decode(a),c={version:b.slice(d.VersionStart,d.VersionEnd),depth:b.slice(d.DepthStart,d.DepthEnd),parentFingerPrint:b.slice(d.ParentFingerPrintStart,d.ParentFingerPrintEnd),childIndex:b.slice(d.ChildIndexStart,d.ChildIndexEnd),chainCode:b.slice(d.ChainCodeStart,d.ChainCodeEnd),publicKey:b.slice(d.PublicKeyStart,d.PublicKeyEnd),checksum:b.slice(d.ChecksumStart,d.ChecksumEnd),xpubkey:a};return this._buildFromBuffers(c)},d.prototype._buildFromBuffers=function(a){d._validateBufferArguments(a),t.defineImmutable(this,{_buffers:a});var b=[a.version,a.depth,a.parentFingerPrint,a.childIndex,a.chainCode,a.publicKey],e=u.concat(b),f=i.checksum(e);if(a.checksum&&a.checksum.length){if(a.checksum.toString("hex")!==f.toString("hex"))throw new q.InvalidB58Checksum(e,f)}else a.checksum=f;var g,h=m.get(u.integerFromBuffer(a.version));g=i.encode(u.concat(b)),a.xpubkey=new c(g);var k=new o(a.publicKey,{network:h}),l=d.ParentFingerPrintSize,n=j.sha256ripemd160(k.toBuffer()).slice(0,l);return t.defineImmutable(this,{xpubkey:g,network:h,depth:u.integerFromSingleByteBuffer(a.depth),publicKey:k,fingerPrint:n}),this},d._validateBufferArguments=function(a){var b=function(b,c){var d=a[b];s(u.isBuffer(d),b+" argument is not a buffer, it's "+typeof d),s(d.length===c,b+" has not the expected size: found "+d.length+", expected "+c)};b("version",d.VersionSize),b("depth",d.DepthSize),b("parentFingerPrint",d.ParentFingerPrintSize),b("childIndex",d.ChildIndexSize),b("chainCode",d.ChainCodeSize),b("publicKey",d.PublicKeySize),a.checksum&&a.checksum.length&&b("checksum",d.CheckSumSize)},d.fromJSON=function(a){return f.checkArgument(t.isValidJSON(a),"No valid JSON string was provided"),new d(a)},d.fromObject=function(a){return f.checkArgument(e.isObject(a),"No valid argument was provided"),new d(a)},d.fromString=function(a){return f.checkArgument(e.isString(a),"No valid string was provided"),new d(a)},d.prototype.toString=function(){return this.xpubkey},d.prototype.inspect=function(){return""},d.prototype.toObject=function(){return{network:m.get(u.integerFromBuffer(this._buffers.version)).name,depth:u.integerFromSingleByteBuffer(this._buffers.depth),fingerPrint:u.integerFromBuffer(this.fingerPrint),parentFingerPrint:u.integerFromBuffer(this._buffers.parentFingerPrint),childIndex:u.integerFromBuffer(this._buffers.childIndex),chainCode:u.bufferToHex(this._buffers.chainCode),publicKey:this.publicKey.toString(),checksum:u.integerFromBuffer(this._buffers.checksum),xpubkey:this.xpubkey}},d.prototype.toJSON=function(){return JSON.stringify(this.toObject())},d.fromBuffer=function(a){return new d(a)},d.prototype.toBuffer=function(){return u.copy(this._buffers.xpubkey)},d.Hardened=2147483648,d.RootElementAlias=["m","M"],d.VersionSize=4,d.DepthSize=1,d.ParentFingerPrintSize=4,d.ChildIndexSize=4,d.ChainCodeSize=32,d.PublicKeySize=33,d.CheckSumSize=4,d.DataSize=78,d.SerializedByteSize=82,d.VersionStart=0,d.VersionEnd=d.VersionStart+d.VersionSize,d.DepthStart=d.VersionEnd,d.DepthEnd=d.DepthStart+d.DepthSize,d.ParentFingerPrintStart=d.DepthEnd,d.ParentFingerPrintEnd=d.ParentFingerPrintStart+d.ParentFingerPrintSize,d.ChildIndexStart=d.ParentFingerPrintEnd,d.ChildIndexEnd=d.ChildIndexStart+d.ChildIndexSize,d.ChainCodeStart=d.ChildIndexEnd,d.ChainCodeEnd=d.ChainCodeStart+d.ChainCodeSize,d.PublicKeyStart=d.ChainCodeEnd,d.PublicKeyEnd=d.PublicKeyStart+d.PublicKeySize,d.ChecksumStart=d.PublicKeyEnd,d.ChecksumEnd=d.ChecksumStart+d.CheckSumSize,s(d.PublicKeyEnd===d.DataSize),s(d.ChecksumEnd===d.SerializedByteSize),b.exports=d}).call(this,a("buffer").Buffer)},{"./crypto/bn":18,"./crypto/hash":20,"./crypto/point":21,"./encoding/base58":24,"./encoding/base58check":25,"./errors":29,"./hdkeycache":31,"./hdprivatekey":32,"./networks":34,"./publickey":37,"./util/buffer":53,"./util/js":54,"./util/preconditions":55,assert:88,buffer:103,lodash:79}],34:[function(a,b){"use strict";function c(){}function d(a,b){if(~h.indexOf(a))return a;if(b){for(var c in h)if(h[c][b]===a)return h[c];return void 0}return i[a]}function e(a){var b=new c;return f.extend(b,{name:a.name,alias:a.alias,pubkeyhash:a.pubkeyhash,privatekey:a.privatekey,scripthash:a.scripthash,xpubkey:a.xpubkey,xprivkey:a.xprivkey,networkMagic:g.integerAsBuffer(a.networkMagic),port:a.port,dnsSeeds:a.dnsSeeds}),f.each(f.values(b),function(a){f.isObject(a)||(i[a]=b)}),h.push(b),b}var f=a("lodash"),g=a("./util/buffer"),h=[],i={};c.prototype.toString=function(){return this.name},e({name:"livenet",alias:"mainnet",pubkeyhash:0,privatekey:128,scripthash:5,xpubkey:76067358,xprivkey:76066276,networkMagic:4190024921,port:8333,dnsSeeds:["seed.bitcoin.sipa.be","dnsseed.bluematt.me","dnsseed.bitcoin.dashjr.org","seed.bitcoinstats.com","seed.bitnodes.io","bitseed.xf2.org"]}),e({name:"testnet",alias:"testnet",pubkeyhash:111,privatekey:239,scripthash:196,xpubkey:70617039,xprivkey:70615956,networkMagic:185665799,port:18333,dnsSeeds:["testnet-seed.bitcoin.petertodd.org","testnet-seed.bluematt.me","testnet-seed.alexykot.me","testnet-seed.bitcoin.schildbach.de"]});var j=d("livenet"),k=d("testnet");b.exports={add:e,defaultNetwork:j,livenet:j,mainnet:j,testnet:k,get:d}},{"./util/buffer":53,lodash:79}],35:[function(a,b){(function(c){"use strict";function d(a){if(!(this instanceof d))return new d(a);var b;if(e.isNumber(a))b=a;else{if(!e.isString(a))throw new TypeError('Unrecognized num type: "'+typeof a+'" for Opcode');b=d.map[a]}return h.defineImmutable(this,{num:b}),this}var e=a("lodash"),f=a("./util/preconditions"),g=a("./util/buffer"),h=a("./util/js");d.fromBuffer=function(a){return f.checkArgument(g.isBuffer(a)),new d(Number("0x"+a.toString("hex")))},d.fromNumber=function(a){return f.checkArgument(e.isNumber(a)),new d(a)},d.fromString=function(a){f.checkArgument(e.isString(a));var b=d.map[a];if("undefined"==typeof b)throw new TypeError("Invalid opcodestr"); return new d(b)},d.prototype.toHex=function(){return this.num.toString(16)},d.prototype.toBuffer=function(){return new c(this.toHex(),"hex")},d.prototype.toNumber=function(){return this.num},d.prototype.toString=function(){var a=d.reverseMap[this.num];if("undefined"==typeof a)throw new Error("Opcode does not have a string representation");return a},d.smallInt=function(a){return f.checkArgument(a>=0&&16>=a,"Invalid Argument: n must be between 0 and 16"),0===a?d("OP_0"):new d(d.map.OP_1+a-1)},d.map={OP_FALSE:0,OP_0:0,OP_PUSHDATA1:76,OP_PUSHDATA2:77,OP_PUSHDATA4:78,OP_1NEGATE:79,OP_RESERVED:80,OP_TRUE:81,OP_1:81,OP_2:82,OP_3:83,OP_4:84,OP_5:85,OP_6:86,OP_7:87,OP_8:88,OP_9:89,OP_10:90,OP_11:91,OP_12:92,OP_13:93,OP_14:94,OP_15:95,OP_16:96,OP_NOP:97,OP_VER:98,OP_IF:99,OP_NOTIF:100,OP_VERIF:101,OP_VERNOTIF:102,OP_ELSE:103,OP_ENDIF:104,OP_VERIFY:105,OP_RETURN:106,OP_TOALTSTACK:107,OP_FROMALTSTACK:108,OP_2DROP:109,OP_2DUP:110,OP_3DUP:111,OP_2OVER:112,OP_2ROT:113,OP_2SWAP:114,OP_IFDUP:115,OP_DEPTH:116,OP_DROP:117,OP_DUP:118,OP_NIP:119,OP_OVER:120,OP_PICK:121,OP_ROLL:122,OP_ROT:123,OP_SWAP:124,OP_TUCK:125,OP_CAT:126,OP_SUBSTR:127,OP_LEFT:128,OP_RIGHT:129,OP_SIZE:130,OP_INVERT:131,OP_AND:132,OP_OR:133,OP_XOR:134,OP_EQUAL:135,OP_EQUALVERIFY:136,OP_RESERVED1:137,OP_RESERVED2:138,OP_1ADD:139,OP_1SUB:140,OP_2MUL:141,OP_2DIV:142,OP_NEGATE:143,OP_ABS:144,OP_NOT:145,OP_0NOTEQUAL:146,OP_ADD:147,OP_SUB:148,OP_MUL:149,OP_DIV:150,OP_MOD:151,OP_LSHIFT:152,OP_RSHIFT:153,OP_BOOLAND:154,OP_BOOLOR:155,OP_NUMEQUAL:156,OP_NUMEQUALVERIFY:157,OP_NUMNOTEQUAL:158,OP_LESSTHAN:159,OP_GREATERTHAN:160,OP_LESSTHANOREQUAL:161,OP_GREATERTHANOREQUAL:162,OP_MIN:163,OP_MAX:164,OP_WITHIN:165,OP_RIPEMD160:166,OP_SHA1:167,OP_SHA256:168,OP_HASH160:169,OP_HASH256:170,OP_CODESEPARATOR:171,OP_CHECKSIG:172,OP_CHECKSIGVERIFY:173,OP_CHECKMULTISIG:174,OP_CHECKMULTISIGVERIFY:175,OP_NOP1:176,OP_NOP2:177,OP_NOP3:178,OP_NOP4:179,OP_NOP5:180,OP_NOP6:181,OP_NOP7:182,OP_NOP8:183,OP_NOP9:184,OP_NOP10:185,OP_PUBKEYHASH:253,OP_PUBKEY:254,OP_INVALIDOPCODE:255},d.reverseMap=[];for(var i in d.map)d.reverseMap[d.map[i]]=i;e.extend(d,d.map),d.isSmallIntOp=function(a){return a instanceof d&&(a=a.toNumber()),a===d.map.OP_0||a>=d.map.OP_1&&a<=d.map.OP_16},d.prototype.inspect=function(){return""},b.exports=d}).call(this,a("buffer").Buffer)},{"./util/buffer":53,"./util/js":54,"./util/preconditions":55,buffer:103,lodash:79}],36:[function(a,b){(function(c){"use strict";var d=a("lodash"),e=a("./address"),f=a("./encoding/base58check"),g=a("./crypto/bn"),h=a("./util/js"),i=a("./networks"),j=a("./crypto/point"),k=a("./publickey"),l=a("./crypto/random"),m=function n(a,b){if(!(this instanceof n))return new n(a,b);if(a instanceof n)return a;var c=this._classifyArguments(a,b);if(!c.bn||0===c.bn.cmp(new g(0)))throw new TypeError("Number can not be equal to zero, undefined, null or false");if(!c.bn.lt(j.getN()))throw new TypeError("Number must be less than N");if("undefined"==typeof c.network)throw new TypeError('Must specify the network ("livenet" or "testnet")');return h.defineImmutable(this,{bn:c.bn,compressed:c.compressed,network:c.network}),Object.defineProperty(this,"publicKey",{configurable:!1,enumerable:!0,get:this.toPublicKey.bind(this)}),this};m.prototype._classifyArguments=function(a,b){var e={compressed:!0,network:b?i.get(b):i.defaultNetwork};if(d.isUndefined(a)||d.isNull(a))e.bn=m._getRandomBN();else if(a instanceof g)e.bn=a;else if(a instanceof c||a instanceof Uint8Array)e=m._transformBuffer(a,b);else if(m._isJSON(a))e=m._transformJSON(a);else if(!b&&i.get(a))e.bn=m._getRandomBN(),e.network=i.get(a);else{if("string"!=typeof a)throw new TypeError("First argument is an unrecognized data type.");h.isHexa(a)?e.bn=new g(new c(a,"hex")):e=m._transformWIF(a,b)}return e},m._getRandomBN=function(){var a,b;do{var c=l.getRandomBuffer(32);b=g.fromBuffer(c),a=b.lt(j.getN())}while(!a);return b},m._isJSON=function(a){return h.isValidJSON(a)||a.bn&&a.network},m._transformBuffer=function(a,b){var c={};if(32===a.length)return m._transformBNBuffer(a,b);if(c.network=i.get(a[0],"privatekey"),a[0]===i.livenet.privatekey)c.network=i.livenet;else{if(a[0]!==i.testnet.privatekey)throw new Error("Invalid network");c.network=i.testnet}if(b&&c.network!==i.get(b))throw new TypeError("Private key network mismatch");if(34===a.length&&1===a[33])c.compressed=!0;else{if(33!==a.length)throw new Error("Length of buffer must be 33 (uncompressed) or 34 (compressed)");c.compressed=!1}return c.bn=g.fromBuffer(a.slice(1,33)),c},m._transformBNBuffer=function(a,b){var c={};return c.network=i.get(b)||i.defaultNetwork,c.bn=g.fromBuffer(a),c.compressed=!1,c},m._transformWIF=function(a,b){return m._transformBuffer(f.decode(a),b)},m.fromJSON=function(a){if(!m._isJSON(a))throw new TypeError("Must be a valid JSON string or plain object");return new m(a)},m.fromBuffer=function(a,b){return new m(a,b)},m._transformJSON=function(a){h.isValidJSON(a)&&(a=JSON.parse(a));var b=new g(a.bn,"hex");return{bn:b,network:a.network,compressed:a.compressed}},m.fromString=m.fromWIF=function(a){return new m(a)},m.fromRandom=function(a){var b=m._getRandomBN();return new m(b,a)},m.getValidationError=function(a,b){var c;try{new m(a,b)}catch(d){c=d}return c},m.isValid=function(a,b){return a?!m.getValidationError(a,b):!1},m.prototype.toString=function(){return this.toBuffer().toString("hex")},m.prototype.toWIF=function(){var a,b=this.network,d=this.compressed;return a=c.concat(d?[new c([b.privatekey]),this.bn.toBuffer({size:32}),new c([1])]:[new c([b.privatekey]),this.bn.toBuffer({size:32})]),f.encode(a)},m.prototype.toBigNumber=function(){return this.bn},m.prototype.toBuffer=function(){return this.bn.toBuffer()},m.prototype.toPublicKey=function(){return this._pubkey||(this._pubkey=k.fromPrivateKey(this)),this._pubkey},m.prototype.toAddress=function(a){var b=this.toPublicKey();return e.fromPublicKey(b,a||this.network)},m.prototype.toObject=function(){return{bn:this.bn.toString("hex"),compressed:this.compressed,network:this.network.toString()}},m.prototype.toJSON=function(){return JSON.stringify(this.toObject())},m.prototype.inspect=function(){var a=this.compressed?"":", uncompressed";return""},b.exports=m}).call(this,a("buffer").Buffer)},{"./address":13,"./crypto/bn":18,"./crypto/point":21,"./crypto/random":22,"./encoding/base58check":25,"./networks":34,"./publickey":37,"./util/js":54,buffer:103,lodash:79}],37:[function(a,b){(function(c){"use strict";var d=a("./address"),e=a("./crypto/bn"),f=a("./crypto/point"),g=a("./crypto/hash"),h=a("./util/js"),i=a("./networks"),j=a("lodash"),k=a("./util/preconditions"),l=function m(a,b){if(!(this instanceof m))return new m(a,b);if(k.checkArgument(a,new TypeError("First argument is required, please include public key data.")),a instanceof m)return a;b=b||{};var c=this._classifyArgs(a,b);return c.point.validate(),h.defineImmutable(this,{point:c.point,compressed:c.compressed,network:c.network||i.defaultNetwork}),this};l.prototype._classifyArgs=function(a,b){var d={compressed:j.isUndefined(b.compressed)||b.compressed};if(a instanceof f)d.point=a;else if(l._isJSON(a))d=l._transformJSON(a);else if("string"==typeof a)d=l._transformDER(new c(a,"hex"));else if(l._isBuffer(a))d=l._transformDER(a);else{if(!l._isPrivateKey(a))throw new TypeError("First argument is an unrecognized data format.");d=l._transformPrivateKey(a)}return d.network||(d.network=j.isUndefined(b.network)?void 0:i.get(b.network)),d},l._isPrivateKey=function(b){var c=a("./privatekey");return b instanceof c},l._isBuffer=function(a){return a instanceof c||a instanceof Uint8Array},l._isJSON=function(a){return!!(h.isValidJSON(a)||a.x&&a.y)},l._transformPrivateKey=function(a){k.checkArgument(l._isPrivateKey(a),new TypeError("Must be an instance of PrivateKey"));var b={};return b.point=f.getG().mul(a.bn),b.compressed=a.compressed,b.network=a.network,b},l._transformDER=function(a,b){k.checkArgument(l._isBuffer(a),new TypeError("Must be a hex buffer of DER encoded public key"));var c={};b=j.isUndefined(b)?!0:b;var d,g,h,i;if(4!==a[0]&&(b||6!==a[0]&&7!==a[0]))if(3===a[0])h=a.slice(1),d=new e(h),c=l._transformX(!0,d),c.compressed=!0;else{if(2!==a[0])throw new TypeError("Invalid DER format public key");h=a.slice(1),d=new e(h),c=l._transformX(!1,d),c.compressed=!0}else{if(h=a.slice(1,33),i=a.slice(33,65),32!==h.length||32!==i.length||65!==a.length)throw new TypeError("Length of x and y must be 32 bytes");d=new e(h),g=new e(i),c.point=new f(d,g),c.compressed=!1}return c},l._transformX=function(a,b){k.checkArgument("boolean"==typeof a,new TypeError("Must specify whether y is odd or not (true or false)"));var c={};return c.point=f.fromX(a,b),c},l.fromJSON=function(a){return k.checkArgument(l._isJSON(a),new TypeError("Must be a valid JSON string or plain object")),new l(a)},l._transformJSON=function(a){h.isValidJSON(a)&&(a=JSON.parse(a));var b=new e(a.x,"hex"),c=new e(a.y,"hex"),d=new f(b,c);return new l(d,{compressed:a.compressed})},l.fromPrivateKey=function(a){k.checkArgument(l._isPrivateKey(a),new TypeError("Must be an instance of PrivateKey"));var b=l._transformPrivateKey(a);return new l(b.point,{compressed:b.compressed,network:b.network})},l.fromDER=l.fromBuffer=function(a,b){k.checkArgument(l._isBuffer(a),new TypeError("Must be a hex buffer of DER encoded public key"));var c=l._transformDER(a,b);return new l(c.point,{compressed:c.compressed})},l.fromPoint=function(a,b){return k.checkArgument(a instanceof f,new TypeError("First argument must be an instance of Point.")),new l(a,{compressed:b})},l.fromString=function(a,b){var d=new c(a,b||"hex"),e=l._transformDER(d);return new l(e.point,{compressed:e.compressed})},l.fromX=function(a,b){var c=l._transformX(a,b);return new l(c.point,{compressed:c.compressed})},l.getValidationError=function(a){var b;try{new l(a)}catch(c){b=c}return b},l.isValid=function(a){return!l.getValidationError(a)},l.prototype.toObject=function(){return{x:this.point.getX().toString("hex"),y:this.point.getY().toString("hex"),compressed:this.compressed}},l.prototype.toJSON=function(){return JSON.stringify(this.toObject())},l.prototype.toBuffer=l.prototype.toDER=function(){var a,b=this.point.getX(),d=this.point.getY(),e=b.toBuffer({size:32}),f=d.toBuffer({size:32});if(this.compressed){var g=f[f.length-1]%2;return a=new c(g?[3]:[2]),c.concat([a,e])}return a=new c([4]),c.concat([a,e,f])},l.prototype._getID=function(){return g.sha256ripemd160(this.toBuffer())},l.prototype.toAddress=function(a){return d.fromPublicKey(this,a||this.network)},l.prototype.toString=function(){return this.toDER().toString("hex")},l.prototype.inspect=function(){return""},b.exports=l}).call(this,a("buffer").Buffer)},{"./address":13,"./crypto/bn":18,"./crypto/hash":20,"./crypto/point":21,"./networks":34,"./privatekey":36,"./util/js":54,"./util/preconditions":55,buffer:103,lodash:79}],38:[function(a,b){b.exports=a("./script"),b.exports.Interpreter=a("./interpreter")},{"./interpreter":39,"./script":40}],39:[function(a,b){(function(c){"use strict";var d=a("lodash"),e=a("./script"),f=a("../opcode"),g=a("../crypto/bn"),h=a("../crypto/hash"),i=a("../crypto/signature"),j=a("../publickey"),k=function l(a){return this instanceof l?void(a?(this.initialize(),this.set(a)):this.initialize()):new l(a)};k.prototype.verify=function(b,c,f,g,h){var i=a("../transaction");d.isUndefined(f)&&(f=new i),d.isUndefined(g)&&(g=0),d.isUndefined(h)&&(h=0),this.set({script:b,tx:f,nin:g,flags:h});var j;if(0!==(h&k.SCRIPT_VERIFY_SIGPUSHONLY)&&!b.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1;if(!this.evaluate())return!1;h&k.SCRIPT_VERIFY_P2SH&&(j=this.stack.slice());var l=this.stack;if(this.initialize(),this.set({script:c,stack:l,tx:f,nin:g,flags:h}),!this.evaluate())return!1;if(0===this.stack.length)return this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_RESULT",!1;var m=this.stack[this.stack.length-1];if(!k.castToBool(m))return this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_STACK",!1;if(h&k.SCRIPT_VERIFY_P2SH&&c.isScriptHashOut()){if(!b.isPushOnly())return this.errstr="SCRIPT_ERR_SIG_PUSHONLY",!1;if(0===j.length)throw new Error("internal error - stack copy empty");var n=j[j.length-1],o=e.fromBuffer(n);return j.pop(),this.initialize(),this.set({script:o,stack:j,tx:f,nin:g,flags:h}),this.evaluate()?0===j.length?(this.errstr="SCRIPT_ERR_EVAL_FALSE_NO_P2SH_STACK",!1):k.castToBool(j[j.length-1])?!0:(this.errstr="SCRIPT_ERR_EVAL_FALSE_IN_P2SH_STACK",!1):!1}return!0},b.exports=k,k.prototype.initialize=function(){this.stack=[],this.altstack=[],this.pc=0,this.pbegincodehash=0,this.nOpCount=0,this.vfExec=[],this.errstr="",this.flags=0},k.prototype.set=function(a){this.script=a.script||this.script,this.tx=a.tx||this.tx,this.nin="undefined"!=typeof a.nin?a.nin:this.nin,this.stack=a.stack||this.stack,this.altstack=a.altack||this.altstack,this.pc="undefined"!=typeof a.pc?a.pc:this.pc,this.pbegincodehash="undefined"!=typeof a.pbegincodehash?a.pbegincodehash:this.pbegincodehash,this.nOpCount="undefined"!=typeof a.nOpCount?a.nOpCount:this.nOpCount,this.vfExec=a.vfExec||this.vfExec,this.errstr=a.errstr||this.errstr,this.flags="undefined"!=typeof a.flags?a.flags:this.flags},k["true"]=new c([1]),k["false"]=new c([]),k.MAX_SCRIPT_ELEMENT_SIZE=520,k.SCRIPT_VERIFY_NONE=0,k.SCRIPT_VERIFY_P2SH=1,k.SCRIPT_VERIFY_STRICTENC=2,k.SCRIPT_VERIFY_DERSIG=4,k.SCRIPT_VERIFY_LOW_S=8,k.SCRIPT_VERIFY_NULLDUMMY=16,k.SCRIPT_VERIFY_SIGPUSHONLY=32,k.SCRIPT_VERIFY_MINIMALDATA=64,k.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS=128,k.castToBool=function(a){for(var b=0;b1e4)return this.errstr="SCRIPT_ERR_SCRIPT_SIZE",!1;try{for(;this.pc1e3)return this.errstr="SCRIPT_ERR_STACK_SIZE",!1}catch(b){return this.errstr="SCRIPT_ERR_UNKNOWN_ERROR: "+b,!1}return this.vfExec.length>0?(this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1):!0},k.prototype.step=function(){var a,b,c,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z=0!==(this.flags&k.SCRIPT_VERIFY_MINIMALDATA),A=-1===this.vfExec.indexOf(!1),B=this.script.chunks[this.pc];this.pc++;var C=B.opcodenum;if(d.isUndefined(C))return this.errstr="SCRIPT_ERR_UNDEFINED_OPCODE",!1;if(B.buf&&B.buf.length>k.MAX_SCRIPT_ELEMENT_SIZE)return this.errstr="SCRIPT_ERR_PUSH_SIZE",!1;if(C>f.OP_16&&++this.nOpCount>201)return this.errstr="SCRIPT_ERR_OP_COUNT",!1;if(C===f.OP_CAT||C===f.OP_SUBSTR||C===f.OP_LEFT||C===f.OP_RIGHT||C===f.OP_INVERT||C===f.OP_AND||C===f.OP_OR||C===f.OP_XOR||C===f.OP_2MUL||C===f.OP_2DIV||C===f.OP_MUL||C===f.OP_DIV||C===f.OP_MOD||C===f.OP_LSHIFT||C===f.OP_RSHIFT)return this.errstr="SCRIPT_ERR_DISABLED_OPCODE",!1;if(A&&C>=0&&C<=f.OP_PUSHDATA4){if(z&&!this.script.checkMinimalPush(this.pc-1))return this.errstr="SCRIPT_ERR_MINIMALDATA",!1;if(B.buf){if(B.len!==B.buf.length)throw new Error("Length of push value not equal to length of data");this.stack.push(B.buf)}else this.stack.push(k["false"])}else if(A||f.OP_IF<=C&&C<=f.OP_ENDIF)switch(C){case f.OP_1NEGATE:case f.OP_1:case f.OP_2:case f.OP_3:case f.OP_4:case f.OP_5:case f.OP_6:case f.OP_7:case f.OP_8:case f.OP_9:case f.OP_10:case f.OP_11:case f.OP_12:case f.OP_13:case f.OP_14:case f.OP_15:case f.OP_16:m=C-(f.OP_1-1),a=new g(m).toScriptNumBuffer(),this.stack.push(a);break;case f.OP_NOP:break;case f.OP_NOP1:case f.OP_NOP2:case f.OP_NOP3:case f.OP_NOP4:case f.OP_NOP5:case f.OP_NOP6:case f.OP_NOP7:case f.OP_NOP8:case f.OP_NOP9:case f.OP_NOP10:if(this.flags&k.SCRIPT_VERIFY_DISCOURAGE_UPGRADABLE_NOPS)return this.errstr="SCRIPT_ERR_DISCOURAGE_UPGRADABLE_NOPS",!1;break;case f.OP_IF:case f.OP_NOTIF:if(x=!1,A){if(this.stack.length<1)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;a=this.stack.pop(),x=k.castToBool(a),C===f.OP_NOTIF&&(x=!x)}this.vfExec.push(x);break;case f.OP_ELSE:if(0===this.vfExec.length)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;this.vfExec[this.vfExec.length-1]=!this.vfExec[this.vfExec.length-1];break;case f.OP_ENDIF:if(0===this.vfExec.length)return this.errstr="SCRIPT_ERR_UNBALANCED_CONDITIONAL",!1;this.vfExec.pop();break;case f.OP_VERIFY:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(a=this.stack[this.stack.length-1],x=k.castToBool(a),!x)return this.errstr="SCRIPT_ERR_VERIFY",!1;this.stack.pop();break;case f.OP_RETURN:return this.errstr="SCRIPT_ERR_OP_RETURN",!1;case f.OP_TOALTSTACK:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.altstack.push(this.stack.pop());break;case f.OP_FROMALTSTACK:if(this.altstack.length<1)return this.errstr="SCRIPT_ERR_INVALID_ALTSTACK_OPERATION",!1;this.stack.push(this.altstack.pop());break;case f.OP_2DROP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop(),this.stack.pop();break;case f.OP_2DUP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;b=this.stack[this.stack.length-2],c=this.stack[this.stack.length-1],this.stack.push(b),this.stack.push(c);break;case f.OP_3DUP:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;b=this.stack[this.stack.length-3],c=this.stack[this.stack.length-2];var D=this.stack[this.stack.length-1];this.stack.push(b),this.stack.push(c),this.stack.push(D);break;case f.OP_2OVER:if(this.stack.length<4)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;b=this.stack[this.stack.length-4],c=this.stack[this.stack.length-3],this.stack.push(b),this.stack.push(c);break;case f.OP_2ROT:if(this.stack.length<6)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;l=this.stack.splice(this.stack.length-6,2),this.stack.push(l[0]),this.stack.push(l[1]);break;case f.OP_2SWAP:if(this.stack.length<4)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;l=this.stack.splice(this.stack.length-4,2),this.stack.push(l[0]),this.stack.push(l[1]);break;case f.OP_IFDUP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;a=this.stack[this.stack.length-1],x=k.castToBool(a),x&&this.stack.push(a);break;case f.OP_DEPTH:a=new g(this.stack.length).toScriptNumBuffer(),this.stack.push(a);break;case f.OP_DROP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.pop();break;case f.OP_DUP:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.push(this.stack[this.stack.length-1]);break;case f.OP_NIP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.splice(this.stack.length-2,1);break;case f.OP_OVER:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.push(this.stack[this.stack.length-2]);break;case f.OP_PICK:case f.OP_ROLL:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(a=this.stack[this.stack.length-1],p=g.fromScriptNumBuffer(a,z),m=p.toNumber(),this.stack.pop(),0>m||m>=this.stack.length)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;a=this.stack[this.stack.length-m-1],C===f.OP_ROLL&&this.stack.splice(this.stack.length-m-1,1),this.stack.push(a);break;case f.OP_ROT:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;n=this.stack[this.stack.length-3],o=this.stack[this.stack.length-2];var E=this.stack[this.stack.length-1];this.stack[this.stack.length-3]=o,this.stack[this.stack.length-2]=E,this.stack[this.stack.length-1]=n;break;case f.OP_SWAP:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;n=this.stack[this.stack.length-2],o=this.stack[this.stack.length-1],this.stack[this.stack.length-2]=o,this.stack[this.stack.length-1]=n;break;case f.OP_TUCK:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;this.stack.splice(this.stack.length-2,0,this.stack[this.stack.length-1]);break;case f.OP_SIZE:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;p=new g(this.stack[this.stack.length-1].length),this.stack.push(p.toScriptNumBuffer());break;case f.OP_EQUAL:case f.OP_EQUALVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;b=this.stack[this.stack.length-2],c=this.stack[this.stack.length-1];var F=b.toString("hex")===c.toString("hex");if(this.stack.pop(),this.stack.pop(),this.stack.push(F?k["true"]:k["false"]),C===f.OP_EQUALVERIFY){if(!F)return this.errstr="SCRIPT_ERR_EQUALVERIFY",!1;this.stack.pop()}break;case f.OP_1ADD:case f.OP_1SUB:case f.OP_NEGATE:case f.OP_ABS:case f.OP_NOT:case f.OP_0NOTEQUAL:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(a=this.stack[this.stack.length-1],p=g.fromScriptNumBuffer(a,z),C){case f.OP_1ADD:p=p.add(g.One);break;case f.OP_1SUB:p=p.sub(g.One);break;case f.OP_NEGATE:p=p.neg();break;case f.OP_ABS:p.cmp(g.Zero)<0&&(p=p.neg());break;case f.OP_NOT:p=new g((0===p.cmp(g.Zero))+0);break;case f.OP_0NOTEQUAL:p=new g((0!==p.cmp(g.Zero))+0)}this.stack.pop(),this.stack.push(p.toScriptNumBuffer());break;case f.OP_ADD:case f.OP_SUB:case f.OP_BOOLAND:case f.OP_BOOLOR:case f.OP_NUMEQUAL:case f.OP_NUMEQUALVERIFY:case f.OP_NUMNOTEQUAL:case f.OP_LESSTHAN:case f.OP_GREATERTHAN:case f.OP_LESSTHANOREQUAL:case f.OP_GREATERTHANOREQUAL:case f.OP_MIN:case f.OP_MAX:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;switch(q=g.fromScriptNumBuffer(this.stack[this.stack.length-2],z),r=g.fromScriptNumBuffer(this.stack[this.stack.length-1],z),p=new g(0),C){case f.OP_ADD:p=q.add(r);break;case f.OP_SUB:p=q.sub(r);break;case f.OP_BOOLAND:p=new g((0!==q.cmp(g.Zero)&&0!==r.cmp(g.Zero))+0);break;case f.OP_BOOLOR:p=new g((0!==q.cmp(g.Zero)||0!==r.cmp(g.Zero))+0);break;case f.OP_NUMEQUAL:p=new g((0===q.cmp(r))+0);break;case f.OP_NUMEQUALVERIFY:p=new g((0===q.cmp(r))+0);break;case f.OP_NUMNOTEQUAL:p=new g((0!==q.cmp(r))+0);break;case f.OP_LESSTHAN:p=new g((q.cmp(r)<0)+0);break;case f.OP_GREATERTHAN:p=new g((q.cmp(r)>0)+0);break;case f.OP_LESSTHANOREQUAL:p=new g((q.cmp(r)<=0)+0);break;case f.OP_GREATERTHANOREQUAL:p=new g((q.cmp(r)>=0)+0);break;case f.OP_MIN:p=q.cmp(r)<0?q:r;break;case f.OP_MAX:p=q.cmp(r)>0?q:r}if(this.stack.pop(),this.stack.pop(),this.stack.push(p.toScriptNumBuffer()),C===f.OP_NUMEQUALVERIFY){if(!k.castToBool(this.stack[this.stack.length-1]))return this.errstr="SCRIPT_ERR_NUMEQUALVERIFY",!1;this.stack.pop()}break;case f.OP_WITHIN:if(this.stack.length<3)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;q=g.fromScriptNumBuffer(this.stack[this.stack.length-3],z),r=g.fromScriptNumBuffer(this.stack[this.stack.length-2],z);var G=g.fromScriptNumBuffer(this.stack[this.stack.length-1],z);x=r.cmp(q)<=0&&q.cmp(G)<0,this.stack.pop(),this.stack.pop(),this.stack.pop(),this.stack.push(x?k["true"]:k["false"]);break;case f.OP_RIPEMD160:case f.OP_SHA1:case f.OP_SHA256:case f.OP_HASH160:case f.OP_HASH256:if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;a=this.stack[this.stack.length-1];var H;C===f.OP_RIPEMD160?H=h.ripemd160(a):C===f.OP_SHA1?H=h.sha1(a):C===f.OP_SHA256?H=h.sha256(a):C===f.OP_HASH160?H=h.sha256ripemd160(a):C===f.OP_HASH256&&(H=h.sha256sha256(a)),this.stack.pop(),this.stack.push(H);break;case f.OP_CODESEPARATOR:this.pbegincodehash=this.pc;break;case f.OP_CHECKSIG:case f.OP_CHECKSIGVERIFY:if(this.stack.length<2)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;s=this.stack[this.stack.length-2],t=this.stack[this.stack.length-1],u=(new e).set({chunks:this.script.chunks.slice(this.pbegincodehash)});var I=(new e).add(s);if(u.findAndDelete(I),!this.checkSignatureEncoding(s)||!this.checkPubkeyEncoding(t))return!1;try{v=i.fromTxFormat(s),w=j.fromBuffer(t,!1),y=this.tx.verifySignature(v,w,this.nin,u)}catch(J){y=!1}if(this.stack.pop(),this.stack.pop(),this.stack.push(y?k["true"]:k["false"]),C===f.OP_CHECKSIGVERIFY){if(!y)return this.errstr="SCRIPT_ERR_CHECKSIGVERIFY",!1;this.stack.pop()}break;case f.OP_CHECKMULTISIG:case f.OP_CHECKMULTISIGVERIFY:var K=1;if(this.stack.lengthL||L>20)return this.errstr="SCRIPT_ERR_PUBKEY_COUNT",!1;if(this.nOpCount+=L,this.nOpCount>201)return this.errstr="SCRIPT_ERR_OP_COUNT",!1;var M=++K;if(K+=L,this.stack.lengthN||N>L)return this.errstr="SCRIPT_ERR_SIG_COUNT",!1;var O=++K;if(K+=N,this.stack.lengthP;P++)s=this.stack[this.stack.length-O-P],u.findAndDelete((new e).add(s));for(y=!0;y&&N>0;){if(s=this.stack[this.stack.length-O],t=this.stack[this.stack.length-M],!this.checkSignatureEncoding(s)||!this.checkPubkeyEncoding(t))return!1;var Q;try{v=i.fromTxFormat(s),w=j.fromBuffer(t,!1),Q=this.tx.verifySignature(v,w,this.nin,u)}catch(J){Q=!1}Q&&(O++,N--),M++,L--,N>L&&(y=!1)}for(;K-->1;)this.stack.pop();if(this.stack.length<1)return this.errstr="SCRIPT_ERR_INVALID_STACK_OPERATION",!1;if(this.flags&k.SCRIPT_VERIFY_NULLDUMMY&&this.stack[this.stack.length-1].length)return this.errstr="SCRIPT_ERR_SIG_NULLDUMMY",!1;if(this.stack.pop(),this.stack.push(y?k["true"]:k["false"]),C===f.OP_CHECKMULTISIGVERIFY){if(!y)return this.errstr="SCRIPT_ERR_CHECKMULTISIGVERIFY",!1;this.stack.pop()}break;default:return this.errstr="SCRIPT_ERR_BAD_OPCODE",!1}return!0}}).call(this,a("buffer").Buffer)},{"../crypto/bn":18,"../crypto/hash":20,"../crypto/signature":23,"../opcode":35,"../publickey":37,"../transaction":41,"./script":40,buffer:103,lodash:79}],40:[function(a,b){(function(c){"use strict";var d=a("../address"),e=a("../encoding/bufferreader"),f=a("../encoding/bufferwriter"),g=a("../crypto/hash"),h=a("../opcode"),i=a("../publickey"),j=a("../crypto/signature"),k=a("../networks"),l=a("../util/preconditions"),m=a("lodash"),n=a("../errors"),o=a("buffer"),p=a("../util/buffer"),q=a("../util/js"),r=function s(a){return this instanceof s?(this.chunks=[],p.isBuffer(a)?s.fromBuffer(a):a instanceof d?s.fromAddress(a):a instanceof s?s.fromBuffer(a.toBuffer()):"string"==typeof a?s.fromString(a):void("undefined"!=typeof a&&this.set(a))):new s(a)};r.prototype.set=function(a){return this.chunks=a.chunks||this.chunks,this},r.fromBuffer=function(a){var b=new r;b.chunks=[];for(var c=new e(a);!c.finished();){var d,f,g=c.readUInt8();g>0&&g0&&i0&&(a=a+" 0x"+c.buf.toString("hex"));else if("undefined"!=typeof h.reverseMap[d])a=a+" "+h(d).toString();else{var e=d.toString(16);e.length%2!==0&&(e="0"+e),a=a+" 0x"+e}}return a.substr(1)},r.prototype.toHex=function(){return this.toBuffer().toString("hex")},r.prototype.inspect=function(){return""},r.prototype.isPublicKeyHashOut=function(){return!(5!==this.chunks.length||this.chunks[0].opcodenum!==h.OP_DUP||this.chunks[1].opcodenum!==h.OP_HASH160||!this.chunks[2].buf||this.chunks[3].opcodenum!==h.OP_EQUALVERIFY||this.chunks[4].opcodenum!==h.OP_CHECKSIG)},r.prototype.isPublicKeyHashIn=function(){return 2===this.chunks.length&&this.chunks[0].buf&&this.chunks[0].buf.length>=71&&this.chunks[0].buf.length<=73&&i.isValid(this.chunks[1].buf)},r.prototype.getPublicKeyHash=function(){return l.checkState(this.isPublicKeyHashOut(),"Can't retrieve PublicKeyHash from a non-PKH output"),this.chunks[2].buf},r.prototype.isPublicKeyOut=function(){return 2===this.chunks.length&&p.isBuffer(this.chunks[0].buf)&&i.isValid(this.chunks[0].buf)&&this.chunks[1].opcodenum===h.OP_CHECKSIG},r.prototype.isPublicKeyIn=function(){return 1===this.chunks.length&&p.isBuffer(this.chunks[0].buf)&&71===this.chunks[0].buf.length},r.prototype.isScriptHashOut=function(){var a=this.toBuffer();return 23===a.length&&a[0]===h.OP_HASH160&&20===a[1]&&a[a.length-1]===h.OP_EQUAL},r.prototype.isScriptHashIn=function(){if(0===this.chunks.length)return!1;var a=this.chunks[this.chunks.length-1];if(!a)return!1;var b=a.buf;if(!b)return!1;var c=new r(b),d=c.classify();return d!==r.types.UNKNOWN},r.prototype.isMultisigOut=function(){return this.chunks.length>3&&h.isSmallIntOp(this.chunks[0].opcodenum)&&this.chunks.slice(1,this.chunks.length-2).every(function(a){return a.buf&&p.isBuffer(a.buf)})&&h.isSmallIntOp(this.chunks[this.chunks.length-2].opcodenum)&&this.chunks[this.chunks.length-1].opcodenum===h.OP_CHECKMULTISIG},r.prototype.isMultisigIn=function(){return this.chunks.length>=2&&0===this.chunks[0].opcodenum&&this.chunks.slice(1,this.chunks.length).every(function(a){return a.buf&&p.isBuffer(a.buf)&&71===a.buf.length})},r.prototype.isDataOut=function(){return this.chunks.length>=1&&this.chunks[0].opcodenum===h.OP_RETURN&&(1===this.chunks.length||2===this.chunks.length&&this.chunks[1].buf&&this.chunks[1].buf.length<=r.OP_RETURN_STANDARD_SIZE&&this.chunks[1].length===this.chunks.len)},r.prototype.getData=function(){if(this.isDataOut()||this.isScriptHashOut())return new c(this.chunks[1].buf);if(this.isPublicKeyHashOut())return new c(this.chunks[2].buf);throw new Error("Unrecognized script type to get data from")},r.prototype.isPushOnly=function(){return m.every(this.chunks,function(a){return a.opcodenum<=h.OP_16})},r.types={},r.types.UNKNOWN="Unknown",r.types.PUBKEY_OUT="Pay to public key",r.types.PUBKEY_IN="Spend from public key",r.types.PUBKEYHASH_OUT="Pay to public key hash",r.types.PUBKEYHASH_IN="Spend from public key hash",r.types.SCRIPTHASH_OUT="Pay to script hash",r.types.SCRIPTHASH_IN="Spend from script hash",r.types.MULTISIG_OUT="Pay to multisig",r.types.MULTISIG_IN="Spend from multisig",r.types.DATA_OUT="Data push",r.OP_RETURN_STANDARD_SIZE=80,r.identifiers={},r.identifiers.PUBKEY_OUT=r.prototype.isPublicKeyOut,r.identifiers.PUBKEY_IN=r.prototype.isPublicKeyIn,r.identifiers.PUBKEYHASH_OUT=r.prototype.isPublicKeyHashOut,r.identifiers.PUBKEYHASH_IN=r.prototype.isPublicKeyHashIn,r.identifiers.MULTISIG_OUT=r.prototype.isMultisigOut,r.identifiers.MULTISIG_IN=r.prototype.isMultisigIn,r.identifiers.SCRIPTHASH_OUT=r.prototype.isScriptHashOut,r.identifiers.SCRIPTHASH_IN=r.prototype.isScriptHashIn,r.identifiers.DATA_OUT=r.prototype.isDataOut,r.prototype.classify=function(){for(var a in r.identifiers)if(r.identifiers[a].bind(this)())return r.types[a]; diff --git a/bower.json b/bower.json index d4c8eb35..7e7b6fc5 100644 --- a/bower.json +++ b/bower.json @@ -1,7 +1,7 @@ { "name": "bitcore-wallet-client", "main": "index.js", - "version": "0.0.4", + "version": "0.0.5", "homepage": "https://github.com/bitpay/bitcore-wallet-client", "authors": ["BitPay Inc"], "description": "Client for bitcore-wallet-service",