Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Feature/batch requests #439

Open
wants to merge 24 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
24 commits
Select commit Hold shift + click to select a range
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Insight API
# Insight API [![Build Status](https://travis-ci.org/CoinSpace/insight-api.svg)](https://travis-ci.org/CoinSpace/insight-api)

A Bitcoin blockchain REST and web socket API service for [Bitcore Node](https://github.com/bitpay/bitcore-node).

Expand Down Expand Up @@ -53,6 +53,11 @@ Caching support has not yet been added in the v0.3 upgrade.
/insight-api/block/00000000a967199a2fad0877433c93df785a8d8ce062e5f9b451cd1397bdbf62
```

#### Multiple blocks
```
/insight-api/block/[:hash1],[:hash2],...,[:hash,]
```

### Block Index
Get block hash by height
```
Expand All @@ -73,12 +78,24 @@ which is the hash of the Genesis block (0 height)
/insight-api/rawtx/525de308971eabd941b139f46c7198b5af9479325c2395db7f2fb5ae8562556c
```

### Multiple Transactions
```
/insight-api/txs/[:rawid1],[:rawid2],...,[:rawidn]
/insight-api/rawtxs/[:rawid1],[:rawid2],...,[:rawidn]
```

### Address
```
/insight-api/addr/[:addr][?noTxList=1&noCache=1]
/insight-api/addr/mmvP3mTe53qxHdPqXEvdu8WdC7GfQ2vmx5?noTxList=1
```

### Multiple Addresses
```
/insight-api/addrs/[:addr1],[:addr2],...,[:addrn][?noTxList=1&noCache=1]

```

### Address Properties
```
/insight-api/addr/[:addr]/balance
Expand Down
21 changes: 18 additions & 3 deletions lib/addresses.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,23 @@ AddressController.prototype.show = function(req, res) {
});
};

AddressController.prototype.multishow = function(req, res) {
var options = {
noTxList: parseInt(req.query.noTxList)
};

var self = this;

async.map(req.addrs, function(addr, callback) {
self.getAddressSummary(addr, options, callback);
}, function(err, datas) {
if(err) {
return common.handleErrors(err, res);
}
res.jsonp(datas);
});
};

AddressController.prototype.balance = function(req, res) {
this.addressSummarySubQuery(req, res, 'balanceSat');
};
Expand Down Expand Up @@ -51,8 +68,6 @@ AddressController.prototype.addressSummarySubQuery = function(req, res, param) {
};

AddressController.prototype.getAddressSummary = function(address, options, callback) {
var self = this;

this.node.getAddressSummary(address, options, function(err, summary) {
if(err) {
return callback(err);
Expand Down Expand Up @@ -90,7 +105,7 @@ AddressController.prototype.checkAddrs = function(req, res, next) {
}

this.check(req, res, next, req.addrs);
}
};

AddressController.prototype.check = function(req, res, next, addresses) {
if(!addresses.length || !addresses[0]) {
Expand Down
20 changes: 8 additions & 12 deletions lib/blocks.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
'use strict';

var common = require('./common');
var async = require('async');
var batch = require('./common').batch;
var bitcore = require('bitcore-lib');
var pools = require('../pools.json');
var BN = bitcore.crypto.BN;
var common = require('./common');
var pools = require('../pools.json');

function BlockController(node) {
var self = this;
Expand All @@ -26,24 +27,19 @@ var BLOCK_LIMIT = 200;
/**
* Find block by hash ...
*/
BlockController.prototype.block = function(req, res, next, hash) {
BlockController.prototype.block = batch(function(hash, callback) {
var self = this;

this.node.getBlock(hash, function(err, block) {
if(err && err.message === 'Block not found.') {
// TODO libbitcoind should pass an instance of errors.Block.NotFound
return common.handleErrors(null, res);
} else if(err) {
return common.handleErrors(err, res);
if (err) {
return callback(err);
}

var info = self.node.services.bitcoind.getBlockIndex(hash);
info.isMainChain = self.node.services.bitcoind.isMainChain(hash);

req.block = self.transformBlock(block, info);
next();
callback(null, self.transformBlock(block, info));
});
};
}, 'block');

BlockController.prototype.transformBlock = function(block, info) {
var blockObj = block.toObject();
Expand Down
31 changes: 31 additions & 0 deletions lib/common.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
'use strict';

var async = require('async');

exports.notReady = function (err, res, p) {
res.status(503).send('Server not yet ready. Sync Percentage:' + p);
};
Expand All @@ -17,3 +19,32 @@ exports.handleErrors = function (err, res) {
res.status(404).send('Not found');
}
};

/**
* batch
*
* @param handler
* @param outkey
* @returns {Function}
*/
exports.batch = function(handler, outkey) {
return function(req, res, next, inputdata) {
var self = this;

async.mapSeries(inputdata.split(','), async.ensureAsync(function() {
return handler.apply(self, arguments);
}), function(err, results) {
if (err) {
return exports.handleErrors(err, res);
}

if (results.length === 1) {
req[outkey] = results[0]
} else {
req[outkey] = results;
}

return next();
});
};
};
5 changes: 5 additions & 0 deletions lib/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -108,16 +108,21 @@ InsightAPI.prototype.setupRoutes = function(app) {
var transactions = new TxController(this.node);
app.get('/tx/:txid', this.cacheLong(), transactions.show.bind(transactions));
app.param('txid', transactions.transaction.bind(transactions));
app.get('/txs/:txids', this.cacheShort(), transactions.show.bind(transactions));
app.param('txids', transactions.multitransactions.bind(transactions));
app.get('/txs', this.cacheShort(), transactions.list.bind(transactions));
app.post('/tx/send', transactions.send.bind(transactions));

// Raw Routes
app.get('/rawtx/:txid', this.cacheLong(), transactions.showRaw.bind(transactions));
app.param('txid', transactions.rawTransaction.bind(transactions));
app.get('/rawtxs/:txids', this.cacheLong(), transactions.showRaw.bind(transactions));
app.param('txids', transactions.multiRawTransaction.bind(transactions));

// Address routes
var addresses = new AddressController(this.node);
app.get('/addr/:addr', this.cacheShort(), addresses.checkAddr.bind(addresses), addresses.show.bind(addresses));
app.get('/addrs/:addrs', this.cacheShort(), addresses.checkAddrs.bind(addresses), addresses.multishow.bind(addresses));
app.get('/addr/:addr/utxo', this.cacheShort(), addresses.checkAddr.bind(addresses), addresses.utxo.bind(addresses));
app.get('/addrs/:addrs/utxo', this.cacheShort(), addresses.checkAddrs.bind(addresses), addresses.multiutxo.bind(addresses));
app.post('/addrs/utxo', this.cacheShort(), addresses.checkAddrs.bind(addresses), addresses.multiutxo.bind(addresses));
Expand Down
66 changes: 63 additions & 3 deletions lib/transactions.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
'use strict';

var async = require('async');
var bitcore = require('bitcore-lib');
var _ = bitcore.deps._;
var $ = bitcore.util.preconditions;
var common = require('./common');
var async = require('async');

var $ = bitcore.util.preconditions;
var _ = bitcore.deps._;

function TxController(node) {
this.node = node;
Expand Down Expand Up @@ -48,6 +49,42 @@ TxController.prototype.transaction = function(req, res, next, txid) {
});
};

TxController.prototype.multitransactions = function(req, res, next, txids) {
var self = this;

async.map(txids.split(','), function(txid, callback) {
self.node.getTransactionWithBlockInfo(txid, true, function(err, transaction) {
if (err) {
return callback(err);
}

transaction.populateInputs(self.node.services.db, [], function(err) {
if (err) {
return callback(err);
}

self.transformTransaction(transaction, function(err, transformedTransaction) {
if (err) {
return callback(err);
}

callback(null, transformedTransaction);
});
});
});
}, function(err, txs) {
if (err && err instanceof self.node.errors.Transaction.NotFound) {
return common.handleErrors(null, res);
} else if(err) {
return common.handleErrors(err, res);
}

req.transaction = txs;
next();
});
};


TxController.prototype.transformTransaction = function(transaction, callback) {
$.checkArgument(_.isFunction(callback));
var self = this;
Expand Down Expand Up @@ -92,6 +129,7 @@ TxController.prototype.transformTransaction = function(transaction, callback) {
transformed.vout = vout;

transformed.blockhash = transaction.__blockHash;
transformed.blockheight = transaction.__height;
transformed.confirmations = confirmations;
var time = transaction.__timestamp ? transaction.__timestamp : Math.round(Date.now() / 1000);
transformed.time = time;
Expand Down Expand Up @@ -243,6 +281,28 @@ TxController.prototype.rawTransaction = function(req, res, next, txid) {
});
};

TxController.prototype.multiRawTransaction = function(req, res, next, txids) {
var self = this;

async.map(txids.split(','), function(txid, callback) {
self.node.getTransaction(txid, true, callback);
}, function(err, txs) {
if (err && err instanceof self.node.errors.Transaction.NotFound) {
return common.handleErrors(null, res);
} else if(err) {
return common.handleErrors(err, res);
}

req.rawTransaction = {
'rawtx': txs.map(function(tx) {
return tx.toBuffer().toString('hex');
})
};

next();
});
};

TxController.prototype.showRaw = function(req, res) {
if (req.rawTransaction) {
res.jsonp(req.rawTransaction);
Expand Down
5 changes: 5 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,10 @@
{
"name": "Braydon Fuller",
"email": "[email protected]"
},
{
"name": "Eugene Krevenets",
"email": "[email protected]"
}
],
"bugs": {
Expand Down Expand Up @@ -70,6 +74,7 @@
"chai": "*",
"mocha": "~1.16.2",
"proxyquire": "^1.7.2",
"rewire": "^2.5.1",
"should": "^2.1.1",
"sinon": "^1.10.3"
}
Expand Down
Loading