insight-ui-zcash/util/sync.js

103 lines
2.3 KiB
JavaScript
Raw Normal View History

2014-01-06 18:50:29 -08:00
#!/usr/bin/env node
process.env.NODE_ENV = process.env.NODE_ENV || 'development';
2014-01-07 09:12:44 -08:00
2014-01-06 18:50:29 -08:00
require('buffertools').extend();
2014-01-07 09:12:44 -08:00
var SYNC_VERSION = '0.1';
var program = require('commander');
2014-01-07 04:11:01 -08:00
var util = require('util');
2014-01-06 18:50:29 -08:00
var RpcClient = require('../node_modules/bitcore/RpcClient').class();
var networks = require('../node_modules/bitcore/networks');
var Block = require('../app/models/Block');
var config = require('../config/config');
var mongoose = require('mongoose');
2014-01-07 09:12:44 -08:00
program
.version(SYNC_VERSION)
.option('-N --network [livenet]', 'Set bitcoin network [livenet]', 'livenet')
.option('-R --reindex', 'Force reindexing', '0')
.parse(process.argv);
var networkName = program.network;
2014-01-06 19:19:12 -08:00
var network = networkName == 'testnet' ? networks.testnet : networks.livenet;
2014-01-06 18:50:29 -08:00
2014-01-07 09:12:44 -08:00
mongoose.connect(config.db);
var db = mongoose.connection;
var rpc = new RpcClient(config.bitcoind);
db.on('error', console.error.bind(console, 'connection error:'));
db.once('open', function callback () {
syncBlocks(network, program.reindex, function(err) {
if (err) {
console.log(err);
}
mongoose.connection.close();
});
});
2014-01-06 19:19:12 -08:00
function getNextBlock(blockHash,cb) {
if ( !blockHash ) {
console.log("done");
return cb();
}
2014-01-06 18:50:29 -08:00
rpc.getBlock(blockHash, function(err, blockInfo) {
if (err) {
2014-01-06 19:19:12 -08:00
return cb(err);
2014-01-06 18:50:29 -08:00
}
2014-01-07 04:11:01 -08:00
if ( ! ( blockInfo.result.height % 1000) ) {
var h = blockInfo.result.height,
d = blockInfo.result.confirmations;
console.log( util.format("Height: %d/%d [%d%%]", h, d, 100*h/(h+d)));
}
2014-01-06 18:50:29 -08:00
Block.create( blockInfo.result, function(err, inBlock) {
2014-01-06 19:19:12 -08:00
// E11000 => already exists
if (err && ! err.toString().match(/E11000/)) {
return cb(err);
2014-01-06 18:50:29 -08:00
}
2014-01-07 04:48:31 -08:00
return getNextBlock(blockInfo.result.nextblockhash, cb);
2014-01-06 18:50:29 -08:00
});
});
}
2014-01-07 09:12:44 -08:00
function syncBlocks(network, reindex, cb) {
2014-01-06 19:19:12 -08:00
2014-01-07 09:12:44 -08:00
var genesisHash = network.genesisBlock.hash.reverse().toString('hex');
if (reindex)
return getNextBlock(genesisHash, cb);
2014-01-06 19:19:12 -08:00
2014-01-07 09:12:44 -08:00
Block.findOne({}, {}, { sort: { 'confirmations' : 1 } }, function(err, block) {
if (err) return cb(err);
2014-01-06 19:19:12 -08:00
var nextHash =
block && block.hash
? block.hash
2014-01-07 09:12:44 -08:00
: genesisHash
2014-01-06 19:19:12 -08:00
;
2014-01-07 04:48:31 -08:00
console.log('Starting at hash: ' + nextHash);
2014-01-07 09:12:44 -08:00
return getNextBlock(nextHash, cb);
2014-01-06 19:19:12 -08:00
});
}