bitcore-wallet-service/lib/blockchainexplorer.js

69 lines
2.0 KiB
JavaScript
Raw Normal View History

2015-03-30 11:34:05 -07:00
'use strict';
var _ = require('lodash');
var $ = require('preconditions').singleton();
var log = require('npmlog');
log.debug = log.verbose;
var Explorers = require('bitcore-explorers');
var request = require('request');
var io = require('socket.io-client');
2015-03-30 11:34:05 -07:00
2015-03-30 16:16:51 -07:00
function BlockChainExplorer(opts) {
2015-03-30 11:34:05 -07:00
$.checkArgument(opts);
var provider = opts.provider || 'insight';
var network = opts.network || 'livenet';
2015-04-05 09:56:56 -07:00
var dfltUrl = network == 'livenet' ? 'https://insight.bitpay.com:443' :
'https://test-insight.bitpay.com:443';
2015-04-06 11:13:30 -07:00
var url = opts.url || dfltUrl;
2015-03-30 11:34:05 -07:00
var url;
switch (provider) {
case 'insight':
2015-03-31 08:04:02 -07:00
var explorer = new Explorers.Insight(url, network);
explorer.getTransactions = _.bind(getTransactionsInsight, explorer, url);
2015-04-01 12:42:12 -07:00
explorer.getAddressActivity = _.bind(getAddressActivityInsight, explorer, url);
2015-03-31 08:04:02 -07:00
explorer.initSocket = _.bind(initSocketInsight, explorer, url);
return explorer;
2015-03-30 11:34:05 -07:00
default:
throw new Error('Provider ' + provider + ' not supported');
};
};
function getTransactionsInsight(url, addresses, from, to, cb) {
var qs = [];
if (_.isNumber(from)) qs.push('from=' + from);
if (_.isNumber(to)) qs.push('to=' + to);
var url = url + '/api/addrs/txs' + (qs.length > 0 ? '?' + qs.join('&') : '');
2015-03-30 11:34:05 -07:00
request({
method: "POST",
url: url,
2015-03-30 11:34:05 -07:00
json: {
addrs: [].concat(addresses).join(',')
}
}, function(err, res, txs) {
2015-03-30 11:34:05 -07:00
if (err || res.statusCode != 200) return cb(err || res);
2015-04-06 11:13:30 -07:00
// NOTE: Whenever Insight breaks communication with bitcoind, it returns invalid data but no error code.
2015-04-06 13:41:04 -07:00
if (!_.isArray(txs) || (txs.length != _.compact(txs).length)) return cb(new Error('Could not retrieve transactions from blockchain'));
return cb(null, txs);
2015-03-30 11:34:05 -07:00
});
};
2015-04-01 12:42:12 -07:00
function getAddressActivityInsight(url, addresses, cb) {
getTransactionsInsight(url, addresses, 0, 0, function(err, result) {
if (err) return cb(err);
return cb(null, result.totalItems > 0);
});
};
function initSocketInsight(url) {
var socket = io.connect(url, {});
return socket;
};
2015-03-30 16:16:51 -07:00
module.exports = BlockChainExplorer;