bitcore-node-zcash/util/sync.js

90 lines
2.0 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';
require('buffertools').extend();
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');
var networkName = process.argv[2] || 'testnet';
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-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-06 19:19:12 -08:00
return getNextBlock(blockInfo.result.nextblockhash);
2014-01-06 18:50:29 -08:00
});
});
}
2014-01-06 19:19:12 -08:00
function syncBlocks(network, cb) {
Block.findOne({}, {}, { sort: { 'height' : -1 } }, function(err, block) {
if (err) {
return cb(err);
}
var nextHash =
block && block.hash
? block.hash
: network.genesisBlock.hash.reverse().toString('hex')
;
console.log('Starting at hash' + nextHash);
getNextBlock(nextHash, cb);
});
}
2014-01-06 18:50:29 -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 () {
2014-01-06 19:19:12 -08:00
syncBlocks(network, function(err) {
if (err) {
console.log(err);
}
mongoose.connection.close();
});
2014-01-06 18:50:29 -08:00
});