From 5e18dddd37ff2f7d3bac2f8631331a05d70ecda6 Mon Sep 17 00:00:00 2001 From: Christopher Jeffrey Date: Sat, 17 Sep 2016 19:11:08 -0700 Subject: [PATCH] http: make http api safe for spv. --- lib/http/server.js | 26 +++++++++++++++++++++++--- 1 file changed, 23 insertions(+), 3 deletions(-) diff --git a/lib/http/server.js b/lib/http/server.js index c0e35633..1b72ee89 100644 --- a/lib/http/server.js +++ b/lib/http/server.js @@ -578,6 +578,9 @@ HTTPServer.prototype._init = function _init() { // Mempool snapshot this.get('/mempool', function(req, res, next, send) { + if (!self.mempool) + return send(400, { error: 'No mempool available.' }); + self.mempool.getHistory(function(err, txs) { if (err) return next(err); @@ -607,7 +610,13 @@ HTTPServer.prototype._init = function _init() { // Estimate fee this.get('/fee', function(req, res, next, send) { - var fee = self.fees.estimateFee(req.options.blocks); + var fee; + + if (!self.fees) + return send(400, { error: 'Fee estimation not available.' }); + + fee = self.fees.estimateFee(req.options.blocks); + send(200, { rate: utils.btc(fee) }); }); @@ -1234,6 +1243,7 @@ function ClientSocket(server, socket) { this.chain = this.server.chain; this.mempool = this.server.mempool; + this.pool = this.server.pool; this.logger = this.server.logger; this.events = []; @@ -1285,6 +1295,8 @@ ClientSocket.prototype.addFilter = function addFilter(addresses) { if (!this.filter[hash]) { this.filter[hash] = true; this.filterCount++; + if (this.pool.options.spv) + this.pool.watch(hash, 'hex'); } } }; @@ -1335,6 +1347,7 @@ ClientSocket.prototype.unbindAll = function unbindAll() { ClientSocket.prototype.watchChain = function watchChain() { var self = this; + var pool = this.mempool || this.pool; this.bind(this.chain, 'connect', function(entry, block) { var txs; @@ -1351,16 +1364,17 @@ ClientSocket.prototype.watchChain = function watchChain() { self.emit('block disconnect', entry.toJSON()); }); - this.bind(this.mempool, 'tx', function(tx) { + this.bind(pool, 'tx', function(tx) { if (self.testFilter(tx)) self.emit('mempool tx', tx.toJSON()); }); }; ClientSocket.prototype.unwatchChain = function unwatchChain() { + var pool = this.mempool || this.pool; this.unbind(this.chain, 'connect'); this.unbind(this.chain, 'disconnect'); - this.unbind(this.mempool, 'tx'); + this.unbind(pool, 'tx'); }; ClientSocket.prototype.testBlock = function testBlock(block) { @@ -1404,6 +1418,12 @@ ClientSocket.prototype.scan = function scan(start, callback) { if (typeof start === 'string') start = utils.revHex(start); + if (this.chain.db.options.spv) + return this.chain.reset(start, callback); + + if (this.chain.db.options.prune) + return callback(new Error('Cannot scan in pruned mode.')); + this.chain.db.scan(start, this.filter, function(entry, txs, next) { for (i = 0; i < txs.length; i++) txs[i] = txs[i].toJSON();