insight-ui-zcash/lib/HistoricSync.js

504 lines
13 KiB
JavaScript
Raw Normal View History

2014-01-16 11:11:20 -08:00
'use strict';
require('classtool');
2014-01-21 14:13:21 -08:00
2014-01-16 11:11:20 -08:00
function spec() {
2014-01-21 08:28:01 -08:00
var util = require('util');
var RpcClient = require('bitcore/RpcClient').class();
2014-02-01 08:39:29 -08:00
var bitutil = require('bitcore/util/util');
var Address = require('bitcore/Address').class();
var Script = require('bitcore/Script').class();
2014-01-21 08:28:01 -08:00
var networks = require('bitcore/networks');
var async = require('async');
var config = require('../config/config');
var Sync = require('./Sync').class();
var sockets = require('../app/controllers/socket.js');
2014-01-30 18:16:43 -08:00
var BlockExtractor = require('./BlockExtractor.js').class();
2014-02-04 18:50:18 -08:00
//var Deserialize = require('bitcore/Deserialize');
2014-01-16 11:11:20 -08:00
2014-01-21 14:13:21 -08:00
var BAD_GEN_ERROR = 'Bad genesis block. Network mismatch between Insight and bitcoind? Insight is configured for:';
2014-01-23 10:10:52 -08:00
function HistoricSync() {
2014-01-21 08:28:01 -08:00
this.network = config.network === 'testnet' ? networks.testnet: networks.livenet;
2014-01-17 11:36:34 -08:00
var genesisHashReversed = new Buffer(32);
this.network.genesisBlock.hash.copy(genesisHashReversed);
this.genesis = genesisHashReversed.reverse().toString('hex');
2014-01-23 10:10:52 -08:00
//available status: starting / syncing / finished / aborted
this.status = 'starting';
2014-01-21 14:13:21 -08:00
this.error = null;
this.syncPercentage = 0;
this.syncedBlocks = 0;
this.skippedBlocks = 0;
2014-02-03 18:30:46 -08:00
this.orphanBlocks = 0;
2014-02-04 18:50:18 -08:00
this.type ='';
2014-01-16 11:11:20 -08:00
}
function p() {
var args = [];
2014-01-21 08:28:01 -08:00
Array.prototype.push.apply(args, arguments);
args.unshift('[historic_sync]');
/*jshint validthis:true */
console.log.apply(this, args);
2014-01-16 11:11:20 -08:00
}
2014-01-21 14:13:21 -08:00
HistoricSync.prototype.setError = function(err) {
var self = this;
self.error = err.toString();
self.status='error';
self.showProgress();
};
2014-01-21 08:28:01 -08:00
HistoricSync.prototype.init = function(opts, cb) {
2014-01-21 11:43:05 -08:00
var self = this;
self.opts = opts;
2014-01-23 10:10:52 -08:00
self.rpc = new RpcClient(config.bitcoind);
self.sync = new Sync(opts);
2014-01-21 11:43:05 -08:00
self.sync.init(opts, function(err) {
if (err) {
2014-01-21 14:13:21 -08:00
self.setError(err);
2014-01-21 11:43:05 -08:00
return cb(err);
}
else {
// check testnet?
self.rpc.getBlockHash(0, function(err, res){
if (!err && ( res && res.result !== self.genesis)) {
2014-01-21 14:13:21 -08:00
err = new Error(BAD_GEN_ERROR + config.network);
self.setError(err);
2014-01-21 11:43:05 -08:00
}
2014-01-23 08:00:27 -08:00
if (err) self.setError(err);
2014-01-21 11:43:05 -08:00
return cb(err);
});
}
});
2014-01-16 11:11:20 -08:00
};
HistoricSync.prototype.close = function() {
this.sync.close();
};
2014-01-21 14:13:21 -08:00
HistoricSync.prototype.info = function() {
return {
status: this.status,
blockChainHeight: this.blockChainHeight,
syncPercentage: this.syncPercentage,
skippedBlocks: this.skippedBlocks,
syncedBlocks: this.syncedBlocks,
2014-02-03 18:30:46 -08:00
orphanBlocks: this.orphanBlocks,
2014-02-09 14:33:39 -08:00
syncTipHash: this.sync.tip,
2014-01-23 08:00:27 -08:00
error: this.error,
2014-02-04 18:50:18 -08:00
type: this.type,
2014-01-21 14:13:21 -08:00
};
};
2014-02-03 18:30:46 -08:00
HistoricSync.prototype.showProgress = function() {
var self = this;
2014-02-08 05:57:37 -08:00
if ( ( self.syncedBlocks + self.skippedBlocks) % self.step !== 1) return;
2014-01-21 14:13:21 -08:00
if (self.error) {
2014-01-23 08:00:27 -08:00
p('ERROR: ' + self.error);
2014-01-21 14:13:21 -08:00
}
else {
2014-01-29 10:10:36 -08:00
self.syncPercentage = parseFloat(100 * (self.syncedBlocks + self.skippedBlocks) / self.blockChainHeight).toFixed(3);
2014-01-21 14:53:00 -08:00
if (self.syncPercentage > 100) self.syncPercentage = 100;
2014-02-03 18:30:46 -08:00
p(util.format('status: [%d%%] skipped: %d ', self.syncPercentage, self.skippedBlocks));
2014-01-21 14:13:21 -08:00
}
2014-02-09 14:33:39 -08:00
if (self.opts.shouldBroadcastSync) {
2014-01-21 14:13:21 -08:00
sockets.broadcastSyncInfo(self.info());
}
//TODO
// if (self.syncPercentage > 10) {
// process.exit(-1);
// }
};
2014-01-23 10:10:52 -08:00
HistoricSync.prototype.getPrevNextBlock = function(blockHash, blockEnd, scanOpts, cb) {
2014-01-17 11:36:34 -08:00
var self = this;
2014-01-16 11:11:20 -08:00
// recursion end.
2014-01-21 08:28:01 -08:00
if (!blockHash) return cb();
2014-01-16 11:11:20 -08:00
2014-01-21 08:28:01 -08:00
var existed = false;
2014-01-16 11:11:20 -08:00
var blockInfo;
async.series([
2014-01-21 08:28:01 -08:00
// Already got it?
function(c) {
2014-02-05 07:31:38 -08:00
self.sync.bDb.has(blockHash, function(err, ret) {
2014-01-21 08:28:01 -08:00
if (err) {
p(err);
return c(err);
}
2014-02-03 18:30:46 -08:00
if (ret) existed = true;
2014-01-16 11:11:20 -08:00
return c();
2014-01-21 08:28:01 -08:00
});
},
//show some (inacurate) status
function(c) {
2014-02-08 05:57:37 -08:00
self.showProgress();
2014-01-21 08:28:01 -08:00
return c();
},
2014-01-16 11:11:20 -08:00
2014-01-30 18:16:43 -08:00
function(c) {
2014-01-21 08:28:01 -08:00
self.rpc.getBlock(blockHash, function(err, ret) {
if (err) return c(err);
2014-02-08 05:57:37 -08:00
if (ret) {
blockInfo = ret.result;
// this is to match block retreived from file
if (blockInfo.hash === self.genesis)
2014-02-08 15:09:54 -08:00
blockInfo.previousblockhash = self.network.genesisBlock.prev_hash.toString('hex');
2014-02-08 05:57:37 -08:00
}
else {
blockInfo = null;
}
2014-01-16 11:11:20 -08:00
2014-01-21 08:28:01 -08:00
return c();
});
},
//store it
function(c) {
if (existed) return c();
2014-01-30 18:16:43 -08:00
2014-02-08 15:09:54 -08:00
// When storing files from RPC recusively, reorgs are disabled
self.sync.storeTipBlock(blockInfo, false, function(err) {
2014-02-04 21:48:54 -08:00
return c(err);
2014-01-21 08:28:01 -08:00
});
2014-02-08 05:57:37 -08:00
}], function(err) {
2014-01-17 11:36:34 -08:00
2014-01-21 08:28:01 -08:00
if (err) {
2014-02-08 05:57:37 -08:00
self.setError(util.format('ERROR: @%s: %s [count: syncedBlocks: %d]',
blockHash, err, self.syncedBlocks));
2014-01-30 18:16:43 -08:00
return cb(err);
2014-01-21 08:28:01 -08:00
}
else {
self.status = 'syncing';
}
2014-01-17 05:22:00 -08:00
2014-02-08 05:57:37 -08:00
if ( (scanOpts.upToExisting && existed &&
self.syncedBlocks >= self.blockChainHeight) ||
2014-01-21 14:13:21 -08:00
(blockEnd && blockEnd === blockHash)) {
2014-01-18 13:28:24 -08:00
self.status = 'finished';
2014-02-08 05:57:37 -08:00
p('DONE. Found block: ', blockHash);
2014-01-21 14:13:21 -08:00
self.showProgress();
2014-01-17 11:36:34 -08:00
return cb(err);
2014-01-21 08:28:01 -08:00
}
// Continue
2014-01-30 18:16:43 -08:00
if (blockInfo) {
2014-01-21 08:28:01 -08:00
2014-01-21 14:13:21 -08:00
if (existed)
self.skippedBlocks++;
else
self.syncedBlocks++;
// recursion
2014-01-30 18:16:43 -08:00
if (scanOpts.prev && blockInfo.previousblockhash)
return self.getPrevNextBlock(blockInfo.previousblockhash, blockEnd, scanOpts, cb);
2014-01-21 14:13:21 -08:00
2014-01-30 18:16:43 -08:00
if (scanOpts.next && blockInfo.nextblockhash)
return self.getPrevNextBlock(blockInfo.nextblockhash, blockEnd, scanOpts, cb);
2014-01-21 08:28:01 -08:00
}
return cb(err);
2014-01-16 11:11:20 -08:00
});
};
2014-01-30 18:16:43 -08:00
2014-02-01 08:39:29 -08:00
// TODO. replace with
// Script.prototype.getAddrStrs if that one get merged in bitcore
HistoricSync.prototype.getAddrStr = function(s) {
var self = this;
var addrStrs = [];
var type = s.classify();
var addr;
switch(type) {
case Script.TX_PUBKEY:
var chunk = s.captureOne();
addr = new Address(self.network.addressPubkey, bitutil.sha256ripe160(chunk));
addrStrs = [ addr.toString() ];
break;
case Script.TX_PUBKEYHASH:
addr = new Address(self.network.addressPubkey, s.captureOne());
addrStrs = [ addr.toString() ];
break;
case Script.TX_SCRIPTHASH:
addr = new Address(self.network.addressScript, s.captureOne());
addrStrs = [ addr.toString() ];
break;
case Script.TX_MULTISIG:
var chunks = s.capture();
chunks.forEach(function(chunk) {
var a = new Address(self.network.addressPubkey, bitutil.sha256ripe160(chunk));
addrStrs.push(a.toString());
});
break;
case Script.TX_UNKNOWN:
break;
}
return addrStrs;
};
2014-02-08 05:57:37 -08:00
HistoricSync.prototype.getBlockFromFile = function(cb) {
2014-01-30 18:16:43 -08:00
var self = this;
2014-02-08 05:57:37 -08:00
2014-01-30 18:16:43 -08:00
var blockInfo;
//get Info
2014-02-08 05:57:37 -08:00
self.blockExtractor.getNextBlock(function(err, b) {
if (err || ! b) return cb(err);
2014-01-30 18:16:43 -08:00
2014-02-08 05:57:37 -08:00
blockInfo = b.getStandardizedObject(b.txs, self.network);
// blockInfo.curWork = Deserialize.intFromCompact(b.bits);
// We keep the RPC field names
blockInfo.previousblockhash = blockInfo.prev_block;
2014-02-01 08:39:29 -08:00
2014-02-08 05:57:37 -08:00
var ti=0;
// Get TX Address
b.txs.forEach(function(t) {
2014-02-04 22:34:46 -08:00
2014-02-08 05:57:37 -08:00
var objTx = blockInfo.tx[ti++];
2014-02-04 22:34:46 -08:00
2014-02-08 05:57:37 -08:00
//add time from block
objTx.time = blockInfo.time;
2014-02-04 22:34:46 -08:00
2014-02-08 05:57:37 -08:00
var to=0;
t.outs.forEach( function(o) {
2014-02-01 08:39:29 -08:00
2014-02-08 05:57:37 -08:00
var s = new Script(o.s);
var addrs = self.getAddrStr(s);
2014-02-01 08:39:29 -08:00
2014-02-08 05:57:37 -08:00
// support only for p2pubkey p2pubkeyhash and p2sh
if (addrs.length === 1) {
objTx.out[to].addrStr = addrs[0];
}
to++;
2014-02-01 08:39:29 -08:00
});
2014-01-30 18:16:43 -08:00
});
2014-02-01 17:39:08 -08:00
2014-02-08 05:57:37 -08:00
return cb(err,blockInfo);
});
};
HistoricSync.prototype.nextBlockFromFile = function(scanOpts, cb) {
var self = this;
2014-02-03 18:30:46 -08:00
self.showProgress();
self.getBlockFromFile(function(err, blockInfo) {
2014-02-03 18:30:46 -08:00
if (err) {
self.setError(util.format('ERROR: @%s: %s [count: syncedBlocks: %d]',
blockInfo ? blockInfo.hash : '-', err, self.syncedBlocks));
return cb(err);
2014-01-30 18:16:43 -08:00
}
self.sync.storeTipBlock(blockInfo, function(err) {
if (blockInfo && blockInfo.hash) {
self.syncedBlocks++;
} else
self.status = 'finished';
if (err) {
self.setError(util.format('ERROR: @%s: %s [count: syncedBlocks: %d]',
blockInfo ? blockInfo.hash : '-', err, self.syncedBlocks));
}
return cb(err);
});
2014-01-30 18:16:43 -08:00
});
2014-01-30 18:16:43 -08:00
};
2014-02-04 21:48:54 -08:00
HistoricSync.prototype.countNotOrphan = function(cb) {
var self = this;
if (self.notOrphanCount) return cb(null, self.notOrphanCount);
2014-02-05 07:31:38 -08:00
self.sync.bDb.countNotOrphan(function(err, count) {
2014-02-04 21:48:54 -08:00
if (err) return cb(err);
self.notOrphanCount = count;
return cb(null, self.notOrphanCount);
});
};
2014-02-04 08:06:05 -08:00
HistoricSync.prototype.getBlockCount = function(cb) {
var self = this;
if (self.blockChainHeight) return cb();
self.rpc.getBlockCount(function(err, res) {
if (err) return cb(err);
self.blockChainHeight = res.result;
return cb();
});
};
2014-01-30 18:16:43 -08:00
2014-01-23 10:10:52 -08:00
HistoricSync.prototype.importHistory = function(scanOpts, next) {
2014-01-17 11:36:34 -08:00
var self = this;
2014-01-16 11:11:20 -08:00
2014-01-22 05:01:08 -08:00
var lastBlock;
2014-01-16 11:11:20 -08:00
async.series([
2014-01-21 08:28:01 -08:00
function(cb) {
2014-01-23 10:10:52 -08:00
if (scanOpts.destroy) {
2014-01-21 08:28:01 -08:00
p('Deleting DB...');
return self.sync.destroy(cb);
}
return cb();
},
// We are not using getBestBlockHash, because is not available in all clients
2014-02-04 08:06:05 -08:00
function (cb) { return self.getBlockCount(cb); },
2014-01-21 08:28:01 -08:00
function(cb) {
2014-01-23 10:10:52 -08:00
if (!scanOpts.reverse) return cb();
2014-01-21 08:28:01 -08:00
2014-01-21 14:13:21 -08:00
self.rpc.getBlockHash(self.blockChainHeight, function(err, res) {
2014-01-21 08:28:01 -08:00
if (err) return cb(err);
2014-01-22 05:01:08 -08:00
lastBlock = res.result;
2014-01-21 08:28:01 -08:00
return cb();
});
},
function(cb) {
2014-01-23 10:10:52 -08:00
if (scanOpts.upToExisting) {
2014-01-21 08:28:01 -08:00
// should be isOrphan = true or null to be more accurate.
2014-02-04 21:48:54 -08:00
self.countNotOrphan(function(err, count) {
2014-01-17 05:44:14 -08:00
if (err) return cb(err);
2014-01-16 11:11:20 -08:00
2014-01-21 14:13:21 -08:00
self.syncedBlocks = count || 0;
2014-01-16 11:11:20 -08:00
return cb();
});
2014-01-21 08:28:01 -08:00
}
2014-01-23 10:10:52 -08:00
else {
return cb();
}
2014-01-21 08:28:01 -08:00
},
], function(err) {
if (err) {
self.setError(err);
return next(err, 0);
2014-01-21 08:28:01 -08:00
}
2014-01-18 13:28:24 -08:00
2014-01-21 14:13:21 -08:00
// SETUP Sync params
var start, end;
2014-01-29 10:10:36 -08:00
if (!self.step) {
2014-01-21 14:40:41 -08:00
var step = parseInt( (self.blockChainHeight - self.syncedBlocks) / 1000);
2014-01-21 14:13:21 -08:00
if (self.opts.progressStep) {
step = self.opts.progressStep;
}
2014-01-21 14:40:41 -08:00
if (step < 10) step = 10;
2014-01-21 14:13:21 -08:00
self.step = step;
}
if (scanOpts.reverse) {
start = lastBlock;
end = self.genesis;
scanOpts.prev = true;
2014-01-21 08:28:01 -08:00
}
else {
start = self.genesis;
end = null;
scanOpts.next = true;
}
p('Starting from: ', start);
p(' to : ', end);
p(' scanOpts: ', JSON.stringify(scanOpts));
if (scanOpts.fromFiles) {
2014-02-08 05:57:37 -08:00
2014-02-03 18:30:46 -08:00
self.status = 'syncing';
2014-02-08 05:57:37 -08:00
self.type = 'from .dat Files';
async.whilst(function() {
2014-02-03 18:30:46 -08:00
return self.status === 'syncing';
}, function (w_cb) {
2014-02-08 05:57:37 -08:00
self.nextBlockFromFile(scanOpts, function(err) {
setImmediate(function(){
return w_cb(err);
});
2014-02-03 18:30:46 -08:00
});
}, function(err) {
2014-02-03 18:30:46 -08:00
return next(err);
});
2014-01-21 08:28:01 -08:00
}
else {
2014-02-04 18:50:18 -08:00
self.type = 'from RPC calls';
self.getPrevNextBlock(start, end, scanOpts, function(err) {
return next(err);
});
}
2014-01-16 11:11:20 -08:00
});
};
2014-01-16 11:11:20 -08:00
2014-01-17 11:36:34 -08:00
// upto if we have genesis block?
2014-01-30 18:16:43 -08:00
HistoricSync.prototype.smartImport = function(scanOpts, next) {
2014-01-17 11:36:34 -08:00
var self = this;
2014-02-05 07:31:38 -08:00
self.sync.bDb.has(self.genesis, function(err, b) {
2014-01-17 11:36:34 -08:00
if (err) return next(err);
2014-02-04 21:48:54 -08:00
self.countNotOrphan(function(err, count) {
2014-02-04 08:06:05 -08:00
if (err) return next(err);
self.getBlockCount(function(err) {
if (err) return next(err);
2014-02-04 21:48:54 -08:00
if (!b || scanOpts.destroy || count < self.blockChainHeight * 0.8 ) {
2014-02-04 08:06:05 -08:00
if (!b)
p('Could not find Genesis block. Running FULL SYNC');
else
2014-02-04 21:48:54 -08:00
p('Less that 80% of current blockchain is stored. Running FULL SYNC',
2014-02-04 08:06:05 -08:00
parseInt(count/self.blockChainHeight*100));
if (config.bitcoind.dataDir) {
p('bitcoind dataDir configured...importing blocks from .dat files');
scanOpts.fromFiles = true;
self.blockExtractor = new BlockExtractor(config.bitcoind.dataDir, config.network);
}
else {
scanOpts.reverse = true;
}
}
else {
p('Genesis block found. Syncing upto known blocks.');
2014-02-10 14:11:13 -08:00
p('Got ' + count + ' out of ' + self.blockChainHeight + ' blocks');
2014-02-04 08:06:05 -08:00
scanOpts.reverse = true;
scanOpts.upToExisting = true;
}
return self.importHistory(scanOpts, next);
});
});
2014-01-17 11:36:34 -08:00
});
2014-01-16 11:11:20 -08:00
};
return HistoricSync;
}
module.defineClass(spec);